ONE - On-device Neural Engine
Loading...
Searching...
No Matches
ExternalContext.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2024 Samsung Electronics Co., Ltd. All Rights Reserved
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "ExternalContext.h"
18
19#include <fstream>
20#include <string>
21#include <thread>
22#include <unordered_set>
23
24namespace
25{
26
27int32_t countPhysicalCores()
28{
29#ifdef __linux__
30 // Count physical cores, not threads by checking thread_siblings.
31 std::unordered_set<std::string> siblings;
32 for (uint32_t cpu = 0; cpu < UINT32_MAX; ++cpu)
33 {
34 std::ifstream thread_siblings("/sys/devices/system/cpu/cpu" + std::to_string(cpu) +
35 "/topology/thread_siblings");
36 if (!thread_siblings.is_open())
37 {
38 break;
39 }
40
41 std::string line;
42 if (std::getline(thread_siblings, line))
43 {
44 siblings.insert(line);
45 }
46 }
47 if (!siblings.empty())
48 {
49 return static_cast<int32_t>(siblings.size());
50 }
51#endif
52
53 unsigned int n_threads = std::thread::hardware_concurrency();
54 return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 1;
55}
56
57} // namespace
58
59namespace onert
60{
61namespace backend
62{
63namespace cpu
64{
65
66ExternalContext::ExternalContext() : _ruy_context(new ruy::Context)
67{
68 setMaxNumThreads(onert::util::getConfigInt(onert::util::config::NUM_THREADS));
69}
70
71void ExternalContext::setMaxNumThreads(int max_num_threads)
72{
73 _max_num_threads = max_num_threads > -1 ? max_num_threads : countPhysicalCores();
74 _ruy_context->set_max_num_threads(_max_num_threads);
75}
76
78{
79 if (_ggml_context == nullptr)
80 _ggml_context = std::unique_ptr<ggml_context, decltype(&ggml_free)>(
81 ggml_init({.mem_size = 0, .mem_buffer = nullptr, .no_alloc = true}), &ggml_free);
82}
83
84} // namespace cpu
85} // namespace backend
86} // namespace onert
void setMaxNumThreads(int max_num_threads)
int getConfigInt(const std::string &key)