Skip to content

Time device actions asynchronously with CUDA/HIP events - #2709

Merged
sethrj merged 9 commits into
celeritas-project:developfrom
sethrj-bot:async-action-timers
Dec 3, 2026
Merged

sethrj merged 9 commits into
celeritas-project:developfrom
sethrj-bot:async-action-timers

Conversation

@sethrj-bot

@sethrj-bot sethrj-bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Builds on #2711 (merged), which added the DeviceEvent timing and StreamTimer used here. This branch is rebased onto develop 40ae2ac, so its diff now contains only the action-timer changes.

Action timers on device no longer synchronize the stream after every action. Core (ActionSequence) and optical (optical::Transporter) action times are now measured with CUDA/HIP events recorded asynchronously on the state's stream. Host timing still uses the CPU Stopwatch and behaves as before.

Built and tested on CPU and on an NVIDIA V100 (CUDA). The new device tests pass, and the full GPU ctest has no regressions compared with upstream/develop. See "GPU test results" below. After the rebase the tree is byte-identical to the previously tested 1370f5b (develop ac9e26d plus #2711), so those results still apply. The review changes in 8f9f368 were tested on a P100 (release-orange-celer-cuda, sm_60): 194/197 related GPU and CPU tests pass. The 3 failures (StepperGeant:TestEm3Msc, StepperGeant:TestEm15FieldMsc, OpticalCollector, all device step/photon counts) also fail on the same node with develop db9a1d4, so they come from the P100 and not from this PR.

Design

The DeviceEvent timing API and StreamTimer are described in #2711. The action timer constructs one StreamTimer(device, sid) per state and calls start()/stop(TimerId) around each action.

ActionTimesState<M> (new, celeritas/action/ActionTimesState.{hh,cc})

These live in celeritas/action so that the action loop doesn't depend on celeritas/user.

  • ActionTimesStateBase holds the private accumulated times. Its memory-space-independent reads are get_times() (flush pending, return the totals without resetting) and exchange_times() (flush, return, reset), built on a private virtual flush_pending. This is the same pattern as GeneratorStateBase. The class docs list the callers of each read and why both exist.
  • The recording functions begin_step/start/stop are public pure virtuals on the base. ActionTimesState<M> is specialized on the memory space and implements them as final (both specializations are final), so callers holding the derived type don't need virtual dispatch.
    • Host: a CPU Stopwatch whose time is added immediately, as before.
    • Device: owns a StreamTimer and the StreamId, and looks up the stream on each call. begin_step flushes the previous step's intervals and records a start marker. The flush syncs only the last event of the previous step. Both drivers wait on the step counters before starting the next step, and that counter copy is enqueued after the actions, so in practice the flush never blocks.
  • Drivers pass the state directly as a nullable ActionTimesStatePtr<M> (ObserverPtr<ActionTimesState<M>, MemSpace::host>, in ActionLoop.hh); null means timing is disabled. The driver gets the typed state with ActionTimes::state<M>(aux) and calls begin_step() once per step. (An earlier ActionTimer<M> handle was removed in review.)
  • get_action_times now takes AuxStateVec& (in ActionTimes, ActionSequence, optical::Transporter and OpticalCollector) so that it can flush. This is where the final step's intervals get read, and it blocks only for the last recorded event. Callers pass state().aux(), using a new mutable StepperInterface::state() overload that replaces sp_state(), so the accel GetActionTime() const signatures are unchanged. LocalTransporter::GetState() no longer needs its const_cast.
  • ActionTimes::clear_action_times is replaced by exchange_action_times, which flushes, returns, and resets the times. optical::Transporter::exchange_action_times forwards to it.

Shared step loop (celeritas/action/ActionLoop.hh)

  • execute_step_actions(groups, params, state, ActionTimesStatePtr<M>, skip, post) holds the common body that ActionSequence::step and optical::Transporter::transport_impl used to duplicate: loop over step actions, profiling range, action.step, timer stop, post hook.
  • execute_end_transport_actions does the same for end-of-transport actions.
  • The core sequence passes its host single-slot skip_post_action predicate and a post hook that runs the StatusChecker (when enabled) and the optional sync_stream sync.
  • After the checker runs, the post hook calls timer.start() so checker work is not counted against the next action. Previously the timed and untimed paths were two copies of the loop; now there is one.

sync_stream semantics

inp::DeviceDebug::sync_stream was documented as "synchronize after every kernel launch". In practice it only turned on action timers, and those were what synchronized. Now action timers and stream sync are independent:

  • New ActionSequence::Options::sync_stream and optical::Transporter::Input::sync_stream. They are set from inp::DeviceDebug in setup::problem, the latter through OpticalCollector::Input and OpticalLaunchAction, and they sync the stream after each core or optical step action. The standalone inp::OpticalProblem has no DeviceDebug yet.
  • sync_stream no longer enables action timers. Only diagnostics.timers.action (or running on host) does, for both the core sequence and the in-core optical offload.
  • celer-sim (RunnerInput.cc) and accel (SetupOptions.cc) no longer set sync_stream = action_times, so asking for action times no longer brings back the per-action sync.

Timing semantics (documented in inp::Timers, StreamTimer, Stepper::async)

On device, an action's time is the elapsed device time from the previous marker to the marker after that action's launches. It includes kernel execution and any device idle time while waiting for the host to launch the next action. Host-side time that overlaps earlier device work is hidden, and it no longer includes forced synchronization overhead. Step times (inp::Timers::step) are unchanged: host wall clock, synchronized at the end of each device step. Converting them is a follow-up, recorded as a \todo on ActionSequence::step; so is a dedicated time type for query_elapsed_time and StreamTimer.

Tests

  • corecel/sys/DeviceEvent.test.cc, new timing test (device only): a 50 ms host function between timed events gives an elapsed time of at least 45 ms; back-to-back events give a small non-negative time; query_elapsed_time on a pending event throws (DebugError with debug assertions, else RuntimeError), and use_timing() is checked on timed, untimed, and null events.
  • corecel/sys/StreamTimer.test.cc (new):
    • device covers interleaved timer IDs, chained stops, an untimed 100 ms gap that must be excluded, that recording doesn't block, flush/clear, event reuse, and flushing a shorter sequence after a longer one (it must wait on the latest marker, not events_.back()). With debug assertions it also checks that an undersized accumulator throws (not run yet: the GPU build is CELERITAS_DEBUG=OFF).
  • celeritas/global/Stepper.test.cc, new ActionTimesTest.{host,device}: warmup isn't timed; get_action_times works right after async() while a step is still running; times stay the same across repeated (flushing) reads and only increase across steps; exchange_action_times returns the same times and then empties them; expected actions have times > 0.
    • host passes on CPU.
    • device passes on the V100.
  • Existing optical/Generator host tests check that the optical action times are > 0, and they still pass. Their :gpu variants exercise the async optical path, and they pass on the V100.

Build/test status (CPU host)

  • release-orange-cuda (CUDA 70;80;90;120, OpenMP, -Werror): full build OK. CPU ctest with CELER_DISABLE_DEVICE=1: 458/459 pass. The one failure, celeritas/Json, is unrelated and also fails on upstream/develop: it expects _version "0.7.0" but the tree is 0.7.1-rc. ActionTimesTest.host passes; the device tests are skipped. (CPU numbers predate the review changes; the review commits were tested on the GPU build below, including its host tests.)
  • No-device configuration: the preset fails to configure because of an environment problem in the nodevice spack view (ROOT component FFTW missing). All 8 touched .cc files were compiled individually with that build's compile_commands.json flags (-Werror), and they pass.
  • HIP: DeviceEvent.cc and StreamTimer.cc compile with the release-orange-hip flags.

GPU test results (V100, release-orange-cuda)

  • After the third review round (a183d3d): warning-free build. Targeted ctest (DeviceEvent|StreamTimer|Stepper|optical/(Generator|Detector)|accel, 147 tests) passes 147/147, including DeviceEventTest.timing, StreamTimerTest.device, and ActionTimesTest.{host,device}. app/celer-sim|optical/Runner|optical/OpticalCollector fail only on optical/OpticalCollector and app/celer-sim:lar:gpu, the two known upstream failures listed below, with the same messages.
  • After the second review round (4c1ac58): the build is warning-free. Targeted ctest (DeviceEvent|StreamTimer|Stepper|optical|accel, 181 tests) passes except optical/OpticalCollector and app/celer-sim:lar:gpu, the two known upstream failures listed below. StreamTimerTest.device and ActionTimesTest.{host,device} pass. 87498d7 (stream ID lookup, \todo notes) builds cleanly; its targeted test run was stopped early on request, so it was not re-run.

Results from 9579d4b (first review round):

  • New device tests pass:
    • DeviceEventTest.timing
    • StreamTimerTest.device
    • ActionTimesTest.device
    • the rest of corecel/sys/{DeviceEvent,StreamTimer} and celeritas/global/Stepper
  • All optical/Generator*:gpu, optical/Detector:gpu, and accel *:gpu:{serial,mt,task} integration tests pass.
  • celer-sim lar-sphere-gpu with action times on reports 36 actions, all with time > 0, including the optical actions (optical::generate, optical::along-step, ...).
  • Full ctest -j32 gives 507/511 passing. I rebuilt the merge base (upstream/develop 27b38d2) and confirmed all 4 failures there, so none are caused by this PR:
    • celeritas/Json: version string, as on CPU.
    • optical/OpticalCollector device_{distributions,generate}: reference counts differ on this GPU (403128 vs 416523 photons). The values are identical on upstream and are deterministic from run to run.
    • app/celer-sim:lar:gpu: the simple-driver.py:219 assertion len(steps[0]) == num_step_iterations[0] fails on upstream too. Step times accumulate over the 4 events on one stream (16 entries), but the check compares against a single event (4 iterations).
    • celeritas/global/Stepper SimpleComptonTest.fail_initialize (host): fails only when the machine is oversubscribed. It fails 20/20 with OMP_NUM_THREADS=4 taskset -c <one cpu> and passes 40/40 otherwise. The baseline shows the same behavior. The cause is the order of atomic_add in make_track_id, which changes the expected track_id.
  • Gotcha: CELERITAS_DISABLE_DEVICE is cached when CMake configures. If you configure with CELER_DISABLE_DEVICE=1 set, every :gpu g4 test stays disabled even after you unset it. Reconfigure with cmake -U CELERITAS_DISABLE_DEVICE.

Remaining GPU checks

To reproduce:

ctest -R 'corecel/sys/(DeviceEvent|StreamTimer)|celeritas/global/Stepper$|optical/Generator.*:gpu'

Then run celer-sim with "action_times": true (and optionally with sync_stream) and compare the action times against the previous synchronous numbers. Expect similar kernel-dominated times and a lower total wall time.

Things to watch:
Items 1–3 were verified on CUDA (V100). They are still unchecked on HIP. Items 4–5 have shown no failures, but they have not been profiled.

  1. DeviceEventTest.timing ✅ CUDA: the EXPECT_THROW on a pending event assumes cudaEventElapsedTime returns cudaErrorNotReady, which CELER_DEVICE_API_CALL throws and clears. If HIP reports this differently, drop that check.
  2. StreamTimerTest.device ✅ CUDA: timing comes from host functions (launch_host_func) that sleep. Tolerances are 25% relative, and the record loop must take under 100 ms. If cudaLaunchHostFunc turns out to serialize the host in a way that breaks the "doesn't block" check, loosen or remove it.
  3. ActionTimesTest.device ✅ CUDA (all labels > 0): if any listed label has zero time on device, the action was probably skipped or launched nothing. Adjust the list instead of the implementation.
  4. Stream lifetime: ActionTimesState<device> looks up device().stream(stream_id) on each call, and keeps only the StreamId, because tests call create_streams again. Events recorded on an old stream are still valid for cudaEventElapsedTime.
  5. Optical: transport_impl calls begin_step() on the action times every optical step, so each step flushes the previous step's events. That should be free, since the counters were already waited on. Check with nsys that no extra cudaEventSynchronize stalls show up between optical steps.

🤖 (Claude Code, Opus 5.5)

🤖 Generated with Claude Code

@github-actions github-actions Bot added the ai-generated Generated and managed by an agent/bot, not a human. label Nov 29, 2026
@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Test summary

 8 214 files  13 532 suites   14m 45s ⏱️
 2 559 tests  2 501 ✅  58 💤 0 ❌
48 166 runs  47 859 ✅ 307 💤 0 ❌

Results for commit ebb6f73.

♻️ This comment has been updated with latest results.

@sethrj
sethrj marked this pull request as ready for review November 29, 2026 03:43
@sethrj
sethrj marked this pull request as draft November 29, 2026 11:39

@sethrj sethrj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some comments so far

Comment thread src/celeritas/optical/Transporter.cc Resolved
Comment thread src/celeritas/inp/Control.hh Resolved
Comment thread src/celeritas/global/Stepper.cc Resolved
Comment thread src/celeritas/inp/Control.hh Resolved
Comment thread src/corecel/sys/DeviceEvent.hh Resolved
Comment thread src/corecel/sys/DeviceEvent.cc Resolved
Comment thread src/corecel/sys/DeviceEvent.cc Resolved
Comment thread src/corecel/sys/DeviceEvent.hh Resolved
Comment thread src/celeritas/action/ActionLoop.hh Resolved
Comment thread src/celeritas/user/ActionTimes.cc Resolved
Comment thread src/celeritas/user/ActionTimes.hh Resolved
Comment thread src/celeritas/user/ActionTimes.hh Resolved
Comment thread src/corecel/sys/StreamTimer.hh Resolved
Comment thread src/corecel/sys/StreamTimer.hh Resolved
Comment thread src/corecel/sys/StreamTimer.hh Resolved
Comment thread src/corecel/sys/StreamTimer.hh Resolved
Comment thread src/celeritas/action/ActionTimer.hh Resolved
Comment thread src/celeritas/action/ActionTimer.hh Resolved
Comment thread src/celeritas/action/ActionTimer.hh Resolved
Comment thread src/celeritas/action/ActionTimer.hh Resolved
Comment thread src/corecel/sys/StreamTimer.cc Resolved
Comment thread src/corecel/sys/StreamTimer.cc Resolved
Comment thread src/corecel/sys/DeviceEvent.hh Resolved
Comment thread src/corecel/sys/StreamTimer.hh Resolved
Comment thread src/corecel/sys/StreamTimer.cc Resolved
@sethrj sethrj added enhancement New feature or request core Software engineering infrastructure (corecel) labels Nov 30, 2026
elliottbiondo pushed a commit to osanstrong/celeritas that referenced this pull request Dec 1, 2026
…ect#2711)

* Add device event timing and asynchronous stream timer

Add DeviceEvent::query_elapsed_time and a StreamTimer that records a
chain of timing events on a stream without synchronizing, and later
flushes the elapsed intervals into per-ID accumulators. This is split out
of celeritas-project#2709 so it can be reviewed separately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Move stream timer layout notes to flush docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Disable stream timer test when GPU is disabled

* Apply device requirement to stream timer test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Bind stream timer to a single stream at construction

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Seth R Johnson <johnsonsr@ornl.gov>
sethrj-bot and others added 6 commits December 1, 2026 11:51
Add a timing option and elapsed_since to DeviceEvent, and a StreamTimer
that records a chain of timed events on a stream and reads them lazily.
ActionTimesState holds a StreamTimer for device states; ActionTimer
wraps the host stopwatch and the device timer, flushing the previous
step's intervals at the start of the next step (after the host has
already waited on the step counters).

Factor the step-action loop shared by ActionSequence and
optical::Transporter into detail::execute_step_actions and
execute_end_transport_actions.

Since action timers no longer synchronize, keep the documented
DeviceDebug::sync_stream behavior with an explicit ActionSequence
option, and stop the apps from enabling sync_stream just to get action
times.

Device code is built but untested (no GPU available in this session).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Replace DeviceEvent::Timing and elapsed_since with a private bool
  constructor, DeviceEvent::with_timing, use_timing(), and a free
  non-synchronizing elapsed_time(start, stop)
- Move ActionLoop out of global/detail to celeritas/action so optical
  code doesn't use another package's detail; note the rule in AGENTS.md
- Stop enabling action timers from DeviceDebug::sync_stream
- Apply sync_stream to in-core optical offload actions as well

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Replace the StreamTimer integer index and start-marker sentinel with a
  TimerId; a StreamTimer now requires an active device (no null mode)
- Move ActionTimer and the timer state to celeritas/action/ActionTimer.hh
  so that action code does not depend on celeritas/user
- Specialize ActionTimesState and ActionTimer on the memory space, with a
  common ActionTimesStateBase for reading times
- Replace ActionTimes::clear_action_times with exchange_action_times,
  which includes pending device times instead of discarding them
- Document the remaining ActionLoop parameters, the final flush, and the
  StreamTimer event lifetime

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Store the stream ID rather than a stream reference in the device action
times state, since device streams may be recreated during the state's
lifetime. Document the step-timer and time-type follow-ups as todos.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Move the action times state into celeritas/action/ActionTimesState.hh
  and make the accumulated times private
- Replace the specialized ActionTimer classes with a single non-owning
  template that forwards to private state functions
- Remove StreamTimer::add_elapsed: flush is the only read and checks
  that the accumulator covers every pending ID
- Make get_action_times take mutable aux data so it can flush
- Rename elapsed_time to query_elapsed_time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sethrj
sethrj previously requested changes Dec 1, 2026
Comment thread app/celer-sim/Transporter.cc Resolved
Comment thread src/celeritas/action/ActionTimer.hh Resolved
Comment thread src/celeritas/user/ActionTimes.hh Resolved
Comment thread src/celeritas/user/ActionTimes.hh Resolved
Make the recording functions of ActionTimesStateBase public virtual (final
in the memory-space specializations) and pass an ObserverPtr to the state
to the action loop in place of ActionTimer, which is removed. Replace
StepperInterface::sp_state with a mutable state() overload. Add todos for
casting between opaque ID types and for moving the action timing files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sethrj
sethrj marked this pull request as ready for review December 2, 2026 01:31
@sethrj
sethrj dismissed their stale review December 2, 2026 01:31

Changes addressed

@sethrj

sethrj commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

@esseivaju This one's ready 😄

@codecov

codecov Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.21212% with 38 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.96%. Comparing base (db9a1d4) to head (ebb6f73).
⚠️ Report is 2 commits behind head on develop.

Files with missing lines Patch % Lines
src/celeritas/action/ActionTimesState.cc 55.26% 17 Missing ⚠️
src/celeritas/global/ActionSequence.cc 73.68% 2 Missing and 3 partials ⚠️
src/celeritas/action/ActionLoop.hh 80.95% 0 Missing and 4 partials ⚠️
src/celeritas/optical/Transporter.cc 75.00% 3 Missing and 1 partial ⚠️
src/celeritas/setup/Problem.cc 42.85% 2 Missing and 2 partials ⚠️
src/celeritas/user/ActionTimes.cc 75.00% 2 Missing and 1 partial ⚠️
src/accel/SetupOptions.cc 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #2709      +/-   ##
===========================================
- Coverage    86.04%   85.96%   -0.08%     
===========================================
  Files         1417     1423       +6     
  Lines        45512    45543      +31     
  Branches     11660    11637      -23     
===========================================
- Hits         39159    39152       -7     
+ Misses        4641     4609      -32     
- Partials      1712     1782      +70     
Files with missing lines Coverage Δ
src/accel/LocalTransporter.cc 66.66% <100.00%> (-0.56%) ⬇️
src/celeritas/action/ActionTimesState.hh 100.00% <100.00%> (ø)
src/celeritas/global/ActionSequence.hh 100.00% <100.00%> (ø)
src/celeritas/global/Stepper.cc 96.73% <ø> (ø)
src/celeritas/global/Stepper.hh 92.00% <100.00%> (ø)
src/celeritas/inp/Control.hh 81.81% <ø> (ø)
src/celeritas/inp/Diagnostics.hh 93.33% <ø> (+6.66%) ⬆️
src/celeritas/optical/OpticalCollector.cc 92.30% <100.00%> (+0.09%) ⬆️
src/celeritas/optical/OpticalCollector.hh 100.00% <100.00%> (ø)
src/celeritas/optical/Transporter.hh 100.00% <100.00%> (ø)
... and 10 more

... and 120 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@esseivaju esseivaju left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! Two minor comments

Comment thread app/celer-sim/RunnerInput.cc Resolved
Comment thread src/celeritas/optical/Transporter.cc Resolved
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@sethrj
sethrj added this pull request to the merge queue Dec 3, 2026
Merged via the queue into celeritas-project:develop with commit 8dfc575 Dec 3, 2026
49 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-generated Generated and managed by an agent/bot, not a human. core Software engineering infrastructure (corecel) enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants