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 // Returns the number of tasks in the batch.
96 int num_tasks() const;
97
98 // Returns true iff the batch contains 0 tasks.
99 bool empty() const;
100
101 // Returns a reference to the ith task (in terms of insertion order).
102 const TaskType& task(int i) const;
103
104 // Returns a pointer to the ith task (in terms of insertion order).
105 TaskType* mutable_task(int i);
106
107 // Returns the sum of the task sizes.
108 size_t size() const;
109
110 // Returns true iff the batch is currently closed.
111 bool IsClosed() const;
112
113 // Blocks until the batch is closed.
114 void WaitUntilClosed() const;
115
116 // Marks the batch as closed. Dies if called more than once.
117 void Close();
118
119 // Returns the TraceMe context id of this batch.
120 uint64 traceme_context_id() const;
121
122 private:
123 mutable mutex mu_;
124
125 // The tasks in the batch.
126 std::vector<std::unique_ptr<TaskType>> tasks_ TF_GUARDED_BY(mu_);
127
128 // The sum of the sizes of the tasks in 'tasks_'.
129 size_t size_ TF_GUARDED_BY(mu_) = 0;
130
TF_GUARDED_BY(mu_)131 std::atomic<bool> empty_ TF_GUARDED_BY(mu_){true};
132
133 // Whether the batch has been closed.
134 Notification closed_;
135
136 // The TracMe context id.
137 const uint64 traceme_context_id_;
138
139 TF_DISALLOW_COPY_AND_ASSIGN(Batch);
140 };
141
142 // An abstract batch scheduler class. Collects individual tasks into batches,
143 // and processes each batch on a pool of "batch threads" that it manages. The
144 // actual logic for processing a batch is accomplished via a callback.
145 //
146 // Type parameter TaskType must be a subclass of BatchTask.
147 template <typename TaskType>
148 class BatchScheduler {
149 public:
150 virtual ~BatchScheduler() = default;
151
152 // Submits a task to be processed as part of a batch.
153 //
154 // Ownership of '*task' is transferred to the callee iff the method returns
155 // Status::OK. In that case, '*task' is left as nullptr. Otherwise, '*task' is
156 // left as-is.
157 //
158 // If no batch processing capacity is available to process this task at the
159 // present time, and any task queue maintained by the implementing subclass is
160 // full, this method returns an UNAVAILABLE error code. The client may retry
161 // later.
162 //
163 // Other problems, such as the task size being larger than the maximum batch
164 // size, yield other, permanent error types.
165 //
166 // In all cases, this method returns "quickly" without blocking for any
167 // substantial amount of time. If the method returns Status::OK, the task is
168 // processed asynchronously, and any errors that occur during the processing
169 // of the batch that includes the task can be reported to 'task'.
170 virtual Status Schedule(std::unique_ptr<TaskType>* task) = 0;
171
172 // Returns the number of tasks that have been scheduled (i.e. accepted by
173 // Schedule()), but have yet to be handed to a thread for execution as part of
174 // a batch. Note that this returns the number of tasks, not the aggregate task
175 // size (so if there is one task of size 3 and one task of size 5, this method
176 // returns 2 rather than 8).
177 virtual size_t NumEnqueuedTasks() const = 0;
178
179 // Returns a guaranteed number of size 1 tasks that can be Schedule()d without
180 // getting an UNAVAILABLE error. In a typical implementation, returns the
181 // available space on a queue.
182 //
183 // There are two important caveats:
184 // 1. The guarantee does not extend to varying-size tasks due to possible
185 // internal fragmentation of batches.
186 // 2. The guarantee only holds in a single-thread environment or critical
187 // section, i.e. if an intervening thread cannot call Schedule().
188 //
189 // This method is useful for monitoring, or for guaranteeing a future slot in
190 // the schedule (but being mindful about the caveats listed above).
191 virtual size_t SchedulingCapacity() const = 0;
192
193 // Returns the maximum allowed size of tasks submitted to the scheduler. (This
194 // is typically equal to a configured maximum batch size.)
195 virtual size_t max_task_size() const = 0;
196 };
197
198 //////////
199 // Implementation details follow. API users need not read.
200
201 template <typename TaskType>
Batch()202 Batch<TaskType>::Batch() : Batch(0) {}
203
204 template <typename TaskType>
Batch(uint64 traceme_context_id)205 Batch<TaskType>::Batch(uint64 traceme_context_id)
206 : traceme_context_id_(traceme_context_id) {}
207
208 template <typename TaskType>
~Batch()209 Batch<TaskType>::~Batch() {
210 WaitUntilClosed();
211 }
212
213 template <typename TaskType>
AddTask(std::unique_ptr<TaskType> task)214 void Batch<TaskType>::AddTask(std::unique_ptr<TaskType> task) {
215 DCHECK(!IsClosed());
216 {
217 mutex_lock l(mu_);
218 size_ += task->size();
219 tasks_.push_back(std::move(task));
220 empty_.store(false);
221 }
222 }
223
224 template <typename TaskType>
RemoveTask()225 std::unique_ptr<TaskType> Batch<TaskType>::RemoveTask() {
226 {
227 mutex_lock l(mu_);
228 if (tasks_.empty()) {
229 return nullptr;
230 }
231 std::unique_ptr<TaskType> task = std::move(tasks_.back());
232 size_ -= task->size();
233 tasks_.pop_back();
234 if (tasks_.empty()) {
235 empty_.store(true);
236 }
237 return task;
238 }
239 }
240
241 template <typename TaskType>
num_tasks()242 int Batch<TaskType>::num_tasks() const {
243 {
244 mutex_lock l(mu_);
245 return tasks_.size();
246 }
247 }
248
249 template <typename TaskType>
empty()250 bool Batch<TaskType>::empty() const TF_NO_THREAD_SAFETY_ANALYSIS {
251 // tracer is added to zoom in about this method.
252 // TODO(b/160249203): Remove tracer after evaluating a change to reduce
253 // lock contention and cpu usage (which is observed in profiler and
254 // very data-driven).
255 tensorflow::profiler::TraceMe tracer("BatchTask::empty");
256 return empty_.load();
257 }
258
259 template <typename TaskType>
task(int i)260 const TaskType& Batch<TaskType>::task(int i) const {
261 DCHECK_GE(i, 0);
262 {
263 mutex_lock l(mu_);
264 DCHECK_LT(i, tasks_.size());
265 return *tasks_[i].get();
266 }
267 }
268
269 template <typename TaskType>
mutable_task(int i)270 TaskType* Batch<TaskType>::mutable_task(int i) {
271 DCHECK_GE(i, 0);
272 {
273 mutex_lock l(mu_);
274 DCHECK_LT(i, tasks_.size());
275 return tasks_[i].get();
276 }
277 }
278
279 template <typename TaskType>
size()280 size_t Batch<TaskType>::size() const {
281 {
282 mutex_lock l(mu_);
283 return size_;
284 }
285 }
286
287 template <typename TaskType>
IsClosed()288 bool Batch<TaskType>::IsClosed() const {
289 return const_cast<Notification*>(&closed_)->HasBeenNotified();
290 }
291
292 template <typename TaskType>
WaitUntilClosed()293 void Batch<TaskType>::WaitUntilClosed() const {
294 const_cast<Notification*>(&closed_)->WaitForNotification();
295 }
296
297 template <typename TaskType>
Close()298 void Batch<TaskType>::Close() {
299 closed_.Notify();
300 }
301
302 template <typename TaskType>
traceme_context_id()303 uint64 Batch<TaskType>::traceme_context_id() const {
304 return traceme_context_id_;
305 }
306
307 } // namespace serving
308 } // namespace tensorflow
309
310 #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_BATCH_SCHEDULER_H_
311