e453a5e18b2c7712c6024b3032c470537cc1b4d3
[alexxy/gromacs.git] / src / gromacs / gpu_utils / gpuregiontimer.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2016,2017, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 /*! \libinternal \file
37  *  \brief Defines the GPU region timer implementation/wrapper classes.
38  *  The implementations live in gpuregiontimer.cuh for CUDA and gpuregiontimer_ocl.h for OpenCL.
39  *
40  *  \author Aleksei Iupinov <a.yupinov@gmail.com>
41  */
42
43 #ifndef GMX_GPU_UTILS_GPUREGIONTIMER_H
44 #define GMX_GPU_UTILS_GPUREGIONTIMER_H
45
46 #include <string>
47
48 #include "gromacs/utility/gmxassert.h"
49
50 //! Debug GPU timers in debug builds only
51 #if defined(NDEBUG)
52 static const bool c_debugTimerState = false;
53 #else
54 static const bool c_debugTimerState = true;
55 #endif
56
57 /*! \libinternal \brief
58  * Enumeration of possible GPU build-paths.
59  * \todo Move somewhere general?
60  */
61 enum class GpuFramework
62 {
63     CUDA,
64     OpenCL
65 };
66
67 /*! \libinternal \brief
68  * GPU build-path traits such as types.
69  * \todo Move somewhere general?
70  */
71 template <GpuFramework> struct GpuTraits
72 {
73     using CommandStream      = void; //!< GPU command stream
74     using CommandEvent       = void; //!< Single command call timing event - used in OpenCL
75 };
76
77 /*! \libinternal \brief
78  * This is a GPU region timing implementation interface.
79  * It should provide methods for measuring the last timespan.
80  * Copying/assignment is disabled since the underlying timing events are owned by this.
81  */
82 template <GpuFramework framework> class GpuRegionTimerImpl
83 {
84     //! Short-hands
85     using CommandStream = typename GpuTraits<framework>::CommandStream;
86     using CommandEvent  = typename GpuTraits<framework>::CommandEvent;
87
88     public:
89
90         GpuRegionTimerImpl()  = default;
91         ~GpuRegionTimerImpl() = default;
92         //! No copying
93         GpuRegionTimerImpl(const GpuRegionTimerImpl &)       = delete;
94         //! No assignment
95         GpuRegionTimerImpl &operator=(GpuRegionTimerImpl &&) = delete;
96         //! Moving is disabled but can be considered in the future if needed
97         GpuRegionTimerImpl(GpuRegionTimerImpl &&)            = delete;
98
99         /*! \brief Will be called before the region start. */
100         inline void openTimingRegion(CommandStream) = 0;
101         /*! \brief Will be called after the region end. */
102         inline void closeTimingRegion(CommandStream) = 0;
103         /*! \brief Resets any internal state if needed */
104         inline void reset() = 0;
105         /*! \brief Returns the last measured region timespan (in milliseconds) and calls reset() */
106         inline double getLastRangeTime() = 0;
107         /*! \brief Returns a new raw timing event
108          * for passing into individual GPU API calls
109          * within the region if the API requires it (e.g. on OpenCL). */
110         inline CommandEvent *fetchNextEvent() = 0;
111 };
112
113 /*! \libinternal \brief
114  * This is a GPU region timing wrapper class.
115  * It allows for host-side tracking of the accumulated execution timespans in GPU code
116  * (measuring kernel or transfers duration).
117  * It also partially tracks the correctness of the timer state transitions,
118  * as far as current implementation allows (see TODO in getLastRangeTime() for a disabled check).
119  * Internally it uses GpuRegionTimerImpl for measuring regions.
120  */
121 template <GpuFramework framework> class GpuRegionTimerWrapper
122 {
123     //! Short-hands
124     using CommandStream = typename GpuTraits<framework>::CommandStream;
125     using CommandEvent  = typename GpuTraits<framework>::CommandEvent;
126     //! The timer state used for debug-only assertions
127     enum class TimerState
128     {
129         Idle,
130         Recording,
131         Stopped
132     } debugState_ = TimerState::Idle;
133
134     //! The number of times the timespan has been measured
135     unsigned int                  callCount_ = 0;
136     //! The accumulated duration of the timespans measured (milliseconds)
137     double                        totalMilliseconds_ = 0.0;
138     //! The underlying region timer implementation
139     GpuRegionTimerImpl<framework> impl_;
140
141     public:
142
143         /*! \brief
144          * To be called before the region start.
145          *
146          * \param[in] s   The GPU command stream where the event being measured takes place.
147          */
148         void openTimingRegion(CommandStream s)
149         {
150             if (c_debugTimerState)
151             {
152                 std::string error = "GPU timer should be idle, but is " + std::string((debugState_ == TimerState::Stopped) ? "stopped" : "recording") + ".";
153                 GMX_ASSERT(debugState_ == TimerState::Idle, error.c_str());
154                 debugState_ = TimerState::Recording;
155             }
156             impl_.openTimingRegion(s);
157         }
158         /*! \brief
159          * To be called after the region end.
160          *
161          * \param[in] s   The GPU command stream where the event being measured takes place.
162          */
163         void closeTimingRegion(CommandStream s)
164         {
165             if (c_debugTimerState)
166             {
167                 std::string error = "GPU timer should be recording, but is " + std::string((debugState_ == TimerState::Idle) ? "idle" : "stopped") + ".";
168                 GMX_ASSERT(debugState_ == TimerState::Recording, error.c_str());
169                 debugState_ = TimerState::Stopped;
170             }
171             callCount_++;
172             impl_.closeTimingRegion(s);
173         }
174         /*! \brief
175          * Accumulates the last timespan of all the events used into the the total duration,
176          * and resets the internal timer state.
177          * To be called after closeTimingRegion() and the command stream of the event having been synchronized.
178          * \returns The last timespan (in milliseconds).
179          */
180         double getLastRangeTime()
181         {
182             if (c_debugTimerState)
183             {
184                 /* The assertion below is commented because it is currently triggered on a special case:
185                  * the early return before the local non-bonded kernel launch if there is nothing to do.
186                  * This can be reproduced in OpenCL build by running
187                  * mdrun-mpi-test -ntmpi 2 --gtest_filter=*Empty*
188                  * Similarly, the GpuRegionTimerImpl suffers from non-nullptr
189                  * cl_event conditionals which ideally should only be asserts.
190                  * TODO: improve internal task scheduling, re-enable the assert, turn conditionals into asserts
191                  */
192                 /*
193                    std::string error = "GPU timer should be stopped, but is " + std::string((debugState_ == TimerState::Idle) ? "idle" : "recording") + ".";
194                    GMX_ASSERT(debugState_ == TimerState::Stopped, error.c_str());
195                  */
196                 debugState_ = TimerState::Idle;
197             }
198             double milliseconds = impl_.getLastRangeTime();
199             totalMilliseconds_ += milliseconds;
200             return milliseconds;
201         }
202         /*! \brief Resets the implementation and total time/call count to zeroes. */
203         void reset()
204         {
205             if (c_debugTimerState)
206             {
207                 debugState_ = TimerState::Idle;
208             }
209             totalMilliseconds_ = 0.0;
210             callCount_         = 0;
211             impl_.reset();
212         }
213         /*! \brief Gets total time recorded (in milliseconds). */
214         double getTotalTime() const
215         {
216             return totalMilliseconds_;
217         }
218         /*! \brief Gets total call count recorded. */
219         unsigned int getCallCount() const
220         {
221             return callCount_;
222         }
223         /*! \brief
224          * Gets a pointer to a new timing event for passing into individual GPU API calls
225          * within the region if they require it (e.g. on OpenCL).
226          * \returns The pointer to the underlying single command timing event.
227          */
228         CommandEvent *fetchNextEvent()
229         {
230             if (c_debugTimerState)
231             {
232                 std::string error = "GPU timer should be recording, but is " + std::string((debugState_ == TimerState::Idle) ? "idle" : "stopped") + ".";
233                 GMX_ASSERT(debugState_ == TimerState::Recording, error.c_str());
234             }
235             return impl_.fetchNextEvent();
236         }
237 };
238
239 #endif