1/// 2/// Copyright (c) 2017-2020 Arm Limited. 3/// 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/// 24namespace arm_compute 25{ 26/** 27@page architecture Library architecture 28 29@tableofcontents 30 31@section S4_1_1 Core vs Runtime libraries 32 33The Core library is a low level collection of algorithms implementations, it is designed to be embedded in existing projects and applications: 34 35- It doesn't allocate any memory (All the memory allocations/mappings have to be handled by the caller). 36- It doesn't perform any kind of multi-threading (but provide information to the caller about how the workload can be split). 37 38The 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: 39 40- It allocates images and tensors by using standard malloc(). 41- It multi-threads NEON code in a very basic way using a very simple pool of threads. 42- For OpenCL it uses the default CLScheduler command queue for all mapping operations and kernels. 43 44For 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.) 45 46@section S4_1_2 Data-type and Data-layout support 47 48Compute Library supports a wide list of data-types, information can been directly found in the documentation of each kernel/function. 49The main data-types that the Machine Learning functions support are the following: 50- BFLOAT16: 16-bit non-standard brain floating point 51- F16: 16-bit half precision floating point 52- F32: 32-bit single precision floating point 53- QASYMM8: 8-bit unsigned asymmetric quantized 54- QASYMM8_SIGNED: 8-bit signed asymmetric quantized 55- QSYMM8_PER_CHANNEL: 8-bit signed symmetric quantized (Used for the weights) 56 57Moreover, Compute Library supports the following data layouts (fast changing dimension from right to left): 58- NHWC: The native layout of Compute Library that delivers the best performance where channels are in the fastest changing dimension 59- NCHW: Legacy layout where width is in the fastest changing dimension 60where N = batches, C = channels, H = height, W = width 61 62@section S4_1_3 Fast-math support 63 64Compute Library supports different types of convolution methods, fast-math flag is only used for the Winograd algorithm. 65When the fast-math flag is enabled, both 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: 66- For FP32: 67 - no-fast-math: Only supports Winograd 3x3,3x1,1x3,5x1,1x5,7x1,1x7 68 - fast-math: Supports Winograd 3x3,3x1,1x3,5x1,1x5,7x1,1x7,5x5,7x7 69- For fp16: 70 - no-fast-math: No Winograd support 71 - fast-math: Supports Winograd 3x3,3x1,1x3,5x1,1x5,7x1,1x7,5x5,7x7 72 73@section S4_1_4 Thread-safety 74 75Although 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. 76This lies to the fact that the provided scheduling mechanism wasn't designed with thread-safety in mind. 77As 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. 78 79@section S4_2_windows_kernels_mt_functions Windows, kernels, multi-threading and functions 80 81@subsection S4_2_1_windows Windows 82 83A @ref Window represents a workload to execute, it can handle up to @ref Coordinates::num_max_dimensions dimensions. 84Each dimension is defined by a start, end and step. 85 86It can split into subwindows as long as *all* the following rules remain true for all the dimensions: 87 88- max[n].start() <= sub[n].start() < max[n].end() 89- sub[n].start() < sub[n].end() <= max[n].end() 90- max[n].step() == sub[n].step() 91- (sub[n].start() - max[n].start()) % max[n].step() == 0 92- (sub[n].end() - sub[n].start()) % max[n].step() == 0 93 94@subsection S4_2_2 Kernels 95 96Each implementation of the @ref IKernel interface (base class of all the kernels in the core library) works in the same way: 97 98OpenCL kernels: 99 100@code{.cpp} 101// Initialize the CLScheduler with the default context and default command queue 102// 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. 103CLScheduler::get().default_init(); 104 105cl::CommandQueue q = CLScheduler::get().queue(); 106//Create a kernel object: 107MyKernel kernel; 108// Initialize the kernel with the input/output and options you want to use: 109kernel.configure( input, output, option0, option1); 110// Retrieve the execution window of the kernel: 111const Window& max_window = kernel.window(); 112// Run the whole kernel in the current thread: 113kernel.run( q, max_window ); // Enqueue the kernel to process the full window on the default queue 114 115// Wait for the processing to complete: 116q.finish(); 117@endcode 118 119NEON / CPP kernels: 120 121@code{.cpp} 122//Create a kernel object: 123MyKernel kernel; 124// Initialize the kernel with the input/output and options you want to use: 125kernel.configure( input, output, option0, option1); 126// Retrieve the execution window of the kernel: 127const Window& max_window = kernel.window(); 128// Run the whole kernel in the current thread: 129kernel.run( max_window ); // Run the kernel on the full window 130@endcode 131 132@subsection S4_2_3 Multi-threading 133 134The 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: 135 136@code{.cpp} 137 ThreadInfo info; 138 info.cpu_info = &_cpu_info; 139 140 const Window &max_window = kernel->window(); 141 const unsigned int num_iterations = max_window.num_iterations(split_dimension); 142 info.num_threads = std::min(num_iterations, _num_threads); 143 144 if(num_iterations == 0) 145 { 146 return; 147 } 148 149 if(!kernel->is_parallelisable() || info.num_threads == 1) 150 { 151 kernel->run(max_window, info); 152 } 153 else 154 { 155 int t = 0; 156 auto thread_it = _threads.begin(); 157 158 for(; t < info.num_threads - 1; ++t, ++thread_it) 159 { 160 Window win = max_window.split_window(split_dimension, t, info.num_threads); 161 info.thread_id = t; 162 thread_it->start(kernel, win, info); 163 } 164 165 // Run last part on main thread 166 Window win = max_window.split_window(split_dimension, t, info.num_threads); 167 info.thread_id = t; 168 kernel->run(win, info); 169 170 try 171 { 172 for(auto &thread : _threads) 173 { 174 thread.wait(); 175 } 176 } 177 catch(const std::system_error &e) 178 { 179 std::cerr << "Caught system_error with code " << e.code() << " meaning " << e.what() << '\n'; 180 } 181 } 182@endcode 183 184This is a very basic implementation which was originally used in the NEON runtime library by all the NEON functions. 185 186@sa CPPScheduler 187 188@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. 189 190@subsection S4_2_4 Functions 191 192Functions 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. 193 194Simple 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. 195 196@code{.cpp} 197//Create a function object: 198MyFunction function; 199// Initialize the function with the input/output and options you want to use: 200function.configure( input, output, option0, option1); 201// Execute the function: 202function.run(); 203@endcode 204 205@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) 206 207@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. 208 209@subsection S4_4_1_cl_scheduler OpenCL Scheduler and kernel library 210 211The Compute Library runtime uses a single command queue and context for all the operations. 212 213The user can get / set this context and command queue through CLScheduler's interface. 214 215The user can get / set the target GPU device through the CLScheduler's interface. 216 217@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. 218 219@attention Make sure the scheduler's target is not changed after function classes are created. 220 221All OpenCL kernels used by the library are built and stored in @ref CLKernelLibrary. 222If 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" 223 224@subsection S4_4_2_events_sync OpenCL events and synchronization 225 226In 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() 227 228For example: 229@snippet cl_events.cpp OpenCL events 230 231@subsection S4_4_2_cl_neon OpenCL / NEON interoperability 232 233You 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: 234 235@snippet neoncl_scale_median_gaussian.cpp NEON / OpenCL Interop 236 237@sa main_neoncl_scale_median_gaussian 238 239@section S4_5_algorithms Algorithms 240 241All 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. 242 243@section S4_6_images_tensors Images, padding, border modes and tensors 244 245Most 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. 246 247@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. 248 249@subsection S4_6_1_padding_and_border Padding and border modes 250 251Several 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. 252 253You have 3 types of @ref BorderMode : 254 255- @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. 256- @ref BorderMode::REPLICATE : Neighbor pixels outside of the image are treated as having the same value as the closest valid pixel. 257- @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). 258 259Moreover 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. 260 261@subsubsection padding Padding 262 263There are different ways padding can be calculated: 264 265- Accurate padding: 266 267@snippet neon_convolution.cpp Accurate padding 268 269@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). 270 271- 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). 272If 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. 273 274@code{.cpp} 275Image src, dst; 276 277// Use auto padding for the input: 278src.info()->init_auto_padding(TensorShape(640u,480u), Format::U8); 279 280// Use manual padding for the destination image 281dst.info()->init(src.info()->tensor_shape(), Format::U8, strides_in_bytes, offset_first_element_in_bytes, total_size_in_bytes); 282 283// Allocate all the images 284src.allocator()->allocate(); 285dst.allocator()->allocate(); 286// Fill the input image with the content of the PPM image if a filename was provided: 287fill_image(src); 288 289NEGaussian3x3 gauss; 290 291// 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) 292gauss.configure(&src, &dst, BorderMode::UNDEFINED); 293 294//Execute the functions: 295gauss.run(); 296@endcode 297 298@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. 299 300@subsubsection valid_region Valid regions 301 302Some 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. 303 304Another 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. 305 306In 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 307 308@subsection S4_6_2_tensors Tensors 309 310Tensors are multi-dimensional arrays with a maximum of @ref Coordinates::num_max_dimensions dimensions. 311 312Depending 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. 313 314@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). 315 316@subsection S4_6_3_description_conventions Images and Tensors description conventions 317 318Image objects are defined by a @ref Format and dimensions expressed as [width, height, batch] 319 320Tensors 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]. 321 322In 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. 323For 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. 324Each kernel specifies the expected layout of each of its tensors in its documentation. 325 326@note Unless specified otherwise in the kernel's or function's documentation all tensors and images parameters passed must have identical dimensions. 327 328@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). 329 330@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. 331 332For example, to read the element located at the coordinates (x,y) of a float tensor: 333 334@code{.cpp} 335float value = *reinterpret_cast<float*>(input.buffer() + input.info()->offset_element_in_bytes(Coordinates(x,y))); 336@endcode 337 338@subsection S4_6_4_working_with_objects Working with Images and Tensors using iterators 339 340The library provides some iterators to access objects' data. 341Iterators are created by associating a data object (An image or a tensor for example) with an iteration window. 342 343Iteration windows are defined by an array of dimensions, each of which consists of a start, end and step. 344 345The @ref execute_window_loop function takes an execution window, a lambda function and one or more iterators. 346It will iterate through every element of the execution window and for each element it will update the iterators accordingly and call the lambda function. 347 348Here are a couple of examples of how to use the iterators to fill / read tensors: 349 350@snippet examples/neon_copy_objects.cpp Copy objects example 351 352@subsection S4_6_5_sub_tensors Sub-tensors 353 354Sub-tensors are aliases to existing Tensors, as a result creating a sub-tensor does not result in any underlying memory allocation. 355 356Sub-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. 357 358Moreover, sub-tensors can be used to perform zero copy tensor concatenation. 359 360The API for creating a sub-tensor is the following: 361@code{.cpp} 362SubTensor(ITensor *parent, const TensorShape &tensor_shape, const Coordinates &coords) 363@endcode 364 365Where \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. 366 367@note Two sub-tensor concrete classes for different targets are currently supported : @ref CLSubTensor and @ref SubTensor 368 369@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. 370 371@section S4_7_memory_manager MemoryManager 372 373@ref IMemoryManager is a memory managing interface that can be used to reduce the memory requirements of a given pipeline by recycling temporary buffers. 374 375@subsection S4_7_1_memory_manager_components MemoryGroup, MemoryPool and MemoryManager Components 376 377@subsubsection S4_7_1_1_memory_group MemoryGroup 378 379@ref IMemoryGroup defines the memory managing granularity. 380 381MemoryGroup 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. 382 383Requesting backing memory for a specific group can be done using @ref IMemoryGroup::acquire and releasing the memory back using @ref IMemoryGroup::release. 384 385@subsubsection S4_7_1_2_memory_pool MemoryPool 386 387@ref IMemoryPool defines a pool of memory that can be used to provide backing memory to a memory group. 388 389@note @ref BlobMemoryPool is currently implemented which models the memory requirements as a vector of distinct memory blobs. 390 391@subsubsection S4_7_1_2_memory_manager_components MemoryManager Components 392 393@ref IMemoryManager consists of two components: 394- @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. 395- @ref IPoolManager that safely manages the registered memory pools. 396 397@note @ref BlobLifetimeManager is currently implemented which models the memory requirements as a vector of distinct memory blobs. 398 399@subsection S4_7_2_working_with_memory_manager Working with the Memory Manager 400Using a memory manager to reduce the memory requirements of a pipeline can be summed in the following steps: 401 402Initially a memory manager must be set-up: 403@code{.cpp} 404Allocator allocator{}; // Create an allocator to use for the backing memory allocation 405auto lifetime_mgr = std::make_shared<BlobLifetimeManager>(); // Create Lifetime Manager 406auto pool_mgr = std::make_shared<PoolManager>(); // Create Pool Manager 407auto mm = std::make_shared<MemoryManagerOnDemand>(lifetime_mgr, pool_mgr); // Create Memory Manager 408@endcode 409 410Once done, memory groups can be registered to use the memory manager: 411@code{.cpp} 412MemoryGroup memory_group(mm); // Create a memory group and set the memory manager to use 413@endcode 414 415@note If a memory manager is not specified then all allocation will be immediate instead of deferred through the memory manager. 416 417Next 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. 418@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. 419@code{.cpp} 420Tensor tmp1, tmp2, tmp3; // Create example tensors 421memory_group.manage(&tmp1); // Start managing object tmp1 and start its lifetime 422memory_group.manage(&tmp2); // Start managing object tmp2 and start its lifetime 423 424operation1.configure(&tmp1, &tmp2); // Configure a function/kernel using tmp1 and tmp2 425 426tmp1.allocator()->allocate(); // Flag that the lifetime of object tmp1 has ended 427 428memory_group.manage(&tmp3); // Start managing object tmp3 and start its lifetime 429 430operation2.configure(&tmp2, &tmp3); // Configure a function/kernel using tmp2 and tmp3 431 432tmp2.allocator()->allocate(); // Flag that the lifetime of object tmp2 has ended 433tmp3.allocator()->allocate(); // Flag that the lifetime of object tmp3 has ended 434@endcode 435 436@warning The configuration step should be done sequentially by a single thread so that all the lifetimes are captured correclty. 437 438When configuration of all the operations is finished then the memory manager have to be populated: 439@code{.cpp} 440mm->populate(&allocator), 2 /* num_pools */); // Populate memory manager pools 441@endcode 442 443Finally, during execution of the pipeline the memory of the appropriate memory group should be requested before running: 444@code{.cpp} 445memory_group.acquire(); // Request memory for the group 446 447operation1.run(); // Run operation1 448operation2.run(); // Run operation2 449 450memory_group.release(); // Release memory so that it can be reused 451@endcode 452@note Execution of a pipeline can be done in a multi-threading environment as memory acquisition/release are thread safe. 453@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. 454 455@subsection S4_7_3_memory_manager_function_support Function support 456 457Most of the library's function have been ported to use @ref IMemoryManager for their internal temporary buffers. 458 459If that is the case, a memory manager can be passed to them during construction to reuse memory among these functions. 460@code{.cpp} 461// Setup Memory Manager 462CLBufferAllocator allocator{}; // Create an allocator to use for the backing memory allocation 463auto lifetime_mgr = std::make_shared<BlobLifetimeManager>(); // Create Lifetime Manager 464auto pool_mgr = std::make_shared<PoolManager>(); // Create Pool Manager 465auto mm = std::make_shared<MemoryManagerOnDemand>(lifetime_mgr, pool_mgr); // Create Memory Manager 466 467// Create two convolution layers and use the memory manager to manager their internal temporary buffers 468CLConvolutionLayer conv1(mm), conv2(mm); 469 470// Configure layers 471conv1.configure(...); 472conv2.configure(...); 473 474// Populate memory manager 475mm->populate(&allocator), 1 /* num_pools */); // Populate memory manager pools 476 477// Run layers (Memory will be recycled for internal buffers for conv1 and conv2 478conv1.run(); 479conv2.run(); 480@endcode 481 482@section S4_8_import_memory Import Memory Interface 483 484The implemented @ref TensorAllocator and @ref CLTensorAllocator objects provide an interface capable of importing existing memory to a tensor as backing memory. 485 486A simple NEON example can be the following: 487@code{.cpp} 488// External backing memory 489void* external_ptr = ...; 490 491// Create and initialize tensor 492Tensor tensor; 493tensor.allocator()->init(tensor_info); 494 495// Import existing pointer as backing memory 496tensor.allocator()->import_memory(external_ptr); 497@endcode 498 499It is important to note the following: 500- Ownership of the backing memory is not transferred to the tensor itself. 501- The tensor mustn't be memory managed. 502- 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. 503 504@section S4_9_opencl_tuner OpenCL Tuner 505 506OpenCL kernels when dispatched to the GPU take two arguments: 507- 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. 508- 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. 509 510The 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. 511 512However, there is no universal rule regarding which LWS is best for a given kernel, so instead we created the @ref CLTuner. 513 514When 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. 515 516However 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. 517 518But, 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. 519 520@section S4_10_weights_manager Weights Manager 521 522@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. 523@ref IWeightsManager is responsible for managing weight tensors alongside with their transformations. 524@ref ITransformWeights provides an interface for running the desired transform function. This interface is used by the weights manager. 525 526@subsection S4_10_1_working_with_weights_manager Working with the Weights Manager 527Following is a simple example that uses the weights manager: 528 529Initially a weights manager must be set-up: 530@code{.cpp} 531auto wm = std::make_shared<IWeightsManager>(); // Create a weights manager 532@endcode 533 534Once done, weights can be managed, configured and run: 535@code{.cpp} 536wm->manage(weights); // Manage the weights 537wm->acquire(weights, &_reshape_weights_managed_function); // Acquire the address of the transformed weights based on the transform function 538wm->run(weights, &_reshape_weights_managed_function); // Run the transpose function 539@endcode 540 541@section S5_0_experimental Experimental Features 542 543@subsection S5_1_run_time_context Run-time Context 544 545Some of the Compute Library components are modelled as singletons thus posing limitations to supporting some use-cases and ensuring a more client-controlled API. 546Thus, 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. 547Run-time context encapsulates a list of mechanisms, some of them are: scheduling, memory management, kernel caching and others. 548Consequently, this will allow finer control of these services among pipelines when Compute Library is integrated in higher level frameworks. 549 550This feature introduces some changes to our API. 551All the kernels/functions will now accept a Runtime Context object which will allow the function to use the mentioned services. 552 553Finally, 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 three backends: NEON, OpenCL and OpenGL ES. 554*/ 555} // namespace arm_compute 556