jasonfan commited on
Commit
6a9874a
·
verified ·
1 Parent(s): 275f52e

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/tsl/protobuf/error_codes.pb.h +126 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/error_codes.proto +155 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.pb.h +513 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.proto +26 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.pb.h +437 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.proto +41 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.pb.h +314 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.proto +20 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.pb.h +0 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.proto +223 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/ml_dtypes.h +50 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/numpy.h +50 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/byte_swap_array.h +104 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/command_line_flags.h +143 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/determinism.h +27 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/device_name_utils.h +294 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/env_var.h +56 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/onednn_threadpool.h +188 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/proto/proto_utils.h +42 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stat_summarizer_options.h +44 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stats_calculator.h +201 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/use_cudnn.h +43 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AdolcForward +159 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AlignedVector3 +234 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/ArpackSupport +33 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AutoDiff +49 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/BVH +97 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/Tensor +141 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/TensorSymmetry +40 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/ThreadPool +1 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/InternalHeaderCheck.h +3 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/Tensor.h +465 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorArgMax.h +318 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorAssign.h +241 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBase.h +1222 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBlock.h +1607 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBroadcasting.h +1080 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorChipping.h +511 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConcatenation.h +371 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContraction.h +1018 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionBlocking.h +75 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionCuda.h +6 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionGpu.h +1411 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionMapper.h +573 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionSycl.h +1645 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionThreadPool.h +1679 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConversion.h +452 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolution.h +1135 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolutionSycl.h +540 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCostModel.h +216 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/error_codes.pb.h ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated by the protocol buffer compiler. DO NOT EDIT!
2
+ // source: tsl/protobuf/error_codes.proto
3
+
4
+ #ifndef GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2ferror_5fcodes_2eproto
5
+ #define GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2ferror_5fcodes_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/repeated_field.h> // IWYU pragma: export
30
+ #include <google/protobuf/extension_set.h> // IWYU pragma: export
31
+ #include <google/protobuf/generated_enum_reflection.h>
32
+ // @@protoc_insertion_point(includes)
33
+ #include <google/protobuf/port_def.inc>
34
+ #define PROTOBUF_INTERNAL_EXPORT_tsl_2fprotobuf_2ferror_5fcodes_2eproto
35
+ PROTOBUF_NAMESPACE_OPEN
36
+ namespace internal {
37
+ class AnyMetadata;
38
+ } // namespace internal
39
+ PROTOBUF_NAMESPACE_CLOSE
40
+
41
+ // Internal implementation detail -- do not use these members.
42
+ struct TableStruct_tsl_2fprotobuf_2ferror_5fcodes_2eproto {
43
+ static const uint32_t offsets[];
44
+ };
45
+ extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tsl_2fprotobuf_2ferror_5fcodes_2eproto;
46
+ PROTOBUF_NAMESPACE_OPEN
47
+ PROTOBUF_NAMESPACE_CLOSE
48
+ namespace tensorflow {
49
+ namespace error {
50
+
51
+ enum Code : int {
52
+ OK = 0,
53
+ CANCELLED = 1,
54
+ UNKNOWN = 2,
55
+ INVALID_ARGUMENT = 3,
56
+ DEADLINE_EXCEEDED = 4,
57
+ NOT_FOUND = 5,
58
+ ALREADY_EXISTS = 6,
59
+ PERMISSION_DENIED = 7,
60
+ UNAUTHENTICATED = 16,
61
+ RESOURCE_EXHAUSTED = 8,
62
+ FAILED_PRECONDITION = 9,
63
+ ABORTED = 10,
64
+ OUT_OF_RANGE = 11,
65
+ UNIMPLEMENTED = 12,
66
+ INTERNAL = 13,
67
+ UNAVAILABLE = 14,
68
+ DATA_LOSS = 15,
69
+ DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_ = 20,
70
+ Code_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<int32_t>::min(),
71
+ Code_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<int32_t>::max()
72
+ };
73
+ bool Code_IsValid(int value);
74
+ constexpr Code Code_MIN = OK;
75
+ constexpr Code Code_MAX = DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_;
76
+ constexpr int Code_ARRAYSIZE = Code_MAX + 1;
77
+
78
+ const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Code_descriptor();
79
+ template<typename T>
80
+ inline const std::string& Code_Name(T enum_t_value) {
81
+ static_assert(::std::is_same<T, Code>::value ||
82
+ ::std::is_integral<T>::value,
83
+ "Incorrect type passed to function Code_Name.");
84
+ return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum(
85
+ Code_descriptor(), enum_t_value);
86
+ }
87
+ inline bool Code_Parse(
88
+ ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Code* value) {
89
+ return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<Code>(
90
+ Code_descriptor(), name, value);
91
+ }
92
+ // ===================================================================
93
+
94
+
95
+ // ===================================================================
96
+
97
+
98
+ // ===================================================================
99
+
100
+ #ifdef __GNUC__
101
+ #pragma GCC diagnostic push
102
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
103
+ #endif // __GNUC__
104
+ #ifdef __GNUC__
105
+ #pragma GCC diagnostic pop
106
+ #endif // __GNUC__
107
+
108
+ // @@protoc_insertion_point(namespace_scope)
109
+
110
+ } // namespace error
111
+ } // namespace tensorflow
112
+
113
+ PROTOBUF_NAMESPACE_OPEN
114
+
115
+ template <> struct is_proto_enum< ::tensorflow::error::Code> : ::std::true_type {};
116
+ template <>
117
+ inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::error::Code>() {
118
+ return ::tensorflow::error::Code_descriptor();
119
+ }
120
+
121
+ PROTOBUF_NAMESPACE_CLOSE
122
+
123
+ // @@protoc_insertion_point(global_scope)
124
+
125
+ #include <google/protobuf/port_undef.inc>
126
+ #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2ferror_5fcodes_2eproto
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/error_codes.proto ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ syntax = "proto3";
2
+
3
+ // TODO(b/247876220): Change package and java_package once we figure out how to
4
+ // migrate.
5
+
6
+ package tensorflow.error;
7
+
8
+ option cc_enable_arenas = true;
9
+ option java_outer_classname = "ErrorCodesProtos";
10
+ option java_multiple_files = true;
11
+ option java_package = "org.tensorflow.framework";
12
+ option go_package = "github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto";
13
+
14
+ // The canonical error codes for TensorFlow APIs.
15
+ //
16
+ // Warnings:
17
+ //
18
+ // - Do not change any numeric assignments.
19
+ // - Changes to this list should only be made if there is a compelling
20
+ // need that can't be satisfied in another way. Such changes
21
+ // must be approved by at least two OWNERS.
22
+ // - These error codes must match gRPC and protobuf error codes (except for
23
+ // DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_).
24
+ //
25
+ // Sometimes multiple error codes may apply. Services should return
26
+ // the most specific error code that applies. For example, prefer
27
+ // OUT_OF_RANGE over FAILED_PRECONDITION if both codes apply.
28
+ // Similarly prefer NOT_FOUND or ALREADY_EXISTS over FAILED_PRECONDITION.
29
+ enum Code {
30
+ // Not an error; returned on success
31
+ OK = 0;
32
+
33
+ // The operation was cancelled (typically by the caller).
34
+ CANCELLED = 1;
35
+
36
+ // Unknown error. An example of where this error may be returned is
37
+ // if a Status value received from another address space belongs to
38
+ // an error-space that is not known in this address space. Also
39
+ // errors raised by APIs that do not return enough error information
40
+ // may be converted to this error.
41
+ UNKNOWN = 2;
42
+
43
+ // Client specified an invalid argument. Note that this differs
44
+ // from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments
45
+ // that are problematic regardless of the state of the system
46
+ // (e.g., a malformed file name).
47
+ INVALID_ARGUMENT = 3;
48
+
49
+ // Deadline expired before operation could complete. For operations
50
+ // that change the state of the system, this error may be returned
51
+ // even if the operation has completed successfully. For example, a
52
+ // successful response from a server could have been delayed long
53
+ // enough for the deadline to expire.
54
+ DEADLINE_EXCEEDED = 4;
55
+
56
+ // Some requested entity (e.g., file or directory) was not found.
57
+ // For privacy reasons, this code *may* be returned when the client
58
+ // does not have the access right to the entity.
59
+ NOT_FOUND = 5;
60
+
61
+ // Some entity that we attempted to create (e.g., file or directory)
62
+ // already exists.
63
+ ALREADY_EXISTS = 6;
64
+
65
+ // The caller does not have permission to execute the specified
66
+ // operation. PERMISSION_DENIED must not be used for rejections
67
+ // caused by exhausting some resource (use RESOURCE_EXHAUSTED
68
+ // instead for those errors). PERMISSION_DENIED must not be
69
+ // used if the caller can not be identified (use UNAUTHENTICATED
70
+ // instead for those errors).
71
+ PERMISSION_DENIED = 7;
72
+
73
+ // The request does not have valid authentication credentials for the
74
+ // operation.
75
+ UNAUTHENTICATED = 16;
76
+
77
+ // Some resource has been exhausted, perhaps a per-user quota, or
78
+ // perhaps the entire file system is out of space.
79
+ RESOURCE_EXHAUSTED = 8;
80
+
81
+ // Operation was rejected because the system is not in a state
82
+ // required for the operation's execution. For example, directory
83
+ // to be deleted may be non-empty, an rmdir operation is applied to
84
+ // a non-directory, etc.
85
+ //
86
+ // A litmus test that may help a service implementor in deciding
87
+ // between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
88
+ // (a) Use UNAVAILABLE if the client can retry just the failing call.
89
+ // (b) Use ABORTED if the client should retry at a higher-level
90
+ // (e.g., restarting a read-modify-write sequence).
91
+ // (c) Use FAILED_PRECONDITION if the client should not retry until
92
+ // the system state has been explicitly fixed. E.g., if an "rmdir"
93
+ // fails because the directory is non-empty, FAILED_PRECONDITION
94
+ // should be returned since the client should not retry unless
95
+ // they have first fixed up the directory by deleting files from it.
96
+ // (d) Use FAILED_PRECONDITION if the client performs conditional
97
+ // REST Get/Update/Delete on a resource and the resource on the
98
+ // server does not match the condition. E.g., conflicting
99
+ // read-modify-write on the same resource.
100
+ FAILED_PRECONDITION = 9;
101
+
102
+ // The operation was aborted, typically due to a concurrency issue
103
+ // like sequencer check failures, transaction aborts, etc.
104
+ //
105
+ // See litmus test above for deciding between FAILED_PRECONDITION,
106
+ // ABORTED, and UNAVAILABLE.
107
+ ABORTED = 10;
108
+
109
+ // Operation tried to iterate past the valid input range. E.g., seeking or
110
+ // reading past end of file.
111
+ //
112
+ // Unlike INVALID_ARGUMENT, this error indicates a problem that may
113
+ // be fixed if the system state changes. For example, a 32-bit file
114
+ // system will generate INVALID_ARGUMENT if asked to read at an
115
+ // offset that is not in the range [0,2^32-1], but it will generate
116
+ // OUT_OF_RANGE if asked to read from an offset past the current
117
+ // file size.
118
+ //
119
+ // There is a fair bit of overlap between FAILED_PRECONDITION and
120
+ // OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific
121
+ // error) when it applies so that callers who are iterating through
122
+ // a space can easily look for an OUT_OF_RANGE error to detect when
123
+ // they are done.
124
+ OUT_OF_RANGE = 11;
125
+
126
+ // Operation is not implemented or not supported/enabled in this service.
127
+ UNIMPLEMENTED = 12;
128
+
129
+ // Internal errors. Means some invariant expected by the underlying
130
+ // system has been broken. If you see one of these errors,
131
+ // something is very broken.
132
+ INTERNAL = 13;
133
+
134
+ // The service is currently unavailable. This is a most likely a
135
+ // transient condition and may be corrected by retrying with
136
+ // a backoff.
137
+ //
138
+ // See litmus test above for deciding between FAILED_PRECONDITION,
139
+ // ABORTED, and UNAVAILABLE.
140
+ UNAVAILABLE = 14;
141
+
142
+ // Unrecoverable data loss or corruption.
143
+ DATA_LOSS = 15;
144
+
145
+ // An extra enum entry to prevent people from writing code that
146
+ // fails to compile when a new code is added.
147
+ //
148
+ // Nobody should ever reference this enumeration entry. In particular,
149
+ // if you write C++ code that switches on this enumeration, add a default:
150
+ // case instead of a case that mentions this enumeration entry.
151
+ //
152
+ // Nobody should rely on the value (currently 20) listed here. It
153
+ // may change in the future.
154
+ DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_ = 20;
155
+ }
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.pb.h ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated by the protocol buffer compiler. DO NOT EDIT!
2
+ // source: tsl/protobuf/histogram.proto
3
+
4
+ #ifndef GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fhistogram_2eproto
5
+ #define GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fhistogram_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_tsl_2fprotobuf_2fhistogram_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_tsl_2fprotobuf_2fhistogram_2eproto {
44
+ static const uint32_t offsets[];
45
+ };
46
+ extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tsl_2fprotobuf_2fhistogram_2eproto;
47
+ namespace tensorflow {
48
+ class HistogramProto;
49
+ struct HistogramProtoDefaultTypeInternal;
50
+ extern HistogramProtoDefaultTypeInternal _HistogramProto_default_instance_;
51
+ } // namespace tensorflow
52
+ PROTOBUF_NAMESPACE_OPEN
53
+ template<> ::tensorflow::HistogramProto* Arena::CreateMaybeMessage<::tensorflow::HistogramProto>(Arena*);
54
+ PROTOBUF_NAMESPACE_CLOSE
55
+ namespace tensorflow {
56
+
57
+ // ===================================================================
58
+
59
+ class HistogramProto final :
60
+ public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.HistogramProto) */ {
61
+ public:
62
+ inline HistogramProto() : HistogramProto(nullptr) {}
63
+ ~HistogramProto() override;
64
+ explicit PROTOBUF_CONSTEXPR HistogramProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
65
+
66
+ HistogramProto(const HistogramProto& from);
67
+ HistogramProto(HistogramProto&& from) noexcept
68
+ : HistogramProto() {
69
+ *this = ::std::move(from);
70
+ }
71
+
72
+ inline HistogramProto& operator=(const HistogramProto& from) {
73
+ CopyFrom(from);
74
+ return *this;
75
+ }
76
+ inline HistogramProto& operator=(HistogramProto&& from) noexcept {
77
+ if (this == &from) return *this;
78
+ if (GetOwningArena() == from.GetOwningArena()
79
+ #ifdef PROTOBUF_FORCE_COPY_IN_MOVE
80
+ && GetOwningArena() != nullptr
81
+ #endif // !PROTOBUF_FORCE_COPY_IN_MOVE
82
+ ) {
83
+ InternalSwap(&from);
84
+ } else {
85
+ CopyFrom(from);
86
+ }
87
+ return *this;
88
+ }
89
+
90
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
91
+ return GetDescriptor();
92
+ }
93
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
94
+ return default_instance().GetMetadata().descriptor;
95
+ }
96
+ static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
97
+ return default_instance().GetMetadata().reflection;
98
+ }
99
+ static const HistogramProto& default_instance() {
100
+ return *internal_default_instance();
101
+ }
102
+ static inline const HistogramProto* internal_default_instance() {
103
+ return reinterpret_cast<const HistogramProto*>(
104
+ &_HistogramProto_default_instance_);
105
+ }
106
+ static constexpr int kIndexInFileMessages =
107
+ 0;
108
+
109
+ friend void swap(HistogramProto& a, HistogramProto& b) {
110
+ a.Swap(&b);
111
+ }
112
+ inline void Swap(HistogramProto* other) {
113
+ if (other == this) return;
114
+ #ifdef PROTOBUF_FORCE_COPY_IN_SWAP
115
+ if (GetOwningArena() != nullptr &&
116
+ GetOwningArena() == other->GetOwningArena()) {
117
+ #else // PROTOBUF_FORCE_COPY_IN_SWAP
118
+ if (GetOwningArena() == other->GetOwningArena()) {
119
+ #endif // !PROTOBUF_FORCE_COPY_IN_SWAP
120
+ InternalSwap(other);
121
+ } else {
122
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
123
+ }
124
+ }
125
+ void UnsafeArenaSwap(HistogramProto* other) {
126
+ if (other == this) return;
127
+ GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
128
+ InternalSwap(other);
129
+ }
130
+
131
+ // implements Message ----------------------------------------------
132
+
133
+ HistogramProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final {
134
+ return CreateMaybeMessage<HistogramProto>(arena);
135
+ }
136
+ using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
137
+ void CopyFrom(const HistogramProto& from);
138
+ using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
139
+ void MergeFrom( const HistogramProto& from) {
140
+ HistogramProto::MergeImpl(*this, from);
141
+ }
142
+ private:
143
+ static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg);
144
+ public:
145
+ PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
146
+ bool IsInitialized() const final;
147
+
148
+ size_t ByteSizeLong() const final;
149
+ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
150
+ uint8_t* _InternalSerialize(
151
+ uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
152
+ int GetCachedSize() const final { return _impl_._cached_size_.Get(); }
153
+
154
+ private:
155
+ void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned);
156
+ void SharedDtor();
157
+ void SetCachedSize(int size) const final;
158
+ void InternalSwap(HistogramProto* other);
159
+
160
+ private:
161
+ friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
162
+ static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
163
+ return "tensorflow.HistogramProto";
164
+ }
165
+ protected:
166
+ explicit HistogramProto(::PROTOBUF_NAMESPACE_ID::Arena* arena,
167
+ bool is_message_owned = false);
168
+ public:
169
+
170
+ static const ClassData _class_data_;
171
+ const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
172
+
173
+ ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
174
+
175
+ // nested types ----------------------------------------------------
176
+
177
+ // accessors -------------------------------------------------------
178
+
179
+ enum : int {
180
+ kBucketLimitFieldNumber = 6,
181
+ kBucketFieldNumber = 7,
182
+ kMinFieldNumber = 1,
183
+ kMaxFieldNumber = 2,
184
+ kNumFieldNumber = 3,
185
+ kSumFieldNumber = 4,
186
+ kSumSquaresFieldNumber = 5,
187
+ };
188
+ // repeated double bucket_limit = 6 [packed = true];
189
+ int bucket_limit_size() const;
190
+ private:
191
+ int _internal_bucket_limit_size() const;
192
+ public:
193
+ void clear_bucket_limit();
194
+ private:
195
+ double _internal_bucket_limit(int index) const;
196
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
197
+ _internal_bucket_limit() const;
198
+ void _internal_add_bucket_limit(double value);
199
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
200
+ _internal_mutable_bucket_limit();
201
+ public:
202
+ double bucket_limit(int index) const;
203
+ void set_bucket_limit(int index, double value);
204
+ void add_bucket_limit(double value);
205
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
206
+ bucket_limit() const;
207
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
208
+ mutable_bucket_limit();
209
+
210
+ // repeated double bucket = 7 [packed = true];
211
+ int bucket_size() const;
212
+ private:
213
+ int _internal_bucket_size() const;
214
+ public:
215
+ void clear_bucket();
216
+ private:
217
+ double _internal_bucket(int index) const;
218
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
219
+ _internal_bucket() const;
220
+ void _internal_add_bucket(double value);
221
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
222
+ _internal_mutable_bucket();
223
+ public:
224
+ double bucket(int index) const;
225
+ void set_bucket(int index, double value);
226
+ void add_bucket(double value);
227
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
228
+ bucket() const;
229
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
230
+ mutable_bucket();
231
+
232
+ // double min = 1;
233
+ void clear_min();
234
+ double min() const;
235
+ void set_min(double value);
236
+ private:
237
+ double _internal_min() const;
238
+ void _internal_set_min(double value);
239
+ public:
240
+
241
+ // double max = 2;
242
+ void clear_max();
243
+ double max() const;
244
+ void set_max(double value);
245
+ private:
246
+ double _internal_max() const;
247
+ void _internal_set_max(double value);
248
+ public:
249
+
250
+ // double num = 3;
251
+ void clear_num();
252
+ double num() const;
253
+ void set_num(double value);
254
+ private:
255
+ double _internal_num() const;
256
+ void _internal_set_num(double value);
257
+ public:
258
+
259
+ // double sum = 4;
260
+ void clear_sum();
261
+ double sum() const;
262
+ void set_sum(double value);
263
+ private:
264
+ double _internal_sum() const;
265
+ void _internal_set_sum(double value);
266
+ public:
267
+
268
+ // double sum_squares = 5;
269
+ void clear_sum_squares();
270
+ double sum_squares() const;
271
+ void set_sum_squares(double value);
272
+ private:
273
+ double _internal_sum_squares() const;
274
+ void _internal_set_sum_squares(double value);
275
+ public:
276
+
277
+ // @@protoc_insertion_point(class_scope:tensorflow.HistogramProto)
278
+ private:
279
+ class _Internal;
280
+
281
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
282
+ typedef void InternalArenaConstructable_;
283
+ typedef void DestructorSkippable_;
284
+ struct Impl_ {
285
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< double > bucket_limit_;
286
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< double > bucket_;
287
+ double min_;
288
+ double max_;
289
+ double num_;
290
+ double sum_;
291
+ double sum_squares_;
292
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
293
+ };
294
+ union { Impl_ _impl_; };
295
+ friend struct ::TableStruct_tsl_2fprotobuf_2fhistogram_2eproto;
296
+ };
297
+ // ===================================================================
298
+
299
+
300
+ // ===================================================================
301
+
302
+ #ifdef __GNUC__
303
+ #pragma GCC diagnostic push
304
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
305
+ #endif // __GNUC__
306
+ // HistogramProto
307
+
308
+ // double min = 1;
309
+ inline void HistogramProto::clear_min() {
310
+ _impl_.min_ = 0;
311
+ }
312
+ inline double HistogramProto::_internal_min() const {
313
+ return _impl_.min_;
314
+ }
315
+ inline double HistogramProto::min() const {
316
+ // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.min)
317
+ return _internal_min();
318
+ }
319
+ inline void HistogramProto::_internal_set_min(double value) {
320
+
321
+ _impl_.min_ = value;
322
+ }
323
+ inline void HistogramProto::set_min(double value) {
324
+ _internal_set_min(value);
325
+ // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.min)
326
+ }
327
+
328
+ // double max = 2;
329
+ inline void HistogramProto::clear_max() {
330
+ _impl_.max_ = 0;
331
+ }
332
+ inline double HistogramProto::_internal_max() const {
333
+ return _impl_.max_;
334
+ }
335
+ inline double HistogramProto::max() const {
336
+ // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.max)
337
+ return _internal_max();
338
+ }
339
+ inline void HistogramProto::_internal_set_max(double value) {
340
+
341
+ _impl_.max_ = value;
342
+ }
343
+ inline void HistogramProto::set_max(double value) {
344
+ _internal_set_max(value);
345
+ // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.max)
346
+ }
347
+
348
+ // double num = 3;
349
+ inline void HistogramProto::clear_num() {
350
+ _impl_.num_ = 0;
351
+ }
352
+ inline double HistogramProto::_internal_num() const {
353
+ return _impl_.num_;
354
+ }
355
+ inline double HistogramProto::num() const {
356
+ // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.num)
357
+ return _internal_num();
358
+ }
359
+ inline void HistogramProto::_internal_set_num(double value) {
360
+
361
+ _impl_.num_ = value;
362
+ }
363
+ inline void HistogramProto::set_num(double value) {
364
+ _internal_set_num(value);
365
+ // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.num)
366
+ }
367
+
368
+ // double sum = 4;
369
+ inline void HistogramProto::clear_sum() {
370
+ _impl_.sum_ = 0;
371
+ }
372
+ inline double HistogramProto::_internal_sum() const {
373
+ return _impl_.sum_;
374
+ }
375
+ inline double HistogramProto::sum() const {
376
+ // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.sum)
377
+ return _internal_sum();
378
+ }
379
+ inline void HistogramProto::_internal_set_sum(double value) {
380
+
381
+ _impl_.sum_ = value;
382
+ }
383
+ inline void HistogramProto::set_sum(double value) {
384
+ _internal_set_sum(value);
385
+ // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.sum)
386
+ }
387
+
388
+ // double sum_squares = 5;
389
+ inline void HistogramProto::clear_sum_squares() {
390
+ _impl_.sum_squares_ = 0;
391
+ }
392
+ inline double HistogramProto::_internal_sum_squares() const {
393
+ return _impl_.sum_squares_;
394
+ }
395
+ inline double HistogramProto::sum_squares() const {
396
+ // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.sum_squares)
397
+ return _internal_sum_squares();
398
+ }
399
+ inline void HistogramProto::_internal_set_sum_squares(double value) {
400
+
401
+ _impl_.sum_squares_ = value;
402
+ }
403
+ inline void HistogramProto::set_sum_squares(double value) {
404
+ _internal_set_sum_squares(value);
405
+ // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.sum_squares)
406
+ }
407
+
408
+ // repeated double bucket_limit = 6 [packed = true];
409
+ inline int HistogramProto::_internal_bucket_limit_size() const {
410
+ return _impl_.bucket_limit_.size();
411
+ }
412
+ inline int HistogramProto::bucket_limit_size() const {
413
+ return _internal_bucket_limit_size();
414
+ }
415
+ inline void HistogramProto::clear_bucket_limit() {
416
+ _impl_.bucket_limit_.Clear();
417
+ }
418
+ inline double HistogramProto::_internal_bucket_limit(int index) const {
419
+ return _impl_.bucket_limit_.Get(index);
420
+ }
421
+ inline double HistogramProto::bucket_limit(int index) const {
422
+ // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.bucket_limit)
423
+ return _internal_bucket_limit(index);
424
+ }
425
+ inline void HistogramProto::set_bucket_limit(int index, double value) {
426
+ _impl_.bucket_limit_.Set(index, value);
427
+ // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.bucket_limit)
428
+ }
429
+ inline void HistogramProto::_internal_add_bucket_limit(double value) {
430
+ _impl_.bucket_limit_.Add(value);
431
+ }
432
+ inline void HistogramProto::add_bucket_limit(double value) {
433
+ _internal_add_bucket_limit(value);
434
+ // @@protoc_insertion_point(field_add:tensorflow.HistogramProto.bucket_limit)
435
+ }
436
+ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
437
+ HistogramProto::_internal_bucket_limit() const {
438
+ return _impl_.bucket_limit_;
439
+ }
440
+ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
441
+ HistogramProto::bucket_limit() const {
442
+ // @@protoc_insertion_point(field_list:tensorflow.HistogramProto.bucket_limit)
443
+ return _internal_bucket_limit();
444
+ }
445
+ inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
446
+ HistogramProto::_internal_mutable_bucket_limit() {
447
+ return &_impl_.bucket_limit_;
448
+ }
449
+ inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
450
+ HistogramProto::mutable_bucket_limit() {
451
+ // @@protoc_insertion_point(field_mutable_list:tensorflow.HistogramProto.bucket_limit)
452
+ return _internal_mutable_bucket_limit();
453
+ }
454
+
455
+ // repeated double bucket = 7 [packed = true];
456
+ inline int HistogramProto::_internal_bucket_size() const {
457
+ return _impl_.bucket_.size();
458
+ }
459
+ inline int HistogramProto::bucket_size() const {
460
+ return _internal_bucket_size();
461
+ }
462
+ inline void HistogramProto::clear_bucket() {
463
+ _impl_.bucket_.Clear();
464
+ }
465
+ inline double HistogramProto::_internal_bucket(int index) const {
466
+ return _impl_.bucket_.Get(index);
467
+ }
468
+ inline double HistogramProto::bucket(int index) const {
469
+ // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.bucket)
470
+ return _internal_bucket(index);
471
+ }
472
+ inline void HistogramProto::set_bucket(int index, double value) {
473
+ _impl_.bucket_.Set(index, value);
474
+ // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.bucket)
475
+ }
476
+ inline void HistogramProto::_internal_add_bucket(double value) {
477
+ _impl_.bucket_.Add(value);
478
+ }
479
+ inline void HistogramProto::add_bucket(double value) {
480
+ _internal_add_bucket(value);
481
+ // @@protoc_insertion_point(field_add:tensorflow.HistogramProto.bucket)
482
+ }
483
+ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
484
+ HistogramProto::_internal_bucket() const {
485
+ return _impl_.bucket_;
486
+ }
487
+ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
488
+ HistogramProto::bucket() const {
489
+ // @@protoc_insertion_point(field_list:tensorflow.HistogramProto.bucket)
490
+ return _internal_bucket();
491
+ }
492
+ inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
493
+ HistogramProto::_internal_mutable_bucket() {
494
+ return &_impl_.bucket_;
495
+ }
496
+ inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
497
+ HistogramProto::mutable_bucket() {
498
+ // @@protoc_insertion_point(field_mutable_list:tensorflow.HistogramProto.bucket)
499
+ return _internal_mutable_bucket();
500
+ }
501
+
502
+ #ifdef __GNUC__
503
+ #pragma GCC diagnostic pop
504
+ #endif // __GNUC__
505
+
506
+ // @@protoc_insertion_point(namespace_scope)
507
+
508
+ } // namespace tensorflow
509
+
510
+ // @@protoc_insertion_point(global_scope)
511
+
512
+ #include <google/protobuf/port_undef.inc>
513
+ #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fhistogram_2eproto
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.proto ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ syntax = "proto3";
2
+
3
+ package tensorflow;
4
+
5
+ option cc_enable_arenas = true;
6
+ option java_multiple_files = true;
7
+ option java_package = "org.tensorflow.framework";
8
+ option go_package = "github.com/google/tsl/tsl/go/core/protobuf/summary_go_proto";
9
+
10
+ // Serialization format for histogram module in
11
+ // tsl/lib/histogram/histogram.h
12
+ message HistogramProto {
13
+ double min = 1;
14
+ double max = 2;
15
+ double num = 3;
16
+ double sum = 4;
17
+ double sum_squares = 5;
18
+
19
+ // Parallel arrays encoding the bucket boundaries and the bucket values.
20
+ // bucket(i) is the count for the bucket i. The range for
21
+ // a bucket is:
22
+ // i == 0: -DBL_MAX .. bucket_limit(0)
23
+ // i != 0: bucket_limit(i-1) .. bucket_limit(i)
24
+ repeated double bucket_limit = 6 [packed = true];
25
+ repeated double bucket = 7 [packed = true];
26
+ }
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.pb.h ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated by the protocol buffer compiler. DO NOT EDIT!
2
+ // source: tsl/protobuf/rpc_options.proto
3
+
4
+ #ifndef GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2frpc_5foptions_2eproto
5
+ #define GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2frpc_5foptions_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_tsl_2fprotobuf_2frpc_5foptions_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_tsl_2fprotobuf_2frpc_5foptions_2eproto {
44
+ static const uint32_t offsets[];
45
+ };
46
+ extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tsl_2fprotobuf_2frpc_5foptions_2eproto;
47
+ namespace tensorflow {
48
+ class RPCOptions;
49
+ struct RPCOptionsDefaultTypeInternal;
50
+ extern RPCOptionsDefaultTypeInternal _RPCOptions_default_instance_;
51
+ } // namespace tensorflow
52
+ PROTOBUF_NAMESPACE_OPEN
53
+ template<> ::tensorflow::RPCOptions* Arena::CreateMaybeMessage<::tensorflow::RPCOptions>(Arena*);
54
+ PROTOBUF_NAMESPACE_CLOSE
55
+ namespace tensorflow {
56
+
57
+ // ===================================================================
58
+
59
+ class RPCOptions final :
60
+ public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.RPCOptions) */ {
61
+ public:
62
+ inline RPCOptions() : RPCOptions(nullptr) {}
63
+ ~RPCOptions() override;
64
+ explicit PROTOBUF_CONSTEXPR RPCOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
65
+
66
+ RPCOptions(const RPCOptions& from);
67
+ RPCOptions(RPCOptions&& from) noexcept
68
+ : RPCOptions() {
69
+ *this = ::std::move(from);
70
+ }
71
+
72
+ inline RPCOptions& operator=(const RPCOptions& from) {
73
+ CopyFrom(from);
74
+ return *this;
75
+ }
76
+ inline RPCOptions& operator=(RPCOptions&& from) noexcept {
77
+ if (this == &from) return *this;
78
+ if (GetOwningArena() == from.GetOwningArena()
79
+ #ifdef PROTOBUF_FORCE_COPY_IN_MOVE
80
+ && GetOwningArena() != nullptr
81
+ #endif // !PROTOBUF_FORCE_COPY_IN_MOVE
82
+ ) {
83
+ InternalSwap(&from);
84
+ } else {
85
+ CopyFrom(from);
86
+ }
87
+ return *this;
88
+ }
89
+
90
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
91
+ return GetDescriptor();
92
+ }
93
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
94
+ return default_instance().GetMetadata().descriptor;
95
+ }
96
+ static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
97
+ return default_instance().GetMetadata().reflection;
98
+ }
99
+ static const RPCOptions& default_instance() {
100
+ return *internal_default_instance();
101
+ }
102
+ static inline const RPCOptions* internal_default_instance() {
103
+ return reinterpret_cast<const RPCOptions*>(
104
+ &_RPCOptions_default_instance_);
105
+ }
106
+ static constexpr int kIndexInFileMessages =
107
+ 0;
108
+
109
+ friend void swap(RPCOptions& a, RPCOptions& b) {
110
+ a.Swap(&b);
111
+ }
112
+ inline void Swap(RPCOptions* other) {
113
+ if (other == this) return;
114
+ #ifdef PROTOBUF_FORCE_COPY_IN_SWAP
115
+ if (GetOwningArena() != nullptr &&
116
+ GetOwningArena() == other->GetOwningArena()) {
117
+ #else // PROTOBUF_FORCE_COPY_IN_SWAP
118
+ if (GetOwningArena() == other->GetOwningArena()) {
119
+ #endif // !PROTOBUF_FORCE_COPY_IN_SWAP
120
+ InternalSwap(other);
121
+ } else {
122
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
123
+ }
124
+ }
125
+ void UnsafeArenaSwap(RPCOptions* other) {
126
+ if (other == this) return;
127
+ GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
128
+ InternalSwap(other);
129
+ }
130
+
131
+ // implements Message ----------------------------------------------
132
+
133
+ RPCOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final {
134
+ return CreateMaybeMessage<RPCOptions>(arena);
135
+ }
136
+ using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
137
+ void CopyFrom(const RPCOptions& from);
138
+ using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
139
+ void MergeFrom( const RPCOptions& from) {
140
+ RPCOptions::MergeImpl(*this, from);
141
+ }
142
+ private:
143
+ static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg);
144
+ public:
145
+ PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
146
+ bool IsInitialized() const final;
147
+
148
+ size_t ByteSizeLong() const final;
149
+ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
150
+ uint8_t* _InternalSerialize(
151
+ uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
152
+ int GetCachedSize() const final { return _impl_._cached_size_.Get(); }
153
+
154
+ private:
155
+ void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned);
156
+ void SharedDtor();
157
+ void SetCachedSize(int size) const final;
158
+ void InternalSwap(RPCOptions* other);
159
+
160
+ private:
161
+ friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
162
+ static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
163
+ return "tensorflow.RPCOptions";
164
+ }
165
+ protected:
166
+ explicit RPCOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena,
167
+ bool is_message_owned = false);
168
+ public:
169
+
170
+ static const ClassData _class_data_;
171
+ const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
172
+
173
+ ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
174
+
175
+ // nested types ----------------------------------------------------
176
+
177
+ // accessors -------------------------------------------------------
178
+
179
+ enum : int {
180
+ kCompressionAlgorithmFieldNumber = 2,
181
+ kCompressionLevelFieldNumber = 3,
182
+ kUseRpcForInprocessMasterFieldNumber = 1,
183
+ kCacheRpcResponseFieldNumber = 4,
184
+ kDisableSessionConnectionSharingFieldNumber = 5,
185
+ kNumChannelsPerTargetFieldNumber = 6,
186
+ };
187
+ // string compression_algorithm = 2;
188
+ void clear_compression_algorithm();
189
+ const std::string& compression_algorithm() const;
190
+ template <typename ArgT0 = const std::string&, typename... ArgT>
191
+ void set_compression_algorithm(ArgT0&& arg0, ArgT... args);
192
+ std::string* mutable_compression_algorithm();
193
+ PROTOBUF_NODISCARD std::string* release_compression_algorithm();
194
+ void set_allocated_compression_algorithm(std::string* compression_algorithm);
195
+ private:
196
+ const std::string& _internal_compression_algorithm() const;
197
+ inline PROTOBUF_ALWAYS_INLINE void _internal_set_compression_algorithm(const std::string& value);
198
+ std::string* _internal_mutable_compression_algorithm();
199
+ public:
200
+
201
+ // int32 compression_level = 3;
202
+ void clear_compression_level();
203
+ int32_t compression_level() const;
204
+ void set_compression_level(int32_t value);
205
+ private:
206
+ int32_t _internal_compression_level() const;
207
+ void _internal_set_compression_level(int32_t value);
208
+ public:
209
+
210
+ // bool use_rpc_for_inprocess_master = 1;
211
+ void clear_use_rpc_for_inprocess_master();
212
+ bool use_rpc_for_inprocess_master() const;
213
+ void set_use_rpc_for_inprocess_master(bool value);
214
+ private:
215
+ bool _internal_use_rpc_for_inprocess_master() const;
216
+ void _internal_set_use_rpc_for_inprocess_master(bool value);
217
+ public:
218
+
219
+ // bool cache_rpc_response = 4;
220
+ void clear_cache_rpc_response();
221
+ bool cache_rpc_response() const;
222
+ void set_cache_rpc_response(bool value);
223
+ private:
224
+ bool _internal_cache_rpc_response() const;
225
+ void _internal_set_cache_rpc_response(bool value);
226
+ public:
227
+
228
+ // bool disable_session_connection_sharing = 5;
229
+ void clear_disable_session_connection_sharing();
230
+ bool disable_session_connection_sharing() const;
231
+ void set_disable_session_connection_sharing(bool value);
232
+ private:
233
+ bool _internal_disable_session_connection_sharing() const;
234
+ void _internal_set_disable_session_connection_sharing(bool value);
235
+ public:
236
+
237
+ // int32 num_channels_per_target = 6;
238
+ void clear_num_channels_per_target();
239
+ int32_t num_channels_per_target() const;
240
+ void set_num_channels_per_target(int32_t value);
241
+ private:
242
+ int32_t _internal_num_channels_per_target() const;
243
+ void _internal_set_num_channels_per_target(int32_t value);
244
+ public:
245
+
246
+ // @@protoc_insertion_point(class_scope:tensorflow.RPCOptions)
247
+ private:
248
+ class _Internal;
249
+
250
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
251
+ typedef void InternalArenaConstructable_;
252
+ typedef void DestructorSkippable_;
253
+ struct Impl_ {
254
+ ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr compression_algorithm_;
255
+ int32_t compression_level_;
256
+ bool use_rpc_for_inprocess_master_;
257
+ bool cache_rpc_response_;
258
+ bool disable_session_connection_sharing_;
259
+ int32_t num_channels_per_target_;
260
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
261
+ };
262
+ union { Impl_ _impl_; };
263
+ friend struct ::TableStruct_tsl_2fprotobuf_2frpc_5foptions_2eproto;
264
+ };
265
+ // ===================================================================
266
+
267
+
268
+ // ===================================================================
269
+
270
+ #ifdef __GNUC__
271
+ #pragma GCC diagnostic push
272
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
273
+ #endif // __GNUC__
274
+ // RPCOptions
275
+
276
+ // bool use_rpc_for_inprocess_master = 1;
277
+ inline void RPCOptions::clear_use_rpc_for_inprocess_master() {
278
+ _impl_.use_rpc_for_inprocess_master_ = false;
279
+ }
280
+ inline bool RPCOptions::_internal_use_rpc_for_inprocess_master() const {
281
+ return _impl_.use_rpc_for_inprocess_master_;
282
+ }
283
+ inline bool RPCOptions::use_rpc_for_inprocess_master() const {
284
+ // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.use_rpc_for_inprocess_master)
285
+ return _internal_use_rpc_for_inprocess_master();
286
+ }
287
+ inline void RPCOptions::_internal_set_use_rpc_for_inprocess_master(bool value) {
288
+
289
+ _impl_.use_rpc_for_inprocess_master_ = value;
290
+ }
291
+ inline void RPCOptions::set_use_rpc_for_inprocess_master(bool value) {
292
+ _internal_set_use_rpc_for_inprocess_master(value);
293
+ // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.use_rpc_for_inprocess_master)
294
+ }
295
+
296
+ // string compression_algorithm = 2;
297
+ inline void RPCOptions::clear_compression_algorithm() {
298
+ _impl_.compression_algorithm_.ClearToEmpty();
299
+ }
300
+ inline const std::string& RPCOptions::compression_algorithm() const {
301
+ // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.compression_algorithm)
302
+ return _internal_compression_algorithm();
303
+ }
304
+ template <typename ArgT0, typename... ArgT>
305
+ inline PROTOBUF_ALWAYS_INLINE
306
+ void RPCOptions::set_compression_algorithm(ArgT0&& arg0, ArgT... args) {
307
+
308
+ _impl_.compression_algorithm_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
309
+ // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.compression_algorithm)
310
+ }
311
+ inline std::string* RPCOptions::mutable_compression_algorithm() {
312
+ std::string* _s = _internal_mutable_compression_algorithm();
313
+ // @@protoc_insertion_point(field_mutable:tensorflow.RPCOptions.compression_algorithm)
314
+ return _s;
315
+ }
316
+ inline const std::string& RPCOptions::_internal_compression_algorithm() const {
317
+ return _impl_.compression_algorithm_.Get();
318
+ }
319
+ inline void RPCOptions::_internal_set_compression_algorithm(const std::string& value) {
320
+
321
+ _impl_.compression_algorithm_.Set(value, GetArenaForAllocation());
322
+ }
323
+ inline std::string* RPCOptions::_internal_mutable_compression_algorithm() {
324
+
325
+ return _impl_.compression_algorithm_.Mutable(GetArenaForAllocation());
326
+ }
327
+ inline std::string* RPCOptions::release_compression_algorithm() {
328
+ // @@protoc_insertion_point(field_release:tensorflow.RPCOptions.compression_algorithm)
329
+ return _impl_.compression_algorithm_.Release();
330
+ }
331
+ inline void RPCOptions::set_allocated_compression_algorithm(std::string* compression_algorithm) {
332
+ if (compression_algorithm != nullptr) {
333
+
334
+ } else {
335
+
336
+ }
337
+ _impl_.compression_algorithm_.SetAllocated(compression_algorithm, GetArenaForAllocation());
338
+ #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
339
+ if (_impl_.compression_algorithm_.IsDefault()) {
340
+ _impl_.compression_algorithm_.Set("", GetArenaForAllocation());
341
+ }
342
+ #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
343
+ // @@protoc_insertion_point(field_set_allocated:tensorflow.RPCOptions.compression_algorithm)
344
+ }
345
+
346
+ // int32 compression_level = 3;
347
+ inline void RPCOptions::clear_compression_level() {
348
+ _impl_.compression_level_ = 0;
349
+ }
350
+ inline int32_t RPCOptions::_internal_compression_level() const {
351
+ return _impl_.compression_level_;
352
+ }
353
+ inline int32_t RPCOptions::compression_level() const {
354
+ // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.compression_level)
355
+ return _internal_compression_level();
356
+ }
357
+ inline void RPCOptions::_internal_set_compression_level(int32_t value) {
358
+
359
+ _impl_.compression_level_ = value;
360
+ }
361
+ inline void RPCOptions::set_compression_level(int32_t value) {
362
+ _internal_set_compression_level(value);
363
+ // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.compression_level)
364
+ }
365
+
366
+ // bool cache_rpc_response = 4;
367
+ inline void RPCOptions::clear_cache_rpc_response() {
368
+ _impl_.cache_rpc_response_ = false;
369
+ }
370
+ inline bool RPCOptions::_internal_cache_rpc_response() const {
371
+ return _impl_.cache_rpc_response_;
372
+ }
373
+ inline bool RPCOptions::cache_rpc_response() const {
374
+ // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.cache_rpc_response)
375
+ return _internal_cache_rpc_response();
376
+ }
377
+ inline void RPCOptions::_internal_set_cache_rpc_response(bool value) {
378
+
379
+ _impl_.cache_rpc_response_ = value;
380
+ }
381
+ inline void RPCOptions::set_cache_rpc_response(bool value) {
382
+ _internal_set_cache_rpc_response(value);
383
+ // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.cache_rpc_response)
384
+ }
385
+
386
+ // bool disable_session_connection_sharing = 5;
387
+ inline void RPCOptions::clear_disable_session_connection_sharing() {
388
+ _impl_.disable_session_connection_sharing_ = false;
389
+ }
390
+ inline bool RPCOptions::_internal_disable_session_connection_sharing() const {
391
+ return _impl_.disable_session_connection_sharing_;
392
+ }
393
+ inline bool RPCOptions::disable_session_connection_sharing() const {
394
+ // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.disable_session_connection_sharing)
395
+ return _internal_disable_session_connection_sharing();
396
+ }
397
+ inline void RPCOptions::_internal_set_disable_session_connection_sharing(bool value) {
398
+
399
+ _impl_.disable_session_connection_sharing_ = value;
400
+ }
401
+ inline void RPCOptions::set_disable_session_connection_sharing(bool value) {
402
+ _internal_set_disable_session_connection_sharing(value);
403
+ // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.disable_session_connection_sharing)
404
+ }
405
+
406
+ // int32 num_channels_per_target = 6;
407
+ inline void RPCOptions::clear_num_channels_per_target() {
408
+ _impl_.num_channels_per_target_ = 0;
409
+ }
410
+ inline int32_t RPCOptions::_internal_num_channels_per_target() const {
411
+ return _impl_.num_channels_per_target_;
412
+ }
413
+ inline int32_t RPCOptions::num_channels_per_target() const {
414
+ // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.num_channels_per_target)
415
+ return _internal_num_channels_per_target();
416
+ }
417
+ inline void RPCOptions::_internal_set_num_channels_per_target(int32_t value) {
418
+
419
+ _impl_.num_channels_per_target_ = value;
420
+ }
421
+ inline void RPCOptions::set_num_channels_per_target(int32_t value) {
422
+ _internal_set_num_channels_per_target(value);
423
+ // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.num_channels_per_target)
424
+ }
425
+
426
+ #ifdef __GNUC__
427
+ #pragma GCC diagnostic pop
428
+ #endif // __GNUC__
429
+
430
+ // @@protoc_insertion_point(namespace_scope)
431
+
432
+ } // namespace tensorflow
433
+
434
+ // @@protoc_insertion_point(global_scope)
435
+
436
+ #include <google/protobuf/port_undef.inc>
437
+ #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2frpc_5foptions_2eproto
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.proto ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ syntax = "proto3";
2
+
3
+ package tensorflow;
4
+
5
+ option go_package = "github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto";
6
+
7
+ // RPC options for distributed runtime.
8
+ message RPCOptions {
9
+ // If true, always use RPC to contact the session target.
10
+ //
11
+ // If false (the default option), TensorFlow may use an optimized
12
+ // transport for client-master communication that avoids the RPC
13
+ // stack. This option is primarily for used testing the RPC stack.
14
+ bool use_rpc_for_inprocess_master = 1;
15
+
16
+ // The compression algorithm to be used. One of "deflate", "gzip".
17
+ string compression_algorithm = 2;
18
+
19
+ // If compression_algorithm is set, the compression level to be used.
20
+ // From 0 (no compression), up to 3.
21
+ int32 compression_level = 3;
22
+
23
+ // Setting cache_rpc_response to true will enable sender side caching of
24
+ // response for RecvTensorAsync and RecvBufAsync to allow receiver to retry
25
+ // requests . This is only necessary when the network fabric is experiencing a
26
+ // significant error rate. Without it we'll fail a step on an network error,
27
+ // while with it we'll be able to complete long steps (like complex
28
+ // initializations) in the face of some network errors during RecvTensor.
29
+ bool cache_rpc_response = 4;
30
+
31
+ // Disables TCP connection sharing when opening a new RPC channel.
32
+ bool disable_session_connection_sharing = 5;
33
+
34
+ // Setting num_channels_per_target > 0 allows uses of multiple channels to
35
+ // communicate to the same target. This can be used to improve the aggregate
36
+ // throughput on high speed links (e.g 100G) where single connection is not
37
+ // sufficient to maximize link utilization. Note that a single RPC only goes
38
+ // on a single channel, this only helps in situations where there are multiple
39
+ // transfers to the same target overlapping in time.
40
+ int32 num_channels_per_target = 6;
41
+ }
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.pb.h ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated by the protocol buffer compiler. DO NOT EDIT!
2
+ // source: tsl/protobuf/status.proto
3
+
4
+ #ifndef GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fstatus_2eproto
5
+ #define GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fstatus_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
+ #include "tsl/protobuf/error_codes.pb.h"
34
+ // @@protoc_insertion_point(includes)
35
+ #include <google/protobuf/port_def.inc>
36
+ #define PROTOBUF_INTERNAL_EXPORT_tsl_2fprotobuf_2fstatus_2eproto
37
+ PROTOBUF_NAMESPACE_OPEN
38
+ namespace internal {
39
+ class AnyMetadata;
40
+ } // namespace internal
41
+ PROTOBUF_NAMESPACE_CLOSE
42
+
43
+ // Internal implementation detail -- do not use these members.
44
+ struct TableStruct_tsl_2fprotobuf_2fstatus_2eproto {
45
+ static const uint32_t offsets[];
46
+ };
47
+ extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tsl_2fprotobuf_2fstatus_2eproto;
48
+ namespace tensorflow {
49
+ class StatusProto;
50
+ struct StatusProtoDefaultTypeInternal;
51
+ extern StatusProtoDefaultTypeInternal _StatusProto_default_instance_;
52
+ } // namespace tensorflow
53
+ PROTOBUF_NAMESPACE_OPEN
54
+ template<> ::tensorflow::StatusProto* Arena::CreateMaybeMessage<::tensorflow::StatusProto>(Arena*);
55
+ PROTOBUF_NAMESPACE_CLOSE
56
+ namespace tensorflow {
57
+
58
+ // ===================================================================
59
+
60
+ class StatusProto final :
61
+ public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.StatusProto) */ {
62
+ public:
63
+ inline StatusProto() : StatusProto(nullptr) {}
64
+ ~StatusProto() override;
65
+ explicit PROTOBUF_CONSTEXPR StatusProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
66
+
67
+ StatusProto(const StatusProto& from);
68
+ StatusProto(StatusProto&& from) noexcept
69
+ : StatusProto() {
70
+ *this = ::std::move(from);
71
+ }
72
+
73
+ inline StatusProto& operator=(const StatusProto& from) {
74
+ CopyFrom(from);
75
+ return *this;
76
+ }
77
+ inline StatusProto& operator=(StatusProto&& from) noexcept {
78
+ if (this == &from) return *this;
79
+ if (GetOwningArena() == from.GetOwningArena()
80
+ #ifdef PROTOBUF_FORCE_COPY_IN_MOVE
81
+ && GetOwningArena() != nullptr
82
+ #endif // !PROTOBUF_FORCE_COPY_IN_MOVE
83
+ ) {
84
+ InternalSwap(&from);
85
+ } else {
86
+ CopyFrom(from);
87
+ }
88
+ return *this;
89
+ }
90
+
91
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
92
+ return GetDescriptor();
93
+ }
94
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
95
+ return default_instance().GetMetadata().descriptor;
96
+ }
97
+ static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
98
+ return default_instance().GetMetadata().reflection;
99
+ }
100
+ static const StatusProto& default_instance() {
101
+ return *internal_default_instance();
102
+ }
103
+ static inline const StatusProto* internal_default_instance() {
104
+ return reinterpret_cast<const StatusProto*>(
105
+ &_StatusProto_default_instance_);
106
+ }
107
+ static constexpr int kIndexInFileMessages =
108
+ 0;
109
+
110
+ friend void swap(StatusProto& a, StatusProto& b) {
111
+ a.Swap(&b);
112
+ }
113
+ inline void Swap(StatusProto* other) {
114
+ if (other == this) return;
115
+ #ifdef PROTOBUF_FORCE_COPY_IN_SWAP
116
+ if (GetOwningArena() != nullptr &&
117
+ GetOwningArena() == other->GetOwningArena()) {
118
+ #else // PROTOBUF_FORCE_COPY_IN_SWAP
119
+ if (GetOwningArena() == other->GetOwningArena()) {
120
+ #endif // !PROTOBUF_FORCE_COPY_IN_SWAP
121
+ InternalSwap(other);
122
+ } else {
123
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
124
+ }
125
+ }
126
+ void UnsafeArenaSwap(StatusProto* other) {
127
+ if (other == this) return;
128
+ GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
129
+ InternalSwap(other);
130
+ }
131
+
132
+ // implements Message ----------------------------------------------
133
+
134
+ StatusProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final {
135
+ return CreateMaybeMessage<StatusProto>(arena);
136
+ }
137
+ using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
138
+ void CopyFrom(const StatusProto& from);
139
+ using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
140
+ void MergeFrom( const StatusProto& from) {
141
+ StatusProto::MergeImpl(*this, from);
142
+ }
143
+ private:
144
+ static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg);
145
+ public:
146
+ PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
147
+ bool IsInitialized() const final;
148
+
149
+ size_t ByteSizeLong() const final;
150
+ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
151
+ uint8_t* _InternalSerialize(
152
+ uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
153
+ int GetCachedSize() const final { return _impl_._cached_size_.Get(); }
154
+
155
+ private:
156
+ void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned);
157
+ void SharedDtor();
158
+ void SetCachedSize(int size) const final;
159
+ void InternalSwap(StatusProto* other);
160
+
161
+ private:
162
+ friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
163
+ static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
164
+ return "tensorflow.StatusProto";
165
+ }
166
+ protected:
167
+ explicit StatusProto(::PROTOBUF_NAMESPACE_ID::Arena* arena,
168
+ bool is_message_owned = false);
169
+ public:
170
+
171
+ static const ClassData _class_data_;
172
+ const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
173
+
174
+ ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
175
+
176
+ // nested types ----------------------------------------------------
177
+
178
+ // accessors -------------------------------------------------------
179
+
180
+ enum : int {
181
+ kMessageFieldNumber = 2,
182
+ kCodeFieldNumber = 1,
183
+ };
184
+ // string message = 2;
185
+ void clear_message();
186
+ const std::string& message() const;
187
+ template <typename ArgT0 = const std::string&, typename... ArgT>
188
+ void set_message(ArgT0&& arg0, ArgT... args);
189
+ std::string* mutable_message();
190
+ PROTOBUF_NODISCARD std::string* release_message();
191
+ void set_allocated_message(std::string* message);
192
+ private:
193
+ const std::string& _internal_message() const;
194
+ inline PROTOBUF_ALWAYS_INLINE void _internal_set_message(const std::string& value);
195
+ std::string* _internal_mutable_message();
196
+ public:
197
+
198
+ // .tensorflow.error.Code code = 1;
199
+ void clear_code();
200
+ ::tensorflow::error::Code code() const;
201
+ void set_code(::tensorflow::error::Code value);
202
+ private:
203
+ ::tensorflow::error::Code _internal_code() const;
204
+ void _internal_set_code(::tensorflow::error::Code value);
205
+ public:
206
+
207
+ // @@protoc_insertion_point(class_scope:tensorflow.StatusProto)
208
+ private:
209
+ class _Internal;
210
+
211
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
212
+ typedef void InternalArenaConstructable_;
213
+ typedef void DestructorSkippable_;
214
+ struct Impl_ {
215
+ ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr message_;
216
+ int code_;
217
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
218
+ };
219
+ union { Impl_ _impl_; };
220
+ friend struct ::TableStruct_tsl_2fprotobuf_2fstatus_2eproto;
221
+ };
222
+ // ===================================================================
223
+
224
+
225
+ // ===================================================================
226
+
227
+ #ifdef __GNUC__
228
+ #pragma GCC diagnostic push
229
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
230
+ #endif // __GNUC__
231
+ // StatusProto
232
+
233
+ // .tensorflow.error.Code code = 1;
234
+ inline void StatusProto::clear_code() {
235
+ _impl_.code_ = 0;
236
+ }
237
+ inline ::tensorflow::error::Code StatusProto::_internal_code() const {
238
+ return static_cast< ::tensorflow::error::Code >(_impl_.code_);
239
+ }
240
+ inline ::tensorflow::error::Code StatusProto::code() const {
241
+ // @@protoc_insertion_point(field_get:tensorflow.StatusProto.code)
242
+ return _internal_code();
243
+ }
244
+ inline void StatusProto::_internal_set_code(::tensorflow::error::Code value) {
245
+
246
+ _impl_.code_ = value;
247
+ }
248
+ inline void StatusProto::set_code(::tensorflow::error::Code value) {
249
+ _internal_set_code(value);
250
+ // @@protoc_insertion_point(field_set:tensorflow.StatusProto.code)
251
+ }
252
+
253
+ // string message = 2;
254
+ inline void StatusProto::clear_message() {
255
+ _impl_.message_.ClearToEmpty();
256
+ }
257
+ inline const std::string& StatusProto::message() const {
258
+ // @@protoc_insertion_point(field_get:tensorflow.StatusProto.message)
259
+ return _internal_message();
260
+ }
261
+ template <typename ArgT0, typename... ArgT>
262
+ inline PROTOBUF_ALWAYS_INLINE
263
+ void StatusProto::set_message(ArgT0&& arg0, ArgT... args) {
264
+
265
+ _impl_.message_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
266
+ // @@protoc_insertion_point(field_set:tensorflow.StatusProto.message)
267
+ }
268
+ inline std::string* StatusProto::mutable_message() {
269
+ std::string* _s = _internal_mutable_message();
270
+ // @@protoc_insertion_point(field_mutable:tensorflow.StatusProto.message)
271
+ return _s;
272
+ }
273
+ inline const std::string& StatusProto::_internal_message() const {
274
+ return _impl_.message_.Get();
275
+ }
276
+ inline void StatusProto::_internal_set_message(const std::string& value) {
277
+
278
+ _impl_.message_.Set(value, GetArenaForAllocation());
279
+ }
280
+ inline std::string* StatusProto::_internal_mutable_message() {
281
+
282
+ return _impl_.message_.Mutable(GetArenaForAllocation());
283
+ }
284
+ inline std::string* StatusProto::release_message() {
285
+ // @@protoc_insertion_point(field_release:tensorflow.StatusProto.message)
286
+ return _impl_.message_.Release();
287
+ }
288
+ inline void StatusProto::set_allocated_message(std::string* message) {
289
+ if (message != nullptr) {
290
+
291
+ } else {
292
+
293
+ }
294
+ _impl_.message_.SetAllocated(message, GetArenaForAllocation());
295
+ #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
296
+ if (_impl_.message_.IsDefault()) {
297
+ _impl_.message_.Set("", GetArenaForAllocation());
298
+ }
299
+ #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
300
+ // @@protoc_insertion_point(field_set_allocated:tensorflow.StatusProto.message)
301
+ }
302
+
303
+ #ifdef __GNUC__
304
+ #pragma GCC diagnostic pop
305
+ #endif // __GNUC__
306
+
307
+ // @@protoc_insertion_point(namespace_scope)
308
+
309
+ } // namespace tensorflow
310
+
311
+ // @@protoc_insertion_point(global_scope)
312
+
313
+ #include <google/protobuf/port_undef.inc>
314
+ #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fstatus_2eproto
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.proto ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ syntax = "proto3";
2
+
3
+ package tensorflow;
4
+
5
+ import "tsl/protobuf/error_codes.proto";
6
+
7
+ option cc_enable_arenas = true;
8
+ option java_multiple_files = true;
9
+ option java_package = "org.tensorflow.framework";
10
+ option go_package = "github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto";
11
+
12
+ // Wire-format for Status.
13
+ // Next tag: 3
14
+ message StatusProto {
15
+ // Status code as defined in tensorflow/tsl/protobuf/error_codes.proto.
16
+ error.Code code = 1;
17
+
18
+ // Detail error message.
19
+ string message = 2;
20
+ }
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.pb.h ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.proto ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Protocol messages for describing the results of benchmarks and unit tests.
2
+ syntax = "proto3";
3
+
4
+ package tensorflow;
5
+
6
+ import "google/protobuf/any.proto";
7
+ import "google/protobuf/wrappers.proto";
8
+
9
+ option cc_enable_arenas = true;
10
+ option java_outer_classname = "TestLogProtos";
11
+ option java_multiple_files = true;
12
+ option java_package = "org.tensorflow.util.testlog";
13
+
14
+ message EntryValue {
15
+ oneof kind {
16
+ double double_value = 1;
17
+ string string_value = 2;
18
+ }
19
+ }
20
+
21
+ message MetricEntry {
22
+ // Metric name
23
+ string name = 1;
24
+
25
+ // Metric value
26
+ double value = 2;
27
+
28
+ // The minimum acceptable value for the metric if specified
29
+ google.protobuf.DoubleValue min_value = 3;
30
+
31
+ // The maximum acceptable value for the metric if specified
32
+ google.protobuf.DoubleValue max_value = 4;
33
+ }
34
+
35
+ // Each unit test or benchmark in a test or benchmark run provides
36
+ // some set of information. Here we provide some reasonable keys
37
+ // one would expect to see, with optional key/value pairs for things
38
+ // we haven't considered.
39
+ //
40
+ // This BenchmarkEntry should be emitted by each unit test or benchmark
41
+ // reporter.
42
+ message BenchmarkEntry {
43
+ // The name of the specific benchmark or test
44
+ // (e.g. BM_AdjustContrast_gpu_B_W_H)
45
+ string name = 1;
46
+
47
+ // If a benchmark, how many iterations it was run for
48
+ int64 iters = 2;
49
+
50
+ // Total cpu time used for all iterations (in seconds)
51
+ double cpu_time = 3;
52
+
53
+ // Total wall time used for all iterations (in seconds)
54
+ double wall_time = 4;
55
+
56
+ // Throughput (in MB/s)
57
+ double throughput = 5;
58
+
59
+ // Generic map from result key to value.
60
+ map<string, EntryValue> extras = 6;
61
+
62
+ // Metric name, value and expected range. This can include accuracy metrics
63
+ // typically used to determine whether the accuracy test has passed
64
+ repeated MetricEntry metrics = 7;
65
+ }
66
+
67
+ message BenchmarkEntries {
68
+ repeated BenchmarkEntry entry = 1;
69
+ }
70
+
71
+ message BuildConfiguration {
72
+ string mode = 1; // opt, dbg, etc
73
+ repeated string cc_flags = 2; // CC compiler flags, if known
74
+ repeated string opts = 3; // Bazel compilation options, if known
75
+ }
76
+
77
+ message CommitId {
78
+ oneof kind {
79
+ // Submitted changelist.
80
+ int64 changelist = 1;
81
+ string hash = 2;
82
+ }
83
+ // Hash of intermediate change between hash/changelist and what was tested.
84
+ // Not used if the build is from a commit without modifications.
85
+ string snapshot = 3;
86
+ // Changelist tested if the change list is not already submitted.
87
+ int64 pending_changelist = 4;
88
+ }
89
+
90
+ message CPUInfo {
91
+ int64 num_cores = 1;
92
+
93
+ int64 num_cores_allowed = 2;
94
+
95
+ // How fast are these cpus?
96
+ double mhz_per_cpu = 3;
97
+
98
+ // Additional cpu information. For example,
99
+ // Intel Ivybridge with HyperThreading (24 cores) dL1:32KB dL2:256KB dL3:30MB
100
+ string cpu_info = 4;
101
+
102
+ // What kind of cpu scaling is enabled on the host.
103
+ // Examples include "performance", "ondemand", "conservative", "mixed".
104
+ string cpu_governor = 5;
105
+
106
+ // Cache sizes (in bytes), e.g. "L2": 262144 (for 256KB)
107
+ map<string, int64> cache_size = 6;
108
+ }
109
+
110
+ message MemoryInfo {
111
+ int64 total = 1; // Total virtual memory in bytes
112
+ int64 available = 2; // Immediately available memory in bytes
113
+ }
114
+
115
+ message GPUInfo {
116
+ string model = 1; // e.g. "Tesla K40c"
117
+ string uuid = 2; // Final entry in output of "nvidia-smi -L"
118
+ string bus_id = 3; // e.g. "0000:04:00.0"
119
+ }
120
+
121
+ message PlatformInfo {
122
+ string bits = 1; // e.g. '64bit'
123
+ string linkage = 2; // e.g. 'ELF'
124
+ string machine = 3; // e.g. 'i386'
125
+ string release = 4; // e.g. '3.13.0-76-generic'
126
+ string system = 5; // e.g. 'Linux'
127
+ string version = 6; // e.g. '#120-Ubuntu SMP Mon Jan 18 15:59:10 UTC 2016'
128
+ }
129
+
130
+ message AvailableDeviceInfo { // Matches DeviceAttributes
131
+ string name = 1; // Device name.
132
+ string type = 2; // Device type, e.g. 'CPU' or 'GPU'.
133
+ int64 memory_limit = 3; // Memory capacity in bytes.
134
+ string physical_description = 4; // The physical description of this device.
135
+ }
136
+
137
+ message MachineConfiguration {
138
+ // Host name of machine that ran the benchmark.
139
+ string hostname = 1;
140
+
141
+ // Unique serial number of the machine.
142
+ string serial_identifier = 7;
143
+
144
+ // Additional platform information.
145
+ PlatformInfo platform_info = 2;
146
+
147
+ // CPU Information.
148
+ CPUInfo cpu_info = 3;
149
+
150
+ // Other devices that are attached and relevant (e.g. GPUInfo).
151
+ repeated google.protobuf.Any device_info = 4;
152
+
153
+ // Devices accessible to the test (e.g. as given by list_local_devices).
154
+ repeated AvailableDeviceInfo available_device_info = 5;
155
+
156
+ MemoryInfo memory_info = 6;
157
+ }
158
+
159
+ // Run-specific items such as arguments to the test / benchmark.
160
+ message RunConfiguration {
161
+ repeated string argument = 1;
162
+ // Environment variables used to run the test/benchmark.
163
+ map<string, string> env_vars = 2;
164
+ }
165
+
166
+ // The output of one benchmark / test run. Each run contains a list of
167
+ // tests or benchmarks, stored as BenchmarkEntry messages.
168
+ //
169
+ // This message should be emitted by the reporter (which runs the
170
+ // test / BM in a subprocess and then reads the emitted BenchmarkEntry messages;
171
+ // usually from a serialized json file, finally collecting them along
172
+ // with additional information about the test run.
173
+ message TestResults {
174
+ // The target of the run, e.g.:
175
+ // //tensorflow/core:kernels_adjust_contrast_op_benchmark_test
176
+ string target = 1;
177
+
178
+ // The list of tests or benchmarks in this run.
179
+ BenchmarkEntries entries = 2;
180
+
181
+ // The configuration of the build (compiled opt? with cuda? any copts?)
182
+ BuildConfiguration build_configuration = 3;
183
+
184
+ // The commit id (git hash or changelist)
185
+ CommitId commit_id = 4;
186
+
187
+ // The time the run started (in seconds of UTC time since Unix epoch)
188
+ int64 start_time = 5;
189
+
190
+ // The amount of time the total run took (wall time in seconds)
191
+ double run_time = 6;
192
+
193
+ // Machine-specific parameters (Platform and CPU info)
194
+ MachineConfiguration machine_configuration = 7;
195
+
196
+ // Run-specific parameters (arguments, etc)
197
+ RunConfiguration run_configuration = 8;
198
+
199
+ // Benchmark target identifier.
200
+ string name = 9;
201
+
202
+ // The type of benchmark.
203
+ enum BenchmarkType {
204
+ UNKNOWN = 0; // Fallback for protos written before Type was introduced.
205
+ CPP_MICROBENCHMARK = 1;
206
+ PYTHON_BENCHMARK = 2;
207
+ ANDROID_BENCHMARK = 3;
208
+ EDGE_BENCHMARK = 4;
209
+ IOS_BENCHMARK = 5;
210
+ }
211
+ BenchmarkType benchmark_type = 10;
212
+
213
+ // Used for differentiating between continuous and debug builds.
214
+ // Must be one of:
215
+ // * cbuild: results from continuous build.
216
+ // * presubmit: results from oneshot requests.
217
+ // * culprit: results from culprit finder rerun.
218
+ string run_mode = 11;
219
+
220
+ // TensorFlow version this benchmark runs against.
221
+ // This can be either set to full version or just the major version.
222
+ string tf_version = 12;
223
+ }
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/ml_dtypes.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TENSORFLOW_TSL_PYTHON_LIB_CORE_ML_DTYPES_H_
17
+ #define TENSORFLOW_TSL_PYTHON_LIB_CORE_ML_DTYPES_H_
18
+
19
+ // Registers all custom types from the python ml_dtypes package.
20
+ // https://github.com/jax-ml/ml_dtypes
21
+
22
+ namespace tsl {
23
+ namespace ml_dtypes {
24
+
25
+ struct NumpyDtypes {
26
+ int bfloat16;
27
+ int float8_e4m3fn;
28
+ int float8_e4m3b11fnuz;
29
+ int float8_e4m3fnuz;
30
+ int float8_e5m2;
31
+ int float8_e5m2fnuz;
32
+ int int4;
33
+ int uint4;
34
+ };
35
+
36
+ // RegisterTypes imports the ml_dtypes module. It should be called before using
37
+ // the functions below, and it fails (by returning false) if there was an error
38
+ // importing that module. If the build system guarantees that the module exists,
39
+ // the call can be omitted, since it is implied by the functions below.
40
+ bool RegisterTypes();
41
+
42
+ // Implicitly calls RegisterTypes on first use.
43
+ const NumpyDtypes& GetNumpyDtypes();
44
+
45
+ inline int GetBfloat16TypeNum() { return GetNumpyDtypes().bfloat16; }
46
+
47
+ } // namespace ml_dtypes
48
+ } // namespace tsl
49
+
50
+ #endif // TENSORFLOW_TSL_PYTHON_LIB_CORE_ML_DTYPES_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/numpy.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_TSL_PYTHON_LIB_CORE_NUMPY_H_
17
+ #define TENSORFLOW_TSL_PYTHON_LIB_CORE_NUMPY_H_
18
+
19
+ #ifdef PyArray_Type
20
+ #error "Numpy cannot be included before numpy.h."
21
+ #endif
22
+
23
+ // Disallow Numpy 1.7 deprecated symbols.
24
+ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
25
+
26
+ // We import_array in the XLA init function only.
27
+ #define PY_ARRAY_UNIQUE_SYMBOL _xla_numpy_api
28
+ #ifndef XLA_IMPORT_NUMPY
29
+ #define NO_IMPORT_ARRAY
30
+ #endif
31
+
32
+ // Place `<locale>` before <Python.h> to avoid build failure in macOS.
33
+ #include <locale>
34
+
35
+ #include <Python.h>
36
+
37
+ #include "numpy/arrayobject.h"
38
+ #include "numpy/ufuncobject.h"
39
+
40
+ namespace tsl {
41
+
42
+ // Import numpy. This wrapper function exists so that the
43
+ // PY_ARRAY_UNIQUE_SYMBOL can be safely defined in a .cc file to
44
+ // avoid weird linking issues. Should be called only from our
45
+ // module initialization function.
46
+ void ImportNumpy();
47
+
48
+ } // namespace tsl
49
+
50
+ #endif // TENSORFLOW_TSL_PYTHON_LIB_CORE_NUMPY_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/byte_swap_array.h ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_TSL_UTIL_BYTE_SWAP_ARRAY_H_
17
+ #define TENSORFLOW_TSL_UTIL_BYTE_SWAP_ARRAY_H_
18
+
19
+ #include "tsl/platform/byte_order.h"
20
+ #include "tsl/platform/errors.h"
21
+ #include "tsl/platform/status.h"
22
+
23
+ // Define basic byte swapping operations.
24
+ // These operations must be macros to use compiler intrinsics.
25
+ // Note that the code here is written for portability, not speed. Byte swapping
26
+ // only happens when importing a checkpoint from one hardware architecture onto
27
+ // a different architecture. If these operations become part of a fast path,
28
+ // then the function ByteSwapArray() below should be rewritten to use
29
+ // architecture-appropriate SIMD instructions that swap multiple words at once.
30
+
31
+ #if defined(__linux__)
32
+
33
+ // Use the Gnu byte swap macros when available. See bswap(3) for more info.
34
+ #include <byteswap.h>
35
+ #define BYTE_SWAP_16(x) bswap_16(x)
36
+ #define BYTE_SWAP_32(x) bswap_32(x)
37
+ #define BYTE_SWAP_64(x) bswap_64(x)
38
+
39
+ #elif defined(PLATFORM_WINDOWS)
40
+
41
+ // On windows, byte-swapping is in winsock.h, and winsock2.h has a version of
42
+ // of htonl that can byte-swap 64-bit values.
43
+ #include <winsock2.h>
44
+ #define BYTE_SWAP_16(x) htons(x)
45
+ #define BYTE_SWAP_32(x) htonl(x)
46
+ // At the moment the 64-bit and 128-bit byte-swapping routines in Winsock2 are
47
+ // disabled in TensorFlow's standard Windows build environment, so we use
48
+ // htonl() instead of "#define BYTE_SWAP_64(x) htonll (x)".
49
+ #define BYTE_SWAP_64(x) \
50
+ ((uint64_t(htonl((x)&0x00000000ffffffffUL)) << 32) | \
51
+ (htonl(((x)&0xffffffff00000000UL) >> 32)))
52
+
53
+ #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
54
+
55
+ // On non-Linux, non-Windows, but little-endian, environments, use htonl/s,
56
+ // which byte-swap when the host byte order is little-endian. POSIX doesn't
57
+ // define a 64-bit version of these library functions, so we roll our own.
58
+ #include <arpa/inet.h>
59
+ #define BYTE_SWAP_16(x) htons(x)
60
+ #define BYTE_SWAP_32(x) htonl(x)
61
+ #define BYTE_SWAP_64(x) \
62
+ ((uint64_t(htonl((x)&0x00000000ffffffffUL)) << 32) | \
63
+ (htonl(((x)&0xffffffff00000000UL) >> 32)))
64
+
65
+ #else // not defined(__linux__) and not defined(PLATFORM_WINDOWS)
66
+ // and (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__)
67
+
68
+ // Fall back on a non-optimized implementation on other big-endian targets.
69
+ // This code swaps one byte at a time and is probably an order of magnitude
70
+ // slower.
71
+
72
+ #define BYTE_SWAP_16(x) ((((x)&0x00ff) << 8) | (((x)&0xff00) >> 8))
73
+
74
+ #define BYTE_SWAP_32(x) \
75
+ ((((x)&0x000000ffU) << 24) | (((x)&0x0000ff00U) << 8) | \
76
+ (((x)&0x00ff0000U) >> 8) | (((x)&0xff000000U) >> 24))
77
+
78
+ #define BYTE_SWAP_64(x) \
79
+ ((((x)&0x00000000000000ffUL) << 56) | (((x)&0x000000000000ff00UL) << 40) | \
80
+ (((x)&0x0000000000ff0000UL) << 24) | (((x)&0x00000000ff000000UL) << 8) | \
81
+ (((x)&0x000000ff00000000UL) >> 8) | (((x)&0x0000ff0000000000UL) >> 24) | \
82
+ (((x)&0x00ff000000000000UL) >> 40) | (((x)&0xff00000000000000UL) >> 56))
83
+
84
+ #endif // defined(__linux__)
85
+
86
+ namespace tsl {
87
+
88
+ // Byte-swap an entire array of atomic C/C++ types in place.
89
+ //
90
+ // Note: When calling this function on arrays of std::complex<> types,
91
+ // multiply the number of elements by 2 and divide the bytes per element by 2.
92
+ //
93
+ // Args:
94
+ // array: Pointer to the beginning of the array
95
+ // bytes_per_elem: Number of bytes in each element of the array
96
+ // array_len: Number of elements in the array
97
+ //
98
+ // Returns: OkStatus() on success, -1 otherwise
99
+ //
100
+ Status ByteSwapArray(char *array, size_t bytes_per_elem, int array_len);
101
+
102
+ } // namespace tsl
103
+
104
+ #endif // TENSORFLOW_TSL_UTIL_BYTE_SWAP_ARRAY_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/command_line_flags.h ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_TSL_UTIL_COMMAND_LINE_FLAGS_H_
17
+ #define TENSORFLOW_TSL_UTIL_COMMAND_LINE_FLAGS_H_
18
+
19
+ #include <functional>
20
+ #include <string>
21
+ #include <vector>
22
+
23
+ #include "tsl/platform/types.h"
24
+
25
+ namespace tsl {
26
+
27
+ // N.B. This library is for INTERNAL use only.
28
+ //
29
+ // This is a simple command-line argument parsing module to help us handle
30
+ // parameters for C++ binaries. The recommended way of using it is with local
31
+ // variables and an initializer list of Flag objects, for example:
32
+ //
33
+ // int some_int = 10;
34
+ // bool some_switch = false;
35
+ // string some_name = "something";
36
+ // std::vector<tsl::Flag> flag_list = {
37
+ // Flag("some_int", &some_int, "an integer that affects X"),
38
+ // Flag("some_switch", &some_switch, "a bool that affects Y"),
39
+ // Flag("some_name", &some_name, "a string that affects Z")
40
+ // };
41
+ // // Get usage message before ParseFlags() to capture default values.
42
+ // string usage = Flag::Usage(argv[0], flag_list);
43
+ // bool parsed_values_ok = Flags::Parse(&argc, argv, flag_list);
44
+ //
45
+ // tsl::port::InitMain(usage.c_str(), &argc, &argv);
46
+ // if (argc != 1 || !parsed_values_ok) {
47
+ // ...output usage and error message...
48
+ // }
49
+ //
50
+ // The argc and argv values are adjusted by the Parse function so all that
51
+ // remains is the program name (at argv[0]) and any unknown arguments fill the
52
+ // rest of the array. This means you can check for flags that weren't understood
53
+ // by seeing if argv is greater than 1.
54
+ // The result indicates if there were any errors parsing the values that were
55
+ // passed to the command-line switches. For example, --some_int=foo would return
56
+ // false because the argument is expected to be an integer.
57
+ //
58
+ // NOTE: Unlike gflags-style libraries, this library is intended to be
59
+ // used in the `main()` function of your binary. It does not handle
60
+ // flag definitions that are scattered around the source code.
61
+
62
+ // A description of a single command line flag, holding its name, type, usage
63
+ // text, and a pointer to the corresponding variable.
64
+ class Flag {
65
+ public:
66
+ Flag(const char* name, int32* dst, const string& usage_text,
67
+ bool* dst_updated = nullptr);
68
+ Flag(const char* name, int64_t* dst, const string& usage_text,
69
+ bool* dst_updated = nullptr);
70
+ Flag(const char* name, bool* dst, const string& usage_text,
71
+ bool* dst_updated = nullptr);
72
+ Flag(const char* name, string* dst, const string& usage_text,
73
+ bool* dst_updated = nullptr);
74
+ Flag(const char* name, float* dst, const string& usage_text,
75
+ bool* dst_updated = nullptr);
76
+
77
+ // These constructors invoke a hook on a match instead of writing to a
78
+ // specific memory location. The hook may return false to signal a malformed
79
+ // or illegal value, which will then fail the command line parse.
80
+ //
81
+ // "default_value_for_display" is shown as the default value of this flag in
82
+ // Flags::Usage().
83
+ Flag(const char* name, std::function<bool(int32_t)> int32_hook,
84
+ int32_t default_value_for_display, const string& usage_text);
85
+ Flag(const char* name, std::function<bool(int64_t)> int64_hook,
86
+ int64_t default_value_for_display, const string& usage_text);
87
+ Flag(const char* name, std::function<bool(float)> float_hook,
88
+ float default_value_for_display, const string& usage_text);
89
+ Flag(const char* name, std::function<bool(bool)> bool_hook,
90
+ bool default_value_for_display, const string& usage_text);
91
+ Flag(const char* name, std::function<bool(string)> string_hook,
92
+ string default_value_for_display, const string& usage_text);
93
+
94
+ private:
95
+ friend class Flags;
96
+
97
+ bool Parse(string arg, bool* value_parsing_ok) const;
98
+
99
+ string name_;
100
+ enum {
101
+ TYPE_INT32,
102
+ TYPE_INT64,
103
+ TYPE_BOOL,
104
+ TYPE_STRING,
105
+ TYPE_FLOAT,
106
+ } type_;
107
+
108
+ std::function<bool(int32_t)> int32_hook_;
109
+ int32 int32_default_for_display_;
110
+
111
+ std::function<bool(int64_t)> int64_hook_;
112
+ int64_t int64_default_for_display_;
113
+
114
+ std::function<bool(float)> float_hook_;
115
+ float float_default_for_display_;
116
+
117
+ std::function<bool(bool)> bool_hook_;
118
+ bool bool_default_for_display_;
119
+
120
+ std::function<bool(string)> string_hook_;
121
+ string string_default_for_display_;
122
+
123
+ string usage_text_;
124
+ };
125
+
126
+ class Flags {
127
+ public:
128
+ // Parse the command line represented by argv[0, ..., (*argc)-1] to find flag
129
+ // instances matching flags in flaglist[]. Update the variables associated
130
+ // with matching flags, and remove the matching arguments from (*argc, argv).
131
+ // Return true iff all recognized flag values were parsed correctly, and the
132
+ // first remaining argument is not "--help".
133
+ static bool Parse(int* argc, char** argv, const std::vector<Flag>& flag_list);
134
+
135
+ // Return a usage message with command line cmdline, and the
136
+ // usage_text strings in flag_list[].
137
+ static string Usage(const string& cmdline,
138
+ const std::vector<Flag>& flag_list);
139
+ };
140
+
141
+ } // namespace tsl
142
+
143
+ #endif // TENSORFLOW_TSL_UTIL_COMMAND_LINE_FLAGS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/determinism.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TENSORFLOW_TSL_UTIL_DETERMINISM_H_
17
+ #define TENSORFLOW_TSL_UTIL_DETERMINISM_H_
18
+
19
+ namespace tsl {
20
+
21
+ bool OpDeterminismRequired();
22
+ bool OpOrderDeterminismRequired();
23
+ void EnableOpDeterminism(bool enabled);
24
+
25
+ } // namespace tsl
26
+
27
+ #endif // TENSORFLOW_TSL_UTIL_DETERMINISM_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/device_name_utils.h ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_TSL_UTIL_DEVICE_NAME_UTILS_H_
17
+ #define TENSORFLOW_TSL_UTIL_DEVICE_NAME_UTILS_H_
18
+
19
+ #include <string>
20
+
21
+ #include "tsl/platform/status.h"
22
+ #include "tsl/platform/stringpiece.h"
23
+
24
+ namespace tsl {
25
+
26
+ // In TensorFlow a device name is a string of the following form:
27
+ // /job:<name>/replica:<replica>/task:<task>/device:<type>:<device_num>
28
+ //
29
+ // <name> is a short identifier conforming to the regexp
30
+ // [a-zA-Z][_a-zA-Z]*
31
+ // <type> is a supported device type (e.g. 'cpu' or 'gpu')
32
+ // <replica>, <task>, <device_num> are small non-negative integers and are
33
+ // densely allocated (except in tests).
34
+ //
35
+ // For some purposes, we also allow device patterns, which can specify
36
+ // some or none of the specific fields above, with missing components,
37
+ // or "<component>:*" indicating "any value allowed for that component.
38
+ //
39
+ // For example:
40
+ // "/job:param_server" - Consider any devices in the "param_server" job
41
+ // "/device:cpu:*" - Consider any cpu devices in any job/task/replica
42
+ // "/job:*/replica:*/task:*/device:cpu:*" - Consider any cpu devices in any
43
+ // job/task/replica
44
+ // "/job:w/replica:0/task:0/device:gpu:*" - Consider any gpu devices in
45
+ // replica 0, task 0, of job "w"
46
+ class DeviceNameUtils {
47
+ public:
48
+ // Returns a fully qualified device name given the parameters.
49
+ static std::string FullName(const std::string& job, int replica, int task,
50
+ const std::string& type, int id);
51
+
52
+ // TODO(b/278776328): Convert this to a Protobuf, since emptiness of a field
53
+ // is a standardized pattern in Protobuf.
54
+ struct ParsedName {
55
+ void Clear() {
56
+ has_job = false;
57
+ has_replica = false;
58
+ has_task = false;
59
+ has_type = false;
60
+ has_id = false;
61
+ job.clear();
62
+ replica = 0;
63
+ task = 0;
64
+ type.clear();
65
+ id = 0;
66
+ }
67
+
68
+ bool operator==(const ParsedName& other) const {
69
+ return (has_job ? (other.has_job && job == other.job) : !other.has_job) &&
70
+ (has_replica ? (other.has_replica && replica == other.replica)
71
+ : !other.has_replica) &&
72
+ (has_task ? (other.has_task && task == other.task)
73
+ : !other.has_task) &&
74
+ (has_type ? (other.has_type && type == other.type)
75
+ : !other.has_type) &&
76
+ (has_id ? (other.has_id && id == other.id) : !other.has_id);
77
+ }
78
+
79
+ bool operator!=(const ParsedName& other) const {
80
+ return !operator==(other);
81
+ }
82
+
83
+ bool operator<(const ParsedName& other) const {
84
+ if (has_job != other.has_job) return !has_job;
85
+ if (has_job) {
86
+ if (job < other.job) {
87
+ return true;
88
+ }
89
+ if (job > other.job) {
90
+ return false;
91
+ }
92
+ }
93
+ if (has_replica != other.has_replica) return !has_replica;
94
+ if (has_replica) {
95
+ if (replica < other.replica) {
96
+ return true;
97
+ }
98
+ if (replica > other.replica) {
99
+ return false;
100
+ }
101
+ }
102
+ if (has_task != other.has_task) return !has_task;
103
+ if (has_task) {
104
+ if (task < other.task) {
105
+ return true;
106
+ }
107
+ if (task > other.task) {
108
+ return false;
109
+ }
110
+ }
111
+ if (has_type != other.has_type) return !has_type;
112
+ if (has_type) {
113
+ if (type < other.type) {
114
+ return true;
115
+ }
116
+ if (type > other.type) {
117
+ return false;
118
+ }
119
+ }
120
+ if (has_id != other.has_id) return !has_id;
121
+ if (has_id) {
122
+ if (id < other.id) {
123
+ return true;
124
+ }
125
+ if (id > other.id) {
126
+ return false;
127
+ }
128
+ }
129
+ return false;
130
+ }
131
+
132
+ template <typename H>
133
+ friend H AbslHashValue(H h, const ParsedName& n) {
134
+ return H::combine(std::move(h), n.has_job, n.job, n.has_replica,
135
+ n.replica, n.has_task, n.task, n.has_type, n.type,
136
+ n.has_id, n.id);
137
+ }
138
+
139
+ bool has_job = false;
140
+ std::string job;
141
+ bool has_replica = false;
142
+ int replica = 0;
143
+ bool has_task = false;
144
+ int task = 0;
145
+ bool has_type = false;
146
+ std::string type;
147
+ bool has_id = false;
148
+ int id = 0;
149
+ };
150
+
151
+ // Parses the device name, first as a full name, then, if it fails, as a
152
+ // global one. Returns `false` if both attempts fail.
153
+ static bool ParseFullOrLocalName(StringPiece fullname, ParsedName* parsed);
154
+
155
+ // Parses "fullname" into "*parsed". Returns true iff succeeds.
156
+ // Legacy names like "/cpu:0" that don't contain "device",
157
+ // are parsed to mean their current counterparts "/device:CPU:0". More
158
+ // specifically, the lower case "cpu" and "gpu" is capitalized and "device"
159
+ // is added. "/tpu:0" is not treated the same way - it has use the current
160
+ // full syntax.
161
+ // Also, note that lower case "cpu" and "gpu" device types in current syntax
162
+ // are not capitalized. For example, "/device:CPU:0" is different from
163
+ // "/device:cpu:0"
164
+ static bool ParseFullName(StringPiece fullname, ParsedName* parsed);
165
+
166
+ // Canonicalizes "fullname" into "*canonical_name". Uses a fully specified
167
+ // basename to fill in fields that are missing. Accepts both legacy, newer
168
+ // and local versions of the device spec. Returns the newer version of the
169
+ // device spec. If we were unable to interpret / parse "fullname" returns
170
+ // an error and *canonical_name is set to "".
171
+ static Status CanonicalizeDeviceName(StringPiece fullname,
172
+ StringPiece basename,
173
+ std::string* canonical_name);
174
+
175
+ // Returns true if "name" specifies any non-trivial constraint on the device.
176
+ static bool HasSomeDetails(const ParsedName& name) {
177
+ return name.has_job || name.has_replica || name.has_task || name.has_type ||
178
+ name.has_id;
179
+ }
180
+
181
+ // Returns true if more_specific is a specification of
182
+ // less_specific, i.e. everywhere that less-specific has a
183
+ // non-wildcard component value, more_specific has the same value
184
+ // for that component.
185
+ static bool IsSpecification(const ParsedName& less_specific,
186
+ const ParsedName& more_specific);
187
+
188
+ // Makes minimal changes to more_specific so that it becomes a
189
+ // specification of less_specific.
190
+ static void EnsureSpecification(ParsedName* more_specific,
191
+ const ParsedName& less_specific);
192
+
193
+ // Like IsSpecification, but the second argument "name" must have a
194
+ // non-wildcard value for all of its components.
195
+ static bool IsCompleteSpecification(const ParsedName& pattern,
196
+ const ParsedName& name);
197
+
198
+ // True iff there exists any possible device name that is a specification of
199
+ // both "a" and "b".
200
+ static bool AreCompatibleDevNames(const ParsedName& a, const ParsedName& b);
201
+
202
+ // Merges the device specifications in "*target" and "other", and
203
+ // stores the result in "*target". Returns OK if "*target" and
204
+ // "other" are compatible, otherwise returns an error.
205
+ static Status MergeDevNames(ParsedName* target, const ParsedName& other) {
206
+ return MergeDevNames(target, other, false);
207
+ }
208
+ static Status MergeDevNames(ParsedName* target, const ParsedName& other,
209
+ bool allow_soft_placement);
210
+ // Same as MergeDevNames with allow_soft_placement=true, but instead of
211
+ // clearing conflicting fields, overrides them with `other`'s values.
212
+ static Status MergeOverrideDevNames(ParsedName* target,
213
+ const ParsedName& other);
214
+
215
+ // Merges the device specifications in "*target" and "other", and
216
+ // stores the result in "*target" by setting all unset values in target with
217
+ // corresponding set ones in other.
218
+ static void MergeUnsetDevNames(ParsedName* target, const ParsedName& other);
219
+
220
+ // Returns true iff devices identified by 'src' and 'dst' are in the
221
+ // same address space.
222
+ static bool IsSameAddressSpace(StringPiece src, StringPiece dst);
223
+ static bool IsSameAddressSpace(const ParsedName& src, const ParsedName& dst);
224
+
225
+ // Returns true iff devices identified by 'a' and 'b' are in different
226
+ // address space.
227
+ static bool IsDifferentAddressSpace(const ParsedName& a, const ParsedName& b);
228
+
229
+ // Returns the an address space specification containing only the
230
+ // job/replica/task of the given name.
231
+ static const ParsedName AddressSpace(const ParsedName& name);
232
+
233
+ // Returns the local device given its "type" and "id".
234
+ static std::string LocalName(StringPiece type, int id);
235
+
236
+ // Returns a short local device name (cpu:0, gpu:1, etc) based on
237
+ // the given fullname.
238
+ static std::string LocalName(StringPiece fullname);
239
+
240
+ // If "name" is a valid local device name (cpu:0, gpu:1, etc.),
241
+ // fills in parsed.type and parsed.id accordingly. Returns true iff
242
+ // succeeds.
243
+ static bool ParseLocalName(StringPiece name, ParsedName* parsed);
244
+
245
+ // Splits a fully-qualified device name into a task identifier and a
246
+ // relative device identifier. It first parses "name" using
247
+ // ParseFullName(), then assigns *task with everything except for
248
+ // the local device component, and assigns the relative device
249
+ // component into *device. This function will still return true if
250
+ // the task component is empty, but it requires the relative device
251
+ // component to be fully specified.
252
+ static bool SplitDeviceName(StringPiece name, std::string* task,
253
+ std::string* device);
254
+
255
+ // Get the task name from ParsedName. Return false if the task component is
256
+ // not fully specified.
257
+ static bool GetTaskName(const ParsedName& pn, std::string* task);
258
+
259
+ static std::string ParsedNameToString(const ParsedName& pn);
260
+
261
+ // Returns canonical and legacy full names for the given parsed
262
+ // device name 'pn'. The returned string names are often useful to
263
+ // look up devices from a mapping.
264
+ static std::vector<string> GetNamesForDeviceMappings(const ParsedName& pn);
265
+
266
+ // Returns canonical and legacy local names for the given parsed device name
267
+ // 'pn'. The returned string names are often useful to look up devices from a
268
+ // mapping.
269
+ static std::vector<string> GetLocalNamesForDeviceMappings(
270
+ const ParsedName& pn);
271
+
272
+ // Returns name of the CPU:0 device on the same host as the device
273
+ // `device_name`.
274
+ static Status DeviceNameToCpuDeviceName(const std::string& device_name,
275
+ std::string* host_device_name);
276
+
277
+ static bool CompareFullNames(const StringPiece& a, const StringPiece& b) {
278
+ ParsedName parsed_a;
279
+ ParsedName parsed_b;
280
+ bool a_status = ParseFullName(a, &parsed_a);
281
+ bool b_status = ParseFullName(b, &parsed_b);
282
+ // Orders unparsable names first.
283
+ if (a_status != b_status) return !a_status;
284
+ if (!a_status) return a < b;
285
+ return parsed_a < parsed_b;
286
+ }
287
+ };
288
+
289
+ std::ostream& operator<<(std::ostream& os,
290
+ const DeviceNameUtils::ParsedName& x);
291
+
292
+ } // namespace tsl
293
+
294
+ #endif // TENSORFLOW_TSL_UTIL_DEVICE_NAME_UTILS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/env_var.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_TSL_UTIL_ENV_VAR_H_
17
+ #define TENSORFLOW_TSL_UTIL_ENV_VAR_H_
18
+
19
+ #include "tsl/platform/status.h"
20
+ #include "tsl/platform/stringpiece.h"
21
+ #include "tsl/platform/types.h"
22
+
23
+ namespace tsl {
24
+
25
+ // Returns a boolean into "value" from the environmental variable
26
+ // "env_var_name". If it is unset, the default value is used. A string "0" or a
27
+ // case insensitive "false" is interpreted as false. A string "1" or a case
28
+ // insensitive "true" is interpreted as true. Otherwise, an error status is
29
+ // returned.
30
+ Status ReadBoolFromEnvVar(StringPiece env_var_name, bool default_val,
31
+ bool* value);
32
+
33
+ // Returns an int64 into "value" from the environmental variable "env_var_name".
34
+ // If it is unset, the default value is used.
35
+ // If the string cannot be parsed into int64, an error status is returned.
36
+ Status ReadInt64FromEnvVar(StringPiece env_var_name, int64_t default_val,
37
+ int64_t* value);
38
+ // Returns a float into "value" from the environmental variable "env_var_name".
39
+ // If it is unset, the default value is used.
40
+ // If the string cannot be parsed into float, an error status is returned.
41
+ Status ReadFloatFromEnvVar(StringPiece env_var_name, float default_val,
42
+ float* value);
43
+
44
+ // Returns a string into "value" from the environmental variable "env_var_name".
45
+ // If it is unset, the default value is used.
46
+ Status ReadStringFromEnvVar(StringPiece env_var_name, StringPiece default_val,
47
+ std::string* value);
48
+
49
+ // Returns a comma separated string into "value" from the environmental variable
50
+ // "env_var_name". If it is unset, the default value is comma split and used.
51
+ Status ReadStringsFromEnvVar(StringPiece env_var_name, StringPiece default_val,
52
+ std::vector<std::string>* value);
53
+
54
+ } // namespace tsl
55
+
56
+ #endif // TENSORFLOW_TSL_UTIL_ENV_VAR_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/onednn_threadpool.h ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ ==============================================================================*/
16
+
17
+ #ifndef TENSORFLOW_TSL_UTIL_ONEDNN_THREADPOOL_H_
18
+ #define TENSORFLOW_TSL_UTIL_ONEDNN_THREADPOOL_H_
19
+ #ifdef INTEL_MKL
20
+
21
+ #include <list>
22
+ #include <memory>
23
+ #include <string>
24
+ #include <unordered_map>
25
+ #include <utility>
26
+ #include <vector>
27
+
28
+ #define EIGEN_USE_THREADS
29
+
30
+ #include "dnnl.hpp"
31
+ #include "dnnl_threadpool.hpp"
32
+ #include "tsl/platform/blocking_counter.h"
33
+ #include "tsl/platform/cpu_info.h"
34
+ #include "tsl/platform/threadpool.h"
35
+
36
+ namespace tsl {
37
+
38
+ #ifndef ENABLE_ONEDNN_OPENMP
39
+ using dnnl::threadpool_interop::threadpool_iface;
40
+
41
+ // Divide 'n' units of work equally among 'teams' threads. If 'n' is not
42
+ // divisible by 'teams' and has a remainder 'r', the first 'r' teams have one
43
+ // unit of work more than the rest. Returns the range of work that belongs to
44
+ // the team 'tid'.
45
+ // Parameters
46
+ // n Total number of jobs.
47
+ // team Number of workers.
48
+ // tid Current thread_id.
49
+ // n_start start of range operated by the thread.
50
+ // n_end end of the range operated by the thread.
51
+
52
+ template <typename T, typename U>
53
+ inline void balance211(T n, U team, U tid, T* n_start, T* n_end) {
54
+ if (team <= 1 || n == 0) {
55
+ *n_start = 0;
56
+ *n_end = n;
57
+ return;
58
+ }
59
+ T min_per_team = n / team;
60
+ T remainder = n - min_per_team * team; // i.e., n % teams.
61
+ *n_start = tid * min_per_team + std::min(tid, remainder);
62
+ *n_end = *n_start + min_per_team + (tid < remainder);
63
+ }
64
+
65
+ inline void run_jobs(bool balance, int i, int n, int njobs,
66
+ const std::function<void(int, int)>& fn) {
67
+ if (balance) {
68
+ int start, end;
69
+ balance211(n, njobs, i, &start, &end);
70
+ for (int j = start; j < end; j++) fn(j, n);
71
+ } else {
72
+ fn(i, n);
73
+ }
74
+ }
75
+
76
+ class OneDnnThreadPool : public threadpool_iface {
77
+ public:
78
+ OneDnnThreadPool() = default;
79
+
80
+ OneDnnThreadPool(Eigen::ThreadPoolInterface* eigen_interface,
81
+ int num_threads = -1)
82
+ : eigen_interface_(eigen_interface) {
83
+ set_num_and_max_threads(num_threads);
84
+ }
85
+ OneDnnThreadPool(Eigen::ThreadPoolInterface* eigen_interface,
86
+ bool can_use_caller_thread, int num_threads = -1)
87
+ : eigen_interface_(eigen_interface),
88
+ can_use_caller_thread_(can_use_caller_thread) {
89
+ set_num_and_max_threads(num_threads);
90
+ }
91
+ virtual int get_num_threads() const override { return num_threads_; }
92
+ virtual bool get_in_parallel() const override {
93
+ return (eigen_interface_->CurrentThreadId() != -1) ? true : false;
94
+ }
95
+ virtual uint64_t get_flags() const override { return ASYNCHRONOUS; }
96
+ virtual void parallel_for(int n,
97
+ const std::function<void(int, int)>& fn) override {
98
+ // Should never happen (handled by DNNL)
99
+ if (n == 0) return;
100
+
101
+ // Should never happen (handled by DNNL)
102
+ if (n == 1) {
103
+ fn(0, 1);
104
+ return;
105
+ }
106
+
107
+ int nthr = get_num_threads();
108
+ int njobs = std::min(n, nthr);
109
+ bool balance = (nthr < n);
110
+
111
+ // If use_caller_thread, schedule njobs-1 jobs to thread pool and run last
112
+ // job directly.
113
+ const bool use_caller_thread =
114
+ can_use_caller_thread_ && nthr == port::NumSchedulableCPUs();
115
+ const int njobs_to_schedule = use_caller_thread ? njobs - 1 : njobs;
116
+
117
+ if (use_caller_thread) {
118
+ for (int i = 0; i < njobs_to_schedule; i++) {
119
+ eigen_interface_->ScheduleWithHint(
120
+ [balance, i, n, njobs, fn]() {
121
+ run_jobs(balance, i, n, njobs, fn);
122
+ },
123
+ i, i + 1);
124
+ }
125
+ run_jobs(balance, njobs_to_schedule, n, njobs, fn);
126
+ } else {
127
+ tsl::BlockingCounter counter(njobs);
128
+ std::function<void(int, int)> handle_range = [=, &handle_range, &counter](
129
+ int first, int last) {
130
+ while (last - first > 1) {
131
+ const auto mid = first + (last - first) / 2;
132
+ // Find something near the midpoint which is a multiple of block size.
133
+ eigen_interface_->ScheduleWithHint([=]() { handle_range(mid, last); },
134
+ mid, mid + 1);
135
+ last = mid;
136
+ }
137
+ counter.DecrementCount();
138
+ run_jobs(balance, first, n, njobs, fn);
139
+ };
140
+
141
+ // Eigen avoids a thread hop by running the root of the tree on the main
142
+ // thread. We have disabled this because it actually slows things down
143
+ // relative to base because base cheats and uses n threads while letting
144
+ // main continue doing other work
145
+ eigen_interface_->ScheduleWithHint([=]() { handle_range(0, njobs); }, 0,
146
+ 1);
147
+
148
+ counter.Wait();
149
+ }
150
+ }
151
+
152
+ ~OneDnnThreadPool() {}
153
+
154
+ private:
155
+ Eigen::ThreadPoolInterface* eigen_interface_ = nullptr;
156
+ int num_threads_ = 1; // Execute in caller thread.
157
+ bool can_use_caller_thread_ = false; // true if the user set the env variable
158
+ // to use caller thread also.
159
+ inline void set_num_and_max_threads(int num_threads) {
160
+ num_threads_ =
161
+ num_threads == -1 ? eigen_interface_->NumThreads() : num_threads;
162
+ #if DNNL_VERSION_MAJOR >= 3 || \
163
+ (DNNL_VERSION_MAJOR == 2 && DNNL_VERSION_MINOR >= 7)
164
+ #ifndef DNNL_AARCH64_USE_ACL
165
+ dnnl_threadpool_interop_set_max_concurrency(num_threads_);
166
+ #endif // DNNL_AARCH64_USE_ACL
167
+ #endif // DNNL_VERSION_MAJOR >= 3 ||
168
+ // (DNNL_VERSION_MAJOR == 2 && DNNL_VERSION_MINOR >= 7)
169
+ }
170
+ };
171
+
172
+ #else
173
+
174
+ // This class was just added to enable successful OMP-based build.
175
+ class OneDnnThreadPool {
176
+ public:
177
+ OneDnnThreadPool() = default;
178
+ OneDnnThreadPool(Eigen::ThreadPoolInterface* eigen_interface) {}
179
+ OneDnnThreadPool(Eigen::ThreadPoolInterface* eigen_interface,
180
+ bool can_use_caller_thread, int num_threads = -1) {}
181
+ };
182
+
183
+ #endif // !ENABLE_ONEDNN_OPENMP
184
+
185
+ } // namespace tsl
186
+
187
+ #endif // INTEL_MKL
188
+ #endif // TENSORFLOW_TSL_UTIL_ONEDNN_THREADPOOL_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/proto/proto_utils.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 TENSORFLOW_TSL_UTIL_PROTO_PROTO_UTILS_H_
17
+ #define TENSORFLOW_TSL_UTIL_PROTO_PROTO_UTILS_H_
18
+
19
+ #include "google/protobuf/duration.pb.h"
20
+ #include "absl/time/time.h"
21
+
22
+ namespace tsl {
23
+ namespace proto_utils {
24
+
25
+ // Converts an absl::Duration to a google::protobuf::Duration.
26
+ inline google::protobuf::Duration ToDurationProto(absl::Duration duration) {
27
+ google::protobuf::Duration proto;
28
+ proto.set_seconds(absl::IDivDuration(duration, absl::Seconds(1), &duration));
29
+ proto.set_nanos(
30
+ absl::IDivDuration(duration, absl::Nanoseconds(1), &duration));
31
+ return proto;
32
+ }
33
+
34
+ // Converts a google::protobuf::Duration to an absl::Duration.
35
+ inline absl::Duration FromDurationProto(google::protobuf::Duration proto) {
36
+ return absl::Seconds(proto.seconds()) + absl::Nanoseconds(proto.nanos());
37
+ }
38
+
39
+ } // namespace proto_utils
40
+ } // namespace tsl
41
+
42
+ #endif // TENSORFLOW_TSL_UTIL_PROTO_PROTO_UTILS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stat_summarizer_options.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TENSORFLOW_TSL_UTIL_STAT_SUMMARIZER_OPTIONS_H_
17
+ #define TENSORFLOW_TSL_UTIL_STAT_SUMMARIZER_OPTIONS_H_
18
+ namespace tsl {
19
+ // Used to control the output of the statistics summarizer;
20
+ struct StatSummarizerOptions {
21
+ StatSummarizerOptions()
22
+ : show_run_order(true),
23
+ run_order_limit(0),
24
+ show_time(true),
25
+ time_limit(10),
26
+ show_memory(true),
27
+ memory_limit(10),
28
+ show_type(true),
29
+ show_summary(true),
30
+ format_as_csv(false) {}
31
+
32
+ bool show_run_order;
33
+ int run_order_limit;
34
+ bool show_time;
35
+ int time_limit;
36
+ bool show_memory;
37
+ int memory_limit;
38
+ bool show_type;
39
+ bool show_summary;
40
+ bool format_as_csv;
41
+ };
42
+ } // namespace tsl
43
+
44
+ #endif // TENSORFLOW_TSL_UTIL_STAT_SUMMARIZER_OPTIONS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stats_calculator.h ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TENSORFLOW_TSL_UTIL_STATS_CALCULATOR_H_
17
+ #define TENSORFLOW_TSL_UTIL_STATS_CALCULATOR_H_
18
+
19
+ #include <stdlib.h>
20
+
21
+ #include <algorithm>
22
+ #include <cmath>
23
+ #include <limits>
24
+ #include <map>
25
+ #include <sstream>
26
+ #include <string>
27
+ #include <vector>
28
+
29
+ #include "tsl/util/stat_summarizer_options.h"
30
+
31
+ namespace tsl {
32
+
33
+ template <typename ValueType, typename HighPrecisionValueType = double>
34
+ class Stat {
35
+ public:
36
+ void UpdateStat(ValueType v) {
37
+ if (count_ == 0) {
38
+ first_ = v;
39
+ }
40
+
41
+ newest_ = v;
42
+ max_ = std::max(v, max_);
43
+ min_ = std::min(v, min_);
44
+ ++count_;
45
+ sum_ += v;
46
+ squared_sum_ += static_cast<HighPrecisionValueType>(v) * v;
47
+ }
48
+
49
+ void Reset() { new (this) Stat<ValueType, HighPrecisionValueType>(); }
50
+
51
+ bool empty() const { return count_ == 0; }
52
+
53
+ ValueType first() const { return first_; }
54
+
55
+ ValueType newest() const { return newest_; }
56
+
57
+ ValueType max() const { return max_; }
58
+
59
+ ValueType min() const { return min_; }
60
+
61
+ int64_t count() const { return count_; }
62
+
63
+ ValueType sum() const { return sum_; }
64
+
65
+ HighPrecisionValueType squared_sum() const { return squared_sum_; }
66
+
67
+ bool all_same() const { return (count_ == 0 || min_ == max_); }
68
+
69
+ HighPrecisionValueType avg() const {
70
+ return empty() ? std::numeric_limits<ValueType>::quiet_NaN()
71
+ : static_cast<HighPrecisionValueType>(sum_) / count_;
72
+ }
73
+
74
+ // Returns sample variance.
75
+ ValueType sample_variance() const {
76
+ return all_same()
77
+ ? 0
78
+ : (squared_sum_ - std::pow(sum_, 2.0) / count_) / (count_ - 1);
79
+ }
80
+
81
+ // Returns population variance.
82
+ ValueType variance() const {
83
+ return all_same() ? 0 : (squared_sum_ / count_) - (avg() * avg());
84
+ }
85
+
86
+ // Returns population stddev.
87
+ ValueType std_deviation() const {
88
+ return all_same() ? 0 : std::sqrt(variance());
89
+ }
90
+
91
+ void OutputToStream(std::ostream* stream) const {
92
+ if (empty()) {
93
+ *stream << "count=0";
94
+ } else if (all_same()) {
95
+ *stream << "count=" << count_ << " curr=" << newest_;
96
+ if (count_ > 1) *stream << "(all same)";
97
+ } else {
98
+ *stream << "count=" << count_ << " first=" << first_
99
+ << " curr=" << newest_ << " min=" << min_ << " max=" << max_
100
+ << " avg=" << avg() << " std=" << std_deviation();
101
+ }
102
+ }
103
+
104
+ friend std::ostream& operator<<(std::ostream& stream,
105
+ const Stat<ValueType>& stat) {
106
+ stat.OutputToStream(&stream);
107
+ return stream;
108
+ }
109
+
110
+ private:
111
+ ValueType first_ = 0;
112
+ ValueType newest_ = 0;
113
+ ValueType max_ = std::numeric_limits<ValueType>::min();
114
+ ValueType min_ = std::numeric_limits<ValueType>::max();
115
+ int64_t count_ = 0;
116
+ ValueType sum_ = 0;
117
+ HighPrecisionValueType squared_sum_ = 0;
118
+ };
119
+
120
+ // A StatsCalculator assists in performance analysis of Graph executions.
121
+ //
122
+ // It summarizes time spent executing (on GPU/CPU), memory used etc for
123
+ // graph execution.
124
+ //
125
+ // For example usage see StatsSummarizer.
126
+ class StatsCalculator {
127
+ public:
128
+ enum SortingMetric {
129
+ BY_NAME,
130
+ BY_RUN_ORDER,
131
+ BY_TIME,
132
+ BY_MEMORY,
133
+ BY_TYPE,
134
+ };
135
+
136
+ explicit StatsCalculator(const StatSummarizerOptions& options);
137
+
138
+ // Returns a string detailing the accumulated runtime stats in a tab-separated
139
+ // format which can be pasted into a spreadsheet for further analysis.
140
+ std::string GetOutputString() const;
141
+
142
+ std::string GetShortSummary() const;
143
+
144
+ void ComputeStatsByType(
145
+ std::map<std::string, int64_t>* node_type_map_count,
146
+ std::map<std::string, int64_t>* node_type_map_time,
147
+ std::map<std::string, int64_t>* node_type_map_memory,
148
+ std::map<std::string, int64_t>* node_type_map_times_called,
149
+ int64_t* accumulated_us) const;
150
+
151
+ std::string GetStatsByNodeType() const;
152
+
153
+ std::string GetStatsByMetric(const std::string& title,
154
+ SortingMetric sorting_metric,
155
+ int num_stats) const;
156
+
157
+ // Returns number of runs.
158
+ int num_runs() const { return static_cast<int>(run_total_us_.count()); }
159
+
160
+ // Returns stats of total microseconds spent by all nodes in each run.
161
+ const Stat<int64_t>& run_total_us() const { return run_total_us_; }
162
+
163
+ void UpdateRunTotalUs(int64_t run_total_us) {
164
+ run_total_us_.UpdateStat(run_total_us);
165
+ }
166
+
167
+ void UpdateMemoryUsed(int64_t memory) { memory_.UpdateStat(memory); }
168
+
169
+ struct Detail {
170
+ std::string name;
171
+ std::string type;
172
+ int64_t run_order;
173
+ Stat<int64_t> elapsed_time;
174
+ Stat<int64_t> mem_used;
175
+ int64_t times_called;
176
+ };
177
+
178
+ const std::map<std::string, Detail>& GetDetails() const { return details_; }
179
+
180
+ void AddNodeStats(const std::string& name, const std::string& type,
181
+ int64_t run_order, int64_t rel_end_us, int64_t mem_used);
182
+
183
+ private:
184
+ void OrderNodesByMetric(SortingMetric sorting_metric,
185
+ std::vector<const Detail*>* details) const;
186
+
187
+ std::string HeaderString(const std::string& title) const;
188
+ std::string ColumnString(const Detail& detail,
189
+ const int64_t cumulative_stat_on_node,
190
+ const Stat<int64_t>& stat) const;
191
+
192
+ Stat<int64_t> run_total_us_;
193
+ Stat<int64_t> memory_;
194
+
195
+ std::map<std::string, Detail> details_;
196
+ StatSummarizerOptions options_;
197
+ };
198
+
199
+ } // namespace tsl
200
+
201
+ #endif // TENSORFLOW_TSL_UTIL_STATS_CALCULATOR_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/use_cudnn.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2015 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
+ // The utility to check Cudnn dependency and set Cudnn-related flags.
17
+
18
+ #ifndef TENSORFLOW_TSL_UTIL_USE_CUDNN_H_
19
+ #define TENSORFLOW_TSL_UTIL_USE_CUDNN_H_
20
+
21
+ #include <cstdint>
22
+
23
+ namespace tsl {
24
+
25
+ bool CudnnUseAutotune();
26
+ bool CudnnUseFrontend();
27
+ bool CudnnUseRuntimeFusion();
28
+ bool CudnnRnnUseAutotune();
29
+ bool CudnnDisableConv1x1Optimization();
30
+ bool DebugCudnnRnn();
31
+ bool DebugCudnnRnnUseTensorOps();
32
+ int64_t DebugCudnnRnnAlgo();
33
+
34
+ // Returns true if the CuDNN depthwise convolution can be used. See cudnn
35
+ // release note 7.6.3.
36
+ // (https://docs.nvidia.com/deeplearning/sdk/cudnn-release-notes/rel_763.html)
37
+ bool ShouldCudnnGroupedConvolutionBeUsed(const int32_t filter_rows,
38
+ const int32_t filter_cols,
39
+ const int32_t in_depth,
40
+ const int32_t out_depth);
41
+ } // namespace tsl
42
+
43
+ #endif // TENSORFLOW_TSL_UTIL_USE_CUDNN_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AdolcForward ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2008-2009 Gael Guennebaud <g.gael@free.fr>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_ADLOC_FORWARD_MODULE_H
11
+ #define EIGEN_ADLOC_FORWARD_MODULE_H
12
+
13
+ //--------------------------------------------------------------------------------
14
+ //
15
+ // This file provides support for adolc's adouble type in forward mode.
16
+ // ADOL-C is a C++ automatic differentiation library,
17
+ // see https://projects.coin-or.org/ADOL-C for more information.
18
+ //
19
+ // Note that the maximal number of directions is controlled by
20
+ // the preprocessor token NUMBER_DIRECTIONS. The default is 2.
21
+ //
22
+ //--------------------------------------------------------------------------------
23
+
24
+ #define ADOLC_TAPELESS
25
+ #ifndef NUMBER_DIRECTIONS
26
+ # define NUMBER_DIRECTIONS 2
27
+ #endif
28
+ #include <adolc/adtl.h>
29
+
30
+ // adolc defines some very stupid macros:
31
+ #if defined(malloc)
32
+ # undef malloc
33
+ #endif
34
+
35
+ #if defined(calloc)
36
+ # undef calloc
37
+ #endif
38
+
39
+ #if defined(realloc)
40
+ # undef realloc
41
+ #endif
42
+
43
+ #include "../../Eigen/Core"
44
+
45
+ namespace Eigen {
46
+
47
+ /**
48
+ * \defgroup AdolcForward_Module Adolc forward module
49
+ * This module provides support for adolc's adouble type in forward mode.
50
+ * ADOL-C is a C++ automatic differentiation library,
51
+ * see https://projects.coin-or.org/ADOL-C for more information.
52
+ * It mainly consists in:
53
+ * - a struct Eigen::NumTraits<adtl::adouble> specialization
54
+ * - overloads of internal::* math function for adtl::adouble type.
55
+ *
56
+ * Note that the maximal number of directions is controlled by
57
+ * the preprocessor token NUMBER_DIRECTIONS. The default is 2.
58
+ *
59
+ * \code
60
+ * #include <unsupported/Eigen/AdolcSupport>
61
+ * \endcode
62
+ */
63
+ //@{
64
+
65
+ } // namespace Eigen
66
+
67
+ // Eigen's require a few additional functions which must be defined in the same namespace
68
+ // than the custom scalar type own namespace
69
+ namespace adtl {
70
+
71
+ inline const adouble& conj(const adouble& x) { return x; }
72
+ inline const adouble& real(const adouble& x) { return x; }
73
+ inline adouble imag(const adouble&) { return 0.; }
74
+ inline adouble abs(const adouble& x) { return fabs(x); }
75
+ inline adouble abs2(const adouble& x) { return x*x; }
76
+
77
+ inline bool (isinf)(const adouble& x) { return (Eigen::numext::isinf)(x.getValue()); }
78
+ inline bool (isnan)(const adouble& x) { return (Eigen::numext::isnan)(x.getValue()); }
79
+
80
+ }
81
+
82
+ namespace Eigen {
83
+
84
+ template<> struct NumTraits<adtl::adouble>
85
+ : NumTraits<double>
86
+ {
87
+ typedef adtl::adouble Real;
88
+ typedef adtl::adouble NonInteger;
89
+ typedef adtl::adouble Nested;
90
+ enum {
91
+ IsComplex = 0,
92
+ IsInteger = 0,
93
+ IsSigned = 1,
94
+ RequireInitialization = 1,
95
+ ReadCost = 1,
96
+ AddCost = 1,
97
+ MulCost = 1
98
+ };
99
+ };
100
+
101
+ template<typename Functor> class AdolcForwardJacobian : public Functor
102
+ {
103
+ typedef adtl::adouble ActiveScalar;
104
+ public:
105
+
106
+ AdolcForwardJacobian() : Functor() {}
107
+ AdolcForwardJacobian(const Functor& f) : Functor(f) {}
108
+
109
+ // forward constructors
110
+ template<typename T0>
111
+ AdolcForwardJacobian(const T0& a0) : Functor(a0) {}
112
+ template<typename T0, typename T1>
113
+ AdolcForwardJacobian(const T0& a0, const T1& a1) : Functor(a0, a1) {}
114
+ template<typename T0, typename T1, typename T2>
115
+ AdolcForwardJacobian(const T0& a0, const T1& a1, const T1& a2) : Functor(a0, a1, a2) {}
116
+
117
+ typedef typename Functor::InputType InputType;
118
+ typedef typename Functor::ValueType ValueType;
119
+ typedef typename Functor::JacobianType JacobianType;
120
+
121
+ typedef Matrix<ActiveScalar, InputType::SizeAtCompileTime, 1> ActiveInput;
122
+ typedef Matrix<ActiveScalar, ValueType::SizeAtCompileTime, 1> ActiveValue;
123
+
124
+ void operator() (const InputType& x, ValueType* v, JacobianType* _jac) const
125
+ {
126
+ eigen_assert(v!=0);
127
+ if (!_jac)
128
+ {
129
+ Functor::operator()(x, v);
130
+ return;
131
+ }
132
+
133
+ JacobianType& jac = *_jac;
134
+
135
+ ActiveInput ax = x.template cast<ActiveScalar>();
136
+ ActiveValue av(jac.rows());
137
+
138
+ for (int j=0; j<jac.cols(); j++)
139
+ for (int i=0; i<jac.cols(); i++)
140
+ ax[i].setADValue(j, i==j ? 1 : 0);
141
+
142
+ Functor::operator()(ax, &av);
143
+
144
+ for (int i=0; i<jac.rows(); i++)
145
+ {
146
+ (*v)[i] = av[i].getValue();
147
+ for (int j=0; j<jac.cols(); j++)
148
+ jac.coeffRef(i,j) = av[i].getADValue(j);
149
+ }
150
+ }
151
+ protected:
152
+
153
+ };
154
+
155
+ //@}
156
+
157
+ }
158
+
159
+ #endif // EIGEN_ADLOC_FORWARD_MODULE_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AlignedVector3 ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_ALIGNED_VECTOR3_MODULE_H
11
+ #define EIGEN_ALIGNED_VECTOR3_MODULE_H
12
+
13
+ #include "../../Eigen/Geometry"
14
+
15
+ #include "../../Eigen/src/Core/util/DisableStupidWarnings.h"
16
+
17
+ namespace Eigen {
18
+
19
+ /**
20
+ * \defgroup AlignedVector3_Module Aligned vector3 module
21
+ *
22
+ * \code
23
+ * #include <unsupported/Eigen/AlignedVector3>
24
+ * \endcode
25
+ */
26
+ //@{
27
+
28
+
29
+ /** \class AlignedVector3
30
+ *
31
+ * \brief A vectorization friendly 3D vector
32
+ *
33
+ * This class represents a 3D vector internally using a 4D vector
34
+ * such that vectorization can be seamlessly enabled. Of course,
35
+ * the same result can be achieved by directly using a 4D vector.
36
+ * This class makes this process simpler.
37
+ *
38
+ */
39
+ // TODO specialize Cwise
40
+ template<typename Scalar_> class AlignedVector3;
41
+
42
+ namespace internal {
43
+ template<typename Scalar_> struct traits<AlignedVector3<Scalar_> >
44
+ : traits<Matrix<Scalar_,3,1,0,4,1> >
45
+ {
46
+ };
47
+ }
48
+
49
+ template<typename Scalar_> class AlignedVector3
50
+ : public MatrixBase<AlignedVector3<Scalar_> >
51
+ {
52
+ typedef Matrix<Scalar_,4,1> CoeffType;
53
+ CoeffType m_coeffs;
54
+ public:
55
+
56
+ typedef MatrixBase<AlignedVector3<Scalar_> > Base;
57
+ EIGEN_DENSE_PUBLIC_INTERFACE(AlignedVector3)
58
+ using Base::operator*;
59
+
60
+ inline Index rows() const { return 3; }
61
+ inline Index cols() const { return 1; }
62
+
63
+ Scalar* data() { return m_coeffs.data(); }
64
+ const Scalar* data() const { return m_coeffs.data(); }
65
+ Index innerStride() const { return 1; }
66
+ Index outerStride() const { return 3; }
67
+
68
+ inline const Scalar& coeff(Index row, Index col) const
69
+ { return m_coeffs.coeff(row, col); }
70
+
71
+ inline Scalar& coeffRef(Index row, Index col)
72
+ { return m_coeffs.coeffRef(row, col); }
73
+
74
+ inline const Scalar& coeff(Index index) const
75
+ { return m_coeffs.coeff(index); }
76
+
77
+ inline Scalar& coeffRef(Index index)
78
+ { return m_coeffs.coeffRef(index);}
79
+
80
+
81
+ inline AlignedVector3()
82
+ {}
83
+
84
+ inline AlignedVector3(const Scalar& x, const Scalar& y, const Scalar& z)
85
+ : m_coeffs(x, y, z, Scalar(0))
86
+ {}
87
+
88
+ inline AlignedVector3(const AlignedVector3& other)
89
+ : Base(), m_coeffs(other.m_coeffs)
90
+ {}
91
+
92
+ template<typename XprType, int Size=XprType::SizeAtCompileTime>
93
+ struct generic_assign_selector {};
94
+
95
+ template<typename XprType> struct generic_assign_selector<XprType,4>
96
+ {
97
+ inline static void run(AlignedVector3& dest, const XprType& src)
98
+ {
99
+ dest.m_coeffs = src;
100
+ }
101
+ };
102
+
103
+ template<typename XprType> struct generic_assign_selector<XprType,3>
104
+ {
105
+ inline static void run(AlignedVector3& dest, const XprType& src)
106
+ {
107
+ dest.m_coeffs.template head<3>() = src;
108
+ dest.m_coeffs.w() = Scalar(0);
109
+ }
110
+ };
111
+
112
+ template<typename Derived>
113
+ inline AlignedVector3(const MatrixBase<Derived>& other)
114
+ {
115
+ generic_assign_selector<Derived>::run(*this,other.derived());
116
+ }
117
+
118
+ inline AlignedVector3& operator=(const AlignedVector3& other)
119
+ { m_coeffs = other.m_coeffs; return *this; }
120
+
121
+ template <typename Derived>
122
+ inline AlignedVector3& operator=(const MatrixBase<Derived>& other)
123
+ {
124
+ generic_assign_selector<Derived>::run(*this,other.derived());
125
+ return *this;
126
+ }
127
+
128
+ inline AlignedVector3 operator+(const AlignedVector3& other) const
129
+ { return AlignedVector3(m_coeffs + other.m_coeffs); }
130
+
131
+ inline AlignedVector3& operator+=(const AlignedVector3& other)
132
+ { m_coeffs += other.m_coeffs; return *this; }
133
+
134
+ inline AlignedVector3 operator-(const AlignedVector3& other) const
135
+ { return AlignedVector3(m_coeffs - other.m_coeffs); }
136
+
137
+ inline AlignedVector3 operator-() const
138
+ { return AlignedVector3(-m_coeffs); }
139
+
140
+ inline AlignedVector3 operator-=(const AlignedVector3& other)
141
+ { m_coeffs -= other.m_coeffs; return *this; }
142
+
143
+ inline AlignedVector3 operator*(const Scalar& s) const
144
+ { return AlignedVector3(m_coeffs * s); }
145
+
146
+ inline friend AlignedVector3 operator*(const Scalar& s,const AlignedVector3& vec)
147
+ { return AlignedVector3(s * vec.m_coeffs); }
148
+
149
+ inline AlignedVector3& operator*=(const Scalar& s)
150
+ { m_coeffs *= s; return *this; }
151
+
152
+ inline AlignedVector3 operator/(const Scalar& s) const
153
+ { return AlignedVector3(m_coeffs / s); }
154
+
155
+ inline AlignedVector3& operator/=(const Scalar& s)
156
+ { m_coeffs /= s; return *this; }
157
+
158
+ inline Scalar dot(const AlignedVector3& other) const
159
+ {
160
+ eigen_assert(m_coeffs.w()==Scalar(0));
161
+ eigen_assert(other.m_coeffs.w()==Scalar(0));
162
+ return m_coeffs.dot(other.m_coeffs);
163
+ }
164
+
165
+ inline void normalize()
166
+ {
167
+ m_coeffs /= norm();
168
+ }
169
+
170
+ inline AlignedVector3 normalized() const
171
+ {
172
+ return AlignedVector3(m_coeffs / norm());
173
+ }
174
+
175
+ inline Scalar sum() const
176
+ {
177
+ eigen_assert(m_coeffs.w()==Scalar(0));
178
+ return m_coeffs.sum();
179
+ }
180
+
181
+ inline Scalar squaredNorm() const
182
+ {
183
+ eigen_assert(m_coeffs.w()==Scalar(0));
184
+ return m_coeffs.squaredNorm();
185
+ }
186
+
187
+ inline Scalar norm() const
188
+ {
189
+ using std::sqrt;
190
+ return sqrt(squaredNorm());
191
+ }
192
+
193
+ inline AlignedVector3 cross(const AlignedVector3& other) const
194
+ {
195
+ return AlignedVector3(m_coeffs.cross3(other.m_coeffs));
196
+ }
197
+
198
+ template<typename Derived>
199
+ inline bool isApprox(const MatrixBase<Derived>& other, const RealScalar& eps=NumTraits<Scalar>::dummy_precision()) const
200
+ {
201
+ return m_coeffs.template head<3>().isApprox(other,eps);
202
+ }
203
+
204
+ CoeffType& coeffs() { return m_coeffs; }
205
+ const CoeffType& coeffs() const { return m_coeffs; }
206
+ };
207
+
208
+ namespace internal {
209
+
210
+ template<typename Scalar_>
211
+ struct eval<AlignedVector3<Scalar_>, Dense>
212
+ {
213
+ typedef const AlignedVector3<Scalar_>& type;
214
+ };
215
+
216
+ template<typename Scalar>
217
+ struct evaluator<AlignedVector3<Scalar> >
218
+ : evaluator<Matrix<Scalar,4,1> >
219
+ {
220
+ typedef AlignedVector3<Scalar> XprType;
221
+ typedef evaluator<Matrix<Scalar,4,1> > Base;
222
+
223
+ evaluator(const XprType &m) : Base(m.coeffs()) {}
224
+ };
225
+
226
+ }
227
+
228
+ //@}
229
+
230
+ }
231
+
232
+ #include "../../Eigen/src/Core/util/ReenableStupidWarnings.h"
233
+
234
+ #endif // EIGEN_ALIGNED_VECTOR3_MODULE_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/ArpackSupport ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ //
5
+ // This Source Code Form is subject to the terms of the Mozilla
6
+ // Public License v. 2.0. If a copy of the MPL was not distributed
7
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
8
+
9
+ #ifndef EIGEN_ARPACKSUPPORT_MODULE_H
10
+ #define EIGEN_ARPACKSUPPORT_MODULE_H
11
+
12
+ #include "../../Eigen/Core"
13
+
14
+ /** \defgroup ArpackSupport_Module Arpack support module
15
+ *
16
+ * This module provides a wrapper to Arpack, a library for sparse eigenvalue decomposition.
17
+ *
18
+ * \code
19
+ * #include <Eigen/ArpackSupport>
20
+ * \endcode
21
+ */
22
+
23
+ #include "../../Eigen/SparseCholesky"
24
+
25
+ #include "../../Eigen/src/Core/util/DisableStupidWarnings.h"
26
+
27
+ // IWYU pragma: begin_exports
28
+ #include "src/Eigenvalues/ArpackSelfAdjointEigenSolver.h"
29
+ // IWYU pragma: end_exports
30
+
31
+ #include "../../Eigen/src/Core/util/ReenableStupidWarnings.h"
32
+
33
+ #endif // EIGEN_ARPACKSUPPORT_MODULE_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AutoDiff ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2008-2009 Gael Guennebaud <g.gael@free.fr>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_AUTODIFF_MODULE_H
11
+ #define EIGEN_AUTODIFF_MODULE_H
12
+
13
+ #include "../../Eigen/Core"
14
+
15
+ namespace Eigen {
16
+
17
+ /**
18
+ * \defgroup AutoDiff_Module Auto Diff module
19
+ *
20
+ * This module features forward automatic differentation via a simple
21
+ * templated scalar type wrapper AutoDiffScalar.
22
+ *
23
+ * Warning : this should NOT be confused with numerical differentiation, which
24
+ * is a different method and has its own module in Eigen : \ref NumericalDiff_Module.
25
+ *
26
+ * \code
27
+ * #include <unsupported/Eigen/AutoDiff>
28
+ * \endcode
29
+ */
30
+ //@{
31
+
32
+ }
33
+ #include "../../Eigen/src/Core/util/DisableStupidWarnings.h"
34
+
35
+ // IWYU pragma: begin_exports
36
+ #include "src/AutoDiff/AutoDiffScalar.h"
37
+ // #include "src/AutoDiff/AutoDiffVector.h"
38
+ #include "src/AutoDiff/AutoDiffJacobian.h"
39
+ // IWYU pragma: end_exports
40
+
41
+ #include "../../Eigen/src/Core/util/ReenableStupidWarnings.h"
42
+
43
+
44
+
45
+ namespace Eigen {
46
+ //@}
47
+ }
48
+
49
+ #endif // EIGEN_AUTODIFF_MODULE_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/BVH ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2009 Ilya Baran <ibaran@mit.edu>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_BVH_MODULE_H
11
+ #define EIGEN_BVH_MODULE_H
12
+
13
+ #include "../../Eigen/Core"
14
+ #include "../../Eigen/Geometry"
15
+ #include "../../Eigen/StdVector"
16
+ #include <algorithm>
17
+ #include <queue>
18
+
19
+ namespace Eigen {
20
+
21
+ /**
22
+ * \defgroup BVH_Module BVH module
23
+ * \brief This module provides generic bounding volume hierarchy algorithms
24
+ * and reference tree implementations.
25
+ *
26
+ *
27
+ * \code
28
+ * #include <unsupported/Eigen/BVH>
29
+ * \endcode
30
+ *
31
+ * A bounding volume hierarchy (BVH) can accelerate many geometric queries. This module provides a generic implementation
32
+ * of the two basic algorithms over a BVH: intersection of a query object against all objects in the hierarchy and minimization
33
+ * of a function over the objects in the hierarchy. It also provides intersection and minimization over a cartesian product of
34
+ * two BVH's. A BVH accelerates intersection by using the fact that if a query object does not intersect a volume, then it cannot
35
+ * intersect any object contained in that volume. Similarly, a BVH accelerates minimization because the minimum of a function
36
+ * over a volume is no greater than the minimum of a function over any object contained in it.
37
+ *
38
+ * Some sample queries that can be written in terms of intersection are:
39
+ * - Determine all points where a ray intersects a triangle mesh
40
+ * - Given a set of points, determine which are contained in a query sphere
41
+ * - Given a set of spheres, determine which contain the query point
42
+ * - Given a set of disks, determine if any is completely contained in a query rectangle (represent each 2D disk as a point \f$(x,y,r)\f$
43
+ * in 3D and represent the rectangle as a pyramid based on the original rectangle and shrinking in the \f$r\f$ direction)
44
+ * - Given a set of points, count how many pairs are \f$d\pm\epsilon\f$ apart (done by looking at the cartesian product of the set
45
+ * of points with itself)
46
+ *
47
+ * Some sample queries that can be written in terms of function minimization over a set of objects are:
48
+ * - Find the intersection between a ray and a triangle mesh closest to the ray origin (function is infinite off the ray)
49
+ * - Given a polyline and a query point, determine the closest point on the polyline to the query
50
+ * - Find the diameter of a point cloud (done by looking at the cartesian product and using negative distance as the function)
51
+ * - Determine how far two meshes are from colliding (this is also a cartesian product query)
52
+ *
53
+ * This implementation decouples the basic algorithms both from the type of hierarchy (and the types of the bounding volumes) and
54
+ * from the particulars of the query. To enable abstraction from the BVH, the BVH is required to implement a generic mechanism
55
+ * for traversal. To abstract from the query, the query is responsible for keeping track of results.
56
+ *
57
+ * To be used in the algorithms, a hierarchy must implement the following traversal mechanism (see KdBVH for a sample implementation): \code
58
+ typedef Volume //the type of bounding volume
59
+ typedef Object //the type of object in the hierarchy
60
+ typedef Index //a reference to a node in the hierarchy--typically an int or a pointer
61
+ typedef VolumeIterator //an iterator type over node children--returns Index
62
+ typedef ObjectIterator //an iterator over object (leaf) children--returns const Object &
63
+ Index getRootIndex() const //returns the index of the hierarchy root
64
+ const Volume &getVolume(Index index) const //returns the bounding volume of the node at given index
65
+ void getChildren(Index index, VolumeIterator &outVBegin, VolumeIterator &outVEnd,
66
+ ObjectIterator &outOBegin, ObjectIterator &outOEnd) const
67
+ //getChildren takes a node index and makes [outVBegin, outVEnd) range over its node children
68
+ //and [outOBegin, outOEnd) range over its object children
69
+ \endcode
70
+ *
71
+ * To use the hierarchy, call BVIntersect or BVMinimize, passing it a BVH (or two, for cartesian product) and a minimizer or intersector.
72
+ * For an intersection query on a single BVH, the intersector encapsulates the query and must provide two functions:
73
+ * \code
74
+ bool intersectVolume(const Volume &volume) //returns true if the query intersects the volume
75
+ bool intersectObject(const Object &object) //returns true if the intersection search should terminate immediately
76
+ \endcode
77
+ * The guarantee that BVIntersect provides is that intersectObject will be called on every object whose bounding volume
78
+ * intersects the query (but possibly on other objects too) unless the search is terminated prematurely. It is the
79
+ * responsibility of the intersectObject function to keep track of the results in whatever manner is appropriate.
80
+ * The cartesian product intersection and the BVMinimize queries are similar--see their individual documentation.
81
+ *
82
+ * The following is a simple but complete example for how to use the BVH to accelerate the search for a closest red-blue point pair:
83
+ * \include BVH_Example.cpp
84
+ * Output: \verbinclude BVH_Example.out
85
+ */
86
+ }
87
+
88
+ //@{
89
+
90
+ // IWYU pragma: begin_exports
91
+ #include "src/BVH/BVAlgorithms.h"
92
+ #include "src/BVH/KdBVH.h"
93
+ // IWYU pragma: end_exports
94
+
95
+ //@}
96
+
97
+ #endif // EIGEN_BVH_MODULE_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/Tensor ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ // Copyright (C) 2013 Christian Seiler <christian@iwakd.de>
6
+ //
7
+ // This Source Code Form is subject to the terms of the Mozilla
8
+ // Public License v. 2.0. If a copy of the MPL was not distributed
9
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10
+
11
+ //#ifndef EIGEN_CXX11_TENSOR_MODULE_H
12
+ #define EIGEN_CXX11_TENSOR_MODULE_H
13
+
14
+ #include "../../../Eigen/Core"
15
+
16
+ #include "../SpecialFunctions"
17
+
18
+ #include "../../../Eigen/src/Core/util/DisableStupidWarnings.h"
19
+
20
+ // IWYU pragma: begin_exports
21
+ #include "../../../Eigen/src/Core/util/Meta.h"
22
+ #include "../../../Eigen/src/Core/util/MaxSizeVector.h"
23
+ // IWYU pragma: end_exports
24
+
25
+ /** \defgroup CXX11_Tensor_Module Tensor Module
26
+ *
27
+ * This module provides a Tensor class for storing arbitrarily indexed
28
+ * objects.
29
+ *
30
+ * \code
31
+ * #include <Eigen/CXX11/Tensor>
32
+ * \endcode
33
+ *
34
+ * Much of the documentation can be found \ref eigen_tensors "here".
35
+ */
36
+
37
+ #include <atomic>
38
+ #include <chrono>
39
+ #include <cmath>
40
+ #include <cstddef>
41
+ #include <cstring>
42
+ #include <iterator>
43
+ #include <numeric>
44
+ #include <random>
45
+ #include <thread>
46
+
47
+ #if defined(EIGEN_USE_THREADS) || defined(EIGEN_USE_SYCL)
48
+ #include "ThreadPool"
49
+ #endif
50
+
51
+ #ifdef EIGEN_USE_GPU
52
+ #include <iostream>
53
+ #if defined(EIGEN_USE_HIP)
54
+ #include <hip/hip_runtime.h>
55
+ #else
56
+ #include <cuda_runtime.h>
57
+ #endif
58
+ #endif
59
+
60
+ // IWYU pragma: begin_exports
61
+ #include "src/Tensor/TensorMacros.h"
62
+ #include "src/Tensor/TensorForwardDeclarations.h"
63
+ #include "src/Tensor/TensorMeta.h"
64
+ #include "src/Tensor/TensorFunctors.h"
65
+ #include "src/Tensor/TensorCostModel.h"
66
+ #include "src/Tensor/TensorDeviceDefault.h"
67
+ #include "src/Tensor/TensorDeviceThreadPool.h"
68
+ #include "src/Tensor/TensorDeviceGpu.h"
69
+ #ifndef gpu_assert
70
+ #define gpu_assert(x)
71
+ #endif
72
+ #include "src/Tensor/TensorDeviceSycl.h"
73
+ #include "src/Tensor/TensorIndexList.h"
74
+ #include "src/Tensor/TensorDimensionList.h"
75
+ #include "src/Tensor/TensorDimensions.h"
76
+ #include "src/Tensor/TensorInitializer.h"
77
+ #include "src/Tensor/TensorTraits.h"
78
+ #include "src/Tensor/TensorRandom.h"
79
+ #include "src/Tensor/TensorUInt128.h"
80
+ #include "src/Tensor/TensorIntDiv.h"
81
+ #include "src/Tensor/TensorGlobalFunctions.h"
82
+
83
+ #include "src/Tensor/TensorIO.h"
84
+
85
+ #include "src/Tensor/TensorBase.h"
86
+ #include "src/Tensor/TensorBlock.h"
87
+
88
+ #include "src/Tensor/TensorEvaluator.h"
89
+ #include "src/Tensor/TensorExpr.h"
90
+ #include "src/Tensor/TensorReduction.h"
91
+ #include "src/Tensor/TensorReductionGpu.h"
92
+ #include "src/Tensor/TensorArgMax.h"
93
+ #include "src/Tensor/TensorConcatenation.h"
94
+ #include "src/Tensor/TensorContractionMapper.h"
95
+ #include "src/Tensor/TensorContractionBlocking.h"
96
+ #include "src/Tensor/TensorContraction.h"
97
+ #include "src/Tensor/TensorContractionThreadPool.h"
98
+ #include "src/Tensor/TensorContractionGpu.h"
99
+ #include "src/Tensor/TensorConversion.h"
100
+ #include "src/Tensor/TensorConvolution.h"
101
+ #include "src/Tensor/TensorFFT.h"
102
+ #include "src/Tensor/TensorPatch.h"
103
+ #include "src/Tensor/TensorImagePatch.h"
104
+ #include "src/Tensor/TensorVolumePatch.h"
105
+ #include "src/Tensor/TensorBroadcasting.h"
106
+ #include "src/Tensor/TensorChipping.h"
107
+ #include "src/Tensor/TensorInflation.h"
108
+ #include "src/Tensor/TensorLayoutSwap.h"
109
+ #include "src/Tensor/TensorMorphing.h"
110
+ #include "src/Tensor/TensorPadding.h"
111
+ #include "src/Tensor/TensorReverse.h"
112
+ #include "src/Tensor/TensorShuffling.h"
113
+ #include "src/Tensor/TensorStriding.h"
114
+ #include "src/Tensor/TensorCustomOp.h"
115
+ #include "src/Tensor/TensorEvalTo.h"
116
+ #include "src/Tensor/TensorForcedEval.h"
117
+ #include "src/Tensor/TensorGenerator.h"
118
+ #include "src/Tensor/TensorAssign.h"
119
+ #include "src/Tensor/TensorScan.h"
120
+ #include "src/Tensor/TensorTrace.h"
121
+
122
+ #ifdef EIGEN_USE_SYCL
123
+ #include "src/Tensor/TensorReductionSycl.h"
124
+ #include "src/Tensor/TensorConvolutionSycl.h"
125
+ #include "src/Tensor/TensorContractionSycl.h"
126
+ #include "src/Tensor/TensorScanSycl.h"
127
+ #endif
128
+
129
+ #include "src/Tensor/TensorExecutor.h"
130
+ #include "src/Tensor/TensorDevice.h"
131
+
132
+ #include "src/Tensor/TensorStorage.h"
133
+ #include "src/Tensor/Tensor.h"
134
+ #include "src/Tensor/TensorFixedSize.h"
135
+ #include "src/Tensor/TensorMap.h"
136
+ #include "src/Tensor/TensorRef.h"
137
+ // IWYU pragma: end_exports
138
+
139
+ #include "../../../Eigen/src/Core/util/ReenableStupidWarnings.h"
140
+
141
+ //#endif // EIGEN_CXX11_TENSOR_MODULE_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/TensorSymmetry ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2013 Christian Seiler <christian@iwakd.de>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSORSYMMETRY_MODULE_H
11
+ #define EIGEN_CXX11_TENSORSYMMETRY_MODULE_H
12
+
13
+ #include "Tensor"
14
+
15
+ #include "../../../Eigen/src/Core/util/DisableStupidWarnings.h"
16
+
17
+ #include "src/util/CXX11Meta.h"
18
+
19
+ /** \defgroup CXX11_TensorSymmetry_Module Tensor Symmetry Module
20
+ *
21
+ * This module provides a classes that allow for the definition of
22
+ * symmetries w.r.t. tensor indices.
23
+ *
24
+ * Including this module will implicitly include the Tensor module.
25
+ *
26
+ * \code
27
+ * #include <Eigen/TensorSymmetry>
28
+ * \endcode
29
+ */
30
+
31
+ // IWYU pragma: begin_exports
32
+ #include "src/TensorSymmetry/util/TemplateGroupTheory.h"
33
+ #include "src/TensorSymmetry/Symmetry.h"
34
+ #include "src/TensorSymmetry/StaticSymmetry.h"
35
+ #include "src/TensorSymmetry/DynamicSymmetry.h"
36
+ // IWYU pragma: end_exports
37
+
38
+ #include "../../../Eigen/src/Core/util/ReenableStupidWarnings.h"
39
+
40
+ #endif // EIGEN_CXX11_TENSORSYMMETRY_MODULE_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/ThreadPool ADDED
@@ -0,0 +1 @@
 
 
1
+ #include "../../../Eigen/ThreadPool"
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/InternalHeaderCheck.h ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #ifndef EIGEN_CXX11_TENSOR_MODULE_H
2
+ #error "Please include unsupported/Eigen/CXX11/Tensor instead of including headers inside the src directory directly."
3
+ #endif
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/Tensor.h ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ // Copyright (C) 2013 Christian Seiler <christian@iwakd.de>
6
+ //
7
+ // This Source Code Form is subject to the terms of the Mozilla
8
+ // Public License v. 2.0. If a copy of the MPL was not distributed
9
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10
+
11
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_H
12
+ #define EIGEN_CXX11_TENSOR_TENSOR_H
13
+
14
+ #include "./InternalHeaderCheck.h"
15
+
16
+ namespace Eigen {
17
+
18
+ /** \class Tensor
19
+ * \ingroup CXX11_Tensor_Module
20
+ *
21
+ * \brief The tensor class.
22
+ *
23
+ * The %Tensor class is the work-horse for all \em dense tensors within Eigen.
24
+ *
25
+ * The %Tensor class encompasses only dynamic-size objects so far.
26
+ *
27
+ * The first two template parameters are required:
28
+ * \tparam Scalar_ Numeric type, e.g. float, double, int or `std::complex<float>`.
29
+ * User defined scalar types are supported as well (see \ref user_defined_scalars "here").
30
+ * \tparam NumIndices_ Number of indices (i.e. rank of the tensor)
31
+ *
32
+ * The remaining template parameters are optional -- in most cases you don't have to worry about them.
33
+ * \tparam Options_ A combination of either \b #RowMajor or \b #ColMajor, and of either
34
+ * \b #AutoAlign or \b #DontAlign.
35
+ * The former controls \ref TopicStorageOrders "storage order", and defaults to column-major. The latter controls alignment, which is required
36
+ * for vectorization. It defaults to aligning tensors. Note that tensors currently do not support any operations that profit from vectorization.
37
+ * Support for such operations (i.e. adding two tensors etc.) is planned.
38
+ *
39
+ * You can access elements of tensors using normal subscripting:
40
+ *
41
+ * \code
42
+ * Eigen::Tensor<double, 4> t(10, 10, 10, 10);
43
+ * t(0, 1, 2, 3) = 42.0;
44
+ * \endcode
45
+ *
46
+ * This class can be extended with the help of the plugin mechanism described on the page
47
+ * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_TENSOR_PLUGIN,
48
+ * \c EIGEN_TENSORBASE_PLUGIN, and \c EIGEN_READONLY_TENSORBASE_PLUGIN.
49
+ *
50
+ * <i><b>Some notes:</b></i>
51
+ *
52
+ * <dl>
53
+ * <dt><b>Relation to other parts of Eigen:</b></dt>
54
+ * <dd>The midterm development goal for this class is to have a similar hierarchy as Eigen uses for matrices, so that
55
+ * taking blocks or using tensors in expressions is easily possible, including an interface with the vector/matrix code
56
+ * by providing .asMatrix() and .asVector() (or similar) methods for rank 2 and 1 tensors. However, currently, the %Tensor
57
+ * class does not provide any of these features and is only available as a stand-alone class that just allows for
58
+ * coefficient access. Also, when fixed-size tensors are implemented, the number of template arguments is likely to
59
+ * change dramatically.</dd>
60
+ * </dl>
61
+ *
62
+ * \ref TopicStorageOrders
63
+ */
64
+
65
+ template<typename Scalar_, int NumIndices_, int Options_, typename IndexType_>
66
+ class Tensor : public TensorBase<Tensor<Scalar_, NumIndices_, Options_, IndexType_> >
67
+ {
68
+ public:
69
+ typedef Tensor<Scalar_, NumIndices_, Options_, IndexType_> Self;
70
+ typedef TensorBase<Tensor<Scalar_, NumIndices_, Options_, IndexType_> > Base;
71
+ typedef typename Eigen::internal::nested<Self>::type Nested;
72
+ typedef typename internal::traits<Self>::StorageKind StorageKind;
73
+ typedef typename internal::traits<Self>::Index Index;
74
+ typedef Scalar_ Scalar;
75
+ typedef typename NumTraits<Scalar>::Real RealScalar;
76
+ typedef typename Base::CoeffReturnType CoeffReturnType;
77
+
78
+ enum {
79
+ IsAligned = (EIGEN_MAX_ALIGN_BYTES>0) && !(Options_&DontAlign),
80
+ CoordAccess = true,
81
+ RawAccess = true
82
+ };
83
+
84
+ static constexpr int Layout = Options_ & RowMajor ? RowMajor : ColMajor;
85
+ static constexpr int Options = Options_;
86
+ static constexpr int NumIndices = NumIndices_;
87
+ typedef DSizes<Index, NumIndices_> Dimensions;
88
+
89
+ protected:
90
+ TensorStorage<Scalar, Dimensions, Options> m_storage;
91
+
92
+ template<typename CustomIndices>
93
+ struct isOfNormalIndex{
94
+ static const bool is_array = internal::is_base_of<array<Index, NumIndices>, CustomIndices>::value;
95
+ static const bool is_int = NumTraits<CustomIndices>::IsInteger;
96
+ static const bool value = is_array | is_int;
97
+ };
98
+
99
+ public:
100
+ // Metadata
101
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rank() const { return NumIndices; }
102
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index dimension(std::size_t n) const { return m_storage.dimensions()[n]; }
103
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_storage.dimensions(); }
104
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index size() const { return m_storage.size(); }
105
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar *data() { return m_storage.data(); }
106
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar *data() const { return m_storage.data(); }
107
+
108
+ // This makes EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED
109
+ // work, because that uses base().coeffRef() - and we don't yet
110
+ // implement a similar class hierarchy
111
+ inline Self& base() { return *this; }
112
+ inline const Self& base() const { return *this; }
113
+
114
+ template<typename... IndexTypes>
115
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff(Index firstIndex, Index secondIndex, IndexTypes... otherIndices) const
116
+ {
117
+ // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor.
118
+ EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE)
119
+ return coeff(array<Index, NumIndices>{{firstIndex, secondIndex, otherIndices...}});
120
+ }
121
+
122
+ // normal indices
123
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff(const array<Index, NumIndices>& indices) const
124
+ {
125
+ eigen_internal_assert(checkIndexRange(indices));
126
+ return m_storage.data()[linearizedIndex(indices)];
127
+ }
128
+
129
+ // custom indices
130
+ template<typename CustomIndices,
131
+ EIGEN_SFINAE_ENABLE_IF( !(isOfNormalIndex<CustomIndices>::value) )
132
+ >
133
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff(CustomIndices& indices) const
134
+ {
135
+ return coeff(internal::customIndices2Array<Index,NumIndices>(indices));
136
+ }
137
+
138
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff() const
139
+ {
140
+ EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE);
141
+ return m_storage.data()[0];
142
+ }
143
+
144
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff(Index index) const
145
+ {
146
+ eigen_internal_assert(index >= 0 && index < size());
147
+ return m_storage.data()[index];
148
+ }
149
+
150
+ template<typename... IndexTypes>
151
+ inline Scalar& coeffRef(Index firstIndex, Index secondIndex, IndexTypes... otherIndices)
152
+ {
153
+ // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor.
154
+ EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE)
155
+ return coeffRef(array<Index, NumIndices>{{firstIndex, secondIndex, otherIndices...}});
156
+ }
157
+
158
+ // normal indices
159
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(const array<Index, NumIndices>& indices)
160
+ {
161
+ eigen_internal_assert(checkIndexRange(indices));
162
+ return m_storage.data()[linearizedIndex(indices)];
163
+ }
164
+
165
+ // custom indices
166
+ template<typename CustomIndices,
167
+ EIGEN_SFINAE_ENABLE_IF( !(isOfNormalIndex<CustomIndices>::value) )
168
+ >
169
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(CustomIndices& indices)
170
+ {
171
+ return coeffRef(internal::customIndices2Array<Index,NumIndices>(indices));
172
+ }
173
+
174
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef()
175
+ {
176
+ EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE);
177
+ return m_storage.data()[0];
178
+ }
179
+
180
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index)
181
+ {
182
+ eigen_internal_assert(index >= 0 && index < size());
183
+ return m_storage.data()[index];
184
+ }
185
+
186
+ template<typename... IndexTypes>
187
+ inline const Scalar& operator()(Index firstIndex, Index secondIndex, IndexTypes... otherIndices) const
188
+ {
189
+ // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor.
190
+ EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE)
191
+ return this->operator()(array<Index, NumIndices>{{firstIndex, secondIndex, otherIndices...}});
192
+ }
193
+
194
+ // custom indices
195
+ template<typename CustomIndices,
196
+ EIGEN_SFINAE_ENABLE_IF( !(isOfNormalIndex<CustomIndices>::value) )
197
+ >
198
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator()(CustomIndices& indices) const
199
+ {
200
+ return coeff(internal::customIndices2Array<Index,NumIndices>(indices));
201
+ }
202
+
203
+ // normal indices
204
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator()(const array<Index, NumIndices>& indices) const
205
+ {
206
+ return coeff(indices);
207
+ }
208
+
209
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator()(Index index) const
210
+ {
211
+ eigen_internal_assert(index >= 0 && index < size());
212
+ return coeff(index);
213
+ }
214
+
215
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator()() const
216
+ {
217
+ EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE);
218
+ return coeff();
219
+ }
220
+
221
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator[](Index index) const
222
+ {
223
+ // The bracket operator is only for vectors, use the parenthesis operator instead.
224
+ EIGEN_STATIC_ASSERT(NumIndices == 1, YOU_MADE_A_PROGRAMMING_MISTAKE);
225
+ return coeff(index);
226
+ }
227
+
228
+ template<typename... IndexTypes>
229
+ inline Scalar& operator()(Index firstIndex, Index secondIndex, IndexTypes... otherIndices)
230
+ {
231
+ // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor.
232
+ EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE)
233
+ return operator()(array<Index, NumIndices>{{firstIndex, secondIndex, otherIndices...}});
234
+ }
235
+
236
+ // normal indices
237
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()(const array<Index, NumIndices>& indices)
238
+ {
239
+ return coeffRef(indices);
240
+ }
241
+
242
+ // custom indices
243
+ template<typename CustomIndices,
244
+ EIGEN_SFINAE_ENABLE_IF( !(isOfNormalIndex<CustomIndices>::value) )
245
+ >
246
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()(CustomIndices& indices)
247
+ {
248
+ return coeffRef(internal::customIndices2Array<Index,NumIndices>(indices));
249
+ }
250
+
251
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()(Index index)
252
+ {
253
+ eigen_assert(index >= 0 && index < size());
254
+ return coeffRef(index);
255
+ }
256
+
257
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()()
258
+ {
259
+ EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE);
260
+ return coeffRef();
261
+ }
262
+
263
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator[](Index index)
264
+ {
265
+ // The bracket operator is only for vectors, use the parenthesis operator instead
266
+ EIGEN_STATIC_ASSERT(NumIndices == 1, YOU_MADE_A_PROGRAMMING_MISTAKE)
267
+ return coeffRef(index);
268
+ }
269
+
270
+ EIGEN_DEVICE_FUNC
271
+ EIGEN_STRONG_INLINE Tensor()
272
+ : m_storage()
273
+ {
274
+ }
275
+
276
+ EIGEN_DEVICE_FUNC
277
+ EIGEN_STRONG_INLINE Tensor(const Self& other)
278
+ : Base(other), m_storage(other.m_storage)
279
+ {
280
+ }
281
+
282
+ template<typename... IndexTypes>
283
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Tensor(Index firstDimension, IndexTypes... otherDimensions)
284
+ : m_storage(firstDimension, otherDimensions...)
285
+ {
286
+ // The number of dimensions used to construct a tensor must be equal to the rank of the tensor.
287
+ EIGEN_STATIC_ASSERT(sizeof...(otherDimensions) + 1 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE)
288
+ }
289
+
290
+ /** Normal Dimension */
291
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit Tensor(const array<Index, NumIndices>& dimensions)
292
+ : m_storage(internal::array_prod(dimensions), dimensions)
293
+ {
294
+ EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED
295
+ }
296
+
297
+ template<typename OtherDerived>
298
+ EIGEN_DEVICE_FUNC
299
+ EIGEN_STRONG_INLINE Tensor(const TensorBase<OtherDerived, ReadOnlyAccessors>& other)
300
+ {
301
+ typedef TensorAssignOp<Tensor, const OtherDerived> Assign;
302
+ Assign assign(*this, other.derived());
303
+ resize(TensorEvaluator<const Assign, DefaultDevice>(assign, DefaultDevice()).dimensions());
304
+ internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice());
305
+ }
306
+
307
+ template<typename OtherDerived>
308
+ EIGEN_DEVICE_FUNC
309
+ EIGEN_STRONG_INLINE Tensor(const TensorBase<OtherDerived, WriteAccessors>& other)
310
+ {
311
+ typedef TensorAssignOp<Tensor, const OtherDerived> Assign;
312
+ Assign assign(*this, other.derived());
313
+ resize(TensorEvaluator<const Assign, DefaultDevice>(assign, DefaultDevice()).dimensions());
314
+ internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice());
315
+ }
316
+
317
+ EIGEN_DEVICE_FUNC
318
+ EIGEN_STRONG_INLINE Tensor(Self&& other)
319
+ : m_storage(std::move(other.m_storage))
320
+ {
321
+ }
322
+ EIGEN_DEVICE_FUNC
323
+ EIGEN_STRONG_INLINE Tensor& operator=(Self&& other)
324
+ {
325
+ m_storage = std::move(other.m_storage);
326
+ return *this;
327
+ }
328
+
329
+ EIGEN_DEVICE_FUNC
330
+ EIGEN_STRONG_INLINE Tensor& operator=(const Tensor& other)
331
+ {
332
+ typedef TensorAssignOp<Tensor, const Tensor> Assign;
333
+ Assign assign(*this, other);
334
+ resize(TensorEvaluator<const Assign, DefaultDevice>(assign, DefaultDevice()).dimensions());
335
+ internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice());
336
+ return *this;
337
+ }
338
+ template<typename OtherDerived>
339
+ EIGEN_DEVICE_FUNC
340
+ EIGEN_STRONG_INLINE Tensor& operator=(const OtherDerived& other)
341
+ {
342
+ typedef TensorAssignOp<Tensor, const OtherDerived> Assign;
343
+ Assign assign(*this, other);
344
+ resize(TensorEvaluator<const Assign, DefaultDevice>(assign, DefaultDevice()).dimensions());
345
+ internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice());
346
+ return *this;
347
+ }
348
+
349
+ template<typename... IndexTypes> EIGEN_DEVICE_FUNC
350
+ void resize(Index firstDimension, IndexTypes... otherDimensions)
351
+ {
352
+ // The number of dimensions used to resize a tensor must be equal to the rank of the tensor.
353
+ EIGEN_STATIC_ASSERT(sizeof...(otherDimensions) + 1 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE)
354
+ resize(array<Index, NumIndices>{{firstDimension, otherDimensions...}});
355
+ }
356
+
357
+ /** Normal Dimension */
358
+ EIGEN_DEVICE_FUNC void resize(const array<Index, NumIndices>& dimensions)
359
+ {
360
+ int i;
361
+ Index size = Index(1);
362
+ for (i = 0; i < NumIndices; i++) {
363
+ internal::check_rows_cols_for_overflow<Dynamic, Dynamic, Dynamic>::run(size, dimensions[i]);
364
+ size *= dimensions[i];
365
+ }
366
+ #ifdef EIGEN_INITIALIZE_COEFFS
367
+ bool size_changed = size != this->size();
368
+ m_storage.resize(size, dimensions);
369
+ if(size_changed) EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED
370
+ #else
371
+ m_storage.resize(size, dimensions);
372
+ #endif
373
+ }
374
+
375
+ // Why this overload, DSizes is derived from array ??? //
376
+ EIGEN_DEVICE_FUNC void resize(const DSizes<Index, NumIndices>& dimensions) {
377
+ array<Index, NumIndices> dims;
378
+ for (int i = 0; i < NumIndices; ++i) {
379
+ dims[i] = dimensions[i];
380
+ }
381
+ resize(dims);
382
+ }
383
+
384
+ EIGEN_DEVICE_FUNC
385
+ void resize()
386
+ {
387
+ EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE);
388
+ // Nothing to do: rank 0 tensors have fixed size
389
+ }
390
+
391
+ template <typename FirstType, typename... OtherTypes>
392
+ EIGEN_DEVICE_FUNC
393
+ void resize(const Eigen::IndexList<FirstType, OtherTypes...>& dimensions) {
394
+ array<Index, NumIndices> dims;
395
+ for (int i = 0; i < NumIndices; ++i) {
396
+ dims[i] = static_cast<Index>(dimensions[i]);
397
+ }
398
+ resize(dims);
399
+ }
400
+
401
+ /** Custom Dimension */
402
+ template<typename CustomDimension,
403
+ EIGEN_SFINAE_ENABLE_IF( !(isOfNormalIndex<CustomDimension>::value) )
404
+ >
405
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize(CustomDimension& dimensions)
406
+ {
407
+ resize(internal::customIndices2Array<Index,NumIndices>(dimensions));
408
+ }
409
+
410
+ #ifndef EIGEN_EMULATE_CXX11_META_H
411
+ template <typename std::ptrdiff_t... Indices>
412
+ EIGEN_DEVICE_FUNC
413
+ void resize(const Sizes<Indices...>& dimensions) {
414
+ array<Index, NumIndices> dims;
415
+ for (int i = 0; i < NumIndices; ++i) {
416
+ dims[i] = static_cast<Index>(dimensions[i]);
417
+ }
418
+ resize(dims);
419
+ }
420
+ #else
421
+ template <std::size_t V1, std::size_t V2, std::size_t V3, std::size_t V4, std::size_t V5>
422
+ EIGEN_DEVICE_FUNC
423
+ void resize(const Sizes<V1, V2, V3, V4, V5>& dimensions) {
424
+ array<Index, NumIndices> dims;
425
+ for (int i = 0; i < NumIndices; ++i) {
426
+ dims[i] = static_cast<Index>(dimensions[i]);
427
+ }
428
+ resize(dims);
429
+ }
430
+ #endif
431
+
432
+ #ifdef EIGEN_TENSOR_PLUGIN
433
+ #include EIGEN_TENSOR_PLUGIN
434
+ #endif
435
+
436
+ protected:
437
+
438
+ bool checkIndexRange(const array<Index, NumIndices>& indices) const
439
+ {
440
+ using internal::array_apply_and_reduce;
441
+ using internal::array_zip_and_reduce;
442
+ using internal::greater_equal_zero_op;
443
+ using internal::logical_and_op;
444
+ using internal::lesser_op;
445
+
446
+ return
447
+ // check whether the indices are all >= 0
448
+ array_apply_and_reduce<logical_and_op, greater_equal_zero_op>(indices) &&
449
+ // check whether the indices fit in the dimensions
450
+ array_zip_and_reduce<logical_and_op, lesser_op>(indices, m_storage.dimensions());
451
+ }
452
+
453
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index linearizedIndex(const array<Index, NumIndices>& indices) const
454
+ {
455
+ if (Options&RowMajor) {
456
+ return m_storage.dimensions().IndexOfRowMajor(indices);
457
+ } else {
458
+ return m_storage.dimensions().IndexOfColMajor(indices);
459
+ }
460
+ }
461
+ };
462
+
463
+ } // end namespace Eigen
464
+
465
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorArgMax.h ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2015 Eugene Brevdo <ebrevdo@gmail.com>
5
+ // Benoit Steiner <benoit.steiner.goog@gmail.com>
6
+ //
7
+ // This Source Code Form is subject to the terms of the Mozilla
8
+ // Public License v. 2.0. If a copy of the MPL was not distributed
9
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10
+
11
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_ARG_MAX_H
12
+ #define EIGEN_CXX11_TENSOR_TENSOR_ARG_MAX_H
13
+
14
+ #include "./InternalHeaderCheck.h"
15
+
16
+ namespace Eigen {
17
+ namespace internal {
18
+
19
+ /** \class TensorIndexPair
20
+ * \ingroup CXX11_Tensor_Module
21
+ *
22
+ * \brief Tensor + Index Pair class.
23
+ *
24
+ *
25
+ */
26
+ template<typename XprType>
27
+ struct traits<TensorIndexPairOp<XprType> > : public traits<XprType>
28
+ {
29
+ typedef traits<XprType> XprTraits;
30
+ typedef typename XprTraits::StorageKind StorageKind;
31
+ typedef typename XprTraits::Index Index;
32
+ typedef Pair<Index, typename XprTraits::Scalar> Scalar;
33
+ typedef typename XprType::Nested Nested;
34
+ typedef std::remove_reference_t<Nested> Nested_;
35
+ static constexpr int NumDimensions = XprTraits::NumDimensions;
36
+ static constexpr int Layout = XprTraits::Layout;
37
+ };
38
+
39
+ template<typename XprType>
40
+ struct eval<TensorIndexPairOp<XprType>, Eigen::Dense>
41
+ {
42
+ typedef const TensorIndexPairOp<XprType>EIGEN_DEVICE_REF type;
43
+ };
44
+
45
+ template<typename XprType>
46
+ struct nested<TensorIndexPairOp<XprType>, 1,
47
+ typename eval<TensorIndexPairOp<XprType> >::type>
48
+ {
49
+ typedef TensorIndexPairOp<XprType> type;
50
+ };
51
+
52
+ } // end namespace internal
53
+
54
+ template<typename XprType>
55
+ class TensorIndexPairOp : public TensorBase<TensorIndexPairOp<XprType>, ReadOnlyAccessors>
56
+ {
57
+ public:
58
+ typedef typename Eigen::internal::traits<TensorIndexPairOp>::Scalar Scalar;
59
+ typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
60
+ typedef typename Eigen::internal::nested<TensorIndexPairOp>::type Nested;
61
+ typedef typename Eigen::internal::traits<TensorIndexPairOp>::StorageKind StorageKind;
62
+ typedef typename Eigen::internal::traits<TensorIndexPairOp>::Index Index;
63
+ typedef Pair<Index, typename XprType::CoeffReturnType> CoeffReturnType;
64
+
65
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorIndexPairOp(const XprType& expr)
66
+ : m_xpr(expr) {}
67
+
68
+ EIGEN_DEVICE_FUNC
69
+ const internal::remove_all_t<typename XprType::Nested>&
70
+ expression() const { return m_xpr; }
71
+
72
+ protected:
73
+ typename XprType::Nested m_xpr;
74
+ };
75
+
76
+ // Eval as rvalue
77
+ template<typename ArgType, typename Device>
78
+ struct TensorEvaluator<const TensorIndexPairOp<ArgType>, Device>
79
+ {
80
+ typedef TensorIndexPairOp<ArgType> XprType;
81
+ typedef typename XprType::Index Index;
82
+ typedef typename XprType::Scalar Scalar;
83
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
84
+
85
+ typedef typename TensorEvaluator<ArgType, Device>::Dimensions Dimensions;
86
+ static constexpr int NumDims = internal::array_size<Dimensions>::value;
87
+ typedef StorageMemory<CoeffReturnType, Device> Storage;
88
+ typedef typename Storage::Type EvaluatorPointerType;
89
+
90
+ enum {
91
+ IsAligned = /*TensorEvaluator<ArgType, Device>::IsAligned*/ false,
92
+ PacketAccess = /*TensorEvaluator<ArgType, Device>::PacketAccess*/ false,
93
+ BlockAccess = false,
94
+ PreferBlockAccess = TensorEvaluator<ArgType, Device>::PreferBlockAccess,
95
+ CoordAccess = false, // to be implemented
96
+ RawAccess = false
97
+ };
98
+ static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
99
+
100
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
101
+ typedef internal::TensorBlockNotImplemented TensorBlock;
102
+ //===--------------------------------------------------------------------===//
103
+
104
+ EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
105
+ : m_impl(op.expression(), device) { }
106
+
107
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const {
108
+ return m_impl.dimensions();
109
+ }
110
+
111
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) {
112
+ m_impl.evalSubExprsIfNeeded(NULL);
113
+ return true;
114
+ }
115
+ EIGEN_STRONG_INLINE void cleanup() {
116
+ m_impl.cleanup();
117
+ }
118
+
119
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const
120
+ {
121
+ return CoeffReturnType(index, m_impl.coeff(index));
122
+ }
123
+
124
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
125
+ costPerCoeff(bool vectorized) const {
126
+ return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, 1);
127
+ }
128
+
129
+ EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; }
130
+
131
+ protected:
132
+ TensorEvaluator<ArgType, Device> m_impl;
133
+ };
134
+
135
+ namespace internal {
136
+
137
+ /** \class TensorPairIndex
138
+ * \ingroup CXX11_Tensor_Module
139
+ *
140
+ * \brief Converts to Tensor<Pair<Index, Scalar> > and reduces to Tensor<Index>.
141
+ *
142
+ */
143
+ template<typename ReduceOp, typename Dims, typename XprType>
144
+ struct traits<TensorPairReducerOp<ReduceOp, Dims, XprType> > : public traits<XprType>
145
+ {
146
+ typedef traits<XprType> XprTraits;
147
+ typedef typename XprTraits::StorageKind StorageKind;
148
+ typedef typename XprTraits::Index Index;
149
+ typedef Index Scalar;
150
+ typedef typename XprType::Nested Nested;
151
+ typedef std::remove_reference_t<Nested> Nested_;
152
+ static constexpr int NumDimensions = XprTraits::NumDimensions - array_size<Dims>::value;
153
+ static constexpr int Layout = XprTraits::Layout;
154
+ };
155
+
156
+ template<typename ReduceOp, typename Dims, typename XprType>
157
+ struct eval<TensorPairReducerOp<ReduceOp, Dims, XprType>, Eigen::Dense>
158
+ {
159
+ typedef const TensorPairReducerOp<ReduceOp, Dims, XprType>EIGEN_DEVICE_REF type;
160
+ };
161
+
162
+ template<typename ReduceOp, typename Dims, typename XprType>
163
+ struct nested<TensorPairReducerOp<ReduceOp, Dims, XprType>, 1,
164
+ typename eval<TensorPairReducerOp<ReduceOp, Dims, XprType> >::type>
165
+ {
166
+ typedef TensorPairReducerOp<ReduceOp, Dims, XprType> type;
167
+ };
168
+
169
+ } // end namespace internal
170
+
171
+ template<typename ReduceOp, typename Dims, typename XprType>
172
+ class TensorPairReducerOp : public TensorBase<TensorPairReducerOp<ReduceOp, Dims, XprType>, ReadOnlyAccessors>
173
+ {
174
+ public:
175
+ typedef typename Eigen::internal::traits<TensorPairReducerOp>::Scalar Scalar;
176
+ typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
177
+ typedef typename Eigen::internal::nested<TensorPairReducerOp>::type Nested;
178
+ typedef typename Eigen::internal::traits<TensorPairReducerOp>::StorageKind StorageKind;
179
+ typedef typename Eigen::internal::traits<TensorPairReducerOp>::Index Index;
180
+ typedef Index CoeffReturnType;
181
+
182
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorPairReducerOp(const XprType& expr,
183
+ const ReduceOp& reduce_op,
184
+ const Index return_dim,
185
+ const Dims& reduce_dims)
186
+ : m_xpr(expr), m_reduce_op(reduce_op), m_return_dim(return_dim), m_reduce_dims(reduce_dims) {}
187
+
188
+ EIGEN_DEVICE_FUNC
189
+ const internal::remove_all_t<typename XprType::Nested>&
190
+ expression() const { return m_xpr; }
191
+
192
+ EIGEN_DEVICE_FUNC
193
+ const ReduceOp& reduce_op() const { return m_reduce_op; }
194
+
195
+ EIGEN_DEVICE_FUNC
196
+ const Dims& reduce_dims() const { return m_reduce_dims; }
197
+
198
+ EIGEN_DEVICE_FUNC
199
+ Index return_dim() const { return m_return_dim; }
200
+
201
+ protected:
202
+ typename XprType::Nested m_xpr;
203
+ const ReduceOp m_reduce_op;
204
+ const Index m_return_dim;
205
+ const Dims m_reduce_dims;
206
+ };
207
+
208
+ // Eval as rvalue
209
+ template<typename ReduceOp, typename Dims, typename ArgType, typename Device>
210
+ struct TensorEvaluator<const TensorPairReducerOp<ReduceOp, Dims, ArgType>, Device>
211
+ {
212
+ typedef TensorPairReducerOp<ReduceOp, Dims, ArgType> XprType;
213
+ typedef typename XprType::Index Index;
214
+ typedef typename XprType::Scalar Scalar;
215
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
216
+ typedef typename TensorIndexPairOp<ArgType>::CoeffReturnType PairType;
217
+ typedef typename TensorEvaluator<const TensorReductionOp<ReduceOp, Dims, const TensorIndexPairOp<ArgType> >, Device>::Dimensions Dimensions;
218
+ typedef typename TensorEvaluator<const TensorIndexPairOp<ArgType> , Device>::Dimensions InputDimensions;
219
+ static constexpr int NumDims = internal::array_size<InputDimensions>::value;
220
+ typedef array<Index, NumDims> StrideDims;
221
+ typedef StorageMemory<CoeffReturnType, Device> Storage;
222
+ typedef typename Storage::Type EvaluatorPointerType;
223
+ typedef StorageMemory<PairType, Device> PairStorageMem;
224
+
225
+ enum {
226
+ IsAligned = /*TensorEvaluator<ArgType, Device>::IsAligned*/ false,
227
+ PacketAccess = /*TensorEvaluator<ArgType, Device>::PacketAccess*/ false,
228
+ BlockAccess = false,
229
+ PreferBlockAccess = TensorEvaluator<ArgType, Device>::PreferBlockAccess,
230
+ CoordAccess = false, // to be implemented
231
+ RawAccess = false
232
+ };
233
+ static constexpr int Layout = TensorEvaluator<const TensorReductionOp<ReduceOp, Dims, const TensorIndexPairOp<ArgType>>, Device>::Layout;
234
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
235
+ typedef internal::TensorBlockNotImplemented TensorBlock;
236
+ //===--------------------------------------------------------------------===//
237
+
238
+ EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
239
+ : m_orig_impl(op.expression(), device),
240
+ m_impl(op.expression().index_pairs().reduce(op.reduce_dims(), op.reduce_op()), device),
241
+ m_return_dim(op.return_dim())
242
+ {
243
+ gen_strides(m_orig_impl.dimensions(), m_strides);
244
+ if (Layout == static_cast<int>(ColMajor)) {
245
+ const Index total_size = internal::array_prod(m_orig_impl.dimensions());
246
+ m_stride_mod = (m_return_dim < NumDims - 1) ? m_strides[m_return_dim + 1] : total_size;
247
+ } else {
248
+ const Index total_size = internal::array_prod(m_orig_impl.dimensions());
249
+ m_stride_mod = (m_return_dim > 0) ? m_strides[m_return_dim - 1] : total_size;
250
+ }
251
+ // If m_return_dim is not a valid index, returns 1 or this can crash on Windows.
252
+ m_stride_div = ((m_return_dim >= 0) &&
253
+ (m_return_dim < static_cast<Index>(m_strides.size())))
254
+ ? m_strides[m_return_dim] : 1;
255
+ }
256
+
257
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const {
258
+ return m_impl.dimensions();
259
+ }
260
+
261
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) {
262
+ m_impl.evalSubExprsIfNeeded(NULL);
263
+ return true;
264
+ }
265
+ EIGEN_STRONG_INLINE void cleanup() {
266
+ m_impl.cleanup();
267
+ }
268
+
269
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
270
+ const PairType v = m_impl.coeff(index);
271
+ return (m_return_dim < 0) ? v.first : (v.first % m_stride_mod) / m_stride_div;
272
+ }
273
+
274
+ EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; }
275
+
276
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
277
+ costPerCoeff(bool vectorized) const {
278
+ const double compute_cost = 1.0 +
279
+ (m_return_dim < 0 ? 0.0 : (TensorOpCost::ModCost<Index>() + TensorOpCost::DivCost<Index>()));
280
+ return m_orig_impl.costPerCoeff(vectorized) +
281
+ m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, compute_cost);
282
+ }
283
+
284
+ private:
285
+ EIGEN_DEVICE_FUNC void gen_strides(const InputDimensions& dims, StrideDims& strides) {
286
+ if (m_return_dim < 0) {
287
+ return; // Won't be using the strides.
288
+ }
289
+ eigen_assert(m_return_dim < NumDims &&
290
+ "Asking to convert index to a dimension outside of the rank");
291
+
292
+ // Calculate m_stride_div and m_stride_mod, which are used to
293
+ // calculate the value of an index w.r.t. the m_return_dim.
294
+ if (Layout == static_cast<int>(ColMajor)) {
295
+ strides[0] = 1;
296
+ for (int i = 1; i < NumDims; ++i) {
297
+ strides[i] = strides[i-1] * dims[i-1];
298
+ }
299
+ } else {
300
+ strides[NumDims-1] = 1;
301
+ for (int i = NumDims - 2; i >= 0; --i) {
302
+ strides[i] = strides[i+1] * dims[i+1];
303
+ }
304
+ }
305
+ }
306
+
307
+ protected:
308
+ TensorEvaluator<const TensorIndexPairOp<ArgType>, Device> m_orig_impl;
309
+ TensorEvaluator<const TensorReductionOp<ReduceOp, Dims, const TensorIndexPairOp<ArgType> >, Device> m_impl;
310
+ const Index m_return_dim;
311
+ StrideDims m_strides;
312
+ Index m_stride_mod;
313
+ Index m_stride_div;
314
+ };
315
+
316
+ } // end namespace Eigen
317
+
318
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_ARG_MAX_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorAssign.h ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_ASSIGN_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_ASSIGN_H
12
+
13
+ #include "./InternalHeaderCheck.h"
14
+
15
+ namespace Eigen {
16
+
17
+ /** \class TensorAssign
18
+ * \ingroup CXX11_Tensor_Module
19
+ *
20
+ * \brief The tensor assignment class.
21
+ *
22
+ * This class is represents the assignment of the values resulting from the evaluation of
23
+ * the rhs expression to the memory locations denoted by the lhs expression.
24
+ */
25
+ namespace internal {
26
+ template<typename LhsXprType, typename RhsXprType>
27
+ struct traits<TensorAssignOp<LhsXprType, RhsXprType> >
28
+ {
29
+ typedef typename LhsXprType::Scalar Scalar;
30
+ typedef typename traits<LhsXprType>::StorageKind StorageKind;
31
+ typedef typename promote_index_type<typename traits<LhsXprType>::Index,
32
+ typename traits<RhsXprType>::Index>::type Index;
33
+ typedef typename LhsXprType::Nested LhsNested;
34
+ typedef typename RhsXprType::Nested RhsNested;
35
+ typedef std::remove_reference_t<LhsNested> LhsNested_;
36
+ typedef std::remove_reference_t<RhsNested> RhsNested_;
37
+ static constexpr std::size_t NumDimensions = internal::traits<LhsXprType>::NumDimensions;
38
+ static constexpr int Layout = internal::traits<LhsXprType>::Layout;
39
+ typedef typename traits<LhsXprType>::PointerType PointerType;
40
+
41
+ enum {
42
+ Flags = 0
43
+ };
44
+ };
45
+
46
+ template<typename LhsXprType, typename RhsXprType>
47
+ struct eval<TensorAssignOp<LhsXprType, RhsXprType>, Eigen::Dense>
48
+ {
49
+ typedef const TensorAssignOp<LhsXprType, RhsXprType>& type;
50
+ };
51
+
52
+ template<typename LhsXprType, typename RhsXprType>
53
+ struct nested<TensorAssignOp<LhsXprType, RhsXprType>, 1, typename eval<TensorAssignOp<LhsXprType, RhsXprType> >::type>
54
+ {
55
+ typedef TensorAssignOp<LhsXprType, RhsXprType> type;
56
+ };
57
+
58
+ } // end namespace internal
59
+
60
+
61
+
62
+ template<typename LhsXprType, typename RhsXprType>
63
+ class TensorAssignOp : public TensorBase<TensorAssignOp<LhsXprType, RhsXprType> >
64
+ {
65
+ public:
66
+ typedef typename Eigen::internal::traits<TensorAssignOp>::Scalar Scalar;
67
+ typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
68
+ typedef typename LhsXprType::CoeffReturnType CoeffReturnType;
69
+ typedef typename Eigen::internal::nested<TensorAssignOp>::type Nested;
70
+ typedef typename Eigen::internal::traits<TensorAssignOp>::StorageKind StorageKind;
71
+ typedef typename Eigen::internal::traits<TensorAssignOp>::Index Index;
72
+
73
+ static constexpr int NumDims = Eigen::internal::traits<TensorAssignOp>::NumDimensions;
74
+
75
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorAssignOp(LhsXprType& lhs, const RhsXprType& rhs)
76
+ : m_lhs_xpr(lhs), m_rhs_xpr(rhs) {}
77
+
78
+ /** \returns the nested expressions */
79
+ EIGEN_DEVICE_FUNC
80
+ internal::remove_all_t<typename LhsXprType::Nested>&
81
+ lhsExpression() const { return *((internal::remove_all_t<typename LhsXprType::Nested>*)&m_lhs_xpr); }
82
+
83
+ EIGEN_DEVICE_FUNC
84
+ const internal::remove_all_t<typename RhsXprType::Nested>&
85
+ rhsExpression() const { return m_rhs_xpr; }
86
+
87
+ protected:
88
+ internal::remove_all_t<typename LhsXprType::Nested>& m_lhs_xpr;
89
+ const internal::remove_all_t<typename RhsXprType::Nested>& m_rhs_xpr;
90
+ };
91
+
92
+
93
+ template<typename LeftArgType, typename RightArgType, typename Device>
94
+ struct TensorEvaluator<const TensorAssignOp<LeftArgType, RightArgType>, Device>
95
+ {
96
+ typedef TensorAssignOp<LeftArgType, RightArgType> XprType;
97
+ typedef typename XprType::Index Index;
98
+ typedef typename XprType::Scalar Scalar;
99
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
100
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
101
+ typedef typename TensorEvaluator<RightArgType, Device>::Dimensions Dimensions;
102
+ typedef StorageMemory<CoeffReturnType, Device> Storage;
103
+ typedef typename Storage::Type EvaluatorPointerType;
104
+
105
+ static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
106
+ static constexpr int NumDims = XprType::NumDims;
107
+ static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
108
+
109
+ enum {
110
+ IsAligned = int(TensorEvaluator<LeftArgType, Device>::IsAligned) &
111
+ int(TensorEvaluator<RightArgType, Device>::IsAligned),
112
+ PacketAccess = int(TensorEvaluator<LeftArgType, Device>::PacketAccess) &
113
+ int(TensorEvaluator<RightArgType, Device>::PacketAccess),
114
+ BlockAccess = int(TensorEvaluator<LeftArgType, Device>::BlockAccess) &
115
+ int(TensorEvaluator<RightArgType, Device>::BlockAccess),
116
+ PreferBlockAccess = int(TensorEvaluator<LeftArgType, Device>::PreferBlockAccess) |
117
+ int(TensorEvaluator<RightArgType, Device>::PreferBlockAccess),
118
+ RawAccess = TensorEvaluator<LeftArgType, Device>::RawAccess
119
+ };
120
+
121
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
122
+ typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
123
+ typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
124
+
125
+ typedef typename TensorEvaluator<const RightArgType, Device>::TensorBlock
126
+ RightTensorBlock;
127
+ //===--------------------------------------------------------------------===//
128
+
129
+ TensorEvaluator(const XprType& op, const Device& device) :
130
+ m_leftImpl(op.lhsExpression(), device),
131
+ m_rightImpl(op.rhsExpression(), device)
132
+ {
133
+ EIGEN_STATIC_ASSERT(
134
+ (static_cast<int>(TensorEvaluator<LeftArgType, Device>::Layout) ==
135
+ static_cast<int>(TensorEvaluator<RightArgType, Device>::Layout)),
136
+ YOU_MADE_A_PROGRAMMING_MISTAKE);
137
+ }
138
+
139
+ EIGEN_DEVICE_FUNC const Dimensions& dimensions() const
140
+ {
141
+ // The dimensions of the lhs and the rhs tensors should be equal to prevent
142
+ // overflows and ensure the result is fully initialized.
143
+ // TODO: use left impl instead if right impl dimensions are known at compile time.
144
+ return m_rightImpl.dimensions();
145
+ }
146
+
147
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
148
+ eigen_assert(dimensions_match(m_leftImpl.dimensions(), m_rightImpl.dimensions()));
149
+ m_leftImpl.evalSubExprsIfNeeded(NULL);
150
+ // If the lhs provides raw access to its storage area (i.e. if m_leftImpl.data() returns a non
151
+ // null value), attempt to evaluate the rhs expression in place. Returns true iff in place
152
+ // evaluation isn't supported and the caller still needs to manually assign the values generated
153
+ // by the rhs to the lhs.
154
+ return m_rightImpl.evalSubExprsIfNeeded(m_leftImpl.data());
155
+ }
156
+
157
+ #ifdef EIGEN_USE_THREADS
158
+ template <typename EvalSubExprsCallback>
159
+ EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(
160
+ EvaluatorPointerType, EvalSubExprsCallback done) {
161
+ m_leftImpl.evalSubExprsIfNeededAsync(nullptr, [this, done](bool) {
162
+ m_rightImpl.evalSubExprsIfNeededAsync(
163
+ m_leftImpl.data(), [done](bool need_assign) { done(need_assign); });
164
+ });
165
+ }
166
+ #endif // EIGEN_USE_THREADS
167
+
168
+ EIGEN_STRONG_INLINE void cleanup() {
169
+ m_leftImpl.cleanup();
170
+ m_rightImpl.cleanup();
171
+ }
172
+
173
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalScalar(Index i) const {
174
+ m_leftImpl.coeffRef(i) = m_rightImpl.coeff(i);
175
+ }
176
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalPacket(Index i) const {
177
+
178
+ const int LhsStoreMode = TensorEvaluator<LeftArgType, Device>::IsAligned ? Aligned : Unaligned;
179
+ const int RhsLoadMode = TensorEvaluator<RightArgType, Device>::IsAligned ? Aligned : Unaligned;
180
+ m_leftImpl.template writePacket<LhsStoreMode>(i, m_rightImpl.template packet<RhsLoadMode>(i));
181
+ }
182
+ EIGEN_DEVICE_FUNC CoeffReturnType coeff(Index index) const
183
+ {
184
+ return m_leftImpl.coeff(index);
185
+ }
186
+ template<int LoadMode>
187
+ EIGEN_DEVICE_FUNC PacketReturnType packet(Index index) const
188
+ {
189
+ return m_leftImpl.template packet<LoadMode>(index);
190
+ }
191
+
192
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
193
+ costPerCoeff(bool vectorized) const {
194
+ // We assume that evalPacket or evalScalar is called to perform the
195
+ // assignment and account for the cost of the write here, but reduce left
196
+ // cost by one load because we are using m_leftImpl.coeffRef.
197
+ TensorOpCost left = m_leftImpl.costPerCoeff(vectorized);
198
+ return m_rightImpl.costPerCoeff(vectorized) +
199
+ TensorOpCost(
200
+ numext::maxi(0.0, left.bytes_loaded() - sizeof(CoeffReturnType)),
201
+ left.bytes_stored(), left.compute_cycles()) +
202
+ TensorOpCost(0, sizeof(CoeffReturnType), 0, vectorized, PacketSize);
203
+ }
204
+
205
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
206
+ internal::TensorBlockResourceRequirements getResourceRequirements() const {
207
+ return internal::TensorBlockResourceRequirements::merge(
208
+ m_leftImpl.getResourceRequirements(),
209
+ m_rightImpl.getResourceRequirements());
210
+ }
211
+
212
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalBlock(
213
+ TensorBlockDesc& desc, TensorBlockScratch& scratch) {
214
+ if (TensorEvaluator<LeftArgType, Device>::RawAccess &&
215
+ m_leftImpl.data() != NULL) {
216
+ // If destination has raw data access, we pass it as a potential
217
+ // destination for a block descriptor evaluation.
218
+ desc.template AddDestinationBuffer<Layout>(
219
+ /*dst_base=*/m_leftImpl.data() + desc.offset(),
220
+ /*dst_strides=*/internal::strides<Layout>(m_leftImpl.dimensions()));
221
+ }
222
+
223
+ RightTensorBlock block = m_rightImpl.block(desc, scratch, /*root_of_expr_ast=*/true);
224
+ // If block was evaluated into a destination, there is no need to do assignment.
225
+ if (block.kind() != internal::TensorBlockKind::kMaterializedInOutput) {
226
+ m_leftImpl.writeBlock(desc, block);
227
+ }
228
+ block.cleanup();
229
+ }
230
+
231
+ EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_leftImpl.data(); }
232
+
233
+ private:
234
+ TensorEvaluator<LeftArgType, Device> m_leftImpl;
235
+ TensorEvaluator<RightArgType, Device> m_rightImpl;
236
+ };
237
+
238
+ }
239
+
240
+
241
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_ASSIGN_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBase.h ADDED
@@ -0,0 +1,1222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_BASE_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_BASE_H
12
+
13
+ // clang-format off
14
+
15
+ #include "./InternalHeaderCheck.h"
16
+
17
+ namespace Eigen {
18
+
19
+ /** \class TensorBase
20
+ * \ingroup CXX11_Tensor_Module
21
+ *
22
+ * \brief The tensor base class.
23
+ *
24
+ * This class is the common parent of the Tensor and TensorMap class, thus
25
+ * making it possible to use either class interchangeably in expressions.
26
+ */
27
+ #ifndef EIGEN_PARSED_BY_DOXYGEN
28
+ // FIXME Doxygen does not like the inheritance with different template parameters
29
+ // Since there is no doxygen documentation inside, we disable it for now
30
+ template<typename Derived>
31
+ class TensorBase<Derived, ReadOnlyAccessors>
32
+ {
33
+ public:
34
+ typedef internal::traits<Derived> DerivedTraits;
35
+ typedef typename DerivedTraits::Scalar Scalar;
36
+ typedef typename DerivedTraits::Index Index;
37
+ typedef std::remove_const_t<Scalar> CoeffReturnType;
38
+ static constexpr int NumDimensions = DerivedTraits::NumDimensions;
39
+
40
+ // Generic nullary operation support.
41
+ template <typename CustomNullaryOp> EIGEN_DEVICE_FUNC
42
+ EIGEN_STRONG_INLINE const TensorCwiseNullaryOp<CustomNullaryOp, const Derived>
43
+ nullaryExpr(const CustomNullaryOp& func) const {
44
+ return TensorCwiseNullaryOp<CustomNullaryOp, const Derived>(derived(), func);
45
+ }
46
+
47
+ // Coefficient-wise nullary operators
48
+ EIGEN_DEVICE_FUNC
49
+ EIGEN_STRONG_INLINE const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived>
50
+ constant(const Scalar& value) const {
51
+ return nullaryExpr(internal::scalar_constant_op<Scalar>(value));
52
+ }
53
+
54
+ EIGEN_DEVICE_FUNC
55
+ EIGEN_STRONG_INLINE const TensorCwiseNullaryOp<internal::UniformRandomGenerator<Scalar>, const Derived>
56
+ random() const {
57
+ return nullaryExpr(internal::UniformRandomGenerator<Scalar>());
58
+ }
59
+ template <typename RandomGenerator> EIGEN_DEVICE_FUNC
60
+ EIGEN_STRONG_INLINE const TensorCwiseNullaryOp<RandomGenerator, const Derived>
61
+ random(const RandomGenerator& gen = RandomGenerator()) const {
62
+ return nullaryExpr(gen);
63
+ }
64
+
65
+ // Tensor generation
66
+ template <typename Generator> EIGEN_DEVICE_FUNC
67
+ EIGEN_STRONG_INLINE const TensorGeneratorOp<Generator, const Derived>
68
+ generate(const Generator& generator) const {
69
+ return TensorGeneratorOp<Generator, const Derived>(derived(), generator);
70
+ }
71
+
72
+ // Generic unary operation support.
73
+ template <typename CustomUnaryOp> EIGEN_DEVICE_FUNC
74
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<CustomUnaryOp, const Derived>
75
+ unaryExpr(const CustomUnaryOp& func) const {
76
+ return TensorCwiseUnaryOp<CustomUnaryOp, const Derived>(derived(), func);
77
+ }
78
+
79
+ // Coefficient-wise unary operators
80
+ EIGEN_DEVICE_FUNC
81
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_opposite_op<Scalar>, const Derived>
82
+ operator-() const {
83
+ return unaryExpr(internal::scalar_opposite_op<Scalar>());
84
+ }
85
+
86
+ EIGEN_DEVICE_FUNC
87
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_sqrt_op<Scalar>, const Derived>
88
+ sqrt() const {
89
+ return unaryExpr(internal::scalar_sqrt_op<Scalar>());
90
+ }
91
+
92
+ EIGEN_DEVICE_FUNC
93
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_sign_op<Scalar>, const Derived>
94
+ sign() const {
95
+ return unaryExpr(internal::scalar_sign_op<Scalar>());
96
+ }
97
+
98
+ EIGEN_DEVICE_FUNC
99
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_rsqrt_op<Scalar>, const Derived>
100
+ rsqrt() const {
101
+ return unaryExpr(internal::scalar_rsqrt_op<Scalar>());
102
+ }
103
+
104
+ EIGEN_DEVICE_FUNC
105
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_square_op<Scalar>, const Derived>
106
+ square() const {
107
+ return unaryExpr(internal::scalar_square_op<Scalar>());
108
+ }
109
+
110
+ EIGEN_DEVICE_FUNC
111
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_cube_op<Scalar>, const Derived>
112
+ cube() const {
113
+ return unaryExpr(internal::scalar_cube_op<Scalar>());
114
+ }
115
+
116
+ EIGEN_DEVICE_FUNC
117
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_inverse_op<Scalar>, const Derived>
118
+ inverse() const {
119
+ return unaryExpr(internal::scalar_inverse_op<Scalar>());
120
+ }
121
+
122
+ EIGEN_DEVICE_FUNC
123
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_tanh_op<Scalar>, const Derived>
124
+ tanh() const {
125
+ return unaryExpr(internal::scalar_tanh_op<Scalar>());
126
+ }
127
+
128
+ EIGEN_DEVICE_FUNC
129
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_lgamma_op<Scalar>, const Derived>
130
+ lgamma() const {
131
+ return unaryExpr(internal::scalar_lgamma_op<Scalar>());
132
+ }
133
+
134
+ EIGEN_DEVICE_FUNC
135
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_digamma_op<Scalar>, const Derived>
136
+ digamma() const {
137
+ return unaryExpr(internal::scalar_digamma_op<Scalar>());
138
+ }
139
+
140
+ EIGEN_DEVICE_FUNC
141
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_i0_op<Scalar>, const Derived>
142
+ bessel_i0() const {
143
+ return unaryExpr(internal::scalar_bessel_i0_op<Scalar>());
144
+ }
145
+
146
+ EIGEN_DEVICE_FUNC
147
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_i0e_op<Scalar>, const Derived>
148
+ bessel_i0e() const {
149
+ return unaryExpr(internal::scalar_bessel_i0e_op<Scalar>());
150
+ }
151
+
152
+ EIGEN_DEVICE_FUNC
153
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_i1_op<Scalar>, const Derived>
154
+ bessel_i1() const {
155
+ return unaryExpr(internal::scalar_bessel_i1_op<Scalar>());
156
+ }
157
+
158
+ EIGEN_DEVICE_FUNC
159
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_i1e_op<Scalar>, const Derived>
160
+ bessel_i1e() const {
161
+ return unaryExpr(internal::scalar_bessel_i1e_op<Scalar>());
162
+ }
163
+
164
+ EIGEN_DEVICE_FUNC
165
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_j0_op<Scalar>, const Derived>
166
+ bessel_j0() const {
167
+ return unaryExpr(internal::scalar_bessel_j0_op<Scalar>());
168
+ }
169
+
170
+ EIGEN_DEVICE_FUNC
171
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_y0_op<Scalar>, const Derived>
172
+ bessel_y0() const {
173
+ return unaryExpr(internal::scalar_bessel_y0_op<Scalar>());
174
+ }
175
+
176
+ EIGEN_DEVICE_FUNC
177
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_j1_op<Scalar>, const Derived>
178
+ bessel_j1() const {
179
+ return unaryExpr(internal::scalar_bessel_j1_op<Scalar>());
180
+ }
181
+
182
+ EIGEN_DEVICE_FUNC
183
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_y1_op<Scalar>, const Derived>
184
+ bessel_y1() const {
185
+ return unaryExpr(internal::scalar_bessel_y1_op<Scalar>());
186
+ }
187
+
188
+ EIGEN_DEVICE_FUNC
189
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_k0_op<Scalar>, const Derived>
190
+ bessel_k0() const {
191
+ return unaryExpr(internal::scalar_bessel_k0_op<Scalar>());
192
+ }
193
+
194
+ EIGEN_DEVICE_FUNC
195
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_k0e_op<Scalar>, const Derived>
196
+ bessel_k0e() const {
197
+ return unaryExpr(internal::scalar_bessel_k0e_op<Scalar>());
198
+ }
199
+
200
+ EIGEN_DEVICE_FUNC
201
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_k1_op<Scalar>, const Derived>
202
+ bessel_k1() const {
203
+ return unaryExpr(internal::scalar_bessel_k1_op<Scalar>());
204
+ }
205
+
206
+ EIGEN_DEVICE_FUNC
207
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_bessel_k1e_op<Scalar>, const Derived>
208
+ bessel_k1e() const {
209
+ return unaryExpr(internal::scalar_bessel_k1e_op<Scalar>());
210
+ }
211
+
212
+ // igamma(a = this, x = other)
213
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
214
+ const TensorCwiseBinaryOp<internal::scalar_igamma_op<Scalar>, const Derived, const OtherDerived>
215
+ igamma(const OtherDerived& other) const {
216
+ return binaryExpr(other.derived(), internal::scalar_igamma_op<Scalar>());
217
+ }
218
+
219
+ // igamma_der_a(a = this, x = other)
220
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
221
+ const TensorCwiseBinaryOp<internal::scalar_igamma_der_a_op<Scalar>, const Derived, const OtherDerived>
222
+ igamma_der_a(const OtherDerived& other) const {
223
+ return binaryExpr(other.derived(), internal::scalar_igamma_der_a_op<Scalar>());
224
+ }
225
+
226
+ // gamma_sample_der_alpha(alpha = this, sample = other)
227
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
228
+ const TensorCwiseBinaryOp<internal::scalar_gamma_sample_der_alpha_op<Scalar>, const Derived, const OtherDerived>
229
+ gamma_sample_der_alpha(const OtherDerived& other) const {
230
+ return binaryExpr(other.derived(), internal::scalar_gamma_sample_der_alpha_op<Scalar>());
231
+ }
232
+
233
+ // igammac(a = this, x = other)
234
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
235
+ const TensorCwiseBinaryOp<internal::scalar_igammac_op<Scalar>, const Derived, const OtherDerived>
236
+ igammac(const OtherDerived& other) const {
237
+ return binaryExpr(other.derived(), internal::scalar_igammac_op<Scalar>());
238
+ }
239
+
240
+ // zeta(x = this, q = other)
241
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
242
+ const TensorCwiseBinaryOp<internal::scalar_zeta_op<Scalar>, const Derived, const OtherDerived>
243
+ zeta(const OtherDerived& other) const {
244
+ return binaryExpr(other.derived(), internal::scalar_zeta_op<Scalar>());
245
+ }
246
+
247
+ // polygamma(n = this, x = other)
248
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
249
+ const TensorCwiseBinaryOp<internal::scalar_polygamma_op<Scalar>, const Derived, const OtherDerived>
250
+ polygamma(const OtherDerived& other) const {
251
+ return binaryExpr(other.derived(), internal::scalar_polygamma_op<Scalar>());
252
+ }
253
+
254
+ EIGEN_DEVICE_FUNC
255
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_erf_op<Scalar>, const Derived>
256
+ erf() const {
257
+ return unaryExpr(internal::scalar_erf_op<Scalar>());
258
+ }
259
+
260
+ EIGEN_DEVICE_FUNC
261
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_erfc_op<Scalar>, const Derived>
262
+ erfc() const {
263
+ return unaryExpr(internal::scalar_erfc_op<Scalar>());
264
+ }
265
+
266
+ EIGEN_DEVICE_FUNC
267
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_ndtri_op<Scalar>, const Derived>
268
+ ndtri() const {
269
+ return unaryExpr(internal::scalar_ndtri_op<Scalar>());
270
+ }
271
+
272
+ EIGEN_DEVICE_FUNC
273
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_logistic_op<Scalar>, const Derived>
274
+ sigmoid() const {
275
+ return unaryExpr(internal::scalar_logistic_op<Scalar>());
276
+ }
277
+
278
+ EIGEN_DEVICE_FUNC
279
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_exp_op<Scalar>, const Derived>
280
+ exp() const {
281
+ return unaryExpr(internal::scalar_exp_op<Scalar>());
282
+ }
283
+
284
+ EIGEN_DEVICE_FUNC
285
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_expm1_op<Scalar>, const Derived>
286
+ expm1() const {
287
+ return unaryExpr(internal::scalar_expm1_op<Scalar>());
288
+ }
289
+
290
+ EIGEN_DEVICE_FUNC
291
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_log_op<Scalar>, const Derived>
292
+ log() const {
293
+ return unaryExpr(internal::scalar_log_op<Scalar>());
294
+ }
295
+
296
+ EIGEN_DEVICE_FUNC
297
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_log1p_op<Scalar>, const Derived>
298
+ log1p() const {
299
+ return unaryExpr(internal::scalar_log1p_op<Scalar>());
300
+ }
301
+
302
+ EIGEN_DEVICE_FUNC
303
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_log2_op<Scalar>, const Derived>
304
+ log2() const {
305
+ return unaryExpr(internal::scalar_log2_op<Scalar>());
306
+ }
307
+
308
+ EIGEN_DEVICE_FUNC
309
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_abs_op<Scalar>, const Derived>
310
+ abs() const {
311
+ return unaryExpr(internal::scalar_abs_op<Scalar>());
312
+ }
313
+
314
+ EIGEN_DEVICE_FUNC
315
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_arg_op<Scalar>, const Derived>
316
+ arg() const {
317
+ return unaryExpr(internal::scalar_arg_op<Scalar>());
318
+ }
319
+
320
+ EIGEN_DEVICE_FUNC
321
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_clamp_op<Scalar>, const Derived>
322
+ clip(Scalar min, Scalar max) const {
323
+ return unaryExpr(internal::scalar_clamp_op<Scalar>(min, max));
324
+ }
325
+
326
+ EIGEN_DEVICE_FUNC
327
+ EIGEN_STRONG_INLINE const std::conditional_t<NumTraits<CoeffReturnType>::IsComplex,
328
+ TensorCwiseUnaryOp<internal::scalar_conjugate_op<Scalar>, const Derived>,
329
+ Derived>
330
+ conjugate() const {
331
+ return choose(Cond<NumTraits<CoeffReturnType>::IsComplex>(), unaryExpr(internal::scalar_conjugate_op<Scalar>()), derived());
332
+ }
333
+
334
+ template<typename ScalarExponent>
335
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const std::enable_if_t<internal::is_arithmetic<typename NumTraits<ScalarExponent>::Real>::value,
336
+ TensorCwiseUnaryOp<internal::scalar_unary_pow_op<Scalar, ScalarExponent>, const Derived>>
337
+ pow(ScalarExponent exponent) const
338
+ {
339
+ return unaryExpr(internal::scalar_unary_pow_op<Scalar, ScalarExponent>(exponent));
340
+ }
341
+
342
+ EIGEN_DEVICE_FUNC
343
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_real_op<Scalar>, const Derived>
344
+ real() const {
345
+ return unaryExpr(internal::scalar_real_op<Scalar>());
346
+ }
347
+
348
+ EIGEN_DEVICE_FUNC
349
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_imag_op<Scalar>, const Derived>
350
+ imag() const {
351
+ return unaryExpr(internal::scalar_imag_op<Scalar>());
352
+ }
353
+
354
+ EIGEN_DEVICE_FUNC
355
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::bind2nd_op<internal::scalar_sum_op<Scalar,Scalar> >, const Derived>
356
+ operator+ (Scalar rhs) const {
357
+ return unaryExpr(internal::bind2nd_op<internal::scalar_sum_op<Scalar,Scalar> >(rhs));
358
+ }
359
+
360
+ EIGEN_DEVICE_FUNC
361
+ EIGEN_STRONG_INLINE friend
362
+ const TensorCwiseUnaryOp<internal::bind1st_op<internal::scalar_sum_op<Scalar> >, const Derived>
363
+ operator+ (Scalar lhs, const Derived& rhs) {
364
+ return rhs.unaryExpr(internal::bind1st_op<internal::scalar_sum_op<Scalar> >(lhs));
365
+ }
366
+
367
+ EIGEN_DEVICE_FUNC
368
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::bind2nd_op<internal::scalar_difference_op<Scalar,Scalar> >, const Derived>
369
+ operator- (Scalar rhs) const {
370
+ EIGEN_STATIC_ASSERT((NumTraits<Scalar>::IsSigned || internal::is_same<Scalar, const std::complex<float> >::value), YOU_MADE_A_PROGRAMMING_MISTAKE);
371
+ return unaryExpr(internal::bind2nd_op<internal::scalar_difference_op<Scalar,Scalar> >(rhs));
372
+ }
373
+
374
+ EIGEN_DEVICE_FUNC
375
+ EIGEN_STRONG_INLINE friend
376
+ const TensorCwiseUnaryOp<internal::bind1st_op<internal::scalar_difference_op<Scalar> >, const Derived>
377
+ operator- (Scalar lhs, const Derived& rhs) {
378
+ return rhs.unaryExpr(internal::bind1st_op<internal::scalar_difference_op<Scalar> >(lhs));
379
+ }
380
+
381
+ EIGEN_DEVICE_FUNC
382
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::bind2nd_op<internal::scalar_product_op<Scalar,Scalar> >, const Derived>
383
+ operator* (Scalar rhs) const {
384
+ return unaryExpr(internal::bind2nd_op<internal::scalar_product_op<Scalar,Scalar> >(rhs));
385
+ }
386
+
387
+ EIGEN_DEVICE_FUNC
388
+ EIGEN_STRONG_INLINE friend
389
+ const TensorCwiseUnaryOp<internal::bind1st_op<internal::scalar_product_op<Scalar> >, const Derived>
390
+ operator* (Scalar lhs, const Derived& rhs) {
391
+ return rhs.unaryExpr(internal::bind1st_op<internal::scalar_product_op<Scalar> >(lhs));
392
+ }
393
+
394
+ EIGEN_DEVICE_FUNC
395
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::bind2nd_op<internal::scalar_quotient_op<Scalar,Scalar> >, const Derived>
396
+ operator/ (Scalar rhs) const {
397
+ return unaryExpr(internal::bind2nd_op<internal::scalar_quotient_op<Scalar,Scalar> >(rhs));
398
+ }
399
+
400
+ EIGEN_DEVICE_FUNC
401
+ EIGEN_STRONG_INLINE friend
402
+ const TensorCwiseUnaryOp<internal::bind1st_op<internal::scalar_quotient_op<Scalar> >, const Derived>
403
+ operator/ (Scalar lhs, const Derived& rhs) {
404
+ return rhs.unaryExpr(internal::bind1st_op<internal::scalar_quotient_op<Scalar> >(lhs));
405
+ }
406
+
407
+ EIGEN_DEVICE_FUNC
408
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_mod_op<Scalar>, const Derived>
409
+ operator% (Scalar rhs) const {
410
+ EIGEN_STATIC_ASSERT(NumTraits<Scalar>::IsInteger, YOU_MADE_A_PROGRAMMING_MISTAKE_TRY_MOD);
411
+ return unaryExpr(internal::scalar_mod_op<Scalar>(rhs));
412
+ }
413
+
414
+ template <int NanPropagation=PropagateFast>
415
+ EIGEN_DEVICE_FUNC
416
+ EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_max_op<Scalar,Scalar,NanPropagation>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
417
+ cwiseMax(Scalar threshold) const {
418
+ return cwiseMax<NanPropagation>(constant(threshold));
419
+ }
420
+
421
+ template <int NanPropagation=PropagateFast>
422
+ EIGEN_DEVICE_FUNC
423
+ EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_min_op<Scalar,Scalar,NanPropagation>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
424
+ cwiseMin(Scalar threshold) const {
425
+ return cwiseMin<NanPropagation>(constant(threshold));
426
+ }
427
+
428
+ template<typename NewType>
429
+ EIGEN_DEVICE_FUNC
430
+ EIGEN_STRONG_INLINE const std::conditional_t<internal::is_same<NewType, CoeffReturnType>::value,
431
+ Derived,
432
+ TensorConversionOp<NewType, const Derived> >
433
+ cast() const {
434
+ return choose(Cond<internal::is_same<NewType, CoeffReturnType>::value>(), derived(), TensorConversionOp<NewType, const Derived>(derived()));
435
+ }
436
+
437
+ EIGEN_DEVICE_FUNC
438
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_round_op<Scalar>, const Derived>
439
+ round() const {
440
+ return unaryExpr(internal::scalar_round_op<Scalar>());
441
+ }
442
+
443
+ EIGEN_DEVICE_FUNC
444
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_rint_op<Scalar>, const Derived>
445
+ rint() const {
446
+ return unaryExpr(internal::scalar_rint_op<Scalar>());
447
+ }
448
+
449
+ EIGEN_DEVICE_FUNC
450
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_ceil_op<Scalar>, const Derived>
451
+ ceil() const {
452
+ return unaryExpr(internal::scalar_ceil_op<Scalar>());
453
+ }
454
+
455
+ EIGEN_DEVICE_FUNC
456
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_floor_op<Scalar>, const Derived>
457
+ floor() const {
458
+ return unaryExpr(internal::scalar_floor_op<Scalar>());
459
+ }
460
+
461
+ // Generic binary operation support.
462
+ template <typename CustomBinaryOp, typename OtherDerived> EIGEN_DEVICE_FUNC
463
+ EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<CustomBinaryOp, const Derived, const OtherDerived>
464
+ binaryExpr(const OtherDerived& other, const CustomBinaryOp& func) const {
465
+ return TensorCwiseBinaryOp<CustomBinaryOp, const Derived, const OtherDerived>(derived(), other, func);
466
+ }
467
+
468
+ // Coefficient-wise binary operators.
469
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
470
+ const TensorCwiseBinaryOp<internal::scalar_sum_op<Scalar>, const Derived, const OtherDerived>
471
+ operator+(const OtherDerived& other) const {
472
+ return binaryExpr(other.derived(), internal::scalar_sum_op<Scalar>());
473
+ }
474
+
475
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
476
+ const TensorCwiseBinaryOp<internal::scalar_difference_op<Scalar>, const Derived, const OtherDerived>
477
+ operator-(const OtherDerived& other) const {
478
+ return binaryExpr(other.derived(), internal::scalar_difference_op<Scalar>());
479
+ }
480
+
481
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
482
+ const TensorCwiseBinaryOp<internal::scalar_product_op<Scalar>, const Derived, const OtherDerived>
483
+ operator*(const OtherDerived& other) const {
484
+ return binaryExpr(other.derived(), internal::scalar_product_op<Scalar>());
485
+ }
486
+
487
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
488
+ const TensorCwiseBinaryOp<internal::scalar_quotient_op<Scalar>, const Derived, const OtherDerived>
489
+ operator/(const OtherDerived& other) const {
490
+ return binaryExpr(other.derived(), internal::scalar_quotient_op<Scalar>());
491
+ }
492
+
493
+ template<int NaNPropagation=PropagateFast, typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
494
+ const TensorCwiseBinaryOp<internal::scalar_max_op<Scalar,Scalar, NaNPropagation>, const Derived, const OtherDerived>
495
+ cwiseMax(const OtherDerived& other) const {
496
+ return binaryExpr(other.derived(), internal::scalar_max_op<Scalar,Scalar, NaNPropagation>());
497
+ }
498
+
499
+ template<int NaNPropagation=PropagateFast, typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
500
+ const TensorCwiseBinaryOp<internal::scalar_min_op<Scalar,Scalar, NaNPropagation>, const Derived, const OtherDerived>
501
+ cwiseMin(const OtherDerived& other) const {
502
+ return binaryExpr(other.derived(), internal::scalar_min_op<Scalar,Scalar, NaNPropagation>());
503
+ }
504
+
505
+ // logical operators
506
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
507
+ const TensorCwiseBinaryOp<internal::scalar_boolean_and_op<Scalar>, const Derived, const OtherDerived>
508
+ operator&&(const OtherDerived& other) const {
509
+ return binaryExpr(other.derived(), internal::scalar_boolean_and_op<Scalar>());
510
+ }
511
+
512
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
513
+ const TensorCwiseBinaryOp<internal::scalar_boolean_or_op<Scalar>, const Derived, const OtherDerived>
514
+ operator||(const OtherDerived& other) const {
515
+ return binaryExpr(other.derived(), internal::scalar_boolean_or_op<Scalar>());
516
+ }
517
+
518
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
519
+ const TensorCwiseBinaryOp<internal::scalar_bitwise_and_op<Scalar>, const Derived, const OtherDerived>
520
+ operator&(const OtherDerived& other) const {
521
+ return binaryExpr(other.derived(), internal::scalar_bitwise_and_op<Scalar>());
522
+ }
523
+
524
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
525
+ const TensorCwiseBinaryOp<internal::scalar_bitwise_or_op<Scalar>, const Derived, const OtherDerived>
526
+ operator|(const OtherDerived& other) const {
527
+ return binaryExpr(other.derived(), internal::scalar_bitwise_or_op<Scalar>());
528
+ }
529
+
530
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
531
+ const TensorCwiseBinaryOp<internal::scalar_bitwise_xor_op<Scalar>, const Derived, const OtherDerived>
532
+ operator^(const OtherDerived& other) const {
533
+ return binaryExpr(other.derived(), internal::scalar_bitwise_xor_op<Scalar>());
534
+ }
535
+
536
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
537
+ const TensorCwiseUnaryOp<internal::scalar_boolean_not_op<Scalar>, const Derived>
538
+ operator!() const {
539
+ return unaryExpr(internal::scalar_boolean_not_op<Scalar>());
540
+ }
541
+
542
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
543
+ const TensorCwiseUnaryOp<internal::scalar_bitwise_not_op<Scalar>, const Derived>
544
+ operator~() const {
545
+ return unaryExpr(internal::scalar_bitwise_not_op<Scalar>());
546
+ }
547
+
548
+ // Comparisons and tests.
549
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
550
+ const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LT>, const Derived, const OtherDerived>
551
+ operator<(const TensorBase<OtherDerived, ReadOnlyAccessors>& other) const {
552
+ return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LT>());
553
+ }
554
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
555
+ const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LE>, const Derived, const OtherDerived>
556
+ operator<=(const TensorBase<OtherDerived, ReadOnlyAccessors>& other) const {
557
+ return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LE>());
558
+ }
559
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
560
+ const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GT>, const Derived, const OtherDerived>
561
+ operator>(const TensorBase<OtherDerived, ReadOnlyAccessors>& other) const {
562
+ return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GT>());
563
+ }
564
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
565
+ const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GE>, const Derived, const OtherDerived>
566
+ operator>=(const TensorBase<OtherDerived, ReadOnlyAccessors>& other) const {
567
+ return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GE>());
568
+ }
569
+
570
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
571
+ const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_EQ>, const Derived, const OtherDerived>
572
+ operator==(const TensorBase<OtherDerived, ReadOnlyAccessors>& other) const {
573
+ return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_EQ>());
574
+ }
575
+
576
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
577
+ const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_NEQ>, const Derived, const OtherDerived>
578
+ operator!=(const TensorBase<OtherDerived, ReadOnlyAccessors>& other) const {
579
+ return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_NEQ>());
580
+ }
581
+
582
+ // comparisons and tests for Scalars
583
+ EIGEN_DEVICE_FUNC
584
+ EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LT>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
585
+ operator<(Scalar threshold) const {
586
+ return operator<(constant(threshold));
587
+ }
588
+ EIGEN_DEVICE_FUNC
589
+ EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LE>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
590
+ operator<=(Scalar threshold) const {
591
+ return operator<=(constant(threshold));
592
+ }
593
+ EIGEN_DEVICE_FUNC
594
+ EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GT>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
595
+ operator>(Scalar threshold) const {
596
+ return operator>(constant(threshold));
597
+ }
598
+ EIGEN_DEVICE_FUNC
599
+ EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GE>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
600
+ operator>=(Scalar threshold) const {
601
+ return operator>=(constant(threshold));
602
+ }
603
+ EIGEN_DEVICE_FUNC
604
+ EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_EQ>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
605
+ operator==(Scalar threshold) const {
606
+ return operator==(constant(threshold));
607
+ }
608
+ EIGEN_DEVICE_FUNC
609
+ EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_NEQ>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
610
+ operator!=(Scalar threshold) const {
611
+ return operator!=(constant(threshold));
612
+ }
613
+
614
+ // Predicates.
615
+ EIGEN_DEVICE_FUNC
616
+ EIGEN_STRONG_INLINE const TensorConversionOp<bool, const TensorCwiseUnaryOp<internal::scalar_isnan_op<Scalar, true>, const Derived>>
617
+ (isnan)() const {
618
+ return unaryExpr(internal::scalar_isnan_op<Scalar, true>()).template cast<bool>();
619
+ }
620
+
621
+ EIGEN_DEVICE_FUNC
622
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_isinf_op<Scalar>, const Derived>
623
+ (isinf)() const {
624
+ return unaryExpr(internal::scalar_isinf_op<Scalar>());
625
+ }
626
+ EIGEN_DEVICE_FUNC
627
+ EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_isfinite_op<Scalar>, const Derived>
628
+ (isfinite)() const {
629
+ return unaryExpr(internal::scalar_isfinite_op<Scalar>());
630
+ }
631
+
632
+ // Coefficient-wise ternary operators.
633
+ template<typename ThenDerived, typename ElseDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
634
+ const TensorSelectOp<const Derived, const ThenDerived, const ElseDerived>
635
+ select(const ThenDerived& thenTensor, const ElseDerived& elseTensor) const {
636
+ return TensorSelectOp<const Derived, const ThenDerived, const ElseDerived>(derived(), thenTensor.derived(), elseTensor.derived());
637
+ }
638
+
639
+ // Contractions.
640
+ typedef Eigen::IndexPair<Index> DimensionPair;
641
+
642
+ template<typename OtherDerived, typename Dimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
643
+ const TensorContractionOp<const Dimensions, const Derived, const OtherDerived, const NoOpOutputKernel>
644
+ contract(const OtherDerived& other, const Dimensions& dims) const {
645
+ return TensorContractionOp<const Dimensions, const Derived, const OtherDerived, const NoOpOutputKernel>(derived(), other.derived(), dims);
646
+ }
647
+
648
+ template<typename OtherDerived, typename Dimensions, typename OutputKernel> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
649
+ const TensorContractionOp<const Dimensions, const Derived, const OtherDerived, const OutputKernel>
650
+ contract(const OtherDerived& other, const Dimensions& dims, const OutputKernel& output_kernel) const {
651
+ return TensorContractionOp<const Dimensions, const Derived, const OtherDerived, const OutputKernel>(derived(), other.derived(), dims, output_kernel);
652
+ }
653
+
654
+ // Convolutions.
655
+ template<typename KernelDerived, typename Dimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
656
+ const TensorConvolutionOp<const Dimensions, const Derived, const KernelDerived>
657
+ convolve(const KernelDerived& kernel, const Dimensions& dims) const {
658
+ return TensorConvolutionOp<const Dimensions, const Derived, const KernelDerived>(derived(), kernel.derived(), dims);
659
+ }
660
+
661
+ // Fourier transforms
662
+ template <int FFTDataType, int FFTDirection, typename FFT> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
663
+ const TensorFFTOp<const FFT, const Derived, FFTDataType, FFTDirection>
664
+ fft(const FFT& dims) const {
665
+ return TensorFFTOp<const FFT, const Derived, FFTDataType, FFTDirection>(derived(), dims);
666
+ }
667
+
668
+ // Scan.
669
+ typedef TensorScanOp<internal::SumReducer<CoeffReturnType>, const Derived> TensorScanSumOp;
670
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
671
+ const TensorScanSumOp
672
+ cumsum(const Index& axis, bool exclusive = false) const {
673
+ return TensorScanSumOp(derived(), axis, exclusive);
674
+ }
675
+
676
+ typedef TensorScanOp<internal::ProdReducer<CoeffReturnType>, const Derived> TensorScanProdOp;
677
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
678
+ const TensorScanProdOp
679
+ cumprod(const Index& axis, bool exclusive = false) const {
680
+ return TensorScanProdOp(derived(), axis, exclusive);
681
+ }
682
+
683
+ template <typename Reducer>
684
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
685
+ const TensorScanOp<Reducer, const Derived>
686
+ scan(const Index& axis, const Reducer& reducer, bool exclusive = false) const {
687
+ return TensorScanOp<Reducer, const Derived>(derived(), axis, exclusive, reducer);
688
+ }
689
+
690
+ // Reductions.
691
+ template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
692
+ const TensorReductionOp<internal::SumReducer<CoeffReturnType>, const Dims, const Derived>
693
+ sum(const Dims& dims) const {
694
+ return TensorReductionOp<internal::SumReducer<CoeffReturnType>, const Dims, const Derived>(derived(), dims, internal::SumReducer<CoeffReturnType>());
695
+ }
696
+
697
+ const TensorReductionOp<internal::SumReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>
698
+ sum() const {
699
+ DimensionList<Index, NumDimensions> in_dims;
700
+ return TensorReductionOp<internal::SumReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::SumReducer<CoeffReturnType>());
701
+ }
702
+
703
+ template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
704
+ const TensorReductionOp<internal::MeanReducer<CoeffReturnType>, const Dims, const Derived>
705
+ mean(const Dims& dims) const {
706
+ return TensorReductionOp<internal::MeanReducer<CoeffReturnType>, const Dims, const Derived>(derived(), dims, internal::MeanReducer<CoeffReturnType>());
707
+ }
708
+
709
+ const TensorReductionOp<internal::MeanReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>
710
+ mean() const {
711
+ DimensionList<Index, NumDimensions> in_dims;
712
+ return TensorReductionOp<internal::MeanReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::MeanReducer<CoeffReturnType>());
713
+ }
714
+
715
+ template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
716
+ const TensorReductionOp<internal::ProdReducer<CoeffReturnType>, const Dims, const Derived>
717
+ prod(const Dims& dims) const {
718
+ return TensorReductionOp<internal::ProdReducer<CoeffReturnType>, const Dims, const Derived>(derived(), dims, internal::ProdReducer<CoeffReturnType>());
719
+ }
720
+
721
+ const TensorReductionOp<internal::ProdReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>
722
+ prod() const {
723
+ DimensionList<Index, NumDimensions> in_dims;
724
+ return TensorReductionOp<internal::ProdReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::ProdReducer<CoeffReturnType>());
725
+ }
726
+
727
+ template <typename Dims,int NanPropagation=PropagateFast> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
728
+ const TensorReductionOp<internal::MaxReducer<CoeffReturnType,NanPropagation>, const Dims, const Derived>
729
+ maximum(const Dims& dims) const {
730
+ return TensorReductionOp<internal::MaxReducer<CoeffReturnType,NanPropagation>, const Dims, const Derived>(derived(), dims, internal::MaxReducer<CoeffReturnType,NanPropagation>());
731
+ }
732
+
733
+ template <int NanPropagation=PropagateFast>
734
+ const TensorReductionOp<internal::MaxReducer<CoeffReturnType,NanPropagation>, const DimensionList<Index, NumDimensions>, const Derived>
735
+ maximum() const {
736
+ DimensionList<Index, NumDimensions> in_dims;
737
+ return TensorReductionOp<internal::MaxReducer<CoeffReturnType,NanPropagation>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::MaxReducer<CoeffReturnType,NanPropagation>());
738
+ }
739
+
740
+ template <typename Dims,int NanPropagation=PropagateFast> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
741
+ const TensorReductionOp<internal::MinReducer<CoeffReturnType,NanPropagation>, const Dims, const Derived>
742
+ minimum(const Dims& dims) const {
743
+ return TensorReductionOp<internal::MinReducer<CoeffReturnType,NanPropagation>, const Dims, const Derived>(derived(), dims, internal::MinReducer<CoeffReturnType,NanPropagation>());
744
+ }
745
+
746
+ template <int NanPropagation=PropagateFast>
747
+ const TensorReductionOp<internal::MinReducer<CoeffReturnType,NanPropagation>, const DimensionList<Index, NumDimensions>, const Derived>
748
+ minimum() const {
749
+ DimensionList<Index, NumDimensions> in_dims;
750
+ return TensorReductionOp<internal::MinReducer<CoeffReturnType,NanPropagation>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::MinReducer<CoeffReturnType,NanPropagation>());
751
+ }
752
+
753
+ template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
754
+ const TensorReductionOp<internal::AndReducer, const Dims, const std::conditional_t<internal::is_same<bool, CoeffReturnType>::value, Derived, TensorConversionOp<bool, const Derived> > >
755
+ all(const Dims& dims) const {
756
+ return cast<bool>().reduce(dims, internal::AndReducer());
757
+ }
758
+
759
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
760
+ const TensorReductionOp<internal::AndReducer, const DimensionList<Index, NumDimensions>, const std::conditional_t<internal::is_same<bool, CoeffReturnType>::value, Derived, TensorConversionOp<bool, const Derived> > >
761
+ all() const {
762
+ DimensionList<Index, NumDimensions> in_dims;
763
+ return cast<bool>().reduce(in_dims, internal::AndReducer());
764
+ }
765
+
766
+ template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
767
+ const TensorReductionOp<internal::OrReducer, const Dims, const std::conditional_t<internal::is_same<bool, CoeffReturnType>::value, Derived, TensorConversionOp<bool, const Derived> > >
768
+ any(const Dims& dims) const {
769
+ return cast<bool>().reduce(dims, internal::OrReducer());
770
+ }
771
+
772
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
773
+ const TensorReductionOp<internal::OrReducer, const DimensionList<Index, NumDimensions>, const std::conditional_t<internal::is_same<bool, CoeffReturnType>::value, Derived, TensorConversionOp<bool, const Derived> > >
774
+ any() const {
775
+ DimensionList<Index, NumDimensions> in_dims;
776
+ return cast<bool>().reduce(in_dims, internal::OrReducer());
777
+ }
778
+
779
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
780
+ const TensorPairReducerOp<
781
+ internal::ArgMaxPairReducer<Pair<Index, CoeffReturnType> >,
782
+ const array<Index, NumDimensions>, const Derived>
783
+ argmax() const {
784
+ array<Index, NumDimensions> in_dims;
785
+ for (Index d = 0; d < NumDimensions; ++d) in_dims[d] = d;
786
+ return TensorPairReducerOp<
787
+ internal::ArgMaxPairReducer<Pair<Index, CoeffReturnType> >,
788
+ const array<Index, NumDimensions>,
789
+ const Derived>(derived(), internal::ArgMaxPairReducer<Pair<Index, CoeffReturnType> >(), -1, in_dims);
790
+ }
791
+
792
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
793
+ const TensorPairReducerOp<
794
+ internal::ArgMinPairReducer<Pair<Index, CoeffReturnType> >,
795
+ const array<Index, NumDimensions>, const Derived>
796
+ argmin() const {
797
+ array<Index, NumDimensions> in_dims;
798
+ for (Index d = 0; d < NumDimensions; ++d) in_dims[d] = d;
799
+ return TensorPairReducerOp<
800
+ internal::ArgMinPairReducer<Pair<Index, CoeffReturnType> >,
801
+ const array<Index, NumDimensions>,
802
+ const Derived>(derived(), internal::ArgMinPairReducer<Pair<Index, CoeffReturnType> >(), -1, in_dims);
803
+ }
804
+
805
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
806
+ const TensorPairReducerOp<
807
+ internal::ArgMaxPairReducer<Pair<Index, CoeffReturnType> >,
808
+ const array<Index, 1>, const Derived>
809
+ argmax(const Index return_dim) const {
810
+ array<Index, 1> in_dims;
811
+ in_dims[0] = return_dim;
812
+ return TensorPairReducerOp<
813
+ internal::ArgMaxPairReducer<Pair<Index, CoeffReturnType> >,
814
+ const array<Index, 1>,
815
+ const Derived>(derived(), internal::ArgMaxPairReducer<Pair<Index, CoeffReturnType> >(), return_dim, in_dims);
816
+ }
817
+
818
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
819
+ const TensorPairReducerOp<
820
+ internal::ArgMinPairReducer<Pair<Index, CoeffReturnType> >,
821
+ const array<Index, 1>, const Derived>
822
+ argmin(const Index return_dim) const {
823
+ array<Index, 1> in_dims;
824
+ in_dims[0] = return_dim;
825
+ return TensorPairReducerOp<
826
+ internal::ArgMinPairReducer<Pair<Index, CoeffReturnType> >,
827
+ const array<Index, 1>,
828
+ const Derived>(derived(), internal::ArgMinPairReducer<Pair<Index, CoeffReturnType> >(), return_dim, in_dims);
829
+ }
830
+
831
+ template <typename Reducer, typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
832
+ const TensorReductionOp<Reducer, const Dims, const Derived>
833
+ reduce(const Dims& dims, const Reducer& reducer) const {
834
+ return TensorReductionOp<Reducer, const Dims, const Derived>(derived(), dims, reducer);
835
+ }
836
+
837
+ template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
838
+ const TensorTraceOp<const Dims, const Derived>
839
+ trace(const Dims& dims) const {
840
+ return TensorTraceOp<const Dims, const Derived>(derived(), dims);
841
+ }
842
+
843
+ const TensorTraceOp<const DimensionList<Index, NumDimensions>, const Derived>
844
+ trace() const {
845
+ DimensionList<Index, NumDimensions> in_dims;
846
+ return TensorTraceOp<const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims);
847
+ }
848
+
849
+ template <typename Broadcast> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
850
+ const TensorBroadcastingOp<const Broadcast, const Derived>
851
+ broadcast(const Broadcast& bcast) const {
852
+ return TensorBroadcastingOp<const Broadcast, const Derived>(derived(), bcast);
853
+ }
854
+
855
+ template <typename Axis, typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
856
+ const TensorConcatenationOp<Axis, const Derived, const OtherDerived>
857
+ concatenate(const OtherDerived& other, Axis axis) const {
858
+ return TensorConcatenationOp<Axis, const Derived, const OtherDerived>(derived(), other.derived(), axis);
859
+ }
860
+
861
+ template <typename PatchDims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
862
+ const TensorPatchOp<const PatchDims, const Derived>
863
+ extract_patches(const PatchDims& patch_dims) const {
864
+ return TensorPatchOp<const PatchDims, const Derived>(derived(), patch_dims);
865
+ }
866
+
867
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
868
+ const TensorImagePatchOp<Dynamic, Dynamic, const Derived>
869
+ extract_image_patches(const Index patch_rows = 1, const Index patch_cols = 1,
870
+ const Index row_stride = 1, const Index col_stride = 1,
871
+ const Index in_row_stride = 1, const Index in_col_stride = 1,
872
+ const PaddingType padding_type = PADDING_SAME, const Scalar padding_value = Scalar(0)) const {
873
+ return TensorImagePatchOp<Dynamic, Dynamic, const Derived>(derived(), patch_rows, patch_cols, row_stride, col_stride,
874
+ in_row_stride, in_col_stride, 1, 1, padding_type, padding_value);
875
+ }
876
+
877
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
878
+ const TensorImagePatchOp<Dynamic, Dynamic, const Derived>
879
+ extract_image_patches(const Index patch_rows, const Index patch_cols,
880
+ const Index row_stride, const Index col_stride,
881
+ const Index in_row_stride, const Index in_col_stride,
882
+ const Index row_inflate_stride, const Index col_inflate_stride,
883
+ const Index padding_top, const Index padding_bottom,
884
+ const Index padding_left,const Index padding_right,
885
+ const Scalar padding_value) const {
886
+ return TensorImagePatchOp<Dynamic, Dynamic, const Derived>(derived(), patch_rows, patch_cols, row_stride, col_stride,
887
+ in_row_stride, in_col_stride, row_inflate_stride, col_inflate_stride,
888
+ padding_top, padding_bottom, padding_left, padding_right, padding_value);
889
+ }
890
+
891
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
892
+ const TensorVolumePatchOp<Dynamic, Dynamic, Dynamic, const Derived>
893
+ extract_volume_patches(const Index patch_planes, const Index patch_rows, const Index patch_cols,
894
+ const Index plane_stride = 1, const Index row_stride = 1, const Index col_stride = 1,
895
+ const PaddingType padding_type = PADDING_SAME, const Scalar padding_value = Scalar(0)) const {
896
+ return TensorVolumePatchOp<Dynamic, Dynamic, Dynamic, const Derived>(derived(), patch_planes, patch_rows, patch_cols, plane_stride, row_stride, col_stride, 1, 1, 1, 1, 1, 1, padding_type, padding_value);
897
+ }
898
+
899
+
900
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
901
+ const TensorVolumePatchOp<Dynamic, Dynamic, Dynamic, const Derived>
902
+ extract_volume_patches(const Index patch_planes, const Index patch_rows, const Index patch_cols,
903
+ const Index plane_stride, const Index row_stride, const Index col_stride,
904
+ const Index plane_inflate_stride, const Index row_inflate_stride, const Index col_inflate_stride,
905
+ const Index padding_top_z, const Index padding_bottom_z,
906
+ const Index padding_top, const Index padding_bottom,
907
+ const Index padding_left, const Index padding_right, const Scalar padding_value = Scalar(0)) const {
908
+ return TensorVolumePatchOp<Dynamic, Dynamic, Dynamic, const Derived>(derived(), patch_planes, patch_rows, patch_cols, plane_stride, row_stride, col_stride, 1, 1, 1, plane_inflate_stride, row_inflate_stride, col_inflate_stride, padding_top_z, padding_bottom_z, padding_top, padding_bottom, padding_left, padding_right, padding_value);
909
+ }
910
+
911
+ // Morphing operators.
912
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
913
+ const TensorLayoutSwapOp<const Derived>
914
+ swap_layout() const {
915
+ return TensorLayoutSwapOp<const Derived>(derived());
916
+ }
917
+ template <typename NewDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
918
+ const TensorReshapingOp<const NewDimensions, const Derived>
919
+ reshape(const NewDimensions& newDimensions) const {
920
+ return TensorReshapingOp<const NewDimensions, const Derived>(derived(), newDimensions);
921
+ }
922
+ template <typename StartIndices, typename Sizes> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
923
+ const TensorSlicingOp<const StartIndices, const Sizes, const Derived>
924
+ slice(const StartIndices& startIndices, const Sizes& sizes) const {
925
+ return TensorSlicingOp<const StartIndices, const Sizes, const Derived>(derived(), startIndices, sizes);
926
+ }
927
+ template <typename StartIndices, typename StopIndices, typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
928
+ const TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides, const Derived>
929
+ stridedSlice(const StartIndices& startIndices, const StopIndices& stopIndices, const Strides& strides) const {
930
+ return TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides,
931
+ const Derived>(derived(), startIndices, stopIndices, strides);
932
+ }
933
+ template <Index DimId> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
934
+ const TensorChippingOp<DimId, const Derived>
935
+ chip(const Index offset) const {
936
+ return TensorChippingOp<DimId, const Derived>(derived(), offset, DimId);
937
+ }
938
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
939
+ const TensorChippingOp<Dynamic, const Derived>
940
+ chip(const Index offset, const Index dim) const {
941
+ return TensorChippingOp<Dynamic, const Derived>(derived(), offset, dim);
942
+ }
943
+ template <typename ReverseDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
944
+ const TensorReverseOp<const ReverseDimensions, const Derived>
945
+ reverse(const ReverseDimensions& rev) const {
946
+ return TensorReverseOp<const ReverseDimensions, const Derived>(derived(), rev);
947
+ }
948
+ template <typename PaddingDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
949
+ const TensorPaddingOp<const PaddingDimensions, const Derived>
950
+ pad(const PaddingDimensions& padding) const {
951
+ return TensorPaddingOp<const PaddingDimensions, const Derived>(derived(), padding, internal::scalar_cast_op<int, Scalar>()(0));
952
+ }
953
+ template <typename PaddingDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
954
+ const TensorPaddingOp<const PaddingDimensions, const Derived>
955
+ pad(const PaddingDimensions& padding, const Scalar padding_value) const {
956
+ return TensorPaddingOp<const PaddingDimensions, const Derived>(derived(), padding, padding_value);
957
+ }
958
+ template <typename Shuffle> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
959
+ const TensorShufflingOp<const Shuffle, const Derived>
960
+ shuffle(const Shuffle& shfl) const {
961
+ return TensorShufflingOp<const Shuffle, const Derived>(derived(), shfl);
962
+ }
963
+ template <typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
964
+ const TensorStridingOp<const Strides, const Derived>
965
+ stride(const Strides& strides) const {
966
+ return TensorStridingOp<const Strides, const Derived>(derived(), strides);
967
+ }
968
+ template <typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
969
+ const TensorInflationOp<const Strides, const Derived>
970
+ inflate(const Strides& strides) const {
971
+ return TensorInflationOp<const Strides, const Derived>(derived(), strides);
972
+ }
973
+
974
+ // Returns a tensor containing index/value pairs
975
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
976
+ const TensorIndexPairOp<const Derived>
977
+ index_pairs() const {
978
+ return TensorIndexPairOp<const Derived>(derived());
979
+ }
980
+
981
+ // Support for custom unary and binary operations
982
+ template <typename CustomUnaryFunc>
983
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
984
+ const TensorCustomUnaryOp<const CustomUnaryFunc, const Derived> customOp(const CustomUnaryFunc& op) const {
985
+ return TensorCustomUnaryOp<const CustomUnaryFunc, const Derived>(derived(), op);
986
+ }
987
+ template <typename OtherDerived, typename CustomBinaryFunc>
988
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
989
+ const TensorCustomBinaryOp<const CustomBinaryFunc, const Derived, const OtherDerived> customOp(const OtherDerived& other, const CustomBinaryFunc& op) const {
990
+ return TensorCustomBinaryOp<const CustomBinaryFunc, const Derived, const OtherDerived>(derived(), other, op);
991
+ }
992
+
993
+ // Force the evaluation of the expression.
994
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
995
+ const TensorForcedEvalOp<const Derived> eval() const {
996
+ return TensorForcedEvalOp<const Derived>(derived());
997
+ }
998
+
999
+ // Returns a formatted tensor ready for printing to a stream
1000
+ inline const TensorWithFormat<Derived,DerivedTraits::Layout,DerivedTraits::NumDimensions> format(const TensorIOFormat& fmt) const {
1001
+ return TensorWithFormat<Derived,DerivedTraits::Layout,DerivedTraits::NumDimensions>(derived(), fmt);
1002
+ }
1003
+
1004
+ #ifdef EIGEN_READONLY_TENSORBASE_PLUGIN
1005
+ #include EIGEN_READONLY_TENSORBASE_PLUGIN
1006
+ #endif
1007
+
1008
+ protected:
1009
+ template <typename Scalar, int NumIndices, int Options, typename IndexType> friend class Tensor;
1010
+ template <typename Scalar, typename Dimensions, int Option, typename IndexTypes> friend class TensorFixedSize;
1011
+ // the Eigen:: prefix is required to workaround a compilation issue with nvcc 9.0
1012
+ template <typename OtherDerived, int AccessLevel> friend class Eigen::TensorBase;
1013
+ EIGEN_DEVICE_FUNC
1014
+ EIGEN_STRONG_INLINE const Derived& derived() const { return *static_cast<const Derived*>(this); }
1015
+ };
1016
+
1017
+ template<typename Derived, int AccessLevel = internal::accessors_level<Derived>::value>
1018
+ class TensorBase : public TensorBase<Derived, ReadOnlyAccessors> {
1019
+ public:
1020
+ typedef TensorBase<Derived, ReadOnlyAccessors> Base;
1021
+ typedef internal::traits<Derived> DerivedTraits;
1022
+ typedef typename DerivedTraits::Scalar Scalar;
1023
+ typedef typename DerivedTraits::Index Index;
1024
+ typedef Scalar CoeffReturnType;
1025
+ static constexpr int NumDimensions = DerivedTraits::NumDimensions;
1026
+
1027
+ template <typename Scalar, int NumIndices, int Options, typename IndexType> friend class Tensor;
1028
+ template <typename Scalar, typename Dimensions, int Option, typename IndexTypes> friend class TensorFixedSize;
1029
+ // the Eigen:: prefix is required to workaround a compilation issue with nvcc 9.0
1030
+ template <typename OtherDerived, int OtherAccessLevel> friend class Eigen::TensorBase;
1031
+
1032
+ EIGEN_DEVICE_FUNC
1033
+ EIGEN_STRONG_INLINE Derived& setZero() {
1034
+ return setConstant(Scalar(0));
1035
+ }
1036
+ EIGEN_DEVICE_FUNC
1037
+ EIGEN_STRONG_INLINE Derived& setConstant(const Scalar& val) {
1038
+ return derived() = this->constant(val);
1039
+ }
1040
+ EIGEN_DEVICE_FUNC
1041
+ EIGEN_STRONG_INLINE Derived& setRandom() {
1042
+ return derived() = this->random();
1043
+ }
1044
+ template <typename RandomGenerator> EIGEN_DEVICE_FUNC
1045
+ EIGEN_STRONG_INLINE Derived& setRandom() {
1046
+ return derived() = this->template random<RandomGenerator>();
1047
+ }
1048
+
1049
+ EIGEN_DEVICE_FUNC
1050
+ EIGEN_STRONG_INLINE Derived& setValues(
1051
+ const typename internal::Initializer<Derived, NumDimensions>::InitList& vals) {
1052
+ TensorEvaluator<Derived, DefaultDevice> eval(derived(), DefaultDevice());
1053
+ internal::initialize_tensor<Derived, NumDimensions>(eval, vals);
1054
+ return derived();
1055
+ }
1056
+
1057
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1058
+ Derived& operator+=(const OtherDerived& other) {
1059
+ return derived() = derived() + other.derived();
1060
+ }
1061
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1062
+ Derived& operator-=(const OtherDerived& other) {
1063
+ return derived() = derived() - other.derived();
1064
+ }
1065
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1066
+ Derived& operator*=(const OtherDerived& other) {
1067
+ return derived() = derived() * other.derived();
1068
+ }
1069
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1070
+ Derived& operator/=(const OtherDerived& other) {
1071
+ return derived() = derived() / other.derived();
1072
+ }
1073
+
1074
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1075
+ const TensorLayoutSwapOp<const Derived>
1076
+ swap_layout() const {
1077
+ return TensorLayoutSwapOp<const Derived>(derived());
1078
+ }
1079
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1080
+ TensorLayoutSwapOp<Derived>
1081
+ swap_layout() {
1082
+ return TensorLayoutSwapOp<Derived>(derived());
1083
+ }
1084
+
1085
+ template <typename Axis, typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1086
+ const TensorConcatenationOp<const Axis, const Derived, const OtherDerived>
1087
+ concatenate(const OtherDerived& other, const Axis& axis) const {
1088
+ return TensorConcatenationOp<const Axis, const Derived, const OtherDerived>(derived(), other, axis);
1089
+ }
1090
+ template <typename Axis, typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1091
+ TensorConcatenationOp<const Axis, Derived, OtherDerived>
1092
+ concatenate(const OtherDerived& other, const Axis& axis) {
1093
+ return TensorConcatenationOp<const Axis, Derived, OtherDerived>(derived(), other, axis);
1094
+ }
1095
+
1096
+ template <typename NewDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1097
+ const TensorReshapingOp<const NewDimensions, const Derived>
1098
+ reshape(const NewDimensions& newDimensions) const {
1099
+ return TensorReshapingOp<const NewDimensions, const Derived>(derived(), newDimensions);
1100
+ }
1101
+ template <typename NewDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1102
+ TensorReshapingOp<const NewDimensions, Derived>
1103
+ reshape(const NewDimensions& newDimensions) {
1104
+ return TensorReshapingOp<const NewDimensions, Derived>(derived(), newDimensions);
1105
+ }
1106
+
1107
+ template <typename StartIndices, typename Sizes> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1108
+ const TensorSlicingOp<const StartIndices, const Sizes, const Derived>
1109
+ slice(const StartIndices& startIndices, const Sizes& sizes) const {
1110
+ return TensorSlicingOp<const StartIndices, const Sizes, const Derived>(derived(), startIndices, sizes);
1111
+ }
1112
+ template <typename StartIndices, typename Sizes> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1113
+ TensorSlicingOp<const StartIndices, const Sizes, Derived>
1114
+ slice(const StartIndices& startIndices, const Sizes& sizes) {
1115
+ return TensorSlicingOp<const StartIndices, const Sizes, Derived>(derived(), startIndices, sizes);
1116
+ }
1117
+
1118
+ template <typename StartIndices, typename StopIndices, typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1119
+ const TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides, const Derived>
1120
+ stridedSlice(const StartIndices& startIndices, const StopIndices& stopIndices, const Strides& strides) const {
1121
+ return TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides,
1122
+ const Derived>(derived(), startIndices, stopIndices, strides);
1123
+ }
1124
+ template <typename StartIndices, typename StopIndices, typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1125
+ TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides, Derived>
1126
+ stridedSlice(const StartIndices& startIndices, const StopIndices& stopIndices, const Strides& strides) {
1127
+ return TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides,
1128
+ Derived>(derived(), startIndices, stopIndices, strides);
1129
+ }
1130
+
1131
+ template <DenseIndex DimId> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1132
+ const TensorChippingOp<DimId, const Derived>
1133
+ chip(const Index offset) const {
1134
+ return TensorChippingOp<DimId, const Derived>(derived(), offset, DimId);
1135
+ }
1136
+ template <Index DimId> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1137
+ TensorChippingOp<DimId, Derived>
1138
+ chip(const Index offset) {
1139
+ return TensorChippingOp<DimId, Derived>(derived(), offset, DimId);
1140
+ }
1141
+
1142
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1143
+ const TensorChippingOp<Dynamic, const Derived>
1144
+ chip(const Index offset, const Index dim) const {
1145
+ return TensorChippingOp<Dynamic, const Derived>(derived(), offset, dim);
1146
+ }
1147
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1148
+ TensorChippingOp<Dynamic, Derived>
1149
+ chip(const Index offset, const Index dim) {
1150
+ return TensorChippingOp<Dynamic, Derived>(derived(), offset, dim);
1151
+ }
1152
+
1153
+ template <typename ReverseDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1154
+ const TensorReverseOp<const ReverseDimensions, const Derived>
1155
+ reverse(const ReverseDimensions& rev) const {
1156
+ return TensorReverseOp<const ReverseDimensions, const Derived>(derived(), rev);
1157
+ }
1158
+ template <typename ReverseDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1159
+ TensorReverseOp<const ReverseDimensions, Derived>
1160
+ reverse(const ReverseDimensions& rev) {
1161
+ return TensorReverseOp<const ReverseDimensions, Derived>(derived(), rev);
1162
+ }
1163
+
1164
+ template <typename Shuffle> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1165
+ const TensorShufflingOp<const Shuffle, const Derived>
1166
+ shuffle(const Shuffle& shfl) const {
1167
+ return TensorShufflingOp<const Shuffle, const Derived>(derived(), shfl);
1168
+ }
1169
+ template <typename Shuffle> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1170
+ TensorShufflingOp<const Shuffle, Derived>
1171
+ shuffle(const Shuffle& shfl) {
1172
+ return TensorShufflingOp<const Shuffle, Derived>(derived(), shfl);
1173
+ }
1174
+
1175
+ template <typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1176
+ const TensorStridingOp<const Strides, const Derived>
1177
+ stride(const Strides& strides) const {
1178
+ return TensorStridingOp<const Strides, const Derived>(derived(), strides);
1179
+ }
1180
+ template <typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
1181
+ TensorStridingOp<const Strides, Derived>
1182
+ stride(const Strides& strides) {
1183
+ return TensorStridingOp<const Strides, Derived>(derived(), strides);
1184
+ }
1185
+
1186
+ // Select the device on which to evaluate the expression.
1187
+ template <typename DeviceType>
1188
+ TensorDevice<Derived, DeviceType> device(const DeviceType& dev) {
1189
+ return TensorDevice<Derived, DeviceType>(dev, derived());
1190
+ }
1191
+
1192
+ // Select the async device on which to evaluate the expression.
1193
+ template <typename DeviceType, typename DoneCallback>
1194
+ TensorAsyncDevice<Derived, DeviceType, DoneCallback> device(const DeviceType& dev, DoneCallback done) {
1195
+ return TensorAsyncDevice<Derived, DeviceType, DoneCallback>(dev, derived(), std::move(done));
1196
+ }
1197
+
1198
+ #ifdef EIGEN_TENSORBASE_PLUGIN
1199
+ #include EIGEN_TENSORBASE_PLUGIN
1200
+ #endif
1201
+
1202
+ protected:
1203
+ EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(TensorBase)
1204
+ EIGEN_DEFAULT_COPY_CONSTRUCTOR(TensorBase)
1205
+
1206
+ template<typename OtherDerived> EIGEN_DEVICE_FUNC
1207
+ EIGEN_STRONG_INLINE Derived& operator=(const OtherDerived& other)
1208
+ {
1209
+ typedef TensorAssignOp<Derived, const OtherDerived> Assign;
1210
+ Assign assign(derived(), other.derived());
1211
+ internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice());
1212
+ return derived();
1213
+ }
1214
+ EIGEN_DEVICE_FUNC
1215
+ EIGEN_STRONG_INLINE Derived& derived() { return *static_cast<Derived*>(this); }
1216
+ EIGEN_DEVICE_FUNC
1217
+ EIGEN_STRONG_INLINE const Derived& derived() const { return *static_cast<const Derived*>(this); }
1218
+ };
1219
+ #endif // EIGEN_PARSED_BY_DOXYGEN
1220
+ } // end namespace Eigen
1221
+
1222
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_BASE_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBlock.h ADDED
@@ -0,0 +1,1607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // This Source Code Form is subject to the terms of the Mozilla
5
+ // Public License v. 2.0. If a copy of the MPL was not distributed
6
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
+
8
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_BLOCK_H
9
+ #define EIGEN_CXX11_TENSOR_TENSOR_BLOCK_H
10
+
11
+ #include "./InternalHeaderCheck.h"
12
+
13
+ namespace Eigen {
14
+ namespace internal {
15
+
16
+ // -------------------------------------------------------------------------- //
17
+ // Forward declarations for templates defined below.
18
+ template <typename Scalar, typename IndexType, int NumDims, int Layout>
19
+ class TensorBlockIO;
20
+
21
+ // -------------------------------------------------------------------------- //
22
+ // Helper function to compute strides for densely stored buffer of given
23
+ // dimensions.
24
+
25
+ // TODO(ezhulenev): We compute strides 1000 times in different evaluators, use
26
+ // this function instead everywhere.
27
+ template <int Layout, typename IndexType, int NumDims>
28
+ EIGEN_ALWAYS_INLINE DSizes<IndexType, NumDims> strides(
29
+ const DSizes<IndexType, NumDims>& dimensions) {
30
+ DSizes<IndexType, NumDims> strides;
31
+ if (NumDims == 0) return strides;
32
+
33
+ // TODO(ezhulenev): Use templates to unroll this loop (similar to
34
+ // h_array_reduce in CXX11meta.h)? Benchmark it.
35
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
36
+ strides[0] = 1;
37
+ for (int i = 1; i < NumDims; ++i) {
38
+ strides[i] = strides[i - 1] * dimensions[i - 1];
39
+ }
40
+ } else {
41
+ strides[NumDims - 1] = 1;
42
+ for (int i = NumDims - 2; i >= 0; --i) {
43
+ strides[i] = strides[i + 1] * dimensions[i + 1];
44
+ }
45
+ }
46
+
47
+ return strides;
48
+ }
49
+
50
+ template <int Layout, typename IndexType, size_t NumDims>
51
+ EIGEN_ALWAYS_INLINE DSizes<IndexType, NumDims> strides(
52
+ const Eigen::array<IndexType, NumDims>& dimensions) {
53
+ return strides<Layout>(DSizes<IndexType, NumDims>(dimensions));
54
+ }
55
+
56
+ template <int Layout, std::ptrdiff_t... Indices>
57
+ EIGEN_STRONG_INLINE DSizes<std::ptrdiff_t, sizeof...(Indices)> strides(
58
+ const Sizes<Indices...>& sizes) {
59
+ return strides<Layout>(DSizes<std::ptrdiff_t, sizeof...(Indices)>(sizes));
60
+ }
61
+
62
+ // -------------------------------------------------------------------------- //
63
+
64
+ // Tensor block shape type defines what are the shape preference for the blocks
65
+ // extracted from the larger tensor.
66
+ //
67
+ // Example: blocks of 100 elements from the large 100x100 tensor:
68
+ // - tensor: 100x100
69
+ // - target_block_size: 100
70
+ //
71
+ // TensorBlockShapeType:
72
+ // - kUniformAllDims: 100 blocks of size 10x10
73
+ // - kSkewedInnerDims: 100 blocks of size 100x1 (or 1x100 depending on a column
74
+ // or row major layout)
75
+ enum class TensorBlockShapeType { kUniformAllDims, kSkewedInnerDims };
76
+
77
+ struct TensorBlockResourceRequirements {
78
+ TensorBlockShapeType shape_type; // target block shape
79
+ size_t size; // target block size
80
+ TensorOpCost cost_per_coeff; // cost of computing a single block element
81
+
82
+ #ifdef EIGEN_HIPCC
83
+ // For HIPCC, we need to explicitly declare as a "device fun", the constructor
84
+ // which is implicitly invoked in the "merge" / "any" routines. else HIPCC
85
+ // errors out complaining about the lack of a matching constructor
86
+ EIGEN_DEVICE_FUNC
87
+ TensorBlockResourceRequirements(TensorBlockShapeType shape_type_, size_t size_,
88
+ TensorOpCost cost_)
89
+ : shape_type(shape_type_), size(size_), cost_per_coeff(cost_)
90
+ {}
91
+ #endif
92
+
93
+ template <typename Scalar>
94
+ EIGEN_DEVICE_FUNC static TensorBlockResourceRequirements withShapeAndSize(
95
+ TensorBlockShapeType shape_type, size_t size_in_bytes,
96
+ TensorOpCost cost) {
97
+ const size_t size = numext::maxi(size_t(1), size_in_bytes / sizeof(Scalar));
98
+ return {shape_type, size, cost};
99
+ }
100
+
101
+ template <typename Scalar>
102
+ EIGEN_DEVICE_FUNC static TensorBlockResourceRequirements withShapeAndSize(
103
+ TensorBlockShapeType shape_type, size_t size_in_bytes) {
104
+ // This default cost per coefficient is valid for most materialized tensor
105
+ // block evaluation implementations, because they typically just read
106
+ // coefficients from the underlying tensor storage, and write to the tensor
107
+ // block buffer (scratch or destination memory, reads and writes have linear
108
+ // access pattern). We ignore the fixed cost of block evaluation, because in
109
+ // practice it should negligible.
110
+ //
111
+ // Lazy block evaluation adds the cost of calling a functor for each
112
+ // coefficient.
113
+ //
114
+ // All non-trivial block evaluation implementations must provide their own
115
+ // cost approximation (e.g. shuffling inner dimension has a much higher cost
116
+ // because it reads memory randomly, although the total number of moved
117
+ // bytes is the same).
118
+ return withShapeAndSize<Scalar>(shape_type, size_in_bytes,
119
+ {/*bytes_loaded=*/sizeof(Scalar),
120
+ /*bytes_stored=*/sizeof(Scalar),
121
+ /*compute_cycles=*/0});
122
+ }
123
+
124
+ template <typename Scalar>
125
+ EIGEN_DEVICE_FUNC static TensorBlockResourceRequirements skewed(
126
+ size_t size_in_bytes) {
127
+ return withShapeAndSize<Scalar>(TensorBlockShapeType::kSkewedInnerDims,
128
+ size_in_bytes);
129
+ }
130
+
131
+ template <typename Scalar>
132
+ EIGEN_DEVICE_FUNC static TensorBlockResourceRequirements uniform(
133
+ size_t size_in_bytes) {
134
+ return withShapeAndSize<Scalar>(TensorBlockShapeType::kUniformAllDims,
135
+ size_in_bytes);
136
+ }
137
+
138
+ EIGEN_DEVICE_FUNC
139
+ static EIGEN_STRONG_INLINE TensorBlockResourceRequirements
140
+ merge(const TensorBlockResourceRequirements& lhs,
141
+ const TensorBlockResourceRequirements& rhs) {
142
+ return {merge(lhs.shape_type, rhs.shape_type), // shape_type
143
+ merge(lhs.size, rhs.size), // size
144
+ merge(lhs.cost_per_coeff, rhs.cost_per_coeff)}; // cost_per_coeff
145
+ }
146
+
147
+ EIGEN_DEVICE_FUNC TensorBlockResourceRequirements& addCostPerCoeff(
148
+ TensorOpCost cost) {
149
+ cost_per_coeff += cost;
150
+ return *this;
151
+ }
152
+
153
+ // This is a resource requirement that should be returned from expressions
154
+ // that do not have any block evaluation preference (e.g. default tensor
155
+ // expression with raw buffer access).
156
+ EIGEN_DEVICE_FUNC
157
+ static EIGEN_STRONG_INLINE TensorBlockResourceRequirements any() {
158
+ return {TensorBlockShapeType::kUniformAllDims, 1, {0, 0, 0}};
159
+ }
160
+
161
+ private:
162
+ using Requirements = TensorBlockResourceRequirements;
163
+
164
+ EIGEN_DEVICE_FUNC
165
+ static EIGEN_STRONG_INLINE size_t merge(size_t lhs_size, size_t rhs_size) {
166
+ return numext::maxi(lhs_size, rhs_size);
167
+ }
168
+
169
+ EIGEN_DEVICE_FUNC
170
+ static EIGEN_STRONG_INLINE TensorBlockShapeType
171
+ merge(TensorBlockShapeType lhs, TensorBlockShapeType rhs) {
172
+ return (lhs == TensorBlockShapeType::kSkewedInnerDims ||
173
+ rhs == TensorBlockShapeType::kSkewedInnerDims)
174
+ ? TensorBlockShapeType::kSkewedInnerDims
175
+ : TensorBlockShapeType::kUniformAllDims;
176
+ }
177
+
178
+ EIGEN_DEVICE_FUNC
179
+ static EIGEN_STRONG_INLINE TensorOpCost merge(TensorOpCost lhs_cost,
180
+ TensorOpCost rhs_cost) {
181
+ return lhs_cost + rhs_cost;
182
+ }
183
+ };
184
+
185
+ // -------------------------------------------------------------------------- //
186
+ // TensorBlockDescriptor specifies a block offset within a tensor and the block
187
+ // sizes along each of the tensor dimensions.
188
+
189
+ template <int NumDims, typename IndexType = Eigen::Index>
190
+ class TensorBlockDescriptor {
191
+ public:
192
+ typedef DSizes<IndexType, NumDims> Dimensions;
193
+
194
+ // If we evaluate a Tensor assignment, and expression on the left, already has
195
+ // a memory buffer, then we might do performance optimization, and evaluate
196
+ // the root expression directly into the final output memory. Some time it's
197
+ // possible to reuse it for materializing subexpressions inside an expression
198
+ // tree, to to avoid dynamic memory allocation.
199
+ //
200
+ // The pointer type of the underlying storage is erased, because passing
201
+ // Scalar type through all the expression evaluation layers is way too many
202
+ // templates. In practice destination buffer type should always match the
203
+ // evaluated expression scalar type.
204
+ class DestinationBuffer {
205
+ public:
206
+ enum DestinationBufferKind : int {
207
+ // The above explicit specification of "int" as the enum basetype is
208
+ // needed to get around a HIPCC link error ("the field type is not
209
+ // amp-compatible")
210
+ // which is issued for class members with the enum type.
211
+ // TODO(rocm):
212
+ // remove the "int" basetype once HIPCC has been fixed to not error out
213
+ // in the above scenario.
214
+
215
+ // Destination buffer is not defined (`m_data` == nullptr).
216
+ kEmpty,
217
+
218
+ // Tensor block defined by an owning tensor block descriptor can fit
219
+ // contiguously into the destination buffer. In this case it's safe to
220
+ // materialize tensor block in the destination buffer, wrap it in a
221
+ // TensorMap, and use to build Eigen expression on top of it.
222
+ kContiguous,
223
+
224
+ // Destination buffer strides do not match strides of the contiguously
225
+ // stored block, and it's impossible to define a TensorMap over this
226
+ // buffer. However if we are evaluating a root of an expression tree, we
227
+ // still can materialize an output into this destination, because we can
228
+ // guarantee that no one will ever access it through block API.
229
+ //
230
+ // In theory it is possible to build valid TensorStriding<TensorMap>
231
+ // expression on top of this destination buffer, however it has
232
+ // inefficient coeff/packet access, and defeats the purpose of fast block
233
+ // evaluation API.
234
+ kStrided
235
+ };
236
+
237
+ template <typename Scalar>
238
+ Scalar* data() const {
239
+ eigen_assert(m_data_type_size == sizeof(Scalar));
240
+ return static_cast<Scalar*>(m_data);
241
+ }
242
+
243
+ const Dimensions& strides() const { return m_strides; }
244
+ const DestinationBufferKind& kind() const { return m_kind; }
245
+
246
+ private:
247
+ friend class TensorBlockDescriptor<NumDims, IndexType>;
248
+
249
+ DestinationBuffer() : m_data(NULL), m_data_type_size(0), m_kind(kEmpty) {}
250
+
251
+ template <typename Scalar>
252
+ DestinationBuffer(Scalar* data, const Dimensions& strides,
253
+ DestinationBufferKind kind)
254
+ : m_data(static_cast<void*>(data)),
255
+ m_data_type_size(sizeof(Scalar)),
256
+ m_strides(strides),
257
+ m_kind(kind) {}
258
+
259
+ template <int Layout, typename Scalar>
260
+ static DestinationBuffer make(const TensorBlockDescriptor& desc,
261
+ Scalar* data, const Dimensions& strides) {
262
+ return DestinationBuffer(data, strides, kind<Layout>(desc, strides));
263
+ }
264
+
265
+ template <int Layout>
266
+ static DestinationBufferKind kind(const TensorBlockDescriptor& desc,
267
+ const Dimensions& strides) {
268
+ const Dimensions& desc_dims = desc.dimensions();
269
+ const Dimensions& desc_strides = internal::strides<Layout>(desc_dims);
270
+ for (int i = 0; i < NumDims; ++i) {
271
+ if (desc_dims[i] == 1) continue;
272
+ if (desc_strides[i] != strides[i]) return kStrided;
273
+ }
274
+ return kContiguous;
275
+ }
276
+
277
+ // Storage pointer is type erased, to reduce template bloat, but we still
278
+ // keep the size of the underlying element type for error checking.
279
+ void* m_data;
280
+ size_t m_data_type_size;
281
+
282
+ // Destination buffer dimensions always match the dimensions of a tensor
283
+ // block descriptor it belongs to, however strides might be different.
284
+ Dimensions m_strides;
285
+
286
+ DestinationBufferKind m_kind;
287
+ };
288
+
289
+ TensorBlockDescriptor(const IndexType offset, const Dimensions& dimensions,
290
+ const DestinationBuffer& destination)
291
+ : m_offset(offset),
292
+ m_dimensions(dimensions),
293
+ m_destination(destination) {}
294
+
295
+ TensorBlockDescriptor(const IndexType offset, const Dimensions& dimensions)
296
+ : m_offset(offset),
297
+ m_dimensions(dimensions),
298
+ m_destination(DestinationBuffer()) {}
299
+
300
+ IndexType offset() const { return m_offset; }
301
+ const Dimensions& dimensions() const { return m_dimensions; }
302
+ IndexType dimension(int index) const { return m_dimensions[index]; }
303
+ IndexType size() const { return array_prod<IndexType>(m_dimensions); }
304
+
305
+ const DestinationBuffer& destination() const { return m_destination; }
306
+
307
+ template <int Layout, typename Scalar>
308
+ void AddDestinationBuffer(Scalar* dst_base, const Dimensions& dst_strides) {
309
+ eigen_assert(dst_base != NULL);
310
+ m_destination =
311
+ DestinationBuffer::template make<Layout>(*this, dst_base, dst_strides);
312
+ }
313
+
314
+ template <int Layout, typename Scalar, typename DstStridesIndexType>
315
+ void AddDestinationBuffer(
316
+ Scalar* dst_base,
317
+ const DSizes<DstStridesIndexType, NumDims>& dst_strides) {
318
+ // DSizes constructor will do index type promotion if it's safe.
319
+ AddDestinationBuffer<Layout>(dst_base, Dimensions(dst_strides));
320
+ }
321
+
322
+ TensorBlockDescriptor& DropDestinationBuffer() {
323
+ m_destination.m_data = NULL;
324
+ m_destination.m_kind = DestinationBuffer::kEmpty;
325
+ return *this;
326
+ }
327
+
328
+ bool HasDestinationBuffer() const {
329
+ return m_destination.kind() != DestinationBuffer::kEmpty;
330
+ }
331
+
332
+ // Returns a copy of `*this` with updated offset.
333
+ TensorBlockDescriptor WithOffset(IndexType offset) const {
334
+ return TensorBlockDescriptor(offset, m_dimensions, m_destination);
335
+ }
336
+
337
+ private:
338
+ // Offset and dimensions are immutable after construction. Block descriptor
339
+ // can only be mutated by adding or dropping destination.
340
+ const IndexType m_offset;
341
+ const Dimensions m_dimensions;
342
+ DestinationBuffer m_destination;
343
+ };
344
+
345
+ // -------------------------------------------------------------------------- //
346
+ // TensorBlockMapper is responsible for iterating over the blocks of a tensor.
347
+
348
+ template <int NumDims, int Layout, typename IndexType = Eigen::Index>
349
+ class TensorBlockMapper {
350
+ typedef TensorBlockDescriptor<NumDims, IndexType> BlockDescriptor;
351
+
352
+ public:
353
+ typedef DSizes<IndexType, NumDims> Dimensions;
354
+
355
+ TensorBlockMapper() = default;
356
+ TensorBlockMapper(const DSizes<IndexType, NumDims>& dimensions,
357
+ const TensorBlockResourceRequirements& requirements)
358
+ : m_tensor_dimensions(dimensions), m_requirements(requirements) {
359
+ // Compute block dimensions and the total number of blocks.
360
+ InitializeBlockDimensions();
361
+ }
362
+
363
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE IndexType blockCount() const {
364
+ return m_total_block_count;
365
+ }
366
+
367
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE IndexType blockTotalSize() const {
368
+ return m_block_dimensions.TotalSize();
369
+ }
370
+
371
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const DSizes<IndexType, NumDims>&
372
+ blockDimensions() const {
373
+ return m_block_dimensions;
374
+ }
375
+
376
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockDescriptor
377
+ blockDescriptor(IndexType block_index) const {
378
+ static const bool isColMajor = Layout == static_cast<int>(ColMajor);
379
+
380
+ IndexType offset = 0;
381
+ DSizes<IndexType, NumDims> dimensions;
382
+
383
+ if (NumDims == 0) return BlockDescriptor(offset, dimensions);
384
+
385
+ // Iterate outer -> inner dimensions.
386
+ for (int i = NumDims - 1; i >= 0; --i) {
387
+ const int dim = isColMajor ? i : NumDims - i - 1;
388
+
389
+ const IndexType idx = block_index / m_block_strides[dim];
390
+ block_index -= idx * m_block_strides[dim];
391
+
392
+ const IndexType coord = idx * m_block_dimensions[dim];
393
+ dimensions[dim] = numext::mini(m_tensor_dimensions[dim] - coord,
394
+ m_block_dimensions[dim]);
395
+ offset += coord * m_tensor_strides[dim];
396
+ }
397
+
398
+ return {offset, dimensions};
399
+ }
400
+
401
+ private:
402
+ void InitializeBlockDimensions() {
403
+ // Requested block shape and size.
404
+ const TensorBlockShapeType shape_type = m_requirements.shape_type;
405
+ IndexType target_block_size =
406
+ numext::maxi<IndexType>(1, static_cast<IndexType>(m_requirements.size));
407
+
408
+ IndexType tensor_size = m_tensor_dimensions.TotalSize();
409
+
410
+ // Corner case: one of the dimensions is zero. Logic below is too complex
411
+ // to handle this case on a general basis, just use unit block size.
412
+ // Note: we must not yield blocks with zero dimensions (recipe for
413
+ // overflows/underflows, divisions by zero and NaNs later).
414
+ if (tensor_size == 0) {
415
+ for (int i = 0; i < NumDims; ++i) {
416
+ m_block_dimensions[i] = 1;
417
+ }
418
+ m_total_block_count = 0;
419
+ return;
420
+ }
421
+
422
+ // If tensor fits into a target block size, evaluate it as a single block.
423
+ if (tensor_size <= target_block_size) {
424
+ m_block_dimensions = m_tensor_dimensions;
425
+ m_total_block_count = 1;
426
+ // The only valid block index is `0`, and in this case we do not need
427
+ // to compute real strides for tensor or blocks (see blockDescriptor).
428
+ for (int i = 0; i < NumDims; ++i) {
429
+ m_tensor_strides[i] = 0;
430
+ m_block_strides[i] = 1;
431
+ }
432
+ return;
433
+ }
434
+
435
+ static const bool isColMajor = Layout == static_cast<int>(ColMajor);
436
+
437
+ // Block shape skewed towards inner dimension.
438
+ if (shape_type == TensorBlockShapeType::kSkewedInnerDims) {
439
+ IndexType coeff_to_allocate = target_block_size;
440
+
441
+ for (int i = 0; i < NumDims; ++i) {
442
+ const int dim = isColMajor ? i : NumDims - i - 1;
443
+ m_block_dimensions[dim] =
444
+ numext::mini(coeff_to_allocate, m_tensor_dimensions[dim]);
445
+ coeff_to_allocate = divup(
446
+ coeff_to_allocate,
447
+ numext::maxi(static_cast<IndexType>(1), m_block_dimensions[dim]));
448
+ }
449
+ eigen_assert(coeff_to_allocate == 1);
450
+
451
+ } else if (shape_type == TensorBlockShapeType::kUniformAllDims) {
452
+ // Tensor will not fit within 'target_block_size' budget: calculate tensor
453
+ // block dimension sizes based on "square" dimension size target.
454
+ const IndexType dim_size_target = convert_index<IndexType>(
455
+ std::pow(static_cast<float>(target_block_size),
456
+ 1.0f / static_cast<float>(m_block_dimensions.rank())));
457
+
458
+ for (int i = 0; i < NumDims; ++i) {
459
+ // TODO(andydavis) Adjust the inner most 'block_dim_size' to make it
460
+ // a multiple of the packet size. Note that reducing
461
+ // 'block_dim_size' in this manner can increase the number of
462
+ // blocks, and so will amplify any per-block overhead.
463
+ m_block_dimensions[i] =
464
+ numext::mini(dim_size_target, m_tensor_dimensions[i]);
465
+ }
466
+
467
+ // Add any un-allocated coefficients to inner dimension(s).
468
+ IndexType total_size = m_block_dimensions.TotalSize();
469
+ for (int i = 0; i < NumDims; ++i) {
470
+ const int dim = isColMajor ? i : NumDims - i - 1;
471
+
472
+ if (m_block_dimensions[dim] < m_tensor_dimensions[dim]) {
473
+ const IndexType total_size_other_dims =
474
+ total_size / m_block_dimensions[dim];
475
+ const IndexType alloc_avail =
476
+ divup<IndexType>(target_block_size, total_size_other_dims);
477
+ if (alloc_avail == m_block_dimensions[dim]) {
478
+ // Insufficient excess coefficients to allocate.
479
+ break;
480
+ }
481
+ m_block_dimensions[dim] =
482
+ numext::mini(m_tensor_dimensions[dim], alloc_avail);
483
+ total_size = total_size_other_dims * m_block_dimensions[dim];
484
+ }
485
+ }
486
+
487
+ } else {
488
+ eigen_assert(false); // unknown block shape
489
+ }
490
+
491
+ eigen_assert(m_block_dimensions.TotalSize() >=
492
+ numext::mini<IndexType>(target_block_size,
493
+ m_tensor_dimensions.TotalSize()));
494
+
495
+ // Calculate block counts by dimension and total block count.
496
+ DSizes<IndexType, NumDims> block_count;
497
+ for (int i = 0; i < NumDims; ++i) {
498
+ block_count[i] = divup(m_tensor_dimensions[i], m_block_dimensions[i]);
499
+ }
500
+ m_total_block_count = array_prod(block_count);
501
+
502
+ // Calculate block strides (used for enumerating blocks).
503
+ m_tensor_strides = strides<Layout>(m_tensor_dimensions);
504
+ m_block_strides = strides<Layout>(block_count);
505
+ }
506
+
507
+ DSizes<IndexType, NumDims> m_tensor_dimensions;
508
+ TensorBlockResourceRequirements m_requirements;
509
+
510
+ DSizes<IndexType, NumDims> m_block_dimensions;
511
+ IndexType m_total_block_count;
512
+
513
+ DSizes<IndexType, NumDims> m_tensor_strides;
514
+ DSizes<IndexType, NumDims> m_block_strides;
515
+ };
516
+
517
+ // -------------------------------------------------------------------------- //
518
+ // TensorBlockScratchAllocator is responsible for allocating temporary buffers
519
+ // for block evaluation (output or input block materialization). Given that
520
+ // Eigen expression traversal order is deterministic, all temporary allocations
521
+ // are happening in the same order, and usually have exactly the same size.
522
+ // Scratch allocator keeps a trace of all dynamic allocations, and after the
523
+ // first block evaluation is completed, we should be able to reuse all the
524
+ // temporary buffers for the next block evaluation.
525
+
526
+ template <typename Device>
527
+ class TensorBlockScratchAllocator {
528
+ public:
529
+ explicit TensorBlockScratchAllocator(const Device& device)
530
+ : m_device(device), m_allocation_index(0) {}
531
+
532
+ ~TensorBlockScratchAllocator() {
533
+ for (size_t i = 0; i < m_allocations.size(); ++i) {
534
+ m_device.deallocate(m_allocations[i].ptr);
535
+ }
536
+ }
537
+
538
+ void* allocate(size_t size) {
539
+ // TODO(ezhulenev): Remove when replaced with inlined vector.
540
+ if (m_allocations.capacity() == 0) m_allocations.reserve(8);
541
+
542
+ // Check if we already have an existing allocation att current index.
543
+ const int num_allocations = static_cast<int>(m_allocations.size());
544
+ const bool has_allocation = m_allocation_index < num_allocations;
545
+
546
+ // Allocation index can't be larger than the number of allocations.
547
+ eigen_assert(m_allocation_index <= num_allocations);
548
+
549
+ // If we have existing allocation, and its size is larger or equal to
550
+ // requested size, we do nothing.
551
+
552
+ // If current allocation can't fit requested size, we deallocate it, and
553
+ // replace with a larger allocation.
554
+ if (has_allocation && m_allocations[m_allocation_index].size < size) {
555
+ m_device.deallocate(m_allocations[m_allocation_index].ptr);
556
+ m_allocations[m_allocation_index].ptr = m_device.allocate(size);
557
+ m_allocations[m_allocation_index].size = size;
558
+ }
559
+
560
+ // Make a new allocation if we don't have and existing one.
561
+ if (!has_allocation) {
562
+ Allocation allocation;
563
+ allocation.ptr = m_device.allocate(size);
564
+ allocation.size = size;
565
+ m_allocations.push_back(allocation);
566
+ }
567
+
568
+ eigen_assert(m_allocations[m_allocation_index].ptr != NULL);
569
+ eigen_assert(m_allocations[m_allocation_index].size >= size);
570
+
571
+ return m_allocations[m_allocation_index++].ptr;
572
+ }
573
+
574
+ void reset() { m_allocation_index = 0; }
575
+
576
+ private:
577
+ struct Allocation {
578
+ void* ptr;
579
+ size_t size;
580
+ };
581
+
582
+ const Device& m_device;
583
+ int m_allocation_index;
584
+ // TODO(ezhulenev): This should be an inlined vector.
585
+ std::vector<Allocation> m_allocations;
586
+ };
587
+
588
+ // -------------------------------------------------------------------------- //
589
+ // TensorBlockKind represents all possible block kinds, that can be produced by
590
+ // TensorEvaluator::evalBlock function.
591
+ enum TensorBlockKind {
592
+ // Tensor block that is a lazy expression that must be assigned to a
593
+ // destination using TensorBlockAssign.
594
+ kExpr,
595
+
596
+ // Tensor block that is a view into a memory buffer owned by an underlying
597
+ // Tensor expression (e.g. it can be a view into a Tensor buffer).
598
+ kView,
599
+
600
+ // Tensor block that was materialized in a scratch memory buffer, allocated
601
+ // with TensorBlockScratchAllocator. This block must be copied to a
602
+ // destination, similar to a block of `kExpr` type.
603
+ kMaterializedInScratch,
604
+
605
+ // Tensor block that was materialized directly into the final output memory
606
+ // buffer. For example if the left side of an assignment is a Tensor, we can
607
+ // directly materialize the block in the destination memory.
608
+ //
609
+ // If strides in the output buffer do not match tensor block strides, the
610
+ // Tensor expression will be invalid, and should not be used by
611
+ // TensorBlockAssign or for constructing another block expression.
612
+ kMaterializedInOutput
613
+ };
614
+
615
+ // -------------------------------------------------------------------------- //
616
+ // TensorBlockNotImplemented should be used to defined TensorBlock typedef in
617
+ // TensorEvaluators that do not support block evaluation.
618
+
619
+ class TensorBlockNotImplemented {
620
+ public:
621
+ typedef void XprType;
622
+ };
623
+
624
+ // -------------------------------------------------------------------------- //
625
+ // XprScalar extracts Scalar type from the Eigen expressions (if expression type
626
+ // is not void). It's required to be able to define lazy block expression for
627
+ // argument types, that do not support block evaluation.
628
+
629
+ template <typename XprType>
630
+ struct XprScalar {
631
+ typedef typename XprType::Scalar type;
632
+ };
633
+ template <>
634
+ struct XprScalar<void> {
635
+ typedef void type;
636
+ };
637
+
638
+ // -------------------------------------------------------------------------- //
639
+ // TensorMaterializedBlock is a fully evaluated block of the original tensor,
640
+ // and XprType is just a TensorMap over the data. This block type is typically
641
+ // used to materialize blocks of tensor expressions, that can't be efficiently
642
+ // represented as lazy Tensor expressions with fast coeff/packet operations,
643
+ // e.g. we materialize all broadcasts into evaluated blocks.
644
+ //
645
+ // TensorMaterializedBlock does not own its memory buffer, it's either a memory
646
+ // buffer that backs the original expression (e.g. block is just a view into a
647
+ // Tensor), or a memory buffer allocated with scratch allocator, and in this
648
+ // case the scratch allocator will deallocate it at the end of block based
649
+ // expression execution.
650
+ //
651
+ // If the block was evaluated directly into the output buffer, and strides in
652
+ // the output buffer do not match block strides, the TensorMap expression will
653
+ // be invalid, and should never be used in block assignment or any other tensor
654
+ // expression.
655
+
656
+ template <typename Scalar, int NumDims, int Layout,
657
+ typename IndexType = Eigen::Index>
658
+ class TensorMaterializedBlock {
659
+ public:
660
+ typedef DSizes<IndexType, NumDims> Dimensions;
661
+ typedef TensorMap<const Tensor<Scalar, NumDims, Layout> > XprType;
662
+
663
+ TensorMaterializedBlock(TensorBlockKind kind, const Scalar* data,
664
+ const Dimensions& dimensions, bool valid_expr = true)
665
+ : m_kind(kind),
666
+ m_data(data),
667
+ m_dimensions(dimensions),
668
+ m_expr(m_data, m_dimensions),
669
+ m_valid_expr(valid_expr) {
670
+ eigen_assert(m_kind == internal::TensorBlockKind::kView ||
671
+ m_kind == internal::TensorBlockKind::kMaterializedInScratch ||
672
+ m_kind == internal::TensorBlockKind::kMaterializedInOutput);
673
+ }
674
+
675
+ TensorBlockKind kind() const { return m_kind; }
676
+ // NOTE(ezhulenev): Returning XprType by value like in other block types
677
+ // causes asan failures. The theory is that XprType::Nested doesn't work
678
+ // properly for TensorMap.
679
+ const XprType& expr() const {
680
+ eigen_assert(m_valid_expr);
681
+ return m_expr;
682
+ }
683
+ const Scalar* data() const { return m_data; }
684
+ void cleanup() {}
685
+
686
+ typedef internal::TensorBlockDescriptor<NumDims, IndexType> TensorBlockDesc;
687
+
688
+ // TensorMaterializedBlock can be backed by different types of storage:
689
+ //
690
+ // (1) Contiguous block of memory allocated with scratch allocator.
691
+ // (2) Contiguous block of memory reused from tensor block descriptor
692
+ // destination buffer.
693
+ // (3) Strided block of memory reused from tensor block descriptor
694
+ // destination buffer.
695
+ //
696
+ class Storage {
697
+ public:
698
+ Scalar* data() const { return m_data; }
699
+ const Dimensions& dimensions() const { return m_dimensions; }
700
+ const Dimensions& strides() const { return m_strides; }
701
+
702
+ TensorMaterializedBlock AsTensorMaterializedBlock() const {
703
+ return TensorMaterializedBlock(
704
+ m_materialized_in_output
705
+ ? internal::TensorBlockKind::kMaterializedInOutput
706
+ : internal::TensorBlockKind::kMaterializedInScratch,
707
+ m_data, m_dimensions, !m_strided_storage);
708
+ }
709
+
710
+ private:
711
+ friend class TensorMaterializedBlock<Scalar, NumDims, Layout, IndexType>;
712
+
713
+ Storage(Scalar* data, const Dimensions& dimensions,
714
+ const Dimensions& strides, bool materialized_in_output,
715
+ bool strided_storage)
716
+ : m_data(data),
717
+ m_dimensions(dimensions),
718
+ m_strides(strides),
719
+ m_materialized_in_output(materialized_in_output),
720
+ m_strided_storage(strided_storage) {}
721
+
722
+ Scalar* m_data;
723
+ Dimensions m_dimensions;
724
+ Dimensions m_strides;
725
+ bool m_materialized_in_output;
726
+ bool m_strided_storage;
727
+ };
728
+
729
+ // Creates a storage for materialized block either from the block descriptor
730
+ // destination buffer, or allocates a new buffer with scratch allocator.
731
+ template <typename TensorBlockScratch>
732
+ EIGEN_STRONG_INLINE static Storage prepareStorage(
733
+ TensorBlockDesc& desc, TensorBlockScratch& scratch,
734
+ bool allow_strided_storage = false) {
735
+ // Try to reuse destination as an output block buffer.
736
+ typedef typename TensorBlockDesc::DestinationBuffer DestinationBuffer;
737
+
738
+ if (desc.destination().kind() == DestinationBuffer::kContiguous) {
739
+ Scalar* buffer = desc.destination().template data<Scalar>();
740
+ desc.DropDestinationBuffer();
741
+ return Storage(buffer, desc.dimensions(),
742
+ internal::strides<Layout>(desc.dimensions()),
743
+ /*materialized_in_output=*/true,
744
+ /*strided_storage=*/false);
745
+
746
+ } else if (desc.destination().kind() == DestinationBuffer::kStrided &&
747
+ allow_strided_storage) {
748
+ Scalar* buffer = desc.destination().template data<Scalar>();
749
+ desc.DropDestinationBuffer();
750
+ return Storage(buffer, desc.dimensions(), desc.destination().strides(),
751
+ /*materialized_in_output=*/true, /*strided_storage=*/true);
752
+
753
+ } else {
754
+ void* mem = scratch.allocate(desc.size() * sizeof(Scalar));
755
+ return Storage(static_cast<Scalar*>(mem), desc.dimensions(),
756
+ internal::strides<Layout>(desc.dimensions()),
757
+ /*materialized_in_output=*/false,
758
+ /*strided_storage=*/false);
759
+ }
760
+ }
761
+
762
+ // Creates a materialized block for the given descriptor from a memory buffer.
763
+ template <typename DataDimensions, typename TensorBlockScratch>
764
+ EIGEN_STRONG_INLINE static TensorMaterializedBlock materialize(
765
+ const Scalar* data, const DataDimensions& data_dims,
766
+ TensorBlockDesc& desc, TensorBlockScratch& scratch) {
767
+ eigen_assert(array_size<DataDimensions>::value == desc.dimensions().size());
768
+
769
+ // If a tensor block dimensions covers a contiguous block of the underlying
770
+ // memory, we can skip block buffer memory allocation, and construct a block
771
+ // from existing `data` memory buffer.
772
+ //
773
+ // Example: (RowMajor layout)
774
+ // data_dims: [11, 12, 13, 14]
775
+ // desc.dimensions(): [1, 1, 3, 14]
776
+ //
777
+ // In this case we can construct a TensorBlock starting at
778
+ // `data + desc.offset()`, with a `desc.dimensions()` block sizes.
779
+ static const bool is_col_major = Layout == ColMajor;
780
+
781
+ // Find out how many inner dimensions have a matching size.
782
+ int num_matching_inner_dims = 0;
783
+ for (int i = 0; i < NumDims; ++i) {
784
+ int dim = is_col_major ? i : NumDims - i - 1;
785
+ if (data_dims[dim] != desc.dimensions()[dim]) break;
786
+ ++num_matching_inner_dims;
787
+ }
788
+
789
+ // All the outer dimensions must be of size `1`, except a single dimension
790
+ // before the matching inner dimension (`3` in the example above).
791
+ bool can_use_direct_access = true;
792
+ for (int i = num_matching_inner_dims + 1; i < NumDims; ++i) {
793
+ int dim = is_col_major ? i : NumDims - i - 1;
794
+ if (desc.dimension(dim) != 1) {
795
+ can_use_direct_access = false;
796
+ break;
797
+ }
798
+ }
799
+
800
+ if (can_use_direct_access) {
801
+ const Scalar* block_start = data + desc.offset();
802
+ return TensorMaterializedBlock(internal::TensorBlockKind::kView,
803
+ block_start, desc.dimensions());
804
+
805
+ } else {
806
+ // Reuse destination buffer or allocate new buffer with scratch allocator.
807
+ const Storage storage = prepareStorage(desc, scratch);
808
+
809
+ typedef internal::TensorBlockIO<Scalar, IndexType, NumDims, Layout>
810
+ TensorBlockIO;
811
+ typedef typename TensorBlockIO::Dst TensorBlockIODst;
812
+ typedef typename TensorBlockIO::Src TensorBlockIOSrc;
813
+
814
+ TensorBlockIOSrc src(internal::strides<Layout>(Dimensions(data_dims)),
815
+ data, desc.offset());
816
+ TensorBlockIODst dst(storage.dimensions(), storage.strides(),
817
+ storage.data());
818
+
819
+ TensorBlockIO::Copy(dst, src);
820
+ return storage.AsTensorMaterializedBlock();
821
+ }
822
+ }
823
+
824
+ private:
825
+ TensorBlockKind m_kind;
826
+ const Scalar* m_data;
827
+ Dimensions m_dimensions;
828
+ XprType m_expr;
829
+ bool m_valid_expr;
830
+ };
831
+
832
+ // -------------------------------------------------------------------------- //
833
+ // TensorCwiseUnaryBlock is a lazy tensor expression block that applies UnaryOp
834
+ // functor to the blocks produced by the underlying Tensor expression.
835
+
836
+ template <typename UnaryOp, typename ArgTensorBlock>
837
+ class TensorCwiseUnaryBlock {
838
+ static constexpr bool NoArgBlockAccess =
839
+ internal::is_void<typename ArgTensorBlock::XprType>::value;
840
+
841
+ public:
842
+ typedef std::conditional_t<
843
+ NoArgBlockAccess, void,
844
+ TensorCwiseUnaryOp<UnaryOp, const typename ArgTensorBlock::XprType> >
845
+ XprType;
846
+
847
+ typedef typename XprScalar<XprType>::type Scalar;
848
+
849
+ TensorCwiseUnaryBlock(const ArgTensorBlock& arg_block, const UnaryOp& functor)
850
+ : m_arg_block(arg_block), m_functor(functor) {}
851
+
852
+ TensorBlockKind kind() const { return internal::TensorBlockKind::kExpr; }
853
+
854
+ XprType expr() const { return XprType(m_arg_block.expr(), m_functor); }
855
+ const Scalar* data() const { return NULL; }
856
+ void cleanup() { m_arg_block.cleanup(); }
857
+
858
+ private:
859
+ ArgTensorBlock m_arg_block;
860
+ UnaryOp m_functor;
861
+ };
862
+
863
+ // -------------------------------------------------------------------------- //
864
+ // TensorCwiseUnaryBlock is a lazy tensor expression block that applies BinaryOp
865
+ // functor to the blocks produced by the underlying Tensor expression.
866
+
867
+ template <typename BinaryOp, typename LhsTensorBlock, typename RhsTensorBlock>
868
+ class TensorCwiseBinaryBlock {
869
+ static constexpr bool NoArgBlockAccess =
870
+ internal::is_void<typename LhsTensorBlock::XprType>::value ||
871
+ internal::is_void<typename RhsTensorBlock::XprType>::value;
872
+
873
+ public:
874
+ typedef std::conditional_t<
875
+ NoArgBlockAccess, void,
876
+ TensorCwiseBinaryOp<BinaryOp, const typename LhsTensorBlock::XprType,
877
+ const typename RhsTensorBlock::XprType> >
878
+ XprType;
879
+
880
+ typedef typename XprScalar<XprType>::type Scalar;
881
+
882
+ TensorCwiseBinaryBlock(const LhsTensorBlock& left_block,
883
+ const RhsTensorBlock& right_block,
884
+ const BinaryOp& functor)
885
+ : m_left_block(left_block),
886
+ m_right_block(right_block),
887
+ m_functor(functor) {}
888
+
889
+ TensorBlockKind kind() const { return internal::TensorBlockKind::kExpr; }
890
+
891
+ XprType expr() const {
892
+ return XprType(m_left_block.expr(), m_right_block.expr(), m_functor);
893
+ }
894
+
895
+ const Scalar* data() const { return NULL; }
896
+
897
+ void cleanup() {
898
+ m_left_block.cleanup();
899
+ m_right_block.cleanup();
900
+ }
901
+
902
+ private:
903
+ LhsTensorBlock m_left_block;
904
+ RhsTensorBlock m_right_block;
905
+ BinaryOp m_functor;
906
+ };
907
+
908
+ // -------------------------------------------------------------------------- //
909
+ // TensorUnaryExprBlock is a lazy tensor expression block that can construct
910
+ // an arbitrary tensor expression from a block of the underlying type (this is a
911
+ // generalization of the TensorCwiseUnaryBlock for arbitrary expressions).
912
+
913
+ template <typename BlockFactory, typename ArgTensorBlock>
914
+ class TensorUnaryExprBlock {
915
+ typedef typename ArgTensorBlock::XprType ArgXprType;
916
+ static constexpr bool NoArgBlockAccess = internal::is_void<ArgXprType>::value;
917
+
918
+ public:
919
+ typedef std::conditional_t<
920
+ NoArgBlockAccess, void,
921
+ typename BlockFactory::template XprType<ArgXprType>::type> XprType;
922
+
923
+ typedef typename XprScalar<XprType>::type Scalar;
924
+
925
+ TensorUnaryExprBlock(const ArgTensorBlock& arg_block,
926
+ const BlockFactory& factory)
927
+ : m_arg_block(arg_block), m_factory(factory) {}
928
+
929
+ TensorBlockKind kind() const { return internal::TensorBlockKind::kExpr; }
930
+ XprType expr() const { return m_factory.expr(m_arg_block.expr()); }
931
+ const Scalar* data() const { return NULL; }
932
+ void cleanup() { m_arg_block.cleanup(); }
933
+
934
+ private:
935
+ ArgTensorBlock m_arg_block;
936
+ BlockFactory m_factory;
937
+ };
938
+
939
+ // -------------------------------------------------------------------------- //
940
+ // TensorTernaryExprBlock is a lazy tensor expression block that can construct
941
+ // an arbitrary tensor expression from three blocks of the underlying type.
942
+
943
+ template <typename BlockFactory, typename Arg1TensorBlock,
944
+ typename Arg2TensorBlock, typename Arg3TensorBlock>
945
+ class TensorTernaryExprBlock {
946
+ typedef typename Arg1TensorBlock::XprType Arg1XprType;
947
+ typedef typename Arg2TensorBlock::XprType Arg2XprType;
948
+ typedef typename Arg3TensorBlock::XprType Arg3XprType;
949
+
950
+ static constexpr bool NoArgBlockAccess = internal::is_void<Arg1XprType>::value ||
951
+ internal::is_void<Arg2XprType>::value ||
952
+ internal::is_void<Arg3XprType>::value;
953
+
954
+ public:
955
+ typedef std::conditional_t<
956
+ NoArgBlockAccess, void,
957
+ typename BlockFactory::template XprType<Arg1XprType, Arg2XprType,
958
+ Arg3XprType>::type> XprType;
959
+
960
+ typedef typename XprScalar<XprType>::type Scalar;
961
+
962
+ TensorTernaryExprBlock(const Arg1TensorBlock& arg1_block,
963
+ const Arg2TensorBlock& arg2_block,
964
+ const Arg3TensorBlock& arg3_block,
965
+ const BlockFactory& factory)
966
+ : m_arg1_block(arg1_block),
967
+ m_arg2_block(arg2_block),
968
+ m_arg3_block(arg3_block),
969
+ m_factory(factory) {}
970
+
971
+ TensorBlockKind kind() const { return internal::TensorBlockKind::kExpr; }
972
+ XprType expr() const {
973
+ return m_factory.expr(m_arg1_block.expr(), m_arg2_block.expr(),
974
+ m_arg3_block.expr());
975
+ }
976
+ const Scalar* data() const { return NULL; }
977
+ void cleanup() {
978
+ m_arg1_block.cleanup();
979
+ m_arg2_block.cleanup();
980
+ m_arg3_block.cleanup();
981
+ }
982
+
983
+ private:
984
+ Arg1TensorBlock m_arg1_block;
985
+ Arg2TensorBlock m_arg2_block;
986
+ Arg3TensorBlock m_arg3_block;
987
+ BlockFactory m_factory;
988
+ };
989
+
990
+ // -------------------------------------------------------------------------- //
991
+ // StridedLinearBufferCopy provides a method to copy data between two linear
992
+ // buffers with different strides, with optimized paths for scatter/gather.
993
+
994
+ template <typename Scalar, typename IndexType>
995
+ class StridedLinearBufferCopy {
996
+ typedef typename packet_traits<Scalar>::type Packet;
997
+ typedef typename unpacket_traits<Packet>::half HalfPacket;
998
+ enum {
999
+ Vectorizable = packet_traits<Scalar>::Vectorizable,
1000
+ PacketSize = packet_traits<Scalar>::size,
1001
+ HalfPacketSize = unpacket_traits<HalfPacket>::size,
1002
+ HasHalfPacket = static_cast<int>(HalfPacketSize) < static_cast<int>(PacketSize)
1003
+ };
1004
+
1005
+ public:
1006
+ // Specifying linear copy kind statically gives ~30% speedup for small sizes.
1007
+ enum class Kind {
1008
+ Linear = 0, // src_stride == 1 && dst_stride == 1
1009
+ Scatter = 1, // src_stride == 1 && dst_stride != 1
1010
+ FillLinear = 2, // src_stride == 0 && dst_stride == 1
1011
+ FillScatter = 3, // src_stride == 0 && dst_stride != 1
1012
+ Gather = 4, // dst_stride == 1
1013
+ Random = 5 // everything else
1014
+ };
1015
+
1016
+ struct Dst {
1017
+ Dst(IndexType o, IndexType s, Scalar* d) : offset(o), stride(s), data(d) {}
1018
+
1019
+ IndexType offset;
1020
+ IndexType stride;
1021
+ Scalar* data;
1022
+ };
1023
+
1024
+ struct Src {
1025
+ Src(IndexType o, IndexType s, const Scalar* d)
1026
+ : offset(o), stride(s), data(d) {}
1027
+
1028
+ IndexType offset;
1029
+ IndexType stride;
1030
+ const Scalar* data;
1031
+ };
1032
+
1033
+ template <typename StridedLinearBufferCopy::Kind kind>
1034
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void Run(const Dst& dst,
1035
+ const Src& src,
1036
+ const size_t count) {
1037
+ Run<kind>(count, dst.offset, dst.stride, dst.data, src.offset, src.stride,
1038
+ src.data);
1039
+ }
1040
+
1041
+ private:
1042
+ template <typename StridedLinearBufferCopy::Kind kind>
1043
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void Run(
1044
+ const IndexType count, const IndexType dst_offset,
1045
+ const IndexType dst_stride, Scalar* EIGEN_RESTRICT dst_data,
1046
+ const IndexType src_offset, const IndexType src_stride,
1047
+ const Scalar* EIGEN_RESTRICT src_data) {
1048
+ const Scalar* src = &src_data[src_offset];
1049
+ Scalar* dst = &dst_data[dst_offset];
1050
+
1051
+ if (!Vectorizable) {
1052
+ for (Index i = 0; i < count; ++i) {
1053
+ dst[i * dst_stride] = src[i * src_stride];
1054
+ }
1055
+ return;
1056
+ }
1057
+
1058
+ const IndexType vectorized_size = count - PacketSize;
1059
+ IndexType i = 0;
1060
+
1061
+ if (kind == StridedLinearBufferCopy::Kind::Linear) {
1062
+ // ******************************************************************** //
1063
+ // Linear copy from `src` to `dst`.
1064
+ const IndexType unrolled_size = count - 4 * PacketSize;
1065
+ eigen_assert(src_stride == 1 && dst_stride == 1);
1066
+ for (; i <= unrolled_size; i += 4 * PacketSize) {
1067
+ for (int j = 0; j < 4; ++j) {
1068
+ Packet p = ploadu<Packet>(src + i + j * PacketSize);
1069
+ pstoreu<Scalar, Packet>(dst + i + j * PacketSize, p);
1070
+ }
1071
+ }
1072
+ for (; i <= vectorized_size; i += PacketSize) {
1073
+ Packet p = ploadu<Packet>(src + i);
1074
+ pstoreu<Scalar, Packet>(dst + i, p);
1075
+ }
1076
+ if (HasHalfPacket) {
1077
+ const IndexType vectorized_half_size = count - HalfPacketSize;
1078
+ if (i <= vectorized_half_size) {
1079
+ HalfPacket p = ploadu<HalfPacket>(src + i);
1080
+ pstoreu<Scalar, HalfPacket>(dst + i, p);
1081
+ i += HalfPacketSize;
1082
+ }
1083
+ }
1084
+ for (; i < count; ++i) {
1085
+ dst[i] = src[i];
1086
+ }
1087
+ // ******************************************************************** //
1088
+ } else if (kind == StridedLinearBufferCopy::Kind::Scatter) {
1089
+ // Scatter from `src` to `dst`.
1090
+ eigen_assert(src_stride == 1 && dst_stride != 1);
1091
+ for (; i <= vectorized_size; i += PacketSize) {
1092
+ Packet p = ploadu<Packet>(src + i);
1093
+ pscatter<Scalar, Packet>(dst + i * dst_stride, p, dst_stride);
1094
+ }
1095
+ if (HasHalfPacket) {
1096
+ const IndexType vectorized_half_size = count - HalfPacketSize;
1097
+ if (i <= vectorized_half_size) {
1098
+ HalfPacket p = ploadu<HalfPacket>(src + i);
1099
+ pscatter<Scalar, HalfPacket>(dst + i * dst_stride, p, dst_stride);
1100
+ i += HalfPacketSize;
1101
+ }
1102
+ }
1103
+ for (; i < count; ++i) {
1104
+ dst[i * dst_stride] = src[i];
1105
+ }
1106
+ // ******************************************************************** //
1107
+ } else if (kind == StridedLinearBufferCopy::Kind::FillLinear) {
1108
+ // Fill `dst` with value at `*src`.
1109
+ eigen_assert(src_stride == 0 && dst_stride == 1);
1110
+ const IndexType unrolled_size = count - 4 * PacketSize;
1111
+ Scalar s = *src;
1112
+ Packet p = pset1<Packet>(s);
1113
+ for (; i <= unrolled_size; i += 4 * PacketSize) {
1114
+ for (int j = 0; j < 4; ++j) {
1115
+ pstoreu<Scalar, Packet>(dst + i + j * PacketSize, p);
1116
+ }
1117
+ }
1118
+ for (; i <= vectorized_size; i += PacketSize) {
1119
+ pstoreu<Scalar, Packet>(dst + i, p);
1120
+ }
1121
+ if (HasHalfPacket) {
1122
+ const IndexType vectorized_half_size = count - HalfPacketSize;
1123
+ if (i <= vectorized_half_size) {
1124
+ HalfPacket hp = pset1<HalfPacket>(s);
1125
+ pstoreu<Scalar, HalfPacket>(dst + i, hp);
1126
+ i += HalfPacketSize;
1127
+ }
1128
+ }
1129
+ for (; i < count; ++i) {
1130
+ dst[i] = s;
1131
+ }
1132
+ // ******************************************************************** //
1133
+ } else if (kind == StridedLinearBufferCopy::Kind::FillScatter) {
1134
+ // Scatter `*src` into `dst`.
1135
+ eigen_assert(src_stride == 0 && dst_stride != 1);
1136
+ Scalar s = *src;
1137
+ Packet p = pset1<Packet>(s);
1138
+ for (; i <= vectorized_size; i += PacketSize) {
1139
+ pscatter<Scalar, Packet>(dst + i * dst_stride, p, dst_stride);
1140
+ }
1141
+ if (HasHalfPacket) {
1142
+ const IndexType vectorized_half_size = count - HalfPacketSize;
1143
+ if (i <= vectorized_half_size) {
1144
+ HalfPacket hp = pset1<HalfPacket>(s);
1145
+ pscatter<Scalar, HalfPacket>(dst + i * dst_stride, hp, dst_stride);
1146
+ i += HalfPacketSize;
1147
+ }
1148
+ }
1149
+ for (; i < count; ++i) {
1150
+ dst[i * dst_stride] = s;
1151
+ }
1152
+ // ******************************************************************** //
1153
+ } else if (kind == StridedLinearBufferCopy::Kind::Gather) {
1154
+ // Gather from `src` into `dst`.
1155
+ eigen_assert(dst_stride == 1);
1156
+ for (; i <= vectorized_size; i += PacketSize) {
1157
+ Packet p = pgather<Scalar, Packet>(src + i * src_stride, src_stride);
1158
+ pstoreu<Scalar, Packet>(dst + i, p);
1159
+ }
1160
+ if (HasHalfPacket) {
1161
+ const IndexType vectorized_half_size = count - HalfPacketSize;
1162
+ if (i <= vectorized_half_size) {
1163
+ HalfPacket p =
1164
+ pgather<Scalar, HalfPacket>(src + i * src_stride, src_stride);
1165
+ pstoreu<Scalar, HalfPacket>(dst + i, p);
1166
+ i += HalfPacketSize;
1167
+ }
1168
+ }
1169
+ for (; i < count; ++i) {
1170
+ dst[i] = src[i * src_stride];
1171
+ }
1172
+ // ******************************************************************** //
1173
+ } else if (kind == StridedLinearBufferCopy::Kind::Random) {
1174
+ // Random.
1175
+ for (; i < count; ++i) {
1176
+ dst[i * dst_stride] = src[i * src_stride];
1177
+ }
1178
+ } else {
1179
+ eigen_assert(false);
1180
+ }
1181
+ }
1182
+ };
1183
+
1184
+ // -------------------------------------------------------------------------- //
1185
+ // TensorBlockIO copies data from `src` tensor block, to the `dst` tensor block.
1186
+ // It's possible to specify src->dst dimension mapping for the copy operation.
1187
+ // Dimensions of `dst` specify how many elements have to be copied, for the
1188
+ // `src` we need to know only stride to navigate through source memory buffer.
1189
+
1190
+ template <typename Scalar, typename IndexType, int NumDims, int Layout>
1191
+ class TensorBlockIO {
1192
+ static constexpr bool IsColMajor = (Layout == ColMajor);
1193
+
1194
+ typedef StridedLinearBufferCopy<Scalar, IndexType> LinCopy;
1195
+
1196
+ public:
1197
+ typedef DSizes<IndexType, NumDims> Dimensions;
1198
+ typedef DSizes<int, NumDims> DimensionsMap;
1199
+
1200
+ struct Dst {
1201
+ Dst(const Dimensions& dst_dims, const Dimensions& dst_strides, Scalar* dst,
1202
+ IndexType dst_offset = 0)
1203
+ : dims(dst_dims), strides(dst_strides), data(dst), offset(dst_offset) {}
1204
+
1205
+ Dimensions dims;
1206
+ Dimensions strides;
1207
+ Scalar* data;
1208
+ IndexType offset;
1209
+ };
1210
+
1211
+ struct Src {
1212
+ Src(const Dimensions& src_strides, const Scalar* src,
1213
+ IndexType src_offset = 0)
1214
+ : strides(src_strides), data(src), offset(src_offset) {}
1215
+
1216
+ Dimensions strides;
1217
+ const Scalar* data;
1218
+ IndexType offset;
1219
+ };
1220
+
1221
+ // Copies data to `dst` from `src`, using provided dimensions mapping:
1222
+ //
1223
+ // src_dimension_index = dst_to_src_dim_map[dst_dimension_index]
1224
+ //
1225
+ // Returns the number of copied elements.
1226
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE IndexType Copy(
1227
+ const Dst& dst, const Src& src, const DimensionsMap& dst_to_src_dim_map) {
1228
+ // Copy single scalar value from `src` to `dst`.
1229
+ if (NumDims == 0) {
1230
+ *(dst.data + dst.offset) = *(src.data + src.offset);
1231
+ return 1;
1232
+ }
1233
+
1234
+ // Both `dst` and `src` must have contiguous innermost dimension. We also
1235
+ // accept the special case with stride '0', because it's used as a trick to
1236
+ // implement broadcasting.
1237
+ {
1238
+ int inner_dim = IsColMajor ? 0 : NumDims - 1;
1239
+ EIGEN_UNUSED_VARIABLE(inner_dim);
1240
+ eigen_assert(dst.strides[inner_dim] == 1 || dst.strides[inner_dim] == 0);
1241
+ eigen_assert(src.strides[inner_dim] == 1 || src.strides[inner_dim] == 0);
1242
+ }
1243
+
1244
+ // Give a shorter name to `dst_to_src_dim_map`.
1245
+ const DimensionsMap& dim_map = dst_to_src_dim_map;
1246
+
1247
+ // Do not squeeze reordered inner dimensions.
1248
+ int num_squeezable_dims = NumSqueezableInnerDims(dim_map);
1249
+
1250
+ // NOTE: We find the innermost dimension (contiguous in memory) in the dst
1251
+ // block, and we write data linearly into that dimension, reading it from
1252
+ // the src. If dimensions are reordered, we might end up reading data from
1253
+ // the src with `stride != 1`.
1254
+ //
1255
+ // NOTE: Random-Read/Linear-Write can be up to ~2X faster than
1256
+ // Linear-Read/Random-Write: https://stackoverflow.com/a/54935680
1257
+
1258
+ // Find the innermost dimension in the dst whose size is not 1. This is the
1259
+ // effective inner dim.
1260
+ int num_size_one_inner_dims = 0;
1261
+ for (int i = 0; i < num_squeezable_dims; ++i) {
1262
+ const int dst_dim = IsColMajor ? i : NumDims - i - 1;
1263
+ if (dst.dims[dst_dim] != 1) break;
1264
+ num_size_one_inner_dims++;
1265
+ }
1266
+
1267
+ // If all dimensions are of size 1, just copy a scalar from `src` to `dst`.
1268
+ if (num_size_one_inner_dims == NumDims) {
1269
+ *(dst.data + dst.offset) = *(src.data + src.offset);
1270
+ return 1;
1271
+ }
1272
+
1273
+ // Outermost dimension in the dst with `stride == 1` (contiguous in memory).
1274
+ const int dst_stride1_dim = IsColMajor
1275
+ ? num_size_one_inner_dims
1276
+ : NumDims - num_size_one_inner_dims - 1;
1277
+
1278
+ // Dimension in the src that corresponds to the dst innermost dimension.
1279
+ const int src_dim_for_dst_stride1_dim =
1280
+ NumDims == 0 ? 1 : dim_map[dst_stride1_dim];
1281
+
1282
+ // Size of the innermost dimension (length of contiguous blocks of memory).
1283
+ IndexType dst_inner_dim_size = NumDims == 0 ? 1 : dst.dims[dst_stride1_dim];
1284
+
1285
+ // Squeeze multiple inner dims into one if they are contiguous in `dst` and
1286
+ // `src` memory, so we can do less linear copy calls.
1287
+ for (int i = num_size_one_inner_dims + 1; i < num_squeezable_dims; ++i) {
1288
+ const int dst_dim = IsColMajor ? i : NumDims - i - 1;
1289
+ const IndexType dst_stride = dst.strides[dst_dim];
1290
+ const IndexType src_stride = src.strides[dim_map[dst_dim]];
1291
+ if (dst_inner_dim_size == dst_stride && dst_stride == src_stride) {
1292
+ dst_inner_dim_size *= dst.dims[dst_dim];
1293
+ ++num_size_one_inner_dims;
1294
+ } else {
1295
+ break;
1296
+ }
1297
+ }
1298
+
1299
+ // Setup strides to read data from `src` and write to `dst`.
1300
+ IndexType input_offset = src.offset;
1301
+ IndexType output_offset = dst.offset;
1302
+ IndexType input_stride =
1303
+ NumDims == 0 ? 1 : src.strides[src_dim_for_dst_stride1_dim];
1304
+ IndexType output_stride = NumDims == 0 ? 1 : dst.strides[dst_stride1_dim];
1305
+
1306
+ const int at_least_1_dim = NumDims <= 1 ? 1 : NumDims - 1;
1307
+ array<BlockIteratorState, at_least_1_dim> it;
1308
+
1309
+ // Initialize block iterator state. Squeeze away any dimension of size 1.
1310
+ int idx = 0; // currently initialized iterator state index
1311
+ for (int i = num_size_one_inner_dims; i < NumDims - 1; ++i) {
1312
+ const int dst_dim = IsColMajor ? i + 1 : NumDims - i - 2;
1313
+ if (dst.dims[dst_dim] == 1) continue;
1314
+
1315
+ it[idx].size = dst.dims[dst_dim];
1316
+ it[idx].input_stride = src.strides[dim_map[dst_dim]];
1317
+ it[idx].output_stride = dst.strides[dst_dim];
1318
+
1319
+ it[idx].input_span = it[idx].input_stride * (it[idx].size - 1);
1320
+ it[idx].output_span = it[idx].output_stride * (it[idx].size - 1);
1321
+
1322
+ idx++;
1323
+ }
1324
+
1325
+ // Iterate copying data from src to dst.
1326
+ const IndexType block_total_size = NumDims == 0 ? 1 : dst.dims.TotalSize();
1327
+
1328
+ #define COPY_INNER_DIM(KIND) \
1329
+ IndexType num_copied = 0; \
1330
+ for (num_copied = 0; num_copied < block_total_size; \
1331
+ num_copied += dst_inner_dim_size) { \
1332
+ LinCopy::template Run<KIND>( \
1333
+ typename LinCopy::Dst(output_offset, output_stride, dst.data), \
1334
+ typename LinCopy::Src(input_offset, input_stride, src.data), \
1335
+ dst_inner_dim_size); \
1336
+ \
1337
+ for (int j = 0; j < idx; ++j) { \
1338
+ if (++it[j].count < it[j].size) { \
1339
+ input_offset += it[j].input_stride; \
1340
+ output_offset += it[j].output_stride; \
1341
+ break; \
1342
+ } \
1343
+ it[j].count = 0; \
1344
+ input_offset -= it[j].input_span; \
1345
+ output_offset -= it[j].output_span; \
1346
+ } \
1347
+ } \
1348
+ return num_copied;
1349
+
1350
+ if (input_stride == 1 && output_stride == 1) {
1351
+ COPY_INNER_DIM(LinCopy::Kind::Linear);
1352
+ } else if (input_stride == 1 && output_stride != 1) {
1353
+ COPY_INNER_DIM(LinCopy::Kind::Scatter);
1354
+ } else if (input_stride == 0 && output_stride == 1) {
1355
+ COPY_INNER_DIM(LinCopy::Kind::FillLinear);
1356
+ } else if (input_stride == 0 && output_stride != 1) {
1357
+ COPY_INNER_DIM(LinCopy::Kind::FillScatter);
1358
+ } else if (output_stride == 1) {
1359
+ COPY_INNER_DIM(LinCopy::Kind::Gather);
1360
+ } else {
1361
+ COPY_INNER_DIM(LinCopy::Kind::Random);
1362
+ }
1363
+
1364
+ #undef COPY_INNER_DIM
1365
+ }
1366
+
1367
+ // Copy from `src` to `dst` with an identity src->dst dimension map. Returns
1368
+ // the number of copied elements.
1369
+ static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE IndexType Copy(const Dst& dst,
1370
+ const Src& src) {
1371
+ DimensionsMap dst_to_src_map;
1372
+ for (int i = 0; i < NumDims; ++i) dst_to_src_map[i] = i;
1373
+ return Copy(dst, src, dst_to_src_map);
1374
+ }
1375
+
1376
+ private:
1377
+ struct BlockIteratorState {
1378
+ BlockIteratorState()
1379
+ : size(0),
1380
+ count(0),
1381
+ input_stride(0),
1382
+ output_stride(0),
1383
+ input_span(0),
1384
+ output_span(0) {}
1385
+
1386
+ IndexType size;
1387
+ IndexType count;
1388
+ IndexType input_stride;
1389
+ IndexType output_stride;
1390
+ IndexType input_span;
1391
+ IndexType output_span;
1392
+ };
1393
+
1394
+ // Compute how many inner dimensions it's allowed to squeeze when doing IO
1395
+ // between two tensor blocks. It's safe to squeeze inner dimensions, only
1396
+ // if they are not reordered.
1397
+ static int NumSqueezableInnerDims(const DimensionsMap& dim_map) {
1398
+ int num_squeezable_dims = 0;
1399
+ for (int i = 0; i < NumDims; ++i) {
1400
+ const int dim = IsColMajor ? i : NumDims - i - 1;
1401
+ if (dim_map[dim] != dim) break;
1402
+ num_squeezable_dims++;
1403
+ }
1404
+ return num_squeezable_dims;
1405
+ }
1406
+ };
1407
+
1408
+ // -------------------------------------------------------------------------- //
1409
+ // TensorBlockAssignment assigns a block expression of type `TensorBlockExpr` to
1410
+ // a Tensor block defined by `desc`, backed by a memory buffer at `target`.
1411
+ //
1412
+ // Currently there is no way to write from a Tensor expression to a block of
1413
+ // memory, if dimensions are reordered. If you need to do that, you should
1414
+ // materialize a Tensor block expression into a memory buffer, and then use
1415
+ // TensorBlockIO to copy data between two memory buffers with a custom
1416
+ // `target->src` dimension map (see definition above).
1417
+ //
1418
+ // Also currently the innermost dimension of `target` must have a stride '1'
1419
+ // (contiguous in memory). This restriction could be lifted with a `pscatter`,
1420
+ // but in practice it's never needed, and there is a similar TensorBlockIO
1421
+ // workaround for that.
1422
+ //
1423
+ // TODO(ezhulenev): TensorBlockAssignment is a special case of TensorBlockIO
1424
+ // where `src` is a tensor expression. Explore if it is possible to rewrite IO
1425
+ // to use expressions instead of pointers, and after that TensorBlockAssignment
1426
+ // will become an alias to IO.
1427
+ template <typename Scalar, int NumDims, typename TensorBlockExpr,
1428
+ typename IndexType = Eigen::Index>
1429
+ class TensorBlockAssignment {
1430
+ // We will use coeff/packet path to evaluate block expressions.
1431
+ typedef TensorEvaluator<const TensorBlockExpr, DefaultDevice>
1432
+ TensorBlockEvaluator;
1433
+
1434
+ typedef DSizes<IndexType, NumDims> Dimensions;
1435
+
1436
+ enum {
1437
+ Vectorizable = packet_traits<Scalar>::Vectorizable,
1438
+ PacketSize = packet_traits<Scalar>::size
1439
+ };
1440
+
1441
+ template <bool Vectorizable, typename Evaluator>
1442
+ struct InnerDimAssign {
1443
+ EIGEN_ALWAYS_INLINE static void Run(Scalar* target, IndexType count,
1444
+ const Evaluator& eval,
1445
+ IndexType eval_offset) {
1446
+ for (IndexType i = 0; i < count; ++i) {
1447
+ target[i] = eval.coeff(eval_offset + i);
1448
+ }
1449
+ }
1450
+ };
1451
+
1452
+ template <typename Evaluator>
1453
+ struct InnerDimAssign<true, Evaluator> {
1454
+ EIGEN_ALWAYS_INLINE static void Run(Scalar* target, IndexType count,
1455
+ const Evaluator& eval,
1456
+ IndexType eval_offset) {
1457
+ typedef typename packet_traits<Scalar>::type Packet;
1458
+
1459
+ const IndexType unrolled_size = count - 4 * PacketSize;
1460
+ const IndexType vectorized_size = count - PacketSize;
1461
+ IndexType i = 0;
1462
+
1463
+ for (; i <= unrolled_size; i += 4 * PacketSize) {
1464
+ for (int j = 0; j < 4; ++j) {
1465
+ const IndexType idx = eval_offset + i + j * PacketSize;
1466
+ Packet p = eval.template packet<Unaligned>(idx);
1467
+ pstoreu<Scalar>(target + i + j * PacketSize, p);
1468
+ }
1469
+ }
1470
+
1471
+ for (; i <= vectorized_size; i += PacketSize) {
1472
+ Packet p = eval.template packet<Unaligned>(eval_offset + i);
1473
+ pstoreu<Scalar>(target + i, p);
1474
+ }
1475
+
1476
+ for (; i < count; ++i) {
1477
+ target[i] = eval.coeff(eval_offset + i);
1478
+ }
1479
+ }
1480
+ };
1481
+
1482
+ public:
1483
+ struct Target {
1484
+ Target(const Dimensions& target_dims, const Dimensions& target_strides,
1485
+ Scalar* target_data, IndexType target_offset = 0)
1486
+ : dims(target_dims),
1487
+ strides(target_strides),
1488
+ data(target_data),
1489
+ offset(target_offset) {}
1490
+
1491
+ Dimensions dims;
1492
+ Dimensions strides;
1493
+ Scalar* data;
1494
+ IndexType offset;
1495
+ };
1496
+
1497
+ static Target target(const Dimensions& target_dims,
1498
+ const Dimensions& target_strides, Scalar* target_data,
1499
+ IndexType target_offset = 0) {
1500
+ return Target(target_dims, target_strides, target_data, target_offset);
1501
+ }
1502
+
1503
+ template <typename TargetDimsIndexType, typename TargetStridesIndexType>
1504
+ static Target target(
1505
+ const DSizes<TargetDimsIndexType, NumDims>& target_dims,
1506
+ const DSizes<TargetStridesIndexType, NumDims>& target_strides,
1507
+ Scalar* target_data, IndexType target_offset = 0) {
1508
+ // DSizes constructor will do index type promotion if it's safe.
1509
+ return Target(Dimensions(target_dims), Dimensions(target_strides),
1510
+ target_data, target_offset);
1511
+ }
1512
+
1513
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void Run(
1514
+ const Target& target, const TensorBlockExpr& expr) {
1515
+ // Prepare evaluator for block expression.
1516
+ DefaultDevice default_device;
1517
+ TensorBlockEvaluator eval(expr, default_device);
1518
+
1519
+ // Tensor block expression dimension should match destination dimensions.
1520
+ eigen_assert(dimensions_match(target.dims, eval.dimensions()));
1521
+
1522
+ static const int Layout = TensorBlockEvaluator::Layout;
1523
+ static const bool is_col_major = Layout == ColMajor;
1524
+
1525
+ // Initialize output inner dimension size based on a layout.
1526
+ const IndexType output_size = NumDims == 0 ? 1 : target.dims.TotalSize();
1527
+ const int inner_dim_idx = is_col_major ? 0 : NumDims - 1;
1528
+ IndexType output_inner_dim_size = target.dims[inner_dim_idx];
1529
+
1530
+ // Target inner dimension stride must be '1'.
1531
+ eigen_assert(target.strides[inner_dim_idx] == 1);
1532
+
1533
+ // Squeeze multiple inner dims into one if they are contiguous in `target`.
1534
+ IndexType num_squeezed_dims = 0;
1535
+ for (Index i = 1; i < NumDims; ++i) {
1536
+ const Index dim = is_col_major ? i : NumDims - i - 1;
1537
+ const IndexType target_stride = target.strides[dim];
1538
+
1539
+ if (output_inner_dim_size == target_stride) {
1540
+ output_inner_dim_size *= target.dims[dim];
1541
+ num_squeezed_dims++;
1542
+ } else {
1543
+ break;
1544
+ }
1545
+ }
1546
+
1547
+ // Initialize output block iterator state. Dimension in this array are
1548
+ // always in inner_most -> outer_most order (col major layout).
1549
+ array<BlockIteratorState, NumDims> it;
1550
+
1551
+ int idx = 0; // currently initialized iterator state index
1552
+ for (Index i = num_squeezed_dims; i < NumDims - 1; ++i) {
1553
+ const Index dim = is_col_major ? i + 1 : NumDims - i - 2;
1554
+
1555
+ it[idx].count = 0;
1556
+ it[idx].size = target.dims[dim];
1557
+ it[idx].output_stride = target.strides[dim];
1558
+ it[idx].output_span = it[idx].output_stride * (it[idx].size - 1);
1559
+ idx++;
1560
+ }
1561
+
1562
+ // We read block expression from the beginning, and start writing data to
1563
+ // `target` at given offset.
1564
+ IndexType input_offset = 0;
1565
+ IndexType output_offset = target.offset;
1566
+
1567
+ // Iterate copying data from `eval` to `target`.
1568
+ for (IndexType i = 0; i < output_size; i += output_inner_dim_size) {
1569
+ // Assign to `target` at current offset.
1570
+ InnerDimAssign<Vectorizable && TensorBlockEvaluator::PacketAccess,
1571
+ TensorBlockEvaluator>::Run(target.data + output_offset,
1572
+ output_inner_dim_size, eval,
1573
+ input_offset);
1574
+
1575
+ // Move input offset forward by the number of assigned coefficients.
1576
+ input_offset += output_inner_dim_size;
1577
+
1578
+ // Update index.
1579
+ for (int j = 0; j < idx; ++j) {
1580
+ if (++it[j].count < it[j].size) {
1581
+ output_offset += it[j].output_stride;
1582
+ break;
1583
+ }
1584
+ it[j].count = 0;
1585
+ output_offset -= it[j].output_span;
1586
+ }
1587
+ }
1588
+ }
1589
+
1590
+ private:
1591
+ struct BlockIteratorState {
1592
+ BlockIteratorState()
1593
+ : count(0), size(0), output_stride(0), output_span(0) {}
1594
+
1595
+ IndexType count;
1596
+ IndexType size;
1597
+ IndexType output_stride;
1598
+ IndexType output_span;
1599
+ };
1600
+ };
1601
+
1602
+ // -------------------------------------------------------------------------- //
1603
+
1604
+ } // namespace internal
1605
+ } // namespace Eigen
1606
+
1607
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_BLOCK_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBroadcasting.h ADDED
@@ -0,0 +1,1080 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_BROADCASTING_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_BROADCASTING_H
12
+
13
+ #include "./InternalHeaderCheck.h"
14
+
15
+ namespace Eigen {
16
+
17
+ /** \class TensorBroadcasting
18
+ * \ingroup CXX11_Tensor_Module
19
+ *
20
+ * \brief Tensor broadcasting class.
21
+ *
22
+ *
23
+ */
24
+ namespace internal {
25
+ template<typename Broadcast, typename XprType>
26
+ struct traits<TensorBroadcastingOp<Broadcast, XprType> > : public traits<XprType>
27
+ {
28
+ typedef typename XprType::Scalar Scalar;
29
+ typedef traits<XprType> XprTraits;
30
+ typedef typename XprTraits::StorageKind StorageKind;
31
+ typedef typename XprTraits::Index Index;
32
+ typedef typename XprType::Nested Nested;
33
+ typedef std::remove_reference_t<Nested> Nested_;
34
+ static constexpr int NumDimensions = XprTraits::NumDimensions;
35
+ static constexpr int Layout = XprTraits::Layout;
36
+ typedef typename XprTraits::PointerType PointerType;
37
+ };
38
+
39
+ template<typename Broadcast, typename XprType>
40
+ struct eval<TensorBroadcastingOp<Broadcast, XprType>, Eigen::Dense>
41
+ {
42
+ typedef const TensorBroadcastingOp<Broadcast, XprType> EIGEN_DEVICE_REF type;
43
+ };
44
+
45
+ template<typename Broadcast, typename XprType>
46
+ struct nested<TensorBroadcastingOp<Broadcast, XprType>, 1, typename eval<TensorBroadcastingOp<Broadcast, XprType> >::type>
47
+ {
48
+ typedef TensorBroadcastingOp<Broadcast, XprType> type;
49
+ };
50
+
51
+ template <typename Dims>
52
+ struct is_input_scalar {
53
+ static const bool value = false;
54
+ };
55
+ template <>
56
+ struct is_input_scalar<Sizes<> > {
57
+ static const bool value = true;
58
+ };
59
+ #ifndef EIGEN_EMULATE_CXX11_META_H
60
+ template <typename std::ptrdiff_t... Indices>
61
+ struct is_input_scalar<Sizes<Indices...> > {
62
+ static const bool value = (Sizes<Indices...>::total_size == 1);
63
+ };
64
+ #endif
65
+
66
+ } // end namespace internal
67
+
68
+
69
+
70
+ template<typename Broadcast, typename XprType>
71
+ class TensorBroadcastingOp : public TensorBase<TensorBroadcastingOp<Broadcast, XprType>, ReadOnlyAccessors>
72
+ {
73
+ public:
74
+ typedef typename Eigen::internal::traits<TensorBroadcastingOp>::Scalar Scalar;
75
+ typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
76
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
77
+ typedef typename Eigen::internal::nested<TensorBroadcastingOp>::type Nested;
78
+ typedef typename Eigen::internal::traits<TensorBroadcastingOp>::StorageKind StorageKind;
79
+ typedef typename Eigen::internal::traits<TensorBroadcastingOp>::Index Index;
80
+
81
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBroadcastingOp(const XprType& expr, const Broadcast& broadcast)
82
+ : m_xpr(expr), m_broadcast(broadcast) {}
83
+
84
+ EIGEN_DEVICE_FUNC
85
+ const Broadcast& broadcast() const { return m_broadcast; }
86
+
87
+ EIGEN_DEVICE_FUNC
88
+ const internal::remove_all_t<typename XprType::Nested>&
89
+ expression() const { return m_xpr; }
90
+
91
+ protected:
92
+ typename XprType::Nested m_xpr;
93
+ const Broadcast m_broadcast;
94
+ };
95
+
96
+
97
+ // Eval as rvalue
98
+ template<typename Broadcast, typename ArgType, typename Device>
99
+ struct TensorEvaluator<const TensorBroadcastingOp<Broadcast, ArgType>, Device>
100
+ {
101
+ typedef TensorBroadcastingOp<Broadcast, ArgType> XprType;
102
+ typedef typename XprType::Index Index;
103
+ static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
104
+ typedef DSizes<Index, NumDims> Dimensions;
105
+ typedef typename XprType::Scalar Scalar;
106
+ typedef typename TensorEvaluator<ArgType, Device>::Dimensions InputDimensions;
107
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
108
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
109
+ static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
110
+ protected: // all the non-static fields must have the same access control, otherwise the TensorEvaluator won't be standard layout;
111
+ bool isCopy, nByOne, oneByN;
112
+ public:
113
+ typedef StorageMemory<CoeffReturnType, Device> Storage;
114
+ typedef typename Storage::Type EvaluatorPointerType;
115
+
116
+ enum {
117
+ IsAligned = TensorEvaluator<ArgType, Device>::IsAligned,
118
+ PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
119
+ BlockAccess = TensorEvaluator<ArgType, Device>::BlockAccess,
120
+ PreferBlockAccess = true,
121
+ RawAccess = false
122
+ };
123
+ static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
124
+
125
+ typedef std::remove_const_t<Scalar> ScalarNoConst;
126
+
127
+ // We do block based broadcasting using a trick with 2x tensor rank and 0
128
+ // strides. See block method implementation for details.
129
+ typedef DSizes<Index, 2 * NumDims> BroadcastDimensions;
130
+
131
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
132
+ typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
133
+ typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
134
+
135
+ typedef typename TensorEvaluator<const ArgType, Device>::TensorBlock
136
+ ArgTensorBlock;
137
+
138
+ typedef typename internal::TensorMaterializedBlock<ScalarNoConst, NumDims,
139
+ Layout, Index>
140
+ TensorBlock;
141
+ //===--------------------------------------------------------------------===//
142
+
143
+ EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
144
+ : isCopy(false), nByOne(false), oneByN(false),
145
+ m_device(device), m_broadcast(op.broadcast()), m_impl(op.expression(), device)
146
+ {
147
+
148
+ // The broadcasting op doesn't change the rank of the tensor. One can't broadcast a scalar
149
+ // and store the result in a scalar. Instead one should reshape the scalar into a N-D
150
+ // tensor with N >= 1 of 1 element first and then broadcast.
151
+ EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
152
+ const InputDimensions& input_dims = m_impl.dimensions();
153
+ isCopy = true;
154
+ for (int i = 0; i < NumDims; ++i) {
155
+ eigen_assert(input_dims[i] > 0);
156
+ m_dimensions[i] = input_dims[i] * m_broadcast[i];
157
+ if (m_broadcast[i] != 1) {
158
+ isCopy = false;
159
+ }
160
+ }
161
+
162
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
163
+ m_inputStrides[0] = 1;
164
+ m_outputStrides[0] = 1;
165
+ for (int i = 1; i < NumDims; ++i) {
166
+ m_inputStrides[i] = m_inputStrides[i-1] * input_dims[i-1];
167
+ m_outputStrides[i] = m_outputStrides[i-1] * m_dimensions[i-1];
168
+ }
169
+ } else {
170
+ m_inputStrides[NumDims-1] = 1;
171
+ m_outputStrides[NumDims-1] = 1;
172
+ for (int i = NumDims-2; i >= 0; --i) {
173
+ m_inputStrides[i] = m_inputStrides[i+1] * input_dims[i+1];
174
+ m_outputStrides[i] = m_outputStrides[i+1] * m_dimensions[i+1];
175
+ }
176
+ }
177
+
178
+ if (input_dims[0] == 1) {
179
+ oneByN = true;
180
+ for (int i = 1; i < NumDims; ++i) {
181
+ if (m_broadcast[i] != 1) {
182
+ oneByN = false;
183
+ break;
184
+ }
185
+ }
186
+ } else if (input_dims[NumDims-1] == 1) {
187
+ nByOne = true;
188
+ for (int i = 0; i < NumDims-1; ++i) {
189
+ if (m_broadcast[i] != 1) {
190
+ nByOne = false;
191
+ break;
192
+ }
193
+ }
194
+ }
195
+
196
+ // Handle special format like NCHW, its input shape is '[1, N..., 1]' and
197
+ // broadcast shape is '[N, 1..., N]'
198
+ if (!oneByN && !nByOne) {
199
+ if (input_dims[0] == 1 && input_dims[NumDims-1] == 1 && NumDims > 2) {
200
+ nByOne = true;
201
+ oneByN = true;
202
+ for (int i = 1; i < NumDims-1; ++i) {
203
+ if (m_broadcast[i] != 1) {
204
+ nByOne = false;
205
+ oneByN = false;
206
+ break;
207
+ }
208
+ }
209
+ }
210
+ }
211
+ }
212
+
213
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
214
+
215
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
216
+ m_impl.evalSubExprsIfNeeded(NULL);
217
+ return true;
218
+ }
219
+
220
+ #ifdef EIGEN_USE_THREADS
221
+ template <typename EvalSubExprsCallback>
222
+ EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(
223
+ EvaluatorPointerType, EvalSubExprsCallback done) {
224
+ m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); });
225
+ }
226
+ #endif // EIGEN_USE_THREADS
227
+
228
+ EIGEN_STRONG_INLINE void cleanup() {
229
+ m_impl.cleanup();
230
+ }
231
+
232
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE CoeffReturnType coeff(Index index) const
233
+ {
234
+ if (internal::is_input_scalar<internal::remove_all_t<InputDimensions>>::value) {
235
+ return m_impl.coeff(0);
236
+ }
237
+
238
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
239
+ if (isCopy) {
240
+ return m_impl.coeff(index);
241
+ } else {
242
+ return coeffColMajor(index);
243
+ }
244
+ } else {
245
+ if (isCopy) {
246
+ return m_impl.coeff(index);
247
+ } else {
248
+ return coeffRowMajor(index);
249
+ }
250
+ }
251
+ }
252
+
253
+ // TODO: attempt to speed this up. The integer divisions and modulo are slow
254
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index indexColMajor(Index index) const {
255
+ Index inputIndex = 0;
256
+ EIGEN_UNROLL_LOOP
257
+ for (int i = NumDims - 1; i > 0; --i) {
258
+ const Index idx = index / m_outputStrides[i];
259
+ if (internal::index_statically_eq<Broadcast>(i, 1)) {
260
+ eigen_assert(idx < m_impl.dimensions()[i]);
261
+ inputIndex += idx * m_inputStrides[i];
262
+ } else {
263
+ if (internal::index_statically_eq<InputDimensions>(i, 1)) {
264
+ eigen_assert(idx % m_impl.dimensions()[i] == 0);
265
+ } else {
266
+ inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i];
267
+ }
268
+ }
269
+ index -= idx * m_outputStrides[i];
270
+ }
271
+ if (internal::index_statically_eq<Broadcast>(0, 1)) {
272
+ eigen_assert(index < m_impl.dimensions()[0]);
273
+ inputIndex += index;
274
+ } else {
275
+ if (internal::index_statically_eq<InputDimensions>(0, 1)) {
276
+ eigen_assert(index % m_impl.dimensions()[0] == 0);
277
+ } else {
278
+ inputIndex += (index % m_impl.dimensions()[0]);
279
+ }
280
+ }
281
+ return inputIndex;
282
+ }
283
+
284
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeffColMajor(Index index) const
285
+ {
286
+ return m_impl.coeff(indexColMajor(index));
287
+ }
288
+
289
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index indexRowMajor(Index index) const {
290
+ Index inputIndex = 0;
291
+ EIGEN_UNROLL_LOOP
292
+ for (int i = 0; i < NumDims - 1; ++i) {
293
+ const Index idx = index / m_outputStrides[i];
294
+ if (internal::index_statically_eq<Broadcast>(i, 1)) {
295
+ eigen_assert(idx < m_impl.dimensions()[i]);
296
+ inputIndex += idx * m_inputStrides[i];
297
+ } else {
298
+ if (internal::index_statically_eq<InputDimensions>(i, 1)) {
299
+ eigen_assert(idx % m_impl.dimensions()[i] == 0);
300
+ } else {
301
+ inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i];
302
+ }
303
+ }
304
+ index -= idx * m_outputStrides[i];
305
+ }
306
+ if (internal::index_statically_eq<Broadcast>(NumDims - 1, 1)) {
307
+ eigen_assert(index < m_impl.dimensions()[NumDims - 1]);
308
+ inputIndex += index;
309
+ } else {
310
+ if (internal::index_statically_eq<InputDimensions>(NumDims - 1, 1)) {
311
+ eigen_assert(index % m_impl.dimensions()[NumDims - 1] == 0);
312
+ } else {
313
+ inputIndex += (index % m_impl.dimensions()[NumDims - 1]);
314
+ }
315
+ }
316
+ return inputIndex;
317
+ }
318
+
319
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeffRowMajor(Index index) const
320
+ {
321
+ return m_impl.coeff(indexRowMajor(index));
322
+ }
323
+
324
+ template<int LoadMode>
325
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketReturnType packet(Index index) const
326
+ {
327
+ if (internal::is_input_scalar<internal::remove_all_t<InputDimensions>>::value) {
328
+ return internal::pset1<PacketReturnType>(m_impl.coeff(0));
329
+ }
330
+
331
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
332
+ if (isCopy) {
333
+ #ifdef EIGEN_GPU_COMPILE_PHASE
334
+ // See PR 437: on NVIDIA P100 and K20m we observed a x3-4 speed up by enforcing
335
+ // unaligned loads here. The reason is unclear though.
336
+ return m_impl.template packet<Unaligned>(index);
337
+ #else
338
+ return m_impl.template packet<LoadMode>(index);
339
+ #endif
340
+ } else if (oneByN && !nByOne) {
341
+ return packetNByOne<LoadMode>(index);
342
+ } else if (!oneByN && nByOne) {
343
+ return packetOneByN<LoadMode>(index);
344
+ } else if (oneByN && nByOne) {
345
+ return packetOneByNByOne<LoadMode>(index);
346
+ } else {
347
+ return packetColMajor<LoadMode>(index);
348
+ }
349
+ } else {
350
+ if (isCopy) {
351
+ #ifdef EIGEN_GPU_COMPILE_PHASE
352
+ // See above.
353
+ return m_impl.template packet<Unaligned>(index);
354
+ #else
355
+ return m_impl.template packet<LoadMode>(index);
356
+ #endif
357
+ } else if (oneByN && !nByOne) {
358
+ return packetOneByN<LoadMode>(index);
359
+ } else if (!oneByN && nByOne) {
360
+ return packetNByOne<LoadMode>(index);
361
+ } else if (oneByN && nByOne) {
362
+ return packetOneByNByOne<LoadMode>(index);
363
+ } else {
364
+ return packetRowMajor<LoadMode>(index);
365
+ }
366
+ }
367
+ }
368
+
369
+ template<int LoadMode>
370
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetOneByNByOne
371
+ (Index index) const
372
+ {
373
+ eigen_assert(index+PacketSize-1 < dimensions().TotalSize());
374
+
375
+ EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
376
+ Index startDim, endDim;
377
+ Index inputIndex, outputOffset, batchedIndex;
378
+
379
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
380
+ startDim = NumDims - 1;
381
+ endDim = 1;
382
+ } else {
383
+ startDim = 0;
384
+ endDim = NumDims - 2;
385
+ }
386
+
387
+ batchedIndex = index % m_outputStrides[startDim];
388
+ inputIndex = batchedIndex / m_outputStrides[endDim];
389
+ outputOffset = batchedIndex % m_outputStrides[endDim];
390
+
391
+ if (outputOffset + PacketSize <= m_outputStrides[endDim]) {
392
+ values[0] = m_impl.coeff(inputIndex);
393
+ return internal::pload1<PacketReturnType>(values);
394
+ } else {
395
+ EIGEN_UNROLL_LOOP
396
+ for (int i = 0, cur = 0; i < PacketSize; ++i, ++cur) {
397
+ if (outputOffset + cur < m_outputStrides[endDim]) {
398
+ values[i] = m_impl.coeff(inputIndex);
399
+ } else {
400
+ ++inputIndex;
401
+ inputIndex = (inputIndex == m_inputStrides[startDim] ? 0 : inputIndex);
402
+ values[i] = m_impl.coeff(inputIndex);
403
+ outputOffset = 0;
404
+ cur = 0;
405
+ }
406
+ }
407
+ return internal::pload<PacketReturnType>(values);
408
+ }
409
+ }
410
+
411
+ template<int LoadMode>
412
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetOneByN(Index index) const
413
+ {
414
+ // Consider the flattened tensor [v0, ..., vN],
415
+ // Concatenates m_broadcast[dim] copies,
416
+ // [v0, ..., vN, v0, ..., vN, ... ]
417
+ // with dim == NumDims - 1 for col-major, dim == 0 for row-major.
418
+ eigen_assert(index+PacketSize-1 < dimensions().TotalSize());
419
+
420
+ // Size of flattened tensor.
421
+ const Index M = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ?
422
+ m_inputStrides[NumDims - 1] : m_inputStrides[0];
423
+ Index inputIndex = index % M;
424
+ if (inputIndex + PacketSize <= M) {
425
+ return m_impl.template packet<Unaligned>(inputIndex);
426
+ } else {
427
+ EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
428
+ EIGEN_UNROLL_LOOP
429
+ for (int i = 0; i < PacketSize; ++i) {
430
+ if (inputIndex > M - 1) {
431
+ inputIndex = 0;
432
+ }
433
+ values[i] = m_impl.coeff(inputIndex++);
434
+ }
435
+ return internal::pload<PacketReturnType>(values);
436
+ }
437
+ }
438
+
439
+ template<int LoadMode>
440
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetNByOne(Index index) const
441
+ {
442
+ // Consider the flattened tensor [v0, ..., vN],
443
+ // Interleaves m_broadcast[dim] copies,
444
+ // [v0, v0, ..., v1, v1, ..., vN, vN, ... ]
445
+ // with dim == 0 for col-major, dim == NumDims - 1 for row-major.
446
+ eigen_assert(index + PacketSize-1 < dimensions().TotalSize());
447
+
448
+ const Index M = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ?
449
+ m_broadcast[0] : m_broadcast[NumDims - 1];
450
+
451
+ Index inputIndex = index / M;
452
+ Index outputOffset = index % M;
453
+ if (outputOffset + PacketSize <= M) {
454
+ return internal::pset1<PacketReturnType>(m_impl.coeff(inputIndex));
455
+ } else {
456
+ EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
457
+ EIGEN_UNROLL_LOOP
458
+ for (int i = 0; i < PacketSize; ++i) {
459
+ if (outputOffset < M) {
460
+ values[i] = m_impl.coeff(inputIndex);
461
+ ++outputOffset;
462
+ } else {
463
+ values[i] = m_impl.coeff(++inputIndex);
464
+ outputOffset = 1; // Next offset.
465
+ }
466
+ }
467
+ return internal::pload<PacketReturnType>(values);
468
+ }
469
+ }
470
+
471
+ // Ignore the LoadMode and always use unaligned loads since we can't guarantee
472
+ // the alignment at compile time.
473
+ template<int LoadMode>
474
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetColMajor(Index index) const
475
+ {
476
+ eigen_assert(index+PacketSize-1 < dimensions().TotalSize());
477
+
478
+ const Index originalIndex = index;
479
+
480
+ Index inputIndex = 0;
481
+ EIGEN_UNROLL_LOOP
482
+ for (int i = NumDims - 1; i > 0; --i) {
483
+ const Index idx = index / m_outputStrides[i];
484
+ if (internal::index_statically_eq<Broadcast>(i, 1)) {
485
+ eigen_assert(idx < m_impl.dimensions()[i]);
486
+ inputIndex += idx * m_inputStrides[i];
487
+ } else {
488
+ if (internal::index_statically_eq<InputDimensions>(i, 1)) {
489
+ eigen_assert(idx % m_impl.dimensions()[i] == 0);
490
+ } else {
491
+ inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i];
492
+ }
493
+ }
494
+ index -= idx * m_outputStrides[i];
495
+ }
496
+ Index innermostLoc;
497
+ if (internal::index_statically_eq<Broadcast>(0, 1)) {
498
+ eigen_assert(index < m_impl.dimensions()[0]);
499
+ innermostLoc = index;
500
+ } else {
501
+ if (internal::index_statically_eq<InputDimensions>(0, 1)) {
502
+ eigen_assert(index % m_impl.dimensions()[0] == 0);
503
+ innermostLoc = 0;
504
+ } else {
505
+ innermostLoc = index % m_impl.dimensions()[0];
506
+ }
507
+ }
508
+ inputIndex += innermostLoc;
509
+
510
+ // Todo: this could be extended to the second dimension if we're not
511
+ // broadcasting alongside the first dimension, and so on.
512
+ if (innermostLoc + PacketSize <= m_impl.dimensions()[0]) {
513
+ return m_impl.template packet<Unaligned>(inputIndex);
514
+ } else {
515
+ EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
516
+ values[0] = m_impl.coeff(inputIndex);
517
+ EIGEN_UNROLL_LOOP
518
+ for (int i = 1; i < PacketSize; ++i) {
519
+ if (innermostLoc + i < m_impl.dimensions()[0]) {
520
+ values[i] = m_impl.coeff(inputIndex+i);
521
+ } else {
522
+ values[i] = coeffColMajor(originalIndex+i);
523
+ }
524
+ }
525
+ PacketReturnType rslt = internal::pload<PacketReturnType>(values);
526
+ return rslt;
527
+ }
528
+ }
529
+
530
+ template<int LoadMode>
531
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetRowMajor(Index index) const
532
+ {
533
+ eigen_assert(index+PacketSize-1 < dimensions().TotalSize());
534
+
535
+ const Index originalIndex = index;
536
+
537
+ Index inputIndex = 0;
538
+ EIGEN_UNROLL_LOOP
539
+ for (int i = 0; i < NumDims - 1; ++i) {
540
+ const Index idx = index / m_outputStrides[i];
541
+ if (internal::index_statically_eq<Broadcast>(i, 1)) {
542
+ eigen_assert(idx < m_impl.dimensions()[i]);
543
+ inputIndex += idx * m_inputStrides[i];
544
+ } else {
545
+ if (internal::index_statically_eq<InputDimensions>(i, 1)) {
546
+ eigen_assert(idx % m_impl.dimensions()[i] == 0);
547
+ } else {
548
+ inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i];
549
+ }
550
+ }
551
+ index -= idx * m_outputStrides[i];
552
+ }
553
+ Index innermostLoc;
554
+ if (internal::index_statically_eq<Broadcast>(NumDims-1, 1)) {
555
+ eigen_assert(index < m_impl.dimensions()[NumDims-1]);
556
+ innermostLoc = index;
557
+ } else {
558
+ if (internal::index_statically_eq<InputDimensions>(NumDims-1, 1)) {
559
+ eigen_assert(index % m_impl.dimensions()[NumDims-1] == 0);
560
+ innermostLoc = 0;
561
+ } else {
562
+ innermostLoc = index % m_impl.dimensions()[NumDims-1];
563
+ }
564
+ }
565
+ inputIndex += innermostLoc;
566
+
567
+ // Todo: this could be extended to the second dimension if we're not
568
+ // broadcasting alongside the first dimension, and so on.
569
+ if (innermostLoc + PacketSize <= m_impl.dimensions()[NumDims-1]) {
570
+ return m_impl.template packet<Unaligned>(inputIndex);
571
+ } else {
572
+ EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
573
+ values[0] = m_impl.coeff(inputIndex);
574
+ EIGEN_UNROLL_LOOP
575
+ for (int i = 1; i < PacketSize; ++i) {
576
+ if (innermostLoc + i < m_impl.dimensions()[NumDims-1]) {
577
+ values[i] = m_impl.coeff(inputIndex+i);
578
+ } else {
579
+ values[i] = coeffRowMajor(originalIndex+i);
580
+ }
581
+ }
582
+ PacketReturnType rslt = internal::pload<PacketReturnType>(values);
583
+ return rslt;
584
+ }
585
+ }
586
+
587
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
588
+ costPerCoeff(bool vectorized) const {
589
+ double compute_cost = TensorOpCost::AddCost<Index>();
590
+ if (!isCopy && NumDims > 0) {
591
+ EIGEN_UNROLL_LOOP
592
+ for (int i = NumDims - 1; i > 0; --i) {
593
+ compute_cost += TensorOpCost::DivCost<Index>();
594
+ if (internal::index_statically_eq<Broadcast>(i, 1)) {
595
+ compute_cost +=
596
+ TensorOpCost::MulCost<Index>() + TensorOpCost::AddCost<Index>();
597
+ } else {
598
+ if (!internal::index_statically_eq<InputDimensions>(i, 1)) {
599
+ compute_cost += TensorOpCost::MulCost<Index>() +
600
+ TensorOpCost::ModCost<Index>() +
601
+ TensorOpCost::AddCost<Index>();
602
+ }
603
+ }
604
+ compute_cost +=
605
+ TensorOpCost::MulCost<Index>() + TensorOpCost::AddCost<Index>();
606
+ }
607
+ }
608
+ return m_impl.costPerCoeff(vectorized) +
609
+ TensorOpCost(0, 0, compute_cost, vectorized, PacketSize);
610
+ }
611
+
612
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
613
+ internal::TensorBlockResourceRequirements getResourceRequirements() const {
614
+ // TODO(wuke): Targeting L1 size is 30% faster than targeting L{-1} on large
615
+ // tensors. But this might need further tuning.
616
+ const size_t target_size = m_device.firstLevelCacheSize();
617
+ return internal::TensorBlockResourceRequirements::merge(
618
+ m_impl.getResourceRequirements(),
619
+ internal::TensorBlockResourceRequirements::skewed<Scalar>(target_size));
620
+ }
621
+
622
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock
623
+ block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
624
+ bool /*root_of_expr_ast*/ = false) const {
625
+ BlockBroadcastingParams params = blockBroadcastingParams(desc);
626
+
627
+ if (params.inner_dim_size == 0 || params.bcast_dim_size == 0) {
628
+ return emptyBlock();
629
+ }
630
+
631
+ // Prepare storage for the materialized broadcasting result.
632
+ const typename TensorBlock::Storage block_storage =
633
+ TensorBlock::prepareStorage(desc, scratch);
634
+ ScalarNoConst* materialized_output = block_storage.data();
635
+
636
+ // We potentially will need to materialize input blocks.
637
+ size_t materialized_input_size = 0;
638
+ ScalarNoConst* materialized_input = NULL;
639
+
640
+ // Initialize block broadcating iterator state for outer dimensions (outer
641
+ // with regard to bcast dimension). Dimension in this array are always in
642
+ // inner_most -> outer_most order (col major layout).
643
+ array<BlockBroadcastingIteratorState, NumDims> it;
644
+ int idx = 0;
645
+
646
+ for (int i = params.inner_dim_count + 1; i < NumDims; ++i) {
647
+ const Index dim = IsColMajor ? i : NumDims - 1 - i;
648
+ it[idx].size = params.output_dims[dim];
649
+ it[idx].count = 0;
650
+ it[idx].output_stride = m_outputStrides[dim];
651
+ it[idx].output_span = it[idx].output_stride * (it[idx].size - 1);
652
+ idx++;
653
+ }
654
+
655
+ // Write output into the beginning of `materialized_output`.
656
+ Index output_offset = 0;
657
+
658
+ // We will fill output block by broadcasting along the bcast dim, and
659
+ // iterating over outer dimension.
660
+ const Index output_size = NumDims == 0 ? 1 : params.output_dims.TotalSize();
661
+
662
+ for (Index num_output_coeffs = 0; num_output_coeffs < output_size;) {
663
+ ScalarNoConst* bcast_output = materialized_output + num_output_coeffs;
664
+ Index bcast_offset = desc.offset() + output_offset;
665
+
666
+ // Broadcast along the bcast dimension.
667
+ num_output_coeffs += BroadcastBlockAlongBcastDim(
668
+ params, bcast_offset, scratch, bcast_output, &materialized_input,
669
+ &materialized_input_size);
670
+
671
+ // Switch to the next outer dimension.
672
+ for (int j = 0; j < idx; ++j) {
673
+ if (++it[j].count < it[j].size) {
674
+ output_offset += it[j].output_stride;
675
+ break;
676
+ }
677
+ it[j].count = 0;
678
+ output_offset -= it[j].output_span;
679
+ }
680
+ }
681
+
682
+ return block_storage.AsTensorMaterializedBlock();
683
+ }
684
+
685
+ EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; }
686
+
687
+ const TensorEvaluator<ArgType, Device>& impl() const { return m_impl; }
688
+
689
+ Broadcast functor() const { return m_broadcast; }
690
+ private:
691
+ static constexpr bool IsColMajor =
692
+ static_cast<int>(Layout) == static_cast<int>(ColMajor);
693
+
694
+ // We will build a general case block broadcasting on top of broadcasting
695
+ // primitive that will do broadcasting only for the inner dimension(s) along
696
+ // the first dimension smaller than the input size (it's called `bcast_dim`).
697
+ //
698
+ // Example:
699
+ // dim: 0 1 2 (ColMajor)
700
+ // input size: [9, 3, 6]
701
+ // block size: [9, 2, 6]
702
+ //
703
+ // We will compute broadcasted block by iterating over the outer dimensions
704
+ // before `bcast_dim` (only dimension `2` in this example) and computing
705
+ // broadcasts along the `bcast_dim` (dimension `1` in this example).
706
+
707
+ // BlockBroadcastingParams holds precomputed parameters for broadcasting a
708
+ // single block along the broadcasting dimension. Sizes and strides along the
709
+ // `bcast_dim` might be invalid, they will be adjusted later in
710
+ // `BroadcastBlockAlongBcastDim`.
711
+ struct BlockBroadcastingParams {
712
+ Dimensions input_dims; // input expression dimensions
713
+ Dimensions output_dims; // output block sizes
714
+ Dimensions output_strides; // output block strides
715
+
716
+ int inner_dim_count; // count inner dimensions matching in size
717
+ int bcast_dim; // broadcasting dimension index
718
+ Index bcast_dim_size; // broadcasting dimension size
719
+ Index inner_dim_size; // inner dimensions size
720
+
721
+ // Block sizes and strides for the input block where all dimensions before
722
+ // `bcast_dim` are equal to `1`.
723
+ Dimensions input_block_sizes;
724
+ Dimensions input_block_strides;
725
+
726
+ // Block sizes and strides for blocks with extra dimensions and strides `0`.
727
+ BroadcastDimensions bcast_block_sizes;
728
+ BroadcastDimensions bcast_block_strides;
729
+ BroadcastDimensions bcast_input_strides;
730
+ };
731
+
732
+ struct BlockBroadcastingIteratorState {
733
+ Index size;
734
+ Index count;
735
+ Index output_stride;
736
+ Index output_span;
737
+ };
738
+
739
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE BlockBroadcastingParams
740
+ blockBroadcastingParams(TensorBlockDesc& desc) const {
741
+ BlockBroadcastingParams params;
742
+
743
+ params.input_dims = Dimensions(m_impl.dimensions());
744
+
745
+ // Output block sizes and strides.
746
+ params.output_dims = desc.dimensions();
747
+ params.output_strides = internal::strides<Layout>(params.output_dims);
748
+
749
+ // Find the broadcasting dimension (first dimension with output size smaller
750
+ // that the input size).
751
+ params.bcast_dim = 0;
752
+ params.bcast_dim_size = 1;
753
+ params.inner_dim_size = 1;
754
+
755
+ // Count the number of inner dimensions that have the same size in the block
756
+ // and in the broadcast expression.
757
+ params.inner_dim_count = 0;
758
+
759
+ for (int i = 0; i < NumDims; ++i) {
760
+ const int dim = IsColMajor ? i : NumDims - i - 1;
761
+
762
+ if (params.output_dims[dim] == m_dimensions[dim]) {
763
+ params.inner_dim_size *= params.output_dims[dim];
764
+ ++params.inner_dim_count;
765
+ continue;
766
+ }
767
+
768
+ // First non-matching dimension is the broadcasting dimension.
769
+ eigen_assert(params.output_dims[dim] < m_dimensions[dim]);
770
+ params.bcast_dim = dim;
771
+ params.bcast_dim_size = params.output_dims[dim];
772
+ break;
773
+ }
774
+
775
+ // Calculate the input block size for looking into the input.
776
+ for (int i = 0; i < params.inner_dim_count; ++i) {
777
+ const int dim = IsColMajor ? i : NumDims - i - 1;
778
+ params.input_block_sizes[dim] = params.input_dims[dim];
779
+ }
780
+ for (int i = params.inner_dim_count; i < NumDims; ++i) {
781
+ const int dim = IsColMajor ? i : NumDims - i - 1;
782
+ params.input_block_sizes[dim] = 1;
783
+ }
784
+ params.input_block_strides =
785
+ internal::strides<Layout>(params.input_block_sizes);
786
+
787
+ // Broadcast with the 0-stride trick: Create 1 extra dim for each
788
+ // broadcast, set the input stride to 0.
789
+ //
790
+ // When ColMajor:
791
+ //
792
+ // - bcast_block_sizes:
793
+ // [d_0, b_0, d_1, b_1, ...]
794
+ //
795
+ // - bcast_block_strides:
796
+ // [output_block_strides[0], output_block_strides[0] * d_0,
797
+ // output_block_strides[1], output_block_strides[1] * d_1,
798
+ // ...]
799
+ //
800
+ // - bcast_input_strides:
801
+ // [input_block_strides[0], 0,
802
+ // input_block_strides[1], 0,
803
+ // ...].
804
+ //
805
+ for (int i = 0; i < params.inner_dim_count; ++i) {
806
+ const int dim = IsColMajor ? i : NumDims - i - 1;
807
+
808
+ const int copy_dim = IsColMajor ? 2 * i : 2 * NumDims - 2 * i - 1;
809
+ const int broadcast_dim = IsColMajor ? copy_dim + 1 : copy_dim - 1;
810
+
811
+ params.bcast_block_sizes[copy_dim] = params.input_dims[dim];
812
+ params.bcast_block_sizes[broadcast_dim] = m_broadcast[dim];
813
+ params.bcast_block_strides[copy_dim] = params.output_strides[dim];
814
+ params.bcast_block_strides[broadcast_dim] =
815
+ params.output_strides[dim] * params.input_dims[dim];
816
+ params.bcast_input_strides[copy_dim] = params.input_block_strides[dim];
817
+ params.bcast_input_strides[broadcast_dim] = 0;
818
+ }
819
+
820
+ for (int i = 2 * params.inner_dim_count; i < 2 * NumDims; ++i) {
821
+ const int dim = IsColMajor ? i : 2 * NumDims - i - 1;
822
+ params.bcast_block_sizes[dim] = 1;
823
+ params.bcast_block_strides[dim] = 0;
824
+ params.bcast_input_strides[dim] = 0;
825
+ }
826
+
827
+ return params;
828
+ }
829
+
830
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock emptyBlock() const {
831
+ DSizes<Index, NumDims> dimensions;
832
+ for (int i = 0; i < NumDims; ++i) dimensions[i] = 0;
833
+ return TensorBlock(internal::TensorBlockKind::kView, NULL, dimensions);
834
+ }
835
+
836
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index BroadcastBlockAlongBcastDim(
837
+ BlockBroadcastingParams params, Index bcast_offset,
838
+ TensorBlockScratch& scratch, ScalarNoConst* materialized_output,
839
+ ScalarNoConst** materialized_input,
840
+ size_t* materialized_input_size) const {
841
+ if (params.bcast_dim_size == 1) {
842
+ // We just need one block read using the ready-set values above.
843
+ return BroadcastBlock(
844
+ params.input_block_sizes, params.input_block_strides,
845
+ params.bcast_block_sizes, params.bcast_block_strides,
846
+ params.bcast_input_strides, bcast_offset, 0, scratch,
847
+ materialized_output, materialized_input, materialized_input_size);
848
+
849
+ } else if (params.input_dims[params.bcast_dim] == 1) {
850
+ // Broadcast bcast dimension (< NumDims) by bcast_dim_size.
851
+ const int broadcast_bcast_dim =
852
+ IsColMajor ? 2 * params.inner_dim_count + 1
853
+ : 2 * NumDims - 2 * params.inner_dim_count - 2;
854
+
855
+ params.bcast_block_sizes[broadcast_bcast_dim] = params.bcast_dim_size;
856
+ params.bcast_input_strides[broadcast_bcast_dim] = 0;
857
+ params.bcast_block_strides[broadcast_bcast_dim] =
858
+ params.output_strides[params.bcast_dim];
859
+
860
+ return BroadcastBlock(
861
+ params.input_block_sizes, params.input_block_strides,
862
+ params.bcast_block_sizes, params.bcast_block_strides,
863
+ params.bcast_input_strides, bcast_offset, 0, scratch,
864
+ materialized_output, materialized_input, materialized_input_size);
865
+
866
+ } else {
867
+ // Keep track of the total number of the coefficients written to the
868
+ // output block.
869
+ Index num_output_coeffs = 0;
870
+
871
+ // The general case. Let's denote the output block as
872
+ //
873
+ // x[..., a:a+bcast_dim_size, :, ..., :]
874
+ //
875
+ // where a:a+bcast_dim_size is a slice on the bcast_dim dimension
876
+ // (< NumDims). We need to split the a:a+bcast_dim_size into possibly 3
877
+ // sub-blocks:
878
+ //
879
+ // (1) a:b, where b is the smallest multiple of
880
+ // input_dims[bcast_dim_start] in [a, a+bcast_dim_size].
881
+ //
882
+ // (2) b:c, where c is the largest multiple of input_dims[bcast_dim_start]
883
+ // in [a, a+bcast_dim_size].
884
+ //
885
+ // (3) c:a+bcast_dim_size .
886
+ //
887
+ // Or, when b and c do not exist, we just need to process the whole block
888
+ // together.
889
+
890
+ // Find a.
891
+ const Index bcast_dim_left_index =
892
+ bcast_offset / m_outputStrides[params.bcast_dim];
893
+
894
+ // Find b and c.
895
+ const Index input_bcast_dim_size = params.input_dims[params.bcast_dim];
896
+
897
+ // First multiple after a. This is b when <= bcast_dim_left_index +
898
+ // bcast_dim_size.
899
+ const Index first_multiple =
900
+ divup<Index>(bcast_dim_left_index, input_bcast_dim_size) *
901
+ input_bcast_dim_size;
902
+
903
+ if (first_multiple <= bcast_dim_left_index + params.bcast_dim_size) {
904
+ // b exists, so does c. Find it.
905
+ const Index last_multiple =
906
+ (bcast_dim_left_index + params.bcast_dim_size) /
907
+ input_bcast_dim_size * input_bcast_dim_size;
908
+ const int copy_bcast_dim =
909
+ IsColMajor ? 2 * params.inner_dim_count
910
+ : 2 * NumDims - 2 * params.inner_dim_count - 1;
911
+ const int broadcast_bcast_dim =
912
+ IsColMajor ? 2 * params.inner_dim_count + 1
913
+ : 2 * NumDims - 2 * params.inner_dim_count - 2;
914
+
915
+ if (first_multiple > bcast_dim_left_index) {
916
+ const Index head_size = first_multiple - bcast_dim_left_index;
917
+ params.input_block_sizes[params.bcast_dim] = head_size;
918
+ params.bcast_block_sizes[copy_bcast_dim] = head_size;
919
+ params.bcast_input_strides[copy_bcast_dim] =
920
+ params.input_block_strides[params.bcast_dim];
921
+ params.bcast_block_strides[copy_bcast_dim] =
922
+ params.output_strides[params.bcast_dim];
923
+ params.bcast_block_sizes[broadcast_bcast_dim] = 1;
924
+ params.bcast_input_strides[broadcast_bcast_dim] = 0;
925
+ params.bcast_block_strides[broadcast_bcast_dim] =
926
+ params.output_strides[params.bcast_dim] *
927
+ params.input_dims[params.bcast_dim];
928
+
929
+ num_output_coeffs += BroadcastBlock(
930
+ params.input_block_sizes, params.input_block_strides,
931
+ params.bcast_block_sizes, params.bcast_block_strides,
932
+ params.bcast_input_strides, bcast_offset, 0, scratch,
933
+ materialized_output, materialized_input, materialized_input_size);
934
+ }
935
+ if (first_multiple < last_multiple) {
936
+ params.input_block_sizes[params.bcast_dim] = input_bcast_dim_size;
937
+ params.bcast_block_sizes[copy_bcast_dim] = input_bcast_dim_size;
938
+ params.bcast_input_strides[copy_bcast_dim] =
939
+ params.input_block_strides[params.bcast_dim];
940
+ params.bcast_block_strides[copy_bcast_dim] =
941
+ params.output_strides[params.bcast_dim];
942
+ params.bcast_block_sizes[broadcast_bcast_dim] =
943
+ (last_multiple - first_multiple) / input_bcast_dim_size;
944
+ params.bcast_input_strides[broadcast_bcast_dim] = 0;
945
+ params.bcast_block_strides[broadcast_bcast_dim] =
946
+ params.output_strides[params.bcast_dim] *
947
+ params.input_dims[params.bcast_dim];
948
+ const Index offset = (first_multiple - bcast_dim_left_index) *
949
+ m_outputStrides[params.bcast_dim];
950
+
951
+ num_output_coeffs += BroadcastBlock(
952
+ params.input_block_sizes, params.input_block_strides,
953
+ params.bcast_block_sizes, params.bcast_block_strides,
954
+ params.bcast_input_strides, bcast_offset, offset, scratch,
955
+ materialized_output, materialized_input, materialized_input_size);
956
+ }
957
+ if (last_multiple < bcast_dim_left_index + params.bcast_dim_size) {
958
+ const Index tail_size =
959
+ bcast_dim_left_index + params.bcast_dim_size - last_multiple;
960
+ params.input_block_sizes[params.bcast_dim] = tail_size;
961
+ params.bcast_block_sizes[copy_bcast_dim] = tail_size;
962
+ params.bcast_input_strides[copy_bcast_dim] =
963
+ params.input_block_strides[params.bcast_dim];
964
+ params.bcast_block_strides[copy_bcast_dim] =
965
+ params.output_strides[params.bcast_dim];
966
+ params.bcast_block_sizes[broadcast_bcast_dim] = 1;
967
+ params.bcast_input_strides[broadcast_bcast_dim] = 0;
968
+ params.bcast_block_strides[broadcast_bcast_dim] =
969
+ params.output_strides[params.bcast_dim] *
970
+ params.input_dims[params.bcast_dim];
971
+ const Index offset = (last_multiple - bcast_dim_left_index) *
972
+ m_outputStrides[params.bcast_dim];
973
+
974
+ num_output_coeffs += BroadcastBlock(
975
+ params.input_block_sizes, params.input_block_strides,
976
+ params.bcast_block_sizes, params.bcast_block_strides,
977
+ params.bcast_input_strides, bcast_offset, offset, scratch,
978
+ materialized_output, materialized_input, materialized_input_size);
979
+ }
980
+ } else {
981
+ // b and c do not exist.
982
+ const int copy_bcast_dim =
983
+ IsColMajor ? 2 * params.inner_dim_count
984
+ : 2 * NumDims - 2 * params.inner_dim_count - 1;
985
+ params.input_block_sizes[params.bcast_dim] = params.bcast_dim_size;
986
+ params.bcast_block_sizes[copy_bcast_dim] = params.bcast_dim_size;
987
+ params.bcast_input_strides[copy_bcast_dim] =
988
+ params.input_block_strides[params.bcast_dim];
989
+ params.bcast_block_strides[copy_bcast_dim] =
990
+ params.output_strides[params.bcast_dim];
991
+
992
+ num_output_coeffs += BroadcastBlock(
993
+ params.input_block_sizes, params.input_block_strides,
994
+ params.bcast_block_sizes, params.bcast_block_strides,
995
+ params.bcast_input_strides, bcast_offset, 0, scratch,
996
+ materialized_output, materialized_input, materialized_input_size);
997
+ }
998
+
999
+ return num_output_coeffs;
1000
+ }
1001
+ }
1002
+
1003
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index BroadcastBlock(
1004
+ const Dimensions& input_block_sizes,
1005
+ const Dimensions& input_block_strides,
1006
+ const BroadcastDimensions& bcast_block_sizes,
1007
+ const BroadcastDimensions& bcast_block_strides,
1008
+ const BroadcastDimensions& bcast_input_strides, Index bcast_offset,
1009
+ Index offset, TensorBlockScratch& scratch,
1010
+ ScalarNoConst* materialized_output, ScalarNoConst** materialized_input,
1011
+ size_t* materialized_input_size) const {
1012
+ // ---------------------------------------------------------------------- //
1013
+ // Tensor block descriptor for reading block from the input.
1014
+ const Index input_offset = bcast_offset + offset;
1015
+ TensorBlockDesc input_desc(
1016
+ IsColMajor ? indexColMajor(input_offset) : indexRowMajor(input_offset),
1017
+ input_block_sizes);
1018
+
1019
+ ArgTensorBlock input_block = m_impl.block(input_desc, scratch);
1020
+
1021
+ // ---------------------------------------------------------------------- //
1022
+ // Materialize input block into a temporary memory buffer only if it's not
1023
+ // already available in the arg block.
1024
+ const ScalarNoConst* input_buffer = NULL;
1025
+
1026
+ if (input_block.data() != NULL) {
1027
+ // Input block already has raw data, there is no need to materialize it.
1028
+ input_buffer = input_block.data();
1029
+
1030
+ } else {
1031
+ // Otherwise we have to do block assignment into a temporary buffer.
1032
+
1033
+ // Maybe reuse previously allocated buffer, or allocate a new one with a
1034
+ // scratch allocator.
1035
+ const size_t input_total_size = input_block_sizes.TotalSize();
1036
+ if (*materialized_input == NULL ||
1037
+ *materialized_input_size < input_total_size) {
1038
+ *materialized_input_size = input_total_size;
1039
+ void* mem = scratch.allocate(*materialized_input_size * sizeof(Scalar));
1040
+ *materialized_input = static_cast<ScalarNoConst*>(mem);
1041
+ }
1042
+
1043
+ typedef internal::TensorBlockAssignment<
1044
+ ScalarNoConst, NumDims, typename ArgTensorBlock::XprType, Index>
1045
+ TensorBlockAssignment;
1046
+
1047
+ TensorBlockAssignment::Run(
1048
+ TensorBlockAssignment::target(input_block_sizes, input_block_strides,
1049
+ *materialized_input),
1050
+ input_block.expr());
1051
+
1052
+ input_buffer = *materialized_input;
1053
+ }
1054
+
1055
+ // ---------------------------------------------------------------------- //
1056
+ // Copy data from materialized input block to the materialized output, using
1057
+ // given broadcast strides (strides with zeroes).
1058
+ typedef internal::TensorBlockIO<ScalarNoConst, Index, 2 * NumDims, Layout>
1059
+ TensorBlockIO;
1060
+
1061
+ typename TensorBlockIO::Src src(bcast_input_strides, input_buffer);
1062
+ typename TensorBlockIO::Dst dst(bcast_block_sizes, bcast_block_strides,
1063
+ materialized_output + offset);
1064
+
1065
+ return TensorBlockIO::Copy(dst, src);
1066
+ }
1067
+
1068
+ protected:
1069
+ const Device EIGEN_DEVICE_REF m_device;
1070
+ const std::remove_reference_t<Broadcast> m_broadcast;
1071
+ Dimensions m_dimensions;
1072
+ array<Index, NumDims> m_outputStrides;
1073
+ array<Index, NumDims> m_inputStrides;
1074
+ TensorEvaluator<ArgType, Device> m_impl;
1075
+ };
1076
+
1077
+
1078
+ } // end namespace Eigen
1079
+
1080
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_BROADCASTING_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorChipping.h ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H
12
+
13
+ #include "./InternalHeaderCheck.h"
14
+
15
+ namespace Eigen {
16
+
17
+ /** \class TensorKChippingReshaping
18
+ * \ingroup CXX11_Tensor_Module
19
+ *
20
+ * \brief A chip is a thin slice, corresponding to a column or a row in a 2-d tensor.
21
+ *
22
+ *
23
+ */
24
+
25
+ namespace internal {
26
+ template<DenseIndex DimId, typename XprType>
27
+ struct traits<TensorChippingOp<DimId, XprType> > : public traits<XprType>
28
+ {
29
+ typedef typename XprType::Scalar Scalar;
30
+ typedef traits<XprType> XprTraits;
31
+ typedef typename XprTraits::StorageKind StorageKind;
32
+ typedef typename XprTraits::Index Index;
33
+ typedef typename XprType::Nested Nested;
34
+ typedef std::remove_reference_t<Nested> Nested_;
35
+ static constexpr int NumDimensions = XprTraits::NumDimensions - 1;
36
+ static constexpr int Layout = XprTraits::Layout;
37
+ typedef typename XprTraits::PointerType PointerType;
38
+ };
39
+
40
+ template<DenseIndex DimId, typename XprType>
41
+ struct eval<TensorChippingOp<DimId, XprType>, Eigen::Dense>
42
+ {
43
+ typedef const TensorChippingOp<DimId, XprType> EIGEN_DEVICE_REF type;
44
+ };
45
+
46
+ template<DenseIndex DimId, typename XprType>
47
+ struct nested<TensorChippingOp<DimId, XprType>, 1, typename eval<TensorChippingOp<DimId, XprType> >::type>
48
+ {
49
+ typedef TensorChippingOp<DimId, XprType> type;
50
+ };
51
+
52
+ template <DenseIndex DimId>
53
+ struct DimensionId
54
+ {
55
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DimensionId(DenseIndex dim) {
56
+ EIGEN_UNUSED_VARIABLE(dim);
57
+ eigen_assert(dim == DimId);
58
+ }
59
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex actualDim() const {
60
+ return DimId;
61
+ }
62
+ };
63
+ template <>
64
+ struct DimensionId<Dynamic>
65
+ {
66
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DimensionId(DenseIndex dim) : actual_dim(dim) {
67
+ eigen_assert(dim >= 0);
68
+ }
69
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex actualDim() const {
70
+ return actual_dim;
71
+ }
72
+ private:
73
+ const DenseIndex actual_dim;
74
+ };
75
+
76
+
77
+ } // end namespace internal
78
+
79
+
80
+
81
+ template<DenseIndex DimId, typename XprType>
82
+ class TensorChippingOp : public TensorBase<TensorChippingOp<DimId, XprType> >
83
+ {
84
+ public:
85
+ typedef TensorBase<TensorChippingOp<DimId, XprType> > Base;
86
+ typedef typename Eigen::internal::traits<TensorChippingOp>::Scalar Scalar;
87
+ typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
88
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
89
+ typedef typename Eigen::internal::nested<TensorChippingOp>::type Nested;
90
+ typedef typename Eigen::internal::traits<TensorChippingOp>::StorageKind StorageKind;
91
+ typedef typename Eigen::internal::traits<TensorChippingOp>::Index Index;
92
+
93
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorChippingOp(const XprType& expr, const Index offset, const Index dim)
94
+ : m_xpr(expr), m_offset(offset), m_dim(dim) {
95
+ }
96
+
97
+ EIGEN_DEVICE_FUNC
98
+ const Index offset() const { return m_offset; }
99
+ EIGEN_DEVICE_FUNC
100
+ const Index dim() const { return m_dim.actualDim(); }
101
+
102
+ EIGEN_DEVICE_FUNC
103
+ const internal::remove_all_t<typename XprType::Nested>&
104
+ expression() const { return m_xpr; }
105
+
106
+ EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorChippingOp)
107
+
108
+ protected:
109
+ typename XprType::Nested m_xpr;
110
+ const Index m_offset;
111
+ const internal::DimensionId<DimId> m_dim;
112
+ };
113
+
114
+
115
+ // Eval as rvalue
116
+ template<DenseIndex DimId, typename ArgType, typename Device>
117
+ struct TensorEvaluator<const TensorChippingOp<DimId, ArgType>, Device>
118
+ {
119
+ typedef TensorChippingOp<DimId, ArgType> XprType;
120
+ static constexpr int NumInputDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
121
+ static constexpr int NumDims = NumInputDims-1;
122
+ typedef typename XprType::Index Index;
123
+ typedef DSizes<Index, NumDims> Dimensions;
124
+ typedef typename XprType::Scalar Scalar;
125
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
126
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
127
+ static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
128
+ typedef StorageMemory<CoeffReturnType, Device> Storage;
129
+ typedef typename Storage::Type EvaluatorPointerType;
130
+ static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
131
+
132
+ enum {
133
+ // Alignment can't be guaranteed at compile time since it depends on the
134
+ // slice offsets.
135
+ IsAligned = false,
136
+ PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
137
+ BlockAccess = TensorEvaluator<ArgType, Device>::BlockAccess,
138
+ // Chipping of outer-most dimension is a trivial operation, because we can
139
+ // read and write directly from the underlying tensor using single offset.
140
+ IsOuterChipping = (Layout == ColMajor && DimId == NumInputDims - 1) ||
141
+ (Layout == RowMajor && DimId == 0),
142
+ // Chipping inner-most dimension.
143
+ IsInnerChipping = (Layout == ColMajor && DimId == 0) ||
144
+ (Layout == RowMajor && DimId == NumInputDims - 1),
145
+ // Prefer block access if the underlying expression prefers it, otherwise
146
+ // only if chipping is not trivial.
147
+ PreferBlockAccess = TensorEvaluator<ArgType, Device>::PreferBlockAccess ||
148
+ !IsOuterChipping,
149
+ CoordAccess = false, // to be implemented
150
+ RawAccess = false
151
+ };
152
+
153
+ typedef std::remove_const_t<Scalar> ScalarNoConst;
154
+
155
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
156
+ typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
157
+ typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
158
+
159
+ typedef internal::TensorBlockDescriptor<NumInputDims, Index>
160
+ ArgTensorBlockDesc;
161
+ typedef typename TensorEvaluator<const ArgType, Device>::TensorBlock
162
+ ArgTensorBlock;
163
+
164
+ typedef typename internal::TensorMaterializedBlock<ScalarNoConst, NumDims,
165
+ Layout, Index>
166
+ TensorBlock;
167
+ //===--------------------------------------------------------------------===//
168
+
169
+ EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
170
+ : m_impl(op.expression(), device), m_dim(op.dim()), m_device(device)
171
+ {
172
+ EIGEN_STATIC_ASSERT((NumInputDims >= 1), YOU_MADE_A_PROGRAMMING_MISTAKE);
173
+ eigen_assert(NumInputDims > m_dim.actualDim());
174
+
175
+ const typename TensorEvaluator<ArgType, Device>::Dimensions& input_dims = m_impl.dimensions();
176
+ eigen_assert(op.offset() < input_dims[m_dim.actualDim()]);
177
+
178
+ int j = 0;
179
+ for (int i = 0; i < NumInputDims; ++i) {
180
+ if (i != m_dim.actualDim()) {
181
+ m_dimensions[j] = input_dims[i];
182
+ ++j;
183
+ }
184
+ }
185
+
186
+ m_stride = 1;
187
+ m_inputStride = 1;
188
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
189
+ for (int i = 0; i < m_dim.actualDim(); ++i) {
190
+ m_stride *= input_dims[i];
191
+ m_inputStride *= input_dims[i];
192
+ }
193
+ } else {
194
+ for (int i = NumInputDims-1; i > m_dim.actualDim(); --i) {
195
+ m_stride *= input_dims[i];
196
+ m_inputStride *= input_dims[i];
197
+ }
198
+ }
199
+ m_inputStride *= input_dims[m_dim.actualDim()];
200
+ m_inputOffset = m_stride * op.offset();
201
+ }
202
+
203
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
204
+
205
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
206
+ m_impl.evalSubExprsIfNeeded(NULL);
207
+ return true;
208
+ }
209
+
210
+ EIGEN_STRONG_INLINE void cleanup() {
211
+ m_impl.cleanup();
212
+ }
213
+
214
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const
215
+ {
216
+ return m_impl.coeff(srcCoeff(index));
217
+ }
218
+
219
+ template<int LoadMode>
220
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const
221
+ {
222
+ eigen_assert(index+PacketSize-1 < dimensions().TotalSize());
223
+
224
+ if (isInnerChipping()) {
225
+ // m_stride is equal to 1, so let's avoid the integer division.
226
+ eigen_assert(m_stride == 1);
227
+ Index inputIndex = index * m_inputStride + m_inputOffset;
228
+ EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
229
+ EIGEN_UNROLL_LOOP
230
+ for (int i = 0; i < PacketSize; ++i) {
231
+ values[i] = m_impl.coeff(inputIndex);
232
+ inputIndex += m_inputStride;
233
+ }
234
+ PacketReturnType rslt = internal::pload<PacketReturnType>(values);
235
+ return rslt;
236
+ } else if (isOuterChipping()) {
237
+ // m_stride is always greater than index, so let's avoid the integer division.
238
+ eigen_assert(m_stride > index);
239
+ return m_impl.template packet<LoadMode>(index + m_inputOffset);
240
+ } else {
241
+ const Index idx = index / m_stride;
242
+ const Index rem = index - idx * m_stride;
243
+ if (rem + PacketSize <= m_stride) {
244
+ Index inputIndex = idx * m_inputStride + m_inputOffset + rem;
245
+ return m_impl.template packet<LoadMode>(inputIndex);
246
+ } else {
247
+ // Cross the stride boundary. Fallback to slow path.
248
+ EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
249
+ EIGEN_UNROLL_LOOP
250
+ for (int i = 0; i < PacketSize; ++i) {
251
+ values[i] = coeff(index);
252
+ ++index;
253
+ }
254
+ PacketReturnType rslt = internal::pload<PacketReturnType>(values);
255
+ return rslt;
256
+ }
257
+ }
258
+ }
259
+
260
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
261
+ costPerCoeff(bool vectorized) const {
262
+ double cost = 0;
263
+ if ((static_cast<int>(Layout) == static_cast<int>(ColMajor) &&
264
+ m_dim.actualDim() == 0) ||
265
+ (static_cast<int>(Layout) == static_cast<int>(RowMajor) &&
266
+ m_dim.actualDim() == NumInputDims - 1)) {
267
+ cost += TensorOpCost::MulCost<Index>() + TensorOpCost::AddCost<Index>();
268
+ } else if ((static_cast<int>(Layout) == static_cast<int>(ColMajor) &&
269
+ m_dim.actualDim() == NumInputDims - 1) ||
270
+ (static_cast<int>(Layout) == static_cast<int>(RowMajor) &&
271
+ m_dim.actualDim() == 0)) {
272
+ cost += TensorOpCost::AddCost<Index>();
273
+ } else {
274
+ cost += 3 * TensorOpCost::MulCost<Index>() + TensorOpCost::DivCost<Index>() +
275
+ 3 * TensorOpCost::AddCost<Index>();
276
+ }
277
+
278
+ return m_impl.costPerCoeff(vectorized) +
279
+ TensorOpCost(0, 0, cost, vectorized, PacketSize);
280
+ }
281
+
282
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
283
+ internal::TensorBlockResourceRequirements getResourceRequirements() const {
284
+ const size_t target_size = m_device.lastLevelCacheSize();
285
+ return internal::TensorBlockResourceRequirements::merge(
286
+ internal::TensorBlockResourceRequirements::skewed<Scalar>(target_size),
287
+ m_impl.getResourceRequirements());
288
+ }
289
+
290
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock
291
+ block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
292
+ bool root_of_expr_ast = false) const {
293
+ const Index chip_dim = m_dim.actualDim();
294
+
295
+ DSizes<Index, NumInputDims> input_block_dims;
296
+ for (int i = 0; i < NumInputDims; ++i) {
297
+ input_block_dims[i]
298
+ = i < chip_dim ? desc.dimension(i)
299
+ : i > chip_dim ? desc.dimension(i - 1)
300
+ : 1;
301
+ }
302
+
303
+ ArgTensorBlockDesc arg_desc(srcCoeff(desc.offset()), input_block_dims);
304
+
305
+ // Try to reuse destination buffer for materializing argument block.
306
+ if (desc.HasDestinationBuffer()) {
307
+ DSizes<Index, NumInputDims> arg_destination_strides;
308
+ for (int i = 0; i < NumInputDims; ++i) {
309
+ arg_destination_strides[i]
310
+ = i < chip_dim ? desc.destination().strides()[i]
311
+ : i > chip_dim ? desc.destination().strides()[i - 1]
312
+ : 0; // for dimensions of size `1` stride should never be used.
313
+ }
314
+
315
+ arg_desc.template AddDestinationBuffer<Layout>(
316
+ desc.destination().template data<ScalarNoConst>(),
317
+ arg_destination_strides);
318
+ }
319
+
320
+ ArgTensorBlock arg_block = m_impl.block(arg_desc, scratch, root_of_expr_ast);
321
+ if (!arg_desc.HasDestinationBuffer()) desc.DropDestinationBuffer();
322
+
323
+ if (arg_block.data() != NULL) {
324
+ // Forward argument block buffer if possible.
325
+ return TensorBlock(arg_block.kind(), arg_block.data(),
326
+ desc.dimensions());
327
+
328
+ } else {
329
+ // Assign argument block expression to a buffer.
330
+
331
+ // Prepare storage for the materialized chipping result.
332
+ const typename TensorBlock::Storage block_storage =
333
+ TensorBlock::prepareStorage(desc, scratch);
334
+
335
+ typedef internal::TensorBlockAssignment<
336
+ ScalarNoConst, NumInputDims, typename ArgTensorBlock::XprType, Index>
337
+ TensorBlockAssignment;
338
+
339
+ TensorBlockAssignment::Run(
340
+ TensorBlockAssignment::target(
341
+ arg_desc.dimensions(),
342
+ internal::strides<Layout>(arg_desc.dimensions()),
343
+ block_storage.data()),
344
+ arg_block.expr());
345
+
346
+ return block_storage.AsTensorMaterializedBlock();
347
+ }
348
+ }
349
+
350
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Storage::Type data() const {
351
+ typename Storage::Type result = constCast(m_impl.data());
352
+ if (isOuterChipping() && result) {
353
+ return result + m_inputOffset;
354
+ } else {
355
+ return NULL;
356
+ }
357
+ }
358
+
359
+ protected:
360
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index) const
361
+ {
362
+ Index inputIndex;
363
+ if (isInnerChipping()) {
364
+ // m_stride is equal to 1, so let's avoid the integer division.
365
+ eigen_assert(m_stride == 1);
366
+ inputIndex = index * m_inputStride + m_inputOffset;
367
+ } else if (isOuterChipping()) {
368
+ // m_stride is always greater than index, so let's avoid the integer
369
+ // division.
370
+ eigen_assert(m_stride > index);
371
+ inputIndex = index + m_inputOffset;
372
+ } else {
373
+ const Index idx = index / m_stride;
374
+ inputIndex = idx * m_inputStride + m_inputOffset;
375
+ index -= idx * m_stride;
376
+ inputIndex += index;
377
+ }
378
+ return inputIndex;
379
+ }
380
+
381
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool isInnerChipping() const {
382
+ return IsInnerChipping ||
383
+ (static_cast<int>(Layout) == ColMajor && m_dim.actualDim() == 0) ||
384
+ (static_cast<int>(Layout) == RowMajor && m_dim.actualDim() == NumInputDims - 1);
385
+ }
386
+
387
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool isOuterChipping() const {
388
+ return IsOuterChipping ||
389
+ (static_cast<int>(Layout) == ColMajor && m_dim.actualDim() == NumInputDims-1) ||
390
+ (static_cast<int>(Layout) == RowMajor && m_dim.actualDim() == 0);
391
+ }
392
+
393
+ Dimensions m_dimensions;
394
+ Index m_stride;
395
+ Index m_inputOffset;
396
+ Index m_inputStride;
397
+ TensorEvaluator<ArgType, Device> m_impl;
398
+ const internal::DimensionId<DimId> m_dim;
399
+ const Device EIGEN_DEVICE_REF m_device;
400
+ };
401
+
402
+
403
+ // Eval as lvalue
404
+ template<DenseIndex DimId, typename ArgType, typename Device>
405
+ struct TensorEvaluator<TensorChippingOp<DimId, ArgType>, Device>
406
+ : public TensorEvaluator<const TensorChippingOp<DimId, ArgType>, Device>
407
+ {
408
+ typedef TensorEvaluator<const TensorChippingOp<DimId, ArgType>, Device> Base;
409
+ typedef TensorChippingOp<DimId, ArgType> XprType;
410
+ static constexpr int NumInputDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
411
+ static constexpr int NumDims = NumInputDims-1;
412
+ typedef typename XprType::Index Index;
413
+ typedef DSizes<Index, NumDims> Dimensions;
414
+ typedef typename XprType::Scalar Scalar;
415
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
416
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
417
+ static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
418
+
419
+ enum {
420
+ IsAligned = false,
421
+ PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
422
+ BlockAccess = TensorEvaluator<ArgType, Device>::RawAccess,
423
+ Layout = TensorEvaluator<ArgType, Device>::Layout,
424
+ RawAccess = false
425
+ };
426
+
427
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
428
+ typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
429
+ //===--------------------------------------------------------------------===//
430
+
431
+ EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
432
+ : Base(op, device)
433
+ { }
434
+
435
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const
436
+ {
437
+ return this->m_impl.coeffRef(this->srcCoeff(index));
438
+ }
439
+
440
+ template <int StoreMode> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
441
+ void writePacket(Index index, const PacketReturnType& x) const
442
+ {
443
+ if (this->isInnerChipping()) {
444
+ // m_stride is equal to 1, so let's avoid the integer division.
445
+ eigen_assert(this->m_stride == 1);
446
+ EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
447
+ internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
448
+ Index inputIndex = index * this->m_inputStride + this->m_inputOffset;
449
+ EIGEN_UNROLL_LOOP
450
+ for (int i = 0; i < PacketSize; ++i) {
451
+ this->m_impl.coeffRef(inputIndex) = values[i];
452
+ inputIndex += this->m_inputStride;
453
+ }
454
+ } else if (this->isOuterChipping()) {
455
+ // m_stride is always greater than index, so let's avoid the integer division.
456
+ eigen_assert(this->m_stride > index);
457
+ this->m_impl.template writePacket<StoreMode>(index + this->m_inputOffset, x);
458
+ } else {
459
+ const Index idx = index / this->m_stride;
460
+ const Index rem = index - idx * this->m_stride;
461
+ if (rem + PacketSize <= this->m_stride) {
462
+ const Index inputIndex = idx * this->m_inputStride + this->m_inputOffset + rem;
463
+ this->m_impl.template writePacket<StoreMode>(inputIndex, x);
464
+ } else {
465
+ // Cross stride boundary. Fallback to slow path.
466
+ EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
467
+ internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
468
+ EIGEN_UNROLL_LOOP
469
+ for (int i = 0; i < PacketSize; ++i) {
470
+ this->coeffRef(index) = values[i];
471
+ ++index;
472
+ }
473
+ }
474
+ }
475
+ }
476
+
477
+ template <typename TensorBlock>
478
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writeBlock(
479
+ const TensorBlockDesc& desc, const TensorBlock& block) {
480
+ eigen_assert(this->m_impl.data() != NULL);
481
+
482
+ const Index chip_dim = this->m_dim.actualDim();
483
+
484
+ DSizes<Index, NumInputDims> input_block_dims;
485
+ for (int i = 0; i < NumInputDims; ++i) {
486
+ input_block_dims[i] = i < chip_dim ? desc.dimension(i)
487
+ : i > chip_dim ? desc.dimension(i - 1)
488
+ : 1;
489
+ }
490
+
491
+ typedef TensorReshapingOp<const DSizes<Index, NumInputDims>,
492
+ const typename TensorBlock::XprType>
493
+ TensorBlockExpr;
494
+
495
+ typedef internal::TensorBlockAssignment<Scalar, NumInputDims,
496
+ TensorBlockExpr, Index>
497
+ TensorBlockAssign;
498
+
499
+ TensorBlockAssign::Run(
500
+ TensorBlockAssign::target(
501
+ input_block_dims,
502
+ internal::strides<Layout>(this->m_impl.dimensions()),
503
+ this->m_impl.data(), this->srcCoeff(desc.offset())),
504
+ block.expr().reshape(input_block_dims));
505
+ }
506
+ };
507
+
508
+
509
+ } // end namespace Eigen
510
+
511
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConcatenation.h ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONCATENATION_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONCATENATION_H
12
+
13
+ #include "./InternalHeaderCheck.h"
14
+
15
+ namespace Eigen {
16
+
17
+ /** \class TensorConcatenationOp
18
+ * \ingroup CXX11_Tensor_Module
19
+ *
20
+ * \brief Tensor concatenation class.
21
+ *
22
+ *
23
+ */
24
+ namespace internal {
25
+ template<typename Axis, typename LhsXprType, typename RhsXprType>
26
+ struct traits<TensorConcatenationOp<Axis, LhsXprType, RhsXprType> >
27
+ {
28
+ // Type promotion to handle the case where the types of the lhs and the rhs are different.
29
+ typedef typename promote_storage_type<typename LhsXprType::Scalar,
30
+ typename RhsXprType::Scalar>::ret Scalar;
31
+ typedef typename promote_storage_type<typename traits<LhsXprType>::StorageKind,
32
+ typename traits<RhsXprType>::StorageKind>::ret StorageKind;
33
+ typedef typename promote_index_type<typename traits<LhsXprType>::Index,
34
+ typename traits<RhsXprType>::Index>::type Index;
35
+ typedef typename LhsXprType::Nested LhsNested;
36
+ typedef typename RhsXprType::Nested RhsNested;
37
+ typedef std::remove_reference_t<LhsNested> LhsNested_;
38
+ typedef std::remove_reference_t<RhsNested> RhsNested_;
39
+ static constexpr int NumDimensions = traits<LhsXprType>::NumDimensions;
40
+ static constexpr int Layout = traits<LhsXprType>::Layout;
41
+ enum { Flags = 0 };
42
+ typedef std::conditional_t<Pointer_type_promotion<typename LhsXprType::Scalar, Scalar>::val,
43
+ typename traits<LhsXprType>::PointerType, typename traits<RhsXprType>::PointerType> PointerType;
44
+ };
45
+
46
+ template<typename Axis, typename LhsXprType, typename RhsXprType>
47
+ struct eval<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>, Eigen::Dense>
48
+ {
49
+ typedef const TensorConcatenationOp<Axis, LhsXprType, RhsXprType>& type;
50
+ };
51
+
52
+ template<typename Axis, typename LhsXprType, typename RhsXprType>
53
+ struct nested<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>, 1, typename eval<TensorConcatenationOp<Axis, LhsXprType, RhsXprType> >::type>
54
+ {
55
+ typedef TensorConcatenationOp<Axis, LhsXprType, RhsXprType> type;
56
+ };
57
+
58
+ } // end namespace internal
59
+
60
+
61
+ template<typename Axis, typename LhsXprType, typename RhsXprType>
62
+ class TensorConcatenationOp : public TensorBase<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>, WriteAccessors>
63
+ {
64
+ public:
65
+ typedef TensorBase<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>, WriteAccessors> Base;
66
+ typedef typename internal::traits<TensorConcatenationOp>::Scalar Scalar;
67
+ typedef typename internal::traits<TensorConcatenationOp>::StorageKind StorageKind;
68
+ typedef typename internal::traits<TensorConcatenationOp>::Index Index;
69
+ typedef typename internal::nested<TensorConcatenationOp>::type Nested;
70
+ typedef typename internal::promote_storage_type<typename LhsXprType::CoeffReturnType,
71
+ typename RhsXprType::CoeffReturnType>::ret CoeffReturnType;
72
+ typedef typename NumTraits<Scalar>::Real RealScalar;
73
+
74
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorConcatenationOp(const LhsXprType& lhs, const RhsXprType& rhs, Axis axis)
75
+ : m_lhs_xpr(lhs), m_rhs_xpr(rhs), m_axis(axis) {}
76
+
77
+ EIGEN_DEVICE_FUNC
78
+ const internal::remove_all_t<typename LhsXprType::Nested>&
79
+ lhsExpression() const { return m_lhs_xpr; }
80
+
81
+ EIGEN_DEVICE_FUNC
82
+ const internal::remove_all_t<typename RhsXprType::Nested>&
83
+ rhsExpression() const { return m_rhs_xpr; }
84
+
85
+ EIGEN_DEVICE_FUNC const Axis& axis() const { return m_axis; }
86
+
87
+ EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorConcatenationOp)
88
+ protected:
89
+ typename LhsXprType::Nested m_lhs_xpr;
90
+ typename RhsXprType::Nested m_rhs_xpr;
91
+ const Axis m_axis;
92
+ };
93
+
94
+
95
+ // Eval as rvalue
96
+ template<typename Axis, typename LeftArgType, typename RightArgType, typename Device>
97
+ struct TensorEvaluator<const TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device>
98
+ {
99
+ typedef TensorConcatenationOp<Axis, LeftArgType, RightArgType> XprType;
100
+ typedef typename XprType::Index Index;
101
+ static constexpr int NumDims = internal::array_size<typename TensorEvaluator<LeftArgType, Device>::Dimensions>::value;
102
+ static constexpr int RightNumDims = internal::array_size<typename TensorEvaluator<RightArgType, Device>::Dimensions>::value;
103
+ typedef DSizes<Index, NumDims> Dimensions;
104
+ typedef typename XprType::Scalar Scalar;
105
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
106
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
107
+ typedef StorageMemory<CoeffReturnType, Device> Storage;
108
+ typedef typename Storage::Type EvaluatorPointerType;
109
+ static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
110
+ enum {
111
+ IsAligned = false,
112
+ PacketAccess = TensorEvaluator<LeftArgType, Device>::PacketAccess &&
113
+ TensorEvaluator<RightArgType, Device>::PacketAccess,
114
+ BlockAccess = false,
115
+ PreferBlockAccess = TensorEvaluator<LeftArgType, Device>::PreferBlockAccess ||
116
+ TensorEvaluator<RightArgType, Device>::PreferBlockAccess,
117
+ RawAccess = false
118
+ };
119
+
120
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
121
+ typedef internal::TensorBlockNotImplemented TensorBlock;
122
+ //===--------------------------------------------------------------------===//
123
+
124
+ EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
125
+ : m_leftImpl(op.lhsExpression(), device), m_rightImpl(op.rhsExpression(), device), m_axis(op.axis())
126
+ {
127
+ EIGEN_STATIC_ASSERT((static_cast<int>(TensorEvaluator<LeftArgType, Device>::Layout) == static_cast<int>(TensorEvaluator<RightArgType, Device>::Layout) || NumDims == 1), YOU_MADE_A_PROGRAMMING_MISTAKE);
128
+ EIGEN_STATIC_ASSERT((NumDims == RightNumDims), YOU_MADE_A_PROGRAMMING_MISTAKE);
129
+ EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
130
+
131
+ eigen_assert(0 <= m_axis && m_axis < NumDims);
132
+ const Dimensions& lhs_dims = m_leftImpl.dimensions();
133
+ const Dimensions& rhs_dims = m_rightImpl.dimensions();
134
+ {
135
+ int i = 0;
136
+ for (; i < m_axis; ++i) {
137
+ eigen_assert(lhs_dims[i] > 0);
138
+ eigen_assert(lhs_dims[i] == rhs_dims[i]);
139
+ m_dimensions[i] = lhs_dims[i];
140
+ }
141
+ eigen_assert(lhs_dims[i] > 0); // Now i == m_axis.
142
+ eigen_assert(rhs_dims[i] > 0);
143
+ m_dimensions[i] = lhs_dims[i] + rhs_dims[i];
144
+ for (++i; i < NumDims; ++i) {
145
+ eigen_assert(lhs_dims[i] > 0);
146
+ eigen_assert(lhs_dims[i] == rhs_dims[i]);
147
+ m_dimensions[i] = lhs_dims[i];
148
+ }
149
+ }
150
+
151
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
152
+ m_leftStrides[0] = 1;
153
+ m_rightStrides[0] = 1;
154
+ m_outputStrides[0] = 1;
155
+
156
+ for (int j = 1; j < NumDims; ++j) {
157
+ m_leftStrides[j] = m_leftStrides[j-1] * lhs_dims[j-1];
158
+ m_rightStrides[j] = m_rightStrides[j-1] * rhs_dims[j-1];
159
+ m_outputStrides[j] = m_outputStrides[j-1] * m_dimensions[j-1];
160
+ }
161
+ } else {
162
+ m_leftStrides[NumDims - 1] = 1;
163
+ m_rightStrides[NumDims - 1] = 1;
164
+ m_outputStrides[NumDims - 1] = 1;
165
+
166
+ for (int j = NumDims - 2; j >= 0; --j) {
167
+ m_leftStrides[j] = m_leftStrides[j+1] * lhs_dims[j+1];
168
+ m_rightStrides[j] = m_rightStrides[j+1] * rhs_dims[j+1];
169
+ m_outputStrides[j] = m_outputStrides[j+1] * m_dimensions[j+1];
170
+ }
171
+ }
172
+ }
173
+
174
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
175
+
176
+ // TODO(phli): Add short-circuit memcpy evaluation if underlying data are linear?
177
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType)
178
+ {
179
+ m_leftImpl.evalSubExprsIfNeeded(NULL);
180
+ m_rightImpl.evalSubExprsIfNeeded(NULL);
181
+ return true;
182
+ }
183
+
184
+ EIGEN_STRONG_INLINE void cleanup()
185
+ {
186
+ m_leftImpl.cleanup();
187
+ m_rightImpl.cleanup();
188
+ }
189
+
190
+ // TODO(phli): attempt to speed this up. The integer divisions and modulo are slow.
191
+ // See CL/76180724 comments for more ideas.
192
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const
193
+ {
194
+ // Collect dimension-wise indices (subs).
195
+ array<Index, NumDims> subs;
196
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
197
+ for (int i = NumDims - 1; i > 0; --i) {
198
+ subs[i] = index / m_outputStrides[i];
199
+ index -= subs[i] * m_outputStrides[i];
200
+ }
201
+ subs[0] = index;
202
+ } else {
203
+ for (int i = 0; i < NumDims - 1; ++i) {
204
+ subs[i] = index / m_outputStrides[i];
205
+ index -= subs[i] * m_outputStrides[i];
206
+ }
207
+ subs[NumDims - 1] = index;
208
+ }
209
+
210
+ const Dimensions& left_dims = m_leftImpl.dimensions();
211
+ if (subs[m_axis] < left_dims[m_axis]) {
212
+ Index left_index;
213
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
214
+ left_index = subs[0];
215
+ EIGEN_UNROLL_LOOP
216
+ for (int i = 1; i < NumDims; ++i) {
217
+ left_index += (subs[i] % left_dims[i]) * m_leftStrides[i];
218
+ }
219
+ } else {
220
+ left_index = subs[NumDims - 1];
221
+ EIGEN_UNROLL_LOOP
222
+ for (int i = NumDims - 2; i >= 0; --i) {
223
+ left_index += (subs[i] % left_dims[i]) * m_leftStrides[i];
224
+ }
225
+ }
226
+ return m_leftImpl.coeff(left_index);
227
+ } else {
228
+ subs[m_axis] -= left_dims[m_axis];
229
+ const Dimensions& right_dims = m_rightImpl.dimensions();
230
+ Index right_index;
231
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
232
+ right_index = subs[0];
233
+ EIGEN_UNROLL_LOOP
234
+ for (int i = 1; i < NumDims; ++i) {
235
+ right_index += (subs[i] % right_dims[i]) * m_rightStrides[i];
236
+ }
237
+ } else {
238
+ right_index = subs[NumDims - 1];
239
+ EIGEN_UNROLL_LOOP
240
+ for (int i = NumDims - 2; i >= 0; --i) {
241
+ right_index += (subs[i] % right_dims[i]) * m_rightStrides[i];
242
+ }
243
+ }
244
+ return m_rightImpl.coeff(right_index);
245
+ }
246
+ }
247
+
248
+ // TODO(phli): Add a real vectorization.
249
+ template<int LoadMode>
250
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const
251
+ {
252
+ const int packetSize = PacketType<CoeffReturnType, Device>::size;
253
+ EIGEN_STATIC_ASSERT((packetSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE)
254
+ eigen_assert(index + packetSize - 1 < dimensions().TotalSize());
255
+
256
+ EIGEN_ALIGN_MAX CoeffReturnType values[packetSize];
257
+ EIGEN_UNROLL_LOOP
258
+ for (int i = 0; i < packetSize; ++i) {
259
+ values[i] = coeff(index+i);
260
+ }
261
+ PacketReturnType rslt = internal::pload<PacketReturnType>(values);
262
+ return rslt;
263
+ }
264
+
265
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
266
+ costPerCoeff(bool vectorized) const {
267
+ const double compute_cost = NumDims * (2 * TensorOpCost::AddCost<Index>() +
268
+ 2 * TensorOpCost::MulCost<Index>() +
269
+ TensorOpCost::DivCost<Index>() +
270
+ TensorOpCost::ModCost<Index>());
271
+ const double lhs_size = m_leftImpl.dimensions().TotalSize();
272
+ const double rhs_size = m_rightImpl.dimensions().TotalSize();
273
+ return (lhs_size / (lhs_size + rhs_size)) *
274
+ m_leftImpl.costPerCoeff(vectorized) +
275
+ (rhs_size / (lhs_size + rhs_size)) *
276
+ m_rightImpl.costPerCoeff(vectorized) +
277
+ TensorOpCost(0, 0, compute_cost);
278
+ }
279
+
280
+ EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; }
281
+
282
+ protected:
283
+ Dimensions m_dimensions;
284
+ array<Index, NumDims> m_outputStrides;
285
+ array<Index, NumDims> m_leftStrides;
286
+ array<Index, NumDims> m_rightStrides;
287
+ TensorEvaluator<LeftArgType, Device> m_leftImpl;
288
+ TensorEvaluator<RightArgType, Device> m_rightImpl;
289
+ const Axis m_axis;
290
+ };
291
+
292
+ // Eval as lvalue
293
+ template<typename Axis, typename LeftArgType, typename RightArgType, typename Device>
294
+ struct TensorEvaluator<TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device>
295
+ : public TensorEvaluator<const TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device>
296
+ {
297
+ typedef TensorEvaluator<const TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device> Base;
298
+ typedef TensorConcatenationOp<Axis, LeftArgType, RightArgType> XprType;
299
+ typedef typename Base::Dimensions Dimensions;
300
+ static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
301
+ enum {
302
+ IsAligned = false,
303
+ PacketAccess = TensorEvaluator<LeftArgType, Device>::PacketAccess &&
304
+ TensorEvaluator<RightArgType, Device>::PacketAccess,
305
+ BlockAccess = false,
306
+ PreferBlockAccess = TensorEvaluator<LeftArgType, Device>::PreferBlockAccess ||
307
+ TensorEvaluator<RightArgType, Device>::PreferBlockAccess,
308
+ RawAccess = false
309
+ };
310
+
311
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
312
+ typedef internal::TensorBlockNotImplemented TensorBlock;
313
+ //===--------------------------------------------------------------------===//
314
+
315
+ EIGEN_STRONG_INLINE TensorEvaluator(XprType& op, const Device& device)
316
+ : Base(op, device)
317
+ {
318
+ EIGEN_STATIC_ASSERT((static_cast<int>(Layout) == static_cast<int>(ColMajor)), YOU_MADE_A_PROGRAMMING_MISTAKE);
319
+ }
320
+
321
+ typedef typename XprType::Index Index;
322
+ typedef typename XprType::Scalar Scalar;
323
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
324
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
325
+
326
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const
327
+ {
328
+ // Collect dimension-wise indices (subs).
329
+ array<Index, Base::NumDims> subs;
330
+ for (int i = Base::NumDims - 1; i > 0; --i) {
331
+ subs[i] = index / this->m_outputStrides[i];
332
+ index -= subs[i] * this->m_outputStrides[i];
333
+ }
334
+ subs[0] = index;
335
+
336
+ const Dimensions& left_dims = this->m_leftImpl.dimensions();
337
+ if (subs[this->m_axis] < left_dims[this->m_axis]) {
338
+ Index left_index = subs[0];
339
+ for (int i = 1; i < Base::NumDims; ++i) {
340
+ left_index += (subs[i] % left_dims[i]) * this->m_leftStrides[i];
341
+ }
342
+ return this->m_leftImpl.coeffRef(left_index);
343
+ } else {
344
+ subs[this->m_axis] -= left_dims[this->m_axis];
345
+ const Dimensions& right_dims = this->m_rightImpl.dimensions();
346
+ Index right_index = subs[0];
347
+ for (int i = 1; i < Base::NumDims; ++i) {
348
+ right_index += (subs[i] % right_dims[i]) * this->m_rightStrides[i];
349
+ }
350
+ return this->m_rightImpl.coeffRef(right_index);
351
+ }
352
+ }
353
+
354
+ template <int StoreMode> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
355
+ void writePacket(Index index, const PacketReturnType& x) const
356
+ {
357
+ const int packetSize = PacketType<CoeffReturnType, Device>::size;
358
+ EIGEN_STATIC_ASSERT((packetSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE)
359
+ eigen_assert(index + packetSize - 1 < this->dimensions().TotalSize());
360
+
361
+ EIGEN_ALIGN_MAX CoeffReturnType values[packetSize];
362
+ internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
363
+ for (int i = 0; i < packetSize; ++i) {
364
+ coeffRef(index+i) = values[i];
365
+ }
366
+ }
367
+ };
368
+
369
+ } // end namespace Eigen
370
+
371
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONCATENATION_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContraction.h ADDED
@@ -0,0 +1,1018 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_H
12
+
13
+ #include "./InternalHeaderCheck.h"
14
+
15
+ namespace Eigen {
16
+
17
+ /** \class TensorContraction
18
+ * \ingroup CXX11_Tensor_Module
19
+ *
20
+ * \brief Tensor contraction class.
21
+ *
22
+ *
23
+ */
24
+ namespace internal {
25
+
26
+ template<typename Dimensions, typename LhsXprType, typename RhsXprType, typename OutputKernelType>
27
+ struct traits<TensorContractionOp<Dimensions, LhsXprType, RhsXprType, OutputKernelType> >
28
+ {
29
+ // Type promotion to handle the case where the types of the lhs and the rhs are different.
30
+ typedef typename gebp_traits<std::remove_const_t<typename LhsXprType::Scalar>,
31
+ std::remove_const_t<typename RhsXprType::Scalar>>::ResScalar Scalar;
32
+
33
+ typedef typename promote_storage_type<typename traits<LhsXprType>::StorageKind,
34
+ typename traits<RhsXprType>::StorageKind>::ret StorageKind;
35
+ typedef typename promote_index_type<typename traits<LhsXprType>::Index,
36
+ typename traits<RhsXprType>::Index>::type Index;
37
+ typedef typename LhsXprType::Nested LhsNested;
38
+ typedef typename RhsXprType::Nested RhsNested;
39
+ typedef std::remove_reference_t<LhsNested> LhsNested_;
40
+ typedef std::remove_reference_t<RhsNested> RhsNested_;
41
+
42
+ // From NumDims below.
43
+ static constexpr int NumDimensions = traits<LhsXprType>::NumDimensions + traits<RhsXprType>::NumDimensions - 2 * array_size<Dimensions>::value;
44
+ static constexpr int Layout = traits<LhsXprType>::Layout;
45
+ typedef std::conditional_t<Pointer_type_promotion<typename LhsXprType::Scalar, Scalar>::val,
46
+ typename traits<LhsXprType>::PointerType,
47
+ typename traits<RhsXprType>::PointerType>
48
+ PointerType;
49
+
50
+ enum {
51
+ Flags = 0
52
+ };
53
+ };
54
+
55
+ template<typename Dimensions, typename LhsXprType, typename RhsXprType, typename OutputKernelType>
56
+ struct eval<TensorContractionOp<Dimensions, LhsXprType, RhsXprType, OutputKernelType>, Eigen::Dense>
57
+ {
58
+ typedef const TensorContractionOp<Dimensions, LhsXprType, RhsXprType, OutputKernelType>& type;
59
+ };
60
+
61
+ template<typename Dimensions, typename LhsXprType, typename RhsXprType, typename OutputKernelType>
62
+ struct nested<TensorContractionOp<Dimensions, LhsXprType, RhsXprType, OutputKernelType>, 1, typename eval<TensorContractionOp<Dimensions, LhsXprType, RhsXprType, OutputKernelType> >::type>
63
+ {
64
+ typedef TensorContractionOp<Dimensions, LhsXprType, RhsXprType, OutputKernelType> type;
65
+ };
66
+
67
+ template<typename Indices_, typename LeftArgType_, typename RightArgType_, typename OutputKernelType_, typename Device_>
68
+ struct traits<TensorEvaluator<const TensorContractionOp<Indices_, LeftArgType_, RightArgType_, OutputKernelType_>, Device_> > {
69
+ typedef Indices_ Indices;
70
+ typedef LeftArgType_ LeftArgType;
71
+ typedef RightArgType_ RightArgType;
72
+ typedef OutputKernelType_ OutputKernelType;
73
+ typedef Device_ Device;
74
+
75
+ // From NumDims below.
76
+ static constexpr int NumDimensions = traits<LeftArgType_>::NumDimensions + traits<RightArgType_>::NumDimensions - 2 * array_size<Indices_>::value;
77
+ };
78
+
79
+ // Helper class to allocate and deallocate temporary memory for packed buffers.
80
+ template <typename LhsScalar, typename RhsScalar>
81
+ struct TensorContractionBlockMemAllocator {
82
+ typedef void* BlockMemHandle;
83
+
84
+ template <typename Device>
85
+ EIGEN_DEVICE_FUNC static BlockMemHandle allocate(Device& d, const Index bm,
86
+ const Index bk,
87
+ const Index bn,
88
+ LhsScalar** lhs_block,
89
+ RhsScalar** rhs_block) {
90
+ eigen_assert(lhs_block);
91
+ eigen_assert(rhs_block);
92
+ BlockSizes sz = ComputeLhsRhsBlockSizes(bm, bk, bn);
93
+ char* block_mem = static_cast<char*>(d.allocate(sz.lhs_size + sz.rhs_size));
94
+ *lhs_block = static_cast<LhsScalar*>(static_cast<void*>(block_mem));
95
+ *rhs_block = static_cast<RhsScalar*>(static_cast<void*>(block_mem + sz.lhs_size));
96
+ return block_mem;
97
+ }
98
+
99
+ template <typename Device>
100
+ EIGEN_DEVICE_FUNC static BlockMemHandle allocateSlices(
101
+ Device& d, const Index bm, const Index bk, const Index bn,
102
+ const Index num_lhs, const Index num_rhs, const Index num_slices,
103
+ std::vector<LhsScalar*>* lhs_blocks,
104
+ std::vector<RhsScalar*>* rhs_blocks) {
105
+ eigen_assert(num_slices > 0);
106
+ eigen_assert(num_lhs >= 0 && num_rhs >= 0);
107
+ eigen_assert(num_lhs == 0 || lhs_blocks);
108
+ eigen_assert(num_rhs == 0 || rhs_blocks);
109
+ BlockSizes sz = ComputeLhsRhsBlockSizes(bm, bk, bn);
110
+ void* block_mem = d.allocate(
111
+ (num_lhs * sz.lhs_size + num_rhs * sz.rhs_size) * num_slices);
112
+ eigen_assert(block_mem);
113
+ char* mem = static_cast<char*>(block_mem);
114
+
115
+ for (Index x = 0; x < num_slices; x++) {
116
+ if (num_lhs > 0) lhs_blocks[x].resize(num_lhs);
117
+ for (Index m = 0; m < num_lhs; m++) {
118
+ lhs_blocks[x][m] = static_cast<LhsScalar*>(static_cast<void*>(mem));
119
+ mem += sz.lhs_size;
120
+ }
121
+ if (num_rhs > 0) rhs_blocks[x].resize(num_rhs);
122
+ for (Index n = 0; n < num_rhs; n++) {
123
+ rhs_blocks[x][n] = static_cast<RhsScalar*>(static_cast<void*>(mem));
124
+ mem += sz.rhs_size;
125
+ }
126
+ }
127
+
128
+ return block_mem;
129
+ }
130
+
131
+ template <typename Device>
132
+ EIGEN_DEVICE_FUNC static void deallocate(Device& d, BlockMemHandle handle) {
133
+ d.deallocate(handle);
134
+ }
135
+
136
+ private:
137
+ struct BlockSizes {
138
+ Index lhs_size;
139
+ Index rhs_size;
140
+ };
141
+ EIGEN_DEVICE_FUNC static BlockSizes ComputeLhsRhsBlockSizes(const Index bm,
142
+ const Index bk,
143
+ const Index bn) {
144
+ Index align = numext::maxi(EIGEN_MAX_ALIGN_BYTES, 1);
145
+ BlockSizes sz;
146
+ sz.lhs_size = divup<Index>(bm * bk * sizeof(LhsScalar), align) * align;
147
+ sz.rhs_size = divup<Index>(bn * bk * sizeof(RhsScalar), align) * align;
148
+ return sz;
149
+ }
150
+ };
151
+
152
+ // WARNING: In this code we assume that Lhs and Rhs tensor expressions are in
153
+ // ColMajor storage order. This property is guaranteed by the
154
+ // TensorContractionOp evaluator. TensorContractionKernel specifies how we pack
155
+ // blocks of Lhs and Rhs tensor expressions, and how we invoke matrix
156
+ // multiplication for these blocks. Default tensor contraction uses
157
+ // gemm_pack_rhs, gemm_pack_lhs and gebp_kernel from Eigen Core (see
158
+ // GeneralBlocPanelKernel.h for details).
159
+ //
160
+ // By specializing contraction kernels we can use other low level libraries to
161
+ // perform matrix multiplication, and still rely on Eigen contraction evaluator.
162
+ // This also includes full support in TensorContractionThreadPool, assuming that
163
+ // underlying gemm do not use it's own threading.
164
+ //
165
+ // - ResScalar/LhsScalar/RhsScalar - scalar type for the result of
166
+ // multiplication, lhs tensor and rhs tensor respectively.
167
+ //
168
+ // - StorageIndex - index type for the tensor expressions. In practice almost
169
+ // always is Eigen::Index.
170
+ //
171
+ // - OutputMapper provides access to the memory of the output matrix. In
172
+ // practice it's always column major blas_data_mapper (it must be of ResScalar
173
+ // type).
174
+ //
175
+ // - LhsMapper/RhsMapper similarly to blas_data_mapper provide a two dimensional
176
+ // view into the Lhs/Rhs tensor expressions. In practice it's
177
+ // TensorContractionInputMapper, or some specialization of it based on the
178
+ // type of tensor expression (e.g. TensorImagePatchOp has optimized input
179
+ // mapper).
180
+ template <typename ResScalar, typename LhsScalar, typename RhsScalar,
181
+ typename StorageIndex, typename OutputMapper, typename LhsMapper,
182
+ typename RhsMapper>
183
+ struct TensorContractionKernel {
184
+ // True if `invoke()` supports `beta` in `C <- alpha * A * B + beta * C`
185
+ // (otherwise beta should be always equal to 1).
186
+ enum { HasBeta = false };
187
+
188
+ EIGEN_DEVICE_FUNC
189
+ TensorContractionKernel(StorageIndex m_, StorageIndex k_, StorageIndex n_,
190
+ StorageIndex bm_, StorageIndex bk_, StorageIndex bn_)
191
+ : m(m_), k(k_), n(n_), bm(bm_), bk(bk_), bn(bn_) {}
192
+
193
+ // Pack blocks of Lhs and Rhs into contiguous blocks in memory.
194
+ typedef LhsScalar* LhsBlock;
195
+ typedef RhsScalar* RhsBlock;
196
+
197
+ // Packed Lhs/Rhs block memory allocator.
198
+ typedef TensorContractionBlockMemAllocator<LhsScalar, RhsScalar>
199
+ BlockMemAllocator;
200
+ typedef typename BlockMemAllocator::BlockMemHandle BlockMemHandle;
201
+
202
+ typedef typename internal::gebp_traits<LhsScalar, RhsScalar> Traits;
203
+
204
+ typedef internal::gemm_pack_lhs<
205
+ LhsScalar, StorageIndex, typename LhsMapper::SubMapper, Traits::mr,
206
+ Traits::LhsProgress, typename Traits::LhsPacket4Packing, ColMajor>
207
+ LhsPacker;
208
+
209
+ typedef internal::gemm_pack_rhs<RhsScalar, StorageIndex,
210
+ typename RhsMapper::SubMapper, Traits::nr,
211
+ ColMajor>
212
+ RhsPacker;
213
+
214
+ typedef internal::gebp_kernel<LhsScalar, RhsScalar, StorageIndex,
215
+ OutputMapper, Traits::mr, Traits::nr,
216
+ /*ConjugateLhs*/ false, /*ConjugateRhs*/ false>
217
+ GebpKernel;
218
+
219
+ template <typename Device>
220
+ EIGEN_DEVICE_FUNC BlockMemHandle allocate(Device& d, LhsBlock* lhs_block,
221
+ RhsBlock* rhs_block) {
222
+ return BlockMemAllocator::allocate(d, bm, bk, bn, lhs_block, rhs_block);
223
+ }
224
+
225
+ template <typename Device>
226
+ EIGEN_DEVICE_FUNC BlockMemHandle allocateSlices(
227
+ Device& d, const StorageIndex num_lhs, const StorageIndex num_rhs,
228
+ const StorageIndex num_slices, std::vector<LhsBlock>* lhs_blocks,
229
+ std::vector<RhsBlock>* rhs_blocks) {
230
+ return BlockMemAllocator::allocateSlices(
231
+ d, bm, bk, bn, num_lhs, num_rhs, num_slices, lhs_blocks, rhs_blocks);
232
+ }
233
+
234
+ template <typename Device>
235
+ EIGEN_DEVICE_FUNC static void deallocate(Device& d, BlockMemHandle handle) {
236
+ BlockMemAllocator::deallocate(d, handle);
237
+ }
238
+
239
+ EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE void packLhs(
240
+ LhsBlock* lhsBlock, const typename LhsMapper::SubMapper& data_mapper,
241
+ const StorageIndex depth, const StorageIndex rows) {
242
+ LhsPacker()(*lhsBlock, data_mapper, depth, rows, /*stride*/ 0,
243
+ /*offset*/ 0);
244
+ }
245
+
246
+ EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE void packRhs(
247
+ RhsBlock* rhsBlock, const typename RhsMapper::SubMapper& data_mapper,
248
+ const StorageIndex depth, const StorageIndex cols) {
249
+ RhsPacker()(*rhsBlock, data_mapper, depth, cols);
250
+ }
251
+
252
+ EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE void invoke(
253
+ const OutputMapper& output_mapper, const LhsBlock& lhsBlock,
254
+ const RhsBlock& rhsBlock, const StorageIndex rows,
255
+ const StorageIndex depth, const StorageIndex cols,
256
+ const ResScalar alpha, const ResScalar beta) {
257
+ // Default GEBP kernel does not support beta.
258
+ eigen_assert(beta == ResScalar(1));
259
+ static const int kComputeStrideFromBlockDimensions = -1;
260
+ GebpKernel()(output_mapper, lhsBlock, rhsBlock, rows, depth, cols, alpha,
261
+ /*strideA*/ kComputeStrideFromBlockDimensions,
262
+ /*strideB*/ kComputeStrideFromBlockDimensions,
263
+ /*offsetA*/ 0, /*offsetB*/ 0);
264
+ }
265
+
266
+ private:
267
+ // These are dimensions of the original Tensors, and selected block sizes. The
268
+ // actual block sizes passed to all function above might be smaller because of
269
+ // the partial blocks at the end.
270
+ const StorageIndex m;
271
+ const StorageIndex k;
272
+ const StorageIndex n;
273
+ const StorageIndex bm;
274
+ const StorageIndex bk;
275
+ const StorageIndex bn;
276
+ };
277
+
278
+ } // end namespace internal
279
+
280
+ // Tensor contraction params that should enable to get from output matrix
281
+ // 2-dimensional coordinates to the output tensor dimensions.
282
+ struct TensorContractionParams {
283
+ // TensorContraction evaluator assumes that both tensors are in ColMajor
284
+ // layout, if tensors are in RowMajor evaluator swap lhs with rhs.
285
+ bool swapped_arguments;
286
+ };
287
+
288
+ // Output kernel allows to fuse operations into the tensor contraction.
289
+ //
290
+ // Examples:
291
+ // 1. Elementwise Relu transformation following Conv2D.
292
+ // 2. AddBias to the Conv2D output channels dimension.
293
+ //
294
+ // The NoOpOutputKernel implements an output kernel that does absolutely nothing.
295
+ struct NoOpOutputKernel {
296
+ /**
297
+ * Tensor contraction evaluator calls this kernel after finishing each block
298
+ * of output matrix. Output blocks belong to the 2-dimensional output tensor.
299
+ *
300
+ * TensorContractionParams contains contraction dimensions information
301
+ * required to map output 2-d space into the expected output tensor space
302
+ * (potentially higher dimensional).
303
+ *
304
+ * \param[in] output_mapper Access to output tensor memory
305
+ * \param[in] params Tensor contraction parameters
306
+ * \param[in] i Index of a first row available through output_mapper
307
+ * \param[in] j Index of a first column available through output_mapper
308
+ * \param[in] num_rows Number of available rows
309
+ * \param[in] num_cols Number of available columns
310
+ */
311
+ template <typename Index, typename Scalar>
312
+ EIGEN_ALWAYS_INLINE void operator()(
313
+ const internal::blas_data_mapper<Scalar, Index, ColMajor>& output_mapper,
314
+ const TensorContractionParams& params, Index i,
315
+ Index j, Index num_rows, Index num_cols) const {
316
+ EIGEN_UNUSED_VARIABLE(output_mapper);
317
+ EIGEN_UNUSED_VARIABLE(params);
318
+ EIGEN_UNUSED_VARIABLE(i);
319
+ EIGEN_UNUSED_VARIABLE(j);
320
+ EIGEN_UNUSED_VARIABLE(num_rows);
321
+ EIGEN_UNUSED_VARIABLE(num_cols);
322
+ }
323
+ };
324
+
325
+ template<typename Indices, typename LhsXprType, typename RhsXprType, typename OutputKernelType = const NoOpOutputKernel>
326
+ class TensorContractionOp : public TensorBase<TensorContractionOp<Indices, LhsXprType, RhsXprType, OutputKernelType>, ReadOnlyAccessors>
327
+ {
328
+ public:
329
+ typedef typename Eigen::internal::traits<TensorContractionOp>::Scalar Scalar;
330
+ typedef typename internal::gebp_traits<typename LhsXprType::CoeffReturnType,
331
+ typename RhsXprType::CoeffReturnType>::ResScalar CoeffReturnType;
332
+ typedef typename Eigen::internal::nested<TensorContractionOp>::type Nested;
333
+ typedef typename Eigen::internal::traits<TensorContractionOp>::StorageKind StorageKind;
334
+ typedef typename Eigen::internal::traits<TensorContractionOp>::Index Index;
335
+
336
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorContractionOp(
337
+ const LhsXprType& lhs, const RhsXprType& rhs, const Indices& dims,
338
+ const OutputKernelType& output_kernel = OutputKernelType())
339
+ : m_lhs_xpr(lhs), m_rhs_xpr(rhs), m_indices(dims),
340
+ m_output_kernel(output_kernel) {}
341
+
342
+ EIGEN_DEVICE_FUNC
343
+ const Indices& indices() const { return m_indices; }
344
+
345
+ /** \returns the nested expressions */
346
+ EIGEN_DEVICE_FUNC
347
+ const internal::remove_all_t<typename LhsXprType::Nested>&
348
+ lhsExpression() const { return m_lhs_xpr; }
349
+
350
+ EIGEN_DEVICE_FUNC
351
+ const internal::remove_all_t<typename RhsXprType::Nested>&
352
+ rhsExpression() const { return m_rhs_xpr; }
353
+
354
+ EIGEN_DEVICE_FUNC
355
+ const OutputKernelType& outputKernel() const { return m_output_kernel; }
356
+
357
+ protected:
358
+ typename LhsXprType::Nested m_lhs_xpr;
359
+ typename RhsXprType::Nested m_rhs_xpr;
360
+ const Indices m_indices;
361
+ const OutputKernelType m_output_kernel;
362
+ };
363
+
364
+ template<typename Derived>
365
+ struct TensorContractionEvaluatorBase {
366
+ typedef typename internal::traits<Derived>::Indices Indices;
367
+ typedef typename internal::traits<Derived>::LeftArgType LeftArgType;
368
+ typedef typename internal::traits<Derived>::RightArgType RightArgType;
369
+ typedef typename internal::traits<Derived>::OutputKernelType OutputKernelType;
370
+ typedef typename internal::traits<Derived>::Device Device;
371
+
372
+ typedef TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType> XprType;
373
+ typedef std::remove_const_t<typename XprType::Scalar> Scalar;
374
+ typedef typename XprType::Index Index;
375
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
376
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
377
+ typedef StorageMemory<Scalar, Device> Storage;
378
+ typedef typename Storage::Type EvaluatorPointerType;
379
+
380
+ static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
381
+ enum {
382
+ IsAligned = true,
383
+ PacketAccess = (PacketType<CoeffReturnType, Device>::size > 1),
384
+ BlockAccess = false,
385
+ PreferBlockAccess = false,
386
+ CoordAccess = false, // to be implemented
387
+ RawAccess = true
388
+ };
389
+
390
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
391
+ typedef internal::TensorBlockNotImplemented TensorBlock;
392
+ //===--------------------------------------------------------------------===//
393
+
394
+ // Most of the code is assuming that both input tensors are ColMajor. If the
395
+ // inputs are RowMajor, we will "cheat" by swapping the LHS and RHS:
396
+ // If we want to compute A * B = C, where A is LHS and B is RHS, the code
397
+ // will pretend B is LHS and A is RHS.
398
+ typedef std::conditional_t<
399
+ static_cast<int>(Layout) == static_cast<int>(ColMajor), LeftArgType, RightArgType> EvalLeftArgType;
400
+ typedef std::conditional_t<
401
+ static_cast<int>(Layout) == static_cast<int>(ColMajor), RightArgType, LeftArgType> EvalRightArgType;
402
+
403
+ typedef TensorEvaluator<EvalLeftArgType, Device> LeftEvaluatorType;
404
+ typedef TensorEvaluator<EvalRightArgType, Device> RightEvaluatorType;
405
+
406
+ static constexpr int LDims =
407
+ internal::array_size<typename TensorEvaluator<EvalLeftArgType, Device>::Dimensions>::value;
408
+ static constexpr int RDims =
409
+ internal::array_size<typename TensorEvaluator<EvalRightArgType, Device>::Dimensions>::value;
410
+ static constexpr int ContractDims = internal::array_size<Indices>::value;
411
+ static constexpr int NumDims = LDims + RDims - 2 * ContractDims;
412
+
413
+ typedef array<Index, ContractDims> contract_t;
414
+ typedef array<Index, LDims - ContractDims> left_nocontract_t;
415
+ typedef array<Index, RDims - ContractDims> right_nocontract_t;
416
+
417
+ typedef DSizes<Index, NumDims> Dimensions;
418
+
419
+ EIGEN_STRONG_INLINE
420
+ TensorContractionEvaluatorBase(const XprType& op, const Device& device)
421
+ : m_leftImpl(choose(Cond<static_cast<int>(Layout) == static_cast<int>(ColMajor)>(),
422
+ op.lhsExpression(), op.rhsExpression()), device),
423
+ m_rightImpl(choose(Cond<static_cast<int>(Layout) == static_cast<int>(ColMajor)>(),
424
+ op.rhsExpression(), op.lhsExpression()), device),
425
+ m_device(device),
426
+ m_output_kernel(op.outputKernel()),
427
+ m_result(NULL) {
428
+ EIGEN_STATIC_ASSERT((static_cast<int>(TensorEvaluator<LeftArgType, Device>::Layout) ==
429
+ static_cast<int>(TensorEvaluator<RightArgType, Device>::Layout)),
430
+ YOU_MADE_A_PROGRAMMING_MISTAKE);
431
+
432
+
433
+ DSizes<Index, LDims> eval_left_dims;
434
+ DSizes<Index, RDims> eval_right_dims;
435
+ array<IndexPair<Index>, ContractDims> eval_op_indices;
436
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
437
+ // For ColMajor, we keep using the existing dimensions
438
+ for (int i = 0; i < LDims; i++) {
439
+ eval_left_dims[i] = m_leftImpl.dimensions()[i];
440
+ }
441
+ for (int i = 0; i < RDims; i++) {
442
+ eval_right_dims[i] = m_rightImpl.dimensions()[i];
443
+ }
444
+ // We keep the pairs of contracting indices.
445
+ for (int i = 0; i < ContractDims; i++) {
446
+ eval_op_indices[i].first = op.indices()[i].first;
447
+ eval_op_indices[i].second = op.indices()[i].second;
448
+ }
449
+ } else {
450
+ // For RowMajor, we need to reverse the existing dimensions
451
+ for (int i = 0; i < LDims; i++) {
452
+ eval_left_dims[i] = m_leftImpl.dimensions()[LDims - i - 1];
453
+ }
454
+ for (int i = 0; i < RDims; i++) {
455
+ eval_right_dims[i] = m_rightImpl.dimensions()[RDims - i - 1];
456
+ }
457
+ // We need to flip all the pairs of contracting indices as well as
458
+ // reversing the dimensions.
459
+ for (int i = 0; i < ContractDims; i++) {
460
+ eval_op_indices[i].first = LDims - 1 - op.indices()[ContractDims - 1 - i].second;
461
+ eval_op_indices[i].second = RDims - 1 - op.indices()[ContractDims - 1 - i].first;
462
+ }
463
+ }
464
+
465
+ // Check for duplicate axes and make sure the first index in eval_op_indices
466
+ // is increasing. Using O(n^2) sorting is OK since ContractDims is small
467
+ for (int i = 0; i < ContractDims; i++) {
468
+ for (int j = i + 1; j < ContractDims; j++) {
469
+ eigen_assert(eval_op_indices[j].first != eval_op_indices[i].first &&
470
+ eval_op_indices[j].second != eval_op_indices[i].second &&
471
+ "contraction axes should be unique");
472
+ if (eval_op_indices[j].first < eval_op_indices[i].first) {
473
+ numext::swap(eval_op_indices[j], eval_op_indices[i]);
474
+ }
475
+ }
476
+ }
477
+
478
+ array<Index, LDims> lhs_strides;
479
+ lhs_strides[0] = 1;
480
+ for (int i = 0; i < LDims-1; ++i) {
481
+ lhs_strides[i+1] = lhs_strides[i] * eval_left_dims[i];
482
+ }
483
+
484
+ array<Index, RDims> rhs_strides;
485
+ rhs_strides[0] = 1;
486
+ for (int i = 0; i < RDims-1; ++i) {
487
+ rhs_strides[i+1] = rhs_strides[i] * eval_right_dims[i];
488
+ }
489
+
490
+ if (m_i_strides.size() > 0) m_i_strides[0] = 1;
491
+ if (m_j_strides.size() > 0) m_j_strides[0] = 1;
492
+ if (m_k_strides.size() > 0) m_k_strides[0] = 1;
493
+
494
+ m_i_size = 1;
495
+ m_j_size = 1;
496
+ m_k_size = 1;
497
+
498
+ // To compute the dimension, we simply concatenate the non-contracting
499
+ // dimensions of the left and then the right tensor. Additionally, we also
500
+ // compute the strides corresponding to the left non-contracting
501
+ // dimensions and right non-contracting dimensions.
502
+ m_lhs_inner_dim_contiguous = true;
503
+ int dim_idx = 0;
504
+ Index nocontract_idx = 0;
505
+
506
+ for (int i = 0; i < LDims; i++) {
507
+ // find if we are contracting on index i of left tensor
508
+ bool contracting = false;
509
+ for (int j = 0; j < ContractDims; j++) {
510
+ if (eval_op_indices[j].first == i) {
511
+ contracting = true;
512
+ break;
513
+ }
514
+ }
515
+ if (!contracting) {
516
+ // add dimension size to output dimensions
517
+ m_dimensions[dim_idx] = eval_left_dims[i];
518
+ m_left_nocontract_strides[nocontract_idx] = lhs_strides[i];
519
+ if (dim_idx != i) {
520
+ m_lhs_inner_dim_contiguous = false;
521
+ }
522
+ if (nocontract_idx+1 < internal::array_size<left_nocontract_t>::value) {
523
+ m_i_strides[nocontract_idx+1] =
524
+ m_i_strides[nocontract_idx] * eval_left_dims[i];
525
+ } else {
526
+ m_i_size = m_i_strides[nocontract_idx] * eval_left_dims[i];
527
+ }
528
+ dim_idx++;
529
+ nocontract_idx++;
530
+ }
531
+ }
532
+
533
+ nocontract_idx = 0;
534
+ for (int i = 0; i < RDims; i++) {
535
+ bool contracting = false;
536
+ // find if we are contracting on index i of right tensor
537
+ for (int j = 0; j < ContractDims; j++) {
538
+ if (eval_op_indices[j].second == i) {
539
+ contracting = true;
540
+ break;
541
+ }
542
+ }
543
+ if (!contracting) {
544
+ m_dimensions[dim_idx] = eval_right_dims[i];
545
+ if (nocontract_idx+1 < internal::array_size<right_nocontract_t>::value) {
546
+ m_j_strides[nocontract_idx+1] =
547
+ m_j_strides[nocontract_idx] * eval_right_dims[i];
548
+ } else {
549
+ m_j_size = m_j_strides[nocontract_idx] * eval_right_dims[i];
550
+ }
551
+ m_right_nocontract_strides[nocontract_idx] = rhs_strides[i];
552
+ dim_idx++;
553
+ nocontract_idx++;
554
+ }
555
+ }
556
+
557
+ // Now compute the strides corresponding to the contracting dimensions. We
558
+ // assumed above that non-contracting axes are represented in the same order
559
+ // in the matrix as they are in the tensor. This is not the case for
560
+ // contracting axes. As the contracting axes must be of the same size in
561
+ // each tensor, we'll only look at the first tensor here.
562
+ m_rhs_inner_dim_contiguous = true;
563
+ m_rhs_inner_dim_reordered = false;
564
+ for (int i = 0; i < ContractDims; i++) {
565
+ Index left = eval_op_indices[i].first;
566
+ Index right = eval_op_indices[i].second;
567
+
568
+ Index size = eval_left_dims[left];
569
+ eigen_assert(size == eval_right_dims[right] &&
570
+ "Contraction axes must be same size");
571
+
572
+ if (i+1 < static_cast<int>(internal::array_size<contract_t>::value)) {
573
+ m_k_strides[i+1] = m_k_strides[i] * size;
574
+ } else {
575
+ m_k_size = m_k_strides[i] * size;
576
+ }
577
+ m_left_contracting_strides[i] = lhs_strides[left];
578
+ m_right_contracting_strides[i] = rhs_strides[right];
579
+
580
+ if (i > 0 && right < eval_op_indices[i-1].second) {
581
+ m_rhs_inner_dim_reordered = true;
582
+ }
583
+ if (right != i) {
584
+ m_rhs_inner_dim_contiguous = false;
585
+ }
586
+ }
587
+
588
+ // If the layout is RowMajor, we need to reverse the m_dimensions
589
+ if (static_cast<int>(Layout) == static_cast<int>(RowMajor)) {
590
+ for (int i = 0, j = NumDims - 1; i < j; i++, j--) {
591
+ numext::swap(m_dimensions[i], m_dimensions[j]);
592
+ }
593
+ }
594
+
595
+ // A set of parameters that will allow output kernel to get from output
596
+ // tensor dimensions (i, j) into the original tensor dimensions.
597
+ // TODO(ezhulenev): Add parameters required to infer output tensor index for
598
+ // more complex contractions than 2x2 on internal dimension.
599
+ m_tensor_contraction_params.swapped_arguments = static_cast<int>(Layout) == RowMajor;
600
+ }
601
+
602
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
603
+
604
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) {
605
+ m_leftImpl.evalSubExprsIfNeeded(NULL);
606
+ m_rightImpl.evalSubExprsIfNeeded(NULL);
607
+ if (data) {
608
+ evalTo(data);
609
+ return false;
610
+ } else {
611
+ m_result = static_cast<EvaluatorPointerType>(m_device.allocate(dimensions().TotalSize() * sizeof(Scalar)));
612
+ evalTo(m_result);
613
+ return true;
614
+ }
615
+ }
616
+
617
+ #ifdef EIGEN_USE_THREADS
618
+ template <typename EvalSubExprsCallback>
619
+ EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(
620
+ EvaluatorPointerType dest, EvalSubExprsCallback done) {
621
+ m_leftImpl.evalSubExprsIfNeededAsync(nullptr, [this, done, dest](bool) {
622
+ m_rightImpl.evalSubExprsIfNeededAsync(nullptr, [this, done, dest](bool) {
623
+ if (dest) {
624
+ evalToAsync(dest, [done]() { done(false); });
625
+ } else {
626
+ m_result = static_cast<EvaluatorPointerType>(
627
+ m_device.allocate(dimensions().TotalSize() * sizeof(Scalar)));
628
+ evalToAsync(m_result, [done]() { done(true); });
629
+ }
630
+ });
631
+ });
632
+ }
633
+ #endif // EIGEN_USE_THREADS
634
+
635
+ #ifndef TENSOR_CONTRACTION_DISPATCH
636
+ #define TENSOR_CONTRACTION_DISPATCH(METHOD, ALIGNMENT, ARGS) \
637
+ if (this->m_lhs_inner_dim_contiguous) { \
638
+ if (this->m_rhs_inner_dim_contiguous) { \
639
+ if (this->m_rhs_inner_dim_reordered) { \
640
+ METHOD<true, true, true, ALIGNMENT> ARGS; \
641
+ } else { \
642
+ METHOD<true, true, false, ALIGNMENT> ARGS; \
643
+ } \
644
+ } else { \
645
+ if (this->m_rhs_inner_dim_reordered) { \
646
+ METHOD<true, false, true, ALIGNMENT> ARGS; \
647
+ } else { \
648
+ METHOD<true, false, false, ALIGNMENT> ARGS; \
649
+ } \
650
+ } \
651
+ } else { \
652
+ if (this->m_rhs_inner_dim_contiguous) { \
653
+ if (this->m_rhs_inner_dim_reordered) { \
654
+ METHOD<false, true, true, ALIGNMENT> ARGS; \
655
+ } else { \
656
+ METHOD<false, true, false, ALIGNMENT> ARGS; \
657
+ } \
658
+ } else { \
659
+ if (this->m_rhs_inner_dim_reordered) { \
660
+ METHOD<false, false, true, ALIGNMENT> ARGS; \
661
+ } else { \
662
+ METHOD<false, false, false, ALIGNMENT> ARGS; \
663
+ } \
664
+ } \
665
+ }
666
+ #endif
667
+
668
+ #ifndef TENSOR_CONTRACTION_ASYNC_DISPATCH
669
+ #define TENSOR_CONTRACTION_ASYNC_DISPATCH(METHOD, DONE, ALIGNMENT, ARGS, FN) \
670
+ if (this->m_lhs_inner_dim_contiguous) { \
671
+ if (this->m_rhs_inner_dim_contiguous) { \
672
+ if (this->m_rhs_inner_dim_reordered) { \
673
+ (new METHOD<DONE, true, true, true, ALIGNMENT> ARGS)->FN; \
674
+ } else { \
675
+ (new METHOD<DONE, true, true, false, ALIGNMENT> ARGS)->FN; \
676
+ } \
677
+ } else { \
678
+ if (this->m_rhs_inner_dim_reordered) { \
679
+ (new METHOD<DONE, true, false, true, ALIGNMENT> ARGS)->FN; \
680
+ } else { \
681
+ (new METHOD<DONE, true, false, false, ALIGNMENT> ARGS)->FN; \
682
+ } \
683
+ } \
684
+ } else { \
685
+ if (this->m_rhs_inner_dim_contiguous) { \
686
+ if (this->m_rhs_inner_dim_reordered) { \
687
+ (new METHOD<DONE, false, true, true, ALIGNMENT> ARGS)->FN; \
688
+ } else { \
689
+ (new METHOD<DONE, false, true, false, ALIGNMENT> ARGS)->FN; \
690
+ } \
691
+ } else { \
692
+ if (this->m_rhs_inner_dim_reordered) { \
693
+ (new METHOD<DONE, false, false, true, ALIGNMENT> ARGS)->FN; \
694
+ } else { \
695
+ (new METHOD<DONE, false, false, false, ALIGNMENT> ARGS)->FN; \
696
+ } \
697
+ } \
698
+ }
699
+ #endif
700
+
701
+ EIGEN_DEVICE_FUNC void evalTo(Scalar* buffer) const {
702
+ static_cast<const Derived*>(this)->template evalProduct<Unaligned>(buffer);
703
+ }
704
+
705
+ #ifdef EIGEN_USE_THREADS
706
+ template <typename EvalToCallback>
707
+ void evalToAsync(Scalar* buffer, EvalToCallback done) const {
708
+ static_cast<const Derived*>(this)
709
+ ->template evalProductAsync<EvalToCallback, Unaligned>(buffer,
710
+ std::move(done));
711
+ }
712
+ #endif // EIGEN_USE_THREADS
713
+
714
+ template <bool lhs_inner_dim_contiguous, bool rhs_inner_dim_contiguous,
715
+ bool rhs_inner_dim_reordered, int Alignment>
716
+ void evalProductSequential(Scalar* buffer) const {
717
+ if (this->m_j_size == 1) {
718
+ this->template evalGemv<lhs_inner_dim_contiguous,
719
+ rhs_inner_dim_contiguous, rhs_inner_dim_reordered,
720
+ Alignment>(buffer);
721
+ } else {
722
+ this->template evalGemm<lhs_inner_dim_contiguous, rhs_inner_dim_contiguous,
723
+ rhs_inner_dim_reordered, Alignment>(buffer);
724
+ }
725
+ }
726
+
727
+ template <bool lhs_inner_dim_contiguous, bool rhs_inner_dim_contiguous, bool rhs_inner_dim_reordered, int Alignment>
728
+ #if !defined(EIGEN_HIPCC)
729
+ EIGEN_DEVICE_FUNC
730
+ #endif
731
+ void evalGemv(Scalar* buffer) const {
732
+ const Index rows = m_i_size;
733
+ const Index cols = m_k_size;
734
+
735
+ typedef std::remove_const_t<typename EvalLeftArgType::Scalar> LhsScalar;
736
+ typedef std::remove_const_t<typename EvalRightArgType::Scalar> RhsScalar;
737
+ typedef TensorEvaluator<EvalLeftArgType, Device> LeftEvaluator;
738
+ typedef TensorEvaluator<EvalRightArgType, Device> RightEvaluator;
739
+ const Index lhs_packet_size = internal::unpacket_traits<typename LeftEvaluator::PacketReturnType>::size;
740
+ const Index rhs_packet_size = internal::unpacket_traits<typename RightEvaluator::PacketReturnType>::size;
741
+ const int lhs_alignment = LeftEvaluator::IsAligned ? Aligned : Unaligned;
742
+ const int rhs_alignment = RightEvaluator::IsAligned ? Aligned : Unaligned;
743
+ typedef internal::TensorContractionInputMapper<LhsScalar, Index, internal::Lhs,
744
+ LeftEvaluator, left_nocontract_t,
745
+ contract_t, lhs_packet_size,
746
+ lhs_inner_dim_contiguous,
747
+ false, lhs_alignment> LhsMapper;
748
+
749
+ typedef internal::TensorContractionInputMapper<RhsScalar, Index, internal::Rhs,
750
+ RightEvaluator, right_nocontract_t,
751
+ contract_t, rhs_packet_size,
752
+ rhs_inner_dim_contiguous,
753
+ rhs_inner_dim_reordered, rhs_alignment> RhsMapper;
754
+
755
+ LhsMapper lhs(m_leftImpl, m_left_nocontract_strides, m_i_strides,
756
+ m_left_contracting_strides, m_k_strides);
757
+ RhsMapper rhs(m_rightImpl, m_right_nocontract_strides, m_j_strides,
758
+ m_right_contracting_strides, m_k_strides);
759
+
760
+ const Scalar alpha(1);
761
+ const Index resIncr(1);
762
+
763
+ // zero out the result buffer (which must be of size at least rows * sizeof(Scalar)
764
+ m_device.fill(buffer, buffer + rows, Scalar(0));
765
+
766
+ internal::general_matrix_vector_product<Index,LhsScalar,LhsMapper,ColMajor,false,RhsScalar,RhsMapper,false>::run(
767
+ rows, cols, lhs, rhs,
768
+ buffer, resIncr, alpha);
769
+
770
+ typedef internal::blas_data_mapper<Scalar, Index, ColMajor> OutputMapper;
771
+ m_output_kernel(OutputMapper(buffer, rows), m_tensor_contraction_params,
772
+ static_cast<Index>(0), static_cast<Index>(0), rows,
773
+ static_cast<Index>(1));
774
+ }
775
+
776
+ template <bool lhs_inner_dim_contiguous, bool rhs_inner_dim_contiguous, bool rhs_inner_dim_reordered, int Alignment>
777
+ #if !defined(EIGEN_HIPCC)
778
+ EIGEN_DEVICE_FUNC
779
+ #endif
780
+ void evalGemm(Scalar* buffer) const {
781
+ // columns in left side, rows in right side
782
+ const Index k = this->m_k_size;
783
+ this->template evalGemmPartial<lhs_inner_dim_contiguous,
784
+ rhs_inner_dim_contiguous,
785
+ rhs_inner_dim_reordered,
786
+ Alignment, true>(buffer, 0, k, 1);
787
+ }
788
+
789
+ template <bool lhs_inner_dim_contiguous, bool rhs_inner_dim_contiguous,
790
+ bool rhs_inner_dim_reordered, int Alignment>
791
+ EIGEN_DEVICE_FUNC void evalGemmPartialWithoutOutputKernel(
792
+ Scalar* buffer, Index k_start, Index k_end, int num_threads) const {
793
+ evalGemmPartial<lhs_inner_dim_contiguous, rhs_inner_dim_contiguous,
794
+ rhs_inner_dim_reordered, Alignment,
795
+ /*use_output_kernel*/ false>(buffer, k_start, k_end,
796
+ num_threads);
797
+ }
798
+
799
+ template <bool lhs_inner_dim_contiguous, bool rhs_inner_dim_contiguous, bool rhs_inner_dim_reordered, int Alignment, bool use_output_kernel>
800
+ EIGEN_DEVICE_FUNC void evalGemmPartial(Scalar* buffer, Index k_start, Index k_end, int num_threads) const {
801
+ eigen_assert(k_end >= k_start && k_start >= 0 && k_end <= this->m_k_size);
802
+ // columns in slice on left side, rows on right side
803
+ const Index k_slice = k_end - k_start;
804
+
805
+ // rows in left side
806
+ const Index m = this->m_i_size;
807
+
808
+ // columns in right side
809
+ const Index n = this->m_j_size;
810
+
811
+ // define data mappers for Lhs and Rhs
812
+ typedef std::remove_const_t<typename EvalLeftArgType::Scalar> LhsScalar;
813
+ typedef std::remove_const_t<typename EvalRightArgType::Scalar> RhsScalar;
814
+
815
+ typedef TensorEvaluator<EvalLeftArgType, Device> LeftEvaluator;
816
+ typedef TensorEvaluator<EvalRightArgType, Device> RightEvaluator;
817
+
818
+ const Index lhs_packet_size = internal::unpacket_traits<typename LeftEvaluator::PacketReturnType>::size;
819
+ const Index rhs_packet_size = internal::unpacket_traits<typename RightEvaluator::PacketReturnType>::size;
820
+
821
+ typedef internal::TensorContractionInputMapper<LhsScalar, Index, internal::Lhs,
822
+ LeftEvaluator, left_nocontract_t,
823
+ contract_t, lhs_packet_size,
824
+ lhs_inner_dim_contiguous,
825
+ false, Unaligned> LhsMapper;
826
+
827
+ typedef internal::TensorContractionInputMapper<RhsScalar, Index, internal::Rhs,
828
+ RightEvaluator, right_nocontract_t,
829
+ contract_t, rhs_packet_size,
830
+ rhs_inner_dim_contiguous,
831
+ rhs_inner_dim_reordered, Unaligned> RhsMapper;
832
+
833
+ typedef internal::blas_data_mapper<Scalar, Index, ColMajor> OutputMapper;
834
+
835
+ typedef internal::TensorContractionKernel<
836
+ Scalar, LhsScalar, RhsScalar, Index, OutputMapper, LhsMapper, RhsMapper>
837
+ TensorContractionKernel;
838
+
839
+ // initialize data mappers
840
+ LhsMapper lhs(this->m_leftImpl, this->m_left_nocontract_strides, this->m_i_strides,
841
+ this->m_left_contracting_strides, this->m_k_strides);
842
+
843
+ RhsMapper rhs(this->m_rightImpl, this->m_right_nocontract_strides, this->m_j_strides,
844
+ this->m_right_contracting_strides, this->m_k_strides);
845
+
846
+ OutputMapper output(buffer, m);
847
+
848
+ // Sizes of the blocks to load in cache. See the Goto paper for details.
849
+ internal::TensorContractionBlocking<Scalar, LhsScalar, RhsScalar,
850
+ Index, internal::ShardByCol>
851
+ blocking(k_slice, m, n, num_threads);
852
+ const Index kc = blocking.kc();
853
+ const Index mc = numext::mini(m, blocking.mc());
854
+ const Index nc = numext::mini(n, blocking.nc());
855
+
856
+ typedef typename TensorContractionKernel::LhsBlock LhsBlock;
857
+ typedef typename TensorContractionKernel::RhsBlock RhsBlock;
858
+
859
+ LhsBlock blockA;
860
+ RhsBlock blockB;
861
+
862
+ TensorContractionKernel kernel(m, k_slice, n, mc, kc, nc);
863
+
864
+ typedef typename TensorContractionKernel::BlockMemHandle BlockMemHandle;
865
+ const BlockMemHandle packed_mem =
866
+ kernel.allocate(this->m_device, &blockA, &blockB);
867
+
868
+ // If a contraction kernel does not support beta, explicitly initialize
869
+ // output buffer with zeroes.
870
+ if (!TensorContractionKernel::HasBeta) {
871
+ this->m_device.fill(buffer, buffer + m * n, Scalar(0));
872
+ }
873
+
874
+ for(Index i2=0; i2<m; i2+=mc)
875
+ {
876
+ const Index actual_mc = numext::mini(i2+mc,m)-i2;
877
+ for (Index k2 = k_start; k2 < k_end; k2 += kc) {
878
+ // make sure we don't overshoot right edge of left matrix, then pack vertical panel
879
+ const Index actual_kc = numext::mini(k2 + kc, k_end) - k2;
880
+ kernel.packLhs(&blockA, lhs.getSubMapper(i2, k2), actual_kc, actual_mc);
881
+
882
+ // If kernel supports beta, there is no need to initialize output
883
+ // buffer with zeroes.
884
+ const Scalar alpha = Scalar(1);
885
+ const Scalar beta = (TensorContractionKernel::HasBeta && k2 == k_start)
886
+ ? Scalar(0)
887
+ : Scalar(1);
888
+
889
+ // series of horizontal blocks
890
+ for (Index j2 = 0; j2 < n; j2 += nc) {
891
+ // make sure we don't overshoot right edge of right matrix, then pack block
892
+ const Index actual_nc = numext::mini(j2 + nc, n) - j2;
893
+ kernel.packRhs(&blockB, rhs.getSubMapper(k2, j2), actual_kc,
894
+ actual_nc);
895
+
896
+ // call gebp (matrix kernel)
897
+ // The parameters here are copied from Eigen's GEMM implementation
898
+ const OutputMapper output_mapper = output.getSubMapper(i2, j2);
899
+ kernel.invoke(output_mapper, blockA, blockB, actual_mc, actual_kc,
900
+ actual_nc, alpha, beta);
901
+
902
+ // We are done with this [i2, j2] output block.
903
+ if (use_output_kernel && k2 + kc >= k_end) {
904
+ m_output_kernel(output_mapper, m_tensor_contraction_params, i2, j2,
905
+ actual_mc, actual_nc);
906
+ }
907
+ }
908
+ }
909
+ }
910
+
911
+ kernel.deallocate(this->m_device, packed_mem);
912
+ }
913
+
914
+ EIGEN_STRONG_INLINE void cleanup() {
915
+ m_leftImpl.cleanup();
916
+ m_rightImpl.cleanup();
917
+
918
+ if (m_result != NULL) {
919
+ m_device.deallocate(m_result);
920
+ m_result = NULL;
921
+ }
922
+ }
923
+
924
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
925
+ return m_result[index];
926
+ }
927
+
928
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool) const {
929
+ return TensorOpCost(sizeof(CoeffReturnType), 0, 0);
930
+ }
931
+
932
+ template<int LoadMode>
933
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
934
+ return internal::ploadt<PacketReturnType, LoadMode>(m_result + index);
935
+ }
936
+
937
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EvaluatorPointerType data() const { return m_result; }
938
+
939
+ protected:
940
+ Dimensions m_dimensions;
941
+
942
+ contract_t m_k_strides;
943
+ contract_t m_left_contracting_strides;
944
+ contract_t m_right_contracting_strides;
945
+
946
+ bool m_lhs_inner_dim_contiguous;
947
+ bool m_rhs_inner_dim_contiguous;
948
+ bool m_rhs_inner_dim_reordered;
949
+
950
+ left_nocontract_t m_i_strides;
951
+ right_nocontract_t m_j_strides;
952
+ left_nocontract_t m_left_nocontract_strides;
953
+ right_nocontract_t m_right_nocontract_strides;
954
+
955
+ Index m_i_size;
956
+ Index m_j_size;
957
+ Index m_k_size;
958
+
959
+ TensorContractionParams m_tensor_contraction_params;
960
+
961
+ TensorEvaluator<EvalLeftArgType, Device> m_leftImpl;
962
+ TensorEvaluator<EvalRightArgType, Device> m_rightImpl;
963
+ const Device EIGEN_DEVICE_REF m_device;
964
+ OutputKernelType m_output_kernel;
965
+ EvaluatorPointerType m_result;
966
+ };
967
+
968
+
969
+ // evaluator for default device
970
+ template<typename Indices, typename LeftArgType, typename RightArgType, typename OutputKernelType, typename Device>
971
+ struct TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, Device> :
972
+ public TensorContractionEvaluatorBase<
973
+ TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, Device> > {
974
+ typedef TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, Device> Self;
975
+ typedef TensorContractionEvaluatorBase<Self> Base;
976
+
977
+ typedef TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType> XprType;
978
+ typedef std::remove_const_t<typename XprType::Scalar> Scalar;
979
+ typedef typename XprType::Index Index;
980
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
981
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
982
+
983
+ static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
984
+
985
+ // Most of the code is assuming that both input tensors are ColMajor. If the
986
+ // inputs are RowMajor, we will "cheat" by swapping the LHS and RHS:
987
+ // If we want to compute A * B = C, where A is LHS and B is RHS, the code
988
+ // will pretend B is LHS and A is RHS.
989
+ typedef std::conditional_t<Layout == static_cast<int>(ColMajor), LeftArgType, RightArgType> EvalLeftArgType;
990
+ typedef std::conditional_t<Layout == static_cast<int>(ColMajor), RightArgType, LeftArgType> EvalRightArgType;
991
+
992
+ static constexpr int LDims =
993
+ internal::array_size<typename TensorEvaluator<EvalLeftArgType, Device>::Dimensions>::value;
994
+ static constexpr int RDims =
995
+ internal::array_size<typename TensorEvaluator<EvalRightArgType, Device>::Dimensions>::value;
996
+ static constexpr int ContractDims = internal::array_size<Indices>::value;
997
+
998
+ typedef array<Index, ContractDims> contract_t;
999
+ typedef array<Index, LDims - ContractDims> left_nocontract_t;
1000
+ typedef array<Index, RDims - ContractDims> right_nocontract_t;
1001
+
1002
+ static constexpr int NumDims = LDims + RDims - 2 * ContractDims;
1003
+
1004
+ // Could we use NumDimensions here?
1005
+ typedef DSizes<Index, NumDims> Dimensions;
1006
+
1007
+ TensorEvaluator(const XprType& op, const Device& device) :
1008
+ Base(op, device) { }
1009
+
1010
+ template <int Alignment>
1011
+ void evalProduct(Scalar* buffer) const {
1012
+ TENSOR_CONTRACTION_DISPATCH(this->template evalProductSequential, Alignment, (buffer));
1013
+ }
1014
+ };
1015
+
1016
+ } // end namespace Eigen
1017
+
1018
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionBlocking.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_BLOCKING_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_BLOCKING_H
12
+
13
+
14
+ #include "./InternalHeaderCheck.h"
15
+
16
+ namespace Eigen {
17
+ namespace internal {
18
+
19
+ enum {
20
+ ShardByRow = 0,
21
+ ShardByCol = 1
22
+ };
23
+
24
+
25
+ // Default Blocking Strategy
26
+ template<typename ResScalar, typename LhsScalar, typename RhsScalar, typename StorageIndex, int ShardingType = ShardByCol>
27
+ class TensorContractionBlocking {
28
+ public:
29
+
30
+ /*
31
+ adding EIGEN_DEVICE_FUNC unconditionally to 'TensorContractionBlocking' constructor in `TensorContractionBlocking.h`
32
+ requires adding EIGEN_DEVICE_FUNC to `computeProductBlockingSizes` in `GeneralBlockPanelKernel.h`
33
+ which in turn, requires adding EIGEN_DEVICE_FUNC to `evaluateProductBlockingSizesHeuristic` in `GeneralBlockPanelKernel.h`
34
+ which in turn, requires adding EIGEN_DEVICE_FUNC to `manage_caching_sizes` in `GeneralBlockPanelKernel.h`
35
+ (else HIPCC will error out)
36
+
37
+ However adding EIGEN_DEVICE_FUNC to `manage_caching_sizes` in `GeneralBlockPanelKernel.h`
38
+ results in NVCC erroring out with the following error
39
+
40
+ ../Eigen/src/Core/products/GeneralBlockPanelKernel.h(57): error #2901:
41
+ dynamic initialization is not supported for function-scope static variables within a __device__/__global__ function
42
+ */
43
+
44
+ #if !defined(EIGEN_HIPCC)
45
+ EIGEN_DEVICE_FUNC
46
+ #endif
47
+ TensorContractionBlocking(StorageIndex k, StorageIndex m, StorageIndex n, StorageIndex num_threads = 1) :
48
+ kc_(k), mc_(m), nc_(n)
49
+ {
50
+ if (ShardingType == ShardByCol) {
51
+ computeProductBlockingSizes<LhsScalar, RhsScalar, 1>(kc_, mc_, nc_, num_threads);
52
+ }
53
+ else {
54
+ computeProductBlockingSizes<LhsScalar, RhsScalar, 1>(kc_, nc_, mc_, num_threads);
55
+ }
56
+
57
+ const int rhs_packet_size = internal::packet_traits<RhsScalar>::size;
58
+ kc_ = (rhs_packet_size <= 8 || kc_ <= rhs_packet_size) ?
59
+ kc_ : (kc_ / rhs_packet_size) * rhs_packet_size;
60
+ }
61
+
62
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE StorageIndex kc() const { return kc_; }
63
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE StorageIndex mc() const { return mc_; }
64
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE StorageIndex nc() const { return nc_; }
65
+
66
+ private:
67
+ StorageIndex kc_;
68
+ StorageIndex mc_;
69
+ StorageIndex nc_;
70
+ };
71
+
72
+ } // end namespace internal
73
+ } // end namespace Eigen
74
+
75
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_BLOCKING_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionCuda.h ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+
2
+ #if defined(__clang__) || defined(__GNUC__)
3
+ #warning "Deprecated header file, please either include the main Eigen/CXX11/Tensor header or the respective TensorContractionGpu.h file"
4
+ #endif
5
+
6
+ #include "TensorContractionGpu.h"
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionGpu.h ADDED
@@ -0,0 +1,1411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014-2015 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ // Copyright (C) 2015 Navdeep Jaitly <ndjaitly@google.com>
6
+ // Copyright (C) 2014 Eric Martin <eric@ericmart.in>
7
+ //
8
+ // This Source Code Form is subject to the terms of the Mozilla
9
+ // Public License v. 2.0. If a copy of the MPL was not distributed
10
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
11
+
12
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_GPU_H
13
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_GPU_H
14
+
15
+ #if defined(EIGEN_USE_GPU) && defined(EIGEN_GPUCC)
16
+
17
+ #include "./InternalHeaderCheck.h"
18
+
19
+ namespace Eigen {
20
+
21
+ template<typename Scalar, typename Index, typename LhsMapper,
22
+ typename RhsMapper, typename OutputMapper, bool needs_edge_check>
23
+ __device__ EIGEN_STRONG_INLINE void
24
+ EigenContractionKernelInternal(const LhsMapper lhs, const RhsMapper rhs,
25
+ const OutputMapper output, Scalar* lhs_shmem, Scalar* rhs_shmem,
26
+ const Index m_size, const Index n_size, const Index k_size) {
27
+
28
+ const Index m_block_idx = blockIdx.x;
29
+ const Index n_block_idx = blockIdx.y;
30
+
31
+ const Index base_m = 64 * m_block_idx;
32
+ const Index base_n = 64 * n_block_idx;
33
+
34
+ // declare and initialize 64 registers for output 8x8 block
35
+
36
+ // prefetch registers
37
+ Scalar lhs_pf0;
38
+ Scalar lhs_pf1;
39
+ Scalar lhs_pf2;
40
+ Scalar lhs_pf3;
41
+ Scalar lhs_pf4;
42
+ Scalar lhs_pf5;
43
+ Scalar lhs_pf6;
44
+ Scalar lhs_pf7;
45
+
46
+ Scalar rhs_pf0;
47
+ Scalar rhs_pf1;
48
+ Scalar rhs_pf2;
49
+ Scalar rhs_pf3;
50
+ Scalar rhs_pf4;
51
+ Scalar rhs_pf5;
52
+ Scalar rhs_pf6;
53
+ Scalar rhs_pf7;
54
+
55
+ // shared memory is formatted
56
+ // (contract idx in block, nocontract idx in block, block idx)
57
+ // where block idx is column major. This transposition limits the number of
58
+ // bank conflicts when reading the LHS. The core idea is that since the contracting
59
+ // index is shared by both sides, then the contracting index should be in threadIdx.x.
60
+
61
+ // On the LHS, we pad each row inside of each block with an extra element. This makes
62
+ // each block 8 rows of 9 elements, which is 72 elements. This gives no bank conflicts
63
+ // on writes and very few 2-way conflicts on reads. There is an 8x8 grid of these blocks.
64
+
65
+ // On the RHS we just add 8 padding elements to the end of each block. This gives no bank
66
+ // conflicts on writes and also none on reads.
67
+
68
+ // storage indices
69
+ const Index lhs_store_idx_base = threadIdx.y * 72 + threadIdx.x * 9 + threadIdx.z;
70
+ const Index rhs_store_idx_base = threadIdx.y * 72 + threadIdx.z * 8 + threadIdx.x;
71
+
72
+ const Index lhs_store_idx_0 = lhs_store_idx_base + 576 * 0;
73
+ const Index lhs_store_idx_1 = lhs_store_idx_base + 576 * 1;
74
+ const Index lhs_store_idx_2 = lhs_store_idx_base + 576 * 2;
75
+ const Index lhs_store_idx_3 = lhs_store_idx_base + 576 * 3;
76
+ const Index lhs_store_idx_4 = lhs_store_idx_base + 576 * 4;
77
+ const Index lhs_store_idx_5 = lhs_store_idx_base + 576 * 5;
78
+ const Index lhs_store_idx_6 = lhs_store_idx_base + 576 * 6;
79
+ const Index lhs_store_idx_7 = lhs_store_idx_base + 576 * 7;
80
+
81
+ const Index rhs_store_idx_0 = rhs_store_idx_base + 576 * 0;
82
+ const Index rhs_store_idx_1 = rhs_store_idx_base + 576 * 1;
83
+ const Index rhs_store_idx_2 = rhs_store_idx_base + 576 * 2;
84
+ const Index rhs_store_idx_3 = rhs_store_idx_base + 576 * 3;
85
+ const Index rhs_store_idx_4 = rhs_store_idx_base + 576 * 4;
86
+ const Index rhs_store_idx_5 = rhs_store_idx_base + 576 * 5;
87
+ const Index rhs_store_idx_6 = rhs_store_idx_base + 576 * 6;
88
+ const Index rhs_store_idx_7 = rhs_store_idx_base + 576 * 7;
89
+
90
+ // in the loading code, the following variables are important:
91
+ // threadIdx.x: the vertical position in an 8x8 block
92
+ // threadIdx.y: the vertical index of the 8x8 block in the grid
93
+ // threadIdx.z: the horizontal position in an 8x8 block
94
+ // k: the horizontal index of the 8x8 block in the grid
95
+ //
96
+ // The k parameter is implicit (it was the loop counter for a loop that went
97
+ // from 0 to <8, but now that loop is unrolled in the below code.
98
+
99
+ const Index load_idx_vert = threadIdx.x + 8 * threadIdx.y;
100
+ const Index lhs_vert = base_m + load_idx_vert;
101
+
102
+ #define prefetchIntoRegisters(base_k) \
103
+ { \
104
+ lhs_pf0 = conv(0); \
105
+ lhs_pf1 = conv(0); \
106
+ lhs_pf2 = conv(0); \
107
+ lhs_pf3 = conv(0); \
108
+ lhs_pf4 = conv(0); \
109
+ lhs_pf5 = conv(0); \
110
+ lhs_pf6 = conv(0); \
111
+ lhs_pf7 = conv(0); \
112
+ \
113
+ rhs_pf0 = conv(0); \
114
+ rhs_pf1 = conv(0); \
115
+ rhs_pf2 = conv(0); \
116
+ rhs_pf3 = conv(0); \
117
+ rhs_pf4 = conv(0); \
118
+ rhs_pf5 = conv(0); \
119
+ rhs_pf6 = conv(0); \
120
+ rhs_pf7 = conv(0); \
121
+ \
122
+ if (!needs_edge_check || lhs_vert < m_size) { \
123
+ const Index lhs_horiz_0 = base_k + threadIdx.z + 0 * 8; \
124
+ const Index lhs_horiz_1 = base_k + threadIdx.z + 1 * 8; \
125
+ const Index lhs_horiz_2 = base_k + threadIdx.z + 2 * 8; \
126
+ const Index lhs_horiz_3 = base_k + threadIdx.z + 3 * 8; \
127
+ const Index lhs_horiz_4 = base_k + threadIdx.z + 4 * 8; \
128
+ const Index lhs_horiz_5 = base_k + threadIdx.z + 5 * 8; \
129
+ const Index lhs_horiz_6 = base_k + threadIdx.z + 6 * 8; \
130
+ const Index lhs_horiz_7 = base_k + threadIdx.z + 7 * 8; \
131
+ \
132
+ if (!needs_edge_check || lhs_horiz_7 < k_size) { \
133
+ lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \
134
+ lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \
135
+ lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \
136
+ lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \
137
+ lhs_pf4 = lhs(lhs_vert, lhs_horiz_4); \
138
+ lhs_pf5 = lhs(lhs_vert, lhs_horiz_5); \
139
+ lhs_pf6 = lhs(lhs_vert, lhs_horiz_6); \
140
+ lhs_pf7 = lhs(lhs_vert, lhs_horiz_7); \
141
+ } else if (lhs_horiz_6 < k_size) { \
142
+ lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \
143
+ lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \
144
+ lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \
145
+ lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \
146
+ lhs_pf4 = lhs(lhs_vert, lhs_horiz_4); \
147
+ lhs_pf5 = lhs(lhs_vert, lhs_horiz_5); \
148
+ lhs_pf6 = lhs(lhs_vert, lhs_horiz_6); \
149
+ } else if (lhs_horiz_5 < k_size) { \
150
+ lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \
151
+ lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \
152
+ lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \
153
+ lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \
154
+ lhs_pf4 = lhs(lhs_vert, lhs_horiz_4); \
155
+ lhs_pf5 = lhs(lhs_vert, lhs_horiz_5); \
156
+ } else if (lhs_horiz_4 < k_size) { \
157
+ lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \
158
+ lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \
159
+ lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \
160
+ lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \
161
+ lhs_pf4 = lhs(lhs_vert, lhs_horiz_4); \
162
+ } else if (lhs_horiz_3 < k_size) { \
163
+ lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \
164
+ lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \
165
+ lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \
166
+ lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \
167
+ } else if (lhs_horiz_2 < k_size) { \
168
+ lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \
169
+ lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \
170
+ lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \
171
+ } else if (lhs_horiz_1 < k_size) { \
172
+ lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \
173
+ lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \
174
+ } else if (lhs_horiz_0 < k_size) { \
175
+ lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \
176
+ } \
177
+ } \
178
+ \
179
+ const Index rhs_vert = base_k + load_idx_vert; \
180
+ if (!needs_edge_check || rhs_vert < k_size) { \
181
+ const Index rhs_horiz_0 = base_n + threadIdx.z + 0 * 8; \
182
+ const Index rhs_horiz_1 = base_n + threadIdx.z + 1 * 8; \
183
+ const Index rhs_horiz_2 = base_n + threadIdx.z + 2 * 8; \
184
+ const Index rhs_horiz_3 = base_n + threadIdx.z + 3 * 8; \
185
+ const Index rhs_horiz_4 = base_n + threadIdx.z + 4 * 8; \
186
+ const Index rhs_horiz_5 = base_n + threadIdx.z + 5 * 8; \
187
+ const Index rhs_horiz_6 = base_n + threadIdx.z + 6 * 8; \
188
+ const Index rhs_horiz_7 = base_n + threadIdx.z + 7 * 8; \
189
+ \
190
+ if (rhs_horiz_7 < n_size) { \
191
+ rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \
192
+ rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \
193
+ rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \
194
+ rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \
195
+ rhs_pf4 = rhs(rhs_vert, rhs_horiz_4); \
196
+ rhs_pf5 = rhs(rhs_vert, rhs_horiz_5); \
197
+ rhs_pf6 = rhs(rhs_vert, rhs_horiz_6); \
198
+ rhs_pf7 = rhs(rhs_vert, rhs_horiz_7); \
199
+ } else if (rhs_horiz_6 < n_size) { \
200
+ rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \
201
+ rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \
202
+ rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \
203
+ rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \
204
+ rhs_pf4 = rhs(rhs_vert, rhs_horiz_4); \
205
+ rhs_pf5 = rhs(rhs_vert, rhs_horiz_5); \
206
+ rhs_pf6 = rhs(rhs_vert, rhs_horiz_6); \
207
+ } else if (rhs_horiz_5 < n_size) { \
208
+ rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \
209
+ rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \
210
+ rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \
211
+ rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \
212
+ rhs_pf4 = rhs(rhs_vert, rhs_horiz_4); \
213
+ rhs_pf5 = rhs(rhs_vert, rhs_horiz_5); \
214
+ } else if (rhs_horiz_4 < n_size) { \
215
+ rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \
216
+ rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \
217
+ rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \
218
+ rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \
219
+ rhs_pf4 = rhs(rhs_vert, rhs_horiz_4); \
220
+ } else if (rhs_horiz_3 < n_size) { \
221
+ rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \
222
+ rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \
223
+ rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \
224
+ rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \
225
+ } else if (rhs_horiz_2 < n_size) { \
226
+ rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \
227
+ rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \
228
+ rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \
229
+ } else if (rhs_horiz_1 < n_size) { \
230
+ rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \
231
+ rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \
232
+ } else if (rhs_horiz_0 < n_size) { \
233
+ rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \
234
+ } \
235
+ } \
236
+ } \
237
+
238
+ #define writeRegToShmem() \
239
+ lhs_shmem[lhs_store_idx_0] = lhs_pf0; \
240
+ rhs_shmem[rhs_store_idx_0] = rhs_pf0; \
241
+ \
242
+ lhs_shmem[lhs_store_idx_1] = lhs_pf1; \
243
+ rhs_shmem[rhs_store_idx_1] = rhs_pf1; \
244
+ \
245
+ lhs_shmem[lhs_store_idx_2] = lhs_pf2; \
246
+ rhs_shmem[rhs_store_idx_2] = rhs_pf2; \
247
+ \
248
+ lhs_shmem[lhs_store_idx_3] = lhs_pf3; \
249
+ rhs_shmem[rhs_store_idx_3] = rhs_pf3; \
250
+ \
251
+ lhs_shmem[lhs_store_idx_4] = lhs_pf4; \
252
+ rhs_shmem[rhs_store_idx_4] = rhs_pf4; \
253
+ \
254
+ lhs_shmem[lhs_store_idx_5] = lhs_pf5; \
255
+ rhs_shmem[rhs_store_idx_5] = rhs_pf5; \
256
+ \
257
+ lhs_shmem[lhs_store_idx_6] = lhs_pf6; \
258
+ rhs_shmem[rhs_store_idx_6] = rhs_pf6; \
259
+ \
260
+ lhs_shmem[lhs_store_idx_7] = lhs_pf7; \
261
+ rhs_shmem[rhs_store_idx_7] = rhs_pf7; \
262
+
263
+ // declare and initialize result array
264
+ #define res(i, j) _res_##i##j
265
+ #define initResultRow(i) \
266
+ Scalar res(i, 0) = conv(0); \
267
+ Scalar res(i, 1) = conv(0); \
268
+ Scalar res(i, 2) = conv(0); \
269
+ Scalar res(i, 3) = conv(0); \
270
+ Scalar res(i, 4) = conv(0); \
271
+ Scalar res(i, 5) = conv(0); \
272
+ Scalar res(i, 6) = conv(0); \
273
+ Scalar res(i, 7) = conv(0); \
274
+
275
+ internal::scalar_cast_op<int, Scalar> conv;
276
+ initResultRow(0);
277
+ initResultRow(1);
278
+ initResultRow(2);
279
+ initResultRow(3);
280
+ initResultRow(4);
281
+ initResultRow(5);
282
+ initResultRow(6);
283
+ initResultRow(7);
284
+ #undef initResultRow
285
+
286
+ for (Index base_k = 0; base_k < k_size; base_k += 64) {
287
+ // wait for previous iteration to finish with shmem. Despite common sense,
288
+ // the code is a bit faster with this here then at bottom of loop
289
+ __syncthreads();
290
+
291
+ prefetchIntoRegisters(base_k);
292
+ writeRegToShmem();
293
+
294
+ #undef prefetchIntoRegisters
295
+ #undef writeRegToShmem
296
+
297
+ // wait for shared mem packing to be done before starting computation
298
+ __syncthreads();
299
+
300
+ // compute 8x8 matrix product by outer product. This involves packing one column
301
+ // of LHS and one row of RHS into registers (takes 16 registers).
302
+
303
+ #define lcol(i) _lcol##i
304
+ Scalar lcol(0);
305
+ Scalar lcol(1);
306
+ Scalar lcol(2);
307
+ Scalar lcol(3);
308
+ Scalar lcol(4);
309
+ Scalar lcol(5);
310
+ Scalar lcol(6);
311
+ Scalar lcol(7);
312
+
313
+ #define rrow(j) _rrow##j
314
+ Scalar rrow(0);
315
+ Scalar rrow(1);
316
+ Scalar rrow(2);
317
+ Scalar rrow(3);
318
+ Scalar rrow(4);
319
+ Scalar rrow(5);
320
+ Scalar rrow(6);
321
+ Scalar rrow(7);
322
+
323
+ // Now x corresponds to k, y to m, and z to n
324
+ const Scalar* lhs_block = &lhs_shmem[threadIdx.x + 9 * threadIdx.y];
325
+ const Scalar* rhs_block = &rhs_shmem[threadIdx.x + 8 * threadIdx.z];
326
+
327
+ #define lhs_element(i, j) lhs_block[72 * ((i) + 8 * (j))]
328
+ #define rhs_element(i, j) rhs_block[72 * ((i) + 8 * (j))]
329
+
330
+ #define loadData(i, j) \
331
+ lcol(0) = lhs_element(0, j); \
332
+ rrow(0) = rhs_element(i, 0); \
333
+ lcol(1) = lhs_element(1, j); \
334
+ rrow(1) = rhs_element(i, 1); \
335
+ lcol(2) = lhs_element(2, j); \
336
+ rrow(2) = rhs_element(i, 2); \
337
+ lcol(3) = lhs_element(3, j); \
338
+ rrow(3) = rhs_element(i, 3); \
339
+ lcol(4) = lhs_element(4, j); \
340
+ rrow(4) = rhs_element(i, 4); \
341
+ lcol(5) = lhs_element(5, j); \
342
+ rrow(5) = rhs_element(i, 5); \
343
+ lcol(6) = lhs_element(6, j); \
344
+ rrow(6) = rhs_element(i, 6); \
345
+ lcol(7) = lhs_element(7, j); \
346
+ rrow(7) = rhs_element(i, 7); \
347
+
348
+ #define computeCol(j) \
349
+ res(0, j) += lcol(0) * rrow(j); \
350
+ res(1, j) += lcol(1) * rrow(j); \
351
+ res(2, j) += lcol(2) * rrow(j); \
352
+ res(3, j) += lcol(3) * rrow(j); \
353
+ res(4, j) += lcol(4) * rrow(j); \
354
+ res(5, j) += lcol(5) * rrow(j); \
355
+ res(6, j) += lcol(6) * rrow(j); \
356
+ res(7, j) += lcol(7) * rrow(j); \
357
+
358
+ #define computePass(i) \
359
+ loadData(i, i); \
360
+ \
361
+ computeCol(0); \
362
+ computeCol(1); \
363
+ computeCol(2); \
364
+ computeCol(3); \
365
+ computeCol(4); \
366
+ computeCol(5); \
367
+ computeCol(6); \
368
+ computeCol(7); \
369
+
370
+ computePass(0);
371
+ computePass(1);
372
+ computePass(2);
373
+ computePass(3);
374
+ computePass(4);
375
+ computePass(5);
376
+ computePass(6);
377
+ computePass(7);
378
+
379
+ #undef lcol
380
+ #undef rrow
381
+ #undef lhs_element
382
+ #undef rhs_element
383
+ #undef loadData
384
+ #undef computeCol
385
+ #undef computePass
386
+ } // end loop over k
387
+
388
+ // we've now iterated over all of the large (ie width 64) k blocks and
389
+ // accumulated results in registers. At this point thread (x, y, z) contains
390
+ // the sum across all big k blocks of the product of little k block of index (x, y)
391
+ // with block of index (y, z). To compute the final output, we need to reduce
392
+ // the 8 threads over y by summation.
393
+ #if defined(EIGEN_HIPCC) || (defined(EIGEN_CUDA_SDK_VER) && EIGEN_CUDA_SDK_VER < 90000)
394
+ #define shuffleInc(i, j, mask) res(i, j) += __shfl_xor(res(i, j), mask)
395
+ #else
396
+ #define shuffleInc(i, j, mask) res(i, j) += __shfl_xor_sync(0xFFFFFFFF, res(i, j), mask)
397
+ #endif
398
+
399
+ #define reduceRow(i, mask) \
400
+ shuffleInc(i, 0, mask); \
401
+ shuffleInc(i, 1, mask); \
402
+ shuffleInc(i, 2, mask); \
403
+ shuffleInc(i, 3, mask); \
404
+ shuffleInc(i, 4, mask); \
405
+ shuffleInc(i, 5, mask); \
406
+ shuffleInc(i, 6, mask); \
407
+ shuffleInc(i, 7, mask); \
408
+
409
+ #define reduceMatrix(mask) \
410
+ reduceRow(0, mask); \
411
+ reduceRow(1, mask); \
412
+ reduceRow(2, mask); \
413
+ reduceRow(3, mask); \
414
+ reduceRow(4, mask); \
415
+ reduceRow(5, mask); \
416
+ reduceRow(6, mask); \
417
+ reduceRow(7, mask); \
418
+
419
+ // actually perform the reduction, now each thread of index (_, y, z)
420
+ // contains the correct values in its registers that belong in the output
421
+ // block
422
+ reduceMatrix(1);
423
+ reduceMatrix(2);
424
+ reduceMatrix(4);
425
+
426
+ #undef shuffleInc
427
+ #undef reduceRow
428
+ #undef reduceMatrix
429
+
430
+ // now we need to copy the 64 values into main memory. We can't split work
431
+ // among threads because all variables are in registers. There's 2 ways
432
+ // to do this:
433
+ // (1) have 1 thread do 64 writes from registers into global memory
434
+ // (2) have 1 thread do 64 writes into shared memory, and then 8 threads
435
+ // each do 8 writes into global memory. We can just overwrite the shared
436
+ // memory from the problem we just solved.
437
+ // (2) is slightly faster than (1) due to less branching and more ILP
438
+
439
+ // TODO: won't yield much gain, but could just use currently unused shared mem
440
+ // and then we won't have to sync
441
+ // wait for shared mem to be out of use
442
+ __syncthreads();
443
+
444
+ #define writeResultShmem(i, j) \
445
+ lhs_shmem[i + 8 * threadIdx.y + 64 * threadIdx.z + 512 * j] = res(i, j); \
446
+
447
+ #define writeRow(i) \
448
+ writeResultShmem(i, 0); \
449
+ writeResultShmem(i, 1); \
450
+ writeResultShmem(i, 2); \
451
+ writeResultShmem(i, 3); \
452
+ writeResultShmem(i, 4); \
453
+ writeResultShmem(i, 5); \
454
+ writeResultShmem(i, 6); \
455
+ writeResultShmem(i, 7); \
456
+
457
+ if (threadIdx.x == 0) {
458
+ writeRow(0);
459
+ writeRow(1);
460
+ writeRow(2);
461
+ writeRow(3);
462
+ writeRow(4);
463
+ writeRow(5);
464
+ writeRow(6);
465
+ writeRow(7);
466
+ }
467
+ #undef writeResultShmem
468
+ #undef writeRow
469
+
470
+ const int max_i_write = numext::mini((int)((m_size - base_m - threadIdx.y + 7) / 8), 8);
471
+ const int max_j_write = numext::mini((int)((n_size - base_n - threadIdx.z + 7) / 8), 8);
472
+
473
+ if (threadIdx.x < max_i_write) {
474
+ if (max_j_write == 8) {
475
+ // TODO: can i trade bank conflicts for coalesced writes?
476
+ Scalar val0 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 0];
477
+ Scalar val1 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 1];
478
+ Scalar val2 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 2];
479
+ Scalar val3 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 3];
480
+ Scalar val4 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 4];
481
+ Scalar val5 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 5];
482
+ Scalar val6 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 6];
483
+ Scalar val7 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 7];
484
+
485
+ output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 0) = val0;
486
+ output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 1) = val1;
487
+ output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 2) = val2;
488
+ output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 3) = val3;
489
+ output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 4) = val4;
490
+ output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 5) = val5;
491
+ output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 6) = val6;
492
+ output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 7) = val7;
493
+ } else {
494
+ #pragma unroll 7
495
+ for (int j = 0; j < max_j_write; j++) {
496
+ Scalar val = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * j];
497
+ output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * j) = val;
498
+ }
499
+ }
500
+ }
501
+ #undef res
502
+ }
503
+
504
+
505
+ template<typename Scalar, typename Index, typename LhsMapper,
506
+ typename RhsMapper, typename OutputMapper>
507
+ __global__ void
508
+ #if defined(EIGEN_HIPCC)
509
+ __launch_bounds__(512, 1)
510
+ #else
511
+ __launch_bounds__(512)
512
+ #endif
513
+ EigenContractionKernel(const LhsMapper lhs, const RhsMapper rhs,
514
+ const OutputMapper output,
515
+ const Index m_size, const Index n_size, const Index k_size) {
516
+ __shared__ Scalar lhs_shmem[72 * 64];
517
+ __shared__ Scalar rhs_shmem[72 * 64];
518
+
519
+ const Index m_block_idx = blockIdx.x;
520
+ const Index n_block_idx = blockIdx.y;
521
+
522
+ const Index base_m = 64 * m_block_idx;
523
+ const Index base_n = 64 * n_block_idx;
524
+
525
+ if (base_m + 63 < m_size && base_n + 63 < n_size) {
526
+ EigenContractionKernelInternal<Scalar, Index, LhsMapper, RhsMapper, OutputMapper, false>(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size);
527
+ } else {
528
+ EigenContractionKernelInternal<Scalar, Index, LhsMapper, RhsMapper, OutputMapper, true>(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size);
529
+ }
530
+ }
531
+
532
+
533
+ template<typename Index, typename LhsMapper,
534
+ typename RhsMapper, typename OutputMapper, bool CHECK_LHS_BOUNDARY,
535
+ bool CHECK_RHS_BOUNDARY>
536
+ __device__ __forceinline__ void
537
+ EigenFloatContractionKernelInternal16x16(const LhsMapper lhs, const RhsMapper rhs,
538
+ const OutputMapper output, float2 lhs_shmem2[][16],
539
+ float2 rhs_shmem2[][8], const Index m_size,
540
+ const Index n_size, const Index k_size,
541
+ const Index base_m, const Index base_n) {
542
+
543
+ // prefetch registers
544
+ float4 lhs_pf0, rhs_pf0;
545
+
546
+ float4 results[4];
547
+ for (int i=0; i < 4; i++) {
548
+ results[i].x = results[i].y = results[i].z = results[i].w = 0;
549
+ }
550
+
551
+ #define prefetch_lhs(reg, row, col) \
552
+ if (!CHECK_LHS_BOUNDARY) { \
553
+ if (col < k_size) { \
554
+ reg =lhs.template loadPacket<float4,Unaligned>(row, col); \
555
+ } \
556
+ } else { \
557
+ if (col < k_size) { \
558
+ if (row + 3 < m_size) { \
559
+ reg =lhs.template loadPacket<float4,Unaligned>(row, col); \
560
+ } else if (row + 2 < m_size) { \
561
+ reg.x =lhs(row + 0, col); \
562
+ reg.y =lhs(row + 1, col); \
563
+ reg.z =lhs(row + 2, col); \
564
+ } else if (row + 1 < m_size) { \
565
+ reg.x =lhs(row + 0, col); \
566
+ reg.y =lhs(row + 1, col); \
567
+ } else if (row < m_size) { \
568
+ reg.x =lhs(row + 0, col); \
569
+ } \
570
+ } \
571
+ } \
572
+
573
+ Index lhs_vert = base_m+threadIdx.x*4;
574
+
575
+ for (Index k = 0; k < k_size; k += 16) {
576
+
577
+ lhs_pf0 = internal::pset1<float4>(0);
578
+ rhs_pf0 = internal::pset1<float4>(0);
579
+
580
+ Index lhs_horiz = threadIdx.y+k;
581
+ prefetch_lhs(lhs_pf0, lhs_vert, lhs_horiz)
582
+
583
+ Index rhs_vert = k+(threadIdx.x%4)*4;
584
+ Index rhs_horiz0 = (threadIdx.x>>2)+threadIdx.y*4+base_n;
585
+
586
+ if (!CHECK_RHS_BOUNDARY) {
587
+ if ((rhs_vert + 3) < k_size) {
588
+ // just CHECK_RHS_BOUNDARY
589
+ rhs_pf0 = rhs.template loadPacket<float4,Unaligned>(rhs_vert, rhs_horiz0);
590
+ } else if (rhs_vert + 2 < k_size) {
591
+ // just CHECK_RHS_BOUNDARY
592
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
593
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
594
+ rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0);
595
+ } else if (rhs_vert + 1 < k_size) {
596
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
597
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
598
+ } else if (rhs_vert < k_size) {
599
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
600
+ }
601
+ } else {
602
+ if (rhs_horiz0 < n_size) {
603
+ if ((rhs_vert + 3) < k_size) {
604
+ rhs_pf0 = rhs.template loadPacket<float4,Unaligned>(rhs_vert, rhs_horiz0);
605
+ } else if ((rhs_vert + 2) < k_size) {
606
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
607
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
608
+ rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0);
609
+ } else if ((rhs_vert + 1) < k_size) {
610
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
611
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
612
+ } else if (rhs_vert < k_size) {
613
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
614
+ }
615
+ }
616
+ }
617
+ float x1, x2 ;
618
+ // the following can be a bitwise operation..... some day.
619
+ if((threadIdx.x%8) < 4) {
620
+ x1 = rhs_pf0.y;
621
+ x2 = rhs_pf0.w;
622
+ } else {
623
+ x1 = rhs_pf0.x;
624
+ x2 = rhs_pf0.z;
625
+ }
626
+ #if defined(EIGEN_HIPCC) || (defined(EIGEN_CUDA_SDK_VER) && EIGEN_CUDA_SDK_VER < 90000)
627
+ x1 = __shfl_xor(x1, 4);
628
+ x2 = __shfl_xor(x2, 4);
629
+ #else
630
+ x1 = __shfl_xor_sync(0xFFFFFFFF, x1, 4);
631
+ x2 = __shfl_xor_sync(0xFFFFFFFF, x2, 4);
632
+ #endif
633
+ if((threadIdx.x%8) < 4) {
634
+ rhs_pf0.y = x1;
635
+ rhs_pf0.w = x2;
636
+ } else {
637
+ rhs_pf0.x = x1;
638
+ rhs_pf0.z = x2;
639
+ }
640
+
641
+ // We have 64 features.
642
+ // Row 0 -> times (0, 4, 8, 12, 1, 5, 9, 13) for features 0, 1.
643
+ // Row 1 -> times (0, 4, 8, 12, 1, 5, 9, 13) for features 2, 3.
644
+ // ...
645
+ // Row 31 -> times (0, 4, 8, 12, 1, 5, 9, 13) for features 62, 63
646
+ // Row 32 -> times (2, 6, 10, 14, 3, 7, 11, 15) for features 0, 1
647
+ // ...
648
+ rhs_shmem2[(threadIdx.x>>3)+ threadIdx.y*2][threadIdx.x%8] = make_float2(rhs_pf0.x, rhs_pf0.y);
649
+ rhs_shmem2[(threadIdx.x>>3)+ threadIdx.y*2+32][threadIdx.x%8] = make_float2(rhs_pf0.z, rhs_pf0.w);
650
+
651
+ // Row 0 (time 0) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61)
652
+ // Row 1 (time 1) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61)
653
+ // ...
654
+ // Row 15 (time 15) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61)
655
+ // Row 16 (time 0) -> features (2, 3), (6, 7), .. (30, 31), (34, 35), .. (62, 63)
656
+ // ...
657
+
658
+ lhs_shmem2[threadIdx.y][threadIdx.x] = make_float2(lhs_pf0.x, lhs_pf0.y);
659
+ lhs_shmem2[threadIdx.y+16][threadIdx.x] = make_float2(lhs_pf0.z, lhs_pf0.w);
660
+
661
+
662
+ #define add_vals(fl1, fl2, fr1, fr2)\
663
+ results[0].x += fl1.x * fr1.x;\
664
+ results[0].y += fl1.y * fr1.x;\
665
+ results[0].z += fl2.x * fr1.x;\
666
+ results[0].w += fl2.y * fr1.x;\
667
+ \
668
+ results[1].x += fl1.x * fr1.y;\
669
+ results[1].y += fl1.y * fr1.y;\
670
+ results[1].z += fl2.x * fr1.y;\
671
+ results[1].w += fl2.y * fr1.y;\
672
+ \
673
+ results[2].x += fl1.x * fr2.x;\
674
+ results[2].y += fl1.y * fr2.x;\
675
+ results[2].z += fl2.x * fr2.x;\
676
+ results[2].w += fl2.y * fr2.x;\
677
+ \
678
+ results[3].x += fl1.x * fr2.y;\
679
+ results[3].y += fl1.y * fr2.y;\
680
+ results[3].z += fl2.x * fr2.y;\
681
+ results[3].w += fl2.y * fr2.y;\
682
+
683
+ __syncthreads();
684
+
685
+ // Do the multiplies.
686
+ #pragma unroll
687
+ for (int koff = 0; koff < 16; koff ++) {
688
+ // 32 x threads.
689
+ float2 fl1 = lhs_shmem2[koff][threadIdx.x];
690
+ float2 fl2 = lhs_shmem2[koff + 16][threadIdx.x];
691
+
692
+ int start_feature = threadIdx.y * 4;
693
+ float2 fr1 = rhs_shmem2[(start_feature>>1) + 32*((koff%4)/2)][koff/4 + (koff%2)*4];
694
+ float2 fr2 = rhs_shmem2[(start_feature>>1) + 1 + 32*((koff%4)/2)][koff/4 + (koff%2)*4];
695
+
696
+ add_vals(fl1, fl2, fr1, fr2)
697
+ }
698
+ __syncthreads();
699
+ }
700
+
701
+ #undef prefetch_lhs
702
+ #undef add_vals
703
+
704
+ Index horiz_base = threadIdx.y*4+base_n;
705
+ if (!CHECK_LHS_BOUNDARY && !CHECK_RHS_BOUNDARY) {
706
+ for (int i = 0; i < 4; i++) {
707
+ output(lhs_vert, horiz_base + i) = results[i].x;
708
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
709
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
710
+ output(lhs_vert + 3, horiz_base + i) = results[i].w;
711
+ }
712
+ } else if (!CHECK_RHS_BOUNDARY) {
713
+ // CHECK LHS
714
+ if (lhs_vert + 3 < m_size) {
715
+ for (int i = 0; i < 4; i++) {
716
+ output(lhs_vert, horiz_base + i) = results[i].x;
717
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
718
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
719
+ output(lhs_vert + 3, horiz_base + i) = results[i].w;
720
+ }
721
+ } else if (lhs_vert + 2 < m_size) {
722
+ for (int i = 0; i < 4; i++) {
723
+ output(lhs_vert, horiz_base + i) = results[i].x;
724
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
725
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
726
+ }
727
+ } else if (lhs_vert + 1 < m_size) {
728
+ for (int i = 0; i < 4; i++) {
729
+ output(lhs_vert, horiz_base + i) = results[i].x;
730
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
731
+ }
732
+ } else if (lhs_vert < m_size) {
733
+ for (int i = 0; i < 4; i++) {
734
+ output(lhs_vert, horiz_base + i) = results[i].x;
735
+ }
736
+ }
737
+ } else if (!CHECK_LHS_BOUNDARY) {
738
+ // CHECK RHS
739
+ /*
740
+ int ncols_rem = fminf(n_size- horiz_base, 4);
741
+ for (int i = 0; i < ncols_rem; i++) {
742
+ output(lhs_vert, horiz_base + i) = results[i].x;
743
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
744
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
745
+ output(lhs_vert + 3, horiz_base + i) = results[i].w;
746
+ }*/
747
+ for (int i = 0; i < 4; i++) {
748
+ if (horiz_base+i < n_size) {
749
+ output(lhs_vert, horiz_base + i) = results[i].x;
750
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
751
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
752
+ output(lhs_vert + 3, horiz_base + i) = results[i].w;
753
+ }
754
+ }
755
+ } else {
756
+ // CHECK both boundaries.
757
+ for (int i = 0; i < 4; i++) {
758
+ if (horiz_base+i < n_size) {
759
+ if (lhs_vert < m_size)
760
+ output(lhs_vert, horiz_base + i) = results[i].x;
761
+ if (lhs_vert + 1 < m_size)
762
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
763
+ if (lhs_vert + 2 < m_size)
764
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
765
+ if (lhs_vert + 3 < m_size)
766
+ output(lhs_vert + 3, horiz_base + i) = results[i].w;
767
+ }
768
+ }
769
+ }
770
+ }
771
+
772
+
773
+ template<typename Index, typename LhsMapper,
774
+ typename RhsMapper, typename OutputMapper, bool CHECK_LHS_BOUNDARY,
775
+ bool CHECK_RHS_BOUNDARY>
776
+ __device__ __forceinline__ void
777
+ EigenFloatContractionKernelInternal(const LhsMapper lhs, const RhsMapper rhs,
778
+ const OutputMapper output, float2 lhs_shmem2[][32],
779
+ float2 rhs_shmem2[][8], const Index m_size,
780
+ const Index n_size, const Index k_size,
781
+ const Index base_m, const Index base_n) {
782
+
783
+ // prefetch registers
784
+ float4 lhs_pf0, lhs_pf1, lhs_pf2, lhs_pf3;
785
+ float4 rhs_pf0, rhs_pf1;
786
+
787
+ float4 results[8];
788
+ for (int i=0; i < 8; i++) {
789
+ results[i].x = results[i].y = results[i].z = results[i].w = 0;
790
+ }
791
+
792
+ Index lhs_vert = base_m+threadIdx.x*4+(threadIdx.y%4)*32;
793
+ for (Index k = 0; k < k_size; k += 32) {
794
+ lhs_pf0 = internal::pset1<float4>(0);
795
+ lhs_pf1 = internal::pset1<float4>(0);
796
+ lhs_pf2 = internal::pset1<float4>(0);
797
+ lhs_pf3 = internal::pset1<float4>(0);
798
+
799
+ rhs_pf0 = internal::pset1<float4>(0);
800
+ rhs_pf1 = internal::pset1<float4>(0);
801
+
802
+ if (!CHECK_LHS_BOUNDARY) {
803
+ if ((threadIdx.y/4+k+24) < k_size) {
804
+ lhs_pf0 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k));
805
+ lhs_pf1 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+8));
806
+ lhs_pf2 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+16));
807
+ lhs_pf3 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+24));
808
+ } else if ((threadIdx.y/4+k+16) < k_size) {
809
+ lhs_pf0 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k));
810
+ lhs_pf1 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+8));
811
+ lhs_pf2 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+16));
812
+ } else if ((threadIdx.y/4+k+8) < k_size) {
813
+ lhs_pf0 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k));
814
+ lhs_pf1 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+8));
815
+ } else if ((threadIdx.y/4+k) < k_size) {
816
+ lhs_pf0 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k));
817
+ }
818
+ } else {
819
+ // just CHECK_LHS_BOUNDARY
820
+ if (lhs_vert + 3 < m_size) {
821
+ if ((threadIdx.y/4+k+24) < k_size) {
822
+ lhs_pf0 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k));
823
+ lhs_pf1 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+8));
824
+ lhs_pf2 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+16));
825
+ lhs_pf3 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+24));
826
+ } else if ((threadIdx.y/4+k+16) < k_size) {
827
+ lhs_pf0 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k));
828
+ lhs_pf1 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+8));
829
+ lhs_pf2 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+16));
830
+ } else if ((threadIdx.y/4+k+8) < k_size) {
831
+ lhs_pf0 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k));
832
+ lhs_pf1 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k+8));
833
+ } else if ((threadIdx.y/4+k) < k_size) {
834
+ lhs_pf0 =lhs.template loadPacket<float4,Unaligned>(lhs_vert, (threadIdx.y/4+k));
835
+ }
836
+ } else if (lhs_vert + 2 < m_size) {
837
+ if ((threadIdx.y/4+k+24) < k_size) {
838
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
839
+ lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k));
840
+ lhs_pf0.z =lhs(lhs_vert + 2, (threadIdx.y/4+k));
841
+ lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8));
842
+ lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8));
843
+ lhs_pf1.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+8));
844
+ lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16));
845
+ lhs_pf2.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+16));
846
+ lhs_pf2.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+16));
847
+ lhs_pf3.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+24));
848
+ lhs_pf3.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+24));
849
+ lhs_pf3.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+24));
850
+ } else if ((threadIdx.y/4+k+16) < k_size) {
851
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
852
+ lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k));
853
+ lhs_pf0.z =lhs(lhs_vert + 2, (threadIdx.y/4+k));
854
+ lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8));
855
+ lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8));
856
+ lhs_pf1.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+8));
857
+ lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16));
858
+ lhs_pf2.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+16));
859
+ lhs_pf2.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+16));
860
+ } else if ((threadIdx.y/4+k+8) < k_size) {
861
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
862
+ lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k));
863
+ lhs_pf0.z =lhs(lhs_vert + 2, (threadIdx.y/4+k));
864
+ lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8));
865
+ lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8));
866
+ lhs_pf1.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+8));
867
+ } else if ((threadIdx.y/4+k) < k_size) {
868
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
869
+ lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k));
870
+ lhs_pf0.z =lhs(lhs_vert + 2, (threadIdx.y/4+k));
871
+ }
872
+ } else if (lhs_vert + 1 < m_size) {
873
+ if ((threadIdx.y/4+k+24) < k_size) {
874
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
875
+ lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k));
876
+ lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8));
877
+ lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8));
878
+ lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16));
879
+ lhs_pf2.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+16));
880
+ lhs_pf3.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+24));
881
+ lhs_pf3.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+24));
882
+ } else if ((threadIdx.y/4+k+16) < k_size) {
883
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
884
+ lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k));
885
+ lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8));
886
+ lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8));
887
+ lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16));
888
+ lhs_pf2.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+16));
889
+ } else if ((threadIdx.y/4+k+8) < k_size) {
890
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
891
+ lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k));
892
+ lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8));
893
+ lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8));
894
+ } else if ((threadIdx.y/4+k) < k_size) {
895
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
896
+ lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k));
897
+ }
898
+ } else if (lhs_vert < m_size) {
899
+ if ((threadIdx.y/4+k+24) < k_size) {
900
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
901
+ lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8));
902
+ lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16));
903
+ lhs_pf3.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+24));
904
+ } else if ((threadIdx.y/4+k+16) < k_size) {
905
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
906
+ lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8));
907
+ lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16));
908
+ } else if ((threadIdx.y/4+k+8) < k_size) {
909
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
910
+ lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8));
911
+ } else if ((threadIdx.y/4+k) < k_size) {
912
+ lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k));
913
+ }
914
+ }
915
+ }
916
+ __syncthreads();
917
+ Index rhs_vert = k+threadIdx.x*4;
918
+ Index rhs_horiz0 = threadIdx.y*2+base_n;
919
+ Index rhs_horiz1 = threadIdx.y*2+1+base_n;
920
+ if (!CHECK_RHS_BOUNDARY) {
921
+ if ((rhs_vert + 3) < k_size) {
922
+ // just CHECK_RHS_BOUNDARY
923
+ rhs_pf0 = rhs.template loadPacket<float4,Unaligned>(rhs_vert, rhs_horiz0);
924
+ rhs_pf1 = rhs.template loadPacket<float4,Unaligned>(rhs_vert, rhs_horiz1);
925
+ } else if (rhs_vert + 2 < k_size) {
926
+ // just CHECK_RHS_BOUNDARY
927
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
928
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
929
+ rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0);
930
+ rhs_pf1.x = rhs(rhs_vert, rhs_horiz1);
931
+ rhs_pf1.y = rhs(rhs_vert + 1, rhs_horiz1);
932
+ rhs_pf1.z = rhs(rhs_vert + 2, rhs_horiz1);
933
+ } else if (rhs_vert + 1 < k_size) {
934
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
935
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
936
+ rhs_pf1.x = rhs(rhs_vert, rhs_horiz1);
937
+ rhs_pf1.y = rhs(rhs_vert + 1, rhs_horiz1);
938
+ } else if (rhs_vert < k_size) {
939
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
940
+ rhs_pf1.x = rhs(rhs_vert, rhs_horiz1);
941
+ }
942
+ } else {
943
+ if (rhs_horiz1 < n_size) {
944
+ if ((rhs_vert + 3) < k_size) {
945
+ // just CHECK_RHS_BOUNDARY
946
+ rhs_pf0 = rhs.template loadPacket<float4,Unaligned>(rhs_vert, rhs_horiz0);
947
+ rhs_pf1 = rhs.template loadPacket<float4,Unaligned>(rhs_vert, rhs_horiz1);
948
+ } else if (rhs_vert + 2 < k_size) {
949
+ // just CHECK_RHS_BOUNDARY
950
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
951
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
952
+ rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0);
953
+ rhs_pf1.x = rhs(rhs_vert, rhs_horiz1);
954
+ rhs_pf1.y = rhs(rhs_vert + 1, rhs_horiz1);
955
+ rhs_pf1.z = rhs(rhs_vert + 2, rhs_horiz1);
956
+ } else if (k+threadIdx.x*4 + 1 < k_size) {
957
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
958
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
959
+ rhs_pf1.x = rhs(rhs_vert, rhs_horiz1);
960
+ rhs_pf1.y = rhs(rhs_vert + 1, rhs_horiz1);
961
+ } else if (k+threadIdx.x*4 < k_size) {
962
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
963
+ rhs_pf1.x = rhs(rhs_vert, rhs_horiz1);
964
+ }
965
+ } else if (rhs_horiz0 < n_size) {
966
+ if ((rhs_vert + 3) < k_size) {
967
+ // just CHECK_RHS_BOUNDARY
968
+ rhs_pf0 = rhs.template loadPacket<float4,Unaligned>(rhs_vert, rhs_horiz0);
969
+ } else if ((rhs_vert + 2) < k_size) {
970
+ // just CHECK_RHS_BOUNDARY
971
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
972
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
973
+ rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0);
974
+ } else if ((rhs_vert + 1) < k_size) {
975
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
976
+ rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0);
977
+ } else if (rhs_vert < k_size) {
978
+ rhs_pf0.x = rhs(rhs_vert, rhs_horiz0);
979
+ }
980
+ }
981
+ }
982
+ __syncthreads();
983
+ // Loaded. Do computation
984
+ // Row 0 -> times (0, 4, 8, .. 28) for features 0, 1.
985
+ // Row 1 -> times (0, 4, 8, .. 28) for features 2, 3.
986
+ // ..
987
+ // Row 31 -> times (0, 4, 8, .. 28) for features 62, 63
988
+ rhs_shmem2[threadIdx.y][threadIdx.x] = make_float2(rhs_pf0.x, rhs_pf1.x);
989
+ // Row 32 -> times (1, 5, 9, .. 29) for features 0, 1.
990
+ // Row 33 -> times (1, 5, 9, .. 29) for features 2, 3.
991
+ // ..
992
+ rhs_shmem2[threadIdx.y+32][threadIdx.x] = make_float2(rhs_pf0.y, rhs_pf1.y);
993
+ // Row 64 -> times (2, 6, 10, .. 30) for features 0, 1.
994
+ // Row 65 -> times (2, 6, 10, .. 30) for features 2, 3.
995
+ rhs_shmem2[threadIdx.y+64][threadIdx.x] = make_float2(rhs_pf0.z, rhs_pf1.z);
996
+ // Row 96 -> times (3, 7, 11, .. 31) for features 0, 1.
997
+ // Row 97 -> times (3, 7, 11, .. 31) for features 2, 3.
998
+ rhs_shmem2[threadIdx.y+96][threadIdx.x] = make_float2(rhs_pf0.w, rhs_pf1.w);
999
+
1000
+ // LHS.
1001
+ // Row 0 (time 0) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61) .. (124, 125)
1002
+ // Row 1 (time 1) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61) .. (124, 125)
1003
+ // ...
1004
+ // Row 8 (time 0) -> features (2, 3), (6, 7), .. (30, 31), (34, 35), .. (62, 63) .. (126, 127)
1005
+ // Row 15 (time 7) -> features (2, 3), (6, 7), .. (30, 31), (34, 35), .. (62, 63) .. (126, 127)
1006
+
1007
+
1008
+ #define add_vals(a_feat1, a_feat2, f1, f2, f3, f4)\
1009
+ results[0].x += a_feat1.x * f1.x;\
1010
+ results[1].x += a_feat1.x * f1.y;\
1011
+ results[2].x += a_feat1.x * f2.x;\
1012
+ results[3].x += a_feat1.x * f2.y;\
1013
+ results[4].x += a_feat1.x * f3.x;\
1014
+ results[5].x += a_feat1.x * f3.y;\
1015
+ results[6].x += a_feat1.x * f4.x;\
1016
+ results[7].x += a_feat1.x * f4.y;\
1017
+ \
1018
+ results[0].y += a_feat1.y * f1.x;\
1019
+ results[1].y += a_feat1.y * f1.y;\
1020
+ results[2].y += a_feat1.y * f2.x;\
1021
+ results[3].y += a_feat1.y * f2.y;\
1022
+ results[4].y += a_feat1.y * f3.x;\
1023
+ results[5].y += a_feat1.y * f3.y;\
1024
+ results[6].y += a_feat1.y * f4.x;\
1025
+ results[7].y += a_feat1.y * f4.y;\
1026
+ \
1027
+ results[0].z += a_feat2.x * f1.x;\
1028
+ results[1].z += a_feat2.x * f1.y;\
1029
+ results[2].z += a_feat2.x * f2.x;\
1030
+ results[3].z += a_feat2.x * f2.y;\
1031
+ results[4].z += a_feat2.x * f3.x;\
1032
+ results[5].z += a_feat2.x * f3.y;\
1033
+ results[6].z += a_feat2.x * f4.x;\
1034
+ results[7].z += a_feat2.x * f4.y;\
1035
+ \
1036
+ results[0].w += a_feat2.y * f1.x;\
1037
+ results[1].w += a_feat2.y * f1.y;\
1038
+ results[2].w += a_feat2.y * f2.x;\
1039
+ results[3].w += a_feat2.y * f2.y;\
1040
+ results[4].w += a_feat2.y * f3.x;\
1041
+ results[5].w += a_feat2.y * f3.y;\
1042
+ results[6].w += a_feat2.y * f4.x;\
1043
+ results[7].w += a_feat2.y * f4.y;\
1044
+
1045
+ lhs_shmem2[threadIdx.y/4][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf0.x, lhs_pf0.y);
1046
+ lhs_shmem2[threadIdx.y/4+8][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf1.x, lhs_pf1.y);
1047
+ lhs_shmem2[threadIdx.y/4+16][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf2.x, lhs_pf2.y);
1048
+ lhs_shmem2[threadIdx.y/4+24][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf3.x, lhs_pf3.y);
1049
+
1050
+ lhs_shmem2[threadIdx.y/4 + 32][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf0.z, lhs_pf0.w);
1051
+ lhs_shmem2[threadIdx.y/4 + 40][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf1.z, lhs_pf1.w);
1052
+ lhs_shmem2[threadIdx.y/4 + 48][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf2.z, lhs_pf2.w);
1053
+ lhs_shmem2[threadIdx.y/4 + 56][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf3.z, lhs_pf3.w);
1054
+
1055
+ __syncthreads();
1056
+
1057
+ // Do the multiplies.
1058
+ #pragma unroll
1059
+ for (int koff = 0; koff < 32; koff ++) {
1060
+ float2 a3 = lhs_shmem2[koff][threadIdx.x + (threadIdx.y % 4) * 8];
1061
+ float2 a4 = lhs_shmem2[koff + 32][threadIdx.x + (threadIdx.y % 4) * 8];
1062
+
1063
+ // first feature is at (threadIdx.y/4) * 8 last is at start + 8.
1064
+ int start_feature = (threadIdx.y / 4) * 8;
1065
+
1066
+ float2 br1 = rhs_shmem2[start_feature/2 + (koff % 4) * 32][koff/4];
1067
+ float2 br2 = rhs_shmem2[start_feature/2 + 1 + (koff % 4) * 32][koff/4];
1068
+ float2 br3 = rhs_shmem2[start_feature/2 + 2 + (koff % 4) * 32][koff/4];
1069
+ float2 br4 = rhs_shmem2[start_feature/2 + 3 + (koff % 4) * 32][koff/4];
1070
+
1071
+ add_vals(a3, a4, br1, br2, br3, br4)
1072
+ }
1073
+ __syncthreads();
1074
+ } // end loop over k
1075
+
1076
+ __syncthreads();
1077
+ Index horiz_base = (threadIdx.y/4)*8+base_n;
1078
+ if (!CHECK_LHS_BOUNDARY && !CHECK_RHS_BOUNDARY) {
1079
+ for (int i = 0; i < 8; i++) {
1080
+ output(lhs_vert, horiz_base + i) = results[i].x;
1081
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
1082
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
1083
+ output(lhs_vert + 3, horiz_base + i) = results[i].w;
1084
+ }
1085
+ } else if (!CHECK_RHS_BOUNDARY) {
1086
+ if (lhs_vert + 3 < m_size) {
1087
+ for (int i = 0; i < 8; i++) {
1088
+ output(lhs_vert, horiz_base + i) = results[i].x;
1089
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
1090
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
1091
+ output(lhs_vert + 3, horiz_base + i) = results[i].w;
1092
+ }
1093
+ } else if (lhs_vert + 2 < m_size) {
1094
+ for (int i = 0; i < 8; i++) {
1095
+ output(lhs_vert, horiz_base + i) = results[i].x;
1096
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
1097
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
1098
+ }
1099
+ } else if (lhs_vert + 1 < m_size) {
1100
+ for (int i = 0; i < 8; i++) {
1101
+ output(lhs_vert, horiz_base + i) = results[i].x;
1102
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
1103
+ }
1104
+ } else if (lhs_vert < m_size) {
1105
+ for (int i = 0; i < 8; i++) {
1106
+ output(lhs_vert, horiz_base + i) = results[i].x;
1107
+ }
1108
+ }
1109
+ } else if (!CHECK_LHS_BOUNDARY) {
1110
+ // CHECK BOUNDARY_B
1111
+ for (int i = 0; i < 8; i++) {
1112
+ if (horiz_base + i < n_size) {
1113
+ output(lhs_vert, horiz_base + i) = results[i].x;
1114
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
1115
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
1116
+ output(lhs_vert + 3, horiz_base + i) = results[i].w;
1117
+ }
1118
+ }
1119
+ } else {
1120
+ // CHECK both boundaries.
1121
+ for (int i = 0; i < 8; i++) {
1122
+ if (horiz_base + i < n_size) {
1123
+ if (lhs_vert < m_size)
1124
+ output(lhs_vert, horiz_base + i) = results[i].x;
1125
+ if (lhs_vert + 1 < m_size)
1126
+ output(lhs_vert + 1, horiz_base + i) = results[i].y;
1127
+ if (lhs_vert + 2 < m_size)
1128
+ output(lhs_vert + 2, horiz_base + i) = results[i].z;
1129
+ if (lhs_vert + 3 < m_size)
1130
+ output(lhs_vert + 3, horiz_base + i) = results[i].w;
1131
+ }
1132
+ }
1133
+ }
1134
+ }
1135
+
1136
+
1137
+ template<typename Index, typename LhsMapper,
1138
+ typename RhsMapper, typename OutputMapper>
1139
+ __global__ void
1140
+ #if defined(EIGEN_HIPCC)
1141
+ __launch_bounds__(256, 1)
1142
+ #else
1143
+ __launch_bounds__(256)
1144
+ #endif
1145
+ EigenFloatContractionKernel(const LhsMapper lhs, const RhsMapper rhs,
1146
+ const OutputMapper output,
1147
+ const Index m_size, const Index n_size, const Index k_size) {
1148
+ __shared__ float2 lhs_shmem[64*32];
1149
+ __shared__ float2 rhs_shmem[128*8];
1150
+
1151
+ typedef float2 LHS_MEM[64][32];
1152
+ typedef float2 RHS_MEM[128][8];
1153
+
1154
+ const Index m_block_idx = blockIdx.x;
1155
+ const Index n_block_idx = blockIdx.y;
1156
+
1157
+ const Index base_m = 128 * m_block_idx;
1158
+ const Index base_n = 64 * n_block_idx;
1159
+
1160
+ bool check_rhs = (base_n + 63) >= n_size;
1161
+ bool check_lhs128 = (base_m + 127) >= m_size;
1162
+
1163
+ if (!check_rhs) {
1164
+ if (!check_lhs128) {
1165
+ // >= 128 rows left
1166
+ EigenFloatContractionKernelInternal<Index, LhsMapper, RhsMapper, OutputMapper, false, false>(
1167
+ lhs, rhs, output, *((LHS_MEM *) lhs_shmem), *((RHS_MEM *) rhs_shmem), m_size, n_size, k_size, base_m, base_n);
1168
+ } else {
1169
+ EigenFloatContractionKernelInternal<Index, LhsMapper, RhsMapper, OutputMapper, true, false>(
1170
+ lhs, rhs, output, *((LHS_MEM *) lhs_shmem), *((RHS_MEM *) rhs_shmem), m_size, n_size, k_size, base_m, base_n);
1171
+ }
1172
+ } else {
1173
+ if (!check_lhs128) {
1174
+ // >= 128 rows left
1175
+ EigenFloatContractionKernelInternal<Index, LhsMapper, RhsMapper, OutputMapper, false, true>(
1176
+ lhs, rhs, output, *((LHS_MEM *) lhs_shmem), *((RHS_MEM *) rhs_shmem), m_size, n_size, k_size, base_m, base_n);
1177
+ } else {
1178
+ EigenFloatContractionKernelInternal<Index, LhsMapper, RhsMapper, OutputMapper, true, true>(
1179
+ lhs, rhs, output, *((LHS_MEM *) lhs_shmem), *((RHS_MEM *) rhs_shmem), m_size, n_size, k_size, base_m, base_n);
1180
+ }
1181
+ }
1182
+ }
1183
+
1184
+ template<typename Index, typename LhsMapper,
1185
+ typename RhsMapper, typename OutputMapper>
1186
+ __global__ void
1187
+ #if defined(EIGEN_HIPCC)
1188
+ __launch_bounds__(256, 1)
1189
+ #else
1190
+ __launch_bounds__(256)
1191
+ #endif
1192
+ EigenFloatContractionKernel16x16(const LhsMapper lhs, const RhsMapper rhs,
1193
+ const OutputMapper output,
1194
+ const Index m_size, const Index n_size, const Index k_size) {
1195
+ __shared__ float2 lhs_shmem[32][16];
1196
+ __shared__ float2 rhs_shmem[64][8];
1197
+
1198
+ const Index m_block_idx = blockIdx.x;
1199
+ const Index n_block_idx = blockIdx.y;
1200
+
1201
+ const Index base_m = 64 * m_block_idx;
1202
+ const Index base_n = 64 * n_block_idx;
1203
+
1204
+ if (base_m + 63 < m_size) {
1205
+ if (base_n + 63 < n_size) {
1206
+ EigenFloatContractionKernelInternal16x16<Index, LhsMapper, RhsMapper, OutputMapper, false, false>(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size, base_m, base_n);
1207
+ } else {
1208
+ EigenFloatContractionKernelInternal16x16<Index, LhsMapper, RhsMapper, OutputMapper, false, true>(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size, base_m, base_n);
1209
+ }
1210
+ } else {
1211
+ if (base_n + 63 < n_size) {
1212
+ EigenFloatContractionKernelInternal16x16<Index, LhsMapper, RhsMapper, OutputMapper, true, false>(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size, base_m, base_n);
1213
+ } else {
1214
+ EigenFloatContractionKernelInternal16x16<Index, LhsMapper, RhsMapper, OutputMapper, true, true>(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size, base_m, base_n);
1215
+ }
1216
+ }
1217
+ }
1218
+
1219
+
1220
+ template<typename Indices, typename LeftArgType, typename RightArgType, typename OutputKernelType>
1221
+ struct TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, GpuDevice> :
1222
+ public TensorContractionEvaluatorBase<TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, GpuDevice> > {
1223
+
1224
+ typedef GpuDevice Device;
1225
+
1226
+ typedef TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, Device> Self;
1227
+ typedef TensorContractionEvaluatorBase<Self> Base;
1228
+
1229
+ typedef TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType> XprType;
1230
+ typedef std::remove_const_t<typename XprType::Scalar> Scalar;
1231
+ typedef typename XprType::Index Index;
1232
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
1233
+ typedef typename PacketType<CoeffReturnType, GpuDevice>::type PacketReturnType;
1234
+
1235
+ static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
1236
+
1237
+ // Most of the code is assuming that both input tensors are ColMajor. If the
1238
+ // inputs are RowMajor, we will "cheat" by swapping the LHS and RHS:
1239
+ // If we want to compute A * B = C, where A is LHS and B is RHS, the code
1240
+ // will pretend B is LHS and A is RHS.
1241
+ typedef std::conditional_t<Layout == static_cast<int>(ColMajor), LeftArgType, RightArgType> EvalLeftArgType;
1242
+ typedef std::conditional_t<Layout == static_cast<int>(ColMajor), RightArgType, LeftArgType> EvalRightArgType;
1243
+
1244
+ static constexpr int LDims =
1245
+ internal::array_size<typename TensorEvaluator<EvalLeftArgType, Device>::Dimensions>::value;
1246
+ static constexpr int RDims =
1247
+ internal::array_size<typename TensorEvaluator<EvalRightArgType, Device>::Dimensions>::value;
1248
+ static constexpr int ContractDims = internal::array_size<Indices>::value;
1249
+
1250
+ typedef array<Index, LDims> left_dim_mapper_t;
1251
+ typedef array<Index, RDims> right_dim_mapper_t;
1252
+
1253
+ typedef array<Index, ContractDims> contract_t;
1254
+ typedef array<Index, LDims - ContractDims> left_nocontract_t;
1255
+ typedef array<Index, RDims - ContractDims> right_nocontract_t;
1256
+
1257
+ static constexpr int NumDims = LDims + RDims - 2 * ContractDims;
1258
+
1259
+ typedef DSizes<Index, NumDims> Dimensions;
1260
+
1261
+ // typedefs needed in evalTo
1262
+ typedef std::remove_const_t<typename EvalLeftArgType::Scalar> LhsScalar;
1263
+ typedef std::remove_const_t<typename EvalRightArgType::Scalar> RhsScalar;
1264
+
1265
+ typedef TensorEvaluator<EvalLeftArgType, Device> LeftEvaluator;
1266
+ typedef TensorEvaluator<EvalRightArgType, Device> RightEvaluator;
1267
+
1268
+ typedef typename LeftEvaluator::Dimensions LeftDimensions;
1269
+ typedef typename RightEvaluator::Dimensions RightDimensions;
1270
+
1271
+ TensorEvaluator(const XprType& op, const Device& device) :
1272
+ Base(op, device)
1273
+ {
1274
+ EIGEN_STATIC_ASSERT( (internal::is_same<OutputKernelType, const NoOpOutputKernel>::value),
1275
+ GPU_TENSOR_CONTRACTION_DOES_NOT_SUPPORT_OUTPUT_KERNELS);
1276
+ }
1277
+
1278
+ // We need to redefine this method to make nvcc happy
1279
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(Scalar* data) {
1280
+ this->m_leftImpl.evalSubExprsIfNeeded(NULL);
1281
+ this->m_rightImpl.evalSubExprsIfNeeded(NULL);
1282
+ if (data) {
1283
+ evalTo(data);
1284
+ return false;
1285
+ } else {
1286
+ this->m_result = static_cast<Scalar *>(this->m_device.allocate(this->dimensions().TotalSize() * sizeof(Scalar)));
1287
+ evalTo(this->m_result);
1288
+ return true;
1289
+ }
1290
+ }
1291
+
1292
+ void evalTo(Scalar* buffer) const {
1293
+ if (this->m_lhs_inner_dim_contiguous) {
1294
+ if (this->m_rhs_inner_dim_contiguous) {
1295
+ if (this->m_rhs_inner_dim_reordered) {
1296
+ evalTyped<true, true, true, Unaligned>(buffer);
1297
+ }
1298
+ else {
1299
+ evalTyped<true, true, false, Unaligned>(buffer);
1300
+ }
1301
+ }
1302
+ else {
1303
+ if (this->m_rhs_inner_dim_reordered) {
1304
+ evalTyped<true, false, true, Unaligned>(buffer);
1305
+ }
1306
+ else {
1307
+ evalTyped<true, false, false, Unaligned>(buffer);
1308
+ }
1309
+ }
1310
+ }
1311
+ else {
1312
+ if (this->m_rhs_inner_dim_contiguous) {
1313
+ if (this->m_rhs_inner_dim_reordered) {
1314
+ evalTyped<false, true, true, Unaligned>(buffer);
1315
+ }
1316
+ else {
1317
+ evalTyped<false, true, false, Unaligned>(buffer);
1318
+ }
1319
+ }
1320
+ else {
1321
+ if (this->m_rhs_inner_dim_reordered) {
1322
+ evalTyped<false, false, true, Unaligned>(buffer);
1323
+ }
1324
+ else {
1325
+ evalTyped<false, false, false, Unaligned>(buffer);
1326
+ }
1327
+ }
1328
+ }
1329
+ }
1330
+
1331
+ template <typename LhsScalar, typename RhsScalar, typename Index, typename LhsMapper, typename RhsMapper, typename OutputMapper> struct LaunchKernels {
1332
+ static void Run(const LhsMapper& lhs, const RhsMapper& rhs, const OutputMapper& output, Index m, Index n, Index k, const GpuDevice& device) {
1333
+ const Index m_blocks = (m + 63) / 64;
1334
+ const Index n_blocks = (n + 63) / 64;
1335
+ const dim3 num_blocks(m_blocks, n_blocks, 1);
1336
+ const dim3 block_size(8, 8, 8);
1337
+ LAUNCH_GPU_KERNEL((EigenContractionKernel<Scalar, Index, LhsMapper, RhsMapper, OutputMapper>), num_blocks, block_size, 0, device, lhs, rhs, output, m, n, k);
1338
+ }
1339
+ };
1340
+
1341
+ template <typename Index, typename LhsMapper, typename RhsMapper, typename OutputMapper> struct LaunchKernels<float, float, Index, LhsMapper, RhsMapper, OutputMapper> {
1342
+ static void Run(const LhsMapper& lhs, const RhsMapper& rhs, const OutputMapper& output, Index m, Index n, Index k, const GpuDevice& device) {
1343
+ if (m < 768 || n < 768) {
1344
+ const Index m_blocks = (m + 63) / 64;
1345
+ const Index n_blocks = (n + 63) / 64;
1346
+ const dim3 num_blocks(m_blocks, n_blocks, 1);
1347
+ const dim3 block_size(16, 16, 1);
1348
+ LAUNCH_GPU_KERNEL((EigenFloatContractionKernel16x16<Index, LhsMapper, RhsMapper, OutputMapper>), num_blocks, block_size, 0, device, lhs, rhs, output, m, n, k);
1349
+ } else {
1350
+ const Index m_blocks = (m + 127) / 128;
1351
+ const Index n_blocks = (n + 63) / 64;
1352
+ const dim3 num_blocks(m_blocks, n_blocks, 1);
1353
+ const dim3 block_size(8, 32, 1);
1354
+ LAUNCH_GPU_KERNEL((EigenFloatContractionKernel<Index, LhsMapper, RhsMapper, OutputMapper>), num_blocks, block_size, 0, device, lhs, rhs, output, m, n, k);
1355
+ }
1356
+ }
1357
+ };
1358
+
1359
+ template <bool lhs_inner_dim_contiguous, bool rhs_inner_dim_contiguous, bool rhs_inner_dim_reordered, int Alignment>
1360
+ void evalTyped(Scalar* buffer) const {
1361
+ // columns in left side, rows in right side
1362
+ const Index k = this->m_k_size;
1363
+ EIGEN_UNUSED_VARIABLE(k)
1364
+
1365
+ // rows in left side
1366
+ const Index m = this->m_i_size;
1367
+
1368
+ // columns in right side
1369
+ const Index n = this->m_j_size;
1370
+
1371
+ // zero out the result buffer (which must be of size at least m * n * sizeof(Scalar))
1372
+ this->m_device.fill(buffer, buffer + m * n, Scalar(0));
1373
+
1374
+ typedef internal::TensorContractionInputMapper<LhsScalar, Index, internal::Lhs,
1375
+ LeftEvaluator, left_nocontract_t,
1376
+ contract_t, 4,
1377
+ lhs_inner_dim_contiguous,
1378
+ false, Unaligned> LhsMapper;
1379
+
1380
+ typedef internal::TensorContractionInputMapper<RhsScalar, Index, internal::Rhs,
1381
+ RightEvaluator, right_nocontract_t,
1382
+ contract_t, 4,
1383
+ rhs_inner_dim_contiguous,
1384
+ rhs_inner_dim_reordered, Unaligned> RhsMapper;
1385
+
1386
+ typedef internal::blas_data_mapper<Scalar, Index, ColMajor> OutputMapper;
1387
+
1388
+
1389
+ // initialize data mappers
1390
+ LhsMapper lhs(this->m_leftImpl, this->m_left_nocontract_strides, this->m_i_strides,
1391
+ this->m_left_contracting_strides, this->m_k_strides);
1392
+
1393
+ RhsMapper rhs(this->m_rightImpl, this->m_right_nocontract_strides, this->m_j_strides,
1394
+ this->m_right_contracting_strides, this->m_k_strides);
1395
+
1396
+ OutputMapper output(buffer, m);
1397
+
1398
+ #if defined(EIGEN_USE_HIP)
1399
+ setGpuSharedMemConfig(hipSharedMemBankSizeEightByte);
1400
+ #else
1401
+ setGpuSharedMemConfig(cudaSharedMemBankSizeEightByte);
1402
+ #endif
1403
+
1404
+ LaunchKernels<LhsScalar, RhsScalar, Index, LhsMapper, RhsMapper, OutputMapper>::Run(lhs, rhs, output, m, n, k, this->m_device);
1405
+ }
1406
+ };
1407
+
1408
+ } // end namespace Eigen
1409
+
1410
+ #endif // EIGEN_USE_GPU and EIGEN_GPUCC
1411
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_GPU_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionMapper.h ADDED
@@ -0,0 +1,573 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_MAPPER_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_MAPPER_H
12
+
13
+ #include "./InternalHeaderCheck.h"
14
+
15
+ namespace Eigen {
16
+
17
+ namespace internal {
18
+
19
+ enum {
20
+ Rhs = 0,
21
+ Lhs = 1
22
+ };
23
+
24
+ /*
25
+ * Implementation of the Eigen blas_data_mapper class for tensors.
26
+ */
27
+ /// The make pointer class is used by sycl in order to build the mapper class on the device. For other platform the default make pointer is used which
28
+ /// is scalar * for CoeffLoader.
29
+ template <typename Tensor, bool HasRawAccess, template <class> class MakePointer_ = MakePointer>
30
+ struct CoeffLoader;
31
+
32
+ template <typename Scalar, typename Index, int side, typename Tensor,
33
+ typename nocontract_t, typename contract_t, int packet_size,
34
+ bool inner_dim_contiguous, bool inner_dim_reordered, int Alignment,
35
+ template <class> class MakePointer_ = MakePointer>
36
+ class BaseTensorContractionMapper;
37
+
38
+ template <typename Tensor, bool HasRawAccess, template <class> class MakePointer_>
39
+ struct CoeffLoader {
40
+ enum {
41
+ DirectOffsets = false
42
+ };
43
+
44
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE CoeffLoader(const Tensor& tensor) : m_tensor(tensor) { }
45
+
46
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void offsetBuffer(typename Tensor::Index) {
47
+ eigen_assert(false && "unsupported");
48
+ }
49
+
50
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE const typename MakePointer_<const typename Tensor::Scalar>::Type
51
+ data() const {
52
+ eigen_assert(false && "unsupported");
53
+ return NULL;
54
+ }
55
+
56
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE typename Tensor::Scalar coeff(typename Tensor::Index index) const { return m_tensor.coeff(index); }
57
+
58
+ template<int LoadMode> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
59
+ typename Tensor::PacketReturnType packet(typename Tensor::Index index) const
60
+ {
61
+ return m_tensor.template packet<LoadMode>(index);
62
+ }
63
+
64
+ private:
65
+ const Tensor m_tensor;
66
+ };
67
+
68
+ template <typename Tensor, template <class> class MakePointer_>
69
+ struct CoeffLoader<Tensor, true, MakePointer_> {
70
+ enum {
71
+ DirectOffsets = true
72
+ };
73
+
74
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE CoeffLoader(const Tensor& tensor) : m_data(tensor.data()) {}
75
+
76
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void offsetBuffer(typename Tensor::Index offset) {
77
+ m_data += offset;
78
+ }
79
+
80
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE const typename MakePointer_<const typename Tensor::Scalar>::Type
81
+ data() const {
82
+ return m_data;
83
+ }
84
+
85
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE typename Tensor::Scalar coeff(typename Tensor::Index index) const { return loadConstant(m_data+index); }
86
+
87
+ template<int LoadMode> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
88
+ typename Tensor::PacketReturnType packet(typename Tensor::Index index) const
89
+ {
90
+ return internal::ploadt_ro<typename Tensor::PacketReturnType, LoadMode>(m_data + index);
91
+ }
92
+
93
+ private:
94
+ typedef typename Tensor::Scalar Scalar;
95
+
96
+ typename MakePointer_<const Scalar>::Type m_data;
97
+ };
98
+
99
+ template<typename Scalar, typename Index, int side,
100
+ typename Tensor,
101
+ typename nocontract_t, typename contract_t,
102
+ int packet_size, bool inner_dim_contiguous, int Alignment, template <class> class MakePointer_ = MakePointer>
103
+ class SimpleTensorContractionMapper {
104
+ public:
105
+ EIGEN_DEVICE_FUNC
106
+ SimpleTensorContractionMapper(const Tensor& tensor,
107
+ const nocontract_t& nocontract_strides,
108
+ const nocontract_t& ij_strides,
109
+ const contract_t& contract_strides,
110
+ const contract_t& k_strides) :
111
+ m_tensor(tensor),
112
+ m_nocontract_strides(nocontract_strides),
113
+ m_ij_strides(ij_strides),
114
+ m_contract_strides(contract_strides),
115
+ m_k_strides(k_strides) { }
116
+
117
+ enum {
118
+ DirectOffsets = CoeffLoader<Tensor, Tensor::RawAccess, MakePointer_>::DirectOffsets
119
+ };
120
+
121
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void offsetBuffer(typename Tensor::Index offset) {
122
+ m_tensor.offsetBuffer(offset);
123
+ }
124
+
125
+ EIGEN_DEVICE_FUNC
126
+ EIGEN_STRONG_INLINE void prefetch(Index /*i*/) { }
127
+
128
+ EIGEN_DEVICE_FUNC
129
+ EIGEN_STRONG_INLINE Scalar operator()(Index row) const {
130
+ // column major assumption
131
+ return operator()(row, 0);
132
+ }
133
+
134
+ EIGEN_DEVICE_FUNC
135
+ EIGEN_STRONG_INLINE Scalar operator()(Index row, Index col) const {
136
+ return m_tensor.coeff(computeIndex(row, col));
137
+ }
138
+
139
+ EIGEN_DEVICE_FUNC
140
+ EIGEN_STRONG_INLINE Index computeIndex(Index row, Index col) const {
141
+ const bool left = (side == Lhs);
142
+ EIGEN_UNUSED_VARIABLE(left); // annoying bug in g++8.1: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85963
143
+ Index nocontract_val = left ? row : col;
144
+ Index linidx = 0;
145
+ EIGEN_UNROLL_LOOP
146
+ for (int i = static_cast<int>(array_size<nocontract_t>::value) - 1; i > 0; i--) {
147
+ const Index idx = nocontract_val / m_ij_strides[i];
148
+ linidx += idx * m_nocontract_strides[i];
149
+ nocontract_val -= idx * m_ij_strides[i];
150
+ }
151
+ if (array_size<typename Tensor::Dimensions>::value > array_size<contract_t>::value) {
152
+ if (side == Lhs && inner_dim_contiguous) {
153
+ eigen_assert(m_nocontract_strides[0] == 1);
154
+ linidx += nocontract_val;
155
+ } else {
156
+ linidx += nocontract_val * m_nocontract_strides[0];
157
+ }
158
+ }
159
+
160
+ Index contract_val = left ? col : row;
161
+ if(array_size<contract_t>::value > 0) {
162
+ EIGEN_UNROLL_LOOP
163
+ for (int i = static_cast<int>(array_size<contract_t>::value) - 1; i > 0; i--) {
164
+ const Index idx = contract_val / m_k_strides[i];
165
+ linidx += idx * m_contract_strides[i];
166
+ contract_val -= idx * m_k_strides[i];
167
+ }
168
+
169
+ if (side == Rhs && inner_dim_contiguous) {
170
+ eigen_assert(m_contract_strides[0] == 1);
171
+ linidx += contract_val;
172
+ } else {
173
+ linidx += contract_val * m_contract_strides[0];
174
+ }
175
+ }
176
+
177
+ return linidx;
178
+ }
179
+
180
+ EIGEN_DEVICE_FUNC
181
+ EIGEN_STRONG_INLINE IndexPair<Index> computeIndexPair(Index row, Index col, const Index distance) const {
182
+ const bool left = (side == Lhs);
183
+ EIGEN_UNUSED_VARIABLE(left); // annoying bug in g++8.1: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85963
184
+ Index nocontract_val[2] = {left ? row : col, left ? row + distance : col};
185
+ Index linidx[2] = {0, 0};
186
+ if (array_size<typename Tensor::Dimensions>::value > array_size<contract_t>::value) {
187
+ EIGEN_UNROLL_LOOP
188
+ for (int i = static_cast<int>(array_size<nocontract_t>::value) - 1; i > 0; i--) {
189
+ const Index idx0 = nocontract_val[0] / m_ij_strides[i];
190
+ const Index idx1 = nocontract_val[1] / m_ij_strides[i];
191
+ linidx[0] += idx0 * m_nocontract_strides[i];
192
+ linidx[1] += idx1 * m_nocontract_strides[i];
193
+ nocontract_val[0] -= idx0 * m_ij_strides[i];
194
+ nocontract_val[1] -= idx1 * m_ij_strides[i];
195
+ }
196
+ if (side == Lhs && inner_dim_contiguous) {
197
+ eigen_assert(m_nocontract_strides[0] == 1);
198
+ linidx[0] += nocontract_val[0];
199
+ linidx[1] += nocontract_val[1];
200
+ } else {
201
+ linidx[0] += nocontract_val[0] * m_nocontract_strides[0];
202
+ linidx[1] += nocontract_val[1] * m_nocontract_strides[0];
203
+ }
204
+ }
205
+
206
+ Index contract_val[2] = {left ? col : row, left ? col : row + distance};
207
+ if (array_size<contract_t>::value> 0) {
208
+ EIGEN_UNROLL_LOOP
209
+ for (int i = static_cast<int>(array_size<contract_t>::value) - 1; i > 0; i--) {
210
+ const Index idx0 = contract_val[0] / m_k_strides[i];
211
+ const Index idx1 = contract_val[1] / m_k_strides[i];
212
+ linidx[0] += idx0 * m_contract_strides[i];
213
+ linidx[1] += idx1 * m_contract_strides[i];
214
+ contract_val[0] -= idx0 * m_k_strides[i];
215
+ contract_val[1] -= idx1 * m_k_strides[i];
216
+ }
217
+
218
+ if (side == Rhs && inner_dim_contiguous) {
219
+ eigen_assert(m_contract_strides[0] == 1);
220
+ linidx[0] += contract_val[0];
221
+ linidx[1] += contract_val[1];
222
+ } else {
223
+ linidx[0] += contract_val[0] * m_contract_strides[0];
224
+ linidx[1] += contract_val[1] * m_contract_strides[0];
225
+ }
226
+ }
227
+ return IndexPair<Index>(linidx[0], linidx[1]);
228
+ }
229
+
230
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Index firstAligned(Index size) const {
231
+ // Only claim alignment when we can compute the actual stride (ie when we're
232
+ // dealing with the lhs with inner_dim_contiguous. This is because the
233
+ // matrix-vector product relies on the stride when dealing with aligned inputs.
234
+ return (Alignment == Aligned) && (side == Lhs) && inner_dim_contiguous ? 0 : size;
235
+ }
236
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Index stride() const {
237
+ return ((side == Lhs) && inner_dim_contiguous && array_size<contract_t>::value > 0) ? m_contract_strides[0] : 1;
238
+ }
239
+
240
+ const CoeffLoader<Tensor, Tensor::RawAccess, MakePointer_>& tensor() const {
241
+ return m_tensor;
242
+ }
243
+
244
+ const nocontract_t& nocontract_strides() const {
245
+ return m_nocontract_strides;
246
+ }
247
+ const nocontract_t& ij_strides() const { return m_ij_strides; }
248
+ const contract_t& contract_strides() const { return m_contract_strides; }
249
+ const contract_t& k_strides() const { return m_k_strides; }
250
+
251
+ protected:
252
+ CoeffLoader<Tensor, Tensor::RawAccess, MakePointer_> m_tensor;
253
+ const nocontract_t m_nocontract_strides;
254
+ const nocontract_t m_ij_strides;
255
+ const contract_t m_contract_strides;
256
+ const contract_t m_k_strides;
257
+ };
258
+
259
+ template<typename Scalar, typename Index, int side,
260
+ typename Tensor,
261
+ typename nocontract_t, typename contract_t,
262
+ int packet_size, bool inner_dim_contiguous,
263
+ bool inner_dim_reordered, int Alignment, template <class> class MakePointer_>
264
+ class BaseTensorContractionMapper : public SimpleTensorContractionMapper<Scalar, Index, side, Tensor, nocontract_t, contract_t, packet_size, inner_dim_contiguous, Alignment, MakePointer_>
265
+ {
266
+ public:
267
+ typedef SimpleTensorContractionMapper<Scalar, Index, side, Tensor, nocontract_t, contract_t, packet_size, inner_dim_contiguous, Alignment, MakePointer_> ParentMapper;
268
+
269
+ EIGEN_DEVICE_FUNC
270
+ BaseTensorContractionMapper(const Tensor& tensor,
271
+ const nocontract_t& nocontract_strides,
272
+ const nocontract_t& ij_strides,
273
+ const contract_t& contract_strides,
274
+ const contract_t& k_strides) :
275
+ ParentMapper(tensor, nocontract_strides, ij_strides, contract_strides, k_strides) { }
276
+
277
+ template <typename PacketT,int AlignmentType>
278
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
279
+ std::enable_if_t<internal::unpacket_traits<PacketT>::size==packet_size,PacketT>
280
+ load(Index i, Index j) const
281
+ {
282
+ // whole method makes column major assumption
283
+
284
+ // don't need to add offsets for now (because operator handles that)
285
+ // current code assumes packet size must be a multiple of 2
286
+ EIGEN_STATIC_ASSERT(packet_size % 2 == 0, YOU_MADE_A_PROGRAMMING_MISTAKE);
287
+
288
+ if (Tensor::PacketAccess && inner_dim_contiguous && !inner_dim_reordered) {
289
+ const Index index = this->computeIndex(i, j);
290
+ eigen_assert(this->computeIndex(i+packet_size-1, j) == index + packet_size-1);
291
+ return this->m_tensor.template packet<AlignmentType>(index);
292
+ }
293
+
294
+ const IndexPair<Index> indexPair = this->computeIndexPair(i, j, packet_size - 1);
295
+ const Index first = indexPair.first;
296
+ const Index lastIdx = indexPair.second;
297
+
298
+ // We can always do optimized packet reads from left hand side right now, because
299
+ // the vertical matrix dimension on the left hand side is never contracting.
300
+ // On the right hand side we need to check if the contracting dimensions may have
301
+ // been shuffled first.
302
+ if (Tensor::PacketAccess &&
303
+ (side == Lhs || internal::array_size<contract_t>::value <= 1 || !inner_dim_reordered) &&
304
+ (lastIdx - first) == (packet_size - 1)) {
305
+
306
+ return this->m_tensor.template packet<AlignmentType>(first);
307
+ }
308
+
309
+ EIGEN_ALIGN_MAX Scalar data[packet_size];
310
+
311
+ data[0] = this->m_tensor.coeff(first);
312
+ EIGEN_UNROLL_LOOP
313
+ for (Index k = 1; k < packet_size - 1; k += 2) {
314
+ const IndexPair<Index> internal_pair = this->computeIndexPair(i + k, j, 1);
315
+ data[k] = this->m_tensor.coeff(internal_pair.first);
316
+ data[k + 1] = this->m_tensor.coeff(internal_pair.second);
317
+ }
318
+ data[packet_size - 1] = this->m_tensor.coeff(lastIdx);
319
+
320
+ return pload<PacketT>(data);
321
+ }
322
+
323
+ template <typename PacketT,int AlignmentType>
324
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
325
+ std::enable_if_t<internal::unpacket_traits<PacketT>::size!=packet_size,PacketT>
326
+ load(Index i, Index j) const
327
+ {
328
+ const Index requested_packet_size = internal::unpacket_traits<PacketT>::size;
329
+ EIGEN_ALIGN_MAX Scalar data[requested_packet_size];
330
+
331
+ const IndexPair<Index> indexPair = this->computeIndexPair(i, j, requested_packet_size - 1);
332
+ const Index first = indexPair.first;
333
+ const Index lastIdx = indexPair.second;
334
+
335
+ data[0] = this->m_tensor.coeff(first);
336
+ for (Index k = 1; k < requested_packet_size - 1; k += 2) {
337
+ const IndexPair<Index> internal_pair = this->computeIndexPair(i + k, j, 1);
338
+ data[k] = this->m_tensor.coeff(internal_pair.first);
339
+ data[k + 1] = this->m_tensor.coeff(internal_pair.second);
340
+ }
341
+ data[requested_packet_size - 1] = this->m_tensor.coeff(lastIdx);
342
+
343
+ return pload<PacketT>(data);
344
+ }
345
+
346
+ template <typename PacketT,int AlignmentType>
347
+ EIGEN_DEVICE_FUNC
348
+ EIGEN_STRONG_INLINE PacketT loadPacket(Index i, Index j) const {
349
+ return this->load<PacketT,AlignmentType>(i,j);
350
+ }
351
+ };
352
+
353
+
354
+ template<typename Scalar, typename Index, int side,
355
+ typename Tensor,
356
+ typename nocontract_t, typename contract_t,
357
+ bool inner_dim_contiguous,
358
+ bool inner_dim_reordered, int Alignment, template <class> class MakePointer_>
359
+ class BaseTensorContractionMapper<Scalar, Index, side, Tensor, nocontract_t, contract_t, 1, inner_dim_contiguous, inner_dim_reordered, Alignment, MakePointer_>
360
+ : public SimpleTensorContractionMapper<Scalar, Index, side, Tensor, nocontract_t, contract_t, 1, inner_dim_contiguous, Alignment, MakePointer_>
361
+ {
362
+ public:
363
+ typedef SimpleTensorContractionMapper<Scalar, Index, side, Tensor, nocontract_t, contract_t, 1, inner_dim_contiguous, Alignment, MakePointer_> ParentMapper;
364
+
365
+ EIGEN_DEVICE_FUNC
366
+ BaseTensorContractionMapper(const Tensor& tensor,
367
+ const nocontract_t& nocontract_strides,
368
+ const nocontract_t& ij_strides,
369
+ const contract_t& contract_strides,
370
+ const contract_t& k_strides) :
371
+ ParentMapper(tensor, nocontract_strides, ij_strides, contract_strides, k_strides) { }
372
+
373
+ template <typename PacketT,int> EIGEN_DEVICE_FUNC
374
+ EIGEN_STRONG_INLINE PacketT loadPacket(Index i, Index j) const {
375
+ EIGEN_ALIGN_MAX Scalar data[1];
376
+ data[0] = this->m_tensor.coeff(this->computeIndex(i, j));
377
+ return pload<PacketT>(data);
378
+ }
379
+ template <typename PacketT,int> EIGEN_DEVICE_FUNC
380
+ EIGEN_STRONG_INLINE PacketT load(Index i, Index j) const {
381
+ EIGEN_ALIGN_MAX Scalar data[1];
382
+ data[0] = this->m_tensor.coeff(this->computeIndex(i, j));
383
+ return pload<PacketT>(data);
384
+ }
385
+ };
386
+
387
+
388
+ template<typename Scalar, typename Index, int side,
389
+ typename Tensor,
390
+ typename nocontract_t, typename contract_t,
391
+ int packet_size,
392
+ bool inner_dim_contiguous, bool inner_dim_reordered, int Alignment, template <class> class MakePointer_=MakePointer>
393
+ class TensorContractionSubMapper {
394
+ public:
395
+
396
+ typedef BaseTensorContractionMapper<Scalar, Index, side, Tensor, nocontract_t, contract_t, packet_size, inner_dim_contiguous, inner_dim_reordered, Alignment, MakePointer_> ParentMapper;
397
+ typedef TensorContractionSubMapper<Scalar, Index, side, Tensor, nocontract_t, contract_t, packet_size, inner_dim_contiguous, inner_dim_reordered, Alignment, MakePointer_> Self;
398
+ typedef Self LinearMapper;
399
+ typedef Self SubMapper;
400
+
401
+ enum {
402
+ // We can use direct offsets iff the parent mapper supports then and we can compute the strides.
403
+ // TODO: we should also enable direct offsets for the Rhs case.
404
+ UseDirectOffsets = ParentMapper::DirectOffsets && (side == Lhs) && inner_dim_contiguous && (array_size<contract_t>::value > 0)
405
+ };
406
+
407
+ EIGEN_DEVICE_FUNC TensorContractionSubMapper(const ParentMapper& base_mapper, Index vert_offset, Index horiz_offset)
408
+ : m_base_mapper(base_mapper), m_vert_offset(vert_offset), m_horiz_offset(horiz_offset) {
409
+ // Bake the offsets into the buffer used by the base mapper whenever possible. This avoids the need to recompute
410
+ // this offset every time we attempt to access a coefficient.
411
+ if (UseDirectOffsets) {
412
+ Index stride = m_base_mapper.stride();
413
+ m_base_mapper.offsetBuffer(vert_offset + horiz_offset * stride);
414
+ }
415
+ }
416
+
417
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Scalar operator()(Index i) const {
418
+ if (UseDirectOffsets) {
419
+ return m_base_mapper(i, 0);
420
+ }
421
+ return m_base_mapper(i + m_vert_offset, m_horiz_offset);
422
+ }
423
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Scalar operator()(Index i, Index j) const {
424
+ if (UseDirectOffsets) {
425
+ return m_base_mapper(i, j);
426
+ }
427
+ return m_base_mapper(i + m_vert_offset, j + m_horiz_offset);
428
+ }
429
+
430
+ template <typename PacketT>
431
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT loadPacket(Index i) const {
432
+ if (UseDirectOffsets) {
433
+ return m_base_mapper.template loadPacket<PacketT,Alignment>(i, 0);
434
+ }
435
+ return m_base_mapper.template loadPacket<PacketT,Alignment>(i + m_vert_offset, m_horiz_offset);
436
+ }
437
+
438
+ template <typename PacketT>
439
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT loadPacket(Index i, Index j) const {
440
+ if (UseDirectOffsets) {
441
+ return m_base_mapper.template loadPacket<PacketT,Alignment>(i, j);
442
+ }
443
+ return m_base_mapper.template loadPacket<PacketT,Alignment>(i + m_vert_offset, j + m_horiz_offset);
444
+ }
445
+
446
+ template <typename PacketT>
447
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT loadPacketPartial(Index i, Index j, Index, Index = 0) const {
448
+ if (UseDirectOffsets) {
449
+ return m_base_mapper.template loadPacket<PacketT,Alignment>(i, j);
450
+ }
451
+ return m_base_mapper.template loadPacket<PacketT,Alignment>(i + m_vert_offset, j + m_horiz_offset);
452
+ }
453
+
454
+ template <typename PacketT, int AlignmentType>
455
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT loadPacket(Index i, Index j) const {
456
+ if (UseDirectOffsets) {
457
+ return m_base_mapper.template load<PacketT,AlignmentType>(i, j);
458
+ }
459
+ return m_base_mapper.template loadPacket<PacketT,AlignmentType>(i + m_vert_offset, j + m_horiz_offset);
460
+ }
461
+
462
+ template <typename PacketT>
463
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void storePacket(Index i, const PacketT& p) const {
464
+ if (UseDirectOffsets) {
465
+ m_base_mapper.storePacket(i, 0, p);
466
+ }
467
+ m_base_mapper.storePacket(i + m_vert_offset, m_horiz_offset, p);
468
+ }
469
+
470
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE LinearMapper getLinearMapper(Index i, Index j) const {
471
+ if (UseDirectOffsets) {
472
+ return LinearMapper(m_base_mapper, i, j);
473
+ }
474
+ return LinearMapper(m_base_mapper, i + m_vert_offset, j + m_horiz_offset);
475
+ }
476
+
477
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE SubMapper getSubMapper(Index i, Index j) const {
478
+ if (UseDirectOffsets) {
479
+ return SubMapper(m_base_mapper, i, j);
480
+ }
481
+ return SubMapper(m_base_mapper, i + m_vert_offset, j + m_horiz_offset);
482
+ }
483
+
484
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE const Index stride() const { return m_base_mapper.stride(); }
485
+
486
+ template <typename PacketT, int AlignmentType>
487
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT load(Index i) const {
488
+ EIGEN_STATIC_ASSERT((internal::is_same<PacketT, PacketT>::value), YOU_MADE_A_PROGRAMMING_MISTAKE);
489
+ const int ActualAlignment = (AlignmentType == Aligned) && (Alignment == Aligned) ? Aligned : Unaligned;
490
+ if (UseDirectOffsets) {
491
+ return m_base_mapper.template loadPacket<PacketT,ActualAlignment>(i, 0);
492
+ }
493
+ return m_base_mapper.template loadPacket<PacketT,ActualAlignment>(i + m_vert_offset, m_horiz_offset);
494
+ }
495
+
496
+ template <typename PacketT>
497
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE bool aligned(Index) const {
498
+ return false;
499
+ }
500
+
501
+ const ParentMapper& base_mapper() const { return m_base_mapper; }
502
+ Index vert_offset() const { return m_vert_offset; }
503
+ Index horiz_offset() const { return m_horiz_offset; }
504
+
505
+ private:
506
+ ParentMapper m_base_mapper;
507
+ const Index m_vert_offset;
508
+ const Index m_horiz_offset;
509
+ };
510
+
511
+
512
+ template<typename Scalar_, typename Index, int side,
513
+ typename Tensor,
514
+ typename nocontract_t, typename contract_t,
515
+ int packet_size,
516
+ bool inner_dim_contiguous, bool inner_dim_reordered, int Alignment, template <class> class MakePointer_=MakePointer>
517
+ class TensorContractionInputMapper
518
+ : public BaseTensorContractionMapper<Scalar_, Index, side, Tensor, nocontract_t, contract_t, packet_size, inner_dim_contiguous, inner_dim_reordered, Alignment, MakePointer_> {
519
+
520
+ public:
521
+ typedef Scalar_ Scalar;
522
+ typedef BaseTensorContractionMapper<Scalar, Index, side, Tensor, nocontract_t, contract_t, packet_size, inner_dim_contiguous, inner_dim_reordered, Alignment, MakePointer_> Base;
523
+ typedef TensorContractionSubMapper<Scalar, Index, side, Tensor, nocontract_t, contract_t, packet_size, inner_dim_contiguous, inner_dim_reordered, Alignment, MakePointer_> SubMapper;
524
+ typedef SubMapper VectorMapper;
525
+ typedef SubMapper LinearMapper;
526
+
527
+ EIGEN_DEVICE_FUNC TensorContractionInputMapper(const Tensor& tensor,
528
+ const nocontract_t& nocontract_strides,
529
+ const nocontract_t& ij_strides,
530
+ const contract_t& contract_strides,
531
+ const contract_t& k_strides)
532
+ : Base(tensor, nocontract_strides, ij_strides, contract_strides, k_strides) { }
533
+
534
+ EIGEN_DEVICE_FUNC
535
+ EIGEN_STRONG_INLINE SubMapper getSubMapper(Index i, Index j) const {
536
+ return SubMapper(*this, i, j);
537
+ }
538
+
539
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE LinearMapper getLinearMapper(Index i, Index j) const {
540
+ return LinearMapper(*this, i, j);
541
+ }
542
+
543
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE VectorMapper getVectorMapper(Index i, Index j) const {
544
+ return VectorMapper(*this, i, j);
545
+ }
546
+
547
+ EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE const CoeffLoader<Tensor, Tensor::RawAccess, MakePointer_>& get_tensor() const {
548
+ return Base::m_tensor;
549
+ }
550
+ };
551
+
552
+
553
+ template <typename T> struct TensorContractionInputMapperTrait;
554
+
555
+ template<typename Scalar_, typename Index_, int side_,
556
+ typename Tensor_,
557
+ typename nocontract_t_, typename contract_t_,
558
+ int packet_size_,
559
+ bool inner_dim_contiguous_, bool inner_dim_reordered_, int Alignment_, template <class> class MakePointer_>
560
+ struct TensorContractionInputMapperTrait<TensorContractionInputMapper<Scalar_, Index_, side_, Tensor_,
561
+ nocontract_t_, contract_t_, packet_size_, inner_dim_contiguous_,
562
+ inner_dim_reordered_, Alignment_, MakePointer_> > {
563
+
564
+ typedef Tensor_ XprType;
565
+ static const bool inner_dim_contiguous = inner_dim_contiguous_;
566
+ static const bool inner_dim_reordered = inner_dim_reordered_;
567
+ };
568
+
569
+
570
+ } // end namespace internal
571
+ } // end namespace Eigen
572
+
573
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_MAPPER_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionSycl.h ADDED
@@ -0,0 +1,1645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library for linear algebra.
2
+ //
3
+ // Mehdi Goli Codeplay Software Ltd.
4
+ // Ralph Potter Codeplay Software Ltd.
5
+ // Luke Iwanski Codeplay Software Ltd.
6
+ // Contact: <eigen@codeplay.com>
7
+ //
8
+ // This Source Code Form is subject to the terms of the Mozilla Public License v. 2.0. If a copy of the MPL was not
9
+ // distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10
+
11
+ /*****************************************************************
12
+ * TensorContractionSycl.h
13
+ *
14
+ * \brief:
15
+ * TensorContractionSycl.h, provides various tensor contraction kernel for SYCL backend
16
+ *
17
+ *****************************************************************/
18
+
19
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_SYCL_H
20
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_SYCL_H
21
+
22
+ #include "./InternalHeaderCheck.h"
23
+
24
+ namespace Eigen {
25
+
26
+ namespace TensorSycl {
27
+ namespace internal {
28
+
29
+ #ifndef EIGEN_SYCL_DISABLE_GEMV
30
+ /*!
31
+ * \brief TVPanelSize, a template class used for setting the panel size required for launching General TensorVector
32
+ * contraction kernel on various hardware devices.
33
+ *
34
+ * \tparam Scalar: determines the element type of the tensor/vector
35
+ *
36
+ * \tparam StorageIndex determines the Index type.
37
+ *
38
+ * \tparam NCWindow: determines the number of non-contracting element to be process by each work-group
39
+ *
40
+ * \tparam CFactor: determines the number of contracting element to be process by each thread
41
+ *
42
+ * \tparam NCFactor: determines the number of non-contracting element to be process by each thread
43
+ */
44
+ template <typename Scalar, typename StorageIndex, StorageIndex NCWindow, StorageIndex CFactor, StorageIndex NCFactor>
45
+ struct TVPanelSize {
46
+ // LocalThreadSizeC: determines total number of thread per workgroup for the contracting dimension
47
+ static EIGEN_CONSTEXPR StorageIndex LocalThreadSizeC = EIGEN_SYCL_LOCAL_THREAD_DIM0;
48
+ // LocalThreadSizeNC: determines total number of thread per workgroup for the non-contracting dimension
49
+ static EIGEN_CONSTEXPR StorageIndex LocalThreadSizeNC = EIGEN_SYCL_LOCAL_THREAD_DIM1;
50
+ // TileSizeDimNC: determines the tile size for the non-contracting dimension
51
+ static EIGEN_CONSTEXPR StorageIndex TileSizeDimNC = NCWindow / NCFactor;
52
+ // TileSizeDimC: determines the tile size for the contracting dimension
53
+ static EIGEN_CONSTEXPR StorageIndex TileSizeDimC = CFactor * LocalThreadSizeNC * LocalThreadSizeC;
54
+ // WorkLoadPerThreadNC : determines workload per thread for loading the non-contracting dimension
55
+ static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadNC = TileSizeDimNC / LocalThreadSizeNC;
56
+ // WorkLoadPerThreadC: determines workload per thread for loading the non-contracting dimension
57
+ static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadC = TileSizeDimC / LocalThreadSizeC;
58
+ // BC : determines if supporting bank conflict is required
59
+ static EIGEN_CONSTEXPR bool BC = false;
60
+ };
61
+ #endif
62
+
63
+ /*!
64
+ * \brief TTPanelSize, a template class used for setting the panel size required for launching General Tensor Tensor
65
+ contraction kernel on various hardware devices.
66
+ *
67
+ * \tparam Scalar: determines the element type of the tensor
68
+ *
69
+ * \tparam StorageIndex: determines the Index type.
70
+ *
71
+ * \tparam REG_SIZE_M: determines workload per thread for loading the M dimension This can be varied based on the
72
+ available register on a chosen device(can be controlled by EIGEN_SYCL_REG_M macro).
73
+ *
74
+ * \tparam REG_SIZE_N: determines workload per thread for loading the N dimension This can be varied based on the
75
+ available register on a chosen device(can be controlled by EIGEN_SYCL_REG_N macro).
76
+ *
77
+ * \tparam TSDK: determines Tile size for dimension K. The packet size is assumed to be considered
78
+ */
79
+
80
+ template <typename Scalar, typename StorageIndex, StorageIndex REG_SIZE_M, StorageIndex REG_SIZE_N, StorageIndex TSDK>
81
+ struct TTPanelSize {
82
+ // TileSizeDimK: determines Tile size for dimension K. The packet size is assumed to be considered
83
+ static EIGEN_CONSTEXPR StorageIndex TileSizeDimK = TSDK;
84
+ // WorkLoadPerThreadM : determines workload per thread for loading the M dimension This can be varied based on the
85
+ // available register on a chosen device(can be controlled by EIGEN_SYCL_REG_M macro//
86
+ #ifndef EIGEN_SYCL_REG_M
87
+ static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadM = REG_SIZE_M;
88
+ #else
89
+ static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadM = EIGEN_SYCL_REG_M;
90
+ #endif
91
+ // WorkLoadPerThreadN : determines workload per thread for loading the N dimension This can be varied based on the
92
+ // available register on a chosen device(can be controlled by EIGEN_SYCL_REG_N macro
93
+ #ifndef EIGEN_SYCL_REG_N
94
+ static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadN = REG_SIZE_N;
95
+ #else
96
+ static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadN = EIGEN_SYCL_REG_N;
97
+ #endif
98
+ // LocalThreadSizeM: determines total number of thread per workgroup for the m dimension
99
+ static EIGEN_CONSTEXPR StorageIndex LocalThreadSizeM = EIGEN_SYCL_LOCAL_THREAD_DIM0;
100
+ // LocalThreadSizeN: determines total number of thread per workgroup for the n dimension
101
+ static EIGEN_CONSTEXPR StorageIndex LocalThreadSizeN = EIGEN_SYCL_LOCAL_THREAD_DIM1;
102
+ // TileSizeDimM: determines the tile size for the m dimension
103
+ static EIGEN_CONSTEXPR StorageIndex TileSizeDimM = LocalThreadSizeM * WorkLoadPerThreadM;
104
+ // TileSizeDimN: determines the tile size for the n dimension
105
+ static EIGEN_CONSTEXPR StorageIndex TileSizeDimN = LocalThreadSizeN * WorkLoadPerThreadN;
106
+ // LoadPerThreadLhs: determines workload per thread for loading Lhs Tensor. This must be divisable by packetsize
107
+ static EIGEN_CONSTEXPR StorageIndex LoadPerThreadLhs =
108
+ ((TileSizeDimK * WorkLoadPerThreadM * WorkLoadPerThreadN) / (TileSizeDimN));
109
+ // LoadPerThreadRhs: determines workload per thread for loading Rhs Tensor. This must be divisable by packetsize
110
+ static EIGEN_CONSTEXPR StorageIndex LoadPerThreadRhs =
111
+ ((TileSizeDimK * WorkLoadPerThreadM * WorkLoadPerThreadN) / (TileSizeDimM));
112
+ // BC : determines if supporting bank conflict is required
113
+ static EIGEN_CONSTEXPR bool BC = true;
114
+ // DoubleBuffer: determines if double buffering technique should be used (This can be disabled by
115
+ // EIGEN_SYCL_DISABLE_DOUBLE_BUFFER macro when the device does not have sufficient local memory)
116
+ static EIGEN_CONSTEXPR bool DoubleBuffer =
117
+ #ifdef EIGEN_SYCL_DISABLE_DOUBLE_BUFFER
118
+ false;
119
+ #else
120
+ true;
121
+ #endif
122
+ };
123
+
124
+ /* !
125
+ * \brief contraction_type: an enum class representing the Tensor Contraction implementation algorithm. This is used to
126
+ * specialize the contraction algorithm based on device support for dedicated local memory.
127
+ */
128
+ enum class contraction_type { local, no_local };
129
+ /* !
130
+ * \brief data_source an enum class determining the location of the data in a memory hierarchy (global, local, private).
131
+ */
132
+ enum class data_source { global_mem, local_mem, private_mem };
133
+
134
+ /*!
135
+ * \brief read, a template function used for loading the data from global
136
+ memory. This function is used to guarantee coalesced and vectorized load whenever possible
137
+ *
138
+ * \tparam PacketLoad: determines if the each element of this tensor block should be loaded in a packet mode
139
+ *
140
+ * \param is_coalesced_layout: determines whether or not the Tensor data in a memory can be access coalesced and
141
+ vectorized when possible. Coalesced memory access is a key factor in Kernel performance. When a tensor is 2d and the
142
+ contracting dimension is 1, it is always possible to accessed tensor data coalesced and vectorized. This is the case
143
+ when RHS(right hand side) Tensor is transposed or when LHS(left hand side) Tensor is not transposed.
144
+ *
145
+ * \tparam PacketType: determines the type of packet
146
+ *
147
+ * \tparam TensorMapper: determines the input tensor mapper type
148
+ *
149
+ * \tparam StorageIndex: determines the Index type
150
+
151
+ * \param tensorMapper: is the input tensor
152
+ *
153
+ * \param NCIndex: is the non-contracting dim index
154
+ *
155
+ * \param CIndex is the contracting dim index
156
+ *
157
+ * \param ld: is the leading dimension of the flattened tensor
158
+ */
159
+ template <bool PacketLoad, bool is_coalesced_layout, bool, typename PacketType, typename TensorMapper,
160
+ typename StorageIndex>
161
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::enable_if_t<PacketLoad, PacketType> read(
162
+ const TensorMapper &tensorMapper, const StorageIndex &NCIndex, const StorageIndex &CIndex, const StorageIndex &ld) {
163
+ const StorageIndex row = (is_coalesced_layout) ? NCIndex : CIndex;
164
+ const StorageIndex col = (is_coalesced_layout) ? CIndex : NCIndex;
165
+ return tensorMapper.get_tensor().template packet<Unaligned>(row + (col * ld));
166
+ }
167
+
168
+ /*!
169
+ * \brief read, special overload of read function, when the read access is not vectorized
170
+ *
171
+ * \tparam PacketLoad: determines if the each element of this tensor block should be loaded in a packet mode
172
+ *
173
+ * \param is_coalesced_layout: determines whether or not the Tensor data in a memory can be access coalesced and
174
+ vectorized when possible. Coalesced memory access is a key factor in Kernel performance. When a tensor is 2d and the
175
+ contracting dimension is 1, it is always possible to accessed tensor data coalesced and vectorized. This is the case
176
+ when RHS(right hand side) Tensor is transposed or when LHS(left hand side) Tensor is not transposed.
177
+ *
178
+ * \tparam PacketType: determines the type of packet
179
+ *
180
+ * \tparam TensorMapper: determines the input tensor mapper type
181
+ *
182
+ * \tparam StorageIndex: determines the Index type
183
+
184
+ * \param tensorMapper: is the input tensor
185
+ *
186
+ * \param NCIndex: is the non-contracting dim index
187
+ *
188
+ * \param CIndex: is the contracting dim index
189
+ */
190
+ template <bool PacketLoad, bool, bool IsRhs, typename PacketType, typename TensorMapper, typename StorageIndex>
191
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::enable_if_t<!PacketLoad, PacketType> read(
192
+ const TensorMapper &tensorMapper, const StorageIndex &NCIndex, const StorageIndex &CIndex, const StorageIndex &) {
193
+ const StorageIndex row = (IsRhs) ? CIndex : NCIndex;
194
+ const StorageIndex col = (IsRhs) ? NCIndex : CIndex;
195
+ return tensorMapper(row, col);
196
+ }
197
+
198
+ /*!
199
+ * \brief write, a template function used for storing the data to local memory. This function is used to guarantee
200
+ * coalesced and vectorized store whenever possible.
201
+ *
202
+ * \tparam StorageIndex: determines the Index type
203
+ *
204
+ * \param ld is the leading dimension of the local memory. ld is a compile time value for the local memory
205
+ *
206
+ * \tparam data_source: an enum value representing if the location of the data in a memory hierarchy.
207
+ *
208
+ * \tparam PacketType: determines the type of packet
209
+ *
210
+ * \tparam DataScalar: determines the output data type
211
+ *
212
+ * \param packet_data: the data to be written in the local memory
213
+ *
214
+ * \param ptr: a pointer to the local memory
215
+ *
216
+ * \param CIndex is the contracting dim index
217
+ */
218
+
219
+ template <typename StorageIndex, StorageIndex ld, data_source dt, typename PacketType, typename DataScalar>
220
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
221
+ std::enable_if_t<dt != data_source::global_mem, void>
222
+ write(PacketType &packet_data, DataScalar ptr) {
223
+ EIGEN_CONSTEXPR int PacketSize = Eigen::internal::unpacket_traits<PacketType>::size;
224
+ EIGEN_UNROLL_LOOP
225
+ for (int i = 0; i < PacketSize; i++) {
226
+ *ptr = PacketWrapper<PacketType, PacketSize>::scalarize(i, packet_data);
227
+ ptr += ld;
228
+ }
229
+ }
230
+
231
+ /*!
232
+ * \brief Overloading the write function for storing the data to global memory, when vectorization enabled This function
233
+ * is used to guarantee coalesced and vectorized store whenever possible.
234
+ *
235
+ * \tparam data_source: an enum value representing if the location of the data in a memory hierarchy.
236
+ *
237
+ * \tparam PacketType: determines the type of packet
238
+ *
239
+ * \tparam DataScalar: determines the output data type
240
+ *
241
+ * \param packet_data: the data to be written in the local memory
242
+ *
243
+ * \param ptr: a pointer to the local memory
244
+ */
245
+
246
+ template <data_source dt, typename PacketType, typename DataScalar>
247
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if_t<
248
+ Eigen::internal::unpacket_traits<PacketType>::size != 1 && dt == data_source::global_mem, void>
249
+ write(PacketType &packet_data, DataScalar *ptr) {
250
+ ::Eigen::internal::pstoreu<DataScalar, PacketType>(ptr, packet_data);
251
+ }
252
+
253
+ /*!
254
+ * \brief Overloading the write function for storing the data to global memory, when vectorization is disabled.
255
+ *
256
+ * \tparam data_source: an enum value representing if the location of the data in a memory hierarchy.
257
+ *
258
+ * \tparam PacketType: determines the type of packet
259
+ *
260
+ * \tparam DataScalar: determines the output data type
261
+ *
262
+ * \param packet_data: the data to be written in the local memory
263
+ *
264
+ * \param ptr: a pointer to the local memory
265
+ */
266
+ template <data_source dt, typename PacketType, typename DataScalar>
267
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if_t<
268
+ Eigen::internal::unpacket_traits<PacketType>::size == 1 && dt == data_source::global_mem, void>
269
+ write(PacketType &packet_data, DataScalar *ptr) {
270
+ *ptr = packet_data;
271
+ }
272
+
273
+ /*!
274
+ * \brief check_boundary: is used to check the edge condition for non-internal blocks.
275
+ *
276
+ * \tparam is_internal: determines if the block is internal
277
+ */
278
+ template <bool is_internal>
279
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool check_boundary(bool) {
280
+ return true;
281
+ }
282
+
283
+ /*!
284
+ * \brief check_boundary: specialization of the check_boundary for non-internal blocks.
285
+ *
286
+ * \param cond: true when the data is in range. Otherwise false
287
+ */
288
+ template <>
289
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool check_boundary<false>(bool cond) {
290
+ return cond;
291
+ }
292
+
293
+ /*!
294
+ * \brief BlockProperties is a template class that provides different characteristic of a block of each Tensor processed
295
+ * by each workgroup.
296
+ *
297
+ * \tparam is_transposed: iff true, determines whether or not the block of the Tensor is transposed
298
+ *
299
+ * \tparam packet_load_: determines if the each element of this tensor block should be loaded in a packet mode
300
+ *
301
+ * \tparam PacketType: determines the type of packet
302
+ *
303
+ * \tparam OutType: determines the type of each element for this block of tensor. If packet load is true, it will be
304
+ * packetType; Otherwise it will be scalar Type
305
+ *
306
+ * \param elements_per_access determines the size of each element based on OutType
307
+ *
308
+ * \param is_coalesced_layout determines whether or not the Tensor data in a memory can be access coalesced and
309
+ * vectorized when possible. Coalesced memory access is a key factor in Kernel performance. When a tensor is 2d and the
310
+ * contracting dimension is 1, it is always possible to accessed tensor data coalesced and vectorized. This is the case
311
+ * when RHS(right hand side) Tensor is transposed or when LHS(left hand side) Tensor is not transposed.
312
+ *
313
+ * \param nc_stride determines the stride of non-contracting dimension to access the next adjustment element within the
314
+ * Tensor Block for each workgroup
315
+ *
316
+ * \param c_stride determines the stride of contracting dimension to access the next adjustment element within the
317
+ * Tensor Block for each workgroup
318
+ */
319
+ template <bool is_transposed, bool is_rhs_, bool packet_load_, typename PacketType>
320
+ struct BlockProperties {
321
+ static EIGEN_CONSTEXPR bool packet_load = packet_load_;
322
+ typedef typename Eigen::internal::unpacket_traits<PacketType>::type OutScalar;
323
+ static EIGEN_CONSTEXPR bool is_rhs = is_rhs_;
324
+ typedef std::conditional_t<packet_load, PacketType, OutScalar> OutType;
325
+ static EIGEN_CONSTEXPR int elements_per_access = Eigen::internal::unpacket_traits<OutType>::size;
326
+ static EIGEN_CONSTEXPR bool is_coalesced_layout = !(is_transposed ^ is_rhs);
327
+ static EIGEN_CONSTEXPR int nc_stride = (is_coalesced_layout ? elements_per_access : 1);
328
+ static EIGEN_CONSTEXPR int c_stride = (is_coalesced_layout ? 1 : elements_per_access);
329
+ };
330
+
331
+ /*!
332
+ * \brief ThreadProperties is a template class that provides each thread's properties within a workgroup. Please see
333
+ * the sycl-1.2.1 specification (https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf) for the workgroup,
334
+ * work-items
335
+ *
336
+ * \tparam StorageIndex: determines the StorageIndex Type
337
+ *
338
+ * \param linearLocalThreadId: determines the linearized location of a thread within a work-group
339
+ *
340
+ * \param kGroupId: determines the logical group id in a k dimension of the flattened tensor. It will be > 1 when
341
+ * tall/skinny algorithm is used
342
+ *
343
+ * \param mGroupOffset: determines the logical start position of all thread within a workgroup for the m dimension of
344
+ * the flattened tensor.
345
+ *
346
+ * \param kGroupOffset determines the logical start position of all thread within a workgroup for the k dimension of the
347
+ * flattened tensor. It will be > 1 when tall/skinny algorithm is used.
348
+ *
349
+ * \param mLocalOffset: determines the logical start position of each thread within a workgroup for the m dimension of a
350
+ * flattened tensor. The position determines the distance of each thread within the workgroup from each other
351
+ * independent from their global position.
352
+ *
353
+ * \param nLocalOffset: determines the logical start position of each thread within a workgroup for the n dimension of a
354
+ * flattened tensor. The position determines the distance of each thread within the workgroup from each other
355
+ * independent from their global position.
356
+ *
357
+ * \param mGlobalOffset: determines the logical start position of each thread a thread for the m dimension on a
358
+ * flattened tensor
359
+ *
360
+ * \param nGlobalOffset: determines the logical start position of each thread a thread for the n dimension on a
361
+ * flattened tensor
362
+ *
363
+ * \param kSize : determine the number of the k elements of the flattened Tensor to be processed by each thread for the
364
+ * given tensor block. This is !=K dimension of Flattened Tensor when Tall/Skinny matrix is used.
365
+ *
366
+ * \param is_internal : this will determined if the thread within the work-group computes an internal block of tensor or
367
+ * the edge blocks. When it is internal, there is no need to check the boundaries and all the if stantement can be
368
+ * resolve by compiler.
369
+ */
370
+ template <typename StorageIndex>
371
+ struct ThreadProperties {
372
+ const StorageIndex linearLocalThreadId;
373
+ const StorageIndex kGroupId;
374
+ const StorageIndex mGroupOffset;
375
+ const StorageIndex nGroupOffset;
376
+ const StorageIndex kGroupOffset;
377
+ const StorageIndex mLocalOffset;
378
+ const StorageIndex nLocalOffset;
379
+ const StorageIndex mGlobalOffset;
380
+ const StorageIndex nGlobalOffset;
381
+ StorageIndex kSize;
382
+ const bool is_internal;
383
+ // this is used to adjust the last block
384
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ThreadProperties(
385
+ const StorageIndex linearLocalThreadId_, const StorageIndex kGroupId_, const StorageIndex mGroupOffset_,
386
+ const StorageIndex nGroupOffset_, const StorageIndex kGroupOffset_, const StorageIndex mLocalOffset_,
387
+ const StorageIndex nLocalOffset_, const StorageIndex mGlobalOffset_, const StorageIndex nGlobalOffset_,
388
+ StorageIndex kSize_, const bool is_internal_)
389
+ : linearLocalThreadId(linearLocalThreadId_),
390
+ kGroupId(kGroupId_),
391
+ mGroupOffset(mGroupOffset_),
392
+ nGroupOffset(nGroupOffset_),
393
+ kGroupOffset(kGroupOffset_),
394
+ mLocalOffset(mLocalOffset_),
395
+ nLocalOffset(nLocalOffset_),
396
+ mGlobalOffset(mGlobalOffset_),
397
+ nGlobalOffset(nGlobalOffset_),
398
+ kSize(kSize_),
399
+ is_internal(is_internal_) {}
400
+ };
401
+
402
+ /*!
403
+ * \brief TensorContractionKernel is a template class that provides Tensor -Tensor contraction operation.
404
+ *
405
+ * \tparam OutScalar: determines the output scalar type
406
+ *
407
+ * \tparam LhsScalar: determines the left-hand-side scalar type
408
+ *
409
+ * \tparam RhsScalar: determines the right-hand-side scalar type
410
+ *
411
+ * \tparam OutAccessor: determines the sycl accessor type for out put (please see the sycl-1.2.1 specification
412
+ (https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf) for accessor definition)
413
+ *
414
+ * \tparam LhsMapper determines the tensor contraction mapper type for left-hand-side matrix
415
+ *
416
+ * \tparam RhsMapper determines the tensor contraction mapper type for right-hand-side matrix
417
+ *
418
+ * \tparam StorageIndex: determines the StorageIndex Type
419
+ *
420
+ * \tparam Properties: determines the Contraction Panel properties
421
+ *
422
+ * \tparam TripleDim: determines the M, K, N dimensions for the flatten tensors in order to treat them as a matrix
423
+ *
424
+ * \tparam Vectorizable: determines whether or not the vectorization is enabled for the Eigen expression.
425
+ *
426
+ * \tparam input_mapper_properties : determine if the input tensors are matrix. If they are matrix, special memory
427
+ access is used to guarantee that always the memory access are coalesced.
428
+ *
429
+ * \tptaram IsFinal : determine if this is the final kernel. If so, the result will be written in a final output.
430
+ Otherwise, the result of contraction will be written iin a temporary buffer. This is the case when Tall/Skinny
431
+ contraction is used. So in this case, a final reduction step is required to compute final output.
432
+
433
+ * \tparam contraction_tp: it is an enum value representing whether the local memory/no local memory implementation of
434
+ the algorithm to be used
435
+ *
436
+ * \param scratch: local memory containing tiles of LHS and RHS tensors for each work-group
437
+ *
438
+ * \param lhs: determines the left-hand-side flattened tensor (tensor mapper)
439
+ *
440
+ * \param rhs: determines the right-hand-side flattened tensor (tensor mapper)
441
+ *
442
+ * \param out_res: determines the output tensor containing the contraction result
443
+ *
444
+ * \param groupSizeM: a logical number determining the number of work-group for m dimension
445
+ *
446
+ * \param groupSizeN: a logical number determining the number of work-group for n dimension
447
+ *
448
+ * \param numTiles: determines total number of tiles on the k dimension
449
+ *
450
+ * \param TripleDim: determines the M, K, N dimensions for the flatten tensors in order to treat them as a matrix
451
+ */
452
+ template <typename OutScalar, typename LhsScalar, typename RhsScalar, typename OutAccessor, typename LhsMapper,
453
+ typename RhsMapper, typename StorageIndex, typename Properties, typename TripleDim, bool Vectorizable,
454
+ typename input_mapper_properties, bool IsFinal, contraction_type contraction_tp>
455
+ class TensorContractionKernel {
456
+ public:
457
+ typedef typename Eigen::TensorSycl::internal::Vectorise<OutScalar, Eigen::SyclDevice, Vectorizable>::PacketReturnType
458
+ PacketReturnType;
459
+ static EIGEN_CONSTEXPR int PacketSize =
460
+ Eigen::TensorSycl::internal::Vectorise<OutScalar, Eigen::SyclDevice, Vectorizable>::PacketSize;
461
+ static EIGEN_CONSTEXPR bool is_lhs_transposed =
462
+ !::Eigen::internal::TensorContractionInputMapperTrait<LhsMapper>::inner_dim_contiguous;
463
+ static EIGEN_CONSTEXPR bool is_rhs_transposed =
464
+ !::Eigen::internal::TensorContractionInputMapperTrait<RhsMapper>::inner_dim_contiguous;
465
+
466
+ typedef BlockProperties<is_lhs_transposed, false, input_mapper_properties::is_lhs_matrix && Vectorizable,
467
+ PacketReturnType>
468
+ LHSBlockProperties;
469
+
470
+ typedef BlockProperties<is_rhs_transposed, true, input_mapper_properties::is_rhs_matrix && Vectorizable,
471
+ PacketReturnType>
472
+ RHSBlockProperties;
473
+
474
+ static EIGEN_CONSTEXPR StorageIndex NStride =
475
+ contraction_tp == contraction_type::local ? Properties::WorkLoadPerThreadN : RHSBlockProperties::nc_stride;
476
+
477
+ typedef cl::sycl::accessor<OutScalar, 1, cl::sycl::access::mode::read_write, cl::sycl::access::target::local> Scratch;
478
+ typedef cl::sycl::multi_ptr<OutScalar, cl::sycl::access::address_space::local_space> local_ptr;
479
+ typedef OutScalar * /*cl::sycl::multi_ptr<OutScalar, cl::sycl::access::address_space::private_space>*/ private_ptr;
480
+ typedef std::conditional_t<contraction_tp == contraction_type::local, local_ptr, private_ptr>
481
+ tile_ptr;
482
+ static EIGEN_CONSTEXPR StorageIndex LSDL = contraction_tp == contraction_type::local
483
+ ? Properties::TileSizeDimM + Properties::BC
484
+ : Properties::WorkLoadPerThreadM;
485
+ static EIGEN_CONSTEXPR StorageIndex LSDR = contraction_tp == contraction_type::local
486
+ ? Properties::TileSizeDimN + Properties::BC
487
+ : Properties::WorkLoadPerThreadN;
488
+ static EIGEN_CONSTEXPR StorageIndex LocalOffset = Properties::LocalThreadSizeM * Properties::LocalThreadSizeN;
489
+
490
+ /**
491
+ * \brief MemHolder this is a place holder struct for creating memory hierarchy in SYCL. Inside SYCL kernel it is not
492
+ * allowed to have dynamic memory allocation. While the local memory is created outside of the kernel and passed to
493
+ * the kernel as an accessor, the private memory can only allowed to be allocated statically. Since we are abstracting
494
+ * the TiledMemory for both local and private memory, the MemHolder structs is used as a helper to abstract out
495
+ * different type of memory needed when local/no_local memory computation is called.
496
+ *
497
+ * \tparam contraction_type: it is an enum value representing whether the local memory/no local memory implementation
498
+ of the algorithm to be used
499
+ * \tparam the private memory size
500
+ * \param ptr the tile memory pointer type
501
+ */
502
+ template <contraction_type, StorageIndex>
503
+ struct MemHolder {
504
+ tile_ptr ptr;
505
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE MemHolder(local_ptr block_start_ptr) : ptr(block_start_ptr) {}
506
+ };
507
+ /**
508
+ * \brief specialization of memHolder class when no local memory kernel is used.
509
+ */
510
+ template <StorageIndex MemSize>
511
+ struct MemHolder<contraction_type::no_local, MemSize> {
512
+ OutScalar ptr[MemSize] = {OutScalar{0}};
513
+ };
514
+ /**
515
+ * \brief TiledMemory: contains required memory pointer for loading each tile of the TensorContraction panel from
516
+ * global memory to local/private memory when local/no_local algorithm used.
517
+ *
518
+ * \param lhs_scratch_extract : determines the LHS tile memory. It is either private or local memory based on the
519
+ * selected contraction_type.
520
+ *
521
+ * \param rhs_scratch_extract : determines the RHS tile memory. It is either private or local memory based on the
522
+ * selected contraction_type.
523
+ *
524
+ * \param lhs_extract_index: determines the position of each thread on a local memory for lhs input. When private
525
+ * memory is used this is set to zero as this is not applicable in case of private memory.
526
+ *
527
+ * \param rhs_extract_index: determines the position of each thread on a local memory for rhs input. When private
528
+ * memory is used this is set to zero as this is not applicable in case of private memory.
529
+ *
530
+ * \param lhs_scratch_compute : determines the location to load for computation for lhs_local memory. This is the
531
+ * same as lhs_scratch_extract for private memory.
532
+ *
533
+ * \param rhs_scratch_compute : determines the location to load for computation for rhs_local memory. This is the
534
+ * same as rhs_scratch_extract for private memory.
535
+ */
536
+ struct TiledMemory {
537
+ MemHolder<contraction_tp, Properties::WorkLoadPerThreadM * Properties::TileSizeDimK> lhs_scratch_extract;
538
+ MemHolder<contraction_tp, Properties::WorkLoadPerThreadN * Properties::TileSizeDimK> rhs_scratch_extract;
539
+ tile_ptr lhs_scratch_ptr_compute;
540
+ tile_ptr rhs_scratch_ptr_compute;
541
+ const std::pair<StorageIndex, StorageIndex> lhs_extract_index;
542
+ const std::pair<StorageIndex, StorageIndex> rhs_extract_index;
543
+ template <contraction_type tp = contraction_tp>
544
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
545
+ TiledMemory(const ThreadProperties<StorageIndex> &, local_ptr,
546
+ std::enable_if_t<tp == contraction_type::no_local> * = 0)
547
+ : lhs_scratch_extract{},
548
+ rhs_scratch_extract{},
549
+ lhs_scratch_ptr_compute(lhs_scratch_extract.ptr),
550
+ rhs_scratch_ptr_compute(rhs_scratch_extract.ptr),
551
+ lhs_extract_index(std::pair<StorageIndex, StorageIndex>(StorageIndex{0}, StorageIndex{0})),
552
+ rhs_extract_index(std::pair<StorageIndex, StorageIndex>(StorageIndex{0}, StorageIndex{0})) {}
553
+
554
+ template <contraction_type tp = contraction_tp>
555
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
556
+ TiledMemory(const ThreadProperties<StorageIndex> &thread_properties, local_ptr block_start_ptr,
557
+ std::enable_if_t<tp == contraction_type::local> * = 0)
558
+ : lhs_scratch_extract{block_start_ptr},
559
+ rhs_scratch_extract{lhs_scratch_extract.ptr +
560
+ ((Properties::DoubleBuffer + 1) * LSDL * Properties::TileSizeDimK)},
561
+ lhs_scratch_ptr_compute(lhs_scratch_extract.ptr + thread_properties.mLocalOffset),
562
+ rhs_scratch_ptr_compute(rhs_scratch_extract.ptr + thread_properties.nLocalOffset),
563
+ lhs_extract_index(
564
+ local_id_extract<LHSBlockProperties, Properties::TileSizeDimM>(thread_properties.linearLocalThreadId)),
565
+ rhs_extract_index(
566
+ local_id_extract<RHSBlockProperties, Properties::TileSizeDimN>(thread_properties.linearLocalThreadId)) {}
567
+ };
568
+
569
+ Scratch scratch;
570
+ const LhsMapper lhs;
571
+ const RhsMapper rhs;
572
+ OutAccessor out_res;
573
+ const StorageIndex groupSizeM;
574
+ const StorageIndex groupSizeN;
575
+ const StorageIndex numTiles;
576
+ const TripleDim triple_dim;
577
+
578
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorContractionKernel(Scratch scratch_, const LhsMapper lhs_,
579
+ const RhsMapper rhs_, OutAccessor out_res_,
580
+ const StorageIndex groupSizeM_,
581
+ const StorageIndex groupSizeN_,
582
+ const StorageIndex numTiles_,
583
+ const TripleDim triple_dim_)
584
+ : scratch(scratch_),
585
+ lhs(lhs_),
586
+ rhs(rhs_),
587
+ out_res(out_res_),
588
+ groupSizeM(groupSizeM_),
589
+ groupSizeN(groupSizeN_),
590
+ numTiles(numTiles_),
591
+ triple_dim(triple_dim_) {}
592
+
593
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorContractionKernel(Scratch scratch_, const LhsMapper lhs_,
594
+ const RhsMapper rhs_, OutAccessor out_res_,
595
+ const StorageIndex groupSizeM_,
596
+ const StorageIndex numTiles_,
597
+ const TripleDim triple_dim_)
598
+ : TensorContractionKernel(scratch_, lhs_, rhs_, out_res_, groupSizeM_, 1, numTiles_, triple_dim_) {}
599
+
600
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(cl::sycl::nd_item<1> itemID) const {
601
+ const StorageIndex linearLocalThreadId = itemID.get_local_id(0);
602
+ const StorageIndex nLocalThreadId = linearLocalThreadId / Properties::LocalThreadSizeM;
603
+ const StorageIndex mLocalThreadId = linearLocalThreadId % Properties::LocalThreadSizeM;
604
+ const StorageIndex mGroupId = itemID.get_group(0) % groupSizeM;
605
+ const StorageIndex tmp = itemID.get_group(0) / groupSizeM;
606
+ const StorageIndex nGroupId = IsFinal ? tmp : tmp % groupSizeN;
607
+ const StorageIndex kGroupId = IsFinal ? 0 : tmp / groupSizeN;
608
+ const StorageIndex mGroupOffset = mGroupId * Properties::TileSizeDimM;
609
+ const StorageIndex nGroupOffset = nGroupId * Properties::TileSizeDimN;
610
+ const StorageIndex mLocalOffset = PacketSize * mLocalThreadId;
611
+ const StorageIndex nLocalOffset = NStride * nLocalThreadId;
612
+ const StorageIndex mGlobalOffset = mGroupOffset + mLocalOffset;
613
+ const StorageIndex nGlobalOffset = nGroupOffset + nLocalOffset;
614
+
615
+ const StorageIndex kSizePerWG = IsFinal ? triple_dim.K : numTiles * Properties::TileSizeDimK;
616
+ StorageIndex kGroupOffset = kGroupId * kSizePerWG;
617
+ const bool is_internal = triple_dim.M - mGroupOffset >= Properties::TileSizeDimM &&
618
+ triple_dim.N - nGroupOffset >= Properties::TileSizeDimN &&
619
+ triple_dim.K - kGroupOffset >= kSizePerWG;
620
+ // this is used to adjust the last block
621
+ StorageIndex kSize = IsFinal ? triple_dim.K : std::min(kSizePerWG, triple_dim.K - kGroupOffset);
622
+ // This is used to find out the lats K offset so that kGroupOffset -kSize can compute the coffset for loading to
623
+ // tile
624
+ kGroupOffset += kSize;
625
+
626
+ auto thread_properties =
627
+ ThreadProperties<StorageIndex>(linearLocalThreadId, kGroupId, mGroupOffset, nGroupOffset, kGroupOffset,
628
+ mLocalOffset, nLocalOffset, mGlobalOffset, nGlobalOffset, kSize, is_internal);
629
+
630
+ auto out_ptr = out_res + (IsFinal ? 0 : thread_properties.kGroupId * triple_dim.M * triple_dim.N);
631
+
632
+ (thread_properties.is_internal) ? compute_panel<true>(itemID, thread_properties, out_ptr)
633
+ : compute_panel<false>(itemID, thread_properties, out_ptr);
634
+ }
635
+ // The compute block computes the contraction operation private block for each thread and store the resutl in the
636
+ // privateRes memory of Each computation the compute block function is independent of local and no local concepts as
637
+ // it only compute the block on each thread's private memory space
638
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_block_per_tile(OutScalar *lhs_block_ptr, OutScalar *rhs_block_ptr,
639
+ PacketReturnType *privateRes) const {
640
+ StorageIndex idx = 0;
641
+ EIGEN_CONSTEXPR StorageIndex lhs_stride =
642
+ contraction_tp == contraction_type::local ? (PacketSize * Properties::LocalThreadSizeM) : 1;
643
+ EIGEN_UNROLL_LOOP
644
+ for (StorageIndex wLPTN = 0; wLPTN < Properties::WorkLoadPerThreadN; wLPTN++) {
645
+ auto rhsPacket = PacketReturnType{*(rhs_block_ptr + wLPTN)};
646
+ StorageIndex lhs_index = 0;
647
+ EIGEN_UNROLL_LOOP
648
+ for (StorageIndex wLPTM = 0; wLPTM < Properties::WorkLoadPerThreadM / PacketSize; wLPTM++) {
649
+ PacketReturnType lhsPack{};
650
+ Eigen::TensorSycl::internal::PacketWrapper<PacketReturnType, PacketSize>::set_packet(lhsPack,
651
+ lhs_block_ptr + lhs_index);
652
+ privateRes[idx] = ::Eigen::internal::pmadd(lhsPack, rhsPacket, privateRes[idx]);
653
+
654
+ lhs_index += lhs_stride;
655
+ idx++;
656
+ }
657
+ }
658
+ }
659
+ // The store function write the computed contraction operation in the private memory of each thread to the global
660
+ // memory. The store function is independent of local and no local concepts s that it can be abstract out in the base
661
+ // class.
662
+ template <bool is_internal_block, StorageIndex PrivateNStride, typename OutPtr>
663
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void store(OutPtr *out_ptr, PacketReturnType *privateRes,
664
+ StorageIndex mGlobalOffset, StorageIndex nGlobalOffset) const {
665
+ auto chk_bound = [&](const StorageIndex &mIndex, const StorageIndex &nIndex) EIGEN_DEVICE_FUNC {
666
+ return (mIndex + PacketSize - 1 < triple_dim.M && nGlobalOffset + nIndex < triple_dim.N);
667
+ };
668
+ // when local memory is not used M and N are both accessed in a coalesced way. However, when local memory is
669
+ // available the k*N is transposed in the local to N*K therefore, each blocks operates on blockId*
670
+ // WorkLoadPerThreadN slice of N
671
+ EIGEN_CONSTEXPR StorageIndex GlobalNStride =
672
+ contraction_tp == contraction_type::local ? 1 : Properties::LocalThreadSizeN;
673
+ EIGEN_UNROLL_LOOP
674
+ for (StorageIndex wLPTN = 0; wLPTN < Properties::WorkLoadPerThreadN / PrivateNStride; wLPTN++) {
675
+ // output leading dimension
676
+ StorageIndex outputLD = 0;
677
+ // When local memory is used the PrivateNstride is always 1 because the coalesed access on N is loaded into Local
678
+ // memory and extracting from local to global is the same as no transposed version. However, when local memory is
679
+ // not used and RHS is transposed we packetize the load for RHS.
680
+ EIGEN_UNROLL_LOOP
681
+ for (StorageIndex nId = 0; nId < PrivateNStride; nId++) {
682
+ StorageIndex globalRow = mGlobalOffset;
683
+ EIGEN_UNROLL_LOOP
684
+ for (StorageIndex wLPTM = 0; wLPTM < Properties::WorkLoadPerThreadM / PacketSize; wLPTM++) {
685
+ PacketReturnType privetOut = privateRes[wLPTM];
686
+ if (check_boundary<is_internal_block>(chk_bound(globalRow, nId))) {
687
+ // Store the final results in C. The C matrix has always M as a first StorageIndex and N as a second
688
+ // StorageIndex Therefore it is always coalesced layout
689
+ write<data_source::global_mem>(privetOut, out_ptr + outputLD + globalRow);
690
+ } else {
691
+ EIGEN_UNROLL_LOOP
692
+ for (StorageIndex mId = 0; mId < PacketSize; mId++) {
693
+ StorageIndex mOffset = globalRow + mId;
694
+ if (mOffset < triple_dim.M && (nGlobalOffset + nId < triple_dim.N)) {
695
+ out_ptr[mOffset + outputLD] =
696
+ Eigen::TensorSycl::internal::PacketWrapper<PacketReturnType, PacketSize>::scalarize(mId, privetOut);
697
+ }
698
+ }
699
+ }
700
+ globalRow += (PacketSize * Properties::LocalThreadSizeM);
701
+ }
702
+ outputLD += triple_dim.M;
703
+ privateRes += Properties::WorkLoadPerThreadM / PacketSize;
704
+ }
705
+ out_ptr += (GlobalNStride * outputLD);
706
+
707
+ nGlobalOffset += (PrivateNStride * GlobalNStride);
708
+ }
709
+ }
710
+ // when no local memory is used the following extract_block will be enabled
711
+ template <typename InputBlockProperties, bool is_internal_block, typename Input, typename PrivateReg,
712
+ contraction_type contract_tp = contraction_tp>
713
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
714
+ std::enable_if_t<contract_tp == contraction_type::no_local>
715
+ extract_block(const Input &inpt, PrivateReg private_ptr, const std::pair<StorageIndex, StorageIndex> &,
716
+ const StorageIndex &ncOffset, const StorageIndex cOffset) const {
717
+ EIGEN_CONSTEXPR StorageIndex LocalThreadSizeNC =
718
+ InputBlockProperties::is_rhs ? Properties::LocalThreadSizeN : Properties::LocalThreadSizeM;
719
+ EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadNC =
720
+ InputBlockProperties::is_rhs ? Properties::WorkLoadPerThreadN : Properties::WorkLoadPerThreadM;
721
+ const StorageIndex &NC = InputBlockProperties::is_rhs ? triple_dim.N : triple_dim.M;
722
+
723
+ auto chk_bound = [&](const StorageIndex &CIndex, const StorageIndex &NCIndex) EIGEN_DEVICE_FUNC {
724
+ return ((CIndex + InputBlockProperties::c_stride - 1 < triple_dim.K) &&
725
+ (NCIndex + InputBlockProperties::nc_stride - 1 < NC));
726
+ };
727
+ const StorageIndex ld = InputBlockProperties::is_coalesced_layout ? NC : triple_dim.K;
728
+ StorageIndex cIndex = cOffset;
729
+
730
+ EIGEN_UNROLL_LOOP
731
+ for (StorageIndex cId = 0; cId < Properties::TileSizeDimK / InputBlockProperties::c_stride; cId++) {
732
+ StorageIndex ncIndex = ncOffset;
733
+ EIGEN_UNROLL_LOOP
734
+ for (StorageIndex ncId = 0; ncId < WorkLoadPerThreadNC / InputBlockProperties::nc_stride; ncId++) {
735
+ if (check_boundary<is_internal_block>(chk_bound(cIndex, ncIndex))) {
736
+ auto val =
737
+ read<InputBlockProperties::packet_load, InputBlockProperties::is_coalesced_layout,
738
+ InputBlockProperties::is_rhs, typename InputBlockProperties::OutType>(inpt, ncIndex, cIndex, ld);
739
+
740
+ write<StorageIndex, (InputBlockProperties::is_coalesced_layout ? 1 : WorkLoadPerThreadNC),
741
+ data_source::private_mem>(val, private_ptr);
742
+ } else {
743
+ EIGEN_UNROLL_LOOP
744
+ for (StorageIndex i = 0; i < InputBlockProperties::elements_per_access; i++) {
745
+ const StorageIndex ncInd = ncIndex + (InputBlockProperties::is_coalesced_layout ? i : 0);
746
+ const StorageIndex cInd = cIndex + (InputBlockProperties::is_coalesced_layout ? 0 : i);
747
+ OutScalar val =
748
+ (ncInd < NC && cInd < triple_dim.K)
749
+ ? read<false, InputBlockProperties::is_coalesced_layout, InputBlockProperties::is_rhs, OutScalar>(
750
+ inpt, ncInd, cInd, ld)
751
+ : OutScalar(0);
752
+ write<StorageIndex, (InputBlockProperties::is_coalesced_layout ? 1 : WorkLoadPerThreadNC),
753
+ data_source::private_mem>(
754
+ val, private_ptr + (InputBlockProperties::is_coalesced_layout ? i : 0) +
755
+ ((InputBlockProperties::is_coalesced_layout ? 0 : i) * WorkLoadPerThreadNC));
756
+ }
757
+ }
758
+
759
+ // if it is lhs we have to load it packetised when the packet size is > 1, because the output is coalesced. So
760
+ // even if M is not accessed in a coalesced mode, we have to load packet_size number of m per thread.
761
+ ncIndex = (!InputBlockProperties::is_rhs && InputBlockProperties::nc_stride == 1 && PacketSize != 1)
762
+ ? ncOffset + (ncId + 1) % PacketSize + ((ncId + 1) / PacketSize) * LocalThreadSizeNC
763
+ : (ncIndex + InputBlockProperties::nc_stride * LocalThreadSizeNC);
764
+ private_ptr += InputBlockProperties::nc_stride;
765
+ }
766
+ // the previous for loop ( private_ptr += (ncId * nc_stride)) has already moved ptr with one WorkLoadPerThreadNC
767
+ private_ptr += (InputBlockProperties::c_stride - 1) * WorkLoadPerThreadNC;
768
+ cIndex += InputBlockProperties::c_stride;
769
+ }
770
+ }
771
+ template <typename InputBlockProperties, StorageIndex TileSizeDimNC>
772
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::pair<StorageIndex, StorageIndex> local_id_extract(
773
+ const StorageIndex &linearLocalThreadId) {
774
+ const StorageIndex localThreadNC =
775
+ (InputBlockProperties::is_coalesced_layout)
776
+ ? linearLocalThreadId % (TileSizeDimNC / InputBlockProperties::nc_stride)
777
+ : linearLocalThreadId / (Properties::TileSizeDimK / InputBlockProperties::c_stride);
778
+ const StorageIndex localThreadC =
779
+ (InputBlockProperties::is_coalesced_layout)
780
+ ? linearLocalThreadId / (TileSizeDimNC / InputBlockProperties::nc_stride)
781
+ : linearLocalThreadId % (Properties::TileSizeDimK / InputBlockProperties::c_stride);
782
+ return std::pair<StorageIndex, StorageIndex>(localThreadNC, localThreadC);
783
+ }
784
+
785
+ template <bool db = Properties::DoubleBuffer, contraction_type ctp = contraction_tp>
786
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
787
+ std::enable_if_t<db && ctp == contraction_type::local>
788
+ sync_mem(const cl::sycl::nd_item<1> &, bool &db_offset) noexcept {
789
+ db_offset = !db_offset;
790
+ }
791
+
792
+ template <bool db = Properties::DoubleBuffer, contraction_type ctp = contraction_tp>
793
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
794
+ std::enable_if_t<!db && ctp == contraction_type::local>
795
+ sync_mem(const cl::sycl::nd_item<1> &itemID, bool &) noexcept {
796
+ itemID.barrier(cl::sycl::access::fence_space::local_space);
797
+ }
798
+
799
+ template <contraction_type ctp = contraction_tp>
800
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
801
+ std::enable_if_t<ctp == contraction_type::no_local>
802
+ sync_mem(const cl::sycl::nd_item<1> &, bool &) noexcept {
803
+ return;
804
+ }
805
+
806
+ template <bool need_sync, contraction_type ctp = contraction_tp>
807
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
808
+ std::enable_if_t<need_sync && ctp == contraction_type::no_local>
809
+ sync_thread(const cl::sycl::nd_item<1> &
810
+ #ifdef EIGEN_SYCL_ARM_GPU_CACHE_OPTIMISATION
811
+ itemID
812
+ #endif
813
+ ) noexcept {
814
+ #ifdef EIGEN_SYCL_ARM_GPU_CACHE_OPTIMISATION
815
+ itemID.barrier(cl::sycl::access::fence_spacce::local_space);
816
+ #else
817
+ return;
818
+ #endif
819
+ }
820
+ template <bool need_sync, contraction_type ctp = contraction_tp>
821
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
822
+ std::enable_if_t<need_sync && ctp == contraction_type::local>
823
+ sync_thread(const cl::sycl::nd_item<1> &itemID) {
824
+ itemID.barrier(cl::sycl::access::fence_space::local_space);
825
+ }
826
+ template <bool need_sync>
827
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::enable_if_t<!need_sync> sync_thread(
828
+ const cl::sycl::nd_item<1> &) {
829
+ return;
830
+ }
831
+
832
+ template <bool is_internal_block>
833
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_tile_per_panel(const cl::sycl::nd_item<1> &itemID,
834
+ ThreadProperties<StorageIndex> &thread_properties,
835
+ TiledMemory &tiled_input_block,
836
+ PacketReturnType *privateRes, bool &db_offset) const {
837
+
838
+ // Tiling the Rhs block from global to local memory
839
+ extract_block<RHSBlockProperties, is_internal_block>(
840
+ rhs, tiled_input_block.rhs_scratch_extract.ptr + (db_offset * Properties::TileSizeDimK * LSDR),
841
+ tiled_input_block.rhs_extract_index,
842
+ contraction_tp == contraction_type::local ? thread_properties.nGroupOffset : thread_properties.nGlobalOffset,
843
+ thread_properties.kGroupOffset - thread_properties.kSize);
844
+
845
+ sync_thread<contraction_tp == contraction_type::no_local>(itemID);
846
+
847
+ // Tiling the Lhs block from global to local memory
848
+ extract_block<LHSBlockProperties, is_internal_block>(
849
+ lhs, tiled_input_block.lhs_scratch_extract.ptr + (db_offset * LSDL * Properties::TileSizeDimK),
850
+ tiled_input_block.lhs_extract_index,
851
+ contraction_tp == contraction_type::local ? thread_properties.mGroupOffset : thread_properties.mGlobalOffset,
852
+ thread_properties.kGroupOffset - thread_properties.kSize);
853
+
854
+ // itemID.barrier(cl::sycl::access::fence_space::local_space);
855
+ sync_thread<contraction_tp == contraction_type::local>(itemID);
856
+ // switch to compute mede
857
+ StorageIndex lhs_offset = (db_offset * LSDL * Properties::TileSizeDimK);
858
+ StorageIndex rhs_offset = (db_offset * Properties::TileSizeDimK * LSDR);
859
+ // Loop over the values of a single tile
860
+ for (StorageIndex k = 0; k < Properties::TileSizeDimK; k++) {
861
+ compute_block_per_tile(tiled_input_block.lhs_scratch_ptr_compute + lhs_offset,
862
+ tiled_input_block.rhs_scratch_ptr_compute + rhs_offset, privateRes);
863
+ lhs_offset += LSDL;
864
+ rhs_offset += LSDR;
865
+ }
866
+ // computing the K index for the next tile
867
+ thread_properties.kSize -= Properties::TileSizeDimK;
868
+ sync_mem(itemID, db_offset);
869
+ }
870
+
871
+ // when local memory is available the following compute_panel will be enabled
872
+ template <bool is_internal_block, typename OutPtr>
873
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_panel(const cl::sycl::nd_item<1> &itemID,
874
+ ThreadProperties<StorageIndex> &thread_properties,
875
+ OutPtr out_ptr) const {
876
+ auto tiled_input_block = TiledMemory{thread_properties, scratch.get_pointer()};
877
+ // Allocate register space
878
+ PacketReturnType privateRes[Properties::WorkLoadPerThreadM * Properties::WorkLoadPerThreadN / PacketSize] = {
879
+ PacketReturnType{0}};
880
+ bool db_offset = 0;
881
+
882
+ while (thread_properties.kSize >= Properties::TileSizeDimK) {
883
+ compute_tile_per_panel<is_internal_block>(itemID, thread_properties, tiled_input_block, privateRes, db_offset);
884
+ }
885
+ if (thread_properties.kSize > 0) {
886
+ compute_tile_per_panel<false>(itemID, thread_properties, tiled_input_block, privateRes, db_offset);
887
+ }
888
+
889
+ // Storing the final results in the output
890
+ store<is_internal_block,
891
+ contraction_tp == contraction_type::local ? static_cast<StorageIndex>(1) : RHSBlockProperties::nc_stride>(
892
+ out_ptr + thread_properties.nGlobalOffset * triple_dim.M, privateRes, thread_properties.mGlobalOffset,
893
+ thread_properties.nGlobalOffset);
894
+ }
895
+ // When local memory is available the following extract_block will be enabled
896
+ template <typename InputBlockProperties, bool is_internal_block, typename Input, typename Local,
897
+ contraction_type contract_tp = contraction_tp>
898
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
899
+ std::enable_if_t<contract_tp == contraction_type::local>
900
+ extract_block(const Input &inpt, Local local_ptr, const std::pair<StorageIndex, StorageIndex>& local_index,
901
+ const StorageIndex &ncOffset, const StorageIndex cOffset) const {
902
+ EIGEN_CONSTEXPR StorageIndex TileSizeDimNC =
903
+ InputBlockProperties::is_rhs ? Properties::TileSizeDimN : Properties::TileSizeDimM;
904
+ EIGEN_CONSTEXPR StorageIndex LoadPerThread =
905
+ InputBlockProperties::is_rhs ? Properties::LoadPerThreadRhs : Properties::LoadPerThreadLhs;
906
+ EIGEN_CONSTEXPR StorageIndex LSD = InputBlockProperties::is_rhs ? LSDR : LSDL;
907
+ static_assert(((LocalOffset % (TileSizeDimNC / InputBlockProperties::nc_stride) == 0) &&
908
+ (LocalOffset % (Properties::TileSizeDimK / InputBlockProperties::c_stride) == 0)),
909
+ " LocalOffset must be divisable by stride");
910
+ const StorageIndex &NC = InputBlockProperties::is_rhs ? triple_dim.N : triple_dim.M;
911
+ StorageIndex localThreadNC = local_index.first;
912
+ StorageIndex localThreadC = local_index.second;
913
+ auto chk_bound = [&](const StorageIndex &CIndex, const StorageIndex &NCIndex) EIGEN_DEVICE_FUNC {
914
+ return ((CIndex + InputBlockProperties::c_stride - 1 < triple_dim.K) &&
915
+ (NCIndex + InputBlockProperties::nc_stride - 1 < NC));
916
+ };
917
+ EIGEN_UNROLL_LOOP
918
+ for (StorageIndex lPT = 0; lPT < LoadPerThread / InputBlockProperties::elements_per_access; lPT++) {
919
+ const StorageIndex CIndex = cOffset + (InputBlockProperties::c_stride * localThreadC);
920
+ const StorageIndex NCIndex = ncOffset + (InputBlockProperties::nc_stride * localThreadNC);
921
+ const StorageIndex ld = InputBlockProperties::is_coalesced_layout ? NC : triple_dim.K;
922
+ if (check_boundary<is_internal_block>(chk_bound(CIndex, NCIndex))) {
923
+ auto val =
924
+ read<InputBlockProperties::packet_load, InputBlockProperties::is_coalesced_layout,
925
+ InputBlockProperties::is_rhs, typename InputBlockProperties::OutType>(inpt, NCIndex, CIndex, ld);
926
+ write<StorageIndex, (InputBlockProperties::is_coalesced_layout ? 1 : LSD), data_source::local_mem>(
927
+ val, local_ptr + (InputBlockProperties::nc_stride * localThreadNC) +
928
+ (InputBlockProperties::c_stride * localThreadC * LSD));
929
+ } else {
930
+ EIGEN_UNROLL_LOOP
931
+ for (StorageIndex i = 0; i < InputBlockProperties::elements_per_access; i++) {
932
+ const StorageIndex nCInd = NCIndex + (InputBlockProperties::is_coalesced_layout ? i : 0);
933
+ const StorageIndex cInd = CIndex + (InputBlockProperties::is_coalesced_layout ? 0 : i);
934
+ OutScalar val =
935
+ (nCInd < NC && cInd < triple_dim.K)
936
+ ? read<false, InputBlockProperties::is_coalesced_layout, InputBlockProperties::is_rhs, OutScalar>(
937
+ inpt, nCInd, cInd, ld)
938
+ : OutScalar(0);
939
+
940
+ write<StorageIndex, (InputBlockProperties::is_coalesced_layout ? 1 : LSD), data_source::local_mem>(
941
+ val, local_ptr + (InputBlockProperties::nc_stride * localThreadNC) +
942
+ (InputBlockProperties::is_coalesced_layout ? i : 0) +
943
+ ((InputBlockProperties::c_stride * localThreadC +
944
+ (InputBlockProperties::is_coalesced_layout ? 0 : i)) *
945
+ LSD));
946
+ }
947
+ }
948
+ localThreadNC += (InputBlockProperties::is_coalesced_layout)
949
+ ? LocalOffset % (TileSizeDimNC / InputBlockProperties::nc_stride)
950
+ : LocalOffset / (Properties::TileSizeDimK / InputBlockProperties::c_stride);
951
+ localThreadC += (InputBlockProperties::is_coalesced_layout)
952
+ ? LocalOffset / (TileSizeDimNC / InputBlockProperties::nc_stride)
953
+ : LocalOffset % (Properties::TileSizeDimK / InputBlockProperties::c_stride);
954
+ }
955
+ }
956
+ };
957
+
958
+ #ifndef EIGEN_SYCL_DISABLE_GEMV
959
+
960
+ /*!
961
+ * \brief GeneralVectorTensor is a template class that provides Tensor -vector contraction operation, which is a special
962
+ * case of Tensor Tensor contraction.
963
+ *
964
+ * \tparam OutScalar: determines the output scalar type
965
+ *
966
+ * \tparam OutAccessor: determines the sycl accessor type for out put (please see the sycl-1.2.1 specification
967
+ * (https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf) for accessor definition)
968
+ *
969
+ * \tparam VectorMapper: determines the tensor contraction mapper for the vector input (can be lhs or rhs)
970
+ *
971
+ * \tparam TensorMapper: determines the tensor contraction mapper for the tensor input (can be lhs or rhs)
972
+ *
973
+ * \tparam StorageIndex: determines the StorageIndex Type
974
+ *
975
+ * \tparam Properties: determines the Contraction Panel properties
976
+ *
977
+ * \tparam KFactor: determines the number of elements in K dimension in a Tile
978
+ *
979
+ * \tparam Vectorizable: determines whether or not the vectorization is enabled for the Eigen expression.
980
+ *
981
+ * \tparam is_lhs_vec: determines whether lhs is a vector or rhs is a vector
982
+ *
983
+ * \tparam IsFinal: determine if this is the final kernel. If so, the result will be written in a final output.
984
+ * Otherwise, the result of contraction will be written iin a temporary buffer.
985
+ *
986
+ * \param scratch: determines the local memory containing the vector block for each work-group
987
+ *
988
+ * \param vec: determines the vector input (tensor mapper)
989
+ *
990
+ * \param mat: determines the tensor input (tensor mapper)
991
+ *
992
+ * \param out_res: determines the output vector containing the contraction result
993
+ *
994
+ * \param nonContractGroupSize: a logical number determining the number of work-group for non-contracting dimension
995
+ *
996
+ * \param nonContractDim: determines the size of non contracting dimension for the flattened tensor
997
+ *
998
+ * \param contractDim: determines the size of non contracting dimension for the flattened tensor
999
+ *
1000
+ */
1001
+ template <typename OutScalar, typename OutAccessor, typename VectorMapper, typename TensorMapper, typename StorageIndex,
1002
+ typename Properties, StorageIndex KFactor, bool Vectorizable, bool is_lhs_vec, bool IsFinal>
1003
+ struct GeneralVectorTensor {
1004
+ typedef typename Eigen::TensorSycl::internal::Vectorise<OutScalar, Eigen::SyclDevice, Vectorizable>::PacketReturnType
1005
+ PacketReturnType;
1006
+ static EIGEN_CONSTEXPR int PacketSize =
1007
+ Eigen::TensorSycl::internal::Vectorise<OutScalar, Eigen::SyclDevice, Vectorizable>::PacketSize;
1008
+ typedef cl::sycl::accessor<OutScalar, 1, cl::sycl::access::mode::read_write, cl::sycl::access::target::local> Scratch;
1009
+
1010
+ static EIGEN_CONSTEXPR StorageIndex OutScratchOffset =
1011
+ KFactor * Properties::LocalThreadSizeC * Properties::LocalThreadSizeNC;
1012
+
1013
+ // Since the access layout for a vector can always be coalesced, when LHS is a vector, we pass false and false to make
1014
+ // sure that the !^ is true When RHS is a vector, we pass true and true to make sure that the !^ is true.
1015
+ typedef BlockProperties<is_lhs_vec ? false : true, is_lhs_vec ? false : true, Vectorizable, PacketReturnType>
1016
+ VecBlockProperties;
1017
+
1018
+ Scratch scratch;
1019
+ const VectorMapper vec;
1020
+ const TensorMapper mat;
1021
+ OutAccessor out_res;
1022
+ const StorageIndex nonContractGroupSize;
1023
+ const StorageIndex nonContractDim;
1024
+ const StorageIndex contractDim;
1025
+
1026
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE GeneralVectorTensor(Scratch scratch_, const VectorMapper vec_,
1027
+ const TensorMapper mat_, OutAccessor out_res_,
1028
+ const StorageIndex nonContractGroupSize_,
1029
+ const StorageIndex nonContractDim_,
1030
+ const StorageIndex contractDim_)
1031
+ : scratch(scratch_),
1032
+ vec(vec_),
1033
+ mat(mat_),
1034
+ out_res(out_res_),
1035
+ nonContractGroupSize(nonContractGroupSize_),
1036
+ nonContractDim(nonContractDim_),
1037
+ contractDim(contractDim_) {}
1038
+
1039
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(cl::sycl::nd_item<1> itemID) const {
1040
+ auto scratch_ptr = scratch.get_pointer();
1041
+ const StorageIndex linearLocalThreadId = itemID.get_local_id(0);
1042
+ StorageIndex nonContractId = is_lhs_vec ? linearLocalThreadId / Properties::LocalThreadSizeC
1043
+ : linearLocalThreadId % Properties::LocalThreadSizeNC;
1044
+ StorageIndex contractId = is_lhs_vec ? linearLocalThreadId % Properties::LocalThreadSizeC
1045
+ : linearLocalThreadId / Properties::LocalThreadSizeNC;
1046
+ const StorageIndex cGroupSize = itemID.get_group_range(0) / nonContractGroupSize;
1047
+ const StorageIndex nonContractGroupId =
1048
+ is_lhs_vec ? itemID.get_group(0) / cGroupSize : itemID.get_group(0) % nonContractGroupSize;
1049
+ const StorageIndex contractGroupId =
1050
+ is_lhs_vec ? itemID.get_group(0) % cGroupSize : itemID.get_group(0) / nonContractGroupSize;
1051
+ auto out_ptr = out_res + (IsFinal ? 0 : contractGroupId * nonContractDim);
1052
+
1053
+ const StorageIndex nonContractGroupOffset = nonContractGroupId * Properties::TileSizeDimNC;
1054
+ const StorageIndex contractGroupOffset = contractGroupId * Properties::TileSizeDimC;
1055
+ auto outScratchIndex = nonContractId + contractId * Properties::LocalThreadSizeNC;
1056
+ const StorageIndex globalNonContractDimOffset = nonContractGroupOffset + nonContractId;
1057
+ const StorageIndex globalContractDimOffset = contractGroupOffset + contractId;
1058
+ auto local_output = scratch_ptr + OutScratchOffset;
1059
+ const bool is_internal = nonContractDim - nonContractGroupOffset >= Properties::TileSizeDimNC &&
1060
+ contractDim - contractGroupOffset >= Properties::TileSizeDimC;
1061
+ is_internal
1062
+ ? compute_panel<true>(itemID, vec, mat, local_output, out_ptr,
1063
+ #ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON
1064
+ scratch_ptr, contractGroupOffset,
1065
+ #endif
1066
+ nonContractGroupOffset, linearLocalThreadId, contractDim, nonContractDim, contractId,
1067
+ nonContractId, globalContractDimOffset, globalNonContractDimOffset, outScratchIndex)
1068
+ : compute_panel<false>(itemID, vec, mat, local_output, out_ptr,
1069
+ #ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON
1070
+ scratch_ptr, contractGroupOffset,
1071
+ #endif
1072
+ nonContractGroupOffset, linearLocalThreadId, contractDim, nonContractDim, contractId,
1073
+ nonContractId, globalContractDimOffset, globalNonContractDimOffset, outScratchIndex);
1074
+ }
1075
+ template <bool is_internal_block, typename OutPtr>
1076
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_panel(
1077
+ const cl::sycl::nd_item<1> &itemID, const VectorMapper &vec, const TensorMapper &mat, OutScalar *local_output,
1078
+ OutPtr out_ptr,
1079
+ #ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON
1080
+ OutScalar *scratch_ptr, const StorageIndex contractGroupOffset,
1081
+ #endif
1082
+ const StorageIndex nonContractGroupOffset, const StorageIndex linearLocalThreadId, StorageIndex contractDim,
1083
+ StorageIndex nonContractDim, StorageIndex contractId, StorageIndex nonContractId,
1084
+ StorageIndex globalContractDimOffset, StorageIndex globalNonContractDimOffset, StorageIndex outScratchIndex) {
1085
+ OutScalar outScalar[Properties::WorkLoadPerThreadNC] = {OutScalar(0)};
1086
+ // Reading the vector
1087
+ #ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON
1088
+ const StorageIndex vectorOffset = contractGroupOffset + linearLocalThreadId;
1089
+ extract_block<VecBlockProperties, is_internal_block, KFactor,
1090
+ Properties::LocalThreadSizeNC * Properties::LocalThreadSizeC>(vec, scratch_ptr, linearLocalThreadId,
1091
+ vectorOffset, contractDim);
1092
+
1093
+ itemID.barrier(cl::sycl::access::fence_space::local_space);
1094
+ auto in_scratch_ptr = scratch_ptr + contractId;
1095
+ #endif
1096
+
1097
+ StorageIndex privateOffsetC = 0;
1098
+ EIGEN_UNROLL_LOOP
1099
+ for (StorageIndex i = 0; i < Properties::WorkLoadPerThreadC; i++) {
1100
+ StorageIndex privateOffsetNC = 0;
1101
+ bool contract_conds = ((globalContractDimOffset + privateOffsetC) < contractDim);
1102
+ #ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON
1103
+ auto vecScalar = *in_scratch_ptr;
1104
+ #else
1105
+ auto vecScalar = (check_boundary<is_internal_block>(contract_conds))
1106
+ ? vec(is_lhs_vec ? StorageIndex(0) : globalContractDimOffset + privateOffsetC,
1107
+ is_lhs_vec ? globalContractDimOffset + privateOffsetC : StorageIndex(0))
1108
+ : OutScalar(0);
1109
+ #endif
1110
+ EIGEN_UNROLL_LOOP
1111
+ for (StorageIndex j = 0; j < Properties::WorkLoadPerThreadNC; j++) {
1112
+ auto matScalar = (check_boundary<is_internal_block>(
1113
+ contract_conds && ((globalNonContractDimOffset + privateOffsetNC) < nonContractDim)))
1114
+ ? mat(is_lhs_vec ? globalContractDimOffset + privateOffsetC
1115
+ : globalNonContractDimOffset + privateOffsetNC,
1116
+ is_lhs_vec ? globalNonContractDimOffset + privateOffsetNC
1117
+ : globalContractDimOffset + privateOffsetC)
1118
+ : OutScalar(0);
1119
+
1120
+ outScalar[j] = cl::sycl::mad(matScalar, vecScalar, outScalar[j]);
1121
+ privateOffsetNC += Properties::LocalThreadSizeNC;
1122
+ }
1123
+ privateOffsetC += Properties::LocalThreadSizeC;
1124
+ #ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON
1125
+ in_scratch_ptr += Properties::LocalThreadSizeC;
1126
+ #endif
1127
+ }
1128
+
1129
+ auto out_scratch_ptr = local_output + outScratchIndex;
1130
+ // Each block of 16*16 element in shared memory should reduce to 16*1
1131
+ EIGEN_UNROLL_LOOP
1132
+ for (StorageIndex j = 0; j < Properties::WorkLoadPerThreadNC; j++) {
1133
+ *out_scratch_ptr = outScalar[j];
1134
+
1135
+ out_scratch_ptr += (Properties::LocalThreadSizeNC * Properties::LocalThreadSizeC);
1136
+ }
1137
+ if (is_lhs_vec) {
1138
+ nonContractId = linearLocalThreadId % Properties::LocalThreadSizeNC;
1139
+ contractId = linearLocalThreadId / Properties::LocalThreadSizeNC;
1140
+ outScratchIndex = nonContractId + contractId * Properties::LocalThreadSizeNC;
1141
+ }
1142
+
1143
+ out_scratch_ptr = local_output + outScratchIndex;
1144
+ EIGEN_UNROLL_LOOP
1145
+ for (StorageIndex j = 0; j < Properties::WorkLoadPerThreadNC; j++) {
1146
+ EIGEN_UNROLL_LOOP
1147
+ for (StorageIndex offset = Properties::LocalThreadSizeC >> 1; offset > 0; offset >>= 1) {
1148
+ itemID.barrier(cl::sycl::access::fence_space::local_space);
1149
+ if (contractId < offset) {
1150
+ StorageIndex myNeigbourId = (Properties::LocalThreadSizeNC * offset);
1151
+ *out_scratch_ptr += out_scratch_ptr[myNeigbourId];
1152
+ }
1153
+ }
1154
+ // moving to next 16 by 16 block
1155
+ out_scratch_ptr += (Properties::LocalThreadSizeNC * Properties::LocalThreadSizeC);
1156
+ }
1157
+
1158
+ if (contractId == 0) {
1159
+ out_scratch_ptr = local_output + nonContractId;
1160
+ StorageIndex global_final_offset = nonContractGroupOffset + nonContractId;
1161
+ out_ptr += global_final_offset;
1162
+ EIGEN_UNROLL_LOOP
1163
+ for (StorageIndex j = 0; j < Properties::WorkLoadPerThreadNC; j++) {
1164
+ if (check_boundary<is_internal_block>(global_final_offset < nonContractDim)) {
1165
+ auto res = *out_scratch_ptr;
1166
+
1167
+ *out_ptr = res;
1168
+ out_ptr += Properties::LocalThreadSizeNC;
1169
+ }
1170
+ // moving to next 16 by 16 block to ge the next 16 reduced elements
1171
+ out_scratch_ptr += (Properties::LocalThreadSizeNC * Properties::LocalThreadSizeC);
1172
+ if (!(is_internal_block)) global_final_offset += Properties::LocalThreadSizeNC;
1173
+ }
1174
+ }
1175
+ }
1176
+
1177
+ template <typename InputBlockProperties, bool is_internal_block, int CFactor, int GroupSize, typename Input,
1178
+ typename Local>
1179
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void extract_block(const Input &inpt, Local *local_ptr,
1180
+ const StorageIndex &linearLocalThreadId,
1181
+ const StorageIndex &cOffset, const StorageIndex &C) {
1182
+ local_ptr += InputBlockProperties::c_stride * linearLocalThreadId;
1183
+ StorageIndex cIndex = cOffset;
1184
+ for (StorageIndex cId = 0; cId < CFactor / InputBlockProperties::c_stride; cId++) {
1185
+ if (check_boundary<is_internal_block>(cIndex + InputBlockProperties::c_stride - 1 < C)) {
1186
+ auto val = read<InputBlockProperties::packet_load, InputBlockProperties::is_coalesced_layout,
1187
+ InputBlockProperties::is_rhs, typename InputBlockProperties::OutType>(inpt, StorageIndex(0),
1188
+ cIndex, StorageIndex(1));
1189
+ write<StorageIndex, 1, data_source::local_mem>(val, local_ptr);
1190
+ } else {
1191
+ EIGEN_UNROLL_LOOP
1192
+ for (StorageIndex i = 0; i < InputBlockProperties::elements_per_access; i++) {
1193
+ OutScalar val =
1194
+ (cIndex + i < C)
1195
+ ? read<false, InputBlockProperties::is_coalesced_layout, InputBlockProperties::is_rhs, OutScalar>(
1196
+ inpt, StorageIndex(0), cIndex + i, StorageIndex(1))
1197
+ : OutScalar(0);
1198
+ write<StorageIndex, 1, data_source::local_mem>(val, local_ptr + i);
1199
+ }
1200
+ }
1201
+ local_ptr += InputBlockProperties::c_stride * GroupSize;
1202
+ cIndex += InputBlockProperties::c_stride * GroupSize;
1203
+ }
1204
+ }
1205
+ };
1206
+ #endif
1207
+
1208
+ #ifndef EIGEN_SYCL_DISABLE_SCALAR
1209
+
1210
+ /*!
1211
+ * \brief GeneralScalarContraction is a template class that provides the scalar value of Tensor -Tensor contraction
1212
+ * operation, when all the dimensions are contracting dimensions. This Kernel reduces two tensors to an scalar
1213
+ *
1214
+ * \tparam OutScalar: determines the output scalar type
1215
+ *
1216
+ * \tparam LhsScalar: determines the left-hand-side scalar type
1217
+ *
1218
+ * \tparam RhsScalar: determines the right-hand-side scalar type
1219
+ *
1220
+ * \tparam OutAccessor: determines the sycl accessor type for out put (please see the sycl-1.2.1 specification
1221
+ * (https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf) for accessor definition)
1222
+ *
1223
+ * \tparam LhsMapper: determines the tensor contraction mapper type for left-hand-side matrix
1224
+ *
1225
+ * \tparam RhsMapper: determines the tensor contraction mapper type for right-hand-side matrix
1226
+ *
1227
+ * \tparam StorageIndex: determines the StorageIndex Type
1228
+ *
1229
+ * \tparam Vectorizable: determines whether or not the vectorization is enabled for the Eigen expression.
1230
+ *
1231
+ * \param scratch: local memory containing tiles of LHS and RHS tensors for each work-group
1232
+ *
1233
+ * \param lhs: determines the left-hand-side flattened tensor (tensor mapper)
1234
+ *
1235
+ * \param rhs: determines the right-hand-side flattened tensor (tensor mapper)
1236
+ *
1237
+ * \param out_res: determines the output tensor containing the contraction result
1238
+ *
1239
+ * \param rng: determines the total input data size
1240
+ */
1241
+ template <typename OutScalar, typename LhsScalar, typename RhsScalar, typename OutAccessor, typename LhsMapper,
1242
+ typename RhsMapper, typename StorageIndex, bool Vectorizable>
1243
+ struct GeneralScalarContraction {
1244
+ typedef cl::sycl::accessor<OutScalar, 1, cl::sycl::access::mode::read_write, cl::sycl::access::target::local> Scratch;
1245
+ Scratch scratch;
1246
+ const LhsMapper lhs;
1247
+ const RhsMapper rhs;
1248
+ OutAccessor out_res;
1249
+ const StorageIndex rng;
1250
+
1251
+ EIGEN_DEVICE_FUNC
1252
+ GeneralScalarContraction(Scratch scratch_, const LhsMapper lhs_, const RhsMapper rhs_, OutAccessor out_res_,
1253
+ const StorageIndex rng_)
1254
+ : scratch(scratch_), lhs(lhs_), rhs(rhs_), out_res(out_res_), rng(rng_) {}
1255
+
1256
+ EIGEN_DEVICE_FUNC void operator()(cl::sycl::nd_item<1> itemID) const {
1257
+
1258
+ auto out_ptr = out_res;
1259
+ OutScalar * scratch_ptr = scratch.get_pointer();
1260
+
1261
+ StorageIndex globalid = itemID.get_global_id(0);
1262
+ StorageIndex localid = itemID.get_local_id(0);
1263
+ OutScalar accumulator = OutScalar(0);
1264
+ for (StorageIndex i = globalid; i < rng; i += itemID.get_global_range(0)) {
1265
+ accumulator = cl::sycl::mad(lhs(0, i), rhs(i, 0), accumulator);
1266
+ }
1267
+ auto out_scratch_ptr = scratch_ptr + localid;
1268
+ *out_scratch_ptr = accumulator;
1269
+ for (StorageIndex offset = itemID.get_local_range(0) >> 1; offset > 0; offset >>= 1) {
1270
+ itemID.barrier(cl::sycl::access::fence_space::local_space);
1271
+ if (localid < offset) {
1272
+ *out_scratch_ptr = (accumulator += out_scratch_ptr[offset]);
1273
+ }
1274
+ }
1275
+ if (localid == 0) {
1276
+ out_ptr[itemID.get_group(0)] = accumulator;
1277
+ }
1278
+ }
1279
+ };
1280
+ #endif
1281
+
1282
+ } // namespace internal
1283
+ } // namespace TensorSycl
1284
+
1285
+ template <typename Indices, typename LeftArgType, typename RightArgType, typename OutputKernelType>
1286
+ struct TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>,
1287
+ Eigen::SyclDevice>
1288
+ : public TensorContractionEvaluatorBase<TensorEvaluator<
1289
+ const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, Eigen::SyclDevice>> {
1290
+ static_assert(std::is_same<OutputKernelType, const NoOpOutputKernel>::value,
1291
+ "SYCL tensor contraction does not support output kernels.");
1292
+
1293
+ typedef Eigen::SyclDevice Device;
1294
+
1295
+ typedef TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, Device> Self;
1296
+ typedef TensorContractionEvaluatorBase<Self> Base;
1297
+ typedef TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType> XprType;
1298
+ typedef std::remove_const_t<typename XprType::Scalar> Scalar;
1299
+ typedef typename XprType::Index StorageIndex;
1300
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
1301
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
1302
+ typedef typename Base::Storage Storage;
1303
+ typedef typename Base::EvaluatorPointerType EvaluatorPointerType;
1304
+ struct TripleDim {
1305
+ const StorageIndex M;
1306
+ const StorageIndex N;
1307
+ const StorageIndex K;
1308
+ TripleDim(const StorageIndex M_, const StorageIndex N_, const StorageIndex K_) : M(M_), N(N_), K(K_) {}
1309
+ };
1310
+ enum {
1311
+ PacketAccess = (PacketType<CoeffReturnType, Device>::size > 1),
1312
+ BlockAccess = false,
1313
+ };
1314
+
1315
+ static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
1316
+ static constexpr int LDims = Base::LDims;
1317
+ static constexpr int RDims = Base::RDims;
1318
+ static constexpr int ContractDims = Base::ContractDims;
1319
+
1320
+ typedef array<StorageIndex, LDims> left_dim_mapper_t;
1321
+ typedef array<StorageIndex, RDims> right_dim_mapper_t;
1322
+
1323
+ typedef array<StorageIndex, ContractDims> contract_t;
1324
+ typedef array<StorageIndex, LDims - ContractDims> left_nocontract_t;
1325
+ typedef array<StorageIndex, RDims - ContractDims> right_nocontract_t;
1326
+
1327
+ static constexpr int NumDims = LDims + RDims - 2 * ContractDims;
1328
+
1329
+ typedef DSizes<StorageIndex, NumDims> Dimensions;
1330
+
1331
+ typedef TensorEvaluator<typename Base::EvalLeftArgType, Device> LeftEvaluator;
1332
+ typedef TensorEvaluator<typename Base::EvalRightArgType, Device> RightEvaluator;
1333
+ typedef std::remove_const_t<typename LeftEvaluator::CoeffReturnType> LhsScalar;
1334
+ typedef std::remove_const_t<typename RightEvaluator::CoeffReturnType> RhsScalar;
1335
+
1336
+ typedef typename LeftEvaluator::Dimensions LeftDimensions;
1337
+ typedef typename RightEvaluator::Dimensions RightDimensions;
1338
+
1339
+ template <bool lhs_inner_dim_contiguous, bool rhs_inner_dim_contiguous, bool rhs_inner_dim_reordered>
1340
+ struct input_mapper_propertis {
1341
+ static EIGEN_CONSTEXPR bool is_lhs_matrix = (LDims == 2 && ContractDims == 1) || lhs_inner_dim_contiguous;
1342
+ static EIGEN_CONSTEXPR bool is_rhs_matrix =
1343
+ (RDims == 2 && ContractDims == 1) || (rhs_inner_dim_contiguous && !rhs_inner_dim_reordered);
1344
+ };
1345
+
1346
+ TensorEvaluator(const XprType &op, const Device &device) : Base(op, device) {}
1347
+
1348
+ // We need to redefine this method to make nvcc happy
1349
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(typename Base::EvaluatorPointerType data) {
1350
+ this->m_leftImpl.evalSubExprsIfNeeded(NULL);
1351
+ this->m_rightImpl.evalSubExprsIfNeeded(NULL);
1352
+ if (!data) {
1353
+ this->m_result = this->m_device.get(
1354
+ static_cast<Scalar *>(this->m_device.allocate_temp(this->dimensions().TotalSize() * sizeof(Scalar))));
1355
+ data = this->m_result;
1356
+ }
1357
+ evalToSycl(data);
1358
+ return (this->m_result != NULL);
1359
+ }
1360
+ const Eigen::SyclDevice &device() const { return this->m_device; }
1361
+ void evalToSycl(typename Base::EvaluatorPointerType buffer) const {
1362
+ if (this->m_lhs_inner_dim_contiguous) {
1363
+ if (this->m_rhs_inner_dim_contiguous) {
1364
+ if (this->m_rhs_inner_dim_reordered) {
1365
+ evalTyped<true, true, true, Unaligned>(buffer);
1366
+ } else {
1367
+ evalTyped<true, true, false, Unaligned>(buffer);
1368
+ }
1369
+ } else {
1370
+ if (this->m_rhs_inner_dim_reordered) {
1371
+ evalTyped<true, false, true, Unaligned>(buffer);
1372
+ } else {
1373
+ evalTyped<true, false, false, Unaligned>(buffer);
1374
+ }
1375
+ }
1376
+ } else {
1377
+ if (this->m_rhs_inner_dim_contiguous) {
1378
+ if (this->m_rhs_inner_dim_reordered) {
1379
+ evalTyped<false, true, true, Unaligned>(buffer);
1380
+ } else {
1381
+ evalTyped<false, true, false, Unaligned>(buffer);
1382
+ }
1383
+ } else {
1384
+ if (this->m_rhs_inner_dim_reordered) {
1385
+ evalTyped<false, false, true, Unaligned>(buffer);
1386
+ } else {
1387
+ evalTyped<false, false, false, Unaligned>(buffer);
1388
+ }
1389
+ }
1390
+ }
1391
+ }
1392
+
1393
+ template <bool lhs_inner_dim_contiguous, bool rhs_inner_dim_contiguous, bool rhs_inner_dim_reordered, int Alignment>
1394
+ void evalTyped(typename Base::EvaluatorPointerType buffer) const {
1395
+ const auto triple_dim = TripleDim{this->m_i_size, this->m_j_size, this->m_k_size};
1396
+ typedef internal::TensorContractionInputMapper<
1397
+ LhsScalar, StorageIndex, internal::Lhs, LeftEvaluator, left_nocontract_t, contract_t,
1398
+ PacketType<CoeffReturnType, Device>::size, lhs_inner_dim_contiguous, false, Unaligned, MakePointer>
1399
+ LhsMapper;
1400
+
1401
+ typedef internal::TensorContractionInputMapper<RhsScalar, StorageIndex, internal::Rhs, RightEvaluator,
1402
+ right_nocontract_t, contract_t,
1403
+ PacketType<CoeffReturnType, Device>::size, rhs_inner_dim_contiguous,
1404
+ rhs_inner_dim_reordered, Unaligned, MakePointer>
1405
+ RhsMapper;
1406
+
1407
+ // initialize data mappers
1408
+ LhsMapper lhs(this->m_leftImpl, this->m_left_nocontract_strides, this->m_i_strides,
1409
+ this->m_left_contracting_strides, this->m_k_strides);
1410
+
1411
+ RhsMapper rhs(this->m_rightImpl, this->m_right_nocontract_strides, this->m_j_strides,
1412
+ this->m_right_contracting_strides, this->m_k_strides);
1413
+
1414
+ #ifndef EIGEN_SYCL_DISABLE_SCALAR
1415
+ if (triple_dim.M == 1 && triple_dim.N == 1) {
1416
+ launchSC(buffer, lhs, rhs, triple_dim.K);
1417
+ } else
1418
+ #endif
1419
+ #ifndef EIGEN_SYCL_DISABLE_GEMV
1420
+ if (triple_dim.M != 1 && triple_dim.N == 1) {
1421
+ LaunchVT<false>(buffer, rhs, lhs, triple_dim.M, triple_dim.K);
1422
+ } else if (triple_dim.M == 1 && triple_dim.N != 1) {
1423
+ LaunchVT<true>(buffer, lhs, rhs, triple_dim.N, triple_dim.K);
1424
+ } else // This is equivalent of if (m!=1 && n!=1)
1425
+ #endif
1426
+ {
1427
+ typedef input_mapper_propertis<lhs_inner_dim_contiguous, rhs_inner_dim_contiguous, rhs_inner_dim_reordered>
1428
+ inpt_mapper_properties;
1429
+ #ifndef EIGEN_SYCL_DISABLE_SKINNY
1430
+ bool skinny = false;
1431
+ auto platform_name = this->device().getPlatformName();
1432
+ // This is based on empirical calculation for AMD r9-nano and Fiji
1433
+ if (platform_name.find("AMD") == 0) {
1434
+ skinny = (triple_dim.M < triple_dim.K || triple_dim.N < triple_dim.K) &&
1435
+ ((triple_dim.M < 1024 && triple_dim.N < 1024) ||
1436
+ (uint64_t(triple_dim.M * triple_dim.N) < uint64_t(triple_dim.K)));
1437
+ } else {
1438
+ skinny = (((std::max(triple_dim.K, triple_dim.N) / std::min(triple_dim.K, triple_dim.N)) > 100) ||
1439
+ ((std::max(triple_dim.K, triple_dim.M) / std::min(triple_dim.K, triple_dim.M)) > 100) ||
1440
+ ((std::max(triple_dim.N, triple_dim.M) / std::min(triple_dim.N, triple_dim.M)) > 100));
1441
+ }
1442
+ if (skinny)
1443
+ adjustTT<true, inpt_mapper_properties>(buffer, lhs, rhs, triple_dim);
1444
+ else
1445
+ #endif // EIGEN_SYCL_DISABLE_SKINNY
1446
+ adjustTT<false, inpt_mapper_properties>(buffer, lhs, rhs, triple_dim);
1447
+ }
1448
+ }
1449
+
1450
+ template <bool skinny, typename input_mapper_properties, typename LhsMapper, typename RhsMapper>
1451
+ void EIGEN_ALWAYS_INLINE adjustTT(EvaluatorPointerType buffer, const LhsMapper &lhs, const RhsMapper &rhs,
1452
+ const TripleDim &triple_dim) const {
1453
+ #ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON
1454
+ if (device().has_local_memory()) {
1455
+ typedef TensorSycl::internal::TTPanelSize<CoeffReturnType, StorageIndex, 4, 4, 16> PanelParameters;
1456
+ launchTT<TensorSycl::internal::contraction_type::local, skinny, input_mapper_properties, PanelParameters>(
1457
+ buffer, lhs, rhs, triple_dim);
1458
+ }
1459
+ #endif
1460
+ #ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_OFF
1461
+ if (!(device().has_local_memory())) {
1462
+ typedef TensorSycl::internal::TTPanelSize<CoeffReturnType, StorageIndex, 4, 4, 4> PanelParameters;
1463
+ launchTT<TensorSycl::internal::contraction_type::no_local, skinny, input_mapper_properties, PanelParameters>(
1464
+ buffer, lhs, rhs, triple_dim);
1465
+ }
1466
+ #endif
1467
+ }
1468
+
1469
+ template <TensorSycl::internal::contraction_type ct, bool skinny, typename input_mapper_properties,
1470
+ typename Properties, typename LhsMapper, typename RhsMapper>
1471
+ void launchTT(EvaluatorPointerType buffer, const LhsMapper &lhs, const RhsMapper &rhs,
1472
+ const TripleDim &triple_dim) const {
1473
+ const StorageIndex roundUpM = Eigen::TensorSycl::internal::roundUp(triple_dim.M, Properties::TileSizeDimM);
1474
+ const StorageIndex roundUpN = Eigen::TensorSycl::internal::roundUp(triple_dim.N, Properties::TileSizeDimN);
1475
+ const StorageIndex groupSizeM = roundUpM / Properties::TileSizeDimM;
1476
+ const StorageIndex groupSizeN = roundUpN / Properties::TileSizeDimN;
1477
+
1478
+ const StorageIndex roundUpK = Eigen::TensorSycl::internal::roundUp(triple_dim.K, Properties::TileSizeDimK);
1479
+ StorageIndex totalTilesK = roundUpK / Properties::TileSizeDimK;
1480
+ StorageIndex groupSizeK =
1481
+ skinny
1482
+ ? std::max(std::min(totalTilesK,
1483
+ (StorageIndex)(device().getPowerOfTwo(device().getNumSyclMultiProcessors(), true) * 4) /
1484
+ (groupSizeM * groupSizeN)),
1485
+ StorageIndex(1))
1486
+ : StorageIndex(1);
1487
+
1488
+ const StorageIndex numTilesPerGroup = Eigen::TensorSycl::internal::roundUp(totalTilesK, groupSizeK) / groupSizeK;
1489
+
1490
+ const StorageIndex totalGroupSize = groupSizeM * groupSizeN * groupSizeK;
1491
+
1492
+ const StorageIndex localRange = Properties::LocalThreadSizeM * Properties::LocalThreadSizeN;
1493
+ const StorageIndex globalRange = totalGroupSize * localRange;
1494
+
1495
+ const StorageIndex scratchSize = (ct == TensorSycl::internal::contraction_type::local)
1496
+ ? ((Properties::DoubleBuffer + 1) *
1497
+ (Properties::TileSizeDimM + Properties::BC) * (Properties::TileSizeDimK)) +
1498
+ ((Properties::DoubleBuffer + 1) * (Properties::TileSizeDimK) *
1499
+ (Properties::TileSizeDimN + Properties::BC))
1500
+ : StorageIndex(1);
1501
+
1502
+ auto thread_range = cl::sycl::nd_range<1>(cl::sycl::range<1>(globalRange), cl::sycl::range<1>(localRange));
1503
+ if (groupSizeK == 1) {
1504
+ typedef TensorSycl::internal::TensorContractionKernel<CoeffReturnType, LhsScalar, RhsScalar, EvaluatorPointerType,
1505
+ LhsMapper, RhsMapper, StorageIndex, Properties, TripleDim,
1506
+ PacketAccess, input_mapper_properties, true, ct>
1507
+ ContractKernelName;
1508
+ device().template binary_kernel_launcher<CoeffReturnType, ContractKernelName>(
1509
+ lhs, rhs, buffer, thread_range, scratchSize, groupSizeM, groupSizeN, numTilesPerGroup, triple_dim).wait();
1510
+ } else {
1511
+ typedef TensorSycl::internal::TensorContractionKernel<CoeffReturnType, LhsScalar, RhsScalar, EvaluatorPointerType,
1512
+ LhsMapper, RhsMapper, StorageIndex, Properties, TripleDim,
1513
+ PacketAccess, input_mapper_properties, false, ct>
1514
+ ContractKernelName;
1515
+ CoeffReturnType *temp_pointer = static_cast<CoeffReturnType *>(
1516
+ device().allocate_temp(triple_dim.M * triple_dim.N * groupSizeK * sizeof(CoeffReturnType)));
1517
+ EvaluatorPointerType tmp_global_accessor = device().get(temp_pointer);
1518
+
1519
+ device().template binary_kernel_launcher<CoeffReturnType, ContractKernelName>(
1520
+ lhs, rhs, tmp_global_accessor, thread_range, scratchSize, groupSizeM, groupSizeN, numTilesPerGroup,
1521
+ triple_dim).wait();
1522
+
1523
+ typedef Eigen::internal::SumReducer<CoeffReturnType> Op;
1524
+ auto op = Op();
1525
+ typedef TensorSycl::internal::SecondStepPartialReduction<CoeffReturnType, StorageIndex, EvaluatorPointerType,
1526
+ EvaluatorPointerType, Op>
1527
+ ReductionKernel;
1528
+
1529
+ device().template unary_kernel_launcher<CoeffReturnType, ReductionKernel>(
1530
+ tmp_global_accessor, buffer,
1531
+ cl::sycl::nd_range<1>(cl::sycl::range<1>(StorageIndex(
1532
+ Eigen::TensorSycl::internal::roundUp(triple_dim.M * triple_dim.N, localRange))),
1533
+ cl::sycl::range<1>(localRange)),
1534
+ StorageIndex(1), op, StorageIndex(triple_dim.M * triple_dim.N), groupSizeK).wait();
1535
+ device().deallocate_temp(temp_pointer);
1536
+ }
1537
+ }
1538
+
1539
+ #ifndef EIGEN_SYCL_DISABLE_GEMV
1540
+ template <bool is_lhs_vec, typename VectorMapper, typename TensorMapper, typename StorageIndex>
1541
+ void EIGEN_ALWAYS_INLINE LaunchVT(EvaluatorPointerType buffer, const VectorMapper &vec, const TensorMapper &mat,
1542
+ StorageIndex NC, StorageIndex C) const {
1543
+ const StorageIndex nonContractDim = NC;
1544
+ EIGEN_CONSTEXPR StorageIndex NCFactor = 1;
1545
+ EIGEN_CONSTEXPR StorageIndex CFactor = 1;
1546
+ EIGEN_CONSTEXPR StorageIndex NCWindow = 16;
1547
+ typedef Eigen::TensorSycl::internal::TVPanelSize<CoeffReturnType, StorageIndex, NCWindow, CFactor, NCFactor>
1548
+ Properties;
1549
+ const StorageIndex roundUpC = Eigen::TensorSycl::internal::roundUp(C, Properties::TileSizeDimC);
1550
+ const StorageIndex cNumGroups = roundUpC / (Properties::LocalThreadSizeC * Properties::WorkLoadPerThreadC);
1551
+ const StorageIndex roundUpNC = Eigen::TensorSycl::internal::roundUp(nonContractDim, Properties::TileSizeDimNC);
1552
+ const StorageIndex nCNumGroups = roundUpNC / (Properties::LocalThreadSizeNC * Properties::WorkLoadPerThreadNC);
1553
+ const StorageIndex globalRange =
1554
+ (roundUpNC / (Properties::WorkLoadPerThreadNC)) * (roundUpC / (Properties::WorkLoadPerThreadC));
1555
+ const StorageIndex localRange = Properties::LocalThreadSizeNC * Properties::LocalThreadSizeC;
1556
+ const StorageIndex scratchSize =
1557
+ (Properties::WorkLoadPerThreadNC + CFactor) * Properties::LocalThreadSizeC * Properties::LocalThreadSizeNC;
1558
+ auto thread_range = cl::sycl::nd_range<1>(cl::sycl::range<1>(globalRange), cl::sycl::range<1>(localRange));
1559
+ if (cNumGroups > 1) {
1560
+ typedef Eigen::TensorSycl::internal::GeneralVectorTensor<CoeffReturnType, EvaluatorPointerType, VectorMapper,
1561
+ TensorMapper, StorageIndex, Properties, CFactor, false,
1562
+ is_lhs_vec, false>
1563
+ ContractKernelName;
1564
+ CoeffReturnType *temp_pointer =
1565
+ static_cast<CoeffReturnType *>(device().allocate_temp(nonContractDim * cNumGroups * sizeof(CoeffReturnType)));
1566
+ EvaluatorPointerType tmp_global_accessor = device().get(temp_pointer);
1567
+
1568
+ device().template binary_kernel_launcher<CoeffReturnType, ContractKernelName>(
1569
+ vec, mat, tmp_global_accessor, thread_range, scratchSize, nCNumGroups, nonContractDim, C).wait();
1570
+
1571
+ typedef Eigen::internal::SumReducer<CoeffReturnType> Op;
1572
+ typedef TensorSycl::internal::SecondStepPartialReduction<CoeffReturnType, StorageIndex, EvaluatorPointerType,
1573
+ EvaluatorPointerType, Op>
1574
+ ReductionKernel;
1575
+
1576
+ device().template unary_kernel_launcher<CoeffReturnType, ReductionKernel>(
1577
+ tmp_global_accessor, buffer,
1578
+ cl::sycl::nd_range<1>(cl::sycl::range<1>(Eigen::TensorSycl::internal::roundUp(nonContractDim, localRange)),
1579
+ cl::sycl::range<1>(localRange)),
1580
+ StorageIndex(1), Op(), nonContractDim, cNumGroups).wait();
1581
+ device().deallocate_temp(temp_pointer);
1582
+ } else {
1583
+ typedef Eigen::TensorSycl::internal::GeneralVectorTensor<CoeffReturnType, EvaluatorPointerType, VectorMapper,
1584
+ TensorMapper, StorageIndex, Properties, CFactor, false,
1585
+ is_lhs_vec, true>
1586
+ ContractKernelName;
1587
+ device().template binary_kernel_launcher<CoeffReturnType, ContractKernelName>(
1588
+ vec, mat, buffer, thread_range, scratchSize, nCNumGroups, nonContractDim, C).wait();
1589
+
1590
+ }
1591
+ }
1592
+ #endif
1593
+
1594
+ #ifndef EIGEN_SYCL_DISABLE_SCALAR
1595
+ template <typename LhsMapper, typename RhsMapper>
1596
+ EIGEN_ALWAYS_INLINE void launchSC(EvaluatorPointerType buffer, const LhsMapper &lhs, const RhsMapper &rhs,
1597
+ StorageIndex K) const {
1598
+ EIGEN_STATIC_ASSERT(!((EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1) &
1599
+ (EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1 - 1)),
1600
+ "The Local thread size must be a power of 2 for the reduction "
1601
+ "operation");
1602
+ EIGEN_CONSTEXPR StorageIndex local_range = EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1;
1603
+
1604
+ // Here we force the code not to be more than 2-step reduction: Our empirical research shows that if each thread
1605
+ // reduces at least 512 elementss individually, we get better performance.
1606
+ const StorageIndex num_work_group = ((K + (512 * local_range - 1)) / (512 * local_range) > 1 ? local_range : 1);
1607
+ const StorageIndex global_range = num_work_group * local_range;
1608
+
1609
+ typedef Eigen::TensorSycl::internal::GeneralScalarContraction<
1610
+ CoeffReturnType, LhsScalar, RhsScalar, EvaluatorPointerType, LhsMapper, RhsMapper, StorageIndex, false>
1611
+ ContractKernelName;
1612
+ auto thread_range = cl::sycl::nd_range<1>(cl::sycl::range<1>(global_range), cl::sycl::range<1>(local_range));
1613
+ if (num_work_group > 1) {
1614
+ CoeffReturnType *temp_pointer =
1615
+ static_cast<CoeffReturnType *>(device().allocate_temp(num_work_group * sizeof(CoeffReturnType)));
1616
+ EvaluatorPointerType tmp_global_accessor = device().get(temp_pointer);
1617
+ device().template binary_kernel_launcher<CoeffReturnType, ContractKernelName>(lhs, rhs, tmp_global_accessor,
1618
+ thread_range, local_range, K).wait();
1619
+ typedef Eigen::internal::SumReducer<CoeffReturnType> Op;
1620
+ typedef TensorSycl::internal::SecondStepFullReducer<CoeffReturnType, Op, EvaluatorPointerType,
1621
+ EvaluatorPointerType, StorageIndex, local_range>
1622
+ GenericRKernel;
1623
+ device().template unary_kernel_launcher<CoeffReturnType, GenericRKernel>(
1624
+ tmp_global_accessor, buffer,
1625
+ cl::sycl::nd_range<1>(cl::sycl::range<1>(local_range), cl::sycl::range<1>(local_range)), local_range, Op()).wait();
1626
+ device().deallocate_temp(temp_pointer);
1627
+ } else {
1628
+ device().template binary_kernel_launcher<CoeffReturnType, ContractKernelName>(lhs, rhs, buffer, thread_range,
1629
+ local_range, K).wait();
1630
+ }
1631
+ }
1632
+ #endif
1633
+
1634
+ EIGEN_STRONG_INLINE void cleanup() {
1635
+ this->m_leftImpl.cleanup();
1636
+ this->m_rightImpl.cleanup();
1637
+
1638
+ if (this->m_result) {
1639
+ this->m_device.deallocate_temp(this->m_result);
1640
+ this->m_result = NULL;
1641
+ }
1642
+ }
1643
+ };
1644
+ } // namespace Eigen
1645
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_SYCL_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionThreadPool.h ADDED
@@ -0,0 +1,1679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_THREAD_POOL_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_THREAD_POOL_H
12
+
13
+ // evaluator for thread pool device
14
+ #ifdef EIGEN_USE_THREADS
15
+
16
+ #include "./InternalHeaderCheck.h"
17
+
18
+ namespace Eigen {
19
+
20
+ template<typename Indices, typename LeftArgType, typename RightArgType, typename OutputKernelType>
21
+ struct TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, ThreadPoolDevice> :
22
+ public TensorContractionEvaluatorBase<TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, ThreadPoolDevice> > {
23
+
24
+ typedef ThreadPoolDevice Device;
25
+
26
+ typedef TensorEvaluator<const TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType>, Device> Self;
27
+ typedef TensorContractionEvaluatorBase<Self> Base;
28
+
29
+ typedef TensorContractionOp<Indices, LeftArgType, RightArgType, OutputKernelType> XprType;
30
+ typedef std::remove_const_t<typename XprType::Scalar> Scalar;
31
+ typedef typename XprType::Index Index;
32
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
33
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
34
+
35
+ static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
36
+
37
+ // Most of the code is assuming that both input tensors are ColMajor. If the
38
+ // inputs are RowMajor, we will "cheat" by swapping the LHS and RHS:
39
+ // If we want to compute A * B = C, where A is LHS and B is RHS, the code
40
+ // will pretend B is LHS and A is RHS.
41
+ typedef std::conditional_t<
42
+ static_cast<int>(Layout) == static_cast<int>(ColMajor), LeftArgType, RightArgType> EvalLeftArgType;
43
+ typedef std::conditional_t<
44
+ static_cast<int>(Layout) == static_cast<int>(ColMajor), RightArgType, LeftArgType> EvalRightArgType;
45
+
46
+ static constexpr int LDims =
47
+ internal::array_size<typename TensorEvaluator<EvalLeftArgType, Device>::Dimensions>::value;
48
+ static constexpr int RDims =
49
+ internal::array_size<typename TensorEvaluator<EvalRightArgType, Device>::Dimensions>::value;
50
+ static constexpr int ContractDims = internal::array_size<Indices>::value;
51
+
52
+ typedef array<Index, LDims> left_dim_mapper_t;
53
+ typedef array<Index, RDims> right_dim_mapper_t;
54
+
55
+ typedef array<Index, ContractDims> contract_t;
56
+ typedef array<Index, LDims - ContractDims> left_nocontract_t;
57
+ typedef array<Index, RDims - ContractDims> right_nocontract_t;
58
+
59
+ static constexpr int NumDims = LDims + RDims - 2 * ContractDims;
60
+
61
+ typedef DSizes<Index, NumDims> Dimensions;
62
+
63
+ // typedefs needed in evalTo
64
+ typedef std::remove_const_t<typename EvalLeftArgType::Scalar> LhsScalar;
65
+ typedef std::remove_const_t<typename EvalRightArgType::Scalar> RhsScalar;
66
+ typedef typename internal::gebp_traits<LhsScalar, RhsScalar> Traits;
67
+
68
+ typedef TensorEvaluator<EvalLeftArgType, Device> LeftEvaluator;
69
+ typedef TensorEvaluator<EvalRightArgType, Device> RightEvaluator;
70
+
71
+ TensorEvaluator(const XprType& op, const Device& device) :
72
+ Base(op, device) {}
73
+
74
+ template <int Alignment>
75
+ void evalProduct(Scalar* buffer) const {
76
+ evalProductImpl<NoCallback, Alignment>(buffer, NoCallback());
77
+ }
78
+
79
+ template <typename EvalToCallback, int Alignment>
80
+ void evalProductAsync(Scalar* buffer, EvalToCallback done) const {
81
+ evalProductImpl<EvalToCallback, Alignment>(buffer, std::move(done));
82
+ }
83
+
84
+ template <typename DoneCallback, int Alignment>
85
+ void evalProductImpl(Scalar* buffer, DoneCallback done) const {
86
+ // This function computes a lot of heuristics in multiple steps, and it
87
+ // also has multiple exit points. To keep it sane, readable and all in one
88
+ // place, sync/async execution decision is made at runtime at the very end.
89
+ //
90
+ // (1) In sync mode we allocate Context on the stack, submit computations
91
+ // to the device thread pool, and block on a barrier until it is
92
+ // completed.
93
+ //
94
+ // (2) In async mode we allocate Context on the heap, and after all tasks
95
+ // are finished, we call provided the done callback, and delete a
96
+ // context from the heap.
97
+ //
98
+ // (*) EvalParallelContext & EvalShardedByInnerDimContext owns all the state
99
+ // and temporary buffers, required for executing the tensor contraction.
100
+ // They are responsible for cleaning it up after contraction is done.
101
+ static const bool IsEvalInSyncMode =
102
+ std::is_same<DoneCallback, NoCallback>::value;
103
+
104
+ const Index m = this->m_i_size;
105
+ const Index n = this->m_j_size;
106
+ const Index k = this->m_k_size;
107
+ if (m == 0 || n == 0 || k == 0) return;
108
+
109
+ // Compute a set of algorithm parameters:
110
+ // - kernel block sizes (bm, bn, bk)
111
+ // - task grain sizes (number of kernels executed per task: gm, gn)
112
+ // - number of threads
113
+ // - sharding by row/column
114
+ // - parallel packing or first lhs then rhs
115
+ // and some derived parameters:
116
+ // - number of tasks (nm, nn, nk)
117
+ // - number of kernels (nm0, nn0)
118
+ // Unfortunately, all these parameters are tightly interdependent.
119
+ // So in some cases we first compute approximate values, then compute other
120
+ // values based on these approximations and then refine the approximations.
121
+
122
+ // There are lots of heuristics here. There is some reasoning behind them,
123
+ // but ultimately they are just tuned on contraction benchmarks for
124
+ // different input configurations, thread counts and instruction sets.
125
+ // So feel free to question any of them.
126
+
127
+ // Compute whether we want to shard by row or by column.
128
+ // This is a first approximation, it will be refined later. Since we don't
129
+ // know number of threads yet we use 2, because what's we are most
130
+ // interested in at this point is whether it makes sense to use
131
+ // parallelization at all or not.
132
+ bool shard_by_col = shardByCol(m, n, 2);
133
+
134
+ // First approximation of kernel blocking sizes.
135
+ // Again, we don't know number of threads yet, so we use 2.
136
+ Index bm, bn, bk;
137
+ if (shard_by_col) {
138
+ internal::TensorContractionBlocking<Scalar, LhsScalar, RhsScalar, Index,
139
+ internal::ShardByCol>
140
+ blocking(k, m, n, 2);
141
+ bm = blocking.mc();
142
+ bn = blocking.nc();
143
+ bk = blocking.kc();
144
+ } else {
145
+ internal::TensorContractionBlocking<Scalar, LhsScalar, RhsScalar, Index,
146
+ internal::ShardByRow>
147
+ blocking(k, m, n, 2);
148
+ bm = blocking.mc();
149
+ bn = blocking.nc();
150
+ bk = blocking.kc();
151
+ }
152
+
153
+ // Compute optimal number of threads.
154
+ // Note: we use bk instead of k here because we are interested in amount of
155
+ // _parallelizable_ computations, and computations are not parallelizable
156
+ // across k dimension.
157
+ const TensorOpCost cost =
158
+ contractionCost(m, n, bm, bn, bk, shard_by_col, false);
159
+ int num_threads = TensorCostModel<ThreadPoolDevice>::numThreads(
160
+ static_cast<double>(n) * m, cost, this->m_device.numThreads());
161
+ int num_threads_by_k = numThreadsInnerDim(m, n, k);
162
+ if (shardByInnerDim(m, n, k, num_threads, num_threads_by_k)) {
163
+ // We are in the scenario where it is more effective to shard by the
164
+ // inner dimension.
165
+ if (IsEvalInSyncMode) {
166
+ EvalShardedByInnerDimContext<DoneCallback> ctx(
167
+ this, num_threads_by_k, buffer, m, n, k, std::move(done));
168
+ ctx.template run<Alignment>();
169
+ } else {
170
+ auto* ctx = new EvalShardedByInnerDimContext<DoneCallback>(
171
+ this, num_threads_by_k, buffer, m, n, k, std::move(done));
172
+ ctx->template runAsync<Alignment>();
173
+ }
174
+
175
+ return;
176
+ }
177
+
178
+ // TODO(dvyukov): this is a stop-gap to prevent regressions while the cost
179
+ // model is not tuned. Remove this when the cost model is tuned.
180
+ if (n == 1) num_threads = 1;
181
+
182
+ if (num_threads == 1) {
183
+ TENSOR_CONTRACTION_DISPATCH(this->template evalProductSequential,
184
+ Unaligned, (buffer));
185
+ if (!IsEvalInSyncMode) done();
186
+ return;
187
+ }
188
+
189
+ // Now that we know number of threads, recalculate sharding and blocking.
190
+ shard_by_col = shardByCol(m, n, num_threads);
191
+ if (shard_by_col) {
192
+ internal::TensorContractionBlocking<Scalar, LhsScalar, RhsScalar, Index,
193
+ internal::ShardByCol>
194
+ blocking(k, m, n, num_threads);
195
+ bm = blocking.mc();
196
+ bn = blocking.nc();
197
+ bk = blocking.kc();
198
+ } else {
199
+ internal::TensorContractionBlocking<Scalar, LhsScalar, RhsScalar, Index,
200
+ internal::ShardByRow>
201
+ blocking(k, m, n, num_threads);
202
+ bm = blocking.mc();
203
+ bn = blocking.nc();
204
+ bk = blocking.kc();
205
+ }
206
+
207
+ // Number of kernels for each dimension.
208
+ Index nm0 = divup(m, bm);
209
+ Index nn0 = divup(n, bn);
210
+ Index nk = divup(k, bk);
211
+
212
+ // Calculate task grain size (number of kernels executed per task).
213
+ // This task size coarsening serves two purposes:
214
+ // 1. It reduces per-task overheads including synchronization overheads.
215
+ // 2. It allows to use caches better (reuse the same packed rhs in several
216
+ // consecutive kernels).
217
+ Index gm = 1;
218
+ Index gn = 1;
219
+ // If we are sharding by column, then we prefer to reduce rows first.
220
+ if (shard_by_col) {
221
+ gm = coarsenM(m, n, bm, bn, bk, gn, num_threads, shard_by_col);
222
+ gn = coarsenN(m, n, bm, bn, bk, gm, num_threads, shard_by_col);
223
+ } else {
224
+ gn = coarsenN(m, n, bm, bn, bk, gm, num_threads, shard_by_col);
225
+ gm = coarsenM(m, n, bm, bn, bk, gn, num_threads, shard_by_col);
226
+ }
227
+ // Number of tasks in each dimension.
228
+ Index nm = divup(nm0, gm);
229
+ Index nn = divup(nn0, gn);
230
+
231
+ // If there is enough concurrency in the sharding dimension, we choose not
232
+ // to paralellize by the other dimension, and execute all kernels in sync
233
+ // mode. This reduces parallelism from the nm x nn down to nn
234
+ // (shard_by_col==true) or nm (shard_by_col==false).
235
+ const Index sharding_dim_tasks = shard_by_col ? nn : nm;
236
+ const int num_worker_threads = this->m_device.numThreadsInPool();
237
+
238
+ // With small number of threads we want to make sure that we do not reduce
239
+ // parallelism too much. With large number of threads we trade maximum
240
+ // parallelism for better memory locality.
241
+ const float oversharding_factor =
242
+ num_worker_threads <= 4 ? 8.0 :
243
+ num_worker_threads <= 8 ? 4.0 :
244
+ num_worker_threads <= 16 ? 2.0 :
245
+ num_worker_threads <= 32 ? 1.0 :
246
+ num_worker_threads <= 64 ? 0.8 : /* num_worker_threads > 64 */ 0.6;
247
+
248
+ const bool parallelize_by_sharding_dim_only =
249
+ sharding_dim_tasks >= oversharding_factor * num_worker_threads;
250
+
251
+ // Last by not least, decide whether we want to issue both lhs and rhs
252
+ // packing in parallel; or issue lhs packing first, and then issue rhs
253
+ // packing when lhs packing completes (for !shard_by_col lhs and rhs are
254
+ // swapped). Parallel packing allows more parallelism (for both packing and
255
+ // kernels), while sequential packing provides better locality (once
256
+ // a thread finishes rhs packing it proceed to kernels with that rhs).
257
+ // First, we are interested in parallel packing if there are few tasks.
258
+ bool parallel_pack = num_threads >= nm * nn;
259
+ // Also do parallel packing if all data fits into L2$.
260
+ if (m * bk * Index(sizeof(LhsScalar)) + n * bk * Index(sizeof(RhsScalar)) <=
261
+ l2CacheSize() * num_threads)
262
+ parallel_pack = true;
263
+ // But don't do it if we will use each rhs only once. Locality seems to be
264
+ // more important in this case.
265
+ if ((shard_by_col ? nm : nn) == 1) parallel_pack = false;
266
+ // Also don't get in the way of parallelize_by_sharding_dim_only
267
+ // optimization.
268
+ if (parallelize_by_sharding_dim_only) parallel_pack = false;
269
+
270
+ // TODO(ezhulnev): With if contexpr we don't need SyncEvalParallelContext.
271
+ if (IsEvalInSyncMode) {
272
+ #define CONTEXT_ARGS \
273
+ (this, num_threads, buffer, m, n, k, bm, bn, bk, nm, nn, nk, gm, gn, nm0, \
274
+ nn0, shard_by_col, parallel_pack, parallelize_by_sharding_dim_only, \
275
+ NoCallback()) \
276
+ .run()
277
+ TENSOR_CONTRACTION_DISPATCH(SyncEvalParallelContext, Alignment,
278
+ CONTEXT_ARGS);
279
+ #undef CONTEXT_ARGS
280
+
281
+ } else {
282
+ #define CONTEXT_ARGS \
283
+ (this, num_threads, buffer, m, n, k, bm, bn, bk, nm, nn, nk, gm, gn, nm0, \
284
+ nn0, shard_by_col, parallel_pack, parallelize_by_sharding_dim_only, \
285
+ std::move(done))
286
+ TENSOR_CONTRACTION_ASYNC_DISPATCH(EvalParallelContext, DoneCallback,
287
+ Alignment, CONTEXT_ARGS, run());
288
+ #undef CONTEXT_ARGS
289
+ }
290
+ }
291
+
292
+ // ------------------------------------------------------------------------ //
293
+
294
+ // Dummy struct to represent an empty DoneCallback.
295
+
296
+ struct NoCallback {
297
+ void operator()() {
298
+ eigen_assert(false && "NoCallback should never be called");
299
+ }
300
+ };
301
+
302
+ // ------------------------------------------------------------------------ //
303
+
304
+ template <typename DoneCallback, typename Context>
305
+ class EvalParallelNotification;
306
+
307
+ // Synchronous evaluation notification that blocks caller thread in Wait().
308
+ template <typename Context>
309
+ class EvalParallelNotification<NoCallback, Context> {
310
+ public:
311
+ EvalParallelNotification(Context*, NoCallback) {}
312
+ void Notify() { done_.Notify(); }
313
+ void Wait() { done_.Wait(); }
314
+ private:
315
+ Eigen::Notification done_;
316
+ };
317
+
318
+ // Asynchronous evaluation notification that does not block in Wait().
319
+ template <typename DoneCallback, typename Context>
320
+ class EvalParallelNotification {
321
+ public:
322
+ EvalParallelNotification(Context* ctx, DoneCallback done)
323
+ : ctx_(ctx), done_(std::move(done)) {}
324
+
325
+ void Notify() {
326
+ // Make a copy of done callback, because it will be destructed when we
327
+ // will delete context in the next line (EvalParallelNotification is a
328
+ // data member of EvalParallelContext class).
329
+ DoneCallback done_copy = std::move(done_);
330
+
331
+ // Delete parallel evaluation context.
332
+ delete ctx_;
333
+
334
+ // Now safely call the done callback.
335
+ done_copy();
336
+ }
337
+
338
+ void Wait() {}
339
+
340
+ private:
341
+ Context* ctx_;
342
+ DoneCallback done_;
343
+ };
344
+
345
+ // Context orchestrates sync/async parallel contraction evaluation. When it is
346
+ // executed in asynchronous mode, it owns all the shared state that might be
347
+ // accessible by block packing and kernel tasks.
348
+
349
+ template <typename DoneCallback, bool lhs_inner_dim_contiguous,
350
+ bool rhs_inner_dim_contiguous, bool rhs_inner_dim_reordered,
351
+ int Alignment>
352
+ class EvalParallelContext {
353
+ public:
354
+ typedef internal::TensorContractionInputMapper<
355
+ LhsScalar, Index, internal::Lhs, LeftEvaluator, left_nocontract_t,
356
+ contract_t, internal::packet_traits<LhsScalar>::size,
357
+ lhs_inner_dim_contiguous, false, Unaligned>
358
+ LhsMapper;
359
+ typedef internal::TensorContractionInputMapper<
360
+ RhsScalar, Index, internal::Rhs, RightEvaluator, right_nocontract_t,
361
+ contract_t, internal::packet_traits<RhsScalar>::size,
362
+ rhs_inner_dim_contiguous, rhs_inner_dim_reordered, Unaligned>
363
+ RhsMapper;
364
+
365
+ typedef internal::blas_data_mapper<Scalar, Index, ColMajor> OutputMapper;
366
+
367
+ typedef internal::TensorContractionKernel<
368
+ Scalar, LhsScalar, RhsScalar, Index, OutputMapper, LhsMapper, RhsMapper>
369
+ TensorContractionKernel;
370
+
371
+ typedef typename TensorContractionKernel::LhsBlock LhsBlock;
372
+ typedef typename TensorContractionKernel::RhsBlock RhsBlock;
373
+ typedef typename TensorContractionKernel::BlockMemHandle BlockMemHandle;
374
+
375
+ EvalParallelContext(const Self* self, int num_threads, Scalar* buffer,
376
+ Index tm, Index tn, Index tk, Index bm, Index bn,
377
+ Index bk, Index nm, Index nn, Index nk, Index gm,
378
+ Index gn, Index nm0, Index nn0, bool shard_by_col,
379
+ bool parallel_pack,
380
+ bool parallelize_by_sharding_dim_only,
381
+ DoneCallback done)
382
+ : created_by_thread_id_(std::this_thread::get_id()),
383
+ done_(this, std::move(done)),
384
+ device_(self->m_device),
385
+ lhs_(self->m_leftImpl, self->m_left_nocontract_strides,
386
+ self->m_i_strides, self->m_left_contracting_strides,
387
+ self->m_k_strides),
388
+ rhs_(self->m_rightImpl, self->m_right_nocontract_strides,
389
+ self->m_j_strides, self->m_right_contracting_strides,
390
+ self->m_k_strides),
391
+ buffer_(buffer),
392
+ output_(buffer, tm),
393
+ output_kernel_(self->m_output_kernel),
394
+ tensor_contraction_params_(self->m_tensor_contraction_params),
395
+ num_threads_(num_threads),
396
+ shard_by_col_(shard_by_col),
397
+ parallel_pack_(parallel_pack),
398
+ parallelize_by_sharding_dim_only_(parallelize_by_sharding_dim_only),
399
+ m_(tm),
400
+ n_(tn),
401
+ k_(tk),
402
+ bm_(bm),
403
+ bn_(bn),
404
+ bk_(bk),
405
+ nm_(nm),
406
+ nn_(nn),
407
+ nk_(nk),
408
+ gm_(gm),
409
+ gn_(gn),
410
+ nm0_(nm0),
411
+ nn0_(nn0),
412
+ kernel_(m_, k_, n_, bm_, bk_, bn_),
413
+ num_thread_local_allocations_(0),
414
+ // We reserve 2X more capacity for a thread local values, than the
415
+ // number of threads in the pool to efficiently handle task stealing
416
+ // by threads that are not managed by the pool.
417
+ thread_local_capacity(2 * (parallelize_by_sharding_dim_only_
418
+ ? device_.numThreadsInPool()
419
+ : 0)),
420
+ // We will use only one of the Lhs/Rhs thread local storage depending
421
+ // on the shard_by_col value and we parallelize by sharding dim ONLY.
422
+ lhs_thread_local_blocks_(shard_by_col_ ? 0 : thread_local_capacity,
423
+ {*this}, {*this}),
424
+ rhs_thread_local_blocks_(shard_by_col_ ? thread_local_capacity : 0,
425
+ {*this}, {*this}) {
426
+ // These two options are mutually exclusive.
427
+ eigen_assert(!(parallel_pack && parallelize_by_sharding_dim_only));
428
+
429
+ for (Index x = 0; x < P; x++) {
430
+ // Normal number of notifications for k slice switch is
431
+ // nm_ + nn_ + nm_ * nn_. However, first P - 1 slices will receive only
432
+ // nm_ + nn_ notifications, because they will not receive notifications
433
+ // from preceding kernels.
434
+ state_switch_[x] =
435
+ x == 0
436
+ ? 1
437
+ : (parallel_pack_ ? nn_ + nm_ : (shard_by_col_ ? nn_ : nm_)) +
438
+ (x == P - 1 ? nm_ * nn_ : 0);
439
+ state_packing_ready_[x] =
440
+ parallel_pack_ ? 0 : (shard_by_col_ ? nm_ : nn_);
441
+ state_kernel_[x] = new std::atomic<uint8_t>*[nm_];
442
+ for (Index m = 0; m < nm_; m++) {
443
+ state_kernel_[x][m] = new std::atomic<uint8_t>[nn_];
444
+ // Kernels generally receive 3 notifications (previous kernel + 2
445
+ // packing), but the first slice won't get notifications from previous
446
+ // kernels.
447
+ for (Index n = 0; n < nn_; n++)
448
+ state_kernel_[x][m][n].store(
449
+ (x == 0 ? 0 : 1) + (parallel_pack_ ? 2 : 1),
450
+ std::memory_order_relaxed);
451
+ }
452
+ }
453
+
454
+ // Allocate memory for packed rhs/lhs matrices.
455
+ packed_mem_ = kernel_.allocateSlices( //
456
+ device_, //
457
+ /*num_lhs=*/nm0_, //
458
+ /*num_rhs=*/nn0_, //
459
+ /*num_slices=*/std::min<Index>(nk_, P - 1), //
460
+ packed_lhs_, packed_rhs_);
461
+
462
+ if (parallelize_by_sharding_dim_only_) {
463
+ const int num_worker_threads = device_.numThreadsInPool();
464
+
465
+ if (shard_by_col) {
466
+ can_use_thread_local_packed_ = new std::atomic<bool>[nn_];
467
+ for (int i = 0; i < nn_; ++i)
468
+ can_use_thread_local_packed_[i].store(true,
469
+ std::memory_order_relaxed);
470
+
471
+ Index num_blocks = num_worker_threads * gn_;
472
+ thread_local_pre_alocated_mem_ = kernel_.allocateSlices( //
473
+ device_, //
474
+ /*num_lhs=*/0, //
475
+ /*num_rhs=*/num_blocks, //
476
+ /*num_slices=*/1, //
477
+ /*lhs_blocks=*/nullptr, &rhs_thread_local_pre_allocated_);
478
+
479
+ } else {
480
+ can_use_thread_local_packed_ = new std::atomic<bool>[nm_];
481
+ for (int i = 0; i < nm_; ++i)
482
+ can_use_thread_local_packed_[i].store(true,
483
+ std::memory_order_relaxed);
484
+
485
+ Index num_blocks = num_worker_threads * gm_;
486
+ thread_local_pre_alocated_mem_ = kernel_.allocateSlices( //
487
+ device_, //
488
+ /*num_lhs=*/num_blocks, //
489
+ /*num_rhs=*/0, //
490
+ /*num_slices=*/1, &lhs_thread_local_pre_allocated_, //
491
+ /*rhs_blocks=*/nullptr);
492
+ }
493
+ }
494
+ }
495
+
496
+ ~EvalParallelContext() {
497
+ for (Index x = 0; x < P; x++) {
498
+ for (Index m = 0; m < nm_; m++) delete[] state_kernel_[x][m];
499
+ delete[] state_kernel_[x];
500
+ }
501
+ kernel_.deallocate(device_, packed_mem_);
502
+ if (parallelize_by_sharding_dim_only_) {
503
+ kernel_.deallocate(device_, thread_local_pre_alocated_mem_);
504
+ delete[] can_use_thread_local_packed_;
505
+ }
506
+ }
507
+
508
+ void run() {
509
+ // Kick off packing of the first slice.
510
+ signal_switch(0, 1);
511
+
512
+ // Wait for overall completion.
513
+ //
514
+ // If parallel evaluation is executed in async mode, this is a no-op, and
515
+ // Wait() will return immediately. In synchronous mode it will block the
516
+ // caller thread until it will receive notification from last task.
517
+ //
518
+ // In async mode, last task when completed will call done callback from
519
+ // the same thread, and will delete this context.
520
+ //
521
+ // TODO(dvyukov): This wait can lead to deadlock if contraction is
522
+ // evaluated in synchronous mode. If nthreads contractions are
523
+ // concurrently submitted from worker threads, this wait will block all
524
+ // worker threads and the system will deadlock.
525
+ done_.Wait();
526
+ }
527
+
528
+ private:
529
+ std::thread::id created_by_thread_id_;
530
+
531
+ // This notification is specialized on the type of DoneCallback and can be
532
+ // blocking or non-blocking.
533
+ EvalParallelNotification<DoneCallback, EvalParallelContext> done_;
534
+
535
+ const Device& device_;
536
+ LhsMapper lhs_;
537
+ RhsMapper rhs_;
538
+ Scalar* const buffer_;
539
+ OutputMapper output_;
540
+ OutputKernelType output_kernel_;
541
+ TensorContractionParams tensor_contraction_params_;
542
+ const int num_threads_;
543
+ const bool shard_by_col_;
544
+ const bool parallel_pack_;
545
+ const bool parallelize_by_sharding_dim_only_;
546
+ // Matrix sizes.
547
+ const Index m_;
548
+ const Index n_;
549
+ const Index k_;
550
+ // Block sizes.
551
+ const Index bm_;
552
+ const Index bn_;
553
+ const Index bk_;
554
+ // Number of tasks.
555
+ const Index nm_;
556
+ const Index nn_;
557
+ const Index nk_;
558
+ // Task grain sizes (number of kernels executed per task).
559
+ const Index gm_;
560
+ const Index gn_;
561
+ // Number of blocks (this is different from ni_/nn_ because of task size
562
+ // coarsening).
563
+ const Index nm0_;
564
+ const Index nn0_;
565
+ // Tensor contraction kernel.
566
+ TensorContractionKernel kernel_;
567
+
568
+ // Parallelization strategy.
569
+ //
570
+ // Blocks related to the same k block can run in parallel because they write
571
+ // to different output blocks. So we parallelize within k slices, this
572
+ // gives us parallelism level of m x n. Before we can start any kernels
573
+ // related to k-th slice, we need to issue m lhs packing tasks and n rhs
574
+ // packing tasks.
575
+ //
576
+ // However, there is a bottleneck when we are finishing kernels for k-th
577
+ // slice (at the very end there is only 1 runnable kernel). To mitigate this
578
+ // bottleneck we allow kernels from k-th and k+1-th slices to run in
579
+ // parallel. Note that (m, n, k) and (m, n, k+1) kernels write to the same
580
+ // output block, so they must not run in parallel.
581
+ //
582
+ // This gives us the following dependency graph.
583
+ // On each k slice we have m x n kernel tasks, m lhs paking tasks and n rhs
584
+ // packing tasks.
585
+ // Kernel (m, n, k) can start when:
586
+ // - kernel (m, n, k-1) has finished
587
+ // - lhs packing (m, k) has finished
588
+ // - rhs packing (n, k) has finished
589
+ // Lhs/rhs packing can start when:
590
+ // - all k-1 packing has finished (artificially imposed to limit amount of
591
+ // parallel packing)
592
+ //
593
+ // On top of that we limit runnable tasks to two consecutive k slices.
594
+ // This is done to limit amount of memory we need for packed lhs/rhs
595
+ // (for each k slice we need m*bk + n*bk memory in packed_lhs_/packed_rhs_).
596
+ //
597
+ // state_switch_ tracks when we are ready to switch to the next k slice.
598
+ // state_kernel_[m][n] tracks when we are ready to kick off kernel (m, n).
599
+ // These variable are rolling over 3 consecutive k slices: first two we are
600
+ // actively executing + one to track completion of kernels in the second
601
+ // slice.
602
+ static constexpr Index P = 3;
603
+
604
+ // Handle to the allocated temporary storage for Lhs/Rhs blocks.
605
+ BlockMemHandle packed_mem_;
606
+ std::vector<LhsBlock> packed_lhs_[P - 1];
607
+ std::vector<RhsBlock> packed_rhs_[P - 1];
608
+
609
+ // If we choose to parallelize only by the sharding dimension, each thread
610
+ // will have it's own "thead local" (not a c++ thread local storage) memory
611
+ // for packed_lhs or packed_rhs (shard_by_col = false of true). This memory
612
+ // can't be passed to a kernel that might execute on a different thread.
613
+ //
614
+ // In practice when we are ready to pack memory for the sharding dimension
615
+ // (rhs if shard_by_col==true) of the K-th slice, all kernels for K-1 slice
616
+ // already computed (99% of the time), and we can pack data into the thread
617
+ // local storage, and guarantee that all the kernels will be executed
618
+ // immediately in the same thread. This significantly increases L1 cache hit
619
+ // ratio and reduces pressure on the memory bus.
620
+ //
621
+ // It's still possible that kernel for the K-th slice will be ready before
622
+ // completion of the K-1 kernel, so we have to allocate "global" packed_lhs_
623
+ // and packed_rhs_ to allow kernels to be executed later on a thread
624
+ // different from the thread that was used for packing.
625
+
626
+ // Handle for pre-allocated thread local memory buffers.
627
+ BlockMemHandle thread_local_pre_alocated_mem_;
628
+
629
+ // Only one of these will be initialized depending on shard_by_col value
630
+ // (the size will be `num_worker_threads * num_grains_in_the_sharding_dim`).
631
+ std::vector<LhsBlock> lhs_thread_local_pre_allocated_;
632
+ std::vector<RhsBlock> rhs_thread_local_pre_allocated_;
633
+
634
+ // How many thread local blocks were already allocated.
635
+ std::atomic<int> num_thread_local_allocations_;
636
+ const int thread_local_capacity;
637
+
638
+ // We will use pre-allocated Lhs/Rhs blocks defined above, if the number of
639
+ // unique threads in a system is below or equal to the number of threads in
640
+ // a thread pool. We will fallback on dynamic memory allocation after that.
641
+
642
+ // ThreadLocalBlocks is a container for Lhs or Rhs thread local buffers. Its
643
+ // size is equal to the grain size in Lhs/Rhs sharding dimension.
644
+ template <typename BlockType>
645
+ class ThreadLocalBlocks {
646
+ public:
647
+ ThreadLocalBlocks() = default;
648
+
649
+ ThreadLocalBlocks(BlockType* base, size_t grain_size)
650
+ : is_pre_allocated_(true),
651
+ thread_local_pre_allocated_base_(base),
652
+ grain_size_(grain_size) {}
653
+
654
+ ThreadLocalBlocks(BlockMemHandle mem_handle,
655
+ std::vector<BlockType> blocks)
656
+ : is_pre_allocated_(false),
657
+ mem_handle_(std::move(mem_handle)),
658
+ blocks_(std::move(blocks)) {}
659
+
660
+ BlockType& block(int grain_index) {
661
+ eigen_assert(grain_index >= 0);
662
+ eigen_assert(static_cast<size_t>(grain_index) < size());
663
+ return is_pre_allocated_ ? thread_local_pre_allocated_base_[grain_index]
664
+ : blocks_[grain_index];
665
+ }
666
+
667
+ void Release(EvalParallelContext& ctx) const {
668
+ if (!is_pre_allocated_) {
669
+ ctx.kernel_.deallocate(ctx.device_, mem_handle_);
670
+ }
671
+ }
672
+
673
+ size_t size() const {
674
+ return is_pre_allocated_ ? grain_size_ : blocks_.size();
675
+ }
676
+
677
+ private:
678
+ bool is_pre_allocated_;
679
+
680
+ // Reuse pre-allocated thread local buffers.
681
+ BlockType* thread_local_pre_allocated_base_ = nullptr;
682
+ size_t grain_size_ = 0;
683
+
684
+ // These will be initialized only if `is_pre_allocated == false`.
685
+ BlockMemHandle mem_handle_{};
686
+ std::vector<BlockType> blocks_;
687
+ };
688
+
689
+ // ThreadLocalBlocksInitialize callable does custom thread local blocks
690
+ // initialization, and will reuse pre-allocated buffers if possible, or will
691
+ // dynamically allocate new memory.
692
+ //
693
+ // Lhs/Rhs blocks might be of the same type, so we have to pass explicitly
694
+ // for what side do we plan to do block allocation.
695
+ template <typename BlockType, bool is_rhs>
696
+ class ThreadLocalBlocksInitialize {
697
+ static constexpr bool kIsLhs =
698
+ !is_rhs && std::is_same<BlockType, LhsBlock>::value;
699
+ static const bool kIsRhs =
700
+ is_rhs && std::is_same<BlockType, RhsBlock>::value;
701
+ static_assert(kIsLhs || kIsRhs, "Unknown block type");
702
+
703
+ using Blocks = ThreadLocalBlocks<BlockType>;
704
+
705
+ public:
706
+ ThreadLocalBlocksInitialize(EvalParallelContext& ctx)
707
+ : ctx_(ctx),
708
+ num_worker_threads_(ctx_.device_.numThreadsInPool()) {}
709
+
710
+ void operator()(Blocks& blocks) {
711
+ const int n = ctx_.num_thread_local_allocations_.fetch_add(
712
+ 1, std::memory_order_relaxed);
713
+
714
+ if (n >= num_worker_threads_) {
715
+ ThreadLocalBlocksAllocator<is_rhs>::allocate(ctx_, blocks);
716
+ } else {
717
+ ThreadLocalBlocksAllocator<is_rhs>::reuse(ctx_, n, blocks);
718
+ }
719
+ }
720
+
721
+ private:
722
+ // NOTE(ezhulenev): Without 'if constexpr' we have to put calls to
723
+ // TensorContractionKernel::allocateSlices into template specializations.
724
+ // Also explicit specializations are not allowed at class scope in C++03,
725
+ // EvalCtx type parameter is just a workaround for that limitation.
726
+ template <bool pack_rhs, typename EvalCtx = EvalParallelContext>
727
+ struct ThreadLocalBlocksAllocator;
728
+
729
+ template <typename EvalCtx>
730
+ struct ThreadLocalBlocksAllocator</*pack_rhs=*/true, EvalCtx> {
731
+ static void allocate(EvalCtx& ctx, Blocks& blocks) {
732
+ std::vector<RhsBlock> rhs_blocks;
733
+ BlockMemHandle mem_handle = ctx.kernel_.allocateSlices(
734
+ ctx.device_,
735
+ /*num_lhs=*/0,
736
+ /*num_rhs=*/ctx.gn_,
737
+ /*num_slices=*/1,
738
+ /*lhs_blocks=*/nullptr, /*rhs_blocks=*/&rhs_blocks);
739
+
740
+ blocks = ThreadLocalBlocks<RhsBlock>(std::move(mem_handle),
741
+ std::move(rhs_blocks));
742
+ }
743
+
744
+ static void reuse(EvalCtx& ctx, int index, Blocks& blocks) {
745
+ RhsBlock* ptr = &ctx.rhs_thread_local_pre_allocated_[ctx.gn_ * index];
746
+ blocks = ThreadLocalBlocks<RhsBlock>(ptr, ctx.gn_);
747
+ }
748
+ };
749
+
750
+ template <typename EvalCtx>
751
+ struct ThreadLocalBlocksAllocator</*pack_rhs=*/false, EvalCtx> {
752
+ static void allocate(EvalCtx& ctx, Blocks& blocks) {
753
+ std::vector<LhsBlock> lhs_blocks;
754
+ BlockMemHandle mem_handle = ctx.kernel_.allocateSlices(
755
+ ctx.device_,
756
+ /*num_lhs=*/ctx.gm_,
757
+ /*num_rhs=*/0,
758
+ /*num_slices=*/1,
759
+ /*lhs_blocks=*/&lhs_blocks, /*rhs_blocks=*/nullptr);
760
+
761
+ blocks = ThreadLocalBlocks<LhsBlock>(std::move(mem_handle),
762
+ std::move(lhs_blocks));
763
+ }
764
+
765
+ static void reuse(EvalCtx& ctx, int index, Blocks& blocks) {
766
+ LhsBlock* ptr = &ctx.lhs_thread_local_pre_allocated_[ctx.gm_ * index];
767
+ blocks = ThreadLocalBlocks<LhsBlock>(ptr, ctx.gm_);
768
+ }
769
+ };
770
+
771
+ EvalParallelContext& ctx_;
772
+ const int num_worker_threads_;
773
+ };
774
+
775
+ template <typename BlockType>
776
+ class ThreadLocalBlocksRelease {
777
+ public:
778
+ using Blocks = ThreadLocalBlocks<BlockType>;
779
+ ThreadLocalBlocksRelease(EvalParallelContext& ctx) : ctx_(ctx) {}
780
+ void operator()(Blocks& blocks) { blocks.Release(ctx_); }
781
+
782
+ private:
783
+ EvalParallelContext& ctx_;
784
+ };
785
+
786
+ // ThreadLocalBlocks initialization callables.
787
+ using ThreadLocalLhsInit =
788
+ ThreadLocalBlocksInitialize<LhsBlock, /*is_rhs=*/false>;
789
+ using ThreadLocalRhsInit =
790
+ ThreadLocalBlocksInitialize<RhsBlock, /*is_rhs=*/true>;
791
+
792
+ // ThreadLocalBlocks release callables.
793
+ using ThreadLocalLhsRelease = ThreadLocalBlocksRelease<LhsBlock>;
794
+ using ThreadLocalRhsRelease = ThreadLocalBlocksRelease<RhsBlock>;
795
+
796
+ // Thread local containers for Lhs/Rhs block packs. In practice only one of
797
+ // them will be used, depending on the shard_by_col value.
798
+ Eigen::ThreadLocal<ThreadLocalBlocks<LhsBlock>, ThreadLocalLhsInit,
799
+ ThreadLocalLhsRelease>
800
+ lhs_thread_local_blocks_;
801
+ Eigen::ThreadLocal<ThreadLocalBlocks<RhsBlock>, ThreadLocalRhsInit,
802
+ ThreadLocalRhsRelease>
803
+ rhs_thread_local_blocks_;
804
+
805
+ // After a particular shard for Kth slice missed thread local execution
806
+ // opportunity (K-1 slice didn't complete kernels execution), we can no
807
+ // longer schedule K+1 and following slices in thread local mode, because
808
+ // there is no more guarantee that previous kernels were executed
809
+ // sequentially in the same thread (size is nn_ or nm_).
810
+ std::atomic<bool>* can_use_thread_local_packed_;
811
+
812
+ std::atomic<uint8_t>** state_kernel_[P];
813
+ // state_switch_ is frequently modified by worker threads, while other
814
+ // fields are read-only after constructor. Let's move it to a separate cache
815
+ // line to reduce cache-coherency traffic.
816
+ char pad_[128];
817
+ std::atomic<Index> state_packing_ready_[P];
818
+ std::atomic<Index> state_switch_[P];
819
+
820
+ LhsBlock& packed_lhs(Index m, Index k, Index m1, bool use_thread_local) {
821
+ if (use_thread_local) {
822
+ eigen_assert(!shard_by_col_);
823
+ ThreadLocalBlocks<LhsBlock>& blocks = lhs_thread_local_blocks_.local();
824
+
825
+ Index grain_index = m1 - m * gm_;
826
+ return blocks.block(internal::convert_index<int>(grain_index)); // FIXME better make ThreadLocalBlocks use Eigen::Index?
827
+ } else {
828
+ return packed_lhs_[k % (P - 1)][m1];
829
+ }
830
+ }
831
+
832
+ RhsBlock& packed_rhs(Index n, Index k, Index n1, bool use_thread_local) {
833
+ if (use_thread_local) {
834
+ eigen_assert(shard_by_col_);
835
+ ThreadLocalBlocks<RhsBlock>& blocks = rhs_thread_local_blocks_.local();
836
+
837
+ Index grain_index = n1 - n * gn_;
838
+ return blocks.block(internal::convert_index<int>(grain_index)); // FIXME better make ThreadLocalBlocks use Eigen::Index?
839
+ } else {
840
+ return packed_rhs_[k % (P - 1)][n1];
841
+ }
842
+ }
843
+
844
+ // In following two methods (pack_lhs and pack_rhs), if we know for sure
845
+ // that we'll be able to immediately call a kernel with packed data, and do
846
+ // not submit it to the thread pool, we can use thread local memory for
847
+ // packed data.
848
+ //
849
+ // We can only reliably check it if we are running all kernels in sync mode
850
+ // (parallelize only by sharding dim). If kernel for m==0 (n==0) is ready to
851
+ // run, it's guaranteed that all kernels with larger values of m (n) are
852
+ // also ready, because we execute them in the same order for all K slices.
853
+
854
+ void pack_lhs(Index m, Index k) {
855
+ bool use_thread_local = false;
856
+
857
+ if (parallelize_by_sharding_dim_only_ && !shard_by_col_ &&
858
+ can_use_thread_local_packed_[m].load(std::memory_order_relaxed)) {
859
+ if (state_kernel_[k % P][m][0].load(std::memory_order_relaxed) == 1) {
860
+ use_thread_local = true;
861
+ } else {
862
+ // If we can't guarantee that all kernels in `k` slice will be
863
+ // executed sequentially in current thread, it's no longer safe to use
864
+ // thread local memory in following slices along the k dimensions.
865
+ eigen_assert(k > 0);
866
+ can_use_thread_local_packed_[m].store(false,
867
+ std::memory_order_relaxed);
868
+ }
869
+ }
870
+
871
+ const Index mend = m * gm_ + gm(m);
872
+ for (Index m1 = m * gm_; m1 < mend; m1++)
873
+ kernel_.packLhs(&packed_lhs(m, k, m1, use_thread_local),
874
+ lhs_.getSubMapper(m1 * bm_, k * bk_), bk(k), bm(m1));
875
+
876
+ if (!parallel_pack_ && shard_by_col_) {
877
+ eigen_assert(!use_thread_local);
878
+ signal_packing(k);
879
+ } else {
880
+ signal_switch(k + 1);
881
+ for (Index n = nn_ - 1; n >= 0; n--) {
882
+ bool sync = parallelize_by_sharding_dim_only_ || n == 0;
883
+ signal_kernel(m, n, k, sync, use_thread_local);
884
+ }
885
+ }
886
+ }
887
+
888
+ void pack_rhs(Index n, Index k) {
889
+ bool use_thread_local = false;
890
+
891
+ if (parallelize_by_sharding_dim_only_ && shard_by_col_ &&
892
+ can_use_thread_local_packed_[n].load(std::memory_order_relaxed)) {
893
+ if (state_kernel_[k % P][0][n].load(std::memory_order_relaxed) == 1) {
894
+ use_thread_local = true;
895
+ } else {
896
+ // If we can't guarantee that all kernels in `k` slice will be
897
+ // executed sequentially in current thread, it's no longer safe to use
898
+ // thread local memory in following slices along the k dimensions.
899
+ eigen_assert(k > 0);
900
+ can_use_thread_local_packed_[n].store(false,
901
+ std::memory_order_relaxed);
902
+ }
903
+ }
904
+
905
+ const Index nend = n * gn_ + gn(n);
906
+ for (Index n1 = n * gn_; n1 < nend; n1++) {
907
+ if (!TensorContractionKernel::HasBeta && k == 0) {
908
+ // Zero the output memory in parallel, only if contraction kernel does
909
+ // not support `beta`. Otherwise we will pass beta 0.0 to the first
910
+ // call to the `TensorContractionKernel::invoke()`.
911
+ //
912
+ // On 10000x2x10000 mm zeroing can easily take half of time. Zero (bn
913
+ // x m) row. Safe to do here because all kernels that will write to
914
+ // this memory depend on completion of this task. Note: don't call
915
+ // device_.fill() here. device_.fill() blocks on thread pool
916
+ // worker thread, which can lead to underutilization and deadlocks.
917
+ std::fill_n(buffer_ + n1 * bn_ * m_, bn(n1) * m_, Scalar(0));
918
+ }
919
+ kernel_.packRhs(&packed_rhs(n, k, n1, use_thread_local),
920
+ rhs_.getSubMapper(k * bk_, n1 * bn_), bk(k), bn(n1));
921
+ }
922
+
923
+ if (parallel_pack_ || shard_by_col_) {
924
+ signal_switch(k + 1);
925
+ for (Index m = nm_ - 1; m >= 0; m--) {
926
+ bool sync = parallelize_by_sharding_dim_only_ || m == 0;
927
+ signal_kernel(m, n, k, sync, use_thread_local);
928
+ }
929
+ } else {
930
+ eigen_assert(!use_thread_local);
931
+ signal_packing(k);
932
+ }
933
+ }
934
+
935
+ void kernel(Index m, Index n, Index k, bool use_thread_local) {
936
+ // Note: order of iteration matters here. Iteration over m is innermost
937
+ // because we want to reuse the same packed rhs in consecutive tasks
938
+ // (rhs fits into L2$ while lhs only into L3$).
939
+ const Index nend = n * gn_ + gn(n);
940
+ const Index mend = m * gm_ + gm(m);
941
+
942
+ // NOTE: output = alpha * LHS * RHS + beta * output.
943
+ const Scalar alpha = Scalar(1);
944
+ const Scalar beta =
945
+ (TensorContractionKernel::HasBeta && k == 0) ? Scalar(0) : Scalar(1);
946
+
947
+ if (shard_by_col_) {
948
+ for (Index n1 = n * gn_; n1 < nend; n1++) {
949
+ for (Index m1 = m * gm_; m1 < mend; m1++) {
950
+ const auto output_mapper = output_.getSubMapper(m1 * bm_, n1 * bn_);
951
+ kernel_.invoke(
952
+ output_mapper,
953
+ packed_lhs(m, k, m1, !shard_by_col_ && use_thread_local),
954
+ packed_rhs(n, k, n1, shard_by_col_ && use_thread_local), bm(m1),
955
+ bk(k), bn(n1), alpha, beta);
956
+
957
+ // We are done with the last task for the [m1, n1] block.
958
+ if (k + 1 == nk_) {
959
+ output_kernel_(output_mapper, tensor_contraction_params_,
960
+ m1 * bm_, n1 * bn_, bm(m1), bn(n1));
961
+ }
962
+ }
963
+ }
964
+ } else {
965
+ for (Index m1 = m * gm_; m1 < mend; m1++)
966
+ for (Index n1 = n * gn_; n1 < nend; n1++) {
967
+ const auto output_mapper = output_.getSubMapper(m1 * bm_, n1 * bn_);
968
+ kernel_.invoke(
969
+ output_mapper,
970
+ packed_lhs(m, k, m1, !shard_by_col_ && use_thread_local),
971
+ packed_rhs(n, k, n1, shard_by_col_ && use_thread_local), bm(m1),
972
+ bk(k), bn(n1), alpha, beta);
973
+
974
+ // We are done with the last task for the [m1, n1] block.
975
+ if (k + 1 == nk_) {
976
+ output_kernel_(output_mapper, tensor_contraction_params_,
977
+ m1 * bm_, n1 * bn_, bm(m1), bn(n1));
978
+ }
979
+ }
980
+ }
981
+ signal_kernel(m, n, k + 1, /*sync=*/false, /*use_thread_local=*/false);
982
+ signal_switch(k + 2);
983
+ }
984
+
985
+ void signal_packing(Index k) {
986
+ eigen_assert(!parallel_pack_);
987
+ Index s = state_packing_ready_[k % P].fetch_sub(1);
988
+ eigen_assert(s > 0);
989
+ if (s != 1) return;
990
+ state_packing_ready_[k % P] = shard_by_col_ ? nm_ : nn_;
991
+ enqueue_packing(k, shard_by_col_);
992
+ }
993
+
994
+ void signal_kernel(Index m, Index n, Index k, bool sync,
995
+ bool use_thread_local) {
996
+ std::atomic<uint8_t>* state = &state_kernel_[k % P][m][n];
997
+ Index s = state->load();
998
+ eigen_assert(s > 0);
999
+ if (s != 1 && state->fetch_sub(1) != 1) {
1000
+ eigen_assert(!use_thread_local);
1001
+ return;
1002
+ }
1003
+ state->store(parallel_pack_ ? 3 : 2, std::memory_order_relaxed);
1004
+ if (sync) {
1005
+ kernel(m, n, k, use_thread_local);
1006
+ } else {
1007
+ eigen_assert(!use_thread_local);
1008
+ device_.enqueueNoNotification(
1009
+ [=]() { kernel(m, n, k, use_thread_local); });
1010
+ }
1011
+ }
1012
+
1013
+ void signal_switch(Index k, Index v = 1) {
1014
+ Index s = state_switch_[k % P].fetch_sub(v);
1015
+ eigen_assert(s >= v);
1016
+ if (s != v) return;
1017
+
1018
+ // Ready to switch to the next k slice.
1019
+ // Reset counter for the next iteration.
1020
+ state_switch_[k % P] =
1021
+ (parallel_pack_ ? nm_ + nn_ : (shard_by_col_ ? nn_ : nm_)) +
1022
+ nm_ * nn_;
1023
+ if (k < nk_) {
1024
+ // Issue lhs/rhs packing. Their completion will in turn kick off
1025
+ // kernels.
1026
+ if (parallel_pack_) {
1027
+ enqueue_packing(k, !shard_by_col_);
1028
+ enqueue_packing(k, shard_by_col_);
1029
+ } else if (shard_by_col_) {
1030
+ enqueue_packing(k, false);
1031
+ } else {
1032
+ enqueue_packing(k, true);
1033
+ }
1034
+
1035
+ // Termination handling.
1036
+ // Because kernel completion signals k + 2 switch, we need to finish nk
1037
+ // + 2 slices without issuing any tasks on nk + 1 slice. So here we
1038
+ // pretend that all nk + 1 packing tasks just finish instantly; so that
1039
+ // nk + 2 switch only waits for completion of nk kernels.
1040
+ } else if (k == nk_) {
1041
+ signal_switch(k + 1,
1042
+ parallel_pack_ ? nm_ + nn_ : (shard_by_col_ ? nn_ : nm_));
1043
+ } else {
1044
+ done_.Notify();
1045
+ }
1046
+ }
1047
+
1048
+ // Enqueue all rhs/lhs packing for k-th slice.
1049
+ void enqueue_packing(Index k, bool rhs) {
1050
+ enqueue_packing_helper(0, rhs ? nn_ : nm_, k, rhs);
1051
+ }
1052
+
1053
+ void enqueue_packing_helper(Index start, Index end, Index k, bool rhs) {
1054
+ if (end - start == 1) {
1055
+ if (rhs)
1056
+ pack_rhs(start, k);
1057
+ else
1058
+ pack_lhs(start, k);
1059
+ } else {
1060
+ while (end - start > 1) {
1061
+ Index mid = (start + end) / 2;
1062
+ device_.enqueueNoNotification(
1063
+ [=]() { enqueue_packing_helper(mid, end, k, rhs); });
1064
+ end = mid;
1065
+ }
1066
+
1067
+ // Decide if we want to run first packing task (start == 0) in
1068
+ // async mode if we parallelize only by sharding dim:
1069
+ // (1) pack_lhs and pack_rhs call signal_switch before completing
1070
+ // all calls to signal_kernel, which in sync mode might lead
1071
+ // to the execution of the first kernel of the k+1 slice, before
1072
+ // completing a call to the last kernel of the k slice.
1073
+ // (2) all pack tasks for sharded dim must be executed in a thread
1074
+ // pool to get pre-allocated thead local buffers.
1075
+ bool pack_async =
1076
+ (start == 0) &&
1077
+ (parallelize_by_sharding_dim_only_&& shard_by_col_ == rhs) &&
1078
+ (k > 0 || std::this_thread::get_id() == created_by_thread_id_);
1079
+
1080
+ if (pack_async) {
1081
+ device_.enqueueNoNotification(
1082
+ [=]() { enqueue_packing_helper(start, end, k, rhs); });
1083
+ } else {
1084
+ enqueue_packing_helper(start, end, k, rhs);
1085
+ }
1086
+ }
1087
+ }
1088
+
1089
+ // Block sizes with accounting for potentially incomplete last block.
1090
+ Index bm(Index m) const { return m + 1 < nm0_ ? bm_ : m_ + bm_ - bm_ * nm0_; }
1091
+ Index bn(Index n) const { return n + 1 < nn0_ ? bn_ : n_ + bn_ - bn_ * nn0_; }
1092
+ Index bk(Index k) const { return k + 1 < nk_ ? bk_ : k_ + bk_ - bk_ * nk_; }
1093
+ // Task grain sizes accounting for potentially incomplete last task.
1094
+ Index gm(Index m) const { return m + 1 < nm_ ? gm_ : nm0_ + gm_ - gm_ * nm_; }
1095
+ Index gn(Index n) const { return n + 1 < nn_ ? gn_ : nn0_ + gn_ - gn_ * nn_; }
1096
+
1097
+ EvalParallelContext(const EvalParallelContext&) = delete;
1098
+ void operator=(const EvalParallelContext&) = delete;
1099
+ };
1100
+
1101
+ template <bool lhs_inner_dim_contiguous, bool rhs_inner_dim_contiguous,
1102
+ bool rhs_inner_dim_reordered, int Alignment>
1103
+ using SyncEvalParallelContext =
1104
+ EvalParallelContext<NoCallback, lhs_inner_dim_contiguous,
1105
+ rhs_inner_dim_contiguous, rhs_inner_dim_reordered,
1106
+ Alignment>;
1107
+
1108
+ // ------------------------------------------------------------------------ //
1109
+
1110
+ // EvalShardedByInnerDimContext orchestrates sync/async contraction
1111
+ // evaluation, when we shard by inner dimension. When it is executed in
1112
+ // asynchronous mode, it owns all the shared state that might be accessible by
1113
+ // block processing tasks.
1114
+
1115
+ template <typename DoneCallback>
1116
+ struct EvalShardedByInnerDimContext {
1117
+ EvalShardedByInnerDimContext(const Self* self, int num_threads,
1118
+ Scalar* result_buffer,
1119
+ Index m_size, Index n_size, Index k_size,
1120
+ DoneCallback done_callback)
1121
+ : evaluator(self),
1122
+ m_lhs_inner_dim_contiguous(evaluator->m_lhs_inner_dim_contiguous),
1123
+ m_rhs_inner_dim_contiguous(evaluator->m_rhs_inner_dim_contiguous),
1124
+ m_rhs_inner_dim_reordered(evaluator->m_rhs_inner_dim_reordered),
1125
+ result(result_buffer),
1126
+ m(m_size),
1127
+ n(n_size),
1128
+ k(k_size),
1129
+ done(std::move(done_callback)),
1130
+ buffer_size_bytes(m * n * sizeof(Scalar)),
1131
+ block_size(blockSize(k, num_threads)),
1132
+ num_blocks(divup<Index>(k, block_size)),
1133
+ num_pending_blocks(internal::convert_index<int>(num_blocks)),
1134
+ l0_ranges(divup<Index>(num_blocks, l0_size)),
1135
+ l0_state(l0_ranges),
1136
+ block_buffers(num_blocks) {
1137
+ // Keep count of pending gemm tasks for each l0 range.
1138
+ for (int i = 0; i < l0_ranges; ++i) {
1139
+ const Index num_pending_tasks = actualRangeSize(l0_ranges, l0_size, i);
1140
+ l0_state.emplace_back(internal::convert_index<int>(num_pending_tasks));
1141
+ }
1142
+
1143
+ // Allocate temporary buffers for each block.
1144
+ for (Index block_idx = 0; block_idx < num_blocks; ++block_idx) {
1145
+ Scalar* buf = block_idx == 0
1146
+ ? result
1147
+ : static_cast<Scalar*>(evaluator->m_device.allocate(
1148
+ buffer_size_bytes));
1149
+ block_buffers.emplace_back(buf);
1150
+ }
1151
+ }
1152
+
1153
+ ~EvalShardedByInnerDimContext() {
1154
+ for (Index i = 1; i < num_blocks; ++i) {
1155
+ evaluator->m_device.deallocate(block_buffers[i]);
1156
+ }
1157
+ }
1158
+
1159
+ template <int Alignment>
1160
+ void run() {
1161
+ Barrier barrier(internal::convert_index<int>(num_blocks));
1162
+ eval<Alignment>(barrier, 0, num_blocks);
1163
+ barrier.Wait();
1164
+
1165
+ // Aggregate partial sums from l0 ranges.
1166
+ aggregateL0Blocks<Alignment>();
1167
+
1168
+ // Apply output kernel.
1169
+ applyOutputKernel();
1170
+ }
1171
+
1172
+ template <int Alignment>
1173
+ void runAsync() {
1174
+ evalAsync<Alignment>(0, num_blocks);
1175
+ }
1176
+
1177
+ private:
1178
+ // The underlying GEMM kernel assumes that k is a multiple of
1179
+ // the packet size and subtle breakage occurs if this is violated.
1180
+ static const Index packet_size = internal::packet_traits<RhsScalar>::size;
1181
+
1182
+ const Self* evaluator; // TensorContraction evaluator
1183
+
1184
+ // These fields required fromTENSOR_CONTRACTION_DISPATCH macro.
1185
+ bool m_lhs_inner_dim_contiguous;
1186
+ bool m_rhs_inner_dim_contiguous;
1187
+ bool m_rhs_inner_dim_reordered;
1188
+
1189
+ Scalar* result;
1190
+
1191
+ Index m;
1192
+ Index n;
1193
+ Index k;
1194
+
1195
+ DoneCallback done;
1196
+
1197
+ // ----------------------------------------------------------------------//
1198
+ // Algorithm parameters.
1199
+
1200
+ // We will compute partial results into the buffers of this size.
1201
+ Index buffer_size_bytes;
1202
+
1203
+ Index block_size;
1204
+ Index num_blocks;
1205
+
1206
+ // Keep track of pending tasks when evaluate in async mode.
1207
+ std::atomic<int> num_pending_blocks;
1208
+
1209
+ // We compute partial gemm results in parallel, and to get the final result
1210
+ // we need to add them all together. For the large number of threads (>= 48)
1211
+ // this adds a very expensive sequential step at the end.
1212
+ //
1213
+ // We split the [0, num_blocks) into small ranges, and when a task for the
1214
+ // block finishes its partial gemm computation, it checks if it was the last
1215
+ // gemm in the range, and if so, it will add all blocks of the range.
1216
+ //
1217
+ // After all tasks done, we need to add only these pre-aggregated blocks.
1218
+
1219
+ // For now we use just a single level of ranges to compute pre-aggregated
1220
+ // partial sums, but in general we can use more layers to compute tree
1221
+ // aggregation in parallel and reduce the size of the sequential step.
1222
+ //
1223
+ // TODO(ezhulenev): Add multilevel tree aggregation? Probably will make
1224
+ // sense only if number of threads >= ~128?
1225
+ static const Index l0_size = 4;
1226
+ Index l0_ranges;
1227
+
1228
+ // Keep count of pending gemm tasks for each l0 range.
1229
+ MaxSizeVector<std::atomic<int>> l0_state; // [0, l0_ranges)
1230
+
1231
+ // Buffers allocated for each temporary block computation.
1232
+ MaxSizeVector<Scalar*> block_buffers; // [0, num_blocks)
1233
+
1234
+ template <int Alignment>
1235
+ void processBlock(Index block_idx, Index begin, Index end) {
1236
+ Scalar* buf = block_buffers[block_idx];
1237
+
1238
+ TENSOR_CONTRACTION_DISPATCH(
1239
+ evaluator->template evalGemmPartialWithoutOutputKernel, Alignment,
1240
+ (buf, begin, end,
1241
+ /*num_threads=*/internal::convert_index<int>(num_blocks)));
1242
+
1243
+ // Check if it was the last task in l0 range.
1244
+ const Index l0_index = block_idx / l0_size;
1245
+ const int v = l0_state[l0_index].fetch_sub(1);
1246
+ eigen_assert(v >= 1);
1247
+
1248
+ // If we processed the last block of the range, we can aggregate all
1249
+ // partial results into the first block of the range.
1250
+ if (v == 1) {
1251
+ const Index rng_size = actualRangeSize(l0_ranges, l0_size, l0_index);
1252
+ const Index dst_block_idx = l0_index * l0_size;
1253
+
1254
+ if (rng_size == l0_size) {
1255
+ addAllToBuffer<Alignment>(
1256
+ m * n,
1257
+ /*src_buf0=*/block_buffers[dst_block_idx + 1],
1258
+ /*src_buf1=*/block_buffers[dst_block_idx + 2],
1259
+ /*src_buf2=*/block_buffers[dst_block_idx + 3],
1260
+ /*dst_buf= */ block_buffers[dst_block_idx]);
1261
+ } else {
1262
+ // Aggregate blocks of potentially incomplete last range.
1263
+ for (int i = 1; i < rng_size; ++i) {
1264
+ addToBuffer<Alignment>(m * n,
1265
+ /*src_buf=*/block_buffers[dst_block_idx + i],
1266
+ /*dst_buf=*/block_buffers[dst_block_idx]);
1267
+ }
1268
+ }
1269
+ }
1270
+ }
1271
+
1272
+ // Aggregate partial sums from l0 ranges.
1273
+ template <int Alignment>
1274
+ void aggregateL0Blocks() const {
1275
+ Index l0_index = 1;
1276
+
1277
+ for (; l0_index + 2 < l0_ranges; l0_index += 3) {
1278
+ addAllToBuffer<Alignment>(
1279
+ m * n,
1280
+ /*src_buf0=*/block_buffers[(l0_index + 0) * l0_size],
1281
+ /*src_buf1=*/block_buffers[(l0_index + 1) * l0_size],
1282
+ /*src_buf2=*/block_buffers[(l0_index + 2) * l0_size],
1283
+ /*dst_buf= */ block_buffers[0]);
1284
+ }
1285
+
1286
+ for (; l0_index < l0_ranges; ++l0_index) {
1287
+ addToBuffer<Alignment>(m * n, block_buffers[l0_index * l0_size],
1288
+ block_buffers[0]);
1289
+ }
1290
+ }
1291
+
1292
+ void applyOutputKernel() const {
1293
+ typedef internal::blas_data_mapper<Scalar, Index, ColMajor> OutputMapper;
1294
+ evaluator->m_output_kernel(
1295
+ OutputMapper(result, m), evaluator->m_tensor_contraction_params,
1296
+ static_cast<Eigen::Index>(0), static_cast<Eigen::Index>(0), m, n);
1297
+ }
1298
+
1299
+ // Compute block size with accounting for potentially incomplete last block.
1300
+ Index actualBlockSize(Index block_idx) const {
1301
+ return block_idx + 1 < num_blocks
1302
+ ? block_size
1303
+ : k + block_size - block_size * num_blocks;
1304
+ };
1305
+
1306
+ // Compute range size with accounting for potentially incomplete last range.
1307
+ Index actualRangeSize(Index num_ranges, Index range_size,
1308
+ Index range_idx) const {
1309
+ eigen_assert(range_idx < num_ranges);
1310
+ return range_idx + 1 < num_ranges
1311
+ ? range_size
1312
+ : num_blocks + range_size - range_size * num_ranges;
1313
+ };
1314
+
1315
+ template <int Alignment>
1316
+ EIGEN_STRONG_INLINE static void addToBuffer(size_t n, const Scalar* src_buf,
1317
+ Scalar* tgt_buf) {
1318
+ const int output_packet_size =
1319
+ internal::unpacket_traits<PacketReturnType>::size;
1320
+ size_t i = 0;
1321
+ const size_t num_packets = n / output_packet_size;
1322
+ for (; i < output_packet_size * num_packets; i += output_packet_size) {
1323
+ const PacketReturnType src_val =
1324
+ internal::pload<PacketReturnType>(src_buf + i);
1325
+ const PacketReturnType tgt_val =
1326
+ internal::ploadt<PacketReturnType, Alignment>(tgt_buf + i);
1327
+ const PacketReturnType sum = internal::padd(src_val, tgt_val);
1328
+ internal::pstoret<Scalar, PacketReturnType, Alignment>(tgt_buf + i,
1329
+ sum);
1330
+ }
1331
+ for (; i < n; ++i) {
1332
+ tgt_buf[i] += src_buf[i];
1333
+ }
1334
+ }
1335
+
1336
+ template <int Alignment>
1337
+ EIGEN_STRONG_INLINE static void addAllToBuffer(size_t n,
1338
+ const Scalar* src_buf0,
1339
+ const Scalar* src_buf1,
1340
+ const Scalar* src_buf2,
1341
+ Scalar* dst_buf) {
1342
+ using ::Eigen::internal::padd;
1343
+ using ::Eigen::internal::pload;
1344
+ using ::Eigen::internal::ploadt;
1345
+ using ::Eigen::internal::pstoret;
1346
+
1347
+ const int output_packet_size =
1348
+ internal::unpacket_traits<PacketReturnType>::size;
1349
+
1350
+ size_t i = 0;
1351
+ const size_t num_packets = n / output_packet_size;
1352
+ for (; i < output_packet_size * num_packets; i += output_packet_size) {
1353
+ const auto src_val0 = pload<PacketReturnType>(src_buf0 + i);
1354
+ const auto src_val1 = pload<PacketReturnType>(src_buf1 + i);
1355
+ const auto src_val2 = pload<PacketReturnType>(src_buf2 + i);
1356
+
1357
+ const auto dst_val = ploadt<PacketReturnType, Alignment>(dst_buf + i);
1358
+ const auto sum =
1359
+ padd(padd(dst_val, src_val0), padd(src_val1, src_val2));
1360
+
1361
+ pstoret<Scalar, PacketReturnType, Alignment>(dst_buf + i, sum);
1362
+ }
1363
+ for (; i < n; ++i) {
1364
+ dst_buf[i] += src_buf0[i] + src_buf1[i] + src_buf2[i];
1365
+ }
1366
+ }
1367
+
1368
+ template <int Alignment>
1369
+ void eval(Barrier& barrier, Index start_block_idx, Index end_block_idx) {
1370
+ while (end_block_idx - start_block_idx > 1) {
1371
+ Index mid_block_idx = (start_block_idx + end_block_idx) / 2;
1372
+ evaluator->m_device.enqueueNoNotification(
1373
+ [this, &barrier, mid_block_idx, end_block_idx]() {
1374
+ eval<Alignment>(barrier, mid_block_idx, end_block_idx);
1375
+ });
1376
+ end_block_idx = mid_block_idx;
1377
+ }
1378
+
1379
+ Index block_idx = start_block_idx;
1380
+ Index block_start = block_idx * block_size;
1381
+ Index block_end = block_start + actualBlockSize(block_idx);
1382
+
1383
+ processBlock<Alignment>(block_idx, block_start, block_end);
1384
+ barrier.Notify();
1385
+ }
1386
+
1387
+ template <int Alignment>
1388
+ void evalAsync(Index start_block_idx, Index end_block_idx) {
1389
+ while (end_block_idx - start_block_idx > 1) {
1390
+ Index mid_block_idx = (start_block_idx + end_block_idx) / 2;
1391
+ evaluator->m_device.enqueueNoNotification(
1392
+ [this, mid_block_idx, end_block_idx]() {
1393
+ evalAsync<Alignment>(mid_block_idx, end_block_idx);
1394
+ });
1395
+ end_block_idx = mid_block_idx;
1396
+ }
1397
+
1398
+ Index block_idx = start_block_idx;
1399
+
1400
+ Index block_start = block_idx * block_size;
1401
+ Index block_end = block_start + actualBlockSize(block_idx);
1402
+
1403
+ processBlock<Alignment>(block_idx, block_start, block_end);
1404
+
1405
+ int v = num_pending_blocks.fetch_sub(1);
1406
+ eigen_assert(v >= 1);
1407
+
1408
+ if (v == 1) {
1409
+ // Aggregate partial sums from l0 ranges.
1410
+ aggregateL0Blocks<Alignment>();
1411
+
1412
+ // Apply output kernel.
1413
+ applyOutputKernel();
1414
+
1415
+ // NOTE: If we call `done` callback before deleting this (context),
1416
+ // it might deallocate Self* pointer captured by context, and we'll
1417
+ // fail in destructor trying to deallocate temporary buffers.
1418
+
1419
+ // Move done call back from context before it will be destructed.
1420
+ DoneCallback done_copy = std::move(done);
1421
+
1422
+ // We are confident that we are the last one who touches context.
1423
+ delete this;
1424
+
1425
+ // Now safely call the done callback.
1426
+ done_copy();
1427
+ }
1428
+ }
1429
+
1430
+ // Cost model doesn't capture well the cost associated with constructing
1431
+ // tensor contraction mappers and computing loop bounds in gemm_pack_lhs
1432
+ // and gemm_pack_rhs, so we specify minimum desired block size.
1433
+ static Index blockSize(Index k, int num_threads) {
1434
+ const auto round_up = [=](Index index) -> Index {
1435
+ const Index kmultiple = packet_size <= 8 ? 8 : packet_size;
1436
+ return divup<Index>(index, kmultiple) * kmultiple;
1437
+ };
1438
+
1439
+ const Index target_block_size = round_up(divup<Index>(k, num_threads));
1440
+ const Index desired_min_block_size = 12 * packet_size;
1441
+
1442
+ return numext::mini<Index>(
1443
+ k, numext::maxi<Index>(desired_min_block_size, target_block_size));
1444
+ }
1445
+
1446
+ EvalShardedByInnerDimContext(const EvalShardedByInnerDimContext&) = delete;
1447
+ void operator=(const EvalShardedByInnerDimContext&) = delete;
1448
+ };
1449
+
1450
+ // ------------------------------------------------------------------------ //
1451
+
1452
+ // Below are the function used by evalProductImpl heuristics, trying to select
1453
+ // optimcal parameters for parallelization algorithm.
1454
+
1455
+ // Decide whether we want to shard m x n contraction by columns or by rows.
1456
+ static bool shardByCol(Index m, Index n, Index num_threads) {
1457
+ // Note: we are comparing both n and m against Traits::nr, it is not
1458
+ // a mistake. We are trying to figure out how both n and m will fit into
1459
+ // the main sharding dimension.
1460
+
1461
+ // Sharding by column is the default
1462
+ // ... unless there is enough data for vectorization over rows
1463
+ if (m / num_threads >= Traits::nr &&
1464
+ // and not enough data for vectorization over columns
1465
+ (n / num_threads < Traits::nr ||
1466
+ // ... or barely enough data for vectorization over columns,
1467
+ // but it is not evenly dividable across threads
1468
+ (n / num_threads < 4 * Traits::nr &&
1469
+ (n % (num_threads * Traits::nr)) != 0 &&
1470
+ // ... and it is evenly dividable across threads for rows
1471
+ ((m % (num_threads * Traits::nr)) == 0 ||
1472
+ // .. or it is not evenly dividable for both dimensions but
1473
+ // there is much more data over rows so that corner effects are
1474
+ // mitigated.
1475
+ (m / n >= 6)))))
1476
+ return false;
1477
+ // Wait, or if matrices are just substantially prolonged over the other
1478
+ // dimension.
1479
+ if (n / num_threads < 16 * Traits::nr && m > n * 32) return false;
1480
+ return true;
1481
+ }
1482
+
1483
+ Index coarsenM(Index m, Index n, Index bm, Index bn, Index bk, Index gn,
1484
+ int num_threads, bool shard_by_col) const {
1485
+ Index gm = 1;
1486
+ Index gm1 = 1;
1487
+ Index nm0 = divup(m, bm);
1488
+ Index nm1 = nm0;
1489
+ for (;;) {
1490
+ // Find the next candidate for m grain size. It needs to result in
1491
+ // different number of blocks. E.g. if we have 10 kernels, we want to try
1492
+ // 5 and 10, but not 6, 7, 8 and 9.
1493
+ while (gm1 <= nm0 && nm1 == divup(nm0, gm1)) gm1++;
1494
+ if (gm1 > nm0) break;
1495
+ // Check the candidate.
1496
+ int res = checkGrain(m, n, bm, bn, bk, gm1, gn, gm, gn, num_threads,
1497
+ shard_by_col);
1498
+ if (res < 0) break;
1499
+ nm1 = divup(nm0, gm1);
1500
+ if (res == 0) continue;
1501
+ // Commit new grain size.
1502
+ gm = gm1;
1503
+ }
1504
+ return gm;
1505
+ }
1506
+
1507
+ Index coarsenN(Index m, Index n, Index bm, Index bn, Index bk, Index gm,
1508
+ int num_threads, bool shard_by_col) const {
1509
+ Index gn = 1;
1510
+ Index gn1 = 1;
1511
+ Index nn0 = divup(n, bn);
1512
+ Index nn1 = nn0;
1513
+ for (;;) {
1514
+ while (gn1 <= nn0 && nn1 == divup(nn0, gn1)) gn1++;
1515
+ if (gn1 > nn0) break;
1516
+ int res = checkGrain(m, n, bm, bn, bk, gm, gn1, gm, gn, num_threads,
1517
+ shard_by_col);
1518
+ if (res < 0) break;
1519
+ nn1 = divup(nn0, gn1);
1520
+ if (res == 0) continue;
1521
+ gn = gn1;
1522
+ }
1523
+ return gn;
1524
+ }
1525
+
1526
+ // checkGrain checks whether grain (gm, gn) is suitable and is better than
1527
+ // (oldgm, oldgn).
1528
+ int checkGrain(Index m, Index n, Index bm, Index bn, Index bk, Index gm,
1529
+ Index gn, Index oldgm, Index oldgn, int num_threads,
1530
+ bool shard_by_col) const {
1531
+ const TensorOpCost cost =
1532
+ contractionCost(bm * gm, bn * gn, bm, bn, bk, shard_by_col, true);
1533
+ double taskSize = TensorCostModel<ThreadPoolDevice>::taskSize(
1534
+ static_cast<double>(bm) * gm * bn * gn, cost);
1535
+ // If the task is too small, then we agree on it regardless of anything
1536
+ // else. Otherwise synchronization overheads will dominate.
1537
+ if (taskSize < 1) return 1;
1538
+ // If it is too large, then we reject it and all larger tasks.
1539
+ if (taskSize > 2) return -1;
1540
+ // Now we are in presumably good task size range.
1541
+ // The main deciding factor here is parallelism. Consider that we have 12
1542
+ // kernels and 4 threads. Grains of 2, 3 and 4 all yield good task sizes.
1543
+ // But 2/4 yield 6/3 tasks, which gives us parallelism of 0.75 (at most 3/4
1544
+ // of cores will be busy). While grain size 3 gives us 4 tasks, which gives
1545
+ // us parallelism of 1 (we can load all cores).
1546
+ Index nm0 = divup(m, bm);
1547
+ Index nn0 = divup(n, bn);
1548
+ Index new_tasks = divup(nm0, gm) * divup(nn0, gn);
1549
+ double new_parallelism = static_cast<double>(new_tasks) /
1550
+ (divup<int>(new_tasks, num_threads) * num_threads);
1551
+ Index old_tasks = divup(nm0, oldgm) * divup(nn0, oldgn);
1552
+ double old_parallelism = static_cast<double>(old_tasks) /
1553
+ (divup<int>(old_tasks, num_threads) * num_threads);
1554
+ if (new_parallelism > old_parallelism || new_parallelism == 1) return 1;
1555
+ return 0;
1556
+ }
1557
+
1558
+ TensorOpCost contractionCost(Index m, Index n, Index bm, Index bn, Index bk,
1559
+ bool shard_by_col, bool prepacked) const {
1560
+ const int packed_size = std::min<int>(PacketType<LhsScalar, Device>::size,
1561
+ PacketType<RhsScalar, Device>::size);
1562
+ const int output_packet_size = internal::unpacket_traits<PacketReturnType>::size;
1563
+ const double kd = static_cast<double>(bk);
1564
+ double compute_bandwidth = computeBandwidth(false, bm, bn, bk);
1565
+ // Computations.
1566
+ TensorOpCost cost = TensorOpCost(0, 0, kd * compute_bandwidth, true, packed_size);
1567
+ // Output stores.
1568
+ cost += TensorOpCost(0, sizeof(CoeffReturnType), 0, true, output_packet_size);
1569
+ if (prepacked) {
1570
+ // Packing and kernels are executed in different tasks. When we calculate
1571
+ // task grain size we look only at kernel cost assuming that kernel
1572
+ // is more expensive than packing.
1573
+ return cost;
1574
+ }
1575
+ // Lhs/rhs loads + computations.
1576
+ TensorOpCost lhsCost = this->m_leftImpl.costPerCoeff(true) * (kd / n);
1577
+ TensorOpCost rhsCost = this->m_rightImpl.costPerCoeff(true) * (kd / m);
1578
+ // Lhs packing memory cost does not contribute considerably to overall
1579
+ // execution time because lhs is prefetched early and accessed sequentially.
1580
+ if (shard_by_col)
1581
+ lhsCost.dropMemoryCost();
1582
+ else
1583
+ rhsCost.dropMemoryCost();
1584
+ return cost + lhsCost + rhsCost;
1585
+ }
1586
+
1587
+ // Decide whether we want to shard m x k x n contraction over the inner
1588
+ // (contraction) dimension (k).
1589
+ static bool shardByInnerDim(Index m, Index n, Index k, int num_threads,
1590
+ int num_threads_by_k) {
1591
+ std::ptrdiff_t bufsize = m * n * sizeof(Scalar);
1592
+ bool shard_by_k = false;
1593
+ if (n == 1 || // If mat*vec or...
1594
+ num_threads_by_k < 2 || // running single threaded or...
1595
+ num_threads_by_k <
1596
+ num_threads || // sharding by k gives less parallelism or...
1597
+ bufsize > l3CacheSize() / num_threads_by_k || // need more buffer space
1598
+ // than L3 cache or...
1599
+ k / num_threads_by_k < 2 * Traits::nr) { // k per thread is tiny.
1600
+ shard_by_k = false;
1601
+ } else if (numext::maxi(m, n) / num_threads <
1602
+ Traits::nr || // both other dimensions are tiny or...
1603
+ // k per thread is not small and...
1604
+ (k / num_threads_by_k > 8 * Traits::nr &&
1605
+ // one of the outer dimensions is tiny or sharding by k offers
1606
+ // more parallelism.
1607
+ (numext::mini(m, n) < 2 * Traits::nr ||
1608
+ num_threads_by_k > num_threads))) {
1609
+ shard_by_k = true;
1610
+ }
1611
+ return shard_by_k;
1612
+ }
1613
+
1614
+ TensorOpCost contractionCostPerInnerDim(Index m, Index n, Index k) const {
1615
+ // Compute cost.
1616
+ const int output_packet_size = internal::unpacket_traits<PacketReturnType>::size;
1617
+ TensorOpCost cost(0, 0, (computeBandwidth(true, m, n, k) * m) * n, true, output_packet_size);
1618
+ // Output stores.
1619
+ cost += TensorOpCost(0, sizeof(CoeffReturnType), 0, true, output_packet_size);
1620
+ TensorOpCost lhsCost = this->m_leftImpl.costPerCoeff(true) * m;
1621
+ TensorOpCost rhsCost = this->m_rightImpl.costPerCoeff(true) * n;
1622
+ // Since the inner gemm kernel is always sharded by column, the lhs
1623
+ // load cost is negligible.
1624
+ lhsCost.dropMemoryCost();
1625
+ return cost + lhsCost + rhsCost;
1626
+ }
1627
+
1628
+ int numThreadsInnerDim(Index m, Index n, Index k) const {
1629
+ const int output_packet_size = internal::unpacket_traits<PacketReturnType>::size;
1630
+ TensorOpCost cost = contractionCostPerInnerDim(m, n, k);
1631
+ double total_parallel_cost =
1632
+ TensorCostModel<ThreadPoolDevice>::totalCost(k, cost);
1633
+ // Cost of reduction step accumulating the m*n per-thread buffers into the
1634
+ // result.
1635
+ double reduction_cost = TensorCostModel<ThreadPoolDevice>::totalCost(
1636
+ m * n, TensorOpCost(2, 1, 1, true, output_packet_size));
1637
+ int num_threads = 1;
1638
+ double min_cost = total_parallel_cost;
1639
+ double kPerThreadOverHead = 3000;
1640
+ double kFixedOverHead = 100000;
1641
+ for (int nt = 2; nt <= this->m_device.numThreads(); nt += 2) {
1642
+ double sequential_cost =
1643
+ kFixedOverHead + nt * (reduction_cost + kPerThreadOverHead);
1644
+ double parallel_cost = total_parallel_cost / nt + sequential_cost;
1645
+ if (parallel_cost < min_cost) {
1646
+ num_threads = nt;
1647
+ min_cost = parallel_cost;
1648
+ }
1649
+ }
1650
+ return num_threads;
1651
+ }
1652
+
1653
+ double computeBandwidth(bool shard_by_col, Index bm, Index bn,
1654
+ Index bk) const {
1655
+ // Peak VFMA bandwidth is 0.5. However if we have not enough data for
1656
+ // vectorization bandwidth drops. The 4.0 and 2.0 bandwidth is determined
1657
+ // experimentally.
1658
+ double computeBandwidth =
1659
+ bk == 1 ? 4.0
1660
+ : (shard_by_col ? bn : bm) < Traits::nr ||
1661
+ (shard_by_col ? bm : bn) < Traits::mr
1662
+ ? 2.0
1663
+ : 0.5;
1664
+ #ifndef EIGEN_VECTORIZE_FMA
1665
+ // Bandwidth of all of VFMA/MULPS/ADDPS is 0.5 on latest Intel processors.
1666
+ // However for MULPS/ADDPS we have dependent sequence of 2 such
1667
+ // instructions,
1668
+ // so overall bandwidth is 1.0.
1669
+ if (computeBandwidth == 0.5) computeBandwidth = 1.0;
1670
+ #endif
1671
+ return computeBandwidth;
1672
+ }
1673
+
1674
+ };
1675
+
1676
+ } // end namespace Eigen
1677
+
1678
+ #endif // EIGEN_USE_THREADS
1679
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_THREAD_POOL_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConversion.h ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2015 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONVERSION_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONVERSION_H
12
+
13
+ #include "./InternalHeaderCheck.h"
14
+
15
+ namespace Eigen {
16
+
17
+ /** \class TensorConversionOp
18
+ * \ingroup CXX11_Tensor_Module
19
+ *
20
+ * \brief Tensor conversion class. This class makes it possible to vectorize
21
+ * type casting operations when the number of scalars per packet in the source
22
+ * and the destination type differ
23
+ */
24
+ namespace internal {
25
+ template<typename TargetType, typename XprType>
26
+ struct traits<TensorConversionOp<TargetType, XprType> >
27
+ {
28
+ // Type promotion to handle the case where the types of the lhs and the rhs are different.
29
+ typedef TargetType Scalar;
30
+ typedef typename traits<XprType>::StorageKind StorageKind;
31
+ typedef typename traits<XprType>::Index Index;
32
+ typedef typename XprType::Nested Nested;
33
+ typedef std::remove_reference_t<Nested> Nested_;
34
+ static constexpr int NumDimensions = traits<XprType>::NumDimensions;
35
+ static constexpr int Layout = traits<XprType>::Layout;
36
+ enum { Flags = 0 };
37
+ typedef typename TypeConversion<Scalar, typename traits<XprType>::PointerType>::type PointerType;
38
+ };
39
+
40
+ template<typename TargetType, typename XprType>
41
+ struct eval<TensorConversionOp<TargetType, XprType>, Eigen::Dense>
42
+ {
43
+ typedef const TensorConversionOp<TargetType, XprType>& type;
44
+ };
45
+
46
+ template<typename TargetType, typename XprType>
47
+ struct nested<TensorConversionOp<TargetType, XprType>, 1, typename eval<TensorConversionOp<TargetType, XprType> >::type>
48
+ {
49
+ typedef TensorConversionOp<TargetType, XprType> type;
50
+ };
51
+
52
+ } // end namespace internal
53
+
54
+
55
+ template <typename TensorEvaluator, typename SrcPacket, typename TgtPacket, int SrcCoeffRatio, int TgtCoeffRatio>
56
+ struct PacketConverter;
57
+
58
+ template <typename TensorEvaluator, typename SrcPacket, typename TgtPacket>
59
+ struct PacketConverter<TensorEvaluator, SrcPacket, TgtPacket, 1, 1> {
60
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
61
+ PacketConverter(const TensorEvaluator& impl)
62
+ : m_impl(impl) {}
63
+
64
+ template<int LoadMode, typename Index>
65
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const {
66
+ return internal::pcast<SrcPacket, TgtPacket>(m_impl.template packet<LoadMode>(index));
67
+ }
68
+
69
+ private:
70
+ const TensorEvaluator& m_impl;
71
+ };
72
+
73
+
74
+ template <typename TensorEvaluator, typename SrcPacket, typename TgtPacket>
75
+ struct PacketConverter<TensorEvaluator, SrcPacket, TgtPacket, 2, 1> {
76
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
77
+ PacketConverter(const TensorEvaluator& impl)
78
+ : m_impl(impl) {}
79
+
80
+ template<int LoadMode, typename Index>
81
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const {
82
+ const int SrcPacketSize = internal::unpacket_traits<SrcPacket>::size;
83
+
84
+ SrcPacket src1 = m_impl.template packet<LoadMode>(index);
85
+ SrcPacket src2 = m_impl.template packet<LoadMode>(index + SrcPacketSize);
86
+ TgtPacket result = internal::pcast<SrcPacket, TgtPacket>(src1, src2);
87
+ return result;
88
+ }
89
+
90
+ private:
91
+ const TensorEvaluator& m_impl;
92
+ };
93
+
94
+ template <typename TensorEvaluator, typename SrcPacket, typename TgtPacket>
95
+ struct PacketConverter<TensorEvaluator, SrcPacket, TgtPacket, 4, 1> {
96
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
97
+ PacketConverter(const TensorEvaluator& impl)
98
+ : m_impl(impl) {}
99
+
100
+ template<int LoadMode, typename Index>
101
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const {
102
+ const int SrcPacketSize = internal::unpacket_traits<SrcPacket>::size;
103
+
104
+ SrcPacket src1 = m_impl.template packet<LoadMode>(index);
105
+ SrcPacket src2 = m_impl.template packet<LoadMode>(index + SrcPacketSize);
106
+ SrcPacket src3 = m_impl.template packet<LoadMode>(index + 2 * SrcPacketSize);
107
+ SrcPacket src4 = m_impl.template packet<LoadMode>(index + 3 * SrcPacketSize);
108
+ TgtPacket result = internal::pcast<SrcPacket, TgtPacket>(src1, src2, src3, src4);
109
+ return result;
110
+ }
111
+
112
+ private:
113
+ const TensorEvaluator& m_impl;
114
+ };
115
+
116
+ template <typename TensorEvaluator, typename SrcPacket, typename TgtPacket>
117
+ struct PacketConverter<TensorEvaluator, SrcPacket, TgtPacket, 8, 1> {
118
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
119
+ PacketConverter(const TensorEvaluator& impl)
120
+ : m_impl(impl) {}
121
+
122
+ template<int LoadMode, typename Index>
123
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const {
124
+ const int SrcPacketSize = internal::unpacket_traits<SrcPacket>::size;
125
+
126
+ SrcPacket src1 = m_impl.template packet<LoadMode>(index);
127
+ SrcPacket src2 = m_impl.template packet<LoadMode>(index + 1 * SrcPacketSize);
128
+ SrcPacket src3 = m_impl.template packet<LoadMode>(index + 2 * SrcPacketSize);
129
+ SrcPacket src4 = m_impl.template packet<LoadMode>(index + 3 * SrcPacketSize);
130
+ SrcPacket src5 = m_impl.template packet<LoadMode>(index + 4 * SrcPacketSize);
131
+ SrcPacket src6 = m_impl.template packet<LoadMode>(index + 5 * SrcPacketSize);
132
+ SrcPacket src7 = m_impl.template packet<LoadMode>(index + 6 * SrcPacketSize);
133
+ SrcPacket src8 = m_impl.template packet<LoadMode>(index + 7 * SrcPacketSize);
134
+ TgtPacket result = internal::pcast<SrcPacket, TgtPacket>(src1, src2, src3, src4, src5, src6, src7, src8);
135
+ return result;
136
+ }
137
+
138
+ private:
139
+ const TensorEvaluator& m_impl;
140
+ };
141
+
142
+ template <typename TensorEvaluator, typename SrcPacket, typename TgtPacket, int TgtCoeffRatio>
143
+ struct PacketConverter<TensorEvaluator, SrcPacket, TgtPacket, 1, TgtCoeffRatio> {
144
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
145
+ PacketConverter(const TensorEvaluator& impl)
146
+ : m_impl(impl), m_maxIndex(impl.dimensions().TotalSize()) {}
147
+
148
+ template<int LoadMode, typename Index>
149
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const {
150
+ const int SrcPacketSize = internal::unpacket_traits<SrcPacket>::size;
151
+ // Only call m_impl.packet() when we have direct access to the underlying data. This
152
+ // ensures that we don't compute the subexpression twice. We may however load some
153
+ // coefficients twice, but in practice this doesn't negatively impact performance.
154
+ if (m_impl.data() && (index + SrcPacketSize < m_maxIndex)) {
155
+ // Force unaligned memory loads since we can't ensure alignment anymore
156
+ return internal::pcast<SrcPacket, TgtPacket>(m_impl.template packet<Unaligned>(index));
157
+ } else {
158
+ const int TgtPacketSize = internal::unpacket_traits<TgtPacket>::size;
159
+ typedef typename internal::unpacket_traits<SrcPacket>::type SrcType;
160
+ typedef typename internal::unpacket_traits<TgtPacket>::type TgtType;
161
+ internal::scalar_cast_op<SrcType, TgtType> converter;
162
+ EIGEN_ALIGN_MAX typename internal::unpacket_traits<TgtPacket>::type values[TgtPacketSize];
163
+ EIGEN_UNROLL_LOOP
164
+ for (int i = 0; i < TgtPacketSize; ++i) {
165
+ values[i] = converter(m_impl.coeff(index+i));
166
+ }
167
+ TgtPacket rslt = internal::pload<TgtPacket>(values);
168
+ return rslt;
169
+ }
170
+ }
171
+
172
+ private:
173
+ const TensorEvaluator& m_impl;
174
+ const typename TensorEvaluator::Index m_maxIndex;
175
+ };
176
+
177
+ template<typename TargetType, typename XprType>
178
+ class TensorConversionOp : public TensorBase<TensorConversionOp<TargetType, XprType>, ReadOnlyAccessors>
179
+ {
180
+ public:
181
+ typedef typename internal::traits<TensorConversionOp>::Scalar Scalar;
182
+ typedef typename internal::traits<TensorConversionOp>::StorageKind StorageKind;
183
+ typedef typename internal::traits<TensorConversionOp>::Index Index;
184
+ typedef typename internal::nested<TensorConversionOp>::type Nested;
185
+ typedef Scalar CoeffReturnType;
186
+ typedef typename NumTraits<Scalar>::Real RealScalar;
187
+
188
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorConversionOp(const XprType& xpr)
189
+ : m_xpr(xpr) {}
190
+
191
+ EIGEN_DEVICE_FUNC
192
+ const internal::remove_all_t<typename XprType::Nested>&
193
+ expression() const { return m_xpr; }
194
+
195
+ protected:
196
+ typename XprType::Nested m_xpr;
197
+ };
198
+
199
+ template <bool SameType, typename Eval, typename EvalPointerType> struct ConversionSubExprEval {
200
+ static EIGEN_STRONG_INLINE bool run(Eval& impl, EvalPointerType) {
201
+ impl.evalSubExprsIfNeeded(NULL);
202
+ return true;
203
+ }
204
+ };
205
+
206
+ template <typename Eval, typename EvalPointerType> struct ConversionSubExprEval<true, Eval, EvalPointerType> {
207
+ static EIGEN_STRONG_INLINE bool run(Eval& impl, EvalPointerType data) {
208
+ return impl.evalSubExprsIfNeeded(data);
209
+ }
210
+ };
211
+
212
+ #ifdef EIGEN_USE_THREADS
213
+ template <bool SameType, typename Eval, typename EvalPointerType,
214
+ typename EvalSubExprsCallback>
215
+ struct ConversionSubExprEvalAsync {
216
+ static EIGEN_STRONG_INLINE void run(Eval& impl, EvalPointerType, EvalSubExprsCallback done) {
217
+ impl.evalSubExprsIfNeededAsync(nullptr, std::move(done));
218
+ }
219
+ };
220
+
221
+ template <typename Eval, typename EvalPointerType,
222
+ typename EvalSubExprsCallback>
223
+ struct ConversionSubExprEvalAsync<true, Eval, EvalPointerType,
224
+ EvalSubExprsCallback> {
225
+ static EIGEN_STRONG_INLINE void run(Eval& impl, EvalPointerType data, EvalSubExprsCallback done) {
226
+ impl.evalSubExprsIfNeededAsync(data, std::move(done));
227
+ }
228
+ };
229
+ #endif
230
+
231
+ namespace internal {
232
+
233
+ template <typename SrcType, typename TargetType, bool IsSameT>
234
+ struct CoeffConv {
235
+ template <typename ArgType, typename Device>
236
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetType run(const TensorEvaluator<ArgType, Device>& impl, Index index) {
237
+ internal::scalar_cast_op<SrcType, TargetType> converter;
238
+ return converter(impl.coeff(index));
239
+ }
240
+ };
241
+
242
+ template <typename SrcType, typename TargetType>
243
+ struct CoeffConv<SrcType, TargetType, true> {
244
+ template <typename ArgType, typename Device>
245
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetType run(const TensorEvaluator<ArgType, Device>& impl, Index index) {
246
+ return impl.coeff(index);
247
+ }
248
+ };
249
+
250
+ template <typename SrcPacket, typename TargetPacket, int LoadMode, bool ActuallyVectorize, bool IsSameT>
251
+ struct PacketConv {
252
+ typedef typename internal::unpacket_traits<SrcPacket>::type SrcType;
253
+ typedef typename internal::unpacket_traits<TargetPacket>::type TargetType;
254
+
255
+ static constexpr int PacketSize = internal::unpacket_traits<TargetPacket>::size;
256
+
257
+ template <typename ArgType, typename Device>
258
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetPacket run(const TensorEvaluator<ArgType, Device>& impl, Index index) {
259
+ internal::scalar_cast_op<SrcType, TargetType> converter;
260
+ EIGEN_ALIGN_MAX std::remove_const_t<TargetType> values[PacketSize];
261
+ EIGEN_UNROLL_LOOP
262
+ for (int i = 0; i < PacketSize; ++i) {
263
+ values[i] = converter(impl.coeff(index+i));
264
+ }
265
+ TargetPacket rslt = internal::pload<TargetPacket>(values);
266
+ return rslt;
267
+ }
268
+ };
269
+
270
+ template <typename SrcPacket, typename TargetPacket, int LoadMode, bool IsSameT>
271
+ struct PacketConv<SrcPacket, TargetPacket, LoadMode, true, IsSameT> {
272
+ typedef typename internal::unpacket_traits<SrcPacket>::type SrcType;
273
+ typedef typename internal::unpacket_traits<TargetPacket>::type TargetType;
274
+
275
+ template <typename ArgType, typename Device>
276
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetPacket run(const TensorEvaluator<ArgType, Device>& impl, Index index) {
277
+ const int SrcCoeffRatio = internal::type_casting_traits<SrcType, TargetType>::SrcCoeffRatio;
278
+ const int TgtCoeffRatio = internal::type_casting_traits<SrcType, TargetType>::TgtCoeffRatio;
279
+ PacketConverter<TensorEvaluator<ArgType, Device>, SrcPacket, TargetPacket,
280
+ SrcCoeffRatio, TgtCoeffRatio> converter(impl);
281
+ return converter.template packet<LoadMode>(index);
282
+ }
283
+ };
284
+
285
+ template <typename SrcPacket, typename TargetPacket, int LoadMode>
286
+ struct PacketConv<SrcPacket, TargetPacket, LoadMode, /*ActuallyVectorize=*/false, /*IsSameT=*/true> {
287
+ typedef typename internal::unpacket_traits<TargetPacket>::type TargetType;
288
+ static constexpr int PacketSize = internal::unpacket_traits<TargetPacket>::size;
289
+
290
+ template <typename ArgType, typename Device>
291
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetPacket run(const TensorEvaluator<ArgType, Device>& impl, Index index) {
292
+ EIGEN_ALIGN_MAX std::remove_const_t<TargetType> values[PacketSize];
293
+ for (int i = 0; i < PacketSize; ++i) values[i] = impl.coeff(index+i);
294
+ return internal::pload<TargetPacket>(values);
295
+ }
296
+ };
297
+
298
+ template <typename SrcPacket, typename TargetPacket, int LoadMode>
299
+ struct PacketConv<SrcPacket, TargetPacket, LoadMode, /*ActuallyVectorize=*/true, /*IsSameT=*/true> {
300
+ template <typename ArgType, typename Device>
301
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetPacket run(const TensorEvaluator<ArgType, Device>& impl, Index index) {
302
+ return impl.template packet<LoadMode>(index);
303
+ }
304
+ };
305
+
306
+ } // namespace internal
307
+
308
+ // Eval as rvalue
309
+ template<typename TargetType, typename ArgType, typename Device>
310
+ struct TensorEvaluator<const TensorConversionOp<TargetType, ArgType>, Device>
311
+ {
312
+ typedef TensorConversionOp<TargetType, ArgType> XprType;
313
+ typedef typename XprType::Index Index;
314
+ typedef typename TensorEvaluator<ArgType, Device>::Dimensions Dimensions;
315
+ typedef TargetType Scalar;
316
+ typedef TargetType CoeffReturnType;
317
+ typedef internal::remove_all_t<typename internal::traits<ArgType>::Scalar> SrcType;
318
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
319
+ typedef typename PacketType<SrcType, Device>::type PacketSourceType;
320
+ static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
321
+ static constexpr bool IsSameType = internal::is_same<TargetType, SrcType>::value;
322
+ typedef StorageMemory<CoeffReturnType, Device> Storage;
323
+ typedef typename Storage::Type EvaluatorPointerType;
324
+
325
+ enum {
326
+ IsAligned = false,
327
+ PacketAccess =
328
+ #ifndef EIGEN_USE_SYCL
329
+ true,
330
+ #else
331
+ TensorEvaluator<ArgType, Device>::PacketAccess &
332
+ internal::type_casting_traits<SrcType, TargetType>::VectorizedCast,
333
+ #endif
334
+ BlockAccess = TensorEvaluator<ArgType, Device>::BlockAccess,
335
+ PreferBlockAccess = TensorEvaluator<ArgType, Device>::PreferBlockAccess,
336
+ RawAccess = false
337
+ };
338
+
339
+ static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
340
+ static constexpr int NumDims = internal::array_size<Dimensions>::value;
341
+
342
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
343
+ typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
344
+ typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
345
+
346
+ typedef typename TensorEvaluator<const ArgType, Device>::TensorBlock
347
+ ArgTensorBlock;
348
+
349
+ struct TensorConversionOpBlockFactory {
350
+ template <typename ArgXprType>
351
+ struct XprType {
352
+ typedef TensorConversionOp<TargetType, const ArgXprType> type;
353
+ };
354
+
355
+ template <typename ArgXprType>
356
+ typename XprType<ArgXprType>::type expr(const ArgXprType& expr) const {
357
+ return typename XprType<ArgXprType>::type(expr);
358
+ }
359
+ };
360
+
361
+ typedef internal::TensorUnaryExprBlock<TensorConversionOpBlockFactory,
362
+ ArgTensorBlock>
363
+ TensorBlock;
364
+ //===--------------------------------------------------------------------===//
365
+
366
+ EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
367
+ : m_impl(op.expression(), device)
368
+ {
369
+ }
370
+
371
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_impl.dimensions(); }
372
+
373
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data)
374
+ {
375
+ return ConversionSubExprEval<IsSameType, TensorEvaluator<ArgType, Device>, EvaluatorPointerType>::run(m_impl, data);
376
+ }
377
+
378
+ #ifdef EIGEN_USE_THREADS
379
+ template <typename EvalSubExprsCallback>
380
+ EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(
381
+ EvaluatorPointerType data, EvalSubExprsCallback done) {
382
+ ConversionSubExprEvalAsync<IsSameType, TensorEvaluator<ArgType, Device>,
383
+ EvaluatorPointerType,
384
+ EvalSubExprsCallback>::run(m_impl, data, std::move(done));
385
+ }
386
+ #endif
387
+
388
+ EIGEN_STRONG_INLINE void cleanup()
389
+ {
390
+ m_impl.cleanup();
391
+ }
392
+
393
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const
394
+ {
395
+ return internal::CoeffConv<SrcType, TargetType, IsSameType>::run(m_impl,index);
396
+ }
397
+
398
+ template<int LoadMode>
399
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType
400
+ packet(Index index) const {
401
+ // If we are not going to do the cast, we just need to check that base
402
+ // TensorEvaluator has packet access. Otherwise we also need to make sure,
403
+ // that we have an implementation of vectorized cast.
404
+ const bool Vectorizable =
405
+ IsSameType
406
+ ? TensorEvaluator<ArgType, Device>::PacketAccess
407
+ : int(TensorEvaluator<ArgType, Device>::PacketAccess) &
408
+ int(internal::type_casting_traits<SrcType, TargetType>::VectorizedCast);
409
+
410
+ return internal::PacketConv<PacketSourceType, PacketReturnType, LoadMode,
411
+ Vectorizable, IsSameType>::run(m_impl, index);
412
+ }
413
+
414
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
415
+ costPerCoeff(bool vectorized) const {
416
+ const double cast_cost = TensorOpCost::CastCost<SrcType, TargetType>();
417
+ if (vectorized) {
418
+ const double SrcCoeffRatio =
419
+ internal::type_casting_traits<SrcType, TargetType>::SrcCoeffRatio;
420
+ const double TgtCoeffRatio =
421
+ internal::type_casting_traits<SrcType, TargetType>::TgtCoeffRatio;
422
+ return m_impl.costPerCoeff(vectorized) * (SrcCoeffRatio / PacketSize) +
423
+ TensorOpCost(0, 0, TgtCoeffRatio * (cast_cost / PacketSize));
424
+ } else {
425
+ return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, cast_cost);
426
+ }
427
+ }
428
+
429
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
430
+ internal::TensorBlockResourceRequirements getResourceRequirements() const {
431
+ return m_impl.getResourceRequirements();
432
+ }
433
+
434
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock
435
+ block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
436
+ bool /*root_of_expr_ast*/ = false) const {
437
+ return TensorBlock(m_impl.block(desc, scratch),
438
+ TensorConversionOpBlockFactory());
439
+ }
440
+
441
+ EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; }
442
+
443
+ /// required by sycl in order to extract the sycl accessor
444
+ const TensorEvaluator<ArgType, Device>& impl() const { return m_impl; }
445
+
446
+ protected:
447
+ TensorEvaluator<ArgType, Device> m_impl;
448
+ };
449
+
450
+ } // end namespace Eigen
451
+
452
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONVERSION_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolution.h ADDED
@@ -0,0 +1,1135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_H
12
+
13
+ #include "./InternalHeaderCheck.h"
14
+
15
+ namespace Eigen {
16
+
17
+ /** \class TensorConvolution
18
+ * \ingroup CXX11_Tensor_Module
19
+ *
20
+ * \brief Tensor convolution class.
21
+ *
22
+ *
23
+ */
24
+ namespace internal {
25
+
26
+ template <typename Index, typename InputDims, int NumKernelDims, int Layout>
27
+ class IndexMapper {
28
+ public:
29
+ IndexMapper(const InputDims& input_dims, const array<Index, NumKernelDims>& kernel_dims,
30
+ const array<Index, NumKernelDims>& indices) {
31
+
32
+ array<Index, NumDims> dimensions = input_dims;
33
+ for (int i = 0; i < NumKernelDims; ++i) {
34
+ const Index index = indices[i];
35
+ const Index input_dim = input_dims[index];
36
+ const Index kernel_dim = kernel_dims[i];
37
+ const Index result_dim = input_dim - kernel_dim + 1;
38
+ dimensions[index] = result_dim;
39
+ }
40
+
41
+ array<Index, NumDims> inputStrides;
42
+ array<Index, NumDims> outputStrides;
43
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
44
+ inputStrides[0] = 1;
45
+ outputStrides[0] = 1;
46
+ for (int i = 1; i < NumDims; ++i) {
47
+ inputStrides[i] = inputStrides[i-1] * input_dims[i-1];
48
+ outputStrides[i] = outputStrides[i-1] * dimensions[i-1];
49
+ }
50
+ } else {
51
+ inputStrides[NumDims - 1] = 1;
52
+ outputStrides[NumDims - 1] = 1;
53
+ for (int i = static_cast<int>(NumDims) - 2; i >= 0; --i) {
54
+ inputStrides[i] = inputStrides[i + 1] * input_dims[i + 1];
55
+ outputStrides[i] = outputStrides[i + 1] * dimensions[i + 1];
56
+ }
57
+ }
58
+
59
+ array<Index, NumDims> gpuInputDimensions;
60
+ array<Index, NumDims> gpuOutputDimensions;
61
+ array<Index, NumDims> tmp = dimensions;
62
+ array<Index, NumDims> ordering;
63
+ const size_t offset = static_cast<int>(Layout) == static_cast<int>(ColMajor)
64
+ ? 0
65
+ : NumDims - NumKernelDims;
66
+ for (int i = 0; i < NumKernelDims; ++i) {
67
+ const Index index = i + offset;
68
+ ordering[index] = indices[i];
69
+ tmp[indices[i]] = -1;
70
+ gpuInputDimensions[index] = input_dims[indices[i]];
71
+ gpuOutputDimensions[index] = dimensions[indices[i]];
72
+ }
73
+
74
+ int written = static_cast<int>(Layout) == static_cast<int>(ColMajor)
75
+ ? NumKernelDims
76
+ : 0;
77
+ for (int i = 0; i < NumDims; ++i) {
78
+ if (tmp[i] >= 0) {
79
+ ordering[written] = i;
80
+ gpuInputDimensions[written] = input_dims[i];
81
+ gpuOutputDimensions[written] = dimensions[i];
82
+ ++written;
83
+ }
84
+ }
85
+
86
+ for (int i = 0; i < NumDims; ++i) {
87
+ m_inputStrides[i] = inputStrides[ordering[i]];
88
+ m_outputStrides[i] = outputStrides[ordering[i]];
89
+ }
90
+
91
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
92
+ for (int i = 0; i < NumDims; ++i) {
93
+ if (i > NumKernelDims) {
94
+ m_gpuInputStrides[i] =
95
+ m_gpuInputStrides[i - 1] * gpuInputDimensions[i - 1];
96
+ m_gpuOutputStrides[i] =
97
+ m_gpuOutputStrides[i - 1] * gpuOutputDimensions[i - 1];
98
+ } else {
99
+ m_gpuInputStrides[i] = 1;
100
+ m_gpuOutputStrides[i] = 1;
101
+ }
102
+ }
103
+ } else {
104
+ for (int i = NumDims - 1; i >= 0; --i) {
105
+ if (static_cast<size_t>(i + 1) < offset) {
106
+ m_gpuInputStrides[i] =
107
+ m_gpuInputStrides[i + 1] * gpuInputDimensions[i + 1];
108
+ m_gpuOutputStrides[i] =
109
+ m_gpuOutputStrides[i + 1] * gpuOutputDimensions[i + 1];
110
+ } else {
111
+ m_gpuInputStrides[i] = 1;
112
+ m_gpuOutputStrides[i] = 1;
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuInputPlaneToTensorInputOffset(Index p) const {
119
+ Index inputIndex = 0;
120
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
121
+ for (int d = NumDims - 1; d > NumKernelDims; --d) {
122
+ const Index idx = p / m_gpuInputStrides[d];
123
+ inputIndex += idx * m_inputStrides[d];
124
+ p -= idx * m_gpuInputStrides[d];
125
+ }
126
+ if (NumKernelDims < NumDims) {
127
+ inputIndex += p * m_inputStrides[NumKernelDims];
128
+ }
129
+ } else {
130
+ std::ptrdiff_t limit = 0;
131
+ if (NumKernelDims < NumDims) {
132
+ limit = NumDims - NumKernelDims - 1;
133
+ }
134
+ for (int d = 0; d < limit; ++d) {
135
+ const Index idx = p / m_gpuInputStrides[d];
136
+ inputIndex += idx * m_inputStrides[d];
137
+ p -= idx * m_gpuInputStrides[d];
138
+ }
139
+ inputIndex += p * m_inputStrides[limit];
140
+ }
141
+ return inputIndex;
142
+ }
143
+
144
+ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuOutputPlaneToTensorOutputOffset(Index p) const {
145
+ Index outputIndex = 0;
146
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
147
+ for (int d = NumDims - 1; d > NumKernelDims; --d) {
148
+ const Index idx = p / m_gpuOutputStrides[d];
149
+ outputIndex += idx * m_outputStrides[d];
150
+ p -= idx * m_gpuOutputStrides[d];
151
+ }
152
+ if (NumKernelDims < NumDims) {
153
+ outputIndex += p * m_outputStrides[NumKernelDims];
154
+ }
155
+ } else {
156
+ std::ptrdiff_t limit = 0;
157
+ if (NumKernelDims < NumDims) {
158
+ limit = NumDims - NumKernelDims - 1;
159
+ }
160
+ for (int d = 0; d < limit; ++d) {
161
+ const Index idx = p / m_gpuOutputStrides[d];
162
+ outputIndex += idx * m_outputStrides[d];
163
+ p -= idx * m_gpuOutputStrides[d];
164
+ }
165
+ outputIndex += p * m_outputStrides[limit];
166
+ }
167
+ return outputIndex;
168
+ }
169
+
170
+ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuInputKernelToTensorInputOffset(Index i) const {
171
+ const size_t offset = static_cast<int>(Layout) == static_cast<int>(ColMajor)
172
+ ? 0
173
+ : NumDims - NumKernelDims;
174
+ return i * m_inputStrides[offset];
175
+ }
176
+
177
+ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuOutputKernelToTensorOutputOffset(Index i) const {
178
+ const size_t offset = static_cast<int>(Layout) == static_cast<int>(ColMajor)
179
+ ? 0
180
+ : NumDims - NumKernelDims;
181
+ return i * m_outputStrides[offset];
182
+ }
183
+
184
+ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuInputKernelToTensorInputOffset(Index i, Index j) const {
185
+ const size_t offset = static_cast<int>(Layout) == static_cast<int>(ColMajor)
186
+ ? 0
187
+ : NumDims - NumKernelDims;
188
+ return i * m_inputStrides[offset] + j * m_inputStrides[offset + 1];
189
+ }
190
+
191
+ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuOutputKernelToTensorOutputOffset(Index i, Index j) const {
192
+ const size_t offset = static_cast<int>(Layout) == static_cast<int>(ColMajor)
193
+ ? 0
194
+ : NumDims - NumKernelDims;
195
+ return i * m_outputStrides[offset] + j * m_outputStrides[offset + 1];
196
+ }
197
+
198
+ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuInputKernelToTensorInputOffset(Index i, Index j, Index k) const {
199
+ const size_t offset = static_cast<int>(Layout) == static_cast<int>(ColMajor)
200
+ ? 0
201
+ : NumDims - NumKernelDims;
202
+ return i * m_inputStrides[offset] + j * m_inputStrides[offset + 1] +
203
+ k * m_inputStrides[offset + 2];
204
+ }
205
+
206
+ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuOutputKernelToTensorOutputOffset(Index i, Index j, Index k) const {
207
+ const size_t offset = static_cast<int>(Layout) == static_cast<int>(ColMajor)
208
+ ? 0
209
+ : NumDims - NumKernelDims;
210
+ return i * m_outputStrides[offset] + j * m_outputStrides[offset + 1] +
211
+ k * m_outputStrides[offset + 2];
212
+ }
213
+
214
+ private:
215
+ static constexpr int NumDims = internal::array_size<InputDims>::value;
216
+ array<Index, NumDims> m_inputStrides;
217
+ array<Index, NumDims> m_outputStrides;
218
+ array<Index, NumDims> m_gpuInputStrides;
219
+ array<Index, NumDims> m_gpuOutputStrides;
220
+ };
221
+
222
+
223
+
224
+ template<typename Dimensions, typename InputXprType, typename KernelXprType>
225
+ struct traits<TensorConvolutionOp<Dimensions, InputXprType, KernelXprType> >
226
+ {
227
+ // Type promotion to handle the case where the types of the lhs and the rhs are different.
228
+ typedef typename promote_storage_type<typename InputXprType::Scalar,
229
+ typename KernelXprType::Scalar>::ret Scalar;
230
+ typedef typename promote_storage_type<typename traits<InputXprType>::StorageKind,
231
+ typename traits<KernelXprType>::StorageKind>::ret StorageKind;
232
+ typedef typename promote_index_type<typename traits<InputXprType>::Index,
233
+ typename traits<KernelXprType>::Index>::type Index;
234
+ typedef typename InputXprType::Nested LhsNested;
235
+ typedef typename KernelXprType::Nested RhsNested;
236
+ typedef std::remove_reference_t<LhsNested> LhsNested_;
237
+ typedef std::remove_reference_t<RhsNested> RhsNested_;
238
+ static constexpr int NumDimensions = traits<InputXprType>::NumDimensions;
239
+ static constexpr int Layout = traits<InputXprType>::Layout;
240
+ typedef std::conditional_t<Pointer_type_promotion<typename InputXprType::Scalar, Scalar>::val,
241
+ typename traits<InputXprType>::PointerType, typename traits<KernelXprType>::PointerType> PointerType;
242
+
243
+ enum {
244
+ Flags = 0
245
+ };
246
+ };
247
+
248
+ template<typename Dimensions, typename InputXprType, typename KernelXprType>
249
+ struct eval<TensorConvolutionOp<Dimensions, InputXprType, KernelXprType>, Eigen::Dense>
250
+ {
251
+ typedef const TensorConvolutionOp<Dimensions, InputXprType, KernelXprType>& type;
252
+ };
253
+
254
+ template<typename Dimensions, typename InputXprType, typename KernelXprType>
255
+ struct nested<TensorConvolutionOp<Dimensions, InputXprType, KernelXprType>, 1, typename eval<TensorConvolutionOp<Dimensions, InputXprType, KernelXprType> >::type>
256
+ {
257
+ typedef TensorConvolutionOp<Dimensions, InputXprType, KernelXprType> type;
258
+ };
259
+
260
+ } // end namespace internal
261
+
262
+
263
+
264
+ template<typename Indices, typename InputXprType, typename KernelXprType>
265
+ class TensorConvolutionOp : public TensorBase<TensorConvolutionOp<Indices, InputXprType, KernelXprType>, ReadOnlyAccessors>
266
+ {
267
+ public:
268
+ typedef typename Eigen::internal::traits<TensorConvolutionOp>::Scalar Scalar;
269
+ typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
270
+ typedef typename internal::promote_storage_type<typename InputXprType::CoeffReturnType,
271
+ typename KernelXprType::CoeffReturnType>::ret CoeffReturnType;
272
+ typedef typename Eigen::internal::nested<TensorConvolutionOp>::type Nested;
273
+ typedef typename Eigen::internal::traits<TensorConvolutionOp>::StorageKind StorageKind;
274
+ typedef typename Eigen::internal::traits<TensorConvolutionOp>::Index Index;
275
+
276
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorConvolutionOp(const InputXprType& input, const KernelXprType& kernel, const Indices& dims)
277
+ : m_input_xpr(input), m_kernel_xpr(kernel), m_indices(dims) {}
278
+
279
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
280
+ const Indices& indices() const { return m_indices; }
281
+
282
+ /** \returns the nested expressions */
283
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
284
+ const internal::remove_all_t<typename InputXprType::Nested>&
285
+ inputExpression() const { return m_input_xpr; }
286
+
287
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
288
+ const internal::remove_all_t<typename KernelXprType::Nested>&
289
+ kernelExpression() const { return m_kernel_xpr; }
290
+
291
+ protected:
292
+ typename InputXprType::Nested m_input_xpr;
293
+ typename KernelXprType::Nested m_kernel_xpr;
294
+ const Indices m_indices;
295
+ };
296
+
297
+
298
+ template<typename Indices, typename InputArgType, typename KernelArgType, typename Device>
299
+ struct TensorEvaluator<const TensorConvolutionOp<Indices, InputArgType, KernelArgType>, Device>
300
+ {
301
+ typedef TensorConvolutionOp<Indices, InputArgType, KernelArgType> XprType;
302
+
303
+ static constexpr int NumDims = internal::array_size<typename TensorEvaluator<InputArgType, Device>::Dimensions>::value;
304
+ static constexpr int NumKernelDims = internal::array_size<Indices>::value;
305
+ typedef typename XprType::Index Index;
306
+ typedef DSizes<Index, NumDims> Dimensions;
307
+
308
+ typedef typename XprType::Scalar Scalar;
309
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
310
+ typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
311
+ static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
312
+ typedef StorageMemory<Scalar, Device> Storage;
313
+ typedef typename Storage::Type EvaluatorPointerType;
314
+
315
+ static constexpr int Layout = TensorEvaluator<InputArgType, Device>::Layout;
316
+ enum {
317
+ IsAligned = int(TensorEvaluator<InputArgType, Device>::IsAligned) & int(TensorEvaluator<KernelArgType, Device>::IsAligned),
318
+ PacketAccess = int(TensorEvaluator<InputArgType, Device>::PacketAccess) & int(TensorEvaluator<KernelArgType, Device>::PacketAccess),
319
+ BlockAccess = false,
320
+ PreferBlockAccess = false,
321
+ CoordAccess = false, // to be implemented
322
+ RawAccess = false
323
+ };
324
+
325
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
326
+ typedef internal::TensorBlockNotImplemented TensorBlock;
327
+ //===--------------------------------------------------------------------===//
328
+
329
+ EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
330
+ : m_inputImpl(op.inputExpression(), device), m_kernelImpl(op.kernelExpression(), device), m_kernelArg(op.kernelExpression()), m_kernel(NULL), m_local_kernel(false), m_device(device)
331
+ {
332
+ EIGEN_STATIC_ASSERT((static_cast<int>(TensorEvaluator<InputArgType, Device>::Layout) == static_cast<int>(TensorEvaluator<KernelArgType, Device>::Layout)), YOU_MADE_A_PROGRAMMING_MISTAKE);
333
+
334
+ const typename TensorEvaluator<InputArgType, Device>::Dimensions& input_dims = m_inputImpl.dimensions();
335
+ const typename TensorEvaluator<KernelArgType, Device>::Dimensions& kernel_dims = m_kernelImpl.dimensions();
336
+
337
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
338
+ m_inputStride[0] = 1;
339
+ for (int i = 1; i < NumDims; ++i) {
340
+ m_inputStride[i] = m_inputStride[i - 1] * input_dims[i - 1];
341
+ }
342
+ } else {
343
+ m_inputStride[NumDims - 1] = 1;
344
+ for (int i = NumDims - 2; i >= 0; --i) {
345
+ m_inputStride[i] = m_inputStride[i + 1] * input_dims[i + 1];
346
+ }
347
+ }
348
+
349
+ m_dimensions = m_inputImpl.dimensions();
350
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
351
+ for (int i = 0; i < NumKernelDims; ++i) {
352
+ const Index index = op.indices()[i];
353
+ const Index input_dim = input_dims[index];
354
+ const Index kernel_dim = kernel_dims[i];
355
+ const Index result_dim = input_dim - kernel_dim + 1;
356
+ m_dimensions[index] = result_dim;
357
+ if (i > 0) {
358
+ m_kernelStride[i] = m_kernelStride[i - 1] * kernel_dims[i - 1];
359
+ } else {
360
+ m_kernelStride[0] = 1;
361
+ }
362
+ m_indexStride[i] = m_inputStride[index];
363
+ }
364
+
365
+ m_outputStride[0] = 1;
366
+ for (int i = 1; i < NumDims; ++i) {
367
+ m_outputStride[i] = m_outputStride[i - 1] * m_dimensions[i - 1];
368
+ }
369
+ } else {
370
+ for (int i = NumKernelDims - 1; i >= 0; --i) {
371
+ const Index index = op.indices()[i];
372
+ const Index input_dim = input_dims[index];
373
+ const Index kernel_dim = kernel_dims[i];
374
+ const Index result_dim = input_dim - kernel_dim + 1;
375
+ m_dimensions[index] = result_dim;
376
+ if (i < NumKernelDims - 1) {
377
+ m_kernelStride[i] = m_kernelStride[i + 1] * kernel_dims[i + 1];
378
+ } else {
379
+ m_kernelStride[NumKernelDims - 1] = 1;
380
+ }
381
+ m_indexStride[i] = m_inputStride[index];
382
+ }
383
+
384
+ m_outputStride[NumDims - 1] = 1;
385
+ for (int i = NumDims - 2; i >= 0; --i) {
386
+ m_outputStride[i] = m_outputStride[i + 1] * m_dimensions[i + 1];
387
+ }
388
+ }
389
+ }
390
+
391
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
392
+
393
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(Scalar*) {
394
+ m_inputImpl.evalSubExprsIfNeeded(NULL);
395
+ preloadKernel();
396
+ return true;
397
+ }
398
+ EIGEN_STRONG_INLINE void cleanup() {
399
+ m_inputImpl.cleanup();
400
+ if (m_local_kernel) {
401
+ m_device.deallocate((void*)m_kernel);
402
+ m_local_kernel = false;
403
+ }
404
+ m_kernel = NULL;
405
+ }
406
+
407
+ void evalTo(typename XprType::Scalar* buffer) {
408
+ evalSubExprsIfNeeded(NULL);
409
+ for (int i = 0; i < dimensions().TotalSize(); ++i) {
410
+ buffer[i] += coeff(i);
411
+ }
412
+ cleanup();
413
+ }
414
+
415
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const
416
+ {
417
+ CoeffReturnType result = CoeffReturnType(0);
418
+ convolve(firstInput(index), 0, NumKernelDims-1, result);
419
+ return result;
420
+ }
421
+
422
+ template<int LoadMode>
423
+ EIGEN_DEVICE_FUNC PacketReturnType packet(const Index index) const
424
+ {
425
+ Index indices[2] = {index, index+PacketSize-1};
426
+ Index startInputs[2] = {0, 0};
427
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
428
+ for (int i = NumDims - 1; i > 0; --i) {
429
+ const Index idx0 = indices[0] / m_outputStride[i];
430
+ const Index idx1 = indices[1] / m_outputStride[i];
431
+ startInputs[0] += idx0 * m_inputStride[i];
432
+ startInputs[1] += idx1 * m_inputStride[i];
433
+ indices[0] -= idx0 * m_outputStride[i];
434
+ indices[1] -= idx1 * m_outputStride[i];
435
+ }
436
+ } else {
437
+ for (int i = 0; i < NumDims - 1; ++i) {
438
+ const Index idx0 = indices[0] / m_outputStride[i];
439
+ const Index idx1 = indices[1] / m_outputStride[i];
440
+ startInputs[0] += idx0 * m_inputStride[i];
441
+ startInputs[1] += idx1 * m_inputStride[i];
442
+ indices[0] -= idx0 * m_outputStride[i];
443
+ indices[1] -= idx1 * m_outputStride[i];
444
+ }
445
+ }
446
+ startInputs[0] += indices[0];
447
+ startInputs[1] += indices[1];
448
+
449
+ if (startInputs[1]-startInputs[0] == PacketSize-1) {
450
+ PacketReturnType result = internal::pset1<PacketReturnType>(0);
451
+ convolvePacket(startInputs[0], 0, NumKernelDims-1, result);
452
+ return result;
453
+ } else {
454
+ EIGEN_ALIGN_MAX Scalar data[PacketSize];
455
+ data[0] = Scalar(0);
456
+ convolve(startInputs[0], 0, NumKernelDims-1, data[0]);
457
+ for (int i = 1; i < PacketSize-1; ++i) {
458
+ data[i] = Scalar(0);
459
+ convolve(firstInput(index+i), 0, NumKernelDims-1, data[i]);
460
+ }
461
+ data[PacketSize-1] = Scalar(0);
462
+ convolve(startInputs[1], 0, NumKernelDims-1, data[PacketSize-1]);
463
+ return internal::pload<PacketReturnType>(data);
464
+ }
465
+ }
466
+
467
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
468
+ costPerCoeff(bool vectorized) const {
469
+ const double kernel_size = m_kernelImpl.dimensions().TotalSize();
470
+ // We ignore the use of fused multiply-add.
471
+ const double convolve_compute_cost =
472
+ TensorOpCost::AddCost<Scalar>() + TensorOpCost::MulCost<Scalar>();
473
+ const double firstIndex_compute_cost =
474
+ NumDims *
475
+ (2 * TensorOpCost::AddCost<Index>() + 2 * TensorOpCost::MulCost<Index>() +
476
+ TensorOpCost::DivCost<Index>());
477
+ return TensorOpCost(0, 0, firstIndex_compute_cost, vectorized, PacketSize) +
478
+ kernel_size * (m_inputImpl.costPerCoeff(vectorized) +
479
+ m_kernelImpl.costPerCoeff(vectorized) +
480
+ TensorOpCost(0, 0, convolve_compute_cost, vectorized,
481
+ PacketSize));
482
+ }
483
+
484
+ EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; }
485
+
486
+ private:
487
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index firstInput(Index index) const {
488
+ Index startInput = 0;
489
+ if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
490
+ for (int i = NumDims - 1; i > 0; --i) {
491
+ const Index idx = index / m_outputStride[i];
492
+ startInput += idx * m_inputStride[i];
493
+ index -= idx * m_outputStride[i];
494
+ }
495
+ } else {
496
+ for (int i = 0; i < NumDims - 1; ++i) {
497
+ const Index idx = index / m_outputStride[i];
498
+ startInput += idx * m_inputStride[i];
499
+ index -= idx * m_outputStride[i];
500
+ }
501
+ }
502
+ startInput += index;
503
+ return startInput;
504
+ }
505
+
506
+ EIGEN_DEVICE_FUNC void convolve(Index firstIndex, Index firstKernel, int DimIndex, CoeffReturnType& accum) const {
507
+ for (int j = 0; j < m_kernelImpl.dimensions()[DimIndex]; ++j) {
508
+ const Index input = firstIndex + j * m_indexStride[DimIndex];
509
+ const Index kernel = firstKernel + j * m_kernelStride[DimIndex];
510
+ if (DimIndex > 0) {
511
+ convolve(input, kernel, DimIndex-1, accum);
512
+ } else {
513
+ accum += m_inputImpl.coeff(input) * m_kernel[kernel];
514
+ }
515
+ }
516
+ }
517
+
518
+ template <typename Packet>
519
+ EIGEN_DEVICE_FUNC void convolvePacket(Index firstIndex, Index firstKernel, int DimIndex, Packet& accum) const {
520
+ for (int j = 0; j < m_kernelImpl.dimensions()[DimIndex]; ++j) {
521
+ const Index input = firstIndex + j * m_indexStride[DimIndex];
522
+ const Index kernel = firstKernel + j * m_kernelStride[DimIndex];
523
+ if (DimIndex > 0) {
524
+ convolvePacket(input, kernel, DimIndex-1, accum);
525
+ } else {
526
+ accum = internal::pmadd<Packet>(m_inputImpl.template packet<Unaligned>(input), internal::pset1<Packet>(m_kernel[kernel]), accum);
527
+ }
528
+ }
529
+ }
530
+
531
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void preloadKernel() {
532
+ // Don't make a local copy of the kernel unless we have to (i.e. it's an
533
+ // expression that needs to be evaluated)
534
+ const Scalar* in_place = m_kernelImpl.data();
535
+ if (in_place) {
536
+ m_kernel = in_place;
537
+ m_local_kernel = false;
538
+ } else {
539
+ size_t kernel_sz = m_kernelImpl.dimensions().TotalSize() * sizeof(Scalar);
540
+ Scalar* local = (Scalar*)m_device.allocate_temp(kernel_sz);
541
+ typedef TensorEvalToOp<const KernelArgType> EvalTo;
542
+ EvalTo evalToTmp(local, m_kernelArg);
543
+ const bool Vectorize = internal::IsVectorizable<Device, KernelArgType>::value;
544
+ internal::TensorExecutor<const EvalTo, Device, Vectorize>::run(evalToTmp, m_device);
545
+
546
+ m_kernel = local;
547
+ m_local_kernel = true;
548
+ }
549
+ }
550
+
551
+ array<Index, NumDims> m_inputStride;
552
+ array<Index, NumDims> m_outputStride;
553
+
554
+ array<Index, NumKernelDims> m_indexStride;
555
+ array<Index, NumKernelDims> m_kernelStride;
556
+ TensorEvaluator<InputArgType, Device> m_inputImpl;
557
+ TensorEvaluator<KernelArgType, Device> m_kernelImpl;
558
+ Dimensions m_dimensions;
559
+
560
+ KernelArgType m_kernelArg;
561
+ const Scalar* m_kernel;
562
+ bool m_local_kernel;
563
+ const Device EIGEN_DEVICE_REF m_device;
564
+ };
565
+
566
+
567
+
568
+
569
+ // Use an optimized implementation of the evaluation code for GPUs whenever possible.
570
+ #if defined(EIGEN_USE_GPU) && defined(EIGEN_GPUCC)
571
+
572
+ template <int StaticKernelSize>
573
+ struct GetKernelSize {
574
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int operator() (const int /*kernelSize*/) const {
575
+ return StaticKernelSize;
576
+ }
577
+ };
578
+ template <>
579
+ struct GetKernelSize<Dynamic> {
580
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int operator() (const int kernelSize) const {
581
+ return kernelSize;
582
+ }
583
+ };
584
+
585
+ template <typename InputEvaluator, typename Index, typename InputDims,
586
+ int StaticKernelSize>
587
+ __global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void EigenConvolutionKernel1D(
588
+ InputEvaluator eval,
589
+ const internal::IndexMapper<Index, InputDims, 1, InputEvaluator::Layout>
590
+ indexMapper,
591
+ const float* __restrict kernel, const int numPlanes, const int numX,
592
+ const int maxX, const int kernelSize, float* buffer) {
593
+ #if defined(EIGEN_HIPCC)
594
+ HIP_DYNAMIC_SHARED(float, s)
595
+ #else
596
+ extern __shared__ float s[];
597
+ #endif
598
+
599
+ const int first_x = blockIdx.x * maxX;
600
+ const int last_x = (first_x + maxX < numX ? first_x + maxX : numX) - 1;
601
+ const int num_x_input = last_x - first_x + GetKernelSize<StaticKernelSize>()(kernelSize);
602
+ const int num_x_output = last_x - first_x + 1;
603
+
604
+ const int first_plane = blockIdx.y * blockDim.y;
605
+ const int plane_stride = blockDim.y * gridDim.y;
606
+
607
+ for (int p = first_plane + threadIdx.y; p < numPlanes; p += plane_stride) {
608
+ // Load inputs to shared memory
609
+ const int plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(p);
610
+ const int plane_kernel_offset = threadIdx.y * num_x_input;
611
+ #pragma unroll
612
+ for (int i = threadIdx.x; i < num_x_input; i += blockDim.x) {
613
+ const int tensor_index = plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(i+first_x);
614
+ s[i + plane_kernel_offset] = eval.coeff(tensor_index);
615
+ }
616
+
617
+ __syncthreads();
618
+
619
+ // Compute the convolution
620
+ const int plane_output_offset = indexMapper.mapGpuOutputPlaneToTensorOutputOffset(p);
621
+
622
+ #pragma unroll
623
+ for (int i = threadIdx.x; i < num_x_output; i += blockDim.x) {
624
+ const int kernel_offset = plane_kernel_offset + i;
625
+ float result = 0.0f;
626
+ #pragma unroll
627
+ for (int k = 0; k < GetKernelSize<StaticKernelSize>()(kernelSize); ++k) {
628
+ result += s[k + kernel_offset] * kernel[k];
629
+ }
630
+ const int tensor_index = plane_output_offset + indexMapper.mapGpuOutputKernelToTensorOutputOffset(i+first_x);
631
+ buffer[tensor_index] = result;
632
+ }
633
+ __syncthreads();
634
+ }
635
+ };
636
+
637
+ template <typename InputEvaluator, typename Index, typename InputDims,
638
+ int StaticKernelSizeX, int StaticKernelSizeY>
639
+ __global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void EigenConvolutionKernel2D(
640
+ InputEvaluator eval,
641
+ const internal::IndexMapper<Index, InputDims, 2, InputEvaluator::Layout>
642
+ indexMapper,
643
+ const float* __restrict kernel, const int numPlanes, const int numX,
644
+ const int maxX, const int numY, const int maxY, const int kernelSizeX,
645
+ const int kernelSizeY, float* buffer) {
646
+ #if defined(EIGEN_HIPCC)
647
+ HIP_DYNAMIC_SHARED(float, s)
648
+ #else
649
+ extern __shared__ float s[];
650
+ #endif
651
+
652
+ const int first_x = blockIdx.x * maxX;
653
+ const int last_x = (first_x + maxX < numX ? first_x + maxX : numX) - 1;
654
+ const int num_x_input = last_x - first_x + GetKernelSize<StaticKernelSizeX>()(kernelSizeX);
655
+ const int num_x_output = last_x - first_x + 1;
656
+
657
+ const int first_y = blockIdx.y * maxY;
658
+ const int last_y = (first_y + maxY < numY ? first_y + maxY : numY) - 1;
659
+ const int num_y_input = last_y - first_y + GetKernelSize<StaticKernelSizeY>()(kernelSizeY);
660
+ const int num_y_output = last_y - first_y + 1;
661
+
662
+ const int first_plane = blockIdx.z * blockDim.z;
663
+ const int plane_stride = blockDim.z * gridDim.z;
664
+
665
+ for (int p = first_plane + threadIdx.z; p < numPlanes; p += plane_stride) {
666
+
667
+ const int plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(p);
668
+ const int plane_kernel_offset = threadIdx.z * num_y_input;
669
+
670
+ // Load inputs to shared memory
671
+ #pragma unroll
672
+ for (int j = threadIdx.y; j < num_y_input; j += blockDim.y) {
673
+ const int input_offset = num_x_input * (j + plane_kernel_offset);
674
+ #pragma unroll
675
+ for (int i = threadIdx.x; i < num_x_input; i += blockDim.x) {
676
+ const int tensor_index = plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(i+first_x, j+first_y);
677
+ s[i + input_offset] = eval.coeff(tensor_index);
678
+ }
679
+ }
680
+
681
+ __syncthreads();
682
+
683
+ // Convolution
684
+ const int plane_output_offset = indexMapper.mapGpuOutputPlaneToTensorOutputOffset(p);
685
+
686
+ #pragma unroll
687
+ for (int j = threadIdx.y; j < num_y_output; j += blockDim.y) {
688
+ #pragma unroll
689
+ for (int i = threadIdx.x; i < num_x_output; i += blockDim.x) {
690
+ float result = 0.0f;
691
+ #pragma unroll
692
+ for (int l = 0; l < GetKernelSize<StaticKernelSizeY>()(kernelSizeY); ++l) {
693
+ const int kernel_offset = kernelSizeX * l;
694
+ const int input_offset = i + num_x_input * (j + l + plane_kernel_offset);
695
+ #pragma unroll
696
+ for (int k = 0; k < GetKernelSize<StaticKernelSizeX>()(kernelSizeX); ++k) {
697
+ result += s[k + input_offset] * kernel[k + kernel_offset];
698
+ }
699
+ }
700
+ const int tensor_index = plane_output_offset + indexMapper.mapGpuOutputKernelToTensorOutputOffset(i+first_x, j+first_y);
701
+ buffer[tensor_index] = result;
702
+ }
703
+ }
704
+
705
+ __syncthreads();
706
+ }
707
+ };
708
+
709
+ template <typename InputEvaluator, typename Index, typename InputDims>
710
+ __global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void EigenConvolutionKernel3D(
711
+ InputEvaluator eval,
712
+ const internal::IndexMapper<Index, InputDims, 3, InputEvaluator::Layout>
713
+ indexMapper,
714
+ const float* __restrict kernel, const size_t numPlanes, const size_t numX,
715
+ const size_t maxX, const size_t numY, const size_t maxY, const size_t numZ,
716
+ const size_t maxZ, const size_t kernelSizeX, const size_t kernelSizeY,
717
+ const size_t kernelSizeZ, float* buffer) {
718
+ #if defined(EIGEN_HIPCC)
719
+ HIP_DYNAMIC_SHARED(float, s)
720
+ #else
721
+ extern __shared__ float s[];
722
+ #endif
723
+
724
+ // Load inputs to shared memory
725
+ const int first_x = blockIdx.x * maxX;
726
+ const int last_x = (first_x + maxX < numX ? first_x + maxX : numX) - 1;
727
+ const int num_x_input = last_x - first_x + kernelSizeX;
728
+
729
+ const int first_y = blockIdx.y * maxY;
730
+ const int last_y = (first_y + maxY < numY ? first_y + maxY : numY) - 1;
731
+ const int num_y_input = last_y - first_y + kernelSizeY;
732
+
733
+ const int first_z = blockIdx.z * maxZ;
734
+ const int last_z = (first_z + maxZ < numZ ? first_z + maxZ : numZ) - 1;
735
+ const int num_z_input = last_z - first_z + kernelSizeZ;
736
+
737
+ for (int p = 0; p < numPlanes; ++p) {
738
+
739
+ const int plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(p);
740
+ const int plane_kernel_offset = 0;
741
+
742
+ for (int k = threadIdx.z; k < num_z_input; k += blockDim.z) {
743
+ for (int j = threadIdx.y; j < num_y_input; j += blockDim.y) {
744
+ for (int i = threadIdx.x; i < num_x_input; i += blockDim.x) {
745
+ const int tensor_index = plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(i+first_x, j+first_y, k+first_z);
746
+ s[i + num_x_input * (j + num_y_input * (k + plane_kernel_offset))] = eval.coeff(tensor_index);
747
+ }
748
+ }
749
+ }
750
+
751
+ __syncthreads();
752
+
753
+ // Convolution
754
+ const int num_z_output = last_z - first_z + 1;
755
+ const int num_y_output = last_y - first_y + 1;
756
+ const int num_x_output = last_x - first_x + 1;
757
+ const int plane_output_offset = indexMapper.mapGpuOutputPlaneToTensorOutputOffset(p);
758
+
759
+ for (int k = threadIdx.z; k < num_z_output; k += blockDim.z) {
760
+ for (int j = threadIdx.y; j < num_y_output; j += blockDim.y) {
761
+ for (int i = threadIdx.x; i < num_x_output; i += blockDim.x) {
762
+ float result = 0.0f;
763
+ for (int n = 0; n < kernelSizeZ; ++n) {
764
+ for (int m = 0; m < kernelSizeY; ++m) {
765
+ for (int l = 0; l < kernelSizeX; ++l) {
766
+ result += s[i + l + num_x_input * (j + m + num_y_input * (k + n + plane_kernel_offset))] * kernel[l + kernelSizeX * (m + kernelSizeY * n)];
767
+ }
768
+ }
769
+ }
770
+ const int tensor_index = plane_output_offset + indexMapper.mapGpuOutputKernelToTensorOutputOffset(i+first_x, j+first_y, k+first_z);
771
+ buffer[tensor_index] = result;
772
+ }
773
+ }
774
+ }
775
+ __syncthreads();
776
+ }
777
+ };
778
+
779
+
780
+
781
+ template<typename Indices, typename InputArgType, typename KernelArgType>
782
+ struct TensorEvaluator<const TensorConvolutionOp<Indices, InputArgType, KernelArgType>, GpuDevice>
783
+ {
784
+ typedef TensorConvolutionOp<Indices, InputArgType, KernelArgType> XprType;
785
+
786
+ static constexpr int NumDims = internal::array_size<typename TensorEvaluator<InputArgType, GpuDevice>::Dimensions>::value;
787
+ static constexpr int NumKernelDims = internal::array_size<Indices>::value;
788
+ typedef typename XprType::Index Index;
789
+ typedef DSizes<Index, NumDims> Dimensions;
790
+ typedef typename TensorEvaluator<KernelArgType, GpuDevice>::Dimensions KernelDimensions;
791
+
792
+ static constexpr int Layout = TensorEvaluator<InputArgType, GpuDevice>::Layout;
793
+ enum {
794
+ IsAligned = TensorEvaluator<InputArgType, GpuDevice>::IsAligned & TensorEvaluator<KernelArgType, GpuDevice>::IsAligned,
795
+ PacketAccess = false,
796
+ BlockAccess = false,
797
+ PreferBlockAccess = false,
798
+ CoordAccess = false, // to be implemented
799
+ RawAccess = false
800
+ };
801
+
802
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
803
+ typedef internal::TensorBlockNotImplemented TensorBlock;
804
+ //===--------------------------------------------------------------------===//
805
+
806
+ TensorEvaluator(const XprType& op, const GpuDevice& device)
807
+ : m_inputImpl(op.inputExpression(), device), m_kernelImpl(op.kernelExpression(), device), m_kernelArg(op.kernelExpression()), m_indices(op.indices()), m_buf(NULL), m_kernel(NULL), m_local_kernel(false), m_device(device)
808
+ {
809
+ EIGEN_STATIC_ASSERT((static_cast<int>(TensorEvaluator<InputArgType, GpuDevice>::Layout) == static_cast<int>(TensorEvaluator<KernelArgType, GpuDevice>::Layout)), YOU_MADE_A_PROGRAMMING_MISTAKE);
810
+
811
+ const typename TensorEvaluator<InputArgType, GpuDevice>::Dimensions& input_dims = m_inputImpl.dimensions();
812
+ const typename TensorEvaluator<KernelArgType, GpuDevice>::Dimensions& kernel_dims = m_kernelImpl.dimensions();
813
+
814
+ m_dimensions = m_inputImpl.dimensions();
815
+ for (int i = 0; i < NumKernelDims; ++i) {
816
+ const Index index = op.indices()[i];
817
+ const Index input_dim = input_dims[index];
818
+ const Index kernel_dim = kernel_dims[i];
819
+ const Index result_dim = input_dim - kernel_dim + 1;
820
+ m_dimensions[index] = result_dim;
821
+ }
822
+ }
823
+
824
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
825
+ typedef typename PacketType<CoeffReturnType, GpuDevice>::type PacketReturnType;
826
+ typedef typename InputArgType::Scalar Scalar;
827
+ static constexpr int PacketSize = internal::unpacket_traits<PacketReturnType>::size;
828
+
829
+ EIGEN_DEVICE_FUNC const Dimensions& dimensions() const { return m_dimensions; }
830
+
831
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(Scalar* data) {
832
+ preloadKernel();
833
+ m_inputImpl.evalSubExprsIfNeeded(NULL);
834
+ if (data) {
835
+ executeEval(data);
836
+ return false;
837
+ } else {
838
+ m_buf = (Scalar*)m_device.allocate(dimensions().TotalSize() * sizeof(Scalar));
839
+ executeEval(m_buf);
840
+ return true;
841
+ }
842
+ }
843
+
844
+ EIGEN_STRONG_INLINE void cleanup() {
845
+ m_inputImpl.cleanup();
846
+ if (m_buf) {
847
+ m_device.deallocate(m_buf);
848
+ m_buf = NULL;
849
+ }
850
+ if (m_local_kernel) {
851
+ m_device.deallocate((void*)m_kernel);
852
+ m_local_kernel = false;
853
+ }
854
+ m_kernel = NULL;
855
+ }
856
+
857
+ EIGEN_STRONG_INLINE void preloadKernel() {
858
+ // Don't make a local copy of the kernel unless we have to (i.e. it's an
859
+ // expression that needs to be evaluated)
860
+ const Scalar* in_place = m_kernelImpl.data();
861
+ if (in_place) {
862
+ m_kernel = in_place;
863
+ m_local_kernel = false;
864
+ } else {
865
+ size_t kernel_sz = m_kernelImpl.dimensions().TotalSize() * sizeof(Scalar);
866
+ Scalar* local = (Scalar*)m_device.allocate(kernel_sz);
867
+ typedef TensorEvalToOp<const KernelArgType> EvalTo;
868
+ EvalTo evalToTmp(local, m_kernelArg);
869
+ const bool PacketAccess = internal::IsVectorizable<GpuDevice, KernelArgType>::value;
870
+ internal::TensorExecutor<const EvalTo, GpuDevice, PacketAccess>::run(evalToTmp, m_device);
871
+
872
+ m_kernel = local;
873
+ m_local_kernel = true;
874
+ }
875
+ }
876
+
877
+ static unsigned int ceil(unsigned int num, unsigned int denom) {
878
+ const unsigned int rounded_toward_zero = num / denom;
879
+ if (num > rounded_toward_zero * denom) {
880
+ return rounded_toward_zero + 1;
881
+ }
882
+ return rounded_toward_zero;
883
+ }
884
+
885
+ void executeEval(Scalar* data) const {
886
+ typedef typename TensorEvaluator<InputArgType, GpuDevice>::Dimensions InputDims;
887
+
888
+ const int maxSharedMem = m_device.sharedMemPerBlock();
889
+ const int maxThreadsPerBlock = m_device.maxGpuThreadsPerBlock();
890
+ const int maxBlocksPerProcessor = m_device.maxGpuThreadsPerMultiProcessor() / maxThreadsPerBlock;
891
+ const int numMultiProcessors = m_device.getNumGpuMultiProcessors();
892
+ const int warpSize = 32;
893
+
894
+ switch (NumKernelDims) {
895
+ case 1: {
896
+ const int kernel_size = m_kernelImpl.dimensions().TotalSize();
897
+
898
+ const int numX = dimensions()[m_indices[0]];
899
+ const int numP = dimensions().TotalSize() / numX;
900
+ int maxX;
901
+ dim3 block_size;
902
+
903
+ const int single_stride_dim =
904
+ static_cast<int>(Layout) == static_cast<int>(ColMajor)
905
+ ? 0
906
+ : m_inputImpl.dimensions().rank() - 1;
907
+ if (m_indices[0] == single_stride_dim) {
908
+ // Maximum the reuse
909
+ const int inner_dim = ((maxSharedMem / (sizeof(Scalar)) - kernel_size + 1 + 31) / 32) * 32;
910
+ maxX = numext::mini<int>(inner_dim, numX);
911
+ const int maxP = numext::mini<int>(maxSharedMem / ((kernel_size - 1 + maxX) * sizeof(Scalar)), numP);
912
+ block_size.x = numext::mini(maxThreadsPerBlock, maxX);
913
+ block_size.y = numext::mini<int>(maxThreadsPerBlock / block_size.x, maxP);
914
+ }
915
+ else {
916
+ // Read as much as possible alongside the inner most dimension, that is the plane
917
+ const int inner_dim = maxSharedMem / ((warpSize + kernel_size) * sizeof(Scalar));
918
+ const int maxP = numext::mini<int>(inner_dim, numP);
919
+ maxX = numext::mini<int>(maxSharedMem / (inner_dim * sizeof(Scalar)) - kernel_size + 1, numX);
920
+
921
+ block_size.x = numext::mini(warpSize, maxX);
922
+ block_size.y = numext::mini<int>(maxThreadsPerBlock/block_size.x, maxP);
923
+ }
924
+
925
+ const int shared_mem = block_size.y * (maxX + kernel_size - 1) * sizeof(Scalar);
926
+ gpu_assert(shared_mem <= maxSharedMem);
927
+
928
+ const int num_x_blocks = ceil(numX, maxX);
929
+ const int blocksPerProcessor = numext::mini(maxBlocksPerProcessor, maxSharedMem / shared_mem);
930
+ const int num_y_blocks = ceil(numMultiProcessors * blocksPerProcessor, num_x_blocks);
931
+
932
+ dim3 num_blocks(num_x_blocks, numext::mini<int>(num_y_blocks, ceil(numP, block_size.y)));
933
+
934
+
935
+ //cout << "launching 1D kernel with block_size.x: " << block_size.x << " block_size.y: " << block_size.y << " num_blocks.x: " << num_blocks.x << " num_blocks.y: " << num_blocks.y << " maxX: " << maxX << " shared_mem: " << shared_mem << " in stream " << m_device.stream() << endl;
936
+
937
+ const array<Index, 1> indices(m_indices[0]);
938
+ const array<Index, 1> kernel_dims(m_kernelImpl.dimensions()[0]);
939
+ internal::IndexMapper<Index, InputDims, 1, Layout> indexMapper(
940
+ m_inputImpl.dimensions(), kernel_dims, indices);
941
+ switch(kernel_size) {
942
+ case 4: {
943
+ LAUNCH_GPU_KERNEL((EigenConvolutionKernel1D<TensorEvaluator<InputArgType, GpuDevice>, Index, InputDims, 4>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, 4, data);
944
+ break;
945
+ }
946
+ case 7: {
947
+ LAUNCH_GPU_KERNEL((EigenConvolutionKernel1D<TensorEvaluator<InputArgType, GpuDevice>, Index, InputDims, 7>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, 7, data);
948
+ break;
949
+ }
950
+ default: {
951
+ LAUNCH_GPU_KERNEL((EigenConvolutionKernel1D<TensorEvaluator<InputArgType, GpuDevice>, Index, InputDims, Dynamic>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, kernel_size, data);
952
+ }
953
+ }
954
+ break;
955
+ }
956
+
957
+ case 2: {
958
+ const int idxX =
959
+ static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 0 : 1;
960
+ const int idxY =
961
+ static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 1 : 0;
962
+ const int kernel_size_x = m_kernelImpl.dimensions()[idxX];
963
+ const int kernel_size_y = m_kernelImpl.dimensions()[idxY];
964
+
965
+ const int numX = dimensions()[m_indices[idxX]];
966
+ const int numY = dimensions()[m_indices[idxY]];
967
+ const int numP = dimensions().TotalSize() / (numX*numY);
968
+
969
+ const float scaling_factor = sqrtf(static_cast<float>(maxSharedMem) / (sizeof(Scalar) * kernel_size_y * kernel_size_x));
970
+
971
+ // Snap maxX to warp size
972
+ int inner_dim = ((static_cast<int>(scaling_factor * kernel_size_x) - kernel_size_x + 1 + 32) / 32) * 32;
973
+ const int maxX = numext::mini<int>(inner_dim, numX);
974
+ const int maxY = numext::mini<int>(maxSharedMem / (sizeof(Scalar) * (maxX + kernel_size_x - 1)) - kernel_size_y + 1, numY);
975
+ const int maxP = numext::mini<int>(maxSharedMem / ((kernel_size_x - 1 + maxX) * (kernel_size_y - 1 + maxY) * sizeof(Scalar)), numP);
976
+
977
+ dim3 block_size;
978
+ block_size.x = numext::mini(1024, maxX);
979
+ block_size.y = numext::mini<int>(1024/block_size.x, maxY);
980
+ block_size.z = numext::mini<int>(1024/(block_size.x*block_size.y), maxP);
981
+
982
+ const int shared_mem = block_size.z * (maxX + kernel_size_x - 1) * (maxY + kernel_size_y - 1) * sizeof(Scalar);
983
+ gpu_assert(shared_mem <= maxSharedMem);
984
+
985
+ const int num_x_blocks = ceil(numX, maxX);
986
+ const int num_y_blocks = ceil(numY, maxY);
987
+ const int blocksPerProcessor = numext::mini(maxBlocksPerProcessor, maxSharedMem / shared_mem);
988
+ const int num_z_blocks = ceil(numMultiProcessors * blocksPerProcessor, num_x_blocks * num_y_blocks);
989
+
990
+ dim3 num_blocks(num_x_blocks, num_y_blocks, numext::mini<int>(num_z_blocks, ceil(numP, block_size.z)));
991
+
992
+
993
+ //cout << "launching 2D kernel with block_size.x: " << block_size.x << " block_size.y: " << block_size.y << " block_size.z: " << block_size.z << " num_blocks.x: " << num_blocks.x << " num_blocks.y: " << num_blocks.y << " num_blocks.z: " << num_blocks.z << " maxX: " << maxX << " maxY: " << maxY << " maxP: " << maxP << " shared_mem: " << shared_mem << " in stream " << m_device.stream() << endl;
994
+
995
+ const array<Index, 2> indices(m_indices[idxX], m_indices[idxY]);
996
+ const array<Index, 2> kernel_dims(m_kernelImpl.dimensions()[idxX],
997
+ m_kernelImpl.dimensions()[idxY]);
998
+ internal::IndexMapper<Index, InputDims, 2, Layout> indexMapper(
999
+ m_inputImpl.dimensions(), kernel_dims, indices);
1000
+ switch (kernel_size_x) {
1001
+ case 4: {
1002
+ switch (kernel_size_y) {
1003
+ case 7: {
1004
+ LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D<TensorEvaluator<InputArgType, GpuDevice>, Index, InputDims, 4, 7>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, 4, 7, data);
1005
+ break;
1006
+ }
1007
+ default: {
1008
+ LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D<TensorEvaluator<InputArgType, GpuDevice>, Index, InputDims, 4, Dynamic>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, 4, kernel_size_y, data);
1009
+ break;
1010
+ }
1011
+ }
1012
+ break;
1013
+ }
1014
+ case 7: {
1015
+ switch (kernel_size_y) {
1016
+ case 4: {
1017
+ LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D<TensorEvaluator<InputArgType, GpuDevice>, Index, InputDims, 7, 4>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, 7, 4, data);
1018
+ break;
1019
+ }
1020
+ default: {
1021
+ LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D<TensorEvaluator<InputArgType, GpuDevice>, Index, InputDims, 7, Dynamic>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, 7, kernel_size_y, data);
1022
+ break;
1023
+ }
1024
+ }
1025
+ break;
1026
+ }
1027
+ default: {
1028
+ LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D<TensorEvaluator<InputArgType, GpuDevice>, Index, InputDims, Dynamic, Dynamic>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, kernel_size_x, kernel_size_y, data);
1029
+ break;
1030
+ }
1031
+ }
1032
+ break;
1033
+ }
1034
+
1035
+ case 3: {
1036
+ const int idxX =
1037
+ static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 0 : 2;
1038
+ const int idxY =
1039
+ static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 1 : 1;
1040
+ const int idxZ =
1041
+ static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 2 : 0;
1042
+
1043
+ const int kernel_size_x = m_kernelImpl.dimensions()[idxX];
1044
+ const int kernel_size_y = m_kernelImpl.dimensions()[idxY];
1045
+ const int kernel_size_z = m_kernelImpl.dimensions()[idxZ];
1046
+
1047
+ const int numX = dimensions()[m_indices[idxX]];
1048
+ const int numY = dimensions()[m_indices[idxY]];
1049
+ const int numZ = dimensions()[m_indices[idxZ]];
1050
+ const int numP = dimensions().TotalSize() / (numX*numY*numZ);
1051
+
1052
+ const int maxX = numext::mini<int>(128, numext::mini<int>(maxSharedMem / (sizeof(Scalar) * kernel_size_y * kernel_size_z) - kernel_size_x + 1, numX));
1053
+ const int maxY = numext::mini<int>(128, numext::mini<int>(maxSharedMem / (sizeof(Scalar) * (maxX + kernel_size_x - 1) * kernel_size_z) - kernel_size_y + 1, numY));
1054
+ const int maxZ = numext::mini<int>(128, numext::mini<int>(maxSharedMem / (sizeof(Scalar) * (maxX + kernel_size_x - 1) * (maxY + kernel_size_y - 1)) - kernel_size_z + 1, numZ));
1055
+
1056
+ dim3 block_size;
1057
+ block_size.x = numext::mini(32, maxX);
1058
+ block_size.y = numext::mini(32, maxY);
1059
+ block_size.z = numext::mini<int>(1024/(block_size.x*block_size.y), maxZ);
1060
+ dim3 num_blocks(ceil(numX, maxX), ceil(numY, maxY), ceil(numZ, maxZ));
1061
+
1062
+ const int shared_mem = (maxX + kernel_size_x - 1) * (maxY + kernel_size_y - 1) * (maxZ + kernel_size_z - 1) * sizeof(Scalar);
1063
+ gpu_assert(shared_mem <= maxSharedMem);
1064
+
1065
+ //cout << "launching 3D kernel with block_size.x: " << block_size.x << " block_size.y: " << block_size.y << " block_size.z: " << block_size.z << " num_blocks.x: " << num_blocks.x << " num_blocks.y: " << num_blocks.y << " num_blocks.z: " << num_blocks.z << " shared_mem: " << shared_mem << " in stream " << m_device.stream() << endl;
1066
+ const array<Index, 3> indices(m_indices[idxX], m_indices[idxY],
1067
+ m_indices[idxZ]);
1068
+ const array<Index, 3> kernel_dims(m_kernelImpl.dimensions()[idxX],
1069
+ m_kernelImpl.dimensions()[idxY],
1070
+ m_kernelImpl.dimensions()[idxZ]);
1071
+ internal::IndexMapper<Index, InputDims, 3, Layout> indexMapper(
1072
+ m_inputImpl.dimensions(), kernel_dims, indices);
1073
+
1074
+ LAUNCH_GPU_KERNEL((EigenConvolutionKernel3D<TensorEvaluator<InputArgType, GpuDevice>, Index, InputDims>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, numZ, maxZ, kernel_size_x, kernel_size_y, kernel_size_z, data);
1075
+ break;
1076
+ }
1077
+
1078
+ default: {
1079
+ EIGEN_STATIC_ASSERT((NumKernelDims >= 1 && NumKernelDims <= 3), THIS_METHOD_IS_ONLY_FOR_OBJECTS_OF_A_SPECIFIC_SIZE);
1080
+ }
1081
+ }
1082
+ }
1083
+
1084
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const
1085
+ {
1086
+ eigen_assert(m_buf);
1087
+ eigen_assert(index < m_dimensions.TotalSize());
1088
+ return m_buf[index];
1089
+ }
1090
+
1091
+ template<int LoadMode>
1092
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(const Index index) const
1093
+ {
1094
+ eigen_assert(m_buf);
1095
+ eigen_assert(index < m_dimensions.TotalSize());
1096
+ return internal::ploadt<PacketReturnType, LoadMode>(m_buf+index);
1097
+ }
1098
+
1099
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
1100
+ costPerCoeff(bool vectorized) const {
1101
+ // TODO(rmlarsen): FIXME: For now, this is just a copy of the CPU cost
1102
+ // model.
1103
+ const double kernel_size = m_kernelImpl.dimensions().TotalSize();
1104
+ // We ignore the use of fused multiply-add.
1105
+ const double convolve_compute_cost =
1106
+ TensorOpCost::AddCost<Scalar>() + TensorOpCost::MulCost<Scalar>();
1107
+ const double firstIndex_compute_cost =
1108
+ NumDims *
1109
+ (2 * TensorOpCost::AddCost<Index>() + 2 * TensorOpCost::MulCost<Index>() +
1110
+ TensorOpCost::DivCost<Index>());
1111
+ return TensorOpCost(0, 0, firstIndex_compute_cost, vectorized, PacketSize) +
1112
+ kernel_size * (m_inputImpl.costPerCoeff(vectorized) +
1113
+ m_kernelImpl.costPerCoeff(vectorized) +
1114
+ TensorOpCost(0, 0, convolve_compute_cost, vectorized,
1115
+ PacketSize));
1116
+ }
1117
+
1118
+ private:
1119
+ TensorEvaluator<InputArgType, GpuDevice> m_inputImpl;
1120
+ TensorEvaluator<KernelArgType, GpuDevice> m_kernelImpl;
1121
+ KernelArgType m_kernelArg;
1122
+ Indices m_indices;
1123
+ Dimensions m_dimensions;
1124
+ Scalar* m_buf;
1125
+ const Scalar* m_kernel;
1126
+ bool m_local_kernel;
1127
+
1128
+ const GpuDevice& m_device;
1129
+ };
1130
+ #endif
1131
+
1132
+
1133
+ } // end namespace Eigen
1134
+
1135
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolutionSycl.h ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Mehdi Goli Codeplay Software Ltd.
5
+ // Ralph Potter Codeplay Software Ltd.
6
+ // Luke Iwanski Codeplay Software Ltd.
7
+ // Contact: <eigen@codeplay.com>
8
+ // Copyright (C) 2016 Benoit Steiner <benoit.steiner.goog@gmail.com>
9
+
10
+ //
11
+ // This Source Code Form is subject to the terms of the Mozilla
12
+ // Public License v. 2.0. If a copy of the MPL was not distributed
13
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
14
+
15
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_SYCL_H
16
+ #define EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_SYCL_H
17
+
18
+ #include "./InternalHeaderCheck.h"
19
+
20
+ namespace Eigen {
21
+
22
+ /** \class TensorConvolution
23
+ * \ingroup CXX11_Tensor_Module
24
+ *
25
+ * \brief Tensor convolution class.
26
+ *
27
+ *
28
+ */
29
+
30
+ enum class convolution_type { CONV1D, CONV2D, CONV3D };
31
+ template <typename Evaluator, typename CoeffReturnType, typename KernelType, typename Index, typename InputDims,
32
+ typename Kernel_accessor, typename Buffer_accessor, convolution_type Conv_Dim>
33
+ struct EigenConvolutionKernel;
34
+ template <typename Evaluator, typename CoeffReturnType, typename KernelType, typename Index, typename InputDims,
35
+ typename Kernel_accessor, typename Buffer_accessor>
36
+ struct EigenConvolutionKernel<Evaluator, CoeffReturnType, KernelType, Index, InputDims, Kernel_accessor,
37
+ Buffer_accessor, convolution_type::CONV1D> {
38
+ typedef cl::sycl::accessor<CoeffReturnType, 1, cl::sycl::access::mode::read_write, cl::sycl::access::target::local>
39
+ Local_accessor;
40
+ Local_accessor local_acc;
41
+ Evaluator device_evaluator;
42
+ Kernel_accessor kernel_filter;
43
+ Buffer_accessor buffer_acc;
44
+ internal::IndexMapper<Index, InputDims, 1, Evaluator::Layout> indexMapper;
45
+ const size_t kernelSize;
46
+ const cl::sycl::range<2> input_range;
47
+ EigenConvolutionKernel(Local_accessor local_acc_, Evaluator device_evaluator_, Kernel_accessor kernel_filter_,
48
+ Buffer_accessor buffer_acc_,
49
+ internal::IndexMapper<Index, InputDims, 1, Evaluator::Layout> indexMapper_,
50
+ const size_t kernelSize_, const cl::sycl::range<2> input_range_)
51
+ : local_acc(local_acc_),
52
+ device_evaluator(device_evaluator_),
53
+ kernel_filter(kernel_filter_),
54
+ buffer_acc(buffer_acc_),
55
+ indexMapper(indexMapper_),
56
+ kernelSize(kernelSize_),
57
+ input_range(input_range_) {}
58
+
59
+ template <typename BooleanDim2>
60
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool boundary_check(const BooleanDim2 boolean_check) const {
61
+ return (boolean_check[0] && boolean_check[1]);
62
+ }
63
+ void operator()(cl::sycl::nd_item<2> itemID) const {
64
+ auto buffer_ptr = buffer_acc;
65
+ auto kernel_ptr = kernel_filter;
66
+ // the required row to be calculated for the for each plane in shered memory
67
+ const size_t num_input = (itemID.get_local_range()[0] + kernelSize - 1);
68
+ const size_t plane_kernel_offset = itemID.get_local_id(1) * num_input;
69
+ const size_t input_offset = itemID.get_group(0) * itemID.get_local_range()[0];
70
+ const size_t plane_tensor_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(itemID.get_global_id(1));
71
+ /// fill the shared memory
72
+ for (size_t i = itemID.get_local_id(0); i < num_input; i += itemID.get_local_range()[0]) {
73
+ const size_t local_index = i + plane_kernel_offset;
74
+ const size_t tensor_index =
75
+ plane_tensor_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(i + input_offset);
76
+
77
+ local_acc[local_index] =
78
+ (((i + input_offset) < (input_range[0] + kernelSize - 1)) && itemID.get_global_id(1) < input_range[1])
79
+ ? device_evaluator.coeff(tensor_index)
80
+ : CoeffReturnType(0);
81
+ }
82
+
83
+ itemID.barrier(cl::sycl::access::fence_space::local_space);
84
+
85
+ // calculate the convolution // output start x
86
+ const size_t first_output_start = itemID.get_group(0) * (itemID.get_local_range()[0]);
87
+ if (boundary_check(itemID.get_global_id() < input_range)) {
88
+ CoeffReturnType result = static_cast<CoeffReturnType>(0);
89
+ const size_t index = plane_kernel_offset + itemID.get_local_id(0);
90
+ for (size_t k = 0; k < kernelSize; ++k) {
91
+ result += (local_acc[k + index] * kernel_ptr[k]);
92
+ }
93
+ const size_t tensor_index =
94
+ indexMapper.mapGpuOutputPlaneToTensorOutputOffset(itemID.get_global_id(1)) +
95
+ indexMapper.mapGpuOutputKernelToTensorOutputOffset(itemID.get_local_id(0) + first_output_start);
96
+ buffer_ptr[tensor_index] = result;
97
+ }
98
+ }
99
+ };
100
+
101
+ template <typename Evaluator, typename CoeffReturnType, typename KernelType, typename Index, typename InputDims,
102
+ typename Kernel_accessor, typename Buffer_accessor>
103
+ struct EigenConvolutionKernel<Evaluator, CoeffReturnType, KernelType, Index, InputDims, Kernel_accessor,
104
+ Buffer_accessor, convolution_type::CONV2D> {
105
+ typedef cl::sycl::accessor<CoeffReturnType, 1, cl::sycl::access::mode::read_write, cl::sycl::access::target::local>
106
+ Local_accessor;
107
+ Local_accessor local_acc;
108
+ Evaluator device_evaluator;
109
+ Kernel_accessor kernel_filter;
110
+ Buffer_accessor buffer_acc;
111
+ internal::IndexMapper<Index, InputDims, 2, Evaluator::Layout> indexMapper;
112
+ const cl::sycl::range<2> kernel_size;
113
+ const cl::sycl::range<3> input_range;
114
+ EigenConvolutionKernel(Local_accessor local_acc_, Evaluator device_evaluator_, Kernel_accessor kernel_filter_,
115
+ Buffer_accessor buffer_acc_,
116
+ internal::IndexMapper<Index, InputDims, 2, Evaluator::Layout> indexMapper_,
117
+ const cl::sycl::range<2> kernel_size_, const cl::sycl::range<3> input_range_)
118
+ : local_acc(local_acc_),
119
+ device_evaluator(device_evaluator_),
120
+ kernel_filter(kernel_filter_),
121
+ buffer_acc(buffer_acc_),
122
+ indexMapper(indexMapper_),
123
+ kernel_size(kernel_size_),
124
+ input_range(input_range_) {}
125
+ template <typename BooleanDim3>
126
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool boundary_check(const BooleanDim3 boolean_check) const {
127
+ return (boolean_check[0] && boolean_check[1] && boolean_check[2]);
128
+ }
129
+
130
+ void operator()(cl::sycl::nd_item<3> itemID) const {
131
+ auto buffer_ptr = buffer_acc;
132
+ auto kernel_ptr = kernel_filter;
133
+ // the required row to be calculated for the for each plane in shered memory
134
+ const auto num_input = cl::sycl::range<2>{
135
+ (cl::sycl::range<2>(itemID.get_local_range()[0], itemID.get_local_range()[1]) + kernel_size - 1)};
136
+
137
+ const size_t plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(itemID.get_global_id(2));
138
+ const size_t plane_kernel_offset = itemID.get_local_id(2) * num_input[1];
139
+
140
+ const auto input_offset = cl::sycl::range<2>{itemID.get_group(0) * itemID.get_local_range()[0],
141
+ itemID.get_group(1) * itemID.get_local_range()[1]};
142
+
143
+ // fill the local memory
144
+ bool in_range_dim2 = itemID.get_global_id(2) < input_range[2];
145
+ for (size_t j = itemID.get_local_id(1); j < num_input[1]; j += itemID.get_local_range()[1]) {
146
+ const size_t local_input_offset = num_input[0] * (j + plane_kernel_offset);
147
+ bool in_range_dim1 = ((j + input_offset[1]) < (input_range[1] + kernel_size[1] - 1));
148
+ for (size_t i = itemID.get_local_id(0); i < num_input[0]; i += itemID.get_local_range()[0]) {
149
+ const size_t local_index = i + local_input_offset;
150
+ const size_t tensor_index = plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(
151
+ i + input_offset[0], j + input_offset[1]);
152
+ local_acc[local_index] = (((i + input_offset[0]) < (input_range[0] + kernel_size[0] - 1)) &&
153
+ in_range_dim1 && in_range_dim2)
154
+ ? device_evaluator.coeff(tensor_index)
155
+ : CoeffReturnType(0);
156
+ }
157
+ }
158
+
159
+ itemID.barrier(cl::sycl::access::fence_space::local_space);
160
+
161
+ // output offset start for each thread
162
+ const auto output_offset = cl::sycl::range<2>{itemID.get_group(0) * itemID.get_local_range()[0],
163
+ itemID.get_group(1) * itemID.get_local_range()[1]};
164
+
165
+ if (boundary_check(itemID.get_global_id() < input_range)) {
166
+ CoeffReturnType result = static_cast<CoeffReturnType>(0);
167
+
168
+ for (size_t j = 0; j < kernel_size[1]; j++) {
169
+ size_t kernel_offset = kernel_size[0] * j;
170
+ const size_t index =
171
+ (num_input[0] * (plane_kernel_offset + j + itemID.get_local_id(1))) + itemID.get_local_id(0);
172
+ for (size_t i = 0; i < kernel_size[0]; i++) {
173
+ result += (local_acc[i + index] * kernel_ptr[i + kernel_offset]);
174
+ }
175
+ }
176
+ const size_t tensor_index =
177
+ indexMapper.mapGpuOutputPlaneToTensorOutputOffset(itemID.get_global_id(2)) +
178
+ indexMapper.mapGpuOutputKernelToTensorOutputOffset(itemID.get_local_id(0) + output_offset[0],
179
+ itemID.get_local_id(1) + output_offset[1]);
180
+
181
+ buffer_ptr[tensor_index] = result;
182
+ }
183
+ }
184
+ };
185
+
186
+ template <typename Evaluator, typename CoeffReturnType, typename KernelType, typename Index, typename InputDims,
187
+ typename Kernel_accessor, typename Buffer_accessor>
188
+ struct EigenConvolutionKernel<Evaluator, CoeffReturnType, KernelType, Index, InputDims, Kernel_accessor,
189
+ Buffer_accessor, convolution_type::CONV3D> {
190
+ typedef cl::sycl::accessor<CoeffReturnType, 1, cl::sycl::access::mode::read_write, cl::sycl::access::target::local>
191
+ Local_accessor;
192
+ Local_accessor local_acc;
193
+ Evaluator device_evaluator;
194
+ Kernel_accessor kernel_filter;
195
+ Buffer_accessor buffer_acc;
196
+ internal::IndexMapper<Index, InputDims, 3, Evaluator::Layout> indexMapper;
197
+ const cl::sycl::range<3> kernel_size;
198
+ const cl::sycl::range<3> input_range;
199
+ const size_t numP;
200
+
201
+ EigenConvolutionKernel(Local_accessor local_acc_, Evaluator device_evaluator_, Kernel_accessor kernel_filter_,
202
+ Buffer_accessor buffer_acc_,
203
+ internal::IndexMapper<Index, InputDims, 3, Evaluator::Layout> indexMapper_,
204
+ const cl::sycl::range<3> kernel_size_, const cl::sycl::range<3> input_range_,
205
+ const size_t numP_)
206
+ : local_acc(local_acc_),
207
+ device_evaluator(device_evaluator_),
208
+ kernel_filter(kernel_filter_),
209
+ buffer_acc(buffer_acc_),
210
+ indexMapper(indexMapper_),
211
+ kernel_size(kernel_size_),
212
+ input_range(input_range_),
213
+ numP(numP_) {}
214
+ template <typename BooleanDim3>
215
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool boundary_check(const BooleanDim3 boolean_check) const {
216
+ return (boolean_check[0] && boolean_check[1] && boolean_check[2]);
217
+ }
218
+ void operator()(cl::sycl::nd_item<3> itemID) const {
219
+ auto buffer_ptr = buffer_acc;
220
+ auto kernel_ptr = kernel_filter;
221
+ const auto num_input = cl::sycl::range<3>{itemID.get_local_range() + kernel_size - 1};
222
+
223
+ const auto input_offset = cl::sycl::range<3>{itemID.get_group().get_id() * itemID.get_local_range()};
224
+
225
+ const auto output_offset =
226
+ cl::sycl::range<3>{itemID.get_group().get_id() * itemID.get_local_range() + itemID.get_local_id()};
227
+
228
+ for (size_t p = 0; p < numP; p++) {
229
+ /// fill the shared memory
230
+ const size_t plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(p);
231
+ for (size_t k = itemID.get_local_id(2); k < num_input[2]; k += itemID.get_local_range()[2]) {
232
+ size_t local_index_dim2 = num_input[0] * num_input[1] * k;
233
+ bool cond_k_dim = (k + input_offset[2] < (input_range[2] + kernel_size[2] - 1));
234
+ for (size_t j = itemID.get_local_id(1); j < num_input[1]; j += itemID.get_local_range()[1]) {
235
+ bool cond_j_dim = cond_k_dim && (j + input_offset[1] < (input_range[1] + kernel_size[1] - 1));
236
+ size_t local_index_dim1 = (num_input[0] * j) + local_index_dim2;
237
+ for (size_t i = itemID.get_local_id(0); i < num_input[0]; i += itemID.get_local_range()[0]) {
238
+ bool conds = cond_j_dim && (i + input_offset[0] < (input_range[0] + kernel_size[0] - 1));
239
+ const size_t local_index = local_index_dim1 + i;
240
+ const size_t tensor_index =
241
+ plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(
242
+ i + input_offset[0], j + input_offset[1], k + input_offset[2]);
243
+ local_acc[local_index] = conds ? device_evaluator.coeff(tensor_index) : CoeffReturnType(0);
244
+ }
245
+ }
246
+ }
247
+ itemID.barrier(cl::sycl::access::fence_space::local_space);
248
+
249
+ // calculate the convolution
250
+
251
+ if (boundary_check(itemID.get_global_id() < input_range)) {
252
+ CoeffReturnType result = static_cast<CoeffReturnType>(0);
253
+ for (size_t k = 0; k < kernel_size[2]; k++) {
254
+ for (size_t j = 0; j < kernel_size[1]; j++) {
255
+ for (size_t i = 0; i < kernel_size[0]; i++) {
256
+ const size_t kernel_index = i + kernel_size[0] * (j + kernel_size[1] * k);
257
+ const size_t local_index =
258
+ ((i + itemID.get_local_id(0)) +
259
+ num_input[0] * ((j + itemID.get_local_id(1)) + num_input[1] * (k + itemID.get_local_id(2))));
260
+
261
+ result += (local_acc[local_index] * kernel_ptr[kernel_index]);
262
+ }
263
+ }
264
+ }
265
+ const size_t tensor_index =
266
+ indexMapper.mapGpuOutputPlaneToTensorOutputOffset(p) +
267
+ indexMapper.mapGpuOutputKernelToTensorOutputOffset(output_offset[0], output_offset[1], output_offset[2]);
268
+ buffer_ptr[tensor_index] = result;
269
+ }
270
+
271
+ itemID.barrier(cl::sycl::access::fence_space::local_space);
272
+ }
273
+ }
274
+ };
275
+
276
+ template <typename Indices, typename InputArgType, typename KernelArgType>
277
+ struct TensorEvaluator<const TensorConvolutionOp<Indices, InputArgType, KernelArgType>, Eigen::SyclDevice> {
278
+ typedef TensorConvolutionOp<Indices, InputArgType, KernelArgType> XprType;
279
+
280
+ static constexpr int NumDims =
281
+ internal::array_size<typename TensorEvaluator<InputArgType, Eigen::SyclDevice>::Dimensions>::value;
282
+ static constexpr int NumKernelDims = internal::array_size<Indices>::value;
283
+ typedef typename XprType::Index Index;
284
+ typedef DSizes<Index, NumDims> Dimensions;
285
+ typedef typename TensorEvaluator<KernelArgType, Eigen::SyclDevice>::Dimensions KernelDimensions;
286
+ typedef const Eigen::SyclDevice Device;
287
+ typedef typename XprType::CoeffReturnType CoeffReturnType;
288
+ typedef typename PacketType<CoeffReturnType, Eigen::SyclDevice>::type PacketReturnType;
289
+ typedef typename InputArgType::Scalar Scalar;
290
+ static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
291
+ typedef StorageMemory<CoeffReturnType, Eigen::SyclDevice> Storage;
292
+ typedef typename Storage::Type EvaluatorPointerType;
293
+ typedef StorageMemory<const CoeffReturnType, Eigen::SyclDevice> KernelStorage;
294
+
295
+ static constexpr int Layout = TensorEvaluator<InputArgType, Eigen::SyclDevice>::Layout;
296
+ enum {
297
+ IsAligned = TensorEvaluator<InputArgType, Eigen::SyclDevice>::IsAligned &
298
+ TensorEvaluator<KernelArgType, Eigen::SyclDevice>::IsAligned,
299
+ PacketAccess = false,
300
+ BlockAccess = false,
301
+ PreferBlockAccess = false,
302
+ CoordAccess = false, // to be implemented
303
+ RawAccess = false
304
+ };
305
+
306
+ //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
307
+ typedef internal::TensorBlockNotImplemented TensorBlock;
308
+ //===--------------------------------------------------------------------===//
309
+
310
+ TensorEvaluator(const XprType &op, const Eigen::SyclDevice &device)
311
+ : m_inputImpl(op.inputExpression(), device),
312
+ m_kernelArg(op.kernelExpression()),
313
+ m_kernelImpl(op.kernelExpression(), device),
314
+ m_indices(op.indices()),
315
+ m_buf(NULL),
316
+ m_kernel(NULL),
317
+ m_local_kernel(false),
318
+ m_device(device) {
319
+ EIGEN_STATIC_ASSERT((static_cast<int>(TensorEvaluator<InputArgType, Eigen::SyclDevice>::Layout) ==
320
+ static_cast<int>(TensorEvaluator<KernelArgType, Eigen::SyclDevice>::Layout)),
321
+ YOU_MADE_A_PROGRAMMING_MISTAKE);
322
+
323
+ const typename TensorEvaluator<InputArgType, Eigen::SyclDevice>::Dimensions &input_dims = m_inputImpl.dimensions();
324
+ const typename TensorEvaluator<KernelArgType, Eigen::SyclDevice>::Dimensions &kernel_dims =
325
+ m_kernelImpl.dimensions();
326
+
327
+ m_dimensions = m_inputImpl.dimensions();
328
+ for (int i = 0; i < NumKernelDims; ++i) {
329
+ const Index index = op.indices()[i];
330
+ const Index input_dim = input_dims[index];
331
+ const Index kernel_dim = kernel_dims[i];
332
+ const Index result_dim = input_dim - kernel_dim + 1;
333
+ m_dimensions[index] = result_dim;
334
+ }
335
+ }
336
+
337
+ EIGEN_DEVICE_FUNC const Dimensions &dimensions() const { return m_dimensions; }
338
+
339
+ EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) {
340
+ preloadKernel();
341
+ m_inputImpl.evalSubExprsIfNeeded(NULL);
342
+ if (data) {
343
+ executeEval(data);
344
+ return false;
345
+ } else {
346
+ m_buf = (EvaluatorPointerType)m_device.get(
347
+ (Scalar *)m_device.allocate_temp(dimensions().TotalSize() * sizeof(Scalar)));
348
+ executeEval(m_buf);
349
+ return true;
350
+ }
351
+ }
352
+
353
+ EIGEN_STRONG_INLINE void cleanup() {
354
+ m_inputImpl.cleanup();
355
+ if (m_buf) {
356
+ m_device.deallocate_temp(m_buf);
357
+ m_buf = NULL;
358
+ }
359
+ if (m_local_kernel) {
360
+ m_device.deallocate_temp(m_kernel);
361
+ m_local_kernel = false;
362
+ }
363
+ m_kernel = NULL;
364
+ }
365
+ /// used by sycl in order to build the sycl buffer
366
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Device &device() const { return m_device; }
367
+ /// used by sycl in order to build the sycl buffer
368
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EvaluatorPointerType data() const { return m_buf; }
369
+
370
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void preloadKernel() {
371
+ // Don't make a local copy of the kernel unless we have to (i.e. it's an
372
+ // expression that needs to be evaluated)
373
+ typename KernelStorage::Type in_place = m_kernelImpl.data();
374
+ if (in_place) {
375
+ m_kernel = in_place;
376
+ m_local_kernel = false;
377
+ } else {
378
+ ptrdiff_t kernel_sz = m_kernelImpl.dimensions().TotalSize() * sizeof(Scalar);
379
+ EvaluatorPointerType local = (EvaluatorPointerType)m_device.get((Scalar *)m_device.allocate_temp(kernel_sz));
380
+ typedef TensorEvalToOp<const KernelArgType> EvalTo;
381
+ EvalTo evalToTmp(m_device.get(local), m_kernelArg);
382
+ const bool PacketAccess = internal::IsVectorizable<Eigen::SyclDevice, KernelArgType>::value;
383
+ internal::TensorExecutor<const EvalTo, Eigen::SyclDevice, PacketAccess>::run(evalToTmp, m_device);
384
+ m_kernel = local;
385
+ m_local_kernel = true;
386
+ }
387
+ }
388
+
389
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void executeEval(EvaluatorPointerType data) const {
390
+ typedef TensorEvaluator<InputArgType, Eigen::SyclDevice> InputEvaluator;
391
+ typedef typename InputEvaluator::Dimensions InputDims;
392
+ switch (NumKernelDims) {
393
+ case 1: {
394
+ const size_t numX = dimensions()[m_indices[0]];
395
+ const size_t numP = dimensions().TotalSize() / numX;
396
+ const auto input_dim = std::array<size_t, 2>{numX, numP};
397
+ auto global_range = cl::sycl::range<2>{1, 1};
398
+ auto local_range = cl::sycl::range<2>{1, 1};
399
+ const size_t kernel_size = m_kernelImpl.dimensions().TotalSize();
400
+
401
+ m_device.parallel_for_setup(input_dim, global_range, local_range);
402
+ const size_t local_memory_size = (local_range[0] + kernel_size - 1) * (local_range[1]);
403
+ gpu_assert(static_cast<unsigned long>(local_memory_size) <= m_device.sharedMemPerBlock());
404
+ const array<Index, 1> indices{{m_indices[0]}};
405
+ const array<Index, 1> kernel_dims{{m_kernelImpl.dimensions()[0]}};
406
+ internal::IndexMapper<Index, InputDims, 1, Layout> indexMapper(m_inputImpl.dimensions(), kernel_dims, indices);
407
+
408
+ typedef EigenConvolutionKernel<InputEvaluator, CoeffReturnType, Scalar, Index, InputDims,
409
+ typename KernelStorage::Type, EvaluatorPointerType, convolution_type::CONV1D>
410
+ ConvKernel;
411
+
412
+ m_device.template binary_kernel_launcher<CoeffReturnType, ConvKernel>(
413
+ m_inputImpl, m_kernel, data, cl::sycl::nd_range<2>(global_range, local_range), local_memory_size,
414
+ indexMapper, kernel_size, cl::sycl::range<2>(input_dim[0], input_dim[1])).wait();
415
+ break;
416
+ }
417
+
418
+ case 2: {
419
+ auto kernel_index = std::array<size_t, 2>{static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 0 : 1,
420
+ static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 1 : 0};
421
+ auto kernel_size = cl::sycl::range<2>{(size_t)m_kernelImpl.dimensions()[kernel_index[0]],
422
+ (size_t)m_kernelImpl.dimensions()[kernel_index[1]]};
423
+ const size_t numX = dimensions()[m_indices[kernel_index[0]]];
424
+ const size_t numY = dimensions()[m_indices[kernel_index[1]]];
425
+ const size_t numP = dimensions().TotalSize() / (numX * numY);
426
+ auto input_dim = std::array<size_t, 3>{numX, numY, numP};
427
+
428
+ auto global_range = cl::sycl::range<3>{1, 1, 1};
429
+ auto local_range = cl::sycl::range<3>{1, 1, 1};
430
+
431
+ m_device.parallel_for_setup(input_dim, global_range, local_range);
432
+
433
+ const size_t local_memory_size =
434
+ (local_range[0] + kernel_size[0] - 1) * (local_range[1] + kernel_size[1] - 1) * local_range[2];
435
+ gpu_assert(static_cast<unsigned long>(local_memory_size) <= m_device.sharedMemPerBlock());
436
+ const array<Index, 2> indices{{m_indices[kernel_index[0]], m_indices[kernel_index[1]]}};
437
+ const array<Index, 2> kernel_dims{
438
+ {m_kernelImpl.dimensions()[kernel_index[0]], m_kernelImpl.dimensions()[kernel_index[1]]}};
439
+ internal::IndexMapper<Index, InputDims, 2, Layout> indexMapper(m_inputImpl.dimensions(), kernel_dims, indices);
440
+ typedef EigenConvolutionKernel<InputEvaluator, CoeffReturnType, Scalar, Index, InputDims,
441
+ typename KernelStorage::Type, EvaluatorPointerType, convolution_type::CONV2D>
442
+ ConvKernel;
443
+ m_device.template binary_kernel_launcher<CoeffReturnType, ConvKernel>(
444
+ m_inputImpl, m_kernel, data, cl::sycl::nd_range<3>(global_range, local_range), local_memory_size,
445
+ indexMapper, kernel_size, cl::sycl::range<3>{input_dim[0], input_dim[1], input_dim[2]}).wait();
446
+ break;
447
+ }
448
+
449
+ case 3: {
450
+ auto kernel_index = std::array<size_t, 3>{static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 0 : 2,
451
+ static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 1 : 1,
452
+ static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 2 : 0};
453
+
454
+ auto kernel_size = cl::sycl::range<3>{(size_t)m_kernelImpl.dimensions()[kernel_index[0]],
455
+ (size_t)m_kernelImpl.dimensions()[kernel_index[1]],
456
+ (size_t)m_kernelImpl.dimensions()[kernel_index[2]]};
457
+
458
+ const size_t numX = dimensions()[m_indices[kernel_index[0]]];
459
+ const size_t numY = dimensions()[m_indices[kernel_index[1]]];
460
+ const size_t numZ = dimensions()[m_indices[kernel_index[2]]];
461
+ auto input_dim = std::array<size_t, 3>{numX, numY, numZ};
462
+ const size_t numP = dimensions().TotalSize() / (numX * numY * numZ);
463
+
464
+ const array<Index, 3> indices{
465
+ {m_indices[kernel_index[0]], m_indices[kernel_index[1]], m_indices[kernel_index[2]]}};
466
+ const array<Index, 3> kernel_dims{{m_kernelImpl.dimensions()[kernel_index[0]],
467
+ m_kernelImpl.dimensions()[kernel_index[1]],
468
+ m_kernelImpl.dimensions()[kernel_index[2]]}};
469
+
470
+ internal::IndexMapper<Index, InputDims, 3, Layout> indexMapper(m_inputImpl.dimensions(), kernel_dims, indices);
471
+
472
+ auto global_range = cl::sycl::range<3>{1, 1, 1};
473
+ auto local_range = cl::sycl::range<3>{1, 1, 1};
474
+
475
+ m_device.parallel_for_setup(input_dim, global_range, local_range);
476
+ auto local_memory_range = (local_range + kernel_size - 1);
477
+ const size_t local_memory_size = local_memory_range[0] * local_memory_range[1] * local_memory_range[2];
478
+
479
+ gpu_assert(static_cast<unsigned long>(local_memory_size) <= m_device.sharedMemPerBlock());
480
+ typedef EigenConvolutionKernel<InputEvaluator, CoeffReturnType, Scalar, Index, InputDims,
481
+ typename KernelStorage::Type, EvaluatorPointerType, convolution_type::CONV3D>
482
+ ConvKernel;
483
+ m_device.template binary_kernel_launcher<CoeffReturnType, ConvKernel>(
484
+ m_inputImpl, m_kernel, data, cl::sycl::nd_range<3>(global_range, local_range), local_memory_size,
485
+ indexMapper, kernel_size, cl::sycl::range<3>(input_dim[0], input_dim[1], input_dim[2]), numP).wait();
486
+ break;
487
+ }
488
+
489
+ default: {
490
+ EIGEN_STATIC_ASSERT((NumKernelDims >= 1 && NumKernelDims <= 3),
491
+ THIS_METHOD_IS_ONLY_FOR_OBJECTS_OF_A_SPECIFIC_SIZE);
492
+ }
493
+ }
494
+ }
495
+
496
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
497
+ eigen_assert(m_buf != NULL);
498
+ eigen_assert(index < m_dimensions.TotalSize());
499
+ return m_buf[index];
500
+ }
501
+
502
+ template <int LoadMode>
503
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(const Index index) const {
504
+ eigen_assert(m_buf != NULL);
505
+ eigen_assert(index < m_dimensions.TotalSize());
506
+ return internal::ploadt<PacketReturnType, LoadMode>(m_buf + index);
507
+ }
508
+
509
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
510
+ // TODO(rmlarsen): FIXME: For now, this is just a copy of the CPU cost
511
+ // model.
512
+ const double kernel_size = m_kernelImpl.dimensions().TotalSize();
513
+ // We ignore the use of fused multiply-add.
514
+ const double convolve_compute_cost = TensorOpCost::AddCost<Scalar>() + TensorOpCost::MulCost<Scalar>();
515
+ const double firstIndex_compute_cost =
516
+ NumDims *
517
+ (2 * TensorOpCost::AddCost<Index>() + 2 * TensorOpCost::MulCost<Index>() + TensorOpCost::DivCost<Index>());
518
+ return TensorOpCost(0, 0, firstIndex_compute_cost, vectorized, PacketSize) +
519
+ kernel_size * (m_inputImpl.costPerCoeff(vectorized) + m_kernelImpl.costPerCoeff(vectorized) +
520
+ TensorOpCost(0, 0, convolve_compute_cost, vectorized, PacketSize));
521
+ }
522
+
523
+
524
+ private:
525
+ // No assignment (copies are needed by the kernels)
526
+ TensorEvaluator &operator=(const TensorEvaluator &);
527
+ TensorEvaluator<InputArgType, Eigen::SyclDevice> m_inputImpl;
528
+ KernelArgType m_kernelArg;
529
+ TensorEvaluator<KernelArgType, Eigen::SyclDevice> m_kernelImpl;
530
+ Indices m_indices;
531
+ Dimensions m_dimensions;
532
+ EvaluatorPointerType m_buf;
533
+ typename KernelStorage::Type m_kernel;
534
+ bool m_local_kernel;
535
+ const Eigen::SyclDevice EIGEN_DEVICE_REF m_device;
536
+ }; // namespace Eigen
537
+
538
+ } // end namespace Eigen
539
+
540
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_H
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCostModel.h ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of Eigen, a lightweight C++ template library
2
+ // for linear algebra.
3
+ //
4
+ // Copyright (C) 2016 Rasmus Munk Larsen <rmlarsen@google.com>
5
+ //
6
+ // This Source Code Form is subject to the terms of the Mozilla
7
+ // Public License v. 2.0. If a copy of the MPL was not distributed
8
+ // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
+
10
+ #ifndef EIGEN_CXX11_TENSOR_TENSOR_COST_MODEL_H
11
+ #define EIGEN_CXX11_TENSOR_TENSOR_COST_MODEL_H
12
+
13
+ #include "./InternalHeaderCheck.h"
14
+
15
+ namespace Eigen {
16
+
17
+ /** \class TensorEvaluator
18
+ * \ingroup CXX11_Tensor_Module
19
+ *
20
+ * \brief A cost model used to limit the number of threads used for evaluating
21
+ * tensor expression.
22
+ *
23
+ */
24
+
25
+ // Class storing the cost of evaluating a tensor expression in terms of the
26
+ // estimated number of operand bytes loads, bytes stored, and compute cycles.
27
+ class TensorOpCost {
28
+ public:
29
+ // TODO(rmlarsen): Fix the scalar op costs in Eigen proper. Even a simple
30
+ // model based on minimal reciprocal throughput numbers from Intel or
31
+ // Agner Fog's tables would be better than what is there now.
32
+ template <typename ArgType>
33
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int MulCost() {
34
+ return internal::functor_traits<
35
+ internal::scalar_product_op<ArgType, ArgType> >::Cost;
36
+ }
37
+ template <typename ArgType>
38
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int AddCost() {
39
+ return internal::functor_traits<internal::scalar_sum_op<ArgType> >::Cost;
40
+ }
41
+ template <typename ArgType>
42
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int DivCost() {
43
+ return internal::functor_traits<
44
+ internal::scalar_quotient_op<ArgType, ArgType> >::Cost;
45
+ }
46
+ template <typename ArgType>
47
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int ModCost() {
48
+ return internal::functor_traits<internal::scalar_mod_op<ArgType> >::Cost;
49
+ }
50
+ template <typename SrcType, typename TargetType>
51
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int CastCost() {
52
+ return internal::functor_traits<
53
+ internal::scalar_cast_op<SrcType, TargetType> >::Cost;
54
+ }
55
+
56
+ EIGEN_DEVICE_FUNC
57
+ TensorOpCost() : bytes_loaded_(0), bytes_stored_(0), compute_cycles_(0) {}
58
+ EIGEN_DEVICE_FUNC
59
+ TensorOpCost(double bytes_loaded, double bytes_stored, double compute_cycles)
60
+ : bytes_loaded_(bytes_loaded),
61
+ bytes_stored_(bytes_stored),
62
+ compute_cycles_(compute_cycles) {}
63
+
64
+ EIGEN_DEVICE_FUNC
65
+ TensorOpCost(double bytes_loaded, double bytes_stored, double compute_cycles,
66
+ bool vectorized, double packet_size)
67
+ : bytes_loaded_(bytes_loaded),
68
+ bytes_stored_(bytes_stored),
69
+ compute_cycles_(vectorized ? compute_cycles / packet_size
70
+ : compute_cycles) {
71
+ eigen_assert(bytes_loaded >= 0 && (numext::isfinite)(bytes_loaded));
72
+ eigen_assert(bytes_stored >= 0 && (numext::isfinite)(bytes_stored));
73
+ eigen_assert(compute_cycles >= 0 && (numext::isfinite)(compute_cycles));
74
+ }
75
+
76
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double bytes_loaded() const {
77
+ return bytes_loaded_;
78
+ }
79
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double bytes_stored() const {
80
+ return bytes_stored_;
81
+ }
82
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double compute_cycles() const {
83
+ return compute_cycles_;
84
+ }
85
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double total_cost(
86
+ double load_cost, double store_cost, double compute_cost) const {
87
+ return load_cost * bytes_loaded_ + store_cost * bytes_stored_ +
88
+ compute_cost * compute_cycles_;
89
+ }
90
+
91
+ // Drop memory access component. Intended for cases when memory accesses are
92
+ // sequential or are completely masked by computations.
93
+ EIGEN_DEVICE_FUNC void dropMemoryCost() {
94
+ bytes_loaded_ = 0;
95
+ bytes_stored_ = 0;
96
+ }
97
+
98
+ // TODO(rmlarsen): Define min in terms of total cost, not elementwise.
99
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost cwiseMin(
100
+ const TensorOpCost& rhs) const {
101
+ double bytes_loaded = numext::mini(bytes_loaded_, rhs.bytes_loaded());
102
+ double bytes_stored = numext::mini(bytes_stored_, rhs.bytes_stored());
103
+ double compute_cycles = numext::mini(compute_cycles_, rhs.compute_cycles());
104
+ return TensorOpCost(bytes_loaded, bytes_stored, compute_cycles);
105
+ }
106
+
107
+ // TODO(rmlarsen): Define max in terms of total cost, not elementwise.
108
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost cwiseMax(
109
+ const TensorOpCost& rhs) const {
110
+ double bytes_loaded = numext::maxi(bytes_loaded_, rhs.bytes_loaded());
111
+ double bytes_stored = numext::maxi(bytes_stored_, rhs.bytes_stored());
112
+ double compute_cycles = numext::maxi(compute_cycles_, rhs.compute_cycles());
113
+ return TensorOpCost(bytes_loaded, bytes_stored, compute_cycles);
114
+ }
115
+
116
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost& operator+=(
117
+ const TensorOpCost& rhs) {
118
+ bytes_loaded_ += rhs.bytes_loaded();
119
+ bytes_stored_ += rhs.bytes_stored();
120
+ compute_cycles_ += rhs.compute_cycles();
121
+ return *this;
122
+ }
123
+
124
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost& operator*=(double rhs) {
125
+ bytes_loaded_ *= rhs;
126
+ bytes_stored_ *= rhs;
127
+ compute_cycles_ *= rhs;
128
+ return *this;
129
+ }
130
+
131
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE friend TensorOpCost operator+(
132
+ TensorOpCost lhs, const TensorOpCost& rhs) {
133
+ lhs += rhs;
134
+ return lhs;
135
+ }
136
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE friend TensorOpCost operator*(
137
+ TensorOpCost lhs, double rhs) {
138
+ lhs *= rhs;
139
+ return lhs;
140
+ }
141
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE friend TensorOpCost operator*(
142
+ double lhs, TensorOpCost rhs) {
143
+ rhs *= lhs;
144
+ return rhs;
145
+ }
146
+
147
+ friend std::ostream& operator<<(std::ostream& os, const TensorOpCost& tc) {
148
+ return os << "[bytes_loaded = " << tc.bytes_loaded()
149
+ << ", bytes_stored = " << tc.bytes_stored()
150
+ << ", compute_cycles = " << tc.compute_cycles() << "]";
151
+ }
152
+
153
+ private:
154
+ double bytes_loaded_;
155
+ double bytes_stored_;
156
+ double compute_cycles_;
157
+ };
158
+
159
+ // TODO(rmlarsen): Implement a policy that chooses an "optimal" number of theads
160
+ // in [1:max_threads] instead of just switching multi-threading off for small
161
+ // work units.
162
+ template <typename Device>
163
+ class TensorCostModel {
164
+ public:
165
+ // Scaling from Eigen compute cost to device cycles.
166
+ static const int kDeviceCyclesPerComputeCycle = 1;
167
+
168
+ // Costs in device cycles.
169
+ static const int kStartupCycles = 100000;
170
+ static const int kPerThreadCycles = 100000;
171
+ static const int kTaskSize = 40000;
172
+
173
+ // Returns the number of threads in [1:max_threads] to use for
174
+ // evaluating an expression with the given output size and cost per
175
+ // coefficient.
176
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int numThreads(
177
+ double output_size, const TensorOpCost& cost_per_coeff, int max_threads) {
178
+ double cost = totalCost(output_size, cost_per_coeff);
179
+ double threads = (cost - kStartupCycles) / kPerThreadCycles + 0.9;
180
+ // Make sure we don't invoke undefined behavior when we convert to an int.
181
+ threads = numext::mini<double>(threads, GenericNumTraits<int>::highest());
182
+ return numext::mini(max_threads,
183
+ numext::maxi<int>(1, static_cast<int>(threads)));
184
+ }
185
+
186
+ // taskSize assesses parallel task size.
187
+ // Value of 1.0 means ideal parallel task size. Values < 1.0 mean that task
188
+ // granularity needs to be increased to mitigate parallelization overheads.
189
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double taskSize(
190
+ double output_size, const TensorOpCost& cost_per_coeff) {
191
+ return totalCost(output_size, cost_per_coeff) / kTaskSize;
192
+ }
193
+
194
+ static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double totalCost(
195
+ double output_size, const TensorOpCost& cost_per_coeff) {
196
+ // Cost of memory fetches from L2 cache. 64 is typical cache line size.
197
+ // 11 is L2 cache latency on Haswell.
198
+ // We don't know whether data is in L1, L2 or L3. But we are most interested
199
+ // in single-threaded computational time around 100us-10ms (smaller time
200
+ // is too small for parallelization, larger time is not interesting
201
+ // either because we are probably using all available threads already).
202
+ // And for the target time range, L2 seems to be what matters. Data set
203
+ // fitting into L1 is too small to take noticeable time. Data set fitting
204
+ // only into L3 presumably will take more than 10ms to load and process.
205
+ const double kLoadCycles = 1.0 / 64 * 11;
206
+ const double kStoreCycles = 1.0 / 64 * 11;
207
+ // Scaling from Eigen compute cost to device cycles.
208
+ return output_size *
209
+ cost_per_coeff.total_cost(kLoadCycles, kStoreCycles,
210
+ kDeviceCyclesPerComputeCycle);
211
+ }
212
+ };
213
+
214
+ } // namespace Eigen
215
+
216
+ #endif // EIGEN_CXX11_TENSOR_TENSOR_COST_MODEL_H