jasonfan commited on
Commit
9f01e18
·
verified ·
1 Parent(s): 1421535

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/tensorflow/core/kernels/batching_util/adaptive_shared_batch_scheduler.h +870 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/batch_input_task.h +266 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/batch_resource_base.h +317 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/batch_scheduler.h +332 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/bounded_executor.h +80 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/concat_split_util.h +252 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/input_split_metadata.h +55 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/periodic_function.h +130 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/shared_batch_scheduler.h +1290 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/threadsafe_status.h +57 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/warmup.h +132 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/batch_dataset_op.h +48 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/cache_dataset_ops.h +52 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/cache_ops.h +99 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/concatenate_dataset_op.h +44 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/dataset_ops.h +74 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/assert_cardinality_dataset_op.h +48 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/assert_next_dataset_op.h +48 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/assert_prev_dataset_op.h +48 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/auto_shard_dataset_op.h +53 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/compression_ops.h +49 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/directed_interleave_dataset_op.h +50 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/list_dataset_op.h +46 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/lmdb_dataset_op.h +44 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/load_dataset_op.h +62 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/map_and_batch_dataset_op.h +61 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/parallel_interleave_dataset_op.h +67 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/random_access_ops.h +64 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/random_dataset_op.h +54 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/sampling_dataset_op.h +53 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/save_dataset_op.h +113 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/snapshot_dataset_op.h +95 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/sql/driver_manager.h +43 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/sql/query_connection.h +73 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/sql/sqlite_query_connection.h +58 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/threadpool_dataset_op.h +74 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/unique_dataset_op.h +46 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/filter_dataset_op.h +48 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/finalize_dataset_op.h +60 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/fixed_length_record_dataset_op.h +46 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/flat_map_dataset_op.h +51 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/generator_dataset_op.h +59 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/get_options_op.h +36 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/interleave_dataset_op.h +53 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/iterator_ops.h +337 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/map_dataset_op.h +55 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/map_defun_op.h +76 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/model_dataset_op.h +87 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/optimize_dataset_op.h +97 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/optional_ops.h +93 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/adaptive_shared_batch_scheduler.h ADDED
@@ -0,0 +1,870 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_ADAPTIVE_SHARED_BATCH_SCHEDULER_H_
17
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_ADAPTIVE_SHARED_BATCH_SCHEDULER_H_
18
+
19
+ #include <algorithm>
20
+ #include <atomic>
21
+ #include <functional>
22
+ #include <memory>
23
+ #include <random>
24
+ #include <unordered_map>
25
+ #include <vector>
26
+
27
+ #include "absl/types/optional.h"
28
+ #include "tensorflow/core/kernels/batching_util/batch_scheduler.h"
29
+ #include "tensorflow/core/kernels/batching_util/periodic_function.h"
30
+ #include "tensorflow/core/lib/core/errors.h"
31
+ #include "tensorflow/core/lib/core/status.h"
32
+ #include "tensorflow/core/lib/core/threadpool.h"
33
+ #include "tensorflow/core/platform/byte_order.h"
34
+ #include "tensorflow/core/platform/cpu_info.h"
35
+ #include "tensorflow/core/platform/env.h"
36
+ #include "tensorflow/core/platform/errors.h"
37
+ #include "tensorflow/core/platform/thread_annotations.h"
38
+ #include "tensorflow/core/platform/threadpool_interface.h"
39
+ #include "tensorflow/core/platform/types.h"
40
+ #include "tensorflow/core/profiler/lib/connected_traceme.h"
41
+
42
+ namespace tensorflow {
43
+ namespace serving {
44
+ namespace internal {
45
+ template <typename TaskType>
46
+ class ASBSBatch;
47
+
48
+ template <typename TaskType>
49
+ class ASBSQueue;
50
+ } // namespace internal
51
+
52
+ // Shared batch scheduler designed to minimize latency. The scheduler keeps
53
+ // track of a number of queues (one per model or model version) which are
54
+ // continuously enqueuing requests. The scheduler groups the requests into
55
+ // batches which it periodically sends off for processing (see
56
+ // shared_batch_scheduler.h for more details). AdaptiveSharedBatchScheduler
57
+ // (ASBS) prioritizes batches primarily by age (i.e. the batch's oldest request)
58
+ // along with a configurable preference for scheduling larger batches first.
59
+ //
60
+ //
61
+ // ASBS tries to keep the system busy by maintaining an adjustable number of
62
+ // concurrently processed batches. If a new batch is created, and the number of
63
+ // in flight batches is below the target, the next (i.e. oldest) batch is
64
+ // immediately scheduled. Similarly, when a batch finishes processing, the
65
+ // target is rechecked, and another batch may be scheduled. To avoid the need
66
+ // to carefully tune the target for workload, model type, platform, etc, it is
67
+ // dynamically adjusted in order to provide the lowest average latency.
68
+ //
69
+ // Some potential use cases:
70
+ // Hardware Accelerators (GPUs & TPUs) - If some phase of batch processing
71
+ // involves serial processing by a device, from a latency perspective it is
72
+ // desirable to keep the device evenly loaded, avoiding the need to wait for
73
+ // the device to process prior batches.
74
+ // CPU utilization - If the batch processing is cpu dominated, you can reap
75
+ // latency gains when underutilized by increasing the processing rate, but
76
+ // back the rate off when the load increases to avoid overload.
77
+
78
+ template <typename TaskType>
79
+ class AdaptiveSharedBatchScheduler
80
+ : public std::enable_shared_from_this<
81
+ AdaptiveSharedBatchScheduler<TaskType>> {
82
+ public:
83
+ ~AdaptiveSharedBatchScheduler() {
84
+ // Finish processing batches before destroying other class members.
85
+ if (owned_batch_thread_pool_) {
86
+ delete batch_thread_pool_;
87
+ }
88
+ }
89
+
90
+ struct Options {
91
+ // The name to use for the pool of batch threads.
92
+ string thread_pool_name = {"batch_threads"};
93
+ // Number of batch processing threads - the maximum value of
94
+ // in_flight_batches_limit_. It is recommended that this value be set by
95
+ // running the system under load, observing the learned value for
96
+ // in_flight_batches_limit_, and setting this maximum to ~ 2x the value.
97
+ // Under low load, in_flight_batches_limit_ has no substantial effect on
98
+ // latency and therefore undergoes a random walk. Unreasonably large values
99
+ // for num_batch_threads allows for large in_flight_batches_limit_, which
100
+ // will harm latency for some time once load increases again.
101
+ int64_t num_batch_threads = port::MaxParallelism();
102
+ // You can pass a ThreadPool directly rather than the above two
103
+ // parameters. If given, the above two parameers are ignored. Ownership of
104
+ // the threadpool is not transferred.
105
+ thread::ThreadPool* thread_pool = nullptr;
106
+
107
+ // Lower bound for in_flight_batches_limit_. As discussed above, can be used
108
+ // to minimize the damage caused by the random walk under low load.
109
+ int64_t min_in_flight_batches_limit = 1;
110
+ // Although batch selection is primarily based on age, this parameter
111
+ // specifies a preference for larger batches. A full batch will be
112
+ // scheduled before an older, nearly empty batch as long as the age gap is
113
+ // less than full_batch_scheduling_boost_micros. The optimal value for this
114
+ // parameter should be of order the batch processing latency, but must be
115
+ // chosen carefully, as too large a value will harm tail latency.
116
+ int64_t full_batch_scheduling_boost_micros = 0;
117
+ // The environment to use (typically only overridden by test code).
118
+ Env* env = Env::Default();
119
+ // Initial limit for number of batches being concurrently processed.
120
+ // Non-integer values correspond to probabilistic limits - i.e. a value of
121
+ // 3.2 results in an actual cap of 3 80% of the time, and 4 20% of the time.
122
+ double initial_in_flight_batches_limit = 3;
123
+ // Number of batches between adjustments of in_flight_batches_limit. Larger
124
+ // numbers will give less noisy latency measurements, but will be less
125
+ // responsive to changes in workload.
126
+ int64_t batches_to_average_over = 1000;
127
+
128
+ // If true, schedule batches using FIFO policy.
129
+ // Requires that `full_batch_scheduling_boost_micros` is zero.
130
+ // NOTE:
131
+ // A new parameter is introduced (not re-using
132
+ // full_batch_scheduling_boost_micros==zero) for backward compatibility of
133
+ // API.
134
+ bool fifo_scheduling = false;
135
+ };
136
+
137
+ // Ownership is shared between the caller of Create() and any queues created
138
+ // via AddQueue().
139
+ static Status Create(
140
+ const Options& options,
141
+ std::shared_ptr<AdaptiveSharedBatchScheduler<TaskType>>* scheduler);
142
+
143
+ struct QueueOptions {
144
+ // Maximum size of a batch that's formed within
145
+ // `ASBSQueue<TaskType>::Schedule`.
146
+ int max_batch_size = 1000;
147
+ // Maximum size of input task, which is submitted to the queue by
148
+ // calling `ASBSQueue<TaskType>::Schedule` and used to form batches.
149
+ //
150
+ // If specified, it should be larger than or equal to 'max_batch_size'.
151
+ absl::optional<int> max_input_task_size = absl::nullopt;
152
+ // Maximum number of tasks to add to a specific batch.
153
+ absl::optional<int> max_tasks_per_batch = absl::nullopt;
154
+ // Maximum number of enqueued (i.e. non-scheduled) batches.
155
+ int max_enqueued_batches = 10;
156
+ // Amount of time non-full batches must wait before becoming schedulable.
157
+ // A non-zero value can improve performance by limiting the scheduling of
158
+ // nearly empty batches.
159
+ int64_t batch_timeout_micros = 0;
160
+ // If non nullptr, split_input_task_func should split input_task into
161
+ // multiple tasks, the first of which has size first_size and the remaining
162
+ // not exceeding max_size. This function may acquire ownership of input_task
163
+ // and should return a status indicating if the split was successful. Upon
164
+ // success, the caller can assume that all output_tasks will be scheduled.
165
+ // Including this option allows the scheduler to pack batches better and
166
+ // should usually improve overall throughput.
167
+ std::function<Status(std::unique_ptr<TaskType>* input_task, int first_size,
168
+ int max_batch_size,
169
+ std::vector<std::unique_ptr<TaskType>>* output_tasks)>
170
+ split_input_task_func;
171
+
172
+ // If true, the padding will not be appended.
173
+ bool disable_padding = false;
174
+ };
175
+
176
+ using BatchProcessor = std::function<void(std::unique_ptr<Batch<TaskType>>)>;
177
+
178
+ // Adds queue (and its callback) to be managed by this scheduler.
179
+ Status AddQueue(const QueueOptions& options,
180
+ BatchProcessor process_batch_callback,
181
+ std::unique_ptr<BatchScheduler<TaskType>>* queue);
182
+
183
+ double in_flight_batches_limit() {
184
+ mutex_lock l(mu_);
185
+ return in_flight_batches_limit_;
186
+ }
187
+
188
+ private:
189
+ // access to AddBatch, MaybeScheduleClosedBatches, RemoveQueue, GetEnv.
190
+ friend class internal::ASBSQueue<TaskType>;
191
+
192
+ explicit AdaptiveSharedBatchScheduler(const Options& options);
193
+
194
+ // Tracks processing latency and adjusts in_flight_batches_limit to minimize.
195
+ void CallbackWrapper(const internal::ASBSBatch<TaskType>* batch,
196
+ BatchProcessor callback, bool is_express);
197
+
198
+ // Schedules batch if in_flight_batches_limit_ is not met.
199
+ void MaybeScheduleNextBatch() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
200
+
201
+ // Schedules batch using FIFO policy if in_flight_batches_limit_ is not met.
202
+ void MaybeScheduleNextBatchFIFO() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
203
+
204
+ // Schedules all closed batches in batches_ for which an idle thread is
205
+ // available in batch_thread_pool_.
206
+ // Batches scheduled this way are called express batches.
207
+ // Express batches are not limited by in_flight_batches_limit_, and
208
+ // their latencies will not affect in_flight_batches_limit_.
209
+ void MaybeScheduleClosedBatches();
210
+
211
+ void MaybeScheduleClosedBatchesLocked() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
212
+
213
+ void MaybeScheduleClosedBatchesLockedFIFO() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
214
+
215
+ void MaybeAdjustInflightLimit() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
216
+
217
+ // Notifies scheduler of non-empty batch which is eligible for processing.
218
+ void AddBatch(const internal::ASBSBatch<TaskType>* batch);
219
+
220
+ // Removes queue from scheduler.
221
+ void RemoveQueue(const internal::ASBSQueue<TaskType>* queue);
222
+
223
+ Env* GetEnv() const { return options_.env; }
224
+
225
+ const Options options_;
226
+
227
+ // Collection of batches added by AddBatch, ordered by age. Owned by scheduler
228
+ // until they are released for processing.
229
+ std::vector<const internal::ASBSBatch<TaskType>*> batches_ TF_GUARDED_BY(mu_);
230
+
231
+ // Collection of batches added by AddBatch, ordered by age. Owned by
232
+ // scheduler until they are released for processing.
233
+ std::deque<const internal::ASBSBatch<TaskType>*> fifo_batches_
234
+ TF_GUARDED_BY(mu_);
235
+
236
+ // Unowned queues and callbacks added by AddQueue.
237
+ std::unordered_map<const internal::ASBSQueue<TaskType>*, BatchProcessor>
238
+ queues_and_callbacks_ TF_GUARDED_BY(mu_);
239
+
240
+ mutex mu_;
241
+
242
+ // Responsible for running the batch processing callbacks.
243
+ thread::ThreadPool* batch_thread_pool_;
244
+
245
+ bool owned_batch_thread_pool_ = false;
246
+
247
+ // Limit on number of batches which can be concurrently processed.
248
+ // Non-integer values correspond to probabilistic limits - i.e. a value of 3.2
249
+ // results in an actual cap of 3 80% of the time, and 4 20% of the time.
250
+ double in_flight_batches_limit_ TF_GUARDED_BY(mu_);
251
+
252
+ // Number of regular batches currently being processed.
253
+ int64_t in_flight_batches_ TF_GUARDED_BY(mu_) = 0;
254
+ // Number of express batches currently being processed.
255
+ int64_t in_flight_express_batches_ TF_GUARDED_BY(mu_) = 0;
256
+
257
+ // RNG engine and distribution.
258
+ std::default_random_engine rand_engine_;
259
+ std::uniform_real_distribution<double> rand_double_;
260
+
261
+ // Fields controlling the dynamic adjustment of in_flight_batches_limit_.
262
+ // Number of batches since the last in_flight_batches_limit_ adjustment.
263
+ int64_t batch_count_ TF_GUARDED_BY(mu_) = 0;
264
+
265
+ struct DelayStats {
266
+ // Sum of processing latency for batches counted by batch_count_.
267
+ int64_t batch_latency_sum = 0;
268
+ // Average batch latency for previous value of in_flight_batches_limit_.
269
+ double last_avg_latency_ms = 0;
270
+ // Did last_avg_latency_ms decrease from the previous last_avg_latency_ms?
271
+ bool last_latency_decreased = false;
272
+ // Current direction (+-) to adjust in_flight_batches_limit_
273
+ int step_direction = 1;
274
+ };
275
+
276
+ // Delay stats between the creation of a batch and the completion of a
277
+ // batch.
278
+ DelayStats batch_delay_stats_ TF_GUARDED_BY(mu_);
279
+
280
+ // Max adjustment size (as a fraction of in_flight_batches_limit_).
281
+ constexpr static double kMaxStepSizeMultiplier = 0.125; // 1/8;
282
+ // Min adjustment size (as a fraction of in_flight_batches_limit_).
283
+ constexpr static double kMinStepSizeMultiplier = 0.0078125; // 1/128
284
+ // Current adjustment size (as a fraction of in_flight_batches_limit_).
285
+ double step_size_multiplier_ TF_GUARDED_BY(mu_) = kMaxStepSizeMultiplier;
286
+
287
+ AdaptiveSharedBatchScheduler(const AdaptiveSharedBatchScheduler&) = delete;
288
+ void operator=(const AdaptiveSharedBatchScheduler&) = delete;
289
+ };
290
+
291
+ //////////////////////////////////////////////////////////
292
+ // Implementation details follow. API users need not read.
293
+
294
+ namespace internal {
295
+ // Consolidates tasks into batches, passing them off to the
296
+ // AdaptiveSharedBatchScheduler for processing.
297
+ template <typename TaskType>
298
+ class ASBSQueue : public BatchScheduler<TaskType> {
299
+ public:
300
+ using QueueOptions =
301
+ typename AdaptiveSharedBatchScheduler<TaskType>::QueueOptions;
302
+
303
+ ASBSQueue(std::shared_ptr<AdaptiveSharedBatchScheduler<TaskType>> scheduler,
304
+ const QueueOptions& options);
305
+
306
+ ~ASBSQueue() override;
307
+
308
+ // Adds task to current batch. Fails if the task size is larger than the batch
309
+ // size or if the current batch is full and this queue's number of outstanding
310
+ // batches is at its maximum.
311
+ Status Schedule(std::unique_ptr<TaskType>* task) override;
312
+
313
+ // Number of tasks waiting to be scheduled.
314
+ size_t NumEnqueuedTasks() const override;
315
+
316
+ // Number of size 1 tasks which could currently be scheduled without failing.
317
+ size_t SchedulingCapacity() const override;
318
+
319
+ // Notifies queue that a batch is about to be scheduled; the queue should not
320
+ // place any more tasks in this batch.
321
+ void ReleaseBatch(const ASBSBatch<TaskType>* batch);
322
+
323
+ size_t max_task_size() const override { return options_.max_batch_size; }
324
+
325
+ private:
326
+ // Number of size 1 tasks which could currently be scheduled without failing.
327
+ size_t SchedulingCapacityLocked() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
328
+
329
+ // Returns uint64 one greater than was returned by the previous call.
330
+ // Context id is reused after std::numeric_limits<uint64>::max is exhausted.
331
+ static uint64 NewTraceMeContextIdForBatch();
332
+
333
+ std::shared_ptr<AdaptiveSharedBatchScheduler<TaskType>> scheduler_;
334
+ const QueueOptions options_;
335
+ // Owned by scheduler_.
336
+ ASBSBatch<TaskType>* current_batch_ TF_GUARDED_BY(mu_) = nullptr;
337
+ int64_t num_enqueued_batches_ TF_GUARDED_BY(mu_) = 0;
338
+ int64_t num_enqueued_tasks_ TF_GUARDED_BY(mu_) = 0;
339
+ mutable mutex mu_;
340
+ ASBSQueue(const ASBSQueue&) = delete;
341
+ void operator=(const ASBSQueue&) = delete;
342
+ };
343
+
344
+ // Batch which remembers when and by whom it was created.
345
+ template <typename TaskType>
346
+ class ASBSBatch : public Batch<TaskType> {
347
+ public:
348
+ ASBSBatch(ASBSQueue<TaskType>* queue, int64_t creation_time_micros,
349
+ int64_t batch_timeout_micros, uint64 traceme_context_id)
350
+ : queue_(queue),
351
+ creation_time_micros_(creation_time_micros),
352
+ schedulable_time_micros_(creation_time_micros + batch_timeout_micros),
353
+ traceme_context_id_(traceme_context_id) {}
354
+
355
+ ~ASBSBatch() override {}
356
+
357
+ ASBSQueue<TaskType>* queue() const { return queue_; }
358
+
359
+ int64_t creation_time_micros() const { return creation_time_micros_; }
360
+
361
+ int64_t schedulable_time_micros() const { return schedulable_time_micros_; }
362
+
363
+ uint64 traceme_context_id() const { return traceme_context_id_; }
364
+
365
+ private:
366
+ ASBSQueue<TaskType>* queue_;
367
+ const int64_t creation_time_micros_;
368
+ const int64_t schedulable_time_micros_;
369
+ const uint64 traceme_context_id_;
370
+ ASBSBatch(const ASBSBatch&) = delete;
371
+ void operator=(const ASBSBatch&) = delete;
372
+ };
373
+ } // namespace internal
374
+
375
+ // ---------------- AdaptiveSharedBatchScheduler ----------------
376
+
377
+ template <typename TaskType>
378
+ constexpr double AdaptiveSharedBatchScheduler<TaskType>::kMaxStepSizeMultiplier;
379
+
380
+ template <typename TaskType>
381
+ constexpr double AdaptiveSharedBatchScheduler<TaskType>::kMinStepSizeMultiplier;
382
+
383
+ template <typename TaskType>
384
+ Status AdaptiveSharedBatchScheduler<TaskType>::Create(
385
+ const Options& options,
386
+ std::shared_ptr<AdaptiveSharedBatchScheduler<TaskType>>* scheduler) {
387
+ if (options.num_batch_threads < 1) {
388
+ return errors::InvalidArgument("num_batch_threads must be positive; was ",
389
+ options.num_batch_threads);
390
+ }
391
+ if (options.min_in_flight_batches_limit < 1) {
392
+ return errors::InvalidArgument(
393
+ "min_in_flight_batches_limit must be >= 1; was ",
394
+ options.min_in_flight_batches_limit);
395
+ }
396
+ if (options.min_in_flight_batches_limit > options.num_batch_threads) {
397
+ return errors::InvalidArgument(
398
+ "min_in_flight_batches_limit (", options.min_in_flight_batches_limit,
399
+ ") must be <= num_batch_threads (", options.num_batch_threads, ")");
400
+ }
401
+ if (options.full_batch_scheduling_boost_micros < 0) {
402
+ return errors::InvalidArgument(
403
+ "full_batch_scheduling_boost_micros can't be negative; was ",
404
+ options.full_batch_scheduling_boost_micros);
405
+ }
406
+ if (options.initial_in_flight_batches_limit > options.num_batch_threads) {
407
+ return errors::InvalidArgument(
408
+ "initial_in_flight_batches_limit (",
409
+ options.initial_in_flight_batches_limit,
410
+ ") should not be larger than num_batch_threads (",
411
+ options.num_batch_threads, ")");
412
+ }
413
+ if (options.initial_in_flight_batches_limit <
414
+ options.min_in_flight_batches_limit) {
415
+ return errors::InvalidArgument("initial_in_flight_batches_limit (",
416
+ options.initial_in_flight_batches_limit,
417
+ "must be >= min_in_flight_batches_limit (",
418
+ options.min_in_flight_batches_limit, ")");
419
+ }
420
+ if (options.batches_to_average_over < 1) {
421
+ return errors::InvalidArgument(
422
+ "batches_to_average_over should be "
423
+ "greater than or equal to 1; was ",
424
+ options.batches_to_average_over);
425
+ }
426
+ scheduler->reset(new AdaptiveSharedBatchScheduler<TaskType>(options));
427
+ return OkStatus();
428
+ }
429
+
430
+ template <typename TaskType>
431
+ AdaptiveSharedBatchScheduler<TaskType>::AdaptiveSharedBatchScheduler(
432
+ const Options& options)
433
+ : options_(options),
434
+ in_flight_batches_limit_(options.initial_in_flight_batches_limit),
435
+ rand_double_(0.0, 1.0) {
436
+ std::random_device device;
437
+ rand_engine_.seed(device());
438
+ if (options.thread_pool == nullptr) {
439
+ owned_batch_thread_pool_ = true;
440
+ batch_thread_pool_ = new thread::ThreadPool(
441
+ GetEnv(), options.thread_pool_name, options.num_batch_threads);
442
+ } else {
443
+ owned_batch_thread_pool_ = false;
444
+ batch_thread_pool_ = options.thread_pool;
445
+ }
446
+ }
447
+
448
+ template <typename TaskType>
449
+ Status AdaptiveSharedBatchScheduler<TaskType>::AddQueue(
450
+ const QueueOptions& options, BatchProcessor process_batch_callback,
451
+ std::unique_ptr<BatchScheduler<TaskType>>* queue) {
452
+ if (options.max_batch_size <= 0) {
453
+ return errors::InvalidArgument("max_batch_size must be positive; was ",
454
+ options.max_batch_size);
455
+ }
456
+ if (options.max_enqueued_batches <= 0) {
457
+ return errors::InvalidArgument(
458
+ "max_enqueued_batches must be positive; was ",
459
+ options.max_enqueued_batches);
460
+ }
461
+ if (options.max_input_task_size.has_value()) {
462
+ if (options.max_input_task_size.value() < options.max_batch_size) {
463
+ return errors::InvalidArgument(
464
+ "max_input_task_size must be larger than or equal to max_batch_size;"
465
+ "got max_input_task_size as ",
466
+ options.max_input_task_size.value(), " and max_batch_size as ",
467
+ options.max_batch_size);
468
+ }
469
+ }
470
+ internal::ASBSQueue<TaskType>* asbs_queue_raw;
471
+ queue->reset(asbs_queue_raw = new internal::ASBSQueue<TaskType>(
472
+ this->shared_from_this(), options));
473
+ mutex_lock l(mu_);
474
+ queues_and_callbacks_[asbs_queue_raw] = process_batch_callback;
475
+ return OkStatus();
476
+ }
477
+
478
+ template <typename TaskType>
479
+ void AdaptiveSharedBatchScheduler<TaskType>::AddBatch(
480
+ const internal::ASBSBatch<TaskType>* batch) {
481
+ mutex_lock l(mu_);
482
+ if (options_.fifo_scheduling) {
483
+ fifo_batches_.push_back(batch);
484
+ } else {
485
+ batches_.push_back(batch);
486
+ }
487
+ int64_t delay_micros =
488
+ batch->schedulable_time_micros() - GetEnv()->NowMicros();
489
+ if (delay_micros <= 0) {
490
+ MaybeScheduleNextBatch();
491
+ return;
492
+ }
493
+ // Try to schedule batch once it becomes schedulable. Although scheduler waits
494
+ // for all batches to finish processing before allowing itself to be deleted,
495
+ // MaybeScheduleNextBatch() is called in other places, and therefore it's
496
+ // possible the scheduler could be deleted by the time this closure runs.
497
+ // Grab a shared_ptr reference to prevent this from happening.
498
+ GetEnv()->SchedClosureAfter(
499
+ delay_micros, [this, lifetime_preserver = this->shared_from_this()] {
500
+ mutex_lock l(mu_);
501
+ MaybeScheduleNextBatch();
502
+ });
503
+ }
504
+
505
+ template <typename TaskType>
506
+ void AdaptiveSharedBatchScheduler<TaskType>::RemoveQueue(
507
+ const internal::ASBSQueue<TaskType>* queue) {
508
+ mutex_lock l(mu_);
509
+ queues_and_callbacks_.erase(queue);
510
+ }
511
+
512
+ template <typename TaskType>
513
+ void AdaptiveSharedBatchScheduler<TaskType>::MaybeScheduleNextBatchFIFO() {
514
+ const internal::ASBSBatch<TaskType>* batch = *fifo_batches_.begin();
515
+ if (batch->schedulable_time_micros() > GetEnv()->NowMicros()) {
516
+ return;
517
+ }
518
+ fifo_batches_.pop_front();
519
+ // Queue may destroy itself after ReleaseBatch is called.
520
+ batch->queue()->ReleaseBatch(batch);
521
+ batch_thread_pool_->Schedule(std::bind(
522
+ &AdaptiveSharedBatchScheduler<TaskType>::CallbackWrapper, this, batch,
523
+ queues_and_callbacks_[batch->queue()], false /* is express */));
524
+ in_flight_batches_++;
525
+ }
526
+
527
+ template <typename TaskType>
528
+ void AdaptiveSharedBatchScheduler<
529
+ TaskType>::MaybeScheduleClosedBatchesLockedFIFO() {
530
+ // Only schedule closed batches if we have spare capacity.
531
+ int available_threads =
532
+ static_cast<int>(options_.num_batch_threads - in_flight_batches_ -
533
+ in_flight_express_batches_);
534
+ for (auto it = fifo_batches_.begin();
535
+ it != fifo_batches_.end() && available_threads > 0;
536
+ it = fifo_batches_.begin()) {
537
+ if ((*it)->IsClosed()) {
538
+ const internal::ASBSBatch<TaskType>* batch = *it;
539
+ fifo_batches_.pop_front();
540
+ batch->queue()->ReleaseBatch(batch);
541
+ batch_thread_pool_->Schedule(
542
+ std::bind(&AdaptiveSharedBatchScheduler<TaskType>::CallbackWrapper,
543
+ this, batch, queues_and_callbacks_[batch->queue()], true));
544
+ in_flight_express_batches_++;
545
+ available_threads--;
546
+ } else {
547
+ // Batches are FIFO, so stop iteration after finding the first non-closed
548
+ // batches.
549
+ break;
550
+ }
551
+ }
552
+ }
553
+
554
+ template <typename TaskType>
555
+ void AdaptiveSharedBatchScheduler<TaskType>::MaybeScheduleNextBatch() {
556
+ bool batch_empty =
557
+ options_.fifo_scheduling ? fifo_batches_.empty() : batches_.empty();
558
+ if (batch_empty || in_flight_batches_ >= in_flight_batches_limit_) return;
559
+ // Non-integer limit handled probabilistically.
560
+ if (in_flight_batches_limit_ - in_flight_batches_ < 1 &&
561
+ rand_double_(rand_engine_) >
562
+ in_flight_batches_limit_ - in_flight_batches_) {
563
+ return;
564
+ }
565
+
566
+ if (options_.fifo_scheduling) {
567
+ MaybeScheduleNextBatchFIFO();
568
+ return;
569
+ }
570
+
571
+ auto best_it = batches_.end();
572
+ double best_score = (std::numeric_limits<double>::max)();
573
+ int64_t now_micros = GetEnv()->NowMicros();
574
+ for (auto it = batches_.begin(); it != batches_.end(); it++) {
575
+ if ((*it)->schedulable_time_micros() > now_micros) continue;
576
+ const double score =
577
+ (*it)->creation_time_micros() -
578
+ options_.full_batch_scheduling_boost_micros * (*it)->size() /
579
+ static_cast<double>((*it)->queue()->max_task_size());
580
+ if (best_it == batches_.end() || score < best_score) {
581
+ best_score = score;
582
+ best_it = it;
583
+ }
584
+ }
585
+ // No schedulable batches.
586
+ if (best_it == batches_.end()) return;
587
+ const internal::ASBSBatch<TaskType>* batch = *best_it;
588
+ batches_.erase(best_it);
589
+ // Queue may destroy itself after ReleaseBatch is called.
590
+ batch->queue()->ReleaseBatch(batch);
591
+ batch_thread_pool_->Schedule(
592
+ std::bind(&AdaptiveSharedBatchScheduler<TaskType>::CallbackWrapper, this,
593
+ batch, queues_and_callbacks_[batch->queue()], false));
594
+ in_flight_batches_++;
595
+ }
596
+
597
+ template <typename TaskType>
598
+ void AdaptiveSharedBatchScheduler<TaskType>::MaybeScheduleClosedBatches() {
599
+ mutex_lock l(mu_);
600
+ MaybeScheduleClosedBatchesLocked();
601
+ }
602
+
603
+ template <typename TaskType>
604
+ void AdaptiveSharedBatchScheduler<
605
+ TaskType>::MaybeScheduleClosedBatchesLocked() {
606
+ if (options_.fifo_scheduling) {
607
+ MaybeScheduleClosedBatchesLockedFIFO();
608
+ return;
609
+ }
610
+ // Only schedule closed batches if we have spare capacity.
611
+ int available_threads =
612
+ static_cast<int>(options_.num_batch_threads - in_flight_batches_ -
613
+ in_flight_express_batches_);
614
+ for (auto it = batches_.begin();
615
+ it != batches_.end() && available_threads > 0;) {
616
+ if ((*it)->IsClosed()) {
617
+ const internal::ASBSBatch<TaskType>* batch = *it;
618
+ it = batches_.erase(it);
619
+ batch->queue()->ReleaseBatch(batch);
620
+ batch_thread_pool_->Schedule(
621
+ std::bind(&AdaptiveSharedBatchScheduler<TaskType>::CallbackWrapper,
622
+ this, batch, queues_and_callbacks_[batch->queue()], true));
623
+ in_flight_express_batches_++;
624
+ available_threads--;
625
+ } else {
626
+ ++it;
627
+ }
628
+ }
629
+ }
630
+
631
+ template <typename TaskType>
632
+ void AdaptiveSharedBatchScheduler<TaskType>::CallbackWrapper(
633
+ const internal::ASBSBatch<TaskType>* batch,
634
+ AdaptiveSharedBatchScheduler<TaskType>::BatchProcessor callback,
635
+ bool is_express) {
636
+ profiler::TraceMeConsumer trace_me(
637
+ [&] {
638
+ return profiler::TraceMeEncode(
639
+ "ProcessBatch", {{"batch_size_before_padding", batch->size()},
640
+ {"_r", 2} /*root_event*/});
641
+ },
642
+ profiler::ContextType::kAdaptiveSharedBatchScheduler,
643
+ batch->traceme_context_id());
644
+ const int64_t start_time = batch->creation_time_micros();
645
+ callback(std::unique_ptr<Batch<TaskType>>(
646
+ const_cast<internal::ASBSBatch<TaskType>*>(batch)));
647
+ int64_t end_time = GetEnv()->NowMicros();
648
+ mutex_lock l(mu_);
649
+ if (is_express) {
650
+ in_flight_express_batches_--;
651
+ MaybeScheduleClosedBatchesLocked();
652
+ return;
653
+ }
654
+ in_flight_batches_--;
655
+ batch_count_++;
656
+ batch_delay_stats_.batch_latency_sum += end_time - start_time;
657
+
658
+ MaybeAdjustInflightLimit();
659
+
660
+ MaybeScheduleNextBatch();
661
+ }
662
+
663
+ template <typename TaskType>
664
+ void AdaptiveSharedBatchScheduler<TaskType>::MaybeAdjustInflightLimit() {
665
+ // Occasionally adjust in_flight_batches_limit_ to minimize average latency.
666
+ // Although the optimal value may depend on the workload, the latency should
667
+ // be a simple convex function of in_flight_batches_limit_, allowing us to
668
+ // locate the global minimum relatively quickly.
669
+ if (batch_count_ == options_.batches_to_average_over) {
670
+ double current_avg_latency_ms =
671
+ (batch_delay_stats_.batch_latency_sum / 1000.) / batch_count_;
672
+ bool current_latency_decreased =
673
+ current_avg_latency_ms < batch_delay_stats_.last_avg_latency_ms;
674
+ if (current_latency_decreased) {
675
+ // If latency improvement was because we're moving in the correct
676
+ // direction, increase step_size so that we can get to the minimum faster.
677
+ // If latency improvement was due to backtracking from a previous failure,
678
+ // decrease step_size in order to refine our location.
679
+ step_size_multiplier_ *=
680
+ (batch_delay_stats_.last_latency_decreased ? 2 : 0.5);
681
+ step_size_multiplier_ =
682
+ std::min(step_size_multiplier_, kMaxStepSizeMultiplier);
683
+ step_size_multiplier_ =
684
+ std::max(step_size_multiplier_, kMinStepSizeMultiplier);
685
+ } else {
686
+ // Return (nearly) to previous position and confirm that latency is better
687
+ // there before decreasing step size.
688
+ batch_delay_stats_.step_direction = -batch_delay_stats_.step_direction;
689
+ }
690
+ in_flight_batches_limit_ += batch_delay_stats_.step_direction *
691
+ in_flight_batches_limit_ *
692
+ step_size_multiplier_;
693
+ in_flight_batches_limit_ =
694
+ std::min(in_flight_batches_limit_,
695
+ static_cast<double>(options_.num_batch_threads));
696
+ in_flight_batches_limit_ =
697
+ std::max(in_flight_batches_limit_,
698
+ static_cast<double>(options_.min_in_flight_batches_limit));
699
+ batch_delay_stats_.last_avg_latency_ms = current_avg_latency_ms;
700
+ batch_delay_stats_.last_latency_decreased = current_latency_decreased;
701
+ batch_count_ = 0;
702
+ batch_delay_stats_.batch_latency_sum = 0;
703
+ }
704
+ }
705
+
706
+ // ---------------- ASBSQueue ----------------
707
+
708
+ namespace internal {
709
+ template <typename TaskType>
710
+ ASBSQueue<TaskType>::ASBSQueue(
711
+ std::shared_ptr<AdaptiveSharedBatchScheduler<TaskType>> scheduler,
712
+ const QueueOptions& options)
713
+ : scheduler_(scheduler), options_(options) {}
714
+
715
+ template <typename TaskType>
716
+ ASBSQueue<TaskType>::~ASBSQueue() {
717
+ // Wait until last batch has been scheduled.
718
+ const int kSleepMicros = 1000;
719
+ for (;;) {
720
+ {
721
+ mutex_lock l(mu_);
722
+ if (num_enqueued_batches_ == 0) {
723
+ break;
724
+ }
725
+ }
726
+ scheduler_->GetEnv()->SleepForMicroseconds(kSleepMicros);
727
+ }
728
+ scheduler_->RemoveQueue(this);
729
+ }
730
+
731
+ template <typename TaskType>
732
+ Status ASBSQueue<TaskType>::Schedule(std::unique_ptr<TaskType>* task) {
733
+ size_t size = (*task)->size();
734
+ if (options_.split_input_task_func == nullptr &&
735
+ size > options_.max_batch_size) {
736
+ return errors::InvalidArgument("Task size ", size,
737
+ " is larger than maximum batch size ",
738
+ options_.max_batch_size);
739
+ }
740
+ if (options_.max_input_task_size.has_value() &&
741
+ (size > options_.max_input_task_size.value())) {
742
+ return errors::InvalidArgument("Task size ", size,
743
+ " is larger than max input task size ",
744
+ options_.max_input_task_size.value());
745
+ }
746
+
747
+ std::vector<std::unique_ptr<TaskType>> tasks_to_schedule;
748
+ std::vector<ASBSBatch<TaskType>*> new_batches;
749
+ bool closed_batch = false;
750
+ {
751
+ mutex_lock l(mu_);
752
+ if (size > SchedulingCapacityLocked()) {
753
+ return errors::Unavailable("The batch scheduling queue is full");
754
+ }
755
+
756
+ int remaining_batch_size =
757
+ current_batch_ == nullptr
758
+ ? options_.max_batch_size
759
+ : options_.max_batch_size - current_batch_->size();
760
+ if (options_.split_input_task_func == nullptr ||
761
+ size <= remaining_batch_size) {
762
+ // Either we don't allow task splitting or task fits within the current
763
+ // batch.
764
+ tasks_to_schedule.push_back(std::move(*task));
765
+ } else {
766
+ // Split task in order to completely fill the current batch.
767
+ // Beyond this point Schedule should not fail, as the caller has been
768
+ // promised that all of the split tasks will be scheduled.
769
+ TF_RETURN_IF_ERROR(options_.split_input_task_func(
770
+ task, remaining_batch_size, options_.max_batch_size,
771
+ &tasks_to_schedule));
772
+ }
773
+ for (auto& task : tasks_to_schedule) {
774
+ // Can't fit within current batch, close it off and try to create another.
775
+ if (current_batch_ &&
776
+ current_batch_->size() + task->size() > options_.max_batch_size) {
777
+ current_batch_->Close();
778
+ closed_batch = true;
779
+ current_batch_ = nullptr;
780
+ }
781
+ if (!current_batch_) {
782
+ num_enqueued_batches_++;
783
+ // batch.traceme_context_id connects TraceMeProducer and
784
+ // TraceMeConsumer.
785
+ // When multiple calls to "ASBS::Schedule" accumulate to one batch, they
786
+ // are processed in the same batch and should share traceme_context_id.
787
+ current_batch_ = new ASBSBatch<TaskType>(
788
+ this, scheduler_->GetEnv()->NowMicros(),
789
+ options_.batch_timeout_micros, NewTraceMeContextIdForBatch());
790
+ new_batches.push_back(current_batch_);
791
+ }
792
+
793
+ // Annotate each task (corresponds to one call of schedule) with a
794
+ // TraceMeProducer.
795
+ profiler::TraceMeProducer trace_me(
796
+ [task_size = task->size()] {
797
+ return profiler::TraceMeEncode(
798
+ "ASBSQueue::Schedule",
799
+ {{"batching_input_task_size", task_size}});
800
+ },
801
+ profiler::ContextType::kAdaptiveSharedBatchScheduler,
802
+ this->current_batch_->traceme_context_id());
803
+ current_batch_->AddTask(std::move(task));
804
+ num_enqueued_tasks_++;
805
+ // If current_batch_ is now full, allow it to be processed immediately.
806
+ bool reached_max_tasks =
807
+ (options_.max_tasks_per_batch.has_value() &&
808
+ current_batch_->num_tasks() >= options_.max_tasks_per_batch.value());
809
+ if (current_batch_->size() == options_.max_batch_size ||
810
+ reached_max_tasks) {
811
+ current_batch_->Close();
812
+ closed_batch = true;
813
+ current_batch_ = nullptr;
814
+ }
815
+ }
816
+ }
817
+ // Scheduler functions must be called outside of lock, since they may call
818
+ // ReleaseBatch.
819
+ for (auto* batch : new_batches) {
820
+ scheduler_->AddBatch(batch);
821
+ }
822
+ if (closed_batch) {
823
+ scheduler_->MaybeScheduleClosedBatches();
824
+ }
825
+ return OkStatus();
826
+ }
827
+
828
+ template <typename TaskType>
829
+ void ASBSQueue<TaskType>::ReleaseBatch(const ASBSBatch<TaskType>* batch) {
830
+ mutex_lock l(mu_);
831
+ num_enqueued_batches_--;
832
+ num_enqueued_tasks_ -= batch->num_tasks();
833
+ if (batch == current_batch_) {
834
+ current_batch_->Close();
835
+ current_batch_ = nullptr;
836
+ }
837
+ }
838
+
839
+ template <typename TaskType>
840
+ size_t ASBSQueue<TaskType>::NumEnqueuedTasks() const {
841
+ mutex_lock l(mu_);
842
+ return num_enqueued_tasks_;
843
+ }
844
+
845
+ template <typename TaskType>
846
+ size_t ASBSQueue<TaskType>::SchedulingCapacity() const {
847
+ mutex_lock l(mu_);
848
+ return SchedulingCapacityLocked();
849
+ }
850
+
851
+ template <typename TaskType>
852
+ size_t ASBSQueue<TaskType>::SchedulingCapacityLocked() const {
853
+ const int current_batch_capacity =
854
+ current_batch_ ? options_.max_batch_size - current_batch_->size() : 0;
855
+ const int spare_batches =
856
+ options_.max_enqueued_batches - num_enqueued_batches_;
857
+ return spare_batches * options_.max_batch_size + current_batch_capacity;
858
+ }
859
+
860
+ template <typename TaskType>
861
+ // static
862
+ uint64 ASBSQueue<TaskType>::NewTraceMeContextIdForBatch() {
863
+ static std::atomic<uint64> traceme_context_id(0);
864
+ return traceme_context_id.fetch_add(1, std::memory_order_relaxed);
865
+ }
866
+ } // namespace internal
867
+ } // namespace serving
868
+ } // namespace tensorflow
869
+
870
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_ADAPTIVE_SHARED_BATCH_SCHEDULER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/batch_input_task.h ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_CORE_KERNELS_BATCHING_UTIL_BATCH_INPUT_TASK_H_
17
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BATCH_INPUT_TASK_H_
18
+
19
+ #include <algorithm>
20
+ #include <atomic>
21
+ #include <functional>
22
+ #include <memory>
23
+ #include <utility>
24
+
25
+ #include "absl/base/call_once.h"
26
+ #include "absl/container/fixed_array.h"
27
+ #include "absl/synchronization/mutex.h"
28
+ #include "tensorflow/core/kernels/batching_util/batch_scheduler.h"
29
+ #include "tensorflow/core/kernels/batching_util/concat_split_util.h"
30
+ #include "tensorflow/core/kernels/batching_util/input_split_metadata.h"
31
+ #include "tensorflow/core/platform/errors.h"
32
+ #include "tensorflow/core/platform/thread_annotations.h"
33
+ #include "tensorflow/core/util/incremental_barrier.h"
34
+
35
+ namespace tensorflow {
36
+ namespace serving {
37
+
38
+ namespace internal {
39
+ template <typename TaskType>
40
+ class BatchInputTaskHandleTestAccess;
41
+
42
+ template <typename TaskType>
43
+ class BatchInputTaskTestAccess;
44
+
45
+ template <typename TaskType>
46
+ class BatchInputTask;
47
+
48
+ // A RAII-style object that holds a ref-counted batch-input-task, and
49
+ // represents a slice of batch-input-task.
50
+
51
+ // To be handed out to callers of `BatchInputTask::ToTaskHandles` quickly
52
+ // (i.e. not necessarily waiting for input split)
53
+ //
54
+ // `BatchInputTaskHandle::GetSplitTask` evaluates to the slice of task.
55
+ template <typename TaskType>
56
+ class BatchInputTaskHandle : public BatchTask {
57
+ public:
58
+ BatchInputTaskHandle(
59
+ std::shared_ptr<BatchInputTask<TaskType>> batch_input_task, int split_id,
60
+ size_t task_size);
61
+
62
+ // Should be called once. Returns nullptr on subsequent calls.
63
+ std::unique_ptr<TaskType> GetSplitTask();
64
+
65
+ // Returns the size of this task.
66
+ size_t size() const override { return task_size_; }
67
+
68
+ private:
69
+ template <typename T>
70
+ friend class internal::BatchInputTaskHandleTestAccess;
71
+
72
+ int split_id() const { return split_id_; }
73
+
74
+ std::shared_ptr<BatchInputTask<TaskType>> batch_input_task_;
75
+
76
+ // The handle evaluates to the N-th slice of original task, and
77
+ // N is `split_id_`.
78
+ const int split_id_;
79
+
80
+ const size_t task_size_;
81
+
82
+ std::atomic<bool> once_{false};
83
+ };
84
+
85
+ // BatchInputTask encapsulates a input (`input_task`) to be batched and the
86
+ // information to get task splits after it's enqueued, so as to support lazy
87
+ // split of a task.
88
+ //
89
+ // Input split could reduce excessive padding for efficiency; lazy split
90
+ // moves task-split out of the critical path of enqueue and dequeue and reduces
91
+ // contention.
92
+ //
93
+ // BatchInputTask is thread safe.
94
+ //
95
+ // Usage
96
+ //
97
+ // ... a deque with frequent enqueue and dequeue operations ...
98
+ // ... Note, a deque of Batch of BatchInputTaskHandle is used to form batches
99
+ // at enqueue time (split is lazy at deque time);
100
+ // ... For use cases to form batches at dequeue time, we can use a deque of
101
+ // BatchInputTaskHandle directly, and "peek" metadata to form a batch by
102
+ // then.
103
+ // std::deque<std::unique_ptr<Batch<BatchInputTaskHandle<TaskType>>>> deque_
104
+ // TF_GUARDED_BY(mu_);
105
+ //
106
+ // std::unique_ptr<TaskType> input_task;
107
+ //
108
+ // ... Enqueue path ...
109
+ //
110
+ // {
111
+ // mutex_lock l(mu_);
112
+ // std::shared_ptr<BatchInputTask<TaskType>> batch_input_task =
113
+ // ConstructLazyBatchWithoutSplit(input_task);
114
+ //
115
+ // std::vector<std::unique_ptr<BatchInputTaskHandle<TaskType>>> task_handles;
116
+ // input_batch->ToTaskHandles(&task_handles);
117
+ // for (int i = 0; i < task_handles.size(); ++i) {
118
+ // EnqueueTaskHandleIntoDeque(deque_);
119
+ // }
120
+ //
121
+ // ... Dequeue path ...
122
+ // std::unique_ptr<Batch<BatchInputTaskHandle<TaskType>>> handles_to_schedule;
123
+ // {
124
+ // mutex_lock l(mu_);
125
+ // ... HasBatchToSchedule could be customized or specialized
126
+ // ... (e.g., readiness depending on enqueue time)
127
+ // if (HasBatchToSchedule(deque_)) {
128
+ // handles_to_schedule = std::move(deque_.front());
129
+ // deque_.pop_front();
130
+ // }
131
+ // }
132
+ // ...... `mu_` is released ......
133
+ //
134
+ // std::vector<std::unique_ptr<BatchInputTaskHandle<TaskType>>> tasks_in_batch =
135
+ // RemoveAllTasksFromBatch(handles_to_schedule);
136
+ //
137
+ // std::unique_ptr<Batch<TaskType>> batch_to_schedule;
138
+ // for (int i = 0; i < tasks_in_batch.size(); i++) {
139
+ // batch_to_schedule->AddTask(std::move(tasks_in_batch[i]->GetSplitTask()));
140
+ // }
141
+ // batch_to_schedule->Close();
142
+ //
143
+ // `batch_to_schedule` is ready for schedule.
144
+ template <typename TaskType>
145
+ class BatchInputTask
146
+ : public std::enable_shared_from_this<BatchInputTask<TaskType>> {
147
+ public:
148
+ using SplitInputFunc = std::function<Status(
149
+ std::unique_ptr<TaskType>* input_task, int first_output_task_size,
150
+ int input_batch_size_limit,
151
+ std::vector<std::unique_ptr<TaskType>>* output_tasks)>;
152
+
153
+ BatchInputTask(std::unique_ptr<TaskType> input_task,
154
+ int open_batch_remaining_slot, int batch_size_limit,
155
+ SplitInputFunc split_input_func);
156
+
157
+ // Outputs the task handles for the input task.
158
+ // Each task handle represents a slice of task after input task is split, and
159
+ // could evaluate to that slice.
160
+ //
161
+ // NOTE:
162
+ // Each task handle in `output_task_handles` takes ownership of a reference of
163
+ // this BatchInputTask.
164
+ void ToTaskHandles(
165
+ std::vector<std::unique_ptr<BatchInputTaskHandle<TaskType>>>*
166
+ output_task_handles);
167
+
168
+ private:
169
+ friend class BatchInputTaskHandle<TaskType>;
170
+ template <typename T>
171
+ friend class internal::BatchInputTaskTestAccess;
172
+
173
+ std::unique_ptr<TaskType> GetSplitTask(int split_id);
174
+
175
+ Status SplitBatches(std::vector<std::unique_ptr<TaskType>>* output_tasks);
176
+
177
+ std::unique_ptr<TaskType> input_task_;
178
+
179
+ const int input_task_size_ = 0;
180
+ const int open_batch_remaining_slot_;
181
+
182
+ const int batch_size_limit_;
183
+ const SplitInputFunc split_func_;
184
+
185
+ const InputSplitMetadata input_split_metadata_;
186
+
187
+ mutable absl::once_flag once_;
188
+
189
+ std::vector<std::unique_ptr<TaskType>> task_splits_;
190
+ Status split_status_;
191
+ };
192
+
193
+ //
194
+ // Implementation details. API readers may skip.
195
+ //
196
+
197
+ template <typename TaskType>
198
+ BatchInputTaskHandle<TaskType>::BatchInputTaskHandle(
199
+ std::shared_ptr<BatchInputTask<TaskType>> batch_input_task, int split_id,
200
+ size_t task_size)
201
+ : batch_input_task_(batch_input_task),
202
+ split_id_(split_id),
203
+ task_size_(task_size) {}
204
+
205
+ template <typename TaskType>
206
+ std::unique_ptr<TaskType> BatchInputTaskHandle<TaskType>::GetSplitTask() {
207
+ if (once_.load(std::memory_order_acquire)) {
208
+ return nullptr;
209
+ }
210
+ once_.store(true, std::memory_order_release);
211
+ return batch_input_task_->GetSplitTask(split_id_);
212
+ }
213
+
214
+ template <typename TaskType>
215
+ BatchInputTask<TaskType>::BatchInputTask(std::unique_ptr<TaskType> input_task,
216
+ int open_batch_remaining_slot,
217
+ int batch_size_limit,
218
+ SplitInputFunc split_input_func)
219
+ : input_task_(std::move(input_task)),
220
+ input_task_size_(input_task_->size()),
221
+ open_batch_remaining_slot_(open_batch_remaining_slot),
222
+ batch_size_limit_(batch_size_limit),
223
+ split_func_(split_input_func),
224
+ input_split_metadata_(input_task_size_, open_batch_remaining_slot,
225
+ batch_size_limit) {}
226
+
227
+ template <typename TaskType>
228
+ void BatchInputTask<TaskType>::ToTaskHandles(
229
+ std::vector<std::unique_ptr<BatchInputTaskHandle<TaskType>>>*
230
+ task_handles) {
231
+ const absl::FixedArray<int>& task_sizes = input_split_metadata_.task_sizes();
232
+ task_handles->resize(task_sizes.size());
233
+ for (int i = 0; i < task_handles->size(); i++) {
234
+ (*task_handles)[i] = std::make_unique<BatchInputTaskHandle<TaskType>>(
235
+ this->shared_from_this(), i, task_sizes[i]);
236
+ }
237
+ }
238
+
239
+ template <typename TaskType>
240
+ std::unique_ptr<TaskType> BatchInputTask<TaskType>::GetSplitTask(int split_id) {
241
+ absl::call_once(once_,
242
+ [this]() { split_status_ = SplitBatches(&task_splits_); });
243
+ if (!split_status_.ok()) {
244
+ LOG_EVERY_N_SEC(WARNING, 60 /* seconds */)
245
+ << "Split task with error: " << split_status_ << " split metadata is "
246
+ << input_split_metadata_.DebugString();
247
+ return nullptr;
248
+ }
249
+ if (split_id >= 0 && split_id < task_splits_.size()) {
250
+ return std::move(task_splits_[split_id]);
251
+ }
252
+ return nullptr;
253
+ }
254
+
255
+ template <typename TaskType>
256
+ Status BatchInputTask<TaskType>::SplitBatches(
257
+ std::vector<std::unique_ptr<TaskType>>* output_tasks) {
258
+ return split_func_(&input_task_, open_batch_remaining_slot_,
259
+ batch_size_limit_, output_tasks);
260
+ }
261
+
262
+ } // namespace internal
263
+ } // namespace serving
264
+ } // namespace tensorflow
265
+
266
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BATCH_INPUT_TASK_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/batch_resource_base.h ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BATCH_RESOURCE_BASE_H_
17
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BATCH_RESOURCE_BASE_H_
18
+
19
+ #include <cstdint>
20
+ #include <functional>
21
+ #include <map>
22
+ #include <memory>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ #include "absl/strings/str_join.h"
27
+ #include "absl/synchronization/blocking_counter.h"
28
+ #include "tensorflow/core/common_runtime/cost_measurement_registry.h"
29
+ #include "tensorflow/core/common_runtime/request_cost.h"
30
+ #include "tensorflow/core/framework/op_kernel.h"
31
+ #include "tensorflow/core/framework/resource_mgr.h"
32
+ #include "tensorflow/core/framework/tensor.h"
33
+ #include "tensorflow/core/framework/tensor_shape.h"
34
+ #include "tensorflow/core/kernels/batching_util/adaptive_shared_batch_scheduler.h"
35
+ #include "tensorflow/core/kernels/batching_util/batch_scheduler.h"
36
+ #include "tensorflow/core/kernels/batching_util/shared_batch_scheduler.h"
37
+ #include "tensorflow/core/kernels/batching_util/threadsafe_status.h"
38
+ #include "tensorflow/core/platform/context.h"
39
+ #include "tensorflow/core/platform/status.h"
40
+ #include "tensorflow/core/platform/thread_annotations.h"
41
+ #include "tensorflow/core/protobuf/config.pb.h"
42
+ #include "tsl/platform/criticality.h"
43
+
44
+ namespace tensorflow {
45
+ namespace serving {
46
+
47
+ // Base class for resource that encapsulating the state and logic for batching
48
+ // tensors.
49
+ class BatchResourceBase : public ResourceBase {
50
+ public:
51
+ // Given a BatchTask (from one op invocation) with 'num_outputs'== M and
52
+ // splitted into N sub tasks, TensorMatrix is a N X M matrix.
53
+ // Namely, TensorMatrix[i][j] indicates the i-th split tensor of j-th output;
54
+ // concatenating tensors along the 2nd dimension gives a output tensor.
55
+ typedef std::vector<std::vector<Tensor>> TensorMatrix;
56
+
57
+ // One task to be batched, corresponds to a `slice` of input from one batch-op
58
+ // invocation.
59
+ //
60
+ // Given input from one batch-op invocation, a `slice` of this input is:
61
+ // 1) Split each Tensor in `BatchTask::inputs` along the 0th dimension.
62
+ // 2) 'split_index' is calculated along the 0-th dimension.
63
+ //
64
+ // Note input from one batch-op invocation is valid and considered a
65
+ // specialized `slice`.
66
+ struct BatchTask : public tensorflow::serving::BatchTask {
67
+ // A unique ID to identify this invocation of Batch.
68
+ int64_t guid;
69
+
70
+ Context propagated_context;
71
+
72
+ std::vector<Tensor> inputs;
73
+ std::vector<Tensor> captured_inputs;
74
+ OpKernelContext* context;
75
+ AsyncOpKernel::DoneCallback done_callback;
76
+
77
+ // The index of this split, along the 0-th dimension of input from op
78
+ // invocation.
79
+ int split_index = 0;
80
+
81
+ // Two-dimensional tensor matrix, ownership shared by:
82
+ // 1) each split of task (to fill one row in this matrix)
83
+ // and
84
+ // 2) callback that runs to merge output of individual splits for an op
85
+ // invocation, after all splits complete.
86
+ std::shared_ptr<TensorMatrix> output;
87
+
88
+ // 'status' records error (could be from any split) if at least one split
89
+ // returns error, OK otherwise.
90
+ // Ownership is shared by individual splits and callback.
91
+ std::shared_ptr<ThreadSafeStatus> status;
92
+
93
+ bool is_partial = false;
94
+
95
+ uint64 start_time;
96
+
97
+ size_t size() const override { return inputs[0].shape().dim_size(0); }
98
+
99
+ // Create a split task from this one. The caller needs to setup the inputs
100
+ // of the new task
101
+ std::unique_ptr<BatchTask> CreateSplitTask(
102
+ int split_index, AsyncOpKernel::DoneCallback done_callback);
103
+
104
+ // RequestCost is for collecting the cost and must outlive the batching
105
+ // processing.
106
+ //
107
+ // For example, to collect cost in rpc processing, `request_cost` is owned
108
+ // by rpc handler and points to the RequestCost of an rpc which provides
109
+ // the inputs to this BatchTask.
110
+ //
111
+ // After the batch processing, the request cost will be incremented with
112
+ // this task's processing costs.
113
+ RequestCost* request_cost = nullptr;
114
+
115
+ tsl::criticality::Criticality criticality;
116
+
117
+ // If nonzero, make a batch of this size entirely out of padding. This
118
+ // batch is processed, but is not propagated to the kernel outputs.
119
+ int forced_warmup_batch_size = 0;
120
+
121
+ protected:
122
+ virtual std::unique_ptr<BatchTask> CreateDerivedTask() {
123
+ return std::make_unique<BatchTask>();
124
+ }
125
+ };
126
+
127
+ // Appending a T suffix to make the type alias different to those in
128
+ // tensorflow::serving namespace, because some versions of compiler complain
129
+ // about changing meaning of the symbols.
130
+ using BatcherT = SharedBatchScheduler<BatchResourceBase::BatchTask>;
131
+ using AdaptiveBatcherT =
132
+ AdaptiveSharedBatchScheduler<BatchResourceBase::BatchTask>;
133
+ using BatcherQueueT = BatchScheduler<BatchResourceBase::BatchTask>;
134
+ using BatchT = Batch<BatchResourceBase::BatchTask>;
135
+
136
+ BatchResourceBase(bool has_process_batch_function,
137
+ std::shared_ptr<BatcherT> batcher,
138
+ const BatcherT::QueueOptions& batcher_queue_options,
139
+ std::vector<int32> allowed_batch_sizes)
140
+ : has_process_batch_function_(has_process_batch_function),
141
+ batcher_(std::move(batcher)),
142
+ batcher_queue_options_(batcher_queue_options),
143
+ allowed_batch_sizes_(std::move(allowed_batch_sizes)),
144
+ allowed_batch_sizes_str_(absl::StrJoin(allowed_batch_sizes_, ",")) {}
145
+
146
+ BatchResourceBase(bool has_process_batch_function,
147
+ std::shared_ptr<AdaptiveBatcherT> batcher,
148
+ const AdaptiveBatcherT::QueueOptions& batcher_queue_options,
149
+ std::vector<int32> allowed_batch_sizes)
150
+ : has_process_batch_function_(has_process_batch_function),
151
+ adaptive_batcher_(std::move(batcher)),
152
+ adaptive_batcher_queue_options_(batcher_queue_options),
153
+ allowed_batch_sizes_(std::move(allowed_batch_sizes)),
154
+ allowed_batch_sizes_str_(absl::StrJoin(allowed_batch_sizes_, ",")) {}
155
+
156
+ void set_session_metadata(tensorflow::SessionMetadata session_metadata) {
157
+ session_metadata_ = std::move(session_metadata);
158
+ }
159
+
160
+ const SessionMetadata& session_metadata() const { return session_metadata_; }
161
+
162
+ using CreateBatchTaskFn =
163
+ std::function<StatusOr<std::unique_ptr<BatchTask>>()>;
164
+
165
+ // Like `RegisterInput`, but extra "dummy" batches are processed for each
166
+ // batch size. Only the real request's outputs are propagated to the caller.
167
+ Status RegisterWarmupInputs(int64_t guid, OpKernelContext* context,
168
+ const string& batcher_queue_name,
169
+ const CreateBatchTaskFn& create_batch_task_fn,
170
+ AsyncOpKernel::DoneCallback done);
171
+ // Ingests data from one invocation of the batch op. The data is enqueued to
172
+ // be combined with others into a batch, asynchronously.
173
+ Status RegisterInput(int64_t guid, OpKernelContext* context,
174
+ const string& batcher_queue_name,
175
+ const CreateBatchTaskFn& create_batch_task_fn,
176
+ AsyncOpKernel::DoneCallback done_callback,
177
+ int forced_warmup_batch_size = 0);
178
+
179
+ static BatcherT::QueueOptions GetBatcherQueueOptions(
180
+ int32_t num_batch_threads, int32_t max_batch_size,
181
+ int32_t batch_timeout_micros, int32_t max_enqueued_batches,
182
+ const std::vector<int32>& allowed_batch_sizes,
183
+ bool enable_large_batch_splitting, bool disable_padding);
184
+
185
+ static BatcherT::QueueOptions GetBatcherQueueOptions(
186
+ int32_t num_batch_threads, int32_t max_batch_size,
187
+ int32_t batch_timeout_micros, int32_t max_enqueued_batches,
188
+ const std::vector<int32>& allowed_batch_sizes,
189
+ bool enable_large_batch_splitting, bool disable_padding,
190
+ int32_t low_priority_max_batch_size,
191
+ int32_t low_priority_batch_timeout_micros,
192
+ int32_t low_priority_max_enqueued_batches,
193
+ const std::vector<int32>& low_priority_allowed_batch_sizes);
194
+
195
+ static AdaptiveBatcherT::QueueOptions GetAdaptiveBatcherQueueOptions(
196
+ int32_t max_batch_size, int32_t batch_timeout_micros,
197
+ int32_t max_enqueued_batches, bool enable_large_batch_splitting,
198
+ const std::vector<int32>& allowed_batch_sizes, bool disable_padding);
199
+
200
+ // Split 'input' of 'input_task_ptr' along 0th dimension, into a list of
201
+ // 'output_tasks'.
202
+ // Task sizes are determined by
203
+ // 1) open_batch_remaining_slot
204
+ // 2) max_batch_size
205
+ // 3) size-of-input-task
206
+ // in a way that
207
+ // 1) Task sizes add up to `size-of-input-task`.
208
+ // 2) Task sizes from left to right are like
209
+ // [open_batch_remaining_slot, max_batch_size, max_batch_size, ...,
210
+ // `size-of-input-task` - `sum-of-previous-elements`].
211
+ //
212
+ // REQUIRES:
213
+ // Caller should make sure size-of-input-task is greater than
214
+ // open_batch_remaining_slot.
215
+ static Status SplitInputTask(
216
+ std::unique_ptr<BatchTask>* input_task_ptr, int open_batch_remaining_slot,
217
+ int max_batch_size,
218
+ std::vector<std::unique_ptr<BatchTask>>* output_tasks);
219
+
220
+ // Splits the batch costs to each task.
221
+ //
222
+ // Inputs:
223
+ // 1) batch_cost_measurements, which provides the total cost of each type;
224
+ // 2) processed_size, it's the batch size plus the padding amount;
225
+ // 3) batch, provides the batch size and input sizes.
226
+ //
227
+ // Outputs:
228
+ // The request_cost in each batch task will be updated.
229
+ // - This function will use two approaches to split the batch cost (if it's
230
+ // non-zero), thus two costs will be output.
231
+ // 1) smeared cost: batch cost is split proportionally to each task's size,
232
+ // and paddings do not share any cost;
233
+ // 2) non-smeared cost: batch cost is split proportionally to each task or
234
+ // padding's size. Here padding's cost is not assigned to any tasks.
235
+ // - This function will also record the metrics of this batch in each task,
236
+ // including:
237
+ // 1) the batch size;
238
+ // 2) the input size from this task;
239
+ // 3) the padding amount.
240
+ static void SplitBatchCostsAndRecordMetrics(
241
+ std::vector<std::unique_ptr<CostMeasurement>>& batch_cost_measurements,
242
+ int64_t processed_size, BatchT& batch);
243
+
244
+ private:
245
+ // Implementation of calling the process batch function.
246
+ virtual void ProcessFuncBatchImpl(
247
+ const BatchResourceBase::BatchTask& last_task,
248
+ absl::Span<const Tensor> inputs, std::vector<Tensor>* combined_outputs,
249
+ std::function<void(const Status&)> done) const = 0;
250
+
251
+ // Validates that it's legal to combine the tasks in 'batch' into a batch.
252
+ // Assumes the batch is non-empty.
253
+ static Status ValidateBatch(const BatchT& batch);
254
+
255
+ // Returns the smallest entry in 'allowed_batch_sizes_' that is greater than
256
+ // or equal to 'batch_size'. If 'allowed_batch_sizes_' is empty, simply
257
+ // returns 'batch_size'.
258
+ int RoundToLowestAllowedBatchSize(int batch_size) const;
259
+
260
+ Status ConcatInputTensors(const BatchT& batch, OpKernelContext* context,
261
+ std::vector<Tensor>* concatenated_tensors) const;
262
+
263
+ Status SplitOutputTensors(const std::vector<Tensor>& combined_outputs,
264
+ BatchT* batch) const;
265
+
266
+ void ProcessFuncBatch(std::unique_ptr<BatchT> batch) const;
267
+
268
+ // Processes a batch of one or more BatchTask entries.
269
+ void ProcessBatch(std::unique_ptr<BatchT> batch) const;
270
+
271
+ // Emits an index tensor, which the Unbatch op will use to un-concatenate
272
+ // the tensor and attribute the pieces to the right batch keys. The index
273
+ // tensor contains, for each input: [batch_key, start_offset, end_offset]
274
+ // where start_offset and end_offset represent the range of entries in the
275
+ // concatenated tensors that belong to that input.
276
+ //
277
+ // Emits the result to the output at 'output_index' using 'context'.
278
+ static Status EmitIndexTensor(OpKernelContext* context, const BatchT& batch,
279
+ int output_index);
280
+
281
+ // Looks up the batcher queue for 'queue_name'. If it did't previously exist,
282
+ // creates it.
283
+ Status LookupOrCreateBatcherQueue(const string& queue_name,
284
+ BatcherQueueT** queue);
285
+
286
+ SessionMetadata session_metadata_;
287
+
288
+ absl::Mutex outstanding_batch_mu_;
289
+ int num_outstanding_batched_items_ TF_GUARDED_BY(outstanding_batch_mu_) = 0;
290
+
291
+ // True if user specified a batch processing function for this resource.
292
+ const bool has_process_batch_function_;
293
+ // A batch scheduler, and options for creating queues.
294
+ std::shared_ptr<BatcherT> batcher_;
295
+ BatcherT::QueueOptions batcher_queue_options_;
296
+
297
+ // A batch scheduler, and options for creating queues.
298
+ std::shared_ptr<AdaptiveBatcherT> adaptive_batcher_;
299
+ AdaptiveBatcherT::QueueOptions adaptive_batcher_queue_options_;
300
+
301
+ // A collection of batcher queues, keyed on queue name.
302
+ // TODO(olston): Garbage-collect unused queues (perhaps simply remove empty
303
+ // ones (with a time delay?); it's okay if they get recreated later).
304
+ mutable mutex batcher_queues_mu_;
305
+ std::map<string, std::unique_ptr<BatcherQueueT>> batcher_queues_
306
+ TF_GUARDED_BY(batcher_queues_mu_);
307
+
308
+ std::vector<int32> allowed_batch_sizes_;
309
+ // A concatenated string of <allowed_batch_sizes_>, separated by ",". This is
310
+ // used to record batching parameter.
311
+ string allowed_batch_sizes_str_;
312
+ };
313
+
314
+ } // namespace serving
315
+ } // namespace tensorflow
316
+
317
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BATCH_RESOURCE_BASE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/batch_scheduler.h ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ // Abstractions for processing small tasks in a batched fashion, to reduce
17
+ // processing times and costs that can be amortized across multiple tasks.
18
+ //
19
+ // The core class is BatchScheduler, which groups tasks into batches.
20
+ //
21
+ // BatchScheduler encapsulates logic for aggregating multiple tasks into a
22
+ // batch, and kicking off processing of a batch on a thread pool it manages.
23
+ //
24
+ // This file defines an abstract BatchScheduler class.
25
+
26
+ #ifndef TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BATCH_SCHEDULER_H_
27
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BATCH_SCHEDULER_H_
28
+
29
+ #include <stddef.h>
30
+
31
+ #include <algorithm>
32
+ #include <functional>
33
+ #include <memory>
34
+ #include <utility>
35
+ #include <vector>
36
+
37
+ #include "tensorflow/core/lib/core/notification.h"
38
+ #include "tensorflow/core/lib/core/status.h"
39
+ #include "tensorflow/core/platform/logging.h"
40
+ #include "tensorflow/core/platform/macros.h"
41
+ #include "tensorflow/core/platform/mutex.h"
42
+ #include "tensorflow/core/platform/thread_annotations.h"
43
+ #include "tensorflow/core/platform/types.h"
44
+ #include "tensorflow/core/profiler/lib/traceme.h"
45
+
46
+ namespace tensorflow {
47
+ namespace serving {
48
+
49
+ // The abstract superclass for a unit of work to be done as part of a batch.
50
+ //
51
+ // An implementing subclass typically contains (or points to):
52
+ // (a) input data;
53
+ // (b) a thread-safe completion signal (e.g. a Notification);
54
+ // (c) a place to store the outcome (success, or some error), upon completion;
55
+ // (d) a place to store the output data, upon success.
56
+ //
57
+ // Items (b), (c) and (d) are typically non-owned pointers to data homed
58
+ // elsewhere, because a task's ownership gets transferred to a BatchScheduler
59
+ // (see below) and it may be deleted as soon as it is done executing.
60
+ class BatchTask {
61
+ public:
62
+ virtual ~BatchTask() = default;
63
+
64
+ // Returns the size of the task, in terms of how much it contributes to the
65
+ // size of a batch. (A batch's size is the sum of its task sizes.)
66
+ virtual size_t size() const = 0;
67
+ };
68
+
69
+ // A thread-safe collection of BatchTasks, to be executed together in some
70
+ // fashion.
71
+ //
72
+ // At a given time, a batch is either "open" or "closed": an open batch can
73
+ // accept new tasks; a closed one cannot. A batch is monotonic: initially it is
74
+ // open and tasks can be added to it; then it is closed and its set of tasks
75
+ // remains fixed for the remainder of its life. A closed batch cannot be re-
76
+ // opened. Tasks can never be removed from a batch.
77
+ //
78
+ // Type parameter TaskType must be a subclass of BatchTask.
79
+ template <typename TaskType>
80
+ class Batch {
81
+ public:
82
+ Batch();
83
+ explicit Batch(uint64 traceme_context_id);
84
+ virtual ~Batch(); // Blocks until the batch is closed.
85
+
86
+ // Appends 'task' to the batch. After calling AddTask(), the newly-added task
87
+ // can be accessed via task(num_tasks()-1) or mutable_task(num_tasks()-1).
88
+ // Dies if the batch is closed.
89
+ void AddTask(std::unique_ptr<TaskType> task);
90
+
91
+ // Removes the most recently added task. Returns nullptr if the batch is
92
+ // empty.
93
+ std::unique_ptr<TaskType> RemoveTask();
94
+
95
+ // Caller takes ownership of returned tasks.
96
+ // Must be called after a batch is closed.
97
+ std::vector<std::unique_ptr<TaskType>> RemoveAllTasks();
98
+
99
+ // Returns the number of tasks in the batch.
100
+ int num_tasks() const;
101
+
102
+ // Returns true iff the batch contains 0 tasks.
103
+ bool empty() const;
104
+
105
+ // Returns a reference to the ith task (in terms of insertion order).
106
+ const TaskType& task(int i) const;
107
+
108
+ // Returns a pointer to the ith task (in terms of insertion order).
109
+ //
110
+ // Caller doesn't take ownership.
111
+ TaskType* mutable_task(int i);
112
+
113
+ // Returns the sum of the task sizes.
114
+ size_t size() const;
115
+
116
+ // Returns true iff the batch is currently closed.
117
+ bool IsClosed() const;
118
+
119
+ // Blocks until the batch is closed.
120
+ void WaitUntilClosed() const;
121
+
122
+ // Marks the batch as closed. Dies if called more than once.
123
+ void Close();
124
+
125
+ // Returns the TraceMe context id of this batch.
126
+ uint64 traceme_context_id() const;
127
+
128
+ private:
129
+ mutable mutex mu_;
130
+
131
+ // The tasks in the batch.
132
+ std::vector<std::unique_ptr<TaskType>> tasks_ TF_GUARDED_BY(mu_);
133
+
134
+ // The sum of the sizes of the tasks in 'tasks_'.
135
+ size_t size_ TF_GUARDED_BY(mu_) = 0;
136
+
137
+ std::atomic<bool> empty_ TF_GUARDED_BY(mu_){true};
138
+
139
+ // Whether the batch has been closed.
140
+ Notification closed_;
141
+
142
+ // The TracMe context id.
143
+ const uint64 traceme_context_id_;
144
+
145
+ Batch(const Batch&) = delete;
146
+ void operator=(const Batch&) = delete;
147
+ };
148
+
149
+ // An abstract batch scheduler class. Collects individual tasks into batches,
150
+ // and processes each batch on a pool of "batch threads" that it manages. The
151
+ // actual logic for processing a batch is accomplished via a callback.
152
+ //
153
+ // Type parameter TaskType must be a subclass of BatchTask.
154
+ template <typename TaskType>
155
+ class BatchScheduler {
156
+ public:
157
+ virtual ~BatchScheduler() = default;
158
+
159
+ // Submits a task to be processed as part of a batch.
160
+ //
161
+ // Ownership of '*task' is transferred to the callee iff the method returns
162
+ // Status::OK. In that case, '*task' is left as nullptr. Otherwise, '*task' is
163
+ // left as-is.
164
+ //
165
+ // If no batch processing capacity is available to process this task at the
166
+ // present time, and any task queue maintained by the implementing subclass is
167
+ // full, this method returns an UNAVAILABLE error code. The client may retry
168
+ // later.
169
+ //
170
+ // Other problems, such as the task size being larger than the maximum batch
171
+ // size, yield other, permanent error types.
172
+ //
173
+ // In all cases, this method returns "quickly" without blocking for any
174
+ // substantial amount of time. If the method returns Status::OK, the task is
175
+ // processed asynchronously, and any errors that occur during the processing
176
+ // of the batch that includes the task can be reported to 'task'.
177
+ virtual Status Schedule(std::unique_ptr<TaskType>* task) = 0;
178
+
179
+ // Returns the number of tasks that have been scheduled (i.e. accepted by
180
+ // Schedule()), but have yet to be handed to a thread for execution as part of
181
+ // a batch. Note that this returns the number of tasks, not the aggregate task
182
+ // size (so if there is one task of size 3 and one task of size 5, this method
183
+ // returns 2 rather than 8).
184
+ virtual size_t NumEnqueuedTasks() const = 0;
185
+
186
+ // Returns a guaranteed number of size 1 tasks that can be Schedule()d without
187
+ // getting an UNAVAILABLE error. In a typical implementation, returns the
188
+ // available space on a queue.
189
+ //
190
+ // There are two important caveats:
191
+ // 1. The guarantee does not extend to varying-size tasks due to possible
192
+ // internal fragmentation of batches.
193
+ // 2. The guarantee only holds in a single-thread environment or critical
194
+ // section, i.e. if an intervening thread cannot call Schedule().
195
+ //
196
+ // This method is useful for monitoring, or for guaranteeing a future slot in
197
+ // the schedule (but being mindful about the caveats listed above).
198
+ virtual size_t SchedulingCapacity() const = 0;
199
+
200
+ // Returns the maximum allowed size of tasks submitted to the scheduler. (This
201
+ // is typically equal to a configured maximum batch size.)
202
+ virtual size_t max_task_size() const = 0;
203
+ };
204
+
205
+ //////////
206
+ // Implementation details follow. API users need not read.
207
+
208
+ template <typename TaskType>
209
+ Batch<TaskType>::Batch() : Batch(0) {}
210
+
211
+ template <typename TaskType>
212
+ Batch<TaskType>::Batch(uint64 traceme_context_id)
213
+ : traceme_context_id_(traceme_context_id) {}
214
+
215
+ template <typename TaskType>
216
+ Batch<TaskType>::~Batch() {
217
+ WaitUntilClosed();
218
+ }
219
+
220
+ template <typename TaskType>
221
+ void Batch<TaskType>::AddTask(std::unique_ptr<TaskType> task) {
222
+ DCHECK(!IsClosed());
223
+ {
224
+ mutex_lock l(mu_);
225
+ size_ += task->size();
226
+ tasks_.push_back(std::move(task));
227
+ empty_.store(false);
228
+ }
229
+ }
230
+
231
+ template <typename TaskType>
232
+ std::vector<std::unique_ptr<TaskType>> Batch<TaskType>::RemoveAllTasks() {
233
+ DCHECK(IsClosed());
234
+ {
235
+ mutex_lock l(mu_);
236
+ size_ = 0;
237
+ empty_.store(true);
238
+ std::vector<std::unique_ptr<TaskType>> tasks_to_return;
239
+
240
+ // Swapping vector takes constant time.
241
+ tasks_to_return.swap(tasks_);
242
+ return std::move(tasks_to_return);
243
+ }
244
+ }
245
+
246
+ template <typename TaskType>
247
+ std::unique_ptr<TaskType> Batch<TaskType>::RemoveTask() {
248
+ {
249
+ mutex_lock l(mu_);
250
+ if (tasks_.empty()) {
251
+ return nullptr;
252
+ }
253
+ std::unique_ptr<TaskType> task = std::move(tasks_.back());
254
+ size_ -= task->size();
255
+ tasks_.pop_back();
256
+ if (tasks_.empty()) {
257
+ empty_.store(true);
258
+ }
259
+ return task;
260
+ }
261
+ }
262
+
263
+ template <typename TaskType>
264
+ int Batch<TaskType>::num_tasks() const {
265
+ {
266
+ mutex_lock l(mu_);
267
+ return tasks_.size();
268
+ }
269
+ }
270
+
271
+ template <typename TaskType>
272
+ bool Batch<TaskType>::empty() const TF_NO_THREAD_SAFETY_ANALYSIS {
273
+ // tracer is added to zoom in about this method.
274
+ // TODO(b/160249203): Remove tracer after evaluating a change to reduce
275
+ // lock contention and cpu usage (which is observed in profiler and
276
+ // very data-driven).
277
+ tensorflow::profiler::TraceMe tracer("BatchTask::empty");
278
+ return empty_.load();
279
+ }
280
+
281
+ template <typename TaskType>
282
+ const TaskType& Batch<TaskType>::task(int i) const {
283
+ DCHECK_GE(i, 0);
284
+ {
285
+ mutex_lock l(mu_);
286
+ DCHECK_LT(i, tasks_.size());
287
+ return *tasks_[i].get();
288
+ }
289
+ }
290
+
291
+ template <typename TaskType>
292
+ TaskType* Batch<TaskType>::mutable_task(int i) {
293
+ DCHECK_GE(i, 0);
294
+ {
295
+ mutex_lock l(mu_);
296
+ DCHECK_LT(i, tasks_.size());
297
+ return tasks_[i].get();
298
+ }
299
+ }
300
+
301
+ template <typename TaskType>
302
+ size_t Batch<TaskType>::size() const {
303
+ {
304
+ mutex_lock l(mu_);
305
+ return size_;
306
+ }
307
+ }
308
+
309
+ template <typename TaskType>
310
+ bool Batch<TaskType>::IsClosed() const {
311
+ return const_cast<Notification*>(&closed_)->HasBeenNotified();
312
+ }
313
+
314
+ template <typename TaskType>
315
+ void Batch<TaskType>::WaitUntilClosed() const {
316
+ const_cast<Notification*>(&closed_)->WaitForNotification();
317
+ }
318
+
319
+ template <typename TaskType>
320
+ void Batch<TaskType>::Close() {
321
+ closed_.Notify();
322
+ }
323
+
324
+ template <typename TaskType>
325
+ uint64 Batch<TaskType>::traceme_context_id() const {
326
+ return traceme_context_id_;
327
+ }
328
+
329
+ } // namespace serving
330
+ } // namespace tensorflow
331
+
332
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BATCH_SCHEDULER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/bounded_executor.h ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_CORE_KERNELS_BATCHING_UTIL_BOUNDED_EXECUTOR_H_
17
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BOUNDED_EXECUTOR_H_
18
+
19
+ #include <string>
20
+
21
+ #include "tensorflow/core/platform/status.h"
22
+ #include "tensorflow/core/platform/statusor.h"
23
+ #include "tensorflow/core/platform/thread_annotations.h"
24
+ #include "tensorflow/core/platform/threadpool.h"
25
+ #include "tensorflow/core/platform/threadpool_interface.h"
26
+
27
+ namespace tensorflow {
28
+ namespace serving {
29
+ // BoundedExecutor has a bounded number of threads and unlimited queue length,
30
+ // scheduled tasks are executed in a FIFO way.
31
+ class BoundedExecutor : public thread::ThreadPoolInterface {
32
+ public:
33
+ struct Options {
34
+ Env* env = Env::Default();
35
+ ThreadOptions thread_options;
36
+ std::string thread_name;
37
+ int num_threads = -1;
38
+ };
39
+
40
+ static StatusOr<std::unique_ptr<BoundedExecutor>> Create(
41
+ const Options& options);
42
+
43
+ // Destructor. All threads will be joined.
44
+ ~BoundedExecutor() override;
45
+
46
+ // Enqueue a function to be executed.
47
+ //
48
+ // Callers are responsible to guarantee `func` is not nullptr.
49
+ void Schedule(std::function<void()> func) override;
50
+
51
+ // Returns the number of threads.
52
+ int NumThreads() const override;
53
+
54
+ int CurrentThreadId() const override;
55
+
56
+ private:
57
+ explicit BoundedExecutor(const Options& options);
58
+
59
+ // Starts N workers (N == num_threads), polling tasks from `work_queue_`.
60
+ void InitWorker();
61
+
62
+ // A loop to fetch task from `work_queue_` and execute task.
63
+ void Run();
64
+
65
+ const Options& options_;
66
+
67
+ mutex work_queue_mu_;
68
+ std::deque<std::function<void()>> work_queue_ TF_GUARDED_BY(work_queue_mu_);
69
+ condition_variable work_queue_cv_ TF_GUARDED_BY(work_queue_mu_);
70
+
71
+ // A fixed number of threads.
72
+ std::vector<std::unique_ptr<Thread>> threads_;
73
+ BoundedExecutor(const BoundedExecutor&) = delete;
74
+ void operator=(const BoundedExecutor&) = delete;
75
+ };
76
+
77
+ } // namespace serving
78
+ } // namespace tensorflow
79
+
80
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BOUNDED_EXECUTOR_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/concat_split_util.h ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_CONCAT_SPLIT_UTIL_H_
17
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_CONCAT_SPLIT_UTIL_H_
18
+
19
+ #include "tensorflow/core/framework/op_kernel.h"
20
+ #include "tensorflow/core/framework/ops_util.h"
21
+ #include "tensorflow/core/framework/tensor.h"
22
+ #include "tensorflow/core/framework/tensor_shape.h"
23
+ #include "tensorflow/core/kernels/concat_lib.h"
24
+ #include "tensorflow/core/kernels/split_lib.h"
25
+ #include "tensorflow/core/platform/status.h"
26
+
27
+ namespace tensorflow {
28
+ namespace concat_split_util {
29
+
30
+ typedef Eigen::ThreadPoolDevice CPUDevice;
31
+ typedef Eigen::GpuDevice GPUDevice;
32
+
33
+ // Concatenates 'inputs' into a single tensor along the zeroth dimension.
34
+ // Requires that all elements of 'inputs' have element type T. Writes to
35
+ // 'output' using 'context' for the allocation to ensure proper device
36
+ // placement.
37
+ template <typename T>
38
+ Status Concat(OpKernelContext* context, const gtl::ArraySlice<Tensor> inputs,
39
+ Tensor* output) {
40
+ const int input_dims = inputs[0].dims();
41
+ const TensorShape& input_shape = inputs[0].shape();
42
+
43
+ // Note that we reduce the concat of k-dimensional tensors into a two
44
+ // dimensional concat. Assuming the dimensions of any input tensor are
45
+ // {y0, y1,...,ym-1}, we flatten it to {1, y}, where y = Prod_i(yi).
46
+ std::vector<std::unique_ptr<typename TTypes<T, 2>::ConstMatrix>> inputs_flat;
47
+ inputs_flat.reserve(inputs.size());
48
+ int64_t output_dim0 = 0;
49
+ for (size_t i = 0; i < inputs.size(); ++i) {
50
+ const Tensor& input = inputs[i];
51
+ if (input.dims() != input_dims) {
52
+ return errors::InvalidArgument(
53
+ "Ranks of all input tensors should match: shape[0] = ",
54
+ input_shape.DebugString(), " vs. shape[", i,
55
+ "] = ", input.shape().DebugString());
56
+ }
57
+ for (int j = 1; j < input_dims; ++j) {
58
+ if (input.dim_size(j) != input_shape.dim_size(j)) {
59
+ return errors::InvalidArgument(
60
+ "Dimensions of inputs should match: shape[0] = ",
61
+ input_shape.DebugString(), " vs. shape[", i,
62
+ "] = ", input.shape().DebugString());
63
+ }
64
+ }
65
+ if (input.NumElements() > 0) {
66
+ inputs_flat.emplace_back(new typename TTypes<T, 2>::ConstMatrix(
67
+ input.shaped<T, 2>({1, input.NumElements()})));
68
+ }
69
+ output_dim0 += input.dim_size(0);
70
+ }
71
+
72
+ TensorShape output_shape(input_shape);
73
+ output_shape.set_dim(0, output_dim0);
74
+ AllocatorAttributes attr;
75
+ attr.set_on_host(true);
76
+ TF_RETURN_IF_ERROR(context->allocate_temp(DataTypeToEnum<T>::value,
77
+ output_shape, output, attr));
78
+ if (output->NumElements() > 0) {
79
+ auto output_flat = output->shaped<T, 2>({1, output->NumElements()});
80
+ #if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \
81
+ (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)
82
+ if (std::is_same<Device, GPUDevice>::value) {
83
+ ConcatGPU<T>(context, inputs_flat, output, &output_flat);
84
+ return OkStatus();
85
+ }
86
+ #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
87
+ ConcatCPU<T>(context->device(), inputs_flat, &output_flat);
88
+ }
89
+
90
+ return OkStatus();
91
+ }
92
+
93
+ // Same as 'Concat' above, but handles Tensor dtype deduction automatically.
94
+ inline Status Concat(OpKernelContext* context,
95
+ const gtl::ArraySlice<Tensor> inputs, Tensor* output) {
96
+ const DataType type = inputs[0].dtype();
97
+ Status concat_status;
98
+ switch (type) {
99
+ #define CASE(type) \
100
+ case DataTypeToEnum<type>::value: \
101
+ concat_status = Concat<type>(context, inputs, output); \
102
+ break;
103
+ TF_CALL_ALL_TYPES(CASE);
104
+ #undef CASE
105
+ default:
106
+ concat_status = errors::InvalidArgument("Unsupported data type: ", type);
107
+ break;
108
+ }
109
+ return concat_status;
110
+ }
111
+
112
+ // The Split*() functions split 'input' with element type T into 'sizes.size()'
113
+ // tensors along the zeroth dimension, with the ith split having zeroth-
114
+ // dimension size 'sizes[i]'. They allocate the output tensors using 'context',
115
+ // for proper device placement.
116
+
117
+ // Handles special cases that are cheap. Sets 'done==true' iff it found an
118
+ // applicable special case and wrote to the outputs. Otherwise acts as a no-op.
119
+ template <typename T>
120
+ Status SplitEasyCases(OpKernelContext* context, const Tensor& input,
121
+ const gtl::ArraySlice<int64_t> sizes,
122
+ std::vector<Tensor>* outputs, bool* done) {
123
+ *done = false;
124
+
125
+ int64_t total_size = 0;
126
+ for (const int64_t size : sizes) {
127
+ total_size += size;
128
+ }
129
+ if (total_size > input.shape().dim_size(0)) {
130
+ return errors::InvalidArgument(
131
+ "Sum of split sizes must not exceed dim0-size of input tensor");
132
+ }
133
+
134
+ // Special case 0: trivial 1-way split.
135
+ if (sizes.size() == 1 && sizes.at(0) == input.shape().dim_size(0)) {
136
+ outputs->push_back(input);
137
+ *done = true;
138
+ return OkStatus();
139
+ }
140
+
141
+ // Special case 1: input is aligned.
142
+ if (IsInnerDimsSizeAligned<T>(input.shape())) {
143
+ int64_t position = 0;
144
+ for (const int64_t size : sizes) {
145
+ outputs->emplace_back(input.Slice(position, position + size));
146
+ position += size;
147
+ }
148
+ *done = true;
149
+ return OkStatus();
150
+ }
151
+
152
+ return OkStatus();
153
+ }
154
+
155
+ // Handles the general case, on CPU.
156
+ template <typename T>
157
+ Status SplitCPU(OpKernelContext* context, const Tensor& input,
158
+ const gtl::ArraySlice<int64_t> sizes,
159
+ std::vector<Tensor>* outputs) {
160
+ int64_t suffix_dim_size = 1;
161
+ for (int i = 1; i < input.shape().dims(); ++i) {
162
+ suffix_dim_size *= input.shape().dim_size(i);
163
+ }
164
+ auto input_reshaped =
165
+ input.shaped<T, 2>({input.shape().dim_size(0), suffix_dim_size});
166
+
167
+ int64_t position = 0;
168
+ for (const int64_t size : sizes) {
169
+ TensorShape output_shape = input.shape();
170
+ output_shape.set_dim(0, size);
171
+ Tensor output;
172
+ AllocatorAttributes attr;
173
+ attr.set_on_host(true);
174
+ TF_RETURN_IF_ERROR(
175
+ context->allocate_temp(input.dtype(), output_shape, &output, attr));
176
+ auto output_shaped = output.shaped<T, 2>({size, suffix_dim_size});
177
+
178
+ Eigen::DSizes<Eigen::DenseIndex, 2> slice_indices{
179
+ static_cast<Eigen::DenseIndex>(position), 0};
180
+ Eigen::DSizes<Eigen::DenseIndex, 2> slice_sizes{
181
+ static_cast<Eigen::DenseIndex>(size),
182
+ static_cast<Eigen::DenseIndex>(suffix_dim_size)};
183
+ functor::Split<CPUDevice, T, 2>()(context->eigen_device<CPUDevice>(),
184
+ output_shaped, input_reshaped,
185
+ slice_indices, slice_sizes);
186
+
187
+ outputs->emplace_back(output);
188
+
189
+ position += size;
190
+ }
191
+
192
+ return OkStatus();
193
+ }
194
+
195
+ #if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \
196
+ (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)
197
+
198
+ // Handles the general case, on GPU.
199
+ template <typename T>
200
+ Status SplitGPU(OpKernelContext* context, const Tensor& input,
201
+ const gtl::ArraySlice<int64_t>& sizes,
202
+ std::vector<Tensor>* outputs) {
203
+ // TODO(olston, apassos): Implement this.
204
+ LOG(FATAL) << "Not yet implemented"; // Crash ok
205
+ }
206
+
207
+ #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
208
+
209
+ // The outer function that dispatches to the various Split*() functions above.
210
+ template <typename T>
211
+ Status Split(OpKernelContext* context, const Tensor& input,
212
+ const gtl::ArraySlice<int64_t> sizes,
213
+ std::vector<Tensor>* outputs) {
214
+ bool easy_cases_done;
215
+ TF_RETURN_IF_ERROR(
216
+ SplitEasyCases<T>(context, input, sizes, outputs, &easy_cases_done));
217
+ if (easy_cases_done) {
218
+ return OkStatus();
219
+ }
220
+
221
+ #if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \
222
+ (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)
223
+ // TODO(olston, apassos): Handle non-CPU cases.
224
+ // return SplitGPU<T>(context, input, sizes, outputs);
225
+ #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
226
+ return SplitCPU<T>(context, input, sizes, outputs);
227
+ }
228
+
229
+ // Same as 'Split' above, but handles Tensor dtype automatically.
230
+ inline Status Split(OpKernelContext* context, const Tensor& input,
231
+ const gtl::ArraySlice<int64_t> sizes,
232
+ std::vector<Tensor>* outputs) {
233
+ const DataType type = input.dtype();
234
+ Status split_status;
235
+ switch (type) {
236
+ #define CASE(type) \
237
+ case DataTypeToEnum<type>::value: \
238
+ split_status = Split<type>(context, input, sizes, outputs); \
239
+ break;
240
+ TF_CALL_ALL_TYPES(CASE);
241
+ #undef CASE
242
+ default:
243
+ split_status = errors::InvalidArgument("Unsupported data type: ", type);
244
+ break;
245
+ }
246
+ return split_status;
247
+ }
248
+
249
+ } // namespace concat_split_util
250
+ } // namespace tensorflow
251
+
252
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_CONCAT_SPLIT_UTIL_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/input_split_metadata.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_CORE_KERNELS_BATCHING_UTIL_INPUT_SPLIT_METADATA_H_
17
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_INPUT_SPLIT_METADATA_H_
18
+
19
+ #include <algorithm>
20
+
21
+ #include "absl/container/fixed_array.h"
22
+
23
+ namespace tensorflow {
24
+ namespace serving {
25
+ namespace internal {
26
+ // InputSplitMetadata represents the task sizes of an batch-task after it's
27
+ // tailored according to queue status (`open_batch_remaining_slot` and
28
+ // `batch_size_limit`).
29
+ //
30
+ // This is an internal helper class, and the implementation is shared
31
+ // shared across different instantiations of internal::Queue<TaskType>
32
+ // in input-split mode (QueueOptions.enable_large_batch_splitting is true).
33
+ class InputSplitMetadata {
34
+ public:
35
+ InputSplitMetadata(int input_task_size, int open_batch_remaining_slot,
36
+ int batch_size_limit);
37
+
38
+ // Returns underlying task sizes.
39
+ const absl::FixedArray<int>& task_sizes() const;
40
+
41
+ // Serializes task split metadata into a string for debugging.
42
+ std::string DebugString() const;
43
+
44
+ private:
45
+ absl::FixedArray<int> generate_task_sizes(int input_task_size,
46
+ int open_batch_remaining_slot,
47
+ int batch_size_limit) const;
48
+
49
+ const absl::FixedArray<int> task_sizes_;
50
+ };
51
+ } // namespace internal
52
+ } // namespace serving
53
+ } // namespace tensorflow
54
+
55
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_INPUT_SPLIT_METADATA_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/periodic_function.h ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ // PeriodicFunction will periodically call the given function with a specified
17
+ // period in a background thread. After Start() returns, the thread is
18
+ // guaranteed to have started. The destruction of the class causes the
19
+ // background thread to be destroyed as well. Start() should not be called more
20
+ // than once.
21
+ //
22
+ // PeriodicFunction runs the function as soon as any previous run both is
23
+ // complete and was started more than "interval_micros" earlier. Thus, runs are
24
+ // both serialized, and normally have a period of "interval_micros" if no run
25
+ // exceeds the time.
26
+ //
27
+ // Note that, if the function takes longer than two interval_micross to finish,
28
+ // then PeriodicFunction will "skip" at least one call to the function. For
29
+ // instance, if the period is 50ms and the function starts runs at time 0 for
30
+ // 150ms, then the function will immediately start executing again at time 150,
31
+ // but there will be no function runs corresponding to times 50 or 100. This is
32
+ // especially important to remember when using an environment with a simulated
33
+ // clock: advancing simulated time atomically over N interval_micross will not
34
+ // cause the function to be called N times.
35
+ //
36
+ // This object is thread-safe.
37
+ //
38
+ // Example:
39
+ //
40
+ // class Foo {
41
+ // public:
42
+ // Foo() : periodic_function_([this]() { Bar(); },
43
+ // 1000 /* 1000us == 1ms*/) {
44
+ // }
45
+ //
46
+ // private:
47
+ // void Bar() { ... }
48
+ //
49
+ // PeriodicFunction periodic_function_;
50
+ // };
51
+
52
+ #ifndef TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_PERIODIC_FUNCTION_H_
53
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_PERIODIC_FUNCTION_H_
54
+
55
+ #include <functional>
56
+ #include <memory>
57
+ #include <string>
58
+
59
+ #include "absl/functional/any_invocable.h"
60
+ #include "tensorflow/core/lib/core/notification.h"
61
+ #include "tensorflow/core/platform/env.h"
62
+ #include "tensorflow/core/platform/macros.h"
63
+ #include "tensorflow/core/platform/types.h"
64
+
65
+ namespace tensorflow {
66
+ namespace serving {
67
+
68
+ namespace internal {
69
+ class PeriodicFunctionTestAccess;
70
+ }
71
+
72
+ class PeriodicFunction {
73
+ public:
74
+ // Provides the ability to customize several aspects of the PeriodicFunction.
75
+ // Passed to constructor of PeriodicFunction.
76
+ struct Options {
77
+ Options() {}
78
+
79
+ // Any standard thread options, such as stack size, should
80
+ // be passed via "thread_options".
81
+ ThreadOptions thread_options;
82
+
83
+ // Specifies the thread name prefix (see the description in class
84
+ // Thread).
85
+ string thread_name_prefix = "periodic_function";
86
+
87
+ // The environment to use. Does not take ownership, but must remain alive
88
+ // for as long as the PeriodicFunction exists.
89
+ Env* env = Env::Default();
90
+
91
+ // Specifies the length of sleep before the first invocation of the
92
+ // function.
93
+ // This can be used for adding a random jitter to avoid synchronous behavior
94
+ // across multiple periodic functions.
95
+ int64_t startup_delay_micros = 0;
96
+ };
97
+
98
+ // Also starts the background thread which will be calling the function.
99
+ PeriodicFunction(absl::AnyInvocable<void()> function, int64_t interval_micros,
100
+ const Options& options = Options());
101
+
102
+ ~PeriodicFunction();
103
+
104
+ private:
105
+ friend class internal::PeriodicFunctionTestAccess;
106
+
107
+ // Notifies the background thread to stop.
108
+ void NotifyStop();
109
+
110
+ // (Blocking.) Loops forever calling "function_" every "interval_micros_".
111
+ void RunLoop(int64_t start);
112
+
113
+ absl::AnyInvocable<void()> function_; // Actual client function
114
+ const int64_t interval_micros_; // Interval between calls.
115
+ const Options options_;
116
+
117
+ // Used to notify the thread to stop.
118
+ Notification stop_thread_;
119
+
120
+ // Thread for running "function_"
121
+ std::unique_ptr<Thread> thread_ = nullptr;
122
+
123
+ PeriodicFunction(const PeriodicFunction&) = delete;
124
+ void operator=(const PeriodicFunction&) = delete;
125
+ };
126
+
127
+ } // namespace serving
128
+ } // namespace tensorflow
129
+
130
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_PERIODIC_FUNCTION_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/shared_batch_scheduler.h ADDED
@@ -0,0 +1,1290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_CORE_KERNELS_BATCHING_UTIL_SHARED_BATCH_SCHEDULER_H_
17
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_SHARED_BATCH_SCHEDULER_H_
18
+
19
+ #include <stddef.h>
20
+
21
+ #include <deque>
22
+ #include <functional>
23
+ #include <list>
24
+ #include <memory>
25
+ #include <utility>
26
+ #include <vector>
27
+
28
+ #include "absl/time/clock.h"
29
+ #include "absl/types/variant.h"
30
+ #include "tensorflow/core/kernels/batching_util/batch_input_task.h"
31
+ #include "tensorflow/core/kernels/batching_util/batch_scheduler.h"
32
+ #include "tensorflow/core/kernels/batching_util/periodic_function.h"
33
+ #include "tensorflow/core/lib/core/errors.h"
34
+ #include "tensorflow/core/lib/core/status.h"
35
+ #include "tensorflow/core/lib/strings/strcat.h"
36
+ #include "tensorflow/core/platform/cpu_info.h"
37
+ #include "tensorflow/core/platform/env.h"
38
+ #include "tensorflow/core/platform/errors.h"
39
+ #include "tensorflow/core/platform/thread_annotations.h"
40
+ #include "tensorflow/core/platform/types.h"
41
+ #include "tensorflow/core/profiler/lib/connected_traceme.h"
42
+ #include "tensorflow/core/profiler/lib/traceme.h"
43
+ #include "tensorflow/core/profiler/lib/traceme_encode.h"
44
+
45
+ namespace tensorflow {
46
+ namespace serving {
47
+ namespace internal {
48
+ template <typename TaskType>
49
+ class Queue;
50
+ } // namespace internal
51
+ } // namespace serving
52
+ } // namespace tensorflow
53
+
54
+ namespace tensorflow {
55
+ namespace serving {
56
+
57
+ // A batch scheduler for server instances that service multiple request types
58
+ // (e.g. multiple machine-learned models, or multiple versions of a model served
59
+ // concurrently), or even multiple distinct tasks for a given request. The
60
+ // scheduler multiplexes batches of different kinds of tasks onto a fixed-size
61
+ // thread pool (each batch contains tasks of a single type), in a carefully
62
+ // controlled manner. A common configuration is to set the number of threads
63
+ // equal to the number of hardware accelerator units, in which case the
64
+ // scheduler takes care of multiplexing the task types onto the shared hardware,
65
+ // in a manner that is both fair and efficient.
66
+ //
67
+ // Semantically, SharedBatchScheduler behaves like having N instances of
68
+ // BasicBatchScheduler (see basic_batch_scheduler.h), one per task type. The
69
+ // difference is that under the covers there is a single shared thread pool,
70
+ // instead of N independent ones, with their sharing deliberately coordinated.
71
+ //
72
+ // SharedBatchScheduler does not implement the BatchScheduler API; rather, it
73
+ // presents an abstraction of "queues", where each queue corresponds to one type
74
+ // of task. Tasks submitted to a given queue are placed in their own batches,
75
+ // and cannot be mixed with other tasks. Queues can be added and deleted
76
+ // dynamically, to accommodate e.g. versions of a model being brought up and
77
+ // down over the lifetime of a server.
78
+ //
79
+ // The batch thread pool round-robins through the queues, running one batch
80
+ // from a queue and then moving to the next queue. Each queue behaves like a
81
+ // BasicBatchScheduler instance, in the sense that it has maximum batch size and
82
+ // timeout parameters, which govern when a batch is eligible to be processed.
83
+ //
84
+ // Each queue is independently configured with a maximum size (in terms of the
85
+ // maximum number of batches worth of enqueued tasks). For online serving, it is
86
+ // recommended that the queue sizes be configured such that the sum of the sizes
87
+ // of the active queues roughly equal the number of batch threads. (The idea is
88
+ // that if all threads become available at roughly the same time, there will be
89
+ // enough enqueued work for them to take on, but no more.)
90
+ //
91
+ // If queue sizes are configured in the manner suggested above, the maximum time
92
+ // a task can spend in a queue before being placed in a batch and assigned to a
93
+ // thread for processing, is the greater of:
94
+ // - the maximum time to process one batch of tasks from any active queue
95
+ // - the configured timeout parameter for the task's queue (which can be 0)
96
+ //
97
+ // For bulk processing jobs and throughput-oriented benchmarks, you may want to
98
+ // set the maximum queue size to a large value.
99
+ //
100
+ // TODO(b/26539183): Support queue servicing policies other than round-robin.
101
+ // E.g. let each queue specify a "share" (an int >= 1), so e.g. with queues A
102
+ // and B having shares 1 and 2 respectively, the servicing pattern is ABBABB...
103
+ //
104
+ //
105
+ // PERFORMANCE TUNING: See README.md.
106
+ //
107
+ template <typename TaskType>
108
+ class SharedBatchScheduler
109
+ : public std::enable_shared_from_this<SharedBatchScheduler<TaskType>> {
110
+ public:
111
+ using BatchTaskHandleUniquePtr =
112
+ std::unique_ptr<Batch<internal::BatchInputTaskHandle<TaskType>>>;
113
+ using BatchTaskUniqueptr = std::unique_ptr<Batch<TaskType>>;
114
+ using BatchUniquePtr =
115
+ absl::variant<BatchTaskUniqueptr, BatchTaskHandleUniquePtr>;
116
+ // TODO(b/25089730): Tune defaults based on best practices as they develop.
117
+ struct Options {
118
+ // The name to use for the pool of batch threads.
119
+ string thread_pool_name = {"batch_threads"};
120
+
121
+ // The number of threads to use to process batches.
122
+ // Must be >= 1, and should be tuned carefully.
123
+ int num_batch_threads = port::MaxParallelism();
124
+
125
+ // The environment to use.
126
+ // (Typically only overridden by test code.)
127
+ Env* env = Env::Default();
128
+ };
129
+ // Ownership is shared between the caller of Create() and any queues created
130
+ // via AddQueue().
131
+ static Status Create(
132
+ const Options& options,
133
+ std::shared_ptr<SharedBatchScheduler<TaskType>>* scheduler);
134
+
135
+ ~SharedBatchScheduler();
136
+
137
+ // Adds a queue to which tasks may be submitted. The returned queue implements
138
+ // the BatchScheduler API. Each queue has its own set of scheduling options,
139
+ // and its own callback to process batches of tasks submitted to the queue.
140
+ //
141
+ // The returned queue's destructor blocks until all tasks submitted to it have
142
+ // been processed.
143
+ struct QueueOptions {
144
+ // The size limit of an input batch to the queue.
145
+ //
146
+ // If `enable_large_batch_splitting` is True, 'input_batch_size_limit'
147
+ // should be greater or equal than `max_execution_batch_size`; otherwise
148
+ // `input_batch_size_limit` should be equal to `max_execution_batch_size`.
149
+ size_t input_batch_size_limit = 1000;
150
+
151
+ // If a task has been enqueued for this amount of time (in microseconds),
152
+ // and a thread is available, the scheduler will immediately form a batch
153
+ // from enqueued tasks and assign the batch to the thread for processing,
154
+ // even if the batch's size is below 'input_batch_size_limit'.
155
+ //
156
+ // This parameter offers a way to bound queue latency, so that a task isn't
157
+ // stuck in the queue indefinitely waiting for enough tasks to arrive to
158
+ // make a full batch. (The latency bound is given in the class documentation
159
+ // above.)
160
+ //
161
+ // The goal is to smooth out batch sizes under low request rates, and thus
162
+ // avoid latency spikes.
163
+ int64_t batch_timeout_micros = 0;
164
+
165
+ // The maximum allowable number of enqueued (accepted by Schedule() but
166
+ // not yet being processed on a batch thread) tasks in terms of batches.
167
+ // If this limit is reached, Schedule() will return an UNAVAILABLE error.
168
+ // See the class documentation above for guidelines on how to tune this
169
+ // parameter.
170
+ //
171
+ // Must be positive, or else invalid argument error will be returned at
172
+ // queue creation time.
173
+ size_t max_enqueued_batches = 10;
174
+
175
+ // If true, queue implementation would split one input batch task into
176
+ // subtasks (as specified by `split_input_task_func` below) and fit subtasks
177
+ // into different batches.
178
+ //
179
+ // For usage of `split_input_task_func`, please see its comment.
180
+ bool enable_large_batch_splitting = false;
181
+
182
+ // `input_task`: a unit of task to be split.
183
+ // `first_output_task_size`: task size of first output.
184
+ // `max_execution_batch_size`: Maximum size of each batch.
185
+ // `output_tasks`: A list of output tasks after split.
186
+ //
187
+ // REQUIRED:
188
+ // 1) All `output_tasks` should be non-empty tasks.
189
+ // 2) Sizes of `output_tasks` add up to size of `input_task`.
190
+ //
191
+ // NOTE:
192
+ // Instantiations of `TaskType` may vary, so it's up to caller to define
193
+ // how (e.g., which members to access) to split input tasks.
194
+ std::function<Status(std::unique_ptr<TaskType>* input_task,
195
+ int first_output_task_size, int input_batch_size_limit,
196
+ std::vector<std::unique_ptr<TaskType>>* output_tasks)>
197
+ split_input_task_func;
198
+
199
+ // If true, batch input tasks are split lazily after dequeue and not on the
200
+ // critical path of enqueue operations.
201
+ //
202
+ // Must be false if `enable_large_batch_splitting` is false; elsewise errors
203
+ // will be returned at queue creation time.
204
+ //
205
+ // TODO(b/194294263):
206
+ // Make `enable_lazy_split` a template parameter of queue, and adapts
207
+ // `high_priority_batches_` and `task_handle_batches_` into one deque of
208
+ // tensorflow::serving::Batch.
209
+ bool enable_lazy_split = false;
210
+
211
+ // The maximum size of each enqueued batch (i.e., in
212
+ // `high_priority_batches_`).
213
+ //
214
+ // The scheduler may form batches of any size between 1 and this number
215
+ // (inclusive). If there is a need to quantize the batch sizes, i.e. only
216
+ // submit batches whose size is in a small set of allowed sizes, that can be
217
+ // done by adding padding in the process-batch callback.
218
+ size_t max_execution_batch_size = 1000;
219
+
220
+ // If true, the padding will not be appended.
221
+ bool disable_padding = false;
222
+
223
+ // If true, queue implementation would split high priority and low priority
224
+ // inputs into two sub queues.
225
+ bool enable_priority_queue = false;
226
+
227
+ // A separate set of queue options for different priority inputs.
228
+ // Use iff `enable_priority_queue` is true.
229
+ struct PriorityQueueOptions {
230
+ // See QueueOptions.max_execution_batch_size
231
+ size_t max_execution_batch_size = 0;
232
+ // See QueueOptions.batch_timeout_micros
233
+ int64_t batch_timeout_micros = 0;
234
+ // See QueueOptions.input_batch_size_limit
235
+ size_t input_batch_size_limit = 0;
236
+ // See QueueOptions.max_enqueued_batches
237
+ size_t max_enqueued_batches = 0;
238
+ };
239
+ // A subset of queue options for high priority input.
240
+ PriorityQueueOptions high_priority_queue_options;
241
+ // A subset of queue options for low priority input.
242
+ PriorityQueueOptions low_priority_queue_options;
243
+ };
244
+ Status AddQueue(const QueueOptions& options,
245
+ std::function<void(std::unique_ptr<Batch<TaskType>>)>
246
+ process_batch_callback,
247
+ std::unique_ptr<BatchScheduler<TaskType>>* queue);
248
+
249
+ private:
250
+ explicit SharedBatchScheduler(const Options& options);
251
+
252
+ void GetNextWorkItem_Locked(internal::Queue<TaskType>** queue_for_batch_out,
253
+ BatchUniquePtr* batch_to_process_out)
254
+ TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
255
+
256
+ // The code executed in 'batch_threads_'. Obtains a batch to process from the
257
+ // queue pointed to by 'next_queue_to_schedule_', and processes it. If that
258
+ // queue declines to provide a batch to process, moves onto the next queue. If
259
+ // no queues provide a batch to process, just sleeps briefly and exits.
260
+ void ThreadLogic();
261
+
262
+ // Called by `AddQueue`.
263
+ Status AddQueueAfterRewritingOptions(
264
+ const QueueOptions& options,
265
+ std::function<void(std::unique_ptr<Batch<TaskType>>)>
266
+ process_batch_callback,
267
+ std::unique_ptr<BatchScheduler<TaskType>>* queue);
268
+
269
+ static bool BatchExists(const BatchUniquePtr& batch_to_process);
270
+
271
+ const Options options_;
272
+
273
+ mutex mu_;
274
+
275
+ // A list of queues. (We use std::list instead of std::vector to ensure that
276
+ // iterators are not invalidated by adding/removing elements. It also offers
277
+ // efficient removal of elements from the middle.)
278
+ using QueueList = std::list<std::unique_ptr<internal::Queue<TaskType>>>;
279
+
280
+ // All "active" queues, i.e. ones that either:
281
+ // - have not been removed, or
282
+ // - have been removed but are not yet empty.
283
+ QueueList queues_ TF_GUARDED_BY(mu_);
284
+
285
+ // An iterator over 'queues_', pointing to the queue from which the next
286
+ // available batch thread should grab work.
287
+ typename QueueList::iterator next_queue_to_schedule_ TF_GUARDED_BY(mu_);
288
+
289
+ // Used by idle batch threads to wait for work to enter the system. Notified
290
+ // whenever a batch becomes schedulable.
291
+ condition_variable schedulable_batch_cv_;
292
+
293
+ // Threads that process batches obtained from the queues.
294
+ std::vector<std::unique_ptr<PeriodicFunction>> batch_threads_;
295
+
296
+ SharedBatchScheduler(const SharedBatchScheduler&) = delete;
297
+ void operator=(const SharedBatchScheduler&) = delete;
298
+ };
299
+
300
+ //////////
301
+ // Implementation details follow. API users need not read.
302
+
303
+ namespace internal {
304
+
305
+ // A task queue for SharedBatchScheduler. Accepts tasks and accumulates them
306
+ // into batches, and dispenses those batches to be processed via a "pull"
307
+ // interface. The queue's behavior is governed by maximum batch size, timeout
308
+ // and maximum queue length parameters; see their documentation in
309
+ // SharedBatchScheduler.
310
+ //
311
+ // The queue is implemented as a deque of batches, with these invariants:
312
+ // - The number of batches is between 1 and 'options_.max_enqueued_batches'.
313
+ // - The back-most batch is open; the rest are closed.
314
+ //
315
+ // Submitted tasks are added to the open batch. If that batch doesn't have room
316
+ // but the queue isn't full, then that batch is closed and a new open batch is
317
+ // started.
318
+ //
319
+ // Batch pull requests are handled by dequeuing the front-most batch if it is
320
+ // closed. If the front-most batch is open (i.e. the queue contains only one
321
+ // batch) and has reached the timeout, it is immediately closed and returned;
322
+ // otherwise no batch is returned for the request.
323
+ template <typename TaskType>
324
+ class Queue {
325
+ public:
326
+ using ProcessBatchCallback =
327
+ std::function<void(std::unique_ptr<Batch<TaskType>>)>;
328
+ using SchedulableBatchCallback = std::function<void()>;
329
+ using SplitInputTaskIntoSubtasksCallback = std::function<Status(
330
+ std::unique_ptr<TaskType>* input_task, int open_batch_remaining_slot,
331
+ int max_execution_batch_size,
332
+ std::vector<std::unique_ptr<TaskType>>* output_tasks)>;
333
+ Queue(const typename SharedBatchScheduler<TaskType>::QueueOptions& options,
334
+ Env* env, ProcessBatchCallback process_batch_callback,
335
+ SchedulableBatchCallback schedulable_batch_callback);
336
+
337
+ // Illegal to destruct unless the queue is empty.
338
+ ~Queue();
339
+
340
+ // Submits a task to the queue, with the same semantics as
341
+ // BatchScheduler::Schedule().
342
+ Status Schedule(std::unique_ptr<TaskType>* task);
343
+
344
+ // Enqueue `task` as it is OR split it inline (eagerly) to form batches to be
345
+ // processed by `Queue<TaskType>::ProcessBatch`
346
+ Status ScheduleWithoutOrEagerSplit(std::unique_ptr<TaskType>* task);
347
+
348
+ // Enqueue `task` along with the batch queue metadata.
349
+ // Batches are formed by the time `ScheduleWithLazySplit` returns; and each
350
+ // batch in the deque could evaluate to a batch to be processed after it's
351
+ // dequeued (out of mutex-protected area).
352
+ Status ScheduleWithLazySplit(std::unique_ptr<TaskType>* task);
353
+
354
+ // Returns the number of enqueued tasks, with the same semantics as
355
+ // BatchScheduler::NumEnqueuedTasks().
356
+ size_t NumEnqueuedTasks() const;
357
+
358
+ // Returns the queue capacity, with the same semantics as
359
+ // BatchScheduler::SchedulingCapacity().
360
+ size_t SchedulingCapacity() const;
361
+
362
+ // Returns the maximum allowed size of tasks submitted to the queue.
363
+ size_t max_task_size() const { return options_.input_batch_size_limit; }
364
+
365
+ // Returns the maximum allowed size of tasks to be executed.
366
+ // Returned value would be less than or equal to the maximum allowed input
367
+ // size that's provided by caller of batch scheduler.
368
+ size_t max_execution_batch_size() const { return max_execution_batch_size_; }
369
+
370
+ // Called by a thread that is ready to process a batch, to request one from
371
+ // this queue. Either returns a batch that is ready to be processed, or
372
+ // nullptr if the queue declines to schedule a batch at this time. If it
373
+ // returns a batch, the batch is guaranteed to be closed.
374
+ typename SharedBatchScheduler<TaskType>::BatchUniquePtr ScheduleBatch();
375
+
376
+ // A variant of `ScheduleBatch`.
377
+ // Batches are guaranteed to form at task enqueue time.
378
+ std::unique_ptr<Batch<TaskType>> ScheduleBatchWithEagerSplit();
379
+
380
+ // Processes a batch that has been returned earlier by ScheduleBatch().
381
+ void ProcessBatch(std::unique_ptr<Batch<TaskType>> batch);
382
+
383
+ // Determines whether the queue is empty, i.e. has no tasks waiting or being
384
+ // processed.
385
+ bool IsEmpty() const;
386
+
387
+ // Marks the queue closed, and waits until it is empty.
388
+ void CloseAndWaitUntilEmpty();
389
+
390
+ bool closed() const TF_NO_THREAD_SAFETY_ANALYSIS { return closed_.load(); }
391
+
392
+ private:
393
+ // Computes the max_execution_batch_size of the queue based on queue options.
394
+ static size_t GetMaxExecutionBatchSize(
395
+ const typename SharedBatchScheduler<TaskType>::QueueOptions& options) {
396
+ // If `enable_large_batch_splitting`, returns `max_execution_batch_size`
397
+ // configured by user options directly; returns `input_batch_size_limit`
398
+ // otherwise.
399
+ //
400
+ // Note `input_batch_size_limit` is used for backward compatibitliy ->
401
+ // users may not specify `max_execution_batch_size` explicitly.
402
+ if (options.enable_large_batch_splitting) {
403
+ return options.max_execution_batch_size;
404
+ } else {
405
+ return options.input_batch_size_limit;
406
+ }
407
+ }
408
+
409
+ // Same as IsEmpty(), but assumes the caller already holds a lock on 'mu_'.
410
+ bool IsEmptyInternal() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
411
+
412
+ // Closes the open batch residing at the back of std::deque, and inserts a
413
+ // fresh open batch behind it.
414
+ void StartNewBatch() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
415
+
416
+ // Split `input task` into `output_tasks` according to 'task_sizes'.
417
+ Status SplitInputBatchIntoSubtasks(
418
+ std::unique_ptr<TaskType>* input_task,
419
+ std::vector<std::unique_ptr<TaskType>>* output_tasks)
420
+ TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
421
+
422
+ // Determines whether the open batch residing at the back of
423
+ // 'high_priority_batches_' is currently schedulable.
424
+ bool IsOpenBatchSchedulable() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
425
+
426
+ // A variant of `IsOpenBatchSchedulable`; used when batches are formed at
427
+ // task enqueue time, and open batch is `high_priority_batches_.back()`.
428
+ bool IsOpenBatchSchedulableAfterEagerSplit() const
429
+ TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
430
+
431
+ // Same as SchedulingCapacity(), but assumes the caller already holds a
432
+ // lock on 'mu_'.
433
+ size_t SchedulingCapacityInternal() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
434
+
435
+ // Returns an error if queue doesn't have capacity for this task.
436
+ //
437
+ // `task` must outlive this method.
438
+ Status ValidateBatchTaskQueueCapacity(TaskType* task) const
439
+ TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
440
+
441
+ // The task size of the last batch in the queue.
442
+ size_t tail_batch_task_size() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
443
+
444
+ // Returns the number of enqueued batches.
445
+ int64 num_enqueued_batches() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
446
+
447
+ // Gets the appropriate batches.
448
+ std::deque<std::unique_ptr<Batch<TaskType>>>& GetBatches()
449
+ TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
450
+
451
+ // Gets the appropriate batches (const version).
452
+ const std::deque<std::unique_ptr<Batch<TaskType>>>& GetBatches() const
453
+ TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
454
+
455
+ const typename SharedBatchScheduler<TaskType>::QueueOptions options_;
456
+
457
+ // The environment to use.
458
+ Env* env_;
459
+
460
+ // The maximum batch size to be executed by `Queue::ProcessBatch`.
461
+ // See the comment of QueueOptions and helper function
462
+ // `GetMaxExecutionBatchSize` for more details on what it means.
463
+ const size_t max_execution_batch_size_;
464
+
465
+ // A callback invoked to processes a batch of work units. Always invoked
466
+ // from a batch thread.
467
+ ProcessBatchCallback process_batch_callback_;
468
+
469
+ // A callback invoked to notify the scheduler that a new batch has become
470
+ // schedulable.
471
+ SchedulableBatchCallback schedulable_batch_callback_;
472
+
473
+ mutable mutex mu_;
474
+
475
+ // Whether this queue can accept new tasks. This variable is monotonic: it
476
+ // starts as false, and then at some point gets set to true and remains true
477
+ // for the duration of this object's life.
478
+ std::atomic<bool> closed_ TF_GUARDED_BY(mu_){false};
479
+
480
+ // The enqueued batches.
481
+ //
482
+ // Each element corresponds to the `task` enqueued in `Queue::Schedule`; the
483
+ // element could be split and processed in batches at dequeue time.
484
+ //
485
+ // Used iff `QueueOptions.enable_lazy_split` is true.
486
+ std::deque<std::unique_ptr<Batch<BatchInputTaskHandle<TaskType>>>>
487
+ task_handle_batches_ TF_GUARDED_BY(mu_);
488
+
489
+ // The enqueued batches for low priority input.
490
+ // Each element corresponds to a task to be dequeued and processed by
491
+ // `Queue<TaskType>::ProcessBatch`.
492
+ //
493
+ // Used iff `QueueOptions.enable_lazy_split` is false.
494
+ std::deque<std::unique_ptr<Batch<TaskType>>> low_priority_batches_
495
+ TF_GUARDED_BY(mu_);
496
+
497
+ // The enqueued batches for high priority input.
498
+ // Each element corresponds to a task to be dequeued and processed by
499
+ // `Queue<TaskType>::ProcessBatch`.
500
+ //
501
+ // Used iff `QueueOptions.enable_lazy_split` is false.
502
+ std::deque<std::unique_ptr<Batch<TaskType>>> high_priority_batches_
503
+ TF_GUARDED_BY(mu_);
504
+
505
+ // The counter of the TraceMe context ids.
506
+ uint64 traceme_context_id_counter_ TF_GUARDED_BY(mu_) = 0;
507
+
508
+ // The time at which the first task was added to the open (back-most) batch
509
+ // in 'high_priority_batches_'. Valid iff that batch contains at least one
510
+ // task.
511
+ uint64 open_batch_start_time_micros_ TF_GUARDED_BY(mu_);
512
+
513
+ // Whether this queue contains a batch that is eligible to be scheduled.
514
+ // Used to keep track of when to call 'schedulable_batch_callback_'.
515
+ bool schedulable_batch_ TF_GUARDED_BY(mu_) = false;
516
+
517
+ // The number of batches currently being processed by batch threads.
518
+ // Incremented in ScheduleBatch() and decremented in ProcessBatch().
519
+ int num_batches_being_processed_ TF_GUARDED_BY(mu_) = 0;
520
+
521
+ // Used by CloseAndWaitUntilEmpty() to wait until the queue is empty, for
522
+ // the case in which the queue is not empty when CloseAndWaitUntilEmpty()
523
+ // starts. When ProcessBatch() dequeues the last batch and makes the queue
524
+ // empty, if 'empty_notification_' is non-null it calls
525
+ // 'empty_notification_->Notify()'.
526
+ Notification* empty_notification_ TF_GUARDED_BY(mu_) = nullptr;
527
+
528
+ Queue(const Queue&) = delete;
529
+ void operator=(const Queue&) = delete;
530
+ };
531
+
532
+ // A RAII-style object that points to a Queue and implements
533
+ // the BatchScheduler API. To be handed out to clients who call AddQueue().
534
+ template <typename TaskType>
535
+ class QueueHandle : public BatchScheduler<TaskType> {
536
+ public:
537
+ QueueHandle(std::shared_ptr<SharedBatchScheduler<TaskType>> scheduler,
538
+ Queue<TaskType>* queue);
539
+ ~QueueHandle() override;
540
+
541
+ Status Schedule(std::unique_ptr<TaskType>* task) override;
542
+ size_t NumEnqueuedTasks() const override;
543
+ size_t SchedulingCapacity() const override;
544
+
545
+ size_t max_task_size() const override { return queue_->max_task_size(); }
546
+
547
+ private:
548
+ // The scheduler that owns 'queue_'.
549
+ std::shared_ptr<SharedBatchScheduler<TaskType>> scheduler_;
550
+
551
+ // The queue this handle wraps. Owned by 'scheduler_', which keeps it alive at
552
+ // least until this class's destructor closes it.
553
+ Queue<TaskType>* queue_;
554
+
555
+ QueueHandle(const QueueHandle&) = delete;
556
+ void operator=(const QueueHandle&) = delete;
557
+ };
558
+
559
+ } // namespace internal
560
+
561
+ template <typename TaskType>
562
+ Status SharedBatchScheduler<TaskType>::Create(
563
+ const Options& options,
564
+ std::shared_ptr<SharedBatchScheduler<TaskType>>* scheduler) {
565
+ if (options.num_batch_threads < 1) {
566
+ return errors::InvalidArgument("num_batch_threads must be positive; was ",
567
+ options.num_batch_threads);
568
+ }
569
+ scheduler->reset(new SharedBatchScheduler<TaskType>(options));
570
+ return OkStatus();
571
+ }
572
+
573
+ template <typename TaskType>
574
+ SharedBatchScheduler<TaskType>::~SharedBatchScheduler() {
575
+ // Wait until the batch threads finish clearing out and deleting the closed
576
+ // queues.
577
+ for (;;) {
578
+ {
579
+ mutex_lock l(mu_);
580
+ if (queues_.empty()) {
581
+ break;
582
+ }
583
+ }
584
+ const int64_t kSleepTimeMicros = 100;
585
+ options_.env->SleepForMicroseconds(kSleepTimeMicros);
586
+ }
587
+ // Delete the batch threads before allowing state the threads may access (e.g.
588
+ // 'mu_') to be deleted.
589
+ batch_threads_.clear();
590
+ }
591
+
592
+ template <typename TaskType>
593
+ Status SharedBatchScheduler<TaskType>::AddQueue(
594
+ const QueueOptions& options,
595
+ std::function<void(std::unique_ptr<Batch<TaskType>>)>
596
+ process_batch_callback,
597
+ std::unique_ptr<BatchScheduler<TaskType>>* queue) {
598
+ QueueOptions rewrite_options = options;
599
+ if ((!rewrite_options.enable_large_batch_splitting) &&
600
+ rewrite_options.max_enqueued_batches == 0) {
601
+ // Many existing models (with very low QPS) rely on this option to be >0.
602
+ // Rewrite and set this to one and retain old behavior to allow such models
603
+ // to continue to work.
604
+ //
605
+ // Note, technically an invalid-argument error should be returned, but
606
+ // that may break such models.
607
+ rewrite_options.max_enqueued_batches = 1;
608
+ }
609
+ return AddQueueAfterRewritingOptions(rewrite_options, process_batch_callback,
610
+ queue);
611
+ }
612
+
613
+ template <typename TaskType>
614
+ Status SharedBatchScheduler<TaskType>::AddQueueAfterRewritingOptions(
615
+ const QueueOptions& options,
616
+ std::function<void(std::unique_ptr<Batch<TaskType>>)>
617
+ process_batch_callback,
618
+ std::unique_ptr<BatchScheduler<TaskType>>* queue) {
619
+ if (options.input_batch_size_limit == 0) {
620
+ return errors::InvalidArgument(
621
+ "input_batch_size_limit must be positive; was ",
622
+ options.input_batch_size_limit);
623
+ }
624
+ if (options.batch_timeout_micros < 0) {
625
+ return errors::InvalidArgument(
626
+ "batch_timeout_micros must be non-negative; was ",
627
+ options.batch_timeout_micros);
628
+ }
629
+ if (options.max_enqueued_batches == 0) {
630
+ return errors::InvalidArgument(
631
+ "max_enqueued_batches must be positive; was ",
632
+ options.max_enqueued_batches);
633
+ }
634
+
635
+ if (options.enable_large_batch_splitting &&
636
+ options.split_input_task_func == nullptr) {
637
+ return errors::InvalidArgument(
638
+ "split_input_task_func must be specified when split_input_task is "
639
+ "true: ",
640
+ options.enable_large_batch_splitting);
641
+ }
642
+
643
+ if (options.enable_lazy_split && (!options.enable_large_batch_splitting)) {
644
+ return errors::InvalidArgument(
645
+ "enable_lazy_split should be enabled only if "
646
+ "enable_large_batch_splitting is enabled.");
647
+ }
648
+
649
+ if (options.enable_large_batch_splitting &&
650
+ (options.input_batch_size_limit < options.max_execution_batch_size)) {
651
+ return errors::InvalidArgument(
652
+ "When enable_large_batch_splitting is true, input_batch_size_limit "
653
+ "must be "
654
+ "greater than or equal to max_execution_batch_size.",
655
+ options.enable_large_batch_splitting, options.input_batch_size_limit,
656
+ options.max_execution_batch_size);
657
+ }
658
+
659
+ auto schedulable_batch_callback = [this] {
660
+ mutex_lock l(mu_);
661
+ schedulable_batch_cv_.notify_one();
662
+ };
663
+ auto internal_queue =
664
+ std::unique_ptr<internal::Queue<TaskType>>(new internal::Queue<TaskType>(
665
+ options, options_.env, process_batch_callback,
666
+ schedulable_batch_callback));
667
+ auto handle = std::unique_ptr<BatchScheduler<TaskType>>(
668
+ new internal::QueueHandle<TaskType>(this->shared_from_this(),
669
+ internal_queue.get()));
670
+ {
671
+ mutex_lock l(mu_);
672
+ queues_.push_back(std::move(internal_queue));
673
+ if (next_queue_to_schedule_ == queues_.end()) {
674
+ next_queue_to_schedule_ = queues_.begin();
675
+ }
676
+ }
677
+ *queue = std::move(handle);
678
+ return OkStatus();
679
+ }
680
+
681
+ template <typename TaskType>
682
+ SharedBatchScheduler<TaskType>::SharedBatchScheduler(const Options& options)
683
+ : options_(options), next_queue_to_schedule_(queues_.end()) {
684
+ // Kick off the batch threads.
685
+ PeriodicFunction::Options periodic_fn_options;
686
+ periodic_fn_options.thread_name_prefix =
687
+ strings::StrCat(options.thread_pool_name, "_");
688
+ for (int i = 0; i < options.num_batch_threads; ++i) {
689
+ std::unique_ptr<PeriodicFunction> thread(new PeriodicFunction(
690
+ [this] { this->ThreadLogic(); },
691
+ 0 /* function invocation interval time */, periodic_fn_options));
692
+ batch_threads_.push_back(std::move(thread));
693
+ }
694
+ }
695
+
696
+ template <typename TaskType>
697
+ bool SharedBatchScheduler<TaskType>::BatchExists(
698
+ const BatchUniquePtr& batch_to_process) {
699
+ if (absl::holds_alternative<BatchTaskUniqueptr>(batch_to_process)) {
700
+ return absl::get<BatchTaskUniqueptr>(batch_to_process) != nullptr;
701
+ }
702
+ return absl::get<BatchTaskHandleUniquePtr>(batch_to_process) != nullptr;
703
+ }
704
+
705
+ template <typename TaskType>
706
+ void SharedBatchScheduler<TaskType>::GetNextWorkItem_Locked(
707
+ internal::Queue<TaskType>** queue_for_batch_out,
708
+ BatchUniquePtr* batch_to_process_out) {
709
+ BatchUniquePtr batch_to_process;
710
+ internal::Queue<TaskType>* queue_for_batch = nullptr;
711
+ const int num_queues = queues_.size();
712
+ for (int num_queues_tried = 0;
713
+ !BatchExists(batch_to_process) && num_queues_tried < num_queues;
714
+ ++num_queues_tried) {
715
+ DCHECK(next_queue_to_schedule_ != queues_.end());
716
+
717
+ // If a closed queue responds to ScheduleBatch() with nullptr, the queue
718
+ // will never yield any further batches so we can drop it. To avoid a
719
+ // race, we take a snapshot of the queue's closedness state *before*
720
+ // calling ScheduleBatch().
721
+ const bool queue_closed = (*next_queue_to_schedule_)->closed();
722
+
723
+ // Ask '*next_queue_to_schedule_' if it wants us to process a batch.
724
+ batch_to_process = (*next_queue_to_schedule_)->ScheduleBatch();
725
+
726
+ if (BatchExists(batch_to_process)) {
727
+ queue_for_batch = next_queue_to_schedule_->get();
728
+ }
729
+
730
+ // Advance 'next_queue_to_schedule_'.
731
+ if (queue_closed && (*next_queue_to_schedule_)->IsEmpty() &&
732
+ !BatchExists(batch_to_process)) {
733
+ // We've encountered a closed queue with no work to do. Drop it.
734
+ DCHECK_NE(queue_for_batch, next_queue_to_schedule_->get());
735
+ next_queue_to_schedule_ = queues_.erase(next_queue_to_schedule_);
736
+ } else {
737
+ ++next_queue_to_schedule_;
738
+ }
739
+ if (next_queue_to_schedule_ == queues_.end() && !queues_.empty()) {
740
+ // We've hit the end. Wrap to the first queue.
741
+ next_queue_to_schedule_ = queues_.begin();
742
+ }
743
+ }
744
+ *queue_for_batch_out = queue_for_batch;
745
+ *batch_to_process_out = std::move(batch_to_process);
746
+ }
747
+
748
+ template <typename TaskType>
749
+ void SharedBatchScheduler<TaskType>::ThreadLogic() {
750
+ // A batch to process next (or nullptr if no work to do).
751
+ BatchUniquePtr batch_to_process;
752
+ // The queue with which 'batch_to_process' is associated.
753
+ internal::Queue<TaskType>* queue_for_batch = nullptr;
754
+ {
755
+ mutex_lock l(mu_);
756
+ while (true) {
757
+ GetNextWorkItem_Locked(&queue_for_batch, &batch_to_process);
758
+ if (BatchExists(batch_to_process)) break;
759
+ // We couldn't find any work to do. Wait until a new batch becomes
760
+ // schedulable, or some time has elapsed, before checking again.
761
+ const int64_t kTimeoutMillis =
762
+ 1; // The smallest accepted granule of time.
763
+ WaitForMilliseconds(&l, &schedulable_batch_cv_, kTimeoutMillis);
764
+ if (queues_.empty()) return;
765
+ }
766
+ }
767
+
768
+ std::unique_ptr<Batch<TaskType>> batch_to_schedule;
769
+ if (absl::holds_alternative<BatchTaskHandleUniquePtr>(batch_to_process)) {
770
+ // The corresponding `queue_for_batch` must be created with
771
+ // `enable_lazy_split=true`.
772
+ BatchTaskHandleUniquePtr ptr =
773
+ std::move(absl::get<BatchTaskHandleUniquePtr>(batch_to_process));
774
+ batch_to_schedule = std::make_unique<Batch<TaskType>>();
775
+ std::vector<std::unique_ptr<internal::BatchInputTaskHandle<TaskType>>>
776
+ task_handles = ptr->RemoveAllTasks();
777
+
778
+ // TODO(b/194294263):
779
+ // Handle the batch-kernel callback properly when lazy split returns
780
+ // error.
781
+ for (int i = 0; i < task_handles.size(); i++) {
782
+ batch_to_schedule->AddTask(std::move(task_handles[i]->GetSplitTask()));
783
+ }
784
+ batch_to_schedule->Close();
785
+
786
+ } else {
787
+ // The corresponding `queue_for_batch` must be created with
788
+ // `enable_lazy_split=false`.
789
+ batch_to_schedule =
790
+ std::move(absl::get<BatchTaskUniqueptr>(batch_to_process));
791
+ }
792
+
793
+ queue_for_batch->ProcessBatch(std::move(batch_to_schedule));
794
+ }
795
+
796
+ namespace internal {
797
+
798
+ template <typename TaskType>
799
+ Queue<TaskType>::Queue(
800
+ const typename SharedBatchScheduler<TaskType>::QueueOptions& options,
801
+ Env* env, ProcessBatchCallback process_batch_callback,
802
+ SchedulableBatchCallback schedulable_batch_callback)
803
+ : options_(options),
804
+ env_(env),
805
+ max_execution_batch_size_(GetMaxExecutionBatchSize(options_)),
806
+ process_batch_callback_(process_batch_callback),
807
+ schedulable_batch_callback_(schedulable_batch_callback) {
808
+ // Set the higher 32 bits of traceme_context_id_counter_ to be the creation
809
+ // time of the queue. This prevents the batches in different queues to have
810
+ // the same traceme_context_id_counter_.
811
+ traceme_context_id_counter_ = (absl::GetCurrentTimeNanos() & 0xFFFFFFFF)
812
+ << 32;
813
+ // Create an initial, open batch.
814
+ if (options_.enable_lazy_split) {
815
+ task_handle_batches_.emplace_back(
816
+ new Batch<BatchInputTaskHandle<TaskType>>);
817
+ } else {
818
+ GetBatches().emplace_back(new Batch<TaskType>);
819
+ }
820
+ }
821
+
822
+ template <typename TaskType>
823
+ Queue<TaskType>::~Queue() {
824
+ mutex_lock l(mu_);
825
+ DCHECK(IsEmptyInternal());
826
+
827
+ // Close the (empty) open batch, so its destructor doesn't block.
828
+ if (options_.enable_lazy_split) {
829
+ task_handle_batches_.back()->Close();
830
+ } else {
831
+ GetBatches().back()->Close();
832
+ }
833
+ }
834
+
835
+ template <typename TaskType>
836
+ Status Queue<TaskType>::Schedule(std::unique_ptr<TaskType>* task) {
837
+ if ((*task)->size() > options_.input_batch_size_limit) {
838
+ return errors::InvalidArgument("Task size ", (*task)->size(),
839
+ " is larger than maximum input batch size ",
840
+ options_.input_batch_size_limit);
841
+ }
842
+ if (options_.enable_lazy_split) {
843
+ return ScheduleWithLazySplit(std::move(task));
844
+ }
845
+ return ScheduleWithoutOrEagerSplit(std::move(task));
846
+ }
847
+
848
+ template <typename TaskType>
849
+ Status Queue<TaskType>::ScheduleWithLazySplit(std::unique_ptr<TaskType>* task) {
850
+ profiler::TraceMe trace_me([task] {
851
+ return profiler::TraceMeEncode(
852
+ "ScheduleWithLazySplit",
853
+ {{"batching_input_task_size", (*task)->size()}});
854
+ });
855
+ // The max size to be enqueued.
856
+ const int max_execution_batch_size = options_.max_execution_batch_size;
857
+
858
+ bool notify_of_schedulable_batch = false;
859
+ {
860
+ mutex_lock l(mu_);
861
+
862
+ DCHECK(!closed_);
863
+
864
+ TF_RETURN_IF_ERROR(ValidateBatchTaskQueueCapacity((*task).get()));
865
+
866
+ const int64 open_batch_capacity =
867
+ max_execution_batch_size - this->tail_batch_task_size();
868
+
869
+ auto input_batch = std::make_shared<BatchInputTask<TaskType>>(
870
+ std::move(*task), open_batch_capacity, max_execution_batch_size,
871
+ options_.split_input_task_func);
872
+ std::vector<std::unique_ptr<BatchInputTaskHandle<TaskType>>> task_handles;
873
+
874
+ input_batch->ToTaskHandles(&task_handles);
875
+
876
+ for (int i = 0; i < task_handles.size(); ++i) {
877
+ if (task_handle_batches_.back()->size() + task_handles[i]->size() >
878
+ options_.max_execution_batch_size) {
879
+ StartNewBatch();
880
+ }
881
+ if (task_handle_batches_.back()->empty()) {
882
+ open_batch_start_time_micros_ = env_->NowMicros();
883
+ }
884
+ profiler::TraceMeProducer trace_me(
885
+ [&task_handles, i] {
886
+ return profiler::TraceMeEncode("ScheduleOutputTask",
887
+ {{"size", task_handles[i]->size()}});
888
+ },
889
+ profiler::ContextType::kSharedBatchScheduler,
890
+ task_handle_batches_.back()->traceme_context_id());
891
+
892
+ task_handle_batches_.back()->AddTask(std::move(task_handles[i]));
893
+ }
894
+
895
+ if (!schedulable_batch_) {
896
+ if (GetBatches().size() > 1 || IsOpenBatchSchedulable()) {
897
+ schedulable_batch_ = true;
898
+ notify_of_schedulable_batch = true;
899
+ }
900
+ }
901
+ }
902
+ // TODO(b/194294263):
903
+ // Add unit tests to verify that `schedulable_batch_callback_` could be
904
+ // triggered when batches are scheduled.
905
+ if (notify_of_schedulable_batch) {
906
+ schedulable_batch_callback_();
907
+ }
908
+
909
+ return OkStatus();
910
+ }
911
+
912
+ // TODO(b/194294263):
913
+ // Merge `ScheduleWithoutOrEagerSplit` and `ScheduleWithLazySplit` into
914
+ // `Schedule`.
915
+ template <typename TaskType>
916
+ Status Queue<TaskType>::ScheduleWithoutOrEagerSplit(
917
+ std::unique_ptr<TaskType>* task) {
918
+ const bool large_batch_splitting = options_.enable_large_batch_splitting;
919
+ profiler::TraceMe trace_me([task, large_batch_splitting] {
920
+ return profiler::TraceMeEncode(
921
+ large_batch_splitting ? "ScheduleWithEagerSplit"
922
+ : "ScheduleWithoutSplit",
923
+ {{"batching_input_task_size", (*task)->size()}});
924
+ });
925
+
926
+ bool notify_of_schedulable_batch = false;
927
+ {
928
+ mutex_lock l(mu_);
929
+
930
+ DCHECK(!closed_);
931
+
932
+ // TODO(b/161857471):
933
+ // Add test coverage when when concurrent incoming batches arrives and
934
+ // use up all queue capacity.
935
+ TF_RETURN_IF_ERROR(ValidateBatchTaskQueueCapacity((*task).get()));
936
+
937
+ std::deque<std::unique_ptr<Batch<TaskType>>>& batches = GetBatches();
938
+
939
+ const int64_t open_batch_remaining_slot =
940
+ max_execution_batch_size() - batches.back()->size();
941
+
942
+ const int64_t input_task_size = (*task)->size();
943
+
944
+ std::vector<std::unique_ptr<TaskType>> output_tasks;
945
+
946
+ if (input_task_size <= open_batch_remaining_slot ||
947
+ !large_batch_splitting) {
948
+ // This is the fast path when input doesn't need to be split.
949
+ output_tasks.push_back(std::move(*task));
950
+ } else {
951
+ TF_RETURN_IF_ERROR(SplitInputBatchIntoSubtasks(task, &output_tasks));
952
+ }
953
+
954
+ for (int i = 0; i < output_tasks.size(); ++i) {
955
+ if (batches.back()->size() + output_tasks[i]->size() >
956
+ max_execution_batch_size()) {
957
+ StartNewBatch();
958
+ }
959
+ if (batches.back()->empty()) {
960
+ open_batch_start_time_micros_ = env_->NowMicros();
961
+ }
962
+ profiler::TraceMeProducer trace_me(
963
+ [&output_tasks, i] {
964
+ return profiler::TraceMeEncode("ScheduleOutputTask",
965
+ {{"size", output_tasks[i]->size()}});
966
+ },
967
+ profiler::ContextType::kSharedBatchScheduler,
968
+ batches.back()->traceme_context_id());
969
+ batches.back()->AddTask(std::move(output_tasks[i]));
970
+ }
971
+
972
+ if (!schedulable_batch_) {
973
+ if (batches.size() > 1 || IsOpenBatchSchedulable()) {
974
+ schedulable_batch_ = true;
975
+ notify_of_schedulable_batch = true;
976
+ }
977
+ }
978
+ }
979
+
980
+ if (notify_of_schedulable_batch) {
981
+ schedulable_batch_callback_();
982
+ }
983
+
984
+ return OkStatus();
985
+ }
986
+
987
+ template <typename TaskType>
988
+ size_t Queue<TaskType>::NumEnqueuedTasks() const {
989
+ size_t num_enqueued_tasks = 0;
990
+ mutex_lock l(mu_);
991
+ if (options_.enable_lazy_split) {
992
+ for (const auto& batch : task_handle_batches_) {
993
+ num_enqueued_tasks += batch->num_tasks();
994
+ }
995
+ return num_enqueued_tasks;
996
+ }
997
+
998
+ for (const auto& batch : GetBatches()) {
999
+ num_enqueued_tasks += batch->num_tasks();
1000
+ }
1001
+ return num_enqueued_tasks;
1002
+ }
1003
+
1004
+ template <typename TaskType>
1005
+ size_t Queue<TaskType>::SchedulingCapacity() const {
1006
+ mutex_lock l(mu_);
1007
+ return SchedulingCapacityInternal();
1008
+ }
1009
+
1010
+ template <typename TaskType>
1011
+ size_t Queue<TaskType>::SchedulingCapacityInternal() const {
1012
+ const int64 num_new_batches_schedulable =
1013
+ static_cast<int64_t>(options_.max_enqueued_batches) -
1014
+ this->num_enqueued_batches();
1015
+ const int64 execution_batch_size_limit = max_execution_batch_size();
1016
+ const int64 open_batch_capacity =
1017
+ execution_batch_size_limit - this->tail_batch_task_size();
1018
+ // Note the returned value is guaranteed to be not negative, since
1019
+ // enqueue operation could only happen if queue has enough capacity.
1020
+ return (num_new_batches_schedulable * execution_batch_size_limit) +
1021
+ open_batch_capacity;
1022
+ }
1023
+
1024
+ template <typename TaskType>
1025
+ Status Queue<TaskType>::ValidateBatchTaskQueueCapacity(TaskType* task) const {
1026
+ // Queue creation requires that `enable_large_batch_splitting` is true
1027
+ // when `enable_lazy_split` is true, so this covers both eager split and
1028
+ // lazy split.
1029
+ if (options_.enable_large_batch_splitting) {
1030
+ if (task->size() > SchedulingCapacityInternal()) {
1031
+ return errors::Unavailable(
1032
+ "The batch scheduling queue to which this task was submitted is "
1033
+ "full; task size is ",
1034
+ task->size(), " but scheduling capacity is only ",
1035
+ SchedulingCapacityInternal(),
1036
+ " (num_enqueued_batches=", num_enqueued_batches(),
1037
+ ", max_enqueued_batches=", options_.max_enqueued_batches,
1038
+ ", open_batch_size=", tail_batch_task_size(),
1039
+ ", max_execution_batch_size=", max_execution_batch_size(), ")");
1040
+ }
1041
+ return OkStatus();
1042
+ }
1043
+
1044
+ // NOTE, the capacity checking below is loose and is retained
1045
+ // for backward compatibility that was broken due to the merge of no-split
1046
+ // and eager split.
1047
+ // There are existing clients/models that rely on the loose check
1048
+ // and can get errors after the merge. Retaining the old behavior
1049
+ // allows such models to continue to work.
1050
+ //
1051
+ // We need to revisit/remove this check after we fix model configs.
1052
+ const std::deque<std::unique_ptr<Batch<TaskType>>>& batches = GetBatches();
1053
+ if (batches.back()->size() + task->size() > options_.input_batch_size_limit) {
1054
+ if (batches.size() >= options_.max_enqueued_batches) {
1055
+ return errors::Unavailable(
1056
+ "The batch scheduling queue to which this task was submitted is "
1057
+ "full; currently ",
1058
+ batches.size(), " batches enqueued and max_enqueued_batches is ",
1059
+ options_.max_enqueued_batches);
1060
+ }
1061
+ }
1062
+ return OkStatus();
1063
+ }
1064
+
1065
+ template <typename TaskType>
1066
+ std::unique_ptr<Batch<TaskType>>
1067
+ Queue<TaskType>::ScheduleBatchWithEagerSplit() {
1068
+ // The batch to schedule, which we may populate below. (If left as nullptr,
1069
+ // that means we are electing not to schedule a batch at this time.)
1070
+ std::unique_ptr<Batch<TaskType>> batch_to_schedule;
1071
+
1072
+ {
1073
+ mutex_lock l(mu_);
1074
+
1075
+ std::deque<std::unique_ptr<Batch<TaskType>>>& batches = GetBatches();
1076
+ // Consider closing the open batch at this time, to schedule it.
1077
+ if (batches.size() == 1 && IsOpenBatchSchedulable()) {
1078
+ StartNewBatch();
1079
+ }
1080
+
1081
+ if (batches.size() >= 2) {
1082
+ // There is at least one closed batch that is ready to be scheduled.
1083
+ ++num_batches_being_processed_;
1084
+ batch_to_schedule = std::move(batches.front());
1085
+ batches.pop_front();
1086
+ } else {
1087
+ schedulable_batch_ = false;
1088
+ }
1089
+ }
1090
+
1091
+ return batch_to_schedule;
1092
+ }
1093
+
1094
+ template <typename TaskType>
1095
+ typename SharedBatchScheduler<TaskType>::BatchUniquePtr
1096
+ Queue<TaskType>::ScheduleBatch() {
1097
+ if (!options_.enable_lazy_split) {
1098
+ return ScheduleBatchWithEagerSplit();
1099
+ }
1100
+ // The batch to schedule, which we may populate below. (If left as nullptr,
1101
+ // that means we are electing not to schedule a batch at this time.)
1102
+ std::unique_ptr<Batch<BatchInputTaskHandle<TaskType>>>
1103
+ task_handles_to_schedule;
1104
+
1105
+ {
1106
+ mutex_lock l(mu_);
1107
+
1108
+ // Consider closing the open batch at this time, to schedule it.
1109
+ if (task_handle_batches_.size() == 1 && IsOpenBatchSchedulable()) {
1110
+ StartNewBatch();
1111
+ }
1112
+
1113
+ if (task_handle_batches_.size() >= 2) {
1114
+ // There is at least one closed batch that is ready to be scheduled.
1115
+ ++num_batches_being_processed_;
1116
+ task_handles_to_schedule = std::move(task_handle_batches_.front());
1117
+ task_handle_batches_.pop_front();
1118
+ } else {
1119
+ schedulable_batch_ = false;
1120
+ }
1121
+ }
1122
+
1123
+ return std::move(task_handles_to_schedule);
1124
+ }
1125
+
1126
+ template <typename TaskType>
1127
+ void Queue<TaskType>::ProcessBatch(std::unique_ptr<Batch<TaskType>> batch) {
1128
+ profiler::TraceMeConsumer trace_me(
1129
+ [&] {
1130
+ return profiler::TraceMeEncode(
1131
+ "ProcessBatch", {{"batch_size_before_padding", batch->size()},
1132
+ {"_r", 2} /*root_event*/});
1133
+ },
1134
+ profiler::ContextType::kSharedBatchScheduler,
1135
+ batch->traceme_context_id());
1136
+ process_batch_callback_(std::move(batch));
1137
+
1138
+ {
1139
+ mutex_lock l(mu_);
1140
+ --num_batches_being_processed_;
1141
+ if (empty_notification_ != nullptr && IsEmptyInternal()) {
1142
+ empty_notification_->Notify();
1143
+ }
1144
+ }
1145
+ }
1146
+
1147
+ template <typename TaskType>
1148
+ bool Queue<TaskType>::IsEmpty() const {
1149
+ mutex_lock l(mu_);
1150
+ return IsEmptyInternal();
1151
+ }
1152
+
1153
+ template <typename TaskType>
1154
+ void Queue<TaskType>::CloseAndWaitUntilEmpty() {
1155
+ Notification empty;
1156
+ {
1157
+ mutex_lock l(mu_);
1158
+ closed_ = true;
1159
+ if (IsEmptyInternal()) {
1160
+ empty.Notify();
1161
+ } else {
1162
+ // Arrange for ProcessBatch() to notify when the queue becomes empty.
1163
+ empty_notification_ = &empty;
1164
+ }
1165
+ }
1166
+ empty.WaitForNotification();
1167
+ }
1168
+
1169
+ template <typename TaskType>
1170
+ bool Queue<TaskType>::IsEmptyInternal() const {
1171
+ if (options_.enable_lazy_split) {
1172
+ return num_batches_being_processed_ == 0 &&
1173
+ task_handle_batches_.size() == 1 &&
1174
+ task_handle_batches_.back()->empty();
1175
+ }
1176
+ const std::deque<std::unique_ptr<Batch<TaskType>>>& batches = GetBatches();
1177
+ return num_batches_being_processed_ == 0 && batches.size() == 1 &&
1178
+ batches.back()->empty();
1179
+ }
1180
+
1181
+ template <typename TaskType>
1182
+ void Queue<TaskType>::StartNewBatch() {
1183
+ if (options_.enable_lazy_split) {
1184
+ task_handle_batches_.back()->Close();
1185
+ task_handle_batches_.emplace_back(new Batch<BatchInputTaskHandle<TaskType>>(
1186
+ ++traceme_context_id_counter_));
1187
+ return;
1188
+ }
1189
+ std::deque<std::unique_ptr<Batch<TaskType>>>& batches = GetBatches();
1190
+ batches.back()->Close();
1191
+ batches.emplace_back(new Batch<TaskType>(++traceme_context_id_counter_));
1192
+ }
1193
+
1194
+ template <typename TaskType>
1195
+ Status Queue<TaskType>::SplitInputBatchIntoSubtasks(
1196
+ std::unique_ptr<TaskType>* input_task,
1197
+ std::vector<std::unique_ptr<TaskType>>* output_tasks) {
1198
+ const int open_batch_remaining_slot =
1199
+ max_execution_batch_size() - this->tail_batch_task_size();
1200
+ return options_.split_input_task_func(
1201
+ std::move(input_task), open_batch_remaining_slot,
1202
+ max_execution_batch_size(), std::move(output_tasks));
1203
+ }
1204
+
1205
+ template <typename TaskType>
1206
+ bool Queue<TaskType>::IsOpenBatchSchedulableAfterEagerSplit() const {
1207
+ Batch<TaskType>* open_batch = GetBatches().back().get();
1208
+ if (open_batch->empty()) {
1209
+ return false;
1210
+ }
1211
+ return closed_ || open_batch->size() >= max_execution_batch_size() ||
1212
+ env_->NowMicros() >=
1213
+ open_batch_start_time_micros_ + options_.batch_timeout_micros;
1214
+ }
1215
+
1216
+ template <typename TaskType>
1217
+ bool Queue<TaskType>::IsOpenBatchSchedulable() const {
1218
+ if (!options_.enable_lazy_split) {
1219
+ return IsOpenBatchSchedulableAfterEagerSplit();
1220
+ }
1221
+ Batch<BatchInputTaskHandle<TaskType>>* open_batch =
1222
+ task_handle_batches_.back().get();
1223
+ if (open_batch->empty()) {
1224
+ return false;
1225
+ }
1226
+ return closed_ || open_batch->size() >= max_execution_batch_size() ||
1227
+ env_->NowMicros() >=
1228
+ open_batch_start_time_micros_ + options_.batch_timeout_micros;
1229
+ }
1230
+
1231
+ template <typename TaskType>
1232
+ size_t Queue<TaskType>::tail_batch_task_size() const {
1233
+ if (options_.enable_lazy_split) {
1234
+ return task_handle_batches_.back()->size();
1235
+ }
1236
+
1237
+ return GetBatches().back()->size();
1238
+ }
1239
+
1240
+ template <typename TaskType>
1241
+ int64 Queue<TaskType>::num_enqueued_batches() const {
1242
+ if (options_.enable_lazy_split) {
1243
+ return task_handle_batches_.size();
1244
+ }
1245
+ return GetBatches().size();
1246
+ }
1247
+
1248
+ template <typename TaskType>
1249
+ std::deque<std::unique_ptr<Batch<TaskType>>>& Queue<TaskType>::GetBatches() {
1250
+ return high_priority_batches_;
1251
+ }
1252
+
1253
+ template <typename TaskType>
1254
+ const std::deque<std::unique_ptr<Batch<TaskType>>>&
1255
+ Queue<TaskType>::GetBatches() const {
1256
+ return high_priority_batches_;
1257
+ }
1258
+
1259
+ template <typename TaskType>
1260
+ QueueHandle<TaskType>::QueueHandle(
1261
+ std::shared_ptr<SharedBatchScheduler<TaskType>> scheduler,
1262
+ Queue<TaskType>* queue)
1263
+ : scheduler_(scheduler), queue_(queue) {}
1264
+
1265
+ template <typename TaskType>
1266
+ QueueHandle<TaskType>::~QueueHandle() {
1267
+ queue_->CloseAndWaitUntilEmpty();
1268
+ }
1269
+
1270
+ template <typename TaskType>
1271
+ Status QueueHandle<TaskType>::Schedule(std::unique_ptr<TaskType>* task) {
1272
+ return queue_->Schedule(task);
1273
+ }
1274
+
1275
+ template <typename TaskType>
1276
+ size_t QueueHandle<TaskType>::NumEnqueuedTasks() const {
1277
+ return queue_->NumEnqueuedTasks();
1278
+ }
1279
+
1280
+ template <typename TaskType>
1281
+ size_t QueueHandle<TaskType>::SchedulingCapacity() const {
1282
+ return queue_->SchedulingCapacity();
1283
+ }
1284
+
1285
+ } // namespace internal
1286
+
1287
+ } // namespace serving
1288
+ } // namespace tensorflow
1289
+
1290
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_SHARED_BATCH_SCHEDULER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/threadsafe_status.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_THREADSAFE_STATUS_H_
17
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_THREADSAFE_STATUS_H_
18
+
19
+ #include "tensorflow/core/platform/mutex.h"
20
+ #include "tensorflow/core/platform/status.h"
21
+ #include "tensorflow/core/platform/thread_annotations.h"
22
+
23
+ namespace tensorflow {
24
+ // Wrapper class to allow both lock-free construction and concurrent updates on
25
+ // a 'status'.
26
+ //
27
+ // Example Usage:
28
+ // std::thread threads[2];
29
+ // ThreadSafeStatus thread_safe_status;
30
+ // threads[0] = std::thread([&]() {
31
+ // status.Update(errors::Internal("internal error"));
32
+ // });
33
+ // threads[1] = std::thread([&]() {
34
+ // status.Update(errors::InvalidArgument("invalid argument"));
35
+ // });
36
+ // threads[0].Join();
37
+ // threads[1].Join();
38
+ //
39
+ // NOTE:
40
+ // When updated in a multi-threading setup, only the first error is retained.
41
+ class ThreadSafeStatus {
42
+ public:
43
+ const Status& status() const& TF_LOCKS_EXCLUDED(mutex_);
44
+ Status status() && TF_LOCKS_EXCLUDED(mutex_);
45
+
46
+ // Retains the first error status: replaces the current status with
47
+ // `new_status` if `new_status` is not OK and the previous status is OK.
48
+ void Update(const Status& new_status) TF_LOCKS_EXCLUDED(mutex_);
49
+ void Update(Status&& new_status) TF_LOCKS_EXCLUDED(mutex_);
50
+
51
+ private:
52
+ mutable mutex mutex_;
53
+ Status status_ TF_GUARDED_BY(mutex_);
54
+ };
55
+ } // namespace tensorflow
56
+
57
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_THREADSAFE_STATUS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/batching_util/warmup.h ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2023 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_WARMUP_H_
17
+ #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_WARMUP_H_
18
+
19
+ #include <memory>
20
+ #include <optional>
21
+ #include <string>
22
+ #include <utility>
23
+
24
+ #include "absl/container/flat_hash_map.h"
25
+ #include "absl/hash/hash.h"
26
+ #include "absl/status/statusor.h"
27
+ #include "absl/synchronization/mutex.h"
28
+ #include "tensorflow/core/framework/op_kernel.h"
29
+ #include "tensorflow/core/protobuf/config.pb.h"
30
+ #include "tsl/platform/logging.h"
31
+
32
+ namespace tensorflow {
33
+ namespace serving {
34
+
35
+ // Global registry for model's warm-up states. Before a model executes warm-up
36
+ // requests, it is registered here so that the runtime can distinguish demand
37
+ // requests vs. warm-up requests and apply warm-up specific optimizations.
38
+ class WarmupStateRegistry {
39
+ public:
40
+ struct Key {
41
+ std::string name;
42
+ int64_t version;
43
+
44
+ Key(std::string name, int64_t version)
45
+ : name(std::move(name)), version(version) {}
46
+
47
+ template <typename H>
48
+ friend H AbslHashValue(H state, const Key& key) {
49
+ return H::combine(std::move(state), key.name, key.version);
50
+ }
51
+
52
+ friend bool operator==(const Key& x, const Key& y) {
53
+ return x.name == y.name && x.version == y.version;
54
+ }
55
+ };
56
+ // Data stored per key.
57
+ struct PerModelData {
58
+ // If true, supported batch ops will execute the model on dummy batches
59
+ // for all `allowed_batch_sizes` of that batch op. This removes the
60
+ // need to issue separate warmup requests for each batch size.
61
+ bool warmup_all_batch_sizes = false;
62
+ };
63
+
64
+ // RAII handle for registered models.
65
+ class Handle {
66
+ public:
67
+ Handle() = default;
68
+
69
+ Handle(const Handle& other) = delete;
70
+ Handle& operator=(const Handle& other) = delete;
71
+ Handle(Handle&& other)
72
+ : key_(std::move(other.key_)), registry_(other.registry_) {
73
+ other.key_.reset();
74
+ }
75
+ Handle& operator=(Handle&& other) {
76
+ if (key_.has_value()) {
77
+ Release();
78
+ }
79
+
80
+ key_ = std::move(other.key_);
81
+ other.key_.reset();
82
+ registry_ = other.registry_;
83
+ return *this;
84
+ }
85
+
86
+ ~Handle() { Release(); }
87
+
88
+ void Release();
89
+
90
+ private:
91
+ friend class WarmupStateRegistry;
92
+
93
+ // Can only be constructed by `WarmupStateRegistry::Register()`.
94
+ Handle(const Key& key, WarmupStateRegistry* registry)
95
+ : key_(key), registry_(registry) {
96
+ DCHECK(registry_);
97
+ }
98
+
99
+ std::optional<Key> key_;
100
+ WarmupStateRegistry* registry_ = nullptr;
101
+ };
102
+
103
+ // Registers the given model to be in a warm-up state and associates the given
104
+ // metadata with the model. Returns an RAII handle that unregisters the model
105
+ // at its destruction.
106
+ absl::StatusOr<Handle> Register(const Key& model_key,
107
+ std::unique_ptr<PerModelData> per_model_data);
108
+
109
+ // Return model data. A nullptr indicates the key was not present.
110
+ const PerModelData* Lookup(const Key& model_key);
111
+
112
+ private:
113
+ friend class Handle;
114
+
115
+ void Unregister(const Key& model_key);
116
+
117
+ absl::Mutex mu_;
118
+ // Map of model names/versions to miscellaneous data.
119
+ absl::flat_hash_map<Key, std::unique_ptr<PerModelData>> states_
120
+ ABSL_GUARDED_BY(&mu_);
121
+ };
122
+
123
+ WarmupStateRegistry& GetGlobalWarmupStateRegistry();
124
+
125
+ // Utility function that returns whether or not to warmup all batch sizes,
126
+ // based on the state of WarmupStateRegistry.
127
+ bool ShouldWarmupAllBatchSizes(const OpKernelContext* c);
128
+
129
+ } // namespace serving
130
+ } // namespace tensorflow
131
+
132
+ #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_WARMUP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/batch_dataset_op.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_BATCH_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_BATCH_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+
23
+ class BatchDatasetOp : public UnaryDatasetOpKernel {
24
+ public:
25
+ static constexpr const char* const kDatasetType = "Batch";
26
+ static constexpr const char* const kInputDataset = "input_dataset";
27
+ static constexpr const char* const kBatchSize = "batch_size";
28
+ static constexpr const char* const kDropRemainder = "drop_remainder";
29
+ static constexpr const char* const kParallelCopy = "parallel_copy";
30
+ static constexpr const char* const kOutputTypes = "output_types";
31
+ static constexpr const char* const kOutputShapes = "output_shapes";
32
+
33
+ explicit BatchDatasetOp(OpKernelConstruction* ctx);
34
+
35
+ protected:
36
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
37
+ DatasetBase** output) override;
38
+
39
+ private:
40
+ class Dataset;
41
+ const int op_version_;
42
+ bool parallel_copy_ = false;
43
+ };
44
+
45
+ } // namespace data
46
+ } // namespace tensorflow
47
+
48
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_BATCH_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/cache_dataset_ops.h ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_CACHE_DATASET_OPS_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_CACHE_DATASET_OPS_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+
23
+ class CacheDatasetOp : public UnaryDatasetOpKernel {
24
+ public:
25
+ class FileDatasetBase;
26
+ class MemoryDatasetBase;
27
+
28
+ static constexpr const char* const kDatasetType = "Cache";
29
+ static constexpr const char* const kInputDataset = "input_dataset";
30
+ static constexpr const char* const kFileName = "filename";
31
+ static constexpr const char* const kOutputTypes = "output_types";
32
+ static constexpr const char* const kOutputShapes = "output_shapes";
33
+
34
+ explicit CacheDatasetOp(OpKernelConstruction* ctx);
35
+
36
+ protected:
37
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
38
+ DatasetBase** output) override;
39
+
40
+ private:
41
+ class FileDataset;
42
+ class FileDatasetV2;
43
+ class MemoryDataset;
44
+ class MemoryDatasetV2;
45
+
46
+ const int op_version_;
47
+ };
48
+
49
+ } // namespace data
50
+ } // namespace tensorflow
51
+
52
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_CACHE_DATASET_OPS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/cache_ops.h ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_CORE_KERNELS_DATA_CACHE_OPS_H_
17
+ #define TENSORFLOW_CORE_KERNELS_DATA_CACHE_OPS_H_
18
+
19
+ #include "tensorflow/core/data/dataset_utils.h"
20
+ #include "tensorflow/core/framework/resource_mgr.h"
21
+
22
+ namespace tensorflow {
23
+ namespace data {
24
+
25
+ // A thread-safe data structure for caching dataset elements.
26
+ //
27
+ // The expected use is that a single `MemoryWriterIterator` populates the
28
+ // cache with dataset elements. Once all elements are cached, the cache can
29
+ // be used by one or more `MemoryReaderIterator`s.
30
+ class MemoryCache {
31
+ public:
32
+ MemoryCache() = default;
33
+
34
+ // Marks the cache as completed.
35
+ void Complete(std::vector<std::vector<Tensor>>&& cache);
36
+
37
+ // Returns whether the cache is completed.
38
+ bool IsCompleted();
39
+
40
+ // Resets the cache.
41
+ void Reset();
42
+
43
+ // Returns the element at the given index.
44
+ const std::vector<Tensor>& at(int64_t index);
45
+
46
+ // Returns the size of the cache.
47
+ size_t size();
48
+
49
+ // Returns a reference to the cache's data. The returned reference will be
50
+ // invalidated by any call to Reset().
51
+ const std::vector<std::vector<Tensor>>& data();
52
+
53
+ private:
54
+ mutex mu_;
55
+ // Determines whether all elements of the dataset have been cached.
56
+ bool completed_ TF_GUARDED_BY(mu_) = false;
57
+ std::vector<std::vector<Tensor>> cache_ TF_GUARDED_BY(mu_);
58
+ };
59
+
60
+ // A resource wrapping a shared instance of a memory cache.
61
+ class MemoryCacheManager : public ResourceBase {
62
+ public:
63
+ MemoryCacheManager() : cache_(std::make_shared<MemoryCache>()) {}
64
+
65
+ string DebugString() const override;
66
+
67
+ std::shared_ptr<MemoryCache> get() { return cache_; }
68
+
69
+ private:
70
+ std::shared_ptr<MemoryCache> cache_;
71
+ };
72
+
73
+ // Creates an instance of cache resource and transfers ownership to the caller.
74
+ class AnonymousMemoryCacheHandleOp
75
+ : public AnonymousResourceOp<MemoryCacheManager> {
76
+ public:
77
+ explicit AnonymousMemoryCacheHandleOp(OpKernelConstruction* ctx);
78
+
79
+ private:
80
+ string name() override;
81
+ Status CreateResource(OpKernelContext* ctx,
82
+ std::unique_ptr<FunctionLibraryDefinition> flib_def,
83
+ std::unique_ptr<ProcessFunctionLibraryRuntime> pflr,
84
+ FunctionLibraryRuntime* lib,
85
+ MemoryCacheManager** manager) override;
86
+ };
87
+
88
+ // Deletes an instance of cache resource.
89
+ class DeleteMemoryCacheOp : public OpKernel {
90
+ public:
91
+ explicit DeleteMemoryCacheOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
92
+
93
+ void Compute(OpKernelContext* ctx) override;
94
+ };
95
+
96
+ } // namespace data
97
+ } // namespace tensorflow
98
+
99
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_CACHE_OPS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/concatenate_dataset_op.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_CONCATENATE_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_CONCATENATE_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+
23
+ class ConcatenateDatasetOp : public BinaryDatasetOpKernel {
24
+ public:
25
+ static constexpr const char* const kDatasetType = "Concatenate";
26
+ static constexpr const char* const kInputDataset = "input_dataset";
27
+ static constexpr const char* const kAnotherDataset = "another_dataset";
28
+ static constexpr const char* const kOutputTypes = "output_types";
29
+ static constexpr const char* const kOutputShapes = "output_shapes";
30
+
31
+ explicit ConcatenateDatasetOp(OpKernelConstruction* ctx);
32
+
33
+ protected:
34
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
35
+ DatasetBase* to_concatenate, DatasetBase** output) override;
36
+
37
+ private:
38
+ class Dataset;
39
+ };
40
+
41
+ } // namespace data
42
+ } // namespace tensorflow
43
+
44
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_CONCATENATE_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/dataset_ops.h ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_DATASET_OPS_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_DATASET_OPS_H_
17
+
18
+ #include <memory>
19
+
20
+ #include "tensorflow/core/platform/platform.h"
21
+
22
+ // On mobile we do not provide this functionality because not all of its
23
+ // dependencies are available there.
24
+ #if !defined(IS_MOBILE_PLATFORM)
25
+ #include "tensorflow/core/framework/dataset.h"
26
+ #include "tensorflow/core/framework/op_kernel.h"
27
+
28
+ namespace tensorflow {
29
+ namespace data {
30
+
31
+ class DatasetToGraphOp : public OpKernel {
32
+ public:
33
+ static constexpr const char* const kAllowStateful = "allow_stateful";
34
+ static constexpr const char* const kStripDeviceAssignment =
35
+ "strip_device_assignment";
36
+ static constexpr const char* const kExternalStatePolicy =
37
+ "external_state_policy";
38
+ static constexpr const char* const kDatasetToGraph = "DatasetToGraph";
39
+
40
+ explicit DatasetToGraphOp(OpKernelConstruction* ctx);
41
+
42
+ void Compute(OpKernelContext* ctx) override;
43
+
44
+ private:
45
+ const int op_version_;
46
+ ExternalStatePolicy external_state_policy_ = ExternalStatePolicy::POLICY_WARN;
47
+ bool strip_device_assignment_ = false;
48
+ };
49
+
50
+ class DatasetCardinalityOp : public OpKernel {
51
+ public:
52
+ explicit DatasetCardinalityOp(OpKernelConstruction* ctx);
53
+
54
+ void Compute(OpKernelContext* ctx) override;
55
+
56
+ private:
57
+ std::unique_ptr<CardinalityOptions> cardinality_options_;
58
+ };
59
+
60
+ class DatasetFromGraphOp : public OpKernel {
61
+ public:
62
+ static constexpr const char* const kGraphDef = "graph_def";
63
+ static constexpr const char* const kHandle = "handle";
64
+
65
+ explicit DatasetFromGraphOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
66
+
67
+ void Compute(OpKernelContext* ctx) override;
68
+ };
69
+
70
+ } // namespace data
71
+ } // namespace tensorflow
72
+ #endif // !IS_MOBILE_PLATFORM
73
+
74
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_DATASET_OPS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/assert_cardinality_dataset_op.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_ASSERT_CARDINALITY_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_ASSERT_CARDINALITY_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ class AssertCardinalityDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "AssertCardinality";
27
+ static constexpr const char* const kInputDataset = "input_dataset";
28
+ static constexpr const char* const kCardinality = "cardinality";
29
+ static constexpr const char* const kOutputTypes = "output_types";
30
+ static constexpr const char* const kOutputShapes = "output_shapes";
31
+
32
+ explicit AssertCardinalityDatasetOp(OpKernelConstruction* ctx);
33
+
34
+ protected:
35
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
36
+ DatasetBase** output) override;
37
+
38
+ private:
39
+ class Dataset;
40
+ DataTypeVector output_types_;
41
+ std::vector<PartialTensorShape> output_shapes_;
42
+ };
43
+
44
+ } // namespace experimental
45
+ } // namespace data
46
+ } // namespace tensorflow
47
+
48
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_ASSERT_CARDINALITY_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/assert_next_dataset_op.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_ASSERT_NEXT_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_ASSERT_NEXT_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ class AssertNextDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "AssertNext";
27
+ static constexpr const char* const kInputDataset = "input_dataset";
28
+ static constexpr const char* const kTransformations = "transformations";
29
+ static constexpr const char* const kOutputTypes = "output_types";
30
+ static constexpr const char* const kOutputShapes = "output_shapes";
31
+
32
+ explicit AssertNextDatasetOp(OpKernelConstruction* ctx);
33
+
34
+ protected:
35
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
36
+ DatasetBase** output) override;
37
+
38
+ private:
39
+ class Dataset;
40
+ DataTypeVector output_types_;
41
+ std::vector<PartialTensorShape> output_shapes_;
42
+ };
43
+
44
+ } // namespace experimental
45
+ } // namespace data
46
+ } // namespace tensorflow
47
+
48
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_ASSERT_NEXT_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/assert_prev_dataset_op.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_ASSERT_PREV_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_ASSERT_PREV_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ class AssertPrevDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr char kDatasetType[] = "AssertPrev";
27
+ static constexpr char kInputDataset[] = "input_dataset";
28
+ static constexpr char kTransformations[] = "transformations";
29
+ static constexpr char kOutputTypes[] = "output_types";
30
+ static constexpr char kOutputShapes[] = "output_shapes";
31
+
32
+ explicit AssertPrevDatasetOp(OpKernelConstruction* ctx);
33
+
34
+ protected:
35
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
36
+ DatasetBase** output) override;
37
+
38
+ private:
39
+ class Dataset;
40
+ DataTypeVector output_types_;
41
+ std::vector<PartialTensorShape> output_shapes_;
42
+ };
43
+
44
+ } // namespace experimental
45
+ } // namespace data
46
+ } // namespace tensorflow
47
+
48
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_ASSERT_PREV_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/auto_shard_dataset_op.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_AUTO_SHARD_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_AUTO_SHARD_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ class AutoShardDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "AutoShard";
27
+ static constexpr const char* const kInputDataset = "input_dataset";
28
+ static constexpr const char* const kNumWorkers = "num_workers";
29
+ static constexpr const char* const kIndex = "index";
30
+ static constexpr const char* const kAutoShardPolicy = "auto_shard_policy";
31
+ static constexpr const char* const kNumReplicas = "num_replicas";
32
+ static constexpr const char* const kOutputTypes = "output_types";
33
+ static constexpr const char* const kOutputShapes = "output_shapes";
34
+
35
+ explicit AutoShardDatasetOp(OpKernelConstruction* ctx);
36
+
37
+ protected:
38
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
39
+ DatasetBase** output) override;
40
+
41
+ private:
42
+ static RewriterConfig CreateConfig(int64_t num_workers, int64_t index,
43
+ int64_t auto_shard_policy,
44
+ int64_t num_replicas);
45
+ int64_t auto_shard_policy_;
46
+ int64_t num_replicas_;
47
+ };
48
+
49
+ } // namespace experimental
50
+ } // namespace data
51
+ } // namespace tensorflow
52
+
53
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_AUTO_SHARD_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/compression_ops.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_COMPRESSION_OPS_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_COMPRESSION_OPS_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ class CompressElementOp : public OpKernel {
25
+ public:
26
+ explicit CompressElementOp(OpKernelConstruction* ctx);
27
+
28
+ void Compute(OpKernelContext* ctx) override;
29
+ };
30
+
31
+ class UncompressElementOp : public OpKernel {
32
+ public:
33
+ static constexpr const char* const kOutputTypes = "output_types";
34
+ static constexpr const char* const kOutputShapes = "output_shapes";
35
+
36
+ explicit UncompressElementOp(OpKernelConstruction* ctx);
37
+
38
+ void Compute(OpKernelContext* ctx) override;
39
+
40
+ private:
41
+ DataTypeVector output_types_;
42
+ std::vector<PartialTensorShape> output_shapes_;
43
+ };
44
+
45
+ } // namespace experimental
46
+ } // namespace data
47
+ } // namespace tensorflow
48
+
49
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_COMPRESSION_OPS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/directed_interleave_dataset_op.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_DIRECTED_INTERLEAVE_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_DIRECTED_INTERLEAVE_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ class DirectedInterleaveDatasetOp : public DatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "DirectedInterleave";
27
+ static constexpr const char* const kSelectorInputDataset =
28
+ "selector_input_dataset";
29
+ static constexpr const char* const kDataInputDatasets = "data_input_datasets";
30
+ static constexpr const char* const kOutputTypes = "output_types";
31
+ static constexpr const char* const kOutputShapes = "output_shapes";
32
+ static constexpr const char* const kNumInputDatasets = "N";
33
+ static constexpr const char* const kStopOnEmptyDataset =
34
+ "stop_on_empty_dataset";
35
+
36
+ explicit DirectedInterleaveDatasetOp(OpKernelConstruction* ctx);
37
+
38
+ protected:
39
+ void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override;
40
+
41
+ private:
42
+ class Dataset;
43
+ bool stop_on_empty_dataset_ = false;
44
+ };
45
+
46
+ } // namespace experimental
47
+ } // namespace data
48
+ } // namespace tensorflow
49
+
50
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_DIRECTED_INTERLEAVE_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/list_dataset_op.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_LIST_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_LIST_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+
23
+ class ListDatasetOp : public DatasetOpKernel {
24
+ public:
25
+ static constexpr const char* const kDatasetType = "List";
26
+ static constexpr const char* const kTensors = "tensors";
27
+ static constexpr const char* const kTinputTypes = "Tinput_types";
28
+ static constexpr const char* const kOutputTypes = "output_types";
29
+ static constexpr const char* const kOutputShapes = "output_shapes";
30
+
31
+ explicit ListDatasetOp(OpKernelConstruction* ctx);
32
+
33
+ protected:
34
+ void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override;
35
+
36
+ private:
37
+ class Dataset;
38
+ DataTypeVector input_types_;
39
+ DataTypeVector output_types_;
40
+ std::vector<PartialTensorShape> output_shapes_;
41
+ };
42
+
43
+ } // namespace data
44
+ } // namespace tensorflow
45
+
46
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_LIST_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/lmdb_dataset_op.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_LMDB_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_LMDB_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ class LMDBDatasetOp : public DatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "LMDB";
27
+ static constexpr const char* const kFileNames = "filenames";
28
+ static constexpr const char* const kOutputTypes = "output_types";
29
+ static constexpr const char* const kOutputShapes = "output_shapes";
30
+
31
+ using DatasetOpKernel::DatasetOpKernel;
32
+
33
+ protected:
34
+ void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override;
35
+
36
+ private:
37
+ class Dataset;
38
+ };
39
+
40
+ } // namespace experimental
41
+ } // namespace data
42
+ } // namespace tensorflow
43
+
44
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_LMDB_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/load_dataset_op.h ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_LOAD_DATASET_OP_H_
17
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_LOAD_DATASET_OP_H_
18
+
19
+ #include <memory>
20
+ #include <string>
21
+ #include <vector>
22
+
23
+ #include "tensorflow/core/data/captured_function.h"
24
+ #include "tensorflow/core/framework/dataset.h"
25
+ #include "tensorflow/core/framework/op_kernel.h"
26
+
27
+ namespace tensorflow {
28
+ namespace data {
29
+ namespace experimental {
30
+
31
+ // An operation that can load a dataset from one or more files.
32
+ class LoadDatasetOp : public DatasetOpKernel {
33
+ public:
34
+ static constexpr const char* const kCompression = "compression";
35
+ static constexpr const char* const kDatasetType = "Load";
36
+ static constexpr const char* const kOutputTypes = "output_types";
37
+ static constexpr const char* const kOutputShapes = "output_shapes";
38
+ static constexpr const char* const kPath = "path";
39
+ static constexpr const char* const kReaderFunc = "reader_func";
40
+ static constexpr const char* const kReaderFuncOtherArgs =
41
+ "reader_func_other_args";
42
+ static constexpr const char* const kReaderFuncTarguments =
43
+ "Treader_func_args";
44
+
45
+ explicit LoadDatasetOp(OpKernelConstruction* ctx);
46
+
47
+ void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override;
48
+
49
+ private:
50
+ class Dataset;
51
+
52
+ std::string compression_;
53
+ DataTypeVector output_types_;
54
+ std::vector<PartialTensorShape> output_shapes_;
55
+ std::shared_ptr<FunctionMetadata> reader_func_metadata_;
56
+ };
57
+
58
+ } // namespace experimental
59
+ } // namespace data
60
+ } // namespace tensorflow
61
+
62
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_LOAD_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/map_and_batch_dataset_op.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_MAP_AND_BATCH_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_MAP_AND_BATCH_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/data/captured_function.h"
19
+ #include "tensorflow/core/framework/dataset.h"
20
+
21
+ namespace tensorflow {
22
+ namespace data {
23
+ namespace experimental {
24
+
25
+ // See documentation in ../../ops/experimental_dataset_ops.cc for a high-level
26
+ // description of the following op.
27
+
28
+ class MapAndBatchDatasetOp : public UnaryDatasetOpKernel {
29
+ public:
30
+ static constexpr const char* const kDatasetType = "MapAndBatch";
31
+ static constexpr const char* const kInputDataset = "input_dataset";
32
+ static constexpr const char* const kOtherArguments = "other_arguments";
33
+ static constexpr const char* const kBatchSize = "batch_size";
34
+ static constexpr const char* const kNumParallelCalls = "num_parallel_calls";
35
+ static constexpr const char* const kDropRemainder = "drop_remainder";
36
+ static constexpr const char* const kFunc = "f";
37
+ static constexpr const char* const kTarguments = "Targuments";
38
+ static constexpr const char* const kOutputTypes = "output_types";
39
+ static constexpr const char* const kOutputShapes = "output_shapes";
40
+ static constexpr const char* const kPreserveCardinality =
41
+ "preserve_cardinality";
42
+
43
+ explicit MapAndBatchDatasetOp(OpKernelConstruction* ctx);
44
+
45
+ protected:
46
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
47
+ DatasetBase** output) override;
48
+
49
+ private:
50
+ class Dataset;
51
+ std::shared_ptr<FunctionMetadata> func_metadata_ = nullptr;
52
+ DataTypeVector output_types_;
53
+ std::vector<PartialTensorShape> output_shapes_;
54
+ bool preserve_cardinality_;
55
+ };
56
+
57
+ } // namespace experimental
58
+ } // namespace data
59
+ } // namespace tensorflow
60
+
61
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_MAP_AND_BATCH_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/parallel_interleave_dataset_op.h ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_PARALLEL_INTERLEAVE_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_PARALLEL_INTERLEAVE_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/data/captured_function.h"
19
+ #include "tensorflow/core/data/dataset_utils.h"
20
+ #include "tensorflow/core/framework/dataset.h"
21
+
22
+ namespace tensorflow {
23
+ namespace data {
24
+ namespace experimental {
25
+
26
+ // See documentation in ../../ops/experimental_dataset_ops.cc for a high-level
27
+ // description of the following op.
28
+
29
+ class ParallelInterleaveDatasetOp : public UnaryDatasetOpKernel {
30
+ public:
31
+ static constexpr const char* const kDatasetType = "LegacyParallelInterleave";
32
+ static constexpr const char* const kInputDataset = "input_dataset";
33
+ static constexpr const char* const kOtherArguments = "other_arguments";
34
+ static constexpr const char* const kCycleLength = "cycle_length";
35
+ static constexpr const char* const kBlockLength = "block_length";
36
+ static constexpr const char* const kDeterministic = "deterministic";
37
+ static constexpr const char* const kSloppy = "sloppy";
38
+ static constexpr const char* const kBufferOutputElements =
39
+ "buffer_output_elements";
40
+ static constexpr const char* const kPrefetchInputElements =
41
+ "prefetch_input_elements";
42
+ static constexpr const char* const kFunc = "f";
43
+ static constexpr const char* const kTarguments = "Targuments";
44
+ static constexpr const char* const kOutputTypes = "output_types";
45
+ static constexpr const char* const kOutputShapes = "output_shapes";
46
+
47
+ explicit ParallelInterleaveDatasetOp(OpKernelConstruction* ctx);
48
+
49
+ protected:
50
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
51
+ DatasetBase** output) override;
52
+
53
+ private:
54
+ class Dataset;
55
+ const int op_version_;
56
+
57
+ std::shared_ptr<FunctionMetadata> func_metadata_ = nullptr;
58
+ DataTypeVector output_types_;
59
+ std::vector<PartialTensorShape> output_shapes_;
60
+ DeterminismPolicy deterministic_;
61
+ };
62
+
63
+ } // namespace experimental
64
+ } // namespace data
65
+ } // namespace tensorflow
66
+
67
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_PARALLEL_INTERLEAVE_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/random_access_ops.h ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_RANDOM_ACCESS_OPS_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_RANDOM_ACCESS_OPS_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+ #include "tensorflow/core/framework/op_kernel.h"
20
+ #include "tensorflow/core/framework/op_requires.h"
21
+ #include "tensorflow/core/kernels/data/iterator_ops.h"
22
+ #include "tensorflow/core/platform/platform.h"
23
+
24
+ namespace tensorflow {
25
+ namespace data {
26
+ namespace experimental {
27
+
28
+ // An operation that can get an element at a specified index in a dataset.
29
+ class GetElementAtIndexOp : public AsyncOpKernel {
30
+ public:
31
+ explicit GetElementAtIndexOp(OpKernelConstruction* ctx)
32
+ : AsyncOpKernel(ctx),
33
+ unbounded_threadpool_(ctx->env(), "tf_data_get_element_at_index") {
34
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
35
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_));
36
+ }
37
+
38
+ ~GetElementAtIndexOp() override {}
39
+
40
+ void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
41
+ unbounded_threadpool_.Schedule([this, ctx, done = std::move(done)]() {
42
+ ctx->SetStatus(DoCompute(ctx));
43
+ done();
44
+ });
45
+ }
46
+
47
+ void Compute(OpKernelContext* ctx) override {
48
+ ctx->SetStatus(DoCompute(ctx));
49
+ }
50
+
51
+ protected:
52
+ Status DoCompute(OpKernelContext* ctx);
53
+
54
+ private:
55
+ UnboundedThreadPool unbounded_threadpool_;
56
+ DataTypeVector output_types_;
57
+ std::vector<PartialTensorShape> output_shapes_;
58
+ };
59
+
60
+ } // namespace experimental
61
+ } // namespace data
62
+ } // namespace tensorflow
63
+
64
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_RANDOM_ACCESS_OPS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/random_dataset_op.h ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_RANDOM_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_RANDOM_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ // See tensorflow/core/api_def/base_api/api_def_RandomDataset.pbtxt for the
25
+ // API definition that corresponds to this kernel.
26
+ class RandomDatasetOp : public DatasetOpKernel {
27
+ public:
28
+ // Names of op parameters, public so that they can be accessed by test cases.
29
+ // Make sure that these are kept in sync with the REGISTER_OP call in
30
+ // tensorflow/core/ops/experimental_dataset_ops.cc
31
+ static constexpr const char* const kDatasetType = "Random";
32
+ static constexpr const char* const kSeed = "seed";
33
+ static constexpr const char* const kSeed2 = "seed2";
34
+ static constexpr const char* const kOutputTypes = "output_types";
35
+ static constexpr const char* const kOutputShapes = "output_shapes";
36
+ static constexpr const char* const kRerandomizeEachIteration =
37
+ "rerandomize_each_iteration";
38
+
39
+ explicit RandomDatasetOp(OpKernelConstruction* ctx);
40
+
41
+ protected:
42
+ void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override;
43
+
44
+ private:
45
+ class Dataset;
46
+ int32_t op_version_;
47
+ bool rerandomize_each_iteration_ = false;
48
+ };
49
+
50
+ } // namespace experimental
51
+ } // namespace data
52
+ } // namespace tensorflow
53
+
54
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_RANDOM_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/sampling_dataset_op.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SAMPLING_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SAMPLING_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ // See tensorflow/core/api_def/base_api/api_def_SamplingDataset.pbtxt for the
25
+ // API definition that corresponds to this kernel.
26
+ class SamplingDatasetOp : public UnaryDatasetOpKernel {
27
+ public:
28
+ // Names of op parameters, public so that they can be accessed by test cases.
29
+ // Make sure that these are kept in sync with the REGISTER_OP call in
30
+ // tensorflow/core/ops/experimental_dataset_ops.cc
31
+ static constexpr const char* const kDatasetType = "Sampling";
32
+ static constexpr const char* const kInputDataset = "input_dataset";
33
+ static constexpr const char* const kRate = "rate";
34
+ static constexpr const char* const kSeed = "seed";
35
+ static constexpr const char* const kSeed2 = "seed2";
36
+ static constexpr const char* const kOutputTypes = "output_types";
37
+ static constexpr const char* const kOutputShapes = "output_shapes";
38
+
39
+ explicit SamplingDatasetOp(OpKernelConstruction* ctx);
40
+
41
+ protected:
42
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
43
+ DatasetBase** output) override;
44
+
45
+ private:
46
+ class Dataset;
47
+ };
48
+
49
+ } // namespace experimental
50
+ } // namespace data
51
+ } // namespace tensorflow
52
+
53
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SAMPLING_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/save_dataset_op.h ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SAVE_DATASET_OP_H_
17
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SAVE_DATASET_OP_H_
18
+
19
+ #include <memory>
20
+ #include <string>
21
+ #include <vector>
22
+
23
+ #include "tensorflow/core/data/captured_function.h"
24
+ #include "tensorflow/core/framework/dataset.h"
25
+ #include "tensorflow/core/framework/op_kernel.h"
26
+ #include "tensorflow/core/kernels/data/iterator_ops.h"
27
+ #include "tensorflow/core/platform/thread_annotations.h"
28
+
29
+ namespace tensorflow {
30
+ namespace data {
31
+ namespace experimental {
32
+
33
+ // An operation that can save a dataset to one or more files.
34
+ class SaveDatasetOp : public HybridAsyncOpKernel {
35
+ public:
36
+ static constexpr const char* const kCompression = "compression";
37
+ static constexpr const char* const kPath = "path";
38
+ static constexpr const char* const kShardFunc = "shard_func";
39
+ static constexpr const char* const kShardFuncOtherArgs =
40
+ "shard_func_other_args";
41
+ static constexpr const char* const kUseShardFunc = "use_shard_func";
42
+
43
+ explicit SaveDatasetOp(OpKernelConstruction* ctx);
44
+
45
+ Status DoCompute(OpKernelContext* ctx) override;
46
+
47
+ private:
48
+ static constexpr const int kFileFormatVersion = 2;
49
+
50
+ Status ConsumeElement();
51
+
52
+ Status GetShardIndex(IteratorContext* ctx,
53
+ InstantiatedCapturedFunction* function,
54
+ const std::vector<Tensor>& element,
55
+ int64_t* shard_index);
56
+
57
+ Status WriteData(OpKernelContext* ctx, DatasetBase* dataset,
58
+ std::unique_ptr<CapturedFunction> captured_func,
59
+ const std::string& run_dir, uint64* num_elements);
60
+
61
+ Status WriteMetadataFile(Env* env, const std::string& path, uint64 run_id,
62
+ const DataTypeVector& output_dtypes,
63
+ uint64 num_elements, bool finalized);
64
+
65
+ bool use_shard_func_;
66
+ std::string compression_;
67
+ std::shared_ptr<FunctionMetadata> func_metadata_;
68
+ };
69
+
70
+ // An operation that can save a dataset to one or more files. This
71
+ // version of the implementation subclasses from UnaryDatasetOpKernel to align
72
+ // the implementation of save with that of the other tf.data transformations.
73
+ class SaveDatasetV2Op : public UnaryDatasetOpKernel {
74
+ public:
75
+ static constexpr const char* const kInputDataset = "input_dataset";
76
+ static constexpr const char* const kPath = "path";
77
+ static constexpr const char* const kCompression = "compression";
78
+
79
+ static constexpr const char* const kDatasetType = "SaveV2";
80
+ static constexpr const char* const kOutputTypes = "output_types";
81
+ static constexpr const char* const kOutputShapes = "output_shapes";
82
+
83
+ static constexpr const char* const kShardFunc = "shard_func";
84
+ static constexpr const char* const kShardFuncOtherArgs =
85
+ "shard_func_other_args";
86
+ static constexpr const char* const kUseShardFunc = "use_shard_func";
87
+ static constexpr const char* const kShardFuncTarguments = "Tshard_func_args";
88
+
89
+ explicit SaveDatasetV2Op(OpKernelConstruction* ctx);
90
+
91
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
92
+ DatasetBase** output) override;
93
+
94
+ private:
95
+ class Dataset;
96
+
97
+ static constexpr const int kFileFormatVersion = 2;
98
+
99
+ tstring path_;
100
+ std::string compression_;
101
+ std::unique_ptr<CapturedFunction> shard_func_;
102
+ bool use_shard_func_;
103
+ DataTypeVector output_types_;
104
+ std::vector<PartialTensorShape> output_shapes_;
105
+ std::shared_ptr<FunctionMetadata> func_metadata_;
106
+ std::string writer_prefix_;
107
+ };
108
+
109
+ } // namespace experimental
110
+ } // namespace data
111
+ } // namespace tensorflow
112
+
113
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SAVE_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/snapshot_dataset_op.h ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SNAPSHOT_DATASET_OP_H_
17
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SNAPSHOT_DATASET_OP_H_
18
+
19
+ #include <string>
20
+
21
+ #include "absl/container/flat_hash_map.h"
22
+ #include "tensorflow/core/data/captured_function.h"
23
+ #include "tensorflow/core/data/dataset_utils.h"
24
+ #include "tensorflow/core/data/name_utils.h"
25
+ #include "tensorflow/core/data/snapshot_utils.h"
26
+ #include "tensorflow/core/framework/dataset.h"
27
+ #include "tensorflow/core/framework/op_kernel.h"
28
+ #include "tensorflow/core/framework/op_requires.h"
29
+ #include "tensorflow/core/framework/tensor_shape.h"
30
+ #include "tensorflow/core/framework/types.h"
31
+ #include "tensorflow/core/lib/gtl/map_util.h"
32
+ #include "tensorflow/core/platform/env.h"
33
+ #include "tensorflow/core/platform/errors.h"
34
+ #include "tensorflow/core/platform/mutex.h"
35
+ #include "tensorflow/core/platform/path.h"
36
+ #include "tensorflow/core/platform/random.h"
37
+ #include "tensorflow/core/platform/thread_annotations.h"
38
+
39
+ namespace tensorflow {
40
+ namespace data {
41
+ namespace experimental {
42
+
43
+ class SnapshotDatasetV2Op : public UnaryDatasetOpKernel {
44
+ public:
45
+ static constexpr const char* const kDatasetType = "Snapshot";
46
+ static constexpr const char* const kOutputTypes = "output_types";
47
+ static constexpr const char* const kOutputShapes = "output_shapes";
48
+ static constexpr const char* const kCompression = "compression";
49
+ static constexpr const char* const kReaderPrefix = "reader_prefix";
50
+ static constexpr const char* const kWriterPrefix = "writer_prefix";
51
+ static constexpr const char* const kHashValid = "hash_valid";
52
+ static constexpr const char* const kHash = "hash";
53
+ static constexpr const char* const kCompressionAuto = "AUTO";
54
+ static constexpr const char* const kReaderFunc = "reader_func";
55
+ static constexpr const char* const kShardFunc = "shard_func";
56
+ static constexpr const char* const kReaderFuncOtherArgs =
57
+ "reader_func_other_args";
58
+ static constexpr const char* const kShardFuncOtherArgs =
59
+ "shard_func_other_args";
60
+ static constexpr const char* const kReaderFuncTarguments =
61
+ "Treader_func_args";
62
+ static constexpr const char* const kShardFuncTarguments = "Tshard_func_args";
63
+ // Note: If a new constant is declared here, it *must* be defined in
64
+ // snapshot_dataset_op.cc, otherwise it will not compile in debug mode.
65
+
66
+ explicit SnapshotDatasetV2Op(OpKernelConstruction* ctx);
67
+
68
+ protected:
69
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
70
+ DatasetBase** output) override;
71
+
72
+ private:
73
+ static constexpr const int kFileFormatVersion = 2;
74
+
75
+ class Dataset;
76
+
77
+ const int graph_def_version_;
78
+ DataTypeVector output_types_;
79
+ std::vector<PartialTensorShape> output_shapes_;
80
+
81
+ std::string compression_;
82
+ std::string reader_prefix_;
83
+ std::string writer_prefix_;
84
+ bool hash_valid_;
85
+ uint64 hash_;
86
+
87
+ std::shared_ptr<FunctionMetadata> reader_func_metadata_;
88
+ std::shared_ptr<FunctionMetadata> shard_func_metadata_;
89
+ };
90
+
91
+ } // namespace experimental
92
+ } // namespace data
93
+ } // namespace tensorflow
94
+
95
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SNAPSHOT_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/sql/driver_manager.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SQL_DRIVER_MANAGER_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SQL_DRIVER_MANAGER_H_
17
+
18
+ #include "tensorflow/core/kernels/data/experimental/sql/query_connection.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+ namespace sql {
24
+
25
+ // A factory class for creating `QueryConnection` instances.
26
+ class DriverManager {
27
+ public:
28
+ // A factory method for creating `QueryConnection` instances.
29
+ //
30
+ // `driver_name` is the database type (e.g. 'sqlite'). `driver_name`
31
+ // corresponds to a `QueryConnection` subclass. For example, if `driver_name`
32
+ // == `sqlite`, then `CreateQueryConnection` will create a
33
+ // `SqliteQueryConnection` instance.
34
+ static std::unique_ptr<QueryConnection> CreateQueryConnection(
35
+ const string& driver_name);
36
+ };
37
+
38
+ } // namespace sql
39
+ } // namespace experimental
40
+ } // namespace data
41
+ } // namespace tensorflow
42
+
43
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SQL_DRIVER_MANAGER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/sql/query_connection.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SQL_QUERY_CONNECTION_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SQL_QUERY_CONNECTION_H_
17
+
18
+ #include "tensorflow/core/framework/tensor.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+
23
+ class IteratorContext;
24
+
25
+ namespace experimental {
26
+
27
+ namespace sql {
28
+ // This interface allows a user to connect to a database, execute a query, and
29
+ // iterate over the result set, putting the results into an output tensor.
30
+ // A subclass implementation is required for each type of database
31
+ // (e.g. sqlite3, mysql, etc.)
32
+ //
33
+ // Presently, a `QueryConnection` instance can only handle one query at a time.
34
+ // In a future extension, this class may be refactored so that it creates
35
+ // instances of a new class (named, say, `Statement`) which could have a
36
+ // one-to-one correspondence with queries. This would make `QueryConnection`
37
+ // more consistent with `Connection` classes of other database APIs.
38
+ // `QueryConnection` would then be renamed simply `Connection`.
39
+ //
40
+ // This class is not thread safe. Access to it is guarded by a mutex in
41
+ // `SqlDatasetOp::Dataset::Iterator`.
42
+ class QueryConnection {
43
+ public:
44
+ virtual ~QueryConnection() {}
45
+ // Opens a connection to the database named by `data_source_name`. Prepares to
46
+ // execute `query` against the database.
47
+ //
48
+ // The client must call `Close()` to release the connection resources, even
49
+ // if `Open()` fails. `Close()` must be called before making another call
50
+ // to `Open()`.
51
+ virtual Status Open(const string& data_source_name, const string& query,
52
+ const DataTypeVector& output_types) = 0;
53
+ // Closes an opened connection.
54
+ virtual Status Close() = 0;
55
+ // Retrieves the next row of the result set of the query from the most recent
56
+ // call to `Open()`.
57
+ //
58
+ // If such a row exists, then the row will be stored in `*out_tensors`, and
59
+ // `false` will be stored in `*end_of_sequence`.
60
+ //
61
+ // If there are no more rows in the result set, then instead `true` will be
62
+ // stored in `*end_of_sequence`, and the content of `*out_tensors` will be
63
+ // undefined.
64
+ virtual Status GetNext(IteratorContext* ctx, std::vector<Tensor>* out_tensors,
65
+ bool* end_of_sequence) = 0;
66
+ };
67
+
68
+ } // namespace sql
69
+ } // namespace experimental
70
+ } // namespace data
71
+ } // namespace tensorflow
72
+
73
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SQL_QUERY_CONNECTION_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/sql/sqlite_query_connection.h ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SQL_SQLITE_QUERY_CONNECTION_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SQL_SQLITE_QUERY_CONNECTION_H_
17
+
18
+ #include <memory>
19
+
20
+ #include "tensorflow/core/kernels/data/experimental/sql/query_connection.h"
21
+ #include "tensorflow/core/lib/db/sqlite.h"
22
+ #include "tensorflow/core/platform/types.h"
23
+
24
+ namespace tensorflow {
25
+ namespace data {
26
+ namespace experimental {
27
+ namespace sql {
28
+
29
+ class SqliteQueryConnection : public QueryConnection {
30
+ public:
31
+ SqliteQueryConnection();
32
+ ~SqliteQueryConnection() override;
33
+ Status Open(const string& data_source_name, const string& query,
34
+ const DataTypeVector& output_types) override;
35
+ Status Close() override;
36
+ Status GetNext(IteratorContext* ctx, std::vector<Tensor>* out_tensors,
37
+ bool* end_of_sequence) override;
38
+
39
+ private:
40
+ // Prepares the query string `query_`.
41
+ Status PrepareQuery();
42
+ // Fills `tensor` with the column_index_th element of the current row of
43
+ // `stmt_`.
44
+ void FillTensorWithResultSetEntry(const DataType& data_type, int column_index,
45
+ Tensor* tensor);
46
+ Sqlite* db_ = nullptr;
47
+ SqliteStatement stmt_;
48
+ int column_count_ = 0;
49
+ string query_;
50
+ DataTypeVector output_types_;
51
+ };
52
+
53
+ } // namespace sql
54
+ } // namespace experimental
55
+ } // namespace data
56
+ } // namespace tensorflow
57
+
58
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_SQL_SQLITE_QUERY_CONNECTION_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/threadpool_dataset_op.h ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_THREADPOOL_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_THREADPOOL_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+ #include "tensorflow/core/platform/platform.h"
20
+
21
+ namespace tensorflow {
22
+ namespace data {
23
+ namespace experimental {
24
+
25
+ class MaxIntraOpParallelismDatasetOp : public UnaryDatasetOpKernel {
26
+ public:
27
+ static constexpr const char* const kDatasetType =
28
+ "MaxIntraOpParallelismDataset";
29
+ static constexpr const char* const kDatasetOp =
30
+ "MaxIntraOpParallelismDatasetOp";
31
+
32
+ // Executes the logic of the MaxIntraOpParallelismDatasetOp directly (as
33
+ // opposed to through executing the MaxIntraOpParallelismDatasetOp op kernel).
34
+ static void MakeDatasetFromOptions(OpKernelContext* ctx, DatasetBase* input,
35
+ int32_t max_intra_op_parallelism,
36
+ DatasetBase** output);
37
+
38
+ explicit MaxIntraOpParallelismDatasetOp(OpKernelConstruction* ctx)
39
+ : UnaryDatasetOpKernel(ctx) {}
40
+
41
+ protected:
42
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
43
+ DatasetBase** output) override;
44
+
45
+ private:
46
+ class Dataset;
47
+ };
48
+
49
+ class PrivateThreadPoolDatasetOp : public UnaryDatasetOpKernel {
50
+ public:
51
+ static constexpr const char* const kDatasetType = "PrivateThreadPoolDataset";
52
+ static constexpr const char* const kDatasetOp = "PrivateThreadPoolDatasetOp";
53
+
54
+ // Executes the logic of the PrivateThreadpoolDatasetOp directly (as
55
+ // opposed to through executing the PrivateThreadpoolDatasetOp op kernel).
56
+ static void MakeDatasetFromOptions(OpKernelContext* ctx, DatasetBase* input,
57
+ int32_t num_threads, DatasetBase** output);
58
+
59
+ explicit PrivateThreadPoolDatasetOp(OpKernelConstruction* ctx)
60
+ : UnaryDatasetOpKernel(ctx) {}
61
+
62
+ protected:
63
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
64
+ DatasetBase** output) override;
65
+
66
+ private:
67
+ class Dataset;
68
+ };
69
+
70
+ } // namespace experimental
71
+ } // namespace data
72
+ } // namespace tensorflow
73
+
74
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_THREADPOOL_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/experimental/unique_dataset_op.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_UNIQUE_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_UNIQUE_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+ namespace experimental {
23
+
24
+ class UniqueDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "Unique";
27
+ static constexpr const char* const kInputDataset = "input_dataset";
28
+ static constexpr const char* const kOutputTypes = "output_types";
29
+ static constexpr const char* const kOutputShapes = "output_shapes";
30
+
31
+ explicit UniqueDatasetOp(OpKernelConstruction* ctx)
32
+ : UnaryDatasetOpKernel(ctx) {}
33
+
34
+ protected:
35
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
36
+ DatasetBase** output) override;
37
+
38
+ private:
39
+ class Dataset;
40
+ };
41
+
42
+ } // namespace experimental
43
+ } // namespace data
44
+ } // namespace tensorflow
45
+
46
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_UNIQUE_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/filter_dataset_op.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_FILTER_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_FILTER_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/data/captured_function.h"
19
+ #include "tensorflow/core/framework/dataset.h"
20
+
21
+ namespace tensorflow {
22
+ namespace data {
23
+
24
+ class FilterDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "Filter";
27
+ static constexpr const char* const kInputDataset = "input_dataset";
28
+ static constexpr const char* const kOtherArguments = "other_arguments";
29
+ static constexpr const char* const kPredicate = "predicate";
30
+ static constexpr const char* const kTarguments = "Targuments";
31
+ static constexpr const char* const kOutputTypes = "output_types";
32
+ static constexpr const char* const kOutputShapes = "output_shapes";
33
+
34
+ explicit FilterDatasetOp(OpKernelConstruction* ctx);
35
+
36
+ protected:
37
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
38
+ DatasetBase** output) override;
39
+
40
+ private:
41
+ class Dataset;
42
+ std::shared_ptr<FunctionMetadata> func_metadata_ = nullptr;
43
+ };
44
+
45
+ } // namespace data
46
+ } // namespace tensorflow
47
+
48
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_FILTER_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/finalize_dataset_op.h ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_FINALIZE_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_FINALIZE_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+ #include "tensorflow/core/framework/op_kernel.h"
20
+
21
+ namespace tensorflow {
22
+ namespace data {
23
+
24
+ class FinalizeDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "Finalize";
27
+ static constexpr const char* const kInputDataset = "input_dataset";
28
+ static constexpr const char* const kOutputTypes = "output_types";
29
+ static constexpr const char* const kOutputShapes = "output_shapes";
30
+ static constexpr const char* const kHasCapturedRef = "has_captured_ref";
31
+
32
+ explicit FinalizeDatasetOp(OpKernelConstruction* ctx);
33
+
34
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
35
+ DatasetBase** output) override;
36
+
37
+ private:
38
+ class Dataset;
39
+ bool has_captured_ref_;
40
+ };
41
+
42
+ class FinalizeDatasetNoopOp : public UnaryDatasetOpKernel {
43
+ public:
44
+ explicit FinalizeDatasetNoopOp(OpKernelConstruction* ctx)
45
+ : UnaryDatasetOpKernel(ctx) {}
46
+
47
+ protected:
48
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
49
+ DatasetBase** output) override {
50
+ LOG(WARNING) << "FinalizeDataset is only supported on CPU. Using it on "
51
+ "devices other than CPU has no effect.";
52
+ input->Ref();
53
+ *output = input;
54
+ }
55
+ };
56
+
57
+ } // namespace data
58
+ } // namespace tensorflow
59
+
60
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_FINALIZE_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/fixed_length_record_dataset_op.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_FIXED_LENGTH_RECORD_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_FIXED_LENGTH_RECORD_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+
23
+ class FixedLengthRecordDatasetOp : public DatasetOpKernel {
24
+ public:
25
+ static constexpr const char* const kDatasetType = "FixedLengthRecord";
26
+ static constexpr const char* const kFileNames = "filenames";
27
+ static constexpr const char* const kHeaderBytes = "header_bytes";
28
+ static constexpr const char* const kRecordBytes = "record_bytes";
29
+ static constexpr const char* const kFooterBytes = "footer_bytes";
30
+ static constexpr const char* const kBufferSize = "buffer_size";
31
+ static constexpr const char* const kCompressionType = "compression_type";
32
+
33
+ explicit FixedLengthRecordDatasetOp(OpKernelConstruction* ctx);
34
+
35
+ protected:
36
+ void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override;
37
+
38
+ private:
39
+ class Dataset;
40
+ const int op_version_;
41
+ };
42
+
43
+ } // namespace data
44
+ } // namespace tensorflow
45
+
46
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_FIXED_LENGTH_RECORD_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/flat_map_dataset_op.h ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_FLAT_MAP_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_FLAT_MAP_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/data/captured_function.h"
19
+ #include "tensorflow/core/framework/dataset.h"
20
+
21
+ namespace tensorflow {
22
+ namespace data {
23
+
24
+ class FlatMapDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "FlatMap";
27
+ static constexpr const char* const kInputDataset = "input_dataset";
28
+ static constexpr const char* const kOtherArguments = "other_arguments";
29
+ static constexpr const char* const kFunc = "f";
30
+ static constexpr const char* const kTarguments = "Targuments";
31
+ static constexpr const char* const kOutputTypes = "output_types";
32
+ static constexpr const char* const kOutputShapes = "output_shapes";
33
+
34
+ explicit FlatMapDatasetOp(OpKernelConstruction* ctx);
35
+
36
+ protected:
37
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
38
+ DatasetBase** output) override;
39
+
40
+ private:
41
+ class Dataset;
42
+ const int graph_def_version_;
43
+ DataTypeVector output_types_;
44
+ std::vector<PartialTensorShape> output_shapes_;
45
+ std::shared_ptr<FunctionMetadata> func_metadata_ = nullptr;
46
+ };
47
+
48
+ } // namespace data
49
+ } // namespace tensorflow
50
+
51
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_FLAT_MAP_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/generator_dataset_op.h ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_CORE_KERNELS_DATA_GENERATOR_DATASET_OP_H_
17
+ #define TENSORFLOW_CORE_KERNELS_DATA_GENERATOR_DATASET_OP_H_
18
+
19
+ #include "tensorflow/core/data/captured_function.h"
20
+ #include "tensorflow/core/framework/dataset.h"
21
+
22
+ namespace tensorflow {
23
+ namespace data {
24
+
25
+ class GeneratorDatasetOp : public DatasetOpKernel {
26
+ public:
27
+ static constexpr const char* const kDatasetType = "Generator";
28
+ static constexpr const char* const kInitFuncOtherArgs =
29
+ "init_func_other_args";
30
+ static constexpr const char* const kNextFuncOtherArgs =
31
+ "next_func_other_args";
32
+ static constexpr const char* const kFinalizeFuncOtherArgs =
33
+ "finalize_func_other_args";
34
+ static constexpr const char* const kInitFunc = "init_func";
35
+ static constexpr const char* const kNextFunc = "next_func";
36
+ static constexpr const char* const kFinalizeFunc = "finalize_func";
37
+ static constexpr const char* const kTinitFuncArgs = "Tinit_func_args";
38
+ static constexpr const char* const kTnextFuncArgs = "Tnext_func_args";
39
+ static constexpr const char* const kTfinalizeFuncArgs = "Tfinalize_func_args";
40
+ static constexpr const char* const kOutputTypes = "output_types";
41
+ static constexpr const char* const kOutputShapes = "output_shapes";
42
+
43
+ explicit GeneratorDatasetOp(OpKernelConstruction* ctx);
44
+
45
+ void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override;
46
+
47
+ private:
48
+ class Dataset;
49
+
50
+ DataTypeVector output_types_;
51
+ std::vector<PartialTensorShape> output_shapes_;
52
+ std::shared_ptr<FunctionMetadata> init_func_metadata_ = nullptr;
53
+ std::shared_ptr<FunctionMetadata> next_func_metadata_ = nullptr;
54
+ std::shared_ptr<FunctionMetadata> finalize_func_metadata_ = nullptr;
55
+ };
56
+
57
+ } // namespace data
58
+ } // namespace tensorflow
59
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_GENERATOR_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/get_options_op.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_GET_OPTIONS_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_GET_OPTIONS_OP_H_
17
+
18
+ #include "tensorflow/core/framework/op_kernel.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+
23
+ // TODO(jsimsa): Provide class-level documentation for this and the other ops.
24
+ class GetOptionsOp : public OpKernel {
25
+ public:
26
+ explicit GetOptionsOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
27
+
28
+ void Compute(OpKernelContext* ctx) final;
29
+
30
+ string TraceString(const OpKernelContext& ctx, bool verbose) const override;
31
+ };
32
+
33
+ } // namespace data
34
+ } // namespace tensorflow
35
+
36
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_GET_OPTIONS_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/interleave_dataset_op.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_INTERLEAVE_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_INTERLEAVE_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/data/captured_function.h"
19
+ #include "tensorflow/core/framework/dataset.h"
20
+
21
+ namespace tensorflow {
22
+ namespace data {
23
+
24
+ class InterleaveDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "Interleave";
27
+ static constexpr const char* const kInputDataset = "input_dataset";
28
+ static constexpr const char* const kOtherArguments = "other_arguments";
29
+ static constexpr const char* const kCycleLength = "cycle_length";
30
+ static constexpr const char* const kBlockLength = "block_length";
31
+ static constexpr const char* const kFunc = "f";
32
+ static constexpr const char* const kTarguments = "Targuments";
33
+ static constexpr const char* const kOutputTypes = "output_types";
34
+ static constexpr const char* const kOutputShapes = "output_shapes";
35
+
36
+ explicit InterleaveDatasetOp(OpKernelConstruction* ctx);
37
+
38
+ protected:
39
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
40
+ DatasetBase** output) override;
41
+
42
+ private:
43
+ class Dataset;
44
+ const int graph_def_version_;
45
+ DataTypeVector output_types_;
46
+ std::vector<PartialTensorShape> output_shapes_;
47
+ std::shared_ptr<FunctionMetadata> func_metadata_ = nullptr;
48
+ };
49
+
50
+ } // namespace data
51
+ } // namespace tensorflow
52
+
53
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_INTERLEAVE_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/iterator_ops.h ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_CORE_KERNELS_DATA_ITERATOR_OPS_H_
17
+ #define TENSORFLOW_CORE_KERNELS_DATA_ITERATOR_OPS_H_
18
+
19
+ #include <memory>
20
+ #include <utility>
21
+ #include <vector>
22
+
23
+ #include "tensorflow/core/data/dataset_utils.h"
24
+ #include "tensorflow/core/data/metric_utils.h"
25
+ #include "tensorflow/core/data/tfdataz_metrics.h"
26
+ #include "tensorflow/core/data/unbounded_thread_pool.h"
27
+ #include "tensorflow/core/framework/dataset.h"
28
+ #include "tensorflow/core/framework/function_handle_cache.h"
29
+ #include "tensorflow/core/framework/op_kernel.h"
30
+ #include "tensorflow/core/framework/tensor_shape.h"
31
+ #include "tensorflow/core/framework/types.h"
32
+ #include "tensorflow/core/platform/refcount.h"
33
+
34
+ namespace tensorflow {
35
+ namespace data {
36
+
37
+ class IteratorResource : public ResourceBase {
38
+ public:
39
+ IteratorResource(Env* env, const DataTypeVector& output_dtypes,
40
+ const std::vector<PartialTensorShape>& output_shapes,
41
+ std::unique_ptr<DeviceMgr> device_mgr,
42
+ std::unique_ptr<FunctionLibraryDefinition> flib_def,
43
+ std::unique_ptr<ProcessFunctionLibraryRuntime> pflr,
44
+ FunctionLibraryRuntime* flr);
45
+
46
+ ~IteratorResource() override;
47
+
48
+ // Gets the next output from the iterator managed by this iterator resource.
49
+ //
50
+ // If at least one output remains, that output will be stored in
51
+ // `*out_tensors` and `false` will be stored in `*end_of_sequence`.
52
+ //
53
+ // If no more outputs remain, `true` will be stored in `*end_of_sequence`, and
54
+ // the content of `*out_tensors` will be undefined.
55
+ Status GetNext(OpKernelContext* ctx, std::vector<Tensor>* out_tensors,
56
+ bool* end_of_sequence);
57
+
58
+ // Saves a checkpoint of the state of the iterator through the given `writer`.
59
+ Status Save(OpKernelContext* ctx, ExternalStatePolicy external_state_policy,
60
+ IteratorStateWriter* writer);
61
+
62
+ // Restores the state of the iterator from a checkpoint created by `Save`.
63
+ Status Restore(OpKernelContext* ctx, IteratorStateReader* reader);
64
+
65
+ // Creates an iterator for `dataset`, and associates the iterator with this
66
+ // iterator resource.
67
+ //
68
+ // `SetIteratorFromDataset` should be called before calling `GetNext`, `Save`,
69
+ // or `Restore`.
70
+ Status SetIteratorFromDataset(OpKernelContext* ctx,
71
+ const DatasetBase* dataset);
72
+
73
+ string DebugString() const override { return "Iterator resource"; }
74
+
75
+ const DataTypeVector& output_dtypes() const { return output_dtypes_; }
76
+
77
+ const std::vector<PartialTensorShape>& output_shapes() const {
78
+ return output_shapes_;
79
+ }
80
+
81
+ private:
82
+ class State {
83
+ public:
84
+ State(std::shared_ptr<FunctionLibraryDefinition> flib_def,
85
+ std::shared_ptr<ProcessFunctionLibraryRuntime> pflr,
86
+ FunctionLibraryRuntime* flr,
87
+ std::unique_ptr<DatasetBaseIterator> iterator)
88
+ : flib_def_(std::move(flib_def)),
89
+ flr_(flr),
90
+ pflr_(std::move(pflr)),
91
+ function_handle_cache_(std::make_unique<FunctionHandleCache>(flr)),
92
+ iterator_(std::move(iterator)),
93
+
94
+ id_registry_(std::make_shared<MemoryCheckpoint::IdRegistry>()),
95
+ checkpoint_(MemoryCheckpoint::CreateRootCheckpoint(id_registry_)) {}
96
+
97
+ ~State() { cancellation_manager_.StartCancel(); }
98
+
99
+ std::shared_ptr<FunctionLibraryDefinition> flib_def() { return flib_def_; }
100
+
101
+ FunctionLibraryRuntime* flr() { return flr_; }
102
+
103
+ std::shared_ptr<ProcessFunctionLibraryRuntime> pflr() { return pflr_; }
104
+
105
+ FunctionHandleCache* function_handle_cache() {
106
+ return function_handle_cache_.get();
107
+ }
108
+
109
+ ResourceMgr* resource_mgr() { return &resource_mgr_; }
110
+
111
+ CancellationManager* cancellation_manager() {
112
+ return &cancellation_manager_;
113
+ }
114
+
115
+ DatasetBaseIterator* iterator() { return iterator_.get(); }
116
+
117
+ const MemoryCheckpoint& checkpoint() const { return checkpoint_; }
118
+
119
+ DatasetBase* dataset() { return dataset_.get(); }
120
+
121
+ // Downcasts the given `IteratorBase` to a `DatasetBaseIterator`, and uses
122
+ // it to set the `iterator` and the `dataset` field.
123
+ void DowncastAndSetIteratorAndDataset(std::unique_ptr<IteratorBase> it,
124
+ const DatasetBase* dataset);
125
+
126
+ // Merges the given checkpoint with the checkpoint of this state.
127
+ void MergeCheckpoint(MemoryCheckpoint* other);
128
+
129
+ std::shared_ptr<MemoryCheckpoint::IdRegistry> id_registry() {
130
+ return id_registry_;
131
+ }
132
+
133
+ private:
134
+ std::shared_ptr<FunctionLibraryDefinition> flib_def_;
135
+ FunctionLibraryRuntime* flr_ = nullptr; // not owned
136
+ std::shared_ptr<ProcessFunctionLibraryRuntime> pflr_;
137
+ std::unique_ptr<FunctionHandleCache> function_handle_cache_;
138
+ ResourceMgr resource_mgr_;
139
+ CancellationManager cancellation_manager_;
140
+ std::unique_ptr<DatasetBaseIterator> iterator_;
141
+ core::RefCountPtr<DatasetBase> dataset_;
142
+ std::shared_ptr<MemoryCheckpoint::IdRegistry> id_registry_;
143
+ MemoryCheckpoint checkpoint_;
144
+ };
145
+
146
+ IteratorMetricsCollector metrics_collector_;
147
+ std::shared_ptr<TfDatazMetricsCollector> tf_dataz_metrics_collector_;
148
+ UnboundedThreadPool unbounded_thread_pool_;
149
+
150
+ mutex mu_;
151
+ const Env& env_;
152
+ const std::unique_ptr<DeviceMgr> device_mgr_ TF_GUARDED_BY(mu_);
153
+ std::shared_ptr<State> iterator_state_ TF_GUARDED_BY(mu_);
154
+ const DataTypeVector output_dtypes_;
155
+ const std::vector<PartialTensorShape> output_shapes_;
156
+ };
157
+
158
+ class IteratorHandleOp : public OpKernel {
159
+ public:
160
+ explicit IteratorHandleOp(OpKernelConstruction* ctx);
161
+
162
+ // The resource is deleted from the resource manager only when it is private
163
+ // to kernel. Ideally the resource should be deleted when it is no longer held
164
+ // by anyone, but it would break backward compatibility.
165
+ ~IteratorHandleOp() override;
166
+
167
+ void Compute(OpKernelContext* context) override TF_LOCKS_EXCLUDED(mu_);
168
+
169
+ private:
170
+ // During the first Compute(), resource is either created or looked up using
171
+ // shared_name. In the latter case, the resource found should be verified if
172
+ // it is compatible with this op's configuration. The verification may fail in
173
+ // cases such as two graphs asking queues of the same shared name to have
174
+ // inconsistent capacities.
175
+ Status VerifyResource(IteratorResource* resource);
176
+
177
+ FunctionLibraryRuntime* CreatePrivateFLR(
178
+ OpKernelContext* ctx, std::unique_ptr<DeviceMgr>* device_mgr,
179
+ std::unique_ptr<FunctionLibraryDefinition>* flib_def,
180
+ std::unique_ptr<ProcessFunctionLibraryRuntime>* pflr);
181
+
182
+ mutex mu_;
183
+ ContainerInfo cinfo_; // Written once under mu_ then constant afterwards.
184
+ IteratorResource* resource_ TF_GUARDED_BY(mu_) = nullptr;
185
+ DataTypeVector output_dtypes_;
186
+ std::vector<PartialTensorShape> output_shapes_;
187
+ const int graph_def_version_;
188
+ string name_;
189
+ };
190
+
191
+ // Like IteratorHandleOp, but creates handles which are never shared, and does
192
+ // not hold a reference to these handles. The latter is important for eager
193
+ // execution, since OpKernel instances generally live as long as the program
194
+ // running them.
195
+ class AnonymousIteratorHandleOp : public AnonymousResourceOp<IteratorResource> {
196
+ public:
197
+ explicit AnonymousIteratorHandleOp(OpKernelConstruction* context);
198
+
199
+ private:
200
+ string name() override;
201
+
202
+ Status CreateResource(OpKernelContext* ctx,
203
+ std::unique_ptr<FunctionLibraryDefinition> flib_def,
204
+ std::unique_ptr<ProcessFunctionLibraryRuntime> pflr,
205
+ FunctionLibraryRuntime* lib,
206
+ IteratorResource** resource) override;
207
+
208
+ DataTypeVector output_dtypes_;
209
+ std::vector<PartialTensorShape> output_shapes_;
210
+ const int graph_def_version_;
211
+ };
212
+
213
+ // A hybrid asynchronous-and-synchronous OpKernel with efficient support for
214
+ // both modes.
215
+ //
216
+ // Inherit from this class when the application logic of the kernel (i) is
217
+ // implemented synchronously, (ii) must run on a background thread when the
218
+ // kernel executes in the inter-op threadpool (typically because it depends on
219
+ // inter-op threadpool threads, e.g. for function execution), and (iii) can run
220
+ // synchronously on the calling thread when the caller donates a thread
221
+ // (typically in eager execution). The implementation avoids a thread-hop in
222
+ // case (iii).
223
+ //
224
+ // NOTE: Unlike typical OpKernel subclasses, the application logic is
225
+ // implemented in a method (DoCompute()) that returns Status. Use
226
+ // TF_RETURN_IF_ERROR for error-related control flow rather than
227
+ // OP_REQUIRES_OK().
228
+ class HybridAsyncOpKernel : public AsyncOpKernel {
229
+ public:
230
+ HybridAsyncOpKernel(OpKernelConstruction* ctx,
231
+ const char* background_worker_name);
232
+
233
+ void Compute(OpKernelContext* ctx) final;
234
+ void ComputeAsync(OpKernelContext* ctx, DoneCallback done) final;
235
+
236
+ protected:
237
+ virtual Status DoCompute(OpKernelContext* ctx) = 0;
238
+
239
+ private:
240
+ BackgroundWorker background_worker_;
241
+ };
242
+
243
+ class MakeIteratorOp : public HybridAsyncOpKernel {
244
+ public:
245
+ explicit MakeIteratorOp(OpKernelConstruction* ctx)
246
+ : HybridAsyncOpKernel(ctx, "tf_data_make_iterator") {}
247
+
248
+ protected:
249
+ Status DoCompute(OpKernelContext* ctx) override;
250
+ };
251
+
252
+ class IteratorGetNextOp : public HybridAsyncOpKernel {
253
+ public:
254
+ explicit IteratorGetNextOp(OpKernelConstruction* ctx)
255
+ : HybridAsyncOpKernel(ctx, "tf_data_iterator_get_next") {
256
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
257
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_));
258
+ }
259
+
260
+ AsyncOpKernel* AsAsync() override;
261
+
262
+ protected:
263
+ Status DoCompute(OpKernelContext* ctx) override;
264
+
265
+ private:
266
+ DataTypeVector output_types_;
267
+ std::vector<PartialTensorShape> output_shapes_;
268
+ };
269
+
270
+ class DeleteIteratorOp : public HybridAsyncOpKernel {
271
+ public:
272
+ explicit DeleteIteratorOp(OpKernelConstruction* ctx)
273
+ : HybridAsyncOpKernel(ctx, "tf_data_delete_iterator") {}
274
+
275
+ protected:
276
+ Status DoCompute(OpKernelContext* ctx) override;
277
+ };
278
+
279
+ class IteratorGetNextAsOptionalOp : public HybridAsyncOpKernel {
280
+ public:
281
+ explicit IteratorGetNextAsOptionalOp(OpKernelConstruction* ctx)
282
+ : HybridAsyncOpKernel(ctx, "tf_data_iterator_get_next_as_optional") {
283
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
284
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_));
285
+ }
286
+
287
+ protected:
288
+ Status DoCompute(OpKernelContext* ctx) override;
289
+
290
+ private:
291
+ DataTypeVector output_types_;
292
+ std::vector<PartialTensorShape> output_shapes_;
293
+ };
294
+
295
+ class IteratorToStringHandleOp : public OpKernel {
296
+ public:
297
+ explicit IteratorToStringHandleOp(OpKernelConstruction* ctx)
298
+ : OpKernel(ctx) {}
299
+
300
+ void Compute(OpKernelContext* ctx) override;
301
+ };
302
+
303
+ class IteratorFromStringHandleOp : public OpKernel {
304
+ public:
305
+ explicit IteratorFromStringHandleOp(OpKernelConstruction* ctx);
306
+
307
+ void Compute(OpKernelContext* ctx) override;
308
+
309
+ private:
310
+ DataTypeVector output_dtypes_;
311
+ std::vector<PartialTensorShape> output_shapes_;
312
+ };
313
+
314
+ class SerializeIteratorOp : public OpKernel {
315
+ public:
316
+ static constexpr const char* const kExternalStatePolicy =
317
+ "external_state_policy";
318
+
319
+ explicit SerializeIteratorOp(OpKernelConstruction* ctx);
320
+
321
+ void Compute(OpKernelContext* ctx) override;
322
+
323
+ private:
324
+ ExternalStatePolicy external_state_policy_ = ExternalStatePolicy::POLICY_WARN;
325
+ };
326
+
327
+ class DeserializeIteratorOp : public OpKernel {
328
+ public:
329
+ explicit DeserializeIteratorOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
330
+
331
+ void Compute(OpKernelContext* ctx) override;
332
+ };
333
+
334
+ } // namespace data
335
+ } // namespace tensorflow
336
+
337
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_ITERATOR_OPS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/map_dataset_op.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_MAP_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_MAP_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/data/captured_function.h"
19
+ #include "tensorflow/core/framework/dataset.h"
20
+
21
+ namespace tensorflow {
22
+ namespace data {
23
+
24
+ class MapDatasetOp : public UnaryDatasetOpKernel {
25
+ public:
26
+ static constexpr const char* const kDatasetType = "Map";
27
+ static constexpr const char* const kInputDataset = "input_dataset";
28
+ static constexpr const char* const kOtherArguments = "other_arguments";
29
+ static constexpr const char* const kFunc = "f";
30
+ static constexpr const char* const kTarguments = "Targuments";
31
+ static constexpr const char* const kOutputTypes = "output_types";
32
+ static constexpr const char* const kOutputShapes = "output_shapes";
33
+ static constexpr const char* const kUseInterOpParallelism =
34
+ "use_inter_op_parallelism";
35
+ static constexpr const char* const kPreserveCardinality =
36
+ "preserve_cardinality";
37
+
38
+ explicit MapDatasetOp(OpKernelConstruction* ctx);
39
+
40
+ protected:
41
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
42
+ DatasetBase** output) override;
43
+
44
+ private:
45
+ class Dataset;
46
+ std::shared_ptr<FunctionMetadata> func_metadata_ = nullptr;
47
+ DataTypeVector output_types_;
48
+ std::vector<PartialTensorShape> output_shapes_;
49
+ bool preserve_cardinality_;
50
+ };
51
+
52
+ } // namespace data
53
+ } // namespace tensorflow
54
+
55
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_MAP_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/map_defun_op.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_MAP_DEFUN_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_MAP_DEFUN_OP_H_
17
+
18
+ #include "tensorflow/core/framework/dataset.h"
19
+
20
+ namespace tensorflow {
21
+ namespace data {
22
+
23
+ // This op runs a given defun on slices of the input arguments. The function
24
+ // given by "f" is assumed to be stateless, and is executed concurrently
25
+ // on all the slices; up to batch_size (i.e. the 0th dimension of each argument)
26
+ // functions will be scheduled at once.
27
+ //
28
+ // The "max_intra_op_parallelism" attr, which defaults to 1, can be used to
29
+ // limit the intra op parallelism. To limit inter-op parallelism, a user
30
+ // can set a private threadpool on the dataset using `tf.data.Options`'s
31
+ // `ThreadingOptions`.
32
+ //
33
+ // Note that this op is not exposed to users directly, but is invoked in
34
+ // tf.data rewrites.
35
+ class MapDefunOp : public AsyncOpKernel {
36
+ public:
37
+ static constexpr const char* const kArguments = "arguments";
38
+ static constexpr const char* const kCapturedInputs = "captured_inputs";
39
+ static constexpr const char* const kTarguments = "Targuments";
40
+ static constexpr const char* const kTcaptured = "Tcaptured";
41
+ static constexpr const char* const kOutputTypes = "output_types";
42
+ static constexpr const char* const kOutputShapes = "output_shapes";
43
+ static constexpr const char* const kFunc = "f";
44
+ static constexpr const char* const kMaxIntraOpParallelism =
45
+ "max_intra_op_parallelism";
46
+
47
+ explicit MapDefunOp(OpKernelConstruction* ctx);
48
+
49
+ ~MapDefunOp() override = default;
50
+
51
+ void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override;
52
+
53
+ private:
54
+ struct ComputeOptions;
55
+ class MapFunctionCallFrame;
56
+
57
+ void SetRunOptions(OpKernelContext* ctx,
58
+ FunctionLibraryRuntime::Options* opts,
59
+ ComputeOptions* compute_opts, bool always_collect_stats);
60
+
61
+ // Get inputs to Compute and check that they are valid.
62
+ Status SetupArgs(OpKernelContext* ctx, ComputeOptions** compute_opts);
63
+
64
+ Status SetupOutputs(OpKernelContext* ctx, ComputeOptions* opts);
65
+
66
+ FunctionLibraryRuntime::Handle func_handle_;
67
+ std::vector<PartialTensorShape> output_shapes_;
68
+ // If this value is positive, limit the max intra op parallelism when the
69
+ // function is run on slices of the input.
70
+ int max_intra_op_parallelism_;
71
+ };
72
+
73
+ } // namespace data
74
+ } // namespace tensorflow
75
+
76
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_MAP_DEFUN_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/model_dataset_op.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_MODEL_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_MODEL_DATASET_OP_H_
17
+
18
+ #include "tensorflow/core/platform/platform.h"
19
+
20
+ // On mobile we do not provide model dataset op because not all of its
21
+ // dependencies are available there. The op is replaced with a no-op.
22
+ #if !defined(IS_MOBILE_PLATFORM)
23
+ #include "tensorflow/core/framework/dataset.h"
24
+ #include "tensorflow/core/framework/model.h"
25
+
26
+ namespace tensorflow {
27
+ namespace data {
28
+
29
+ class ModelDatasetOp : public UnaryDatasetOpKernel {
30
+ public:
31
+ static constexpr const char* const kDatasetType = "ModelDataset";
32
+ static constexpr const char* const kDatasetOp = "ModelDatasetOp";
33
+ static constexpr const char* const kAlgorithm = "algorithm";
34
+ static constexpr const char* const kCpuBudget = "cpu_budget";
35
+ static constexpr const char* const kRamBudget = "ram_budget";
36
+
37
+ // Executes the logic of the ModelDatasetOp directly (as opposed to through
38
+ // executing the ModelDatasetOp op kernel).
39
+ static void MakeDatasetFromOptions(OpKernelContext* ctx, DatasetBase* input,
40
+ model::AutotuneAlgorithm algorithm,
41
+ int64_t cpu_budget, int64_t ram_budget,
42
+ DatasetBase** output);
43
+
44
+ explicit ModelDatasetOp(OpKernelConstruction* ctx);
45
+
46
+ protected:
47
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
48
+ DatasetBase** output) override;
49
+
50
+ private:
51
+ class Dataset;
52
+
53
+ model::AutotuneAlgorithm algorithm_;
54
+ int64_t cpu_budget_;
55
+ int64_t ram_budget_;
56
+ };
57
+
58
+ } // namespace data
59
+ } // namespace tensorflow
60
+ #else // !IS_MOBILE_PLATFORM
61
+ #include "tensorflow/core/framework/dataset.h"
62
+
63
+ namespace tensorflow {
64
+ namespace data {
65
+
66
+ class ModelDatasetOp : public UnaryDatasetOpKernel {
67
+ public:
68
+ // Creates and returns a ModelDatasetOp::Dataset in output, given the
69
+ // input, algorithm, cpu_budget and ram_budget parameters. This method is used
70
+ // to create the dataset without explicitly using the ModelDatasetOp.
71
+ static void MakeDatasetFromOptions(OpKernelContext* ctx, DatasetBase* input,
72
+ model::AutotuneAlgorithm algorithm,
73
+ bool cpu_budget, bool ram_budget,
74
+ DatasetBase** output);
75
+
76
+ explicit ModelDatasetOp(OpKernelConstruction* ctx);
77
+
78
+ protected:
79
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
80
+ DatasetBase** output) override;
81
+ };
82
+
83
+ } // namespace data
84
+ } // namespace tensorflow
85
+ #endif // !IS_MOBILE_PLATFORM
86
+
87
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_MODEL_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/optimize_dataset_op.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_OPTIMIZE_DATASET_OP_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_OPTIMIZE_DATASET_OP_H_
17
+
18
+ #include "absl/container/flat_hash_set.h"
19
+ #include "tensorflow/core/framework/dataset.h"
20
+ #include "tensorflow/core/platform/platform.h"
21
+
22
+ // On mobile we do not provide optimize dataset op because not all of its
23
+ // dependencies are available there. The op is replaced with a no-op.
24
+ #if !defined(IS_MOBILE_PLATFORM)
25
+ namespace tensorflow {
26
+ namespace data {
27
+
28
+ class OptimizeDatasetOp : public UnaryDatasetOpKernel {
29
+ public:
30
+ static constexpr const char* const kDatasetType = "Optimize";
31
+ static constexpr const char* const kInputDataset = "input_dataset";
32
+ static constexpr const char* const kOptimizations = "optimizations";
33
+ static constexpr const char* const kOptimizationsEnabled =
34
+ "optimizations_enabled";
35
+ static constexpr const char* const kOptimizationsDisabled =
36
+ "optimizations_disabled";
37
+ static constexpr const char* const kOptimizationsDefault =
38
+ "optimizations_default";
39
+ static constexpr const char* const kOutputTypes = "output_types";
40
+ static constexpr const char* const kOutputShapes = "output_shapes";
41
+ static constexpr const char* const kOptimizationConfigs =
42
+ "optimization_configs";
43
+ static constexpr const char* const kOptimizeDatasetV1 = "OptimizeDataset";
44
+ static constexpr const char* const kOptimizeDatasetV2 = "OptimizeDatasetV2";
45
+
46
+ // Creates and returns a OptimizeDatasetOp::Dataset in output, given the
47
+ // default optimizations and those that are enabled, disabled. This method is
48
+ // used to create the dataset without explicitly using the OptimizeDatasetOp.
49
+ static void MakeDatasetFromOptions(
50
+ OpKernelContext* ctx, DatasetBase* input,
51
+ const absl::flat_hash_set<tstring>& optimizations_enabled,
52
+ const absl::flat_hash_set<tstring>& optimizations_disabled,
53
+ const absl::flat_hash_set<tstring>& optimizations_default,
54
+ const absl::flat_hash_set<tstring>& optimization_configs,
55
+ DatasetBase** output);
56
+
57
+ explicit OptimizeDatasetOp(OpKernelConstruction* ctx);
58
+
59
+ protected:
60
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
61
+ DatasetBase** output) override;
62
+
63
+ private:
64
+ absl::flat_hash_set<tstring> optimization_configs_;
65
+ int op_version_ = 0;
66
+ };
67
+
68
+ } // namespace data
69
+ } // namespace tensorflow
70
+ #else // !IS_MOBILE_PLATFORM
71
+ namespace tensorflow {
72
+ namespace data {
73
+
74
+ class OptimizeDatasetOp : public UnaryDatasetOpKernel {
75
+ public:
76
+ // Executes the logic of the OptimizeDatasetOp directly (as opposed to through
77
+ // executing the OptimizeDatasetOp op kernel).
78
+ static void MakeDatasetFromOptions(
79
+ OpKernelContext* ctx, DatasetBase* input,
80
+ const absl::flat_hash_set<tstring>& optimizations_enabled,
81
+ const absl::flat_hash_set<tstring>& optimizations_disabled,
82
+ const absl::flat_hash_set<tstring>& optimizations_default,
83
+ const absl::flat_hash_set<tstring>& optimization_configs,
84
+ DatasetBase** output);
85
+
86
+ explicit OptimizeDatasetOp(OpKernelConstruction* ctx);
87
+
88
+ protected:
89
+ void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
90
+ DatasetBase** output) override;
91
+ };
92
+
93
+ } // namespace data
94
+ } // namespace tensorflow
95
+ #endif // !IS_MOBILE_PLATFORM
96
+
97
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_OPTIMIZE_DATASET_OP_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/kernels/data/optional_ops.h ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_CORE_KERNELS_DATA_OPTIONAL_OPS_H_
16
+ #define TENSORFLOW_CORE_KERNELS_DATA_OPTIONAL_OPS_H_
17
+
18
+ #include <vector>
19
+
20
+ #include "tensorflow/core/framework/tensor.h"
21
+ #include "tensorflow/core/framework/variant_tensor_data.h"
22
+ #include "tensorflow/core/kernels/data/optional_ops_util.h"
23
+ #include "tensorflow/core/util/tensor_ops_util.h"
24
+
25
+ namespace tensorflow {
26
+ namespace data {
27
+
28
+ // Stores a DT_VARIANT value representing an Optional with the given value
29
+ // in the `output_index`^th output of the given kernel execution context.
30
+ Status WriteOptionalWithValueToOutput(OpKernelContext* ctx, int output_index,
31
+ std::vector<Tensor> value);
32
+
33
+ // Stores a DT_VARIANT value representing an Optional with no value
34
+ // in the `output_index`^th output of the given kernel execution context.
35
+ Status WriteOptionalNoneToOutput(OpKernelContext* ctx, int output_index);
36
+
37
+ template <typename Device>
38
+ Status OptionalZerosLike(OpKernelContext* ctx, const OptionalVariant& x,
39
+ OptionalVariant* y) {
40
+ return OptionalZerosLike(ctx, x, y, ZerosLikeTensor<Device>);
41
+ }
42
+
43
+ template <typename Device>
44
+ Status OptionalBinaryAdd(OpKernelContext* ctx, const OptionalVariant& a,
45
+ const OptionalVariant& b, OptionalVariant* out) {
46
+ return OptionalBinaryAdd(ctx, a, b, out, BinaryAddTensors<Device>);
47
+ }
48
+
49
+ class OptionalNoneOp : public OpKernel {
50
+ public:
51
+ explicit OptionalNoneOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
52
+
53
+ void Compute(OpKernelContext* ctx) override;
54
+ };
55
+
56
+ class OptionalFromValueOp : public OpKernel {
57
+ public:
58
+ explicit OptionalFromValueOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
59
+
60
+ void Compute(OpKernelContext* ctx) override;
61
+ };
62
+
63
+ class OptionalHasValueOp : public OpKernel {
64
+ public:
65
+ explicit OptionalHasValueOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
66
+
67
+ void Compute(OpKernelContext* ctx) override;
68
+ };
69
+
70
+ class OptionalGetValueOp : public OpKernel {
71
+ public:
72
+ explicit OptionalGetValueOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
73
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_));
74
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
75
+ OP_REQUIRES(
76
+ ctx, output_shapes_.size() == output_types_.size(),
77
+ errors::InvalidArgument(
78
+ "output_types and output_shapes must be same length, got:\n",
79
+ "output_types: ", output_types_.size(), "\n",
80
+ "output_shapes: ", output_shapes_.size()));
81
+ }
82
+
83
+ void Compute(OpKernelContext* ctx) override;
84
+
85
+ private:
86
+ DataTypeVector output_types_;
87
+ std::vector<PartialTensorShape> output_shapes_;
88
+ };
89
+
90
+ } // namespace data
91
+ } // namespace tensorflow
92
+
93
+ #endif // TENSORFLOW_CORE_KERNELS_DATA_OPTIONAL_OPS_H_