blob: bd4b300d7d0a56f116165d752851a03f3555d8e0 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001namespace arm_compute
2{
Georgios Pinitas74180bb2017-09-26 19:28:02 +01003/**
Anthony Barbier6ff3b192017-09-04 18:44:23 +01004@page architecture Library architecture
5
6@tableofcontents
7
8@section S4_1 Core vs Runtime libraries
9
10The Core library is a low level collection of algorithms implementations, it is designed to be embedded in existing projects and applications:
11
12- It doesn't allocate any memory (All the memory allocations/mappings have to be handled by the caller).
13- It doesn't perform any kind of multi-threading (but provide information to the caller about how the workload can be split).
14
15The Runtime library is a very basic wrapper around the Core library which can be used for quick prototyping, it is basic in the sense that:
16
17- It allocates images and tensors by using standard malloc().
18- It multi-threads NEON code in a very basic way using a very simple pool of threads.
19- For OpenCL it uses the default CLScheduler command queue for all mapping operations and kernels.
20
21For maximum performance, it is expected that the users would re-implement an equivalent to the runtime library which suits better their needs (With a more clever multi-threading strategy, load-balancing between NEON and OpenCL, etc.)
22
23@section S4_2_windows_kernels_mt_functions Windows, kernels, multi-threading and functions
24
25@subsection S4_2_1_windows Windows
26
27A @ref Window represents a workload to execute, it can handle up to @ref Coordinates::num_max_dimensions dimensions.
28Each dimension is defined by a start, end and step.
29
30It can split into subwindows as long as *all* the following rules remain true for all the dimensions:
31
32- max[n].start() <= sub[n].start() < max[n].end()
33- sub[n].start() < sub[n].end() <= max[n].end()
34- max[n].step() == sub[n].step()
35- (sub[n].start() - max[n].start()) % max[n].step() == 0
36- (sub[n].end() - sub[n].start()) % max[n].step() == 0
37
38@subsection S4_2_2 Kernels
39
40Each implementation of the @ref IKernel interface (base class of all the kernels in the core library) works in the same way:
41
42OpenCL kernels:
43
44@code{.cpp}
45// Initialize the CLScheduler with the default context and default command queue
46// Implicitly initializes the CLKernelLibrary to use ./cl_kernels as location for OpenCL kernels files and sets a default device for which OpenCL programs are built.
47CLScheduler::get().default_init();
48
49cl::CommandQueue q = CLScheduler::get().queue();
50//Create a kernel object:
51MyKernel kernel;
52// Initialize the kernel with the input/output and options you want to use:
53kernel.configure( input, output, option0, option1);
54// Retrieve the execution window of the kernel:
55const Window& max_window = kernel.window();
56// Run the whole kernel in the current thread:
57kernel.run( q, max_window ); // Enqueue the kernel to process the full window on the default queue
58
59// Wait for the processing to complete:
60q.finish();
61@endcode
62
63NEON / CPP kernels:
64
65@code{.cpp}
66//Create a kernel object:
67MyKernel kernel;
68// Initialize the kernel with the input/output and options you want to use:
69kernel.configure( input, output, option0, option1);
70// Retrieve the execution window of the kernel:
71const Window& max_window = kernel.window();
72// Run the whole kernel in the current thread:
73kernel.run( max_window ); // Run the kernel on the full window
74@endcode
75
76@subsection S4_2_3 Multi-threading
77
78The previous section shows how to run a NEON / CPP kernel in the current thread, however if your system has several CPU cores, you will probably want the kernel to use several cores. Here is how this can be done:
79
Anthony Barbier52ecb062018-05-25 13:32:10 +010080@code{.cpp}
81 ThreadInfo info;
82 info.cpu_info = &_cpu_info;
Anthony Barbier6ff3b192017-09-04 18:44:23 +010083
Anthony Barbier52ecb062018-05-25 13:32:10 +010084 const Window &max_window = kernel->window();
85 const unsigned int num_iterations = max_window.num_iterations(split_dimension);
86 info.num_threads = std::min(num_iterations, _num_threads);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010087
Anthony Barbier52ecb062018-05-25 13:32:10 +010088 if(num_iterations == 0)
89 {
90 return;
91 }
92
93 if(!kernel->is_parallelisable() || info.num_threads == 1)
94 {
95 kernel->run(max_window, info);
96 }
97 else
98 {
99 int t = 0;
100 auto thread_it = _threads.begin();
101
102 for(; t < info.num_threads - 1; ++t, ++thread_it)
103 {
104 Window win = max_window.split_window(split_dimension, t, info.num_threads);
105 info.thread_id = t;
106 thread_it->start(kernel, win, info);
107 }
108
109 // Run last part on main thread
110 Window win = max_window.split_window(split_dimension, t, info.num_threads);
111 info.thread_id = t;
112 kernel->run(win, info);
113
114 try
115 {
116 for(auto &thread : _threads)
117 {
118 thread.wait();
119 }
120 }
121 catch(const std::system_error &e)
122 {
123 std::cerr << "Caught system_error with code " << e.code() << " meaning " << e.what() << '\n';
124 }
125 }
126@endcode
127
128This is a very basic implementation which was originally used in the NEON runtime library by all the NEON functions.
129
130@sa CPPScheduler
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100131
Moritz Pflanzerc186b572017-09-07 09:48:04 +0100132@note Some kernels like for example @ref NEHistogramKernel need some local temporary buffer to perform their calculations. In order to avoid memory corruption between threads, the local buffer must be of size: ```memory_needed_per_thread * num_threads``` and a unique thread_id between 0 and num_threads must be assigned to the @ref ThreadInfo object passed to the ```run``` function.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100133
134@subsection S4_2_4 Functions
135
136Functions will automatically allocate the temporary buffers mentioned above, and will automatically multi-thread kernels' executions using the very basic scheduler described in the previous section.
137
138Simple functions only call a single kernel (e.g @ref NEConvolution3x3), while more complex ones consist of several kernels pipelined together (e.g @ref NEGaussianPyramid, @ref NEHarrisCorners). Check their documentation to find out which kernels are used by each function.
139
140@code{.cpp}
141//Create a function object:
142MyFunction function;
143// Initialize the function with the input/output and options you want to use:
144function.configure( input, output, option0, option1);
145// Execute the function:
146function.run();
147@endcode
148
149@warning The Compute Library requires Mali OpenCL DDK r8p0 or higher (OpenCL kernels are compiled using the -cl-arm-non-uniform-work-group-size flag)
150
151@note All OpenCL functions and objects in the runtime library use the command queue associated with CLScheduler for all operations, a real implementation would be expected to use different queues for mapping operations and kernels in order to reach a better GPU utilization.
152
153@subsection S4_4_1_cl_scheduler OpenCL Scheduler and kernel library
154
155The Compute Library runtime uses a single command queue and context for all the operations.
156
157The user can get / set this context and command queue through CLScheduler's interface.
158
159The user can get / set the target GPU device through the CLScheduler's interface.
160
161@attention Make sure the application is using the same context as the library as in OpenCL it is forbidden to share objects across contexts. This is done by calling @ref CLScheduler::init() or @ref CLScheduler::default_init() at the beginning of your application.
162
163@attention Make sure the scheduler's target is not changed after function classes are created.
164
165All OpenCL kernels used by the library are built and stored in @ref CLKernelLibrary.
166If the library is compiled with embed_kernels=0 the application can set the path to the OpenCL kernels by calling @ref CLKernelLibrary::init(), by default the path is set to "./cl_kernels"
167
168@subsection S4_4_2_events_sync OpenCL events and synchronization
169
170In order to block until all the jobs in the CLScheduler's command queue are done executing the user can call @ref CLScheduler::sync() or create a sync event using @ref CLScheduler::enqueue_sync_event()
171
172For example:
173@snippet cl_events.cpp OpenCL events
174
175@subsection S4_4_2_cl_neon OpenCL / NEON interoperability
176
177You can mix OpenCL and NEON kernels and functions. However it is the user's responsibility to handle the mapping/unmapping of OpenCL objects, for example:
178
179@snippet neoncl_scale_median_gaussian.cpp NEON / OpenCL Interop
180
181@sa main_neoncl_scale_median_gaussian
182
183@section S4_5_algorithms Algorithms
184
Anthony Barbier14c86a92017-12-14 16:27:41 +0000185All computer vision algorithms in this library have been implemented following the [OpenVX 1.1 specifications](https://www.khronos.org/registry/vx/specs/1.1/html/). Please refer to the Khronos documentation for more information.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100186
187@section S4_6_images_tensors Images, padding, border modes and tensors
188
189Most kernels and functions in the library process images, however, in order to be future proof most of the kernels actually accept tensors. See below for more information about how they are related.
190
191@attention Each memory object can be written by only one kernel, however it can be read by several kernels. Writing to the same object from several kernels will result in undefined behavior. The kernel writing to an object must be configured before the kernel(s) reading from it.
192
193@subsection S4_6_1_padding_and_border Padding and border modes
194
195Several algorithms require a neighborhood around the current pixel to compute it's value. This means the algorithm will not be able to process the borders of the image unless you give it more information about how those border pixels should be processed. The @ref BorderMode enum is used for this purpose.
196
197You have 3 types of @ref BorderMode :
198
199- @ref BorderMode::UNDEFINED : Neighbor pixels outside of the image are treated as undefined. As a result all the pixels which are on the border will have a value which is undefined.
200- @ref BorderMode::REPLICATE : Neighbor pixels outside of the image are treated as having the same value as the closest valid pixel.
201- @ref BorderMode::CONSTANT : Neighbor pixels outside of the image are treated as having the same constant value. (The user can choose what this value should be).
202
203Moreover both OpenCL and NEON use vector loads and stores instructions to access the data in buffers, so in order to avoid having special cases to handle for the borders all the images and tensors used in this library must be padded.
204
205@subsubsection padding Padding
206
207There are different ways padding can be calculated:
208
209- Accurate padding:
210
211@snippet neon_convolution.cpp Accurate padding
212
213@note It's important to call allocate @b after the function is configured: if the image / tensor is already allocated then the function will shrink its execution window instead of increasing the padding. (See below for more details).
214
215- Manual padding / no padding / auto padding: You can allocate your images / tensors up front (before configuring your functions). In that case the function will use whatever padding is available and will shrink its execution window if there isn't enough padding available (which translates into a smaller valid region for the output). See also @ref valid_region).
216If you don't want to manually set the padding but still want to allocate your objects upfront then you can use auto_padding. It guarantees that the allocation will have enough padding to run any of the provided functions.
217
218@code{.cpp}
219Image src, dst;
220
221// Use auto padding for the input:
222src.info()->init_auto_padding(TensorShape(640u,480u), Format::U8);
223
224// Use manual padding for the destination image
225dst.info()->init(src.info()->tensor_shape(), Format::U8, strides_in_bytes, offset_first_element_in_bytes, total_size_in_bytes);
226
227// Allocate all the images
228src.allocator()->allocate();
229dst.allocator()->allocate();
230// Fill the input image with the content of the PPM image if a filename was provided:
231fill_image(src);
232
233NEGaussian3x3 gauss;
234
235// Apply a Gaussian 3x3 filter to the source image (Note: if the padding provided is not enough then the execution window and valid region of the output will be shrunk)
236gauss.configure(&src, &dst, BorderMode::UNDEFINED);
237
238//Execute the functions:
239gauss.run();
240@endcode
241
242@warning Some kernels need up to 3 neighbor values to calculate the value of a given pixel. Therefore, to be safe, we use a 4-pixel padding all around the image. In addition, some kernels read and write up to 32 pixels at the same time. To cover that case as well we add an extra 32 pixels of padding at the end of each row. As a result auto padded buffers waste a lot of memory and are less cache friendly. It is therefore recommended to use accurate padding or manual padding wherever possible.
243
244@subsubsection valid_region Valid regions
245
246Some kernels (like edge detectors for example) need to read values of neighboring pixels to calculate the value of a given pixel, it is therefore not possible to calculate the values of the pixels on the edges.
247
248Another case is: if a kernel processes 8 pixels per iteration and the image's dimensions are not a multiple of 8 and not enough padding is available then the kernel will not be able to process the pixels near the right edge. As a result these pixels will be left undefined.
249
250In order to know which pixels have been calculated, each kernel sets a valid region for each output image or tensor. See also @ref TensorInfo::valid_region(), @ref ValidRegion
251
252@subsection S4_6_2_tensors Tensors
253
254Tensors are multi-dimensional arrays with a maximum of @ref Coordinates::num_max_dimensions dimensions.
255
256Depending on the number of dimensions tensors can be interpreted as various objects. A scalar can be represented as a zero-dimensional tensor and a vector of numbers can be represented as an one-dimensional tensor. Further, an image is actually just a 2D tensor, a 3D tensor can be seen as an array of images and a 4D tensor as a 2D array of images, etc.
257
258@note Most algorithms process images (i.e a 2D slice of the tensor), therefore only padding along the X and Y axes is required (2D slices can be stored contiguously in memory).
259
260@subsection S4_6_3_description_conventions Images and Tensors description conventions
261
262Image objects are defined by a @ref Format and dimensions expressed as [width, height, batch]
263
264Tensors are defined by a @ref DataType plus a number of channels (Always expected to be 1 for now) and their dimensions are expressed as [width, height, feature_maps, batch].
265
266In other words, the lower three dimensions of a tensor specify a single input in [width, height, feature_maps], while any other specified dimension represents a batch in the appropriate dimension space.
267For example, a tensor with dimensions [128, 128, 64, 16] represents a 1D batch space with 16 batches of 128 elements in width and height and 64 feature maps each.
268Each kernel specifies the expected layout of each of its tensors in its documentation.
269
270@note Unless specified otherwise in the kernel's or function's documentation all tensors and images parameters passed must have identical dimensions.
271
272@note Unless specified otherwise in the kernel's or function's documentation the number of channels for tensors is expected to be 1 (For images, the number of channels is inferred from the @ref Format).
273
274@attention Regardless of the @ref DataType used by a tensor the @ref ITensor::buffer() method will always return a uint8_t pointer, and all the metadata in @ref TensorInfo will be expressed in bytes. It is the user's responsibility to cast the pointer to the correct type.
275
276For example, to read the element located at the coordinates (x,y) of a float tensor:
277
278@code{.cpp}
279float value = *reinterpret_cast<float*>(input.buffer() + input.info()->offset_element_in_bytes(Coordinates(x,y)));
280@endcode
281
282@subsection S4_6_4_working_with_objects Working with Images and Tensors using iterators
283
284The library provides some iterators to access objects' data.
285Iterators are created by associating a data object (An image or a tensor for example) with an iteration window.
286
287Iteration windows are defined by an array of dimensions, each of which consists of a start, end and step.
288
289The @ref execute_window_loop function takes an execution window, a lambda function and one or more iterators.
290It will iterate through every element of the execution window and for each element it will update the iterators accordingly and call the lambda function.
291
292Here are a couple of examples of how to use the iterators to fill / read tensors:
293
294@snippet examples/neon_copy_objects.cpp Copy objects example
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100295
Georgios Pinitas98f085b2018-07-09 20:21:08 +0100296@subsection S4_6_5_sub_tensors Sub-tensors
297
298Sub-tensors are aliases to existing Tensors, as a result creating a sub-tensor does not result in any underlying memory allocation.
299
300Sub-tensors can be used to access a sub-set of the parent tensor, something that can be useful in case different operations need to be performed on different parts of a tensor.
301
302Moreover, sub-tensors can be used to perform zero copy tensor concatenation.
303
304The API for creating a sub-tensor is the following:
305@code{.cpp}
306SubTensor(ITensor *parent, const TensorShape &tensor_shape, const Coordinates &coords)
307@endcode
308
309Where \a parent is the parent tensor which we want to create an alias for, \a tensor_shape is the shape of the sub-tensor and \a coords are the starting indexing coordinates of the sub-tensor within the parent tensor.
310
311@note Two sub-tensor concrete classes for different targets are currently supported : @ref CLSubTensor and @ref SubTensor
312
313@warning Limitation of the sub-tensor is that it cannot be extracted spatially, meaning sub-tensors should have the same width and height as the parent tensor. The main reasons for this is the fact that individual kernels might need to operate with a step size that is not a multiple of the sub-tensor spatial dimension. This could lead to elements being overwritten by different kernels operating on different sub-tensors of the same underlying tensor.
314
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100315@section S4_7_memory_manager MemoryManager
316
317@ref IMemoryManager is a memory managing interface that can be used to reduce the memory requirements of a given pipeline by recycling temporary buffers.
318
319@subsection S4_7_1_memory_manager_components MemoryGroup, MemoryPool and MemoryManager Components
320
321@subsubsection S4_7_1_1_memory_group MemoryGroup
322
323@ref IMemoryGroup defines the memory managing granularity.
324
325MemoryGroup binds a number of objects to a bucket of memory requirements that need to be fulfilled in order for an operation or list of operations to be executed.
326
327Requesting backing memory for a specific group can be done using @ref IMemoryGroup::acquire and releasing the memory back using @ref IMemoryGroup::release.
328
329@note Two types of memory groups are currently implemented:
330- @ref MemoryGroup that manages @ref Tensor objects
331- @ref CLMemoryGroup that manages @ref CLTensor objects.
332
333@subsubsection S4_7_1_2_memory_pool MemoryPool
334
335@ref IMemoryPool defines a pool of memory that can be used to provide backing memory to a memory group.
336
337@note @ref BlobMemoryPool is currently implemented which models the memory requirements as a vector of distinct memory blobs.
338
339@subsubsection S4_7_1_2_memory_manager_components MemoryManager Components
340
341@ref IMemoryManager consists of two components:
342- @ref ILifetimeManager that keeps track of the lifetime of the registered objects of the memory groups and given an @ref IAllocator creates an appropriate memory pool that fulfils the memory requirements of all the registered memory groups.
343- @ref IPoolManager that safely manages the registered memory pools.
344
345@note @ref IMemoryManager::finalize should be called once the configuration of all the memory groups, kernels and functions is done, so that the memory manager can allocate the appropriate backing memory.
346
347@note @ref BlobLifetimeManager is currently implemented which models the memory requirements as a vector of distinct memory blobs.
348
349@subsection S4_7_2_working_with_memory_manager Working with the Memory Manager
350Using a memory manager to reduce the memory requirements of a pipeline can be summed in the following steps:
351
352Initially a memory manager must be set-up:
353@code{.cpp}
354Allocator allocator{}; // Create an allocator to use for the backing memory allocation
355auto lifetime_mgr = std::make_shared<BlobLifetimeManager>(); // Create Lifetime Manager
356auto pool_mgr = std::make_shared<PoolManager>(); // Create Pool Manager
357auto mm = std::make_shared<MemoryManagerOnDemand>(lifetime_mgr, pool_mgr); // Create Memory Manager
358@endcode
359
360Once done, memory groups can be registered to use the memory manager:
361@code{.cpp}
362MemoryGroup memory_group(mm); // Create a memory group and set the memory manager to use
363@endcode
364
365@note If a memory manager is not specified then all allocation will be immediate instead of deferred through the memory manager.
366
367Next step is to set objects to be managed by the memory group. It is important though to note that the lifetime of an object is tracked from the @ref MemoryGroup::manage() and the @ref TensorAllocator::allocate calls.
368@ref MemoryGroup::manage flags that the object will be needed starting now and when @ref TensorAllocator::allocate is called it signals the end of the object lifetime.
369@code{.cpp}
370Tensor tmp1, tmp2, tmp3; // Create example tensors
371memory_group.manage(&tmp1); // Start managing object tmp1 and start its lifetime
372memory_group.manage(&tmp2); // Start managing object tmp2 and start its lifetime
373
374operation1.configure(&tmp1, &tmp2); // Configure a function/kernel using tmp1 and tmp2
375
376tmp1.allocator()->allocate(); // Flag that the lifetime of object tmp1 has ended
377
378memory_group.manage(&tmp3); // Start managing object tmp3 and start its lifetime
379
380operation2.configure(&tmp2, &tmp3); // Configure a function/kernel using tmp2 and tmp3
381
382tmp2.allocator()->allocate(); // Flag that the lifetime of object tmp2 has ended
383tmp3.allocator()->allocate(); // Flag that the lifetime of object tmp3 has ended
384@endcode
385
386@warning The configuration step should be done sequentially by a single thread so that all the lifetimes are captured correclty.
387
388When configuration of all the operations is finished then the memory manager have to be finalized:
389@code{.cpp}
390mm->set_allocator(&allocator); // Set allocator to use
391mm->set_set_num_pools(2); // Set number of pools to create in case parallel operations can be run
392mm->finalize(); // Finalize memory manager (Object lifetime check, Memory pool creation etc)
393@endcode
394
395Finally, during execution of the pipeline the memory of the appropriate memory group should be requested before running:
396@code{.cpp}
397memory_group.acquire(); // Request memory for the group
398
399operation1.run(); // Run operation1
400operation2.run(); // Run operation2
401
402memory_group.release(); // Release memory so that it can be reused
403@endcode
404@note Execution of a pipeline can be done in a multi-threading environment as memory acquisition/release are thread safe.
405
406@subsection S4_7_3_memory_manager_function_support Function support
407
408Most of the library's function have been ported to use @ref IMemoryManager for their internal temporary buffers.
409
410If that is the case, a memory manager can be passed to them during construction to reuse memory among these functions.
411@code{.cpp}
412// Setup Memory Manager
413CLBufferAllocator allocator{}; // Create an allocator to use for the backing memory allocation
414auto lifetime_mgr = std::make_shared<BlobLifetimeManager>(); // Create Lifetime Manager
415auto pool_mgr = std::make_shared<PoolManager>(); // Create Pool Manager
416auto mm = std::make_shared<MemoryManagerOnDemand>(lifetime_mgr, pool_mgr); // Create Memory Manager
417
418// Create two convolution layers and use the memory manager to manager their internal temporary buffers
419CLConvolutionLayer conv1(mm), conv2(mm);
420
421// Configure layers
422conv1.configure(...);
423conv2.configure(...);
424
425// Finalize memory manager
426mm->set_allocator(&allocator); // Set allocator to use
427mm->set_set_num_pools(1); // Set number of pools to create in case parallel operations can be run
428mm->finalize(); // Finalize memory manager (Object lifetime check, Memory pool creation etc)
429
430// Run layers (Memory will be recycled for internal buffers for conv1 and conv2
431conv1.run();
432conv2.run();
433@endcode
Anthony Barbier3762e742018-03-02 11:49:33 +0000434
435@section S4_8_opencl_tuner OpenCL Tuner
436
437OpenCL kernels when dispatched to the GPU take two arguments:
438- The Global Workgroup Size (GWS): That's the number of times to run an OpenCL kernel to process all the elements we want to process.
439- The Local Workgroup Size (LWS): That's the number of elements we want to run in parallel on a GPU core at a given point in time.
440
441The LWS can be required by an algorithm (For example if it contains memory barriers or uses local memory) but it can also be used for performance reasons to tweak the performance of a kernel: the execution time of the overall kernel might vary significantly depending on how the GWS is broken down.
442
443However, there is no universal rule regarding which LWS is best for a given kernel, so instead we created the @ref CLTuner.
444
445When the @ref CLTuner is enabled ( Target = 2 for the graph examples), the first time an OpenCL kernel is executed the Compute Library will try to run it with a variety of LWS values and will remember which one performed best for subsequent runs. At the end of the run the @ref graph::Graph will try to save these tuning parameters to a file.
446
447However this process takes quite a lot of time, which is why it cannot be enabled all the time.
448
449But, when the @ref CLTuner is disabled ( Target = 1 for the graph examples), the @ref graph::Graph will try to reload the file containing the tuning parameters, then for each executed kernel the Compute Library will use the fine tuned LWS if it was present in the file or use a default LWS value if it's not.
450
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100451*/
452} // namespace arm_compute