Arcane  4.1.12.0
Developer documentation
Loading...
Searching...
No Matches
VariableSynchronizerMng.cc
1// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
2//-----------------------------------------------------------------------------
3// Copyright 2000-2026 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
4// See the top-level COPYRIGHT file for details.
5// SPDX-License-Identifier: Apache-2.0
6//-----------------------------------------------------------------------------
7/*---------------------------------------------------------------------------*/
8/* VariableSynchronizerMng.cc (C) 2000-2025 */
9/* */
10/* Variable Synchronizer Manager. */
11/*---------------------------------------------------------------------------*/
12/*---------------------------------------------------------------------------*/
13
14#include "arcane/impl/internal/VariableSynchronizerMng.h"
15
16#include "arcane/utils/PlatformUtils.h"
17#include "arcane/utils/ValueConvert.h"
18#include "arcane/utils/FatalErrorException.h"
19#include "arcane/utils/OStringStream.h"
20#include "arcane/utils/internal/MemoryBuffer.h"
21
22#include "arcane/core/IVariableMng.h"
23#include "arcane/core/IParallelMng.h"
24#include "arcane/core/VariableSynchronizerEventArgs.h"
25#include "arcane/core/IVariable.h"
26
27#include <map>
28#include <mutex>
29#include <stack>
30
31/*---------------------------------------------------------------------------*/
32/*---------------------------------------------------------------------------*/
33
34namespace Arcane
35{
36
37/*---------------------------------------------------------------------------*/
38/*---------------------------------------------------------------------------*/
39
56class VariableSynchronizerStats
57: public TraceAccessor
58{
59 public:
60
61 // We use a ReduceMin for the comparison value.
62 // For them to be considered identical, all ranks
63 // must be identical. One 'Unknown' rank is enough to consider
64 // it 'Unknown'. Therefore, 'Unknown' must be the lowest value and 'Same' the highest.
65 static constexpr unsigned char LOCAL_UNKNOWN = 0;
66 static constexpr unsigned char LOCAL_DIFF = 1;
67 static constexpr unsigned char LOCAL_SAME = 2;
68
69 public:
70
72 {
73 public:
74
75 void add(const StatInfo& x)
76 {
77 m_count += x.m_count;
78 m_nb_same += x.m_nb_same;
79 m_nb_different += x.m_nb_different;
80 m_nb_unknown += x.m_nb_unknown;
81 }
82
83 public:
84
85 Int32 m_count = 0;
86 Int32 m_nb_same = 0;
87 Int32 m_nb_different = 0;
88 Int32 m_nb_unknown = 0;
89 };
90
91 public:
92
93 explicit VariableSynchronizerStats(VariableSynchronizerMng* vsm)
94 : TraceAccessor(vsm->traceMng())
95 , m_variable_synchronizer_mng(vsm)
96 {}
97
98 public:
99
100 void init()
101 {
102 if (m_is_event_registered)
103 ARCANE_FATAL("instance is already initialized.");
104 auto handler = [&](const VariableSynchronizerEventArgs& args) {
105 _handleEvent(args);
106 };
107 m_variable_synchronizer_mng->onSynchronized().attach(m_observer_pool, handler);
108 m_is_event_registered = true;
109 }
110
111 void flushPendingStats(IParallelMng* pm);
112
113 Int32 dumpStats(std::ostream& ostr)
114 {
115 std::streamsize old_precision = ostr.precision(20);
116 ostr << "Synchronization Stats\n";
117 ostr << Trace::Width(8) << "Total"
118 << Trace::Width(8) << " Nb "
119 << Trace::Width(8) << " Nb "
120 << Trace::Width(8) << " Nb "
121 << " Variable name"
122 << "\n";
123 ostr << Trace::Width(8) << "Count"
124 << Trace::Width(8) << "Same"
125 << Trace::Width(8) << "Diff"
126 << Trace::Width(8) << "Unknown"
127 << "\n";
128 StatInfo total_stat;
129 for (const auto& p : m_stats) {
130 total_stat.add(p.second);
131 ostr << " " << Trace::Width(7) << p.second.m_count
132 << " " << Trace::Width(7) << p.second.m_nb_same
133 << " " << Trace::Width(7) << p.second.m_nb_different
134 << " " << Trace::Width(7) << p.second.m_nb_unknown
135 << " " << p.first
136 << "\n";
137 }
138 ostr << "\n";
139 ostr << " " << Trace::Width(7) << total_stat.m_count
140 << " " << Trace::Width(7) << total_stat.m_nb_same
141 << " " << Trace::Width(7) << total_stat.m_nb_different
142 << " " << Trace::Width(7) << total_stat.m_nb_unknown
143 << " "
144 << "TOTAL"
145 << "\n\n";
146 ostr.precision(old_precision);
147 return total_stat.m_count;
148 }
149
150 private:
151
152 VariableSynchronizerMng* m_variable_synchronizer_mng = nullptr;
153 EventObserverPool m_observer_pool;
154 std::map<String, StatInfo> m_stats;
155 bool m_is_event_registered = false;
156 UniqueArray<String> m_pending_variable_name_list;
157 UniqueArray<unsigned char> m_pending_compare_status_list;
158
159 private:
160
161 void _handleEvent(const VariableSynchronizerEventArgs& args);
162};
163
164void VariableSynchronizerStats::
165_handleEvent(const VariableSynchronizerEventArgs& args)
166{
167 // We only process end-of-synchronization events
168 if (args.state() != VariableSynchronizerEventArgs::State::EndSynchronize)
169 return;
170 if (!m_variable_synchronizer_mng->isDoingStats())
171 return;
172 Int32 level = m_variable_synchronizer_mng->synchronizationCompareLevel();
173 IParallelMng* pm = m_variable_synchronizer_mng->parallelMng();
174 auto compare_status_list = args.compareStatusList();
175 {
176 Int32 index = 0;
177 for (IVariable* var : args.variables()) {
178 m_pending_variable_name_list.add(var->fullName());
179 VariableSynchronizerEventArgs::CompareStatus s = compare_status_list[index];
180 unsigned char rs = LOCAL_UNKNOWN; // Compare == Unknown;
182 rs = LOCAL_SAME;
184 rs = LOCAL_DIFF;
185 m_pending_compare_status_list.add(rs);
186 ++index;
187 if (level >= 2) {
188 // We perform the reduction here because we want to know immediately if there is a
189 // difference.
190 unsigned char global_rs = pm->reduce(Parallel::ReduceMax, rs);
191 if (global_rs == LOCAL_SAME) {
192 info() << "Synchronize: same values for variable name=" << var->fullName();
193 if (level >= 3)
194 info() << "Stack=" << platform::getStackTrace();
195 }
196 }
197 }
198 }
199}
200
201/*---------------------------------------------------------------------------*/
202/*---------------------------------------------------------------------------*/
203
204void VariableSynchronizerStats::
205flushPendingStats(IParallelMng* pm)
206{
207 Int32 nb_pending = m_pending_variable_name_list.size();
208 Int32 total_nb_pending = pm->reduce(Parallel::ReduceMax, nb_pending);
209 if (total_nb_pending != nb_pending)
210 ARCANE_FATAL("Bad number of pending stats local={0} global={1}", nb_pending, total_nb_pending);
211 pm->reduce(Parallel::ReduceMin, m_pending_compare_status_list);
212 for (Int32 i = 0; i < total_nb_pending; ++i) {
213 unsigned char rs = m_pending_compare_status_list[i];
214 auto& v = m_stats[m_pending_variable_name_list[i]];
215 if (rs == LOCAL_SAME)
216 ++v.m_nb_same;
217 else if (rs == LOCAL_DIFF)
218 ++v.m_nb_different;
219 else
220 ++v.m_nb_unknown;
221 ++v.m_count;
222 }
223 m_pending_variable_name_list.clear();
224 m_pending_compare_status_list.clear();
225}
226
227/*---------------------------------------------------------------------------*/
228/*---------------------------------------------------------------------------*/
229
230/*---------------------------------------------------------------------------*/
231/*---------------------------------------------------------------------------*/
232
233VariableSynchronizerMng::
234VariableSynchronizerMng(IVariableMng* vm)
235: TraceAccessor(vm->traceMng())
236, m_variable_mng(vm)
237, m_parallel_mng(vm->parallelMng())
238, m_stats(new VariableSynchronizerStats(this))
239{
240 if (auto v = Convert::Type<Int32>::tryParseFromEnvironment("ARCANE_AUTO_COMPARE_SYNCHRONIZE", true)) {
241 m_synchronize_compare_level = v.value();
242 // If comparison is active, statistics are also active
243 m_is_doing_stats = m_synchronize_compare_level > 0;
244 }
245 if (auto v = Convert::Type<Int32>::tryParseFromEnvironment("ARCANE_SYNCHRONIZE_STATS", true))
246 m_is_doing_stats = (v.value() != 0);
247}
248
249/*---------------------------------------------------------------------------*/
250/*---------------------------------------------------------------------------*/
251
252VariableSynchronizerMng::
253~VariableSynchronizerMng()
254{
255 delete m_stats;
256}
257
258/*---------------------------------------------------------------------------*/
259/*---------------------------------------------------------------------------*/
260
261void VariableSynchronizerMng::
262initialize()
263{
264 m_stats->init();
265}
266
267/*---------------------------------------------------------------------------*/
268/*---------------------------------------------------------------------------*/
269
271dumpStats(std::ostream& ostr) const
272{
273 if (!m_parallel_mng->isParallel())
274 return;
275 {
276 OStringStream ostr2;
277 Int32 count = m_stats->dumpStats(ostr2());
278 if (count > 0)
279 ostr << ostr2.str();
280 }
281 m_internal_api.dumpStats(ostr);
282}
283
284/*---------------------------------------------------------------------------*/
285/*---------------------------------------------------------------------------*/
286
289{
290 if (isDoingStats())
291 m_stats->flushPendingStats(m_parallel_mng);
292}
293
294/*---------------------------------------------------------------------------*/
295/*---------------------------------------------------------------------------*/
296
303{
304 public:
305
306 using MemoryBufferMap = std::map<MemoryBuffer*, Ref<MemoryBuffer>>;
307 using MapList = std::map<IMemoryAllocator*, MemoryBufferMap>;
308
309 using FreeList = std::map<IMemoryAllocator*, std::stack<Ref<MemoryBuffer>>>;
310
311 public:
312
313 Ref<MemoryBuffer> createSynchronizeBuffer(IMemoryAllocator* allocator);
314 void releaseSynchronizeBuffer(IMemoryAllocator* allocator, MemoryBuffer* v);
315 void dumpStats(std::ostream& ostr) const;
316
317 private:
318
320 MapList m_used_map;
321
323 FreeList m_free_map;
324
326 mutable std::mutex m_mutex;
327};
328
329/*---------------------------------------------------------------------------*/
330/*---------------------------------------------------------------------------*/
331
332/*
333 * \brief Creates or retrieves a buffer.
334 *
335 * It is possible to create buffers with a null allocator. In this
336 * case, the default allocator will be used and therefore for
337 * a given MemoryBuffer, new_buffer.allocator() will not necessarily equal allocator.
338 * You must always use \a allocator.
339 */
340Ref<MemoryBuffer> VariableSynchronizerMng::InternalApi::BufferList::
341createSynchronizeBuffer(IMemoryAllocator* allocator)
342{
343 std::scoped_lock lock(m_mutex);
344
345 auto& free_map = m_free_map;
346 auto x = free_map.find(allocator);
347 Ref<MemoryBuffer> new_buffer;
348 // Checks if a buffer is available in \a free_map.
349 if (x == free_map.end()) {
350 // No buffer associated with this allocator, so we create one
351 new_buffer = MemoryBuffer::create(allocator);
352 }
353 else {
354 auto& buffer_stack = x->second;
355 // If the stack is empty, we create a buffer. Otherwise, we take the first
356 // from the stack.
357 if (buffer_stack.empty()) {
358 new_buffer = MemoryBuffer::create(allocator);
359 }
360 else {
361 new_buffer = buffer_stack.top();
362 buffer_stack.pop();
363 }
364 }
365
366 // Registers the instance in the used list
367 m_used_map[allocator].insert(std::make_pair(new_buffer.get(), new_buffer));
368 return new_buffer;
369}
370
371/*---------------------------------------------------------------------------*/
372/*---------------------------------------------------------------------------*/
373
374void VariableSynchronizerMng::InternalApi::BufferList::
375releaseSynchronizeBuffer(IMemoryAllocator* allocator, MemoryBuffer* v)
376{
377 std::scoped_lock lock(m_mutex);
378
379 auto& main_map = m_used_map;
380 auto x = main_map.find(allocator);
381 if (x == main_map.end())
382 ARCANE_FATAL("Invalid allocator '{0}'", allocator);
383
384 auto& sub_map = x->second;
385 auto x2 = sub_map.find(v);
386 if (x2 == sub_map.end())
387 ARCANE_FATAL("Invalid buffer '{0}'", v);
388
389 Ref<MemoryBuffer> ref_memory = x2->second;
390
391 sub_map.erase(x2);
392
393 m_free_map[allocator].push(ref_memory);
394}
395
396/*---------------------------------------------------------------------------*/
397/*---------------------------------------------------------------------------*/
398
400dumpStats(std::ostream& ostr) const
401{
402 std::scoped_lock lock(m_mutex);
403
405 for (const auto& x : m_used_map)
406 ostr << "SynchronizeBuffer: nb_used_map = " << x.second.size() << "\n";
407
409 for (const auto& x : m_free_map)
410 ostr << "SynchronizeBuffer: nb_free_map = " << x.second.size() << "\n";
411}
412
413/*---------------------------------------------------------------------------*/
414/*---------------------------------------------------------------------------*/
415
416/*---------------------------------------------------------------------------*/
417/*---------------------------------------------------------------------------*/
418
419VariableSynchronizerMng::InternalApi::
420InternalApi(VariableSynchronizerMng* vms)
421: TraceAccessor(vms->traceMng())
422, m_synchronizer_mng(vms)
423, m_buffer_list(new BufferList())
424{
425}
426
427/*---------------------------------------------------------------------------*/
428/*---------------------------------------------------------------------------*/
429
430VariableSynchronizerMng::InternalApi::
431~InternalApi()
432{
433 // The destructor cannot be deleted because 'm_buffer_list' is not
434 // known when the class is defined.
435}
436
437/*---------------------------------------------------------------------------*/
438/*---------------------------------------------------------------------------*/
439
440Ref<MemoryBuffer> VariableSynchronizerMng::InternalApi::
441createSynchronizeBuffer(IMemoryAllocator* allocator)
442{
443 return m_buffer_list->createSynchronizeBuffer(allocator);
444}
445
446/*---------------------------------------------------------------------------*/
447/*---------------------------------------------------------------------------*/
448
449void VariableSynchronizerMng::InternalApi::
450releaseSynchronizeBuffer(IMemoryAllocator* allocator, MemoryBuffer* v)
451{
452 m_buffer_list->releaseSynchronizeBuffer(allocator, v);
453}
454
455/*---------------------------------------------------------------------------*/
456/*---------------------------------------------------------------------------*/
457
458void VariableSynchronizerMng::InternalApi::
459dumpStats(std::ostream& ostr) const
460{
461 m_buffer_list->dumpStats(ostr);
462}
463
464/*---------------------------------------------------------------------------*/
465/*---------------------------------------------------------------------------*/
466
467} // End namespace Arcane
468
469/*---------------------------------------------------------------------------*/
470/*---------------------------------------------------------------------------*/
#define ARCANE_FATAL(...)
Macro throwing a FatalErrorException.
static std::optional< Int32 > tryParseFromEnvironment(StringView s, bool throw_if_invalid)
Interface of the parallelism manager for a subdomain.
Variable manager interface.
Management of a memory buffer.
Output stream linked to a String.
InstanceType * get() const
Associated instance or nullptr if none.
Reference to an instance.
TraceAccessor(ITraceMng *m)
Constructs an accessor via the trace manager m.
TraceMessage info() const
Flow for an information message.
ITraceMng * traceMng() const
Trace manager.
Arguments for the event notifying a variable synchronization.
CompareStatus
Comparison of phantom entity values before/after a synchronization.
@ Different
Different values before and after synchronization.
@ Same
Same values before and after synchronization.
Manages a pool of buffers associated with an allocator.
MapList m_used_map
List of buffers currently in use by allocator.
std::mutex m_mutex
Mutex to protect buffer creation/retrieval.
Variable synchronizer manager.
EventObservable< const VariableSynchronizerEventArgs & > & onSynchronized() override
Event sent at the beginning and end of synchronization.
void dumpStats(std::ostream &ostr) const override
Prints statistics to the stream ostr.
void flushPendingStats() override
Processes pending statistics.
@ ReduceMin
Minimum of values.
@ ReduceMax
Maximum of values.
String getStackTrace()
Returns a string containing the call stack.
-- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature --
std::int32_t Int32
Signed integer type of 32 bits.