@@ -462,6 +462,42 @@ bool CommandEncoder::needs_commit() {
462462
463463void CommandEncoder::commit () {
464464 nvtx3::scoped_range r (" CommandEncoder::commit" );
465+ try {
466+ commit_impl ();
467+ } catch (...) {
468+ // Clear pending CUDA error first.
469+ cudaGetLastError ();
470+ // Clear states.
471+ clear_graph_state ();
472+ node_count_ = 0 ;
473+ bytes_in_graph_ = 0 ;
474+ // Clear graph.
475+ try {
476+ graph_.reset ();
477+ } catch (...) {
478+ // Destroying could fail.
479+ graph_.release ();
480+ }
481+ try {
482+ graph_ = CudaGraph (device_);
483+ } catch (...) {
484+ // Keep the original error.
485+ }
486+ // Re-throw the error.
487+ throw ;
488+ }
489+ }
490+
491+ void CommandEncoder::synchronize () {
492+ CHECK_CUDA_ERROR (cudaStreamSynchronize (stream_));
493+ auto p = std::make_shared<std::promise<void >>();
494+ std::future<void > f = p->get_future ();
495+ add_completed_handler ([p = std::move (p)]() { p->set_value (); });
496+ commit ();
497+ f.wait ();
498+ }
499+
500+ void CommandEncoder::commit_impl () {
465501 if (!temporaries_.empty ()) {
466502 add_completed_handler ([temporaries = std::move (temporaries_)]() {});
467503 }
@@ -520,13 +556,8 @@ void CommandEncoder::commit() {
520556 }
521557
522558 // Reset state
523- from_nodes_.clear ();
524- to_nodes_.clear ();
525- graph_deps_key_.clear ();
526- graph_nodes_key_.clear ();
527- node_map_.clear ();
559+ clear_graph_state ();
528560 graph_ = CudaGraph (device_);
529- is_graph_updatable_ = true ;
530561 }
531562
532563 // Put completion handlers in a batch.
@@ -535,13 +566,16 @@ void CommandEncoder::commit() {
535566 bytes_in_graph_ = 0 ;
536567}
537568
538- void CommandEncoder::synchronize () {
539- CHECK_CUDA_ERROR (cudaStreamSynchronize (stream_));
540- auto p = std::make_shared<std::promise<void >>();
541- std::future<void > f = p->get_future ();
542- add_completed_handler ([p = std::move (p)]() { p->set_value (); });
543- commit ();
544- f.wait ();
569+ void CommandEncoder::clear_graph_state () {
570+ from_nodes_.clear ();
571+ to_nodes_.clear ();
572+ graph_deps_key_.clear ();
573+ graph_nodes_key_.clear ();
574+ node_map_.clear ();
575+ active_deps_.clear ();
576+ active_outputs_.clear ();
577+ concurrent_nodes_.clear ();
578+ is_graph_updatable_ = true ;
545579}
546580
547581Device& device (int cuda_device) {
0 commit comments