The Gaudi Framework  master (50869dff)
Loading...
Searching...
No Matches
AvalancheSchedulerSvc.h
Go to the documentation of this file.
1/***********************************************************************************\
2* (c) Copyright 1998-2026 CERN for the benefit of the LHCb and ATLAS collaborations *
3* *
4* This software is distributed under the terms of the Apache version 2 licence, *
5* copied verbatim in the file "LICENSE". *
6* *
7* In applying this licence, CERN does not waive the privileges and immunities *
8* granted to it by virtue of its status as an Intergovernmental Organization *
9* or submit itself to any jurisdiction. *
10\***********************************************************************************/
11#pragma once
12
13// Local includes
14#include "AlgsExecutionStates.h"
15#include "EventSlot.h"
16#include "FiberManager.h"
17#include "PrecedenceSvc.h"
18
19// Framework include files
27#include <GaudiKernel/Service.h>
28
29// C++ include files
30#include <functional>
31#include <memory>
32#include <queue>
33#include <string>
34#include <string_view>
35#include <thread>
36#include <unordered_map>
37#include <vector>
38
39// External libs
40#include <tbb/concurrent_priority_queue.h>
41#include <tbb/concurrent_queue.h>
42#include <tbb/task_arena.h>
43
44class IAlgorithm;
45
46//---------------------------------------------------------------------------
47
114class AvalancheSchedulerSvc : public extends<Service, IScheduler> {
115
116 friend class AlgTask;
117
118public:
120 using extends::extends;
121
123 StatusCode initialize() override;
124
126 StatusCode finalize() override;
127
129 StatusCode pushNewEvent( EventContext* eventContext ) override;
130
131 // Make multiple events available to the scheduler
132 StatusCode pushNewEvents( std::vector<EventContext*>& eventContexts ) override;
133
135 StatusCode popFinishedEvent( EventContext*& eventContext ) override;
136
138 StatusCode tryPopFinishedEvent( EventContext*& eventContext ) override;
139
141 unsigned int freeSlots() override;
142
144 void dumpState() override;
145
147 virtual StatusCode scheduleEventView( const EventContext* sourceContext, const std::string& nodeName,
148 std::unique_ptr<EventContext> viewContext ) override;
149
153 virtual void recordOccupancy( int samplePeriod, std::function<void( OccupancySnapshot )> callback ) override;
154
155private:
156 StatusCode dumpDataDepsGraphFile( const std::map<std::string, DataObjIDColl>& inDeps,
157 const std::map<std::string, DataObjIDColl>& outDeps ) const;
158
159private:
161 using action = std::function<StatusCode()>;
162
163 enum ActivationState { INACTIVE = 0, ACTIVE = 1, FAILURE = 2 };
164
165 // Occupancy snapshot data
166 std::chrono::duration<int64_t, std::milli> m_snapshotInterval = std::chrono::duration<int64_t, std::milli>::min();
167 std::chrono::system_clock::time_point m_lastSnapshot = std::chrono::system_clock::now();
168 std::function<void( OccupancySnapshot )> m_snapshotCallback;
169
171 this, "ThreadPoolSize", -1,
172 "Size of the global thread pool initialised by TBB; a value of -1 requests to use"
173 "all available hardware threads; -100 requests to bypass TBB executing "
174 "all algorithms in the scheduler's thread." };
176 this, "maxParallelismExtra", 0,
177 "Allows to add some extra threads to the maximum parallelism set in TBB"
178 "The TBB max parallelism is set as: ThreadPoolSize + maxParallelismExtra + 1" };
179 Gaudi::Property<std::string> m_whiteboardSvcName{ this, "WhiteboardSvc", "EventDataSvc", "The whiteboard name" };
181 this, "SimulateExecution", false,
182 "Flag to perform single-pass simulation of execution flow before the actual execution" };
184 "The following modes are currently available: PCE, COD, DRE, E" };
185 Gaudi::Property<bool> m_dumpIntraEventDynamics{ this, "DumpIntraEventDynamics", false,
186 "Dump intra-event concurrency dynamics to csv file" };
188 this, "NumOffloadThreads", 0,
189 "Number of threads to use for CPU portion of asynchronous algorithms. Asynchronous algorithms must be flagged "
190 "and use Boost Fiber functionality to suspend while waiting for offloaded work." };
191 Gaudi::Property<bool> m_checkDeps{ this, "CheckDependencies", false,
192 "Runtime check of Algorithm Input Data Dependencies" };
193 Gaudi::Property<bool> m_checkOutput{ this, "CheckOutputUsage", false,
194 "Runtime check of Algorithm Output Data usage" };
196 this,
197 "CheckOutputUsageIgnoreList",
198 {},
199 "Ignore outputs of the Algorithms of this name when doing the check",
200 "OrderedSet<std::string>" };
201
203 "Attribute unmet input dependencies to this DataLoader Algorithm" };
204
205 Gaudi::Property<bool> m_enableCondSvc{ this, "EnableConditions", false, "Enable ConditionsSvc" };
206
207 Gaudi::Property<bool> m_showDataDeps{ this, "ShowDataDependencies", true,
208 "Show the INPUT and OUTPUT data dependencies of Algorithms" };
209
210 Gaudi::Property<bool> m_showDataFlow{ this, "ShowDataFlow", false,
211 "Show the configuration of DataFlow between Algorithms" };
212
213 Gaudi::Property<bool> m_showControlFlow{ this, "ShowControlFlow", false,
214 "Show the configuration of all Algorithms and Sequences" };
215
216 Gaudi::Property<bool> m_verboseSubSlots{ this, "VerboseSubSlots", false, "Dump algorithm states for all sub-slots" };
217
219 this, "DataDepsGraphFile", "",
220 "Name of the output file (.dot, .md or .graphml extensions allowed) containing the data dependency graph "
221 "for some selected Algorithms" };
222
224 this, "DataDepsGraphAlgPattern", ".*",
225 "Regex pattern for selecting desired Algorithms by name, whose data dependency has to be included in the data "
226 "deps graph" };
227
229 this, "DataDepsGraphObjectPattern", ".*",
230 "Regex pattern for selecting desired input or output by their full key" };
231
232 // Utils and shortcuts ----------------------------------------------------
233
235 void activate();
236
239
241 std::atomic<ActivationState> m_isActive{ INACTIVE };
242
244 std::thread m_thread;
245
247 inline unsigned int algname2index( const std::string& algoname ) { return m_algname_index_map[algoname]; }
248
250 std::unordered_map<std::string, unsigned int> m_algname_index_map;
251
253 inline const std::string& index2algname( unsigned int index ) { return m_algname_vect[index]; }
254
256 std::vector<std::string> m_algname_vect;
257
260
263
265 std::vector<EventSlot> m_eventSlots;
266
268 std::atomic_int m_freeSlots{ 0 };
269
271 tbb::concurrent_bounded_queue<EventContext*> m_finishedEvents;
272
275
278
280 unsigned int m_algosInFlight = 0;
281
282 // States management ------------------------------------------------------
283
286
287 // Update algorithm state and, optionally, revise states of other downstream algorithms
288 StatusCode revise( unsigned int iAlgo, EventContext* contextPtr, AState state, bool iterate = false );
289
291 struct TaskSpec;
293 StatusCode signoff( const TaskSpec& );
294
296 bool isStalled( const EventSlot& ) const;
298 void eventFailed( EventContext* eventContext );
299
301 void dumpSchedulerState( int iSlot );
302
303 // Algos Management -------------------------------------------------------
304
307
308 // Actions management -----------------------------------------------------
309
311 tbb::concurrent_bounded_queue<action> m_actionsQueue;
312
314 struct TaskSpec {
317 TaskSpec( IAlgorithm* algPtr, unsigned int algIndex, const std::string& algName, unsigned int algRank,
318 bool asynchronous, int slotIndex, EventContext* eventContext )
319 : algPtr( algPtr )
320 , algIndex( algIndex )
321 , algName( algName )
322 , algRank( algRank )
325 , contextPtr( eventContext ) {}
326
327 TaskSpec( const TaskSpec& ) = default;
329 TaskSpec& operator=( const TaskSpec& ) = delete;
331 TaskSpec( TaskSpec&& ) = default;
333 TaskSpec& operator=( TaskSpec&& ) = default;
334
335 IAlgorithm* algPtr{ nullptr };
336 unsigned int algIndex{ 0 };
337 std::string_view algName;
338 unsigned int algRank{ 0 };
339 bool asynchronous{ false };
340 int slotIndex{ 0 };
342 };
343
346 bool operator()( const TaskSpec& i, const TaskSpec& j ) const { return ( i.algRank < j.algRank ); }
347 };
348
350 tbb::concurrent_priority_queue<TaskSpec, AlgQueueSort> m_scheduledQueue;
351 tbb::concurrent_priority_queue<TaskSpec, AlgQueueSort> m_scheduledAsynchronousQueue;
352 std::queue<TaskSpec> m_retryQueue;
353
354 // Prompt the scheduler to call updateStates
355 std::atomic<bool> m_needsUpdate{ true };
356
357 // ------------------------------------------------------------------------
358
359 // Service for thread pool initialization
361 tbb::task_arena* m_arena{ nullptr };
362 std::unique_ptr<FiberManager> m_fiberManager{ nullptr };
363
365
366public:
367 // get next schedule-able TaskSpec
368 bool next( TaskSpec& ts, bool asynchronous ) {
369 if ( asynchronous ) { return m_scheduledAsynchronousQueue.try_pop( ts ); }
370 return m_scheduledQueue.try_pop( ts );
371 }
372};
State
Execution states of the algorithms Must have contiguous integer values 0, 1... N.
StatusCode pushNewEvent(EventContext *eventContext) override
Make an event available to the scheduler.
Gaudi::Property< std::vector< std::string > > m_checkOutputIgnoreList
SmartIF< IThreadPoolSvc > m_threadPoolSvc
Gaudi::Property< std::string > m_useDataLoader
void dumpState() override
Dump scheduler state for all slots.
void activate()
Activate scheduler.
Gaudi::Property< std::string > m_optimizationMode
bool next(TaskSpec &ts, bool asynchronous)
StatusCode popFinishedEvent(EventContext *&eventContext) override
Blocks until an event is available.
Gaudi::Property< bool > m_dumpIntraEventDynamics
std::chrono::system_clock::time_point m_lastSnapshot
std::vector< std::string > m_algname_vect
Vector to bookkeep the information necessary to the index2name conversion.
Gaudi::Property< int > m_threadPoolSize
StatusCode finalize() override
Finalise.
tbb::concurrent_priority_queue< TaskSpec, AlgQueueSort > m_scheduledQueue
Queues for scheduled algorithms.
std::function< void(OccupancySnapshot)> m_snapshotCallback
std::queue< TaskSpec > m_retryQueue
Gaudi::Property< bool > m_verboseSubSlots
tbb::concurrent_bounded_queue< action > m_actionsQueue
Queue where closures are stored and picked for execution.
unsigned int algname2index(const std::string &algoname)
Convert a name to an integer.
SmartIF< ICondSvc > m_condSvc
A shortcut to service for Conditions handling.
AlgsExecutionStates::State AState
bool isStalled(const EventSlot &) const
Check if scheduling in a particular slot is in a stall.
SmartIF< IAlgExecStateSvc > m_algExecStateSvc
Algorithm execution state manager.
StatusCode pushNewEvents(std::vector< EventContext * > &eventContexts) override
StatusCode revise(unsigned int iAlgo, EventContext *contextPtr, AState state, bool iterate=false)
tbb::concurrent_bounded_queue< EventContext * > m_finishedEvents
Queue of finished events.
StatusCode deactivate()
Deactivate scheduler.
unsigned int m_algosInFlight
Number of algorithms presently in flight.
Gaudi::Property< std::string > m_dataDepsGraphObjectPattern
Gaudi::Property< bool > m_showDataFlow
StatusCode schedule(TaskSpec &&)
SmartIF< IPrecedenceSvc > m_precSvc
A shortcut to the Precedence Service.
Gaudi::Property< bool > m_checkDeps
std::chrono::duration< int64_t, std::milli > m_snapshotInterval
Gaudi::Property< std::string > m_dataDepsGraphFile
SmartIF< IAlgResourcePool > m_algResourcePool
Cache for the algorithm resource pool.
Gaudi::Property< bool > m_showControlFlow
Gaudi::Property< bool > m_simulateExecution
Gaudi::Property< std::string > m_whiteboardSvcName
StatusCode tryPopFinishedEvent(EventContext *&eventContext) override
Try to fetch an event from the scheduler.
std::unordered_map< std::string, unsigned int > m_algname_index_map
Map to bookkeep the information necessary to the name2index conversion.
std::atomic< bool > m_needsUpdate
virtual StatusCode scheduleEventView(const EventContext *sourceContext, const std::string &nodeName, std::unique_ptr< EventContext > viewContext) override
Method to inform the scheduler about event views.
Gaudi::Property< int > m_maxParallelismExtra
StatusCode signoff(const TaskSpec &)
The call to this method is triggered only from within the AlgTask.
std::function< StatusCode()> action
Gaudi::Property< std::string > m_dataDepsGraphAlgoPattern
Gaudi::Property< int > m_numOffloadThreads
Gaudi::Property< bool > m_checkOutput
std::atomic< ActivationState > m_isActive
Flag to track if the scheduler is active or not.
StatusCode initialize() override
Initialise.
Gaudi::Property< bool > m_enableCondSvc
virtual void recordOccupancy(int samplePeriod, std::function< void(OccupancySnapshot)> callback) override
Sample occupancy at fixed interval (ms) Negative value to deactivate, 0 to snapshot every change Each...
void eventFailed(EventContext *eventContext)
Method to execute if an event failed.
std::atomic_int m_freeSlots
Atomic to account for asyncronous updates by the scheduler wrt the rest.
StatusCode dumpDataDepsGraphFile(const std::map< std::string, DataObjIDColl > &inDeps, const std::map< std::string, DataObjIDColl > &outDeps) const
unsigned int freeSlots() override
Get free slots number.
void dumpSchedulerState(int iSlot)
Dump the state of the scheduler.
std::unique_ptr< FiberManager > m_fiberManager
SmartIF< IHiveWhiteBoard > m_whiteboard
A shortcut to the whiteboard.
tbb::concurrent_priority_queue< TaskSpec, AlgQueueSort > m_scheduledAsynchronousQueue
StatusCode iterate()
Loop on all slots to schedule DATAREADY algorithms and sign off ready events.
Gaudi::Property< bool > m_showDataDeps
std::thread m_thread
The thread in which the activate function runs.
const std::string & index2algname(unsigned int index)
Convert an integer to a name.
std::vector< EventSlot > m_eventSlots
Vector of events slots.
This class represents an entry point to all the event specific data.
Implementation of property with value of concrete type.
Definition Property.h:35
The IAlgorithm is the interface implemented by the Algorithm base class.
Definition IAlgorithm.h:37
Small smart pointer class with automatic reference counting for IInterface.
Definition SmartIF.h:28
This class is used for returning status codes from appropriate routines.
Definition StatusCode.h:64
Base class used to extend a class implementing other interfaces.
Definition extends.h:19
Comparison operator to sort the queues.
bool operator()(const TaskSpec &i, const TaskSpec &j) const
Struct to hold entries in the alg queues.
TaskSpec & operator=(const TaskSpec &)=delete
Assignment operator.
TaskSpec(IAlgorithm *algPtr, unsigned int algIndex, const std::string &algName, unsigned int algRank, bool asynchronous, int slotIndex, EventContext *eventContext)
TaskSpec(const TaskSpec &)=default
Copy constructor (to keep a lambda capturing a TaskSpec storable as a std::function value).
TaskSpec & operator=(TaskSpec &&)=default
Move assignment.
TaskSpec(TaskSpec &&)=default
Move constructor.
Class representing an event slot.
Definition EventSlot.h:23