blob: a2c1b87359b7dd2d28e6748aa20f31d9b286664a [file] [log] [blame]
David Beck1b61be52018-11-08 09:19:14 +00001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
6#include "ClBackendContext.hpp"
7#include "ClContextControl.hpp"
8
9#include <boost/log/trivial.hpp>
10
11#ifdef ARMCOMPUTECL_ENABLED
12#include <arm_compute/core/CL/OpenCL.h>
13#include <arm_compute/core/CL/CLKernelLibrary.h>
14#include <arm_compute/runtime/CL/CLScheduler.h>
15#endif
16
17namespace armnn
18{
19
20struct ClBackendContext::ClContextControlWrapper
21{
22 ClContextControlWrapper(IGpuAccTunedParameters* clTunedParameters,
23 bool profilingEnabled)
24 : m_ClContextControl(clTunedParameters, profilingEnabled)
25 {}
26
27 bool Sync()
28 {
29#ifdef ARMCOMPUTECL_ENABLED
30 if (arm_compute::CLScheduler::get().context()() != NULL)
31 {
32 // Waits for all queued CL requests to finish before unloading the network they may be using.
33 try
34 {
35 // Coverity fix: arm_compute::CLScheduler::sync() may throw an exception of type cl::Error.
36 arm_compute::CLScheduler::get().sync();
37 }
38 catch (const cl::Error&)
39 {
40 BOOST_LOG_TRIVIAL(warning) << "WARNING: Runtime::UnloadNetwork(): an error occurred while waiting for "
41 "the queued CL requests to finish";
42 return false;
43 }
44 }
45#endif
46 return true;
47 }
48
49 void ClearClCache()
50 {
51#ifdef ARMCOMPUTECL_ENABLED
52 if (arm_compute::CLScheduler::get().context()() != NULL)
53 {
54 // There are no loaded networks left, so clear the CL cache to free up memory
55 m_ClContextControl.ClearClCache();
56 }
57#endif
58 }
59
60
61 ClContextControl m_ClContextControl;
62};
63
64
65ClBackendContext::ClBackendContext(const IRuntime::CreationOptions& options)
66 : IBackendContext(options)
67 , m_ClContextControlWrapper(
68 std::make_unique<ClContextControlWrapper>(options.m_GpuAccTunedParameters.get(),
69 options.m_EnableGpuProfiling))
70{
71}
72
73bool ClBackendContext::BeforeLoadNetwork(NetworkId)
74{
75 return true;
76}
77
78bool ClBackendContext::AfterLoadNetwork(NetworkId networkId)
79{
80 {
81 std::lock_guard<std::mutex> lockGuard(m_Mutex);
82 m_NetworkIds.insert(networkId);
83 }
84 return true;
85}
86
87bool ClBackendContext::BeforeUnloadNetwork(NetworkId)
88{
89 return m_ClContextControlWrapper->Sync();
90}
91
92bool ClBackendContext::AfterUnloadNetwork(NetworkId networkId)
93{
94 bool clearCache = false;
95 {
96 std::lock_guard<std::mutex> lockGuard(m_Mutex);
97 m_NetworkIds.erase(networkId);
98 clearCache = m_NetworkIds.empty();
99 }
100
101 if (clearCache)
102 {
103 m_ClContextControlWrapper->ClearClCache();
104 }
105
106 return true;
107}
108
109ClBackendContext::~ClBackendContext()
110{
111}
112
113} // namespace armnn