blob: 5a337c374b08e428d23b05846b348b65202dba2a [file] [log] [blame]
Vidhya Sudhan Loganathand646ae12018-11-19 15:18:20 +00001///
Pablo Marquez Telloc7f550d2024-01-17 15:40:59 +00002/// Copyright (c) 2017-2021, 2023-2024 Arm Limited.
Vidhya Sudhan Loganathand646ae12018-11-19 15:18:20 +00003///
4/// SPDX-License-Identifier: MIT
5///
6/// Permission is hereby granted, free of charge, to any person obtaining a copy
7/// of this software and associated documentation files (the "Software"), to
8/// deal in the Software without restriction, including without limitation the
9/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10/// sell copies of the Software, and to permit persons to whom the Software is
11/// furnished to do so, subject to the following conditions:
12///
13/// The above copyright notice and this permission notice shall be included in all
14/// copies or substantial portions of the Software.
15///
16/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22/// SOFTWARE.
23///
Anthony Barbier6ff3b192017-09-04 18:44:23 +010024namespace arm_compute
25{
Georgios Pinitas74180bb2017-09-26 19:28:02 +010026/**
Sheri Zhangd813bab2021-04-30 16:53:41 +010027@page architecture Library Architecture
Anthony Barbier6ff3b192017-09-04 18:44:23 +010028
29@tableofcontents
30
Jakub Sujak59b9ff02023-06-11 21:35:11 +010031@section architecture_compute_library Compute Library architecture
Anthony Barbier6ff3b192017-09-04 18:44:23 +010032
Jakub Sujak59b9ff02023-06-11 21:35:11 +010033The Compute Library is a collection of low level algorithm implementations known as kernels @ref IKernel.
34These kernels are implemented as operators @ref IOperator that do not allocate any memory (i.e. all the memory allocations/mappings have to be handled by the caller)
35and are are designed to be embedded in existing projects and applications.
Anthony Barbier6ff3b192017-09-04 18:44:23 +010036
Jakub Sujak59b9ff02023-06-11 21:35:11 +010037A higher-level interface wraps the operators into functions @ref IFunction that:
38- Performs memory allocation of images and tensors through the use of standard malloc().
39- Enables multi-threading of Arm® Neon™ code in a very basic way using a very simple pool of threads.
40- For OpenCL, uses the default CLScheduler command queue for all mapping operations and kernels.
Anthony Barbier6ff3b192017-09-04 18:44:23 +010041
Jakub Sujak59b9ff02023-06-11 21:35:11 +010042For maximum performance, it is expected that the users would re-implement an equivalent to the function interface which suits better their needs (With a more clever multi-threading strategy, load-balancing between Arm® Neon™ and OpenCL, etc.)
Anthony Barbier6ff3b192017-09-04 18:44:23 +010043
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +010044@section architecture_fast_math Fast-math support
Sheri Zhangff9612c2020-10-08 14:21:46 +010045
46Compute Library supports different types of convolution methods, fast-math flag is only used for the Winograd algorithm.
Michele Di Giorgio33f41fa2021-03-09 14:09:08 +000047When the fast-math flag is enabled, both Arm® Neon™ and CL convolution layers will try to dispatch the fastest implementation available, which may introduce a drop in accuracy as well. The different scenarios involving the fast-math flag are presented below:
Sheri Zhangff9612c2020-10-08 14:21:46 +010048- For FP32:
49 - no-fast-math: Only supports Winograd 3x3,3x1,1x3,5x1,1x5,7x1,1x7
50 - fast-math: Supports Winograd 3x3,3x1,1x3,5x1,1x5,7x1,1x7,5x5,7x7
51- For fp16:
52 - no-fast-math: No Winograd support
53 - fast-math: Supports Winograd 3x3,3x1,1x3,5x1,1x5,7x1,1x7,5x5,7x7
54
Viet-Hoa Do38ac4102022-11-16 16:11:45 +000055@section bf16_acceleration BF16 acceleration
Ramy Elgammalc8cc0242022-10-05 17:05:20 +010056
Viet-Hoa Do38ac4102022-11-16 16:11:45 +000057Required toolchain: android-ndk-r23-beta5 or later.
58
59To build for BF16: "neon" flag should be set "=1" and "arch" has to be "=armv8.6-a", "=armv8.6-a-sve", or "=armv8.6-a-sve2". For example:
60
61 scons arch=armv8.6-a-sve neon=1 opencl=0 extra_cxx_flags="-fPIC" benchmark_tests=0 validation_tests=0 validation_examples=1 os=android Werror=0 toolchain_prefix=aarch64-linux-android29
62
63To enable BF16 acceleration when running FP32 "fast-math" has to be enabled and that works only for Neon convolution layer using cpu gemm.
64In this scenario on CPU: the CpuGemmConv2d kernel performs the conversion from FP32, type of input tensor, to BF16 at block level to exploit the arithmetic capabilities dedicated to BF16. Then transforms back to FP32, the output tensor type.
Ramy Elgammalc8cc0242022-10-05 17:05:20 +010065
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +010066@section architecture_thread_safety Thread-safety
Georgios Pinitascce2ea62019-10-04 13:52:11 +010067
68Although the library supports multi-threading during workload dispatch, thus parallelizing the execution of the workload at multiple threads, the current runtime module implementation is not thread-safe in the sense of executing different functions from separate threads.
69This lies to the fact that the provided scheduling mechanism wasn't designed with thread-safety in mind.
70As it is true with the rest of the runtime library a custom scheduling mechanism can be re-implemented to account for thread-safety if needed and be injected as the library's default scheduler.
71
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +010072@section architecture__algorithms Algorithms
Anthony Barbier6ff3b192017-09-04 18:44:23 +010073
Anthony Barbier14c86a92017-12-14 16:27:41 +000074All 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 +010075
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +010076@section architecture_images_tensors Images, padding, border modes and tensors
Anthony Barbier6ff3b192017-09-04 18:44:23 +010077
78Most 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.
79
80@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.
81
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +010082@subsection architecture_images_tensors_padding_and_border Padding and border modes
Anthony Barbier6ff3b192017-09-04 18:44:23 +010083
84Several 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.
85
86You have 3 types of @ref BorderMode :
87
88- @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.
89- @ref BorderMode::REPLICATE : Neighbor pixels outside of the image are treated as having the same value as the closest valid pixel.
90- @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).
91
Michele Di Giorgio33f41fa2021-03-09 14:09:08 +000092Moreover both OpenCL and Arm® 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.
Anthony Barbier6ff3b192017-09-04 18:44:23 +010093
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +010094@subsubsection architecture_images_tensors_padding Padding
Anthony Barbier6ff3b192017-09-04 18:44:23 +010095
96There are different ways padding can be calculated:
97
98- Accurate padding:
99
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100100@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).
101
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100102- 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 architecture_images_tensors_valid_region).
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100103If 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.
104
105@code{.cpp}
Jakub Sujakee301b32021-06-04 09:46:08 +0100106Image src{}, dst{};
107NEScale scale{};
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100108
Jakub Sujakee301b32021-06-04 09:46:08 +0100109// Create an empty grayscale 640x480 image
110src.allocator()->init(TensorInfo(640, 480, Format::U8));
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100111
Jakub Sujakee301b32021-06-04 09:46:08 +0100112constexpr int scale_factor = 2;
113TensorInfo dst_tensor_info(src.info()->dimension(0) / scale_factor, src.info()->dimension(1) / scale_factor,
114 Format::U8);
115
116// Configure the destination image
117dst.allocator()->init(dst_tensor_info);
118
119// Configure Scale function object:
120scale.configure(&src, &dst, ScaleKernelInfo{
121 InterpolationPolicy::NEAREST_NEIGHBOR,
122 BorderMode::UNDEFINED,
123 PixelValue(),
124 SamplingPolicy::CENTER,
125 false
126});
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100127
128// Allocate all the images
129src.allocator()->allocate();
130dst.allocator()->allocate();
131// Fill the input image with the content of the PPM image if a filename was provided:
132fill_image(src);
133
Jakub Sujakee301b32021-06-04 09:46:08 +0100134// Run the scale operation:
135scale.run();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100136@endcode
137
Jakub Sujakee301b32021-06-04 09:46:08 +0100138The full example is provided in examples/neon_scale.cpp
139
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100140@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.
141
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100142@subsubsection architecture_images_tensors_valid_region Valid regions
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100143
144Some 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.
145
146Another 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.
147
148In 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
149
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100150@subsection architecture_images_tensors_tensors Tensors
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100151
152Tensors are multi-dimensional arrays with a maximum of @ref Coordinates::num_max_dimensions dimensions.
153
154Depending 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.
155
156@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).
157
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100158@subsection architecture_images_tensors_description_conventions Images and Tensors description conventions
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100159
160Image objects are defined by a @ref Format and dimensions expressed as [width, height, batch]
161
162Tensors 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].
163
164In 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.
165For 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.
166Each kernel specifies the expected layout of each of its tensors in its documentation.
167
168@note Unless specified otherwise in the kernel's or function's documentation all tensors and images parameters passed must have identical dimensions.
169
170@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).
171
172@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.
173
174For example, to read the element located at the coordinates (x,y) of a float tensor:
175
176@code{.cpp}
177float value = *reinterpret_cast<float*>(input.buffer() + input.info()->offset_element_in_bytes(Coordinates(x,y)));
178@endcode
179
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100180@subsection architecture_images_tensors_working_with_objects Working with Images and Tensors using iterators
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100181
182The library provides some iterators to access objects' data.
183Iterators are created by associating a data object (An image or a tensor for example) with an iteration window.
184
185Iteration windows are defined by an array of dimensions, each of which consists of a start, end and step.
186
187The @ref execute_window_loop function takes an execution window, a lambda function and one or more iterators.
188It will iterate through every element of the execution window and for each element it will update the iterators accordingly and call the lambda function.
189
190Here are a couple of examples of how to use the iterators to fill / read tensors:
191
192@snippet examples/neon_copy_objects.cpp Copy objects example
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100193
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100194@subsection architecture_images_tensors_sub_tensors Sub-tensors
Georgios Pinitas98f085b2018-07-09 20:21:08 +0100195
196Sub-tensors are aliases to existing Tensors, as a result creating a sub-tensor does not result in any underlying memory allocation.
197
198Sub-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.
199
200Moreover, sub-tensors can be used to perform zero copy tensor concatenation.
201
202The API for creating a sub-tensor is the following:
203@code{.cpp}
204SubTensor(ITensor *parent, const TensorShape &tensor_shape, const Coordinates &coords)
205@endcode
206
207Where \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.
208
209@note Two sub-tensor concrete classes for different targets are currently supported : @ref CLSubTensor and @ref SubTensor
210
211@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.
212
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100213@section architecture_memory_manager MemoryManager
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100214
215@ref IMemoryManager is a memory managing interface that can be used to reduce the memory requirements of a given pipeline by recycling temporary buffers.
216
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100217@subsection architecture_memory_manager_component MemoryGroup, MemoryPool and MemoryManager Components
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100218
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100219@subsubsection architecture_memory_manager_component_memory_group MemoryGroup
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100220
221@ref IMemoryGroup defines the memory managing granularity.
222
223MemoryGroup 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.
224
225Requesting backing memory for a specific group can be done using @ref IMemoryGroup::acquire and releasing the memory back using @ref IMemoryGroup::release.
226
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100227@subsubsection architecture_memory_manager_component_memory_pool MemoryPool
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100228
229@ref IMemoryPool defines a pool of memory that can be used to provide backing memory to a memory group.
230
231@note @ref BlobMemoryPool is currently implemented which models the memory requirements as a vector of distinct memory blobs.
232
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100233@subsubsection architecture_memory_manager_component_memory_manager_components MemoryManager Components
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100234
235@ref IMemoryManager consists of two components:
236- @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.
237- @ref IPoolManager that safely manages the registered memory pools.
238
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100239@note @ref BlobLifetimeManager is currently implemented which models the memory requirements as a vector of distinct memory blobs.
240
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100241@subsection architecture_memory_manager_working_with_memory_manager Working with the Memory Manager
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100242Using a memory manager to reduce the memory requirements of a pipeline can be summed in the following steps:
243
244Initially a memory manager must be set-up:
245@code{.cpp}
246Allocator allocator{}; // Create an allocator to use for the backing memory allocation
247auto lifetime_mgr = std::make_shared<BlobLifetimeManager>(); // Create Lifetime Manager
248auto pool_mgr = std::make_shared<PoolManager>(); // Create Pool Manager
249auto mm = std::make_shared<MemoryManagerOnDemand>(lifetime_mgr, pool_mgr); // Create Memory Manager
250@endcode
251
252Once done, memory groups can be registered to use the memory manager:
253@code{.cpp}
254MemoryGroup memory_group(mm); // Create a memory group and set the memory manager to use
255@endcode
256
257@note If a memory manager is not specified then all allocation will be immediate instead of deferred through the memory manager.
258
259Next 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.
260@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.
261@code{.cpp}
262Tensor tmp1, tmp2, tmp3; // Create example tensors
263memory_group.manage(&tmp1); // Start managing object tmp1 and start its lifetime
264memory_group.manage(&tmp2); // Start managing object tmp2 and start its lifetime
265
266operation1.configure(&tmp1, &tmp2); // Configure a function/kernel using tmp1 and tmp2
267
268tmp1.allocator()->allocate(); // Flag that the lifetime of object tmp1 has ended
269
270memory_group.manage(&tmp3); // Start managing object tmp3 and start its lifetime
271
272operation2.configure(&tmp2, &tmp3); // Configure a function/kernel using tmp2 and tmp3
273
274tmp2.allocator()->allocate(); // Flag that the lifetime of object tmp2 has ended
275tmp3.allocator()->allocate(); // Flag that the lifetime of object tmp3 has ended
276@endcode
277
Jakub Sujakee301b32021-06-04 09:46:08 +0100278@warning The configuration step should be done sequentially by a single thread so that all the lifetimes are captured correctly.
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100279
Georgios Pinitas9da19e92018-10-11 15:33:11 +0100280When configuration of all the operations is finished then the memory manager have to be populated:
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100281@code{.cpp}
Georgios Pinitas9da19e92018-10-11 15:33:11 +0100282mm->populate(&allocator), 2 /* num_pools */); // Populate memory manager pools
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100283@endcode
284
285Finally, during execution of the pipeline the memory of the appropriate memory group should be requested before running:
286@code{.cpp}
287memory_group.acquire(); // Request memory for the group
288
289operation1.run(); // Run operation1
290operation2.run(); // Run operation2
291
292memory_group.release(); // Release memory so that it can be reused
293@endcode
294@note Execution of a pipeline can be done in a multi-threading environment as memory acquisition/release are thread safe.
Michalis Spyrou2dab2e92019-11-12 16:28:47 +0000295@note If you are handling sensitive data and it's required to zero out the memory buffers before freeing, make sure to also zero out the intermediate buffers. You can access the buffers through the memory group's mappings.
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100296
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100297@subsection architecture_memory_manager_function_support Function support
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100298
299Most of the library's function have been ported to use @ref IMemoryManager for their internal temporary buffers.
300
301If that is the case, a memory manager can be passed to them during construction to reuse memory among these functions.
302@code{.cpp}
303// Setup Memory Manager
304CLBufferAllocator allocator{}; // Create an allocator to use for the backing memory allocation
305auto lifetime_mgr = std::make_shared<BlobLifetimeManager>(); // Create Lifetime Manager
306auto pool_mgr = std::make_shared<PoolManager>(); // Create Pool Manager
307auto mm = std::make_shared<MemoryManagerOnDemand>(lifetime_mgr, pool_mgr); // Create Memory Manager
308
309// Create two convolution layers and use the memory manager to manager their internal temporary buffers
310CLConvolutionLayer conv1(mm), conv2(mm);
311
312// Configure layers
313conv1.configure(...);
314conv2.configure(...);
315
Georgios Pinitas9da19e92018-10-11 15:33:11 +0100316// Populate memory manager
317mm->populate(&allocator), 1 /* num_pools */); // Populate memory manager pools
Georgios Pinitas74180bb2017-09-26 19:28:02 +0100318
319// Run layers (Memory will be recycled for internal buffers for conv1 and conv2
320conv1.run();
321conv2.run();
322@endcode
Anthony Barbier3762e742018-03-02 11:49:33 +0000323
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100324@section architecture_import_memory Import Memory Interface
Georgios Pinitasdb09b372019-06-17 17:46:17 +0100325
326The implemented @ref TensorAllocator and @ref CLTensorAllocator objects provide an interface capable of importing existing memory to a tensor as backing memory.
327
Michele Di Giorgio33f41fa2021-03-09 14:09:08 +0000328A simple Arm® Neon™ example can be the following:
Georgios Pinitasdb09b372019-06-17 17:46:17 +0100329@code{.cpp}
330// External backing memory
331void* external_ptr = ...;
332
333// Create and initialize tensor
334Tensor tensor;
335tensor.allocator()->init(tensor_info);
336
337// Import existing pointer as backing memory
338tensor.allocator()->import_memory(external_ptr);
339@endcode
340
341It is important to note the following:
342- Ownership of the backing memory is not transferred to the tensor itself.
343- The tensor mustn't be memory managed.
344- Padding requirements should be accounted by the client code. In other words, if padding is required by the tensor after the function configuration step, then the imported backing memory should account for it. Padding can be checked through the @ref TensorInfo::padding() interface.
345
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100346@section architecture_opencl_tuner OpenCL Tuner
Anthony Barbier3762e742018-03-02 11:49:33 +0000347
348OpenCL kernels when dispatched to the GPU take two arguments:
349- 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.
350- 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.
351
352The 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.
353
354However, there is no universal rule regarding which LWS is best for a given kernel, so instead we created the @ref CLTuner.
355
356When 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.
357
Vidhya Sudhan Loganathandc5d3432019-04-29 11:44:11 +0100358However this process takes quite a lot of time, which is why it cannot be enabled all the time. @ref CLTuner supports three modes of tuning with different trade-offs between the time taken to tune and the kernel execution time achieved using the best LWS found. In the Exhaustive mode, it searches all the supported values of LWS. This mode takes the longest time to tune and is the most likely to find the optimal LWS. Normal mode searches a subset of LWS values to yield a good approximation of the optimal LWS. It takes less time to tune than Exhaustive mode. Rapid mode takes the shortest time to tune and finds an LWS value that is at least as good or better than the default LWS value. The mode affects only the search for the optimal LWS and has no effect when the LWS value is imported from a file.
Anthony Barbier3762e742018-03-02 11:49:33 +0000359
360But, 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.
361
Jakub Sujakee301b32021-06-04 09:46:08 +0100362@section architecture_cl_queue_priorities OpenCL Queue Priorities
Georgios Pinitasc3c352e2021-03-18 10:59:40 +0000363
364OpenCL 2.1 exposes the `cl_khr_priority_hints` extensions that if supported by an underlying implementation allows the user to specify priority hints to the created command queues.
365Is important to note that this does not specify guarantees or the explicit scheduling behavior, this is something that each implementation needs to expose.
366
367In some cases, priority queues can be used when there is an implicit internal priority between graphics and compute queues and thus allow some level of priority control between them.
368At the moment three priority level can be specified:
369- CL_QUEUE_PRIORITY_HIGH_KHR
370- CL_QUEUE_PRIORITY_MED_KHR
371- CL_QUEUE_PRIORITY_LOW_KHR
372
373Compute Library allows extraction of the internal OpenCL queue or the ability to inject directly a user-defined queue to the @ref CLScheduler.
374This way the user can utilize this extension to define priorities between the queues and setup the OpenCL scheduler mechanism to utilize them.
375
376@code{.cpp}
377cl_queue_properties queue_properties[] = {CL_QUEUE_PRIORITY_KHR, CL_QUEUE_PRIORITY_HIGH_KHR, 0};
378cl_command_queue priority_queue = clCreateCommandQueueWithProperties(ctx, dev, queue_properties, &error);
379CLScheduler::get().set_queue(::cl::CommandQueue(priority_queue));
380@endcode
381
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100382@section architecture_weights_manager Weights Manager
Michalis Spyrou422da262019-10-18 15:19:33 +0100383
384@ref IWeightsManager is a weights managing interface that can be used to reduce the memory requirements of a given pipeline by reusing transformed weights across multiple function executions.
385@ref IWeightsManager is responsible for managing weight tensors alongside with their transformations.
386@ref ITransformWeights provides an interface for running the desired transform function. This interface is used by the weights manager.
387
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100388@subsection architecture_weights_manager_working_with_weights_manager Working with the Weights Manager
Michalis Spyrou422da262019-10-18 15:19:33 +0100389Following is a simple example that uses the weights manager:
390
391Initially a weights manager must be set-up:
392@code{.cpp}
393auto wm = std::make_shared<IWeightsManager>(); // Create a weights manager
394@endcode
395
396Once done, weights can be managed, configured and run:
397@code{.cpp}
398wm->manage(weights); // Manage the weights
399wm->acquire(weights, &_reshape_weights_managed_function); // Acquire the address of the transformed weights based on the transform function
400wm->run(weights, &_reshape_weights_managed_function); // Run the transpose function
401@endcode
402
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100403@section programming_model Programming Model
404@subsection programming_model_functions Functions
Georgios Pinitas45ce5662019-10-16 16:49:39 +0100405
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100406Functions 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.
407
408Simple functions only call a single kernel (e.g NEConvolution3x3), while more complex ones consist of several kernels pipelined together (e.g @ref NEFullyConnectedLayer ). Check their documentation to find out which kernels are used by each function.
409
410@code{.cpp}
411//Create a function object:
412MyFunction function;
413// Initialize the function with the input/output and options you want to use:
414function.configure( input, output, option0, option1);
415// Execute the function:
416function.run();
417@endcode
418
419@warning The Compute Library requires Arm® Mali™ OpenCL DDK r8p0 or higher (OpenCL kernels are compiled using the -cl-arm-non-uniform-work-group-size flag)
420
421@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.
422
423@subsection programming_model_scheduler OpenCL Scheduler
424
425The Compute Library runtime uses a single command queue and context for all the operations.
426
427The user can get / set this context and command queue through CLScheduler's interface.
428
429The user can get / set the target GPU device through the CLScheduler's interface.
430
431@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.
432
433@attention Make sure the scheduler's target is not changed after function classes are created.
434
435@subsection programming_model__events_sync OpenCL events and synchronization
436
437In 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()
438
439@subsection programming_model_cl_neon OpenCL / Arm® Neon™ interoperability
440
441You can mix OpenCL and Arm® Neon™ kernels and functions. However it is the user's responsibility to handle the mapping/unmapping of OpenCL objects.
442
443@section architecture_experimental Experimental Features
444
445@subsection architecture_experimental_run_time_context Run-time Context
Georgios Pinitas45ce5662019-10-16 16:49:39 +0100446
447Some of the Compute Library components are modelled as singletons thus posing limitations to supporting some use-cases and ensuring a more client-controlled API.
448Thus, we are introducing an aggregate service interface @ref IRuntimeContext which will encapsulate the services that the singletons were providing and allow better control of these by the client code.
449Run-time context encapsulates a list of mechanisms, some of them are: scheduling, memory management, kernel caching and others.
Georgios Pinitasfd7780d2020-03-17 11:41:00 +0000450Consequently, this will allow finer control of these services among pipelines when Compute Library is integrated in higher level frameworks.
Georgios Pinitas45ce5662019-10-16 16:49:39 +0100451
452This feature introduces some changes to our API.
453All the kernels/functions will now accept a Runtime Context object which will allow the function to use the mentioned services.
Georgios Pinitas45ce5662019-10-16 16:49:39 +0100454
Jakub Sujakee301b32021-06-04 09:46:08 +0100455Finally, we will try to adapt our code-base progressively to use the new mechanism but will continue supporting the legacy mechanism to allow a smooth transition. Changes will apply to all our backends: Neon™ and OpenCL.
Michalis Spyrou402740d2021-04-20 11:26:21 +0100456
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100457@subsection architecture_experimental_clvk CLVK
Michalis Spyrou402740d2021-04-20 11:26:21 +0100458
459Compute Library offers experimental support for [CLVK](https://github.com/kpet/clvk). If CLVK is installed in the system, users can select the backend when running a graph example with --target=clvk.
460If no target is specified and more that one OpenCL implementations are present, Compute Library will pick the first available.
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100461
462@section architecture_experimental_api Experimental Application Programming Interface
463
464@subsection architecture_experimental_api_overview Overview
465
466In this section we present Compute Library's experimental application programming interface (API) architecture along with
467a detailed explanation of its components. Compute Library's API consists of multiple high-level operators and
468even more internally distinct computational blocks that can be executed on a command queue.
469Operators can be bound to multiple Tensor objects and executed concurrently or asynchronously if needed.
470All operators and associated objects are encapsulated in a Context-based mechanism, which provides all related
471construction services.
472
473@subsection architecture_experimental_api_objects Fundamental objects
474
475Compute Library consists of a list of fundamental objects that are responsible for creating and orchestrating operator execution.
476Below we present these objects in more detail.
477
478@subsubsection architecture_experimental_api_objects_context AclContext or Context
479
480AclContext or Context acts as a central creational aggregate service. All other objects are bound to or created from a context.
481It provides, internally, common facilities such as
482- allocators for object creation or backing memory allocation
483- serialization interfaces
484- any other modules that affect the construction of objects (e.g., program cache for OpenCL).
485
486The followings sections will describe parameters that can be given on the creation of Context.
487
488@paragraph architecture_experimental_api_object_context_target AclTarget
489Context is initialized with a backend target (AclTarget) as different backends might have a different subset of services.
490Currently the following targets are supported:
491- #AclCpu: a generic CPU target that accelerates primitives through SIMD technologies
492- #AclGpuOcl: a target for GPU acceleration using OpenCL
493
494@paragraph architecture_experimental_api_object_context_execution_mode AclExecutionMode
495An execution mode (AclExecutionMode) can be passed as an argument that affects the operator creation.
496At the moment the following execution modes are supported:
497- #AclPreferFastRerun: Provides faster re-run. It can be used when the operators are expected to be executed multiple
498times under the same execution context
499- #AclPreferFastStart: Provides faster single execution. It can be used when the operators will be executed only once,
500thus reducing their latency is important (Currently, it is not implemented)
501
Jakub Sujakee301b32021-06-04 09:46:08 +0100502@paragraph architecture_experimental_api_object_context_capabilities AclTargetCapabilities
Sang-Hoon Parkc9309f22021-05-05 10:34:47 +0100503Context creation can also have a list of capabilities of hardware as one of its parameters. This is currently
504available only for the CPU backend. A list of architecture capabilities can be passed to influence the selection
505of the underlying kernels. Such capabilities can be for example the enablement of SVE or the dot product
506instruction explicitly.
507@note The underlying hardware should support the given capability list.
508
509@paragraph architecture_experimental_api_object_context_allocator Allocator
510An allocator object that implements @ref AclAllocator can be passed to the Context upon its creation.
511This user-provided allocator will be used for allocation of any internal backing memory.
512
513@note To enable interoperability with OpenCL, additional entrypoints are provided
514to extract (@ref AclGetClContext) or set (@ref AclSetClContext) the internal OpenCL context.
515
516@subsubsection architecture_experimental_api_objects_tensor AclTensor or Tensor
517
518A tensor is a mathematical object that can describe physical properties like matrices.
519It can be also considered a generalization of matrices that can represent arbitrary
520dimensionalities. AclTensor is an abstracted interface that represents a tensor.
521
522AclTensor, in addition to the elements of the physical properties they represent,
523also contains the information such as shape, data type, data layout and strides to not only
524fully describe the characteristics of the physical properties but also provide information
525how the object stored in memory should be traversed. @ref AclTensorDescriptor is a dedicated
526object to represent such metadata.
527
528@note The allocation of an AclTensor can be deferred until external memory is imported
529as backing memory to accomplish a zero-copy context.
530
531@note To enable interoperability with OpenCL, additional entrypoints are provided
532to extract (@ref AclGetClMem) the internal OpenCL memory object.
533
534As Tensors can reside in different memory spaces, @ref AclMapTensor and @ref AclUnmapTensor entrypoints
535are provided to map Tensors in and out of the host memory system, respectively.
536
537@subsubsection architecture_experimental_api_objects_queue AclQueue or Queue
538
539AclQueue acts as a runtime aggregate service. It provides facilities to schedule
540and execute operators using underlying hardware. It also contains services like
541tuning mechanisms (e.g., Local workgroup size tuning for OpenCL) that can be specified
542during operator execution.
543
544@note To enable interoperability with OpenCL, additional entrypoints are provided
545to extract (@ref AclGetClQueue) or set (@ref AclSetClQueue) the internal OpenCL queue.
546
547@subsection architecture_experimental_api_internal Internal
548@subsubsection architecture_experimental_api_internal_operator_vs_kernels Operators vs Kernels
549
550Internally, Compute Library separates the executable primitives in two categories: kernels and operators
551which operate in a hierarchical way.
552
553A kernel is the lowest-level computation block whose responsibility is performing a task on a given group of data.
554For design simplicity, kernels computation does NOT involve the following:
555
556- Memory allocation: All the memory manipulation should be handled by the caller.
557- Multi-threading: The information on how the workload can be split is provided by kernels,
558so the caller can effectively distribute the workload to multiple threads.
559
560On the other hand, operators combine one or multiple kernels to achieve more complex calculations.
561The responsibilities of the operators can be summarized as follows:
562
563- Defining the scheduling policy and dispatching of the underlying kernels to the hardware backend
564- Providing information to the caller required by the computation (e.g., memory requirements)
565- Allocation of any required auxiliary memory if it isn't given by its caller explicitly
566
Motti Gondabi6f3a9f52021-11-09 15:47:17 +0200567@subsection architecture_experimental_build_multi_isa Build multi-ISA binary
Michalis Spyrou62c2ad62021-06-21 17:40:09 +0100568
Motti Gondabi6f3a9f52021-11-09 15:47:17 +0200569Selecting multi_isa when building Compute Library, will create a library that contains all the supported ISA features.
Michalis Spyrou62c2ad62021-06-21 17:40:09 +0100570Based on the CPU support, the appropriate kernel will be selected at runtime for execution. Currently this option is
Pablo Marquez Telloc7f550d2024-01-17 15:40:59 +0000571supported in two configurations: (i) with armv8.2-a (ii) with armv8-a. In both cases all the supported ISA features are enabled
572in the build.
573
574The arch option in a multi_isa build sets the minimum architecture required to run the resulting binary.
575For example a multi_isa build for armv8-a will run on any armv8-a or later, when the binary is executed on a armv8.2-a device
576it will use the additional cpu features present in this architecture: FP16 and dot product.
577In order to have a binary like this (multi_isa+armv8-a) the FP16 and dot product kernels in the library are compiled for the
578target armv8.2-a and all other common code for armv8-a.
Michalis Spyrou62c2ad62021-06-21 17:40:09 +0100579
Georgios Pinitasb6af4822021-09-14 12:33:34 +0100580@subsection architecture_experimental_per_operator_build Per-operator build
581
582Dependencies for all operators have been explicitly defined, this provides the ability to users to generate Compute Library
583binaries that include a user-defined list of operators.
584
585An experimental flag 'build_config' has been introduced where a JSON configuration file can be provided and consumed.
586An example config looks like:
587@code{.py}
588{
589 "operators": [
590 "Activation",
591 "DepthwiseConv2d",
592 "Conv2d",
593 "Permute",
594 "Pool2d",
595 "Reshape"
596 ],
597 "data_types": [
598 "NHWC"
599 ]
600}
601@endcode
602
603Supported data-types options are:
604- "NHWC"
605- "NCHW"
606
607The list of supported operators can be found in filelist.json in the root of Compute Library repo.
608
Michalis Spyrou62c2ad62021-06-21 17:40:09 +0100609@subsection architecture_experimental_build_high_priority_operators Build high priority operators
610
611Selecting high_priority when building Compute Library, one new library will be created: libarm_compute_hp and
612will contain a selected subset of the libary operators. Currently the operators are staticly set.
613
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100614*/
615} // namespace arm_compute