aboutsummaryrefslogtreecommitdiff
path: root/deps/cudnn-frontend
diff options
context:
space:
mode:
authorOnur Gündüz <ogunduz@gmail.com>2026-07-02 19:44:08 +0200
committerOnur Gündüz <ogunduz@gmail.com>2026-07-02 19:44:08 +0200
commit6a10d3577232f1fd646a20f22a4a1ab4ec29f28a (patch)
treee4a077b064876ddb39144935fa256a4ab0692488 /deps/cudnn-frontend
parent98a713e86c23bc6098bf7a5558507a9f27a7a1c1 (diff)
downloadffwd-6a10d3577232f1fd646a20f22a4a1ab4ec29f28a.tar.gz
ffwd-6a10d3577232f1fd646a20f22a4a1ab4ec29f28a.zip
cuda: add cuDNN fused attention path with runtime fallback
Diffstat (limited to 'deps/cudnn-frontend')
-rw-r--r--deps/cudnn-frontend/LICENSE.txt21
-rw-r--r--deps/cudnn-frontend/README.md16
-rw-r--r--deps/cudnn-frontend/include/cudnn_backend_base.h165
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend.h152
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/backend/backend_descriptor.h138
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/backend/device_properties.h165
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/backend/execution_helpers.h125
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/backend/kernel_cache.h168
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/backend/plan_helpers.h212
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/context.h138
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/cudnn_interface.h251
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/attention_utils.h385
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/nvrtc_shim.h252
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/oss_engine_interface.h261
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_engine.h697
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_knobs.h215
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_sdpa_prefill_engine.h544
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/sm90_sdpa_prefill_engine.h450
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_fwd_silu_kernel.h468
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_headers.h2043
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d128_fprop_kernel.h3479
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d64_fprop_kernel.h3481
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d128_fprop_kernel.h1762
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d64_fprop_kernel.h1763
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/graph_helpers.h587
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/graph_interface.h3878
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/graph_properties.h3143
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/knobs.h254
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/adaptive_layernorm.h454
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/batchnorm.h268
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/batchnorm_inference.h156
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/block_scale_dequantize.h169
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/block_scale_quantize.h205
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/bn_finalize.h263
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/concatenate.h163
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/conv_dgrad.h205
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/conv_fprop.h254
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/conv_wgrad.h201
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/dbn.h206
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/dbn_weight.h215
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/diagonal_band_mask.h474
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/dln.h226
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/genstats.h147
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/instancenorm.h414
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/layernorm.h259
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/matmul.h253
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/matmul_fp8.h104
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/moe_grouped_matmul.h221
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/moe_grouped_matmul_bwd.h181
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/paged_cache_load.h153
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/pointwise.h390
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/reduction.h232
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/resample.h291
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/reshape.h156
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/rmsnorm.h406
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/rng.h187
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/rope.h146
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/rope_backward.h143
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/scaled_dot_product_flash_attention.h2730
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/sdpa_fp8_bwd.h1172
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/sdpa_support_surface.h553
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/slice.h224
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/softmax.h366
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node/transpose.h164
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/node_interface.h557
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/plans.h1175
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/thirdparty/nlohmann/LICENSE.MIT21
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/thirdparty/nlohmann/json.hpp26710
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/utils/attn_score_modifiers.h330
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/utils/serialize.h677
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_ConvDesc.h425
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Engine.h341
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_EngineConfig.h246
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_EngineConfigGenerator.h123
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_EngineFallbackList.h180
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Errata.h293
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_ExecutionPlan.h599
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_ExecutionPlanCache.h183
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Filters.h96
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Heuristics.h491
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Logging.h166
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_MatMulDesc.h198
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Operation.h3167
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_OperationGraph.h360
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_PointWiseDesc.h411
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_ReductionDesc.h245
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Reorder_Tensor.h105
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Resample.h494
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Rng.h339
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_Tensor.h644
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_VariantPack.h202
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_find_plan.h163
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_get_plan.h62
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_shim.h768
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_utils.h2722
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend_version.h29
96 files changed, 80086 insertions, 0 deletions
diff --git a/deps/cudnn-frontend/LICENSE.txt b/deps/cudnn-frontend/LICENSE.txt
new file mode 100644
index 0000000..eef9c44
--- /dev/null
+++ b/deps/cudnn-frontend/LICENSE.txt
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
diff --git a/deps/cudnn-frontend/README.md b/deps/cudnn-frontend/README.md
new file mode 100644
index 0000000..728e9f5
--- /dev/null
+++ b/deps/cudnn-frontend/README.md
@@ -0,0 +1,16 @@
+# cudnn-frontend (vendored)
+
+Header-only C++ frontend for the cuDNN graph API, used by the CUDA backend for
+fused scaled-dot-product attention (`libffwd/cuda_sdpa.cu`).
+
+- Upstream: https://github.com/NVIDIA/cudnn-frontend
+- Version: 1.25.0 (commit `91bebc8aef59722c21b39391ea5c16ed3583d959`)
+- License: MIT (see `LICENSE.txt`)
+- Only `include/` is vendored; samples, docs, and python bindings are dropped.
+
+The frontend is compiled with `NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING`, so
+libcudnn is dlopen'd at runtime rather than linked. Building still requires the
+cuDNN headers (`cudnn.h`); see the `CUDNN_INC` variable in `build.mk`.
+
+To update: replace `include/` and `LICENSE.txt` from a release tag, then record
+the new version and commit here.
diff --git a/deps/cudnn-frontend/include/cudnn_backend_base.h b/deps/cudnn-frontend/include/cudnn_backend_base.h
new file mode 100644
index 0000000..bae2de8
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_backend_base.h
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <ostream>
+
+namespace cudnn_frontend {
+
+///
+/// OpaqueBackendPointer class
+/// Holds the raws pointer to backend_descriptor
+/// Usage is to wrap this into a smart pointer as
+/// it helps to create and destroy the backendpointer
+
+class OpaqueBackendPointer {
+ cudnnBackendDescriptor_t m_desc = nullptr; //!< Raw void pointer
+ cudnnStatus_t status = CUDNN_STATUS_SUCCESS; //!< status of creation of the Descriptor
+
+ public:
+ OpaqueBackendPointer(const OpaqueBackendPointer&) = delete; //!< Delete the copy constructor to prevent bad copies
+ OpaqueBackendPointer&
+ operator=(const OpaqueBackendPointer&) = delete;
+ OpaqueBackendPointer(OpaqueBackendPointer&&) = default;
+
+ /**
+ * OpaqueBackendPointer constructor.
+ * Calls the cudnnBackendCreateDescriptor. Allocates memory according to the type.
+ */
+ OpaqueBackendPointer(cudnnBackendDescriptorType_t type) { status = detail::create_descriptor(type, &m_desc); }
+ /**
+ * OpaqueBackendPointer destructor.
+ * Calls the cudnnBackendDestroyDescriptor. Frees memory allocated in the constructor.
+ */
+ ~OpaqueBackendPointer() { detail::destroy_descriptor(m_desc); };
+ /**
+ * Accessor.
+ * Returns the const reference to raw underlying descriptor.
+ * Treat it like the data() function of a smart pointer. Can be freed behind the back.
+ */
+ cudnnBackendDescriptor_t const&
+ get_backend_descriptor() const {
+ return m_desc;
+ }
+ /**
+ * Accessor.
+ * Queries the status of the descriptor after calling the cudnnCreate.
+ */
+ cudnnStatus_t
+ get_status() const {
+ return status;
+ }
+ /**
+ * Accessor.
+ * Queries the status of the descriptor returns true if all good.
+ */
+ bool
+ is_good() const {
+ return status == CUDNN_STATUS_SUCCESS;
+ }
+};
+
+/*! \var A shared_ptr wrapper on top of the OpaqueBackendPointer */
+using ManagedOpaqueDescriptor = std::shared_ptr<OpaqueBackendPointer>;
+
+/*! \fn A wrapper on top of the std::make_shared for the OpaqueBackendPointer */
+static ManagedOpaqueDescriptor
+make_shared_backend_pointer(cudnnBackendDescriptorType_t type) {
+ return std::make_shared<OpaqueBackendPointer>(type);
+}
+
+///
+/// BackendDescriptor class
+/// Holds a Managed pointer to OpaqueBackendPointer class
+/// Contains the status and error message if set after any operation.
+/// If exception is disabled the user must query the status after
+/// build operation in order to check if the cudnn construct was built
+/// correctly.
+class BackendDescriptor {
+ public:
+ //! Return a string describing the backend Descriptor
+ virtual std::string
+ describe() const = 0;
+
+ //! Get a copy of the raw descriptor pointer. Ownership is reatined and
+ //! gets deleted when out of scope
+ cudnnBackendDescriptor_t
+ get_raw_desc() const {
+ return pointer->get_backend_descriptor();
+ }
+
+ //! Current status of the descriptor
+ cudnnStatus_t
+ get_status() const {
+ return status;
+ }
+
+ //! Set status of the descriptor
+ void
+ set_status(cudnnStatus_t const status_) const {
+ status = status_;
+ }
+
+ //! Set Diagonistic error message.
+ void
+ set_error(const char* message) const {
+ err_msg = message;
+ }
+
+ //! Diagonistic error message if any
+ const char*
+ get_error() const {
+ return err_msg.c_str();
+ }
+
+ //! Returns a copy of underlying managed descriptor
+ ManagedOpaqueDescriptor
+ get_desc() const {
+ return pointer;
+ }
+
+ //! Initializes the underlying managed descriptor
+ cudnnStatus_t
+ initialize_managed_backend_pointer(cudnnBackendDescriptorType_t type) {
+ pointer = make_shared_backend_pointer(type);
+ return pointer->get_status();
+ }
+
+ protected:
+ /**
+ * BackendDescriptor constructor.
+ * Initializes the member variables as passed.
+ */
+ BackendDescriptor(ManagedOpaqueDescriptor pointer_, cudnnStatus_t status_, std::string err_msg_)
+ : pointer(pointer_), status(status_), err_msg(err_msg_) {}
+ BackendDescriptor() = default;
+
+ virtual ~BackendDescriptor() {};
+
+ ManagedOpaqueDescriptor pointer; //! Shared pointer of the OpaqueBackendPointer
+
+ mutable cudnnStatus_t status = CUDNN_STATUS_SUCCESS; //!< Error code if any being set
+ mutable std::string err_msg; //!< Error message if any being set
+};
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend.h b/deps/cudnn-frontend/include/cudnn_frontend.h
new file mode 100644
index 0000000..fe1a350
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend.h
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+// Suppress MSVC warning C4756 (overflow in constant arithmetic) that occurs
+// in MSVC's <optional> header with certain compiler versions
+#ifdef _MSC_VER
+#pragma warning(disable : 4756)
+#endif
+
+/*! \mainpage CUDNN FRONTEND API
+ *
+ * \section Introduction
+ *
+ * The cuDNN Frontend API is a C++ header-only library that demonstrates how to use the cuDNN C backend API. The cuDNN C
+ * backend API is documented in the cuDNN developer guide.
+ *
+ * \section Why use Frontend API
+ *
+ * Consider the following code snippet which showcases cudnnBackendTensor creation using the backend API and its
+ * equivalent front-end API code. Many among the backend constructs follow similar pattern.
+ *
+ * ~~~~~~~~~~~~~~~{.cpp}
+ *
+ * ===========================================================================================
+ * auto check_status = [](cudnnStatus_t status) { assert (status == CUDNN_STATUS_SUCCESS); };
+ * ===========================================================================================
+ * // Backend code for Tensor Creation.
+ * cudnnBackendDescriptor_t tensor;
+ *
+ * check_status (cudnnBackendCreateDescriptor(CUDNN_BACKEND_TENSOR_DESCRIPTOR, &tensor));
+ *
+ * check_status (cudnnBackendSetAttribute(tensor,
+ * CUDNN_ATTR_TENSOR_DATA_TYPE,
+ * CUDNN_TYPE_DATA_TYPE,
+ * 1,
+ * &data_type));
+ * check_status (cudnnBackendSetAttribute(tensor,
+ * CUDNN_ATTR_TENSOR_DIMENSIONS,
+ * CUDNN_TYPE_INT64,
+ * tensor_dim.size(),
+ * tensor_dim.data()));
+ * check_status (cudnnBackendSetAttribute(tensor,
+ * CUDNN_ATTR_TENSOR_STRIDES,
+ * CUDNN_TYPE_INT64,
+ * tensor_str.size(),
+ * tensor_str.data()));
+ * check_status (cudnnBackendSetAttribute(tensor,
+ * CUDNN_ATTR_TENSOR_UNIQUE_ID,
+ * CUDNN_TYPE_INT64,
+ * 1,
+ * &id));
+ * check_status (cudnnBackendSetAttribute(tensor,
+ * CUDNN_ATTR_TENSOR_BYTE_ALIGNMENT,
+ * CUDNN_TYPE_INT64,
+ * 1,
+ * &alignment));
+ * check_status (cudnnBackendFinalize(tensor));
+ *
+ * check_status (cudnnBackendDestroyDescriptor(tensor));
+ * ===========================================================================================
+ * // FrontEnd equivalent code.
+ * auto tensor = cudnn_frontend::TensorBuilder()
+ * .setDim(tensor_dim.size(), tensor_dim.data())
+ * .setStrides(tensor_str.size(), tensor_str.data())
+ * .setId(id)
+ * .setAlignment(alignment)
+ * .setDataType(data_type)
+ * .build();
+ * check_status(tensor.get_status());
+ * ===========================================================================================
+ *
+ * ~~~~~~~~~~~~~~~
+ *
+ * Frontend API serves two major purpose as a companion to the backend API.
+ * - Functional additions:
+ * - Support for auto-tuning. (cudnnGet and cudnnFind)
+ * - Errata filters.
+ * - Programmatic ease:
+ * - Easy memory management for the cudnnBackendDescriptor_t (RAII based classes).
+ * - Error handling with optional exception support. Better error messages.
+ * - Fewer lines of code (5-10x reduction in LOC).
+ * - Simpler samples on how to use the new API.
+ */
+
+#include <cudnn.h>
+
+#include "cudnn_frontend_ConvDesc.h"
+#include "cudnn_frontend_Heuristics.h"
+#include "cudnn_frontend_Engine.h"
+#include "cudnn_frontend_EngineConfig.h"
+#include "cudnn_frontend_EngineFallbackList.h"
+#include "cudnn_frontend_Errata.h"
+#include "cudnn_frontend_ExecutionPlan.h"
+#include "cudnn_frontend_Filters.h"
+#include "cudnn_frontend_Operation.h"
+#include "cudnn_frontend_OperationGraph.h"
+#include "cudnn_frontend_Tensor.h"
+#include "cudnn_frontend_VariantPack.h"
+#include "cudnn_frontend_PointWiseDesc.h"
+#include "cudnn_frontend_MatMulDesc.h"
+#include "cudnn_frontend_Logging.h"
+#include "cudnn_frontend_Reorder_Tensor.h"
+#include "cudnn_frontend_ExecutionPlanCache.h"
+#include "cudnn_frontend_utils.h"
+
+#include "cudnn_frontend_Resample.h"
+
+#include "cudnn_frontend/graph_interface.h"
+#include "cudnn_frontend/utils/serialize.h"
+#include "cudnn_frontend/backend/kernel_cache.h"
+#include "cudnn_frontend/utils/attn_score_modifiers.h"
+#include "cudnn_frontend/backend/device_properties.h"
+
+#include "cudnn_frontend_version.h"
+
+namespace cudnn_frontend {
+using ConvDesc = ConvDesc_v8;
+using ConvDescBuilder = ConvDescBuilder_v8;
+using ReductionDesc = ReductionDesc_v8;
+using ReductionDescBuilder = ReductionDescBuilder_v8;
+using EngineHeuristicsBuilder = EngineHeuristicsBuilder_v8;
+using EngineHeuristics = EngineHeuristics_v8;
+using EngineBuilder = EngineBuilder_v8;
+using Engine = Engine_v8;
+using EngineConfig = EngineConfig_v8;
+using EngineConfigBuilder = EngineConfigBuilder_v8;
+using EngineFallbackList = EngineFallbackList_v8;
+using EngineFallbackListBuilder = EngineFallbackListBuilder_v8;
+using ResampleDesc = ResampleDesc_v8;
+using ResampleDescBuilder = ResampleDescBuilder_v8;
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/backend/backend_descriptor.h b/deps/cudnn-frontend/include/cudnn_frontend/backend/backend_descriptor.h
new file mode 100644
index 0000000..2cd68c0
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/backend/backend_descriptor.h
@@ -0,0 +1,138 @@
+#pragma once
+
+#include <memory>
+
+#include "../graph_helpers.h"
+#include "cudnn.h"
+
+namespace cudnn_frontend::detail {
+
+/**
+ * @brief RAII wrapper around a `cudnnBackendDescriptor_t` object.
+ *
+ * This class provides a convenient way to manage the lifetime of a `cudnnBackendDescriptor_t`
+ * object using the RAII (Resource Acquisition Is Initialization) idiom. It automatically
+ * creates the descriptor when the object is constructed and destroys it when the object
+ * is destroyed, ensuring proper resource management and preventing memory leaks.
+ *
+ * @note The constructor of this class does not throw exceptions. Instead, it stores the
+ * status of the descriptor creation operation in the `status` member variable. Callers
+ * should check this status and handle any errors accordingly.
+ */
+class backend_descriptor {
+ public:
+ /**
+ * @brief Constructs a `backend_descriptor` object.
+ *
+ * @param type The type of the backend descriptor to create.
+ */
+ backend_descriptor(cudnnBackendDescriptorType_t type) { status = detail::create_descriptor(type, &desc); }
+
+ /**
+ * @brief Move constructor.
+ *
+ * Transfers the ownership of the `cudnnBackendDescriptor_t` object to the new
+ * `backend_descriptor` instance.
+ *
+ * @param other The source `backend_descriptor` object.
+ */
+ backend_descriptor(backend_descriptor&& other) noexcept : desc(other.desc), status(other.status) {
+ other.desc = nullptr;
+ other.status = CUDNN_STATUS_NOT_INITIALIZED;
+ }
+
+ /**
+ * @brief Move assignment operator.
+ *
+ * Transfers the ownership of the `cudnnBackendDescriptor_t` object to the new
+ * `backend_descriptor` instance.
+ *
+ * @param other The source `backend_descriptor` object.
+ * @return A reference to the current `backend_descriptor` object.
+ */
+ backend_descriptor&
+ operator=(backend_descriptor&& other) noexcept {
+ if (this != &other) {
+ desc = other.desc;
+ status = other.status;
+
+ other.desc = nullptr;
+ }
+ return *this;
+ }
+
+ /**
+ * @brief Destructor.
+ *
+ * Destroys the `cudnnBackendDescriptor_t` object and frees the associated resources.
+ */
+ ~backend_descriptor() {
+ if (desc) {
+ detail::destroy_descriptor(desc);
+ }
+ }
+
+ /**
+ * @brief Deleted copy constructor and assignment operator.
+ *
+ * `backend_descriptor` objects are not copyable to prevent unintended resource
+ * sharing and potential memory leaks.
+ */
+ backend_descriptor(backend_descriptor const&) = delete;
+ backend_descriptor&
+ operator=(backend_descriptor const&) = delete;
+
+ /**
+ * @brief Initializes a `backend_descriptor` object.
+ *
+ * @param type The type of the backend descriptor to create.
+ */
+ error_t
+ initialize(cudnnBackendDescriptorType_t type) {
+ _CUDNN_CHECK_CUDNN_ERROR(detail::create_descriptor(type, &desc));
+ return {error_code_t::OK, ""};
+ }
+
+ /**
+ * @brief Finalizes a `backend_descriptor` object.
+ *
+ */
+ error_t
+ finalize() {
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(desc));
+ return {error_code_t::OK, ""};
+ }
+
+ /**
+ * @brief Accessor for the underlying `cudnnBackendDescriptor_t` object.
+ *
+ * @return A const reference to `cudnnBackendDescriptor_t`, the raw pointer to the backend descriptor.
+ */
+ cudnnBackendDescriptor_t const&
+ get_ptr() const {
+ return desc;
+ }
+
+ /**
+ * @brief Accessor for the status of the backend descriptor creation.
+ *
+ * @return `cudnnStatus_t` The status of the backend descriptor creation operation.
+ */
+ cudnnStatus_t
+ get_status() const {
+ return status;
+ }
+
+ /**
+ * @brief Constructs a default `backend_descriptor` object, but without initializing descriptor
+ *
+ * Used to return an error code to user for incorrect cuDNN version
+ */
+ backend_descriptor() = default;
+
+ private:
+ cudnnBackendDescriptor_t desc = nullptr; //!< Raw pointer to the backend descriptor.
+ cudnnStatus_t status = CUDNN_STATUS_NOT_INITIALIZED; //!< Status of the descriptor creation operation.
+};
+
+} // namespace cudnn_frontend::detail \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/backend/device_properties.h b/deps/cudnn-frontend/include/cudnn_frontend/backend/device_properties.h
new file mode 100644
index 0000000..d31c555
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/backend/device_properties.h
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "../graph_helpers.h"
+#include "backend_descriptor.h"
+
+namespace cudnn_frontend {
+///
+/// DeviceProperties Class
+/// Wraps the device_properties backend descriptor
+/// Wraps backend utility functions for user's convenience
+/// Backend accessor functions: size()
+/// Contains internal utilities for device properties finalization and operation graph attributes
+///
+class DeviceProperties : public detail::backend_descriptor {
+ public:
+ // Uses the default backend constructor so that we can check for initialization error during build()
+ DeviceProperties() = default;
+
+ std::string
+ describe() const {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_DEVICEPROP_DESCRIPTOR : " << std::endl;
+ return ss.str();
+ }
+
+ inline DeviceProperties&
+ set_device_id(int32_t device_id) {
+ this->device_id = device_id;
+ return *this;
+ }
+
+ inline DeviceProperties&
+ set_handle(cudnnHandle_t handle) {
+ this->handle = handle;
+ return *this;
+ }
+
+ // Used to check device properties status (particularly after initialization)
+ error_t
+ status() const {
+ if (get_status() != CUDNN_STATUS_SUCCESS) {
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_BACKEND_DEVICEPROP_DESCRIPTOR: Check CUDNN_VERSION >= 9.8"};
+ }
+ return {};
+ }
+
+ error_t
+ serialize(std::vector<uint8_t>& serialization_buf) const {
+#if (CUDNN_VERSION >= 90800)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90800,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_DEVICEPROP_JSON_REPRESENTATION is only available starting 9.8.");
+
+ int64_t serializationSize;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(
+ get_ptr(), CUDNN_ATTR_DEVICEPROP_JSON_REPRESENTATION, CUDNN_TYPE_CHAR, 0, &serializationSize, nullptr));
+ serialization_buf.resize(static_cast<size_t>(serializationSize));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(get_ptr(),
+ CUDNN_ATTR_DEVICEPROP_JSON_REPRESENTATION,
+ CUDNN_TYPE_CHAR,
+ serializationSize,
+ &serializationSize,
+ serialization_buf.data()));
+ return {};
+#else
+ (void)serialization_buf;
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_DEVICEPROP_JSON_REPRESENTATION is only available starting 9.8."};
+#endif
+ }
+
+ error_t
+ deserialize(const std::vector<uint8_t>& serialized_buf) {
+#if (CUDNN_VERSION >= 90800)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90800,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_DEVICEPROP_JSON_REPRESENTATION is only available starting 9.8.");
+
+ // Check if the device properties is already initialized
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ get_ptr() != nullptr, error_code_t::CUDNN_BACKEND_API_FAILED, "Device properties is already initialized.");
+
+ // Initialize the device properties descriptor
+ CHECK_CUDNN_FRONTEND_ERROR(initialize(CUDNN_BACKEND_DEVICEPROP_DESCRIPTOR));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(get_ptr(),
+ CUDNN_ATTR_DEVICEPROP_JSON_REPRESENTATION,
+ CUDNN_TYPE_CHAR,
+ serialized_buf.size(),
+ serialized_buf.data()));
+
+ CHECK_CUDNN_FRONTEND_ERROR(finalize());
+ return {};
+#else
+ (void)serialized_buf;
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_DEVICEPROP_JSON_REPRESENTATION is only available starting 9.8."};
+#endif
+ }
+
+ // Check for both compile-time and runtime cuDNN version
+ error_t
+ build() {
+#if (CUDNN_VERSION >= 90800)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90800,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "CUDNN_BACKEND_DEVICEPROP_DESCRIPTOR is only available starting 9.8.");
+ if (get_ptr() == nullptr) {
+ CHECK_CUDNN_FRONTEND_ERROR(initialize(CUDNN_BACKEND_DEVICEPROP_DESCRIPTOR));
+ }
+
+ if (handle != nullptr) {
+ _CUDNN_CHECK_CUDNN_ERROR(
+ detail::set_attribute(get_ptr(), CUDNN_ATTR_DEVICEPROP_HANDLE, CUDNN_TYPE_HANDLE, 1, &handle));
+ }
+
+ if (device_id >= 0) {
+ _CUDNN_CHECK_CUDNN_ERROR(
+ detail::set_attribute(get_ptr(), CUDNN_ATTR_DEVICEPROP_DEVICE_ID, CUDNN_TYPE_INT32, 1, &device_id));
+ }
+
+ CHECK_CUDNN_FRONTEND_ERROR(finalize());
+ return {};
+#else
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_BACKEND_DEVICEPROP_DESCRIPTOR is only available starting 9.8."};
+#endif
+ }
+
+ private:
+ cudnnHandle_t handle = nullptr;
+ int32_t device_id = 0;
+};
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/backend/execution_helpers.h b/deps/cudnn-frontend/include/cudnn_frontend/backend/execution_helpers.h
new file mode 100644
index 0000000..7138d48
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/backend/execution_helpers.h
@@ -0,0 +1,125 @@
+#pragma once
+
+#include <vector>
+
+#include "cudnn.h"
+
+#include "backend_descriptor.h"
+
+namespace cudnn_frontend::detail {
+/**
+ * @brief Creates a CUDNN backend variant pack descriptor.
+ *
+ * This function creates a `backend_descriptor` object representing a CUDNN backend variant pack
+ * descriptor. The variant pack descriptor is configured with the provided device pointers, unique
+ * IDs, and a workspace pointer.
+ *
+ * @param[out] variant_pack The created `backend_descriptor` object representing the variant pack.
+ * @param device_ptrs A pointer to an array of device pointers to be associated with the variant pack.
+ * @param uids A vector of unique IDs to be associated with the variant pack.
+ * @param workspace_ptr A pointer to the workspace memory to be associated with the variant pack.
+ * @return `error_t` A tuple containing the error code and an optional error message.
+ * The error code is `error_code_t::OK` on success, or an appropriate error code on failure.
+ */
+inline error_t
+create_variant_pack(backend_descriptor& variant_pack,
+ void* const* device_ptrs,
+ std::vector<int64_t> const& uids,
+ void* workspace_ptr) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(device_ptrs == nullptr && !uids.empty(),
+ error_code_t::INVALID_VARIANT_PACK,
+ "device_ptrs must be non-null when uids are provided.");
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ variant_pack.get_ptr(), CUDNN_ATTR_VARIANT_PACK_WORKSPACE, CUDNN_TYPE_VOID_PTR, 1, &workspace_ptr));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ variant_pack.get_ptr(), CUDNN_ATTR_VARIANT_PACK_DATA_POINTERS, CUDNN_TYPE_VOID_PTR, uids.size(), device_ptrs));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ variant_pack.get_ptr(), CUDNN_ATTR_VARIANT_PACK_UNIQUE_IDS, CUDNN_TYPE_INT64, uids.size(), uids.data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(variant_pack.get_ptr()));
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+create_variant_pack(backend_descriptor& variant_pack,
+ std::vector<void*>& device_ptrs,
+ std::vector<int64_t> const& uids,
+ void* workspace_ptr) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(device_ptrs.size() != uids.size(),
+ error_code_t::INVALID_VARIANT_PACK,
+ "device_ptrs and uids must have the same length.");
+ return create_variant_pack(variant_pack, device_ptrs.data(), uids, workspace_ptr);
+}
+
+inline error_t
+create_variant_pack(backend_descriptor& variant_pack,
+ void* const* device_ptrs,
+ std::vector<int64_t> const& uids,
+ void* workspace_ptr,
+ std::vector<int64_t> const& override_uids,
+ std::vector<std::vector<int64_t>> const& override_shapes,
+ std::vector<std::vector<int64_t>> const& override_strides) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(device_ptrs == nullptr && !uids.empty(),
+ error_code_t::INVALID_VARIANT_PACK,
+ "device_ptrs must be non-null when uids are provided.");
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Dynamic shapes requires cuDNN v9.18.0"};
+
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91800, cudnn_ver_error);
+
+ CUDNN_FRONTEND_UNUSED(override_uids);
+ CUDNN_FRONTEND_UNUSED(override_shapes);
+ CUDNN_FRONTEND_UNUSED(override_strides);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ variant_pack.get_ptr(), CUDNN_ATTR_VARIANT_PACK_WORKSPACE, CUDNN_TYPE_VOID_PTR, 1, &workspace_ptr));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ variant_pack.get_ptr(), CUDNN_ATTR_VARIANT_PACK_DATA_POINTERS, CUDNN_TYPE_VOID_PTR, uids.size(), device_ptrs));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ variant_pack.get_ptr(), CUDNN_ATTR_VARIANT_PACK_UNIQUE_IDS, CUDNN_TYPE_INT64, uids.size(), uids.data()));
+
+#if (CUDNN_VERSION >= 91800)
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(variant_pack.get_ptr(),
+ CUDNN_ATTR_VARIANT_PACK_OVERRIDE_UNIQUE_IDS,
+ CUDNN_TYPE_INT64,
+ override_uids.size(),
+ override_uids.data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(variant_pack.get_ptr(),
+ CUDNN_ATTR_VARIANT_PACK_OVERRIDE_SHAPES,
+ CUDNN_TYPE_VOID_PTR,
+ 1,
+ (void*)&override_shapes));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(variant_pack.get_ptr(),
+ CUDNN_ATTR_VARIANT_PACK_OVERRIDE_STRIDES,
+ CUDNN_TYPE_VOID_PTR,
+ 1,
+ (void*)&override_strides));
+#endif
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(variant_pack.get_ptr()));
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+create_variant_pack(backend_descriptor& variant_pack,
+ std::vector<void*>& device_ptrs,
+ std::vector<int64_t> const& uids,
+ void* workspace_ptr,
+ std::vector<int64_t> const& override_uids,
+ std::vector<std::vector<int64_t>> const& override_shapes,
+ std::vector<std::vector<int64_t>> const& override_strides) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(device_ptrs.size() != uids.size(),
+ error_code_t::INVALID_VARIANT_PACK,
+ "device_ptrs and uids must have the same length.");
+ return create_variant_pack(
+ variant_pack, device_ptrs.data(), uids, workspace_ptr, override_uids, override_shapes, override_strides);
+}
+
+} // namespace cudnn_frontend::detail
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/backend/kernel_cache.h b/deps/cudnn-frontend/include/cudnn_frontend/backend/kernel_cache.h
new file mode 100644
index 0000000..ef173b2
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/backend/kernel_cache.h
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "../graph_helpers.h"
+#include "backend_descriptor.h"
+
+namespace cudnn_frontend {
+namespace graph {
+class Graph;
+} // namespace graph
+///
+/// KernelCache Class
+/// Wraps the kernel_cache backend descriptor
+/// Wraps backend utility functions for user's convenience
+/// Backend accessor functions: size()
+/// Contains internal utilities for kernel cache finalization and operation graph attributes
+///
+class KernelCache : public detail::backend_descriptor {
+ public:
+ friend class graph::Graph;
+ // Uses the default backend constructor so that we can check for initialization error during build()
+ KernelCache() : backend_descriptor() {}
+
+ std::string
+ describe() const {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_KERNEL_CACHE_DESCRIPTOR : " << std::endl;
+ return ss.str();
+ }
+
+ bool
+ is_finalized() {
+ return finalized;
+ }
+
+ // Used to check kernel cache status (particularly after initialization)
+ error_t
+ status() {
+ if (get_status() != CUDNN_STATUS_SUCCESS) {
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_BACKEND_KERNEL_CACHE_DESCRIPTOR: Check CUDNN_VERSION >= 9.4"};
+ }
+ return {};
+ }
+
+ error_t
+ to_json(std::string &str_json) const {
+ str_json.clear();
+#if (CUDNN_VERSION >= 91000)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 91000,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_KERNEL_CACHE_JSON_REPRESENTATION is only available starting 9.10.");
+
+ int64_t serializationSize;
+ std::vector<char> serialization_buf;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(
+ get_ptr(), CUDNN_ATTR_KERNEL_CACHE_JSON_REPRESENTATION, CUDNN_TYPE_CHAR, 0, &serializationSize, nullptr));
+ serialization_buf.resize(static_cast<size_t>(serializationSize));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(get_ptr(),
+ CUDNN_ATTR_KERNEL_CACHE_JSON_REPRESENTATION,
+ CUDNN_TYPE_CHAR,
+ serializationSize,
+ &serializationSize,
+ serialization_buf.data()));
+ std::string json_string(serialization_buf.begin(), serialization_buf.end());
+ str_json = std::move(json_string);
+ return {};
+#else
+ (void)str_json;
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_KERNEL_CACHE_JSON_REPRESENTATION is only available starting 9.10."};
+#endif
+ }
+
+ error_t
+ from_json(const std::string &json_cache) {
+#if (CUDNN_VERSION >= 91000)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 91000,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_KERNEL_CACHE_JSON_REPRESENTATION is only available starting 9.10.");
+
+ // Check if the kernel cache is already initialized
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ get_ptr() != nullptr, error_code_t::CUDNN_BACKEND_API_FAILED, "Kernel cache is already initialized.");
+
+ // // Initialize the kernel cache descriptor
+ CHECK_CUDNN_FRONTEND_ERROR(initialize(CUDNN_BACKEND_KERNEL_CACHE_DESCRIPTOR));
+
+ std::vector<char> serialization_buf;
+ serialization_buf.assign(json_cache.begin(), json_cache.end());
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(get_ptr(),
+ CUDNN_ATTR_KERNEL_CACHE_JSON_REPRESENTATION,
+ CUDNN_TYPE_CHAR,
+ serialization_buf.size(),
+ serialization_buf.data()));
+ return {};
+#else
+ (void)json_cache;
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_KERNEL_CACHE_JSON_REPRESENTATION is only available starting 9.10."};
+#endif
+ }
+
+ // Responsible for initializing, setting operation graph attribute, and finalizing kernel cache
+ // Check for both compile-time and runtime cuDNN version
+ error_t
+ build(cudnnBackendDescriptor_t op_graph) {
+#if (CUDNN_VERSION >= 90400)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90400,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "CUDNN_BACKEND_KERNEL_CACHE_DESCRIPTOR is only available starting 9.4.");
+ if (get_ptr() == nullptr) {
+ CHECK_CUDNN_FRONTEND_ERROR(initialize(CUDNN_BACKEND_KERNEL_CACHE_DESCRIPTOR));
+ }
+#if (CUDNN_VERSION >= 90500)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90500,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "CUDNN_ATTR_KERNEL_CACHE_OPERATION_GRAPH is only available starting 9.5.");
+ if (op_graph) {
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ get_ptr(), CUDNN_ATTR_KERNEL_CACHE_OPERATION_GRAPH, CUDNN_TYPE_BACKEND_DESCRIPTOR, 1, &op_graph));
+ }
+#else
+ (void)op_graph;
+#endif
+ CHECK_CUDNN_FRONTEND_ERROR(finalize());
+ finalized = true;
+ return {};
+#else
+ (void)op_graph;
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_BACKEND_KERNEL_CACHE_DESCRIPTOR is only available starting 9.4."};
+#endif
+ }
+
+ private:
+ bool finalized = false;
+};
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/backend/plan_helpers.h b/deps/cudnn-frontend/include/cudnn_frontend/backend/plan_helpers.h
new file mode 100644
index 0000000..4ef47e2
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/backend/plan_helpers.h
@@ -0,0 +1,212 @@
+#pragma once
+
+#include <vector>
+
+#include "cudnn.h"
+
+#include "backend_descriptor.h"
+#include "../knobs.h"
+
+namespace cudnn_frontend::detail {
+/**
+ * @brief Creates a CUDNN backend variant pack descriptor.
+ *
+ * This function creates a `backend_descriptor` object representing a CUDNN backend variant pack
+ * descriptor. The variant pack descriptor is configured with the provided device pointers, unique
+ * IDs, and a workspace pointer.
+ *
+ * @param[out] variant_pack The created `backend_descriptor` object representing the variant pack.
+ * @param device_ptrs A vector of device pointers to be associated with the variant pack.
+ * @param uids A vector of unique IDs to be associated with the variant pack.
+ * @param workspace_ptr A pointer to the workspace memory to be associated with the variant pack.
+ * @return `error_t` A tuple containing the error code and an optional error message.
+ * The error code is `error_code_t::OK` on success, or an appropriate error code on failure.
+ */
+inline error_t
+get_workspace_size(ManagedOpaqueDescriptor& engine_config, int64_t& workspace) {
+#if CUDNN_VERSION >= 90200
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(engine_config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_WORKSPACE_SIZE,
+ CUDNN_TYPE_INT64,
+ 1,
+ nullptr,
+ &workspace));
+ return {error_code_t::OK, ""};
+#else
+ (void)engine_config;
+ (void)workspace;
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_ENGINECFG_WORKSPACE_SIZE is only available starting 9.2."};
+#endif
+}
+
+inline error_t
+get_shared_memory_size(ManagedOpaqueDescriptor& engine_config, int32_t& shared_memory_size) {
+#if CUDNN_VERSION >= 90200
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(engine_config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_SHARED_MEMORY_USED,
+ CUDNN_TYPE_INT32,
+ 1,
+ nullptr,
+ &shared_memory_size));
+ return {error_code_t::OK, ""};
+#else
+ (void)engine_config;
+ (void)shared_memory_size;
+ return {error_code_t::CUDNN_BACKEND_API_FAILED,
+ "CUDNN_ATTR_ENGINECFG_SHARED_MEMORY_USED is only available starting 9.2."};
+#endif
+}
+
+inline error_t
+create_engine(backend_descriptor& engine,
+ int64_t const engine_id,
+ cudnnBackendDescriptor_t op_graph,
+ std::shared_ptr<const DeviceProperties> device_properties = nullptr) {
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ engine.get_ptr(), CUDNN_ATTR_ENGINE_OPERATION_GRAPH, CUDNN_TYPE_BACKEND_DESCRIPTOR, 1, &op_graph));
+
+ // Validate before setting
+ int64_t count;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(
+ op_graph, CUDNN_ATTR_OPERATIONGRAPH_ENGINE_GLOBAL_COUNT, CUDNN_TYPE_INT64, 1, nullptr, &count));
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ engine_id >= count || engine_id < 0, error_code_t::INVALID_VALUE, "Invalid engine id.");
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ detail::set_attribute(engine.get_ptr(), CUDNN_ATTR_ENGINE_GLOBAL_INDEX, CUDNN_TYPE_INT64, 1, &engine_id));
+
+ if (device_properties != nullptr) {
+#if (CUDNN_VERSION >= 90800)
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(engine.get_ptr(),
+ CUDNN_ATTR_ENGINE_DEVICEPROP,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &device_properties->get_ptr()));
+#endif
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(engine.get_ptr()));
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+query_knobs(int64_t const engine_id, cudnnBackendDescriptor_t op_graph, std::vector<Knob>& knobs) {
+ detail::backend_descriptor engine(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(engine.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create engine's backend descriptor.");
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_engine(engine, engine_id, op_graph));
+
+ // Initialize a backend descriptor for each knob type
+ // The size of the array should be CUDNN_KNOB_TYPE_COUNTS, as currently we dont know how many knobs the engine will
+ // support
+ std::array<backend_descriptor, CUDNN_KNOB_TYPE_COUNTS> frontend_knobs;
+ for (size_t i = 0; i < CUDNN_KNOB_TYPE_COUNTS; i++) {
+ backend_descriptor frontend_knob(CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(frontend_knob.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create knob's backend descriptor.");
+ frontend_knobs[i] = std::move(frontend_knob);
+ }
+
+ // Create an auxillary array to hold the raw knob descriptors
+ std::array<cudnnBackendDescriptor_t, CUDNN_KNOB_TYPE_COUNTS> backend_knobs;
+ for (size_t i = 0; i < CUDNN_KNOB_TYPE_COUNTS; i++) {
+ backend_knobs[i] = frontend_knobs[i].get_ptr();
+ }
+
+ // This is the actual number of knobs that is supported by the engine
+ int64_t knobs_size;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(engine.get_ptr(),
+ CUDNN_ATTR_ENGINE_KNOB_INFO,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ CUDNN_KNOB_TYPE_COUNTS,
+ &knobs_size,
+ backend_knobs.data()));
+
+ for (int64_t i = 0; i < knobs_size; i++) {
+ cudnnBackendKnobType_t type;
+ int64_t elemCount;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(
+ frontend_knobs[i].get_ptr(), CUDNN_ATTR_KNOB_INFO_TYPE, CUDNN_TYPE_KNOB_TYPE, 1, &elemCount, &type));
+
+ int64_t maxValue;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(frontend_knobs[i].get_ptr(),
+ CUDNN_ATTR_KNOB_INFO_MAXIMUM_VALUE,
+ CUDNN_TYPE_INT64,
+ 1,
+ &elemCount,
+ &maxValue));
+
+ int64_t minValue;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(frontend_knobs[i].get_ptr(),
+ CUDNN_ATTR_KNOB_INFO_MINIMUM_VALUE,
+ CUDNN_TYPE_INT64,
+ 1,
+ &elemCount,
+ &minValue));
+
+ int64_t stride;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(
+ frontend_knobs[i].get_ptr(), CUDNN_ATTR_KNOB_INFO_STRIDE, CUDNN_TYPE_INT64, 1, &elemCount, &stride));
+
+ auto frontend_knob_type = convert_from_backend_knob_type(type);
+ knobs.emplace_back(frontend_knob_type, maxValue, minValue, stride);
+ }
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+set_knob_choices(std::unordered_map<KnobType_t, int64_t> const& user_choices,
+ std::vector<detail::backend_descriptor>& knob_choices) {
+ for (auto const& [type, choice] : user_choices) {
+ backend_descriptor knob_choice(CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(knob_choice.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create knob_choice's backend descriptor.");
+
+ cudnnBackendKnobType_t backend_type;
+ _CUDNN_CHECK_CUDNN_ERROR(convert_to_backend_knob_type(type, backend_type));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ knob_choice.get_ptr(), CUDNN_ATTR_KNOB_CHOICE_KNOB_TYPE, CUDNN_TYPE_KNOB_TYPE, 1, &backend_type));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ knob_choice.get_ptr(), CUDNN_ATTR_KNOB_CHOICE_KNOB_VALUE, CUDNN_TYPE_INT64, 1, &choice));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(knob_choice.get_ptr()));
+
+ knob_choices.push_back(std::move(knob_choice));
+ }
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+create_engine_config(ManagedOpaqueDescriptor& engine_config,
+ backend_descriptor& engine,
+ std::vector<detail::backend_descriptor>& knob_choices) {
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(engine_config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_ENGINE,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(engine.get_ptr())));
+
+ std::vector<cudnnBackendDescriptor_t> backend_knob_choices(CUDNN_KNOB_TYPE_COUNTS);
+ for (size_t i = 0; i < knob_choices.size(); i++) {
+ backend_knob_choices[i] = knob_choices[i].get_ptr();
+ }
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(engine_config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_KNOB_CHOICES,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ knob_choices.size(),
+ backend_knob_choices.data()));
+
+ // Finalizing the descriptor
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(engine_config->get_backend_descriptor()));
+
+ return {error_code_t::OK, ""};
+}
+
+} // namespace cudnn_frontend::detail
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/context.h b/deps/cudnn-frontend/include/cudnn_frontend/context.h
new file mode 100644
index 0000000..86e878d
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/context.h
@@ -0,0 +1,138 @@
+#pragma once
+
+#include "../cudnn_frontend_shim.h"
+#include "../cudnn_frontend_utils.h"
+
+namespace cudnn_frontend::detail {
+
+class Context {
+ DataType_t compute_data_type = DataType_t::NOT_SET;
+ DataType_t intermediate_data_type = DataType_t::NOT_SET;
+ DataType_t io_data_type = DataType_t::NOT_SET;
+ int32_t target_sm_count = -1;
+ mutable int32_t target_sm_version = -1;
+ bool is_dynamic_shape_enabled = false;
+ bool is_override_shape_enabled = false;
+
+ std::string name = "";
+
+ public:
+ Context&
+ set_intermediate_data_type(DataType_t const type) {
+ intermediate_data_type = type;
+ return *this;
+ }
+
+ Context&
+ set_io_data_type(DataType_t const type) {
+ io_data_type = type;
+ return *this;
+ }
+
+ Context&
+ set_compute_data_type(DataType_t const type) {
+ compute_data_type = type;
+ return *this;
+ }
+
+ DataType_t
+ get_io_data_type() const {
+ return io_data_type;
+ }
+
+ DataType_t
+ get_intermediate_data_type() const {
+ return intermediate_data_type;
+ }
+
+ DataType_t
+ get_compute_data_type() const {
+ return compute_data_type;
+ }
+
+ Context&
+ set_name(std::string const& name_) {
+ name = name_;
+ return *this;
+ }
+
+ std::string
+ get_name() const {
+ return name;
+ }
+
+ Context&
+ set_target_sm_count(int32_t count) {
+ target_sm_count = count;
+ return *this;
+ }
+
+ Context&
+ set_sm_version(int32_t version) {
+ target_sm_version = version;
+ return *this;
+ }
+
+ Context&
+ set_dynamic_shape_enabled(bool is_enabled) {
+ is_dynamic_shape_enabled = is_enabled;
+ return *this;
+ }
+
+ Context&
+ set_override_shape_enabled(bool is_enabled) {
+ is_override_shape_enabled = is_enabled;
+ return *this;
+ }
+
+ bool
+ get_dynamic_shape_enabled() const {
+ return is_dynamic_shape_enabled;
+ }
+
+ bool
+ get_override_shape_enabled() const {
+ return is_override_shape_enabled;
+ }
+
+ int32_t
+ get_target_sm_count() const {
+ return target_sm_count;
+ }
+
+ int32_t
+ get_sm_version() const {
+ return target_sm_version;
+ }
+
+ error_t
+ populate_sm_version_from_device() const {
+ if (target_sm_version > 0) {
+ // Already set by user or previous call
+ return {error_code_t::OK, ""};
+ }
+ cudaDeviceProp prop;
+ int device;
+ _CUDNN_CHECK_CUDA_ERROR(cuda_get_device(&device));
+ _CUDNN_CHECK_CUDA_ERROR(cuda_get_device_properties(&prop, device));
+ target_sm_version = prop.major * 10 + prop.minor;
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Populated SM version from device: " << device << " " << target_sm_version);
+ return {error_code_t::OK, ""};
+ }
+
+ Context&
+ fill_missing_properties(Context const& global_context) {
+ if (get_compute_data_type() == DataType_t::NOT_SET) {
+ set_compute_data_type(global_context.get_compute_data_type());
+ }
+ if (get_intermediate_data_type() == DataType_t::NOT_SET) {
+ set_intermediate_data_type(global_context.get_intermediate_data_type());
+ }
+ if (get_io_data_type() == DataType_t::NOT_SET) {
+ set_io_data_type(global_context.get_io_data_type());
+ }
+ return *this;
+ }
+};
+
+} // namespace cudnn_frontend::detail \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/cudnn_interface.h b/deps/cudnn-frontend/include/cudnn_frontend/cudnn_interface.h
new file mode 100644
index 0000000..c16d6eb
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/cudnn_interface.h
@@ -0,0 +1,251 @@
+#pragma once
+
+#include <memory>
+#include <vector>
+#include <unordered_map>
+
+#include "../cudnn_frontend_Tensor.h"
+#include "../cudnn_frontend_Operation.h"
+#include "../cudnn_frontend_OperationGraph.h"
+#include "../cudnn_frontend_EngineConfig.h"
+#include "../cudnn_frontend_ExecutionPlan.h"
+#include "../cudnn_frontend_VariantPack.h"
+
+#include "graph_properties.h"
+#include "graph_helpers.h"
+#include "plans.h"
+
+namespace cudnn_frontend {
+
+namespace detail {
+inline void
+assign_uid(graph::Tensor_attributes* const tensor,
+ int64_t& potential_uid,
+ std::unordered_set<int64_t> const& used_uids) {
+ // get_next_potential_uid
+ while (used_uids.find(potential_uid) != used_uids.end()) {
+ ++potential_uid;
+ }
+
+ tensor->set_uid(potential_uid);
+ ++potential_uid; // increment, as used its used now
+}
+
+// TODO: Always returns OK. Can the status and error message be accessed from tensor descriptor?
+inline error_t
+create_cudnn_tensor(
+ std::shared_ptr<graph::Tensor_attributes> const& props,
+ std::unordered_map<graph::Tensor_attributes::uid_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors,
+ int64_t& potential_uid,
+ std::unordered_set<int64_t> const& used_uids) {
+ // Assign tensor a uid
+ if (props->has_uid() == false) {
+ assign_uid(props.get(), potential_uid, used_uids);
+ }
+
+ // Check whether backend tensor already created
+ auto tensor_uid = props->get_uid();
+ if (tensors.find(tensor_uid) != tensors.end()) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Backend Tensor named '" << props->get_name() << "' with UID " << tensor_uid
+ << " already created.");
+ return {error_code_t::OK, ""};
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Backend Tensor named '" << props->get_name() << "' with UID " << tensor_uid
+ << " being created.");
+
+ auto&& tensor_builder = cudnn_frontend::TensorBuilder();
+
+ tensor_builder.setDim(props->get_dim().size(), props->get_dim().data())
+ .setStrides(props->get_stride().size(), props->get_stride().data())
+ .setId(tensor_uid)
+ .setAlignment(props->get_alignment())
+ .setDataType(props->get_data_type())
+ .setVirtual(props->get_is_virtual())
+ .setByValue(props->get_is_pass_by_value())
+ .setReorderType(props->get_reordering_type());
+
+ // Set vector count and dimension if they are non-default
+ if (props->get_vector_count() > 1 || props->get_vector_dimension() >= 0) {
+ tensor_builder.setVectorCountAndDimension(props->get_vector_count(), props->get_vector_dimension());
+ }
+
+ // Set compile-time constant value before build (if present)
+ if (props->get_has_compile_time_constant()) {
+ auto const_value = props->get_compile_time_constant();
+ if (const_value.has_value()) {
+ std::visit([&tensor_builder](auto&& val) { tensor_builder.setConstValue(val); }, *const_value);
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Compile-time constant value set for tensor '" << props->get_name()
+ << "'");
+ }
+ }
+
+ if (auto ragged_offset_props = props->get_ragged_offset()) {
+ CHECK_CUDNN_FRONTEND_ERROR(create_cudnn_tensor(ragged_offset_props, tensors, potential_uid, used_uids));
+ tensor_builder.setRaggedOffset(tensors.at(ragged_offset_props->get_uid()));
+ }
+ if (props->has_ragged_offset_multiplier()) {
+ tensor_builder.setRaggedOffsetMultiplier(props->get_ragged_offset_multiplier());
+ }
+
+#ifdef NV_CUDNN_DISABLE_EXCEPTION
+ // disable exception macro is defined. Calling build will not throw.
+ // Check status of desc and return error.
+ auto tensor = tensor_builder.build();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ tensor.get_status() != CUDNN_STATUS_SUCCESS, error_code_t::CUDNN_BACKEND_API_FAILED, tensor.get_error());
+ tensors.emplace(tensor_uid, std::make_shared<Tensor>(std::move(tensor)));
+#else
+ // build() can throw
+ // wrap in try catch
+ try {
+ auto tensor = tensor_builder.build();
+ tensors.emplace(tensor_uid, std::make_shared<Tensor>(std::move(tensor)));
+ } catch (cudnn_frontend::cudnnException& e) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ e.getCudnnStatus() != CUDNN_STATUS_SUCCESS, error_code_t::CUDNN_BACKEND_API_FAILED, e.what());
+ }
+#endif
+
+ return {error_code_t::OK, ""};
+}
+} // namespace detail
+
+namespace graph {
+class UnifiedSDPANode;
+} // namespace graph
+
+class ICudnn {
+ friend class graph::UnifiedSDPANode;
+
+ protected:
+ using uid_t = int64_t;
+
+ //// Store tensors and operations as they (probably?) need to be kept alive.
+ //
+ // The tensor mapping from fe::Tensor to be::Tensor.
+ //
+ // sub nodes share fe::Tensor. Example, in a conv-bias graph, conv output Y and bias input IN_0 are the same
+ // fe::Tensor. But both sub ndoes need to work together to make sure only one be::Tensor is created. Hence this
+ // uid_to_backend_tensors acts as the global registry for each sub node to use.
+ //
+ // Key cannot be fe::Tensor, or shared_ptr<fe::Tensor>, or underlying object address of fe::Tensor.
+ // Hence using uid, as that uniquely identifies both types of tensors.
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>> uid_to_tensors;
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>> operations;
+ graph::managed_backend_descriptor_t raw_operations;
+
+ std::shared_ptr<OperationGraph_v8> operation_graph;
+ std::unordered_set<graph::Tensor_attributes::uid_t> variant_pack_uids;
+
+ graph::Execution_plan_list plans;
+
+ bool is_dynamic_shape_enabled = false;
+ std::shared_ptr<KernelCache> kernel_cache = nullptr;
+
+ bool is_override_shape_enabled = false;
+
+ std::shared_ptr<const DeviceProperties> device_properties = nullptr;
+
+ std::shared_ptr<OperationGraph_v8>
+ get_operation_graph() const {
+ return operation_graph;
+ }
+
+ error_t
+ create_cudnn_operation_graph(cudnnHandle_t handle) {
+ std::vector<Operation const*> cudnn_operations;
+ for (std::shared_ptr<cudnn_frontend::Operation> operation : operations) {
+ cudnn_operations.push_back(operation.get());
+ }
+
+ auto&& cudnn_operation_graph_builder = cudnn_frontend::OperationGraphBuilder();
+ cudnn_operation_graph_builder.setHandle(handle)
+ .setOperationGraph(cudnn_operations.size(), cudnn_operations.data())
+ .setIsDynamicShapeEnabled(is_dynamic_shape_enabled)
+ .setIsOverrideShapeEnabled(is_override_shape_enabled);
+ for (auto& op : raw_operations) {
+ cudnn_operation_graph_builder.addOperation(op);
+ }
+
+#ifdef NV_CUDNN_DISABLE_EXCEPTION
+ // disable exception macro is defined. Calling build will not throw.
+ // Check status of desc and return error.
+ auto cudnn_operation_graph = cudnn_operation_graph_builder.build();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cudnn_operation_graph.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ cudnn_operation_graph.get_error());
+ operation_graph = std::make_shared<OperationGraph_v8>(std::move(cudnn_operation_graph));
+#else
+ // build() can throw
+ // wrap in try catch
+ try {
+ auto cudnn_operation_graph = cudnn_operation_graph_builder.build();
+ operation_graph = std::make_shared<OperationGraph_v8>(std::move(cudnn_operation_graph));
+ } catch (cudnn_frontend::cudnnException& e) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ e.getCudnnStatus() != CUDNN_STATUS_SUCCESS, error_code_t::CUDNN_BACKEND_API_FAILED, e.what());
+ }
+#endif
+ return {error_code_t::OK, "Successfully built Operation Graph."};
+ }
+
+ public:
+ error_t
+ get_cudnn_workspace_size_node(int64_t const plan_index, int64_t& cudnn_workspace_size) const {
+ CHECK_CUDNN_FRONTEND_ERROR(plans.is_plan_index_executable(plan_index));
+
+ cudnn_workspace_size = std::max(cudnn_workspace_size, plans.execution_plans[plan_index]->getWorkspaceSize());
+
+ return {error_code_t::OK, ""};
+ }
+
+ int64_t
+ get_max_cudnn_workspace_size_node() const {
+ return plans.get_autotune_workspace();
+ }
+
+ error_t
+ execute_cudnn_plan_with_uid(cudnnHandle_t handle,
+ std::unordered_map<int64_t, void*> const& tensor_uid_to_pointer_map,
+ void* workspace_ptr,
+ int64_t plan_index,
+ std::vector<int64_t> const& override_uids,
+ std::vector<std::vector<int64_t>> const& override_shapes,
+ std::vector<std::vector<int64_t>> const& override_strides) const {
+ // Make sure device pointer is provided for all uids expected for this plan
+ std::vector<void*> device_ptrs;
+ std::vector<uid_t> uids;
+ for (auto const& uid : variant_pack_uids) {
+ auto search = tensor_uid_to_pointer_map.find(uid);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(search == tensor_uid_to_pointer_map.end(),
+ error_code_t::INVALID_VARIANT_PACK,
+ "Uid " + std::to_string(uid) + " does not exist in variant pack.");
+ device_ptrs.push_back(search->second);
+ uids.push_back(uid);
+ }
+
+ CHECK_CUDNN_FRONTEND_ERROR(plans.is_plan_index_executable(plan_index));
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executing plan at index " << plan_index
+ << " with override uids: " << override_uids.size());
+
+ if (override_uids.size() == 0) {
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::execute(handle, plans.execution_plans[plan_index].get(), device_ptrs, uids, workspace_ptr));
+ } else {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::execute(handle,
+ plans.execution_plans[plan_index].get(),
+ device_ptrs,
+ uids,
+ workspace_ptr,
+ override_uids,
+ override_shapes,
+ override_strides));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+};
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/attention_utils.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/attention_utils.h
new file mode 100644
index 0000000..b44a55e
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/attention_utils.h
@@ -0,0 +1,385 @@
+#pragma once
+
+#include <cstdint>
+#include <sstream>
+#include <string>
+#include <vector>
+
+// cudaLibrary_t, cudaKernel_t, cudaJitOption, cudaLibraryOption etc.
+// were introduced in CUDA 12.8. On older toolkits (or when using dynamic
+// loading where cuda_runtime.h may lack these types), provide typedefs
+// from the driver API equivalents (available via cuda.h) so that
+// engine headers can declare members without #ifdef clutter.
+// The actual runtime API functions are guarded by CUDART_VERSION checks below.
+#if !defined(CUDART_VERSION) || CUDART_VERSION < 12080
+using cudaLibrary_t = CUlibrary;
+using cudaKernel_t = CUkernel;
+using cudaJitOption = CUjit_option;
+using cudaLibraryOption = CUlibraryOption;
+#endif
+
+namespace cudnn_frontend::experimental {
+
+// ============================================================
+// Internal types matching generated kernel parameter layouts
+// ============================================================
+
+struct AttentionShape_t {
+ uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v;
+};
+
+struct AttentionDescriptor_t {
+ uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v;
+ uint16_t q_heads_per_k, q_heads_per_v, min_q_heads_per_kv;
+};
+
+struct FastDivisor_t {
+ uint32_t val, shr, mul;
+};
+
+struct tensor_descriptor {
+ static const int MAX_DIMS = 12;
+ int64_t num_dims;
+ int64_t dims[MAX_DIMS];
+ int64_t strides[MAX_DIMS];
+};
+
+// ============================================================
+// Utility functions
+// ============================================================
+
+inline int
+div_up(int a, int b) {
+ return (a + b - 1) / b;
+}
+
+// floor(log2(x)) for x > 0.
+inline int
+find_log_2_floor(uint32_t x) {
+ if (x <= 1) return 0;
+ int a = 0;
+ while ((1u << (a + 1)) <= x) a++;
+ return a;
+}
+
+// Compute FastDivisor_t for the kernel's fastDivMod which uses:
+// div = __umulhi(2 * val, mul) >> shr
+// This matches cuDNN backend's find_divisor_v2 fast-math helper.
+inline FastDivisor_t
+make_fast_divisor(uint32_t divisor) {
+ FastDivisor_t d;
+ d.val = divisor;
+
+ if (divisor <= 1) {
+ // Division by 1: umulhi(2*val, 0x80000000) >> 0 = val, mod = 0
+ d.shr = 0;
+ d.mul = 0x80000000u;
+ return d;
+ }
+
+ // find_log_2(2 * divisor, round_up=true)
+ uint32_t x2 = 2u * divisor;
+ int a = 0;
+ {
+ uint32_t tmp = x2;
+ while (tmp > 1) {
+ tmp >>= 1;
+ a++;
+ }
+ }
+ // round up if not a power of 2
+ if (x2 & (x2 - 1)) a++;
+
+ uint32_t p = 31 + static_cast<uint32_t>(a);
+ d.mul = static_cast<uint32_t>(((1ULL << p) + static_cast<uint64_t>(x2) - 1) / static_cast<uint64_t>(x2));
+ d.shr = p - 32;
+ return d;
+}
+
+inline std::vector<std::string>
+parse_flags_string(const char* data, size_t len) {
+ std::vector<std::string> flags;
+ std::string content(data, len);
+ std::istringstream stream(content);
+ std::string line;
+ while (std::getline(stream, line)) {
+ size_t start = line.find_first_not_of(" \t\r\n");
+ if (start == std::string::npos) continue;
+ size_t end = line.find_last_not_of(" \t\r\n");
+ line = line.substr(start, end - start + 1);
+ if (!line.empty()) {
+ flags.push_back(line);
+ }
+ }
+ return flags;
+}
+
+// ============================================================
+// Kernel specification (compile-time metadata per kernel variant)
+// ============================================================
+
+struct KernelSpec {
+ const char* source;
+ size_t source_len;
+ const char* flags_raw;
+ size_t flags_len;
+ const char* kernel_name;
+ int tile_m, tile_n, tile_k;
+ int smem_bytes;
+};
+
+// ============================================================
+// CUDA runtime API wrappers (using NV_FE_CALL_TO_CUDA)
+// ============================================================
+
+namespace detail {
+
+// NV_FE_CALL_TO_CUDA macros reference symbols in cudnn_frontend::detail
+// via unqualified lookup. Import them into this namespace.
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+using cudnn_frontend::detail::CudaLibrary;
+using cudnn_frontend::detail::get_cuda_symbol;
+#endif
+
+// Re-export CUDA runtime wrappers from the main shim so the engine
+// never calls cudaMalloc/cudaFree/etc. directly (required for dynamic loading).
+using cudnn_frontend::detail::cuda_get_device;
+using cudnn_frontend::detail::cuda_get_device_properties;
+using cudnn_frontend::detail::cuda_get_error_string;
+using cudnn_frontend::detail::cuda_mem_cpy_async;
+using cudnn_frontend::detail::cuda_mem_set_async;
+
+// Write a 32-bit pattern to device memory (async, on stream).
+// Uses thread_local storage so the source buffer persists through the async copy.
+// Only used with N=1 in practice (writing float 1.0f for FP8 default scale).
+// Cannot use NV_FE_CALL_TO_CUDA because cudaMemcpyAsync has more args than this wrapper.
+inline cudaError_t
+cuda_mem_set_d32_async(void* dstDevice, unsigned int ui, size_t N, cudaStream_t stream) {
+ static thread_local unsigned int val;
+ val = ui;
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ using fn_t = cudaError_t (*)(void*, const void*, size_t, cudaMemcpyKind, cudaStream_t);
+ auto _fn = reinterpret_cast<fn_t>(cudnn_frontend::detail::get_cuda_symbol(CudaLibrary::CUDART, "cudaMemcpyAsync"));
+ return _fn(dstDevice, &val, N * sizeof(unsigned int), cudaMemcpyHostToDevice, stream);
+#else
+ return cudaMemcpyAsync(dstDevice, &val, N * sizeof(unsigned int), cudaMemcpyHostToDevice, stream);
+#endif
+}
+
+// Convert cudaError_t to a descriptive string (e.g., "invalid argument")
+inline std::string
+cuda_error_to_string(cudaError_t err) {
+ const char* str = cuda_get_error_string(err);
+ return str ? std::string(str) : ("cudaError=" + std::to_string(static_cast<int>(err)));
+}
+
+// cudaGetLastError takes zero arguments — can't use NV_FE_CALL_TO_CUDA
+// (variadic macro requires at least one arg). Handle both paths manually.
+inline cudaError_t
+cuda_get_last_error() {
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ using fn_t = cudaError_t (*)();
+ auto _fn = reinterpret_cast<fn_t>(cudnn_frontend::detail::get_cuda_symbol(CudaLibrary::CUDART, "cudaGetLastError"));
+ return _fn();
+#else
+ return cudaGetLastError();
+#endif
+}
+
+// ============================================================
+// CUDA 12.8+ runtime API wrappers for library/kernel management.
+// These APIs (cudaLibraryLoadData, cudaLibraryGetKernel, cudaLibraryUnload,
+// cudaKernelSetAttributeForDevice, cudaGetDriverEntryPointByVersion) require
+// CUDART_VERSION >= 12080. On older toolkits, the OSS engine check_support()
+// will reject the configuration before these are called.
+// ============================================================
+
+#if !defined(NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING) && defined(CUDART_VERSION) && CUDART_VERSION < 12080
+
+// Stubs that return errors — OSS engines require CUDA 12.8+.
+inline cudaError_t
+cuda_library_load_data(void*, const void*, void*, void**, unsigned int, void*, void**, unsigned int) {
+ return cudaErrorNotSupported;
+}
+inline cudaError_t
+cuda_library_get_kernel(void*, void*, const char*) {
+ return cudaErrorNotSupported;
+}
+inline cudaError_t
+cuda_library_unload(void*) {
+ return cudaErrorNotSupported;
+}
+inline cudaError_t
+cuda_kernel_set_attribute_for_device(void*, int, int, int) {
+ return cudaErrorNotSupported;
+}
+
+#else // CUDART_VERSION >= 12080 or dynamic loading
+
+inline cudaError_t
+cuda_library_load_data(cudaLibrary_t* library,
+ const void* code,
+ cudaJitOption* jitOptions,
+ void** jitOptionsValues,
+ unsigned int numJitOptions,
+ cudaLibraryOption* libraryOptions,
+ void** libraryOptionsValues,
+ unsigned int numLibraryOptions) {
+ NV_FE_CALL_TO_CUDA(cuda_library_load_data,
+ cudaLibraryLoadData,
+ library,
+ code,
+ jitOptions,
+ jitOptionsValues,
+ numJitOptions,
+ libraryOptions,
+ libraryOptionsValues,
+ numLibraryOptions);
+}
+
+inline cudaError_t
+cuda_library_get_kernel(cudaKernel_t* pKernel, cudaLibrary_t library, const char* name) {
+ NV_FE_CALL_TO_CUDA(cuda_library_get_kernel, cudaLibraryGetKernel, pKernel, library, name);
+}
+
+inline cudaError_t
+cuda_library_unload(cudaLibrary_t library) {
+ NV_FE_CALL_TO_CUDA(cuda_library_unload, cudaLibraryUnload, library);
+}
+
+inline cudaError_t
+cuda_kernel_set_attribute_for_device(cudaKernel_t kernel, cudaFuncAttribute attrib, int val, int dev) {
+ NV_FE_CALL_TO_CUDA(cuda_kernel_set_attribute_for_device, cudaKernelSetAttributeForDevice, kernel, attrib, val, dev);
+}
+
+#endif // CUDART_VERSION check
+
+inline cudaError_t
+cuda_launch_kernel(const void* func, dim3 gridDim, dim3 blockDim, void** args, size_t sharedMem, cudaStream_t stream) {
+ NV_FE_CALL_TO_CUDA(cuda_launch_kernel, cudaLaunchKernel, func, gridDim, blockDim, args, sharedMem, stream);
+}
+
+// cuTensorMapEncodeTiled has no runtime API equivalent.
+// Resolve the driver function pointer via cudaGetDriverEntryPointByVersion
+// so we never link against libcuda.so directly. Requires CUDA 12.8+.
+inline CUresult
+cu_tensor_map_encode_tiled(CUtensorMap* tensorMap,
+ CUtensorMapDataType tensorDataType,
+ cuuint32_t tensorRank,
+ void* globalAddress,
+ const cuuint64_t* globalDim,
+ const cuuint64_t* globalStrides,
+ const cuuint32_t* boxDim,
+ const cuuint32_t* elementStrides,
+ CUtensorMapInterleave interleave,
+ CUtensorMapSwizzle swizzle,
+ CUtensorMapL2promotion l2Promotion,
+ CUtensorMapFloatOOBfill oobFill) {
+#if !defined(NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING) && defined(CUDART_VERSION) && CUDART_VERSION < 12080
+ (void)tensorMap;
+ (void)tensorDataType;
+ (void)tensorRank;
+ (void)globalAddress;
+ (void)globalDim;
+ (void)globalStrides;
+ (void)boxDim;
+ (void)elementStrides;
+ (void)interleave;
+ (void)swizzle;
+ (void)l2Promotion;
+ (void)oobFill;
+ return CUDA_ERROR_NOT_SUPPORTED;
+#else
+ using PFN = CUresult(CUDAAPI*)(CUtensorMap*,
+ CUtensorMapDataType,
+ cuuint32_t,
+ void*,
+ const cuuint64_t*,
+ const cuuint64_t*,
+ const cuuint32_t*,
+ const cuuint32_t*,
+ CUtensorMapInterleave,
+ CUtensorMapSwizzle,
+ CUtensorMapL2promotion,
+ CUtensorMapFloatOOBfill);
+ // Thread-safe static initialization (C++11 guarantees)
+ static const PFN pfn = []() -> PFN {
+ void* raw_pfn = nullptr;
+ cudaDriverEntryPointQueryResult status;
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ // In dynamic loading mode, resolve cudaGetDriverEntryPointByVersion via dlsym
+ using GetEntryPointFn =
+ cudaError_t (*)(const char*, void**, unsigned int, int, cudaDriverEntryPointQueryResult*);
+ auto get_entry_point = reinterpret_cast<GetEntryPointFn>(
+ cudnn_frontend::detail::get_cuda_symbol(CudaLibrary::CUDART, "cudaGetDriverEntryPointByVersion"));
+ cudaError_t err = get_entry_point("cuTensorMapEncodeTiled", &raw_pfn, 12000, cudaEnableDefault, &status);
+#else
+ cudaError_t err =
+ cudaGetDriverEntryPointByVersion("cuTensorMapEncodeTiled", &raw_pfn, 12000, cudaEnableDefault, &status);
+#endif
+ if (err != cudaSuccess || status != cudaDriverEntryPointSuccess || !raw_pfn) {
+ return nullptr;
+ }
+ return reinterpret_cast<PFN>(raw_pfn);
+ }();
+ if (!pfn) {
+ return CUDA_ERROR_NOT_FOUND;
+ }
+ return pfn(tensorMap,
+ tensorDataType,
+ tensorRank,
+ globalAddress,
+ globalDim,
+ globalStrides,
+ boxDim,
+ elementStrides,
+ interleave,
+ swizzle,
+ l2Promotion,
+ oobFill);
+#endif // CUDART_VERSION check
+}
+
+} // namespace detail
+
+// ============================================================
+// TMA descriptor creation (4D)
+// ============================================================
+inline error_t
+create_tma_desc_4d(CUtensorMap* desc,
+ void* globalAddress,
+ CUtensorMapDataType dataType,
+ uint32_t dim0,
+ uint32_t dim1,
+ uint32_t dim2,
+ uint32_t dim3,
+ uint64_t stride1_bytes,
+ uint64_t stride2_bytes,
+ uint64_t stride3_bytes,
+ uint32_t boxDim0,
+ uint32_t boxDim1,
+ CUtensorMapSwizzle swizzle) {
+ uint64_t globalDims[4] = {dim0, dim1, dim2, dim3};
+ uint64_t globalStrides[3] = {stride1_bytes, stride2_bytes, stride3_bytes};
+ uint32_t boxDims[4] = {boxDim0, boxDim1, 1, 1};
+ uint32_t elemStrides[4] = {1, 1, 1, 1};
+
+ CUresult err_status = detail::cu_tensor_map_encode_tiled(desc,
+ dataType,
+ 4,
+ globalAddress,
+ globalDims,
+ globalStrides,
+ boxDims,
+ elemStrides,
+ CU_TENSOR_MAP_INTERLEAVE_NONE,
+ swizzle,
+ CU_TENSOR_MAP_L2_PROMOTION_NONE,
+ CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ err_status != CUDA_SUCCESS, error_code_t::CUDA_API_FAILED, "cuTensorMapEncodeTiled failed");
+ return {error_code_t::OK, ""};
+}
+
+} // namespace cudnn_frontend::experimental \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/nvrtc_shim.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/nvrtc_shim.h
new file mode 100644
index 0000000..eaad3de
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/nvrtc_shim.h
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <nvrtc.h>
+#include <cuda_runtime.h> // for cudaError_t (needed by cudnn_frontend_shim.h wrappers)
+
+// Pull in HMODULE, dlopen, dlsym, dlclose macros and platform definitions
+// from the existing cudnn_frontend shim infrastructure.
+#include "../../cudnn_frontend_shim.h"
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+#include <mutex>
+#endif
+
+namespace cudnn_frontend {
+namespace experimental {
+namespace detail {
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+
+/// @brief Attempt to dynamically load the NVRTC shared library.
+///
+/// Tries a sequence of candidate library names in order, returning
+/// the handle for the first one that loads successfully.
+///
+/// @return A valid library handle on success, or nullptr on failure.
+/// This function does NOT throw.
+inline HMODULE
+load_nvrtc_so() {
+#ifdef _WIN32
+ constexpr const char *candidates[] = {
+ "nvrtc64_131_0.dll",
+ "nvrtc64_130_0.dll",
+ "nvrtc64_120_0.dll",
+ };
+#else
+ constexpr const char *candidates[] = {
+ "libnvrtc.so",
+ "libnvrtc.so.13",
+ "libnvrtc.so.12",
+ };
+#endif
+ constexpr size_t num_candidates = sizeof(candidates) / sizeof(candidates[0]);
+
+ for (size_t i = 0; i < num_candidates; ++i) {
+ // Clear any prior error state
+ dlerror();
+
+ HMODULE handle = dlopen(candidates[i], RTLD_NOW);
+ if (handle) {
+ return handle;
+ }
+ }
+
+ // All candidates failed -- return nullptr (no throw)
+ return nullptr;
+}
+
+/// @brief Look up a symbol in the dynamically-loaded NVRTC library.
+///
+/// The library handle is loaded once (lazily, thread-safe) and cached
+/// in a function-local static. If the library could not be loaded,
+/// every call returns nullptr.
+///
+/// @param function_name The mangled / C symbol name to resolve.
+/// @return A generic pointer to the symbol, or nullptr if the library
+/// is not loaded or the symbol is not found.
+inline void *
+get_nvrtc_symbol(const char *function_name) {
+ static std::mutex nvrtc_lib_mutex;
+ static HMODULE nvrtc_handle = nullptr;
+ static bool load_attempted = false;
+
+ std::lock_guard<std::mutex> lock(nvrtc_lib_mutex);
+
+ if (!load_attempted) {
+ load_attempted = true;
+ nvrtc_handle = load_nvrtc_so();
+ }
+
+ if (!nvrtc_handle) {
+ return nullptr;
+ }
+
+ // Clear any existing error before calling dlsym
+ dlerror();
+
+ void *symbol = dlsym(nvrtc_handle, function_name);
+ // If dlsym fails we simply return nullptr -- callers decide how to
+ // report the error (the macro returns NVRTC_ERROR_INTERNAL_ERROR).
+ return symbol;
+}
+
+/// @brief Check whether the NVRTC library was successfully loaded.
+///
+/// Internally triggers a lazy load attempt if one has not been made yet.
+///
+/// @return true if the library handle is valid, false otherwise.
+inline bool
+nvrtc_is_loaded() {
+ // Trigger the lazy load by requesting any symbol (the name is
+ // irrelevant -- we only care about whether the handle is valid).
+ // get_nvrtc_symbol will initialise the handle on the first call.
+ get_nvrtc_symbol("nvrtcVersion");
+
+ // We cannot directly inspect the static inside get_nvrtc_symbol,
+ // so we probe for a symbol that must exist in every NVRTC build.
+ return get_nvrtc_symbol("nvrtcVersion") != nullptr;
+}
+
+/// @brief Macro for calling an NVRTC function via dynamic loading.
+///
+/// Looks up @p nvrtc_symbol by name, and if the symbol is nullptr
+/// returns @c NVRTC_ERROR_INTERNAL_ERROR. Otherwise casts the
+/// pointer to the wrapper function's own signature and tail-calls it.
+#define NV_FE_CALL_TO_NVRTC(function_name, nvrtc_symbol, ...) \
+ void *fptr = get_nvrtc_symbol(#nvrtc_symbol); \
+ if (fptr == nullptr) { \
+ return NVRTC_ERROR_INTERNAL_ERROR; \
+ } \
+ return reinterpret_cast<decltype(function_name) *>(fptr)(__VA_ARGS__);
+
+#else // static linking
+
+/// @brief When statically linked NVRTC is always considered loaded.
+inline bool
+nvrtc_is_loaded() {
+ return true;
+}
+
+/// @brief Macro for calling an NVRTC function via static linking.
+///
+/// Simply forwards the call directly to the NVRTC symbol.
+#define NV_FE_CALL_TO_NVRTC(function_name, nvrtc_symbol, ...) return nvrtc_symbol(__VA_ARGS__);
+
+#endif // NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+
+// ---------------------------------------------------------------------------
+// Wrapper functions for the NVRTC API
+//
+// Each wrapper has the exact same signature as the underlying NVRTC
+// function it delegates to. Under dynamic loading the macro resolves
+// the symbol at first call; under static linking the call is direct.
+// ---------------------------------------------------------------------------
+
+/// @brief Create an NVRTC program from source.
+/// @see nvrtcCreateProgram
+inline nvrtcResult
+nvrtc_create_program(nvrtcProgram *prog,
+ const char *src,
+ const char *name,
+ int numHeaders,
+ const char *const *headers,
+ const char *const *includeNames) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_create_program, nvrtcCreateProgram, prog, src, name, numHeaders, headers, includeNames);
+}
+
+/// @brief Destroy an NVRTC program.
+/// @see nvrtcDestroyProgram
+inline nvrtcResult
+nvrtc_destroy_program(nvrtcProgram *prog) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_destroy_program, nvrtcDestroyProgram, prog);
+}
+
+/// @brief Compile an NVRTC program with the given options.
+/// @see nvrtcCompileProgram
+inline nvrtcResult
+nvrtc_compile_program(nvrtcProgram prog, int numOptions, const char *const *options) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_compile_program, nvrtcCompileProgram, prog, numOptions, options);
+}
+
+/// @brief Query the size of the compilation log (including the NUL terminator).
+/// @see nvrtcGetProgramLogSize
+inline nvrtcResult
+nvrtc_get_program_log_size(nvrtcProgram prog, size_t *logSizeRet) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_program_log_size, nvrtcGetProgramLogSize, prog, logSizeRet);
+}
+
+/// @brief Retrieve the compilation log.
+/// @see nvrtcGetProgramLog
+inline nvrtcResult
+nvrtc_get_program_log(nvrtcProgram prog, char *log) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_program_log, nvrtcGetProgramLog, prog, log);
+}
+
+/// @brief Query the size of the compiled CUBIN image.
+/// @see nvrtcGetCUBINSize
+inline nvrtcResult
+nvrtc_get_cubin_size(nvrtcProgram prog, size_t *cubinSizeRet) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_cubin_size, nvrtcGetCUBINSize, prog, cubinSizeRet);
+}
+
+/// @brief Retrieve the compiled CUBIN image.
+/// @see nvrtcGetCUBIN
+inline nvrtcResult
+nvrtc_get_cubin(nvrtcProgram prog, char *cubin) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_cubin, nvrtcGetCUBIN, prog, cubin);
+}
+
+/// @brief Query the size of the generated PTX.
+/// @see nvrtcGetPTXSize
+inline nvrtcResult
+nvrtc_get_ptx_size(nvrtcProgram prog, size_t *ptxSizeRet) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_ptx_size, nvrtcGetPTXSize, prog, ptxSizeRet);
+}
+
+/// @brief Retrieve the generated PTX.
+/// @see nvrtcGetPTX
+inline nvrtcResult
+nvrtc_get_ptx(nvrtcProgram prog, char *ptx) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_ptx, nvrtcGetPTX, prog, ptx);
+}
+
+/// @brief Map an nvrtcResult code to a human-readable string.
+/// @see nvrtcGetErrorString
+inline const char *
+nvrtc_get_error_string(nvrtcResult result) {
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ void *fptr = get_nvrtc_symbol("nvrtcGetErrorString");
+ if (fptr == nullptr) {
+ return "NVRTC error (library not loaded)";
+ }
+ return reinterpret_cast<decltype(nvrtc_get_error_string) *>(fptr)(result);
+#else
+ return nvrtcGetErrorString(result);
+#endif
+}
+
+} // namespace detail
+} // namespace experimental
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/oss_engine_interface.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/oss_engine_interface.h
new file mode 100644
index 0000000..7c0a38e
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/oss_engine_interface.h
@@ -0,0 +1,261 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "nvrtc_shim.h"
+#include "attention_utils.h"
+#include "../graph_helpers.h"
+#include "../../cudnn_frontend_shim.h"
+
+#include <cuda_runtime.h>
+
+#include <cstdint>
+#include <fstream>
+#include <memory>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+// ============================================================
+// IOssSdpaEngine — virtual interface for OSS SDPA engines
+// Implemented by Sm90SdpaPrefillEngine and Sm100SdpaPrefillEngine.
+// ============================================================
+
+class IOssSdpaEngine {
+ public:
+ virtual ~IOssSdpaEngine() = default;
+
+ virtual error_t
+ check_support(AttentionShape_t shape, int sm_version) = 0;
+ virtual error_t
+ build() = 0;
+
+ virtual error_t
+ execute(int batch,
+ int heads_q,
+ int heads_kv,
+ int seq_q,
+ int seq_kv,
+ int d,
+ void* d_Q,
+ std::vector<int64_t> const& q_strides,
+ void* d_K,
+ std::vector<int64_t> const& k_strides,
+ void* d_V,
+ std::vector<int64_t> const& v_strides,
+ void* d_O,
+ std::vector<int64_t> const& o_strides,
+ void* d_max,
+ std::vector<int64_t> const& max_strides,
+ void* d_sum_exp,
+ std::vector<int64_t> const& se_strides,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ std::optional<float> user_attn_scale = std::nullopt) = 0;
+
+ static int64_t
+ get_workspace_size() {
+ return 16;
+ }
+};
+
+// ============================================================
+// IOssNormEngine — virtual interface for OSS norm+activation engines.
+// Implemented by Sm100RmsNormSiluEngine (SM100/Blackwell).
+// Future implementations: Sm90, Sm110, LayerNorm variants, etc.
+// ============================================================
+
+// RmsNormSiluDtype is defined in sm100_rms_norm_silu_knobs.h (self-contained,
+// also used by standalone tests without the framework). All arch-specific
+// engine implementations share this enum.
+//
+// Forward-declared here; concrete implementations #include the knobs header.
+enum class RmsNormSiluDtype : uint8_t;
+
+// Problem shape for RmsNorm+SiLU (extensible for future fields).
+struct NormSiluShape_t {
+ int C = 0; // hidden dimension (columns)
+ int num_tokens = 0; // number of rows
+ RmsNormSiluDtype output_dtype{}; // output data type (bf16, fp8, nvfp4)
+};
+
+// Optional parameters for FP8 / NVFP4 output modes.
+struct RmsNormSiluExtraParams {
+ // FP8 output: quantization scale (float*). If nullptr, uses 1.0 from workspace.
+ void* fp8_scale = nullptr;
+ void* fp8_scale_inv = nullptr; // optional: written by kernel if hasScaleInv
+ void* fp8_amax = nullptr; // optional: written by kernel if hasAmax
+
+ // NVFP4 (1D1X1X) output: row-wise block-scale factors (float*, written by kernel)
+ // Shape: [num_tokens, ceil(C / 16)]
+ void* nvfp4_scale_row = nullptr;
+};
+
+class IOssNormEngine {
+ public:
+ virtual ~IOssNormEngine() = default;
+
+ // Phase 1: Validate that (shape, sm_version) is supported.
+ virtual error_t
+ check_support(NormSiluShape_t shape, int sm_version) = 0;
+
+ // Phase 2: NVRTC compile the kernel for the selected config.
+ virtual error_t
+ build() = 0;
+
+ // Phase 3: Launch the kernel.
+ // input — [num_tokens, C] bf16 input tensor
+ // output — [num_tokens, C] output tensor (bf16, fp8, or nvfp4)
+ // weight — [C] bf16 gamma weights
+ // bias — [C] bf16 beta bias (can be nullptr)
+ // rows — num_tokens
+ // cols — C (hidden dimension)
+ // epsilon — RMSNorm epsilon (for L2Norm equiv: eps_l2 / C)
+ // extra — optional FP8/NVFP4 params (can be empty)
+ virtual error_t
+ execute(void* input,
+ void* output,
+ void* weight,
+ void* bias,
+ int rows,
+ int cols,
+ float epsilon,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ RmsNormSiluExtraParams const& extra = {}) = 0;
+
+ // Workspace size in bytes. The kernel needs an `rs` (inverse RMS) buffer,
+ // plus a float for FP8 default scale if no external scale is provided.
+ virtual int64_t
+ get_workspace_size() const = 0;
+};
+
+// ============================================================
+// Shared NVRTC compilation + module loading
+// Used by both Sm90 and Sm100 engines to avoid code duplication.
+// ============================================================
+
+inline error_t
+compile_and_load_kernel(const KernelSpec* spec,
+ cudaLibrary_t& module,
+ cudaKernel_t& kernelPtr,
+ std::unique_ptr<char[]>& cubin,
+ size_t& cubinSize,
+ std::string& kernelName) {
+ // Ensure NVRTC library is available
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !detail::nvrtc_is_loaded(), error_code_t::CUDA_API_FAILED, "NVRTC library could not be loaded");
+
+ // Parse flags from embedded string
+ std::vector<std::string> flags = parse_flags_string(spec->flags_raw, spec->flags_len);
+ std::vector<const char*> flag_ptrs;
+ flag_ptrs.reserve(flags.size());
+ for (auto& f : flags) {
+ flag_ptrs.push_back(f.c_str());
+ }
+
+ // Create NVRTC program from embedded source
+ nvrtcProgram prog;
+ nvrtcResult nvrtc_err;
+
+ nvrtc_err = detail::nvrtc_create_program(&prog, spec->source, "kernel.cu", 0, nullptr, nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcCreateProgram failed");
+
+ // Compile
+ nvrtcResult compResult = detail::nvrtc_compile_program(prog, (int)flag_ptrs.size(), flag_ptrs.data());
+
+ if (cudnn_frontend::isLoggingEnabled()) {
+ // Write the source to a file for debugging
+ std::ofstream ofs("kernel.cu");
+ ofs << spec->source;
+
+ // Try to dump PTX (cicc may have succeeded even if ptxas failed)
+ size_t ptxSize = 0;
+ if (detail::nvrtc_get_ptx_size(prog, &ptxSize) == NVRTC_SUCCESS && ptxSize > 1) {
+ std::vector<char> ptx(ptxSize);
+ if (detail::nvrtc_get_ptx(prog, ptx.data()) == NVRTC_SUCCESS) {
+ std::ofstream ptx_ofs("kernel.ptx");
+ ptx_ofs.write(ptx.data(), static_cast<std::streamsize>(ptxSize - 1));
+ }
+ }
+ }
+
+ if (compResult != NVRTC_SUCCESS) {
+ // Try to retrieve the compilation log for diagnostics
+ size_t logSize = 0;
+ detail::nvrtc_get_program_log_size(prog, &logSize);
+ std::string log_msg = "NVRTC compilation failed";
+ if (logSize > 1) {
+ std::vector<char> log(logSize);
+ detail::nvrtc_get_program_log(prog, log.data());
+ log_msg += ": ";
+ log_msg += log.data();
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: NVRTC compilation failed: " << log_msg);
+ detail::nvrtc_destroy_program(&prog);
+ return {error_code_t::CUDA_API_FAILED, log_msg};
+ }
+
+ // Extract CUBIN
+ nvrtc_err = detail::nvrtc_get_cubin_size(prog, &cubinSize);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcGetCUBINSize failed");
+
+ cubin = std::make_unique<char[]>(cubinSize);
+
+ nvrtc_err = detail::nvrtc_get_cubin(prog, cubin.get());
+ RETURN_CUDNN_FRONTEND_ERROR_IF(nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcGetCUBIN failed");
+
+ nvrtc_err = detail::nvrtc_destroy_program(&prog);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcDestroyProgram failed");
+
+ // Load module + extract kernel function
+ cudaError_t cuda_err;
+
+ cuda_err = detail::cuda_library_load_data(&module, cubin.get(), nullptr, nullptr, 0, nullptr, nullptr, 0);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLibraryLoadData failed (cubin_size=" + std::to_string(cubinSize) +
+ ", error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ kernelName = spec->kernel_name;
+ cuda_err = detail::cuda_library_get_kernel(&kernelPtr, module, kernelName.c_str());
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLibraryGetKernel failed: " + detail::cuda_error_to_string(cuda_err) + " (kernel: " + kernelName + ")");
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: NVRTC compilation successful, kernel: " << kernelName);
+ return {error_code_t::OK, ""};
+}
+
+} // namespace experimental
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_engine.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_engine.h
new file mode 100644
index 0000000..bb7048c
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_engine.h
@@ -0,0 +1,697 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "oss_engine_interface.h"
+#include "sm100_rms_norm_silu_knobs.h"
+// LN headers and kernel source for NVRTC compilation.
+#include "../generated/rms_norm_silu/sm100/ln_headers.h"
+#include "../generated/rms_norm_silu/sm100/ln_fwd_silu_kernel.h"
+
+#include <cuda_fp16.h>
+#include <algorithm>
+#include <cmath>
+#include <string>
+#include <memory>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+// ============================================================
+// PersistentLnFwdParams — matches the kernel's expected parameter struct.
+// Matches the kernel's expected parameter struct layout (PersistentLnFwdParams).
+// ============================================================
+
+struct PersistentLnFwdParams {
+ int ctas_per_col = 0;
+ int rows = 0;
+ int cols = 0;
+ int batchSize = 1;
+ int seqLen = 1;
+
+ void* x = nullptr;
+ void* mu = nullptr;
+ void* rs = nullptr;
+ void* gamma = nullptr;
+
+ void* workspace = nullptr;
+ int* barrier = nullptr;
+
+ bool isRMSNorm = false;
+ bool noScale = false;
+ bool noBias = false;
+ bool isAdaLN = false;
+ bool isBatchFirst = true;
+
+ // Output
+ void* z = nullptr;
+ void* beta = nullptr;
+ float epsilon = 0.f;
+
+ // FP8
+ bool fp8_out = false;
+ float* scale = nullptr;
+ float* scale_inv = nullptr;
+ float* amax = nullptr;
+
+ // Block scale (NVFP4) — field order must match CuDNN's ln.h exactly
+ void* scale_row = nullptr;
+ void* scale_col = nullptr; // only used in 1d2x2x
+ void* z_col = nullptr; // only used in 1d2x2x
+ void* z_math = nullptr; // only used for 1d2x2x colwise kernel
+};
+
+// ============================================================
+// reduced_divisor — matches the kernel's expected second argument.
+// Matches the kernel's expected second argument (reduced_divisor).
+// ============================================================
+
+struct reduced_divisor {
+ uint32_t mul_coeff = 0;
+ uint32_t shift_coeff = 0;
+ int32_t y = 0;
+
+ reduced_divisor() = default;
+ reduced_divisor(int32_t _y) : y(_y) {
+ if (_y <= 1) {
+ mul_coeff = 0;
+ shift_coeff = 0;
+ return;
+ }
+ // Find shift such that 2^(32+shift) / y fits in 32 bits
+ for (shift_coeff = 0; shift_coeff < 32; ++shift_coeff) {
+ uint64_t one = 1;
+ uint64_t num = (one << (32 + shift_coeff));
+ uint64_t den = static_cast<uint64_t>(_y);
+ if (num / den < (one << 32)) {
+ mul_coeff = static_cast<uint32_t>(num / den + 1);
+ break;
+ }
+ }
+ }
+};
+
+// ============================================================
+// Sm100RmsNormSiluEngine
+// ============================================================
+
+class Sm100RmsNormSiluEngine : public IOssNormEngine {
+ public:
+ Sm100RmsNormSiluEngine() = default;
+
+ ~Sm100RmsNormSiluEngine() override {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ }
+
+ // Non-copyable
+ Sm100RmsNormSiluEngine(const Sm100RmsNormSiluEngine&) = delete;
+ Sm100RmsNormSiluEngine&
+ operator=(const Sm100RmsNormSiluEngine&) = delete;
+
+ // ---- Phase 1: Support check + knob selection ----
+ error_t
+ check_support(NormSiluShape_t shape, int sm_version) override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sm_version < 80, error_code_t::GRAPH_NOT_SUPPORTED, "RmsNormSiluEngine requires SM80+");
+
+ // FP8 output requires SM89+ (Ada Lovelace / Hopper)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(shape.output_dtype == RmsNormSiluDtype::FP8 && sm_version < 89,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "FP8 output requires SM89+ (Ada/Hopper)");
+
+ // NVFP4 output requires SM100+ (Blackwell)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(shape.output_dtype == RmsNormSiluDtype::NVFP4 && sm_version < 100,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "NVFP4 output requires SM100+ (Blackwell)");
+
+ sm_version_ = sm_version;
+
+ // Look up knobs: SM100 uses sweep-tuned LUT, other archs use fallback heuristic
+ knobs_ = lookup_rms_norm_silu_knobs(shape.C, shape.num_tokens, shape.output_dtype, sm_version);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ knobs_ == nullptr,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Unsupported problem size: C=" + std::to_string(shape.C) + " tokens=" + std::to_string(shape.num_tokens));
+
+ C_ = shape.C;
+ num_tokens_ = shape.num_tokens;
+ output_dtype_ = shape.output_dtype;
+ bytes_per_ldg_ = knobs_->bytes_per_ldg;
+
+ // Derived config
+ warps_m_ = knobs_->warps_m;
+ warps_n_ = 1; // Always 1
+ threads_per_cta_ = warps_m_ * warps_n_ * 32;
+
+ // Estimate CTAS_PER_ROW when the sweep found column splitting optimal.
+ // Matches CuDNN's estimate_ctas_per_row() from LayerNorm_common.cpp:
+ // Find largest LDGS per CTA that avoids register spilling (< 64/NUM_ELTS),
+ // then CTAS_PER_ROW = total_ldgs / ldgs_per_cta.
+ // kernel_cfg=2 (non-persistent) requires CTAS_PER_ROW=1.
+ if (knobs_->split_cols == 4 && knobs_->kernel_cfg != 2) {
+ int input_size = 2; // bf16
+ int num_elts = bytes_per_ldg_ / input_size;
+ int elts_per_ldg = num_elts * warps_n_ * 32;
+ if (elts_per_ldg > 0 && shape.C % elts_per_ldg == 0) {
+ int ldgs_per_row = shape.C / elts_per_ldg;
+ int ldgs_to_cause_register_spill = (num_elts > 0) ? (64 / num_elts) : 1;
+ ctas_per_row_ = 1;
+ for (int ldgs = std::min(ldgs_per_row, ldgs_to_cause_register_spill - 1); ldgs > 0; ldgs--) {
+ if (ldgs_per_row % ldgs == 0) {
+ ctas_per_row_ = ldgs_per_row / ldgs;
+ break;
+ }
+ }
+ } else {
+ ctas_per_row_ = 1;
+ }
+ } else {
+ ctas_per_row_ = 1;
+ }
+ is_cooperative_ = (ctas_per_row_ > 1);
+
+ // Cache SM count
+ cudaDeviceProp devProp;
+ int device_ordinal = 0;
+ cudaError_t cuda_err = detail::cuda_get_device(&device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDevice failed");
+ cuda_err = detail::cuda_get_device_properties(&devProp, device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDeviceProperties failed");
+ sm_count_ = devProp.multiProcessorCount;
+
+ support_checked_ = true;
+ return {error_code_t::OK, ""};
+ }
+
+ // Workspace layout (all offsets 128-byte aligned):
+ // [0] rs : num_tokens * sizeof(float)
+ // [aligned] fp8_scale : sizeof(float)
+ // [aligned] scale_row : num_tokens * ceil(C/16) bytes (NVFP4 only)
+ // [aligned] coop_workspace : ctas_per_col * WARPS_M * CTAS_PER_ROW * sizeof(float2) * 2
+ // [aligned] coop_barrier : 2 * ctas_per_col * sizeof(int32_t)
+ // + 128 padding
+ int64_t
+ get_workspace_size() const override {
+ int64_t ws = static_cast<int64_t>(num_tokens_) * sizeof(float); // rs
+ ws = ((ws + 127) / 128) * 128;
+ ws += sizeof(float); // FP8 default scale
+ ws = ((ws + 127) / 128) * 128;
+ if (output_dtype_ == RmsNormSiluDtype::NVFP4) {
+ ws += static_cast<int64_t>(num_tokens_) * ((C_ + 15) / 16);
+ ws = ((ws + 127) / 128) * 128;
+ }
+ if (is_cooperative_) {
+ int ctas_per_col = std::max(1, (num_tokens_ + warps_m_ - 1) / warps_m_);
+ // Inter-CTA partial stats: ctas_per_col * WARPS_M * CTAS_PER_ROW * sizeof(float2) * 2
+ ws += static_cast<int64_t>(ctas_per_col) * warps_m_ * ctas_per_row_ * sizeof(float) * 2 * 2;
+ ws = ((ws + 127) / 128) * 128;
+ // Barrier array: 2 * ctas_per_col * sizeof(int32_t)
+ ws += 2 * static_cast<int64_t>(ctas_per_col) * sizeof(int32_t);
+ ws = ((ws + 127) / 128) * 128;
+ }
+ ws += 128; // final alignment
+ return ws;
+ }
+
+ // Get offset of scale_row within workspace (for reading back in tests).
+ // Returns -1 if not NVFP4 output.
+ int64_t
+ get_scale_row_workspace_offset() const {
+ if (output_dtype_ != RmsNormSiluDtype::NVFP4) return -1;
+ int64_t off = static_cast<int64_t>(num_tokens_) * sizeof(float);
+ off = ((off + 127) / 128) * 128;
+ off += sizeof(float);
+ off = ((off + 127) / 128) * 128;
+ return off;
+ }
+
+ int64_t
+ get_scale_row_size_bytes() const {
+ if (output_dtype_ != RmsNormSiluDtype::NVFP4) return 0;
+ return static_cast<int64_t>(num_tokens_) * ((C_ + 15) / 16);
+ }
+
+ // ---- Phase 2: NVRTC compilation ----
+ error_t
+ build() override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!support_checked_ || knobs_ == nullptr,
+ error_code_t::INVALID_VALUE,
+ "build() called before check_support()");
+
+ // Assemble the full kernel source:
+ // 1. Generate constexpr defines from knobs
+ // 2. Prepend to headers + kernel body
+
+ // Order: preamble → headers (defines cuda types) → constexpr defines
+ // (uses those types) → kernel body (uses everything).
+ std::string defines = generate_constexpr_defines();
+
+ // Undefine EWP/RDC to avoid removed cudaCGScopeMultiGrid in cooperative_groups
+ std::string preamble = "#undef __CUDACC_EWP__\n#undef __CUDACC_RDC__\n";
+
+ std::string full_source = preamble + std::string(generated::ln_headers_source) + defines +
+ std::string(generated::ln_fwd_silu_kernel_source);
+
+ // Parse compile flags and override --gpu-architecture for the target SM version
+ std::vector<std::string> flags =
+ parse_flags_string(generated::ln_fwd_silu_kernel_flags, generated::ln_fwd_silu_kernel_flags_len);
+
+ // Replace the embedded --gpu-architecture with the correct arch for this GPU.
+ // The 'a' suffix = architecture-specific (enables SM-specific features like redux.sync).
+ // The 'f' suffix = forward-compatible across an SM family (e.g., sm_100f works on SM100-SM103).
+ // The kernel source has #if __CUDA_ARCH__ guards for SM-specific instructions.
+ {
+ std::string target_arch;
+ if (sm_version_ == 100)
+ target_arch = "sm_100a"; // B200: arch-specific for best codegen
+ else if (sm_version_ > 100 && sm_version_ < 110)
+ target_arch = "sm_100f"; // GB300 etc: forward-compat
+ else if (sm_version_ == 90)
+ target_arch = "sm_90a";
+ else if (sm_version_ > 90 && sm_version_ < 100)
+ target_arch = "sm_90"; // SM92 etc
+ else if (sm_version_ >= 89)
+ target_arch = "sm_89";
+ else if (sm_version_ >= 86)
+ target_arch = "sm_86";
+ else
+ target_arch = "sm_80";
+
+ for (auto& f : flags) {
+ if (f.find("--gpu-architecture=") == 0) {
+ f = "--gpu-architecture=" + target_arch;
+ break;
+ }
+ }
+ }
+
+ // Add CUDA Toolkit include paths for NVRTC to resolve #include <cuda_bf16.h> etc.
+ std::string cuda_include = "/usr/local/cuda/include";
+ if (auto env0 = get_environment("CUDA_HOME")) {
+ cuda_include = std::string(env0) + "/include";
+ } else if (auto env1 = get_environment("CUDA_PATH")) {
+ cuda_include = std::string(env1) + "/include";
+ }
+ flags.push_back("--include-path=" + cuda_include);
+
+ // CCCL headers needed for cuda::ptx:: used by block-scale (NVFP4) code paths.
+ // CUDA 13+ ships CCCL under targets/<arch>-linux/include/cccl.
+ // Add both x86_64 and aarch64 paths — NVRTC silently ignores non-existent paths.
+ std::string cuda_base = cuda_include.substr(0, cuda_include.rfind("/include"));
+ for (const char* arch : {"x86_64", "aarch64"}) {
+ std::string target_dir = cuda_base + "/targets/" + arch + "-linux/include";
+ flags.push_back("--include-path=" + target_dir);
+ flags.push_back("--include-path=" + target_dir + "/cccl");
+ }
+
+ std::vector<const char*> flag_ptrs;
+ for (auto& f : flags) flag_ptrs.push_back(f.c_str());
+
+ // NVRTC compile
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !detail::nvrtc_is_loaded(), error_code_t::CUDA_API_FAILED, "NVRTC library could not be loaded");
+
+ nvrtcProgram prog;
+ nvrtcResult nvrtc_err;
+
+ nvrtc_err = detail::nvrtc_create_program(&prog, full_source.c_str(), "ln_fwd_silu.cu", 0, nullptr, nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcCreateProgram failed");
+
+ nvrtcResult compResult = detail::nvrtc_compile_program(prog, (int)flag_ptrs.size(), flag_ptrs.data());
+ if (compResult != NVRTC_SUCCESS) {
+ size_t logSize = 0;
+ detail::nvrtc_get_program_log_size(prog, &logSize);
+ std::string log_msg = "NVRTC compilation failed";
+ if (logSize > 1) {
+ std::vector<char> log(logSize);
+ detail::nvrtc_get_program_log(prog, log.data());
+ log_msg += ": ";
+ log_msg += log.data();
+ }
+ detail::nvrtc_destroy_program(&prog);
+ return {error_code_t::CUDA_API_FAILED, log_msg};
+ }
+
+ // Extract CUBIN
+ nvrtc_err = detail::nvrtc_get_cubin_size(prog, &cubinSize_);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcGetCUBINSize failed");
+
+ cubin_ = std::make_unique<char[]>(cubinSize_);
+ nvrtc_err = detail::nvrtc_get_cubin(prog, cubin_.get());
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcGetCUBIN failed");
+
+ detail::nvrtc_destroy_program(&prog);
+
+ // Load module + kernel
+ cudaError_t cuda_err;
+ cuda_err = detail::cuda_library_load_data(&module_, cubin_.get(), nullptr, nullptr, 0, nullptr, nullptr, 0);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLibraryLoadData failed: " + detail::cuda_error_to_string(cuda_err));
+
+ cuda_err = detail::cuda_library_get_kernel(&kernelPtr_, module_, "ln_fwd_kernel");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLibraryGetKernel failed: " + detail::cuda_error_to_string(cuda_err));
+
+ built_ = true;
+ return {error_code_t::OK, ""};
+ }
+
+ // ---- Phase 3: Execute ----
+ error_t
+ execute(void* input,
+ void* output,
+ void* weight, // gamma
+ void* bias, // beta (can be nullptr)
+ int rows,
+ int cols,
+ float epsilon,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ RmsNormSiluExtraParams const& extra = {}) override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!built_, error_code_t::INVALID_VALUE, "execute() called before build()");
+
+ // Compute grid dimensions
+ int ctas_per_col_max = (rows + warps_m_ - 1) / warps_m_;
+ int ctas_per_col;
+ if (knobs_->kernel_cfg == 2) {
+ // Non-persistent mode: launch one CTA group per row (max CTAs).
+ // CuDNN overrides ctas_per_col to max when use_non_persistent_mode=true.
+ ctas_per_col = ctas_per_col_max;
+ } else {
+ ctas_per_col = std::min(sm_count_ * static_cast<int>(knobs_->occupancy) / ctas_per_row_, ctas_per_col_max);
+ }
+ ctas_per_col = std::max(ctas_per_col, 1);
+
+ dim3 grid(ctas_per_row_ * ctas_per_col);
+ dim3 block(threads_per_cta_);
+
+ // Pack params
+ PersistentLnFwdParams params{};
+ params.rows = rows;
+ params.cols = cols;
+ params.ctas_per_col = ctas_per_col;
+ params.isRMSNorm = true;
+ params.noScale = (weight == nullptr);
+ params.noBias = (bias == nullptr);
+ params.isBatchFirst = true;
+ params.batchSize = 1;
+ params.seqLen = rows;
+ params.epsilon = epsilon;
+ params.x = input;
+ params.z = output;
+ params.gamma = weight;
+ params.beta = bias;
+
+ // Workspace layout (128-byte aligned):
+ // [0] rs : rows * sizeof(float)
+ // [aligned] fp8_scale : sizeof(float)
+ // [aligned] scale_row : rows * ceil(cols/16) bytes (NVFP4 only)
+ char* ws_ptr = static_cast<char*>(workspace);
+ params.rs = ws_ptr;
+ {
+ int64_t off = static_cast<int64_t>(rows) * sizeof(float);
+ off = ((off + 127) / 128) * 128;
+ ws_ptr = static_cast<char*>(workspace) + off;
+ }
+
+ // FP8 output: set scale pointer
+ if (output_dtype_ == RmsNormSiluDtype::FP8) {
+ params.fp8_out = true;
+ if (extra.fp8_scale) {
+ params.scale = static_cast<float*>(extra.fp8_scale);
+ } else {
+ // Use default scale = 1.0 from workspace (device memory)
+ // Write 1.0f (IEEE 754: 0x3F800000) asynchronously on stream
+ float* default_scale = reinterpret_cast<float*>(ws_ptr);
+ cudaError_t memset_err = detail::cuda_mem_set_d32_async(default_scale, 0x3F800000u, 1, stream);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(memset_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaMemcpyAsync for default scale failed");
+ params.scale = default_scale;
+ }
+ params.scale_inv = static_cast<float*>(extra.fp8_scale_inv); // may be nullptr
+ params.amax = static_cast<float*>(extra.fp8_amax); // may be nullptr
+ }
+
+ // NVFP4 output: set scale_row pointer
+ if (output_dtype_ == RmsNormSiluDtype::NVFP4) {
+ if (extra.nvfp4_scale_row) {
+ params.scale_row = extra.nvfp4_scale_row;
+ } else {
+ // Auto-allocate from workspace after fp8_scale slot
+ int64_t scale_row_off = get_scale_row_workspace_offset();
+ params.scale_row = static_cast<char*>(workspace) + scale_row_off;
+ }
+ }
+
+ // Multi-CTA cooperative reduction: allocate workspace + barrier from workspace
+ if (is_cooperative_) {
+ // Compute workspace offset after rs + fp8_scale + scale_row
+ int64_t coop_off = static_cast<int64_t>(rows) * sizeof(float);
+ coop_off = ((coop_off + 127) / 128) * 128;
+ coop_off += sizeof(float);
+ coop_off = ((coop_off + 127) / 128) * 128;
+ if (output_dtype_ == RmsNormSiluDtype::NVFP4) {
+ coop_off += static_cast<int64_t>(rows) * ((cols + 15) / 16);
+ coop_off = ((coop_off + 127) / 128) * 128;
+ }
+
+ // Inter-CTA partial stats workspace
+ int64_t coop_ws_size =
+ static_cast<int64_t>(ctas_per_col) * warps_m_ * ctas_per_row_ * sizeof(float) * 2 * 2;
+ params.workspace = static_cast<char*>(workspace) + coop_off;
+ coop_off += coop_ws_size;
+ coop_off = ((coop_off + 127) / 128) * 128;
+
+ // Barrier array — must be zeroed before each launch
+ int64_t barrier_count = 2 * ctas_per_col;
+ params.barrier = reinterpret_cast<int*>(static_cast<char*>(workspace) + coop_off);
+ cudaError_t memset_err =
+ detail::cuda_mem_set_async(params.barrier, 0, barrier_count * sizeof(int32_t), stream);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ memset_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaMemsetAsync failed for cooperative barrier (count=" + std::to_string(barrier_count) +
+ " offset=" + std::to_string(coop_off) + ")");
+ }
+
+ // reduced_divisor for batch/seqLen (batchFirst=true, so divide by seqLen=rows)
+ reduced_divisor divisor(rows);
+
+ // Kernel args
+ void* kernelParams[] = {
+ reinterpret_cast<void*>(&params),
+ reinterpret_cast<void*>(&divisor),
+ };
+
+ // Static shared memory: USE_STATIC_SMEM_VALUE is defined in the NVRTC source,
+ // so the kernel allocates smem at compile time. Pass 0 for dynamic smem.
+ // The kernel uses compile-time static shared memory (no dynamic smem needed).
+ int smem_bytes = 0;
+
+ // Set shared memory attribute
+ cudaError_t cuda_err;
+ cuda_err = detail::cuda_kernel_set_attribute_for_device(
+ kernelPtr_, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_bytes, device);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaKernelSetAttributeForDevice failed: " + detail::cuda_error_to_string(cuda_err));
+
+ // Launch
+ cuda_err = detail::cuda_launch_kernel((const void*)kernelPtr_, grid, block, kernelParams, smem_bytes, stream);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLaunchKernel failed: " + detail::cuda_error_to_string(cuda_err) +
+ " (grid=" + std::to_string(grid.x) + " block=" + std::to_string(block.x) +
+ " smem=" + std::to_string(smem_bytes) + ")");
+
+ return {error_code_t::OK, ""};
+ }
+
+ private:
+ std::string
+ generate_constexpr_defines() const {
+ std::string s;
+
+ // Type aliases (bf16 input always for VAE)
+ s += "\nusing ITYPE = nv_bfloat16;";
+ switch (output_dtype_) {
+ case RmsNormSiluDtype::BF16:
+ s += "\nusing OTYPE = nv_bfloat16;";
+ break;
+ case RmsNormSiluDtype::FP8:
+ s += "\nusing OTYPE = nv_fp8_e4m3;";
+ break;
+ case RmsNormSiluDtype::NVFP4:
+ s += "\nusing OTYPE = nv_fp4_e2m1;";
+ break;
+ }
+ s += "\nusing WTYPE = nv_bfloat16;";
+ s += "\nusing CTYPE = float;";
+ // NORM_OTYPE must match the norm output type, not compute type.
+ // Must match the norm output type, not compute type.
+ // For bf16 output: nv_bfloat16. For FP8/NVFP4: float (block-scale intermediate).
+ switch (output_dtype_) {
+ case RmsNormSiluDtype::BF16:
+ s += "\nusing NORM_OTYPE = nv_bfloat16;";
+ break;
+ case RmsNormSiluDtype::FP8:
+ case RmsNormSiluDtype::NVFP4:
+ s += "\nusing NORM_OTYPE = float;";
+ break;
+ }
+
+ // Kernel config
+ s += "\nconstexpr int HIDDEN_SIZE = " + std::to_string(C_) + ";";
+ s += "\nconstexpr int BATCH_SIZE = 1;";
+ s += "\nconstexpr int CTAS_PER_ROW = " + std::to_string(ctas_per_row_) + ";";
+ s += "\nconstexpr int WARPS_M = " + std::to_string(warps_m_) + ";";
+ s += "\nconstexpr int WARPS_N = " + std::to_string(warps_n_) + ";";
+ s += "\nconstexpr int BYTES_PER_LDG = " + std::to_string(bytes_per_ldg_) + ";";
+ s += "\nconstexpr bool isRMSNorm = 1;";
+ s += "\nconstexpr bool isAdaLN = 0;";
+ s += "\nconstexpr bool isBatchFirst = 1;";
+ s += "\nconstexpr bool hasGamma = 1;";
+ s += "\nconstexpr bool hasBeta = 0;";
+ s += "\nconstexpr bool isZeroCenteredGamma = 0;";
+ s += "\nconstexpr bool isZeroCenteredGammaCastBeforeAdd = 0;";
+
+ bool use_smem_gamma = (knobs_->kernel_cfg == 1);
+ bool use_non_persistent = (knobs_->kernel_cfg == 2);
+ s += "\nconstexpr bool useSmemGamma = " + std::to_string(use_smem_gamma ? 1 : 0) + ";";
+ s += "\nconstexpr bool GAMMA_ON_DEMAND = " + std::to_string((!use_smem_gamma && use_non_persistent) ? 1 : 0) +
+ ";";
+
+ bool is_fp8 = (output_dtype_ == RmsNormSiluDtype::FP8);
+ bool is_nvfp4 = (output_dtype_ == RmsNormSiluDtype::NVFP4);
+ s += "\nconstexpr bool isFP8Out = " + std::to_string(is_fp8 ? 1 : 0) + ";";
+ s += "\nconstexpr bool hasScaleInv = 0;";
+ s += "\nconstexpr bool hasAmax = 0;";
+ s += "\n#define LN_USE_CLUSTER 0";
+ s += "\nconstexpr bool USE_CLUSTER = 0;";
+ s += "\nconstexpr bool isBlockScaleOut = " + std::to_string(is_nvfp4 ? 1 : 0) + ";";
+ s += "\nconstexpr bool isFP4Out = " + std::to_string(is_nvfp4 ? 1 : 0) + ";";
+ s += "\nconstexpr bool isBlockScale_1D1X1X = " + std::to_string(is_nvfp4 ? 1 : 0) + ";";
+ s += "\nconstexpr bool isBlockScale_1D2X2X = 0;";
+ s += "\nconstexpr bool isBlockScale_1D2X2X_Transpose = 0;";
+ s += "\nconstexpr bool useBlockScaleColwiseKernel = 0;";
+ s += "\nconstexpr int DESIRED_OCCUPANCY = " + std::to_string(knobs_->occupancy) + ";";
+
+ // Ktraits instantiation
+ s += "\nusing Ktraits = Kernel_traits<WTYPE, ITYPE, OTYPE, CTYPE, NORM_OTYPE, uint32_t,";
+ s += "\n HIDDEN_SIZE, BATCH_SIZE, CTAS_PER_ROW, WARPS_M, WARPS_N, BYTES_PER_LDG,";
+ s += "\n isRMSNorm, isAdaLN, isBatchFirst, hasGamma, hasBeta, useSmemGamma,";
+ s += "\n USE_CLUSTER, false>;"; // WHOLE_CTA = false
+
+ // Static shared memory: let the kernel template compute the exact struct size.
+ // The kernel template computes the exact struct size at compile time.
+ // The kernel uses __shared__ char smem[USE_STATIC_SMEM_VALUE] instead of extern __shared__.
+ s += "\n#define USE_STATIC_SMEM_VALUE ((int)sizeof(LnFwdShared<Ktraits>))";
+
+ return s;
+ }
+
+ // Compute shared memory size matching the kernel's LnFwdShared struct.
+ // Every field has at least 1 element and __align__(16).
+ //
+ // LnFwdShared<Ktraits>:
+ // __align__(16) char smem_stats[SMEM_STATS_ELEMENTS] — 1 or Stats::SMEM_BYTES
+ // __align__(16) uint64_t smem_bar[SMEM_BAR_ELEMENTS] — 1 (no cluster)
+ // __align__(16) weight_t smem_gamma[GAMMA_ELEMENTS] — 1 or LDGS*THREADS_PER_ROW*NUM_ELTS
+ // __align__(16) weight_t smem_beta[BETA_ELEMENTS] — 1 (no beta)
+ // __align__(16) float smem_mxfp8[SMEM_MXFP8_ELEMENTS] — 1 (no 1D2X2X)
+ int
+ compute_smem_bytes() const {
+ int elts_per_ldg = bytes_per_ldg_ / 2;
+ int vec_cols = C_ / elts_per_ldg;
+ int threads_per_row = warps_n_ * 32;
+ int vec_cols_per_ldg = ctas_per_row_ * threads_per_row;
+ int ldgs = (vec_cols_per_ldg > 0) ? (vec_cols / vec_cols_per_ldg) : 1;
+ int num_elts = elts_per_ldg;
+
+ auto align16 = [](int bytes) { return ((bytes + 15) / 16) * 16; };
+
+ // smem_stats: min 1 byte → 16 when aligned.
+ // When CTAS_PER_ROW=1 && WARPS_N=1, Stats::SMEM_BYTES=0, so element count = max(0,1) = 1.
+ int stats_bytes = 1;
+ if (ctas_per_row_ > 1 || warps_n_ > 1) {
+ stats_bytes = warps_m_ * warps_n_ * sizeof(float) * 2 * 2;
+ }
+ int smem_stats = align16(stats_bytes);
+
+ // smem_bar: 1 uint64_t (no cluster)
+ int smem_bar = align16(static_cast<int>(sizeof(uint64_t)));
+
+ // smem_gamma: kernel_cfg=1 loads gamma to smem
+ int gamma_elements = 1;
+ if (knobs_->kernel_cfg == 1) {
+ gamma_elements = 1 * ldgs * threads_per_row * num_elts; // BATCH_SIZE=1
+ }
+ int smem_gamma = align16(gamma_elements * 2); // weight_t = bf16 = 2 bytes
+
+ // smem_beta: 1 element (hasBeta=false)
+ int smem_beta = align16(2); // 1 * sizeof(bf16)
+
+ // smem_mxfp8: 1 element (not 1D2X2X)
+ int smem_mxfp8 = align16(static_cast<int>(sizeof(float)));
+
+ int smem_bytes = smem_stats + smem_bar + smem_gamma + smem_beta + smem_mxfp8;
+ smem_bytes = ((smem_bytes + 127) / 128) * 128;
+ return smem_bytes;
+ }
+
+ // State from check_support()
+ const RmsNormSiluKnobs* knobs_ = nullptr;
+ int C_ = 0;
+ int num_tokens_ = 0;
+ RmsNormSiluDtype output_dtype_ = RmsNormSiluDtype::BF16;
+ int bytes_per_ldg_ = 0;
+ int warps_m_ = 0;
+ int warps_n_ = 0;
+ int threads_per_cta_ = 0;
+ int ctas_per_row_ = 0;
+ int sm_count_ = 0;
+ int sm_version_ = 0;
+ bool is_cooperative_ = false;
+ bool support_checked_ = false;
+
+ // State from build()
+ cudaLibrary_t module_ = nullptr;
+ cudaKernel_t kernelPtr_ = nullptr;
+ std::unique_ptr<char[]> cubin_;
+ size_t cubinSize_ = 0;
+ bool built_ = false;
+};
+
+} // namespace experimental
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_knobs.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_knobs.h
new file mode 100644
index 0000000..8080ab2
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_knobs.h
@@ -0,0 +1,215 @@
+#pragma once
+
+// Auto-generated knob selection logic for Sm100RmsNormSiluEngine.
+// Generated from optimal knob sweep results on B200 (SM100).
+// Knob mapping: knobTileRows {0:1,1:4,2:8,3:32}, knobLoadSize {0:2,1:4,2:8,3:16}
+
+#include <cstdint>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+enum class RmsNormSiluDtype : uint8_t {
+ BF16 = 0,
+ FP8 = 1,
+ NVFP4 = 2,
+};
+
+// Compact knob configuration per (C, tokens, dtype) entry.
+// WARPS_N is always 1. All values are the ACTUAL kernel parameters
+// (not knob indices).
+struct RmsNormSiluKnobs {
+ uint8_t warps_m; // WARPS_M value: 1, 4, 8, or 32
+ uint8_t split_cols; // knobSplitCols: 0 = no split, 4 = estimated CTAS_PER_ROW
+ uint8_t kernel_cfg; // knobKernelCfg: 0, 1, or 2
+ uint8_t occupancy; // DESIRED_OCCUPANCY: 0-16
+ uint8_t bytes_per_ldg; // BYTES_PER_LDG: 2, 4, 8, or 16
+};
+
+static constexpr int kSupportedC[] = {64, 128, 160, 256, 320, 512, 640, 1024};
+static constexpr int kSupportedTokens[] = {1560, 6240, 24960, 99840, 399360};
+static constexpr int kNumC = 8;
+static constexpr int kNumTokens = 5;
+static constexpr int kNumDtypes = 3;
+
+// Knob LUT indexed as: knob_lut[c_idx][tokens_idx][dtype_idx]
+// c_idx: 0=64, 1=128, 2=160, 3=256, 4=320, 5=512, 6=640, 7=1024
+// tokens_idx: 0=1560, 1=6240, 2=24960, 3=99840, 4=399360
+// dtype_idx: 0=bf16, 1=fp8, 2=nvfp4
+static constexpr RmsNormSiluKnobs knob_lut[kNumC][kNumTokens][kNumDtypes] = {
+ {
+ // C=64
+ {{8, 0, 0, 2, 4}, {8, 4, 0, 6, 4}, {8, 0, 2, 1, 4}}, // tokens=1560
+ {{32, 4, 0, 2, 4}, {8, 0, 0, 3, 2}, {8, 4, 0, 4, 4}}, // tokens=6240
+ {{32, 4, 0, 2, 4}, {8, 0, 0, 7, 4}, {8, 0, 1, 6, 4}}, // tokens=24960
+ {{8, 0, 1, 8, 4}, {8, 0, 1, 6, 2}, {32, 4, 1, 2, 4}}, // tokens=99840
+ {{4, 0, 1, 16, 4}, {32, 0, 1, 2, 2}, {32, 4, 1, 2, 4}}, // tokens=399360
+ },
+ {
+ // C=128
+ {{8, 4, 0, 3, 4}, {8, 0, 0, 3, 4}, {8, 4, 0, 3, 8}}, // tokens=1560
+ {{8, 0, 0, 3, 4}, {8, 0, 0, 4, 8}, {8, 0, 0, 5, 8}}, // tokens=6240
+ {{8, 0, 0, 6, 4}, {8, 0, 0, 8, 8}, {8, 0, 1, 8, 8}}, // tokens=24960
+ {{32, 4, 0, 2, 4}, {32, 0, 0, 2, 8}, {32, 0, 1, 2, 8}}, // tokens=99840
+ {{8, 0, 0, 8, 4}, {32, 0, 0, 2, 8}, {32, 0, 1, 2, 8}}, // tokens=399360
+ },
+ {
+ // C=160
+ {{8, 0, 0, 4, 2}, {8, 0, 0, 2, 2}, {4, 4, 0, 4, 2}}, // tokens=1560
+ {{8, 0, 0, 4, 2}, {8, 0, 0, 4, 2}, {8, 0, 1, 4, 2}}, // tokens=6240
+ {{8, 4, 1, 6, 2}, {8, 4, 0, 6, 2}, {8, 4, 1, 8, 2}}, // tokens=24960
+ {{32, 4, 1, 2, 2}, {32, 4, 1, 2, 2}, {32, 4, 0, 1, 2}}, // tokens=99840
+ {{32, 4, 1, 2, 2}, {32, 4, 1, 2, 2}, {32, 0, 1, 2, 2}}, // tokens=399360
+ },
+ {
+ // C=256
+ {{8, 0, 0, 6, 16}, {8, 4, 0, 2, 4}, {8, 0, 2, 1, 16}}, // tokens=1560
+ {{8, 0, 0, 4, 4}, {8, 0, 0, 4, 4}, {8, 0, 2, 1, 16}}, // tokens=6240
+ {{8, 0, 0, 8, 16}, {8, 4, 0, 8, 16}, {8, 4, 1, 6, 16}}, // tokens=24960
+ {{4, 4, 0, 16, 16}, {4, 0, 0, 16, 16}, {32, 0, 1, 1, 16}}, // tokens=99840
+ {{4, 0, 0, 16, 16}, {32, 0, 0, 2, 16}, {32, 0, 1, 2, 16}}, // tokens=399360
+ },
+ {
+ // C=320
+ {{8, 4, 1, 4, 4}, {8, 0, 0, 2, 4}, {4, 4, 0, 9, 4}}, // tokens=1560
+ {{8, 4, 0, 5, 4}, {8, 0, 0, 5, 4}, {4, 0, 0, 9, 4}}, // tokens=6240
+ {{8, 0, 0, 5, 4}, {8, 0, 0, 5, 4}, {8, 0, 1, 8, 4}}, // tokens=24960
+ {{4, 0, 1, 16, 4}, {32, 0, 1, 2, 4}, {32, 4, 1, 2, 4}}, // tokens=99840
+ {{32, 4, 0, 2, 4}, {32, 0, 1, 2, 4}, {32, 4, 1, 2, 4}}, // tokens=399360
+ },
+ {
+ // C=512
+ {{8, 0, 0, 2, 16}, {8, 0, 0, 2, 8}, {4, 4, 0, 3, 16}}, // tokens=1560
+ {{8, 0, 0, 5, 16}, {8, 0, 0, 4, 8}, {4, 0, 0, 9, 16}}, // tokens=6240
+ {{4, 0, 0, 8, 16}, {4, 0, 0, 9, 8}, {4, 0, 2, 1, 16}}, // tokens=24960
+ {{4, 0, 2, 1, 8}, {32, 4, 1, 2, 8}, {32, 4, 0, 1, 16}}, // tokens=99840
+ {{4, 0, 2, 1, 4}, {32, 4, 1, 2, 8}, {32, 0, 0, 1, 16}}, // tokens=399360
+ },
+ {
+ // C=640
+ {{4, 0, 0, 4, 4}, {4, 0, 0, 3, 8}, {4, 4, 0, 5, 8}}, // tokens=1560
+ {{4, 0, 0, 5, 4}, {8, 0, 0, 4, 8}, {4, 0, 1, 9, 8}}, // tokens=6240
+ {{4, 0, 0, 5, 4}, {8, 0, 0, 4, 8}, {4, 0, 2, 1, 8}}, // tokens=24960
+ {{4, 0, 2, 1, 8}, {4, 4, 0, 9, 8}, {32, 0, 1, 1, 8}}, // tokens=99840
+ {{4, 0, 2, 1, 8}, {32, 4, 1, 2, 8}, {32, 4, 1, 1, 8}}, // tokens=399360
+ },
+ {
+ // C=1024
+ {{4, 4, 0, 3, 16}, {4, 0, 0, 3, 4}, {4, 4, 0, 7, 16}}, // tokens=1560
+ {{4, 0, 0, 5, 16}, {4, 0, 0, 5, 8}, {4, 0, 2, 1, 16}}, // tokens=6240
+ {{4, 4, 1, 10, 16}, {1, 4, 0, 16, 8}, {4, 0, 2, 1, 16}}, // tokens=24960
+ {{8, 0, 2, 1, 16}, {4, 0, 1, 9, 8}, {32, 0, 1, 1, 16}}, // tokens=99840
+ {{8, 0, 2, 1, 16}, {32, 4, 1, 1, 8}, {32, 4, 1, 1, 16}}, // tokens=399360
+ },
+};
+
+// Compute conservative default knobs for arbitrary problem sizes not in the LUT.
+// Uses safe defaults (WARPS_M=1, BPL=4, occupancy=1) and validates vectorization
+// divisibility constraints before accepting a configuration.
+// Returns true if a valid configuration was found, false otherwise.
+inline bool
+compute_default_knobs(int C, int num_tokens, RmsNormSiluDtype dtype, RmsNormSiluKnobs& out) {
+ // Conservative defaults:
+ // CTAS_PER_ROW = 1, WARPS_M = 1, WARPS_N = 1, BPL = 4, occupancy = 1, kernel_cfg = 0
+ // For block-scale output (NVFP4): WARPS_M = 32
+
+ int input_size = 2; // bf16 input always
+
+ // Start with conservative defaults
+ int warps_m = (dtype == RmsNormSiluDtype::NVFP4) ? 32 : 1;
+ int warps_n = 1; // always 1 for our engine
+ int bpl = 4; // default bytes per load
+ int cpr = 1; // no column splitting for fallback
+ int occ = 1;
+ int kcfg = 0;
+
+ // Validation: C must be evenly divisible into vectorized loads.
+ // NUM_ELTS = BYTES_PER_LDG / sizeof(input_t)
+ // VEC_COLS = C / NUM_ELTS
+ // VEC_COLS_PER_LDG = CTAS_PER_ROW * WARPS_N * 32
+ // Require: C % NUM_ELTS == 0 AND VEC_COLS % VEC_COLS_PER_LDG == 0
+ // Also: LDGS = VEC_COLS / VEC_COLS_PER_LDG <= 1024 (avoid register spill)
+
+ auto validate = [&](int test_bpl, int test_wm) -> bool {
+ int num_elts = test_bpl / input_size;
+ if (num_elts <= 0 || C % num_elts != 0) return false;
+ int vec_cols = C / num_elts;
+ int vec_cols_per_ldg = cpr * warps_n * 32;
+ if (vec_cols_per_ldg <= 0 || vec_cols % vec_cols_per_ldg != 0) return false;
+ int ldgs = vec_cols / vec_cols_per_ldg;
+ if (ldgs > 1024) return false; // reject extreme LDGS to avoid register spilling
+ // Check WARPS_M constraint: if WARPS_M > 1, rows per CTA must divide evenly
+ if (test_wm > 1 && num_tokens % test_wm != 0) return false;
+ return true;
+ };
+
+ // Try default BPL=4, then cascade through {4, 8, 16, 2}
+ static constexpr int bpl_candidates[] = {4, 8, 16, 2};
+ bool found = false;
+ for (int candidate : bpl_candidates) {
+ if (validate(candidate, warps_m)) {
+ bpl = candidate;
+ found = true;
+ break;
+ }
+ }
+
+ // If WARPS_M=1 failed, try bumping to WARPS_M=4 for better row coverage
+ if (!found && warps_m == 1 && num_tokens % 4 == 0) {
+ warps_m = 4;
+ for (int candidate : bpl_candidates) {
+ if (validate(candidate, warps_m)) {
+ bpl = candidate;
+ found = true;
+ break;
+ }
+ }
+ }
+
+ if (!found) return false;
+
+ out.warps_m = static_cast<uint8_t>(warps_m);
+ out.split_cols = 0; // no column splitting
+ out.kernel_cfg = static_cast<uint8_t>(kcfg);
+ out.occupancy = static_cast<uint8_t>(occ);
+ out.bytes_per_ldg = static_cast<uint8_t>(bpl);
+ return true;
+}
+
+// Look up knob configuration for a given (C, num_tokens, output_dtype, sm_version).
+// Tier 1: exact LUT match for SM100 VAE problem sizes (optimal, sweep-tuned on B200).
+// Tier 2: fallback heuristic for other archs or arbitrary sizes (functional, conservative).
+// Returns nullptr only if the problem is fundamentally unsupported.
+inline const RmsNormSiluKnobs*
+lookup_rms_norm_silu_knobs(int C, int num_tokens, RmsNormSiluDtype dtype, int sm_version = 100) {
+ // Tier 1: exact LUT match — only valid for SM100 (swept on B200)
+ if (sm_version >= 100) {
+ int c_idx = -1, t_idx = -1;
+ for (int i = 0; i < kNumC; ++i) {
+ if (kSupportedC[i] == C) {
+ c_idx = i;
+ break;
+ }
+ }
+ for (int i = 0; i < kNumTokens; ++i) {
+ if (kSupportedTokens[i] == num_tokens) {
+ t_idx = i;
+ break;
+ }
+ }
+ if (c_idx >= 0 && t_idx >= 0) {
+ return &knob_lut[c_idx][t_idx][static_cast<int>(dtype)];
+ }
+ }
+
+ // Tier 2: fallback heuristic for non-SM100 archs or non-LUT problem sizes
+ static thread_local RmsNormSiluKnobs fallback;
+ if (compute_default_knobs(C, num_tokens, dtype, fallback)) {
+ return &fallback;
+ }
+
+ return nullptr; // fundamentally unsupported (C not divisible by any valid config)
+}
+
+} // namespace experimental
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_sdpa_prefill_engine.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_sdpa_prefill_engine.h
new file mode 100644
index 0000000..73da07d
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_sdpa_prefill_engine.h
@@ -0,0 +1,544 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "oss_engine_interface.h"
+#include "../generated/sdpa/sm100/prefill/full_seqlens/d128_fprop_kernel.h"
+#include "../generated/sdpa/sm100/prefill/full_seqlens/d64_fprop_kernel.h"
+
+#include <cuda_fp16.h>
+
+// Suppress MSVC C4127 "conditional expression is constant" triggered by
+// RETURN_CUDNN_FRONTEND_ERROR_IF macro (which has `if (retval == error_code_t::OK)`)
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4127)
+#endif
+
+#include <algorithm>
+#include <cmath>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+// ============================================================
+// Kernel spec lookup for SM100 SDPA prefill kernels
+// ============================================================
+
+/// @brief Look up the SM100 kernel specification for a given head dimension.
+/// @param d Head dimension (d_qk). Currently supports 64 and 128.
+/// @param sm_version SM version from cudaDeviceProp (e.g. 100, 101).
+/// @return Pointer to static KernelSpec, or nullptr if unsupported.
+inline const KernelSpec*
+lookup_sm100_kernel_spec(int d, int sm_version) {
+ // SM100 family: sm_version 100..109
+ if (sm_version / 10 != 10) return nullptr;
+
+ static const KernelSpec spec_d128 = {
+ generated::sm100_d128_fprop_source,
+ generated::sm100_d128_fprop_source_len,
+ generated::sm100_d128_fprop_flags,
+ generated::sm100_d128_fprop_flags_len,
+ "cudnn_generated_oss_sdpa_sm100_flash_fprop_f16_knob_7_128x128x128_4x1x1_cga1x1x1_kernel0_0",
+ 128,
+ 128,
+ 128,
+ 232448 // smem_bytes for d=128
+ };
+
+ static const KernelSpec spec_d64 = {
+ generated::sm100_d64_fprop_source,
+ generated::sm100_d64_fprop_source_len,
+ generated::sm100_d64_fprop_flags,
+ generated::sm100_d64_fprop_flags_len,
+ "cudnn_generated_oss_sdpa_sm100_flash_fprop_f16_knob_7_128x128x64_4x1x1_cga1x1x1_kernel0_0",
+ 128,
+ 128,
+ 64,
+ 232448 // smem_bytes for d=64
+ };
+
+ switch (d) {
+ case 128:
+ return &spec_d128;
+ case 64:
+ return &spec_d64;
+ default:
+ return nullptr;
+ }
+}
+
+// ============================================================
+// Sm100SdpaPrefillEngine
+// ============================================================
+
+/// @brief SM100-specific SDPA prefill engine using NVRTC-compiled kernels.
+///
+/// This engine targets the SM100 (Blackwell) architecture and uses L2-aware
+/// tile scheduling instead of the SM90 persistent-tile-counter approach.
+/// The kernel is compiled at runtime via NVRTC from embedded source and
+/// launched with TMA descriptors for Q, K, V, and O tensors.
+///
+/// Usage:
+/// 1. check_support() -- validates shape + SM version, caches device info.
+/// 2. build() -- NVRTC-compiles the kernel and loads the CU module.
+/// 3. execute() -- sets up TMA descriptors, packs params, launches.
+///
+/// Thread safety: instances are NOT thread-safe. Each thread should own its
+/// own engine, or external synchronization must be provided.
+class Sm100SdpaPrefillEngine : public IOssSdpaEngine {
+ public:
+ Sm100SdpaPrefillEngine() = default;
+
+ ~Sm100SdpaPrefillEngine() override {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ }
+
+ // Non-copyable
+ Sm100SdpaPrefillEngine(const Sm100SdpaPrefillEngine&) = delete;
+ Sm100SdpaPrefillEngine&
+ operator=(const Sm100SdpaPrefillEngine&) = delete;
+
+ // Movable
+ Sm100SdpaPrefillEngine(Sm100SdpaPrefillEngine&& other) noexcept
+ : spec_(other.spec_),
+ d_(other.d_),
+ sm_version_(other.sm_version_),
+ sm_count_(other.sm_count_),
+ support_checked_(other.support_checked_),
+ module_(other.module_),
+ kernelPtr_(other.kernelPtr_),
+ cubin_(std::move(other.cubin_)),
+ cubinSize_(other.cubinSize_),
+ tile_m_(other.tile_m_),
+ tile_n_(other.tile_n_),
+ tile_k_(other.tile_k_),
+ smemBytes_(other.smemBytes_),
+ kernelName_(std::move(other.kernelName_)),
+ built_(other.built_) {
+ other.module_ = nullptr;
+ other.kernelPtr_ = nullptr;
+ other.built_ = false;
+ }
+
+ Sm100SdpaPrefillEngine&
+ operator=(Sm100SdpaPrefillEngine&& other) noexcept {
+ if (this != &other) {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ spec_ = other.spec_;
+ d_ = other.d_;
+ sm_version_ = other.sm_version_;
+ sm_count_ = other.sm_count_;
+ support_checked_ = other.support_checked_;
+ module_ = other.module_;
+ kernelPtr_ = other.kernelPtr_;
+ cubin_ = std::move(other.cubin_);
+ cubinSize_ = other.cubinSize_;
+ tile_m_ = other.tile_m_;
+ tile_n_ = other.tile_n_;
+ tile_k_ = other.tile_k_;
+ smemBytes_ = other.smemBytes_;
+ kernelName_ = std::move(other.kernelName_);
+ built_ = other.built_;
+ other.module_ = nullptr;
+ other.kernelPtr_ = nullptr;
+ other.built_ = false;
+ }
+ return *this;
+ }
+
+ // ---- Phase 1: Support check (spec lookup, cache SM count) ----
+
+ /// @brief Validate that the given attention shape and SM version are supported.
+ /// @param shape Attention shape (batch, heads, seqlens, head dim).
+ /// @param sm_version SM version (e.g. 100 for SM100).
+ /// @return error_t with OK on success, GRAPH_NOT_SUPPORTED if unsupported.
+ error_t
+ check_support(AttentionShape_t shape, int sm_version) override {
+ spec_ = lookup_sm100_kernel_spec(shape.d_qk, sm_version);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ spec_ == nullptr,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Unsupported config: d=" + std::to_string(shape.d_qk) + " sm_version=" + std::to_string(sm_version));
+
+ d_ = shape.d_qk;
+ sm_version_ = sm_version;
+ tile_m_ = spec_->tile_m;
+ tile_n_ = spec_->tile_n;
+ tile_k_ = spec_->tile_k;
+ smemBytes_ = spec_->smem_bytes;
+ kernelName_ = spec_->kernel_name;
+
+ // Cache SM count for later use in execute()
+ cudaDeviceProp devProp;
+ int device_ordinal = 0;
+ cudaError_t cuda_err = detail::cuda_get_device(&device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDevice failed");
+ cuda_err = detail::cuda_get_device_properties(&devProp, device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDeviceProperties failed");
+ sm_count_ = devProp.multiProcessorCount;
+
+ support_checked_ = true;
+ return {error_code_t::OK, ""};
+ }
+
+ /// @brief Returns the workspace size in bytes needed by execute().
+ /// SM100 does not use a workspace tile counter, but we keep the interface
+ /// consistent with SM90 for uniform allocation by the caller.
+ static int64_t
+ get_workspace_size() {
+ return 16;
+ }
+
+ // ---- Phase 2: NVRTC compilation + module loading ----
+
+ /// @brief Compile the kernel via NVRTC and load the resulting CU module.
+ /// @pre check_support() must have been called successfully.
+ /// @return error_t with OK on success.
+ error_t
+ build() override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!support_checked_ || spec_ == nullptr,
+ error_code_t::INVALID_VALUE,
+ "build() called before check_support()");
+
+ auto status = compile_and_load_kernel(spec_, module_, kernelPtr_, cubin_, cubinSize_, kernelName_);
+ if (status.is_good()) {
+ built_ = true;
+ }
+ return status;
+ }
+
+ // ---- Phase 3: Set up TMA descriptors, pack params, launch ----
+
+ /// @brief Execute the SM100 SDPA prefill kernel.
+ ///
+ /// Sets up TMA descriptors for Q/K/V/O, computes L2-aware tile scheduling
+ /// parameters, and launches the kernel on the given stream.
+ ///
+ /// Strides are in ELEMENTS (not bytes), matching PyTorch's .stride() convention.
+ /// All stride vectors have 4 elements in (b, h, s, d) order.
+ /// For max/sum_exp the 4th element (d-stride) is typically 1 and is unused internally.
+ ///
+ /// @param batch Batch size (B).
+ /// @param heads_q Number of query heads (H_q).
+ /// @param heads_kv Number of key/value heads (H_kv).
+ /// @param seq_q Query sequence length (S_q).
+ /// @param seq_kv Key/value sequence length (S_kv).
+ /// @param d Head dimension (d_qk = d_v).
+ /// @param d_Q Device pointer to Q tensor (fp16).
+ /// @param q_strides Q strides in elements: [b, h, s, d].
+ /// @param d_K Device pointer to K tensor (fp16).
+ /// @param k_strides K strides in elements: [b, h, s, d].
+ /// @param d_V Device pointer to V tensor (fp16).
+ /// @param v_strides V strides in elements: [b, h, s, d].
+ /// @param d_O Device pointer to O tensor (fp16, output).
+ /// @param o_strides O strides in elements: [b, h, s, d].
+ /// @param d_max Device pointer to per-row max values (fp32, [B, H_q, S_q]).
+ /// @param max_strides Max strides in elements: [b, h, s].
+ /// @param d_sum_exp Device pointer to per-row sum-of-exp values (fp32, [B, H_q, S_q]).
+ /// @param se_strides Sum-exp strides in elements: [b, h, s].
+ /// @param workspace Device workspace pointer (at least 16 bytes, unused by SM100 but kept for API consistency).
+ /// @param device Device ordinal for kernel attribute setting.
+ /// @param stream CUDA stream for asynchronous execution.
+ /// @param user_attn_scale Optional attention scale; defaults to 1/sqrt(D).
+ /// @return error_t with OK on success.
+ error_t
+ execute(int batch,
+ int heads_q,
+ int heads_kv,
+ int seq_q,
+ int seq_kv,
+ int d,
+ void* d_Q,
+ std::vector<int64_t> const& q_strides,
+ void* d_K,
+ std::vector<int64_t> const& k_strides,
+ void* d_V,
+ std::vector<int64_t> const& v_strides,
+ void* d_O,
+ std::vector<int64_t> const& o_strides,
+ void* d_max,
+ std::vector<int64_t> const& max_strides,
+ void* d_sum_exp,
+ std::vector<int64_t> const& se_strides,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ std::optional<float> user_attn_scale = std::nullopt) override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!built_, error_code_t::INVALID_VALUE, "execute() called before build()");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ d > 128, error_code_t::GRAPH_NOT_SUPPORTED, "SM100 OSS engine requires d <= 128");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ q_strides.size() < 4 || k_strides.size() < 4 || v_strides.size() < 4 || o_strides.size() < 4,
+ error_code_t::INVALID_VALUE,
+ "Q/K/V/O strides must have at least 4 elements");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(max_strides.size() < 3 || se_strides.size() < 3,
+ error_code_t::INVALID_VALUE,
+ "max/sum_exp strides must have at least 3 elements");
+
+ // Suppress unused-parameter warning for workspace (SM100 does not use a tile counter)
+ (void)workspace;
+
+ int B = batch;
+ int H_q = heads_q;
+ int H_kv = heads_kv;
+ int S_q = seq_q;
+ int S_kv = seq_kv;
+ int D = d;
+ int TILE_M = tile_m_;
+ int TILE_N = tile_n_;
+
+ // ---- Set up AttentionDescriptor ----
+ AttentionDescriptor_t attnDesc = {};
+ attnDesc.b = B;
+ attnDesc.q_h = H_q;
+ attnDesc.k_h = H_kv;
+ attnDesc.v_h = H_kv;
+ attnDesc.s_q = S_q;
+ attnDesc.s_kv = S_kv;
+ attnDesc.d_qk = D;
+ attnDesc.d_v = D;
+ attnDesc.q_heads_per_k = (H_q >= H_kv && H_kv > 0) ? (uint16_t)(H_q / H_kv) : 1;
+ attnDesc.q_heads_per_v = (H_q >= H_kv && H_kv > 0) ? (uint16_t)(H_q / H_kv) : 1;
+ attnDesc.min_q_heads_per_kv = attnDesc.q_heads_per_k;
+
+ // ---- L2-aware tile scheduling ----
+ // SM100 uses an L2-aware swizzle pattern for better cache utilization
+ // instead of SM90's persistent tile counter approach.
+ constexpr int Tiles_Q = 2;
+ constexpr uint32_t size_l2 = 50u * 1024u * 1024u;
+
+ int ctas_in_q_dim = div_up(S_q, TILE_M * Tiles_Q);
+ int num_hb = B * H_q;
+
+ // Compute the swizzle factor based on how many KV heads fit in L2
+ uint32_t one_kv_head_size = static_cast<uint32_t>(S_kv) * (D + D) * sizeof(half);
+ int swizzle = (one_kv_head_size > 0) ? (1 << find_log_2_floor(size_l2 / one_kv_head_size)) : 1;
+ swizzle = std::max(1, std::min(swizzle, num_hb));
+
+ int num_hb_quotient = num_hb / swizzle;
+ int num_hb_remainder = num_hb % swizzle;
+ int num_block = ctas_in_q_dim;
+ int total_blocks = num_block * num_hb;
+
+ // Fast divisors for tile index decomposition in the kernel
+ FastDivisor_t num_head_divmod = make_fast_divisor(static_cast<uint32_t>(H_q));
+ FastDivisor_t l2_minor_divmod = make_fast_divisor(static_cast<uint32_t>(swizzle));
+ FastDivisor_t l2_major_divmod = make_fast_divisor(static_cast<uint32_t>(swizzle * num_block));
+ FastDivisor_t l2_minor_residual_divmod =
+ make_fast_divisor(static_cast<uint32_t>(std::max(1, num_hb_remainder)));
+
+ // ---- TMA descriptors (4D) ----
+ // Caller strides are in elements; TMA needs bytes.
+ uint32_t elem_bytes = sizeof(half);
+ uint32_t elems_per_ld = std::min(64, D);
+
+ // Q TMA: dims = (D, S_q, H_q, B), box = (elems_per_ld, TILE_M)
+ // SM100 uses TILE_M (128) directly, unlike SM90 which uses TILE_M * 2.
+ CUtensorMap tma_q = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_q,
+ d_Q,
+ CU_TENSOR_MAP_DATA_TYPE_BFLOAT16,
+ D,
+ S_q,
+ H_q,
+ B,
+ (uint64_t)q_strides[2] * elem_bytes,
+ (uint64_t)q_strides[1] * elem_bytes,
+ (uint64_t)q_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_M,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // K TMA: dims = (D, S_kv, H_kv, B), box = (elems_per_ld, TILE_N)
+ CUtensorMap tma_k = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_k,
+ d_K,
+ CU_TENSOR_MAP_DATA_TYPE_BFLOAT16,
+ D,
+ S_kv,
+ H_kv,
+ B,
+ (uint64_t)k_strides[2] * elem_bytes,
+ (uint64_t)k_strides[1] * elem_bytes,
+ (uint64_t)k_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_N,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // V TMA: dims = (D, S_kv, H_kv, B), box = (elems_per_ld, TILE_N)
+ CUtensorMap tma_v = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_v,
+ d_V,
+ CU_TENSOR_MAP_DATA_TYPE_BFLOAT16,
+ D,
+ S_kv,
+ H_kv,
+ B,
+ (uint64_t)v_strides[2] * elem_bytes,
+ (uint64_t)v_strides[1] * elem_bytes,
+ (uint64_t)v_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_N,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // O TMA: dims = (D, S_q, H_q, B), box = (elems_per_ld, TILE_M)
+ // SM100 uses TILE_M (128) for the O box dim, unlike SM90 which uses 16.
+ CUtensorMap tma_o = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_o,
+ d_O,
+ CU_TENSOR_MAP_DATA_TYPE_BFLOAT16,
+ D,
+ S_q,
+ H_q,
+ B,
+ (uint64_t)o_strides[2] * elem_bytes,
+ (uint64_t)o_strides[1] * elem_bytes,
+ (uint64_t)o_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_M,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // ---- Scaling ----
+ float attn_scale = user_attn_scale.value_or(1.0f / std::sqrt((float)D));
+ float tensor_13 = -INFINITY;
+
+ // ---- Tensor descriptors for max and sum_exp (f32, [B, H_q, S_q]) ----
+ // Strides provided by caller in elements.
+ tensor_descriptor desc_max = {};
+ desc_max.num_dims = 3;
+ desc_max.dims[0] = B;
+ desc_max.dims[1] = H_q;
+ desc_max.dims[2] = S_q;
+ desc_max.strides[0] = max_strides[0];
+ desc_max.strides[1] = max_strides[1];
+ desc_max.strides[2] = max_strides[2];
+
+ tensor_descriptor desc_sum_exp = {};
+ desc_sum_exp.num_dims = 3;
+ desc_sum_exp.dims[0] = B;
+ desc_sum_exp.dims[1] = H_q;
+ desc_sum_exp.dims[2] = S_q;
+ desc_sum_exp.strides[0] = se_strides[0];
+ desc_sum_exp.strides[1] = se_strides[1];
+ desc_sum_exp.strides[2] = se_strides[2];
+
+ // ---- Grid/Block ----
+ // SM100 launches total_blocks CTAs with 512 threads each.
+ // No persistent scheduling -- the L2 swizzle parameters handle work distribution.
+ dim3 grid(total_blocks, 1, 1);
+ dim3 block(512, 1, 1);
+
+ // ---- Build kernel params array (18 parameters) ----
+ // The parameter order must match the SM100 kernel's expected layout exactly.
+ void* kernelParams[] = {
+ (void*)&attnDesc,
+ (void*)&num_head_divmod,
+ (void*)&l2_minor_divmod,
+ (void*)&l2_major_divmod,
+ (void*)&l2_minor_residual_divmod,
+ (void*)&num_hb_quotient,
+ (void*)&num_block,
+ (void*)&total_blocks,
+ (void*)&tma_q,
+ (void*)&tma_k,
+ (void*)&attn_scale,
+ (void*)&tensor_13,
+ (void*)&d_max,
+ (void*)&desc_max,
+ (void*)&d_sum_exp,
+ (void*)&desc_sum_exp,
+ (void*)&tma_v,
+ (void*)&tma_o,
+ };
+
+ // ---- Debug logging ----
+ if (cudnn_frontend::isLoggingEnabled()) {
+ CUDNN_FE_LOG_LABEL_ENDL("SM100 OSS Engine Launch:");
+ CUDNN_FE_LOG_LABEL_ENDL(" Grid = (" << grid.x << "," << grid.y << "," << grid.z << ")");
+ CUDNN_FE_LOG_LABEL_ENDL(" Block = (" << block.x << "," << block.y << "," << block.z << ")");
+ CUDNN_FE_LOG_LABEL_ENDL(" Smem = " << smemBytes_);
+ CUDNN_FE_LOG_LABEL_ENDL(" Kernel: " << kernelName_);
+ CUDNN_FE_LOG_LABEL_ENDL(" B=" << B << " H_q=" << H_q << " H_kv=" << H_kv << " S_q=" << S_q
+ << " S_kv=" << S_kv << " D=" << D);
+ CUDNN_FE_LOG_LABEL_ENDL(" L2: swizzle=" << swizzle << " num_hb_quotient=" << num_hb_quotient
+ << " num_block=" << num_block << " total_blocks=" << total_blocks);
+ CUDNN_FE_LOG_LABEL_ENDL(" attn_scale=" << attn_scale);
+ }
+
+ // ---- Set shared memory attribute and launch ----
+ cudaError_t cuda_err;
+
+ cuda_err = detail::cuda_kernel_set_attribute_for_device(
+ kernelPtr_, cudaFuncAttributeMaxDynamicSharedMemorySize, smemBytes_, device);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaKernelSetAttributeForDevice failed (smem=" + std::to_string(smemBytes_) +
+ " bytes, error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ cuda_err = detail::cuda_launch_kernel((const void*)kernelPtr_, grid, block, kernelParams, smemBytes_, stream);
+ cudaError_t last_err = detail::cuda_get_last_error();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLaunchKernel failed (grid=" + std::to_string(grid.x) +
+ ", block=512, smem=" + std::to_string(smemBytes_) +
+ ", error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ last_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaGetLastError after kernel launch: " + detail::cuda_error_to_string(last_err));
+
+ return {error_code_t::OK, ""};
+ }
+
+ private:
+ // State from check_support()
+ const KernelSpec* spec_ = nullptr;
+ int d_ = 0;
+ int sm_version_ = 0;
+ int sm_count_ = 0;
+ bool support_checked_ = false;
+
+ // State from build()
+ cudaLibrary_t module_ = nullptr;
+ cudaKernel_t kernelPtr_ = nullptr;
+ std::unique_ptr<char[]> cubin_;
+ size_t cubinSize_ = 0;
+ int tile_m_ = 0, tile_n_ = 0, tile_k_ = 0;
+ int smemBytes_ = 0;
+ std::string kernelName_;
+ bool built_ = false;
+};
+
+} // namespace experimental
+} // namespace cudnn_frontend
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm90_sdpa_prefill_engine.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm90_sdpa_prefill_engine.h
new file mode 100644
index 0000000..d1fb8a2
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm90_sdpa_prefill_engine.h
@@ -0,0 +1,450 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "oss_engine_interface.h"
+#include "../generated/sdpa/sm90/prefill/full_seqlens/d128_fprop_kernel.h"
+#include "../generated/sdpa/sm90/prefill/full_seqlens/d64_fprop_kernel.h"
+
+#include <cuda_fp16.h>
+
+// Suppress MSVC C4127 "conditional expression is constant" triggered by
+// RETURN_CUDNN_FRONTEND_ERROR_IF macro (which has `if (retval == error_code_t::OK)`)
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4127)
+#endif
+
+#include <algorithm>
+#include <cmath>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+// ============================================================
+// Kernel spec lookup (replaces KernelFactory)
+// ============================================================
+
+inline const KernelSpec*
+lookup_kernel_spec(int d, int sm_version) {
+ if (sm_version != 90) return nullptr;
+
+ static const KernelSpec spec_d128 = {
+ generated::d128_fprop_source,
+ generated::d128_fprop_source_len,
+ generated::d128_fprop_flags,
+ generated::d128_fprop_flags_len,
+ "cudnn_generated_oss_sdpa_sm90_flash_fprop_wgmma_f16_knob_7_64x128x128_4x1x1_cga1x1x1_kernel0_0",
+ 64,
+ 128,
+ 128,
+ 232448 // smem_bytes for d=128 (227 * 1024)
+ };
+
+ static const KernelSpec spec_d64 = {
+ generated::d64_fprop_source,
+ generated::d64_fprop_source_len,
+ generated::d64_fprop_flags,
+ generated::d64_fprop_flags_len,
+ "cudnn_generated_oss_sdpa_sm90_flash_fprop_wgmma_f16_knob_7_64x128x64_4x1x1_cga1x1x1_kernel0_0",
+ 64,
+ 128,
+ 64,
+ 122880 // smem_bytes for d=64 (120 * 1024)
+ };
+
+ switch (d) {
+ case 128:
+ return &spec_d128;
+ case 64:
+ return &spec_d64;
+ default:
+ return nullptr;
+ }
+}
+// ============================================================
+// Sm90SdpaPrefillEngine
+// ============================================================
+
+class Sm90SdpaPrefillEngine : public IOssSdpaEngine {
+ public:
+ Sm90SdpaPrefillEngine() = default;
+
+ ~Sm90SdpaPrefillEngine() override {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ }
+
+ // Non-copyable
+ Sm90SdpaPrefillEngine(const Sm90SdpaPrefillEngine&) = delete;
+ Sm90SdpaPrefillEngine&
+ operator=(const Sm90SdpaPrefillEngine&) = delete;
+
+ // Movable
+ Sm90SdpaPrefillEngine(Sm90SdpaPrefillEngine&& other) noexcept
+ : spec_(other.spec_),
+ d_(other.d_),
+ sm_version_(other.sm_version_),
+ sm_count_(other.sm_count_),
+ support_checked_(other.support_checked_),
+ module_(other.module_),
+ kernelPtr_(other.kernelPtr_),
+ cubin_(std::move(other.cubin_)),
+ cubinSize_(other.cubinSize_),
+ tile_m_(other.tile_m_),
+ tile_n_(other.tile_n_),
+ tile_k_(other.tile_k_),
+ smemBytes_(other.smemBytes_),
+ kernelName_(std::move(other.kernelName_)),
+ built_(other.built_) {
+ other.module_ = nullptr;
+ other.kernelPtr_ = nullptr;
+ other.built_ = false;
+ }
+
+ Sm90SdpaPrefillEngine&
+ operator=(Sm90SdpaPrefillEngine&& other) noexcept {
+ if (this != &other) {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ spec_ = other.spec_;
+ d_ = other.d_;
+ sm_version_ = other.sm_version_;
+ sm_count_ = other.sm_count_;
+ support_checked_ = other.support_checked_;
+ module_ = other.module_;
+ kernelPtr_ = other.kernelPtr_;
+ cubin_ = std::move(other.cubin_);
+ cubinSize_ = other.cubinSize_;
+ tile_m_ = other.tile_m_;
+ tile_n_ = other.tile_n_;
+ tile_k_ = other.tile_k_;
+ smemBytes_ = other.smemBytes_;
+ kernelName_ = std::move(other.kernelName_);
+ built_ = other.built_;
+ other.module_ = nullptr;
+ other.kernelPtr_ = nullptr;
+ other.built_ = false;
+ }
+ return *this;
+ }
+
+ // ---- Phase 1: Support check (spec lookup, cache SM count) ----
+ error_t
+ check_support(AttentionShape_t shape, int sm_version) override {
+ spec_ = lookup_kernel_spec(shape.d_qk, sm_version);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ spec_ == nullptr,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Unsupported config: d=" + std::to_string(shape.d_qk) + " sm_version=" + std::to_string(sm_version));
+
+ d_ = shape.d_qk;
+ sm_version_ = sm_version;
+ tile_m_ = spec_->tile_m;
+ tile_n_ = spec_->tile_n;
+ tile_k_ = spec_->tile_k;
+ smemBytes_ = spec_->smem_bytes;
+ kernelName_ = spec_->kernel_name;
+
+ // Cache SM count for later use in execute()
+ cudaDeviceProp devProp;
+ int device_ordinal = 0;
+ cudaError_t cuda_err = detail::cuda_get_device(&device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDevice failed");
+ cuda_err = detail::cuda_get_device_properties(&devProp, device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDeviceProperties failed");
+ sm_count_ = devProp.multiProcessorCount;
+
+ support_checked_ = true;
+ return {error_code_t::OK, ""};
+ }
+
+ // Workspace size needed by execute() (tile_id_counter: 4 bytes, 16-byte aligned)
+ static int64_t
+ get_workspace_size() {
+ return 16;
+ }
+
+ // ---- Phase 2: NVRTC compilation + module loading ----
+ error_t
+ build() override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!support_checked_ || spec_ == nullptr,
+ error_code_t::INVALID_VALUE,
+ "build() called before check_support()");
+
+ auto status = compile_and_load_kernel(spec_, module_, kernelPtr_, cubin_, cubinSize_, kernelName_);
+ if (status.is_good()) {
+ built_ = true;
+ }
+ return status;
+ }
+
+ // ---- Phase 3: Set up TMA descriptors, pack params, launch ----
+ // Strides are in ELEMENTS (not bytes), matching PyTorch's .stride() convention.
+ // All stride vectors have 4 elements in (b, h, s, d) order.
+ // For max/sum_exp the 4th element (d-stride) is typically 1 and is unused internally.
+ error_t
+ execute(int batch,
+ int heads_q,
+ int heads_kv,
+ int seq_q,
+ int seq_kv,
+ int d,
+ void* d_Q,
+ std::vector<int64_t> const& q_strides,
+ void* d_K,
+ std::vector<int64_t> const& k_strides,
+ void* d_V,
+ std::vector<int64_t> const& v_strides,
+ void* d_O,
+ std::vector<int64_t> const& o_strides,
+ void* d_max,
+ std::vector<int64_t> const& max_strides,
+ void* d_sum_exp,
+ std::vector<int64_t> const& se_strides,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ std::optional<float> user_attn_scale = std::nullopt) override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!built_, error_code_t::INVALID_VALUE, "execute() called before build()");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ q_strides.size() < 4 || k_strides.size() < 4 || v_strides.size() < 4 || o_strides.size() < 4,
+ error_code_t::INVALID_VALUE,
+ "Q/K/V/O strides must have at least 4 elements");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(max_strides.size() < 3 || se_strides.size() < 3,
+ error_code_t::INVALID_VALUE,
+ "max/sum_exp strides must have at least 3 elements");
+
+ int B = batch;
+ int H_q = heads_q;
+ int H_kv = heads_kv;
+ int S_q = seq_q;
+ int S_kv = seq_kv;
+ int D = d;
+ int TILE_M = tile_m_;
+ int TILE_N = tile_n_;
+
+ // ---- Set up AttentionDescriptor ----
+ AttentionDescriptor_t attnDesc = {};
+ attnDesc.b = B;
+ attnDesc.q_h = H_q;
+ attnDesc.k_h = H_kv;
+ attnDesc.v_h = H_kv;
+ attnDesc.s_q = S_q;
+ attnDesc.s_kv = S_kv;
+ attnDesc.d_qk = D;
+ attnDesc.d_v = D;
+ attnDesc.q_heads_per_k = (H_q >= H_kv && H_kv > 0) ? (uint16_t)(H_q / H_kv) : 1;
+ attnDesc.q_heads_per_v = (H_q >= H_kv && H_kv > 0) ? (uint16_t)(H_q / H_kv) : 1;
+ attnDesc.min_q_heads_per_kv = attnDesc.q_heads_per_k;
+
+ // ---- Tile scheduling ----
+ int effective_tile_m = TILE_M * 2;
+ int tiles_r = div_up(S_q, effective_tile_m);
+ int tiles_hr = H_q * tiles_r;
+ int num_tiles = B * tiles_hr;
+ FastDivisor_t tiles_hr_div = make_fast_divisor(tiles_hr);
+ FastDivisor_t tiles_r_div = make_fast_divisor(tiles_r);
+
+ // ---- TMA descriptors (4D) ----
+ // Caller strides are in elements; TMA needs bytes.
+ uint32_t elem_bytes = sizeof(half);
+ uint32_t elems_per_ld = std::min(64, D);
+
+ // Q TMA (tma_tensor_3): dims = (D, S_q, H_q, B)
+ CUtensorMap tma_q = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_q,
+ d_Q,
+ CU_TENSOR_MAP_DATA_TYPE_FLOAT16,
+ D,
+ S_q,
+ H_q,
+ B,
+ (uint64_t)q_strides[2] * elem_bytes,
+ (uint64_t)q_strides[1] * elem_bytes,
+ (uint64_t)q_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_M * 2,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // K TMA (tma_tensor_2)
+ CUtensorMap tma_k = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_k,
+ d_K,
+ CU_TENSOR_MAP_DATA_TYPE_FLOAT16,
+ D,
+ S_kv,
+ H_kv,
+ B,
+ (uint64_t)k_strides[2] * elem_bytes,
+ (uint64_t)k_strides[1] * elem_bytes,
+ (uint64_t)k_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_N,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // V TMA (tma_tensor_1)
+ CUtensorMap tma_v = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_v,
+ d_V,
+ CU_TENSOR_MAP_DATA_TYPE_FLOAT16,
+ D,
+ S_kv,
+ H_kv,
+ B,
+ (uint64_t)v_strides[2] * elem_bytes,
+ (uint64_t)v_strides[1] * elem_bytes,
+ (uint64_t)v_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_N,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // O TMA (tma_tensor_5)
+ CUtensorMap tma_o = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_o,
+ d_O,
+ CU_TENSOR_MAP_DATA_TYPE_FLOAT16,
+ D,
+ S_q,
+ H_q,
+ B,
+ (uint64_t)o_strides[2] * elem_bytes,
+ (uint64_t)o_strides[1] * elem_bytes,
+ (uint64_t)o_strides[0] * elem_bytes,
+ elems_per_ld,
+ 16,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // ---- Scaling ----
+ float attn_scale = user_attn_scale.value_or(1.0f / std::sqrt((float)D));
+ float tensor_13 = -INFINITY;
+
+ // ---- Tensor descriptors for max and sum_exp (f32, [B, H_q, S_q]) ----
+ // Strides provided by caller in elements.
+ tensor_descriptor desc_max = {};
+ desc_max.num_dims = 3;
+ desc_max.dims[0] = B;
+ desc_max.dims[1] = H_q;
+ desc_max.dims[2] = S_q;
+ desc_max.strides[0] = max_strides[0];
+ desc_max.strides[1] = max_strides[1];
+ desc_max.strides[2] = max_strides[2];
+
+ tensor_descriptor desc_sum_exp = {};
+ desc_sum_exp.num_dims = 3;
+ desc_sum_exp.dims[0] = B;
+ desc_sum_exp.dims[1] = H_q;
+ desc_sum_exp.dims[2] = S_q;
+ desc_sum_exp.strides[0] = se_strides[0];
+ desc_sum_exp.strides[1] = se_strides[1];
+ desc_sum_exp.strides[2] = se_strides[2];
+
+ // ---- Grid/Block ----
+ int CTAs = std::min(sm_count_, num_tiles);
+ dim3 grid(CTAs, 1, 1);
+ dim3 block(384, 1, 1);
+
+ // ---- Memset tile_id_counter (uses caller-provided workspace) ----
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!workspace,
+ error_code_t::INVALID_VALUE,
+ "workspace must not be null (need at least 16 bytes for tile_id_counter)");
+ int32_t* d_tile_id_counter = reinterpret_cast<int32_t*>(workspace);
+ {
+ cudaError_t memset_err = detail::cuda_mem_set_async(d_tile_id_counter, 0, sizeof(int32_t), stream);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ memset_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaMemsetAsync for tile_id_counter failed");
+ }
+
+ // ---- Build kernel params array ----
+ void* kernelParams[] = {
+ (void*)&attnDesc,
+ (void*)&num_tiles,
+ (void*)&tiles_hr_div,
+ (void*)&tiles_r_div,
+ (void*)&d_tile_id_counter,
+ (void*)&tma_q,
+ (void*)&tma_k,
+ (void*)&attn_scale,
+ (void*)&tensor_13,
+ (void*)&d_max,
+ (void*)&desc_max,
+ (void*)&d_sum_exp,
+ (void*)&desc_sum_exp,
+ (void*)&tma_v,
+ (void*)&tma_o,
+ };
+
+ // ---- Set shared memory attribute and launch ----
+ cudaError_t cuda_err;
+
+ cuda_err = detail::cuda_kernel_set_attribute_for_device(
+ kernelPtr_, cudaFuncAttributeMaxDynamicSharedMemorySize, smemBytes_, device);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaKernelSetAttributeForDevice failed (smem=" + std::to_string(smemBytes_) +
+ " bytes, error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ cuda_err = detail::cuda_launch_kernel((const void*)kernelPtr_, grid, block, kernelParams, smemBytes_, stream);
+ cudaError_t last_err = detail::cuda_get_last_error();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLaunchKernel failed (grid=" + std::to_string(grid.x) +
+ ", block=384, smem=" + std::to_string(smemBytes_) +
+ ", error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ last_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaGetLastError after kernel launch: " + detail::cuda_error_to_string(last_err));
+
+ return {error_code_t::OK, ""};
+ }
+
+ private:
+ // State from check_support()
+ const KernelSpec* spec_ = nullptr;
+ int d_ = 0;
+ int sm_version_ = 0;
+ int sm_count_ = 0;
+ bool support_checked_ = false;
+
+ // State from build()
+ cudaLibrary_t module_ = nullptr;
+ cudaKernel_t kernelPtr_ = nullptr;
+ std::unique_ptr<char[]> cubin_;
+ size_t cubinSize_ = 0;
+ int tile_m_ = 0, tile_n_ = 0, tile_k_ = 0;
+ int smemBytes_ = 0;
+ std::string kernelName_;
+ bool built_ = false;
+};
+
+} // namespace experimental
+} // namespace cudnn_frontend
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_fwd_silu_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_fwd_silu_kernel.h
new file mode 100644
index 0000000..77b5dd7
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_fwd_silu_kernel.h
@@ -0,0 +1,468 @@
+// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+#pragma once
+
+// Auto-generated from ln_fwd_silu_kernel.cu
+// Do not edit manually.
+
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Woverlength-strings"
+#endif
+
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4068)
+#endif
+
+namespace cudnn_frontend::experimental::generated {
+
+inline constexpr const char ln_fwd_silu_kernel_source[] =
+ R"KERNEL(
+constexpr int mxfp8_block_size = 32;
+constexpr int nvfp4_block_size = 16;
+
+template <typename _Traits>
+struct LnFwdShared {
+ using Traits = _Traits;
+ static constexpr int32_t SMEM_STATS_ELEMENTS = ((Traits::Stats::SMEM_BYTES > 0) ? Traits::Stats::SMEM_BYTES : 1);
+ static constexpr int32_t SMEM_BAR_ELEMENTS = ((Traits::USE_CLUSTER && Traits::CTAS_PER_ROW > 1)
+ ? (Traits::WARPS_M + 1 + Traits::WARPS_M * Traits::CTAS_PER_ROW)
+ : 1);
+ static constexpr int32_t SMEM_MXFP8_ELEMENTS =
+ ((isBlockScale_1D2X2X && !useBlockScaleColwiseKernel)
+ ? ((mxfp8_block_size * Traits::NUM_ELTS + (Traits::NUM_ELTS - 1)) * (mxfp8_block_size + 1))
+ : 1);
+ static constexpr int32_t GAMMA_ELEMENTS =
+ ((Traits::hasGamma && Traits::USE_GAMMA_SMEM)
+ ? (Traits::BATCH_SIZE * Traits::LDGS * Traits::THREADS_PER_ROW * Traits::NUM_ELTS)
+ : 1);
+ static constexpr int32_t BETA_ELEMENTS =
+ ((Traits::hasBeta && Traits::USE_GAMMA_SMEM)
+ ? (Traits::BATCH_SIZE * Traits::LDGS * Traits::THREADS_PER_ROW * Traits::NUM_ELTS)
+ : 1);
+
+ __align__(16) char smem_stats[SMEM_STATS_ELEMENTS];
+ __align__(16) uint64_t smem_bar[SMEM_BAR_ELEMENTS];
+ __align__(16) typename Traits::weight_t smem_gamma[GAMMA_ELEMENTS];
+ __align__(16) typename Traits::weight_t smem_beta[BETA_ELEMENTS];
+ __align__(16) float smem_mxfp8[SMEM_MXFP8_ELEMENTS];
+};
+
+extern "C" __global__
+__launch_bounds__(Ktraits::THREADS_PER_CTA, DESIRED_OCCUPANCY) void ln_fwd_kernel(
+ PersistentLnFwdParams params,
+ reduced_divisor divisor) { // divisor is div_batch if it is batch-first case, else it is div_seqLen
+ enum { ROWS_PER_CTA = Ktraits::ROWS_PER_CTA };
+ enum { WARPS_N = Ktraits::WARPS_N };
+ enum { WARPS_M = Ktraits::WARPS_M };
+ enum { THREADS_PER_ROW = Ktraits::THREADS_PER_ROW };
+ enum { VEC_COLS_PER_LDG = Ktraits::VEC_COLS_PER_LDG };
+ enum { VEC_COLS = Ktraits::VEC_COLS };
+ enum { BYTES_PER_ROW = Ktraits::BYTES_PER_ROW };
+ enum { LDGS = Ktraits::LDGS };
+ enum { NUM_ELTS = Ktraits::NUM_ELTS };
+ enum { THREADS_PER_WARP = Ktraits::THREADS_PER_WARP };
+ enum { CTAS_PER_ROW = Ktraits::CTAS_PER_ROW };
+ enum { COLS = Ktraits::COLS };
+ enum { COLS_PER_LDG = Ktraits::VEC_COLS_PER_LDG * Ktraits::NUM_ELTS };
+ enum { COLS_PER_LDG_PER_CTA = COLS_PER_LDG / Ktraits::CTAS_PER_ROW };
+ enum { VEC_COLS_PER_LDG_PER_CTA = VEC_COLS_PER_LDG / Ktraits::CTAS_PER_ROW };
+ enum { USE_GAMMA_SMEM = Ktraits::USE_GAMMA_SMEM };
+ enum { BATCH_SIZE = Ktraits::BATCH_SIZE };
+ enum { isAdaLN = Ktraits::isAdaLN };
+ enum { isBatchFirst = Ktraits::isBatchFirst };
+
+ using output_t = typename Ktraits::output_t;
+ using weight_t = typename Ktraits::weight_t;
+ using index_t = typename Ktraits::index_t;
+ using compute_t = typename Ktraits::compute_t;
+ using norm_output_t = typename Ktraits::norm_output_t;
+ using Ivec = typename Ktraits::Ivec;
+ using Ovec = typename Ktraits::Ovec;
+ using Wvec = typename Ktraits::Wvec;
+ using Cvec = typename Ktraits::Cvec;
+ using NormOvec = typename Ktraits::NormOvec;
+
+ using Stats = typename Ktraits::Stats;
+ using stats_t = typename Stats::stats_t;
+
+#ifdef USE_STATIC_SMEM_VALUE
+ __shared__ __align__(16) char smem_base_[USE_STATIC_SMEM_VALUE];
+#else
+ extern __shared__ char smem_base_[];
+#endif
+
+ LnFwdShared<Ktraits> *shared = reinterpret_cast<LnFwdShared<Ktraits> *>(smem_base_);
+
+ uint64_t *smemBar = shared->smem_bar;
+#if LN_USE_CLUSTER
+ if (CTAS_PER_ROW > 1) {
+#if (__CUDA_ARCH__ >= 900) && (CUDART_VERSION >= 12080)
+ // Init the empty bars for each warp
+ if (threadIdx.x < WARPS_M) {
+ cuda::ptx::mbarrier_init(&smemBar[threadIdx.x], CTAS_PER_ROW * WARPS_N * THREADS_PER_WARP);
+ }
+ // Init the full bar (shared by the CTA)
+ if (threadIdx.x == 0) {
+ cuda::ptx::mbarrier_init(&smemBar[WARPS_M], 1);
+ cuda::ptx::fence_mbarrier_init(cuda::ptx::sem_release, cuda::ptx::scope_cluster);
+ }
+ cuda::ptx::barrier_cluster_arrive(cuda::ptx::sem_relaxed);
+ cuda::ptx::barrier_cluster_wait();
+#else
+ static_assert(true, "Cluster enabled on host side but not available on device");
+#endif // (__CUDA_ARCH__ >= 900) && (CUDART_VERSION >= 12080)
+ }
+#endif // LN_USE_CLUSTER
+
+ const index_t tidx = threadIdx.x;
+ const index_t bidn = blockIdx.x % CTAS_PER_ROW;
+ const index_t bidm = blockIdx.x / CTAS_PER_ROW;
+ const index_t lane = tidx % THREADS_PER_WARP;
+ const index_t warp = tidx / THREADS_PER_WARP;
+ const index_t warp_m = warp / WARPS_N;
+ const index_t warp_n = warp % WARPS_N;
+
+ const index_t r = bidm * ROWS_PER_CTA + warp_m;
+
+ const index_t col_in_tile = warp_n * THREADS_PER_WARP + lane;
+ const index_t c = bidn * THREADS_PER_ROW + col_in_tile;
+
+ Stats stats(params, bidm, bidn, warp_m, warp_n, tidx, lane, shared->smem_stats, smemBar);
+
+ // Unused when USE_GAMMA_SMEM is true and will be optimized out
+ [[maybe_unused]] Wvec gamma_regs[BATCH_SIZE][LDGS];
+ [[maybe_unused]] Wvec beta_regs[BATCH_SIZE][LDGS];
+ weight_t *gamma_smem = nullptr, *beta_smem = nullptr;
+ if constexpr (USE_GAMMA_SMEM) {
+ static constexpr int32_t SMEM_BYTES_GAMMA = THREADS_PER_ROW * BATCH_SIZE * LDGS * sizeof(Wvec);
+ if constexpr (Ktraits::hasGamma) {
+ gamma_smem = shared->smem_gamma;
+ }
+ if constexpr (Ktraits::hasBeta) {
+ beta_smem = shared->smem_beta;
+ }
+ }
+
+ // If we are mxfp8 output type, we need shared memory for amax calculations across warps
+ // 2d1x1x (not yet implemented) requires 1 (1 for a 32x32 block)
+ // 1d1x1x requires 0 (since it reduces over a row which can be done with warp reduce)
+ // 1d2x2x requires 32x(32+1)xNUM_ELTS, more details as follows:
+ constexpr int block_scale_size = isFP4Out ? nvfp4_block_size : mxfp8_block_size;
+ BlockScaleRowHelper<Cvec, Ovec, block_scale_size> rowwise_scale_helper{};
+ BlockScaleColHelper<Cvec, Ovec, mxfp8_block_size> colwise_scale_helper{shared->smem_mxfp8};
+ compute_t *mu_ptr = static_cast<compute_t *>(params.mu);
+ compute_t *rs_ptr = static_cast<compute_t *>(params.rs);
+
+ constexpr compute_t rn = 1.f / compute_t(Ktraits::COLS);
+
+ index_t idx = c;
+
+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900
+ asm volatile("griddepcontrol.wait;\n");
+#endif
+
+ // Load gamma and beta into shared memory or registers
+#pragma unroll
+ for (int b = 0; b < BATCH_SIZE; b++) {
+// CL-14115: The unroll factor 128 for LDGS was chosen based on the compilation/perf results for APEX LN_fwd engines
+#pragma unroll 128
+ for (int it = 0; it < LDGS; it++) {
+ if constexpr (USE_GAMMA_SMEM) {
+ if (warp_m == 0) {
+ const index_t cur_gamma_smem_base_idx =
+ (b * LDGS + it) * THREADS_PER_ROW * NUM_ELTS + warp_n * THREADS_PER_WARP * NUM_ELTS + lane;
+ if constexpr (Ktraits::hasGamma) {
+ Wvec cur_gamma_vec;
+ cur_gamma_vec.load_from(params.gamma, idx);
+#pragma unroll
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ const index_t cur_gamma_smem_idx = cur_gamma_smem_base_idx + jt * THREADS_PER_WARP;
+ gamma_smem[cur_gamma_smem_idx] = cur_gamma_vec.data.elt[jt];
+ }
+ }
+ if constexpr (Ktraits::hasBeta) {
+ Wvec cur_beta_vec;
+ cur_beta_vec.load_from(params.beta, idx);
+#pragma unroll
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ const index_t cur_beta_smem_idx = cur_gamma_smem_base_idx + jt * THREADS_PER_WARP;
+ beta_smem[cur_beta_smem_idx] = cur_beta_vec.data.elt[jt];
+ }
+ }
+ }
+ } else if constexpr (!GAMMA_ON_DEMAND) {
+ if constexpr (Ktraits::hasGamma) {
+ gamma_regs[b][it].load_from(params.gamma, idx);
+ }
+ if constexpr (Ktraits::hasBeta) {
+ beta_regs[b][it].load_from(params.beta, idx);
+ }
+ }
+ idx += VEC_COLS_PER_LDG;
+ }
+ }
+
+ if constexpr (USE_GAMMA_SMEM) {
+ __syncthreads();
+ }
+
+ // Initialize scale and bias for FP8 output
+ compute_t scale = 1.f;
+ if constexpr (isFP8Out) {
+ scale = __ldg(params.scale);
+ }
+ compute_t amax = 0;
+
+ index_t remaining_rows = params.rows - bidm * ROWS_PER_CTA;
+ int row_increment_step = params.ctas_per_col * ROWS_PER_CTA;
+ int batch_idx = 0, remainder = 0;
+ int batch_increment_step = 0, step_remainder = 0;
+ if constexpr (isAdaLN) {
+ if constexpr (isBatchFirst) {
+ divisor.divmod(r, batch_idx, remainder); // row = batch_idx * seqLen + remainder; (remainder <
+ // seqLen) batch_idx = r/seqLen
+ divisor.divmod(row_increment_step, batch_increment_step, step_remainder); // row_increment_step =
+ // batch_increment_step * seqLen +
+ // step_remainder (remainder <
+ // seqLen)
+ } else {
+ batch_idx = divisor.mod(r); // batch_idx = row % BATCH_SIZE;
+ batch_increment_step =
+ divisor.mod(row_increment_step); // batch_increment_step = row_increment_step % BATCH_SIZE;
+ }
+ }
+
+ for (int row = r; row < params.rows;
+ row += row_increment_step, batch_idx += batch_increment_step, remainder += step_remainder) {
+ index_t idx = static_cast<index_t>(row) * VEC_COLS + c;
+
+ // Load x and convert to compute type per row per thread
+ compute_t xf[LDGS * NUM_ELTS];
+#pragma unroll 128
+ for (int it = 0; it < LDGS; it++) {
+ Ivec x_it{};
+ x_it.load_from(params.x, idx);
+#pragma unroll
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ compute_t x_ij = compute_t(x_it.data.elt[jt]);
+ xf[it * NUM_ELTS + jt] = x_ij;
+ }
+ idx += VEC_COLS_PER_LDG;
+ }
+
+ // Compute mean and variance per row per thread
+ // How many rows current CTA will handle for this iteration
+ int rows_per_cta = remaining_rows >= ROWS_PER_CTA ? ROWS_PER_CTA : remaining_rows;
+ stats_t s = stats.compute<Ktraits::isRMSNorm, LDGS, NUM_ELTS>(xf, rn, rows_per_cta);
+ remaining_rows -= params.ctas_per_col * ROWS_PER_CTA; // for next iteration
+ compute_t mu = Get<0>::of<stats_t, compute_t>(s);
+ compute_t m2 = Get<1>::of<stats_t, compute_t>(s);
+ if constexpr (!Ktraits::isRMSNorm) {
+ if (bidn == 0 && warp_n == 0 && lane == 0) {
+ mu_ptr[row] = mu;
+ }
+ }
+ compute_t rs = rsqrtf(rn * m2 + params.epsilon);
+
+ if (bidn == 0 && warp_n == 0 && lane == 0) {
+ rs_ptr[row] = rs;
+ }
+
+ idx = row * VEC_COLS + c;
+
+ if constexpr (isAdaLN) {
+ if constexpr (isBatchFirst) {
+ if (remainder >= params.seqLen) {
+ batch_idx += 1;
+ remainder -= params.seqLen;
+ }
+ } else {
+ if (batch_idx >= BATCH_SIZE) {
+ batch_idx -= BATCH_SIZE;
+ }
+ }
+ }
+ index_t gamma_idx = c + (batch_idx * LDGS) * VEC_COLS_PER_LDG;
+#pragma unroll 128
+ for (int it = 0; it < LDGS; it++) {
+ Cvec z_math;
+ [[maybe_unused]] Wvec g_wt;
+ [[maybe_unused]] Wvec b_wt;
+ if constexpr (GAMMA_ON_DEMAND && Ktraits::hasGamma && !USE_GAMMA_SMEM) {
+ g_wt.load_from(params.gamma, gamma_idx);
+
+ if constexpr (Ktraits::hasBeta) {
+ b_wt.load_from(params.beta, gamma_idx);
+ }
+ }
+#pragma unroll
+ // Compute output per ldg per row per thread
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ compute_t y_ij = rs * (xf[it * NUM_ELTS + jt] - mu);
+
+ if constexpr (Ktraits::hasGamma) {
+ weight_t g_ij_wt{};
+ const int32_t cur_gamma_smem_base_idx = (batch_idx * LDGS + it) * THREADS_PER_ROW * NUM_ELTS +
+ warp_n * THREADS_PER_WARP * NUM_ELTS + lane;
+ const int32_t cur_gamma_smem_idx = cur_gamma_smem_base_idx + jt * THREADS_PER_WARP;
+ if constexpr (USE_GAMMA_SMEM) {
+ g_ij_wt = gamma_smem[cur_gamma_smem_idx];
+ } else if constexpr (GAMMA_ON_DEMAND) {
+ g_ij_wt = g_wt.data.elt[jt];
+ } else {
+ g_ij_wt = gamma_regs[batch_idx][it].data.elt[jt];
+ }
+ compute_t g_ij = static_cast<compute_t>(g_ij_wt);
+ if constexpr (isZeroCenteredGamma) {
+ if constexpr (isZeroCenteredGammaCastBeforeAdd) {
+ g_ij = static_cast<compute_t>(g_ij_wt) + static_cast<compute_t>(1.f);
+ } else {
+ g_ij = static_cast<compute_t>(g_ij_wt + static_cast<weight_t>(1.f));
+ }
+ }
+ if constexpr (Ktraits::hasBeta) {
+ compute_t b_ij{};
+ const int32_t cur_beta_smem_idx = cur_gamma_smem_base_idx + jt * THREADS_PER_WARP;
+ if constexpr (USE_GAMMA_SMEM) {
+ b_ij = beta_smem[cur_beta_smem_idx];)KERNEL"
+ R"KERNEL( } else if constexpr (GAMMA_ON_DEMAND) {
+ b_ij = static_cast<compute_t>(b_wt.data.elt[jt]);
+ } else {
+ b_ij = beta_regs[batch_idx][it].data.elt[jt];
+ }
+ y_ij = g_ij * y_ij + b_ij;
+ } else {
+ y_ij = g_ij * y_ij;
+ }
+ }
+
+ // SiLU activation: y = y * sigmoid(y) = y / (1 + exp(-y))
+ // Applied after norm + gamma [+ beta], before FP8/block-scale quantization.
+ y_ij = __fdividef(y_ij, 1.0f + __expf(-y_ij));
+
+ if constexpr (isFP8Out) {
+ if (hasAmax) {
+ __builtin_assume(amax >= 0);
+ amax = fmaxf(amax, fabsf(y_ij));
+ }
+ y_ij *= scale;
+ }
+ z_math.data.elt[jt] = y_ij;
+ } // NUM_ELTS
+
+ if constexpr (isBlockScaleOut) {
+ static_assert(!isBlockScaleOut ||
+ (Ktraits::COLS % mxfp8_block_size == 0)); // ensure cols divisable by 32
+
+ index_t sf_row_idx = idx / mxfp8_block_size;
+ [[maybe_unused]] NormOvec z_intermediate;
+ if constexpr (std::is_same<compute_t, norm_output_t>::value) {
+ rowwise_scale_helper.blockQuantizeStore(z_math, params.scale_row, sf_row_idx, params.z, idx);
+ } else {
+ z_math.to(z_intermediate);
+ rowwise_scale_helper.blockQuantizeStore(
+ z_intermediate, params.scale_row, sf_row_idx, params.z, idx);
+ }
+ if constexpr (isBlockScale_1D2X2X) {
+ if constexpr (useBlockScaleColwiseKernel) {
+ // Store the temporary z_math values in workspace and launch a separate kernel to compute the
+ // colwise scaling results
+ if constexpr (std::is_same<compute_t, norm_output_t>::value) {
+ z_math.store_to(params.z_math, idx);
+ } else {
+ z_intermediate.store_to(params.z_math, idx);
+ }
+ } else {
+ if constexpr (std::is_same<compute_t, norm_output_t>::value) {
+ colwise_scale_helper.initTile(z_math, THREADS_PER_ROW * WARPS_M);
+ // static_assert(!std::is_same<compute_t, norm_output_t>::value);
+ } else {
+ colwise_scale_helper.initTile(z_intermediate, THREADS_PER_ROW * WARPS_M);
+ }
+ index_t sf_col_row_idx = 0;
+ index_t sf_col_col_idx = 0;
+ index_t sf_col_row_width = 0;
+ index_t z_col_idx = 0;
+ index_t z_row_offset = row - row % mxfp8_block_size;
+ if constexpr (!isBlockScale_1D2X2X_Transpose) {
+ sf_col_row_idx = row / mxfp8_block_size;
+ sf_col_col_idx = it * VEC_COLS_PER_LDG + bidn * VEC_COLS_PER_LDG_PER_CTA + warp;
+ sf_col_row_width = VEC_COLS;
+ z_col_idx = (z_row_offset + lane) * VEC_COLS + sf_col_col_idx;
+ } else {
+ constexpr index_t group_size = mxfp8_block_size / NUM_ELTS;
+ sf_col_row_idx = it * COLS_PER_LDG + bidn * COLS_PER_LDG_PER_CTA + warp * NUM_ELTS;
+ sf_col_col_idx = row / mxfp8_block_size;
+ sf_col_row_width = params.rows / mxfp8_block_size;
+ z_col_idx = (sf_col_row_idx + lane / group_size) * params.rows / NUM_ELTS +
+ z_row_offset / NUM_ELTS + (lane % group_size);
+ }
+ colwise_scale_helper.blockQuantizeStore<isBlockScale_1D2X2X_Transpose>(
+ params.scale_col,
+ sf_col_row_idx,
+ sf_col_col_idx,
+ sf_col_row_width,
+ params.z_col,
+ z_col_idx,
+ THREADS_PER_ROW * WARPS_M);
+ }
+ }
+ } else {
+ Ovec z;
+ z_math.to(z);
+ z.store_to(params.z, idx);
+ }
+ idx += VEC_COLS_PER_LDG;
+ gamma_idx += VEC_COLS_PER_LDG;
+ } // LDGS
+ } // grid stride loop
+
+ // Write scale_inv before launch_dependents - consumer needs it to dequantize FP8 output
+ if constexpr (isFP8Out) {
+ if (hasScaleInv && blockIdx.x == 0 && threadIdx.x == 0) {
+ *reinterpret_cast<compute_t *>(params.scale_inv) = __fdividef(1.f, scale);
+ }
+ }
+
+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900
+ asm volatile("griddepcontrol.launch_dependents;\n");
+#endif
+
+ // amax can be after launch_dependents - only needed for delayed scaling (next iteration)
+ if constexpr (isFP8Out) {
+ if constexpr (hasAmax) {
+ amax = reduce_max<WARPS_M * WARPS_N>(amax, warp, threadIdx.x);
+ if (threadIdx.x == 0) {
+ atomicMaxFloat(reinterpret_cast<compute_t *>(params.amax), amax);
+ }
+ }
+ }
+}
+
+)KERNEL";
+inline constexpr size_t ln_fwd_silu_kernel_source_len = sizeof(ln_fwd_silu_kernel_source) - 1;
+
+} // namespace cudnn_frontend::experimental::generated
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+namespace cudnn_frontend::experimental::generated {
+
+inline constexpr const char ln_fwd_silu_kernel_flags[] = R"FLAGS(--gpu-architecture=sm_100a
+--std=c++17
+-w
+--define-macro=__CUDACC_RTC__
+-default-device
+--use_fast_math
+)FLAGS";
+inline constexpr size_t ln_fwd_silu_kernel_flags_len = sizeof(ln_fwd_silu_kernel_flags) - 1;
+
+} // namespace cudnn_frontend::experimental::generated
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_headers.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_headers.h
new file mode 100644
index 0000000..59bac63
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_headers.h
@@ -0,0 +1,2043 @@
+// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+#pragma once
+// Auto-generated — do not edit manually.
+// Lightweight LN headers (~3K lines) replacing the 151K-line embedded version.
+// Uses #include directives for CUDA TK headers (requires --include-path at NVRTC compile time).
+
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Woverlength-strings"
+#endif
+
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4068)
+#endif
+
+namespace cudnn_frontend {
+namespace experimental {
+namespace generated {
+
+inline constexpr const char ln_headers_source[] =
+ R"KERNEL(
+#pragma once
+// Auto-generated lightweight LN kernel header.
+// Replaces the 151K-line persistent_ln_headers_13.0.h with:
+// - Standard CUDA TK #include directives (resolved via --include-path at NVRTC compile time)
+// - ~2900 lines of cuDNN-authored LN-specific code extracted from the original
+//
+// CGA/cluster support (USE_CLUSTER) is disabled:
+// - #include <cuda/ptx> and cooperative_groups are NOT included
+// - All if constexpr (USE_CLUSTER) branches changed to if constexpr(USE_CLUSTER) so dead code is not compiled
+//
+// Requires CUDA Toolkit headers available at the --include-path location.
+// Generated by step3b_extract_ln_headers.py — do not edit manually.
+
+// ============================================================
+// Standard CUDA Toolkit headers (resolved via --include-path)
+// ============================================================
+
+// Minimal std stubs needed by NVRTC (no standard library available)
+#if __cplusplus >= 201103L
+namespace std {
+template<bool B, class T = void> struct enable_if {};
+template<class T> struct enable_if<true, T> { typedef T type; };
+#if __cplusplus >= 201402L
+template< bool B, class T = void > using enable_if_t = typename enable_if<B,T>::type;
+#endif
+
+struct true_type { enum { value = true }; operator bool() const { return true; } };
+struct false_type { enum { value = false }; operator bool() const { return false; } };
+
+template<typename T> struct is_floating_point : false_type {};
+template<> struct is_floating_point<float> : true_type {};
+template<> struct is_floating_point<double> : true_type {};
+
+template<typename T> struct is_integral : false_type {};
+template<> struct is_integral<bool> : true_type {};
+template<> struct is_integral<char> : true_type {};
+template<> struct is_integral<short> : true_type {};
+template<> struct is_integral<int> : true_type {};
+template<> struct is_integral<long> : true_type {};
+template<> struct is_integral<long long> : true_type {};
+template<> struct is_integral<unsigned char> : true_type {};
+template<> struct is_integral<unsigned short> : true_type {};
+template<> struct is_integral<unsigned int> : true_type {};
+template<> struct is_integral<unsigned long> : true_type {};
+template<> struct is_integral<unsigned long long> : true_type {};
+
+template<typename T, typename U> struct is_same : false_type {};
+template<typename T> struct is_same<T, T> : true_type {};
+}
+#endif
+
+// CUDA numeric type headers
+#include <cuda_fp16.h>
+#include <cuda_bf16.h>
+#include <cuda_fp8.h>
+#include <cuda_fp4.h>
+
+// NOTE: #include <cuda/ptx> and <cooperative_groups.h> are intentionally omitted.
+// They are only needed for CGA/cluster support (USE_CLUSTER=true), which this
+// OSS engine does not use. All USE_CLUSTER code paths are guarded with
+// "if constexpr" so dead branches are not compiled.
+
+// ============================================================
+// Fixed-width integer typedefs for NVRTC (no <cstdint> available)
+// ============================================================
+constexpr int THREADS_PER_WARP = 32;
+
+#ifndef __CUDACC_RTC__
+#include <stdint.h>
+#else
+typedef signed char int8_t;
+typedef unsigned char uint8_t;
+typedef signed short int16_t;
+typedef unsigned short uint16_t;
+typedef signed int int32_t;
+typedef unsigned int uint32_t;
+typedef signed long long int64_t;
+typedef unsigned long long uint64_t;
+#endif
+
+// ============================================================
+// cuDNN-authored LN kernel utilities
+// Extracted from persistent_ln_headers_13.0.h
+// ============================================================
+
+
+// cuDNN type aliases for FP8 types (from after inlined cuda_fp8.h)
+typedef __nv_fp8_e4m3 nv_fp8_e4m3;
+typedef __nv_fp8x2_e4m3 nv_fp8x2_e4m3;
+typedef __nv_fp8_e5m2 nv_fp8_e5m2;
+typedef __nv_fp8x2_e5m2 nv_fp8x2_e5m2;
+
+// cuDNN type aliases for FP4 types (from after inlined cuda_fp4.h)
+typedef __nv_fp4_e2m1 nv_fp4_e2m1;
+typedef __nv_fp4x2_e2m1 nv_fp4x2_e2m1;
+typedef __nv_fp4x4_e2m1 nv_fp4x4_e2m1;
+
+// Pointer typedefs for NVRTC (from original Jitify stubs)
+typedef int64_t intptr_t;
+typedef uint64_t uintptr_t;
+typedef int64_t intmax_t;
+typedef uint64_t uintmax_t;
+
+// Large vector types for 64-byte and 32-byte loads
+struct uint16 {
+ uint4 u;
+ uint4 v;
+ uint4 s;
+ uint4 t;
+};
+
+struct uint8 {
+ uint4 u;
+ uint4 v;
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// Datatype helpers
+
+template <int BYTES>
+struct BytesToType {};
+
+template <>
+struct BytesToType<64> {
+ using Type = uint16;
+};
+
+template <>
+struct BytesToType<32> {
+ using Type = uint8;
+};
+
+template <>
+struct BytesToType<16> {
+ using Type = uint4;
+};
+
+template <>
+struct BytesToType<8> {
+ using Type = uint64_t;
+};
+
+template <>
+struct BytesToType<4> {
+ using Type = uint32_t;
+};
+
+template <>
+struct BytesToType<2> {
+ using Type = uint16_t;
+};
+
+template <>
+struct BytesToType<1> {
+ using Type = uint8_t;
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+struct TypeToVec2 {};
+
+template <>
+struct TypeToVec2<float> {
+ using Type = float2;
+};
+
+template <>
+struct TypeToVec2<half> {
+ using Type = half2;
+};
+
+template <>
+struct TypeToVec2<nv_bfloat16> {
+ using Type = nv_bfloat162;
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+template <int INDEX>
+struct Get {
+ template <typename T, typename R>
+ static inline __device__ R
+ of(const T& vec);
+};
+
+template <>
+template <typename T, typename R>
+inline __device__ R
+Get<0>::of(const T& vec) {
+ return vec.x;
+}
+
+template <>
+template <typename T, typename R>
+inline __device__ R
+Get<1>::of(const T& vec) {
+ return vec.y;
+}
+
+template <>
+template <typename T, typename R>
+inline __device__ R
+Get<2>::of(const T& vec) {
+ return vec.z;
+}
+
+template <>
+template <typename T, typename R>
+inline __device__ R
+Get<3>::of(const T& vec) {
+ return vec.w;
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+template <typename Src, typename Dst>
+struct Converter {
+ static inline __device__ Dst
+ convert(const Src& from) {
+ return Dst(from);
+ }
+};
+
+template <>
+struct Converter<float2, half2> {
+ static inline __device__ half2
+ convert(const float2& x) {
+ return __float22half2_rn(x);
+ }
+};
+
+template <>
+struct Converter<float2, nv_bfloat162> {
+ static inline __device__ nv_bfloat162
+ convert(const float2& x) {
+#if __CUDA_ARCH__ >= 800
+ return __float22bfloat162_rn(x);
+#else
+ union {
+ nv_bfloat162 raw;
+ nv_bfloat16 x;
+ nv_bfloat16 y;
+ } tmp;
+ tmp.x = __float2bfloat16_rn(x.x);
+ tmp.y = __float2bfloat16_rn(x.y);
+ return tmp.raw;
+#endif
+ }
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+struct Zeros {
+ static inline __device__ T
+ get() {
+ return T(0.f);
+ }
+};
+
+template <>
+struct Zeros<float2> {
+ static inline __device__ float2
+ get() {
+ return make_float2(0.f, 0.f);
+ }
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+__device__ __inline__ uint8_t
+float_to_e8m0(float val) {
+ // CL-15277: use rounding-up mode for float -> e8m0 conversion
+#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000) && \
+ (defined(__CUDA_ARCH_FEAT_SM100_ALL) || defined(__CUDA_ARCH_FEAT_SM101_ALL) || defined(__CUDA_ARCH_FEAT_SM110_ALL) || \
+ defined(__CUDA_ARCH_FEAT_SM120_ALL))
+ uint16_t out;
+ asm volatile(
+ "{\n"
+ "cvt.rp.satfinite.ue8m0x2.f32 %0, 0.0, %1;\n"
+ "}"
+ : "=h"(out)
+ : "f"(val));
+ return *reinterpret_cast<uint8_t*>(&out);
+#else
+#if CUDART_VERSION >= 12080
+ // Use explicit round-up mode to match the SM_100+ hardware instruction
+ return __nv_cvt_float_to_e8m0(val, __NV_SATFINITE, cudaRoundPosInf);
+#else
+ if (isnan(val) || isinf(val)) {
+ return 0xFF;
+ }
+ uint32_t val_u32 = __float_as_uint(val);
+ uint8_t exponent = (val_u32 >> 23) & 0xFF;
+ uint32_t mantissa = val_u32 & 0x7FFFFF;
+ if ((mantissa > 0) && (exponent != 0xFE)) { // exp can only be < 0xFE here
+ exponent++;
+ }
+ return exponent;
+#endif
+#endif
+}
+
+__device__ __inline__ float
+e8m0_to_float(uint8_t val) {
+#if CUDART_VERSION >= 12080
+ __nv_fp8_e8m0 e8m0;
+ e8m0.__x = val;
+ return static_cast<float>(e8m0);
+#else
+ return __uint_as_float(static_cast<uint32_t>(val) << 23);
+#endif
+
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// Vectorization data structures
+template <typename ELT_TYPE, uint32_t NUM_ELT>
+struct Vec {
+ using Elt_type = ELT_TYPE;
+
+ enum { BYTES = NUM_ELT * sizeof(Elt_type) };
+ using Vec_type = typename BytesToType<BYTES>::Type;
+
+ using Alias_type = union {
+ Vec_type vec;
+ Elt_type elt[NUM_ELT];
+ };
+
+ Alias_type data;
+
+ template <typename S>
+ inline __device__ void
+ to(Vec<S, NUM_ELT>& other) {
+#pragma unroll
+ for (int it = 0; it < NUM_ELT; it++) {
+ other.data.elt[it] = S(this->data.elt[it]);
+ }
+ }
+
+ template <typename Op>
+ inline __device__ void
+ assign(const Op& op) {
+#pragma unroll
+ for (int it = 0; it < NUM_ELT; it++) {
+ this->data.elt[it] = op(it);
+ }
+ }
+
+ inline __device__ void
+ load_from(const void* base_ptr, const size_t idx) {
+ this->data.vec = static_cast<const Vec_type*>(base_ptr)[idx];
+ }
+
+ inline __device__ void
+ store_to(void* base_ptr, const size_t idx) {
+ static_cast<Vec_type*>(base_ptr)[idx] = this->data.vec;
+ }
+
+ inline __device__ void
+ operator+=(const Vec<ELT_TYPE, NUM_ELT>& rhs) {
+#pragma unroll
+ for (int it = 0; it < NUM_ELT; it++) {
+ this->data.elt[it] += rhs.data.elt[it];
+ }
+ }
+};
+
+inline __device__ float2
+operator+(const float2& a, const float2& b) {
+ return {a.x + b.x, a.y + b.y};
+}
+
+inline __device__ void
+operator+=(float2& a, const float2& b) {
+ a.x += b.x;
+ a.y += b.y;
+}
+
+template <typename T>
+struct Sum {
+ inline __device__
+ Sum() {}
+ inline __device__ T
+ operator()(const T& a, const T& b) {
+ return a + b;
+ }
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+inline __device__ void
+__nv_ptx_builtin_ocg_fence_view_async_shared(void) {
+ asm volatile("fence.proxy.async.shared::cta;\n");
+}
+
+extern "C" {
+__device__ uint32_t
+__nvvm_get_smem_pointer(void* ptr);
+//__device__ void
+//__nv_ptx_builtin_ocg_fence_view_async_shared(void);
+__device__ void
+__nv_ptx_builtin_ocg_write_async_shared_b32(uint32_t dstAddr, uint32_t mbarrierAddr, uint32_t b0);
+__device__ void
+__nv_ptx_builtin_ocg_write_async_shared_b64(uint32_t dstAddr, uint32_t mbarrierAddr, uint64_t b0);
+__device__ void
+__nv_ptx_builtin_ocg_write_async_shared_v2_b32(uint32_t dstAddr, uint32_t mbarrierAddr, uint32_t b0, uint32_t b1);
+__device__ void
+__nv_ptx_builtin_ocg_write_async_shared_v4_b32(uint32_t dstAddr,
+ uint32_t mbarrierAddr,
+ uint32_t b0,
+ uint32_t b1,
+ uint32_t b2,
+ uint32_t b3);
+}
+
+namespace utils {
+
+//////////////////////////////////////////////////////////////////////////////////////////////////
+//// Shuffle syncronization helpers
+template <typename T>
+inline __device__ T
+warp_shuffle_xor(const T& x, uint32_t idx) {
+ return __shfl_xor_sync(uint32_t(-1), x, idx);
+}
+
+template <>
+inline __device__ float2
+warp_shuffle_xor<float2>(const float2& x, uint32_t idx) {
+ return {warp_shuffle_xor(x.x, idx), warp_shuffle_xor(x.y, idx)};)KERNEL"
+ R"KERNEL(}
+
+template <typename T>
+inline __device__ T
+warp_shuffle_down(const T& x, uint32_t idx) {
+ return __shfl_down_sync(uint32_t(-1), x, idx);
+}
+
+template <>
+inline __device__ float2
+warp_shuffle_down<float2>(const float2& x, uint32_t idx) {
+ return {warp_shuffle_down(x.x, idx), warp_shuffle_down(x.y, idx)};
+}
+
+// This is a helper function to support __shfl_sync(float2)
+template <typename T>
+__device__ inline static T
+shfl_sync_helper(unsigned mask, T var, int srcLane) {
+ return __shfl_sync(mask, var, srcLane);
+}
+
+// specialize for float2
+template <>
+__device__ inline float2
+shfl_sync_helper<float2>(unsigned mask, float2 var, int srcLane) {
+ double ret = __shfl_sync(mask, *reinterpret_cast<double*>(&var), srcLane); // cast to double
+ return *reinterpret_cast<float2*>(&ret);
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////
+__device__ __forceinline__ void
+namedBarrierSync(int name, int numThreads) {
+ asm volatile("bar.sync %0, %1;" : : "r"(name), "r"(numThreads) : "memory");
+}
+
+} // namespace utils
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// Atomics
+static inline __device__ void
+atomicMaxFloat(float* addr, const float value) {
+ atomicMax(reinterpret_cast<int*>(addr), __float_as_int(value));
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// Warp reduction functions
+template <int GROUP_SIZE>
+static inline __device__ float
+warp_reduce_max(const float m, unsigned int mask = 0xFFFFFFFF) {
+ static constexpr int WARP_SIZE = 32;
+ static_assert(GROUP_SIZE > 0 && GROUP_SIZE <= WARP_SIZE, "group size must be less than or equal to warp size");
+
+ float max_val = m;
+#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000) && defined(__CUDA_ARCH_FEAT_SM100_ALL)
+ // Only enable the credux instruction for reduction on the full warp, as we saw perf regression for GROUP_SIZE < 32,
+ // where we need to iterate over #(WARP_SIZE/GROUP_SIZE) groups in the warp
+ if constexpr (GROUP_SIZE == WARP_SIZE) {
+ // For sm_100a arch, we can use redux.sync.op{.abs.}{.NaN}.f32 instruction to reduce the min/max value
+ // https://docs.nvidia.com/cuda/parallel-thread-execution/#parallel-synchronization-and-communication-instructions-redux-sync
+ asm volatile("redux.sync.max.f32 %0, %1, %2;" : "=f"(max_val) : "f"(m), "r"(mask));
+ return max_val;
+ }
+#endif
+#pragma unroll
+ for (int delta = GROUP_SIZE / 2; delta > 0; delta /= 2) {
+ const float other_m = __shfl_down_sync(mask, max_val, delta);
+ __builtin_assume(max_val >= 0);
+ __builtin_assume(other_m >= 0);
+ max_val = fmaxf(max_val, other_m);
+ }
+ return max_val;
+}
+
+template <int num_warps, typename compute_t>
+static inline __device__ compute_t
+reduce_max(const compute_t m, const int warpid) {
+ __shared__ float staging[num_warps];
+ constexpr int warp_size = 32;
+ const float my_max = m;
+ const float my_warp_max = warp_reduce_max<warp_size>(my_max);
+ if (threadIdx.x % 32 == 0) {
+ staging[warpid] = my_warp_max;
+ }
+ __syncthreads();
+ compute_t result = 0;
+ if (warpid == 0) {
+ const float my_max = threadIdx.x < num_warps ? staging[threadIdx.x] : 0;
+ result = warp_reduce_max<warp_size>(my_max);
+ }
+ return result;
+}
+
+template <int num_warps, typename compute_t>
+static inline __device__ compute_t
+reduce_max(const compute_t m, const int warpid, int tidx) {
+ __shared__ float staging[num_warps];
+ constexpr int warp_size = 32;
+ const float my_max = m;
+ const float my_warp_max = warp_reduce_max<warp_size>(my_max);
+ if (tidx % 32 == 0) {
+ staging[warpid] = my_warp_max;
+ }
+ utils::namedBarrierSync(1, num_warps * warp_size);
+ compute_t result = 0;
+ if (warpid == 0) {
+ const float my_max = tidx < num_warps ? staging[tidx] : 0;
+ result = warp_reduce_max<warp_size>(my_max);
+ }
+ return result;
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// Misc
+constexpr __device__ int32_t
+find_largest_divisor(int32_t n, int32_t divisor_upper_bound) {
+ if (n <= divisor_upper_bound) {
+ return n;
+ }
+ for (int32_t i = divisor_upper_bound; i >= 1; --i) {
+ if (n % i == 0) {
+ return i; // found the largest divisor
+ }
+ }
+ return divisor_upper_bound; // fallback
+}
+
+constexpr __device__ bool
+is_power_of_2(unsigned int n) {
+ return (n > 0) && ((n & (n - 1)) == 0);
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// Cooperative groups related
+//// !!!! Keep this block at the end of the file - start !!!!
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// Runtime parameters
+
+struct PersistentLnParamsBase {
+ // For Multi-CTA, number of different CTA groups; otherwise same as gridDim.x.
+ int ctas_per_col = 0;
+
+ // Input is interpreted as matrix and we normalize across columns.
+ int rows = 0;
+ int cols = 0;
+ int batchSize = 1; // For AdaLN
+ int seqLen = 1; // For AdaLN
+
+ // Common data pointers for forward and backward passes.
+ void *x = nullptr;
+ void *mu = nullptr;
+ void *rs = nullptr;
+ void *gamma = nullptr;
+
+ // Multi-CTA workspace in gmem.
+ void *workspace = nullptr;
+
+ // Multi-CTA sync barriers in gmem.
+ int *barrier = nullptr;
+
+ bool isRMSNorm = false;
+ bool noScale = false;
+ bool noBias = false;
+ bool isAdaLN = false;
+ bool isBatchFirst = true;
+};
+
+struct PersistentLnFwdParams : public PersistentLnParamsBase {
+ // Output of LN FWD.
+ void *z = nullptr;
+
+ void *beta = nullptr;
+ float epsilon = 0.f;
+
+ // FP8 support
+ bool fp8_out = false;
+ float *scale = nullptr;
+ float *scale_inv = nullptr;
+ float *amax = nullptr;
+
+ // Reuse z for row scaled output (or block scaled output if we use 2d1x1x)
+ void *scale_row = nullptr;
+ void *scale_col = nullptr; // only used in 1d2x2x
+ void *z_col = nullptr; // only used in 1d2x2x
+ void *z_math = nullptr; // only used when enabling the 1d2x2x colwise kernel
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// Inter-CTA synchronization
+template <uint32_t CTAS_PER_ROW>
+struct InterCTASync {
+ template <typename Params>
+ inline __device__
+ InterCTASync(Params &params, uint32_t bidm, uint32_t bidn, uint32_t tidx)
+ : phase_counter_(0),
+ b0_(params.barrier + bidm) // The barrier for this group of CTAs.
+ ,
+ b1_(params.barrier + bidm + params.ctas_per_col) // The barrier for this group of CTAs.
+ ,
+ tidx_(tidx) {
+ // BARRIERS ARE ASSUMED TO BE INITIALIZED TO 0!
+ }
+
+ inline __device__ void
+ spin_wait_(int *barrier, int step, int expected) {
+ asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(barrier), "r"(step));
+ for (int found = -1; found != expected;) {
+ asm volatile("ld.global.acquire.gpu.b32 %0, [%1];" : "=r"(found) : "l"(barrier));
+ }
+ }
+
+ inline __device__ void
+ sync(uint32_t threads_per_cta) {
+ // ALL THREADS MUST ENTER!
+
+ // We switch barrier every iteration.
+ int *barrier = phase_counter_ & 0x1 ? b1_ : b0_;
+ // We decrement every other iteration.
+ bool dec = phase_counter_ & 0x2;
+ int step = dec ? -1 : 1;
+ int expected = dec ? 0 : CTAS_PER_ROW;
+ // There are only 4 phases: up/down for b0/b1.
+ phase_counter_ = (phase_counter_ + 1) & 0x3;
+
+ if (0 == tidx_) {
+ spin_wait_(barrier, step, expected);
+ }
+
+ // CTA waits for thread 0
+ utils::namedBarrierSync(0, threads_per_cta);
+ }
+
+ int phase_counter_;
+ int *b0_;
+ int *b1_;
+ uint32_t tidx_;
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// LayerNorm Reduction and stats computation
+// NOTE: WHOLE_CTA means if we'll use one empty mbarrier for inter-CTA sync using cluster.
+// In the TMA LN engines it should be "true" since we're syncing the whole CTA with one empty mbarrier, while in the
+// APEX LN engines it should be "false" as there's one empty mbarrier per warp m (and therefore WARPS_M empty mbarriers
+// in total)
+template <typename T, uint32_t CTAS_PER_ROW, uint32_t WARPS_M, uint32_t WARPS_N, bool USE_CLUSTER, bool WHOLE_CTA>
+struct Reducer : public Reducer<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA> {
+ using InterCTASync = InterCTASync<CTAS_PER_ROW>;
+ using Base = Reducer<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>;
+ using Type = typename Base::Type;
+
+ enum { SMEM_BYTES = Base::SMEM_BYTES };
+
+ enum { WS_BARRIER_BYTES = 2 * sizeof(int) };
+ enum { WS_DATA_BYTES = WARPS_M * CTAS_PER_ROW * sizeof(T) };
+
+ // size of the barriers + temporary result per CTA (multiply with CTAS_PER_ROW to get total)
+ enum { WORKSPACE_BYTES_PER_GROUP = Base::WORKSPACE_BYTES_PER_GROUP + WS_BARRIER_BYTES + WS_DATA_BYTES };
+
+ template <typename Params>
+ inline __device__
+ Reducer(Params &params,
+ uint32_t bidm,
+ uint32_t bidn,
+ uint32_t warp_m,
+ uint32_t warp_n,
+ uint32_t tidx,
+ uint32_t lane,
+ void *smem,
+ uint64_t *smem_bar)
+ : Base(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar),
+ inter_cta_(params, bidm, bidn, tidx),
+ bidn_(bidn), // CTA id within the group.
+ warp_m_(warp_m),
+ w0_(static_cast<T *>(params.workspace) + (bidm * WARPS_M + warp_m) * CTAS_PER_ROW),
+ w1_(w0_ + params.ctas_per_col * WARPS_M * CTAS_PER_ROW),
+ smem_bar_(smem_bar),
+ parity_(0) {
+ // the first several elements are the barriers
+ smem_cga_ = reinterpret_cast<T *>(&smem_bar[WHOLE_CTA? 2: (WARPS_M + 1)]);
+ }
+
+ template <typename Op>
+ inline __device__ T
+ allreduce(T data, Op &op, int32_t warps_m) {
+ data = Base::reduce(data, op, warps_m);
+
+ if constexpr (USE_CLUSTER) {
+#if (__CUDA_ARCH__ >= 900) && (CUDART_VERSION >= 12080)
+ auto cluster = cooperative_groups::this_cluster();
+
+ // NOTE: right now only lane 0 has the valid value so that a intra-warp broadcast is required here.
+ // This issue is not in fwd (struct Stats) which does it earlier inside warp_chan_upd_dynamic().
+ data = utils::shfl_sync_helper(uint32_t(-1), data, 0);
+
+ // Broadcast local results to other CTAs inside the CGA
+ // Size of smem_cga_: [WARPS_M][CTAS_PER_ROW]
+ // Thread 0 sends to block 0, Thread 1 sends to block 1, etc...
+ if ((this->warp_n_ == 0) && (this->lane_ < CTAS_PER_ROW)) {
+ st_async_remote(&smem_cga_[warp_m_ * CTAS_PER_ROW + bidn_], data, this->lane_, &smem_bar_[WHOLE_CTA? 0: WARPS_M]);
+ }
+
+ // Leader thread arrives on local barrier to indicate expected tx count
+ // We can't use (threadIdx.x == 0) directly here because it won't work for TMA
+ if ((this->warp_n_ == 0) && (warp_m_ == 0) && (this->lane_ == 0)) {
+ // It's possible that not all warp_m are active here, therefore, we can't use WARPS_M directly
+ uint32_t expected_tx_count = sizeof(data) * CTAS_PER_ROW * warps_m;
+ utils::mbarrier_arrive_expect_tx_relaxed_cluster(&smem_bar_[WHOLE_CTA? 0: WARPS_M], expected_tx_count);
+ }
+
+ // Wait on local barrier
+ while (!utils::mbarrier_try_wait_parity_relaxed_cluster(&smem_bar_[WHOLE_CTA? 0: WARPS_M], parity_)) {}
+ utils::fence_acquire_smem(); // Ensure we can read local smem values that are released by barrier flip
+
+ T total = Zeros<T>::get();
+ if (this->lane_ < CTAS_PER_ROW) {
+ total = smem_cga_[warp_m_ * CTAS_PER_ROW + this->lane_];
+ }
+ utils::fence_release_smem(); // Ensure read of buffer remains ordered before smem_bar.arrive.relaxed
+)KERNEL"
+ R"KERNEL( // Signal barrier is empty.
+ // Each thread must arrive on all the barriers (like an arrive broadcast).
+ // NOTE: here we only let each warp m arrive on the remote barriers of the same warp m (i.e. the same row),
+ // because if we have one empty barrier for the entire CTA, there's a difficulty how to init the count of
+ // the barrier (since some warps could be disabled here). The downside is we'll need a __syncthreads() here,
+ // which doesn't have obvious perf impact though.
+ // TODO: we could probably have one full bar per row (same as the empty bar) to get rid of the CTA sync,
+ // while the downside is more smem (mbarriers) will be needed.
+ if (!WHOLE_CTA) {
+ utils::namedBarrierSync(0, warps_m * WARPS_N * 32);
+ }
+ for (int other_block_rank = 0; other_block_rank < CTAS_PER_ROW; ++other_block_rank) {
+ uint64_t *remote_bar_empty = cluster.map_shared_rank(&smem_bar_[WHOLE_CTA? 1: warp_m_], other_block_rank);
+ utils::mbarrier_arrive_relaxed_cluster(remote_bar_empty);
+ }
+
+ total = Reducer<T, 1, 1, 1, USE_CLUSTER, WHOLE_CTA>::allreduce_(total, op);
+
+ // Wait for remote buffer to be writable again by waiting on local barrier:
+ while (!utils::mbarrier_try_wait_parity_relaxed_cluster(&smem_bar_[WHOLE_CTA? 1: warp_m_], parity_)) {}
+ utils::fence_acquire_smem(); // Order wrt st_async_remote
+
+ // Flip parity bit for next iteration
+ parity_ ^= 1;
+
+ return total;
+#else
+ static_assert(true, "Cluster enabled on host side but not available on device");
+#endif
+ } else {
+ // We switch workspace every iteration.
+ T *workspace = inter_cta_.phase_counter_ & 0x1 ? w1_ : w0_;
+
+ // Warp leaders 0 hold the CTA-local results.
+ if (this->warp_n_ == 0 && this->lane_ == 0) {
+ workspace[bidn_] = data;
+ }
+
+ // We need to check for the case where we are using CTA > 1 and WARP_M > 1 and N == 1
+ // Because in this case we cannot rely on the __syncThreads in template<typename T, uint32_t WARPS_M,
+ // uint32_t WARPS_N>::compute (because we will use the specialized template <typename T, uint32_t
+ // WARPS_M>::compute which does not have a sync)
+ if (CTAS_PER_ROW > 1 && WARPS_M > 1 && WARPS_N == 1) {
+ utils::namedBarrierSync(0, warps_m * WARPS_N * 32);
+ }
+
+ // Wait for all CTAS_PER_ROW CTAS in the group to have written their result.
+ inter_cta_.sync(warps_m * WARPS_N * 32);
+
+ T total = Zeros<T>::get();
+
+ // Every warp does the final reduction locally.
+ if constexpr (CTAS_PER_ROW <= THREADS_PER_WARP) {
+ if (this->lane_ < CTAS_PER_ROW) {
+ total = workspace[this->lane_];
+ }
+ } else {
+ static constexpr int32_t LOOP_PER_THREAD = (CTAS_PER_ROW + THREADS_PER_WARP - 1) / THREADS_PER_WARP;
+
+ // Collect stats for the current lane from ctas (#bidn % THREADS_PER_WARP == #lane) and then do the
+ // intra-warp reduction
+ total = workspace[this->lane_];
+#pragma unroll
+ for (int32_t loop_in_thread = 1; loop_in_thread < LOOP_PER_THREAD; ++loop_in_thread) {
+ const int32_t lane_in_loop = this->lane_ + loop_in_thread * THREADS_PER_WARP;
+ if (lane_in_loop < CTAS_PER_ROW) {
+ total = op(total, workspace[lane_in_loop]);
+ }
+ }
+ }
+
+ total = Reducer<T, 1, 1, 1, false, false>::allreduce_(total, op);
+
+ return total;
+ }
+ }
+
+ InterCTASync inter_cta_;
+ T *w0_;
+ T *w1_;
+ int bidn_;
+ int warp_m_;
+
+ private:
+ T *smem_cga_;
+ uint64_t *smem_bar_;
+ int parity_;
+};
+
+template <typename T, uint32_t WARPS_M, bool USE_CLUSTER, bool WHOLE_CTA>
+struct Reducer<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA> {
+ using Type = T;
+ enum { SMEM_BYTES = 0 };
+ enum { WORKSPACE_BYTES_PER_GROUP = 0 };
+ enum { THREADS_PER_WARP = 32 };
+
+ template <typename Params>
+ inline __device__
+ Reducer(Params &params,
+ uint32_t bidm,
+ uint32_t bidn,
+ uint32_t warp_m,
+ uint32_t warp_n,
+ uint32_t /*tidx*/,
+ uint32_t lane,
+ void *smem,
+ uint64_t *smem_bar)
+ : warp_n_(warp_n), lane_(lane) {}
+
+ template <typename Op>
+ static inline __device__ T
+ allreduce_(T data, Op &op) {
+#pragma unroll
+ for (int it = 1; it < THREADS_PER_WARP; it *= 2) {
+ data = op(data, utils::warp_shuffle_xor(data, it));
+ }
+ return data;
+ }
+
+ template <typename Op>
+ inline __device__ T
+ allreduce(T data, Op &op, int32_t warps_m) {
+ return allreduce_(data, op);
+ }
+
+ protected:
+ template <typename Op>
+ inline __device__ T
+ reduce(T data, Op &op, int32_t warps_m) {
+// only lane 0 holds the result!
+#pragma unroll
+ for (int it = THREADS_PER_WARP / 2; it > 0; it /= 2) {
+ data = op(data, utils::warp_shuffle_down(data, it));
+ }
+ return data;
+ }
+
+ public:
+ int warp_n_;
+ int lane_;
+};
+
+template <typename T, uint32_t WARPS_M, uint32_t WARPS_N, bool USE_CLUSTER, bool WHOLE_CTA>
+struct Reducer<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA> : public Reducer<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA> {
+ using Base = Reducer<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA>;
+ using Type = T;
+
+ enum { SMEM_BYTES = Base::SMEM_BYTES + WARPS_M * WARPS_N * sizeof(T) * 2 };
+ enum { WORKSPACE_BYTES_PER_GROUP = 0 };
+ enum { THREADS_PER_WARP = 32 };
+
+ template <typename Params>
+ inline __device__
+ Reducer(Params &params,
+ uint32_t bidm,
+ uint32_t bidn,
+ uint32_t warp_m,
+ uint32_t warp_n,
+ uint32_t tidx,
+ uint32_t lane,
+ void *smem,
+ uint64_t *smem_bar)
+ : Base(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar), use0_(true) {
+ smem0_ = &static_cast<T *>(smem)[warp_m * WARPS_N];
+ smem1_ = smem0_ + WARPS_M * WARPS_N;
+ }
+
+ template <typename Op>
+ inline __device__ T
+ allreduce(T data, Op &op, int32_t warps_m) {
+ T *smem = use0_ ? smem0_ : smem1_;
+ use0_ = !use0_;
+ data = Base::reduce(data, op, warps_m);
+ if (this->lane_ == 0) {
+ smem[this->warp_n_] = data;
+ }
+ // The number matters here. 0 will only use one barrier per block. "1" will use 2 according to ncu.
+ // We should use 0 unless it is absolutely necessary to use seperate barriers.
+ utils::namedBarrierSync(0, warps_m * WARPS_N * 32);
+ T out = Zeros<T>::get();
+#pragma unroll
+ for (int it = 0; it < WARPS_N; it++) {
+ out = op(out, smem[it]);
+ }
+ return out;
+ }
+
+ protected:
+ template <typename Op>
+ inline __device__ T
+ reduce(T data, Op &op, int32_t warps_m) {
+ T *smem = use0_ ? smem0_ : smem1_;
+ use0_ = !use0_;
+ // only intra-CTA group leader holds the result!
+ data = Base::reduce(data, op, warps_m);
+ if (this->lane_ == 0) {
+ smem[this->warp_n_] = data;
+ }
+ utils::namedBarrierSync(0, warps_m * WARPS_N * 32);
+ T out = Zeros<T>::get();
+ if (this->warp_n_ == 0 && this->lane_ == 0) {
+#pragma unroll
+ for (int it = 0; it < WARPS_N; it++) {
+ out = op(out, smem[it]);
+ }
+ }
+ return out;
+ }
+
+ private:
+ T *smem0_;
+ T *smem1_;
+ bool use0_;
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+template <bool isRMSNorm, typename T, bool handleNan = false>
+inline __device__ void
+update_norm_stats(T &m_a, T &m2_a, T &n_a, T m_b, T m2_b, T n_b) {
+ const T n_ab = n_a + n_b;
+
+ if constexpr (!isRMSNorm) {
+ const T rn_ab = (handleNan && (n_ab == Zeros<T>::get())) ? Zeros<T>::get() : (1.f / n_ab);
+ const T delta = m_a - m_b;
+ const float m2_ab = m2_a + m2_b + delta * delta * n_a * n_b * rn_ab;
+ const float m_ab = (n_a * m_a + n_b * m_b) * rn_ab;
+ n_a = n_ab;
+ m_a = m_ab;
+ m2_a = m2_ab;
+ } else {
+ const float m2_ab = m2_a + m2_b;
+ n_a = n_ab;
+ m_a = Zeros<T>::get();
+ m2_a = m2_ab;
+ }
+}
+
+template <bool isRMSNorm, typename T, bool handleNan = false>
+inline __device__ void
+warp_chan_upd_dynamic(T &m_a, T &m2_a, T &n_a, int num_active) {
+ // Assume at least leftmost is valid and init: step = next_pow2(num_active) / 2 (might get NaN otherwise)
+ int highest_bit_set = (8 * sizeof(num_active)) - __clz(num_active - 1);
+
+#pragma unroll
+ for (int step = (1 << (highest_bit_set - 1)); step > 0; step /= 2) {
+ // Exchange
+ T n_b = utils::warp_shuffle_down(n_a, step);
+ T m_b = (!isRMSNorm ? utils::warp_shuffle_down(m_a, step) : Zeros<T>::get());
+ T m2_b = utils::warp_shuffle_down(m2_a, step);
+ update_norm_stats<isRMSNorm, T, handleNan>(m_a, m2_a, n_a, m_b, m2_b, n_b);
+ }
+ // Intra-warp broadcast (only lane 0 has valid stats).
+ m_a = __shfl_sync(uint32_t(-1), m_a, 0);
+ m2_a = __shfl_sync(uint32_t(-1), m2_a, 0);
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+// NOTE: WHOLE_CTA means if we'll use one empty mbarrier for inter-CTA sync using cluster.
+// In the TMA LN engines it should be "true" since we're syncing the whole CTA with one empty mbarrier, while in the
+// APEX LN engines it should be "false" as there's one empty mbarrier per warp m (and therefore WARPS_M empty mbarriers
+// in total)
+template <typename T, uint32_t CTAS_PER_ROW, uint32_t WARPS_M, uint32_t WARPS_N, bool USE_CLUSTER, bool WHOLE_CTA>
+struct Stats {
+ // This could be done generically with the Reducer. But then we would have to exchange 3 instead of 2 fields.
+
+ using InterCTASync = InterCTASync<CTAS_PER_ROW>;
+ using BlockStats = Stats<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>;
+ using stats_t = typename BlockStats::stats_t;
+
+ enum { SMEM_BYTES = BlockStats::SMEM_BYTES };
+
+ template <typename Params>
+ inline __device__
+ Stats(Params &params,
+ uint32_t bidm,
+ uint32_t bidn,
+ uint32_t warp_m,
+ uint32_t warp_n,
+ uint32_t tidx,
+ uint32_t lane,
+ void *smem,
+ uint64_t *smem_bar)
+ : inter_cta_(params, bidm, bidn, tidx),
+ block_stats_(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar),
+ bidn_(bidn), // CTA id within the group.
+ w0_(static_cast<stats_t *>(params.workspace) + (bidm * WARPS_M + warp_m) * CTAS_PER_ROW),
+ w1_(w0_ + params.ctas_per_col * WARPS_M * CTAS_PER_ROW),
+ warp_n_(warp_n),
+ warp_m_(warp_m),
+ lane_(lane),
+ smem_bar_(smem_bar),
+ parity_(0) {
+ // the first several elements are the barriers
+ smem_cga_ = reinterpret_cast<stats_t *>(&smem_bar[WHOLE_CTA? 2: (WARPS_M + 1)]);
+ }
+
+ template <bool isRMSNorm, uint32_t LDGS, uint32_t NUM_ELTS>
+ inline __device__ stats_t
+ compute(const T (&elts)[LDGS * NUM_ELTS], const T rn, int32_t warps_m) {
+ static constexpr uint32_t N = LDGS * NUM_ELTS;
+ constexpr T ELTS_PER_ROW_PER_CTA = N * WARPS_N * THREADS_PER_WARP;
+ // TODO rn is not really needed here..
+ constexpr T block_rn = 1.f / T(ELTS_PER_ROW_PER_CTA);
+ stats_t block_stats = block_stats_.template compute<isRMSNorm, LDGS, NUM_ELTS>(elts, block_rn, warps_m);
+
+ if constexpr (USE_CLUSTER) {
+#if (__CUDA_ARCH__ >= 900) && (CUDART_VERSION >= 12080)
+ auto cluster = cooperative_groups::this_cluster();
+
+ // Broadcast local results to other CTAs inside the CGA
+ // Size of smem_cga_: [WARPS_M][CTAS_PER_ROW]
+ // Thread 0 sends to block 0, Thread 1 sends to block 1, etc...
+ if ((warp_n_ == 0) && (lane_ < CTAS_PER_ROW)) {
+ st_async_remote(&smem_cga_[warp_m_ * CTAS_PER_ROW + bidn_], block_stats, lane_, &smem_bar_[WHOLE_CTA? 0: WARPS_M]);
+ }
+
+ // Leader thread arrives on local barrier to indicate expected tx count
+ // We can't use (threadIdx.x == 0) directly here because it won't work for TMA
+ if ((warp_n_ == 0) && (warp_m_ == 0) && (lane_ == 0)) {
+ // It's possible that not all warp_m are active here, therefore, we can't use WARPS_M directly
+ uint32_t expected_tx_count = sizeof(block_stats) * CTAS_PER_ROW * warps_m;
+ utils::mbarrier_arrive_expect_tx_relaxed_cluster(&smem_bar_[WHOLE_CTA? 0: WARPS_M], expected_tx_count);
+ }
+
+ // Wait on local barrier
+ while (!utils::mbarrier_try_wait_parity_relaxed_cluster(&smem_bar_[WHOLE_CTA? 0: WARPS_M], parity_)) {}
+ utils::fence_acquire_smem(); // Ensure we can read local smem values that are released by barrier flip
+
+ T n = Zeros<T>::get();
+ T m = Zeros<T>::get();
+ T m2 = Zeros<T>::get();
+ if (lane_ < CTAS_PER_ROW) {
+ stats_t result = smem_cga_[warp_m_ * CTAS_PER_ROW + lane_];
+ n = ELTS_PER_ROW_PER_CTA;
+ m = Get<0>::of<stats_t, T>(result); // should be 0 for RMSNorm
+ m2 = Get<1>::of<stats_t, T>(result);
+ }
+ utils::fence_release_smem(); // Ensure read of buffer remains ordered before smem_bar.arrive.relaxed
+)KERNEL"
+ R"KERNEL( // Signal barrier is empty.
+ // Each thread must arrive on all the barriers (like an arrive broadcast).
+ // NOTE: here we only let each warp m arrive on the remote barriers of the same warp m (i.e. the same row),
+ // because if we have one empty barrier for the entire CTA, there's a difficulty how to init the count of
+ // the barrier (since some warps could be disabled here). The downside is we'll need a __syncthreads() here,
+ // which doesn't have obvious perf impact though.
+ // TODO: we could probably have one full bar per row (same as the empty bar) to get rid of the CTA sync,
+ // while the downside is more smem (mbarriers) will be needed.
+ if (!WHOLE_CTA) {
+ utils::namedBarrierSync(0, warps_m * WARPS_N * 32);
+ }
+ for (int other_block_rank = 0; other_block_rank < CTAS_PER_ROW; ++other_block_rank) {
+ uint64_t *remote_bar_empty = cluster.map_shared_rank(&smem_bar_[WHOLE_CTA? 1: warp_m_], other_block_rank);
+ utils::mbarrier_arrive_relaxed_cluster(remote_bar_empty);
+ }
+
+ warp_chan_upd_dynamic<isRMSNorm, T, !is_power_of_2(CTAS_PER_ROW)>(m, m2, n, CTAS_PER_ROW);
+
+ // Wait for remote buffer to be writable again by waiting on local barrier:
+ while (!utils::mbarrier_try_wait_parity_relaxed_cluster(&smem_bar_[WHOLE_CTA? 1: warp_m_], parity_)) {}
+ utils::fence_acquire_smem(); // Order wrt st_async_remote
+
+ // Flip parity bit for next iteration
+ parity_ ^= 1;
+
+ return {m, m2};
+#else
+ static_assert(true, "Cluster enabled on host side but not available on device");
+#endif
+ } else {
+ // We switch workspace every iteration.
+ stats_t *workspace = inter_cta_.phase_counter_ & 0x1 ? w1_ : w0_;
+
+ // Warp leaders 0 hold the CTA-local results.
+ if (warp_n_ == 0 && lane_ == 0) {
+ workspace[bidn_] = block_stats;
+ }
+
+ // We need to check for the case where we are using CTA > 1 and WARP_M > 1 and N == 1
+ // Because in this case we cannot rely on the __syncThreads in template<typename T, uint32_t WARPS_M,
+ // uint32_t WARPS_N>::compute (because we will use the specialized template <typename T, uint32_t
+ // WARPS_M>::compute which does not have a sync)
+ // Bug 5221388: For WARPS_M > 1 and WARPS_N > 1, we also need the sync here, otherwise the stats received in
+ // `workspace[lane_]` may be NaN (as if some stats from the other CTAs are not initialized).
+ // Reason unknown yet and tracked in CL-16775.
+ if (CTAS_PER_ROW > 1 && WARPS_M > 1) {
+ utils::namedBarrierSync(0, warps_m * WARPS_N * 32);
+ }
+
+ // Wait for all CTAS_PER_ROW CTAS in the group to have written their result.
+ inter_cta_.sync(warps_m * WARPS_N * 32);
+
+ T n = Zeros<T>::get();
+ T m = Zeros<T>::get();
+ T m2 = Zeros<T>::get();
+
+ // Every warp does the final reduction locally.
+ if constexpr (CTAS_PER_ROW <= THREADS_PER_WARP) {
+ if (lane_ < CTAS_PER_ROW) {
+ stats_t result = workspace[lane_];
+ n = ELTS_PER_ROW_PER_CTA;
+ m = Get<0>::of<stats_t, T>(result); // should be 0 for RMSNorm
+ m2 = Get<1>::of<stats_t, T>(result);
+ }
+ warp_chan_upd_dynamic<isRMSNorm, T, !is_power_of_2(CTAS_PER_ROW)>(m, m2, n, CTAS_PER_ROW);
+ } else {
+ static constexpr int32_t LOOP_PER_THREAD = (CTAS_PER_ROW + THREADS_PER_WARP - 1) / THREADS_PER_WARP;
+
+ stats_t curr = workspace[lane_];
+ n = ELTS_PER_ROW_PER_CTA;
+ m = Get<0>::of<stats_t, T>(curr); // should be 0 for RMSNorm
+ m2 = Get<1>::of<stats_t, T>(curr);
+
+ // Collect stats for the current lane from ctas (#bidn % THREADS_PER_WARP == #lane) and then do the
+ // intra-warp reduction
+#pragma unroll
+ for (int32_t loop_in_thread = 1; loop_in_thread < LOOP_PER_THREAD; ++loop_in_thread) {
+ const int32_t lane_in_loop = lane_ + loop_in_thread * THREADS_PER_WARP;
+ if (lane_in_loop < CTAS_PER_ROW) {
+ curr = workspace[lane_in_loop];
+ T m_b = Get<0>::of<stats_t, T>(curr);
+ T m2_b = Get<1>::of<stats_t, T>(curr);
+ update_norm_stats<isRMSNorm>(m, m2, n, m_b, m2_b, ELTS_PER_ROW_PER_CTA);
+ }
+ }
+ warp_chan_upd_dynamic<isRMSNorm>(m, m2, n, THREADS_PER_WARP);
+ }
+
+ return {m, m2};
+ }
+ }
+
+ InterCTASync inter_cta_;
+ BlockStats block_stats_;
+
+ stats_t *w0_;
+ stats_t *w1_;
+ int bidn_;
+ int warp_n_;
+ int warp_m_;
+ int lane_;
+
+ private:
+ stats_t *smem_cga_;
+ uint64_t *smem_bar_;
+ int parity_;
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+template <typename T, uint32_t WARPS_M, uint32_t WARPS_N, bool USE_CLUSTER, bool WHOLE_CTA>
+struct Stats<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA> {
+ using WarpStats = Stats<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA>;
+ using stats_t = typename WarpStats::stats_t;
+
+ enum { SMEM_BYTES = WARPS_M * WARPS_N * sizeof(stats_t) * 2 };
+
+ template <typename Params>
+ inline __device__
+ Stats(Params &params,
+ uint32_t bidm,
+ uint32_t bidn,
+ uint32_t warp_m,
+ uint32_t warp_n,
+ uint32_t tidx,
+ uint32_t lane,
+ void *smem,
+ uint64_t *smem_bar)
+ : warp_stats_(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar), use0_(true) {
+ smem0_ = static_cast<stats_t *>(smem) + warp_m * WARPS_N;
+ smem1_ = smem0_ + WARPS_M * WARPS_N;
+ }
+
+ template <bool isRMSNorm, uint32_t LDGS, uint32_t NUM_ELTS>
+ inline __device__ stats_t
+ compute(const T (&elts)[LDGS * NUM_ELTS], const T rn, int32_t warps_m) {
+ stats_t *smem = use0_ ? smem0_ : smem1_;
+ use0_ = !use0_;
+ // Compute warp local for all WARPS_N
+ static constexpr uint32_t N = LDGS * NUM_ELTS;
+ constexpr T warp_rn = 1.f / T(N * THREADS_PER_WARP);
+ stats_t warp_stats = warp_stats_.template compute<isRMSNorm, LDGS, NUM_ELTS>(elts, warp_rn, warps_m);
+
+ // Each warp warp leader stores its stats
+ const auto warp_n = warp_stats_.reducer_.warp_n_;
+ const auto lane = warp_stats_.reducer_.lane_;
+ if (lane == 0) {
+ smem[warp_n] = warp_stats;
+ }
+ utils::namedBarrierSync(0, warps_m * WARPS_N * 32);
+
+ T n = Zeros<T>::get();
+ T m = Zeros<T>::get();
+ T m2 = Zeros<T>::get();
+
+ if (lane < WARPS_N) {
+ stats_t result = smem[lane];
+ n = N * THREADS_PER_WARP;
+ m = Get<0>::of<stats_t, T>(result); // should be 0 for RMSNorm
+ m2 = Get<1>::of<stats_t, T>(result);
+ }
+
+ warp_chan_upd_dynamic<isRMSNorm>(m, m2, n, WARPS_N);
+
+ return {m, m2};
+ }
+
+ WarpStats warp_stats_;
+ stats_t *smem0_;
+ stats_t *smem1_;
+ bool use0_;
+};
+
+template <typename T, uint32_t WARPS_M, bool USE_CLUSTER, bool WHOLE_CTA>
+struct Stats<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA> {
+ using stats_t = typename TypeToVec2<T>::Type;
+ // The simple Warp reducer.
+ using Reducer = Reducer<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA>;
+
+ enum { SMEM_BYTES = 0 };
+
+ template <typename Params>
+ inline __device__
+ Stats(Params &params,
+ uint32_t bidm,
+ uint32_t bidn,
+ uint32_t warp_m,
+ uint32_t warp_n,
+ uint32_t tidx,
+ uint32_t lane,
+ void *smem,
+ uint64_t *smem_bar)
+ : reducer_(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar) {}
+
+ template <bool isRMSNorm, uint32_t LDGS, uint32_t NUM_ELTS>
+ inline __device__ stats_t
+ compute(const T (&elts)[LDGS * NUM_ELTS], const T rn, int32_t warps_m) {
+ static constexpr uint32_t N = LDGS * NUM_ELTS;
+ auto sum = Sum<T>();
+
+ T m = Zeros<T>::get();
+ if (!isRMSNorm) {
+// CL-14115: The unroll factor 128 for LDGS was chosen based on the compilation/perf results for APEX LN_fwd engines
+#pragma unroll(128 * NUM_ELTS)
+ for (int it = 0; it < N; it++) {
+ m += elts[it];
+ }
+ m = reducer_.allreduce(m, sum, warps_m) * rn;
+ }
+
+ T m2 = Zeros<T>::get();
+#pragma unroll(128 * NUM_ELTS)
+ for (int it = 0; it < N; it++) {
+ T diff = (elts[it] - m);
+ m2 = __fmaf_ieee_rn(diff, diff, m2);
+ }
+ m2 = reducer_.allreduce(m2, sum, warps_m);
+
+ return {m, m2};
+ }
+
+ Reducer reducer_;
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//// Fast division helpers
+
+// Count leading zeros - start from most significant bit.
+static int
+clz(int32_t x) {
+ for (int32_t i = 31; i >= 0; --i)
+ if (((1 << i) & x) != 0) {
+ return 31 - i;
+ }
+ return 32;
+}
+
+static int32_t
+find_log_2(int32_t x, bool round_up = false) {
+ int32_t a = 31 - clz(x);
+ if (round_up) {
+ a += !(0 == (x & (x - 1)));
+ }
+ return a;
+}
+
+static void
+find_divisor(int32_t denom, uint32_t &mul_coeff, uint32_t &shift_coeff) {
+ if (denom == 0) {
+ return;
+ }
+ if (denom == 1) {
+ // if dividing by 1, reduced math doesn't work because mul_coeff would
+ // need to be 2^32, which doesn't fit into unsigned int. the div()
+ // routine handles this special case separately.
+ mul_coeff = 0;
+ shift_coeff = 0;
+ return;
+ }
+ // To express the division N/D in terms of a multiplication, what we first
+ // imagine is simply N*(1/D). However, 1/D will always evaluate to 0 (for D>1),
+ // so we need another way. There's nothing that says we have to use exactly
+ // the fraction 1/D; instead it could be any X/Y that reduces to 1/D (i.e.,
+ // Y=X*D), or at least to "close enough" to it. If we pick Y that is a power
+ // of two, then the N*(X/Y) can be N*X followed by a right-shift by some amount.
+ // The power of two we should pick should be at least 2^32, because in the
+ // div() routine we'll use umulhi(), which returns only the upper 32 bits --
+ // this being equivalent to a right-shift by 32. But we might want a higher
+ // power of two for better accuracy depending on the magnitude of the denominator.
+ // Once we've picked Y, then X [our mul_coeff value] is simply Y/D, rounding up,
+ // and we save shift_coeff as whatever further shift we have to do beyond
+ // what the umulhi() implies.
+ uint32_t p = 31 + find_log_2(denom, true);
+ uint32_t m = ((1ull << p) + static_cast<uint32_t>(denom - 1)) / static_cast<uint32_t>(denom);
+ mul_coeff = m;
+ shift_coeff = p - 32;
+}
+
+__device__ __forceinline__ uint32_t
+umulhi(uint32_t x, uint32_t y) {
+#if defined(__CUDA_ARCH__)
+ return __umulhi(x, y);
+#else
+ uint64_t z = static_cast<uint64_t>(x) * y;
+ return static_cast<uint32_t>(z >> 32);
+#endif
+}
+
+class reduced_divisor {
+ public:
+ reduced_divisor() {}
+ __forceinline__
+ reduced_divisor(int32_t _y)
+ : y(_y) {
+ mul_coeff = 0U;
+ shift_coeff = 0U;
+ find_divisor(y, mul_coeff, shift_coeff);
+ }
+ __device__ __forceinline__
+ reduced_divisor(uint32_t _mul_coeff, uint32_t _shift_coeff, int32_t _y)
+ : mul_coeff(_mul_coeff), shift_coeff(_shift_coeff), y(_y) {}
+ __device__ __forceinline__ int32_t
+ div(int32_t x) const {
+ // if dividing by 1, then find_divisor wouldn't have worked because
+ // mul_coeff would have had to be 2^32, which can't be represented,
+ // so we have to special case that one.
+ return (y != 1) ? umulhi(static_cast<uint32_t>(x), mul_coeff) >> shift_coeff : x;
+ }
+ __device__ __forceinline__ int32_t
+ mod(int32_t x) const {
+ return x - (div(x) * y);
+ }
+ __device__ __forceinline__ void
+ divmod(int32_t x, int32_t &q, int32_t &mod) const {
+ q = div(x);
+ mod = x - (q * y);
+ }
+ __device__ __forceinline__ int32_t
+ get() const {
+ return y;
+ }
+
+ protected:
+ uint32_t mul_coeff;
+ uint32_t shift_coeff;
+ int32_t y;
+};
+
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+template <uint32_t HIDDEN_SIZE_,
+ typename weight_t_,
+ typename input_t_,
+ typename output_t_,
+ typename compute_t_,
+ typename index_t_,
+ uint32_t THREADS_PER_CTA_>
+struct Kernel_traits_base {
+ using weight_t = weight_t_;
+ using input_t = input_t_;
+ using output_t = output_t_;
+ using compute_t = compute_t_;
+ using index_t = index_t_;
+
+ enum { HIDDEN_SIZE = HIDDEN_SIZE_ };
+ enum { THREADS_PER_CTA = THREADS_PER_CTA_ };
+ enum { THREADS_PER_WARP = 32 };
+};)KERNEL"
+ R"KERNEL(
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+template <typename weight_t_,
+ typename input_t_,
+ typename output_t_,
+ typename compute_t_,
+ typename norm_output_t_,
+ typename index_t_,
+ uint32_t HIDDEN_SIZE_,
+ uint32_t BATCH_SIZE_,
+ uint32_t CTAS_PER_ROW_,
+ uint32_t WARPS_M_,
+ uint32_t WARPS_N_,
+ uint32_t BYTES_PER_LDG_ = 16,
+ bool isRMSNorm_ = false,
+ bool isAdaLN_ = false,
+ bool isBatchFirst_ = true,
+ bool hasGamma_ = true,
+ bool hasBeta_ = true,
+ bool useGammaSmem_ = true, // for FWD kernels it denotes the use of shmem for both gamma and beta
+ bool useCluster_ = false,
+ bool wholeCTA_ = false,
+ uint32_t ROWS_PER_WARP_ = 1,
+ typename Base = Kernel_traits_base<HIDDEN_SIZE_,
+ weight_t_,
+ input_t_,
+ output_t_,
+ compute_t_,
+ index_t_,
+ WARPS_M_ * WARPS_N_ * THREADS_PER_WARP> >
+struct Kernel_traits : public Base {
+ using input_t = typename Base::input_t;
+ using weight_t = typename Base::weight_t;
+ using compute_t = typename Base::compute_t;
+ using output_t = typename Base::output_t;
+ using index_t = typename Base::index_t;
+ using norm_output_t = norm_output_t_;
+ enum { isRMSNorm = isRMSNorm_ };
+ enum { isAdaLN = isAdaLN_ };
+ enum { isBatchFirst = isBatchFirst_ };
+ enum { hasGamma = hasGamma_ };
+ enum { hasBeta = hasBeta_ };
+ enum { CTAS_PER_ROW = CTAS_PER_ROW_ };
+ enum { WARPS_M = WARPS_M_ };
+ enum { WARPS_N = WARPS_N_ };
+ enum { COLS = HIDDEN_SIZE_ };
+ enum { HIDDEN_SIZE = HIDDEN_SIZE_ };
+ enum { BATCH_SIZE = BATCH_SIZE_ };
+ enum { BYTES_PER_LDG = BYTES_PER_LDG_ };
+ enum { NUM_ELTS = BYTES_PER_LDG / sizeof(input_t) };
+ enum { USE_GAMMA_SMEM = useGammaSmem_ };
+ enum { USE_CLUSTER = useCluster_ };
+ enum { WHOLE_CTA = wholeCTA_ };
+ enum { THREADS_PER_ROW = WARPS_N * THREADS_PER_WARP };
+ enum { THREADS_PER_CTA = WARPS_M * THREADS_PER_ROW };
+ enum { ROWS_PER_WARP = ROWS_PER_WARP_ };
+ enum { ROWS_PER_CTA = WARPS_M * ROWS_PER_WARP };
+
+ enum { BYTES_PER_ROW = COLS * sizeof(input_t) };
+ enum { BYTES_PER_ROW_PER_CTA = THREADS_PER_ROW * BYTES_PER_LDG };
+ // Multi-row per CTA not supported for multi-CTA => no smem for WGRAD needed
+ enum { SMEM_BYTES_WGRAD = ROWS_PER_CTA == 1 ? 0 : BATCH_SIZE * ROWS_PER_CTA * COLS * sizeof(compute_t) };
+
+ using reduce_t = typename TypeToVec2<compute_t>::Type;
+ using RMSReducer = Reducer<compute_t, CTAS_PER_ROW, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>;
+ using Reducer = Reducer<reduce_t, CTAS_PER_ROW, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>;
+
+ enum { SMEM_BYTES_DGRAD = Reducer::SMEM_BYTES };
+ enum { SMEM_BYTES = SMEM_BYTES_DGRAD + SMEM_BYTES_WGRAD };
+
+ using Ivec = Vec<input_t, NUM_ELTS>;
+ using Ovec = Vec<output_t, NUM_ELTS>;
+ using Wvec = Vec<weight_t, NUM_ELTS>;
+ using Cvec = Vec<compute_t, NUM_ELTS>;
+ using NormOvec = Vec<norm_output_t, NUM_ELTS>;
+ enum { ELTS_PER_LDG = BYTES_PER_LDG / sizeof(input_t) };
+
+ // Assume that each thread can handle the same number of elements in the output and weights as in the input.
+ // The number of columns fetched per load from input: one per thread.
+ enum { VEC_COLS_PER_LDG = CTAS_PER_ROW * THREADS_PER_ROW };
+ // The total number of vectorized loads/stores per hidden vector.
+ enum { VEC_COLS = COLS / ELTS_PER_LDG };
+ // The number of loads per thread for the input.
+ enum { LDGS = VEC_COLS / VEC_COLS_PER_LDG };
+
+ using Stats = Stats<compute_t, CTAS_PER_ROW, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>;
+ enum { SMEM_BYTES_FWD = Stats::SMEM_BYTES };
+};
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+constexpr float CUDNN_FLT_MIN = 1.17549435082228750796873653722224568e-38F; // Minimum positive normalized float value
+/**
+ * Base class to provide common block scaling utilities, private to `BlockScaleHelper`
+ */
+template <typename Cvec, typename Ovec, int32_t BlockSize>
+class BlockScaleHelperBase;
+
+/**
+ * Base class to provide common block scaling utilities, for nvfp4
+ */
+template <typename Cvec, typename Ovec>
+class BlockScaleHelperBase<Cvec, Ovec, 16> {
+ public:
+ using scale_t = nv_fp8_e4m3;
+
+ protected:
+ using compute_t = typename Cvec::Elt_type;
+ using output_t = typename Ovec::Elt_type;
+
+ using index_t = uint32_t;
+
+ static constexpr int32_t THREADS_PER_WARP = 32;
+ static constexpr int32_t BLOCK_SIZE = 16;
+ static constexpr int32_t NUM_ELTS = sizeof(Cvec) / sizeof(compute_t);
+ static constexpr int32_t GROUP_SIZE = BLOCK_SIZE / NUM_ELTS;
+ static constexpr int32_t SF_COUNT = THREADS_PER_WARP / GROUP_SIZE;
+
+ static __device__ compute_t
+ scale(const compute_t value) {
+ constexpr compute_t nvfp4_max = 6.0f;
+ compute_t result = value / nvfp4_max;
+ // Clamp to CUDNN_FLT_MIN to match reference implementation and avoid 0 scaling factors
+ return fmaxf(result, CUDNN_FLT_MIN);
+ }
+
+ static __device__ scale_t
+ fp32ToE4M3(float value) {
+ return scale_t(value);
+ }
+
+ static __device__ Vec<uint8_t, NUM_ELTS>
+ vecDivideAndCast(const Cvec &input, compute_t scale) {
+ // Construct the nv_fp4x2_e2m1 outputs.
+ // If NUM_ELTS == 1, nv_fp4(ele1,0)
+ // If NUM_ELTS % 2 == 0; f2_i=nv_fp4(ele_i, ele_i+1) --> out[i/2]
+ // Per cuda_fp4.h and cuda_fp8.h
+ // The data type of __nv_fp4x2_storage_t is __nv_fp8_storage_t
+ // The data type of __nv_fp8_storage_t is unsigned char:
+ // typedef unsigned char __nv_fp8_storage_t;
+ // The reason why we use unsigned char is that the __shfl_xor_sync don't support nv_fp4 data type
+ Vec<uint8_t, NUM_ELTS> output;
+#pragma unroll
+ for (int i = 0; i < NUM_ELTS; i += 2) {
+ float2 f2 =
+ make_float2((input.data.elt[i] / scale), (i + 1 < NUM_ELTS ? (input.data.elt[i + 1] / scale) : 0));
+ output.data.elt[i / 2] = static_cast<uint8_t>(nv_fp4x2_e2m1(f2).__x);
+ }
+ return output;
+ }
+};
+
+/**
+ * Base class to provide common block scaling utilities, for mxfp8
+ */
+template <typename Cvec, typename Ovec>
+class BlockScaleHelperBase<Cvec, Ovec, 32> {
+ public:
+ using lne8m0_t = uint8_t;
+ using scale_t = lne8m0_t;
+
+ protected:
+ using compute_t = typename Cvec::Elt_type;
+ using output_t = typename Ovec::Elt_type;
+ using index_t = uint32_t;
+
+ static constexpr int32_t THREADS_PER_WARP = 32;
+ static constexpr int32_t BLOCK_SIZE = 32;
+ static constexpr int32_t NUM_ELTS = sizeof(Cvec) / sizeof(compute_t);
+ static constexpr int32_t GROUP_SIZE = BLOCK_SIZE / NUM_ELTS;
+
+ static __device__ compute_t
+ scale(const compute_t value) {
+ static constexpr float FP8_MAX = std::is_same<output_t, nv_fp8_e5m2>::value ? 57344.f : 448.f;
+ compute_t result = value / FP8_MAX;
+ // Clamp to CUDNN_FLT_MIN to match reference implementation and avoid 0 scaling factors
+ return fmaxf(result, CUDNN_FLT_MIN);
+ }
+
+ template <typename IOvec>
+ static __device__ Ovec
+ vecDivideAndCast(const IOvec &input, compute_t scale) {
+ Ovec output;
+#pragma unroll
+ for (int32_t i = 0; i < NUM_ELTS; ++i) {
+ output.data.elt[i] = output_t((compute_t(input.data.elt[i]) / scale));
+ }
+ return output;
+ };
+};
+
+/**
+ * Helper class to define the block scale operations
+ */
+template <typename Cvec, typename Ovec, int32_t BlockSize>
+class BlockScaleRowHelper;
+
+template <typename Cvec, typename Ovec, int32_t BlockSize>
+class BlockScaleColHelper;
+
+/**
+ * Specialization for MXFP8 rowwise scaling
+ */
+template <typename Cvec, typename Ovec>
+class BlockScaleRowHelper<Cvec, Ovec, 32> : private BlockScaleHelperBase<Cvec, Ovec, 32> {
+ private:
+ using Base = BlockScaleHelperBase<Cvec, Ovec, 32>;
+ using Base::BLOCK_SIZE;
+ using Base::GROUP_SIZE;
+ using Base::NUM_ELTS;
+ using Base::THREADS_PER_WARP;
+ using typename Base::compute_t;
+ using typename Base::index_t;
+ using typename Base::scale_t;
+
+ public:
+ __device__
+ BlockScaleRowHelper() = default;
+
+ template <typename IOvec>
+ __device__ void
+ blockQuantizeStore(const IOvec &z_math, void *sf_ptr, index_t sf_idx, void *z_ptr, index_t z_idx) {
+ const index_t group_id = lane / GROUP_SIZE;
+
+ // 1. compute scaling factor
+ compute_t sf = 0;
+#pragma unroll
+ // compute the amax across NUM_ELTS elements
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ sf = fmaxf(sf, fabsf(compute_t(z_math.data.elt[jt])));
+ }
+
+// Currently disabled for rowwise block scaling as perf regression observed
+#if 0 && (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000) && defined(__CUDA_ARCH_FEAT_SM100_ALL)
+#pragma unroll
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ if (group_id == jt) {
+ asm volatile("redux.sync.max.f32 %0, %1, %2;" : "=f"(sf) : "f"(sf), "r"(__activemask()));
+ }
+ }
+#else
+ // warp reduce (binary reduction) starting from GROUP_SIZE / 2 to aggregate
+ // a total of NUM_ELTS * GROUP_SIZE = BLOCK_SIZE number of z values in sf
+#pragma unroll
+ for (int offset = GROUP_SIZE / 2; offset > 0; offset /= 2) {
+ sf = fmaxf(sf, __shfl_down_sync(0xffffffff, sf, offset));
+ }
+
+ // broadcast from the lane with the valid values to the other threads in the group
+ sf = __shfl_sync(0xffffffff, sf, group_id * GROUP_SIZE);
+#endif
+ // scale the row amax to get the scaling factor
+ sf = Base::scale(sf);
+
+ // 2. store scaling factor
+ // Warp orchestration to compute scale_row:
+ // e.g. for NUM_ELTS == 2:
+ // | W0SF0 W0SF1 | W0SF0 W0SF1 | ... | W0SF0 W0SF1 | W0SF0 W0SF1 |...
+ // | W1SF0 W1SF1 | W1SF0 W1SF1 | ... | W1SF0 W1SF1 | W1SF0 W1SF1 |...
+ // | ... | ... | ... | ... | ... |...
+ // | W31SF0 W31SF1 | W31SF0 W31SF1 | ... | W31SF0 W31SF1 | W31SF0 W31SF1 |...
+ // |---------------|---------------|-----|--------------------------|---------------|...
+ // |----- CTA0 ----|----- CTA1 ----| ... |--- CTA<ctas_per_row-1> --|----- CTA0 ----|...
+ // | |
+ // |-------------------------------LDG0-----------------------------|-------LDG1-----...
+ Vec<scale_t, NUM_ELTS> sf_out;
+ // only correct for group_id == 0, but it's ok because only lane == 0 is storing sf_out
+ sf_out.data.elt[0] = float_to_e8m0(sf);
+#pragma unroll
+ for (int jt = 1; jt < NUM_ELTS; jt++) {
+ sf_out.data.elt[jt] = float_to_e8m0(__shfl_sync(0xffffffff, sf, jt * GROUP_SIZE));
+ }
+ if (lane == 0) {
+ sf_out.store_to(sf_ptr, sf_idx);
+ }
+ // No need to check for 0x00 - scale() now clamps to FLT_MIN which converts to 0x01
+ float scale = e8m0_to_float(sf_out.data.elt[0]);
+ Ovec z_row_scaled = Base::vecDivideAndCast(z_math, scale);
+ z_row_scaled.store_to(z_ptr, z_idx);
+ }
+
+ private:
+ const index_t lane = threadIdx.x % THREADS_PER_WARP;
+};
+
+/**
+ * Specialization for MXFP8 colwise scaling in 1D2X2X
+ */
+template <typename Cvec, typename Ovec>
+class BlockScaleColHelper<Cvec, Ovec, 32> : private BlockScaleHelperBase<Cvec, Ovec, 32> {
+ private:
+ using Base = BlockScaleHelperBase<Cvec, Ovec, 32>;
+ using Base::BLOCK_SIZE;
+ using Base::GROUP_SIZE;
+ using Base::NUM_ELTS;
+ using Base::THREADS_PER_WARP;
+ using typename Base::compute_t;
+ using typename Base::index_t;
+ using typename Base::output_t;
+ using typename Base::scale_t;
+
+ public:
+ __device__
+ BlockScaleColHelper(float *mxfp8_tile)
+ : mxfp8_tile_(mxfp8_tile) {}
+
+ template <typename IOvec>
+ __device__ void
+ initTile(const IOvec &z_math, int num_threads) {)KERNEL"
+ R"KERNEL( return initTile(z_math, warp, num_threads);
+ }
+
+ template <typename IOvec>
+ __device__ void
+ initTile(const IOvec &z_math, index_t row_in_tile, int num_threads) {
+ constexpr int entry_barrier_arbitrary = 5;
+ utils::namedBarrierSync(entry_barrier_arbitrary, num_threads);
+#pragma unroll
+ for (index_t jt = 0; jt < NUM_ELTS; jt++) {
+ index_t idx_in_mxfp8_smem =
+ (jt * (BLOCK_SIZE + /*padding row*/ 1) + row_in_tile) * MXFP8_1D2X2X_SMEM_COLS + lane;
+ mxfp8_tile_[idx_in_mxfp8_smem] = float(z_math.data.elt[jt]);
+ }
+ }
+
+ template <bool Transpose>
+ __device__ void
+ blockQuantizeStore(void *sf_ptr,
+ index_t sf_row_idx,
+ index_t sf_col_idx,
+ index_t sf_row_width,
+ void *z_ptr,
+ index_t z_idx,
+ int num_threads) {
+ return blockQuantizeStore<Transpose>(
+ sf_ptr, sf_row_idx, sf_col_idx, sf_row_width, z_ptr, z_idx, num_threads, warp);
+ }
+
+ template <bool Transpose>
+ __device__ void
+ blockQuantizeStore(void *sf_ptr,
+ index_t sf_row_idx,
+ index_t sf_col_idx,
+ index_t sf_row_width,
+ void *z_ptr,
+ index_t z_idx,
+ int num_threads,
+ index_t row_in_tile) {
+ // Ensure all temp outputs have been written to mxfp8 smem for the current ldg
+ constexpr int entry_barrier_arbitrary = 4;
+ utils::namedBarrierSync(entry_barrier_arbitrary, num_threads);
+ const index_t group_id = lane / GROUP_SIZE;
+
+#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000) && defined(__CUDA_ARCH_FEAT_SM100_ALL)
+ // For sm_100a arch, we can use redux.sync.op{.abs.}{.NaN}.f32 instruction to reduce the min/max value
+ // https://docs.nvidia.com/cuda/parallel-thread-execution/#parallel-synchronization-and-communication-instructions-redux-sync
+ compute_t amax_vals[NUM_ELTS];
+#pragma unroll
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ const index_t idx_in_mxfp8_smem = jt * NEXT_COL_SMEM_OFFSET + lane * MXFP8_1D2X2X_SMEM_COLS + row_in_tile;
+ asm volatile("redux.sync.max.abs.f32 %0, %1, 0xffffffff;"
+ : "=f"(amax_vals[jt])
+ : "f"(mxfp8_tile_[idx_in_mxfp8_smem]));
+ }
+ compute_t sf = amax_vals[group_id];
+#else
+ // 1. compute scaling factor
+ compute_t sf = 0;
+#pragma unroll
+ // compute the amax across NUM_ELTS elements in the same col (in shared memory, adjacent rows)
+ for (int jt = 0; jt < NUM_ELTS * MXFP8_1D2X2X_SMEM_COLS; jt += MXFP8_1D2X2X_SMEM_COLS) {
+ const index_t idx_in_mxfp8_smem = ROW_SMEM_OFFSET + jt + row_in_tile;
+ sf = fmaxf(sf, fabsf(mxfp8_tile_[idx_in_mxfp8_smem]));
+ }
+
+ // warp reduce (binary reduction) starting from GROUP_SIZE / 2 to aggregate
+ // a total of NUM_ELTS * GROUP_SIZE = BLOCK_SIZE number of z values in sf
+#pragma unroll
+ for (int offset = GROUP_SIZE / 2; offset > 0; offset /= 2) {
+ sf = fmaxf(sf, __shfl_down_sync(0xffffffff, sf, offset));
+ }
+
+ // broadcast from the lane with the valid values to the other threads in the group
+ sf = __shfl_sync(0xffffffff, sf, group_id * GROUP_SIZE);
+#endif
+
+ // scale the col amax to get the scaling factor
+ sf = Base::scale(sf);
+
+ // Warp orchestration to compute scale_col:
+ // e.g. for NUM_ELTS == 2:
+ // | W0SF0 W0SF1 W1SF0 W1SF1 ... W31SF0 W31SF1 | W0SF0 W0SF1 ... W31SF0 W31SF1 |...
+ // |----warp0---|---warp1--| ... |----warp31---|----warp0---|... |----warp31---|...
+ // |--------------------CTA0-------------------|---------------CTA1------------|...
+ // |------------------------------------------LDG0------------------------------...
+ Ovec z_col_scaled;
+ if constexpr (!Transpose) {
+ // 2. store scaling factor
+ // different columns require different sf, so all threads must exchange sf
+ Vec<scale_t, NUM_ELTS> sf_out;
+#pragma unroll
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ sf_out.data.elt[jt] = float_to_e8m0(__shfl_sync(0xffffffff, sf, jt * GROUP_SIZE));
+ }
+ if (lane == 0) {
+ sf_out.store_to(sf_ptr, sf_row_idx * sf_row_width + sf_col_idx);
+ }
+
+ // 3. scale and store output
+#pragma unroll
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ // iterate over NUM_ELTS elements in a row (in shared memory, every other NUM_ELTS in a column)
+ index_t z_idx_in_mxfp8_smem = jt * NEXT_COL_SMEM_OFFSET + lane * MXFP8_1D2X2X_SMEM_COLS + row_in_tile;
+ // No need to check for 0x00 - scale() now clamps to FLT_MIN which converts to 0x01
+ float scale = e8m0_to_float(sf_out.data.elt[jt]);
+ z_col_scaled.data.elt[jt] =
+ output_t(mxfp8_tile_[z_idx_in_mxfp8_smem] / scale);
+ }
+ } else {
+ // 2. store scaling factor
+ uint8_t sf_e8m0 = float_to_e8m0(sf);
+ // No need to check for 0x00 - scale() now clamps to FLT_MIN which converts to 0x01
+ if (lane % GROUP_SIZE == 0) {
+ static_cast<scale_t *>(sf_ptr)[(sf_row_idx + group_id) * sf_row_width + sf_col_idx] = sf_e8m0;
+ }
+
+ // 3. scale and store output
+ float scale = e8m0_to_float(sf_e8m0);
+ // No need to check for 0.0f - scale() now clamps to FLT_MIN
+#pragma unroll
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ // iterate over NUM_ELTS elements in a column (in shared memory, adjacent NUM_ELTS rows)
+ index_t z_idx_in_mxfp8_smem = ROW_SMEM_OFFSET + jt * MXFP8_1D2X2X_SMEM_COLS + row_in_tile;
+ z_col_scaled.data.elt[jt] = output_t(mxfp8_tile_[z_idx_in_mxfp8_smem] / scale);
+ }
+ }
+ z_col_scaled.store_to(z_ptr, z_idx);
+
+ }
+
+ private:
+ static constexpr index_t MXFP8_1D2X2X_SMEM_ROWS = BLOCK_SIZE * NUM_ELTS + /*padding rows between*/ (NUM_ELTS - 1);
+ static constexpr index_t MXFP8_1D2X2X_SMEM_COLS = BLOCK_SIZE + /*padding col*/ 1;
+ static constexpr index_t NEXT_COL_SMEM_OFFSET = (BLOCK_SIZE + /*padding row*/ 1) * MXFP8_1D2X2X_SMEM_COLS;
+ // For MXFP8 1d2x2x, we store the 32x32xNUM_ELTS tile in shared memory to compute the col amax for scaling within
+ // the current CTA
+ // e.g. for NUM_ELTS == 2, the shared memory layout for 1d2x2x is as follows:
+ //
+ // col0 col2 col4 col6 ... col62
+ // ↓ ↓ ↓ ↓ ↓
+ // |-------------------------------------------|
+ // | T0V0 | T1V0 | T2V0 | T3V0 |...| T31V0 | 0 | <-- warp0 to store at jt=0
+ // | T0V0 | T1V0 | T2V0 | T3V0 |...| T31V0 | 0 | <-- warp1 to store at jt=0
+ // | .. | .. | .. | .. |...| ... | 0 | <-- ...
+ // | T0V0 | T1V0 | T2V0 | T3V0 |...| T31V0 | 0 | <-- warp31 to store at jt=0
+ // |--------------------|------|---|-------|---|
+ // | 0 | 0 | 0 | 0 |...| 0 | 0 | <-- padding row between to avoid bank conflicts when col-scaling
+ // |--------------------|------|---|-------|---|
+ // | T0V1 | T1V1 | T2V1 | T3V1 |...| T31V1 | 0 | <-- warp0 to store at jt=1
+ // | T0V1 | T1V1 | T2V1 | T3V1 |...| T31V1 | 0 | <-- warp1 to store at jt=1
+ // | .. | .. | .. | .. |...| ... | 0 | <-- ...
+ // | T0V1 | T1V1 | T2V1 | T3V1 |...| T31V1 | 0 | <-- warp31 to store at jt=1
+ // |-------------------------------------------|
+ // ↑ ↑ ↑ ↑ ↑ ↑
+ // col1 col3 col5 col7 ... col63 padding col to avoid bank conflicts when computing col-scale factors
+ //
+ // ↑ ↑ ↑ ↑ ↑
+ // warp0 warp1 warp2 warp3 ... warp31
+ // to compute and apply the col-scale factors
+ float *mxfp8_tile_ = nullptr;
+
+ const index_t lane = threadIdx.x % THREADS_PER_WARP;
+ const index_t warp = threadIdx.x / THREADS_PER_WARP;
+
+ const index_t ROW_SMEM_OFFSET = ((lane * NUM_ELTS) + /*padding rows*/ (lane / GROUP_SIZE)) * MXFP8_1D2X2X_SMEM_COLS;
+};
+
+/**
+ * Specialization for NVFP4 rowwise scaling
+ */
+template <typename Cvec, typename Ovec>
+class BlockScaleRowHelper<Cvec, Ovec, 16> : private BlockScaleHelperBase<Cvec, Ovec, 16> {
+ using Base = BlockScaleHelperBase<Cvec, Ovec, 16>;
+ using Base::BLOCK_SIZE;
+ using Base::GROUP_SIZE;
+ using Base::NUM_ELTS;
+ using Base::SF_COUNT;
+ using Base::THREADS_PER_WARP;
+ using typename Base::compute_t;
+ using typename Base::index_t;
+ using typename Base::output_t;
+ using typename Base::scale_t;
+
+ public:
+ __device__
+ BlockScaleRowHelper() = default;
+
+ __device__ void
+ blockQuantizeStore(const Cvec &z_math, void *sf_ptr, index_t sf_idx, void *z_ptr, index_t z_idx) {
+ // 1. compute scaling factor
+ compute_t sf = 0;
+#pragma unroll
+ // compute the amax across NUM_ELTS elements
+ for (int jt = 0; jt < NUM_ELTS; jt++) {
+ sf = fmaxf(sf, fabsf(z_math.data.elt[jt]));
+ }
+
+ // warp reduce (binary reduction) starting from GROUP_SIZE / 2 to aggregate
+ // a total of NUM_ELTS * GROUP_SIZE = BLOCK_SIZE number of z values in sf
+#pragma unroll
+ for (int offset = GROUP_SIZE / 2; offset > 0; offset /= 2) {
+ sf = fmaxf(sf, __shfl_down_sync(0xffffffff, sf, offset));
+ }
+
+ // broadcast from the lane with the valid values to the other threads in the group
+ const index_t group_id = lane / GROUP_SIZE;
+ sf = __shfl_sync(0xffffffff, sf, group_id * GROUP_SIZE);
+
+ // scale the row amax to get the scaling factor
+ sf = Base::scale(sf);
+
+ // 2. store scaling factor
+ Vec<scale_t, SF_COUNT> sf_out;
+ // only correct for group_id == 0, but it's ok because only lane == 0 is storing sf_out
+ sf_out.data.elt[0] = Base::fp32ToE4M3(sf);
+#pragma unroll
+ for (int jt = 1; jt < SF_COUNT; jt++) {
+ sf_out.data.elt[jt] = Base::fp32ToE4M3(__shfl_sync(0xffffffff, sf, jt * GROUP_SIZE));
+ }
+ if (lane == 0) {
+ sf_out.store_to(sf_ptr, sf_idx);
+ }
+
+ // TODO: can consider doing something like the following to remove the need for a shuffle loop
+ // template <int32_t N>
+ // struct UintContainer {
+ // using type = std::conditional_t<N == 1, uint8_t,
+ // std::conditional_t<N == 2, uint16_t,
+ // std::conditional_t<N == 4, uint32_t,
+ // std::conditional_t<N == 8, uint64_t,
+ // void>>>>; // void for unsupported sizes
+ // };
+ // Base::vecDivideAndCast returns Vec<UintContainer<NUM_ELTS / 2>, 2>
+ // 3. scale and store output
+ auto z_row_scaled = Base::vecDivideAndCast(z_math, sf);
+#pragma unroll
+ // Consturct z_row_scaled by combining the adjacent thread's z_row_scaled
+ // Vec<uint8_t, NUM_ELTS> z_row_scaled
+ for (int i = 0; i < NUM_ELTS / 2; i++) {
+ uint8_t adjacent_val = __shfl_xor_sync(0xffffffff, z_row_scaled.data.elt[i], 1);
+ z_row_scaled.data.elt[i + NUM_ELTS / 2] = adjacent_val;
+ }
+ if (NUM_ELTS == 1) {
+ uint8_t adjacent_val = __shfl_xor_sync(0xffffffff, z_row_scaled.data.elt[0], 1);
+ z_row_scaled.data.elt[0] |= adjacent_val << 4U;
+ }
+ if (lane % 2 == 0) {
+ z_row_scaled.store_to(z_ptr, z_idx / 2);
+ }
+ }
+
+ private:
+ const index_t lane = threadIdx.x % THREADS_PER_WARP;
+};
+
+)KERNEL";
+inline constexpr size_t ln_headers_source_len = sizeof(ln_headers_source) - 1;
+
+} // namespace generated
+} // namespace experimental
+} // namespace cudnn_frontend
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d128_fprop_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d128_fprop_kernel.h
new file mode 100644
index 0000000..ee3664a
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d128_fprop_kernel.h
@@ -0,0 +1,3479 @@
+// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+#pragma once
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Woverlength-strings"
+#endif
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4068)
+#endif
+namespace cudnn_frontend {
+namespace experimental {
+namespace generated {
+inline constexpr const char sm100_d128_fprop_source[] =
+ R"KERNEL(
+
+// receive_op 0 includes
+typedef unsigned long long uint64_t;
+typedef unsigned int uint32_t;
+typedef unsigned short uint16_t;
+typedef unsigned char uint8_t;
+typedef long long int64_t;
+typedef int int32_t;
+typedef short int16_t;
+typedef signed char int8_t;
+typedef unsigned int r32;
+
+struct CUtensorMap {
+ alignas(64) uint64_t opaque[16];
+};
+
+#define __FLT_MIN__ 1.17549435082228750796873653722224568e-38F
+#define __FLT_MAX__ 3.40282346638528859811704183484516925e+38F
+
+#define CUDACC_VERSION __CUDACC_VER_MAJOR__ * 10 + __CUDACC_VER_MINOR__
+
+namespace fort {
+static const uint64_t AMPERE_MEM_DESC_DEFAULT = uint64_t(0x1000000000000000ul);
+static const uint64_t MEM_DESC_DEFAULT = AMPERE_MEM_DESC_DEFAULT;
+static const uint32_t MMA_PEER_BIT_MASK = 0xFEFFFFFF;
+
+#define NAN __int_as_float(0x7fffffff)
+#define POS_INFINITY __int_as_float(0x7f800000)
+#define NEG_INFINITY __int_as_float(0xff800000)
+
+typedef uint16_t bfloat16_t;
+
+#define FORT_MIN(a, b) ((a) < (b) ? (a) : (b))
+#define FORT_MAX(a, b) ((a) > (b) ? (a) : (b))
+#define FORT_DIV_UP(a, b) (((a) + (b) - 1) / (b))
+#define FORT_ROUND_UP(a, b) ((((a) + (b) - 1) / (b)) * (b))
+
+typedef struct tensor_descriptor {
+ static const int MAX_DIMS = 12;
+
+ int64_t num_dims;
+ int64_t dims[MAX_DIMS];
+ int64_t strides[MAX_DIMS];
+} tensor_descriptor;
+
+typedef struct FastDivisor {
+ uint32_t val, shr, mul;
+} FastDivisor_t;
+
+inline __device__ void fastDivMod(const FastDivisor_t &d, uint32_t val,
+ uint32_t &div, uint32_t &mod) {
+ div = __umulhi((uint32_t)2 * val, d.mul) >> d.shr;
+ mod = val - div * d.val;
+}
+
+inline __device__ char *get_smem_loc_epilogue_swizzle_128b(
+ char *smem_addr, int local_block_id, int tid, int local_row, int column,
+ size_t element_size, int block_size, int row_per_tile) {
+ if (element_size * block_size == 256) {
+ // Case 1: 2 * swizzle tile size = block size -> half block per swizzle tile
+ int swizzle_col = local_row ^ (column % 8);
+
+ // (local_block_id * 2 + (column / 8)) * row_per_tile * 128: gives offset of
+ // corresponding swizzle tile tid * 128: tid gives number of loads in block
+ // swizzle_col * 16B: swizzle_col gives transformed column
+ return smem_addr +
+ (local_block_id * 2 + (column / 8)) * row_per_tile * 128 +
+ tid * 128 + swizzle_col * 16;
+ } else if (element_size * block_size == 128) {
+ // Case 2: swizzle tile size = block size -> one block per swizzle tile
+ int swizzle_col = local_row ^ (column % 8);
+
+ // local_block_id * row_per_tile * 128: gives offset of corresponding
+ // swizzle tile tid * 128: tid gives number of loads in block swizzle_col *
+ // 16B: swizzle_col gives transformed column
+ return smem_addr + local_block_id * row_per_tile * 128 + tid * 128 +
+ swizzle_col * 16;
+ } else {
+ // Case 3: swizzle tile size / 2 = block size -> two blocks per swizzle tile
+ int swizzle_col = local_row ^ ((column + local_block_id * 4) % 8);
+
+ // (local_block_id / 2) * row_per_tile * 128: gives offset of corresponding
+ // swizzle tile tid * 128: tid gives number of loads in block swizzle_col *
+ // 16B: swizzle_col gives transformed column
+ return smem_addr + (local_block_id / 2) * row_per_tile * 128 + tid * 128 +
+ swizzle_col * 16;
+ }
+}
+
+inline __device__ static void get_next_block_id(uint32_t result,
+ uint32_t mbar) {
+#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300
+ asm volatile("{clusterlaunchcontrol.try_cancel.async.shared::cta.mbarrier::"
+ "complete_tx::bytes.b128 [%0], [%1];}\n\t" ::"r"(result),
+ "r"(mbar));
+#else
+ asm volatile(
+ "{clusterlaunchcontrol.try_cancel.async.shared::cta.mbarrier::complete_"
+ "tx::bytes.multicast::cluster::all.b128 [%0], [%1];}\n\t" ::"r"(result),
+ "r"(mbar));
+#endif
+}
+
+inline __device__ float2 ffma2(const float2 &a, const float2 &b,
+ const float2 &c) {
+ uint64_t d;
+ asm volatile("fma.rn.f32x2 %0, %1, %2, %3;\n"
+ : "=l"(d)
+ : "l"(reinterpret_cast<const uint64_t &>(a)),
+ "l"(reinterpret_cast<const uint64_t &>(b)),
+ "l"(reinterpret_cast<const uint64_t &>(c)));
+ return reinterpret_cast<float2 &>(d);
+}
+
+inline __device__ float2 fadd2(const float2 &a, const float2 &b) {
+ uint64_t c;
+ asm volatile("add.f32x2 %0, %1, %2;\n"
+ : "=l"(c)
+ : "l"(reinterpret_cast<const uint64_t &>(a)),
+ "l"(reinterpret_cast<const uint64_t &>(b)));
+ return reinterpret_cast<float2 &>(c);
+}
+
+inline __device__ float2 fmul2(const float2 &a, const float2 &b) {
+ uint64_t c;
+ asm volatile("mul.f32x2 %0, %1, %2;\n"
+ : "=l"(c)
+ : "l"(reinterpret_cast<const uint64_t &>(a)),
+ "l"(reinterpret_cast<const uint64_t &>(b)));
+ return reinterpret_cast<float2 &>(c);
+}
+
+inline __device__ float fmax3(float a, float b, float c) {
+#if (__CUDACC_VER_MAJOR__ >= 13)
+ float d;
+ asm volatile("max.ftz.f32 %0, %1, %2, %3;\n"
+ : "=f"(d)
+ : "f"((a)), "f"((b)), "f"((c)));
+ return d;
+#else
+ #error "This kernel is not supported for CUDA toolkit version < 13.0"
+ return 0.0f;
+#endif
+}
+
+inline __device__ float row_max_reduction_128_elems(uint32_t reg[128]) {
+ float tmp_max_0[42];
+ float tmp_max_1[14];
+ float tmp_max_2[5];
+ float tmp_max_3[2];
+
+#pragma unroll
+ for (int i = 0; i < 126; i += 3) {
+ tmp_max_0[i / 3] = fmax3(reinterpret_cast<float &>(reg[i + 0]),
+ reinterpret_cast<float &>(reg[i + 1]),
+ reinterpret_cast<float &>(reg[i + 2]));
+ }
+#pragma unroll
+ for (int i = 0; i < 42; i += 3) {
+ tmp_max_1[i / 3] =
+ fmax3(tmp_max_0[i + 0], tmp_max_0[i + 1], tmp_max_0[i + 2]);
+ }
+#pragma unroll
+ for (int i = 0; i < 12; i += 3) {
+ tmp_max_2[i / 3] =
+ fmax3(tmp_max_1[i + 0], tmp_max_1[i + 1], tmp_max_1[i + 2]);
+ }
+ tmp_max_2[4] =
+ fmax3(tmp_max_1[12], tmp_max_1[13], reinterpret_cast<float &>(reg[126]));
+ tmp_max_3[0] = fmax3(tmp_max_2[0], tmp_max_2[1], tmp_max_2[2]);
+ tmp_max_3[1] =
+ fmax3(tmp_max_2[3], tmp_max_2[4], reinterpret_cast<float &>(reg[127]));
+
+ return fmax3(tmp_max_3[0], tmp_max_3[1], tmp_max_3[1]);
+}
+
+#if __CUDA_ARCH__ >= 900
+
+inline __device__ uint32_t elect_one_sync() {
+ uint32_t pred = 0;
+ uint32_t laneid = 0;
+ asm volatile("{\n"
+ ".reg .b32 %%rx;\n"
+ ".reg .pred %%px;\n"
+ " elect.sync %%rx|%%px, %2;\n"
+ "@%%px mov.s32 %1, 1;\n"
+ " mov.s32 %0, %%rx;\n"
+ "}\n"
+ : "+r"(laneid), "+r"(pred)
+ : "r"(0xFFFFFFFF));
+ return pred;
+}
+
+template <int TARGET_REG_COUNT> inline __device__ void reg_alloc() {
+ // const int TARGET_REG_COUNT = 232; // Example values (use with reg_delloc's
+ // VALUE together): 224, 232, 208, 216
+ asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;\n"
+ :
+ : "n"(TARGET_REG_COUNT));
+}
+
+template <int TARGET_REG_COUNT> inline __device__ void reg_dealloc() {
+ // const int TARGET_REG_COUNT = 40; // Exmaple values: 56, 40, 88, 72
+ asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;\n"
+ :
+ : "n"(TARGET_REG_COUNT));
+}
+
+inline __device__ void named_barrier_arrive(uint32_t BARRIER_ID,
+ uint32_t NUM_THREADS) {
+ asm volatile("bar.arrive %0, %1;" : : "r"(BARRIER_ID), "r"(NUM_THREADS));
+}
+
+inline __device__ void named_barrier_wait(uint32_t BARRIER_ID,
+ uint32_t NUM_THREADS) {
+ asm volatile("bar.sync %0, %1;" ::"r"(BARRIER_ID), "r"(NUM_THREADS));
+}
+
+inline __device__ void tmastg_arrive() {
+ asm volatile("cp.async.bulk.commit_group;");
+}
+
+template <int Count> inline __device__ void tmastg_wait_count() {
+ asm volatile("cp.async.bulk.wait_group.read %0;" : : "n"(Count) : "memory");
+}
+
+#endif
+
+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900
+inline __device__ void smem_bar_init(uint32_t smem_ptr, uint32_t thread_count) {
+ asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;\n" ::"r"(smem_ptr),
+ "r"(thread_count));
+}
+
+inline __device__ void
+smem_bar_set_transaction_count(uint32_t smem_ptr, uint32_t expected_copy_bytes,
+ uint32_t pred = 0) {
+ asm volatile("{\n\t.reg .pred p;"
+ " \n\tsetp.eq.u32 p, %2, 1;"
+ " \n\t@p mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;"
+ " \n\t}" ::"r"(smem_ptr),
+ "r"(expected_copy_bytes), "r"(pred));
+}
+
+inline __device__ uint32_t smem_bar_peek(uint32_t smem_ptr,
+ uint32_t bar_phase) {
+ uint32_t bar_phase_out;
+ asm volatile("{\n\t.reg .pred P1;"
+ " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%1], %2;"
+ " \n\tselp.b32 %0, 1, 0, P1; \n\t}"
+ : "=r"(bar_phase_out)
+ : "r"(smem_ptr), "r"(bar_phase));
+ return bar_phase_out;
+}
+
+inline __device__ void
+wait_barrier(uint32_t smem_int_ptr,
+ int phase_bit) // Current phase bit the barrier waiting to flip
+{
+ asm volatile("{\n"
+ ".reg .pred P1;\n"
+ "LAB_WAIT:\n"
+ "mbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1;\n"
+ "@P1 bra.uni DONE;\n"
+ "bra.uni LAB_WAIT;\n"
+ "DONE:\n"
+ "}\n" ::"r"(smem_int_ptr),
+ "r"(phase_bit));
+}
+
+// Barrier arrive on local smem
+inline __device__ void arrive_barrier(uint32_t smem_addr) {
+ asm volatile("{\n\t"
+ "mbarrier.arrive.shared::cta.b64 _, [%0];\n\t"
+ "}"
+ :
+ : "r"(smem_addr));
+}
+
+#endif
+
+// Circular Buffer Index + Associated Phase
+// Assumes only one operation possible - i.e., ++
+template <uint32_t Stages_> struct PipelineState {
+public:
+ static constexpr int Stages = Stages_;
+
+ inline __device__ PipelineState(int index, int state)
+ : state_(state), index_(index) {}
+
+ inline __device__ int phase() const { return state_; }
+
+ inline __device__ int index() const { return index_; }
+
+ inline __device__ void operator++() {
+ if (Stages > 1) {
+ ++index_;
+ if (index_ == Stages) {
+ index_ = 0;
+ state_ ^= 1;
+ }
+ } else {
+ state_ ^= 1;
+ }
+ }
+
+ int state_;
+ int index_;
+};
+
+template <uint64_t MAX_SHIFT_FOR_WS, uint64_t UTCMMA_M, uint64_t UTCMMA_N,
+ uint64_t B_TRANSPOSE, uint64_t A_TRANSPOSE, uint64_t B_NEGATE,
+ uint64_t A_NEGATE, uint64_t SRC_B_TYPE, uint64_t SRC_A_TYPE,
+ uint64_t SPARSE_METADATA_FORMAT, uint64_t ACC_TYPE,
+ uint64_t SATURATE_ENABLED, uint64_t SPARSE_ENABLED,
+ uint64_t SPARSE_METADATA_ID2>
+inline __device__ constexpr uint64_t build_utcmma_instruction_desc() {
+ return (static_cast<uint64_t>(0) | (MAX_SHIFT_FOR_WS << 30) |
+ ((UTCMMA_M >> 5) << 25) | ((UTCMMA_N >> 3) << 17) |
+ (B_TRANSPOSE << 16) | (A_TRANSPOSE << 15) | (B_NEGATE << 14) |
+ (A_NEGATE << 13) | (SRC_B_TYPE << 10) | (SRC_A_TYPE << 7) |
+ (SPARSE_METADATA_FORMAT << 6) | (ACC_TYPE << 4) |
+ (SATURATE_ENABLED << 3) | (SPARSE_ENABLED << 2) |
+ (SPARSE_METADATA_ID2 << 0))
+ << 32;
+}
+)KERNEL"
+ R"KERNEL(
+
+class Smem_utcmma_descriptor {
+public:
+ inline __device__ Smem_utcmma_descriptor(uint64_t SWIZZLE_MODE,
+ uint64_t BASE_OFFSET,
+ uint64_t DESC_VERSION,
+ uint64_t BYTES_PER_LEADING_DIM,
+ uint64_t BYTES_PER_STRIDE_DIM) {
+ // ------------------------------------
+ // Setup smem descriptor for operand A:
+ // ------------------------------------
+ // Note 1: SWIZZLE_NONE = 0, SWIZZLE_128B = 2, SWIZZLE_64B = 4, SWIZZLE_32B
+ // = 6, SWIZZLE_128B_ATOM32B = 1, N/A = 3, N/A = 5, N/A = 7
+ const uint64_t SWIZZLE_MODE_IN_BIT_LOCATION = SWIZZLE_MODE
+ << 61; // bits: 63-61
+
+ // Note 2: Base offset. Valid only for matrix descriptor 1, 2 or 3, 4
+ const uint64_t BASE_OFFSET_IN_BIT_LOCATION = BASE_OFFSET
+ << 49; // bits 51-49
+
+ // Note 3: Descriptor version, needs to be set to 1. ???
+ const uint64_t DESC_VERSION_IN_BIT_LOCATION = DESC_VERSION
+ << 46; // bits 48-46
+
+ // Note 4: Stride dimension byte offset, 16 byte aligned, 4 LSBs not
+ // included
+ const uint64_t STRIDE_DIM_BYTE_OFFSET = BYTES_PER_STRIDE_DIM >> 4;
+ const uint64_t STRIDE_DIM_BYTE_OFFSET_IN_BIT_LOCATION =
+ STRIDE_DIM_BYTE_OFFSET << 32; // bits 45-32
+
+ // Note 5: Leading dimension byte offset, 16 byte aligned, 4 LSBs not
+ // included
+ const uint64_t LEADING_DIM_BYTE_OFFSET = BYTES_PER_LEADING_DIM >> 4;
+ const uint64_t LEADING_DIM_BYTE_OFFSET_IN_BIT_LOCATION =
+ LEADING_DIM_BYTE_OFFSET << 16; // bits 29-16
+
+ desc =
+ (SWIZZLE_MODE_IN_BIT_LOCATION | BASE_OFFSET_IN_BIT_LOCATION |
+ DESC_VERSION_IN_BIT_LOCATION | STRIDE_DIM_BYTE_OFFSET_IN_BIT_LOCATION |
+ LEADING_DIM_BYTE_OFFSET_IN_BIT_LOCATION);
+ }
+ template <int BYTES_PER_BUFFER, int BUFFER_COUNT>
+ inline __device__ void set_smem(uint32_t smem) {
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+ tmp.x |= (static_cast<uint64_t>(smem & 0xFFFFFF) >> 4);
+
+ int2 &tmp_initial = reinterpret_cast<int2 &>(initial_desc);
+ tmp_initial.x = tmp.x;
+
+ max_desc = tmp.x + (BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1);
+ }
+
+ template <int BYTES_PER_BUFFER, int BUFFER_COUNT>
+ inline __device__ void increment_smem_buffer() {
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+ tmp.x += (tmp.x >= max_desc) ? -(BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1)
+ : (BYTES_PER_BUFFER >> 4);
+ }
+
+ template <int BYTES_PER_BUFFER>
+ inline __device__ void stage_increment_smem_buffer(int stage) {
+ int2 &tmp_initial = reinterpret_cast<int2 &>(initial_desc);
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+
+ tmp.x = tmp_initial.x + (BYTES_PER_BUFFER >> 4) * stage;
+ }
+
+ template <int BYTES_OFFSET> inline __device__ void add_smem_offset() {
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+ tmp.x += (BYTES_OFFSET >> 4);
+ }
+
+ uint64_t initial_desc;
+ uint64_t desc;
+ uint32_t max_desc;
+};
+
+// cta1 utcmma with A and B from smem and C stored in tmem, scale denotes if we
+// want to accumulate C or not Something like: Accumulate or overwrite C. 1:
+// read C, 0: ignore C [clear accumulators]
+inline __device__ void
+utcmma_asmem_bsmem_h_cta1(uint64_t sdescA, uint64_t sdescB, uint32_t tmemC,
+ uint64_t idescE, uint32_t scaleC) {
+ uint32_t mask[4] = {0, 0, 0, 0}; // TODO : Figure out what this mask means,
+ // CUTLASS hardcodes to all zeros
+ asm volatile("{\n\t"
+ ".reg .pred p;\n\t"
+ "setp.ne.b32 p, %4, 0;\n\t"
+ "tcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, {%5, %6, "
+ "%7, %8}, p; \n\t"
+ "}\n"
+ :
+ : "r"(tmemC), "l"(sdescA), "l"(sdescB),
+ "r"(uint32_t(idescE >> 32)), "r"(scaleC), "r"(mask[0]),
+ "r"(mask[1]), "r"(mask[2]), "r"(mask[3]));
+}
+
+// cta1 utcmma with A from tmem and B from smem and C stored in tmem, scale
+// denotes if we want to accumulate C or not Something like: Accumulate or
+// overwrite C. 1: read C, 0: ignore C [clear accumulators]
+inline __device__ void
+utcmma_atmem_bsmem_h_cta1(uint32_t tmemA, uint64_t sdescB, uint32_t tmemC,
+ uint64_t idescE, uint32_t scaleC) {
+ uint32_t mask[4] = {0, 0, 0, 0}; // TODO : Figure out what this mask means,
+ // CUTLASS hardcodes to all zeros
+ asm volatile("{\n\t"
+ ".reg .pred p;\n\t"
+ "setp.ne.b32 p, %4, 0;\n\t"
+ "tcgen05.mma.cta_group::1.kind::f16 [%0], [%1], %2, %3, {%5, "
+ "%6, %7, %8}, p; \n\t"
+ "}\n"
+ :
+ : "r"(tmemC), "r"(tmemA), "l"(sdescB),
+ "r"(uint32_t(idescE >> 32)), "r"(scaleC), "r"(mask[0]),
+ "r"(mask[1]), "r"(mask[2]), "r"(mask[3]));
+}
+
+// Check for the utcmma to finish
+inline __device__ void umma_arrive(uint32_t bar_intptr) {
+ asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::"
+ "cluster.b64 [%0];" ::"r"(bar_intptr));
+}
+
+inline __device__ uint32_t cast_smem_ptr_to_uint(void const *const ptr) {
+ return static_cast<uint32_t>(__cvta_generic_to_shared(ptr));
+}
+
+inline __device__ void fence_view_async_shared(void) {
+ asm volatile("fence.proxy.async.shared::cta;\n");
+}
+
+inline __device__ void sts_128(r32 dst, r32 src[4]) {
+ asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};\n" ::"r"(dst),
+ "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]));
+}
+
+inline __device__ void lds_128(r32 dst[4], r32 src) {
+ asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];\n"
+ : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3])
+ : "r"(src));
+}
+
+inline __device__ void lds_32(r32 dst[1], r32 src) {
+ asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst[0]) : "r"(src));
+}
+
+inline __device__ void stg_32(void *ptr, r32 val[1]) {
+ uint32_t *p = reinterpret_cast<uint32_t *>(ptr);
+ p[0] = val[0];
+}
+
+inline __device__ void stg_8(void *ptr, r32 val[1]) {
+ uint8_t *p = reinterpret_cast<uint8_t *>(ptr);
+ p[0] = reinterpret_cast<const uint8_t &>(val[0]);
+}
+
+inline __device__ void ldg_16(r32 dst[1], const void *ptr, bool pred = true) {
+ if (pred) {
+ *reinterpret_cast<uint16_t *>(dst) =
+ *reinterpret_cast<const uint16_t *>(ptr);
+ } else {
+ *reinterpret_cast<uint16_t *>(dst) = 0;
+ }
+}
+
+inline __device__ void ldg_8(r32 dst[1], const void *ptr, bool pred = true) {
+ if (pred) {
+ *reinterpret_cast<uint8_t *>(dst) = *reinterpret_cast<const uint8_t *>(ptr);
+ } else {
+ *reinterpret_cast<uint8_t *>(dst) = 0;
+ }
+}
+
+inline __device__ void ldg_16_reg(r32 dst[1], const void *ptr,
+ bool pred = true) {
+ if (pred) {
+ uint16_t tmp = *reinterpret_cast<const uint16_t *>(ptr);
+ asm volatile("{\nmov.b32 %0, {%1, %1};\n}\n" : "=r"(dst[0]) : "h"(tmp));
+ } else {
+ dst[0] = 0;
+ }
+}
+
+inline __device__ void ldg_8_reg(r32 dst[1], const void *ptr,
+ bool pred = true) {
+ if (pred) {
+ uint8_t tmp_val = *reinterpret_cast<const uint8_t *>(ptr);
+ uint8_t *tmp_ptr = reinterpret_cast<uint8_t *>(dst);
+ tmp_ptr[0] = tmp_ptr[1] = tmp_ptr[2] = tmp_ptr[3] = tmp_val;
+ } else {
+ dst[0] = 0;
+ }
+}
+
+// Forward (non-ReLU) Activations
+// Backward (non-ReLU) Activations
+// Forward ReLU activations
+// Relu helper function: clip the lower part
+// Relu helper function: clip the upper part
+// Forward ReLU: clip only lower part
+// Forward ReLU: clip lower part and upper part
+// Forward ReLU: clip only lower part, but add slope to lower clip
+// Forward ReLU: clip lower part and upper part, but add slope to lower clip
+#if __CUDA_ARCH__ >= 900
+#endif
+
+// optimization opportunity exists here
+inline __device__ void fp32x2_to_fp16x2(r32 dst[1], const r32 src[2]) {
+ asm volatile("cvt.rn.f16x2.f32 %0, %1, %2;\n"
+ : "=r"(dst[0])
+ : "r"(src[1]), "r"(src[0]));
+}
+
+inline __device__ void fp32x2_to_fp16x2_relu(r32 dst[1], const r32 src[2]) {
+ asm volatile("cvt.rn.relu.f16x2.f32 %0, %1, %2;\n"
+ : "=r"(dst[0])
+ : "r"(src[1]), "r"(src[0]));
+}
+
+inline __device__ void fp32x2_to_bf16x2(r32 dst[1], const r32 src[2]) {
+ asm volatile("cvt.rn.bf16x2.f32 %0, %1, %2;\n"
+ : "=r"(dst[0])
+ : "r"(src[1]), "r"(src[0]));
+}
+
+// mma_pipeline_op 1 includes
+typedef struct AttentionDescriptor {
+ // Input parameters
+ // b - batch
+ // q_h - num heads of q/dq/o/do
+ // k_h - num heads of k/dk
+ // v_h - num heads of v/dv
+ // s_q - max sequence length of q
+ // s_kv - max sequence length of kv
+ // d - hidden dim (head dim)
+ uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v;
+ uint16_t q_heads_per_k, q_heads_per_v, min_q_heads_per_kv;
+} AttentionDescriptor_t;
+
+
+inline __device__ void fence_view_async_tmem_load() {
+ asm volatile("{\n\ttcgen05.wait::ld.sync.aligned; \n}" ::);
+}
+
+inline __device__ void fence_view_async_tmem_store() {
+ asm volatile("{\n\ttcgen05.wait::st.sync.aligned; \n}" ::);
+}
+
+inline __device__ void tmem_allocate_1sm(uint32_t num_columns,
+ uint32_t smem_addr) {
+ asm volatile(
+ "tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(
+ smem_addr),
+ "r"(num_columns));
+}
+
+inline __device__ void tmem_free_1sm(uint32_t num_columns, uint32_t tmem_addr) {
+ asm volatile(
+ "{\n\ttcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1; \n\t}" ::"r"(
+ tmem_addr),
+ "r"(num_columns));
+}
+
+inline __device__ void tmem_release_allocation_lock_1sm() {
+)KERNEL"
+ R"KERNEL(
+ asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::);
+}
+
+/////////////////////////////////
+/// TMEM STTM related instructions
+/////////////////////////////////
+
+// 32 data path lanes, 32-bit pattern, repeated 128 times
+// 32 data path lanes, 32-bit pattern, repeated 64 times
+// 32 data path lanes, 32-bit pattern, repeated 32 times
+inline __device__ void sttm_32dp32bit_x32(uint32_t dst, r32 src[32]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x32.b32"
+ "[%0],"
+ "{%1, %2, %3, %4,"
+ "%5, %6, %7, %8,"
+ "%9, %10, %11, %12,"
+ "%13, %14, %15, %16,"
+ "%17, %18, %19, %20,"
+ "%21, %22, %23, %24,"
+ "%25, %26, %27, %28,"
+ "%29, %30, %31, %32};\n"
+ :
+ : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]),
+ "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]),
+ "r"(src[8]), "r"(src[9]), "r"(src[10]), "r"(src[11]),
+ "r"(src[12]), "r"(src[13]), "r"(src[14]), "r"(src[15]),
+ "r"(src[16]), "r"(src[17]), "r"(src[18]), "r"(src[19]),
+ "r"(src[20]), "r"(src[21]), "r"(src[22]), "r"(src[23]),
+ "r"(src[24]), "r"(src[25]), "r"(src[26]), "r"(src[27]),
+ "r"(src[28]), "r"(src[29]), "r"(src[30]), "r"(src[31]));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 16 times
+inline __device__ void sttm_32dp32bit_x16(uint32_t dst, r32 src[16]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x16.b32"
+ "[%0],"
+ "{%1, %2, %3, %4,"
+ "%5, %6, %7, %8,"
+ "%9, %10, %11, %12,"
+ "%13, %14, %15, %16};\n"
+ :
+ : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]),
+ "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]),
+ "r"(src[8]), "r"(src[9]), "r"(src[10]), "r"(src[11]),
+ "r"(src[12]), "r"(src[13]), "r"(src[14]), "r"(src[15]));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 8 times
+inline __device__ void sttm_32dp32bit_x8(uint32_t dst, r32 src[8]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x8.b32"
+ "[%0],"
+ "{%1, %2, %3, %4,"
+ "%5, %6, %7, %8};\n"
+ :
+ : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]),
+ "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 4 times
+// 32 data path lanes, 32-bit pattern, repeated 2 times
+inline __device__ void sttm_32dp32bit_x2(uint32_t dst, r32 src[2]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x2.b32"
+ "[%0],"
+ "{%1, %2};\n"
+ :
+ : "r"(dst), "r"(src[0]), "r"(src[1]));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 1 times
+inline __device__ void sttm_32dp32bit_x1(uint32_t dst, r32 src[1]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x1.b32"
+ "[%0],"
+ "{%1};\n"
+ :
+ : "r"(dst), "r"(src[0]));
+}
+
+/////////////////////////////////
+/// TMEM LDTM related instructions
+/////////////////////////////////
+
+// 32 data path lanes, 32-bit pattern, repeated 128 times
+// 32 data path lanes, 32-bit pattern, repeated 64 times
+// 32 data path lanes, 32-bit pattern, repeated 32 times
+inline __device__ void ldtm_32dp32bit_x32(r32 dst[32], uint32_t src_addr) {
+ asm volatile("tcgen05.ld.sync.aligned.32x32b.x32.b32"
+ "{%0, %1, %2, %3,"
+ "%4, %5, %6, %7,"
+ "%8, %9, %10, %11,"
+ "%12, %13, %14, %15,"
+ "%16, %17, %18, %19,"
+ "%20, %21, %22, %23,"
+ "%24, %25, %26, %27,"
+ "%28, %29, %30, %31},"
+ "[%32];\n"
+ : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]),
+ "=r"(dst[4]), "=r"(dst[5]), "=r"(dst[6]), "=r"(dst[7]),
+ "=r"(dst[8]), "=r"(dst[9]), "=r"(dst[10]), "=r"(dst[11]),
+ "=r"(dst[12]), "=r"(dst[13]), "=r"(dst[14]), "=r"(dst[15]),
+ "=r"(dst[16]), "=r"(dst[17]), "=r"(dst[18]), "=r"(dst[19]),
+ "=r"(dst[20]), "=r"(dst[21]), "=r"(dst[22]), "=r"(dst[23]),
+ "=r"(dst[24]), "=r"(dst[25]), "=r"(dst[26]), "=r"(dst[27]),
+ "=r"(dst[28]), "=r"(dst[29]), "=r"(dst[30]), "=r"(dst[31])
+ : "r"(src_addr));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 16 times
+// 32 data path lanes, 32-bit pattern, repeated 8 times
+inline __device__ void ldtm_32dp32bit_x8(r32 dst[8], uint32_t src_addr) {
+ asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32"
+ "{%0, %1, %2, %3,"
+ "%4, %5, %6, %7},"
+ "[%8];\n"
+ : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]),
+ "=r"(dst[4]), "=r"(dst[5]), "=r"(dst[6]), "=r"(dst[7])
+ : "r"(src_addr));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 4 times
+// 32 data path lanes, 32-bit pattern, repeated 2 times
+inline __device__ void ldtm_32dp32bit_x2(r32 dst[2], uint32_t src_addr) {
+ asm volatile("tcgen05.ld.sync.aligned.32x32b.x2.b32"
+ "{%0, %1},"
+ "[%2];\n"
+ : "=r"(dst[0]), "=r"(dst[1])
+ : "r"(src_addr));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 1 times
+inline __device__ void ldtm_32dp32bit_x1(r32 dst[1], uint32_t src_addr) {
+ asm volatile("tcgen05.ld.sync.aligned.32x32b.x1.b32"
+ "{%0},"
+ "[%1];\n"
+ : "=r"(dst[0])
+ : "r"(src_addr));
+}
+
+// CUtensorMap, when issued using bulk copy async functions, are cached in
+// constant cache. But the producer kernel may have directly written to global
+// memory, without invalidating this constant cache. This acquire fence,
+// invalidates the memory address in constant cache, using UTMACCTL.IV.
+inline __device__ void tma_descriptor_fence_acquire(CUtensorMap const *p_desc) {
+#if (__CUDA_ARCH__ >= 900) && (CUDACC_VERSION >= 123)
+ uint64_t gmem_int_desc = reinterpret_cast<uint64_t>(p_desc);
+ asm volatile("fence.proxy.tensormap::generic.acquire.gpu [%0], 128;\n"
+ :
+ : "l"(gmem_int_desc)
+ : "memory");
+ asm volatile("cvta.global.u64 %0, %0;\n"
+ :
+ : "l"(gmem_int_desc), "l"(gmem_int_desc)
+ : "memory");
+#endif
+}
+
+inline __device__ void
+utmaldg_4d_tiled(const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300
+ asm volatile(
+ "cp.async.bulk.tensor.4d.shared::cta.global.mbarrier::complete_tx::"
+ "bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::"r"(
+ urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1), "l"(mem_desc)
+ : "memory");
+#else
+ asm volatile(
+ "cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::"
+ "bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::"r"(
+ urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1), "l"(mem_desc)
+ : "memory");
+#endif
+ }
+}
+
+inline __device__ void
+utmaldg_4d_tiled_multicast(const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint16_t mcast_mask, const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+ asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::"
+ "complete_tx::bytes.multicast::cluster.L2::cache_hint [%0], "
+ "[%1, {%2, %3, %4, %5}], [%6], %7, %8;\n" ::"r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1), "h"(mcast_mask), "l"(mem_desc)
+ : "memory");
+ }
+}
+
+#if (__CUDA_ARCH__ >= 1000) && (CUDACC_VERSION >= 128)
+inline __device__ void
+utmaldg_4d_tiled_2cta(const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+ asm volatile("cp.async.bulk.tensor.4d.cta_group::2.shared::cluster.global."
+ "mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, "
+ "%3, %4, %5}], [%6], %7;\n" ::"r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1 & MMA_PEER_BIT_MASK),
+ "l"(mem_desc)
+ : "memory");
+ }
+}
+
+inline __device__ void
+utmaldg_4d_tiled_multicast_2cta(const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint16_t mcast_mask,
+ const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+ asm volatile(
+ "cp.async.bulk.tensor.4d.cta_group::2.shared::cluster.global.mbarrier::"
+ "complete_tx::bytes.multicast::cluster.L2::cache_hint [%0], [%1, {%2, "
+ "%3, %4, %5}], [%6], %7, %8;\n" ::"r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1 & MMA_PEER_BIT_MASK), "h"(mcast_mask),
+ "l"(mem_desc)
+ : "memory");
+ }
+}
+#endif
+
+inline __device__ void
+utmastg_atomicAdd_4d_tiled(const void *p_desc, uint32_t smem_offset,
+ int32_t urb0, // m
+ int32_t urb1, // n
+ int32_t urb2, // h
+ int32_t urb3, // b
+ const uint32_t elect_one,
+ uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+ asm volatile(
+ "cp.reduce.async.bulk.tensor.4d.global.shared::cta.add.bulk_group [%0, "
+ "{%1, %2, %3, %4}], [%5];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(smem_offset)
+ : "memory");
+ }
+}
+
+inline __device__ void utmastg_4d_tiled(const void *p_desc,
+ uint32_t smem_offset,
+ int32_t urb0, // m
+ int32_t urb1, // n
+ int32_t urb2, // h
+ int32_t urb3, // b
+ uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ asm volatile(
+ "cp.async.bulk.tensor.4d.global.shared::cta.bulk_group [%0, {%1, %2, %3, "
+ "%4}], [%5];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(smem_offset)
+ : "memory");
+}
+
+inline __device__ void utmastg_5d_tiled(const void *p_desc,
+ uint32_t smem_offset,
+ int32_t urb0, // m
+ int32_t urb1, // n
+ int32_t urb2, // h
+ int32_t urb3, // b
+ int32_t urb4, // lean_tile_id
+ uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ asm volatile(
+ "cp.async.bulk.tensor.5d.global.shared::cta.bulk_group [%0, {%1, %2, %3, "
+ "%4, %5}], [%6];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(urb4), "r"(smem_offset)
+ : "memory");
+}
+
+// mma_loop_op 2 includes
+
+// global_load_shared_store_op 4 includes
+
+// shared_load_op 5 includes
+
+// shared_load_op 6 includes
+
+// global_load_shared_store_op 7 includes
+
+// mma_op 8 includes
+
+// global_load_op 10 includes
+
+// pointwise_calc_op 9 includes
+
+// softmax_op 12 includes
+
+// global_store_op 13 includes
+
+// global_store_op 14 includes
+
+// shared_load_op 15 includes
+
+// global_load_shared_store_op 16 includes
+
+// mma_op 17 includes
+
+// global_store_op 20 includes
+
+// output_loop_op 3 includes
+
+// shared_store_op 18 includes
+
+// shared_load_op 19 includes
+} // namespace fort
+)KERNEL"
+ R"KERNEL(
+
+// receive_op 0 types
+using namespace fort;
+
+static constexpr int THREADS_PER_WARP_0 = 32;
+static constexpr int WARPS_PER_GROUP_0 = FORT_MIN(4, 512 / THREADS_PER_WARP_0);
+static constexpr int THREADS_PER_WARP_GROUP_0 =
+ THREADS_PER_WARP_0 * WARPS_PER_GROUP_0;
+static constexpr int BITS_PER_REGISTER_0 = 32; // NOTE: sizeof(uint)
+static constexpr int BYTES_PER_REGISTER_0 = BITS_PER_REGISTER_0 / 8;
+static constexpr int THREADS_PER_GROUP_0 =
+ WARPS_PER_GROUP_0 * THREADS_PER_WARP_0;
+
+// mma_pipeline_op 1 types
+static constexpr int BYTES_PER_BANK_1 = 16;
+static constexpr int BITS_PER_ELEMENT_1 = 16;
+static constexpr int ELEMS_PER_BANK_1 =
+ BYTES_PER_BANK_1 * 8 / BITS_PER_ELEMENT_1;
+static constexpr int BYTES_PER_ELEMENT_1 = BITS_PER_ELEMENT_1 / 8;
+static constexpr int BYTES_PER_FP16_1 = 2;
+static constexpr int ELEMS_PER_VECTOR_1 =
+ BYTES_PER_REGISTER_0 / BYTES_PER_ELEMENT_1;
+static constexpr int BITS_PER_ACC_1 = 32;
+static constexpr int BYTES_PER_ACC_1 = BITS_PER_ACC_1 / 8;
+static constexpr int TILE_M_1 = 128;
+static constexpr int TILE_N_1 = 128;
+static constexpr int TILE_K_1 = 128;
+static constexpr int TILE_O_1 = FORT_MIN(TILE_K_1, 128);
+static constexpr int TILE_V_1 = TILE_K_1;
+static constexpr int TILE_DV_1 = FORT_MIN(TILE_K_1, 128);
+static constexpr int WARP_TILE_M_1 = 16;
+static constexpr int WARP_TILE_N_1 = 16;
+static constexpr int WARP_TILE_K_1 = 32 / BYTES_PER_ELEMENT_1;
+static constexpr int WARPS_M_1 = 64 / 16;
+static constexpr int WARPS_N_1 = 16 / 16;
+static constexpr int WARPS_K_1 = 16 / 16;
+static constexpr int STAGES_1 = 1;
+static constexpr int GROUPS_M_1 = 1;
+static constexpr int GMMA_TILE_M_1 = WARPS_M_1 * WARP_TILE_M_1;
+static constexpr int GMMA_TILE_K_1 = WARPS_K_1 * WARP_TILE_K_1;
+static constexpr int WARP_TILES_M_1 = TILE_M_1 / WARP_TILE_M_1;
+static constexpr int WARP_TILES_N_1 = TILE_N_1 / WARP_TILE_N_1;
+static constexpr int WARP_TILES_K_1 = TILE_K_1 / WARP_TILE_K_1;
+static constexpr int WARP_REGS_1 = TILE_N_1;
+static constexpr int REGS_M_1 = WARP_TILES_M_1 / WARPS_M_1;
+static constexpr int REGS_N_1 = WARP_TILES_N_1 / WARPS_N_1;
+static constexpr int REGS_K_1 = WARP_TILES_K_1 / WARPS_K_1;
+static constexpr int REGS_K_FOR_DP_1 = TILE_V_1 / 16;
+static constexpr int REGS_dQ_1 = TILE_O_1 / 16;
+static constexpr int REGS_O_1 = REGS_K_1 * 1;
+
+static constexpr int CGA_M_1 = 1;
+static constexpr int CGA_N_1 = 1;
+static constexpr int CTA_MMA_1 = 1;
+static constexpr int M_TILES_PER_OUTPUT_TILE_1 = 4;
+static constexpr int N_TILES_PER_OUTPUT_TILE_1 = 1;
+
+static constexpr int CTA_TILE_M_1 = TILE_M_1;
+static constexpr int CTA_TILE_N_1 = 128;
+static constexpr int CTA_TILE_K_1 = 128;
+
+static constexpr float ln2 = 0.6931471805599453094f;
+static constexpr float inv_ln2 = 1.4426950408889634074f;
+
+static constexpr uint32_t SchedulerPipelineStageCount = 1;
+static constexpr uint32_t AccumulatorPipelineStageCount = 1;
+static constexpr uint32_t SmemPipelineStageCount = 1;
+static constexpr uint32_t num_columns_per_tmem = 512;
+static constexpr uint32_t columns_per_allocation_slice = 32;
+static constexpr int stages_q = 2;
+static constexpr int stages_kv = 2 * CTA_MMA_1;
+static constexpr int Tiles_Q = 2;
+
+static constexpr int SoftmaxWarpGroups = 2;
+static constexpr int CorrectionWarpGroups = 1;
+static constexpr int SoftmaxWarps = SoftmaxWarpGroups * 4;
+static constexpr int CorrectionWarps = 4;
+
+static constexpr int MmaWarpRegs = 40; // warp 12
+static constexpr int TmaldgWarpRegs = 40; // warp 13
+static constexpr int TmastgWarpRegs = 40; // warp 14
+static constexpr int SchedulerWarpRegs = 40; // warp 15
+static constexpr int CorrectionWarpRegs = 88; // warps 8-11
+static constexpr int SoftmaxWarpRegs = 192; // warps 0-7
+
+static constexpr int threads_per_warp = 32;
+static constexpr int warps_per_group = 4;
+static constexpr int threads_per_group = threads_per_warp * warps_per_group;
+static constexpr int threads_per_cta =
+ threads_per_warp * (warps_per_group + SoftmaxWarps + CorrectionWarps);
+
+static constexpr int BUFFERS_Q = stages_q;
+static constexpr int BUFFERS_K = stages_kv;
+static constexpr int BUFFERS_V = stages_kv;
+static constexpr int BUFFERS_S = stages_kv;
+
+using ElementQ = fort::bfloat16_t;
+using ElementK = fort::bfloat16_t;
+using ElementV = fort::bfloat16_t;
+using ElementS = fort::bfloat16_t;
+using ElementO = fort::bfloat16_t;
+using ElementAccumulator = float;
+
+static constexpr int BYTES_PER_ELEMENT = 2;
+static constexpr int BYTES_PER_ACC = 4;
+
+static constexpr int BMM1_TILE_M = TILE_M_1;
+static constexpr int BMM1_TILE_N = 128;
+static constexpr int BMM1_TILE_K = 128;
+
+static constexpr int BMM2_TILE_M = TILE_M_1;
+static constexpr int BMM2_TILE_N = 128;
+static constexpr int BMM2_TILE_K = 128;
+
+static constexpr uint32_t qBufferElems = BMM1_TILE_M * BMM1_TILE_K;
+static constexpr uint32_t kBufferElems = BMM1_TILE_N * BMM1_TILE_K / CTA_MMA_1;
+static constexpr uint32_t vBufferElems = BMM2_TILE_N * BMM2_TILE_K / CTA_MMA_1;
+static constexpr uint32_t oBufferElems =
+ FORT_MAX(8, BMM2_TILE_M) * (BMM2_TILE_N + 0);
+static constexpr uint32_t sBufferElems = FORT_MAX(8, BMM1_TILE_M) * BMM1_TILE_N;
+
+static constexpr uint32_t qTmaTransactionBytes =
+ qBufferElems * sizeof(ElementQ) * CTA_MMA_1;
+static constexpr uint32_t kTmaTransactionBytes =
+ kBufferElems * sizeof(ElementK) * CTA_MMA_1;
+static constexpr uint32_t vTmaTransactionBytes =
+ vBufferElems * sizeof(ElementV) * CTA_MMA_1;
+
+static constexpr int UTCMMA_TILE_M = 128;
+static constexpr int UTCMMA_TILE_N = 128;
+static constexpr int UTCMMA_TILE_K = 32 / BYTES_PER_ELEMENT;
+
+static constexpr int BMM1_XMMAS_K = BMM1_TILE_K / UTCMMA_TILE_K;
+static constexpr int BMM2_XMMAS_K = BMM2_TILE_K / UTCMMA_TILE_K;
+static constexpr int BYTES_PER_MMA_K = UTCMMA_TILE_K * BYTES_PER_ELEMENT;
+
+static constexpr int SMEM_BUFFER_SIZE_Q =
+ BMM1_TILE_M * BMM1_TILE_K * BYTES_PER_ELEMENT;
+static constexpr int SMEM_BUFFER_SIZE_K =
+ BMM1_TILE_N * BMM1_TILE_K * BYTES_PER_ELEMENT / CTA_MMA_1;
+static constexpr int SMEM_BUFFER_SIZE_V =
+ BMM2_TILE_N * BMM2_TILE_K * BYTES_PER_ELEMENT / CTA_MMA_1;
+static constexpr int SMEM_BUFFER_SIZE_S =
+ FORT_MAX(8, BMM1_TILE_M) * BMM1_TILE_N * BYTES_PER_ELEMENT;
+
+static constexpr int SOFTMAX_BARRIER = 1;
+static constexpr int BAND_BIAS_BARRIER = 5;
+static constexpr int TMEM_ALLOC_SOFTMAX_BARRIER = 6;
+static constexpr int TMEM_ALLOC_CORRECTION_BARRIER = 7;
+
+struct SharedStorage {
+ alignas(1024) ElementQ smem_Q[qBufferElems * stages_q];
+ alignas(1024) ElementK smem_K[kBufferElems * stages_kv];
+ alignas(1024) ElementV smem_V[vBufferElems * stages_kv];
+ alignas(1024) ElementO smem_O[oBufferElems];
+
+ alignas(16) uint64_t tma_o_0_empty_mbar[1];
+
+ alignas(16) uint64_t tma_k_empty_mbar[stages_kv];
+ alignas(16) uint64_t tma_k_full_mbar[stages_kv];
+
+ alignas(16) uint64_t tma_v_empty_mbar[stages_kv];
+ alignas(16) uint64_t tma_v_full_mbar[stages_kv];
+
+ alignas(16) uint64_t tma_q_empty_mbar[stages_q];
+ alignas(16) uint64_t tma_q_full_mbar[stages_q];
+
+ alignas(16) uint64_t bmm2_tile0_done_mbar[1];
+ alignas(16) uint64_t bmm2_tile0_ready_mbar[2];
+
+ alignas(16) uint64_t stat_tile0_full_mbar[1];
+ alignas(16) uint64_t stat_tile0_empty_mbar[1];
+ alignas(16) uint64_t final_stat_tile0_empty_mbar[1];
+ alignas(16) uint64_t
+ tma_o_0_full_mbar[FORT_DIV_UP(TILE_O_1 * sizeof(ElementO), 128)];
+ alignas(16) uint64_t
+ tma_o_1_full_mbar[FORT_DIV_UP(TILE_O_1 * sizeof(ElementO), 128)];
+
+ alignas(16) uint64_t epilogue_done_mbar[1];
+ alignas(16) uint64_t tmaldg_tile_started_mbar[1];
+
+ alignas(16) uint64_t bmm1_tile0_done_mbar[1];
+ alignas(16) uint64_t bmm1_tile1_done_mbar[1];
+
+ alignas(16) uint64_t bmm2_tile1_done_mbar[1];
+ alignas(16) uint64_t bmm2_tile1_ready_mbar[2];
+
+ alignas(16) uint64_t stat_tile1_full_mbar[1];
+ alignas(16) uint64_t stat_tile1_empty_mbar[1];
+ alignas(16) uint64_t final_stat_tile1_empty_mbar[1];
+
+ alignas(16) uint64_t empty_mainloop_mbar[1];
+
+ alignas(16) uint64_t scheduler_mbar[SchedulerPipelineStageCount];
+ alignas(16) uint64_t read_tile_id_done_mbar[SchedulerPipelineStageCount];
+ alignas(16) uint64_t tmem_dealloc_smem_bar[1];
+
+ uint32_t tmem_base_ptrs;
+
+ alignas(16) uint32_t tile_id[8 * SchedulerPipelineStageCount];
+};
+
+// global_load_shared_store_op 4 types
+static constexpr int BITS_PER_ELEMENT_4 = 16;
+static constexpr int BYTES_PER_ELEMENT_4 = BITS_PER_ELEMENT_4 / 8;
+static constexpr int BYTES_PER_ACCESS_4 = 16;
+static constexpr int TILE_M_4 = 128;
+static constexpr int TILE_N_4 = 128;
+static constexpr int BYTES_PER_SMEM_4 =
+ TILE_M_4 * TILE_N_4 * BYTES_PER_ELEMENT_4;
+
+// shared_load_op 5 types
+static constexpr int BITS_PER_ELEMENT_5 = 16;
+static constexpr int BYTES_PER_ELEMENT_5 = 2;
+static constexpr int BYTES_PER_QUAD_5 = 16;
+static constexpr int WARP_TILE_M_5 = 16;
+static constexpr int WARP_TILE_N_5 = 16;
+static constexpr int TILE_M_5 = 128;
+static constexpr int TILE_N_5 = 128;
+static constexpr int BYTES_PER_SMEM_5 =
+ TILE_M_5 * TILE_N_5 * BYTES_PER_ELEMENT_5;
+static constexpr int WARPS_M_5 = 4;
+static constexpr int WARPS_N_5 = 1;
+static constexpr int WARP_TILES_M_5 = TILE_M_5 / WARP_TILE_M_5;
+static constexpr int WARP_TILES_N_5 = TILE_N_5 / WARP_TILE_N_5;
+static constexpr int THREADS_PER_WARP_TILE_M_5 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_5 = 4;
+static constexpr int REGS_M_5 = WARP_TILES_M_5 / WARPS_M_5;
+static constexpr int REGS_N_5 = WARP_TILES_N_5 / WARPS_N_5;
+static constexpr int BYTES_PER_LD_5 = 128;
+static constexpr int SWIZZLE_SCALE_5 =
+ FORT_MIN(BYTES_PER_LD_5 / 16, WARPS_PER_GROUP_0 * 4);
+
+// shared_load_op 6 types
+static constexpr int BITS_PER_ELEMENT_6 = 16;
+static constexpr int BYTES_PER_ELEMENT_6 = 2;
+static constexpr int BYTES_PER_QUAD_6 = 16;
+static constexpr int WARP_TILE_M_6 = 16;
+static constexpr int WARP_TILE_N_6 = 16;
+static constexpr int TILE_M_6 = 128;
+static constexpr int TILE_N_6 = 128;
+static constexpr int BYTES_PER_SMEM_6 =
+ TILE_M_6 * TILE_N_6 * BYTES_PER_ELEMENT_6;
+static constexpr int WARPS_M_6 = 1;
+static constexpr int WARPS_N_6 = 1;
+static constexpr int WARP_TILES_M_6 = TILE_M_6 / WARP_TILE_M_6;
+static constexpr int WARP_TILES_N_6 = TILE_N_6 / WARP_TILE_N_6;
+static constexpr int THREADS_PER_WARP_TILE_M_6 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_6 = 4;
+static constexpr int REGS_M_6 = WARP_TILES_M_6 / WARPS_M_6;
+static constexpr int REGS_N_6 = WARP_TILES_N_6 / WARPS_N_6;
+static constexpr int BYTES_PER_LD_6 = 128;
+static constexpr int SWIZZLE_SCALE_6 =
+ FORT_MIN(BYTES_PER_LD_6 / 16, WARPS_PER_GROUP_0 * 4);
+
+// global_load_shared_store_op 7 types
+static constexpr int BITS_PER_ELEMENT_7 = 16;
+static constexpr int BYTES_PER_ELEMENT_7 = BITS_PER_ELEMENT_7 / 8;
+static constexpr int BYTES_PER_ACCESS_7 = 16;
+static constexpr int TILE_M_7 = 128;
+static constexpr int TILE_N_7 = 128;
+static constexpr int BYTES_PER_SMEM_7 =
+ TILE_M_7 * TILE_N_7 * BYTES_PER_ELEMENT_7;
+
+// mma_op 8 types
+static constexpr int ROWS_PER_CORE_MATRIX_A_8 = 8;
+static constexpr int COLS_PER_CORE_MATRIX_A_8 = 8;
+static constexpr int ROWS_PER_CORE_MATRIX_B_8 = 8;
+static constexpr int COLS_PER_CORE_MATRIX_B_8 = 8;
+
+// global_load_op 10 types
+static constexpr int BITS_PER_ELEMENT_10 = 32;
+static constexpr int BYTES_PER_ELEMENT_10 = 4;
+static constexpr int REGISTERS_PER_VECTOR_10 = 1;
+static constexpr int REGISTERS_PER_ACCESS_10 = 1;
+
+// pointwise_calc_op 9 types
+static constexpr int WARP_TILE_M_9 = 16;
+static constexpr int WARP_TILE_N_9 = 16;
+static constexpr int TILE_M_9 = 128;
+static constexpr int TILE_N_9 = 128;
+static constexpr int WARPS_M_9 = 4;
+static constexpr int WARPS_N_9 = 1;
+static constexpr int WARP_TILES_M_9 = TILE_M_9 / WARP_TILE_M_9;
+static constexpr int WARP_TILES_N_9 = TILE_N_9 / WARP_TILE_N_9;
+static constexpr int WARP_REGS_9 = WARP_REGS_1;
+static constexpr int REGS_M_9 = WARP_TILES_M_9 / WARPS_M_9;
+static constexpr int REGS_N_9 = WARP_TILES_N_9 / WARPS_N_9;
+
+// mha_mask_op 11 types
+static constexpr int WARP_TILE_M_11 = 16;
+static constexpr int WARP_TILE_N_11 = 16;
+static constexpr int TILE_M_11 = 128;
+static constexpr int TILE_N_11 = 128;
+static constexpr int WARPS_M_11 = 4;
+static constexpr int WARPS_N_11 = 1;
+static constexpr int WARP_TILES_M_11 = TILE_M_11 / WARP_TILE_M_11;
+static constexpr int WARP_TILES_N_11 = TILE_N_11 / WARP_TILE_N_11;
+static constexpr int WARP_REGS_11 = 8;
+static constexpr int REGS_M_11 = WARP_TILES_M_11 / WARPS_M_11;
+static constexpr int REGS_N_11 = WARP_TILES_N_11 / WARPS_N_11;
+inline __device__ bool compute_diagonal_band_mask_11(
+)KERNEL"
+ R"KERNEL(
+ const int row, const int col, const int actual_seqlen_kv,
+ const int actual_seqlen_q, const int shift_right_bound,
+ const int left_bound) {
+ constexpr bool is_bottom_right_alignment = false;
+ constexpr bool is_shift_right_bound = false;
+ constexpr bool is_right_bound = true;
+ constexpr bool is_left_bound = false;
+ constexpr bool need_oob_check = false;
+
+ const int diag = is_bottom_right_alignment
+ ? row + (actual_seqlen_kv - actual_seqlen_q)
+ : row;
+ const int shifted_right_bound =
+ is_shift_right_bound ? diag + shift_right_bound : diag;
+ const bool right_bound_mask =
+ is_right_bound ? col <= shifted_right_bound : true;
+ const bool left_bound_mask = is_left_bound ? col + left_bound > diag : true;
+ const bool oob_check =
+ need_oob_check ? (row < actual_seqlen_q && col < actual_seqlen_kv) : true;
+ return right_bound_mask && left_bound_mask && oob_check;
+}
+
+// softmax_op 12 types
+static constexpr int BYTES_PER_ELEMENT_12 = 2;
+static constexpr int WARP_TILE_M_12 = 16;
+static constexpr int WARP_TILE_N_12 = 16;
+static constexpr int TILE_M_12 = 128;
+static constexpr int TILE_N_12 = 128;
+static constexpr int WARPS_M_12 = 4;
+static constexpr int WARPS_N_12 = 1;
+static constexpr int WARP_TILES_M_12 = TILE_M_12 / WARP_TILE_M_12;
+static constexpr int WARP_TILES_N_12 = TILE_N_12 / WARP_TILE_N_12;
+static constexpr int THREADS_PER_WARP_TILE_M_12 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_12 = 4;
+static constexpr int WARP_REGS_12 = 8;
+static constexpr int REGS_M_12 = WARP_TILES_M_12 / WARPS_M_12;
+static constexpr int REGS_N_12 = WARP_TILES_N_12 / WARPS_N_12;
+static constexpr int ROWS_PER_THREAD_12 =
+ TILE_M_12 / WARPS_M_12 / THREADS_PER_WARP_TILE_M_12;
+
+// global_store_op 13 types
+static constexpr int BYTES_PER_ELEMENT_13 = 4;
+static constexpr int WARP_TILE_M_13 = 16;
+static constexpr int WARP_TILE_N_13 = 16;
+static constexpr int TILE_M_13 = 128;
+static constexpr int TILE_N_13 = 128;
+static constexpr int WARPS_M_13 = 4;
+static constexpr int WARPS_N_13 = 1;
+static constexpr int WARP_TILES_M_13 = TILE_M_13 / WARP_TILE_M_13;
+static constexpr int WARP_TILES_N_13 = TILE_N_13 / WARP_TILE_N_13;
+static constexpr int THREADS_PER_WARP_TILE_M_13 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_13 = 4;
+static constexpr int ROWS_PER_THREAD_13 =
+ TILE_M_13 / WARPS_M_13 / THREADS_PER_WARP_TILE_M_13;
+
+// global_store_op 14 types
+static constexpr int BYTES_PER_ELEMENT_14 = 4;
+static constexpr int WARP_TILE_M_14 = 16;
+static constexpr int WARP_TILE_N_14 = 16;
+static constexpr int TILE_M_14 = 128;
+static constexpr int TILE_N_14 = 128;
+static constexpr int WARPS_M_14 = 4;
+static constexpr int WARPS_N_14 = 1;
+static constexpr int WARP_TILES_M_14 = TILE_M_14 / WARP_TILE_M_14;
+static constexpr int WARP_TILES_N_14 = TILE_N_14 / WARP_TILE_N_14;
+static constexpr int THREADS_PER_WARP_TILE_M_14 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_14 = 4;
+static constexpr int ROWS_PER_THREAD_14 =
+ TILE_M_14 / WARPS_M_14 / THREADS_PER_WARP_TILE_M_14;
+
+// shared_load_op 15 types
+static constexpr int BITS_PER_ELEMENT_15 = 16;
+static constexpr int BYTES_PER_ELEMENT_15 = 2;
+static constexpr int BYTES_PER_QUAD_15 = 16;
+static constexpr int WARP_TILE_M_15 = 16;
+static constexpr int WARP_TILE_N_15 = 16;
+static constexpr int TILE_M_15 = 128;
+static constexpr int TILE_N_15 = 128;
+static constexpr int BYTES_PER_SMEM_15 =
+ TILE_M_15 * TILE_N_15 * BYTES_PER_ELEMENT_15;
+static constexpr int WARPS_M_15 = 1;
+static constexpr int WARPS_N_15 = 1;
+static constexpr int WARP_TILES_M_15 = TILE_M_15 / WARP_TILE_M_15;
+static constexpr int WARP_TILES_N_15 = TILE_N_15 / WARP_TILE_N_15;
+static constexpr int THREADS_PER_WARP_TILE_M_15 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_15 = 4;
+static constexpr int REGS_M_15 = WARP_TILES_M_15 / WARPS_M_15;
+static constexpr int REGS_N_15 = WARP_TILES_N_15 / WARPS_N_15;
+static constexpr int BYTES_PER_LD_15 = 128;
+static constexpr int SWIZZLE_SCALE_15 =
+ FORT_MIN(BYTES_PER_LD_15 / 16, WARPS_PER_GROUP_0 * 4);
+
+// global_load_shared_store_op 16 types
+static constexpr int BITS_PER_ELEMENT_16 = 16;
+static constexpr int BYTES_PER_ELEMENT_16 = BITS_PER_ELEMENT_16 / 8;
+static constexpr int BYTES_PER_ACCESS_16 = 16;
+static constexpr int TILE_M_16 = 128;
+static constexpr int TILE_N_16 = 128;
+static constexpr int BYTES_PER_SMEM_16 =
+ TILE_M_16 * TILE_N_16 * BYTES_PER_ELEMENT_16;
+
+// mma_op 17 types
+static constexpr int ROWS_PER_CORE_MATRIX_A_17 = 8;
+static constexpr int COLS_PER_CORE_MATRIX_A_17 = 8;
+static constexpr int ROWS_PER_CORE_MATRIX_B_17 = 8;
+static constexpr int COLS_PER_CORE_MATRIX_B_17 = 8;
+
+// global_store_op 20 types
+
+// mma_loop_op 2 types
+inline __device__ int2 compute_kv_loop_bounds(
+ const int row_coord, const int ROW_TILE_SIZE, const int COL_TILE_SIZE,
+ const int actual_seqlen_kv, const int actual_seqlen_q,
+ const int shift_right_bound, const int left_bound) {
+ constexpr bool is_right_bound = true;
+ constexpr bool is_right_bound_bottom_right_alignment = false;
+ constexpr bool is_shift_right_bound = false;
+ constexpr bool is_left_bound = false;
+ constexpr bool is_left_bound_bottom_right_alignment = false;
+
+ const int right_bound_diagonal =
+ is_right_bound_bottom_right_alignment
+ ? row_coord + (actual_seqlen_kv - actual_seqlen_q)
+ : row_coord;
+ const int shifted_right_bound_diagonal =
+ is_shift_right_bound ? right_bound_diagonal + shift_right_bound
+ : right_bound_diagonal;
+ const int left_bound_diagonal =
+ is_left_bound_bottom_right_alignment
+ ? row_coord + (actual_seqlen_kv - actual_seqlen_q)
+ : row_coord;
+
+ const int kv_loop_left_bound =
+ is_left_bound
+ ? FORT_MAX(0, (left_bound_diagonal - left_bound) / COL_TILE_SIZE)
+ : 0;
+ const int kv_loop_right_bound =
+ is_right_bound
+ ? FORT_MIN(FORT_DIV_UP(shifted_right_bound_diagonal + ROW_TILE_SIZE,
+ COL_TILE_SIZE),
+ FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE))
+ : FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE);
+ return make_int2(kv_loop_left_bound, kv_loop_right_bound);
+}
+
+// output_loop_op 3 types
+static constexpr int BYTES_PER_BANK_3 = 16;
+static constexpr int ELEMENTS_PER_VECTOR_3 =
+ FORT_MIN(64, CTA_TILE_N_1 / N_TILES_PER_OUTPUT_TILE_1);
+
+// shared_store_op 18 types
+
+// shared_load_op 19 types
+static constexpr int BITS_PER_ELEMENT_19 = 32 * 1;
+static constexpr int BYTES_PER_ELEMENT_19 = BITS_PER_ELEMENT_19 / 8;
+static constexpr int BITS_PER_VECTOR_19 =
+ BITS_PER_ELEMENT_19 * ELEMENTS_PER_VECTOR_3;
+static constexpr int BYTES_PER_VECTOR_19 = BITS_PER_VECTOR_19 / 8;
+static constexpr int REGISTERS_PER_VECTOR_19 =
+ BITS_PER_VECTOR_19 / BITS_PER_REGISTER_0;
+
+// receive_op 0 code
+
+extern "C" __global__
+__launch_bounds__(512, 1) void cudnn_generated_oss_sdpa_sm100_flash_fprop_f16_knob_7_128x128x128_4x1x1_cga1x1x1_kernel0_0(
+ const AttentionDescriptor_t attnDesc, const FastDivisor_t num_head_divmod,
+ const FastDivisor_t l2_minor_divmod, const FastDivisor_t l2_major_divmod,
+ const FastDivisor_t l2_minor_residual_divmod, const int num_hb_quotient,
+ const int num_block, const int total_blocks,
+ __grid_constant__ const CUtensorMap tma_tensor_3,
+ __grid_constant__ const CUtensorMap tma_tensor_2, float tensor_4,
+ float tensor_13, void *tensor_7, fort::tensor_descriptor desc_7,
+ void *tensor_6, fort::tensor_descriptor desc_6,
+ __grid_constant__ const CUtensorMap tma_tensor_1,
+ __grid_constant__ const CUtensorMap tma_tensor_5) {
+ asm volatile(".pragma \"global knob ForceLateCommoning=1\";\n" ::: "memory");
+ asm volatile(".pragma \"global knob HoistLate=3\";\n" ::: "memory");
+
+ extern __shared__ char smem_[];
+ SharedStorage &shared_storage = *reinterpret_cast<SharedStorage *>(smem_);
+
+ // receive_op 0 decls
+
+ // mma_pipeline_op 1 decls
+ const int tid = threadIdx.x % threads_per_group;
+ const int wid = threadIdx.x / 32;
+ const int tiw = threadIdx.x % 32;
+
+ const uint32_t elect_one = elect_one_sync();
+
+ if (wid == 0 && elect_one) {
+ smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.tma_o_0_empty_mbar[0]),
+ /* 1 tmastg */ 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]),
+ /* 4 epilogue */ warps_per_group * 32 * CTA_MMA_1);
+
+#pragma unroll
+ for (int q_stage = 0; q_stage < stages_q; q_stage++) {
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ /* 1 tma */ 1);
+ }
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32 * 2 * CTA_MMA_1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile0_full_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile0_empty_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.final_stat_tile0_empty_mbar[0]),
+ /* 4 Correction */ warps_per_group * 32 * CTA_MMA_1);
+
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * sizeof(ElementO); i += 128) {
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_0_full_mbar[i / 128]),
+ /* 1 correction */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_1_full_mbar[i / 128]),
+ /* 1 correction */ warps_per_group * 32);
+ }
+ smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]),
+ /* 1 tmastg */ 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]), 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32 * 2 * CTA_MMA_1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[1]),
+ /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[1]),
+ /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile1_full_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile1_empty_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.final_stat_tile1_empty_mbar[0]),
+ /* 4 Correction */ warps_per_group * 32 * CTA_MMA_1);
+
+ smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.empty_mainloop_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1);
+
+#pragma unroll
+ for (int sched_steps = 0; sched_steps < SchedulerPipelineStageCount;
+ sched_steps++) {
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.scheduler_mbar[sched_steps]),
+ /* 1 sched */ 1);
+ smem_bar_init(cast_smem_ptr_to_uint(
+ &shared_storage.read_tile_id_done_mbar[sched_steps]),
+ (SoftmaxWarps + CorrectionWarps + 1 + 1) * CGA_M_1 *
+ CGA_N_1 +
+ CGA_M_1 * CGA_N_1 / CTA_MMA_1);
+ }
+
+#pragma unroll
+ for (int kv_stages = 0; kv_stages < stages_kv; kv_stages++) {
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[kv_stages]),
+ /* 1 mma */ CGA_M_1 / CTA_MMA_1 + CGA_N_1 - 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[kv_stages]),
+ /* 1 tma/32 ldgsts */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stages]),
+ /* 1 tma/32 ldgsts */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[kv_stages]),
+ /* 1 mma */ CGA_M_1 / CTA_MMA_1 + CGA_N_1 - 1);
+ }
+ }
+ __syncthreads();
+
+)KERNEL"
+ R"KERNEL(
+ // mma_pipeline_op 1 code
+
+ // mma_loop_op 2 code
+ uint32_t tile_id_and_coord[8] = {0};
+
+ int actual_seqlen_kv_1 = attnDesc.s_kv;
+ int actual_seqlen_q_1 = attnDesc.s_q;
+ int q_row_coord = 0;
+ int kv_loop_right_bound, kv_loop_left_bound;
+
+ const int left_bound = 0;
+ const int shift_right_bound = 0;
+
+ uint32_t tile_idx = blockIdx.x;
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+ tile_id_and_coord[0] = head_idx;
+ tile_id_and_coord[1] = batch_idx;
+ tile_id_and_coord[2] = block;
+ tile_id_and_coord[3] = 1;
+
+ int head_coord_q_offset_1 = 0;
+ uint32_t head_coord_1, head_coord_k_1, head_coord_v_1;
+ uint32_t blocked_row_coord = tile_id_and_coord[2];
+ uint32_t head_coord_from_grid_1 = tile_id_and_coord[0];
+ uint32_t batch_coord_1 = tile_id_and_coord[1];
+ uint32_t lean_tile_id = tile_id_and_coord[0];
+
+ uint32_t is_valid_tile = true;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+
+ PipelineState<SchedulerPipelineStageCount> sched_state(0, 0); // index, state
+
+ // thread_specialize_op 21 code
+ if (wid >= 0 && wid < SoftmaxWarps) {
+ // Softmax
+ reg_alloc<SoftmaxWarpRegs>();
+
+ const uint32_t softmax_gid = wid / 4;
+ const uint32_t softmax_gid_s_offset = softmax_gid * BMM1_TILE_N;
+
+ uint32_t base_tmem_addr;
+ named_barrier_wait(TMEM_ALLOC_SOFTMAX_BARRIER,
+ threads_per_warp * (SoftmaxWarps + 1));
+ lds_32(&base_tmem_addr,
+ cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs));
+ uint32_t tmem_fp32_S = base_tmem_addr + 0 + softmax_gid_s_offset;
+ uint32_t tmem_fp16_S =
+ base_tmem_addr + BMM1_TILE_N / 2 + softmax_gid_s_offset;
+ uint32_t tmem_Stats = base_tmem_addr + 0 + softmax_gid_s_offset;
+
+ r32 reg_8_0[BMM1_TILE_N];
+ r32 fp32_stats[2];
+
+ // Memory barrier states
+ uint32_t bmm_mbar_state = 0;
+ uint32_t stat_mbar_state = 0;
+ uint32_t epilogue_state = 0;
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ int p_row_1 = q_row_coord + softmax_gid * TILE_M_1 + tid;
+
+ // global_load_op 10 decls
+ r32 reg_10_0[1];
+ reg_10_0[0] = reinterpret_cast<const r32 &>(tensor_4);
+ const int oob_M_10 = 1;
+ const int oob_N_10 = 1;
+
+ // pointwise_calc_op 9 decls
+
+ // mha_mask_op 11 decls
+
+ // softmax_op 12 decls
+ r32 reg_12_0[32];
+ float2 total_sum = {0.0f, 0.0f};
+ float2 local_sum = {0.0f, 0.0f};
+ float total_max = NEG_INFINITY;
+ float actual_total_max = NEG_INFINITY;
+ static constexpr float inv_ln2_12 = 1.4426950408889634074f;
+ float total_max_scale_12 = inv_ln2_12;
+ const float bmm_scale = reinterpret_cast<const float &>(tensor_4);
+ total_max_scale_12 *= bmm_scale;
+
+ uint64_t &bmm1_mbar = softmax_gid == 0
+ ? shared_storage.bmm1_tile0_done_mbar[0]
+ : shared_storage.bmm1_tile1_done_mbar[0];
+ uint64_t &stat_empty_mbar = softmax_gid == 0
+ ? shared_storage.stat_tile0_empty_mbar[0]
+ : shared_storage.stat_tile1_empty_mbar[0];
+ uint64_t *bmm2_mbar = softmax_gid == 0
+ ? &(shared_storage.bmm2_tile0_ready_mbar[0])
+ : &(shared_storage.bmm2_tile1_ready_mbar[0]);
+ uint64_t *stat_full_mbar =
+ softmax_gid == 0 ? &(shared_storage.stat_tile0_full_mbar[0])
+ : &(shared_storage.stat_tile1_full_mbar[0]);
+
+ epilogue_state ^= 1;
+ wait_barrier(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]),
+ epilogue_state);
+ stat_mbar_state ^= 1;
+ wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar), stat_mbar_state);
+
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound;
+ kv_loop <
+ kv_loop_right_bound -
+ FORT_DIV_UP(BMM1_TILE_M * CGA_M_1 * Tiles_Q, BMM1_TILE_N);
+ kv_loop += 1) {
+ int p_col_1 = kv_loop * TILE_N_1;
+ {
+
+ wait_barrier(cast_smem_ptr_to_uint(&bmm1_mbar), bmm_mbar_state);
+
+ r32 stat_reg[BMM1_TILE_N / 64];
+#pragma unroll
+ for (int ldtm_step = 0; ldtm_step < BMM1_TILE_N / 32; ldtm_step++) {
+ ldtm_32dp32bit_x32(&reg_8_0[32 * ldtm_step],
+ tmem_fp32_S + ldtm_step * 32);
+ }
+ constexpr bool use_ldtm_stat_max = false;
+
+ // global_load_op 10 code
+
+ // softmax_op 12 code
+ float current_max =
+ row_max_reduction_128_elems(reg_8_0) * total_max_scale_12;
+
+ // Update total max
+ float total_max_tmp = fmaxf(current_max, total_max);
+ current_max = total_max;
+ total_max = total_max_tmp;
+
+ float2 bmm_scale_x_ln2_x2 =
+ make_float2(total_max_scale_12, total_max_scale_12);
+ float total_max_scaled =
+ (total_max == NEG_INFINITY) ? 0.0f : total_max;
+ float2 minus_scaled_max_x2 =
+ make_float2(-total_max_scaled, -total_max_scaled);
+
+ static constexpr int kMulPipeCount = 14; // must be multiple of 2
+ static constexpr int kSubtractPipeCount = 12; // must be multiple of 2
+ static constexpr int kFmaPipeCount = 12; // must be multiple of 2
+ static constexpr int kConvertPipeCount = 8; // must be multiple of 2
+ static constexpr int kReleasePipeCount = 4; // must be multiple of 2
+ static constexpr int kDropoutPipeCount =
+ 6; // must be multiple of 2 and less than or equal
+ // kConvertPipeCount
+ static constexpr int kAddPipeCount =
+ 4; // must be multiple of 2 and less than kDropoutPipeCount
+
+ // To better overlap EX2 MUFU and emulation, we need to have last
+ // kE2eRes of every kE2eFreq elements in a row to use emulation while
+ // the rest go to MUFU. Also, we need to avoid using emulation after
+ // kE2eLimit elements as it would delay the execution of row sum of
+ // another softmax warpgroup because of resource contention
+ static constexpr int kE2eFreq = 16;
+ static constexpr int kE2eRes = 8;
+ static constexpr int kE2eLimit = BMM1_TILE_N / 16 * 9;
+
+#pragma unroll
+ for (int i = 0; i < kFmaPipeCount; i += 2) {
+ float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i]),
+ reinterpret_cast<float &>(reg_8_0[i + 1]));
+ float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2);
+
+ reinterpret_cast<float &>(reg_8_0[i + 0]) = out.x;
+ reinterpret_cast<float &>(reg_8_0[i + 1]) = out.y;
+ }
+
+ // Optimized version of alpha = __expf(current_max - total_max);
+ float exp_input = (total_max == NEG_INFINITY)
+ ? NEG_INFINITY
+ : (current_max - total_max);
+ float alpha = exp2f(exp_input);
+
+ // Send stats to correction warp
+ reinterpret_cast<float &>(fp32_stats[0]) = alpha;
+
+ // STTM
+ sttm_32dp32bit_x1(tmem_Stats, &fp32_stats[0]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar));
+
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i += 2) {
+ if (i - kConvertPipeCount == 32) {
+ sttm_32dp32bit_x16(tmem_fp16_S, &reg_12_0[0]);
+ }
+ if (i - kConvertPipeCount == 64) {
+ sttm_32dp32bit_x16(tmem_fp16_S + 16, &reg_12_0[16]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(bmm2_mbar + 0));
+ }
+
+ if (i >= kConvertPipeCount) {
+ fp32x2_to_bf16x2(
+ &reg_12_0[((i - kConvertPipeCount) / 2) % 32],
+ reinterpret_cast<r32 *>(&reg_8_0[i - kConvertPipeCount]));
+ }
+
+ reinterpret_cast<float &>(reg_8_0[i + 0]) =
+ exp2f(reinterpret_cast<float &>(reg_8_0[i + 0]));
+
+
+ if (i + kFmaPipeCount < BMM1_TILE_N) {
+ float2 in = make_float2(
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]),
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]));
+ float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2);
+
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]) = out.x;
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]) = out.y;
+ }
+
+ reinterpret_cast<float &>(reg_8_0[i + 1]) =
+ exp2f(reinterpret_cast<float &>(reg_8_0[i + 1]));
+
+ if (i == kE2eLimit) {
+ if (softmax_gid == 1) {
+ named_barrier_arrive(SOFTMAX_BARRIER, 256);
+ named_barrier_wait(SOFTMAX_BARRIER + 1, 256);
+ }
+ }
+ }
+
+#pragma unroll
+ for (int i = BMM1_TILE_N - kConvertPipeCount; i < BMM1_TILE_N;
+ i += 2) {
+ fp32x2_to_bf16x2(&reg_12_0[(i / 2) % 32],
+ reinterpret_cast<r32 *>(&reg_8_0[i]));
+ }
+ sttm_32dp32bit_x32(tmem_fp16_S + BMM1_TILE_N / 64 * 16,
+ &reg_12_0[((BMM1_TILE_N / 64) % 2) * 16]);
+ fence_view_async_tmem_store();
+ arrive_barrier(
+ cast_smem_ptr_to_uint(bmm2_mbar + (BMM1_TILE_N / 64 - 1)));
+
+ stat_mbar_state ^= 1;
+ if (!smem_bar_peek(cast_smem_ptr_to_uint(&stat_empty_mbar),
+ stat_mbar_state)) {
+ wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar),
+ stat_mbar_state);
+ }
+
+ float2 alpha2 = make_float2(alpha, alpha);
+ float local_row_sum_0 = 0.0f;
+ total_sum = fmul2(alpha2, total_sum);
+
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i += 2) {
+ float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i + 0]),
+ reinterpret_cast<float &>(reg_8_0[i + 1]));
+ total_sum = fadd2(total_sum, in);
+ }
+ if (softmax_gid == 0) {
+ named_barrier_arrive(SOFTMAX_BARRIER + 1, 256);
+ named_barrier_wait(SOFTMAX_BARRIER, 256);
+ }
+ named_barrier_wait(SOFTMAX_BARRIER + 2 + softmax_gid, 128);
+ }
+ bmm_mbar_state ^= 1;
+ } // End of mainloop
+#pragma unroll 1
+ for (int kv_loop = FORT_MAX(
+ kv_loop_right_bound -
+ FORT_DIV_UP(BMM1_TILE_M * CGA_M_1 * Tiles_Q, BMM1_TILE_N),
+ kv_loop_left_bound);
+ kv_loop < kv_loop_right_bound; kv_loop += 1) {
+ int p_col_1 = kv_loop * TILE_N_1;
+ {
+
+ wait_barrier(cast_smem_ptr_to_uint(&bmm1_mbar), bmm_mbar_state);
+
+ r32 stat_reg[BMM1_TILE_N / 64];
+#pragma unroll
+ for (int ldtm_step = 0; ldtm_step < BMM1_TILE_N / 32; ldtm_step++) {
+ ldtm_32dp32bit_x32(&reg_8_0[32 * ldtm_step],
+ tmem_fp32_S + ldtm_step * 32);
+ }
+ constexpr bool use_ldtm_stat_max = false;
+
+)KERNEL"
+ R"KERNEL(
+ // global_load_op 10 code
+
+ // mha_mask_op 11 code
+
+ {
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i++) {
+ int row = p_row_1;
+ int col = p_col_1 + i;
+ bool mask = compute_diagonal_band_mask_11(
+ row, col, actual_seqlen_kv_1, actual_seqlen_q_1,
+ shift_right_bound, left_bound);
+ if (!mask) {
+ reinterpret_cast<float &>(reg_8_0[i]) = tensor_13;
+ }
+ }
+ }
+
+ // softmax_op 12 code
+ float current_max =
+ row_max_reduction_128_elems(reg_8_0) * total_max_scale_12;
+
+ // Update total max
+ float total_max_tmp = fmaxf(current_max, total_max);
+ current_max = total_max;
+ total_max = total_max_tmp;
+
+ float2 bmm_scale_x_ln2_x2 =
+ make_float2(total_max_scale_12, total_max_scale_12);
+ float total_max_scaled =
+ (total_max == NEG_INFINITY) ? 0.0f : total_max;
+ float2 minus_scaled_max_x2 =
+ make_float2(-total_max_scaled, -total_max_scaled);
+
+ static constexpr int kMulPipeCount = 14; // must be multiple of 2
+ static constexpr int kSubtractPipeCount = 12; // must be multiple of 2
+ static constexpr int kFmaPipeCount = 12; // must be multiple of 2
+ static constexpr int kConvertPipeCount = 8; // must be multiple of 2
+ static constexpr int kReleasePipeCount = 4; // must be multiple of 2
+ static constexpr int kDropoutPipeCount =
+ 6; // must be multiple of 2 and less than or equal
+ // kConvertPipeCount
+ static constexpr int kAddPipeCount =
+ 4; // must be multiple of 2 and less than kDropoutPipeCount
+
+ // To better overlap EX2 MUFU and emulation, we need to have last
+ // kE2eRes of every kE2eFreq elements in a row to use emulation while
+ // the rest go to MUFU. Also, we need to avoid using emulation after
+ // kE2eLimit elements as it would delay the execution of row sum of
+ // another softmax warpgroup because of resource contention
+ static constexpr int kE2eFreq = 16;
+ static constexpr int kE2eRes = 8;
+ static constexpr int kE2eLimit = BMM1_TILE_N / 16 * 9;
+
+#pragma unroll
+ for (int i = 0; i < kFmaPipeCount; i += 2) {
+ float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i]),
+ reinterpret_cast<float &>(reg_8_0[i + 1]));
+ float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2);
+
+ reinterpret_cast<float &>(reg_8_0[i + 0]) = out.x;
+ reinterpret_cast<float &>(reg_8_0[i + 1]) = out.y;
+ }
+
+ // Optimized version of alpha = __expf(current_max - total_max);
+ float exp_input = (total_max == NEG_INFINITY)
+ ? NEG_INFINITY
+ : (current_max - total_max);
+ float alpha = exp2f(exp_input);
+
+ // Send stats to correction warp
+ reinterpret_cast<float &>(fp32_stats[0]) = alpha;
+
+ // STTM
+ sttm_32dp32bit_x1(tmem_Stats, &fp32_stats[0]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar));
+
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i += 2) {
+ if (i - kConvertPipeCount == 32) {
+ sttm_32dp32bit_x16(tmem_fp16_S, &reg_12_0[0]);
+ }
+ if (i - kConvertPipeCount == 64) {
+ sttm_32dp32bit_x16(tmem_fp16_S + 16, &reg_12_0[16]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(bmm2_mbar + 0));
+ }
+
+ if (i >= kConvertPipeCount) {
+ fp32x2_to_bf16x2(
+ &reg_12_0[((i - kConvertPipeCount) / 2) % 32],
+ reinterpret_cast<r32 *>(&reg_8_0[i - kConvertPipeCount]));
+ }
+
+ reinterpret_cast<float &>(reg_8_0[i + 0]) =
+ exp2f(reinterpret_cast<float &>(reg_8_0[i + 0]));
+
+
+ if (i + kFmaPipeCount < BMM1_TILE_N) {
+ float2 in = make_float2(
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]),
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]));
+ float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2);
+
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]) = out.x;
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]) = out.y;
+ }
+
+ reinterpret_cast<float &>(reg_8_0[i + 1]) =
+ exp2f(reinterpret_cast<float &>(reg_8_0[i + 1]));
+
+ if (i == kE2eLimit) {
+ if (softmax_gid == 1) {
+ named_barrier_arrive(SOFTMAX_BARRIER, 256);
+ named_barrier_wait(SOFTMAX_BARRIER + 1, 256);
+ }
+ }
+ }
+
+#pragma unroll
+ for (int i = BMM1_TILE_N - kConvertPipeCount; i < BMM1_TILE_N;
+ i += 2) {
+ fp32x2_to_bf16x2(&reg_12_0[(i / 2) % 32],
+ reinterpret_cast<r32 *>(&reg_8_0[i]));
+ }
+ sttm_32dp32bit_x32(tmem_fp16_S + BMM1_TILE_N / 64 * 16,
+ &reg_12_0[((BMM1_TILE_N / 64) % 2) * 16]);
+ fence_view_async_tmem_store();
+ arrive_barrier(
+ cast_smem_ptr_to_uint(bmm2_mbar + (BMM1_TILE_N / 64 - 1)));
+
+ stat_mbar_state ^= 1;
+ if (!smem_bar_peek(cast_smem_ptr_to_uint(&stat_empty_mbar),
+ stat_mbar_state)) {
+ wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar),
+ stat_mbar_state);
+ }
+
+ float2 alpha2 = make_float2(alpha, alpha);
+ float local_row_sum_0 = 0.0f;
+ total_sum = fmul2(alpha2, total_sum);
+
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i += 2) {
+ float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i + 0]),
+ reinterpret_cast<float &>(reg_8_0[i + 1]));
+ total_sum = fadd2(total_sum, in);
+ }
+ if (softmax_gid == 0) {
+ named_barrier_arrive(SOFTMAX_BARRIER + 1, 256);
+ named_barrier_wait(SOFTMAX_BARRIER, 256);
+ }
+ named_barrier_wait(SOFTMAX_BARRIER + 2 + softmax_gid, 128);
+ }
+ bmm_mbar_state ^= 1;
+ } // End of mainloop
+
+ float final_total_sum = total_sum.x + total_sum.y;
+
+ reinterpret_cast<float &>(fp32_stats[0]) = total_max;
+ reinterpret_cast<float &>(fp32_stats[1]) = final_total_sum;
+ // STTM
+ sttm_32dp32bit_x2(tmem_Stats, &fp32_stats[0]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar));
+
+ // This portion of the code may seem strange, please read the
+ // Function: work_tile_info_from_workid_response, load_query_response
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ } // end of persistent loop
+ }
+
+ // thread_specialize_op 22 code
+ else if (wid >= SoftmaxWarps && wid < SoftmaxWarps + CorrectionWarps) {
+ // Correction
+ reg_dealloc<CorrectionWarpRegs>();
+ uint32_t base_tmem_addr;
+ named_barrier_wait(TMEM_ALLOC_CORRECTION_BARRIER,
+ threads_per_warp * (CorrectionWarps + 1));
+ lds_32(&base_tmem_addr,
+ cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs));
+ uint32_t tmem_fp32_O_0 = base_tmem_addr + 256;
+ uint32_t tmem_fp32_O_1 = base_tmem_addr + 384;
+ uint32_t tmem_Stats_0 = base_tmem_addr + 0;
+ uint32_t tmem_Stats_1 = base_tmem_addr + 0 + BMM1_TILE_N;
+
+ static constexpr int local_correction_block_size = 16;
+ static constexpr int local_epilogue_block_size =
+ 128 / sizeof(ElementO); // hack as only K=128/64 supported. Both can do
+ // 128B TMASTG.
+
+)KERNEL"
+ R"KERNEL(
+ float amax_s_1 = 0.f;
+ float amax_o_1 = 0.f;
+
+ // Registers
+ uint32_t fp32_stats[2];
+ uint32_t fp32_O[local_correction_block_size];
+
+ // Memory barrier states
+ uint32_t epilogue_state = 0;
+ uint32_t bmm_mbar_state = 0;
+ uint32_t stat_mbar_state = 0;
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ // No correction for iter 0
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.bmm2_tile0_ready_mbar[0])));
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.bmm2_tile1_ready_mbar[0])));
+
+ {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile0_full_mbar[0]),
+ stat_mbar_state);
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.stat_tile0_empty_mbar[0])));
+ }
+ {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile1_full_mbar[0]),
+ stat_mbar_state);
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.stat_tile1_empty_mbar[0])));
+ }
+ stat_mbar_state ^= 1;
+ } else {
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.empty_mainloop_mbar[0])));
+ }
+
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound;
+ kv_loop += 1) {
+#pragma unroll
+ for (int sub_tile_id = 0; sub_tile_id < 2; ++sub_tile_id) {
+ uint32_t tmem_Stats = sub_tile_id == 0 ? tmem_Stats_0 : tmem_Stats_1;
+ uint32_t tmem_fp32_O =
+ sub_tile_id == 0 ? tmem_fp32_O_0 : tmem_fp32_O_1;
+
+ uint64_t &stat_full_mbar =
+ sub_tile_id == 0 ? shared_storage.stat_tile0_full_mbar[0]
+ : shared_storage.stat_tile1_full_mbar[0];
+ uint64_t &bmm_done_mbar =
+ sub_tile_id == 0 ? shared_storage.bmm2_tile0_done_mbar[0]
+ : shared_storage.bmm2_tile1_done_mbar[0];
+ uint64_t *stat_empty_mbar =
+ sub_tile_id == 0 ? &(shared_storage.stat_tile0_empty_mbar[0])
+ : &(shared_storage.stat_tile1_empty_mbar[0]);
+ uint64_t *bmm_ready_mbar =
+ sub_tile_id == 0 ? &(shared_storage.bmm2_tile0_ready_mbar[0])
+ : &(shared_storage.bmm2_tile1_ready_mbar[0]);
+
+ wait_barrier(cast_smem_ptr_to_uint(&stat_full_mbar), stat_mbar_state);
+ ldtm_32dp32bit_x1(&fp32_stats[0], tmem_Stats);
+
+ float alpha = reinterpret_cast<float &>(fp32_stats[0]);
+ fence_view_async_tmem_load();
+ arrive_barrier(cast_smem_ptr_to_uint(stat_empty_mbar));
+
+ bool alpha_is_one = (alpha == 1.0f);
+ bool all_alpha_one = __all_sync(0xFFFFFFFF, alpha_is_one);
+
+ float2 alpha2 = make_float2(alpha, alpha);
+
+ wait_barrier(cast_smem_ptr_to_uint(&bmm_done_mbar), bmm_mbar_state);
+
+ if (!all_alpha_one) {
+#pragma unroll
+ for (int block = 0; block < TILE_O_1 / local_correction_block_size;
+ block++) {
+// LDTM
+#pragma unroll
+ for (int ldtm_step = 0;
+ ldtm_step < local_correction_block_size / 8; ldtm_step++) {
+ ldtm_32dp32bit_x8(&fp32_O[8 * ldtm_step],
+ tmem_fp32_O +
+ block * local_correction_block_size +
+ ldtm_step * 8);
+ }
+
+#pragma unroll
+ for (int i = 0; i < local_correction_block_size; i += 2) {
+ float2 in =
+ make_float2(reinterpret_cast<float &>(fp32_O[i + 0]),
+ reinterpret_cast<float &>(fp32_O[i + 1]));
+ float2 out = fmul2(alpha2, in);
+ reinterpret_cast<float &>(fp32_O[i + 0]) = out.x;
+ reinterpret_cast<float &>(fp32_O[i + 1]) = out.y;
+ }
+
+#pragma unroll
+ for (int sttm_step = 0;
+ sttm_step < local_correction_block_size / 8; sttm_step++) {
+ sttm_32dp32bit_x8(tmem_fp32_O +
+ block * local_correction_block_size +
+ sttm_step * 8,
+ &fp32_O[8 * sttm_step]);
+ }
+ }
+ }
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(bmm_ready_mbar));
+ }
+ stat_mbar_state ^= 1;
+ bmm_mbar_state ^= 1;
+ } // End of mainloop
+
+ // Epilogue
+ {
+ epilogue_state ^= 1;
+
+ static constexpr int stg_step = 16 / sizeof(ElementO);
+ const int local_row = (tid % 8) / 1;
+
+ // global_store_op 13 decls
+ int oob_M_13 = desc_7.dims[2];
+ int row_13 = 0;
+ char *ptr_13 =
+ reinterpret_cast<char *>(tensor_7) +
+ batch_coord_1 * desc_7.strides[0] * BYTES_PER_ELEMENT_13 +
+ head_coord_1 * desc_7.strides[1] * BYTES_PER_ELEMENT_13 +
+ row_13 * desc_7.strides[2] * BYTES_PER_ELEMENT_13;
+
+ // global_store_op 14 decls
+ int oob_M_14 = desc_6.dims[2];
+ int row_14 = 0;
+ char *ptr_14 =
+ reinterpret_cast<char *>(tensor_6) +
+ batch_coord_1 * desc_6.strides[0] * BYTES_PER_ELEMENT_14 +
+ head_coord_1 * desc_6.strides[1] * BYTES_PER_ELEMENT_14 +
+ row_14 * desc_6.strides[2] * BYTES_PER_ELEMENT_14;
+
+#pragma unroll
+ for (int sub_tile_id = 0; sub_tile_id < 2; ++sub_tile_id) {
+ const int row_coord = q_row_coord + sub_tile_id * TILE_M_1 + tid;
+ ElementO *smem_O = (sub_tile_id == 0) ? shared_storage.smem_O
+ : shared_storage.smem_V;
+
+ uint32_t fp32_reg_O[local_epilogue_block_size];
+ uint32_t reg_O[local_epilogue_block_size / (4 / sizeof(ElementO))];
+
+ uint32_t tmem_Stats = sub_tile_id == 0 ? tmem_Stats_0 : tmem_Stats_1;
+ uint32_t tmem_fp32_O =
+ sub_tile_id == 0 ? tmem_fp32_O_0 : tmem_fp32_O_1;
+
+ uint64_t &stat_full_mbar =
+ sub_tile_id == 0 ? shared_storage.stat_tile0_full_mbar[0]
+ : shared_storage.stat_tile1_full_mbar[0];
+ uint64_t &bmm_done_mbar =
+ sub_tile_id == 0 ? shared_storage.bmm2_tile0_done_mbar[0]
+ : shared_storage.bmm2_tile1_done_mbar[0];
+ uint64_t &stat_empty_mbar =
+ sub_tile_id == 0 ? shared_storage.stat_tile0_empty_mbar[0]
+ : shared_storage.stat_tile1_empty_mbar[0];
+ uint64_t &final_stat_empty_mbar =
+ sub_tile_id == 0 ? shared_storage.final_stat_tile0_empty_mbar[0]
+ : shared_storage.final_stat_tile1_empty_mbar[0];
+
+ wait_barrier(cast_smem_ptr_to_uint(&stat_full_mbar), stat_mbar_state);
+ ldtm_32dp32bit_x2(&fp32_stats[0], tmem_Stats);
+
+ float total_max = reinterpret_cast<float &>(fp32_stats[0]) * ln2;
+ float total_sum = reinterpret_cast<float &>(fp32_stats[1]);
+ fence_view_async_tmem_load();
+ arrive_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar));
+ arrive_barrier(cast_smem_ptr_to_uint(&final_stat_empty_mbar));
+
+ float softmax_stats =
+ total_sum == 0.f ? NEG_INFINITY : total_max + __logf(total_sum);
+
+ // global_store_op 13 code
+ if (row_coord < actual_seqlen_q_1) {
+ stg_32(ptr_13 +
+ row_coord * desc_7.strides[2] * BYTES_PER_ELEMENT_13,
+ &(reinterpret_cast<uint32_t &>(total_max)));
+ }
+
+ // global_store_op 14 code
+ if (row_coord < actual_seqlen_q_1) {
+ stg_32(ptr_14 +
+ row_coord * desc_6.strides[2] * BYTES_PER_ELEMENT_14,
+ &(reinterpret_cast<uint32_t &>(total_sum)));
+ }
+
+ float threshold_beta = (total_sum == 0.f) ? 0.f : 1.f / total_sum;
+ float beta = threshold_beta;
+
+ float2 beta2 = make_float2(threshold_beta, threshold_beta);
+
+ wait_barrier(cast_smem_ptr_to_uint(&bmm_done_mbar), bmm_mbar_state);
+
+ if (sub_tile_id == 0) {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_0_empty_mbar[0]),
+ epilogue_state);
+ }
+#pragma unroll
+ for (int block = 0; block < TILE_O_1 / local_epilogue_block_size;
+ block++) {
+ {
+#pragma unroll
+ for (int ldtm_step = 0;
+ ldtm_step < local_epilogue_block_size / 32; ldtm_step++) {
+ ldtm_32dp32bit_x32(&fp32_reg_O[32 * ldtm_step],
+ tmem_fp32_O +
+ block * local_epilogue_block_size +
+ ldtm_step * 32);
+ }
+ }
+
+#pragma unroll
+ for (int i = 0; i < local_epilogue_block_size; i += 2) {
+ float2 in =
+ make_float2(reinterpret_cast<float &>(fp32_reg_O[i + 0]),
+ reinterpret_cast<float &>(fp32_reg_O[i + 1]));
+ float2 out = fmul2(beta2, in);
+ reinterpret_cast<float &>(fp32_reg_O[i + 0]) = out.x;
+ reinterpret_cast<float &>(fp32_reg_O[i + 1]) = out.y;
+ }
+
+// general_data_type_cast code
+#pragma unroll
+ for (int i = 0; i < local_epilogue_block_size; i += 2) {
+ fp32x2_to_bf16x2(&reg_O[i / 2], &fp32_reg_O[i]);
+ }
+
+#pragma unroll
+ for (int i = 0; i < local_epilogue_block_size / stg_step; i++) {
+ char *smem_loc = get_smem_loc_epilogue_swizzle_128b(
+ reinterpret_cast<char *>(smem_O), block, tid, local_row, i,
+ sizeof(ElementO), local_epilogue_block_size, TILE_M_1);
+)KERNEL"
+ R"KERNEL(
+ sts_128(cast_smem_ptr_to_uint(smem_loc),
+ reinterpret_cast<r32 *>(&reg_O[i * 4]));
+ }
+
+ uint64_t *tma_o_full_mbar =
+ sub_tile_id == 0 ? &(shared_storage.tma_o_0_full_mbar[block])
+ : &(shared_storage.tma_o_1_full_mbar[block]);
+ fence_view_async_shared();
+ arrive_barrier(cast_smem_ptr_to_uint(tma_o_full_mbar));
+ }
+ }
+ stat_mbar_state ^= 1;
+ bmm_mbar_state ^= 1;
+ } // Epilogue end
+
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ } // end of persistent loop
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]));
+ }
+
+ // thread_specialize_op 23 code
+ else if (wid == SoftmaxWarps + CorrectionWarps) {
+ // MMA
+ reg_dealloc<MmaWarpRegs>();
+ tmem_allocate_1sm(num_columns_per_tmem,
+ cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs));
+ tmem_release_allocation_lock_1sm();
+ __syncwarp();
+ named_barrier_arrive(TMEM_ALLOC_SOFTMAX_BARRIER,
+ threads_per_warp * (SoftmaxWarps + 1));
+ named_barrier_arrive(TMEM_ALLOC_CORRECTION_BARRIER,
+ threads_per_warp * (CorrectionWarps + 1));
+ uint32_t base_tmem_addr;
+ lds_32(&base_tmem_addr,
+ cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs));
+
+ uint32_t tmem_S_acc_0 = base_tmem_addr + 0;
+ uint32_t tmem_S_acc_1 = base_tmem_addr + BMM1_TILE_N;
+
+ uint32_t tmem_S_bmm2_0 = base_tmem_addr + BMM1_TILE_N / 2;
+ uint32_t tmem_S_bmm2_1 = base_tmem_addr + 3 * BMM1_TILE_N / 2;
+
+ uint32_t tmem_O_0 = base_tmem_addr + 256;
+ uint32_t tmem_O_1 = base_tmem_addr + 384;
+
+ // Memory barrier states
+ uint32_t bmm_mbar_state = 0;
+ uint32_t final_stat_mbar_state = 1;
+ uint32_t empty_mainloop_mbar_state = 0;
+
+ PipelineState<stages_kv> kv_mbar_state(0, 0); // index, state
+ PipelineState<stages_q> q_mbar_state(0, 0); // index, state
+
+ // mma_op 8 decls
+ constexpr uint64_t utcmma_instruction_desc_8 =
+ build_utcmma_instruction_desc<0, // max shift for WS
+ TILE_M_1 * CTA_MMA_1, TILE_N_1,
+ 0, // Transpose for B
+ 0, // Transpose for A
+ 0, // Negate for B
+ 0, // Negate for A
+ 1, // Data type B
+ 1, // Data type A
+ 0, // sparse meta data format
+ 1, // Acc type fp32
+ 0, // saturate disable
+ 0, // sparse disable
+ 0 // sparse meta data id2 ???
+ >();
+ // Swizzle mode, base smem offset, desc type, bytes per leading dim, tile k
+ Smem_utcmma_descriptor utcmma_smem_desc_Q_0(2, 0, 1, 16,
+ ROWS_PER_CORE_MATRIX_A_8 * 128);
+ Smem_utcmma_descriptor utcmma_smem_desc_K(2, 0, 1, 16,
+ ROWS_PER_CORE_MATRIX_B_8 * 128);
+
+ utcmma_smem_desc_Q_0.set_smem<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(
+ cast_smem_ptr_to_uint(shared_storage.smem_Q));
+ utcmma_smem_desc_K.set_smem<SMEM_BUFFER_SIZE_K, BUFFERS_K>(
+ cast_smem_ptr_to_uint(shared_storage.smem_K));
+
+ // mma_op 17 decls
+ constexpr uint64_t utcmma_instruction_desc_17 =
+ build_utcmma_instruction_desc<0, // max shift for WS
+ TILE_M_1 * CTA_MMA_1, TILE_O_1,
+ 1, // Transpose for B
+ 0, // Transpose for A
+ 0, // Negate for B
+ 0, // Negate for A
+ 1, // Data type B
+ 1, // Data type A
+ 0, // sparse meta data format
+ 1, // Acc type fp32
+ 0, // saturate disable
+ 0, // sparse disable
+ 0 // sparse meta data id2 ???
+ >();
+ // Swizzle mode, base smem offset, desc type, bytes per leading dim, tile k
+ Smem_utcmma_descriptor utcmma_smem_desc_V(
+ 2, 0, 1, TILE_O_1 / ROWS_PER_CORE_MATRIX_B_17 <= 8 ? 0 : TILE_N_1 * 128,
+ COLS_PER_CORE_MATRIX_B_17 * 128);
+
+ utcmma_smem_desc_V.set_smem<SMEM_BUFFER_SIZE_V, BUFFERS_V>(
+ cast_smem_ptr_to_uint(shared_storage.smem_V));
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+ //---------------------------------------------------------//
+ //------------------- MMA Pipeline Begin ------------------//
+ //---------------------------------------------------------//
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.final_stat_tile0_empty_mbar[0]),
+ final_stat_mbar_state);
+
+ const int kv_stage = kv_mbar_state.index();
+ const int kv_state = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[kv_stage]),
+ kv_state);
+
+ const int q_stage = q_mbar_state.index();
+ const int q_phase = q_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ q_phase);
+ ++q_mbar_state;
+
+ // Q * K matmul for sub-tile 0
+ {
+ Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0;
+ uint32_t tmem_acc = tmem_S_acc_0;
+
+ // mma_op 8 code
+#pragma unroll
+ for (int k = 0; k < BMM1_XMMAS_K; ++k) {
+ if (elect_one)
+ utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc,
+ utcmma_smem_desc_K.desc, tmem_acc,
+ utcmma_instruction_desc_8, (k > 0));
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>();
+ } else {
+ utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_K
+ .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>();
+ } else {
+ utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ }
+ utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ // change the smem buffer for Q
+ utcmma_smem_desc_Q
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>();
+ }
+
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0]));
+ } // elect_one
+ } // if (kv_loop_left_bound < kv_loop_right_bound)
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.final_stat_tile1_empty_mbar[0]),
+ final_stat_mbar_state);
+
+ const int kv_stage = kv_mbar_state.index();
+ const int kv_state = kv_mbar_state.phase();
+ const int q_stage = q_mbar_state.index();
+ const int q_phase = q_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ q_phase);
+ ++q_mbar_state;
+
+ // Q * K matmul for sub-tile 1
+ {
+ Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0;
+ uint32_t tmem_acc = tmem_S_acc_1;
+
+ // mma_op 8 code
+#pragma unroll
+ for (int k = 0; k < BMM1_XMMAS_K; ++k) {
+ if (elect_one)
+ utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc,
+)KERNEL"
+ R"KERNEL(
+ utcmma_smem_desc_K.desc, tmem_acc,
+ utcmma_instruction_desc_8, (k > 0));
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>();
+ } else {
+ utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_K
+ .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>();
+ } else {
+ utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ }
+ utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ // change the smem buffer for K
+ utcmma_smem_desc_K
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_K, BUFFERS_K>();
+ // change the smem buffer for Q
+ utcmma_smem_desc_Q
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>();
+ const int kv_stage = kv_mbar_state.index();
+ if (elect_one)
+ umma_arrive(cast_smem_ptr_to_uint(
+ &shared_storage.tma_k_empty_mbar[kv_stage]));
+ }
+
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0]));
+ } // elect_one
+ }
+
+// Mainloop
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound;
+ kv_loop += 1) {
+ const int kv_stage = kv_mbar_state.index();
+ const uint32_t kv_state = kv_mbar_state.phase();
+
+ ++kv_mbar_state;
+
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stage]),
+ kv_state);
+
+ // S * V matmul for sub-tile 0
+ {
+ uint32_t bmm2_ready_mbar =
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]);
+ uint32_t tmem_O = tmem_O_0;
+ uint32_t tmem_S = tmem_S_bmm2_0;
+ uint32_t scaleC = kv_loop > kv_loop_left_bound + 1;
+
+ // mma_op 17 code
+#pragma unroll
+ for (int k = 0; k < BMM2_XMMAS_K; ++k) {
+ if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) {
+ wait_barrier(bmm2_ready_mbar +
+ (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8,
+ bmm_mbar_state);
+ }
+ if (elect_one)
+ utcmma_atmem_bsmem_h_cta1(
+ tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)),
+ utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17,
+ scaleC || k > 0);
+ if (k == BMM2_XMMAS_K - 1) {
+ utcmma_smem_desc_V
+ .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>();
+ } else {
+ utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>();
+ }
+ }
+ if (elect_one)
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]));
+ }
+
+ wait_barrier(
+ cast_smem_ptr_to_uint(
+ &shared_storage.tma_k_full_mbar[kv_mbar_state.index()]),
+ kv_mbar_state.phase());
+
+ // Q * K matmul for sub-tile 0
+ {
+ Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0;
+ uint32_t tmem_acc = tmem_S_acc_0;
+
+ // mma_op 8 code
+#pragma unroll
+ for (int k = 0; k < BMM1_XMMAS_K; ++k) {
+ if (elect_one)
+ utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc,
+ utcmma_smem_desc_K.desc, tmem_acc,
+ utcmma_instruction_desc_8, (k > 0));
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>();
+ } else {
+ utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_K
+ .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>();
+ } else {
+ utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ }
+ utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ // change the smem buffer for Q
+ utcmma_smem_desc_Q
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>();
+ }
+
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0]));
+ } // elect_one
+
+ // S * V matmul for sub-tile 1
+ {
+ uint32_t bmm2_ready_mbar =
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]);
+ uint32_t tmem_O = tmem_O_1;
+ uint32_t tmem_S = tmem_S_bmm2_1;
+ uint32_t scaleC = kv_loop > kv_loop_left_bound + 1;
+
+ // mma_op 17 code
+#pragma unroll
+ for (int k = 0; k < BMM2_XMMAS_K; ++k) {
+ if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) {
+ wait_barrier(bmm2_ready_mbar +
+ (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8,
+ bmm_mbar_state);
+ }
+ if (elect_one)
+ utcmma_atmem_bsmem_h_cta1(
+ tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)),
+ utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17,
+ scaleC || k > 0);
+ if (k == BMM2_XMMAS_K - 1) {
+ utcmma_smem_desc_V
+ .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>();
+ } else {
+ utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>();
+ }
+ }
+ if (elect_one)
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]));
+ if (elect_one)
+ umma_arrive(cast_smem_ptr_to_uint(
+ &shared_storage.tma_v_empty_mbar[kv_stage]));
+ // Change the buffer for V
+ utcmma_smem_desc_V
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_V, BUFFERS_V>();
+ }
+ bmm_mbar_state ^= 1;
+
+ // Q * K matmul for sub-tile 1
+ {
+ Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0;
+ uint32_t tmem_acc = tmem_S_acc_1;
+
+ // mma_op 8 code
+#pragma unroll
+ for (int k = 0; k < BMM1_XMMAS_K; ++k) {
+ if (elect_one)
+ utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc,
+ utcmma_smem_desc_K.desc, tmem_acc,
+ utcmma_instruction_desc_8, (k > 0));
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>();
+ } else {
+ utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_K
+ .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>();
+ } else {
+ utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ }
+ utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ // change the smem buffer for K
+ utcmma_smem_desc_K
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_K, BUFFERS_K>();
+ // change the smem buffer for Q
+ utcmma_smem_desc_Q
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>();
+ const int kv_stage = kv_mbar_state.index();
+ if (elect_one)
+ umma_arrive(cast_smem_ptr_to_uint(
+ &shared_storage.tma_k_empty_mbar[kv_stage]));
+ }
+
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0]));
+ } // elect_one
+ }
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[1]));
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[0]));
+ }
+ const int kv_stage = kv_mbar_state.index();
+ const uint32_t kv_state = kv_mbar_state.phase();
+ ++kv_mbar_state;
+
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stage]),
+ kv_state);
+
+ // S * V matmul for sub-tile 0
+ {
+ uint32_t bmm2_ready_mbar =
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]);
+ uint32_t tmem_O = tmem_O_0;
+ uint32_t tmem_S = tmem_S_bmm2_0;
+ uint32_t scaleC = kv_loop_right_bound > kv_loop_left_bound + 1;
+
+ // mma_op 17 code
+#pragma unroll
+ for (int k = 0; k < BMM2_XMMAS_K; ++k) {
+ if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) {
+ wait_barrier(bmm2_ready_mbar +
+)KERNEL"
+ R"KERNEL(
+ (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8,
+ bmm_mbar_state);
+ }
+ if (elect_one)
+ utcmma_atmem_bsmem_h_cta1(
+ tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)),
+ utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17,
+ scaleC || k > 0);
+ if (k == BMM2_XMMAS_K - 1) {
+ utcmma_smem_desc_V
+ .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>();
+ } else {
+ utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>();
+ }
+ }
+ if (elect_one)
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]));
+ }
+ // S * V matmul for sub-tile 1
+ {
+ uint32_t bmm2_ready_mbar =
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]);
+ uint32_t tmem_O = tmem_O_1;
+ uint32_t tmem_S = tmem_S_bmm2_1;
+ uint32_t scaleC = kv_loop_right_bound > kv_loop_left_bound + 1;
+
+ // mma_op 17 code
+#pragma unroll
+ for (int k = 0; k < BMM2_XMMAS_K; ++k) {
+ if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) {
+ wait_barrier(bmm2_ready_mbar +
+ (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8,
+ bmm_mbar_state);
+ }
+ if (elect_one)
+ utcmma_atmem_bsmem_h_cta1(
+ tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)),
+ utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17,
+ scaleC || k > 0);
+ if (k == BMM2_XMMAS_K - 1) {
+ utcmma_smem_desc_V
+ .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>();
+ } else {
+ utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>();
+ }
+ }
+ if (elect_one)
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]));
+ if (elect_one)
+ umma_arrive(cast_smem_ptr_to_uint(
+ &shared_storage.tma_v_empty_mbar[kv_stage]));
+ // Change the buffer for V
+ utcmma_smem_desc_V
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_V, BUFFERS_V>();
+ }
+ bmm_mbar_state ^= 1;
+ } else {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.empty_mainloop_mbar[0]),
+ empty_mainloop_mbar_state);
+ empty_mainloop_mbar_state ^= 1;
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]));
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]));
+ }
+ }
+ final_stat_mbar_state ^= 1;
+ __syncwarp();
+
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ }
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]), 0);
+ tmem_free_1sm(num_columns_per_tmem, shared_storage.tmem_base_ptrs);
+ }
+
+ // thread_specialize_op 24 code
+ else if (wid == SoftmaxWarps + CorrectionWarps + 1) {
+ // TMALDG Q, K, V
+ reg_dealloc<TmaldgWarpRegs>();
+
+ // Memory barrier states
+ uint32_t epilogue_state = 1;
+ PipelineState<stages_q> q_mbar_state(0, 1); // index, state
+ PipelineState<stages_kv> kv_mbar_state(0, 1); // index, state
+ PipelineState<2> sts_page_buffer_state(0, 0); // index, state
+ PipelineState<2> lds_page_buffer_state(0, 0); // index, state
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+
+ // global_load_shared_store_op 4 decls
+
+ // global_load_shared_store_op 7 decls
+
+ // global_load_shared_store_op 16 decls
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ int kv_loop = kv_loop_left_bound;
+
+ const int q_stage = q_mbar_state.index();
+ const int q_phase = q_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]),
+ q_phase);
+ ++q_mbar_state;
+
+ // Load Q sub-tile 0
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ qTmaTransactionBytes, elect_one);
+ }
+ {
+ uint32_t local_smem_q = cast_smem_ptr_to_uint(shared_storage.smem_Q +
+ q_stage * qBufferElems);
+ uint32_t local_smem_bar_tma_q =
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]);
+ const uint32_t row_coord = q_row_coord;
+
+ // global_load_shared_store_op 4 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_tensor_3, local_smem_q + i * TILE_M_1,
+ local_smem_bar_tma_q, i / BYTES_PER_ELEMENT_1,
+ row_coord, head_coord_1 + 0, batch_coord_1,
+ elect_one);
+ }
+ }
+
+ // Load K
+ const int k_stage = kv_mbar_state.index();
+ const int k_phase = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[k_stage]),
+ k_phase);
+
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]),
+ kTmaTransactionBytes, elect_one);
+ }
+ {
+ const int lds_page_buffer_state_idx = lds_page_buffer_state.index();
+ uint32_t local_smem_k = cast_smem_ptr_to_uint(shared_storage.smem_K +
+ k_stage * kBufferElems);
+ uint32_t local_smem_bar_tma_k =
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]);
+ const uint32_t p_col_coord = kv_loop * TILE_N_1;
+
+ // global_load_shared_store_op 7 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_tensor_2, local_smem_k + i * TILE_N_1,
+ local_smem_bar_tma_k, i / BYTES_PER_ELEMENT_1,
+ p_col_coord, head_coord_k_1, batch_coord_1,
+ elect_one);
+ }
+ }
+ } // if (kv_loop_left_bound < kv_loop_right_bound)
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ const int q_stage = q_mbar_state.index();
+ const int q_phase = q_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]),
+ q_phase);
+ ++q_mbar_state;
+
+ // Load Q sub-tile 1
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ qTmaTransactionBytes, elect_one);
+ }
+ {
+ uint32_t local_smem_q = cast_smem_ptr_to_uint(shared_storage.smem_Q +
+ q_stage * qBufferElems);
+ uint32_t local_smem_bar_tma_q =
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]);
+ const uint32_t row_coord = q_row_coord + TILE_M_1;
+
+ // global_load_shared_store_op 4 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_tensor_3, local_smem_q + i * TILE_M_1,
+ local_smem_bar_tma_q, i / BYTES_PER_ELEMENT_1,
+ row_coord, head_coord_1 + 0, batch_coord_1,
+ elect_one);
+ }
+ }
+ } // if (kv_loop_left_bound < kv_loop_right_bound)
+ wait_barrier(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]),
+ epilogue_state);
+ epilogue_state ^= 1;
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ int kv_loop = kv_loop_left_bound;
+ // Load V
+ const int v_stage = kv_mbar_state.index();
+ const int v_phase = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[v_stage]),
+ v_phase);
+ ++kv_mbar_state;
+
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]),
+ vTmaTransactionBytes, elect_one);
+ }
+ {
+ const int lds_page_buffer_state_idx = lds_page_buffer_state.index();
+ uint32_t local_smem_v = cast_smem_ptr_to_uint(shared_storage.smem_V +
+ v_stage * vBufferElems);
+ uint32_t local_smem_bar_tma_v =
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]);
+ const uint32_t p_col_coord = kv_loop * TILE_N_1;
+
+ // global_load_shared_store_op 16 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1;
+ i += 128 * CTA_MMA_1) {
+ utmaldg_4d_tiled(&tma_tensor_1, local_smem_v + i * TILE_N_1,
+ local_smem_bar_tma_v, 0 + i / BYTES_PER_ELEMENT_1,
+ p_col_coord, head_coord_v_1, batch_coord_1,
+ elect_one);
+ }
+ }
+ } // if (kv_loop_left_bound < kv_loop_right_bound)
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]));
+
+// Mainloop to load K and V
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound;
+ kv_loop += 1) {
+
+ // Load K
+ const int k_stage = kv_mbar_state.index();
+ const int k_phase = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[k_stage]),
+ k_phase);
+
+)KERNEL"
+ R"KERNEL(
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]),
+ kTmaTransactionBytes, elect_one);
+ }
+ {
+ const int lds_page_buffer_state_idx = lds_page_buffer_state.index();
+ uint32_t local_smem_k = cast_smem_ptr_to_uint(shared_storage.smem_K +
+ k_stage * kBufferElems);
+ uint32_t local_smem_bar_tma_k =
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]);
+ const uint32_t p_col_coord = kv_loop * TILE_N_1;
+
+ // global_load_shared_store_op 7 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_tensor_2, local_smem_k + i * TILE_N_1,
+ local_smem_bar_tma_k, i / BYTES_PER_ELEMENT_1,
+ p_col_coord, head_coord_k_1, batch_coord_1,
+ elect_one);
+ }
+ }
+ if (kv_loop + 1 < kv_loop_right_bound) {
+ }
+
+ // Load V
+ const int v_stage = kv_mbar_state.index();
+ const int v_phase = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[v_stage]),
+ v_phase);
+ ++kv_mbar_state;
+
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]),
+ vTmaTransactionBytes, elect_one);
+ }
+ {
+ const int lds_page_buffer_state_idx = lds_page_buffer_state.index();
+ uint32_t local_smem_v = cast_smem_ptr_to_uint(shared_storage.smem_V +
+ v_stage * vBufferElems);
+ uint32_t local_smem_bar_tma_v =
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]);
+ const uint32_t p_col_coord = kv_loop * TILE_N_1;
+
+ // global_load_shared_store_op 16 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1;
+ i += 128 * CTA_MMA_1) {
+ utmaldg_4d_tiled(&tma_tensor_1, local_smem_v + i * TILE_N_1,
+ local_smem_bar_tma_v, 0 + i / BYTES_PER_ELEMENT_1,
+ p_col_coord, head_coord_v_1, batch_coord_1,
+ elect_one);
+ }
+ }
+
+ ++lds_page_buffer_state;
+ }
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ ++lds_page_buffer_state;
+ ++sts_page_buffer_state;
+ }
+ __syncwarp();
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ }
+ }
+
+ // thread_specialize_op 25 code
+ else if (wid == SoftmaxWarps + CorrectionWarps + 2) {
+ // TMASTG (epilogue)
+ reg_dealloc<TmastgWarpRegs>();
+
+ ElementO *smem_O_0 = shared_storage.smem_O;
+ ElementO *smem_O_1 = shared_storage.smem_V;
+ // Memory barrier states
+ uint32_t epilogue_state = 0;
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]),
+ epilogue_state);
+
+ // global_store_op 20 decls
+
+// TMASTG for sub-tile 0
+#pragma unroll
+ for (int i = 0; i < BMM2_TILE_N * sizeof(ElementO); i += 128) {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_0_full_mbar[i / 128]),
+ epilogue_state);
+ const uint32_t row_coord = q_row_coord;
+ uint32_t smem_loc = cast_smem_ptr_to_uint(smem_O_0) + i * BMM2_TILE_M;
+ if (actual_seqlen_q_1 > 0) {
+
+ // global_store_op 20 code
+ utmastg_4d_tiled(&tma_tensor_5, smem_loc, 0 + i / sizeof(ElementO),
+ row_coord, head_coord_1 + 0, batch_coord_1);
+ }
+ }
+
+ tmastg_arrive();
+
+// TMASTG for sub-tile 1
+#pragma unroll
+ for (int i = 0; i < BMM2_TILE_N * sizeof(ElementO); i += 128) {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_1_full_mbar[i / 128]),
+ epilogue_state);
+ const uint32_t row_coord = q_row_coord + TILE_M_1;
+ uint32_t smem_loc = cast_smem_ptr_to_uint(smem_O_1) + i * BMM2_TILE_M;
+ if (actual_seqlen_q_1 > 0) {
+
+ // global_store_op 20 code
+ utmastg_4d_tiled(&tma_tensor_5, smem_loc, 0 + i / sizeof(ElementO),
+ row_coord, head_coord_1 + 0, batch_coord_1);
+ }
+ }
+ tmastg_arrive();
+
+ tmastg_wait_count<1>();
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.tma_o_0_empty_mbar[0])));
+
+ tmastg_wait_count<0>();
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.epilogue_done_mbar[0])));
+
+ epilogue_state ^= 1;
+
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ } // end of persistent loop
+ }
+
+ // thread_specialize_op 26 code
+ else if (wid == SoftmaxWarps + CorrectionWarps + 3) {
+ // Scheduler
+ reg_dealloc<SchedulerWarpRegs>();
+
+#pragma unroll 1
+ while (is_valid_tile) {
+ wait_barrier(
+ cast_smem_ptr_to_uint(
+ &shared_storage.read_tile_id_done_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ 16, elect_one);
+
+ if (elect_one) {
+ get_next_block_id(
+ tile_id_smem_int_ptr,
+ cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]));
+ }
+ __syncwarp();
+
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ is_valid_tile = tile_id_and_coord[2] & 1;
+ }
+ }
+}
+)KERNEL";
+inline constexpr size_t sm100_d128_fprop_source_len = sizeof(sm100_d128_fprop_source) - 1;
+
+inline constexpr const char sm100_d128_fprop_flags[] = R"FLAGS(
+--gpu-architecture=sm_100a
+--std=c++17
+-w
+--define-macro=__CUDACC_RTC__
+-default-device
+--use_fast_math
+-Xptxas=-maxrregcount=128
+-DCUDA_ENABLE_TENSOR_MEMORY_INTRINSICS=1
+-DCUDA_ENABLE_VIRTCOUNT_INTRINSICS=1
+-DCUDA_ENABLE_TMEM_MANAGEMENT_INTRINSICS=1
+-DCUDA_BLACKWELL_TMA_SWIZZLE_ENABLED=1
+-DCUDA_ENABLE_FLEXIBLE_CLUSTER=1
+-DCUDA_PTX_TCMMA_V2_SUPPORTED=1
+-DCUDA_PTX_TMEM_MANAGEMENT_SUPPORTED=1
+-DCUDA_ENABLE_CLUSTER_MMA_INTRINSICS=1
+-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1
+-DCUTLASS_ENABLE_EXTENDED_PTX=1
+-DCUTLASS_ENABLE_INTERNAL_NVVM=1
+-DCUTLASS_CUDA_INTERNAL_L2_PREFETCH_ENABLED=1
+-DCUTLASS_CUDA_RP2RP_ENABLED=1
+-DCUTLASS_ENABLE_COMPILER_KNOBS=1
+-DCUTLASS_TEST_LEVEL=0
+-DCUTLASS_TEST_ENABLE_CACHED_RESULTS=1
+-DCUTLASS_CONV_UNIT_TEST_RIGOROUS_SIZE_ENABLED=1
+-DCUTLASS_DEBUG_TRACE_LEVEL=0
+-DCUTLASS_VERSIONS_GENERATED
+)FLAGS";
+inline constexpr size_t sm100_d128_fprop_flags_len = sizeof(sm100_d128_fprop_flags) - 1;
+
+} // namespace generated
+} // namespace experimental
+} // namespace cudnn_frontend
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d64_fprop_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d64_fprop_kernel.h
new file mode 100644
index 0000000..33b9ef2
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d64_fprop_kernel.h
@@ -0,0 +1,3481 @@
+// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+#pragma once
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Woverlength-strings"
+#endif
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4068)
+#endif
+namespace cudnn_frontend {
+namespace experimental {
+namespace generated {
+inline constexpr const char sm100_d64_fprop_source[] =
+ R"KERNEL(
+
+// receive_op 0 includes
+typedef unsigned long long uint64_t;
+typedef unsigned int uint32_t;
+typedef unsigned short uint16_t;
+typedef unsigned char uint8_t;
+typedef long long int64_t;
+typedef int int32_t;
+typedef short int16_t;
+typedef signed char int8_t;
+typedef unsigned int r32;
+
+struct CUtensorMap {
+ alignas(64) uint64_t opaque[16];
+};
+
+#define __FLT_MIN__ 1.17549435082228750796873653722224568e-38F
+#define __FLT_MAX__ 3.40282346638528859811704183484516925e+38F
+
+#define CUDACC_VERSION __CUDACC_VER_MAJOR__ * 10 + __CUDACC_VER_MINOR__
+
+namespace fort {
+static const uint64_t AMPERE_MEM_DESC_DEFAULT = uint64_t(0x1000000000000000ul);
+static const uint64_t MEM_DESC_DEFAULT = AMPERE_MEM_DESC_DEFAULT;
+static const uint32_t MMA_PEER_BIT_MASK = 0xFEFFFFFF;
+
+#define NAN __int_as_float(0x7fffffff)
+#define POS_INFINITY __int_as_float(0x7f800000)
+#define NEG_INFINITY __int_as_float(0xff800000)
+
+typedef uint16_t bfloat16_t;
+
+#define FORT_MIN(a, b) ((a) < (b) ? (a) : (b))
+#define FORT_MAX(a, b) ((a) > (b) ? (a) : (b))
+#define FORT_DIV_UP(a, b) (((a) + (b) - 1) / (b))
+#define FORT_ROUND_UP(a, b) ((((a) + (b) - 1) / (b)) * (b))
+
+typedef struct tensor_descriptor {
+ static const int MAX_DIMS = 12;
+
+ int64_t num_dims;
+ int64_t dims[MAX_DIMS];
+ int64_t strides[MAX_DIMS];
+} tensor_descriptor;
+
+typedef struct FastDivisor {
+ uint32_t val, shr, mul;
+} FastDivisor_t;
+
+inline __device__ void fastDivMod(const FastDivisor_t &d, uint32_t val,
+ uint32_t &div, uint32_t &mod) {
+ div = __umulhi((uint32_t)2 * val, d.mul) >> d.shr;
+ mod = val - div * d.val;
+}
+
+inline __device__ char *get_smem_loc_epilogue_swizzle_128b(
+ char *smem_addr, int local_block_id, int tid, int local_row, int column,
+ size_t element_size, int block_size, int row_per_tile) {
+ if (element_size * block_size == 256) {
+ // Case 1: 2 * swizzle tile size = block size -> half block per swizzle tile
+ int swizzle_col = local_row ^ (column % 8);
+
+ // (local_block_id * 2 + (column / 8)) * row_per_tile * 128: gives offset of
+ // corresponding swizzle tile tid * 128: tid gives number of loads in block
+ // swizzle_col * 16B: swizzle_col gives transformed column
+ return smem_addr +
+ (local_block_id * 2 + (column / 8)) * row_per_tile * 128 +
+ tid * 128 + swizzle_col * 16;
+ } else if (element_size * block_size == 128) {
+ // Case 2: swizzle tile size = block size -> one block per swizzle tile
+ int swizzle_col = local_row ^ (column % 8);
+
+ // local_block_id * row_per_tile * 128: gives offset of corresponding
+ // swizzle tile tid * 128: tid gives number of loads in block swizzle_col *
+ // 16B: swizzle_col gives transformed column
+ return smem_addr + local_block_id * row_per_tile * 128 + tid * 128 +
+ swizzle_col * 16;
+ } else {
+ // Case 3: swizzle tile size / 2 = block size -> two blocks per swizzle tile
+ int swizzle_col = local_row ^ ((column + local_block_id * 4) % 8);
+
+ // (local_block_id / 2) * row_per_tile * 128: gives offset of corresponding
+ // swizzle tile tid * 128: tid gives number of loads in block swizzle_col *
+ // 16B: swizzle_col gives transformed column
+ return smem_addr + (local_block_id / 2) * row_per_tile * 128 + tid * 128 +
+ swizzle_col * 16;
+ }
+}
+
+inline __device__ static void get_next_block_id(uint32_t result,
+ uint32_t mbar) {
+#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300
+ asm volatile("{clusterlaunchcontrol.try_cancel.async.shared::cta.mbarrier::"
+ "complete_tx::bytes.b128 [%0], [%1];}\n\t" ::"r"(result),
+ "r"(mbar));
+#else
+ asm volatile(
+ "{clusterlaunchcontrol.try_cancel.async.shared::cta.mbarrier::complete_"
+ "tx::bytes.multicast::cluster::all.b128 [%0], [%1];}\n\t" ::"r"(result),
+ "r"(mbar));
+#endif
+}
+
+inline __device__ float2 ffma2(const float2 &a, const float2 &b,
+ const float2 &c) {
+ uint64_t d;
+ asm volatile("fma.rn.f32x2 %0, %1, %2, %3;\n"
+ : "=l"(d)
+ : "l"(reinterpret_cast<const uint64_t &>(a)),
+ "l"(reinterpret_cast<const uint64_t &>(b)),
+ "l"(reinterpret_cast<const uint64_t &>(c)));
+ return reinterpret_cast<float2 &>(d);
+}
+
+inline __device__ float2 fadd2(const float2 &a, const float2 &b) {
+ uint64_t c;
+ asm volatile("add.f32x2 %0, %1, %2;\n"
+ : "=l"(c)
+ : "l"(reinterpret_cast<const uint64_t &>(a)),
+ "l"(reinterpret_cast<const uint64_t &>(b)));
+ return reinterpret_cast<float2 &>(c);
+}
+
+inline __device__ float2 fmul2(const float2 &a, const float2 &b) {
+ uint64_t c;
+ asm volatile("mul.f32x2 %0, %1, %2;\n"
+ : "=l"(c)
+ : "l"(reinterpret_cast<const uint64_t &>(a)),
+ "l"(reinterpret_cast<const uint64_t &>(b)));
+ return reinterpret_cast<float2 &>(c);
+}
+
+inline __device__ float fmax3(float a, float b, float c) {
+#if (__CUDACC_VER_MAJOR__ >= 13)
+ float d;
+ asm volatile("max.ftz.f32 %0, %1, %2, %3;\n"
+ : "=f"(d)
+ : "f"((a)), "f"((b)), "f"((c)));
+ return d;
+#else
+ #error "This kernel is not supported for CUDA toolkit version < 13.0"
+ return 0.0f;
+#endif
+}
+
+inline __device__ float row_max_reduction_128_elems(uint32_t reg[128]) {
+ float tmp_max_0[42];
+ float tmp_max_1[14];
+ float tmp_max_2[5];
+ float tmp_max_3[2];
+
+#pragma unroll
+ for (int i = 0; i < 126; i += 3) {
+ tmp_max_0[i / 3] = fmax3(reinterpret_cast<float &>(reg[i + 0]),
+ reinterpret_cast<float &>(reg[i + 1]),
+ reinterpret_cast<float &>(reg[i + 2]));
+ }
+#pragma unroll
+ for (int i = 0; i < 42; i += 3) {
+ tmp_max_1[i / 3] =
+ fmax3(tmp_max_0[i + 0], tmp_max_0[i + 1], tmp_max_0[i + 2]);
+ }
+#pragma unroll
+ for (int i = 0; i < 12; i += 3) {
+ tmp_max_2[i / 3] =
+ fmax3(tmp_max_1[i + 0], tmp_max_1[i + 1], tmp_max_1[i + 2]);
+ }
+ tmp_max_2[4] =
+ fmax3(tmp_max_1[12], tmp_max_1[13], reinterpret_cast<float &>(reg[126]));
+ tmp_max_3[0] = fmax3(tmp_max_2[0], tmp_max_2[1], tmp_max_2[2]);
+ tmp_max_3[1] =
+ fmax3(tmp_max_2[3], tmp_max_2[4], reinterpret_cast<float &>(reg[127]));
+
+ return fmax3(tmp_max_3[0], tmp_max_3[1], tmp_max_3[1]);
+}
+
+#if __CUDA_ARCH__ >= 900
+
+inline __device__ uint32_t elect_one_sync() {
+ uint32_t pred = 0;
+ uint32_t laneid = 0;
+ asm volatile("{\n"
+ ".reg .b32 %%rx;\n"
+ ".reg .pred %%px;\n"
+ " elect.sync %%rx|%%px, %2;\n"
+ "@%%px mov.s32 %1, 1;\n"
+ " mov.s32 %0, %%rx;\n"
+ "}\n"
+ : "+r"(laneid), "+r"(pred)
+ : "r"(0xFFFFFFFF));
+ return pred;
+}
+
+template <int TARGET_REG_COUNT> inline __device__ void reg_alloc() {
+ // const int TARGET_REG_COUNT = 232; // Example values (use with reg_delloc's
+ // VALUE together): 224, 232, 208, 216
+ asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;\n"
+ :
+ : "n"(TARGET_REG_COUNT));
+}
+
+template <int TARGET_REG_COUNT> inline __device__ void reg_dealloc() {
+ // const int TARGET_REG_COUNT = 40; // Exmaple values: 56, 40, 88, 72
+ asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;\n"
+ :
+ : "n"(TARGET_REG_COUNT));
+}
+
+inline __device__ void named_barrier_arrive(uint32_t BARRIER_ID,
+ uint32_t NUM_THREADS) {
+ asm volatile("bar.arrive %0, %1;" : : "r"(BARRIER_ID), "r"(NUM_THREADS));
+}
+
+inline __device__ void named_barrier_wait(uint32_t BARRIER_ID,
+ uint32_t NUM_THREADS) {
+ asm volatile("bar.sync %0, %1;" ::"r"(BARRIER_ID), "r"(NUM_THREADS));
+}
+
+inline __device__ void tmastg_arrive() {
+ asm volatile("cp.async.bulk.commit_group;");
+}
+
+template <int Count> inline __device__ void tmastg_wait_count() {
+ asm volatile("cp.async.bulk.wait_group.read %0;" : : "n"(Count) : "memory");
+}
+
+#endif
+
+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900
+inline __device__ void smem_bar_init(uint32_t smem_ptr, uint32_t thread_count) {
+ asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;\n" ::"r"(smem_ptr),
+ "r"(thread_count));
+}
+
+inline __device__ void
+smem_bar_set_transaction_count(uint32_t smem_ptr, uint32_t expected_copy_bytes,
+ uint32_t pred = 0) {
+ asm volatile("{\n\t.reg .pred p;"
+ " \n\tsetp.eq.u32 p, %2, 1;"
+ " \n\t@p mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;"
+ " \n\t}" ::"r"(smem_ptr),
+ "r"(expected_copy_bytes), "r"(pred));
+}
+
+inline __device__ uint32_t smem_bar_peek(uint32_t smem_ptr,
+ uint32_t bar_phase) {
+ uint32_t bar_phase_out;
+ asm volatile("{\n\t.reg .pred P1;"
+ " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%1], %2;"
+ " \n\tselp.b32 %0, 1, 0, P1; \n\t}"
+ : "=r"(bar_phase_out)
+ : "r"(smem_ptr), "r"(bar_phase));
+ return bar_phase_out;
+}
+
+inline __device__ void
+wait_barrier(uint32_t smem_int_ptr,
+ int phase_bit) // Current phase bit the barrier waiting to flip
+{
+ asm volatile("{\n"
+ ".reg .pred P1;\n"
+ "LAB_WAIT:\n"
+ "mbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1;\n"
+ "@P1 bra.uni DONE;\n"
+ "bra.uni LAB_WAIT;\n"
+ "DONE:\n"
+ "}\n" ::"r"(smem_int_ptr),
+ "r"(phase_bit));
+}
+
+// Barrier arrive on local smem
+inline __device__ void arrive_barrier(uint32_t smem_addr) {
+ asm volatile("{\n\t"
+ "mbarrier.arrive.shared::cta.b64 _, [%0];\n\t"
+ "}"
+ :
+ : "r"(smem_addr));
+}
+
+#endif
+
+// Circular Buffer Index + Associated Phase
+// Assumes only one operation possible - i.e., ++
+template <uint32_t Stages_> struct PipelineState {
+public:
+ static constexpr int Stages = Stages_;
+
+ inline __device__ PipelineState(int index, int state)
+ : state_(state), index_(index) {}
+
+ inline __device__ int phase() const { return state_; }
+
+ inline __device__ int index() const { return index_; }
+
+ inline __device__ void operator++() {
+ if (Stages > 1) {
+ ++index_;
+ if (index_ == Stages) {
+ index_ = 0;
+ state_ ^= 1;
+ }
+ } else {
+ state_ ^= 1;
+ }
+ }
+
+ int state_;
+ int index_;
+};
+
+template <uint64_t MAX_SHIFT_FOR_WS, uint64_t UTCMMA_M, uint64_t UTCMMA_N,
+ uint64_t B_TRANSPOSE, uint64_t A_TRANSPOSE, uint64_t B_NEGATE,
+ uint64_t A_NEGATE, uint64_t SRC_B_TYPE, uint64_t SRC_A_TYPE,
+ uint64_t SPARSE_METADATA_FORMAT, uint64_t ACC_TYPE,
+ uint64_t SATURATE_ENABLED, uint64_t SPARSE_ENABLED,
+ uint64_t SPARSE_METADATA_ID2>
+inline __device__ constexpr uint64_t build_utcmma_instruction_desc() {
+ return (static_cast<uint64_t>(0) | (MAX_SHIFT_FOR_WS << 30) |
+ ((UTCMMA_M >> 5) << 25) | ((UTCMMA_N >> 3) << 17) |
+ (B_TRANSPOSE << 16) | (A_TRANSPOSE << 15) | (B_NEGATE << 14) |
+ (A_NEGATE << 13) | (SRC_B_TYPE << 10) | (SRC_A_TYPE << 7) |
+ (SPARSE_METADATA_FORMAT << 6) | (ACC_TYPE << 4) |
+ (SATURATE_ENABLED << 3) | (SPARSE_ENABLED << 2) |
+ (SPARSE_METADATA_ID2 << 0))
+ << 32;
+}
+)KERNEL"
+ R"KERNEL(
+
+class Smem_utcmma_descriptor {
+public:
+ inline __device__ Smem_utcmma_descriptor(uint64_t SWIZZLE_MODE,
+ uint64_t BASE_OFFSET,
+ uint64_t DESC_VERSION,
+ uint64_t BYTES_PER_LEADING_DIM,
+ uint64_t BYTES_PER_STRIDE_DIM) {
+ // ------------------------------------
+ // Setup smem descriptor for operand A:
+ // ------------------------------------
+ // Note 1: SWIZZLE_NONE = 0, SWIZZLE_128B = 2, SWIZZLE_64B = 4, SWIZZLE_32B
+ // = 6, SWIZZLE_128B_ATOM32B = 1, N/A = 3, N/A = 5, N/A = 7
+ const uint64_t SWIZZLE_MODE_IN_BIT_LOCATION = SWIZZLE_MODE
+ << 61; // bits: 63-61
+
+ // Note 2: Base offset. Valid only for matrix descriptor 1, 2 or 3, 4
+ const uint64_t BASE_OFFSET_IN_BIT_LOCATION = BASE_OFFSET
+ << 49; // bits 51-49
+
+ // Note 3: Descriptor version, needs to be set to 1. ???
+ const uint64_t DESC_VERSION_IN_BIT_LOCATION = DESC_VERSION
+ << 46; // bits 48-46
+
+ // Note 4: Stride dimension byte offset, 16 byte aligned, 4 LSBs not
+ // included
+ const uint64_t STRIDE_DIM_BYTE_OFFSET = BYTES_PER_STRIDE_DIM >> 4;
+ const uint64_t STRIDE_DIM_BYTE_OFFSET_IN_BIT_LOCATION =
+ STRIDE_DIM_BYTE_OFFSET << 32; // bits 45-32
+
+ // Note 5: Leading dimension byte offset, 16 byte aligned, 4 LSBs not
+ // included
+ const uint64_t LEADING_DIM_BYTE_OFFSET = BYTES_PER_LEADING_DIM >> 4;
+ const uint64_t LEADING_DIM_BYTE_OFFSET_IN_BIT_LOCATION =
+ LEADING_DIM_BYTE_OFFSET << 16; // bits 29-16
+
+ desc =
+ (SWIZZLE_MODE_IN_BIT_LOCATION | BASE_OFFSET_IN_BIT_LOCATION |
+ DESC_VERSION_IN_BIT_LOCATION | STRIDE_DIM_BYTE_OFFSET_IN_BIT_LOCATION |
+ LEADING_DIM_BYTE_OFFSET_IN_BIT_LOCATION);
+ }
+ template <int BYTES_PER_BUFFER, int BUFFER_COUNT>
+ inline __device__ void set_smem(uint32_t smem) {
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+ tmp.x |= (static_cast<uint64_t>(smem & 0xFFFFFF) >> 4);
+
+ int2 &tmp_initial = reinterpret_cast<int2 &>(initial_desc);
+ tmp_initial.x = tmp.x;
+
+ max_desc = tmp.x + (BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1);
+ }
+
+ template <int BYTES_PER_BUFFER, int BUFFER_COUNT>
+ inline __device__ void increment_smem_buffer() {
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+ tmp.x += (tmp.x >= max_desc) ? -(BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1)
+ : (BYTES_PER_BUFFER >> 4);
+ }
+
+ template <int BYTES_PER_BUFFER>
+ inline __device__ void stage_increment_smem_buffer(int stage) {
+ int2 &tmp_initial = reinterpret_cast<int2 &>(initial_desc);
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+
+ tmp.x = tmp_initial.x + (BYTES_PER_BUFFER >> 4) * stage;
+ }
+
+ template <int BYTES_OFFSET> inline __device__ void add_smem_offset() {
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+ tmp.x += (BYTES_OFFSET >> 4);
+ }
+
+ uint64_t initial_desc;
+ uint64_t desc;
+ uint32_t max_desc;
+};
+
+// Adapted from :
+// cta1 utcmma with A and B from smem and C stored in tmem, scale denotes if we
+// want to accumulate C or not Something like: Accumulate or overwrite C. 1:
+// read C, 0: ignore C [clear accumulators]
+inline __device__ void
+utcmma_asmem_bsmem_h_cta1(uint64_t sdescA, uint64_t sdescB, uint32_t tmemC,
+ uint64_t idescE, uint32_t scaleC) {
+ uint32_t mask[4] = {0, 0, 0, 0}; // TODO : Figure out what this mask means,
+ // CUTLASS hardcodes to all zeros
+ asm volatile("{\n\t"
+ ".reg .pred p;\n\t"
+ "setp.ne.b32 p, %4, 0;\n\t"
+ "tcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, {%5, %6, "
+ "%7, %8}, p; \n\t"
+ "}\n"
+ :
+ : "r"(tmemC), "l"(sdescA), "l"(sdescB),
+ "r"(uint32_t(idescE >> 32)), "r"(scaleC), "r"(mask[0]),
+ "r"(mask[1]), "r"(mask[2]), "r"(mask[3]));
+}
+
+// cta1 utcmma with A from tmem and B from smem and C stored in tmem, scale
+// denotes if we want to accumulate C or not Something like: Accumulate or
+// overwrite C. 1: read C, 0: ignore C [clear accumulators]
+inline __device__ void
+utcmma_atmem_bsmem_h_cta1(uint32_t tmemA, uint64_t sdescB, uint32_t tmemC,
+ uint64_t idescE, uint32_t scaleC) {
+ uint32_t mask[4] = {0, 0, 0, 0}; // TODO : Figure out what this mask means,
+ // CUTLASS hardcodes to all zeros
+ asm volatile("{\n\t"
+ ".reg .pred p;\n\t"
+ "setp.ne.b32 p, %4, 0;\n\t"
+ "tcgen05.mma.cta_group::1.kind::f16 [%0], [%1], %2, %3, {%5, "
+ "%6, %7, %8}, p; \n\t"
+ "}\n"
+ :
+ : "r"(tmemC), "r"(tmemA), "l"(sdescB),
+ "r"(uint32_t(idescE >> 32)), "r"(scaleC), "r"(mask[0]),
+ "r"(mask[1]), "r"(mask[2]), "r"(mask[3]));
+}
+
+// Check for the utcmma to finish
+inline __device__ void umma_arrive(uint32_t bar_intptr) {
+ asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::"
+ "cluster.b64 [%0];" ::"r"(bar_intptr));
+}
+
+inline __device__ uint32_t cast_smem_ptr_to_uint(void const *const ptr) {
+ return static_cast<uint32_t>(__cvta_generic_to_shared(ptr));
+}
+
+inline __device__ void fence_view_async_shared(void) {
+ asm volatile("fence.proxy.async.shared::cta;\n");
+}
+
+inline __device__ void sts_128(r32 dst, r32 src[4]) {
+ asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};\n" ::"r"(dst),
+ "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]));
+}
+
+inline __device__ void lds_128(r32 dst[4], r32 src) {
+ asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];\n"
+ : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3])
+ : "r"(src));
+}
+
+inline __device__ void lds_32(r32 dst[1], r32 src) {
+ asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst[0]) : "r"(src));
+}
+
+inline __device__ void stg_32(void *ptr, r32 val[1]) {
+ uint32_t *p = reinterpret_cast<uint32_t *>(ptr);
+ p[0] = val[0];
+}
+
+inline __device__ void stg_8(void *ptr, r32 val[1]) {
+ uint8_t *p = reinterpret_cast<uint8_t *>(ptr);
+ p[0] = reinterpret_cast<const uint8_t &>(val[0]);
+}
+
+inline __device__ void ldg_16(r32 dst[1], const void *ptr, bool pred = true) {
+ if (pred) {
+ *reinterpret_cast<uint16_t *>(dst) =
+ *reinterpret_cast<const uint16_t *>(ptr);
+ } else {
+ *reinterpret_cast<uint16_t *>(dst) = 0;
+ }
+}
+
+inline __device__ void ldg_8(r32 dst[1], const void *ptr, bool pred = true) {
+ if (pred) {
+ *reinterpret_cast<uint8_t *>(dst) = *reinterpret_cast<const uint8_t *>(ptr);
+ } else {
+ *reinterpret_cast<uint8_t *>(dst) = 0;
+ }
+}
+
+inline __device__ void ldg_16_reg(r32 dst[1], const void *ptr,
+ bool pred = true) {
+ if (pred) {
+ uint16_t tmp = *reinterpret_cast<const uint16_t *>(ptr);
+ asm volatile("{\nmov.b32 %0, {%1, %1};\n}\n" : "=r"(dst[0]) : "h"(tmp));
+ } else {
+ dst[0] = 0;
+ }
+}
+
+inline __device__ void ldg_8_reg(r32 dst[1], const void *ptr,
+ bool pred = true) {
+ if (pred) {
+ uint8_t tmp_val = *reinterpret_cast<const uint8_t *>(ptr);
+ uint8_t *tmp_ptr = reinterpret_cast<uint8_t *>(dst);
+ tmp_ptr[0] = tmp_ptr[1] = tmp_ptr[2] = tmp_ptr[3] = tmp_val;
+ } else {
+ dst[0] = 0;
+ }
+}
+
+// Forward (non-ReLU) Activations
+// Backward (non-ReLU) Activations
+// Forward ReLU activations
+// Relu helper function: clip the lower part
+// Relu helper function: clip the upper part
+// Forward ReLU: clip only lower part
+// Forward ReLU: clip lower part and upper part
+// Forward ReLU: clip only lower part, but add slope to lower clip
+// Forward ReLU: clip lower part and upper part, but add slope to lower clip
+#if __CUDA_ARCH__ >= 900
+#endif
+
+// optimization opportunity exists here
+inline __device__ void fp32x2_to_fp16x2(r32 dst[1], const r32 src[2]) {
+ asm volatile("cvt.rn.f16x2.f32 %0, %1, %2;\n"
+ : "=r"(dst[0])
+ : "r"(src[1]), "r"(src[0]));
+}
+
+inline __device__ void fp32x2_to_fp16x2_relu(r32 dst[1], const r32 src[2]) {
+ asm volatile("cvt.rn.relu.f16x2.f32 %0, %1, %2;\n"
+ : "=r"(dst[0])
+ : "r"(src[1]), "r"(src[0]));
+}
+
+inline __device__ void fp32x2_to_bf16x2(r32 dst[1], const r32 src[2]) {
+ asm volatile("cvt.rn.bf16x2.f32 %0, %1, %2;\n"
+ : "=r"(dst[0])
+ : "r"(src[1]), "r"(src[0]));
+}
+
+// mma_pipeline_op 1 includes
+typedef struct AttentionDescriptor {
+ // Input parameters
+ // b - batch
+ // q_h - num heads of q/dq/o/do
+ // k_h - num heads of k/dk
+ // v_h - num heads of v/dv
+ // s_q - max sequence length of q
+ // s_kv - max sequence length of kv
+ // d - hidden dim (head dim)
+ uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v;
+ uint16_t q_heads_per_k, q_heads_per_v, min_q_heads_per_kv;
+} AttentionDescriptor_t;
+
+
+inline __device__ void fence_view_async_tmem_load() {
+ asm volatile("{\n\ttcgen05.wait::ld.sync.aligned; \n}" ::);
+}
+
+inline __device__ void fence_view_async_tmem_store() {
+ asm volatile("{\n\ttcgen05.wait::st.sync.aligned; \n}" ::);
+}
+
+inline __device__ void tmem_allocate_1sm(uint32_t num_columns,
+ uint32_t smem_addr) {
+ asm volatile(
+ "tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(
+ smem_addr),
+ "r"(num_columns));
+}
+
+inline __device__ void tmem_free_1sm(uint32_t num_columns, uint32_t tmem_addr) {
+ asm volatile(
+ "{\n\ttcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1; \n\t}" ::"r"(
+ tmem_addr),
+ "r"(num_columns));
+}
+
+inline __device__ void tmem_release_allocation_lock_1sm() {
+)KERNEL"
+ R"KERNEL(
+ asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::);
+}
+
+/////////////////////////////////
+/// TMEM STTM related instructions
+/////////////////////////////////
+
+// 32 data path lanes, 32-bit pattern, repeated 128 times
+// 32 data path lanes, 32-bit pattern, repeated 64 times
+// 32 data path lanes, 32-bit pattern, repeated 32 times
+inline __device__ void sttm_32dp32bit_x32(uint32_t dst, r32 src[32]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x32.b32"
+ "[%0],"
+ "{%1, %2, %3, %4,"
+ "%5, %6, %7, %8,"
+ "%9, %10, %11, %12,"
+ "%13, %14, %15, %16,"
+ "%17, %18, %19, %20,"
+ "%21, %22, %23, %24,"
+ "%25, %26, %27, %28,"
+ "%29, %30, %31, %32};\n"
+ :
+ : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]),
+ "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]),
+ "r"(src[8]), "r"(src[9]), "r"(src[10]), "r"(src[11]),
+ "r"(src[12]), "r"(src[13]), "r"(src[14]), "r"(src[15]),
+ "r"(src[16]), "r"(src[17]), "r"(src[18]), "r"(src[19]),
+ "r"(src[20]), "r"(src[21]), "r"(src[22]), "r"(src[23]),
+ "r"(src[24]), "r"(src[25]), "r"(src[26]), "r"(src[27]),
+ "r"(src[28]), "r"(src[29]), "r"(src[30]), "r"(src[31]));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 16 times
+inline __device__ void sttm_32dp32bit_x16(uint32_t dst, r32 src[16]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x16.b32"
+ "[%0],"
+ "{%1, %2, %3, %4,"
+ "%5, %6, %7, %8,"
+ "%9, %10, %11, %12,"
+ "%13, %14, %15, %16};\n"
+ :
+ : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]),
+ "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]),
+ "r"(src[8]), "r"(src[9]), "r"(src[10]), "r"(src[11]),
+ "r"(src[12]), "r"(src[13]), "r"(src[14]), "r"(src[15]));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 8 times
+inline __device__ void sttm_32dp32bit_x8(uint32_t dst, r32 src[8]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x8.b32"
+ "[%0],"
+ "{%1, %2, %3, %4,"
+ "%5, %6, %7, %8};\n"
+ :
+ : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]),
+ "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 4 times
+// 32 data path lanes, 32-bit pattern, repeated 2 times
+inline __device__ void sttm_32dp32bit_x2(uint32_t dst, r32 src[2]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x2.b32"
+ "[%0],"
+ "{%1, %2};\n"
+ :
+ : "r"(dst), "r"(src[0]), "r"(src[1]));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 1 times
+inline __device__ void sttm_32dp32bit_x1(uint32_t dst, r32 src[1]) {
+ asm volatile("tcgen05.st.sync.aligned.32x32b.x1.b32"
+ "[%0],"
+ "{%1};\n"
+ :
+ : "r"(dst), "r"(src[0]));
+}
+
+/////////////////////////////////
+/// TMEM LDTM related instructions
+/////////////////////////////////
+
+// 32 data path lanes, 32-bit pattern, repeated 128 times
+// 32 data path lanes, 32-bit pattern, repeated 64 times
+// 32 data path lanes, 32-bit pattern, repeated 32 times
+inline __device__ void ldtm_32dp32bit_x32(r32 dst[32], uint32_t src_addr) {
+ asm volatile("tcgen05.ld.sync.aligned.32x32b.x32.b32"
+ "{%0, %1, %2, %3,"
+ "%4, %5, %6, %7,"
+ "%8, %9, %10, %11,"
+ "%12, %13, %14, %15,"
+ "%16, %17, %18, %19,"
+ "%20, %21, %22, %23,"
+ "%24, %25, %26, %27,"
+ "%28, %29, %30, %31},"
+ "[%32];\n"
+ : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]),
+ "=r"(dst[4]), "=r"(dst[5]), "=r"(dst[6]), "=r"(dst[7]),
+ "=r"(dst[8]), "=r"(dst[9]), "=r"(dst[10]), "=r"(dst[11]),
+ "=r"(dst[12]), "=r"(dst[13]), "=r"(dst[14]), "=r"(dst[15]),
+ "=r"(dst[16]), "=r"(dst[17]), "=r"(dst[18]), "=r"(dst[19]),
+ "=r"(dst[20]), "=r"(dst[21]), "=r"(dst[22]), "=r"(dst[23]),
+ "=r"(dst[24]), "=r"(dst[25]), "=r"(dst[26]), "=r"(dst[27]),
+ "=r"(dst[28]), "=r"(dst[29]), "=r"(dst[30]), "=r"(dst[31])
+ : "r"(src_addr));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 16 times
+// 32 data path lanes, 32-bit pattern, repeated 8 times
+inline __device__ void ldtm_32dp32bit_x8(r32 dst[8], uint32_t src_addr) {
+ asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32"
+ "{%0, %1, %2, %3,"
+ "%4, %5, %6, %7},"
+ "[%8];\n"
+ : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]),
+ "=r"(dst[4]), "=r"(dst[5]), "=r"(dst[6]), "=r"(dst[7])
+ : "r"(src_addr));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 4 times
+// 32 data path lanes, 32-bit pattern, repeated 2 times
+inline __device__ void ldtm_32dp32bit_x2(r32 dst[2], uint32_t src_addr) {
+ asm volatile("tcgen05.ld.sync.aligned.32x32b.x2.b32"
+ "{%0, %1},"
+ "[%2];\n"
+ : "=r"(dst[0]), "=r"(dst[1])
+ : "r"(src_addr));
+}
+
+// 32 data path lanes, 32-bit pattern, repeated 1 times
+inline __device__ void ldtm_32dp32bit_x1(r32 dst[1], uint32_t src_addr) {
+ asm volatile("tcgen05.ld.sync.aligned.32x32b.x1.b32"
+ "{%0},"
+ "[%1];\n"
+ : "=r"(dst[0])
+ : "r"(src_addr));
+}
+
+// CUtensorMap, when issued using bulk copy async functions, are cached in
+// constant cache. But the producer kernel may have directly written to global
+// memory, without invalidating this constant cache. This acquire fence,
+// invalidates the memory address in constant cache, using UTMACCTL.IV.
+inline __device__ void tma_descriptor_fence_acquire(CUtensorMap const *p_desc) {
+#if (__CUDA_ARCH__ >= 900) && (CUDACC_VERSION >= 123)
+ uint64_t gmem_int_desc = reinterpret_cast<uint64_t>(p_desc);
+ asm volatile("fence.proxy.tensormap::generic.acquire.gpu [%0], 128;\n"
+ :
+ : "l"(gmem_int_desc)
+ : "memory");
+ asm volatile("cvta.global.u64 %0, %0;\n"
+ :
+ : "l"(gmem_int_desc), "l"(gmem_int_desc)
+ : "memory");
+#endif
+}
+
+inline __device__ void
+utmaldg_4d_tiled(const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300
+ asm volatile(
+ "cp.async.bulk.tensor.4d.shared::cta.global.mbarrier::complete_tx::"
+ "bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::"r"(
+ urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1), "l"(mem_desc)
+ : "memory");
+#else
+ asm volatile(
+ "cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::"
+ "bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::"r"(
+ urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1), "l"(mem_desc)
+ : "memory");
+#endif
+ }
+}
+
+inline __device__ void
+utmaldg_4d_tiled_multicast(const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint16_t mcast_mask, const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+ asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::"
+ "complete_tx::bytes.multicast::cluster.L2::cache_hint [%0], "
+ "[%1, {%2, %3, %4, %5}], [%6], %7, %8;\n" ::"r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1), "h"(mcast_mask), "l"(mem_desc)
+ : "memory");
+ }
+}
+
+#if (__CUDA_ARCH__ >= 1000) && (CUDACC_VERSION >= 128)
+inline __device__ void
+utmaldg_4d_tiled_2cta(const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+ asm volatile("cp.async.bulk.tensor.4d.cta_group::2.shared::cluster.global."
+ "mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, "
+ "%3, %4, %5}], [%6], %7;\n" ::"r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1 & MMA_PEER_BIT_MASK),
+ "l"(mem_desc)
+ : "memory");
+ }
+}
+
+inline __device__ void
+utmaldg_4d_tiled_multicast_2cta(const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint16_t mcast_mask,
+ const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+ asm volatile(
+ "cp.async.bulk.tensor.4d.cta_group::2.shared::cluster.global.mbarrier::"
+ "complete_tx::bytes.multicast::cluster.L2::cache_hint [%0], [%1, {%2, "
+ "%3, %4, %5}], [%6], %7, %8;\n" ::"r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3),
+ "r"(urb4), "r"(urb5), "r"(urb1 & MMA_PEER_BIT_MASK), "h"(mcast_mask),
+ "l"(mem_desc)
+ : "memory");
+ }
+}
+#endif
+
+inline __device__ void
+utmastg_atomicAdd_4d_tiled(const void *p_desc, uint32_t smem_offset,
+ int32_t urb0, // m
+ int32_t urb1, // n
+ int32_t urb2, // h
+ int32_t urb3, // b
+ const uint32_t elect_one,
+ uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ if (elect_one) {
+ asm volatile(
+ "cp.reduce.async.bulk.tensor.4d.global.shared::cta.add.bulk_group [%0, "
+ "{%1, %2, %3, %4}], [%5];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(smem_offset)
+ : "memory");
+ }
+}
+
+inline __device__ void utmastg_4d_tiled(const void *p_desc,
+ uint32_t smem_offset,
+ int32_t urb0, // m
+ int32_t urb1, // n
+ int32_t urb2, // h
+ int32_t urb3, // b
+ uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ asm volatile(
+ "cp.async.bulk.tensor.4d.global.shared::cta.bulk_group [%0, {%1, %2, %3, "
+ "%4}], [%5];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(smem_offset)
+ : "memory");
+}
+
+inline __device__ void utmastg_5d_tiled(const void *p_desc,
+ uint32_t smem_offset,
+ int32_t urb0, // m
+ int32_t urb1, // n
+ int32_t urb2, // h
+ int32_t urb3, // b
+ int32_t urb4, // lean_tile_id
+ uint64_t mem_desc = MEM_DESC_DEFAULT) {
+ asm volatile(
+ "cp.async.bulk.tensor.5d.global.shared::cta.bulk_group [%0, {%1, %2, %3, "
+ "%4, %5}], [%6];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(urb4), "r"(smem_offset)
+ : "memory");
+}
+
+// mma_loop_op 2 includes
+
+// global_load_shared_store_op 4 includes
+
+// shared_load_op 5 includes
+
+// shared_load_op 6 includes
+
+// global_load_shared_store_op 7 includes
+
+// mma_op 8 includes
+
+// global_load_op 10 includes
+
+// pointwise_calc_op 9 includes
+
+// softmax_op 12 includes
+
+// global_store_op 13 includes
+
+// global_store_op 14 includes
+
+// shared_load_op 15 includes
+
+// global_load_shared_store_op 16 includes
+
+// mma_op 17 includes
+
+// global_store_op 20 includes
+
+// output_loop_op 3 includes
+
+// shared_store_op 18 includes
+
+// shared_load_op 19 includes
+} // namespace fort
+)KERNEL"
+ R"KERNEL(
+
+// receive_op 0 types
+using namespace fort;
+
+static constexpr int THREADS_PER_WARP_0 = 32;
+static constexpr int WARPS_PER_GROUP_0 = FORT_MIN(4, 512 / THREADS_PER_WARP_0);
+static constexpr int THREADS_PER_WARP_GROUP_0 =
+ THREADS_PER_WARP_0 * WARPS_PER_GROUP_0;
+static constexpr int BITS_PER_REGISTER_0 = 32; // NOTE: sizeof(uint)
+static constexpr int BYTES_PER_REGISTER_0 = BITS_PER_REGISTER_0 / 8;
+static constexpr int THREADS_PER_GROUP_0 =
+ WARPS_PER_GROUP_0 * THREADS_PER_WARP_0;
+
+// mma_pipeline_op 1 types
+static constexpr int BYTES_PER_BANK_1 = 16;
+static constexpr int BITS_PER_ELEMENT_1 = 16;
+static constexpr int ELEMS_PER_BANK_1 =
+ BYTES_PER_BANK_1 * 8 / BITS_PER_ELEMENT_1;
+static constexpr int BYTES_PER_ELEMENT_1 = BITS_PER_ELEMENT_1 / 8;
+static constexpr int BYTES_PER_FP16_1 = 2;
+static constexpr int ELEMS_PER_VECTOR_1 =
+ BYTES_PER_REGISTER_0 / BYTES_PER_ELEMENT_1;
+static constexpr int BITS_PER_ACC_1 = 32;
+static constexpr int BYTES_PER_ACC_1 = BITS_PER_ACC_1 / 8;
+static constexpr int TILE_M_1 = 128;
+static constexpr int TILE_N_1 = 128;
+static constexpr int TILE_K_1 = 64;
+static constexpr int TILE_O_1 = FORT_MIN(TILE_K_1, 128);
+static constexpr int TILE_V_1 = TILE_K_1;
+static constexpr int TILE_DV_1 = FORT_MIN(TILE_K_1, 128);
+static constexpr int WARP_TILE_M_1 = 16;
+static constexpr int WARP_TILE_N_1 = 16;
+static constexpr int WARP_TILE_K_1 = 32 / BYTES_PER_ELEMENT_1;
+static constexpr int WARPS_M_1 = 64 / 16;
+static constexpr int WARPS_N_1 = 16 / 16;
+static constexpr int WARPS_K_1 = 16 / 16;
+static constexpr int STAGES_1 = 1;
+static constexpr int GROUPS_M_1 = 1;
+static constexpr int GMMA_TILE_M_1 = WARPS_M_1 * WARP_TILE_M_1;
+static constexpr int GMMA_TILE_K_1 = WARPS_K_1 * WARP_TILE_K_1;
+static constexpr int WARP_TILES_M_1 = TILE_M_1 / WARP_TILE_M_1;
+static constexpr int WARP_TILES_N_1 = TILE_N_1 / WARP_TILE_N_1;
+static constexpr int WARP_TILES_K_1 = TILE_K_1 / WARP_TILE_K_1;
+static constexpr int WARP_REGS_1 = TILE_N_1;
+static constexpr int REGS_M_1 = WARP_TILES_M_1 / WARPS_M_1;
+static constexpr int REGS_N_1 = WARP_TILES_N_1 / WARPS_N_1;
+static constexpr int REGS_K_1 = WARP_TILES_K_1 / WARPS_K_1;
+static constexpr int REGS_K_FOR_DP_1 = TILE_V_1 / 16;
+static constexpr int REGS_dQ_1 = TILE_O_1 / 16;
+static constexpr int REGS_O_1 = REGS_K_1 * 1;
+
+static constexpr int CGA_M_1 = 1;
+static constexpr int CGA_N_1 = 1;
+static constexpr int CTA_MMA_1 = 1;
+static constexpr int M_TILES_PER_OUTPUT_TILE_1 = 4;
+static constexpr int N_TILES_PER_OUTPUT_TILE_1 = 1;
+
+static constexpr int CTA_TILE_M_1 = TILE_M_1;
+static constexpr int CTA_TILE_N_1 = 64;
+static constexpr int CTA_TILE_K_1 = 128;
+
+static constexpr float ln2 = 0.6931471805599453094f;
+static constexpr float inv_ln2 = 1.4426950408889634074f;
+
+static constexpr uint32_t SchedulerPipelineStageCount = 1;
+static constexpr uint32_t AccumulatorPipelineStageCount = 1;
+static constexpr uint32_t SmemPipelineStageCount = 1;
+static constexpr uint32_t num_columns_per_tmem = 512;
+static constexpr uint32_t columns_per_allocation_slice = 32;
+static constexpr int stages_q = 2;
+static constexpr int stages_kv = 2 * CTA_MMA_1;
+static constexpr int Tiles_Q = 2;
+
+static constexpr int SoftmaxWarpGroups = 2;
+static constexpr int CorrectionWarpGroups = 1;
+static constexpr int SoftmaxWarps = SoftmaxWarpGroups * 4;
+static constexpr int CorrectionWarps = 4;
+
+static constexpr int MmaWarpRegs = 40; // warp 12
+static constexpr int TmaldgWarpRegs = 40; // warp 13
+static constexpr int TmastgWarpRegs = 40; // warp 14
+static constexpr int SchedulerWarpRegs = 40; // warp 15
+static constexpr int CorrectionWarpRegs = 88; // warps 8-11
+static constexpr int SoftmaxWarpRegs = 192; // warps 0-7
+
+static constexpr int threads_per_warp = 32;
+static constexpr int warps_per_group = 4;
+static constexpr int threads_per_group = threads_per_warp * warps_per_group;
+static constexpr int threads_per_cta =
+ threads_per_warp * (warps_per_group + SoftmaxWarps + CorrectionWarps);
+
+static constexpr int BUFFERS_Q = stages_q;
+static constexpr int BUFFERS_K = stages_kv;
+static constexpr int BUFFERS_V = stages_kv;
+static constexpr int BUFFERS_S = stages_kv;
+
+using ElementQ = fort::bfloat16_t;
+using ElementK = fort::bfloat16_t;
+using ElementV = fort::bfloat16_t;
+using ElementS = fort::bfloat16_t;
+using ElementO = fort::bfloat16_t;
+using ElementAccumulator = float;
+
+static constexpr int BYTES_PER_ELEMENT = 2;
+static constexpr int BYTES_PER_ACC = 4;
+
+static constexpr int BMM1_TILE_M = TILE_M_1;
+static constexpr int BMM1_TILE_N = 128;
+static constexpr int BMM1_TILE_K = 64;
+
+static constexpr int BMM2_TILE_M = TILE_M_1;
+static constexpr int BMM2_TILE_N = 64;
+static constexpr int BMM2_TILE_K = 128;
+
+static constexpr uint32_t qBufferElems = BMM1_TILE_M * BMM1_TILE_K;
+static constexpr uint32_t kBufferElems = BMM1_TILE_N * BMM1_TILE_K / CTA_MMA_1;
+static constexpr uint32_t vBufferElems = BMM2_TILE_N * BMM2_TILE_K / CTA_MMA_1;
+static constexpr uint32_t oBufferElems =
+ FORT_MAX(8, BMM2_TILE_M) * (BMM2_TILE_N + 0);
+static constexpr uint32_t sBufferElems = FORT_MAX(8, BMM1_TILE_M) * BMM1_TILE_N;
+
+static constexpr uint32_t qTmaTransactionBytes =
+ qBufferElems * sizeof(ElementQ) * CTA_MMA_1;
+static constexpr uint32_t kTmaTransactionBytes =
+ kBufferElems * sizeof(ElementK) * CTA_MMA_1;
+static constexpr uint32_t vTmaTransactionBytes =
+ vBufferElems * sizeof(ElementV) * CTA_MMA_1;
+
+static constexpr int UTCMMA_TILE_M = 128;
+static constexpr int UTCMMA_TILE_N = 128;
+static constexpr int UTCMMA_TILE_K = 32 / BYTES_PER_ELEMENT;
+
+static constexpr int BMM1_XMMAS_K = BMM1_TILE_K / UTCMMA_TILE_K;
+static constexpr int BMM2_XMMAS_K = BMM2_TILE_K / UTCMMA_TILE_K;
+static constexpr int BYTES_PER_MMA_K = UTCMMA_TILE_K * BYTES_PER_ELEMENT;
+
+static constexpr int SMEM_BUFFER_SIZE_Q =
+ BMM1_TILE_M * BMM1_TILE_K * BYTES_PER_ELEMENT;
+static constexpr int SMEM_BUFFER_SIZE_K =
+ BMM1_TILE_N * BMM1_TILE_K * BYTES_PER_ELEMENT / CTA_MMA_1;
+static constexpr int SMEM_BUFFER_SIZE_V =
+ BMM2_TILE_N * BMM2_TILE_K * BYTES_PER_ELEMENT / CTA_MMA_1;
+static constexpr int SMEM_BUFFER_SIZE_S =
+ FORT_MAX(8, BMM1_TILE_M) * BMM1_TILE_N * BYTES_PER_ELEMENT;
+
+static constexpr int SOFTMAX_BARRIER = 1;
+static constexpr int BAND_BIAS_BARRIER = 5;
+static constexpr int TMEM_ALLOC_SOFTMAX_BARRIER = 6;
+static constexpr int TMEM_ALLOC_CORRECTION_BARRIER = 7;
+
+struct SharedStorage {
+ alignas(1024) ElementQ smem_Q[qBufferElems * stages_q];
+ alignas(1024) ElementK smem_K[kBufferElems * stages_kv];
+ alignas(1024) ElementV smem_V[vBufferElems * stages_kv];
+ alignas(1024) ElementO smem_O[oBufferElems];
+
+ alignas(16) uint64_t tma_o_0_empty_mbar[1];
+
+ alignas(16) uint64_t tma_k_empty_mbar[stages_kv];
+ alignas(16) uint64_t tma_k_full_mbar[stages_kv];
+
+ alignas(16) uint64_t tma_v_empty_mbar[stages_kv];
+ alignas(16) uint64_t tma_v_full_mbar[stages_kv];
+
+ alignas(16) uint64_t tma_q_empty_mbar[stages_q];
+ alignas(16) uint64_t tma_q_full_mbar[stages_q];
+
+ alignas(16) uint64_t bmm2_tile0_done_mbar[1];
+ alignas(16) uint64_t bmm2_tile0_ready_mbar[2];
+
+ alignas(16) uint64_t stat_tile0_full_mbar[1];
+ alignas(16) uint64_t stat_tile0_empty_mbar[1];
+ alignas(16) uint64_t final_stat_tile0_empty_mbar[1];
+ alignas(16) uint64_t
+ tma_o_0_full_mbar[FORT_DIV_UP(TILE_O_1 * sizeof(ElementO), 128)];
+ alignas(16) uint64_t
+ tma_o_1_full_mbar[FORT_DIV_UP(TILE_O_1 * sizeof(ElementO), 128)];
+
+ alignas(16) uint64_t epilogue_done_mbar[1];
+ alignas(16) uint64_t tmaldg_tile_started_mbar[1];
+
+ alignas(16) uint64_t bmm1_tile0_done_mbar[1];
+ alignas(16) uint64_t bmm1_tile1_done_mbar[1];
+
+ alignas(16) uint64_t bmm2_tile1_done_mbar[1];
+ alignas(16) uint64_t bmm2_tile1_ready_mbar[2];
+
+ alignas(16) uint64_t stat_tile1_full_mbar[1];
+ alignas(16) uint64_t stat_tile1_empty_mbar[1];
+ alignas(16) uint64_t final_stat_tile1_empty_mbar[1];
+
+ alignas(16) uint64_t empty_mainloop_mbar[1];
+
+ alignas(16) uint64_t scheduler_mbar[SchedulerPipelineStageCount];
+ alignas(16) uint64_t read_tile_id_done_mbar[SchedulerPipelineStageCount];
+ alignas(16) uint64_t tmem_dealloc_smem_bar[1];
+
+ uint32_t tmem_base_ptrs;
+
+ alignas(16) uint32_t tile_id[8 * SchedulerPipelineStageCount];
+};
+
+// global_load_shared_store_op 4 types
+static constexpr int BITS_PER_ELEMENT_4 = 16;
+static constexpr int BYTES_PER_ELEMENT_4 = BITS_PER_ELEMENT_4 / 8;
+static constexpr int BYTES_PER_ACCESS_4 = 16;
+static constexpr int TILE_M_4 = 128;
+static constexpr int TILE_N_4 = 64;
+static constexpr int BYTES_PER_SMEM_4 =
+ TILE_M_4 * TILE_N_4 * BYTES_PER_ELEMENT_4;
+
+// shared_load_op 5 types
+static constexpr int BITS_PER_ELEMENT_5 = 16;
+static constexpr int BYTES_PER_ELEMENT_5 = 2;
+static constexpr int BYTES_PER_QUAD_5 = 16;
+static constexpr int WARP_TILE_M_5 = 16;
+static constexpr int WARP_TILE_N_5 = 16;
+static constexpr int TILE_M_5 = 128;
+static constexpr int TILE_N_5 = 64;
+static constexpr int BYTES_PER_SMEM_5 =
+ TILE_M_5 * TILE_N_5 * BYTES_PER_ELEMENT_5;
+static constexpr int WARPS_M_5 = 4;
+static constexpr int WARPS_N_5 = 1;
+static constexpr int WARP_TILES_M_5 = TILE_M_5 / WARP_TILE_M_5;
+static constexpr int WARP_TILES_N_5 = TILE_N_5 / WARP_TILE_N_5;
+static constexpr int THREADS_PER_WARP_TILE_M_5 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_5 = 4;
+static constexpr int REGS_M_5 = WARP_TILES_M_5 / WARPS_M_5;
+static constexpr int REGS_N_5 = WARP_TILES_N_5 / WARPS_N_5;
+static constexpr int BYTES_PER_LD_5 = 128;
+static constexpr int SWIZZLE_SCALE_5 =
+ FORT_MIN(BYTES_PER_LD_5 / 16, WARPS_PER_GROUP_0 * 4);
+
+// shared_load_op 6 types
+static constexpr int BITS_PER_ELEMENT_6 = 16;
+static constexpr int BYTES_PER_ELEMENT_6 = 2;
+static constexpr int BYTES_PER_QUAD_6 = 16;
+static constexpr int WARP_TILE_M_6 = 16;
+static constexpr int WARP_TILE_N_6 = 16;
+static constexpr int TILE_M_6 = 128;
+static constexpr int TILE_N_6 = 64;
+static constexpr int BYTES_PER_SMEM_6 =
+ TILE_M_6 * TILE_N_6 * BYTES_PER_ELEMENT_6;
+static constexpr int WARPS_M_6 = 1;
+static constexpr int WARPS_N_6 = 1;
+static constexpr int WARP_TILES_M_6 = TILE_M_6 / WARP_TILE_M_6;
+static constexpr int WARP_TILES_N_6 = TILE_N_6 / WARP_TILE_N_6;
+static constexpr int THREADS_PER_WARP_TILE_M_6 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_6 = 4;
+static constexpr int REGS_M_6 = WARP_TILES_M_6 / WARPS_M_6;
+static constexpr int REGS_N_6 = WARP_TILES_N_6 / WARPS_N_6;
+static constexpr int BYTES_PER_LD_6 = 128;
+static constexpr int SWIZZLE_SCALE_6 =
+ FORT_MIN(BYTES_PER_LD_6 / 16, WARPS_PER_GROUP_0 * 4);
+
+// global_load_shared_store_op 7 types
+static constexpr int BITS_PER_ELEMENT_7 = 16;
+static constexpr int BYTES_PER_ELEMENT_7 = BITS_PER_ELEMENT_7 / 8;
+static constexpr int BYTES_PER_ACCESS_7 = 16;
+static constexpr int TILE_M_7 = 128;
+static constexpr int TILE_N_7 = 64;
+static constexpr int BYTES_PER_SMEM_7 =
+ TILE_M_7 * TILE_N_7 * BYTES_PER_ELEMENT_7;
+
+// mma_op 8 types
+static constexpr int ROWS_PER_CORE_MATRIX_A_8 = 8;
+static constexpr int COLS_PER_CORE_MATRIX_A_8 = 8;
+static constexpr int ROWS_PER_CORE_MATRIX_B_8 = 8;
+static constexpr int COLS_PER_CORE_MATRIX_B_8 = 8;
+
+// global_load_op 10 types
+static constexpr int BITS_PER_ELEMENT_10 = 32;
+static constexpr int BYTES_PER_ELEMENT_10 = 4;
+static constexpr int REGISTERS_PER_VECTOR_10 = 1;
+static constexpr int REGISTERS_PER_ACCESS_10 = 1;
+
+// pointwise_calc_op 9 types
+static constexpr int WARP_TILE_M_9 = 16;
+static constexpr int WARP_TILE_N_9 = 16;
+static constexpr int TILE_M_9 = 128;
+static constexpr int TILE_N_9 = 128;
+static constexpr int WARPS_M_9 = 4;
+static constexpr int WARPS_N_9 = 1;
+static constexpr int WARP_TILES_M_9 = TILE_M_9 / WARP_TILE_M_9;
+static constexpr int WARP_TILES_N_9 = TILE_N_9 / WARP_TILE_N_9;
+static constexpr int WARP_REGS_9 = WARP_REGS_1;
+static constexpr int REGS_M_9 = WARP_TILES_M_9 / WARPS_M_9;
+static constexpr int REGS_N_9 = WARP_TILES_N_9 / WARPS_N_9;
+
+// mha_mask_op 11 types
+static constexpr int WARP_TILE_M_11 = 16;
+static constexpr int WARP_TILE_N_11 = 16;
+static constexpr int TILE_M_11 = 128;
+static constexpr int TILE_N_11 = 128;
+static constexpr int WARPS_M_11 = 4;
+static constexpr int WARPS_N_11 = 1;
+static constexpr int WARP_TILES_M_11 = TILE_M_11 / WARP_TILE_M_11;
+static constexpr int WARP_TILES_N_11 = TILE_N_11 / WARP_TILE_N_11;
+static constexpr int WARP_REGS_11 = 8;
+static constexpr int REGS_M_11 = WARP_TILES_M_11 / WARPS_M_11;
+static constexpr int REGS_N_11 = WARP_TILES_N_11 / WARPS_N_11;
+inline __device__ bool compute_diagonal_band_mask_11(
+)KERNEL"
+ R"KERNEL(
+ const int row, const int col, const int actual_seqlen_kv,
+ const int actual_seqlen_q, const int shift_right_bound,
+ const int left_bound) {
+ constexpr bool is_bottom_right_alignment = false;
+ constexpr bool is_shift_right_bound = false;
+ constexpr bool is_right_bound = true;
+ constexpr bool is_left_bound = false;
+ constexpr bool need_oob_check = false;
+
+ const int diag = is_bottom_right_alignment
+ ? row + (actual_seqlen_kv - actual_seqlen_q)
+ : row;
+ const int shifted_right_bound =
+ is_shift_right_bound ? diag + shift_right_bound : diag;
+ const bool right_bound_mask =
+ is_right_bound ? col <= shifted_right_bound : true;
+ const bool left_bound_mask = is_left_bound ? col + left_bound > diag : true;
+ const bool oob_check =
+ need_oob_check ? (row < actual_seqlen_q && col < actual_seqlen_kv) : true;
+ return right_bound_mask && left_bound_mask && oob_check;
+}
+
+// softmax_op 12 types
+static constexpr int BYTES_PER_ELEMENT_12 = 2;
+static constexpr int WARP_TILE_M_12 = 16;
+static constexpr int WARP_TILE_N_12 = 16;
+static constexpr int TILE_M_12 = 128;
+static constexpr int TILE_N_12 = 128;
+static constexpr int WARPS_M_12 = 4;
+static constexpr int WARPS_N_12 = 1;
+static constexpr int WARP_TILES_M_12 = TILE_M_12 / WARP_TILE_M_12;
+static constexpr int WARP_TILES_N_12 = TILE_N_12 / WARP_TILE_N_12;
+static constexpr int THREADS_PER_WARP_TILE_M_12 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_12 = 4;
+static constexpr int WARP_REGS_12 = 8;
+static constexpr int REGS_M_12 = WARP_TILES_M_12 / WARPS_M_12;
+static constexpr int REGS_N_12 = WARP_TILES_N_12 / WARPS_N_12;
+static constexpr int ROWS_PER_THREAD_12 =
+ TILE_M_12 / WARPS_M_12 / THREADS_PER_WARP_TILE_M_12;
+
+// global_store_op 13 types
+static constexpr int BYTES_PER_ELEMENT_13 = 4;
+static constexpr int WARP_TILE_M_13 = 16;
+static constexpr int WARP_TILE_N_13 = 16;
+static constexpr int TILE_M_13 = 128;
+static constexpr int TILE_N_13 = 128;
+static constexpr int WARPS_M_13 = 4;
+static constexpr int WARPS_N_13 = 1;
+static constexpr int WARP_TILES_M_13 = TILE_M_13 / WARP_TILE_M_13;
+static constexpr int WARP_TILES_N_13 = TILE_N_13 / WARP_TILE_N_13;
+static constexpr int THREADS_PER_WARP_TILE_M_13 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_13 = 4;
+static constexpr int ROWS_PER_THREAD_13 =
+ TILE_M_13 / WARPS_M_13 / THREADS_PER_WARP_TILE_M_13;
+
+// global_store_op 14 types
+static constexpr int BYTES_PER_ELEMENT_14 = 4;
+static constexpr int WARP_TILE_M_14 = 16;
+static constexpr int WARP_TILE_N_14 = 16;
+static constexpr int TILE_M_14 = 128;
+static constexpr int TILE_N_14 = 128;
+static constexpr int WARPS_M_14 = 4;
+static constexpr int WARPS_N_14 = 1;
+static constexpr int WARP_TILES_M_14 = TILE_M_14 / WARP_TILE_M_14;
+static constexpr int WARP_TILES_N_14 = TILE_N_14 / WARP_TILE_N_14;
+static constexpr int THREADS_PER_WARP_TILE_M_14 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_14 = 4;
+static constexpr int ROWS_PER_THREAD_14 =
+ TILE_M_14 / WARPS_M_14 / THREADS_PER_WARP_TILE_M_14;
+
+// shared_load_op 15 types
+static constexpr int BITS_PER_ELEMENT_15 = 16;
+static constexpr int BYTES_PER_ELEMENT_15 = 2;
+static constexpr int BYTES_PER_QUAD_15 = 16;
+static constexpr int WARP_TILE_M_15 = 16;
+static constexpr int WARP_TILE_N_15 = 16;
+static constexpr int TILE_M_15 = 128;
+static constexpr int TILE_N_15 = 64;
+static constexpr int BYTES_PER_SMEM_15 =
+ TILE_M_15 * TILE_N_15 * BYTES_PER_ELEMENT_15;
+static constexpr int WARPS_M_15 = 1;
+static constexpr int WARPS_N_15 = 1;
+static constexpr int WARP_TILES_M_15 = TILE_M_15 / WARP_TILE_M_15;
+static constexpr int WARP_TILES_N_15 = TILE_N_15 / WARP_TILE_N_15;
+static constexpr int THREADS_PER_WARP_TILE_M_15 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_15 = 4;
+static constexpr int REGS_M_15 = WARP_TILES_M_15 / WARPS_M_15;
+static constexpr int REGS_N_15 = WARP_TILES_N_15 / WARPS_N_15;
+static constexpr int BYTES_PER_LD_15 = 128;
+static constexpr int SWIZZLE_SCALE_15 =
+ FORT_MIN(BYTES_PER_LD_15 / 16, WARPS_PER_GROUP_0 * 4);
+
+// global_load_shared_store_op 16 types
+static constexpr int BITS_PER_ELEMENT_16 = 16;
+static constexpr int BYTES_PER_ELEMENT_16 = BITS_PER_ELEMENT_16 / 8;
+static constexpr int BYTES_PER_ACCESS_16 = 16;
+static constexpr int TILE_M_16 = 128;
+static constexpr int TILE_N_16 = 64;
+static constexpr int BYTES_PER_SMEM_16 =
+ TILE_M_16 * TILE_N_16 * BYTES_PER_ELEMENT_16;
+
+// mma_op 17 types
+static constexpr int ROWS_PER_CORE_MATRIX_A_17 = 8;
+static constexpr int COLS_PER_CORE_MATRIX_A_17 = 8;
+static constexpr int ROWS_PER_CORE_MATRIX_B_17 = 8;
+static constexpr int COLS_PER_CORE_MATRIX_B_17 = 8;
+
+// global_store_op 20 types
+
+// mma_loop_op 2 types
+inline __device__ int2 compute_kv_loop_bounds(
+ const int row_coord, const int ROW_TILE_SIZE, const int COL_TILE_SIZE,
+ const int actual_seqlen_kv, const int actual_seqlen_q,
+ const int shift_right_bound, const int left_bound) {
+ constexpr bool is_right_bound = true;
+ constexpr bool is_right_bound_bottom_right_alignment = false;
+ constexpr bool is_shift_right_bound = false;
+ constexpr bool is_left_bound = false;
+ constexpr bool is_left_bound_bottom_right_alignment = false;
+
+ const int right_bound_diagonal =
+ is_right_bound_bottom_right_alignment
+ ? row_coord + (actual_seqlen_kv - actual_seqlen_q)
+ : row_coord;
+ const int shifted_right_bound_diagonal =
+ is_shift_right_bound ? right_bound_diagonal + shift_right_bound
+ : right_bound_diagonal;
+ const int left_bound_diagonal =
+ is_left_bound_bottom_right_alignment
+ ? row_coord + (actual_seqlen_kv - actual_seqlen_q)
+ : row_coord;
+
+ const int kv_loop_left_bound =
+ is_left_bound
+ ? FORT_MAX(0, (left_bound_diagonal - left_bound) / COL_TILE_SIZE)
+ : 0;
+ const int kv_loop_right_bound =
+ is_right_bound
+ ? FORT_MIN(FORT_DIV_UP(shifted_right_bound_diagonal + ROW_TILE_SIZE,
+ COL_TILE_SIZE),
+ FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE))
+ : FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE);
+ return make_int2(kv_loop_left_bound, kv_loop_right_bound);
+}
+
+// output_loop_op 3 types
+static constexpr int BYTES_PER_BANK_3 = 16;
+static constexpr int ELEMENTS_PER_VECTOR_3 =
+ FORT_MIN(64, CTA_TILE_N_1 / N_TILES_PER_OUTPUT_TILE_1);
+
+// shared_store_op 18 types
+
+// shared_load_op 19 types
+static constexpr int BITS_PER_ELEMENT_19 = 32 * 1;
+static constexpr int BYTES_PER_ELEMENT_19 = BITS_PER_ELEMENT_19 / 8;
+static constexpr int BITS_PER_VECTOR_19 =
+ BITS_PER_ELEMENT_19 * ELEMENTS_PER_VECTOR_3;
+static constexpr int BYTES_PER_VECTOR_19 = BITS_PER_VECTOR_19 / 8;
+static constexpr int REGISTERS_PER_VECTOR_19 =
+ BITS_PER_VECTOR_19 / BITS_PER_REGISTER_0;
+
+// receive_op 0 code
+
+extern "C" __global__
+__launch_bounds__(512, 1) void cudnn_generated_oss_sdpa_sm100_flash_fprop_f16_knob_7_128x128x64_4x1x1_cga1x1x1_kernel0_0(
+ const AttentionDescriptor_t attnDesc, const FastDivisor_t num_head_divmod,
+ const FastDivisor_t l2_minor_divmod, const FastDivisor_t l2_major_divmod,
+ const FastDivisor_t l2_minor_residual_divmod, const int num_hb_quotient,
+ const int num_block, const int total_blocks,
+ __grid_constant__ const CUtensorMap tma_tensor_3,
+ __grid_constant__ const CUtensorMap tma_tensor_2, float tensor_4,
+ float tensor_13, void *tensor_7, fort::tensor_descriptor desc_7,
+ void *tensor_6, fort::tensor_descriptor desc_6,
+ __grid_constant__ const CUtensorMap tma_tensor_1,
+ __grid_constant__ const CUtensorMap tma_tensor_5) {
+ asm volatile(".pragma \"global knob ForceLateCommoning=1\";\n" ::: "memory");
+ asm volatile(".pragma \"global knob HoistLate=3\";\n" ::: "memory");
+
+ extern __shared__ char smem_[];
+ SharedStorage &shared_storage = *reinterpret_cast<SharedStorage *>(smem_);
+
+ // receive_op 0 decls
+
+ // mma_pipeline_op 1 decls
+ const int tid = threadIdx.x % threads_per_group;
+ const int wid = threadIdx.x / 32;
+ const int tiw = threadIdx.x % 32;
+
+ const uint32_t elect_one = elect_one_sync();
+
+ if (wid == 0 && elect_one) {
+ smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.tma_o_0_empty_mbar[0]),
+ /* 1 tmastg */ 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]),
+ /* 4 epilogue */ warps_per_group * 32 * CTA_MMA_1);
+
+#pragma unroll
+ for (int q_stage = 0; q_stage < stages_q; q_stage++) {
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ /* 1 tma */ 1);
+ }
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32 * 2 * CTA_MMA_1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile0_full_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile0_empty_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.final_stat_tile0_empty_mbar[0]),
+ /* 4 Correction */ warps_per_group * 32 * CTA_MMA_1);
+
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * sizeof(ElementO); i += 128) {
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_0_full_mbar[i / 128]),
+ /* 1 correction */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_1_full_mbar[i / 128]),
+ /* 1 correction */ warps_per_group * 32);
+ }
+ smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]),
+ /* 1 tmastg */ 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]), 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32 * 2 * CTA_MMA_1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[1]),
+ /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[1]),
+ /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]),
+ /* 1 mma */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile1_full_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile1_empty_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.final_stat_tile1_empty_mbar[0]),
+ /* 4 Correction */ warps_per_group * 32 * CTA_MMA_1);
+
+ smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.empty_mainloop_mbar[0]),
+ /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1);
+
+#pragma unroll
+ for (int sched_steps = 0; sched_steps < SchedulerPipelineStageCount;
+ sched_steps++) {
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.scheduler_mbar[sched_steps]),
+ /* 1 sched */ 1);
+ smem_bar_init(cast_smem_ptr_to_uint(
+ &shared_storage.read_tile_id_done_mbar[sched_steps]),
+ (SoftmaxWarps + CorrectionWarps + 1 + 1) * CGA_M_1 *
+ CGA_N_1 +
+ CGA_M_1 * CGA_N_1 / CTA_MMA_1);
+ }
+
+#pragma unroll
+ for (int kv_stages = 0; kv_stages < stages_kv; kv_stages++) {
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[kv_stages]),
+ /* 1 mma */ CGA_M_1 / CTA_MMA_1 + CGA_N_1 - 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[kv_stages]),
+ /* 1 tma/32 ldgsts */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stages]),
+ /* 1 tma/32 ldgsts */ 1);
+ smem_bar_init(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[kv_stages]),
+ /* 1 mma */ CGA_M_1 / CTA_MMA_1 + CGA_N_1 - 1);
+ }
+ }
+ __syncthreads();
+
+)KERNEL"
+ R"KERNEL(
+ // mma_pipeline_op 1 code
+
+ // mma_loop_op 2 code
+ uint32_t tile_id_and_coord[8] = {0};
+
+ int actual_seqlen_kv_1 = attnDesc.s_kv;
+ int actual_seqlen_q_1 = attnDesc.s_q;
+ int q_row_coord = 0;
+ int kv_loop_right_bound, kv_loop_left_bound;
+
+ const int left_bound = 0;
+ const int shift_right_bound = 0;
+
+ uint32_t tile_idx = blockIdx.x;
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+ tile_id_and_coord[0] = head_idx;
+ tile_id_and_coord[1] = batch_idx;
+ tile_id_and_coord[2] = block;
+ tile_id_and_coord[3] = 1;
+
+ int head_coord_q_offset_1 = 0;
+ uint32_t head_coord_1, head_coord_k_1, head_coord_v_1;
+ uint32_t blocked_row_coord = tile_id_and_coord[2];
+ uint32_t head_coord_from_grid_1 = tile_id_and_coord[0];
+ uint32_t batch_coord_1 = tile_id_and_coord[1];
+ uint32_t lean_tile_id = tile_id_and_coord[0];
+
+ uint32_t is_valid_tile = true;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+
+ PipelineState<SchedulerPipelineStageCount> sched_state(0, 0); // index, state
+
+ // thread_specialize_op 21 code
+ if (wid >= 0 && wid < SoftmaxWarps) {
+ // Softmax
+ reg_alloc<SoftmaxWarpRegs>();
+
+ const uint32_t softmax_gid = wid / 4;
+ const uint32_t softmax_gid_s_offset = softmax_gid * BMM1_TILE_N;
+
+ uint32_t base_tmem_addr;
+ named_barrier_wait(TMEM_ALLOC_SOFTMAX_BARRIER,
+ threads_per_warp * (SoftmaxWarps + 1));
+ lds_32(&base_tmem_addr,
+ cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs));
+ uint32_t tmem_fp32_S = base_tmem_addr + 0 + softmax_gid_s_offset;
+ uint32_t tmem_fp16_S =
+ base_tmem_addr + BMM1_TILE_N / 2 + softmax_gid_s_offset;
+ uint32_t tmem_Stats = base_tmem_addr + 0 + softmax_gid_s_offset;
+
+ r32 reg_8_0[BMM1_TILE_N];
+ r32 fp32_stats[2];
+
+ // Memory barrier states
+ uint32_t bmm_mbar_state = 0;
+ uint32_t stat_mbar_state = 0;
+ uint32_t epilogue_state = 0;
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ int p_row_1 = q_row_coord + softmax_gid * TILE_M_1 + tid;
+
+ // global_load_op 10 decls
+ r32 reg_10_0[1];
+ reg_10_0[0] = reinterpret_cast<const r32 &>(tensor_4);
+ const int oob_M_10 = 1;
+ const int oob_N_10 = 1;
+
+ // pointwise_calc_op 9 decls
+
+ // mha_mask_op 11 decls
+
+ // softmax_op 12 decls
+ r32 reg_12_0[32];
+ float2 total_sum = {0.0f, 0.0f};
+ float2 local_sum = {0.0f, 0.0f};
+ float total_max = NEG_INFINITY;
+ float actual_total_max = NEG_INFINITY;
+ static constexpr float inv_ln2_12 = 1.4426950408889634074f;
+ float total_max_scale_12 = inv_ln2_12;
+ const float bmm_scale = reinterpret_cast<const float &>(tensor_4);
+ total_max_scale_12 *= bmm_scale;
+
+ uint64_t &bmm1_mbar = softmax_gid == 0
+ ? shared_storage.bmm1_tile0_done_mbar[0]
+ : shared_storage.bmm1_tile1_done_mbar[0];
+ uint64_t &stat_empty_mbar = softmax_gid == 0
+ ? shared_storage.stat_tile0_empty_mbar[0]
+ : shared_storage.stat_tile1_empty_mbar[0];
+ uint64_t *bmm2_mbar = softmax_gid == 0
+ ? &(shared_storage.bmm2_tile0_ready_mbar[0])
+ : &(shared_storage.bmm2_tile1_ready_mbar[0]);
+ uint64_t *stat_full_mbar =
+ softmax_gid == 0 ? &(shared_storage.stat_tile0_full_mbar[0])
+ : &(shared_storage.stat_tile1_full_mbar[0]);
+
+ epilogue_state ^= 1;
+ wait_barrier(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]),
+ epilogue_state);
+ stat_mbar_state ^= 1;
+ wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar), stat_mbar_state);
+
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound;
+ kv_loop <
+ kv_loop_right_bound -
+ FORT_DIV_UP(BMM1_TILE_M * CGA_M_1 * Tiles_Q, BMM1_TILE_N);
+ kv_loop += 1) {
+ int p_col_1 = kv_loop * TILE_N_1;
+ {
+
+ wait_barrier(cast_smem_ptr_to_uint(&bmm1_mbar), bmm_mbar_state);
+
+ r32 stat_reg[BMM1_TILE_N / 64];
+#pragma unroll
+ for (int ldtm_step = 0; ldtm_step < BMM1_TILE_N / 32; ldtm_step++) {
+ ldtm_32dp32bit_x32(&reg_8_0[32 * ldtm_step],
+ tmem_fp32_S + ldtm_step * 32);
+ }
+ constexpr bool use_ldtm_stat_max = false;
+
+ // global_load_op 10 code
+
+ // softmax_op 12 code
+ float current_max =
+ row_max_reduction_128_elems(reg_8_0) * total_max_scale_12;
+
+ // Update total max
+ float total_max_tmp = fmaxf(current_max, total_max);
+ current_max = total_max;
+ total_max = total_max_tmp;
+
+ float2 bmm_scale_x_ln2_x2 =
+ make_float2(total_max_scale_12, total_max_scale_12);
+ float total_max_scaled =
+ (total_max == NEG_INFINITY) ? 0.0f : total_max;
+ float2 minus_scaled_max_x2 =
+ make_float2(-total_max_scaled, -total_max_scaled);
+
+ static constexpr int kMulPipeCount = 14; // must be multiple of 2
+ static constexpr int kSubtractPipeCount = 12; // must be multiple of 2
+ static constexpr int kFmaPipeCount = 12; // must be multiple of 2
+ static constexpr int kConvertPipeCount = 8; // must be multiple of 2
+ static constexpr int kReleasePipeCount = 4; // must be multiple of 2
+ static constexpr int kDropoutPipeCount =
+ 6; // must be multiple of 2 and less than or equal
+ // kConvertPipeCount
+ static constexpr int kAddPipeCount =
+ 4; // must be multiple of 2 and less than kDropoutPipeCount
+
+ // To better overlap EX2 MUFU and emulation, we need to have last
+ // kE2eRes of every kE2eFreq elements in a row to use emulation while
+ // the rest go to MUFU. Also, we need to avoid using emulation after
+ // kE2eLimit elements as it would delay the execution of row sum of
+ // another softmax warpgroup because of resource contention
+ static constexpr int kE2eFreq = 16;
+ static constexpr int kE2eRes = 8;
+ static constexpr int kE2eLimit = BMM1_TILE_N / 16 * 9;
+
+#pragma unroll
+ for (int i = 0; i < kFmaPipeCount; i += 2) {
+ float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i]),
+ reinterpret_cast<float &>(reg_8_0[i + 1]));
+ float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2);
+
+ reinterpret_cast<float &>(reg_8_0[i + 0]) = out.x;
+ reinterpret_cast<float &>(reg_8_0[i + 1]) = out.y;
+ }
+
+ // Optimized version of alpha = __expf(current_max - total_max);
+ float exp_input = (total_max == NEG_INFINITY)
+ ? NEG_INFINITY
+ : (current_max - total_max);
+ float alpha = exp2f(exp_input);
+
+ // Send stats to correction warp
+ reinterpret_cast<float &>(fp32_stats[0]) = alpha;
+
+ // STTM
+ sttm_32dp32bit_x1(tmem_Stats, &fp32_stats[0]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar));
+
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i += 2) {
+ if (i - kConvertPipeCount == 32) {
+ sttm_32dp32bit_x16(tmem_fp16_S, &reg_12_0[0]);
+ }
+ if (i - kConvertPipeCount == 64) {
+ sttm_32dp32bit_x16(tmem_fp16_S + 16, &reg_12_0[16]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(bmm2_mbar + 0));
+ }
+
+ if (i >= kConvertPipeCount) {
+ fp32x2_to_bf16x2(
+ &reg_12_0[((i - kConvertPipeCount) / 2) % 32],
+ reinterpret_cast<r32 *>(&reg_8_0[i - kConvertPipeCount]));
+ }
+
+ reinterpret_cast<float &>(reg_8_0[i + 0]) =
+ exp2f(reinterpret_cast<float &>(reg_8_0[i + 0]));
+
+
+ if (i + kFmaPipeCount < BMM1_TILE_N) {
+ float2 in = make_float2(
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]),
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]));
+ float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2);
+
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]) = out.x;
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]) = out.y;
+ }
+
+ reinterpret_cast<float &>(reg_8_0[i + 1]) =
+ exp2f(reinterpret_cast<float &>(reg_8_0[i + 1]));
+
+ if (i == kE2eLimit) {
+ if (softmax_gid == 1) {
+ named_barrier_arrive(SOFTMAX_BARRIER, 256);
+ named_barrier_wait(SOFTMAX_BARRIER + 1, 256);
+ }
+ }
+ }
+
+#pragma unroll
+ for (int i = BMM1_TILE_N - kConvertPipeCount; i < BMM1_TILE_N;
+ i += 2) {
+ fp32x2_to_bf16x2(&reg_12_0[(i / 2) % 32],
+ reinterpret_cast<r32 *>(&reg_8_0[i]));
+ }
+ sttm_32dp32bit_x32(tmem_fp16_S + BMM1_TILE_N / 64 * 16,
+ &reg_12_0[((BMM1_TILE_N / 64) % 2) * 16]);
+ fence_view_async_tmem_store();
+ arrive_barrier(
+ cast_smem_ptr_to_uint(bmm2_mbar + (BMM1_TILE_N / 64 - 1)));
+
+ stat_mbar_state ^= 1;
+ if (!smem_bar_peek(cast_smem_ptr_to_uint(&stat_empty_mbar),
+ stat_mbar_state)) {
+ wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar),
+ stat_mbar_state);
+ }
+
+ float2 alpha2 = make_float2(alpha, alpha);
+ float local_row_sum_0 = 0.0f;
+ total_sum = fmul2(alpha2, total_sum);
+
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i += 2) {
+ float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i + 0]),
+ reinterpret_cast<float &>(reg_8_0[i + 1]));
+ total_sum = fadd2(total_sum, in);
+ }
+ if (softmax_gid == 0) {
+ named_barrier_arrive(SOFTMAX_BARRIER + 1, 256);
+ named_barrier_wait(SOFTMAX_BARRIER, 256);
+ }
+ named_barrier_wait(SOFTMAX_BARRIER + 2 + softmax_gid, 128);
+ }
+ bmm_mbar_state ^= 1;
+ } // End of mainloop
+#pragma unroll 1
+ for (int kv_loop = FORT_MAX(
+ kv_loop_right_bound -
+ FORT_DIV_UP(BMM1_TILE_M * CGA_M_1 * Tiles_Q, BMM1_TILE_N),
+ kv_loop_left_bound);
+ kv_loop < kv_loop_right_bound; kv_loop += 1) {
+ int p_col_1 = kv_loop * TILE_N_1;
+ {
+
+ wait_barrier(cast_smem_ptr_to_uint(&bmm1_mbar), bmm_mbar_state);
+
+ r32 stat_reg[BMM1_TILE_N / 64];
+#pragma unroll
+ for (int ldtm_step = 0; ldtm_step < BMM1_TILE_N / 32; ldtm_step++) {
+ ldtm_32dp32bit_x32(&reg_8_0[32 * ldtm_step],
+ tmem_fp32_S + ldtm_step * 32);
+ }
+ constexpr bool use_ldtm_stat_max = false;
+
+)KERNEL"
+ R"KERNEL(
+ // global_load_op 10 code
+
+ // mha_mask_op 11 code
+
+ {
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i++) {
+ int row = p_row_1;
+ int col = p_col_1 + i;
+ bool mask = compute_diagonal_band_mask_11(
+ row, col, actual_seqlen_kv_1, actual_seqlen_q_1,
+ shift_right_bound, left_bound);
+ if (!mask) {
+ reinterpret_cast<float &>(reg_8_0[i]) = tensor_13;
+ }
+ }
+ }
+
+ // softmax_op 12 code
+ float current_max =
+ row_max_reduction_128_elems(reg_8_0) * total_max_scale_12;
+
+ // Update total max
+ float total_max_tmp = fmaxf(current_max, total_max);
+ current_max = total_max;
+ total_max = total_max_tmp;
+
+ float2 bmm_scale_x_ln2_x2 =
+ make_float2(total_max_scale_12, total_max_scale_12);
+ float total_max_scaled =
+ (total_max == NEG_INFINITY) ? 0.0f : total_max;
+ float2 minus_scaled_max_x2 =
+ make_float2(-total_max_scaled, -total_max_scaled);
+
+ static constexpr int kMulPipeCount = 14; // must be multiple of 2
+ static constexpr int kSubtractPipeCount = 12; // must be multiple of 2
+ static constexpr int kFmaPipeCount = 12; // must be multiple of 2
+ static constexpr int kConvertPipeCount = 8; // must be multiple of 2
+ static constexpr int kReleasePipeCount = 4; // must be multiple of 2
+ static constexpr int kDropoutPipeCount =
+ 6; // must be multiple of 2 and less than or equal
+ // kConvertPipeCount
+ static constexpr int kAddPipeCount =
+ 4; // must be multiple of 2 and less than kDropoutPipeCount
+
+ // To better overlap EX2 MUFU and emulation, we need to have last
+ // kE2eRes of every kE2eFreq elements in a row to use emulation while
+ // the rest go to MUFU. Also, we need to avoid using emulation after
+ // kE2eLimit elements as it would delay the execution of row sum of
+ // another softmax warpgroup because of resource contention
+ static constexpr int kE2eFreq = 16;
+ static constexpr int kE2eRes = 8;
+ static constexpr int kE2eLimit = BMM1_TILE_N / 16 * 9;
+
+#pragma unroll
+ for (int i = 0; i < kFmaPipeCount; i += 2) {
+ float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i]),
+ reinterpret_cast<float &>(reg_8_0[i + 1]));
+ float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2);
+
+ reinterpret_cast<float &>(reg_8_0[i + 0]) = out.x;
+ reinterpret_cast<float &>(reg_8_0[i + 1]) = out.y;
+ }
+
+ // Optimized version of alpha = __expf(current_max - total_max);
+ float exp_input = (total_max == NEG_INFINITY)
+ ? NEG_INFINITY
+ : (current_max - total_max);
+ float alpha = exp2f(exp_input);
+
+ // Send stats to correction warp
+ reinterpret_cast<float &>(fp32_stats[0]) = alpha;
+
+ // STTM
+ sttm_32dp32bit_x1(tmem_Stats, &fp32_stats[0]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar));
+
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i += 2) {
+ if (i - kConvertPipeCount == 32) {
+ sttm_32dp32bit_x16(tmem_fp16_S, &reg_12_0[0]);
+ }
+ if (i - kConvertPipeCount == 64) {
+ sttm_32dp32bit_x16(tmem_fp16_S + 16, &reg_12_0[16]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(bmm2_mbar + 0));
+ }
+
+ if (i >= kConvertPipeCount) {
+ fp32x2_to_bf16x2(
+ &reg_12_0[((i - kConvertPipeCount) / 2) % 32],
+ reinterpret_cast<r32 *>(&reg_8_0[i - kConvertPipeCount]));
+ }
+
+ reinterpret_cast<float &>(reg_8_0[i + 0]) =
+ exp2f(reinterpret_cast<float &>(reg_8_0[i + 0]));
+
+
+ if (i + kFmaPipeCount < BMM1_TILE_N) {
+ float2 in = make_float2(
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]),
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]));
+ float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2);
+
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]) = out.x;
+ reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]) = out.y;
+ }
+
+ reinterpret_cast<float &>(reg_8_0[i + 1]) =
+ exp2f(reinterpret_cast<float &>(reg_8_0[i + 1]));
+
+ if (i == kE2eLimit) {
+ if (softmax_gid == 1) {
+ named_barrier_arrive(SOFTMAX_BARRIER, 256);
+ named_barrier_wait(SOFTMAX_BARRIER + 1, 256);
+ }
+ }
+ }
+
+#pragma unroll
+ for (int i = BMM1_TILE_N - kConvertPipeCount; i < BMM1_TILE_N;
+ i += 2) {
+ fp32x2_to_bf16x2(&reg_12_0[(i / 2) % 32],
+ reinterpret_cast<r32 *>(&reg_8_0[i]));
+ }
+ sttm_32dp32bit_x32(tmem_fp16_S + BMM1_TILE_N / 64 * 16,
+ &reg_12_0[((BMM1_TILE_N / 64) % 2) * 16]);
+ fence_view_async_tmem_store();
+ arrive_barrier(
+ cast_smem_ptr_to_uint(bmm2_mbar + (BMM1_TILE_N / 64 - 1)));
+
+ stat_mbar_state ^= 1;
+ if (!smem_bar_peek(cast_smem_ptr_to_uint(&stat_empty_mbar),
+ stat_mbar_state)) {
+ wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar),
+ stat_mbar_state);
+ }
+
+ float2 alpha2 = make_float2(alpha, alpha);
+ float local_row_sum_0 = 0.0f;
+ total_sum = fmul2(alpha2, total_sum);
+
+#pragma unroll
+ for (int i = 0; i < BMM1_TILE_N; i += 2) {
+ float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i + 0]),
+ reinterpret_cast<float &>(reg_8_0[i + 1]));
+ total_sum = fadd2(total_sum, in);
+ }
+ if (softmax_gid == 0) {
+ named_barrier_arrive(SOFTMAX_BARRIER + 1, 256);
+ named_barrier_wait(SOFTMAX_BARRIER, 256);
+ }
+ named_barrier_wait(SOFTMAX_BARRIER + 2 + softmax_gid, 128);
+ }
+ bmm_mbar_state ^= 1;
+ } // End of mainloop
+
+ float final_total_sum = total_sum.x + total_sum.y;
+
+ reinterpret_cast<float &>(fp32_stats[0]) = total_max;
+ reinterpret_cast<float &>(fp32_stats[1]) = final_total_sum;
+ // STTM
+ sttm_32dp32bit_x2(tmem_Stats, &fp32_stats[0]);
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar));
+
+ // This portion of the code may seem strange, please read the
+ // documentation here:
+ // Function: work_tile_info_from_workid_response, load_query_response
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ } // end of persistent loop
+ }
+
+ // thread_specialize_op 22 code
+ else if (wid >= SoftmaxWarps && wid < SoftmaxWarps + CorrectionWarps) {
+ // Correction
+ reg_dealloc<CorrectionWarpRegs>();
+ uint32_t base_tmem_addr;
+ named_barrier_wait(TMEM_ALLOC_CORRECTION_BARRIER,
+ threads_per_warp * (CorrectionWarps + 1));
+ lds_32(&base_tmem_addr,
+ cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs));
+ uint32_t tmem_fp32_O_0 = base_tmem_addr + 256;
+ uint32_t tmem_fp32_O_1 = base_tmem_addr + 384;
+ uint32_t tmem_Stats_0 = base_tmem_addr + 0;
+ uint32_t tmem_Stats_1 = base_tmem_addr + 0 + BMM1_TILE_N;
+
+ static constexpr int local_correction_block_size = 16;
+ static constexpr int local_epilogue_block_size =
+ 128 / sizeof(ElementO); // hack as only K=128/64 supported. Both can do
+ // 128B TMASTG.
+
+)KERNEL"
+ R"KERNEL(
+ float amax_s_1 = 0.f;
+ float amax_o_1 = 0.f;
+
+ // Registers
+ uint32_t fp32_stats[2];
+ uint32_t fp32_O[local_correction_block_size];
+
+ // Memory barrier states
+ uint32_t epilogue_state = 0;
+ uint32_t bmm_mbar_state = 0;
+ uint32_t stat_mbar_state = 0;
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ // No correction for iter 0
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.bmm2_tile0_ready_mbar[0])));
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.bmm2_tile1_ready_mbar[0])));
+
+ {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile0_full_mbar[0]),
+ stat_mbar_state);
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.stat_tile0_empty_mbar[0])));
+ }
+ {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.stat_tile1_full_mbar[0]),
+ stat_mbar_state);
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.stat_tile1_empty_mbar[0])));
+ }
+ stat_mbar_state ^= 1;
+ } else {
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.empty_mainloop_mbar[0])));
+ }
+
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound;
+ kv_loop += 1) {
+#pragma unroll
+ for (int sub_tile_id = 0; sub_tile_id < 2; ++sub_tile_id) {
+ uint32_t tmem_Stats = sub_tile_id == 0 ? tmem_Stats_0 : tmem_Stats_1;
+ uint32_t tmem_fp32_O =
+ sub_tile_id == 0 ? tmem_fp32_O_0 : tmem_fp32_O_1;
+
+ uint64_t &stat_full_mbar =
+ sub_tile_id == 0 ? shared_storage.stat_tile0_full_mbar[0]
+ : shared_storage.stat_tile1_full_mbar[0];
+ uint64_t &bmm_done_mbar =
+ sub_tile_id == 0 ? shared_storage.bmm2_tile0_done_mbar[0]
+ : shared_storage.bmm2_tile1_done_mbar[0];
+ uint64_t *stat_empty_mbar =
+ sub_tile_id == 0 ? &(shared_storage.stat_tile0_empty_mbar[0])
+ : &(shared_storage.stat_tile1_empty_mbar[0]);
+ uint64_t *bmm_ready_mbar =
+ sub_tile_id == 0 ? &(shared_storage.bmm2_tile0_ready_mbar[0])
+ : &(shared_storage.bmm2_tile1_ready_mbar[0]);
+
+ wait_barrier(cast_smem_ptr_to_uint(&stat_full_mbar), stat_mbar_state);
+ ldtm_32dp32bit_x1(&fp32_stats[0], tmem_Stats);
+
+ float alpha = reinterpret_cast<float &>(fp32_stats[0]);
+ fence_view_async_tmem_load();
+ arrive_barrier(cast_smem_ptr_to_uint(stat_empty_mbar));
+
+ bool alpha_is_one = (alpha == 1.0f);
+ bool all_alpha_one = __all_sync(0xFFFFFFFF, alpha_is_one);
+
+ float2 alpha2 = make_float2(alpha, alpha);
+
+ wait_barrier(cast_smem_ptr_to_uint(&bmm_done_mbar), bmm_mbar_state);
+
+ if (!all_alpha_one) {
+#pragma unroll
+ for (int block = 0; block < TILE_O_1 / local_correction_block_size;
+ block++) {
+// LDTM
+#pragma unroll
+ for (int ldtm_step = 0;
+ ldtm_step < local_correction_block_size / 8; ldtm_step++) {
+ ldtm_32dp32bit_x8(&fp32_O[8 * ldtm_step],
+ tmem_fp32_O +
+ block * local_correction_block_size +
+ ldtm_step * 8);
+ }
+
+#pragma unroll
+ for (int i = 0; i < local_correction_block_size; i += 2) {
+ float2 in =
+ make_float2(reinterpret_cast<float &>(fp32_O[i + 0]),
+ reinterpret_cast<float &>(fp32_O[i + 1]));
+ float2 out = fmul2(alpha2, in);
+ reinterpret_cast<float &>(fp32_O[i + 0]) = out.x;
+ reinterpret_cast<float &>(fp32_O[i + 1]) = out.y;
+ }
+
+#pragma unroll
+ for (int sttm_step = 0;
+ sttm_step < local_correction_block_size / 8; sttm_step++) {
+ sttm_32dp32bit_x8(tmem_fp32_O +
+ block * local_correction_block_size +
+ sttm_step * 8,
+ &fp32_O[8 * sttm_step]);
+ }
+ }
+ }
+ fence_view_async_tmem_store();
+ arrive_barrier(cast_smem_ptr_to_uint(bmm_ready_mbar));
+ }
+ stat_mbar_state ^= 1;
+ bmm_mbar_state ^= 1;
+ } // End of mainloop
+
+ // Epilogue
+ {
+ epilogue_state ^= 1;
+
+ static constexpr int stg_step = 16 / sizeof(ElementO);
+ const int local_row = (tid % 8) / 1;
+
+ // global_store_op 13 decls
+ int oob_M_13 = desc_7.dims[2];
+ int row_13 = 0;
+ char *ptr_13 =
+ reinterpret_cast<char *>(tensor_7) +
+ batch_coord_1 * desc_7.strides[0] * BYTES_PER_ELEMENT_13 +
+ head_coord_1 * desc_7.strides[1] * BYTES_PER_ELEMENT_13 +
+ row_13 * desc_7.strides[2] * BYTES_PER_ELEMENT_13;
+
+ // global_store_op 14 decls
+ int oob_M_14 = desc_6.dims[2];
+ int row_14 = 0;
+ char *ptr_14 =
+ reinterpret_cast<char *>(tensor_6) +
+ batch_coord_1 * desc_6.strides[0] * BYTES_PER_ELEMENT_14 +
+ head_coord_1 * desc_6.strides[1] * BYTES_PER_ELEMENT_14 +
+ row_14 * desc_6.strides[2] * BYTES_PER_ELEMENT_14;
+
+#pragma unroll
+ for (int sub_tile_id = 0; sub_tile_id < 2; ++sub_tile_id) {
+ const int row_coord = q_row_coord + sub_tile_id * TILE_M_1 + tid;
+ ElementO *smem_O = (sub_tile_id == 0) ? shared_storage.smem_O
+ : shared_storage.smem_V;
+
+ uint32_t fp32_reg_O[local_epilogue_block_size];
+ uint32_t reg_O[local_epilogue_block_size / (4 / sizeof(ElementO))];
+
+ uint32_t tmem_Stats = sub_tile_id == 0 ? tmem_Stats_0 : tmem_Stats_1;
+ uint32_t tmem_fp32_O =
+ sub_tile_id == 0 ? tmem_fp32_O_0 : tmem_fp32_O_1;
+
+ uint64_t &stat_full_mbar =
+ sub_tile_id == 0 ? shared_storage.stat_tile0_full_mbar[0]
+ : shared_storage.stat_tile1_full_mbar[0];
+ uint64_t &bmm_done_mbar =
+ sub_tile_id == 0 ? shared_storage.bmm2_tile0_done_mbar[0]
+ : shared_storage.bmm2_tile1_done_mbar[0];
+ uint64_t &stat_empty_mbar =
+ sub_tile_id == 0 ? shared_storage.stat_tile0_empty_mbar[0]
+ : shared_storage.stat_tile1_empty_mbar[0];
+ uint64_t &final_stat_empty_mbar =
+ sub_tile_id == 0 ? shared_storage.final_stat_tile0_empty_mbar[0]
+ : shared_storage.final_stat_tile1_empty_mbar[0];
+
+ wait_barrier(cast_smem_ptr_to_uint(&stat_full_mbar), stat_mbar_state);
+ ldtm_32dp32bit_x2(&fp32_stats[0], tmem_Stats);
+
+ float total_max = reinterpret_cast<float &>(fp32_stats[0]) * ln2;
+ float total_sum = reinterpret_cast<float &>(fp32_stats[1]);
+ fence_view_async_tmem_load();
+ arrive_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar));
+ arrive_barrier(cast_smem_ptr_to_uint(&final_stat_empty_mbar));
+
+ float softmax_stats =
+ total_sum == 0.f ? NEG_INFINITY : total_max + __logf(total_sum);
+
+ // global_store_op 13 code
+ if (row_coord < actual_seqlen_q_1) {
+ stg_32(ptr_13 +
+ row_coord * desc_7.strides[2] * BYTES_PER_ELEMENT_13,
+ &(reinterpret_cast<uint32_t &>(total_max)));
+ }
+
+ // global_store_op 14 code
+ if (row_coord < actual_seqlen_q_1) {
+ stg_32(ptr_14 +
+ row_coord * desc_6.strides[2] * BYTES_PER_ELEMENT_14,
+ &(reinterpret_cast<uint32_t &>(total_sum)));
+ }
+
+ float threshold_beta = (total_sum == 0.f) ? 0.f : 1.f / total_sum;
+ float beta = threshold_beta;
+
+ float2 beta2 = make_float2(threshold_beta, threshold_beta);
+
+ wait_barrier(cast_smem_ptr_to_uint(&bmm_done_mbar), bmm_mbar_state);
+
+ if (sub_tile_id == 0) {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_0_empty_mbar[0]),
+ epilogue_state);
+ }
+#pragma unroll
+ for (int block = 0; block < TILE_O_1 / local_epilogue_block_size;
+ block++) {
+ {
+#pragma unroll
+ for (int ldtm_step = 0;
+ ldtm_step < local_epilogue_block_size / 32; ldtm_step++) {
+ ldtm_32dp32bit_x32(&fp32_reg_O[32 * ldtm_step],
+ tmem_fp32_O +
+ block * local_epilogue_block_size +
+ ldtm_step * 32);
+ }
+ }
+
+#pragma unroll
+ for (int i = 0; i < local_epilogue_block_size; i += 2) {
+ float2 in =
+ make_float2(reinterpret_cast<float &>(fp32_reg_O[i + 0]),
+ reinterpret_cast<float &>(fp32_reg_O[i + 1]));
+ float2 out = fmul2(beta2, in);
+ reinterpret_cast<float &>(fp32_reg_O[i + 0]) = out.x;
+ reinterpret_cast<float &>(fp32_reg_O[i + 1]) = out.y;
+ }
+
+// general_data_type_cast code
+#pragma unroll
+ for (int i = 0; i < local_epilogue_block_size; i += 2) {
+ fp32x2_to_bf16x2(&reg_O[i / 2], &fp32_reg_O[i]);
+ }
+
+#pragma unroll
+ for (int i = 0; i < local_epilogue_block_size / stg_step; i++) {
+ char *smem_loc = get_smem_loc_epilogue_swizzle_128b(
+ reinterpret_cast<char *>(smem_O), block, tid, local_row, i,
+ sizeof(ElementO), local_epilogue_block_size, TILE_M_1);
+)KERNEL"
+ R"KERNEL(
+ sts_128(cast_smem_ptr_to_uint(smem_loc),
+ reinterpret_cast<r32 *>(&reg_O[i * 4]));
+ }
+
+ uint64_t *tma_o_full_mbar =
+ sub_tile_id == 0 ? &(shared_storage.tma_o_0_full_mbar[block])
+ : &(shared_storage.tma_o_1_full_mbar[block]);
+ fence_view_async_shared();
+ arrive_barrier(cast_smem_ptr_to_uint(tma_o_full_mbar));
+ }
+ }
+ stat_mbar_state ^= 1;
+ bmm_mbar_state ^= 1;
+ } // Epilogue end
+
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ } // end of persistent loop
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]));
+ }
+
+ // thread_specialize_op 23 code
+ else if (wid == SoftmaxWarps + CorrectionWarps) {
+ // MMA
+ reg_dealloc<MmaWarpRegs>();
+ tmem_allocate_1sm(num_columns_per_tmem,
+ cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs));
+ tmem_release_allocation_lock_1sm();
+ __syncwarp();
+ named_barrier_arrive(TMEM_ALLOC_SOFTMAX_BARRIER,
+ threads_per_warp * (SoftmaxWarps + 1));
+ named_barrier_arrive(TMEM_ALLOC_CORRECTION_BARRIER,
+ threads_per_warp * (CorrectionWarps + 1));
+ uint32_t base_tmem_addr;
+ lds_32(&base_tmem_addr,
+ cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs));
+
+ uint32_t tmem_S_acc_0 = base_tmem_addr + 0;
+ uint32_t tmem_S_acc_1 = base_tmem_addr + BMM1_TILE_N;
+
+ uint32_t tmem_S_bmm2_0 = base_tmem_addr + BMM1_TILE_N / 2;
+ uint32_t tmem_S_bmm2_1 = base_tmem_addr + 3 * BMM1_TILE_N / 2;
+
+ uint32_t tmem_O_0 = base_tmem_addr + 256;
+ uint32_t tmem_O_1 = base_tmem_addr + 384;
+
+ // Memory barrier states
+ uint32_t bmm_mbar_state = 0;
+ uint32_t final_stat_mbar_state = 1;
+ uint32_t empty_mainloop_mbar_state = 0;
+
+ PipelineState<stages_kv> kv_mbar_state(0, 0); // index, state
+ PipelineState<stages_q> q_mbar_state(0, 0); // index, state
+
+ // mma_op 8 decls
+ constexpr uint64_t utcmma_instruction_desc_8 =
+ build_utcmma_instruction_desc<0, // max shift for WS
+ TILE_M_1 * CTA_MMA_1, TILE_N_1,
+ 0, // Transpose for B
+ 0, // Transpose for A
+ 0, // Negate for B
+ 0, // Negate for A
+ 1, // Data type B
+ 1, // Data type A
+ 0, // sparse meta data format
+ 1, // Acc type fp32
+ 0, // saturate disable
+ 0, // sparse disable
+ 0 // sparse meta data id2 ???
+ >();
+ // Swizzle mode, base smem offset, desc type, bytes per leading dim, tile k
+ Smem_utcmma_descriptor utcmma_smem_desc_Q_0(2, 0, 1, 16,
+ ROWS_PER_CORE_MATRIX_A_8 * 128);
+ Smem_utcmma_descriptor utcmma_smem_desc_K(2, 0, 1, 16,
+ ROWS_PER_CORE_MATRIX_B_8 * 128);
+
+ utcmma_smem_desc_Q_0.set_smem<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(
+ cast_smem_ptr_to_uint(shared_storage.smem_Q));
+ utcmma_smem_desc_K.set_smem<SMEM_BUFFER_SIZE_K, BUFFERS_K>(
+ cast_smem_ptr_to_uint(shared_storage.smem_K));
+
+ // mma_op 17 decls
+ constexpr uint64_t utcmma_instruction_desc_17 =
+ build_utcmma_instruction_desc<0, // max shift for WS
+ TILE_M_1 * CTA_MMA_1, TILE_O_1,
+ 1, // Transpose for B
+ 0, // Transpose for A
+ 0, // Negate for B
+ 0, // Negate for A
+ 1, // Data type B
+ 1, // Data type A
+ 0, // sparse meta data format
+ 1, // Acc type fp32
+ 0, // saturate disable
+ 0, // sparse disable
+ 0 // sparse meta data id2 ???
+ >();
+ // Swizzle mode, base smem offset, desc type, bytes per leading dim, tile k
+ Smem_utcmma_descriptor utcmma_smem_desc_V(
+ 2, 0, 1, TILE_O_1 / ROWS_PER_CORE_MATRIX_B_17 <= 8 ? 0 : TILE_N_1 * 128,
+ COLS_PER_CORE_MATRIX_B_17 * 128);
+
+ utcmma_smem_desc_V.set_smem<SMEM_BUFFER_SIZE_V, BUFFERS_V>(
+ cast_smem_ptr_to_uint(shared_storage.smem_V));
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+ //---------------------------------------------------------//
+ //------------------- MMA Pipeline Begin ------------------//
+ //---------------------------------------------------------//
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.final_stat_tile0_empty_mbar[0]),
+ final_stat_mbar_state);
+
+ const int kv_stage = kv_mbar_state.index();
+ const int kv_state = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[kv_stage]),
+ kv_state);
+
+ const int q_stage = q_mbar_state.index();
+ const int q_phase = q_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ q_phase);
+ ++q_mbar_state;
+
+ // Q * K matmul for sub-tile 0
+ {
+ Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0;
+ uint32_t tmem_acc = tmem_S_acc_0;
+
+ // mma_op 8 code
+#pragma unroll
+ for (int k = 0; k < BMM1_XMMAS_K; ++k) {
+ if (elect_one)
+ utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc,
+ utcmma_smem_desc_K.desc, tmem_acc,
+ utcmma_instruction_desc_8, (k > 0));
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>();
+ } else {
+ utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_K
+ .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>();
+ } else {
+ utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ }
+ utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ // change the smem buffer for Q
+ utcmma_smem_desc_Q
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>();
+ }
+
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0]));
+ } // elect_one
+ } // if (kv_loop_left_bound < kv_loop_right_bound)
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.final_stat_tile1_empty_mbar[0]),
+ final_stat_mbar_state);
+
+ const int kv_stage = kv_mbar_state.index();
+ const int kv_state = kv_mbar_state.phase();
+ const int q_stage = q_mbar_state.index();
+ const int q_phase = q_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ q_phase);
+ ++q_mbar_state;
+
+ // Q * K matmul for sub-tile 1
+ {
+ Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0;
+ uint32_t tmem_acc = tmem_S_acc_1;
+
+ // mma_op 8 code
+#pragma unroll
+ for (int k = 0; k < BMM1_XMMAS_K; ++k) {
+ if (elect_one)
+ utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc,
+)KERNEL"
+ R"KERNEL(
+ utcmma_smem_desc_K.desc, tmem_acc,
+ utcmma_instruction_desc_8, (k > 0));
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>();
+ } else {
+ utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_K
+ .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>();
+ } else {
+ utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ }
+ utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ // change the smem buffer for K
+ utcmma_smem_desc_K
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_K, BUFFERS_K>();
+ // change the smem buffer for Q
+ utcmma_smem_desc_Q
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>();
+ const int kv_stage = kv_mbar_state.index();
+ if (elect_one)
+ umma_arrive(cast_smem_ptr_to_uint(
+ &shared_storage.tma_k_empty_mbar[kv_stage]));
+ }
+
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0]));
+ } // elect_one
+ }
+
+// Mainloop
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound;
+ kv_loop += 1) {
+ const int kv_stage = kv_mbar_state.index();
+ const uint32_t kv_state = kv_mbar_state.phase();
+
+ ++kv_mbar_state;
+
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stage]),
+ kv_state);
+
+ // S * V matmul for sub-tile 0
+ {
+ uint32_t bmm2_ready_mbar =
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]);
+ uint32_t tmem_O = tmem_O_0;
+ uint32_t tmem_S = tmem_S_bmm2_0;
+ uint32_t scaleC = kv_loop > kv_loop_left_bound + 1;
+
+ // mma_op 17 code
+#pragma unroll
+ for (int k = 0; k < BMM2_XMMAS_K; ++k) {
+ if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) {
+ wait_barrier(bmm2_ready_mbar +
+ (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8,
+ bmm_mbar_state);
+ }
+ if (elect_one)
+ utcmma_atmem_bsmem_h_cta1(
+ tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)),
+ utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17,
+ scaleC || k > 0);
+ if (k == BMM2_XMMAS_K - 1) {
+ utcmma_smem_desc_V
+ .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>();
+ } else {
+ utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>();
+ }
+ }
+ if (elect_one)
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]));
+ }
+
+ wait_barrier(
+ cast_smem_ptr_to_uint(
+ &shared_storage.tma_k_full_mbar[kv_mbar_state.index()]),
+ kv_mbar_state.phase());
+
+ // Q * K matmul for sub-tile 0
+ {
+ Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0;
+ uint32_t tmem_acc = tmem_S_acc_0;
+
+ // mma_op 8 code
+#pragma unroll
+ for (int k = 0; k < BMM1_XMMAS_K; ++k) {
+ if (elect_one)
+ utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc,
+ utcmma_smem_desc_K.desc, tmem_acc,
+ utcmma_instruction_desc_8, (k > 0));
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>();
+ } else {
+ utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_K
+ .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>();
+ } else {
+ utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ }
+ utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ // change the smem buffer for Q
+ utcmma_smem_desc_Q
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>();
+ }
+
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0]));
+ } // elect_one
+
+ // S * V matmul for sub-tile 1
+ {
+ uint32_t bmm2_ready_mbar =
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]);
+ uint32_t tmem_O = tmem_O_1;
+ uint32_t tmem_S = tmem_S_bmm2_1;
+ uint32_t scaleC = kv_loop > kv_loop_left_bound + 1;
+
+ // mma_op 17 code
+#pragma unroll
+ for (int k = 0; k < BMM2_XMMAS_K; ++k) {
+ if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) {
+ wait_barrier(bmm2_ready_mbar +
+ (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8,
+ bmm_mbar_state);
+ }
+ if (elect_one)
+ utcmma_atmem_bsmem_h_cta1(
+ tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)),
+ utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17,
+ scaleC || k > 0);
+ if (k == BMM2_XMMAS_K - 1) {
+ utcmma_smem_desc_V
+ .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>();
+ } else {
+ utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>();
+ }
+ }
+ if (elect_one)
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]));
+ if (elect_one)
+ umma_arrive(cast_smem_ptr_to_uint(
+ &shared_storage.tma_v_empty_mbar[kv_stage]));
+ // Change the buffer for V
+ utcmma_smem_desc_V
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_V, BUFFERS_V>();
+ }
+ bmm_mbar_state ^= 1;
+
+ // Q * K matmul for sub-tile 1
+ {
+ Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0;
+ uint32_t tmem_acc = tmem_S_acc_1;
+
+ // mma_op 8 code
+#pragma unroll
+ for (int k = 0; k < BMM1_XMMAS_K; ++k) {
+ if (elect_one)
+ utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc,
+ utcmma_smem_desc_K.desc, tmem_acc,
+ utcmma_instruction_desc_8, (k > 0));
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>();
+ } else {
+ utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) {
+ utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *(
+ (BMM1_XMMAS_K - 1) % 4)>();
+ utcmma_smem_desc_K
+ .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>();
+ } else {
+ utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>();
+ }
+ }
+ utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 *
+ FORT_MAX(BMM1_XMMAS_K / 4, 1)>();
+ // change the smem buffer for K
+ utcmma_smem_desc_K
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_K, BUFFERS_K>();
+ // change the smem buffer for Q
+ utcmma_smem_desc_Q
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>();
+ const int kv_stage = kv_mbar_state.index();
+ if (elect_one)
+ umma_arrive(cast_smem_ptr_to_uint(
+ &shared_storage.tma_k_empty_mbar[kv_stage]));
+ }
+
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0]));
+ } // elect_one
+ }
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[1]));
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[0]));
+ }
+ const int kv_stage = kv_mbar_state.index();
+ const uint32_t kv_state = kv_mbar_state.phase();
+ ++kv_mbar_state;
+
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stage]),
+ kv_state);
+
+ // S * V matmul for sub-tile 0
+ {
+ uint32_t bmm2_ready_mbar =
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]);
+ uint32_t tmem_O = tmem_O_0;
+ uint32_t tmem_S = tmem_S_bmm2_0;
+ uint32_t scaleC = kv_loop_right_bound > kv_loop_left_bound + 1;
+
+ // mma_op 17 code
+#pragma unroll
+ for (int k = 0; k < BMM2_XMMAS_K; ++k) {
+ if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) {
+ wait_barrier(bmm2_ready_mbar +
+)KERNEL"
+ R"KERNEL(
+ (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8,
+ bmm_mbar_state);
+ }
+ if (elect_one)
+ utcmma_atmem_bsmem_h_cta1(
+ tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)),
+ utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17,
+ scaleC || k > 0);
+ if (k == BMM2_XMMAS_K - 1) {
+ utcmma_smem_desc_V
+ .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>();
+ } else {
+ utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>();
+ }
+ }
+ if (elect_one)
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]));
+ }
+ // S * V matmul for sub-tile 1
+ {
+ uint32_t bmm2_ready_mbar =
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]);
+ uint32_t tmem_O = tmem_O_1;
+ uint32_t tmem_S = tmem_S_bmm2_1;
+ uint32_t scaleC = kv_loop_right_bound > kv_loop_left_bound + 1;
+
+ // mma_op 17 code
+#pragma unroll
+ for (int k = 0; k < BMM2_XMMAS_K; ++k) {
+ if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) {
+ wait_barrier(bmm2_ready_mbar +
+ (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8,
+ bmm_mbar_state);
+ }
+ if (elect_one)
+ utcmma_atmem_bsmem_h_cta1(
+ tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)),
+ utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17,
+ scaleC || k > 0);
+ if (k == BMM2_XMMAS_K - 1) {
+ utcmma_smem_desc_V
+ .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>();
+ } else {
+ utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>();
+ }
+ }
+ if (elect_one)
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]));
+ if (elect_one)
+ umma_arrive(cast_smem_ptr_to_uint(
+ &shared_storage.tma_v_empty_mbar[kv_stage]));
+ // Change the buffer for V
+ utcmma_smem_desc_V
+ .increment_smem_buffer<SMEM_BUFFER_SIZE_V, BUFFERS_V>();
+ }
+ bmm_mbar_state ^= 1;
+ } else {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.empty_mainloop_mbar[0]),
+ empty_mainloop_mbar_state);
+ empty_mainloop_mbar_state ^= 1;
+ if (elect_one) {
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]));
+ umma_arrive(
+ cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]));
+ }
+ }
+ final_stat_mbar_state ^= 1;
+ __syncwarp();
+
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ }
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]), 0);
+ tmem_free_1sm(num_columns_per_tmem, shared_storage.tmem_base_ptrs);
+ }
+
+ // thread_specialize_op 24 code
+ else if (wid == SoftmaxWarps + CorrectionWarps + 1) {
+ // TMALDG Q, K, V
+ reg_dealloc<TmaldgWarpRegs>();
+
+ // Memory barrier states
+ uint32_t epilogue_state = 1;
+ PipelineState<stages_q> q_mbar_state(0, 1); // index, state
+ PipelineState<stages_kv> kv_mbar_state(0, 1); // index, state
+ PipelineState<2> sts_page_buffer_state(0, 0); // index, state
+ PipelineState<2> lds_page_buffer_state(0, 0); // index, state
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+
+ // global_load_shared_store_op 4 decls
+
+ // global_load_shared_store_op 7 decls
+
+ // global_load_shared_store_op 16 decls
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ int kv_loop = kv_loop_left_bound;
+
+ const int q_stage = q_mbar_state.index();
+ const int q_phase = q_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]),
+ q_phase);
+ ++q_mbar_state;
+
+ // Load Q sub-tile 0
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ qTmaTransactionBytes, elect_one);
+ }
+ {
+ uint32_t local_smem_q = cast_smem_ptr_to_uint(shared_storage.smem_Q +
+ q_stage * qBufferElems);
+ uint32_t local_smem_bar_tma_q =
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]);
+ const uint32_t row_coord = q_row_coord;
+
+ // global_load_shared_store_op 4 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_tensor_3, local_smem_q + i * TILE_M_1,
+ local_smem_bar_tma_q, i / BYTES_PER_ELEMENT_1,
+ row_coord, head_coord_1 + 0, batch_coord_1,
+ elect_one);
+ }
+ }
+
+ // Load K
+ const int k_stage = kv_mbar_state.index();
+ const int k_phase = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[k_stage]),
+ k_phase);
+
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]),
+ kTmaTransactionBytes, elect_one);
+ }
+ {
+ const int lds_page_buffer_state_idx = lds_page_buffer_state.index();
+ uint32_t local_smem_k = cast_smem_ptr_to_uint(shared_storage.smem_K +
+ k_stage * kBufferElems);
+ uint32_t local_smem_bar_tma_k =
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]);
+ const uint32_t p_col_coord = kv_loop * TILE_N_1;
+
+ // global_load_shared_store_op 7 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_tensor_2, local_smem_k + i * TILE_N_1,
+ local_smem_bar_tma_k, i / BYTES_PER_ELEMENT_1,
+ p_col_coord, head_coord_k_1, batch_coord_1,
+ elect_one);
+ }
+ }
+ } // if (kv_loop_left_bound < kv_loop_right_bound)
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ const int q_stage = q_mbar_state.index();
+ const int q_phase = q_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]),
+ q_phase);
+ ++q_mbar_state;
+
+ // Load Q sub-tile 1
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]),
+ qTmaTransactionBytes, elect_one);
+ }
+ {
+ uint32_t local_smem_q = cast_smem_ptr_to_uint(shared_storage.smem_Q +
+ q_stage * qBufferElems);
+ uint32_t local_smem_bar_tma_q =
+ cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]);
+ const uint32_t row_coord = q_row_coord + TILE_M_1;
+
+ // global_load_shared_store_op 4 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_tensor_3, local_smem_q + i * TILE_M_1,
+ local_smem_bar_tma_q, i / BYTES_PER_ELEMENT_1,
+ row_coord, head_coord_1 + 0, batch_coord_1,
+ elect_one);
+ }
+ }
+ } // if (kv_loop_left_bound < kv_loop_right_bound)
+ wait_barrier(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]),
+ epilogue_state);
+ epilogue_state ^= 1;
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ int kv_loop = kv_loop_left_bound;
+ // Load V
+ const int v_stage = kv_mbar_state.index();
+ const int v_phase = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[v_stage]),
+ v_phase);
+ ++kv_mbar_state;
+
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]),
+ vTmaTransactionBytes, elect_one);
+ }
+ {
+ const int lds_page_buffer_state_idx = lds_page_buffer_state.index();
+ uint32_t local_smem_v = cast_smem_ptr_to_uint(shared_storage.smem_V +
+ v_stage * vBufferElems);
+ uint32_t local_smem_bar_tma_v =
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]);
+ const uint32_t p_col_coord = kv_loop * TILE_N_1;
+
+ // global_load_shared_store_op 16 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1;
+ i += 128 * CTA_MMA_1) {
+ utmaldg_4d_tiled(&tma_tensor_1, local_smem_v + i * TILE_N_1,
+ local_smem_bar_tma_v, 0 + i / BYTES_PER_ELEMENT_1,
+ p_col_coord, head_coord_v_1, batch_coord_1,
+ elect_one);
+ }
+ }
+ } // if (kv_loop_left_bound < kv_loop_right_bound)
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]));
+
+// Mainloop to load K and V
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound;
+ kv_loop += 1) {
+
+ // Load K
+ const int k_stage = kv_mbar_state.index();
+ const int k_phase = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[k_stage]),
+ k_phase);
+
+)KERNEL"
+ R"KERNEL(
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]),
+ kTmaTransactionBytes, elect_one);
+ }
+ {
+ const int lds_page_buffer_state_idx = lds_page_buffer_state.index();
+ uint32_t local_smem_k = cast_smem_ptr_to_uint(shared_storage.smem_K +
+ k_stage * kBufferElems);
+ uint32_t local_smem_bar_tma_k =
+ cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]);
+ const uint32_t p_col_coord = kv_loop * TILE_N_1;
+
+ // global_load_shared_store_op 7 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_tensor_2, local_smem_k + i * TILE_N_1,
+ local_smem_bar_tma_k, i / BYTES_PER_ELEMENT_1,
+ p_col_coord, head_coord_k_1, batch_coord_1,
+ elect_one);
+ }
+ }
+ if (kv_loop + 1 < kv_loop_right_bound) {
+ }
+
+ // Load V
+ const int v_stage = kv_mbar_state.index();
+ const int v_phase = kv_mbar_state.phase();
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[v_stage]),
+ v_phase);
+ ++kv_mbar_state;
+
+ if (true) {
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]),
+ vTmaTransactionBytes, elect_one);
+ }
+ {
+ const int lds_page_buffer_state_idx = lds_page_buffer_state.index();
+ uint32_t local_smem_v = cast_smem_ptr_to_uint(shared_storage.smem_V +
+ v_stage * vBufferElems);
+ uint32_t local_smem_bar_tma_v =
+ cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]);
+ const uint32_t p_col_coord = kv_loop * TILE_N_1;
+
+ // global_load_shared_store_op 16 code
+#pragma unroll
+ for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1;
+ i += 128 * CTA_MMA_1) {
+ utmaldg_4d_tiled(&tma_tensor_1, local_smem_v + i * TILE_N_1,
+ local_smem_bar_tma_v, 0 + i / BYTES_PER_ELEMENT_1,
+ p_col_coord, head_coord_v_1, batch_coord_1,
+ elect_one);
+ }
+ }
+
+ ++lds_page_buffer_state;
+ }
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ ++lds_page_buffer_state;
+ ++sts_page_buffer_state;
+ }
+ __syncwarp();
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ }
+ }
+
+ // thread_specialize_op 25 code
+ else if (wid == SoftmaxWarps + CorrectionWarps + 2) {
+ // TMASTG (epilogue)
+ reg_dealloc<TmastgWarpRegs>();
+
+ ElementO *smem_O_0 = shared_storage.smem_O;
+ ElementO *smem_O_1 = shared_storage.smem_V;
+ // Memory barrier states
+ uint32_t epilogue_state = 0;
+
+// Persistent loop over tiles
+#pragma unroll 1
+ while (is_valid_tile) {
+ if (elect_one) {
+ arrive_barrier(cast_smem_ptr_to_uint(
+ &(shared_storage.read_tile_id_done_mbar[sched_state.index()])));
+ }
+
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]),
+ epilogue_state);
+
+ // global_store_op 20 decls
+
+// TMASTG for sub-tile 0
+#pragma unroll
+ for (int i = 0; i < BMM2_TILE_N * sizeof(ElementO); i += 128) {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_0_full_mbar[i / 128]),
+ epilogue_state);
+ const uint32_t row_coord = q_row_coord;
+ uint32_t smem_loc = cast_smem_ptr_to_uint(smem_O_0) + i * BMM2_TILE_M;
+ if (actual_seqlen_q_1 > 0) {
+
+ // global_store_op 20 code
+ utmastg_4d_tiled(&tma_tensor_5, smem_loc, 0 + i / sizeof(ElementO),
+ row_coord, head_coord_1 + 0, batch_coord_1);
+ }
+ }
+
+ tmastg_arrive();
+
+// TMASTG for sub-tile 1
+#pragma unroll
+ for (int i = 0; i < BMM2_TILE_N * sizeof(ElementO); i += 128) {
+ wait_barrier(
+ cast_smem_ptr_to_uint(&shared_storage.tma_o_1_full_mbar[i / 128]),
+ epilogue_state);
+ const uint32_t row_coord = q_row_coord + TILE_M_1;
+ uint32_t smem_loc = cast_smem_ptr_to_uint(smem_O_1) + i * BMM2_TILE_M;
+ if (actual_seqlen_q_1 > 0) {
+
+ // global_store_op 20 code
+ utmastg_4d_tiled(&tma_tensor_5, smem_loc, 0 + i / sizeof(ElementO),
+ row_coord, head_coord_1 + 0, batch_coord_1);
+ }
+ }
+ tmastg_arrive();
+
+ tmastg_wait_count<1>();
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.tma_o_0_empty_mbar[0])));
+
+ tmastg_wait_count<0>();
+ arrive_barrier(
+ cast_smem_ptr_to_uint(&(shared_storage.epilogue_done_mbar[0])));
+
+ epilogue_state ^= 1;
+
+ // Get next tile id
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ uint32_t tile_idx = tile_id_and_coord[0];
+ uint32_t bidhb, l2_mod;
+ uint32_t block = 0, bidhb_residual = 0;
+
+ fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod);
+ if (bidhb < num_hb_quotient) {
+ {
+ fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual);
+ }
+ } else {
+ {
+ fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual);
+ }
+ }
+
+ int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual;
+ uint32_t batch_idx, head_idx;
+ fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx);
+ block = num_block - 1 - block;
+
+ lean_tile_id = tile_id_and_coord[0];
+
+ blocked_row_coord = block + 0;
+ head_coord_from_grid_1 = (head_idx) + 0;
+ batch_coord_1 = batch_idx;
+ is_valid_tile = tile_id_and_coord[2] & 1;
+
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M);
+ int2 kv_loop_bounds = compute_kv_loop_bounds(
+ q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1,
+ actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ kv_loop_left_bound = kv_loop_bounds.x;
+ kv_loop_right_bound = kv_loop_bounds.y;
+ if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) {
+ kv_loop_right_bound = kv_loop_left_bound;
+ }
+ } // end of persistent loop
+ }
+
+ // thread_specialize_op 26 code
+ else if (wid == SoftmaxWarps + CorrectionWarps + 3) {
+ // Scheduler
+ reg_dealloc<SchedulerWarpRegs>();
+
+#pragma unroll 1
+ while (is_valid_tile) {
+ wait_barrier(
+ cast_smem_ptr_to_uint(
+ &shared_storage.read_tile_id_done_mbar[sched_state.index()]),
+ sched_state.phase());
+ uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint(
+ &shared_storage.tile_id[sched_state.index() * 8]);
+
+ smem_bar_set_transaction_count(
+ cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ 16, elect_one);
+
+ if (elect_one) {
+ get_next_block_id(
+ tile_id_smem_int_ptr,
+ cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]));
+ }
+ __syncwarp();
+
+ wait_barrier(cast_smem_ptr_to_uint(
+ &shared_storage.scheduler_mbar[sched_state.index()]),
+ sched_state.phase());
+ lds_128(tile_id_and_coord, tile_id_smem_int_ptr);
+ ++sched_state;
+
+ is_valid_tile = tile_id_and_coord[2] & 1;
+ }
+ }
+}
+)KERNEL";
+inline constexpr size_t sm100_d64_fprop_source_len = sizeof(sm100_d64_fprop_source) - 1;
+
+inline constexpr const char sm100_d64_fprop_flags[] = R"FLAGS(
+--gpu-architecture=sm_100a
+--std=c++17
+-w
+--define-macro=__CUDACC_RTC__
+-default-device
+--use_fast_math
+-Xptxas=-maxrregcount=128
+-DCUDA_ENABLE_TENSOR_MEMORY_INTRINSICS=1
+-DCUDA_ENABLE_VIRTCOUNT_INTRINSICS=1
+-DCUDA_ENABLE_TMEM_MANAGEMENT_INTRINSICS=1
+-DCUDA_BLACKWELL_TMA_SWIZZLE_ENABLED=1
+-DCUDA_ENABLE_FLEXIBLE_CLUSTER=1
+-DCUDA_PTX_TCMMA_V2_SUPPORTED=1
+-DCUDA_PTX_TMEM_MANAGEMENT_SUPPORTED=1
+-DCUDA_ENABLE_CLUSTER_MMA_INTRINSICS=1
+-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1
+-DCUTLASS_ENABLE_EXTENDED_PTX=1
+-DCUTLASS_ENABLE_INTERNAL_NVVM=1
+-DCUTLASS_CUDA_INTERNAL_L2_PREFETCH_ENABLED=1
+-DCUTLASS_CUDA_RP2RP_ENABLED=1
+-DCUTLASS_ENABLE_COMPILER_KNOBS=1
+-DCUTLASS_TEST_LEVEL=0
+-DCUTLASS_TEST_ENABLE_CACHED_RESULTS=1
+-DCUTLASS_CONV_UNIT_TEST_RIGOROUS_SIZE_ENABLED=1
+-DCUTLASS_DEBUG_TRACE_LEVEL=0
+-DCUTLASS_VERSIONS_GENERATED
+)FLAGS";
+inline constexpr size_t sm100_d64_fprop_flags_len = sizeof(sm100_d64_fprop_flags) - 1;
+
+} // namespace generated
+} // namespace experimental
+} // namespace cudnn_frontend
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d128_fprop_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d128_fprop_kernel.h
new file mode 100644
index 0000000..d588ce6
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d128_fprop_kernel.h
@@ -0,0 +1,1762 @@
+// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+#pragma once
+// Suppress clang warning for overlength strings (concatenated result may exceed 65536)
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Woverlength-strings"
+#endif
+
+// Suppress MSVC warning C4068 (unknown pragma) if clang pragmas are seen
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4068)
+#endif
+
+namespace cudnn_frontend {
+namespace experimental {
+namespace generated {
+
+inline constexpr const char d128_fprop_source[] =
+ R"KERNEL(
+//receive_op 0 includes
+typedef unsigned long long uint64_t;
+typedef unsigned int uint32_t;
+typedef unsigned short uint16_t;
+typedef unsigned char uint8_t;
+typedef long long int64_t;
+typedef int int32_t;
+typedef short int16_t;
+typedef signed char int8_t;
+typedef unsigned int r32;
+
+struct CUtensorMap {
+ alignas(64) uint64_t opaque[16];
+};
+
+#define CUDACC_VERSION __CUDACC_VER_MAJOR__ * 10 + __CUDACC_VER_MINOR__
+
+namespace fort {
+ static const uint64_t AMPERE_MEM_DESC_DEFAULT = uint64_t(0x1000000000000000ul);
+ static const uint64_t MEM_DESC_DEFAULT = AMPERE_MEM_DESC_DEFAULT;
+ static const uint32_t MMA_PEER_BIT_MASK = 0xFEFFFFFF;
+
+#define NEG_INFINITY __int_as_float(0xff800000)
+
+ typedef uint16_t half_t;
+ typedef uint16_t bfloat16_t;
+
+#define FORT_MIN(a,b) ((a) < (b) ? (a) : (b))
+#define FORT_MAX(a,b) ((a) > (b) ? (a) : (b))
+#define FORT_DIV_UP(a,b) (((a) + (b) - 1) / (b))
+#define FORT_ROUND_UP(a,b) ((((a) + (b) - 1) / (b)) * (b))
+
+ typedef struct tensor_descriptor {
+ static const int MAX_DIMS = 12;
+
+ int64_t num_dims;
+ int64_t dims[MAX_DIMS];
+ int64_t strides[MAX_DIMS];
+ } tensor_descriptor;
+
+ typedef struct FastDivisor {
+ uint32_t val, shr, mul;
+ } FastDivisor_t;
+
+ inline __device__ void
+ fastDivMod(const FastDivisor_t &d, uint32_t val, uint32_t &div, uint32_t &mod) {
+ div = __umulhi((uint32_t)2 * val, d.mul) >> d.shr;
+ mod = val - div * d.val;
+ }
+ __device__ __inline__ void cfence() {}
+
+#if __CUDA_ARCH__ >= 900
+
+ inline __device__ uint32_t elect_one_sync() {
+ uint32_t pred = 0;
+ uint32_t laneid = 0;
+ asm volatile(
+ "{\n"
+ ".reg .b32 %%rx;\n"
+ ".reg .pred %%px;\n"
+ " elect.sync %%rx|%%px, %2;\n"
+ "@%%px mov.s32 %1, 1;\n"
+ " mov.s32 %0, %%rx;\n"
+ "}\n" : "+r"(laneid), "+r"(pred) : "r"(0xFFFFFFFF));
+ return pred;
+ }
+
+ template<int TARGET_REG_COUNT>
+ inline __device__ void reg_alloc() {
+ // const int TARGET_REG_COUNT = 232; // Example values (use with reg_delloc's VALUE together): 224, 232, 208, 216
+ asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;\n" : : "n"(TARGET_REG_COUNT));
+ }
+
+ template<int TARGET_REG_COUNT>
+ inline __device__ void reg_dealloc() {
+ // const int TARGET_REG_COUNT = 40; // Exmaple values: 56, 40, 88, 72
+ asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;\n" : : "n"(TARGET_REG_COUNT));
+ }
+
+ inline __device__ void named_barrier_arrive(uint32_t BARRIER_ID, uint32_t NUM_THREADS) {
+ asm volatile("bar.arrive %0, %1;" : : "r"(BARRIER_ID), "r"(NUM_THREADS));
+ }
+
+ inline __device__ void named_barrier_wait(uint32_t BARRIER_ID, uint32_t NUM_THREADS) {
+ asm volatile("bar.sync %0, %1;" :: "r"(BARRIER_ID), "r"(NUM_THREADS));
+ }
+
+ inline __device__ void tmastg_arrive() {
+ asm volatile("cp.async.bulk.commit_group;");
+ }
+
+ inline __device__ void tmastg_wait() {
+ asm volatile("cp.async.bulk.wait_group.read %0;" : :"n"(0):"memory");
+ }
+
+#endif
+
+#if defined( __CUDA_ARCH__ ) && __CUDA_ARCH__ >= 900
+ inline __device__ void warpgroup_arrive() {
+ asm volatile("wgmma.fence.sync.aligned;\n" ::: "memory");
+ }
+ template <int N> inline __device__ void warpgroup_wait() {
+ asm volatile("wgmma.wait_group.sync.aligned %0;\n" ::"n"(N) : "memory");
+ }
+ inline __device__ void warpgroup_commit() {
+ asm volatile("wgmma.commit_group.sync.aligned;\n" ::: "memory");
+ }
+ template <typename T>
+ inline __device__ T &__wgmma_fence_operand(T &&reg) {
+ asm volatile("" : "+r"(reg)::"memory");
+ return reg;
+ }
+#endif
+
+#if defined( __CUDA_ARCH__ ) && __CUDA_ARCH__ >= 900
+ inline __device__ void smem_bar_init(uint32_t smem_ptr, uint32_t thread_count) {
+ asm volatile ("mbarrier.init.shared::cta.b64 [%0], %1;\n" :: "r"(smem_ptr), "r"(thread_count));
+ }
+
+ inline __device__ void smem_bar_set_transaction_count(uint32_t smem_ptr, uint32_t expected_copy_bytes, uint32_t pred = 0) {
+ asm volatile("{\n\t.reg .pred p;"
+ " \n\tsetp.eq.u32 p, %2, 1;"
+ " \n\t@p mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;"
+ " \n\t}" :: "r"(smem_ptr), "r"(expected_copy_bytes), "r"(pred));
+ }
+
+ inline __device__ uint32_t smem_bar_peek(uint32_t smem_ptr, uint32_t bar_phase) {
+ uint32_t bar_phase_out;
+ asm volatile("{\n\t.reg .pred P1;"
+ " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%1], %2;"
+ " \n\tselp.b32 %0, 1, 0, P1; \n\t}" :"=r" (bar_phase_out):"r"(smem_ptr),"r"(bar_phase));
+ return bar_phase_out;
+ }
+
+ inline __device__ void smem_bar_wait(uint32_t smem_ptr, uint32_t bar_phase) {
+
+ uint32_t large_val = 0x989680;
+ asm volatile("{\n\t.reg .pred P1;"
+ " \n\tLAB_WAIT:"
+ " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1, %2;"
+ " \n\t@P1 bra.uni DONE;"
+ " \n\tbra.uni LAB_WAIT;"
+ " \n\tDONE:"
+ " \n\t}" :: "r"(smem_ptr),"r"(bar_phase), "r"(large_val));
+
+ }
+
+ inline __device__
+ void
+ wait_barrier(uint32_t smem_int_ptr,
+ int phase_bit) // Current phase bit the barrier waiting to flip
+ {
+ asm volatile(
+ "{\n"
+ ".reg .pred P1;\n"
+ "LAB_WAIT:\n"
+ "mbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1;\n"
+ "@P1 bra.uni DONE;\n"
+ "bra.uni LAB_WAIT;\n"
+ "DONE:\n"
+ "}\n"
+ :: "r"(smem_int_ptr),
+ "r"(phase_bit));
+ }
+
+ inline __device__ void smem_bar_arrive(uint32_t smem_ptr) {
+ asm volatile("{\n\t.reg .b64 state;"
+ " \n\tmbarrier.arrive.shared::cta.b64 state, [%0];"
+ " \n\t}" :: "r"(smem_ptr));
+ }
+
+ // Barrier arrive on local smem
+ inline __device__
+ void arrive_barrier(uint32_t smem_addr) {
+ asm volatile(
+ "{\n\t"
+ "mbarrier.arrive.shared::cta.b64 _, [%0];\n\t"
+ "}"
+ :
+ : "r"(smem_addr));
+ }
+
+#endif
+
+ extern "C" __device__ uint32_t __nvvm_get_smem_pointer(void *ptr);
+
+ inline __device__ uint32_t get_smem_pointer(const void *ptr) {
+ return __nvvm_get_smem_pointer(const_cast<void *>(ptr));
+ }
+
+ extern "C" __device__ inline void *__nv_cvta_shared_to_generic_impl(size_t __ptr) {
+ return (void *)(void __attribute__((address_space(3))) *)__ptr;
+ }
+ inline __device__ void *set_smem_pointer(uint32_t ptr) {
+ return __nv_cvta_shared_to_generic_impl(ptr);
+ }
+
+ inline __device__ uint32_t
+ cast_smem_ptr_to_uint(void const* const ptr) {
+ return static_cast<uint32_t>(__cvta_generic_to_shared(ptr));
+ }
+
+ inline __device__ void stsm_x4(r32 dst, r32 src[4]) {
+ asm volatile("stmatrix.sync.aligned.m8n8.x4.shared.b16 [%0], {%1, %2, %3, %4};\n" ::"r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]));
+ }
+
+ inline __device__ void fence_view_async_shared(void){
+ asm volatile ("fence.proxy.async.shared::cta;\n");
+ }
+
+ inline __device__ void sts_32(r32 dst, r32 src[1]) {
+ asm volatile("st.shared.b32 [%0], %1;\n" :: "r"(dst), "r"(src[0]));
+ }
+
+ inline __device__ void lds_32(r32 dst[1], r32 src) {
+ asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst[0]) : "r"(src));
+ }
+
+ inline __device__ void stg_32(void *ptr, r32 val[1]) {
+ uint32_t *p = reinterpret_cast<uint32_t *>(ptr);
+ p[0] = val[0];
+ }
+
+ // Forward ReLU activations
+
+ inline __device__ uint32_t fp32_exp2(uint32_t in) {
+ uint32_t out;
+ asm volatile("ex2.approx.ftz.f32 %0, %1;\n" : "=r"(out) : "r"(in));
+ return out;
+ }
+
+ inline __device__ void fp32x2_to_bf16x2(r32 dst[1], const r32 src[2]) {
+ asm volatile("cvt.rn.bf16x2.f32 %0, %1, %2;\n" : "=r"(dst[0]) : "r"(src[1]), "r"(src[0]));
+ }
+
+ inline __device__ void bf16x2_to_fp32x2(r32 dst[2], const r32 src[1]) {
+ asm volatile( \
+ "{\n" \
+ " .reg .b16 lo, hi;\n" \
+ " mov.b32 {lo, hi}, %2;\n" \
+ " mov.b32 %0, {0, lo};\n" \
+ " mov.b32 %1, {0, hi};\n" \
+ "}\n" : "=r"(dst[0]), "=r"(dst[1]) : "r"(src[0]));
+ }
+
+ //mma_pipeline_op 1 includes
+ typedef struct AttentionDescriptor {
+ // Input parameters
+ // b - batch
+ // q_h - num heads of q/dq/o/do
+ // k_h - num heads of k/dk
+ // v_h - num heads of v/dv
+ // s_q - max sequence length of q
+ // s_kv - max sequence length of kv
+ // d - hidden dim (head dim)
+ uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v;
+ uint16_t q_heads_per_k, q_heads_per_v, min_q_heads_per_kv;
+ } AttentionDescriptor_t;
+
+ // CUtensorMap, when issued using bulk copy async functions, are cached in constant cache.
+ // But the producer kernel may have directly written to global memory, without invalidating this constant cache.
+ // This acquire fence, invalidates the memory address in constant cache, using UTMACCTL.IV.
+ inline __device__ void tma_descriptor_fence_acquire(
+ CUtensorMap const* p_desc
+ ) {
+#if (__CUDA_ARCH__ >= 900) && (CUDACC_VERSION >= 123)
+ uint64_t gmem_int_desc = reinterpret_cast<uint64_t>(p_desc);
+ asm volatile (
+ "fence.proxy.tensormap::generic.acquire.gpu [%0], 128;\n"
+ :
+ : "l"(gmem_int_desc)
+ : "memory");
+ asm volatile (
+ "cvta.global.u64 %0, %0;\n"
+ :
+ : "l"(gmem_int_desc), "l"(gmem_int_desc)
+ : "memory");
+#endif
+ }
+
+ inline __device__ void utmaldg_4d_tiled (
+ const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT
+ ) {
+ if (elect_one) {
+#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300
+ asm volatile(
+ "cp.async.bulk.tensor.4d.shared::cta.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::
+ "r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb2),
+ "r"(urb3),
+ "r"(urb4),
+ "r"(urb5),
+ "r"(urb1),
+ "l"(mem_desc) : "memory"
+ );
+#else
+ asm volatile(
+ "cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::
+ "r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb2),
+ "r"(urb3),
+ "r"(urb4),
+ "r"(urb5),
+ "r"(urb1),
+ "l"(mem_desc) : "memory"
+ );
+#endif
+ }
+ }
+
+ inline __device__ void utmastg_4d_tiled(
+ const void *p_desc,
+ uint32_t smem_offset,
+ int32_t urb0, // m
+ int32_t urb1, // n
+ int32_t urb2, // h
+ int32_t urb3, // b
+ uint64_t mem_desc = MEM_DESC_DEFAULT
+ ) {
+ asm volatile(
+ "cp.async.bulk.tensor.4d.global.shared::cta.bulk_group [%0, {%1, %2, %3, %4}], [%5];\n" ::
+ "l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb0),
+ "r"(urb1),
+ "r"(urb2),
+ "r"(urb3),
+ "r"(smem_offset) : "memory"
+ );
+ }
+
+ inline __device__ void ldgdepbar() {
+ asm volatile("cp.async.commit_group;\n" ::);
+ }
+
+ template<int STAGES>
+ inline __device__ void depbar() {
+ asm volatile("cp.async.wait_group %0;\n" :: "n"(STAGES));
+ }
+
+ //mma_loop_op 2 includes
+
+ //global_load_shared_store_op 4 includes
+
+ // shared_load_op 5 includes
+
+ // shared_load_op 6 includes
+
+ //global_load_shared_store_op 7 includes
+
+ //mma_op 8 includes
+)KERNEL"
+ R"KERNEL(
+// === Section: GMMA Operations ===
+ inline __device__ void bf16gmma_fp32_64x128x16_TN_asmem_bsmem_isb(const uint64_t &desc_a, const uint64_t &desc_b, r32 acc[64]) {
+ __wgmma_mma_async_bf16(64, 128, 16, false, false, false, false, true, acc, desc_a, desc_b);
+ warpgroup_commit();
+ }
+
+ // === Section: GMMA Operations ===
+ inline __device__ void bf16gmma_fp32_64x128x16_TN_asmem_bsmem(const uint64_t &desc_a, const uint64_t &desc_b, r32 acc[64]) {
+ __wgmma_mma_async_bf16(64, 128, 16, false, false, false, false, true, acc, desc_a, desc_b);
+ }
+
+#define BMM_S_GMMA bf16gmma_fp32_64x128x16_TN_asmem_bsmem
+#define BMM_S_GMMA_ISB bf16gmma_fp32_64x128x16_TN_asmem_bsmem_isb
+#define BMM_S_GMMA_C0 bf16gmma_fp32_64x128x16_TN_asmem_bsmem_ignoreC
+
+ //pointwise_calc_op 9 includes
+
+ //global_load_op 10 includes
+
+ //softmax_op 12 includes
+
+ // global_store_op 13 includes
+
+ // global_store_op 14 includes
+
+ // shared_load_op 15 includes
+
+ //global_load_shared_store_op 16 includes
+
+ //mma_op 17 includes
+ inline __device__ void bf16gmma_fp32_64x128x16_TT_arf_bsmem_isb(const r32 a[4], const uint64_t &desc_b, r32 acc[64]) {
+ __wgmma_mma_async_bf16(64, 128, 16, false, false, true, false, true, acc, a, desc_b);
+ warpgroup_commit();
+ }
+
+ inline __device__ void bf16gmma_fp32_64x128x16_TT_arf_bsmem(const r32 a[4], const uint64_t &desc_b, r32 acc[64]) {
+ __wgmma_mma_async_bf16(64, 128, 16, false, false, true, false, true, acc, a, desc_b);
+ }
+
+#define BMM_O_GMMA bf16gmma_fp32_64x128x16_TT_arf_bsmem
+#define BMM_O_GMMA_ISB bf16gmma_fp32_64x128x16_TT_arf_bsmem_isb
+#define BMM_O_GMMA_C0 bf16gmma_fp32_64x128x16_TT_arf_bsmem_ignoreC
+
+ // global_store_op 20 includes
+
+ //output_loop_op 3 includes
+
+ // shared_store_op 18 includes
+
+ // shared_load_op 19 includes
+} // namespace fort
+
+//receive_op 0 types
+using namespace fort;
+
+static constexpr int THREADS_PER_WARP_0 = 32;
+static constexpr int WARPS_PER_GROUP_0 = FORT_MIN(4, 384 / THREADS_PER_WARP_0);
+static constexpr int THREADS_PER_WARP_GROUP_0 = THREADS_PER_WARP_0 * WARPS_PER_GROUP_0;
+static constexpr int BITS_PER_REGISTER_0 = 32; // NOTE: sizeof(uint)
+static constexpr int BYTES_PER_REGISTER_0 = BITS_PER_REGISTER_0 / 8;
+static constexpr int THREADS_PER_GROUP_0 = WARPS_PER_GROUP_0 * THREADS_PER_WARP_0;
+
+// mma_pipeline_op 1 types
+static constexpr int BYTES_PER_BANK_1 = 16;
+static constexpr int BITS_PER_ELEMENT_1 = 16;
+static constexpr int ELEMS_PER_BANK_1 = BYTES_PER_BANK_1 * 8 / BITS_PER_ELEMENT_1;
+static constexpr int BYTES_PER_ELEMENT_1 = BITS_PER_ELEMENT_1 / 8;
+static constexpr int BYTES_PER_FP16_1 = 2;
+static constexpr int ELEMS_PER_VECTOR_1 = BYTES_PER_REGISTER_0 / BYTES_PER_ELEMENT_1;
+static constexpr int BITS_PER_ACC_1 = 32;
+static constexpr int BYTES_PER_ACC_1 = BITS_PER_ACC_1 / 8;
+static constexpr int TILE_M_1 = 64;
+static constexpr int TILE_N_1 = 128;
+static constexpr int TILE_K_1 = 128;
+static constexpr int TILE_O_1 = 128;
+static constexpr int TILE_V_1 = TILE_K_1;
+static constexpr int TILE_DV_1 = 128;
+static constexpr int WARP_TILE_M_1 = 16;
+static constexpr int WARP_TILE_N_1 = 16;
+static constexpr int WARP_TILE_K_1 = 32 / BYTES_PER_ELEMENT_1;
+static constexpr int WARPS_M_1 = 64 / 16;
+static constexpr int WARPS_N_1 = 16 / 16;
+static constexpr int WARPS_K_1 = 16 / 16;
+static constexpr int STAGES_1 = 1;
+static constexpr int GROUPS_M_1 = 1;
+static constexpr int GMMA_TILE_M_1 = WARPS_M_1 * WARP_TILE_M_1;
+static constexpr int GMMA_TILE_K_1 = WARPS_K_1 * WARP_TILE_K_1;
+static constexpr int WARP_TILES_M_1 = TILE_M_1 / WARP_TILE_M_1;
+static constexpr int WARP_TILES_N_1 = TILE_N_1 / WARP_TILE_N_1;
+static constexpr int WARP_TILES_K_1 = TILE_K_1 / WARP_TILE_K_1;
+static constexpr int WARP_REGS_1 = 8;
+static constexpr int REGS_M_1 = WARP_TILES_M_1 / WARPS_M_1;
+static constexpr int REGS_N_1 = WARP_TILES_N_1 / WARPS_N_1;
+static constexpr int REGS_K_1 = WARP_TILES_K_1 / WARPS_K_1;
+static constexpr int REGS_K_FOR_DP_1 = TILE_V_1 / 16;
+
+static constexpr int REGS_dQ_1 = TILE_O_1 / 16;
+static constexpr int REGS_O_1 = 8;
+
+static constexpr int CGA_M_1 = 1;
+static constexpr int CGA_N_1 = 1;
+static constexpr int CTA_MMA_1 = 1;
+static constexpr int M_TILES_PER_OUTPUT_TILE_1 = 4;
+static constexpr int N_TILES_PER_OUTPUT_TILE_1 = 1;
+
+static constexpr int CTA_TILE_M_1 = TILE_M_1 * GROUPS_M_1;
+static constexpr int CTA_TILE_N_1 = 128;
+static constexpr int CTA_TILE_K_1 = 128;
+static constexpr int BUFFERS_Q_1 = 2;
+static constexpr int BUFFERS_K_1 = 2;
+static constexpr int BUFFERS_V_1 = 2;
+static constexpr int BUFFERS_O_1 = 1;
+static constexpr int BUFFERS_D_1 = 1;
+static constexpr int SMEM_Q_1 = TILE_M_1 * TILE_K_1 * BYTES_PER_ELEMENT_1 * 2;
+static constexpr int SMEM_K_1 = TILE_N_1 * TILE_K_1 * BYTES_PER_ELEMENT_1;
+static constexpr int SMEM_V_1 = TILE_N_1 * TILE_K_1 * BYTES_PER_ELEMENT_1;
+static constexpr int SMEM_PAGE_TABLE_1 = FORT_ROUND_UP(TILE_N_1 * 2 * 2 * sizeof(int), 1024);
+static constexpr int SMEM_OFFSET_Q_1 = 1024 + (false ? 0 : SMEM_PAGE_TABLE_1);
+static constexpr int SMEM_OFFSET_K_1 = SMEM_OFFSET_Q_1 + SMEM_Q_1 * BUFFERS_Q_1;
+static constexpr int SMEM_OFFSET_V_1 = SMEM_OFFSET_K_1 + SMEM_K_1 * BUFFERS_K_1;
+static constexpr int SMEM_OFFSET_O_1 = SMEM_OFFSET_V_1 + SMEM_V_1 * BUFFERS_V_1;
+static constexpr int SMEM_OFFSET_D_1 = SMEM_OFFSET_O_1;
+static constexpr int SMEM_OFFSET_BAND_BIAS_1 = SMEM_OFFSET_O_1;
+
+static constexpr int THREADS_ON_TILE_BARRIER_1 = 256+32+0;
+static constexpr int TILE_ID_SYNC_2_BARRIER_1 = 2;
+static constexpr int TILE_ID_SYNC_3_BARRIER_1 = 3;
+static constexpr int SOFTMAX_1_BARRIER_1 = 4;
+static constexpr int SOFTMAX_2_BARRIER_1 = 5;
+static constexpr int MATH_WORKGROUP_1 = 6;
+static constexpr int TMA_SYNC_BARRIER_1 = 7;
+
+static constexpr uint32_t BYTES_PER_GMMA_K_1 = GMMA_TILE_K_1 * BYTES_PER_ELEMENT_1;
+static constexpr uint32_t BYTES_PER_GMMA_K_NO_4LSB_1 = BYTES_PER_GMMA_K_1 >> 4;
+static constexpr uint32_t BYTES_PER_GMMA_K_TRANS_1 = GMMA_TILE_K_1 * 128;
+static constexpr uint32_t BYTES_PER_GMMA_K_NO_4LSB_TRANS_1 = BYTES_PER_GMMA_K_TRANS_1 >> 4;
+
+static constexpr uint32_t GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1 = 2;
+static constexpr uint32_t GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1 = 62; // bits 63-62
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_Q_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_Q_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_Q_1 &
+((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1))
+<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1;
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_K_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_K_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_K_1 &
+((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1))
+<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1;
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_V_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_V_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_V_1 &
+((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1))
+<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1;
+
+static constexpr uint32_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1 = 32; // bits 45-32
+static constexpr uint64_t BYTES_PER_LEADING_DIM_1 = 128;
+static constexpr uint64_t STRIDE_BYTE_OFFSET_Q_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2
+static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 = STRIDE_BYTE_OFFSET_Q_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1;
+static constexpr uint64_t STRIDE_BYTE_OFFSET_K_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2
+static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_K_1 = STRIDE_BYTE_OFFSET_K_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1;
+static constexpr uint64_t STRIDE_BYTE_OFFSET_V_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2
+static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_V_1 = STRIDE_BYTE_OFFSET_V_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1;
+
+static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1 = 16; // bits 29-16
+static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_Q_1 = 128 * 64 / 16; // Not used???
+static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_Q_1
+<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1;
+static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_K_1 = 128 * 32 / 16; // Not used???
+static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_K_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_K_1
+<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1;
+static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_V_1 = 128 * TILE_N_1 / 16;
+static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_V_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_V_1
+<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1;
+
+inline __device__ constexpr uint64_t create_gmma_desc_q_1() {
+ return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_Q_1)
+ | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_Q_1
+ | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_Q_1;
+}
+
+inline __device__ constexpr uint64_t create_gmma_desc_k_1() {
+ return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_K_1)
+ | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_K_1
+ | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_K_1;
+}
+
+// === Section: GMMA Descriptors & Mask Helpers ===
+)KERNEL"
+ R"KERNEL(
+// === Section: GMMA Descriptors & Mask Helpers ===
+inline __device__ constexpr uint64_t create_gmma_desc_v_1() {
+ return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_V_1)
+ | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_V_1
+ | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_V_1;
+}
+
+class Gmma_descriptor {
+ public:
+ inline __device__ Gmma_descriptor(uint64_t desc_) {
+ desc = desc_;
+ }
+ template<int BYTES_PER_BUFFER, int BUFFER_COUNT>
+ inline __device__ void set_smem(uint32_t smem) {
+ desc |= (static_cast<uint64_t>(smem & 0xFFFFFF) >> 4);
+
+ max_desc = desc + (BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1);
+ }
+ template<int BYTES_PER_BUFFER, int BUFFER_COUNT>
+ inline __device__ void increment_smem_buffer() {
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+ tmp.x += (desc >= max_desc) ? -(BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1)
+ : (BYTES_PER_BUFFER >> 4);
+ }
+
+ uint64_t desc;
+ uint64_t max_desc;
+};
+
+//global_load_shared_store_op 4 types
+static constexpr int BITS_PER_ELEMENT_4 = 16;
+static constexpr int BYTES_PER_ELEMENT_4 = BITS_PER_ELEMENT_4 / 8;
+static constexpr int BYTES_PER_ACCESS_4 = 16;
+static constexpr int TILE_M_4 = 64;
+static constexpr int TILE_N_4 = 128;
+static constexpr int BYTES_PER_SMEM_4 = TILE_M_4 * TILE_N_4 * BYTES_PER_ELEMENT_4;
+
+// shared_load_op 5 types
+static constexpr int BITS_PER_ELEMENT_5 = 16;
+static constexpr int BYTES_PER_ELEMENT_5 = 2;
+static constexpr int BYTES_PER_QUAD_5 = 16;
+static constexpr int WARP_TILE_M_5 = 16;
+static constexpr int WARP_TILE_N_5 = 16;
+static constexpr int TILE_M_5 = 64;
+static constexpr int TILE_N_5 = 128;
+static constexpr int BYTES_PER_SMEM_5 = TILE_M_5 * TILE_N_5 * BYTES_PER_ELEMENT_5;
+static constexpr int WARPS_M_5 = 4;
+static constexpr int WARPS_N_5 = 1;
+static constexpr int WARP_TILES_M_5 = TILE_M_5 / WARP_TILE_M_5;
+static constexpr int WARP_TILES_N_5 = TILE_N_5 / WARP_TILE_N_5;
+static constexpr int THREADS_PER_WARP_TILE_M_5 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_5 = 4;
+static constexpr int REGS_M_5 = WARP_TILES_M_5 / WARPS_M_5;
+static constexpr int REGS_N_5 = WARP_TILES_N_5 / WARPS_N_5;
+static constexpr int BYTES_PER_LD_5 = 128;
+static constexpr int SWIZZLE_SCALE_5 = FORT_MIN(BYTES_PER_LD_5 / 16, WARPS_PER_GROUP_0 * 4);
+
+// shared_load_op 6 types
+static constexpr int BITS_PER_ELEMENT_6 = 16;
+static constexpr int BYTES_PER_ELEMENT_6 = 2;
+static constexpr int BYTES_PER_QUAD_6 = 16;
+static constexpr int WARP_TILE_M_6 = 16;
+static constexpr int WARP_TILE_N_6 = 16;
+static constexpr int TILE_M_6 = 128;
+static constexpr int TILE_N_6 = 128;
+
+static constexpr int BYTES_PER_SMEM_6 = TILE_M_6 * TILE_N_6 * BYTES_PER_ELEMENT_6;
+static constexpr int WARPS_M_6 = 1;
+static constexpr int WARPS_N_6 = 1;
+static constexpr int WARP_TILES_M_6 = TILE_M_6 / WARP_TILE_M_6;
+static constexpr int WARP_TILES_N_6 = TILE_N_6 / WARP_TILE_N_6;
+static constexpr int THREADS_PER_WARP_TILE_M_6 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_6 = 4;
+static constexpr int REGS_M_6 = WARP_TILES_M_6 / WARPS_M_6;
+static constexpr int REGS_N_6 = WARP_TILES_N_6 / WARPS_N_6;
+static constexpr int BYTES_PER_LD_6 = 128;
+static constexpr int SWIZZLE_SCALE_6 = FORT_MIN(BYTES_PER_LD_6 / 16, WARPS_PER_GROUP_0 * 4);
+
+//global_load_shared_store_op 7 types
+static constexpr int BITS_PER_ELEMENT_7 = 16;
+static constexpr int BYTES_PER_ELEMENT_7 = BITS_PER_ELEMENT_7 / 8;
+static constexpr int BYTES_PER_ACCESS_7 = 16;
+static constexpr int TILE_M_7 = 128;
+static constexpr int TILE_N_7 = 128;
+static constexpr int BYTES_PER_SMEM_7 = TILE_M_7 * TILE_N_7 * BYTES_PER_ELEMENT_7;
+
+//mma_op 8 types
+static constexpr int BYTES_PER_ELEMENT_8 = 2;
+static constexpr int BYTES_PER_ACC_8 = 4;
+static constexpr int WARP_TILE_M_8 = 16;
+static constexpr int WARP_TILE_N_8 = 16;
+static constexpr int WARP_TILE_K_8 = 16;
+static constexpr int TILE_M_8 = 64;
+static constexpr int TILE_N_8 = 128;
+static constexpr int TILE_K_8 = 128;
+static constexpr int WARPS_M_8 = 4;
+static constexpr int WARPS_N_8 = 1;
+static constexpr int WARP_TILES_M_8 = TILE_M_8 / WARP_TILE_M_8;
+static constexpr int WARP_TILES_N_8 = TILE_N_8 / WARP_TILE_N_8;
+static constexpr int MMA_STEPS_K_8 = TILE_K_8 / WARP_TILE_K_8;
+static constexpr int WARP_REGS_8 = 8;
+static constexpr int REGS_M_8 = WARP_TILES_M_8 / WARPS_M_8;
+static constexpr int REGS_N_8 = WARP_TILES_N_8 / WARPS_N_8;
+
+//pointwise_calc_op 9 types
+static constexpr int WARP_TILE_M_9 = 16;
+static constexpr int WARP_TILE_N_9 = 16;
+static constexpr int TILE_M_9 = 64;
+static constexpr int TILE_N_9 = 128;
+static constexpr int WARPS_M_9 = 4;
+static constexpr int WARPS_N_9 = 1;
+static constexpr int WARP_TILES_M_9 = TILE_M_9 / WARP_TILE_M_9;
+static constexpr int WARP_TILES_N_9 = TILE_N_9 / WARP_TILE_N_9;
+static constexpr int WARP_REGS_9 = 8;
+static constexpr int REGS_M_9 = WARP_TILES_M_9 / WARPS_M_9;
+static constexpr int REGS_N_9 = WARP_TILES_N_9 / WARPS_N_9;
+
+//global_load_op 10 types
+static constexpr int BITS_PER_ELEMENT_10 = 32;
+static constexpr int BYTES_PER_ELEMENT_10 = 4;
+static constexpr int REGISTERS_PER_VECTOR_10 = 1;
+static constexpr int REGISTERS_PER_ACCESS_10 = 1;
+
+//mha_mask_op 11 types
+static constexpr int WARP_TILE_M_11 = 16;
+static constexpr int WARP_TILE_N_11 = 16;
+static constexpr int TILE_M_11 = 64;
+static constexpr int TILE_N_11 = 128;
+static constexpr int WARPS_M_11 = 4;
+static constexpr int WARPS_N_11 = 1;
+static constexpr int WARP_TILES_M_11 = TILE_M_11 / WARP_TILE_M_11;
+static constexpr int WARP_TILES_N_11 = TILE_N_11 / WARP_TILE_N_11;
+static constexpr int WARP_REGS_11 = 8;
+static constexpr int REGS_M_11 = WARP_TILES_M_11 / WARPS_M_11;
+static constexpr int REGS_N_11 = WARP_TILES_N_11 / WARPS_N_11;
+inline __device__ bool compute_diagonal_band_mask_11(const int row, const int col, const int actual_seqlen_kv, const int actual_seqlen_q, const int shift_right_bound, const int left_bound) {
+ constexpr bool is_bottom_right_alignment = false;
+ constexpr bool is_shift_right_bound = false;
+ constexpr bool is_right_bound = true;
+ constexpr bool is_left_bound = false;
+ constexpr bool need_oob_check = false;
+
+ const int diag = is_bottom_right_alignment ? row + (actual_seqlen_kv - actual_seqlen_q) : row;
+ const int shifted_right_bound = is_shift_right_bound ? diag + shift_right_bound : diag;
+ const bool right_bound_mask = is_right_bound ? col <= shifted_right_bound : true;
+ const bool left_bound_mask = is_left_bound ? col + left_bound > diag : true;
+ const bool oob_check = need_oob_check ? (row < actual_seqlen_q && col < actual_seqlen_kv) : true;
+ return right_bound_mask && left_bound_mask && oob_check;
+}
+
+//softmax_op 12 types
+static constexpr int BYTES_PER_ELEMENT_12 = 2;
+static constexpr int WARP_TILE_M_12 = 16;
+static constexpr int WARP_TILE_N_12 = 16;
+static constexpr int TILE_M_12 = 64;
+static constexpr int TILE_N_12 = 128;
+static constexpr int WARPS_M_12 = 4;
+static constexpr int WARPS_N_12 = 1;
+static constexpr int WARP_TILES_M_12 = TILE_M_12 / WARP_TILE_M_12;
+
+static constexpr int WARP_TILES_N_12 = TILE_N_12 / WARP_TILE_N_12;
+static constexpr int THREADS_PER_WARP_TILE_M_12 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_12 = 4;
+static constexpr int WARP_REGS_12 = 8;
+static constexpr int REGS_M_12 = WARP_TILES_M_12 / WARPS_M_12;
+static constexpr int REGS_N_12 = WARP_TILES_N_12 / WARPS_N_12;
+static constexpr int ROWS_PER_THREAD_12 = TILE_M_12 / WARPS_M_12 / THREADS_PER_WARP_TILE_M_12;
+
+// global_store_op 13 types
+static constexpr int BYTES_PER_ELEMENT_13 = 4;
+static constexpr int WARP_TILE_M_13 = 16;
+static constexpr int WARP_TILE_N_13 = 16;
+static constexpr int TILE_M_13 = 64;
+static constexpr int TILE_N_13 = 128;
+static constexpr int WARPS_M_13 = 4;
+static constexpr int WARPS_N_13 = 1;
+static constexpr int WARP_TILES_M_13 = TILE_M_13 / WARP_TILE_M_13;
+static constexpr int WARP_TILES_N_13 = TILE_N_13 / WARP_TILE_N_13;
+static constexpr int THREADS_PER_WARP_TILE_M_13 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_13 = 4;
+static constexpr int ROWS_PER_THREAD_13 = TILE_M_13 / WARPS_M_13 / THREADS_PER_WARP_TILE_M_13;
+
+// global_store_op 14 types
+static constexpr int BYTES_PER_ELEMENT_14 = 4;
+static constexpr int WARP_TILE_M_14 = 16;
+static constexpr int WARP_TILE_N_14 = 16;
+static constexpr int TILE_M_14 = 64;
+static constexpr int TILE_N_14 = 128;
+static constexpr int WARPS_M_14 = 4;
+static constexpr int WARPS_N_14 = 1;
+static constexpr int WARP_TILES_M_14 = TILE_M_14 / WARP_TILE_M_14;
+static constexpr int WARP_TILES_N_14 = TILE_N_14 / WARP_TILE_N_14;
+static constexpr int THREADS_PER_WARP_TILE_M_14 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_14 = 4;
+static constexpr int ROWS_PER_THREAD_14 = TILE_M_14 / WARPS_M_14 / THREADS_PER_WARP_TILE_M_14;
+
+// shared_load_op 15 types
+static constexpr int BITS_PER_ELEMENT_15 = 16;
+static constexpr int BYTES_PER_ELEMENT_15 = 2;
+static constexpr int BYTES_PER_QUAD_15 = 16;
+static constexpr int WARP_TILE_M_15 = 16;
+static constexpr int WARP_TILE_N_15 = 16;
+static constexpr int TILE_M_15 = 128;
+static constexpr int TILE_N_15 = 128;
+static constexpr int BYTES_PER_SMEM_15 = TILE_M_15 * TILE_N_15 * BYTES_PER_ELEMENT_15;
+static constexpr int WARPS_M_15 = 1;
+static constexpr int WARPS_N_15 = 1;
+static constexpr int WARP_TILES_M_15 = TILE_M_15 / WARP_TILE_M_15;
+static constexpr int WARP_TILES_N_15 = TILE_N_15 / WARP_TILE_N_15;
+static constexpr int THREADS_PER_WARP_TILE_M_15 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_15 = 4;
+static constexpr int REGS_M_15 = WARP_TILES_M_15 / WARPS_M_15;
+static constexpr int REGS_N_15 = WARP_TILES_N_15 / WARPS_N_15;
+static constexpr int BYTES_PER_LD_15 = 128;
+static constexpr int SWIZZLE_SCALE_15 = FORT_MIN(BYTES_PER_LD_15 / 16, WARPS_PER_GROUP_0 * 4);
+
+//global_load_shared_store_op 16 types
+static constexpr int BITS_PER_ELEMENT_16 = 16;
+static constexpr int BYTES_PER_ELEMENT_16 = BITS_PER_ELEMENT_16 / 8;
+static constexpr int BYTES_PER_ACCESS_16 = 16;
+static constexpr int TILE_M_16 = 128;
+static constexpr int TILE_N_16 = 128;
+static constexpr int BYTES_PER_SMEM_16 = TILE_M_16 * TILE_N_16 * BYTES_PER_ELEMENT_16;
+
+//mma_op 17 types
+static constexpr int BYTES_PER_ELEMENT_17 = 2;
+static constexpr int BYTES_PER_ACC_17 = 4;
+static constexpr int WARP_TILE_M_17 = 16;
+static constexpr int WARP_TILE_N_17 = 16;
+static constexpr int WARP_TILE_K_17 = 16;
+static constexpr int TILE_M_17 = 64;
+static constexpr int TILE_N_17 = 128;
+static constexpr int TILE_K_17 = 128;
+static constexpr int WARPS_M_17 = 4;
+static constexpr int WARPS_N_17 = 1;
+static constexpr int WARP_TILES_M_17 = TILE_M_17 / WARP_TILE_M_17;
+static constexpr int WARP_TILES_N_17 = TILE_N_17 / WARP_TILE_N_17;
+static constexpr int MMA_STEPS_K_17 = TILE_K_17 / WARP_TILE_K_17;
+static constexpr int WARP_REGS_17 = 8;
+static constexpr int REGS_M_17 = WARP_TILES_M_17 / WARPS_M_17;
+static constexpr int REGS_N_17 = WARP_TILES_N_17 / WARPS_N_17;
+
+// global_store_op 20 types
+
+// mma_loop_op 2 types
+inline __device__ int2 compute_kv_loop_bounds(const int row_coord, const int ROW_TILE_SIZE, const int COL_TILE_SIZE, const int actual_seqlen_kv, const int actual_seqlen_q, const int shift_right_bound, const int left_bound)
+{
+ constexpr bool is_right_bound = true;
+ constexpr bool is_right_bound_bottom_right_alignment = false;
+ constexpr bool is_shift_right_bound = false;
+ constexpr bool is_left_bound = false;
+ constexpr bool is_left_bound_bottom_right_alignment = false;
+
+ const int right_bound_diagonal = is_right_bound_bottom_right_alignment ? row_coord + (actual_seqlen_kv - actual_seqlen_q) : row_coord;
+ const int shifted_right_bound_diagonal = is_shift_right_bound ? right_bound_diagonal + shift_right_bound : right_bound_diagonal;
+ const int left_bound_diagonal = is_left_bound_bottom_right_alignment ? row_coord + (actual_seqlen_kv - actual_seqlen_q) : row_coord;
+
+ const int kv_loop_left_bound = is_left_bound ? FORT_MAX(0, (left_bound_diagonal - left_bound) / COL_TILE_SIZE) : 0;
+ const int kv_loop_right_bound = is_right_bound ? FORT_MIN(FORT_DIV_UP(shifted_right_bound_diagonal + ROW_TILE_SIZE, COL_TILE_SIZE), FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE)) : FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE);
+ return make_int2(kv_loop_left_bound, kv_loop_right_bound);
+}
+
+// output_loop_op 3 types
+static constexpr int BYTES_PER_BANK_3 = 16;
+static constexpr int LDS_TILE_M_3 = 16;
+static constexpr int LDS_TILE_N_3 = 32;
+static constexpr int ACC_CORE_MATRIX_ROWS_3 = 8; // NOTE: fixed due to GMMA design
+static constexpr int ACC_CORE_MATRIX_COLS_3 = 8; // NOTE: fixed due to GMMA design
+static constexpr int ELEMENTS_PER_VECTOR_3 = 8;
+static constexpr int LDS_PER_TILE_3 = ELEMENTS_PER_VECTOR_3 / 2;
+static constexpr int LDS_TILES_N_3 = FORT_MAX(CTA_TILE_N_1 / LDS_TILE_N_3, 1);
+static constexpr int LDS_TILES_M_3 = FORT_MAX(1, (CTA_TILE_M_1 / GROUPS_M_1) / (LDS_TILE_M_3 * WARPS_PER_GROUP_0));
+static constexpr int VECTORS_PER_LDS_TILES_3 = LDS_TILE_M_3 / ACC_CORE_MATRIX_ROWS_3;
+static constexpr int STS_PER_OUTPUT_TILE_N_3 = CTA_TILE_N_1 / ACC_CORE_MATRIX_COLS_3;
+static constexpr int STSM_X4_PER_OUTPUT_TILE_N_3 = CTA_TILE_N_1 / ACC_CORE_MATRIX_COLS_3 / 2;
+static constexpr int BANKS_PER_PAD_LINE_3 = BYTES_PER_ACC_1 == 4 ? 1 : 2;
+
+static constexpr int PADDING_BYTES_3 = BANKS_PER_PAD_LINE_3 * BYTES_PER_BANK_3 * LDS_PER_TILE_3;
+)KERNEL"
+ R"KERNEL(
+static constexpr int BYTES_PER_STS_PER_WARP_3= 16 * THREADS_PER_WARP_0; // 16 bytes due to STS_128
+static constexpr int BYTES_PER_LDS_TILE_3 = LDS_TILE_N_3 * LDS_TILE_M_3 * BYTES_PER_ACC_1 + PADDING_BYTES_3;
+static constexpr int BYTES_PER_WARP_3 = LDS_TILES_N_3 * BYTES_PER_LDS_TILE_3;
+
+static constexpr int ELEMS_PER_STS_BLOCK_3 = 16;
+
+static constexpr int STG_THREADS_PER_TILE_N_3 = LDS_TILE_N_3 / ELEMENTS_PER_VECTOR_3;
+static constexpr int EPILOGUE_SMEM_SIZE_PER_XMMA_M_3 = BYTES_PER_WARP_3 * WARPS_PER_GROUP_0;
+
+// shared_store_op 18 types
+
+// shared_load_op 19 types
+static constexpr int BITS_PER_ELEMENT_19 = 32 * 1;
+static constexpr int BYTES_PER_ELEMENT_19 = BITS_PER_ELEMENT_19 / 8;
+static constexpr int BITS_PER_VECTOR_19 = BITS_PER_ELEMENT_19 * ELEMENTS_PER_VECTOR_3;
+static constexpr int BYTES_PER_VECTOR_19 = BITS_PER_VECTOR_19 / 8;
+static constexpr int REGISTERS_PER_VECTOR_19 = BITS_PER_VECTOR_19 / BITS_PER_REGISTER_0;
+
+//receive_op 0 code
+
+// === Section: Kernel Function ===
+)KERNEL"
+ R"KERNEL(
+// === Section: Kernel Function ===
+extern "C" __global__ __launch_bounds__(384, 1)
+void cudnn_generated_oss_sdpa_sm90_flash_fprop_wgmma_f16_knob_7_64x128x128_4x1x1_cga1x1x1_kernel0_0(const AttentionDescriptor_t attnDesc
+, int num_tiles_1
+, const FastDivisor_t tiles_hr_div_1
+, const FastDivisor_t tiles_r_div_1
+, int32_t* tile_id_counter
+, __grid_constant__ const CUtensorMap tma_Q
+, __grid_constant__ const CUtensorMap tma_K
+, float attn_scale
+, float neg_infinity
+, void* d_max
+, fort::tensor_descriptor desc_max
+, void* d_sum_exp
+, fort::tensor_descriptor desc_sum_exp
+, __grid_constant__ const CUtensorMap tma_V
+, __grid_constant__ const CUtensorMap tma_O
+) {
+ extern __shared__ char smem_[];
+ uint32_t smem_0 = get_smem_pointer(smem_);
+
+ //receive_op 0 decls
+
+ // mma_pipeline_op 1 decls
+ const uint32_t tid = threadIdx.x % THREADS_PER_GROUP_0;
+ const uint32_t gid = threadIdx.x / THREADS_PER_GROUP_0;
+ const uint32_t wid = threadIdx.x / 32;
+ const uint32_t tiw = threadIdx.x % 32;
+
+ const uint32_t elect_one = fort::elect_one_sync();
+
+ uint32_t smem_1 = smem_0;
+ uint32_t smem_bar_qkv_1 = smem_1;
+ uint32_t smem_page = smem_1 + 1024;
+ uint32_t smem_Q = smem_1 + SMEM_OFFSET_Q_1;
+ uint32_t smem_K = smem_1 + SMEM_OFFSET_K_1;
+ uint32_t smem_V = smem_1 + SMEM_OFFSET_V_1;
+ uint32_t smem_O = smem_1 + SMEM_OFFSET_O_1;
+ uint32_t smem_d_1 = smem_1 + SMEM_OFFSET_D_1;
+ uint32_t smem_band_bias_1 = smem_1 + SMEM_OFFSET_BAND_BIAS_1;
+
+ uint32_t smem_bar_qkv_tma_1 = smem_bar_qkv_1;
+ uint32_t smem_bar_qkv_mma_1 = smem_bar_qkv_1 + 1 * 8 * (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0);
+ uint32_t smem_tile_id_1 = smem_bar_qkv_1 + 2 * 8 * (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0);
+ uint32_t smem_bar_tile_id_tma_1 = smem_tile_id_1 + 16;
+ uint32_t smem_bar_bias_tma_1 = smem_bar_tile_id_tma_1 + 8;
+
+ uint32_t smem_bar_bias_mma_1 = smem_bar_bias_tma_1 + 8 * 2;
+
+ if (elect_one) {
+ for (int i = wid; i < (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0); i+=12) {
+ smem_bar_init(smem_bar_qkv_tma_1 + i * 8, 1);
+ smem_bar_init(smem_bar_qkv_mma_1 + i * 8, 2);
+ }
+ }
+ __syncthreads();
+
+ // mma_pipeline_op 1 code
+ const int actual_num_tiles_1 = num_tiles_1;
+ if (gid == 0) {
+ reg_dealloc<40>();
+ const uint32_t local_wid = wid % 4;
+
+ uint32_t tile_id;
+ uint32_t batch_coord_1 = 0, head_coord_1 = 0, q_row_coord = 0, rows_temp;
+ uint32_t head_coord_from_grid_1, head_coord_k_1, head_coord_v_1, head_coord_q_offset_1;
+ int actual_seqlen_kv_1 = attnDesc.s_kv, actual_seqlen_q_1 = attnDesc.s_q, oob_for_stats_1 = attnDesc.s_q;
+
+ if (local_wid == 0) {
+ uint32_t smem_bar_q_tma = smem_bar_qkv_tma_1;
+ uint32_t smem_bar_k_tma = smem_bar_q_tma + 8 * BUFFERS_Q_1;
+ uint32_t smem_bar_v_tma = smem_bar_k_tma + 8 * BUFFERS_K_1;
+
+ uint32_t smem_bar_q_mma = smem_bar_qkv_mma_1;
+ uint32_t smem_bar_k_mma = smem_bar_q_mma + 8 * BUFFERS_Q_1;
+ uint32_t smem_bar_v_mma = smem_bar_k_mma + 8 * BUFFERS_K_1;
+
+ uint32_t buffer_id_q = 0;
+ uint32_t buffer_id_kv = 0;
+ uint32_t cnt_q = 0;
+ uint32_t cnt_kv = 0;
+
+ uint32_t sts_page_buffer_id = 0;
+ uint32_t lds_page_buffer_id = 0;
+
+ int cumulative_tiles = 0;
+ if (tiw == 0) {
+ tile_id = atomicAdd(tile_id_counter, 1);
+ }
+ tile_id = __shfl_sync(0xffffffff, tile_id, 0);
+
+ named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ if (tiw == 0) {
+ sts_32(smem_tile_id_1, &tile_id);
+ }
+ named_barrier_arrive(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+
+ // Persistent loop over output tiles
+#pragma unroll 1
+ while (tile_id < actual_num_tiles_1) {
+ fastDivMod(tiles_hr_div_1, tile_id, batch_coord_1, rows_temp);
+ fastDivMod(tiles_r_div_1, rows_temp, head_coord_from_grid_1, q_row_coord);
+ q_row_coord *= TILE_M_1 * 2;
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ const int left_bound = 0;
+ const int shift_right_bound = 0;
+
+ int2 kv_loop_bounds = compute_kv_loop_bounds(q_row_coord, TILE_M_1 * 2, TILE_N_1, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ int kv_loop_left_bound = kv_loop_bounds.x;
+ int kv_loop_right_bound = kv_loop_bounds.y;
+
+ //global_load_shared_store_op 4 decls
+
+ //global_load_shared_store_op 7 decls
+
+ //global_load_shared_store_op 16 decls
+
+ uint32_t local_smem_q = smem_Q + buffer_id_q * SMEM_Q_1;
+ uint32_t local_smem_bar_tma_q = smem_bar_q_tma + buffer_id_q * 8;
+ uint32_t local_smem_bar_mma_q = smem_bar_q_mma + buffer_id_q * 8;
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ uint32_t smem_bar_phase_q = cnt_q < BUFFERS_Q_1 ? 1 : 0;
+
+ cnt_q = cnt_q < (2 * BUFFERS_Q_1 - 1) ? (cnt_q + 1) : 0;
+ buffer_id_q = buffer_id_q < ( BUFFERS_Q_1 - 1) ? (buffer_id_q + 1) : 0;
+
+ if (!smem_bar_peek(local_smem_bar_mma_q, smem_bar_phase_q)) {
+ smem_bar_wait(local_smem_bar_mma_q, smem_bar_phase_q);
+ }
+
+ smem_bar_set_transaction_count(local_smem_bar_tma_q, SMEM_Q_1, elect_one);
+ {
+ const uint32_t row_coord = q_row_coord;
+
+ //global_load_shared_store_op 4 code
+#pragma unroll
+ for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_Q,
+ local_smem_q + i * TILE_M_1 * 2,
+ local_smem_bar_tma_q,
+ i / BYTES_PER_ELEMENT_1,
+ row_coord,
+ head_coord_1 + 0,
+ batch_coord_1,
+ elect_one);
+ }
+ }
+ }
+
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound; kv_loop < kv_loop_right_bound; kv_loop++) {
+ const int p_col_coord = kv_loop * TILE_N_1;
+
+ uint32_t local_smem_k = smem_K + buffer_id_kv * SMEM_K_1;
+ uint32_t local_smem_bar_tma_k = smem_bar_k_tma + buffer_id_kv * 8;
+ uint32_t local_smem_bar_mma_k = smem_bar_k_mma + buffer_id_kv * 8;
+
+ uint32_t local_smem_v = smem_V + buffer_id_kv * SMEM_V_1;
+ uint32_t local_smem_bar_tma_v = smem_bar_v_tma + buffer_id_kv * 8;
+ uint32_t local_smem_bar_mma_v = smem_bar_v_mma + buffer_id_kv * 8;
+
+ uint32_t smem_bar_phase_kv = cnt_kv < BUFFERS_K_1 ? 1 : 0;
+
+ cnt_kv = cnt_kv < (2 * BUFFERS_K_1 - 1) ? (cnt_kv + 1) : 0;
+ buffer_id_kv = buffer_id_kv < ( BUFFERS_K_1 - 1) ? (buffer_id_kv + 1) : 0;
+
+ uint32_t kv_col_base = (kv_loop + 1) * TILE_N_1;
+
+ if (!smem_bar_peek(local_smem_bar_mma_k, smem_bar_phase_kv)) {
+ smem_bar_wait(local_smem_bar_mma_k, smem_bar_phase_kv);
+ }
+ smem_bar_set_transaction_count(local_smem_bar_tma_k, SMEM_K_1, elect_one);
+
+ //global_load_shared_store_op 7 code
+#pragma unroll
+ for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_K,
+ local_smem_k + i * TILE_N_1,
+ local_smem_bar_tma_k,
+ i / BYTES_PER_ELEMENT_1,
+ p_col_coord,
+ head_coord_k_1,
+ batch_coord_1,
+ elect_one);
+ }
+ if (!smem_bar_peek(local_smem_bar_mma_v, smem_bar_phase_kv)) {
+ smem_bar_wait(local_smem_bar_mma_v, smem_bar_phase_kv);
+ }
+ smem_bar_set_transaction_count(local_smem_bar_tma_v, SMEM_V_1, elect_one);
+
+ //global_load_shared_store_op 16 code
+#pragma unroll
+ for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128 * CTA_MMA_1) {
+ utmaldg_4d_tiled(&tma_V,
+ local_smem_v + i * TILE_N_1,
+ local_smem_bar_tma_v,
+ 0 + i / BYTES_PER_ELEMENT_1,
+ p_col_coord,
+ head_coord_v_1,
+ batch_coord_1,
+ elect_one);
+ }
+ lds_page_buffer_id ^= 1;
+ }
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ lds_page_buffer_id ^= 1;
+ }
+
+ if (tiw == 0) {
+ tile_id = atomicAdd(tile_id_counter, 1);
+ }
+ tile_id = __shfl_sync(0xffffffff, tile_id, 0);
+
+ named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ if (tiw == 0) {
+ sts_32(smem_tile_id_1, &tile_id);
+ }
+ named_barrier_arrive(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ }
+ named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ }
+ reg_dealloc<40>();
+ } else {
+ reg_alloc<232>();
+ named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+
+ const uint32_t local_wid = wid % 4;
+ const uint32_t local_gid = gid % 2;
+
+ uint32_t tile_id;
+ uint32_t batch_coord_1, head_coord_1, q_row_coord, rows_temp;
+ uint32_t head_coord_from_grid_1, head_coord_k_1, head_coord_v_1, head_coord_q_offset_1;
+ int actual_seqlen_kv_1 = attnDesc.s_kv, actual_seqlen_q_1 = attnDesc.s_q, oob_for_stats_1 = attnDesc.s_q;
+
+ uint32_t smem_bar_q_tma = smem_bar_qkv_tma_1;
+ uint32_t smem_bar_k_tma = smem_bar_q_tma + 8 * BUFFERS_Q_1;
+ uint32_t smem_bar_v_tma = smem_bar_k_tma + 8 * BUFFERS_K_1;
+
+ uint32_t smem_bar_q_mma = smem_bar_qkv_mma_1;
+ uint32_t smem_bar_k_mma = smem_bar_q_mma + 8 * BUFFERS_Q_1;
+ uint32_t smem_bar_v_mma = smem_bar_k_mma + 8 * BUFFERS_K_1;
+
+ uint32_t buffer_id_q = 0;
+ uint32_t buffer_id_kv = 0;
+ uint32_t cnt_q = 0;
+ uint32_t cnt_kv = 0;
+
+ static constexpr float inv_ln2 = 1.4426950408889634074f;
+ static constexpr float ln2 = 0.6931471805599453094f;
+
+ Gmma_descriptor gmma_desc_q(create_gmma_desc_q_1());
+ Gmma_descriptor gmma_desc_k(create_gmma_desc_k_1());
+ Gmma_descriptor gmma_desc_v(create_gmma_desc_v_1());
+
+ gmma_desc_q.set_smem<SMEM_Q_1, BUFFERS_Q_1>(smem_Q + local_gid * TILE_M_1 * 128);
+ gmma_desc_k.set_smem<SMEM_K_1, BUFFERS_K_1>(smem_K);
+ gmma_desc_v.set_smem<SMEM_V_1, BUFFERS_V_1>(smem_V);
+
+ named_barrier_wait(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ if (tiw == 0) {
+ lds_32(&tile_id, smem_tile_id_1);
+ }
+ named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ tile_id = __shfl_sync(0xffffffff, tile_id, 0);
+
+ // Persistent loop over output tiles
+#pragma unroll 1
+ while (tile_id < actual_num_tiles_1) {
+ fastDivMod(tiles_hr_div_1, tile_id, batch_coord_1, rows_temp);
+ fastDivMod(tiles_r_div_1, rows_temp, head_coord_from_grid_1, q_row_coord);
+ q_row_coord = q_row_coord * TILE_M_1 * 2;
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+ const int left_bound = 0;
+ const int shift_right_bound = 0;
+
+ int2 kv_loop_bounds = compute_kv_loop_bounds(q_row_coord, TILE_M_1 * 2, TILE_N_1, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ int kv_loop_left_bound = kv_loop_bounds.x;
+ int kv_loop_right_bound = kv_loop_bounds.y;
+ q_row_coord += local_gid * TILE_M_1;
+
+ const int causal_mask_col = (tiw % 4) * 2;
+ const int causal_mask_row = q_row_coord + local_wid * 16 + (tiw / 4);
+
+ // mma_loop_op 2 decls
+
+ //global_load_shared_store_op 4 decls
+
+ // shared_load_op 5 decls
+
+ // shared_load_op 6 decls
+
+ //global_load_shared_store_op 7 decls
+
+ //mma_op 8 decls
+ r32 reg_8_0[REGS_M_8][REGS_N_8][WARP_REGS_8];
+
+ //pointwise_calc_op 9 decls
+
+ //global_load_op 10 decls
+ r32 reg_10_0[1];
+ reg_10_0[0] = reinterpret_cast<const r32 &>(attn_scale);
+ const int oob_M_10 = 1;
+ const int oob_N_10 = 1;
+
+ //mha_mask_op 11 decls
+
+ //softmax_op 12 decls
+ r32 reg_12_0[REGS_M_12][REGS_N_12][4]; // output for second gemm
+ r32 reg_12_1[ROWS_PER_THREAD_12]; // acc_max
+ r32 reg_12_2[ROWS_PER_THREAD_12]; // p_max
+ r32 reg_12_3[ROWS_PER_THREAD_12]; // acc_sum
+ r32 reg_12_4[ROWS_PER_THREAD_12]; // p_sum
+ r32 reg_12_5[ROWS_PER_THREAD_12]; // softmax stats
+ float beta_12[ROWS_PER_THREAD_12];
+
+#pragma unroll
+ for (int i = 0; i < ROWS_PER_THREAD_12; ++i) {
+ reinterpret_cast<float &>(reg_12_1[i]) = NEG_INFINITY;
+ reinterpret_cast<float &>(reg_12_3[i]) = 0.0f;
+ }
+
+ //global_store_op 13 decls
+ int oob_M_13 = desc_max.dims[2];
+ int row_13 = q_row_coord + local_wid * WARP_TILE_M_1 + (tiw / 4);
+ char *ptr_13 = reinterpret_cast<char *>(d_max)
+ + batch_coord_1 * desc_max.strides[0] * BYTES_PER_ELEMENT_13
+ + head_coord_1 * desc_max.strides[1] * BYTES_PER_ELEMENT_13
+ + row_13 * desc_max.strides[2] * BYTES_PER_ELEMENT_13;
+
+ //global_store_op 14 decls
+ int oob_M_14 = desc_sum_exp.dims[2];
+ int row_14 = q_row_coord + local_wid * WARP_TILE_M_1 + (tiw / 4);
+ char *ptr_14 = reinterpret_cast<char *>(d_sum_exp)
+ + batch_coord_1 * desc_sum_exp.strides[0] * BYTES_PER_ELEMENT_14
+)KERNEL"
+ R"KERNEL(
+ + head_coord_1 * desc_sum_exp.strides[1] * BYTES_PER_ELEMENT_14
+ + row_14 * desc_sum_exp.strides[2] * BYTES_PER_ELEMENT_14;
+
+ // shared_load_op 15 decls
+
+ //global_load_shared_store_op 16 decls
+
+ //mma_op 17 decls
+
+ r32 reg_17_0[REGS_M_17][REGS_N_17][WARP_REGS_17];
+
+ //global_store_op 20 decls
+ static constexpr int cols_per_step_20 = (TILE_K_1 <= 128) ? TILE_K_1 : 64;
+ uint32_t smem_20 = smem_O + (local_gid * 4 + local_wid) * 16 * cols_per_step_20 * BYTES_PER_ELEMENT_1;
+
+ const int swizzled_row_20 = (tiw % 16);
+ const int swizzled_col_20 = (tiw / 16);
+ constexpr int stsm_per_tile_20 = 128 / (BYTES_PER_BANK_1 * 2);
+ uint32_t stsm_base_20[stsm_per_tile_20];
+
+#pragma unroll
+ for (int n = 0; n < stsm_per_tile_20; ++n) {
+ stsm_base_20[n] = smem_20 + ((swizzled_row_20 % 8) ^ (n * 2 + swizzled_col_20)) * BYTES_PER_BANK_1 + swizzled_row_20 * 128;
+ }
+
+ const int row_20 = q_row_coord + (local_wid % 4) * 16;
+
+ uint32_t local_smem_bar_tma_q = smem_bar_q_tma + buffer_id_q * 8;
+ uint32_t local_smem_bar_mma_q = smem_bar_q_mma + buffer_id_q * 8;
+
+ if (local_gid == 1) {
+ named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256);
+ }
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ uint32_t smem_bar_phase_q = cnt_q < BUFFERS_Q_1 ? 0 : 1;
+
+ cnt_q = cnt_q < (2 * BUFFERS_Q_1 - 1) ? (cnt_q + 1) : 0;
+ buffer_id_q = buffer_id_q < ( BUFFERS_Q_1 - 1) ? (buffer_id_q + 1) : 0;
+
+ if (!smem_bar_peek(local_smem_bar_tma_q, smem_bar_phase_q)) {
+ smem_bar_wait(local_smem_bar_tma_q, smem_bar_phase_q);
+ }
+ }
+
+ r32 reg_1_0[REGS_M_1][REGS_O_1][WARP_REGS_1];
+ memset(&reg_1_0[0][0][0], 0, sizeof(reg_1_0));
+
+ named_barrier_wait(MATH_WORKGROUP_1, 256);
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound; kv_loop < kv_loop_right_bound; kv_loop++) {
+ static constexpr int kMulPipeCount = REGS_M_1 * REGS_N_1 * WARP_REGS_1;
+
+ static constexpr int kSubtractPipeCount = 6;
+ static constexpr int kConvertPipeCount = 4;
+ static constexpr int oBlockSize = 1;
+
+ const int p_col_coord = kv_loop * TILE_N_1;
+ const int causal_mask_col = p_col_coord + (tiw % 4) * 2;
+ const int causal_mask_row = q_row_coord + local_wid * 16 + (tiw / 4);
+
+ uint32_t local_smem_bar_tma_k = smem_bar_k_tma + buffer_id_kv * 8;
+ uint32_t local_smem_bar_mma_k = smem_bar_k_mma + buffer_id_kv * 8;
+
+ uint32_t local_smem_bar_tma_v = smem_bar_v_tma + buffer_id_kv * 8;
+ uint32_t local_smem_bar_mma_v = smem_bar_v_mma + buffer_id_kv * 8;
+
+ uint32_t smem_bar_phase_kv = cnt_kv < BUFFERS_K_1 ? 0 : 1;
+
+ cnt_kv = cnt_kv < (2 * BUFFERS_K_1 - 1) ? (cnt_kv + 1) : 0;
+ buffer_id_kv = buffer_id_kv < ( BUFFERS_K_1 - 1) ? (buffer_id_kv + 1) : 0;
+
+ memset(&reg_8_0[0][0][0], 0, sizeof(reg_8_0));
+
+ if (!smem_bar_peek(local_smem_bar_tma_k, smem_bar_phase_kv)) {
+ smem_bar_wait(local_smem_bar_tma_k, smem_bar_phase_kv);
+ }
+
+ warpgroup_arrive();
+#pragma unroll
+ for (int k = 0; k < REGS_K_1; ++k) {
+ if (k == REGS_K_1 - 1) {
+ BMM_S_GMMA_ISB(gmma_desc_q.desc, gmma_desc_k.desc, reinterpret_cast<uint32_t *>(reg_8_0[0]));
+ } else {
+ BMM_S_GMMA(gmma_desc_q.desc, gmma_desc_k.desc, reinterpret_cast<uint32_t *>(reg_8_0[0]));
+ }
+ int2 &tmp_desc_q = reinterpret_cast<int2 &>(gmma_desc_q.desc);
+ tmp_desc_q.x += BYTES_PER_GMMA_K_NO_4LSB_1;
+ if ((k % 4) == 3) {
+ tmp_desc_q.x -= BYTES_PER_GMMA_K_NO_4LSB_1 * 4;
+ tmp_desc_q.x += ((128*TILE_M_1*2) >> 4);
+ }
+ int2 &tmp_desc_k = reinterpret_cast<int2 &>(gmma_desc_k.desc);
+ tmp_desc_k.x += BYTES_PER_GMMA_K_NO_4LSB_1;
+ if ((k % 4) == 3) {
+ tmp_desc_k.x -= BYTES_PER_GMMA_K_NO_4LSB_1 * 4;
+ tmp_desc_k.x += ((128*TILE_N_1) >> 4);
+ }
+ }
+ {
+ int2 &tmp_desc_q = reinterpret_cast<int2 &>(gmma_desc_q.desc);
+ tmp_desc_q.x -= ((128 * TILE_M_1 * 2) >> 4) * (REGS_K_1 / 4);
+ int2 &tmp_desc_k = reinterpret_cast<int2 &>(gmma_desc_k.desc);
+ tmp_desc_k.x -= ((128 * TILE_N_1) >> 4) * (REGS_K_1 / 4);
+ }
+ gmma_desc_k.increment_smem_buffer<SMEM_K_1, BUFFERS_K_1>();
+ warpgroup_wait<0>();
+
+ if (local_wid == 0 && elect_one) {
+ smem_bar_arrive(local_smem_bar_mma_k);
+ }
+
+ uint32_t wait_v_done = smem_bar_peek(local_smem_bar_tma_v, smem_bar_phase_kv);
+
+ //mha_mask_op 11 code
+ if (kv_loop >= kv_loop_right_bound - 1)
+ {
+#pragma unroll
+ for (int m = 0; m < REGS_M_11; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_N_11; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_11; ++i) {
+ int row = causal_mask_row + m * WARPS_PER_GROUP_0 * WARP_TILE_M_11 + ((i / 2) % 2) * 8;
+ int col = causal_mask_col + n * WARP_TILE_N_11 + i % 2 + (i / 4) * 8;
+ bool mask = compute_diagonal_band_mask_11(row, col, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ if (!mask) {
+ reinterpret_cast<float &>(reg_8_0[m][n][i]) = neg_infinity;
+ }
+ }
+ }
+ }
+ }
+
+ //global_load_op 10 code
+
+ //mha_mask_op 11 code
+ if (kv_loop >= kv_loop_right_bound - 1)
+ {
+#pragma unroll
+ for (int m = 0; m < REGS_M_11; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_N_11; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_11; ++i) {
+ int row = causal_mask_row + m * WARPS_PER_GROUP_0 * WARP_TILE_M_11 + ((i / 2) % 2) * 8;
+ int col = causal_mask_col + n * WARP_TILE_N_11 + i % 2 + (i / 4) * 8;
+ bool mask = compute_diagonal_band_mask_11(row, col, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ if (!mask) {
+ reinterpret_cast<float &>(reg_8_0[m][n][i]) = neg_infinity;
+ }
+ }
+ }
+ }
+ }
+
+ //softmax_op 12 code
+ static constexpr float inv_ln2_12 = 1.4426950408889634074f;
+ float scaled_inv_ln2_12 = inv_ln2_12 * reinterpret_cast<const float &>(reg_10_0[0]);
+
+ r32 *flattened_s = reinterpret_cast<r32 *>(reg_8_0);
+ r32 *flattened_s_fp16 = reinterpret_cast<r32 *>(reg_12_0);
+ r32 *flattened_o = reinterpret_cast<r32 *>(reg_1_0);
+
+ float tmp_max_level_0[REGS_N_12][4];
+ float tmp_max_level_1[REGS_N_12][2];
+ float tmp_max_level_2[REGS_N_12 / 2][2];
+#pragma unroll
+ for (int m = 0; m < REGS_M_12; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_12; i+=2) {
+ tmp_max_level_0[n][i/2] = fmaxf(reinterpret_cast<const float &>(reg_8_0[m][n][i+0]),
+ reinterpret_cast<const float &>(reg_8_0[m][n][i+1]));
+ }
+ }
+ }
+ // FMUL
+#pragma unroll
+ for (int i = 0; i < kMulPipeCount; i++) {
+ reinterpret_cast<float &>(flattened_s[i]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i]));
+ }
+ {
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; ++n) {
+#pragma unroll
+ for (int i = 0; i < 2; i++) {
+ tmp_max_level_1[n][i] = fmaxf(tmp_max_level_0[n][i + 0],
+ tmp_max_level_0[n][i + 2]);
+ }
+ }
+ }
+ {
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; n+=2) {
+ tmp_max_level_2[n/2][0] = fmaxf(tmp_max_level_1[n][0], tmp_max_level_1[n+1][0]);
+ tmp_max_level_2[n/2][1] = fmaxf(tmp_max_level_1[n][1], tmp_max_level_1[n+1][1]);
+ }
+ }
+ if (TILE_N_1 == 256) {
+ float tmp_max_level_3[REGS_N_12 / 4][2];
+ float tmp_max_level_4[FORT_MAX(1,REGS_N_12 / 8)][2];
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; n+=4) {
+ tmp_max_level_3[n/4][0] = fmaxf(tmp_max_level_2[n/2][0], tmp_max_level_2[n/2+1][0]);
+ tmp_max_level_3[n/4][1] = fmaxf(tmp_max_level_2[n/2][1], tmp_max_level_2[n/2+1][1]);
+ }
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; n+=8) {
+ tmp_max_level_4[n/8][0] = fmaxf(tmp_max_level_3[n/4][0], tmp_max_level_3[n/4+1][0]);
+ tmp_max_level_4[n/8][1] = fmaxf(tmp_max_level_3[n/4][1], tmp_max_level_3[n/4+1][1]);
+ }
+ reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_4[0][0], tmp_max_level_4[1][0]);
+ reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_4[0][1], tmp_max_level_4[1][1]);
+ } else if (TILE_N_1 == 128) {
+ float tmp_max_level_3[REGS_N_12 / 4][2];
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; n+=4) {
+ tmp_max_level_3[n/4][0] = fmaxf(tmp_max_level_2[n/2][0], tmp_max_level_2[n/2+1][0]);
+ tmp_max_level_3[n/4][1] = fmaxf(tmp_max_level_2[n/2][1], tmp_max_level_2[n/2+1][1]);
+ }
+ reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_3[0][0], tmp_max_level_3[1][0]);
+ reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_3[0][1], tmp_max_level_3[1][1]);
+ } else {
+ reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_2[0][0], tmp_max_level_2[1][0]);
+ reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_2[0][1], tmp_max_level_2[1][1]);
+ }
+
+ // Apply the functor for each row inside each group of 4 threads.
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ r32 tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_2[m], 1);
+
+ reinterpret_cast<float &>(reg_12_2[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]),
+ reinterpret_cast<const float &>(tmp_0));
+
+ tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_2[m], 2);
+
+ reinterpret_cast<float &>(reg_12_2[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]),
+ reinterpret_cast<const float &>(tmp_0)) * scaled_inv_ln2_12;
+ }
+
+ // Update acc_max scale of flash attention
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ r32 curr_max = reg_12_1[m];
+ reinterpret_cast<float &>(reg_12_1[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]),
+ reinterpret_cast<const float &>(curr_max));
+ reg_12_2[m] = curr_max;
+ }
+
+ float alpha_12[ROWS_PER_THREAD_12];
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ float p_max = reinterpret_cast<const float &>(reg_12_2[m]);
+ float acc_max = reinterpret_cast<const float &>(reg_12_1[m]);
+
+ // disable FMA for scale * P - max
+ float tmp = (acc_max == NEG_INFINITY) ? p_max : __fsub_rn(p_max, acc_max);
+ reinterpret_cast<r32 &>(alpha_12[m]) = fp32_exp2(reinterpret_cast<r32 &>(tmp));
+ }
+
+#pragma unroll
+ for (int i = 0; i < ROWS_PER_THREAD_12; ++i) {
+ reinterpret_cast<float &>(reg_12_4[i]) = 0.0f;
+ }
+
+ // Broadcast scaled_max and alpha
+ float flattened_scaled_max[REGS_M_12 * REGS_N_12 * WARP_REGS_12];
+ float flattened_alpha[REGS_M_12 * REGS_O_1 * WARP_REGS_12];
+#pragma unroll
+ for (int m = 0; m < REGS_M_12; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_12; ++i) {
+ int row_indx = m * 2 + (i / 2) % 2;
+ float max = reinterpret_cast<const float &>(reg_12_1[row_indx]);
+ flattened_scaled_max[m * REGS_N_12 * WARP_REGS_12 + n * WARP_REGS_12 + i] = (max == NEG_INFINITY ? 0.0f : max);
+ }
+ }
+ }
+
+#pragma unroll
+ for (int m = 0; m < REGS_M_12; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_O_1; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_12; ++i) {
+ int row_indx = m * 2 + (i / 2) % 2;
+ flattened_alpha[m * REGS_O_1 * WARP_REGS_12 + n * WARP_REGS_12 + i] = alpha_12[row_indx];
+ }
+ }
+ }
+
+ cfence();
+ if (local_gid == 1) {
+ named_barrier_wait(SOFTMAX_1_BARRIER_1, 256);
+ } else {
+ named_barrier_wait(SOFTMAX_2_BARRIER_1, 256);
+ }
+ cfence();
+
+ // FSUB
+#pragma unroll
+ for (int i = 0; i < kSubtractPipeCount; i++) {
+)KERNEL"
+ R"KERNEL(
+ reinterpret_cast<float &>(flattened_s[i]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i]), flattened_scaled_max[i]);
+ }
+#pragma unroll
+
+ for (int i = 0; i < REGS_M_12 * REGS_N_12 * WARP_REGS_12; i+=2) {
+ int m_0 = (i-kConvertPipeCount+0) / (REGS_N_12 * WARP_REGS_12);
+ int ii_0 = (i-kConvertPipeCount+0) % WARP_REGS_12;
+ int m_1 = (i-kConvertPipeCount+1) / (REGS_N_12 * WARP_REGS_12);
+ int ii_1 = (i-kConvertPipeCount+1) % WARP_REGS_12;
+ int row_indx_0 = m_0 * 2 + (ii_0 / 2) % 2;
+ int row_indx_1 = m_1 * 2 + (ii_1 / 2) % 2;
+ // cast and FADD
+ if (i >= kConvertPipeCount) {
+ fp32x2_to_bf16x2(&flattened_s_fp16[(i - kConvertPipeCount)/2], &flattened_s[i - kConvertPipeCount]);
+ reinterpret_cast<float &>(reg_12_4[row_indx_0]) += reinterpret_cast<float &>(flattened_s[i-kConvertPipeCount+0]);
+ reinterpret_cast<float &>(reg_12_4[row_indx_1]) += reinterpret_cast<float &>(flattened_s[i-kConvertPipeCount+1]);
+ }
+ cfence();
+
+ // exp
+ flattened_s[i+0] = fp32_exp2(flattened_s[i+0]);
+
+ // O update
+#pragma unroll
+ for (int j = 0; j < oBlockSize; j++) {
+ if (oBlockSize*i+j < REGS_O_1 * REGS_M_1 * WARP_REGS_1) {
+ reinterpret_cast<float &>(flattened_o[oBlockSize*i+j]) *= flattened_alpha[oBlockSize*i+j];
+ }
+ }
+
+ // fmul
+ if (i + kMulPipeCount < REGS_M_12 * REGS_N_12 * WARP_REGS_12) {
+ reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+0]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+0]));
+ reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+1]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+1]));
+ }
+ // fsub
+
+ if (i + kSubtractPipeCount < REGS_M_12 * REGS_N_12 * WARP_REGS_12) {
+ reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+0]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+0]), flattened_scaled_max[i+kSubtractPipeCount+0]);
+ reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+1]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+1]), flattened_scaled_max[i+kSubtractPipeCount+1]);
+ }
+
+ // exp
+ flattened_s[i+1] = fp32_exp2(flattened_s[i+1]);
+
+ // O update
+#pragma unroll
+ for (int j = 0; j < oBlockSize; j++) {
+ if (oBlockSize+oBlockSize*i+j < REGS_O_1 * REGS_M_1 * WARP_REGS_1) {
+ reinterpret_cast<float &>(flattened_o[oBlockSize+oBlockSize*i+j]) *= flattened_alpha[oBlockSize+oBlockSize*i+j];
+ }
+ }
+ }
+
+ if (local_gid == 0) {
+ named_barrier_arrive(SOFTMAX_1_BARRIER_1, 256);
+ } else {
+ named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256);
+ }
+ cfence();
+
+#pragma unroll
+ for (int i = REGS_M_12 * REGS_N_12 * WARP_REGS_12 - kConvertPipeCount; i < REGS_M_12 * REGS_N_12 * WARP_REGS_12; i+=2) {
+ int m_0 = (i + 0) / (REGS_N_12 * WARP_REGS_12);
+ int ii_0 = (i + 0) % WARP_REGS_12;
+ int m_1 = (i + 1) / (REGS_N_12 * WARP_REGS_12);
+ int ii_1 = (i + 1) % WARP_REGS_12;
+ int row_indx_0 = m_0 * 2 + (ii_0 / 2) % 2;
+ int row_indx_1 = m_1 * 2 + (ii_1 / 2) % 2;
+ fp32x2_to_bf16x2(&flattened_s_fp16[i/2], &flattened_s[i]);
+ reinterpret_cast<float &>(reg_12_4[row_indx_0]) += reinterpret_cast<float &>(flattened_s[i+0]);
+ reinterpret_cast<float &>(reg_12_4[row_indx_1]) += reinterpret_cast<float &>(flattened_s[i+1]);
+ }
+
+ if (!wait_v_done) {
+ smem_bar_wait(local_smem_bar_tma_v, smem_bar_phase_kv);
+ }
+
+ warpgroup_arrive();
+#pragma unroll
+ for (int k = 0; k < TILE_N_1 / GMMA_TILE_K_1; ++k) {
+ if (k == (TILE_N_1 / GMMA_TILE_K_1) - 1) {
+ BMM_O_GMMA_ISB(reg_12_0[0][k], gmma_desc_v.desc, reinterpret_cast<uint32_t *>(reg_1_0[0]));
+ } else {
+ BMM_O_GMMA(reg_12_0[0][k], gmma_desc_v.desc, reinterpret_cast<uint32_t *>(reg_1_0[0]));
+ }
+ int2 &tmp_desc_v = reinterpret_cast<int2 &>(gmma_desc_v.desc);
+ tmp_desc_v.x += BYTES_PER_GMMA_K_NO_4LSB_TRANS_1;
+ }
+ {
+ int2 &tmp_desc_v = reinterpret_cast<int2 &>(gmma_desc_v.desc);
+ tmp_desc_v.x -= BYTES_PER_GMMA_K_NO_4LSB_TRANS_1 * (TILE_N_1 / GMMA_TILE_K_1);
+ }
+ gmma_desc_v.increment_smem_buffer<SMEM_V_1, BUFFERS_V_1>();
+
+ warpgroup_wait<0>();
+ if (local_wid == 0 && elect_one) {
+ smem_bar_arrive(local_smem_bar_mma_v);
+ }
+
+ // Update acc_sum of flash attention
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ float p_sum = reinterpret_cast<const float &>(reg_12_4[m]);
+ float acc_sum = reinterpret_cast<const float &>(reg_12_3[m]);
+
+ reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<float &>(alpha_12[m]) * acc_sum + p_sum;
+ }
+ }
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ gmma_desc_q.increment_smem_buffer<SMEM_Q_1, BUFFERS_Q_1>();
+
+ if (local_wid == 0 && elect_one) {
+ smem_bar_arrive(local_smem_bar_mma_q);
+ }
+ }
+ if (local_gid == 0) {
+ named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256);
+ }
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ r32 tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_3[m], 1);
+
+ reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<const float &>(reg_12_3[m]) +
+ reinterpret_cast<const float &>(tmp_0);
+
+ tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_3[m], 2);
+
+ reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<const float &>(reg_12_3[m]) +
+ reinterpret_cast<const float &>(tmp_0);
+
+ float sum = reinterpret_cast<float &>(reg_12_3[m]);
+ reinterpret_cast<float &>(reg_12_1[m]) *= ln2;
+
+ reinterpret_cast<float &>(reg_12_5[m]) = (sum == 0.f) ? NEG_INFINITY : reinterpret_cast<const float &>(reg_12_1[m]) + __logf(sum);
+
+ beta_12[m] = (sum == 0.f) ? 0.f : 1.f / sum;
+ }
+
+#pragma unroll
+ for (int m = 0; m < REGS_M_1; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_O_1; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_1; ++i) {
+ int row_indx = m * 2 + (i / 2) % 2;
+
+ reinterpret_cast<float &>(reg_1_0[m][n][i]) *= beta_12[row_indx];
+ }
+ }
+ }
+
+ //global_store_op 13 code
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_13; ++m) {
+ const int row_offset = (m % 2) * THREADS_PER_WARP_TILE_M_13 + (m / 2) * WARPS_M_13 * WARP_TILE_M_13;
+
+ if (row_13 + row_offset < oob_M_13 && (tiw % 4) == 0) {
+ stg_32(ptr_13 + row_offset * desc_max.strides[2] * BYTES_PER_ELEMENT_13, &reg_12_1[m]);
+ }
+ }
+
+ //global_store_op 14 code
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_14; ++m) {
+ const int row_offset = (m % 2) * THREADS_PER_WARP_TILE_M_14 + (m / 2) * WARPS_M_14 * WARP_TILE_M_14;
+
+ if (row_14 + row_offset < oob_M_14 && (tiw % 4) == 0) {
+ stg_32(ptr_14 + row_offset * desc_sum_exp.strides[2] * BYTES_PER_ELEMENT_14, &reg_12_3[m]);
+ }
+ }
+
+ tmastg_wait();
+
+ //global_store_op 20 code
+#pragma unroll
+ for (int s = 0; s < TILE_O_1 / 64; ++s) {
+#pragma unroll
+ for (int n = 0; n < stsm_per_tile_20; ++n) {
+ uint32_t tmp[4];
+ fp32x2_to_bf16x2(&tmp[0], &reg_1_0[0][s * stsm_per_tile_20 + n][0]);
+ fp32x2_to_bf16x2(&tmp[1], &reg_1_0[0][s * stsm_per_tile_20 + n][2]);
+ fp32x2_to_bf16x2(&tmp[2], &reg_1_0[0][s * stsm_per_tile_20 + n][4]);
+ fp32x2_to_bf16x2(&tmp[3], &reg_1_0[0][s * stsm_per_tile_20 + n][6]);
+ stsm_x4(stsm_base_20[n] + s * 64 * 16 * BYTES_PER_ELEMENT_1, tmp);
+ }
+ }
+ fence_view_async_shared();
+
+ int head_coord_loc = 0;
+ int row = row_20;
+ int head = head_coord_1;
+#pragma unroll
+ for (int s = 0; s < TILE_K_1 / 64; ++s) {
+ utmastg_4d_tiled(&tma_O,
+ smem_20 + s * 64 * 16 * BYTES_PER_ELEMENT_1,
+ s * 64,
+ row,
+ head + head_coord_loc,
+ batch_coord_1);
+ }
+ tmastg_arrive();
+
+ named_barrier_wait(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ if (tiw == 0) {
+ lds_32(&tile_id, smem_tile_id_1);
+ }
+ named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ tile_id = __shfl_sync(0xffffffff, tile_id, 0);
+ }
+ tmastg_wait();
+ reg_alloc<232>();
+ }
+}
+)KERNEL";
+inline constexpr size_t d128_fprop_source_len = sizeof(d128_fprop_source) - 1;
+
+inline constexpr const char d128_fprop_flags[] = R"FLAGS(--gpu-architecture=sm_90a
+--std=c++17
+--define-macro=__x86_64__
+-w
+--define-macro=__CUDACC_RTC__
+-default-device
+--use_fast_math
+)FLAGS";
+inline constexpr size_t d128_fprop_flags_len = sizeof(d128_fprop_flags) - 1;
+
+} // namespace generated
+} // namespace experimental
+} // namespace cudnn_frontend
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d64_fprop_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d64_fprop_kernel.h
new file mode 100644
index 0000000..92d8d1b
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d64_fprop_kernel.h
@@ -0,0 +1,1763 @@
+// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+#pragma once
+
+// Suppress clang warning for overlength strings (concatenated result may exceed 65536)
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Woverlength-strings"
+#endif
+
+// Suppress MSVC warning C4068 (unknown pragma) if clang pragmas are seen
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4068)
+#endif
+
+namespace cudnn_frontend {
+namespace experimental {
+namespace generated {
+
+inline constexpr const char d64_fprop_source[] =
+ R"KERNEL(
+//receive_op 0 includes
+typedef unsigned long long uint64_t;
+typedef unsigned int uint32_t;
+typedef unsigned short uint16_t;
+typedef unsigned char uint8_t;
+typedef long long int64_t;
+typedef int int32_t;
+typedef short int16_t;
+typedef signed char int8_t;
+typedef unsigned int r32;
+
+struct CUtensorMap {
+ alignas(64) uint64_t opaque[16];
+};
+
+#define CUDACC_VERSION __CUDACC_VER_MAJOR__ * 10 + __CUDACC_VER_MINOR__
+
+namespace fort {
+ static const uint64_t AMPERE_MEM_DESC_DEFAULT = uint64_t(0x1000000000000000ul);
+ static const uint64_t MEM_DESC_DEFAULT = AMPERE_MEM_DESC_DEFAULT;
+ static const uint32_t MMA_PEER_BIT_MASK = 0xFEFFFFFF;
+
+#define NEG_INFINITY __int_as_float(0xff800000)
+
+ typedef uint16_t half_t;
+ typedef uint16_t bfloat16_t;
+
+#define FORT_MIN(a,b) ((a) < (b) ? (a) : (b))
+#define FORT_MAX(a,b) ((a) > (b) ? (a) : (b))
+#define FORT_DIV_UP(a,b) (((a) + (b) - 1) / (b))
+#define FORT_ROUND_UP(a,b) ((((a) + (b) - 1) / (b)) * (b))
+
+ typedef struct tensor_descriptor {
+ static const int MAX_DIMS = 12;
+
+ int64_t num_dims;
+ int64_t dims[MAX_DIMS];
+ int64_t strides[MAX_DIMS];
+ } tensor_descriptor;
+
+ typedef struct FastDivisor {
+ uint32_t val, shr, mul;
+ } FastDivisor_t;
+
+ inline __device__ void
+ fastDivMod(const FastDivisor_t &d, uint32_t val, uint32_t &div, uint32_t &mod) {
+ div = __umulhi((uint32_t)2 * val, d.mul) >> d.shr;
+ mod = val - div * d.val;
+ }
+ __device__ __inline__ void cfence() {}
+
+#if __CUDA_ARCH__ >= 900
+
+ inline __device__ uint32_t elect_one_sync() {
+ uint32_t pred = 0;
+ uint32_t laneid = 0;
+ asm volatile(
+ "{\n"
+ ".reg .b32 %%rx;\n"
+ ".reg .pred %%px;\n"
+ " elect.sync %%rx|%%px, %2;\n"
+ "@%%px mov.s32 %1, 1;\n"
+ " mov.s32 %0, %%rx;\n"
+ "}\n" : "+r"(laneid), "+r"(pred) : "r"(0xFFFFFFFF));
+ return pred;
+ }
+
+ template<int TARGET_REG_COUNT>
+ inline __device__ void reg_alloc() {
+ // const int TARGET_REG_COUNT = 232; // Example values (use with reg_delloc's VALUE together): 224, 232, 208, 216
+ asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;\n" : : "n"(TARGET_REG_COUNT));
+ }
+
+ template<int TARGET_REG_COUNT>
+ inline __device__ void reg_dealloc() {
+ // const int TARGET_REG_COUNT = 40; // Exmaple values: 56, 40, 88, 72
+ asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;\n" : : "n"(TARGET_REG_COUNT));
+ }
+
+ inline __device__ void named_barrier_arrive(uint32_t BARRIER_ID, uint32_t NUM_THREADS) {
+ asm volatile("bar.arrive %0, %1;" : : "r"(BARRIER_ID), "r"(NUM_THREADS));
+ }
+
+ inline __device__ void named_barrier_wait(uint32_t BARRIER_ID, uint32_t NUM_THREADS) {
+ asm volatile("bar.sync %0, %1;" :: "r"(BARRIER_ID), "r"(NUM_THREADS));
+ }
+
+ inline __device__ void tmastg_arrive() {
+ asm volatile("cp.async.bulk.commit_group;");
+ }
+
+ inline __device__ void tmastg_wait() {
+ asm volatile("cp.async.bulk.wait_group.read %0;" : :"n"(0):"memory");
+ }
+
+#endif
+
+#if defined( __CUDA_ARCH__ ) && __CUDA_ARCH__ >= 900
+ inline __device__ void warpgroup_arrive() {
+ asm volatile("wgmma.fence.sync.aligned;\n" ::: "memory");
+ }
+ template <int N> inline __device__ void warpgroup_wait() {
+ asm volatile("wgmma.wait_group.sync.aligned %0;\n" ::"n"(N) : "memory");
+ }
+ inline __device__ void warpgroup_commit() {
+ asm volatile("wgmma.commit_group.sync.aligned;\n" ::: "memory");
+ }
+ template <typename T>
+ inline __device__ T &__wgmma_fence_operand(T &&reg) {
+ asm volatile("" : "+r"(reg)::"memory");
+ return reg;
+ }
+#endif
+
+#if defined( __CUDA_ARCH__ ) && __CUDA_ARCH__ >= 900
+ inline __device__ void smem_bar_init(uint32_t smem_ptr, uint32_t thread_count) {
+ asm volatile ("mbarrier.init.shared::cta.b64 [%0], %1;\n" :: "r"(smem_ptr), "r"(thread_count));
+ }
+
+ inline __device__ void smem_bar_set_transaction_count(uint32_t smem_ptr, uint32_t expected_copy_bytes, uint32_t pred = 0) {
+ asm volatile("{\n\t.reg .pred p;"
+ " \n\tsetp.eq.u32 p, %2, 1;"
+ " \n\t@p mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;"
+ " \n\t}" :: "r"(smem_ptr), "r"(expected_copy_bytes), "r"(pred));
+ }
+
+ inline __device__ uint32_t smem_bar_peek(uint32_t smem_ptr, uint32_t bar_phase) {
+ uint32_t bar_phase_out;
+ asm volatile("{\n\t.reg .pred P1;"
+ " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%1], %2;"
+ " \n\tselp.b32 %0, 1, 0, P1; \n\t}" :"=r" (bar_phase_out):"r"(smem_ptr),"r"(bar_phase));
+ return bar_phase_out;
+ }
+
+ inline __device__ void smem_bar_wait(uint32_t smem_ptr, uint32_t bar_phase) {
+ uint32_t large_val = 0x989680;
+ asm volatile("{\n\t.reg .pred P1;"
+ " \n\tLAB_WAIT:"
+ " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1, %2;"
+ " \n\t@P1 bra.uni DONE;"
+ " \n\tbra.uni LAB_WAIT;"
+ " \n\tDONE:"
+ " \n\t}" :: "r"(smem_ptr),"r"(bar_phase), "r"(large_val));
+ }
+
+ inline __device__
+ void
+ wait_barrier(uint32_t smem_int_ptr,
+ int phase_bit) // Current phase bit the barrier waiting to flip
+ {
+ asm volatile(
+ "{\n"
+ ".reg .pred P1;\n"
+ "LAB_WAIT:\n"
+ "mbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1;\n"
+ "@P1 bra.uni DONE;\n"
+ "bra.uni LAB_WAIT;\n"
+ "DONE:\n"
+ "}\n"
+ :: "r"(smem_int_ptr),
+ "r"(phase_bit));
+ }
+
+ inline __device__ void smem_bar_arrive(uint32_t smem_ptr) {
+ asm volatile("{\n\t.reg .b64 state;"
+ " \n\tmbarrier.arrive.shared::cta.b64 state, [%0];"
+ " \n\t}" :: "r"(smem_ptr));
+ }
+
+ // Barrier arrive on local smem
+ inline __device__
+ void arrive_barrier(uint32_t smem_addr) {
+ asm volatile(
+ "{\n\t"
+ "mbarrier.arrive.shared::cta.b64 _, [%0];\n\t"
+ "}"
+ :
+ : "r"(smem_addr));
+ }
+
+#endif
+
+ extern "C" __device__ uint32_t __nvvm_get_smem_pointer(void *ptr);
+
+ inline __device__ uint32_t get_smem_pointer(const void *ptr) {
+ return __nvvm_get_smem_pointer(const_cast<void *>(ptr));
+ }
+
+ extern "C" __device__ inline void *__nv_cvta_shared_to_generic_impl(size_t __ptr) {
+ return (void *)(void __attribute__((address_space(3))) *)__ptr;
+ }
+ inline __device__ void *set_smem_pointer(uint32_t ptr) {
+ return __nv_cvta_shared_to_generic_impl(ptr);
+ }
+
+ inline __device__ uint32_t
+ cast_smem_ptr_to_uint(void const* const ptr) {
+ return static_cast<uint32_t>(__cvta_generic_to_shared(ptr));
+ }
+
+ inline __device__ void stsm_x4(r32 dst, r32 src[4]) {
+ asm volatile("stmatrix.sync.aligned.m8n8.x4.shared.b16 [%0], {%1, %2, %3, %4};\n" ::"r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]));
+ }
+
+ inline __device__ void fence_view_async_shared(void){
+ asm volatile ("fence.proxy.async.shared::cta;\n");
+ }
+
+ inline __device__ void sts_32(r32 dst, r32 src[1]) {
+ asm volatile("st.shared.b32 [%0], %1;\n" :: "r"(dst), "r"(src[0]));
+ }
+
+ inline __device__ void lds_32(r32 dst[1], r32 src) {
+ asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst[0]) : "r"(src));
+ }
+
+ inline __device__ void stg_32(void *ptr, r32 val[1]) {
+ uint32_t *p = reinterpret_cast<uint32_t *>(ptr);
+ p[0] = val[0];
+ }
+
+ // Forward ReLU activations
+
+ inline __device__ uint32_t fp32_exp2(uint32_t in) {
+ uint32_t out;
+ asm volatile("ex2.approx.ftz.f32 %0, %1;\n" : "=r"(out) : "r"(in));
+ return out;
+ }
+
+ inline __device__ void fp32x2_to_bf16x2(r32 dst[1], const r32 src[2]) {
+ asm volatile("cvt.rn.bf16x2.f32 %0, %1, %2;\n" : "=r"(dst[0]) : "r"(src[1]), "r"(src[0]));
+ }
+
+ inline __device__ void bf16x2_to_fp32x2(r32 dst[2], const r32 src[1]) {
+ asm volatile( \
+ "{\n" \
+ " .reg .b16 lo, hi;\n" \
+ " mov.b32 {lo, hi}, %2;\n" \
+ " mov.b32 %0, {0, lo};\n" \
+ " mov.b32 %1, {0, hi};\n" \
+ "}\n" : "=r"(dst[0]), "=r"(dst[1]) : "r"(src[0]));
+ }
+
+ //mma_pipeline_op 1 includes
+ typedef struct AttentionDescriptor {
+ // Input parameters
+ // b - batch
+ // q_h - num heads of q/dq/o/do
+ // k_h - num heads of k/dk
+ // v_h - num heads of v/dv
+ // s_q - max sequence length of q
+ // s_kv - max sequence length of kv
+ // d - hidden dim (head dim)
+ uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v;
+ uint16_t q_heads_per_k, q_heads_per_v, min_q_heads_per_kv;
+ } AttentionDescriptor_t;
+
+ // CUtensorMap, when issued using bulk copy async functions, are cached in constant cache.
+ // But the producer kernel may have directly written to global memory, without invalidating this constant cache.
+ // This acquire fence, invalidates the memory address in constant cache, using UTMACCTL.IV.
+ inline __device__ void tma_descriptor_fence_acquire(
+ CUtensorMap const* p_desc
+ ) {
+#if (__CUDA_ARCH__ >= 900) && (CUDACC_VERSION >= 123)
+ uint64_t gmem_int_desc = reinterpret_cast<uint64_t>(p_desc);
+ asm volatile (
+ "fence.proxy.tensormap::generic.acquire.gpu [%0], 128;\n"
+ :
+ : "l"(gmem_int_desc)
+ : "memory");
+ asm volatile (
+ "cvta.global.u64 %0, %0;\n"
+ :
+ : "l"(gmem_int_desc), "l"(gmem_int_desc)
+ : "memory");
+#endif
+ }
+
+ inline __device__ void utmaldg_4d_tiled (
+ const void *p_desc,
+ uint32_t urb0, // smem offset
+ uint32_t urb1, // smem barrier offset
+ int32_t urb2, // m
+ int32_t urb3, // n
+ int32_t urb4, // b
+ int32_t urb5, // extra coord
+ const uint32_t elect_one,
+ const uint64_t mem_desc = MEM_DESC_DEFAULT
+ ) {
+ if (elect_one) {
+#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300
+ asm volatile(
+ "cp.async.bulk.tensor.4d.shared::cta.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::
+ "r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb2),
+ "r"(urb3),
+ "r"(urb4),
+ "r"(urb5),
+ "r"(urb1),
+ "l"(mem_desc) : "memory"
+ );
+#else
+ asm volatile(
+ "cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::
+ "r"(urb0),
+ "l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb2),
+ "r"(urb3),
+ "r"(urb4),
+ "r"(urb5),
+ "r"(urb1),
+ "l"(mem_desc) : "memory"
+ );
+#endif
+ }
+ }
+
+ inline __device__ void utmastg_4d_tiled(
+ const void *p_desc,
+ uint32_t smem_offset,
+ int32_t urb0, // m
+ int32_t urb1, // n
+ int32_t urb2, // h
+ int32_t urb3, // b
+ uint64_t mem_desc = MEM_DESC_DEFAULT
+ ) {
+ asm volatile(
+ "cp.async.bulk.tensor.4d.global.shared::cta.bulk_group [%0, {%1, %2, %3, %4}], [%5];\n" ::
+ "l"(reinterpret_cast<uint64_t>(p_desc)),
+ "r"(urb0),
+ "r"(urb1),
+ "r"(urb2),
+ "r"(urb3),
+ "r"(smem_offset) : "memory"
+ );
+ }
+
+ inline __device__ void ldgdepbar() {
+ asm volatile("cp.async.commit_group;\n" ::);
+ }
+
+ template<int STAGES>
+ inline __device__ void depbar() {
+ asm volatile("cp.async.wait_group %0;\n" :: "n"(STAGES));
+ }
+
+ //mma_loop_op 2 includes
+
+ //global_load_shared_store_op 4 includes
+
+ // shared_load_op 5 includes
+
+ // shared_load_op 6 includes
+
+ //global_load_shared_store_op 7 includes
+
+ //mma_op 8 includes
+)KERNEL"
+ R"KERNEL(
+// === Section: GMMA Operations ===
+ inline __device__ void bf16gmma_fp32_64x128x16_TN_asmem_bsmem_isb(const uint64_t &desc_a, const uint64_t &desc_b, r32 acc[64]) {
+ __wgmma_mma_async_bf16(64, 128, 16, false, false, false, false, true, acc, desc_a, desc_b);
+ warpgroup_commit();
+ }
+
+ // === Section: GMMA Operations ===
+ inline __device__ void bf16gmma_fp32_64x128x16_TN_asmem_bsmem(const uint64_t &desc_a, const uint64_t &desc_b, r32 acc[64]) {
+ __wgmma_mma_async_bf16(64, 128, 16, false, false, false, false, true, acc, desc_a, desc_b);
+ }
+
+#define BMM_S_GMMA bf16gmma_fp32_64x128x16_TN_asmem_bsmem
+#define BMM_S_GMMA_ISB bf16gmma_fp32_64x128x16_TN_asmem_bsmem_isb
+#define BMM_S_GMMA_C0 bf16gmma_fp32_64x128x16_TN_asmem_bsmem_ignoreC
+
+ //pointwise_calc_op 9 includes
+
+ //global_load_op 10 includes
+
+ //softmax_op 12 includes
+
+ // global_store_op 13 includes
+
+ // global_store_op 14 includes
+
+ // shared_load_op 15 includes
+
+ //global_load_shared_store_op 16 includes
+
+ //mma_op 17 includes
+ inline __device__ void bf16gmma_fp32_64x64x16_TT_arf_bsmem_isb(const r32 a[4], const uint64_t &desc_b, r32 acc[32]) {
+ __wgmma_mma_async_bf16(64, 64, 16, false, false, true, false, true, acc, a, desc_b);
+ warpgroup_commit();
+ }
+
+ inline __device__ void bf16gmma_fp32_64x64x16_TT_arf_bsmem(const r32 a[4], const uint64_t &desc_b, r32 acc[32]) {
+ __wgmma_mma_async_bf16(64, 64, 16, false, false, true, false, true, acc, a, desc_b);
+ }
+
+#define BMM_O_GMMA bf16gmma_fp32_64x64x16_TT_arf_bsmem
+#define BMM_O_GMMA_ISB bf16gmma_fp32_64x64x16_TT_arf_bsmem_isb
+#define BMM_O_GMMA_C0 bf16gmma_fp32_64x64x16_TT_arf_bsmem_ignoreC
+
+ // global_store_op 20 includes
+
+ //output_loop_op 3 includes
+
+ // shared_store_op 18 includes
+
+ // shared_load_op 19 includes
+} // namespace fort
+
+//receive_op 0 types
+using namespace fort;
+
+static constexpr int THREADS_PER_WARP_0 = 32;
+static constexpr int WARPS_PER_GROUP_0 = FORT_MIN(4, 384 / THREADS_PER_WARP_0);
+static constexpr int THREADS_PER_WARP_GROUP_0 = THREADS_PER_WARP_0 * WARPS_PER_GROUP_0;
+static constexpr int BITS_PER_REGISTER_0 = 32; // NOTE: sizeof(uint)
+static constexpr int BYTES_PER_REGISTER_0 = BITS_PER_REGISTER_0 / 8;
+static constexpr int THREADS_PER_GROUP_0 = WARPS_PER_GROUP_0 * THREADS_PER_WARP_0;
+
+// mma_pipeline_op 1 types
+static constexpr int BYTES_PER_BANK_1 = 16;
+static constexpr int BITS_PER_ELEMENT_1 = 16;
+static constexpr int ELEMS_PER_BANK_1 = BYTES_PER_BANK_1 * 8 / BITS_PER_ELEMENT_1;
+static constexpr int BYTES_PER_ELEMENT_1 = BITS_PER_ELEMENT_1 / 8;
+static constexpr int BYTES_PER_FP16_1 = 2;
+static constexpr int ELEMS_PER_VECTOR_1 = BYTES_PER_REGISTER_0 / BYTES_PER_ELEMENT_1;
+static constexpr int BITS_PER_ACC_1 = 32;
+static constexpr int BYTES_PER_ACC_1 = BITS_PER_ACC_1 / 8;
+static constexpr int TILE_M_1 = 64;
+static constexpr int TILE_N_1 = 128;
+static constexpr int TILE_K_1 = 64;
+static constexpr int TILE_O_1 = 64;
+static constexpr int TILE_V_1 = TILE_K_1;
+static constexpr int TILE_DV_1 = 64;
+static constexpr int WARP_TILE_M_1 = 16;
+static constexpr int WARP_TILE_N_1 = 16;
+static constexpr int WARP_TILE_K_1 = 32 / BYTES_PER_ELEMENT_1;
+static constexpr int WARPS_M_1 = 64 / 16;
+static constexpr int WARPS_N_1 = 16 / 16;
+static constexpr int WARPS_K_1 = 16 / 16;
+static constexpr int STAGES_1 = 1;
+static constexpr int GROUPS_M_1 = 1;
+static constexpr int GMMA_TILE_M_1 = WARPS_M_1 * WARP_TILE_M_1;
+static constexpr int GMMA_TILE_K_1 = WARPS_K_1 * WARP_TILE_K_1;
+static constexpr int WARP_TILES_M_1 = TILE_M_1 / WARP_TILE_M_1;
+static constexpr int WARP_TILES_N_1 = TILE_N_1 / WARP_TILE_N_1;
+static constexpr int WARP_TILES_K_1 = TILE_K_1 / WARP_TILE_K_1;
+static constexpr int WARP_REGS_1 = 8;
+static constexpr int REGS_M_1 = WARP_TILES_M_1 / WARPS_M_1;
+static constexpr int REGS_N_1 = WARP_TILES_N_1 / WARPS_N_1;
+static constexpr int REGS_K_1 = WARP_TILES_K_1 / WARPS_K_1;
+static constexpr int REGS_K_FOR_DP_1 = TILE_V_1 / 16;
+static constexpr int REGS_dQ_1 = TILE_O_1 / 16;
+
+static constexpr int REGS_O_1 = 4;
+
+static constexpr int CGA_M_1 = 1;
+static constexpr int CGA_N_1 = 1;
+static constexpr int CTA_MMA_1 = 1;
+static constexpr int M_TILES_PER_OUTPUT_TILE_1 = 4;
+static constexpr int N_TILES_PER_OUTPUT_TILE_1 = 1;
+
+static constexpr int CTA_TILE_M_1 = TILE_M_1 * GROUPS_M_1;
+static constexpr int CTA_TILE_N_1 = 64;
+static constexpr int CTA_TILE_K_1 = 128;
+static constexpr int BUFFERS_Q_1 = 2;
+static constexpr int BUFFERS_K_1 = 2;
+static constexpr int BUFFERS_V_1 = 2;
+static constexpr int BUFFERS_O_1 = 1;
+static constexpr int BUFFERS_D_1 = 1;
+static constexpr int SMEM_Q_1 = TILE_M_1 * TILE_K_1 * BYTES_PER_ELEMENT_1 * 2;
+static constexpr int SMEM_K_1 = TILE_N_1 * TILE_K_1 * BYTES_PER_ELEMENT_1;
+static constexpr int SMEM_V_1 = TILE_N_1 * TILE_K_1 * BYTES_PER_ELEMENT_1;
+static constexpr int SMEM_PAGE_TABLE_1 = FORT_ROUND_UP(TILE_N_1 * 2 * 2 * sizeof(int), 1024);
+static constexpr int SMEM_OFFSET_Q_1 = 1024 + (false ? 0 : SMEM_PAGE_TABLE_1);
+static constexpr int SMEM_OFFSET_K_1 = SMEM_OFFSET_Q_1 + SMEM_Q_1 * BUFFERS_Q_1;
+static constexpr int SMEM_OFFSET_V_1 = SMEM_OFFSET_K_1 + SMEM_K_1 * BUFFERS_K_1;
+static constexpr int SMEM_OFFSET_O_1 = SMEM_OFFSET_V_1 + SMEM_V_1 * BUFFERS_V_1;
+static constexpr int SMEM_OFFSET_D_1 = SMEM_OFFSET_O_1;
+static constexpr int SMEM_OFFSET_BAND_BIAS_1 = SMEM_OFFSET_O_1;
+
+static constexpr int THREADS_ON_TILE_BARRIER_1 = 256+32+0;
+static constexpr int TILE_ID_SYNC_2_BARRIER_1 = 2;
+static constexpr int TILE_ID_SYNC_3_BARRIER_1 = 3;
+static constexpr int SOFTMAX_1_BARRIER_1 = 4;
+static constexpr int SOFTMAX_2_BARRIER_1 = 5;
+static constexpr int MATH_WORKGROUP_1 = 6;
+static constexpr int TMA_SYNC_BARRIER_1 = 7;
+
+static constexpr uint32_t BYTES_PER_GMMA_K_1 = GMMA_TILE_K_1 * BYTES_PER_ELEMENT_1;
+static constexpr uint32_t BYTES_PER_GMMA_K_NO_4LSB_1 = BYTES_PER_GMMA_K_1 >> 4;
+static constexpr uint32_t BYTES_PER_GMMA_K_TRANS_1 = GMMA_TILE_K_1 * 128;
+static constexpr uint32_t BYTES_PER_GMMA_K_NO_4LSB_TRANS_1 = BYTES_PER_GMMA_K_TRANS_1 >> 4;
+
+static constexpr uint32_t GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1 = 2;
+static constexpr uint32_t GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1 = 62; // bits 63-62
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_Q_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_Q_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_Q_1 &
+((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1))
+<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1;
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_K_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_K_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_K_1 &
+((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1))
+<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1;
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_V_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3
+static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_V_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_V_1 &
+((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1))
+<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1;
+
+static constexpr uint32_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1 = 32; // bits 45-32
+static constexpr uint64_t BYTES_PER_LEADING_DIM_1 = 128;
+static constexpr uint64_t STRIDE_BYTE_OFFSET_Q_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2
+static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 = STRIDE_BYTE_OFFSET_Q_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1;
+static constexpr uint64_t STRIDE_BYTE_OFFSET_K_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2
+static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_K_1 = STRIDE_BYTE_OFFSET_K_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1;
+static constexpr uint64_t STRIDE_BYTE_OFFSET_V_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2
+static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_V_1 = STRIDE_BYTE_OFFSET_V_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1;
+
+static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1 = 16; // bits 29-16
+static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_Q_1 = 128 * 64 / 16; // Not used???
+static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_Q_1
+<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1;
+static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_K_1 = 128 * 32 / 16; // Not used???
+static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_K_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_K_1
+<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1;
+static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_V_1 = 128 * TILE_N_1 / 16;
+static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_V_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_V_1
+<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1;
+
+inline __device__ constexpr uint64_t create_gmma_desc_q_1() {
+ return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_Q_1)
+ | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_Q_1
+ | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_Q_1;
+}
+
+inline __device__ constexpr uint64_t create_gmma_desc_k_1() {
+ return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_K_1)
+ | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_K_1
+ | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_K_1;
+}
+
+// === Section: GMMA Descriptors & Mask Helpers ===
+)KERNEL"
+ R"KERNEL(
+// === Section: GMMA Descriptors & Mask Helpers ===
+inline __device__ constexpr uint64_t create_gmma_desc_v_1() {
+ return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_V_1)
+ | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_V_1
+ | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_V_1;
+}
+
+class Gmma_descriptor {
+ public:
+ inline __device__ Gmma_descriptor(uint64_t desc_) {
+ desc = desc_;
+ }
+ template<int BYTES_PER_BUFFER, int BUFFER_COUNT>
+ inline __device__ void set_smem(uint32_t smem) {
+ desc |= (static_cast<uint64_t>(smem & 0xFFFFFF) >> 4);
+
+ max_desc = desc + (BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1);
+ }
+ template<int BYTES_PER_BUFFER, int BUFFER_COUNT>
+ inline __device__ void increment_smem_buffer() {
+ int2 &tmp = reinterpret_cast<int2 &>(desc);
+ tmp.x += (desc >= max_desc) ? -(BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1)
+ : (BYTES_PER_BUFFER >> 4);
+ }
+
+ uint64_t desc;
+ uint64_t max_desc;
+};
+
+//global_load_shared_store_op 4 types
+static constexpr int BITS_PER_ELEMENT_4 = 16;
+static constexpr int BYTES_PER_ELEMENT_4 = BITS_PER_ELEMENT_4 / 8;
+static constexpr int BYTES_PER_ACCESS_4 = 16;
+static constexpr int TILE_M_4 = 64;
+static constexpr int TILE_N_4 = 64;
+static constexpr int BYTES_PER_SMEM_4 = TILE_M_4 * TILE_N_4 * BYTES_PER_ELEMENT_4;
+
+// shared_load_op 5 types
+static constexpr int BITS_PER_ELEMENT_5 = 16;
+static constexpr int BYTES_PER_ELEMENT_5 = 2;
+static constexpr int BYTES_PER_QUAD_5 = 16;
+static constexpr int WARP_TILE_M_5 = 16;
+static constexpr int WARP_TILE_N_5 = 16;
+static constexpr int TILE_M_5 = 64;
+static constexpr int TILE_N_5 = 64;
+static constexpr int BYTES_PER_SMEM_5 = TILE_M_5 * TILE_N_5 * BYTES_PER_ELEMENT_5;
+static constexpr int WARPS_M_5 = 4;
+static constexpr int WARPS_N_5 = 1;
+static constexpr int WARP_TILES_M_5 = TILE_M_5 / WARP_TILE_M_5;
+static constexpr int WARP_TILES_N_5 = TILE_N_5 / WARP_TILE_N_5;
+static constexpr int THREADS_PER_WARP_TILE_M_5 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_5 = 4;
+static constexpr int REGS_M_5 = WARP_TILES_M_5 / WARPS_M_5;
+static constexpr int REGS_N_5 = WARP_TILES_N_5 / WARPS_N_5;
+static constexpr int BYTES_PER_LD_5 = 128;
+static constexpr int SWIZZLE_SCALE_5 = FORT_MIN(BYTES_PER_LD_5 / 16, WARPS_PER_GROUP_0 * 4);
+
+// shared_load_op 6 types
+static constexpr int BITS_PER_ELEMENT_6 = 16;
+static constexpr int BYTES_PER_ELEMENT_6 = 2;
+static constexpr int BYTES_PER_QUAD_6 = 16;
+static constexpr int WARP_TILE_M_6 = 16;
+static constexpr int WARP_TILE_N_6 = 16;
+static constexpr int TILE_M_6 = 128;
+static constexpr int TILE_N_6 = 64;
+
+static constexpr int BYTES_PER_SMEM_6 = TILE_M_6 * TILE_N_6 * BYTES_PER_ELEMENT_6;
+static constexpr int WARPS_M_6 = 1;
+static constexpr int WARPS_N_6 = 1;
+static constexpr int WARP_TILES_M_6 = TILE_M_6 / WARP_TILE_M_6;
+static constexpr int WARP_TILES_N_6 = TILE_N_6 / WARP_TILE_N_6;
+static constexpr int THREADS_PER_WARP_TILE_M_6 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_6 = 4;
+static constexpr int REGS_M_6 = WARP_TILES_M_6 / WARPS_M_6;
+static constexpr int REGS_N_6 = WARP_TILES_N_6 / WARPS_N_6;
+static constexpr int BYTES_PER_LD_6 = 128;
+static constexpr int SWIZZLE_SCALE_6 = FORT_MIN(BYTES_PER_LD_6 / 16, WARPS_PER_GROUP_0 * 4);
+
+//global_load_shared_store_op 7 types
+static constexpr int BITS_PER_ELEMENT_7 = 16;
+static constexpr int BYTES_PER_ELEMENT_7 = BITS_PER_ELEMENT_7 / 8;
+static constexpr int BYTES_PER_ACCESS_7 = 16;
+static constexpr int TILE_M_7 = 128;
+static constexpr int TILE_N_7 = 64;
+static constexpr int BYTES_PER_SMEM_7 = TILE_M_7 * TILE_N_7 * BYTES_PER_ELEMENT_7;
+
+//mma_op 8 types
+static constexpr int BYTES_PER_ELEMENT_8 = 2;
+static constexpr int BYTES_PER_ACC_8 = 4;
+static constexpr int WARP_TILE_M_8 = 16;
+static constexpr int WARP_TILE_N_8 = 16;
+static constexpr int WARP_TILE_K_8 = 16;
+static constexpr int TILE_M_8 = 64;
+static constexpr int TILE_N_8 = 128;
+static constexpr int TILE_K_8 = 64;
+static constexpr int WARPS_M_8 = 4;
+static constexpr int WARPS_N_8 = 1;
+static constexpr int WARP_TILES_M_8 = TILE_M_8 / WARP_TILE_M_8;
+static constexpr int WARP_TILES_N_8 = TILE_N_8 / WARP_TILE_N_8;
+static constexpr int MMA_STEPS_K_8 = TILE_K_8 / WARP_TILE_K_8;
+static constexpr int WARP_REGS_8 = 8;
+static constexpr int REGS_M_8 = WARP_TILES_M_8 / WARPS_M_8;
+static constexpr int REGS_N_8 = WARP_TILES_N_8 / WARPS_N_8;
+
+//pointwise_calc_op 9 types
+static constexpr int WARP_TILE_M_9 = 16;
+static constexpr int WARP_TILE_N_9 = 16;
+static constexpr int TILE_M_9 = 64;
+static constexpr int TILE_N_9 = 128;
+static constexpr int WARPS_M_9 = 4;
+static constexpr int WARPS_N_9 = 1;
+static constexpr int WARP_TILES_M_9 = TILE_M_9 / WARP_TILE_M_9;
+static constexpr int WARP_TILES_N_9 = TILE_N_9 / WARP_TILE_N_9;
+static constexpr int WARP_REGS_9 = 8;
+static constexpr int REGS_M_9 = WARP_TILES_M_9 / WARPS_M_9;
+static constexpr int REGS_N_9 = WARP_TILES_N_9 / WARPS_N_9;
+
+//global_load_op 10 types
+static constexpr int BITS_PER_ELEMENT_10 = 32;
+static constexpr int BYTES_PER_ELEMENT_10 = 4;
+static constexpr int REGISTERS_PER_VECTOR_10 = 1;
+static constexpr int REGISTERS_PER_ACCESS_10 = 1;
+
+//mha_mask_op 11 types
+static constexpr int WARP_TILE_M_11 = 16;
+static constexpr int WARP_TILE_N_11 = 16;
+static constexpr int TILE_M_11 = 64;
+static constexpr int TILE_N_11 = 128;
+static constexpr int WARPS_M_11 = 4;
+static constexpr int WARPS_N_11 = 1;
+static constexpr int WARP_TILES_M_11 = TILE_M_11 / WARP_TILE_M_11;
+static constexpr int WARP_TILES_N_11 = TILE_N_11 / WARP_TILE_N_11;
+static constexpr int WARP_REGS_11 = 8;
+static constexpr int REGS_M_11 = WARP_TILES_M_11 / WARPS_M_11;
+static constexpr int REGS_N_11 = WARP_TILES_N_11 / WARPS_N_11;
+inline __device__ bool compute_diagonal_band_mask_11(const int row, const int col, const int actual_seqlen_kv, const int actual_seqlen_q, const int shift_right_bound, const int left_bound) {
+ constexpr bool is_bottom_right_alignment = false;
+ constexpr bool is_shift_right_bound = false;
+ constexpr bool is_right_bound = true;
+ constexpr bool is_left_bound = false;
+ constexpr bool need_oob_check = false;
+
+ const int diag = is_bottom_right_alignment ? row + (actual_seqlen_kv - actual_seqlen_q) : row;
+ const int shifted_right_bound = is_shift_right_bound ? diag + shift_right_bound : diag;
+ const bool right_bound_mask = is_right_bound ? col <= shifted_right_bound : true;
+ const bool left_bound_mask = is_left_bound ? col + left_bound > diag : true;
+ const bool oob_check = need_oob_check ? (row < actual_seqlen_q && col < actual_seqlen_kv) : true;
+ return right_bound_mask && left_bound_mask && oob_check;
+}
+
+//softmax_op 12 types
+static constexpr int BYTES_PER_ELEMENT_12 = 2;
+static constexpr int WARP_TILE_M_12 = 16;
+static constexpr int WARP_TILE_N_12 = 16;
+static constexpr int TILE_M_12 = 64;
+static constexpr int TILE_N_12 = 128;
+static constexpr int WARPS_M_12 = 4;
+static constexpr int WARPS_N_12 = 1;
+static constexpr int WARP_TILES_M_12 = TILE_M_12 / WARP_TILE_M_12;
+static constexpr int WARP_TILES_N_12 = TILE_N_12 / WARP_TILE_N_12;
+static constexpr int THREADS_PER_WARP_TILE_M_12 = 8;
+
+static constexpr int THREADS_PER_WARP_TILE_N_12 = 4;
+static constexpr int WARP_REGS_12 = 8;
+static constexpr int REGS_M_12 = WARP_TILES_M_12 / WARPS_M_12;
+static constexpr int REGS_N_12 = WARP_TILES_N_12 / WARPS_N_12;
+static constexpr int ROWS_PER_THREAD_12 = TILE_M_12 / WARPS_M_12 / THREADS_PER_WARP_TILE_M_12;
+
+// global_store_op 13 types
+static constexpr int BYTES_PER_ELEMENT_13 = 4;
+static constexpr int WARP_TILE_M_13 = 16;
+static constexpr int WARP_TILE_N_13 = 16;
+static constexpr int TILE_M_13 = 64;
+static constexpr int TILE_N_13 = 128;
+static constexpr int WARPS_M_13 = 4;
+static constexpr int WARPS_N_13 = 1;
+static constexpr int WARP_TILES_M_13 = TILE_M_13 / WARP_TILE_M_13;
+static constexpr int WARP_TILES_N_13 = TILE_N_13 / WARP_TILE_N_13;
+static constexpr int THREADS_PER_WARP_TILE_M_13 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_13 = 4;
+static constexpr int ROWS_PER_THREAD_13 = TILE_M_13 / WARPS_M_13 / THREADS_PER_WARP_TILE_M_13;
+
+// global_store_op 14 types
+static constexpr int BYTES_PER_ELEMENT_14 = 4;
+static constexpr int WARP_TILE_M_14 = 16;
+static constexpr int WARP_TILE_N_14 = 16;
+static constexpr int TILE_M_14 = 64;
+static constexpr int TILE_N_14 = 128;
+static constexpr int WARPS_M_14 = 4;
+static constexpr int WARPS_N_14 = 1;
+static constexpr int WARP_TILES_M_14 = TILE_M_14 / WARP_TILE_M_14;
+static constexpr int WARP_TILES_N_14 = TILE_N_14 / WARP_TILE_N_14;
+static constexpr int THREADS_PER_WARP_TILE_M_14 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_14 = 4;
+static constexpr int ROWS_PER_THREAD_14 = TILE_M_14 / WARPS_M_14 / THREADS_PER_WARP_TILE_M_14;
+
+// shared_load_op 15 types
+static constexpr int BITS_PER_ELEMENT_15 = 16;
+static constexpr int BYTES_PER_ELEMENT_15 = 2;
+static constexpr int BYTES_PER_QUAD_15 = 16;
+static constexpr int WARP_TILE_M_15 = 16;
+static constexpr int WARP_TILE_N_15 = 16;
+static constexpr int TILE_M_15 = 128;
+static constexpr int TILE_N_15 = 64;
+static constexpr int BYTES_PER_SMEM_15 = TILE_M_15 * TILE_N_15 * BYTES_PER_ELEMENT_15;
+static constexpr int WARPS_M_15 = 1;
+static constexpr int WARPS_N_15 = 1;
+static constexpr int WARP_TILES_M_15 = TILE_M_15 / WARP_TILE_M_15;
+static constexpr int WARP_TILES_N_15 = TILE_N_15 / WARP_TILE_N_15;
+static constexpr int THREADS_PER_WARP_TILE_M_15 = 8;
+static constexpr int THREADS_PER_WARP_TILE_N_15 = 4;
+static constexpr int REGS_M_15 = WARP_TILES_M_15 / WARPS_M_15;
+static constexpr int REGS_N_15 = WARP_TILES_N_15 / WARPS_N_15;
+static constexpr int BYTES_PER_LD_15 = 128;
+static constexpr int SWIZZLE_SCALE_15 = FORT_MIN(BYTES_PER_LD_15 / 16, WARPS_PER_GROUP_0 * 4);
+
+//global_load_shared_store_op 16 types
+static constexpr int BITS_PER_ELEMENT_16 = 16;
+static constexpr int BYTES_PER_ELEMENT_16 = BITS_PER_ELEMENT_16 / 8;
+static constexpr int BYTES_PER_ACCESS_16 = 16;
+static constexpr int TILE_M_16 = 128;
+static constexpr int TILE_N_16 = 64;
+static constexpr int BYTES_PER_SMEM_16 = TILE_M_16 * TILE_N_16 * BYTES_PER_ELEMENT_16;
+
+//mma_op 17 types
+static constexpr int BYTES_PER_ELEMENT_17 = 2;
+static constexpr int BYTES_PER_ACC_17 = 4;
+static constexpr int WARP_TILE_M_17 = 16;
+static constexpr int WARP_TILE_N_17 = 16;
+static constexpr int WARP_TILE_K_17 = 16;
+static constexpr int TILE_M_17 = 64;
+static constexpr int TILE_N_17 = 64;
+static constexpr int TILE_K_17 = 128;
+static constexpr int WARPS_M_17 = 4;
+static constexpr int WARPS_N_17 = 1;
+static constexpr int WARP_TILES_M_17 = TILE_M_17 / WARP_TILE_M_17;
+static constexpr int WARP_TILES_N_17 = TILE_N_17 / WARP_TILE_N_17;
+static constexpr int MMA_STEPS_K_17 = TILE_K_17 / WARP_TILE_K_17;
+static constexpr int WARP_REGS_17 = 8;
+static constexpr int REGS_M_17 = WARP_TILES_M_17 / WARPS_M_17;
+static constexpr int REGS_N_17 = WARP_TILES_N_17 / WARPS_N_17;
+
+// global_store_op 20 types
+
+// mma_loop_op 2 types
+inline __device__ int2 compute_kv_loop_bounds(const int row_coord, const int ROW_TILE_SIZE, const int COL_TILE_SIZE, const int actual_seqlen_kv, const int actual_seqlen_q, const int shift_right_bound, const int left_bound)
+{
+ constexpr bool is_right_bound = true;
+ constexpr bool is_right_bound_bottom_right_alignment = false;
+ constexpr bool is_shift_right_bound = false;
+ constexpr bool is_left_bound = false;
+ constexpr bool is_left_bound_bottom_right_alignment = false;
+
+ const int right_bound_diagonal = is_right_bound_bottom_right_alignment ? row_coord + (actual_seqlen_kv - actual_seqlen_q) : row_coord;
+ const int shifted_right_bound_diagonal = is_shift_right_bound ? right_bound_diagonal + shift_right_bound : right_bound_diagonal;
+ const int left_bound_diagonal = is_left_bound_bottom_right_alignment ? row_coord + (actual_seqlen_kv - actual_seqlen_q) : row_coord;
+
+ const int kv_loop_left_bound = is_left_bound ? FORT_MAX(0, (left_bound_diagonal - left_bound) / COL_TILE_SIZE) : 0;
+ const int kv_loop_right_bound = is_right_bound ? FORT_MIN(FORT_DIV_UP(shifted_right_bound_diagonal + ROW_TILE_SIZE, COL_TILE_SIZE), FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE)) : FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE);
+ return make_int2(kv_loop_left_bound, kv_loop_right_bound);
+}
+
+// output_loop_op 3 types
+static constexpr int BYTES_PER_BANK_3 = 16;
+static constexpr int LDS_TILE_M_3 = 16;
+static constexpr int LDS_TILE_N_3 = 32;
+static constexpr int ACC_CORE_MATRIX_ROWS_3 = 8; // NOTE: fixed due to GMMA design
+static constexpr int ACC_CORE_MATRIX_COLS_3 = 8; // NOTE: fixed due to GMMA design
+static constexpr int ELEMENTS_PER_VECTOR_3 = 8;
+static constexpr int LDS_PER_TILE_3 = ELEMENTS_PER_VECTOR_3 / 2;
+static constexpr int LDS_TILES_N_3 = FORT_MAX(CTA_TILE_N_1 / LDS_TILE_N_3, 1);
+static constexpr int LDS_TILES_M_3 = FORT_MAX(1, (CTA_TILE_M_1 / GROUPS_M_1) / (LDS_TILE_M_3 * WARPS_PER_GROUP_0));
+static constexpr int VECTORS_PER_LDS_TILES_3 = LDS_TILE_M_3 / ACC_CORE_MATRIX_ROWS_3;
+static constexpr int STS_PER_OUTPUT_TILE_N_3 = CTA_TILE_N_1 / ACC_CORE_MATRIX_COLS_3;
+static constexpr int STSM_X4_PER_OUTPUT_TILE_N_3 = CTA_TILE_N_1 / ACC_CORE_MATRIX_COLS_3 / 2;
+static constexpr int BANKS_PER_PAD_LINE_3 = BYTES_PER_ACC_1 == 4 ? 1 : 2;
+
+static constexpr int PADDING_BYTES_3 = BANKS_PER_PAD_LINE_3 * BYTES_PER_BANK_3 * LDS_PER_TILE_3;
+)KERNEL"
+ R"KERNEL(
+static constexpr int BYTES_PER_STS_PER_WARP_3= 16 * THREADS_PER_WARP_0; // 16 bytes due to STS_128
+static constexpr int BYTES_PER_LDS_TILE_3 = LDS_TILE_N_3 * LDS_TILE_M_3 * BYTES_PER_ACC_1 + PADDING_BYTES_3;
+static constexpr int BYTES_PER_WARP_3 = LDS_TILES_N_3 * BYTES_PER_LDS_TILE_3;
+
+static constexpr int ELEMS_PER_STS_BLOCK_3 = 16;
+
+static constexpr int STG_THREADS_PER_TILE_N_3 = LDS_TILE_N_3 / ELEMENTS_PER_VECTOR_3;
+static constexpr int EPILOGUE_SMEM_SIZE_PER_XMMA_M_3 = BYTES_PER_WARP_3 * WARPS_PER_GROUP_0;
+
+// shared_store_op 18 types
+
+// shared_load_op 19 types
+static constexpr int BITS_PER_ELEMENT_19 = 32 * 1;
+static constexpr int BYTES_PER_ELEMENT_19 = BITS_PER_ELEMENT_19 / 8;
+static constexpr int BITS_PER_VECTOR_19 = BITS_PER_ELEMENT_19 * ELEMENTS_PER_VECTOR_3;
+static constexpr int BYTES_PER_VECTOR_19 = BITS_PER_VECTOR_19 / 8;
+static constexpr int REGISTERS_PER_VECTOR_19 = BITS_PER_VECTOR_19 / BITS_PER_REGISTER_0;
+
+//receive_op 0 code
+
+// === Section: Kernel Function ===
+)KERNEL"
+ R"KERNEL(
+// === Section: Kernel Function ===
+extern "C" __global__ __launch_bounds__(384, 1)
+void cudnn_generated_oss_sdpa_sm90_flash_fprop_wgmma_f16_knob_7_64x128x64_4x1x1_cga1x1x1_kernel0_0(const AttentionDescriptor_t attnDesc
+, int num_tiles_1
+, const FastDivisor_t tiles_hr_div_1
+, const FastDivisor_t tiles_r_div_1
+, int32_t* tile_id_counter
+, __grid_constant__ const CUtensorMap tma_Q
+, __grid_constant__ const CUtensorMap tma_K
+, float attn_scale
+, float neg_infinity
+, void* d_max
+, fort::tensor_descriptor desc_max
+, void* d_sum_exp
+, fort::tensor_descriptor desc_sum_exp
+, __grid_constant__ const CUtensorMap tma_V
+, __grid_constant__ const CUtensorMap tma_O
+) {
+ extern __shared__ char smem_[];
+ uint32_t smem_0 = get_smem_pointer(smem_);
+
+ //receive_op 0 decls
+
+ // mma_pipeline_op 1 decls
+ const uint32_t tid = threadIdx.x % THREADS_PER_GROUP_0;
+ const uint32_t gid = threadIdx.x / THREADS_PER_GROUP_0;
+ const uint32_t wid = threadIdx.x / 32;
+ const uint32_t tiw = threadIdx.x % 32;
+
+ const uint32_t elect_one = fort::elect_one_sync();
+
+ uint32_t smem_1 = smem_0;
+ uint32_t smem_bar_qkv_1 = smem_1;
+ uint32_t smem_page = smem_1 + 1024;
+ uint32_t smem_Q = smem_1 + SMEM_OFFSET_Q_1;
+ uint32_t smem_K = smem_1 + SMEM_OFFSET_K_1;
+ uint32_t smem_V = smem_1 + SMEM_OFFSET_V_1;
+ uint32_t smem_O = smem_1 + SMEM_OFFSET_O_1;
+ uint32_t smem_d_1 = smem_1 + SMEM_OFFSET_D_1;
+ uint32_t smem_band_bias_1 = smem_1 + SMEM_OFFSET_BAND_BIAS_1;
+
+ uint32_t smem_bar_qkv_tma_1 = smem_bar_qkv_1;
+ uint32_t smem_bar_qkv_mma_1 = smem_bar_qkv_1 + 1 * 8 * (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0);
+ uint32_t smem_tile_id_1 = smem_bar_qkv_1 + 2 * 8 * (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0);
+ uint32_t smem_bar_tile_id_tma_1 = smem_tile_id_1 + 16;
+ uint32_t smem_bar_bias_tma_1 = smem_bar_tile_id_tma_1 + 8;
+
+ uint32_t smem_bar_bias_mma_1 = smem_bar_bias_tma_1 + 8 * 2;
+
+ if (elect_one) {
+ for (int i = wid; i < (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0); i+=12) {
+ smem_bar_init(smem_bar_qkv_tma_1 + i * 8, 1);
+ smem_bar_init(smem_bar_qkv_mma_1 + i * 8, 2);
+ }
+ }
+ __syncthreads();
+
+ // mma_pipeline_op 1 code
+ const int actual_num_tiles_1 = num_tiles_1;
+ if (gid == 0) {
+ reg_dealloc<40>();
+ const uint32_t local_wid = wid % 4;
+
+ uint32_t tile_id;
+ uint32_t batch_coord_1 = 0, head_coord_1 = 0, q_row_coord = 0, rows_temp;
+ uint32_t head_coord_from_grid_1, head_coord_k_1, head_coord_v_1, head_coord_q_offset_1;
+ int actual_seqlen_kv_1 = attnDesc.s_kv, actual_seqlen_q_1 = attnDesc.s_q, oob_for_stats_1 = attnDesc.s_q;
+
+ if (local_wid == 0) {
+ uint32_t smem_bar_q_tma = smem_bar_qkv_tma_1;
+ uint32_t smem_bar_k_tma = smem_bar_q_tma + 8 * BUFFERS_Q_1;
+ uint32_t smem_bar_v_tma = smem_bar_k_tma + 8 * BUFFERS_K_1;
+
+ uint32_t smem_bar_q_mma = smem_bar_qkv_mma_1;
+ uint32_t smem_bar_k_mma = smem_bar_q_mma + 8 * BUFFERS_Q_1;
+ uint32_t smem_bar_v_mma = smem_bar_k_mma + 8 * BUFFERS_K_1;
+
+ uint32_t buffer_id_q = 0;
+ uint32_t buffer_id_kv = 0;
+ uint32_t cnt_q = 0;
+ uint32_t cnt_kv = 0;
+
+ uint32_t sts_page_buffer_id = 0;
+ uint32_t lds_page_buffer_id = 0;
+
+ int cumulative_tiles = 0;
+ if (tiw == 0) {
+ tile_id = atomicAdd(tile_id_counter, 1);
+ }
+ tile_id = __shfl_sync(0xffffffff, tile_id, 0);
+
+ named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ if (tiw == 0) {
+ sts_32(smem_tile_id_1, &tile_id);
+ }
+ named_barrier_arrive(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+
+ // Persistent loop over output tiles
+#pragma unroll 1
+ while (tile_id < actual_num_tiles_1) {
+ fastDivMod(tiles_hr_div_1, tile_id, batch_coord_1, rows_temp);
+ fastDivMod(tiles_r_div_1, rows_temp, head_coord_from_grid_1, q_row_coord);
+ q_row_coord *= TILE_M_1 * 2;
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+
+ const int left_bound = 0;
+ const int shift_right_bound = 0;
+
+ int2 kv_loop_bounds = compute_kv_loop_bounds(q_row_coord, TILE_M_1 * 2, TILE_N_1, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ int kv_loop_left_bound = kv_loop_bounds.x;
+ int kv_loop_right_bound = kv_loop_bounds.y;
+
+ //global_load_shared_store_op 4 decls
+
+ //global_load_shared_store_op 7 decls
+
+ //global_load_shared_store_op 16 decls
+
+ uint32_t local_smem_q = smem_Q + buffer_id_q * SMEM_Q_1;
+ uint32_t local_smem_bar_tma_q = smem_bar_q_tma + buffer_id_q * 8;
+ uint32_t local_smem_bar_mma_q = smem_bar_q_mma + buffer_id_q * 8;
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ uint32_t smem_bar_phase_q = cnt_q < BUFFERS_Q_1 ? 1 : 0;
+
+ cnt_q = cnt_q < (2 * BUFFERS_Q_1 - 1) ? (cnt_q + 1) : 0;
+ buffer_id_q = buffer_id_q < ( BUFFERS_Q_1 - 1) ? (buffer_id_q + 1) : 0;
+
+ if (!smem_bar_peek(local_smem_bar_mma_q, smem_bar_phase_q)) {
+ smem_bar_wait(local_smem_bar_mma_q, smem_bar_phase_q);
+ }
+
+ smem_bar_set_transaction_count(local_smem_bar_tma_q, SMEM_Q_1, elect_one);
+ {
+ const uint32_t row_coord = q_row_coord;
+
+ //global_load_shared_store_op 4 code
+#pragma unroll
+ for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_Q,
+ local_smem_q + i * TILE_M_1 * 2,
+ local_smem_bar_tma_q,
+ i / BYTES_PER_ELEMENT_1,
+ row_coord,
+ head_coord_1 + 0,
+ batch_coord_1,
+ elect_one);
+ }
+ }
+ }
+
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound; kv_loop < kv_loop_right_bound; kv_loop++) {
+ const int p_col_coord = kv_loop * TILE_N_1;
+
+ uint32_t local_smem_k = smem_K + buffer_id_kv * SMEM_K_1;
+ uint32_t local_smem_bar_tma_k = smem_bar_k_tma + buffer_id_kv * 8;
+ uint32_t local_smem_bar_mma_k = smem_bar_k_mma + buffer_id_kv * 8;
+
+ uint32_t local_smem_v = smem_V + buffer_id_kv * SMEM_V_1;
+ uint32_t local_smem_bar_tma_v = smem_bar_v_tma + buffer_id_kv * 8;
+
+ uint32_t local_smem_bar_mma_v = smem_bar_v_mma + buffer_id_kv * 8;
+
+ uint32_t smem_bar_phase_kv = cnt_kv < BUFFERS_K_1 ? 1 : 0;
+
+ cnt_kv = cnt_kv < (2 * BUFFERS_K_1 - 1) ? (cnt_kv + 1) : 0;
+ buffer_id_kv = buffer_id_kv < ( BUFFERS_K_1 - 1) ? (buffer_id_kv + 1) : 0;
+
+ uint32_t kv_col_base = (kv_loop + 1) * TILE_N_1;
+
+ if (!smem_bar_peek(local_smem_bar_mma_k, smem_bar_phase_kv)) {
+ smem_bar_wait(local_smem_bar_mma_k, smem_bar_phase_kv);
+ }
+ smem_bar_set_transaction_count(local_smem_bar_tma_k, SMEM_K_1, elect_one);
+
+ //global_load_shared_store_op 7 code
+#pragma unroll
+ for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128) {
+ utmaldg_4d_tiled(&tma_K,
+ local_smem_k + i * TILE_N_1,
+ local_smem_bar_tma_k,
+ i / BYTES_PER_ELEMENT_1,
+ p_col_coord,
+ head_coord_k_1,
+ batch_coord_1,
+ elect_one);
+ }
+ if (!smem_bar_peek(local_smem_bar_mma_v, smem_bar_phase_kv)) {
+ smem_bar_wait(local_smem_bar_mma_v, smem_bar_phase_kv);
+ }
+ smem_bar_set_transaction_count(local_smem_bar_tma_v, SMEM_V_1, elect_one);
+
+ //global_load_shared_store_op 16 code
+#pragma unroll
+ for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128 * CTA_MMA_1) {
+ utmaldg_4d_tiled(&tma_V,
+ local_smem_v + i * TILE_N_1,
+ local_smem_bar_tma_v,
+ 0 + i / BYTES_PER_ELEMENT_1,
+ p_col_coord,
+ head_coord_v_1,
+ batch_coord_1,
+ elect_one);
+ }
+ lds_page_buffer_id ^= 1;
+ }
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ lds_page_buffer_id ^= 1;
+ }
+
+ if (tiw == 0) {
+ tile_id = atomicAdd(tile_id_counter, 1);
+ }
+ tile_id = __shfl_sync(0xffffffff, tile_id, 0);
+
+ named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ if (tiw == 0) {
+ sts_32(smem_tile_id_1, &tile_id);
+ }
+ named_barrier_arrive(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ }
+ named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ }
+ reg_dealloc<40>();
+ } else {
+ reg_alloc<232>();
+ named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+
+ const uint32_t local_wid = wid % 4;
+ const uint32_t local_gid = gid % 2;
+
+ uint32_t tile_id;
+ uint32_t batch_coord_1, head_coord_1, q_row_coord, rows_temp;
+ uint32_t head_coord_from_grid_1, head_coord_k_1, head_coord_v_1, head_coord_q_offset_1;
+ int actual_seqlen_kv_1 = attnDesc.s_kv, actual_seqlen_q_1 = attnDesc.s_q, oob_for_stats_1 = attnDesc.s_q;
+
+ uint32_t smem_bar_q_tma = smem_bar_qkv_tma_1;
+ uint32_t smem_bar_k_tma = smem_bar_q_tma + 8 * BUFFERS_Q_1;
+ uint32_t smem_bar_v_tma = smem_bar_k_tma + 8 * BUFFERS_K_1;
+
+ uint32_t smem_bar_q_mma = smem_bar_qkv_mma_1;
+ uint32_t smem_bar_k_mma = smem_bar_q_mma + 8 * BUFFERS_Q_1;
+ uint32_t smem_bar_v_mma = smem_bar_k_mma + 8 * BUFFERS_K_1;
+
+ uint32_t buffer_id_q = 0;
+ uint32_t buffer_id_kv = 0;
+ uint32_t cnt_q = 0;
+ uint32_t cnt_kv = 0;
+
+ static constexpr float inv_ln2 = 1.4426950408889634074f;
+ static constexpr float ln2 = 0.6931471805599453094f;
+
+ Gmma_descriptor gmma_desc_q(create_gmma_desc_q_1());
+ Gmma_descriptor gmma_desc_k(create_gmma_desc_k_1());
+ Gmma_descriptor gmma_desc_v(create_gmma_desc_v_1());
+
+ gmma_desc_q.set_smem<SMEM_Q_1, BUFFERS_Q_1>(smem_Q + local_gid * TILE_M_1 * 128);
+ gmma_desc_k.set_smem<SMEM_K_1, BUFFERS_K_1>(smem_K);
+ gmma_desc_v.set_smem<SMEM_V_1, BUFFERS_V_1>(smem_V);
+
+ named_barrier_wait(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ if (tiw == 0) {
+ lds_32(&tile_id, smem_tile_id_1);
+ }
+ named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ tile_id = __shfl_sync(0xffffffff, tile_id, 0);
+
+ // Persistent loop over output tiles
+#pragma unroll 1
+ while (tile_id < actual_num_tiles_1) {
+ fastDivMod(tiles_hr_div_1, tile_id, batch_coord_1, rows_temp);
+ fastDivMod(tiles_r_div_1, rows_temp, head_coord_from_grid_1, q_row_coord);
+ q_row_coord = q_row_coord * TILE_M_1 * 2;
+ head_coord_1 = head_coord_from_grid_1;
+ head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k;
+ head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v;
+ const int left_bound = 0;
+ const int shift_right_bound = 0;
+
+ int2 kv_loop_bounds = compute_kv_loop_bounds(q_row_coord, TILE_M_1 * 2, TILE_N_1, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ int kv_loop_left_bound = kv_loop_bounds.x;
+ int kv_loop_right_bound = kv_loop_bounds.y;
+ q_row_coord += local_gid * TILE_M_1;
+
+ const int causal_mask_col = (tiw % 4) * 2;
+ const int causal_mask_row = q_row_coord + local_wid * 16 + (tiw / 4);
+
+ // mma_loop_op 2 decls
+
+ //global_load_shared_store_op 4 decls
+
+ // shared_load_op 5 decls
+
+ // shared_load_op 6 decls
+
+ //global_load_shared_store_op 7 decls
+
+ //mma_op 8 decls
+ r32 reg_8_0[REGS_M_8][REGS_N_8][WARP_REGS_8];
+
+ //pointwise_calc_op 9 decls
+
+ //global_load_op 10 decls
+ r32 reg_10_0[1];
+ reg_10_0[0] = reinterpret_cast<const r32 &>(attn_scale);
+ const int oob_M_10 = 1;
+ const int oob_N_10 = 1;
+
+ //mha_mask_op 11 decls
+
+ //softmax_op 12 decls
+ r32 reg_12_0[REGS_M_12][REGS_N_12][4]; // output for second gemm
+ r32 reg_12_1[ROWS_PER_THREAD_12]; // acc_max
+ r32 reg_12_2[ROWS_PER_THREAD_12]; // p_max
+ r32 reg_12_3[ROWS_PER_THREAD_12]; // acc_sum
+ r32 reg_12_4[ROWS_PER_THREAD_12]; // p_sum
+ r32 reg_12_5[ROWS_PER_THREAD_12]; // softmax stats
+ float beta_12[ROWS_PER_THREAD_12];
+
+#pragma unroll
+ for (int i = 0; i < ROWS_PER_THREAD_12; ++i) {
+ reinterpret_cast<float &>(reg_12_1[i]) = NEG_INFINITY;
+ reinterpret_cast<float &>(reg_12_3[i]) = 0.0f;
+ }
+
+ //global_store_op 13 decls
+ int oob_M_13 = desc_max.dims[2];
+ int row_13 = q_row_coord + local_wid * WARP_TILE_M_1 + (tiw / 4);
+ char *ptr_13 = reinterpret_cast<char *>(d_max)
+ + batch_coord_1 * desc_max.strides[0] * BYTES_PER_ELEMENT_13
+ + head_coord_1 * desc_max.strides[1] * BYTES_PER_ELEMENT_13
+ + row_13 * desc_max.strides[2] * BYTES_PER_ELEMENT_13;
+
+ //global_store_op 14 decls
+ int oob_M_14 = desc_sum_exp.dims[2];
+ int row_14 = q_row_coord + local_wid * WARP_TILE_M_1 + (tiw / 4);
+ char *ptr_14 = reinterpret_cast<char *>(d_sum_exp)
+ + batch_coord_1 * desc_sum_exp.strides[0] * BYTES_PER_ELEMENT_14
+)KERNEL"
+ R"KERNEL(
+ + head_coord_1 * desc_sum_exp.strides[1] * BYTES_PER_ELEMENT_14
+ + row_14 * desc_sum_exp.strides[2] * BYTES_PER_ELEMENT_14;
+
+ // shared_load_op 15 decls
+
+ //global_load_shared_store_op 16 decls
+
+ //mma_op 17 decls
+
+ r32 reg_17_0[REGS_M_17][REGS_N_17][WARP_REGS_17];
+
+ //global_store_op 20 decls
+ static constexpr int cols_per_step_20 = (TILE_K_1 <= 128) ? TILE_K_1 : 64;
+ uint32_t smem_20 = smem_O + (local_gid * 4 + local_wid) * 16 * cols_per_step_20 * BYTES_PER_ELEMENT_1;
+
+ const int swizzled_row_20 = (tiw % 16);
+ const int swizzled_col_20 = (tiw / 16);
+ constexpr int stsm_per_tile_20 = 128 / (BYTES_PER_BANK_1 * 2);
+ uint32_t stsm_base_20[stsm_per_tile_20];
+
+#pragma unroll
+ for (int n = 0; n < stsm_per_tile_20; ++n) {
+ stsm_base_20[n] = smem_20 + ((swizzled_row_20 % 8) ^ (n * 2 + swizzled_col_20)) * BYTES_PER_BANK_1 + swizzled_row_20 * 128;
+ }
+
+ const int row_20 = q_row_coord + (local_wid % 4) * 16;
+
+ uint32_t local_smem_bar_tma_q = smem_bar_q_tma + buffer_id_q * 8;
+ uint32_t local_smem_bar_mma_q = smem_bar_q_mma + buffer_id_q * 8;
+
+ if (local_gid == 1) {
+ named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256);
+ }
+
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ uint32_t smem_bar_phase_q = cnt_q < BUFFERS_Q_1 ? 0 : 1;
+
+ cnt_q = cnt_q < (2 * BUFFERS_Q_1 - 1) ? (cnt_q + 1) : 0;
+ buffer_id_q = buffer_id_q < ( BUFFERS_Q_1 - 1) ? (buffer_id_q + 1) : 0;
+
+ if (!smem_bar_peek(local_smem_bar_tma_q, smem_bar_phase_q)) {
+ smem_bar_wait(local_smem_bar_tma_q, smem_bar_phase_q);
+ }
+ }
+
+ r32 reg_1_0[REGS_M_1][REGS_O_1][WARP_REGS_1];
+ memset(&reg_1_0[0][0][0], 0, sizeof(reg_1_0));
+
+ named_barrier_wait(MATH_WORKGROUP_1, 256);
+#pragma unroll 1
+ for (int kv_loop = kv_loop_left_bound; kv_loop < kv_loop_right_bound; kv_loop++) {
+ static constexpr int kMulPipeCount = REGS_M_1 * REGS_N_1 * WARP_REGS_1;
+
+ static constexpr int kSubtractPipeCount = 6;
+ static constexpr int kConvertPipeCount = 4;
+ static constexpr int oBlockSize = 2;
+
+ const int p_col_coord = kv_loop * TILE_N_1;
+ const int causal_mask_col = p_col_coord + (tiw % 4) * 2;
+ const int causal_mask_row = q_row_coord + local_wid * 16 + (tiw / 4);
+
+ uint32_t local_smem_bar_tma_k = smem_bar_k_tma + buffer_id_kv * 8;
+ uint32_t local_smem_bar_mma_k = smem_bar_k_mma + buffer_id_kv * 8;
+
+ uint32_t local_smem_bar_tma_v = smem_bar_v_tma + buffer_id_kv * 8;
+ uint32_t local_smem_bar_mma_v = smem_bar_v_mma + buffer_id_kv * 8;
+
+ uint32_t smem_bar_phase_kv = cnt_kv < BUFFERS_K_1 ? 0 : 1;
+
+ cnt_kv = cnt_kv < (2 * BUFFERS_K_1 - 1) ? (cnt_kv + 1) : 0;
+ buffer_id_kv = buffer_id_kv < ( BUFFERS_K_1 - 1) ? (buffer_id_kv + 1) : 0;
+
+ memset(&reg_8_0[0][0][0], 0, sizeof(reg_8_0));
+
+ if (!smem_bar_peek(local_smem_bar_tma_k, smem_bar_phase_kv)) {
+ smem_bar_wait(local_smem_bar_tma_k, smem_bar_phase_kv);
+ }
+
+ warpgroup_arrive();
+#pragma unroll
+ for (int k = 0; k < REGS_K_1; ++k) {
+ if (k == REGS_K_1 - 1) {
+ BMM_S_GMMA_ISB(gmma_desc_q.desc, gmma_desc_k.desc, reinterpret_cast<uint32_t *>(reg_8_0[0]));
+ } else {
+ BMM_S_GMMA(gmma_desc_q.desc, gmma_desc_k.desc, reinterpret_cast<uint32_t *>(reg_8_0[0]));
+ }
+ int2 &tmp_desc_q = reinterpret_cast<int2 &>(gmma_desc_q.desc);
+ tmp_desc_q.x += BYTES_PER_GMMA_K_NO_4LSB_1;
+ if ((k % 4) == 3) {
+ tmp_desc_q.x -= BYTES_PER_GMMA_K_NO_4LSB_1 * 4;
+ tmp_desc_q.x += ((128*TILE_M_1*2) >> 4);
+ }
+ int2 &tmp_desc_k = reinterpret_cast<int2 &>(gmma_desc_k.desc);
+ tmp_desc_k.x += BYTES_PER_GMMA_K_NO_4LSB_1;
+ if ((k % 4) == 3) {
+ tmp_desc_k.x -= BYTES_PER_GMMA_K_NO_4LSB_1 * 4;
+ tmp_desc_k.x += ((128*TILE_N_1) >> 4);
+ }
+ }
+ {
+ int2 &tmp_desc_q = reinterpret_cast<int2 &>(gmma_desc_q.desc);
+ tmp_desc_q.x -= ((128 * TILE_M_1 * 2) >> 4) * (REGS_K_1 / 4);
+ int2 &tmp_desc_k = reinterpret_cast<int2 &>(gmma_desc_k.desc);
+ tmp_desc_k.x -= ((128 * TILE_N_1) >> 4) * (REGS_K_1 / 4);
+ }
+ gmma_desc_k.increment_smem_buffer<SMEM_K_1, BUFFERS_K_1>();
+ warpgroup_wait<0>();
+
+ if (local_wid == 0 && elect_one) {
+ smem_bar_arrive(local_smem_bar_mma_k);
+ }
+
+ uint32_t wait_v_done = smem_bar_peek(local_smem_bar_tma_v, smem_bar_phase_kv);
+
+ //mha_mask_op 11 code
+ if (kv_loop >= kv_loop_right_bound - 1)
+ {
+#pragma unroll
+ for (int m = 0; m < REGS_M_11; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_N_11; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_11; ++i) {
+ int row = causal_mask_row + m * WARPS_PER_GROUP_0 * WARP_TILE_M_11 + ((i / 2) % 2) * 8;
+ int col = causal_mask_col + n * WARP_TILE_N_11 + i % 2 + (i / 4) * 8;
+ bool mask = compute_diagonal_band_mask_11(row, col, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ if (!mask) {
+ reinterpret_cast<float &>(reg_8_0[m][n][i]) = neg_infinity;
+ }
+ }
+ }
+ }
+ }
+
+ //global_load_op 10 code
+
+ //mha_mask_op 11 code
+ if (kv_loop >= kv_loop_right_bound - 1)
+ {
+#pragma unroll
+ for (int m = 0; m < REGS_M_11; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_N_11; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_11; ++i) {
+ int row = causal_mask_row + m * WARPS_PER_GROUP_0 * WARP_TILE_M_11 + ((i / 2) % 2) * 8;
+ int col = causal_mask_col + n * WARP_TILE_N_11 + i % 2 + (i / 4) * 8;
+ bool mask = compute_diagonal_band_mask_11(row, col, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound);
+ if (!mask) {
+ reinterpret_cast<float &>(reg_8_0[m][n][i]) = neg_infinity;
+ }
+ }
+ }
+ }
+ }
+
+ //softmax_op 12 code
+ static constexpr float inv_ln2_12 = 1.4426950408889634074f;
+
+ float scaled_inv_ln2_12 = inv_ln2_12 * reinterpret_cast<const float &>(reg_10_0[0]);
+
+ r32 *flattened_s = reinterpret_cast<r32 *>(reg_8_0);
+ r32 *flattened_s_fp16 = reinterpret_cast<r32 *>(reg_12_0);
+ r32 *flattened_o = reinterpret_cast<r32 *>(reg_1_0);
+
+ float tmp_max_level_0[REGS_N_12][4];
+ float tmp_max_level_1[REGS_N_12][2];
+ float tmp_max_level_2[REGS_N_12 / 2][2];
+#pragma unroll
+ for (int m = 0; m < REGS_M_12; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_12; i+=2) {
+ tmp_max_level_0[n][i/2] = fmaxf(reinterpret_cast<const float &>(reg_8_0[m][n][i+0]),
+ reinterpret_cast<const float &>(reg_8_0[m][n][i+1]));
+ }
+ }
+ }
+ // FMUL
+#pragma unroll
+ for (int i = 0; i < kMulPipeCount; i++) {
+ reinterpret_cast<float &>(flattened_s[i]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i]));
+ }
+ {
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; ++n) {
+#pragma unroll
+ for (int i = 0; i < 2; i++) {
+ tmp_max_level_1[n][i] = fmaxf(tmp_max_level_0[n][i + 0],
+ tmp_max_level_0[n][i + 2]);
+ }
+ }
+ }
+ {
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; n+=2) {
+ tmp_max_level_2[n/2][0] = fmaxf(tmp_max_level_1[n][0], tmp_max_level_1[n+1][0]);
+ tmp_max_level_2[n/2][1] = fmaxf(tmp_max_level_1[n][1], tmp_max_level_1[n+1][1]);
+ }
+ }
+ if (TILE_N_1 == 256) {
+ float tmp_max_level_3[REGS_N_12 / 4][2];
+ float tmp_max_level_4[FORT_MAX(1,REGS_N_12 / 8)][2];
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; n+=4) {
+ tmp_max_level_3[n/4][0] = fmaxf(tmp_max_level_2[n/2][0], tmp_max_level_2[n/2+1][0]);
+ tmp_max_level_3[n/4][1] = fmaxf(tmp_max_level_2[n/2][1], tmp_max_level_2[n/2+1][1]);
+ }
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; n+=8) {
+ tmp_max_level_4[n/8][0] = fmaxf(tmp_max_level_3[n/4][0], tmp_max_level_3[n/4+1][0]);
+ tmp_max_level_4[n/8][1] = fmaxf(tmp_max_level_3[n/4][1], tmp_max_level_3[n/4+1][1]);
+ }
+ reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_4[0][0], tmp_max_level_4[1][0]);
+ reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_4[0][1], tmp_max_level_4[1][1]);
+ } else if (TILE_N_1 == 128) {
+ float tmp_max_level_3[REGS_N_12 / 4][2];
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; n+=4) {
+ tmp_max_level_3[n/4][0] = fmaxf(tmp_max_level_2[n/2][0], tmp_max_level_2[n/2+1][0]);
+ tmp_max_level_3[n/4][1] = fmaxf(tmp_max_level_2[n/2][1], tmp_max_level_2[n/2+1][1]);
+ }
+ reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_3[0][0], tmp_max_level_3[1][0]);
+ reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_3[0][1], tmp_max_level_3[1][1]);
+ } else {
+ reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_2[0][0], tmp_max_level_2[1][0]);
+ reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_2[0][1], tmp_max_level_2[1][1]);
+ }
+
+ // Apply the functor for each row inside each group of 4 threads.
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ r32 tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_2[m], 1);
+
+ reinterpret_cast<float &>(reg_12_2[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]),
+ reinterpret_cast<const float &>(tmp_0));
+
+ tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_2[m], 2);
+
+ reinterpret_cast<float &>(reg_12_2[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]),
+ reinterpret_cast<const float &>(tmp_0)) * scaled_inv_ln2_12;
+ }
+
+ // Update acc_max scale of flash attention
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ r32 curr_max = reg_12_1[m];
+ reinterpret_cast<float &>(reg_12_1[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]),
+ reinterpret_cast<const float &>(curr_max));
+ reg_12_2[m] = curr_max;
+ }
+
+ float alpha_12[ROWS_PER_THREAD_12];
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ float p_max = reinterpret_cast<const float &>(reg_12_2[m]);
+ float acc_max = reinterpret_cast<const float &>(reg_12_1[m]);
+
+ // disable FMA for scale * P - max
+ float tmp = (acc_max == NEG_INFINITY) ? p_max : __fsub_rn(p_max, acc_max);
+ reinterpret_cast<r32 &>(alpha_12[m]) = fp32_exp2(reinterpret_cast<r32 &>(tmp));
+ }
+
+#pragma unroll
+ for (int i = 0; i < ROWS_PER_THREAD_12; ++i) {
+ reinterpret_cast<float &>(reg_12_4[i]) = 0.0f;
+ }
+
+ // Broadcast scaled_max and alpha
+ float flattened_scaled_max[REGS_M_12 * REGS_N_12 * WARP_REGS_12];
+ float flattened_alpha[REGS_M_12 * REGS_O_1 * WARP_REGS_12];
+#pragma unroll
+ for (int m = 0; m < REGS_M_12; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_N_12; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_12; ++i) {
+ int row_indx = m * 2 + (i / 2) % 2;
+ float max = reinterpret_cast<const float &>(reg_12_1[row_indx]);
+ flattened_scaled_max[m * REGS_N_12 * WARP_REGS_12 + n * WARP_REGS_12 + i] = (max == NEG_INFINITY ? 0.0f : max);
+ }
+ }
+ }
+
+#pragma unroll
+ for (int m = 0; m < REGS_M_12; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_O_1; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_12; ++i) {
+ int row_indx = m * 2 + (i / 2) % 2;
+ flattened_alpha[m * REGS_O_1 * WARP_REGS_12 + n * WARP_REGS_12 + i] = alpha_12[row_indx];
+ }
+ }
+ }
+
+ cfence();
+ if (local_gid == 1) {
+ named_barrier_wait(SOFTMAX_1_BARRIER_1, 256);
+ } else {
+ named_barrier_wait(SOFTMAX_2_BARRIER_1, 256);
+ }
+ cfence();
+
+ // FSUB
+#pragma unroll
+ for (int i = 0; i < kSubtractPipeCount; i++) {
+)KERNEL"
+ R"KERNEL(
+ reinterpret_cast<float &>(flattened_s[i]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i]), flattened_scaled_max[i]);
+ }
+
+#pragma unroll
+
+ for (int i = 0; i < REGS_M_12 * REGS_N_12 * WARP_REGS_12; i+=2) {
+ int m_0 = (i-kConvertPipeCount+0) / (REGS_N_12 * WARP_REGS_12);
+ int ii_0 = (i-kConvertPipeCount+0) % WARP_REGS_12;
+ int m_1 = (i-kConvertPipeCount+1) / (REGS_N_12 * WARP_REGS_12);
+ int ii_1 = (i-kConvertPipeCount+1) % WARP_REGS_12;
+ int row_indx_0 = m_0 * 2 + (ii_0 / 2) % 2;
+ int row_indx_1 = m_1 * 2 + (ii_1 / 2) % 2;
+ // cast and FADD
+ if (i >= kConvertPipeCount) {
+ fp32x2_to_bf16x2(&flattened_s_fp16[(i - kConvertPipeCount)/2], &flattened_s[i - kConvertPipeCount]);
+ reinterpret_cast<float &>(reg_12_4[row_indx_0]) += reinterpret_cast<float &>(flattened_s[i-kConvertPipeCount+0]);
+ reinterpret_cast<float &>(reg_12_4[row_indx_1]) += reinterpret_cast<float &>(flattened_s[i-kConvertPipeCount+1]);
+ }
+ cfence();
+
+ // exp
+ flattened_s[i+0] = fp32_exp2(flattened_s[i+0]);
+
+ // O update
+#pragma unroll
+ for (int j = 0; j < oBlockSize; j++) {
+ if (oBlockSize*i+j < REGS_O_1 * REGS_M_1 * WARP_REGS_1) {
+ reinterpret_cast<float &>(flattened_o[oBlockSize*i+j]) *= flattened_alpha[oBlockSize*i+j];
+ }
+ }
+
+ // fmul
+ if (i + kMulPipeCount < REGS_M_12 * REGS_N_12 * WARP_REGS_12) {
+ reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+0]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+0]));
+ reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+1]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+1]));
+ }
+ // fsub
+
+ if (i + kSubtractPipeCount < REGS_M_12 * REGS_N_12 * WARP_REGS_12) {
+ reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+0]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+0]), flattened_scaled_max[i+kSubtractPipeCount+0]);
+ reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+1]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+1]), flattened_scaled_max[i+kSubtractPipeCount+1]);
+ }
+
+ // exp
+ flattened_s[i+1] = fp32_exp2(flattened_s[i+1]);
+
+ // O update
+#pragma unroll
+ for (int j = 0; j < oBlockSize; j++) {
+ if (oBlockSize+oBlockSize*i+j < REGS_O_1 * REGS_M_1 * WARP_REGS_1) {
+ reinterpret_cast<float &>(flattened_o[oBlockSize+oBlockSize*i+j]) *= flattened_alpha[oBlockSize+oBlockSize*i+j];
+ }
+ }
+ }
+ if (local_gid == 0) {
+ named_barrier_arrive(SOFTMAX_1_BARRIER_1, 256);
+ } else {
+ named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256);
+ }
+ cfence();
+
+#pragma unroll
+ for (int i = REGS_M_12 * REGS_N_12 * WARP_REGS_12 - kConvertPipeCount; i < REGS_M_12 * REGS_N_12 * WARP_REGS_12; i+=2) {
+ int m_0 = (i + 0) / (REGS_N_12 * WARP_REGS_12);
+ int ii_0 = (i + 0) % WARP_REGS_12;
+ int m_1 = (i + 1) / (REGS_N_12 * WARP_REGS_12);
+ int ii_1 = (i + 1) % WARP_REGS_12;
+ int row_indx_0 = m_0 * 2 + (ii_0 / 2) % 2;
+ int row_indx_1 = m_1 * 2 + (ii_1 / 2) % 2;
+ fp32x2_to_bf16x2(&flattened_s_fp16[i/2], &flattened_s[i]);
+ reinterpret_cast<float &>(reg_12_4[row_indx_0]) += reinterpret_cast<float &>(flattened_s[i+0]);
+ reinterpret_cast<float &>(reg_12_4[row_indx_1]) += reinterpret_cast<float &>(flattened_s[i+1]);
+ }
+
+ if (!wait_v_done) {
+ smem_bar_wait(local_smem_bar_tma_v, smem_bar_phase_kv);
+ }
+
+ warpgroup_arrive();
+#pragma unroll
+ for (int k = 0; k < TILE_N_1 / GMMA_TILE_K_1; ++k) {
+ if (k == (TILE_N_1 / GMMA_TILE_K_1) - 1) {
+ BMM_O_GMMA_ISB(reg_12_0[0][k], gmma_desc_v.desc, reinterpret_cast<uint32_t *>(reg_1_0[0]));
+ } else {
+ BMM_O_GMMA(reg_12_0[0][k], gmma_desc_v.desc, reinterpret_cast<uint32_t *>(reg_1_0[0]));
+ }
+ int2 &tmp_desc_v = reinterpret_cast<int2 &>(gmma_desc_v.desc);
+ tmp_desc_v.x += BYTES_PER_GMMA_K_NO_4LSB_TRANS_1;
+ }
+ {
+ int2 &tmp_desc_v = reinterpret_cast<int2 &>(gmma_desc_v.desc);
+ tmp_desc_v.x -= BYTES_PER_GMMA_K_NO_4LSB_TRANS_1 * (TILE_N_1 / GMMA_TILE_K_1);
+ }
+ gmma_desc_v.increment_smem_buffer<SMEM_V_1, BUFFERS_V_1>();
+
+ warpgroup_wait<0>();
+ if (local_wid == 0 && elect_one) {
+ smem_bar_arrive(local_smem_bar_mma_v);
+ }
+
+ // Update acc_sum of flash attention
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ float p_sum = reinterpret_cast<const float &>(reg_12_4[m]);
+ float acc_sum = reinterpret_cast<const float &>(reg_12_3[m]);
+
+ reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<float &>(alpha_12[m]) * acc_sum + p_sum;
+ }
+ }
+ if (kv_loop_left_bound < kv_loop_right_bound) {
+ gmma_desc_q.increment_smem_buffer<SMEM_Q_1, BUFFERS_Q_1>();
+
+ if (local_wid == 0 && elect_one) {
+ smem_bar_arrive(local_smem_bar_mma_q);
+ }
+ }
+ if (local_gid == 0) {
+ named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256);
+ }
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_12; ++m) {
+ r32 tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_3[m], 1);
+
+ reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<const float &>(reg_12_3[m]) +
+ reinterpret_cast<const float &>(tmp_0);
+
+ tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_3[m], 2);
+
+ reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<const float &>(reg_12_3[m]) +
+ reinterpret_cast<const float &>(tmp_0);
+
+ float sum = reinterpret_cast<float &>(reg_12_3[m]);
+ reinterpret_cast<float &>(reg_12_1[m]) *= ln2;
+
+ reinterpret_cast<float &>(reg_12_5[m]) = (sum == 0.f) ? NEG_INFINITY : reinterpret_cast<const float &>(reg_12_1[m]) + __logf(sum);
+
+ beta_12[m] = (sum == 0.f) ? 0.f : 1.f / sum;
+ }
+
+#pragma unroll
+ for (int m = 0; m < REGS_M_1; ++m) {
+#pragma unroll
+ for (int n = 0; n < REGS_O_1; ++n) {
+#pragma unroll
+ for (int i = 0; i < WARP_REGS_1; ++i) {
+ int row_indx = m * 2 + (i / 2) % 2;
+
+ reinterpret_cast<float &>(reg_1_0[m][n][i]) *= beta_12[row_indx];
+ }
+ }
+ }
+
+ //global_store_op 13 code
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_13; ++m) {
+ const int row_offset = (m % 2) * THREADS_PER_WARP_TILE_M_13 + (m / 2) * WARPS_M_13 * WARP_TILE_M_13;
+
+ if (row_13 + row_offset < oob_M_13 && (tiw % 4) == 0) {
+ stg_32(ptr_13 + row_offset * desc_max.strides[2] * BYTES_PER_ELEMENT_13, &reg_12_1[m]);
+ }
+ }
+
+ //global_store_op 14 code
+#pragma unroll
+ for (int m = 0; m < ROWS_PER_THREAD_14; ++m) {
+ const int row_offset = (m % 2) * THREADS_PER_WARP_TILE_M_14 + (m / 2) * WARPS_M_14 * WARP_TILE_M_14;
+
+ if (row_14 + row_offset < oob_M_14 && (tiw % 4) == 0) {
+ stg_32(ptr_14 + row_offset * desc_sum_exp.strides[2] * BYTES_PER_ELEMENT_14, &reg_12_3[m]);
+ }
+ }
+
+ tmastg_wait();
+
+ //global_store_op 20 code
+#pragma unroll
+ for (int s = 0; s < TILE_O_1 / 64; ++s) {
+#pragma unroll
+ for (int n = 0; n < stsm_per_tile_20; ++n) {
+ uint32_t tmp[4];
+ fp32x2_to_bf16x2(&tmp[0], &reg_1_0[0][s * stsm_per_tile_20 + n][0]);
+ fp32x2_to_bf16x2(&tmp[1], &reg_1_0[0][s * stsm_per_tile_20 + n][2]);
+ fp32x2_to_bf16x2(&tmp[2], &reg_1_0[0][s * stsm_per_tile_20 + n][4]);
+ fp32x2_to_bf16x2(&tmp[3], &reg_1_0[0][s * stsm_per_tile_20 + n][6]);
+ stsm_x4(stsm_base_20[n] + s * 64 * 16 * BYTES_PER_ELEMENT_1, tmp);
+ }
+ }
+ fence_view_async_shared();
+
+ int head_coord_loc = 0;
+ int row = row_20;
+ int head = head_coord_1;
+#pragma unroll
+ for (int s = 0; s < TILE_K_1 / 64; ++s) {
+ utmastg_4d_tiled(&tma_O,
+ smem_20 + s * 64 * 16 * BYTES_PER_ELEMENT_1,
+ s * 64,
+ row,
+ head + head_coord_loc,
+ batch_coord_1);
+ }
+ tmastg_arrive();
+
+ named_barrier_wait(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ if (tiw == 0) {
+ lds_32(&tile_id, smem_tile_id_1);
+ }
+ named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1);
+ tile_id = __shfl_sync(0xffffffff, tile_id, 0);
+ }
+ tmastg_wait();
+ reg_alloc<232>();
+ }
+}
+)KERNEL";
+inline constexpr size_t d64_fprop_source_len = sizeof(d64_fprop_source) - 1;
+
+inline constexpr const char d64_fprop_flags[] = R"FLAGS(--gpu-architecture=sm_90a
+--std=c++17
+--define-macro=__x86_64__
+-w
+--define-macro=__CUDACC_RTC__
+-default-device
+--use_fast_math
+)FLAGS";
+inline constexpr size_t d64_fprop_flags_len = sizeof(d64_fprop_flags) - 1;
+
+} // namespace generated
+} // namespace experimental
+} // namespace cudnn_frontend
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/graph_helpers.h b/deps/cudnn-frontend/include/cudnn_frontend/graph_helpers.h
new file mode 100644
index 0000000..d2ce9e3
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/graph_helpers.h
@@ -0,0 +1,587 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <unordered_map>
+#include <vector>
+
+#include <iomanip>
+#include <unordered_set>
+#include <algorithm>
+#include <string>
+#include <numeric>
+
+namespace cudnn_frontend {
+
+enum class [[nodiscard]] error_code_t {
+ OK,
+ ATTRIBUTE_NOT_SET,
+ SHAPE_DEDUCTION_FAILED,
+ INVALID_TENSOR_NAME,
+ INVALID_VARIANT_PACK,
+ GRAPH_NOT_SUPPORTED,
+ GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ GRAPH_EXECUTION_FAILED,
+ HEURISTIC_QUERY_FAILED,
+ UNSUPPORTED_GRAPH_FORMAT,
+ CUDA_API_FAILED,
+ CUDNN_BACKEND_API_FAILED,
+ INVALID_CUDA_DEVICE,
+ HANDLE_ERROR,
+ INVALID_VALUE,
+ NVRTC_COMPILATION_FAILED
+};
+
+typedef struct [[nodiscard]] error_object {
+ error_code_t code;
+ std::string err_msg;
+ error_object() : code(error_code_t::OK), err_msg("") {};
+ error_object(error_code_t err, std::string msg) : code(err), err_msg(msg) {};
+
+ error_code_t
+ get_code() {
+ return code;
+ }
+
+ std::string
+ get_message() {
+ return err_msg;
+ }
+
+ bool
+ is_good() const {
+ return code == error_code_t::OK;
+ }
+
+ bool
+ is_bad() const {
+ return !is_good();
+ }
+
+ bool
+ operator==(error_code_t compare_code) {
+ return code == compare_code;
+ }
+
+ bool
+ operator!=(error_code_t compare_code) {
+ return code != compare_code;
+ }
+
+} error_t;
+
+#ifdef WIN32
+#define CUDNN_FRONTEND_WHILE_FALSE \
+ __pragma(warning(push)) __pragma(warning(disable : 4127)) while (0) __pragma(warning(pop))
+#else
+#define CUDNN_FRONTEND_WHILE_FALSE while (0)
+#endif
+
+#define CHECK_CUDNN_FRONTEND_ERROR(x) \
+ do { \
+ if (auto retval = x; retval.is_bad()) { \
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: " << #x << " at " << __FILE__ << ":" << __LINE__); \
+ return retval; \
+ } \
+ } \
+ CUDNN_FRONTEND_WHILE_FALSE
+
+#define RETURN_CUDNN_FRONTEND_ERROR_IF(cond, retval, message) \
+ do { \
+ if (cond) { \
+ if (retval == error_code_t::OK) { \
+ CUDNN_FE_LOG_LABEL("INFO: "); \
+ } else { \
+ CUDNN_FE_LOG_LABEL("ERROR: "); \
+ } \
+ CUDNN_FE_LOG(message << ". " << retval << " because (" << #cond ") at " << __FILE__ << ":" << __LINE__ \
+ << "\n"); \
+ return {retval, message}; \
+ } \
+ } \
+ CUDNN_FRONTEND_WHILE_FALSE
+
+#define _CUDNN_CHECK_CUDNN_ERROR(x) \
+ do { \
+ if (auto cudnn_retval = x; cudnn_retval != CUDNN_STATUS_SUCCESS) { \
+ std::stringstream error_msg; \
+ error_msg << #x << " failed with message: " << detail::get_last_error_string_() \
+ << ", and code: " << detail::get_error_string(cudnn_retval); \
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: " << error_msg.str() << " at " << __FILE__ << ":" << __LINE__); \
+ return {error_code_t::CUDNN_BACKEND_API_FAILED, error_msg.str()}; \
+ } \
+ } \
+ CUDNN_FRONTEND_WHILE_FALSE
+
+#define _CUDNN_CHECK_CUDA_ERROR(x) \
+ do { \
+ if (auto cuda_retval = x; cuda_retval != cudaSuccess) { \
+ std::stringstream error_msg; \
+ error_msg << #x << " failed with " << detail::cuda_get_error_string(cuda_retval); \
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: " << error_msg.str() << " at " << __FILE__ << ":" << __LINE__); \
+ return {error_code_t::CUDA_API_FAILED, error_msg.str()}; \
+ } \
+ } \
+ CUDNN_FRONTEND_WHILE_FALSE
+
+NLOHMANN_JSON_SERIALIZE_ENUM(error_code_t,
+ {
+ {error_code_t::OK, "OK"},
+ {error_code_t::ATTRIBUTE_NOT_SET, "ATTRIBUTE_NOT_SET"},
+ {error_code_t::SHAPE_DEDUCTION_FAILED, "SHAPE_DEDUCTION_FAILED"},
+ {error_code_t::INVALID_TENSOR_NAME, "INVALID_TENSOR_NAME"},
+ {error_code_t::INVALID_VARIANT_PACK, "INVALID_VARIANT_PACK"},
+ {error_code_t::GRAPH_NOT_SUPPORTED, "GRAPH_NOT_SUPPORTED"},
+ {error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "GRAPH_EXECUTION_PLAN_CREATION_FAILED"},
+ {error_code_t::GRAPH_EXECUTION_FAILED, "GRAPH_EXECUTION_FAILED"},
+ {error_code_t::HEURISTIC_QUERY_FAILED, "HEURISTIC_QUERY_FAILED"},
+ {error_code_t::CUDNN_BACKEND_API_FAILED, "CUDNN_BACKEND_API_FAILED"},
+ {error_code_t::CUDA_API_FAILED, "CUDA_API_FAILED"},
+ {error_code_t::INVALID_CUDA_DEVICE, "INVALID_CUDA_DEVICE"},
+ {error_code_t::UNSUPPORTED_GRAPH_FORMAT, "UNSUPPORTED_GRAPH_FORMAT"},
+ {error_code_t::HANDLE_ERROR, "HANDLE_ERROR"},
+ {error_code_t::INVALID_VALUE, "INVALID_VALUE"},
+ {error_code_t::NVRTC_COMPILATION_FAILED, "NVRTC_COMPILATION_FAILED"},
+ })
+
+static inline std::ostream&
+operator<<(std::ostream& os, const error_code_t& mode) {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ os << json{mode};
+#else
+ os << int(mode);
+#endif
+ return os;
+}
+
+static inline std::ostream&
+operator<<(std::ostream& os, cudnn_frontend::error_object& err) {
+ os << err.get_code() << err.get_message();
+ return os;
+}
+
+static bool
+allowAllConfig(cudnnBackendDescriptor_t engine_config) {
+ (void)engine_config;
+ return false;
+}
+
+namespace detail {
+
+inline bool
+is_activation_backward_mode(PointwiseMode_t const mode) {
+ return ((mode == PointwiseMode_t::RELU_BWD) || (mode == PointwiseMode_t::TANH_BWD) ||
+ (mode == PointwiseMode_t::SIGMOID_BWD) || (mode == PointwiseMode_t::ELU_BWD) ||
+ (mode == PointwiseMode_t::GELU_BWD) || (mode == PointwiseMode_t::GELU_APPROX_TANH_BWD) ||
+ (mode == PointwiseMode_t::SOFTPLUS_BWD) || (mode == PointwiseMode_t::SWISH_BWD));
+}
+
+// Creates dense, non-overlapping strides from given dim and stride_order.
+// For example, if a is a 4D tensor with dimensions labeled NCHW, then strided(a, (3, 0, 2, 1)) produces
+// strides where the C dimension has a corresponding stride of one.
+inline std::vector<int64_t>
+generate_stride(std::vector<int64_t> const& dim, std::vector<int64_t> const& stride_order) {
+ size_t num_dims = dim.size();
+ std::vector<int64_t> stride(num_dims);
+
+ // Sort the dimensions according to strides from least to greatest.
+ // Example, dim = (2, 3, 4, 5) stride_order = (3, 1, 2, 0)
+ // sorted_stride_order = ((0, (3, 5)), (1, (1, 3)), (2, (2, 4)), (3, (0, 2)))
+ std::vector<std::pair<int64_t, std::pair<size_t, size_t>>> sorted_stride_order;
+ for (size_t i = 0; i < num_dims; ++i) {
+ sorted_stride_order.push_back({stride_order[i], {i, dim[i]}});
+ }
+ std::sort(sorted_stride_order.begin(), sorted_stride_order.end());
+
+ // As dims have now been ordered starting from fastest changing,
+ // just fill in strides by iterating linearly over them.
+ int64_t product = 1;
+ for (size_t i = 0; i < num_dims; ++i) {
+ stride[sorted_stride_order[i].second.first] = product;
+ product *= sorted_stride_order[i].second.second;
+ }
+
+ return stride;
+}
+
+// Generate NHWC stride_order
+inline std::vector<int64_t>
+generate_NHWC_stride_order(int64_t const num_dims) {
+ std::vector<int64_t> stride_order(num_dims);
+
+ int64_t order = 0;
+ stride_order[1] = order++;
+ for (size_t i = num_dims - 1; i > 1; --i) {
+ stride_order[i] = order++;
+ }
+ stride_order[0] = order;
+
+ return stride_order;
+}
+
+// Generate row major stride_order for matrices
+// dim = (*, M, N) where * is batch dimsensions
+// strides should be (..., N, 1)
+inline std::vector<int64_t>
+generate_row_major_stride_order(int64_t const num_dims) {
+ std::vector<int64_t> stride_order(num_dims);
+
+ int64_t order = num_dims - 1;
+ std::generate(stride_order.begin(), stride_order.end(), [&order] { return order--; });
+
+ return stride_order;
+}
+
+// Generate column major stride_order for matrices
+// dim = (*, M, N)
+// strides should be (*, 1, M)
+inline std::vector<int64_t>
+generate_column_major_stride_order(int64_t const num_dims) {
+ std::vector<int64_t> stride_order = generate_row_major_stride_order(num_dims);
+ if (num_dims > 2) {
+ std::swap(stride_order[num_dims - 1], stride_order[num_dims - 2]);
+ }
+ return stride_order;
+}
+
+/**
+ * @brief Computes the common shape with the fewest dimensions that all input shapes can be broadcast to.
+ *
+ * This function takes a vector of shapes and calculates a common shape that all input shapes
+ * can be broadcast to. It follows broadcasting rules similar to those used in NumPy.
+ *
+ * @param _shapes A vector of vectors, where each inner vector represents a shape.
+ * Each shape is a sequence of dimension sizes.
+ * @param[out] common_shape The computed broadcast shape is stored in this vector.
+ * It will be cleared and resized as necessary.
+ *
+ * @return error_t An error code indicating the result of the operation
+ *
+ * @note
+ * - Shapes are processed from right to left (last dimension to first).
+ * - A dimension of size 1 can be broadcast to any size.
+ * - Non-1 dimensions must match exactly for broadcasting.
+ * - The resulting shape will have the maximum number of dimensions among all input shapes.
+ *
+ * @example
+ * std::vector<std::vector<int64_t>> shapes = {{3, 1, 4}, {1, 2, 4}, {2, 4}};
+ * std::vector<int64_t> result;
+ * error_t err = compute_broadcast_shape(shapes, result);
+ * // If err == error_code_t::OK, result will be {3, 2, 4}
+ */
+inline error_t
+compute_broadcast_shape(const std::vector<std::vector<int64_t>>& _shapes, std::vector<int64_t>& common_shape) {
+ // Filter out empty shapes
+ std::vector<std::vector<int64_t>> shapes;
+ std::copy_if(_shapes.begin(), _shapes.end(), std::back_inserter(shapes), [](const std::vector<int64_t>& shape) {
+ return !shape.empty();
+ });
+
+ // Short-circuits if there are no input shapes
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ shapes.empty(), error_code_t::SHAPE_DEDUCTION_FAILED, "All input shapes provided are empty.");
+
+ // Find the maximum dimension
+ int64_t max_dim = std::max_element(shapes.begin(),
+ shapes.end(),
+ [](const std::vector<int64_t>& a, const std::vector<int64_t>& b) {
+ return a.size() < b.size();
+ })
+ ->size();
+
+ // Initialize common_shape with 1s
+ common_shape.assign(max_dim, 1);
+
+ for (const auto& shape : shapes) {
+ for (int idx = -1; idx >= -static_cast<int>(shape.size()); --idx) {
+ int64_t common_idx = common_shape.size() + idx;
+ int64_t shape_idx = shape.size() + idx;
+
+ if (common_shape[common_idx] == 1) {
+ common_shape[common_idx] = shape[shape_idx];
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF((shape[shape_idx] != 1) && (common_shape[common_idx] != shape[shape_idx]),
+ error_code_t::SHAPE_DEDUCTION_FAILED,
+ "dimensions mismatch as broadcasting 2 non-one dimension sizes.");
+ }
+ }
+
+ return {error_code_t::OK, ""};
+}
+/**
+ * @brief Generates a stride order preserving the format of the input tensor.
+ *
+ * This function derives the exact stride order from the input tensor's strides.
+ * It returns the indices of the strides in ascending order of stride values.
+ *
+ * @param input_stride The stride of the input tensor
+ * @param output_dim_size The number of dimensions in the output tensor
+ * @return std::vector<int64_t> The generated stride order
+ */
+inline error_t
+generate_stride_order_preserving_format(const std::vector<int64_t>& input_stride,
+ size_t output_dim_size,
+ std::vector<int64_t>& stride_order) {
+ std::vector<int64_t> indices(input_stride.size());
+ std::iota(indices.begin(), indices.end(), 0);
+
+ // Sort indices based on stride values in descending order
+ std::sort(indices.begin(), indices.end(), [&input_stride](int64_t i, int64_t j) {
+ return input_stride[i] < input_stride[j];
+ });
+
+ // Enable this after further debug
+ // std::set<int64_t> stride_set(input_stride.begin(), input_stride.end());
+ // RETURN_CUDNN_FRONTEND_ERROR_IF((stride_set.size() != input_stride.size()),
+ // error_code_t::SHAPE_DEDUCTION_FAILED,
+ // "Have multiple stride with same value. Cant determine stride order");
+
+ // Create the stride order
+ stride_order.resize(input_stride.size());
+ for (size_t i = 0; i < indices.size(); ++i) {
+ stride_order[indices[i]] = i;
+ }
+
+ // If output_dim_size is larger, pad with remaining dimensions
+ if (output_dim_size > input_stride.size()) {
+ size_t start = stride_order.size();
+ stride_order.resize(output_dim_size);
+ std::iota(stride_order.begin() + start, stride_order.end(), start);
+ }
+
+ return {error_code_t::OK, ""};
+}
+
+/**
+ * @brief Infers the output dimensions for a matrix multiplication operation.
+ *
+ * This function calculates the output dimensions of a matrix multiplication
+ * based on the input dimensions of tensors A and B. It uses compute_broadcast_shape
+ * for batch dimensions and ensures the last two dimensions are correct for matrix multiplication.
+ *
+ * @param a_dim Dimensions of the first input tensor (A).
+ * @param b_dim Dimensions of the second input tensor (B).
+ * @param output_dim Reference to the vector where the output dimensions will be stored.
+ * @return error_t An error code indicating the result of the operation.
+ */
+inline error_t
+generate_matmul_output_dim(const std::vector<int64_t>& a_dim,
+ const std::vector<int64_t>& b_dim,
+ std::vector<int64_t>& output_dim) {
+ // Ensure a_dim and b_dim have at least 2 dimensions
+ if (a_dim.size() < 2 || b_dim.size() < 2) {
+ return {error_code_t::SHAPE_DEDUCTION_FAILED, "Input tensors must have at least 2 dimensions for matmul."};
+ }
+
+ // Check if inner dimensions are compatible
+ if (a_dim[a_dim.size() - 1] != b_dim[b_dim.size() - 2]) {
+ return {error_code_t::SHAPE_DEDUCTION_FAILED,
+ "Inner dimensions of input tensors are not compatible for matmul."};
+ }
+
+ // Prepare shapes for broadcasting
+ std::vector<int64_t> a_batch_dim(a_dim.begin(), a_dim.end() - 2);
+ std::vector<int64_t> b_batch_dim(b_dim.begin(), b_dim.end() - 2);
+
+ // Compute broadcast shape for batch dimensions
+ std::vector<int64_t> broadcasted_batch;
+ CHECK_CUDNN_FRONTEND_ERROR(detail::compute_broadcast_shape({a_batch_dim, b_batch_dim}, broadcasted_batch));
+
+ // Construct final output shape
+ output_dim = broadcasted_batch;
+ output_dim.push_back(a_dim[a_dim.size() - 2]); // M from A
+ output_dim.push_back(b_dim[b_dim.size() - 1]); // N from B
+
+ return {error_code_t::OK, ""};
+}
+
+inline std::string
+to_hex(const void* data, size_t num_elements, size_t elem_size) {
+ const auto* bytes = static_cast<const unsigned char*>(data);
+ std::stringstream ss;
+ ss << "[";
+ for (size_t i = 0; i < num_elements; ++i) {
+ if (i > 0) ss << ", ";
+ ss << "0x" << std::hex << std::uppercase;
+ switch (elem_size) {
+ case 1:
+ ss << static_cast<unsigned>(bytes[i]);
+ break;
+ case 2:
+ ss << *reinterpret_cast<const uint16_t*>(&bytes[i * 2]);
+ break;
+ case 4:
+ ss << *reinterpret_cast<const uint32_t*>(&bytes[i * 4]);
+ break;
+ case 8:
+ ss << *reinterpret_cast<const uint64_t*>(&bytes[i * 8]);
+ break;
+ default:
+ ss << "?";
+ }
+ }
+ ss << "]";
+ return ss.str();
+}
+
+inline std::string
+to_decimal(const void* data, size_t num_elements, size_t elem_size) {
+ const auto* bytes = static_cast<const unsigned char*>(data);
+ std::stringstream ss;
+ ss << "[";
+ for (size_t i = 0; i < num_elements; ++i) {
+ if (i > 0) ss << ", ";
+ switch (elem_size) {
+ case 1:
+ ss << static_cast<int>(bytes[i]);
+ break;
+ case 2:
+ ss << *reinterpret_cast<const int16_t*>(&bytes[i * 2]);
+ break;
+ case 4:
+ ss << *reinterpret_cast<const int32_t*>(&bytes[i * 4]);
+ break;
+ case 8:
+ ss << *reinterpret_cast<const int64_t*>(&bytes[i * 8]);
+ break;
+ default:
+ ss << "?";
+ }
+ }
+ ss << "]";
+ return ss.str();
+}
+
+inline std::string
+to_base64(const void* data, size_t total_bytes) {
+ static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ const auto* bytes = static_cast<const unsigned char*>(data);
+ std::string result;
+ result.reserve(((total_bytes + 2) / 3) * 4);
+ for (size_t i = 0; i < total_bytes; i += 3) {
+ uint32_t n = static_cast<uint32_t>(bytes[i]) << 16;
+ if (i + 1 < total_bytes) n |= static_cast<uint32_t>(bytes[i + 1]) << 8;
+ if (i + 2 < total_bytes) n |= static_cast<uint32_t>(bytes[i + 2]);
+ result.push_back(table[(n >> 18) & 0x3F]);
+ result.push_back(table[(n >> 12) & 0x3F]);
+ result.push_back((i + 1 < total_bytes) ? table[(n >> 6) & 0x3F] : '=');
+ result.push_back((i + 2 < total_bytes) ? table[n & 0x3F] : '=');
+ }
+ return result;
+}
+
+inline error_t
+log_dump_tensor_content(int64_t uid,
+ std::string const& name,
+ void* ptr,
+ size_t num_elements,
+ size_t elem_size,
+ char fmt,
+ cudaStream_t stream) {
+ if (!isLoggingEnabled()) return {error_code_t::OK, ""};
+
+ size_t total_bytes = num_elements * elem_size;
+
+ cudaPointerAttributes attr;
+ _CUDNN_CHECK_CUDA_ERROR(cuda_pointer_get_attributes(&attr, ptr));
+
+ std::vector<unsigned char> host_buf(total_bytes);
+ if (attr.type == cudaMemoryTypeDevice || attr.type == cudaMemoryTypeManaged) {
+ _CUDNN_CHECK_CUDA_ERROR(cuda_mem_cpy_async(host_buf.data(), ptr, total_bytes, cudaMemcpyDeviceToHost, stream));
+ _CUDNN_CHECK_CUDA_ERROR(cuda_stream_synchronize(stream));
+ } else {
+ std::memcpy(host_buf.data(), ptr, total_bytes);
+ }
+
+ std::string data_str;
+ switch (fmt) {
+ case 'x':
+ data_str = to_hex(host_buf.data(), num_elements, elem_size);
+ break;
+ case 'd':
+ data_str = to_decimal(host_buf.data(), num_elements, elem_size);
+ break;
+ case 'b':
+ data_str = to_base64(host_buf.data(), total_bytes);
+ break;
+ default:
+ data_str = to_hex(host_buf.data(), num_elements, elem_size);
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("Tensor Dump Uid: " << uid << " Name: " << name << " Data: " << data_str);
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+log_variant_pack_memory_type(int64_t uid, void* ptr) {
+ if (!isLoggingEnabled()) return {error_code_t::OK, ""};
+
+ cudaPointerAttributes attributes;
+ _CUDNN_CHECK_CUDA_ERROR(cuda_pointer_get_attributes(&attributes, ptr));
+
+ auto memory_type_to_string = [](cudaMemoryType type) {
+ switch (type) {
+ case cudaMemoryTypeHost:
+ return std::string("Host");
+ case cudaMemoryTypeDevice:
+ return std::string("Device");
+ case cudaMemoryTypeManaged:
+ return std::string("Managed");
+ case cudaMemoryTypeUnregistered:
+ return std::string("Unregistered");
+ default:
+ return "UNKNOWN cudaMemoryType (" + std::to_string(type) + ")";
+ }
+ };
+
+ auto ptr_to_string = [](void* p) {
+ std::stringstream ss;
+ ss << "0x" << std::hex << std::setw(sizeof(void*) * 2) << std::setfill('0') << reinterpret_cast<uintptr_t>(p);
+ return ss.str();
+ };
+
+ // clang-format off
+ CUDNN_FE_LOG_LABEL_ENDL("Variant Pack" << std::setw(0) << " Uid: " << std::setw(20) << uid
+ << std::setw(0) << " MemoryType: " << std::setw(12) << memory_type_to_string(attributes.type)
+ << std::setw(0) << " Device: " << std::setw(4) << attributes.device
+ << std::setw(0) << " UnifiedPtr: " << std::setw(20) << ptr_to_string(ptr)
+ << std::setw(0) << " DevicePtr: " << std::setw(20) << ptr_to_string(attributes.devicePointer)
+ << std::setw(0) << " HostPtr: " << std::setw(20) << ptr_to_string(attributes.hostPointer));
+ // clang-format on
+ return {error_code_t::OK, ""};
+}
+
+} // namespace detail
+
+class cudnnGraphNotSupportedException : public std::runtime_error {
+ public:
+ cudnnGraphNotSupportedException(const char* message) throw() : std::runtime_error(message) {}
+
+ virtual const char*
+ what() const throw() {
+ return std::runtime_error::what();
+ }
+};
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/graph_interface.h b/deps/cudnn-frontend/include/cudnn_frontend/graph_interface.h
new file mode 100644
index 0000000..7cac72b
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/graph_interface.h
@@ -0,0 +1,3878 @@
+#pragma once
+
+#include <atomic>
+#include <mutex>
+#include <unordered_map>
+#include <stdexcept>
+#include <string>
+
+#include "../cudnn_frontend_version.h"
+#include "node/batchnorm.h"
+#include "node/batchnorm_inference.h"
+#include "node/bn_finalize.h"
+#include "node/conv_fprop.h"
+#include "node/conv_dgrad.h"
+#include "node/conv_wgrad.h"
+#include "node/dbn.h"
+#include "node/dln.h"
+#include "node/dbn_weight.h"
+#include "node/genstats.h"
+#include "node/layernorm.h"
+#include "node/adaptive_layernorm.h"
+#include "node/instancenorm.h"
+#include "node/rmsnorm.h"
+#include "node/rope.h"
+#include "node/rope_backward.h"
+#include "node/resample.h"
+#include "node/reshape.h"
+#include "node/slice.h"
+#include "node/transpose.h"
+// #include "node/scaled_dot_product_attention.h"
+#include "node/scaled_dot_product_flash_attention.h"
+#include "node/sdpa_fp8_bwd.h"
+#include "node/block_scale_quantize.h"
+#include "node/block_scale_dequantize.h"
+#include "node/concatenate.h"
+#include "node/moe_grouped_matmul.h"
+#include "node/moe_grouped_matmul_bwd.h"
+
+#include "backend/backend_descriptor.h"
+#include "plans.h"
+#include "knobs.h"
+#include "graph_helpers.h"
+#include "backend/kernel_cache.h"
+
+namespace cudnn_frontend::graph {
+
+class Graph : public ICudnn, public INode {
+ private:
+ std::unordered_set<std::shared_ptr<Tensor_attributes>> full_graph_inputs;
+ std::unordered_set<Tensor_attributes::uid_t> used_uids;
+ int64_t fe_workspace_size = 0;
+ uint64_t graph_uid;
+
+ std::unordered_set<std::shared_ptr<Tensor_attributes>> deserialized_tensor_properties;
+ std::unordered_map<uid_t, pass_by_values_t> deserialized_pass_by_value;
+ std::unordered_map<uid_t, std::tuple<int64_t, int64_t, std::vector<float>>> deserialized_workspace_modifications;
+
+ // Cached values computed during build/deserialize, used during execute to avoid repeated collection.
+ // These are mutable because execute() is const but needs non-const access for pointer extraction.
+ mutable std::unordered_map<uid_t, pass_by_values_t> cached_pass_by_value;
+ mutable std::unordered_map<uid_t, std::tuple<int64_t, int64_t, std::vector<float>>> cached_workspace_modifications;
+
+ // char: 'x'=hex, 'd'=decimal, 'b'=base64
+ std::vector<std::pair<std::shared_ptr<Tensor_attributes>, char>> tensors_to_dump;
+
+ error_t
+ get_pre_assigned_uids(std::unordered_set<Tensor_attributes::uid_t> &used_uids) {
+ for (auto const &input : full_graph_inputs) {
+ if (input->has_uid()) {
+ auto uid = input->get_uid();
+ auto iter = used_uids.find(uid);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(iter != used_uids.end(),
+ error_code_t::INVALID_VALUE,
+ "uid " + std::to_string(uid) + " for tensor named " + input->get_name() +
+ " has been already assigned to another tensor.");
+ used_uids.insert(uid);
+ }
+ }
+ for (auto const &output : full_graph_outputs) {
+ if (output->has_uid()) {
+ auto uid = output->get_uid();
+ auto iter = used_uids.find(uid);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(iter != used_uids.end(),
+ error_code_t::INVALID_VALUE,
+ "uid " + std::to_string(uid) + " for tensor named " +
+ output->get_name() +
+ " has been already assigned to another tensor.");
+ used_uids.insert(uid);
+ }
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ log_tensors_to_dump_(cudnnHandle_t handle,
+ std::unordered_map<int64_t, void *> const &tensor_uid_to_pointer_map) const {
+ if (!isLoggingTensorDumpEnabled()) {
+ return {error_code_t::OK, ""};
+ }
+
+ for (auto const &[uid, ptr] : tensor_uid_to_pointer_map) {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::log_variant_pack_memory_type(uid, ptr));
+ }
+
+ cudaStream_t stream;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_stream(handle, &stream));
+ for (auto const &[tensor, fmt] : tensors_to_dump) {
+ auto it = tensor_uid_to_pointer_map.find(tensor->get_uid());
+ if (it != tensor_uid_to_pointer_map.end()) {
+ auto const &dims = tensor->get_dim();
+ size_t num_elements = 1;
+ for (auto d : dims) num_elements *= static_cast<size_t>(d);
+ size_t elem_size = detail::get_data_type_size(tensor->get_data_type());
+ CHECK_CUDNN_FRONTEND_ERROR(detail::log_dump_tensor_content(
+ it->first, tensor->get_name(), it->second, num_elements, elem_size, fmt, stream));
+ }
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (context.get_dynamic_shape_enabled() || kernel_cache != nullptr) && detail::get_backend_version() < 90400,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Dynamic shapes or kernel caching enabled, but cuDNN version < 9.4!");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(((context.get_dynamic_shape_enabled() == false) && (kernel_cache != nullptr)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Kernel caching enabled but dynamic shapes is disabled");
+ if (detail::get_backend_version() != detail::get_compiled_version()) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: The cuDNN version used at compilation ("
+ << detail::get_compiled_version() << ") and the one used at runtime ("
+ << detail::get_backend_version() << ") differ.");
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ post_validate_node() const override final {
+ return {error_code_t::OK, ""};
+ }
+
+ virtual error_t
+ collect_pass_by_value_tensors_node(
+ std::unordered_map<uid_t, pass_by_values_t> &pass_by_values) const override final {
+ for (auto [uid, value] : deserialized_pass_by_value) {
+ pass_by_values.emplace(uid, value);
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ virtual error_t
+ collect_tensors_in_workspace_node(
+ std::unordered_map<Tensor_attributes::uid_t, std::tuple<int64_t, int64_t, std::vector<float>>>
+ &worskspace_modifications,
+ int64_t &) const override {
+ for (auto [uid, value] : deserialized_workspace_modifications) {
+ worskspace_modifications.emplace(uid, value);
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ virtual error_t
+ create_cudnn_tensors_node(std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>> &,
+ int64_t &,
+ std::unordered_set<int64_t> const &) const override final {
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ extend_tensor_map_with_workspace_tensors_(
+ std::unordered_map<int64_t, void *> &tensor_to_pointer_map,
+ void *workspace,
+ std::unordered_map<uid_t, std::tuple<int64_t, int64_t, std::vector<float>>> const &worskspace_modifications)
+ const {
+ for (auto const &[uid, data] : worskspace_modifications) {
+ tensor_to_pointer_map.emplace(uid, static_cast<char *>(workspace) + std::get<1>(data));
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ extend_tensor_map_with_pass_by_value_tensors_(
+ std::unordered_map<int64_t, void *> &tensor_to_pointer_map,
+ std::unordered_map<uid_t, pass_by_values_t> &tensor_to_pass_by_value) const {
+ for (auto &[uid, value] : tensor_to_pass_by_value) {
+ if (half *half_value_ptr = std::get_if<half>(&value)) {
+ tensor_to_pointer_map.emplace(uid, half_value_ptr);
+ } else if (nv_bfloat16 *nv_bfloat16_value_ptr = std::get_if<nv_bfloat16>(&value)) {
+ tensor_to_pointer_map.emplace(uid, nv_bfloat16_value_ptr);
+ } else if (int32_t *int32_t_value_ptr = std::get_if<int32_t>(&value)) {
+ tensor_to_pointer_map.emplace(uid, int32_t_value_ptr);
+ } else if (int64_t *int64_t_value_ptr = std::get_if<int64_t>(&value)) {
+ tensor_to_pointer_map.emplace(uid, int64_t_value_ptr);
+ } else if (float *float_value_ptr = std::get_if<float>(&value)) {
+ tensor_to_pointer_map.emplace(uid, float_value_ptr);
+ } else if (double *double_value_ptr = std::get_if<double>(&value)) {
+ tensor_to_pointer_map.emplace(uid, double_value_ptr);
+ } else {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ true, error_code_t::INVALID_VARIANT_PACK, "Unexpected type for pass by value tensor.");
+ }
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ make_variant_pack_replacements(
+ std::unordered_map<int64_t, void *> &tensor_to_pointer_map,
+ std::unordered_map<Tensor_attributes::uid_t, std::pair<Tensor_attributes::uid_t, int64_t>> replacements) const {
+ for (auto &[from_uid, value] : replacements) {
+ const auto &[to_uid, start_offset] = value;
+
+ // Check if from_uid exists in the map
+ auto it = tensor_to_pointer_map.find(from_uid);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(it == tensor_to_pointer_map.end(),
+ error_code_t::INVALID_VARIANT_PACK,
+ "Variant pack expected uid " + std::to_string(from_uid) + " but not found.");
+
+ // Perform pointer arithmetic
+ tensor_to_pointer_map[to_uid] = static_cast<void *>(static_cast<char *>(it->second) + start_offset);
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ int64_t
+ get_max_cudnn_workspace_size() const {
+ return get_max_cudnn_workspace_size_node();
+ }
+
+ // Key: uid to replace in variant pack
+ // Value: uid to replace with, start offset to add to pointer
+ std::unordered_map<Tensor_attributes::uid_t, std::pair<Tensor_attributes::uid_t, int64_t>>
+ variant_pack_replacements;
+
+ error_t
+ run_auxiliary_kernels(
+ cudnnHandle_t handle,
+ void *fe_workspace,
+ std::unordered_map<uid_t, std::tuple<int64_t, int64_t, std::vector<float>>> &workspace_modifications) const {
+ cudaStream_t stream;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_stream(handle, &stream));
+ char *workspace = static_cast<char *>(fe_workspace);
+
+ for (auto [uid, data] : workspace_modifications) {
+ (void)uid;
+ if (std::get<0>(data) == 0) {
+ auto &vec_data = std::get<2>(data);
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_mem_cpy_async(workspace + std::get<1>(data),
+ vec_data.data(),
+ vec_data.size() * sizeof(float),
+ cudaMemcpyHostToDevice,
+ stream));
+ } else if (std::get<0>(data) == 1) {
+ int64_t memset_size = (int64_t)std::get<2>(data)[0];
+ _CUDNN_CHECK_CUDA_ERROR(
+ detail::cuda_mem_set_async(workspace + std::get<1>(data), 0, memset_size, stream));
+ }
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ size_t
+ key(bool remove_shape) {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ json j;
+ serialize(j);
+ j.erase("graph_uid");
+ if (remove_shape) {
+ for (auto &tensor : j["tensors"]) {
+ tensor["dim"].clear();
+ tensor["stride"].clear();
+ }
+ }
+ return std::hash<json>{}(j);
+#else
+ CUDNN_FRONTEND_UNUSED(remove_shape);
+ return 1;
+#endif
+ }
+
+ // Private unified sdpa method - internal implementation for both FP16 and FP8 modes
+ inline SDPA_attributes::SDPA_outputs
+ sdpa_internal(std::shared_ptr<Tensor_attributes> q,
+ std::shared_ptr<Tensor_attributes> k,
+ std::shared_ptr<Tensor_attributes> v,
+ SDPA_attributes &&attributes) {
+ // Set inputs
+ attributes.inputs[SDPA_attributes::input_names::Q] = q;
+ attributes.inputs[SDPA_attributes::input_names::K] = k;
+ attributes.inputs[SDPA_attributes::input_names::V] = v;
+
+ // Make required output tensors
+ SDPA_attributes::SDPA_outputs sdpa_outputs;
+
+ sdpa_outputs.O = attributes.outputs[SDPA_attributes::output_names::O] = output_tensor(attributes.name + "::O");
+
+ if (attributes.generate_stats == true) {
+ sdpa_outputs.Stats = attributes.outputs[SDPA_attributes::output_names::Stats] =
+ output_tensor(attributes.name + "::Stats");
+ }
+
+ // Dropout mask dump (created conditionally based on dropout parameters)
+ if (attributes.outputs.find(SDPA_attributes::output_names::RNG_DUMP) != attributes.outputs.end() &&
+ attributes.outputs.at(SDPA_attributes::output_names::RNG_DUMP) != nullptr) {
+ sdpa_outputs.RNG_DUMP = attributes.outputs[SDPA_attributes::output_names::RNG_DUMP];
+ }
+
+ // FP8-specific outputs (created conditionally based on FP8 scaling parameters)
+ if (attributes.inputs.find(SDPA_attributes::input_names::Descale_S) != attributes.inputs.end() &&
+ attributes.inputs.at(SDPA_attributes::input_names::Descale_S) != nullptr) {
+ sdpa_outputs.Amax_S = attributes.outputs[SDPA_attributes::output_names::Amax_S] =
+ output_tensor(attributes.name + "::Amax_S");
+ }
+ if (attributes.mma_core_mode == DataType_t::FP8_E4M3 || attributes.mma_core_mode == DataType_t::FP8_E5M2) {
+ sdpa_outputs.Amax_O = attributes.outputs[SDPA_attributes::output_names::Amax_O] =
+ output_tensor(attributes.name + "::Amax_O");
+ }
+
+ if (attributes.implementation == AttentionImplementation_t::AUTO) {
+ // Sets attributes.implementation to a supporting implementation,
+ // or leaves as AUTO if none found
+ attributes._auto_select_implementation(context);
+ }
+
+ switch (attributes.implementation) {
+ case AttentionImplementation_t::AUTO:
+ throw std::runtime_error("No suitable implementation for given SDPA_attributes");
+ break;
+ case AttentionImplementation_t::COMPOSITE:
+ sub_nodes.emplace_back(std::make_unique<CompositeSDPANode>(std::move(attributes), context));
+ break;
+ case AttentionImplementation_t::UNIFIED:
+ sub_nodes.emplace_back(std::make_unique<UnifiedSDPANode>(std::move(attributes), context));
+ break;
+ }
+
+ return sdpa_outputs;
+ }
+
+ // Register an OSS NVRTC engine for SDPA by extracting tensor metadata from the SDPA node's attributes
+ error_t
+ register_oss_engine_() {
+ // Find the SDPA node in the graph's sub_nodes via dynamic_cast
+ SDPA_attributes const *sdpa_attrs = nullptr;
+ for (auto const &sub_node : sub_nodes) {
+ if (auto *composite = dynamic_cast<CompositeSDPANode *>(sub_node.get())) {
+ sdpa_attrs = &composite->attributes;
+ break;
+ }
+ if (auto *unified = dynamic_cast<UnifiedSDPANode *>(sub_node.get())) {
+ sdpa_attrs = &unified->attributes;
+ break;
+ }
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sdpa_attrs == nullptr, error_code_t::GRAPH_NOT_SUPPORTED, "No SDPA node found for OPENSOURCE engine");
+
+ graph::Execution_plan_list::OssSdpaEngineContext ctx;
+
+ // Q tensor
+ auto q_it = sdpa_attrs->inputs.find(SDPA_attributes::input_names::Q);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(q_it == sdpa_attrs->inputs.end() || !q_it->second,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Q tensor not found in SDPA node");
+ auto const &q = q_it->second;
+ ctx.q_uid = q->get_uid();
+ ctx.q_stride = q->get_stride();
+ ctx.batch = q->get_dim()[0];
+ ctx.heads_q = q->get_dim()[1];
+ ctx.seq_q = q->get_dim()[2];
+ ctx.d = q->get_dim()[3];
+
+ // K tensor — CompositeSDPANode transposes K in-place (swaps dims[2]/dims[3]
+ // and strides[2]/strides[3]) for the Q*K^T GEMM. Detect and undo.
+ auto k_it = sdpa_attrs->inputs.find(SDPA_attributes::input_names::K);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(k_it == sdpa_attrs->inputs.end() || !k_it->second,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "K tensor not found in SDPA node");
+ auto const &k = k_it->second;
+ auto const &k_dims = k->get_dim();
+ auto const &k_strides = k->get_stride();
+ ctx.k_uid = k->get_uid();
+ ctx.heads_kv = k_dims[1];
+ if (k_dims[2] < k_dims[3]) {
+ // dims currently (B, H_kv, D, S_kv) — swapped
+ ctx.seq_kv = k_dims[3];
+ ctx.k_stride = {k_strides[0], k_strides[1], k_strides[3], k_strides[2]};
+ } else {
+ ctx.seq_kv = k_dims[2];
+ ctx.k_stride = k_strides;
+ }
+
+ // V tensor
+ auto v_it = sdpa_attrs->inputs.find(SDPA_attributes::input_names::V);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(v_it == sdpa_attrs->inputs.end() || !v_it->second,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "V tensor not found in SDPA node");
+ ctx.v_uid = v_it->second->get_uid();
+ ctx.v_stride = v_it->second->get_stride();
+
+ // O tensor
+ auto o_it = sdpa_attrs->outputs.find(SDPA_attributes::output_names::O);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(o_it == sdpa_attrs->outputs.end() || !o_it->second,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "O tensor not found in SDPA node");
+ ctx.o_uid = o_it->second->get_uid();
+ ctx.o_stride = o_it->second->get_stride();
+
+ // Max tensor (optional — only present if user called set_logit_max)
+ auto max_it = sdpa_attrs->outputs.find(SDPA_attributes::output_names::Max);
+ if (max_it != sdpa_attrs->outputs.end() && max_it->second) {
+ ctx.max_uid = max_it->second->get_uid();
+ ctx.max_stride = max_it->second->get_stride();
+ }
+
+ // Sum_exp tensor (optional — only present if user called set_score_sum_exp)
+ auto se_it = sdpa_attrs->outputs.find(SDPA_attributes::output_names::Sum_exp);
+ if (se_it != sdpa_attrs->outputs.end() && se_it->second) {
+ ctx.sum_exp_uid = se_it->second->get_uid();
+ ctx.sum_exp_stride = se_it->second->get_stride();
+ }
+
+ // Attention scale (use user-provided value if set, otherwise engine computes 1/sqrt(d))
+ if (sdpa_attrs->attn_scale_value.has_value()) {
+ ctx.attn_scale = sdpa_attrs->attn_scale_value.value();
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(ctx.q_uid == -1 || ctx.k_uid == -1 || ctx.v_uid == -1 || ctx.o_uid == -1,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Could not find Q/K/V/O tensors in SDPA node for OPENSOURCE engine");
+
+ // Detect SM version and instantiate the appropriate OSS engine
+ int oss_device_ordinal = 0;
+ experimental::detail::cuda_get_device(&oss_device_ordinal);
+ cudaDeviceProp oss_dev_prop;
+ experimental::detail::cuda_get_device_properties(&oss_dev_prop, oss_device_ordinal);
+ int oss_sm = oss_dev_prop.major * 10 + oss_dev_prop.minor;
+
+ std::shared_ptr<experimental::IOssSdpaEngine> engine;
+ if (oss_sm / 10 == 10) {
+ engine = std::make_shared<experimental::Sm100SdpaPrefillEngine>();
+ } else {
+ engine = std::make_shared<experimental::Sm90SdpaPrefillEngine>();
+ }
+ plans.set_oss_sdpa_engine(engine);
+ plans.set_oss_sdpa_engine_context(std::move(ctx));
+
+ return {error_code_t::OK, ""};
+ }
+
+ // Register an OSS NVRTC engine for RmsNorm+SiLU by detecting the fusion pattern:
+ // RMSNormNode(X, SCALE) → Y → PointwiseNode(SWISH_FWD) → Z
+ // Extracts tensor metadata and instantiates the appropriate arch-specific engine.
+ error_t
+ register_oss_rms_norm_silu_engine_() {
+ // Scan sub_nodes for the RMSNorm → SiLU pattern
+ Rmsnorm_attributes const *rmsnorm_attrs = nullptr;
+ Pointwise_attributes const *swish_attrs = nullptr;
+ std::shared_ptr<Tensor_attributes> swish_output;
+
+ for (size_t i = 0; i + 1 < sub_nodes.size(); ++i) {
+ auto *rmsnorm_node = dynamic_cast<RMSNormNode *>(sub_nodes[i].get());
+ if (!rmsnorm_node) continue;
+
+ auto *pointwise_node = dynamic_cast<PointwiseNode *>(sub_nodes[i + 1].get());
+ if (!pointwise_node) continue;
+
+ if (pointwise_node->attributes.get_mode() != PointwiseMode_t::SWISH_FWD) continue;
+
+ // OSS engine only supports SiLU (Swish with beta=1.0).
+ // Reject if beta is explicitly set to a non-1.0 value.
+ auto beta = pointwise_node->attributes.get_swish_beta().value_or(1.0f);
+ if (beta != 1.0f) continue;
+
+ // Verify the RMSNorm output feeds into the pointwise input
+ auto rmsnorm_y_it = rmsnorm_node->attributes.outputs.find(Rmsnorm_attributes::output_names::Y);
+ if (rmsnorm_y_it == rmsnorm_node->attributes.outputs.end() || !rmsnorm_y_it->second) continue;
+
+ auto swish_in0_it = pointwise_node->attributes.inputs.find(Pointwise_attributes::input_names::IN_0);
+ if (swish_in0_it == pointwise_node->attributes.inputs.end() || !swish_in0_it->second) continue;
+
+ // Check that RMSNorm output Y == SiLU input IN_0 (same tensor)
+ if (rmsnorm_y_it->second->get_uid() != swish_in0_it->second->get_uid()) continue;
+
+ // Pattern matched!
+ rmsnorm_attrs = &rmsnorm_node->attributes;
+ swish_attrs = &pointwise_node->attributes;
+ swish_output = pointwise_node->attributes.outputs.at(Pointwise_attributes::output_names::OUT_0);
+ break;
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(rmsnorm_attrs == nullptr || swish_attrs == nullptr,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "No RMSNorm → SiLU fusion pattern found for OPENSOURCE engine");
+
+ // Only inference is supported (no mean/inv_variance output for training)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(rmsnorm_attrs->forward_phase != NormFwdPhase_t::INFERENCE,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "OSS RmsNorm+SiLU engine only supports INFERENCE phase");
+
+ // Extract tensor metadata
+ graph::Execution_plan_list::OssRmsNormSiluContext ctx;
+
+ // X input tensor
+ auto x_it = rmsnorm_attrs->inputs.find(Rmsnorm_attributes::input_names::X);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(x_it == rmsnorm_attrs->inputs.end() || !x_it->second,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "X tensor not found in RMSNorm node");
+
+ // Input must be bf16 (the kernel always uses ITYPE = nv_bfloat16)
+ auto x_dtype = x_it->second->get_data_type();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(x_dtype != DataType_t::BFLOAT16,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "OSS RmsNorm+SiLU engine requires BFLOAT16 input");
+
+ ctx.x_uid = x_it->second->get_uid();
+ auto x_dim = x_it->second->get_dim();
+ // X shape in NCHW: [N, C, H, W] where norm operates per-row (N) across columns (C*H*W)
+ // num_tokens = N (first dim), C = product of remaining dims (C*H*W)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ x_dim.size() < 2, error_code_t::GRAPH_NOT_SUPPORTED, "X tensor must have at least 2 dimensions");
+ ctx.num_tokens = x_dim[0];
+ ctx.C = 1;
+ for (size_t d = 1; d < x_dim.size(); ++d) {
+ ctx.C *= x_dim[d];
+ }
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ ctx.num_tokens <= 0 || ctx.C <= 0,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Invalid problem dimensions: num_tokens=" + std::to_string(ctx.num_tokens) + " C=" + std::to_string(ctx.C));
+
+ // SCALE (gamma) tensor — must be bf16 (kernel uses WTYPE = nv_bfloat16)
+ auto scale_it = rmsnorm_attrs->inputs.find(Rmsnorm_attributes::input_names::SCALE);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(scale_it == rmsnorm_attrs->inputs.end() || !scale_it->second,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "SCALE tensor not found in RMSNorm node");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(scale_it->second->get_data_type() != DataType_t::BFLOAT16,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "OSS RmsNorm+SiLU engine requires BFLOAT16 scale weights");
+ ctx.scale_uid = scale_it->second->get_uid();
+
+ // BIAS (beta) tensor — optional
+ auto bias_it = rmsnorm_attrs->inputs.find(Rmsnorm_attributes::input_names::BIAS);
+ if (bias_it != rmsnorm_attrs->inputs.end() && bias_it->second) {
+ ctx.bias_uid = bias_it->second->get_uid();
+ }
+
+ // EPSILON tensor
+ auto eps_it = rmsnorm_attrs->inputs.find(Rmsnorm_attributes::input_names::EPSILON);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(eps_it == rmsnorm_attrs->inputs.end() || !eps_it->second,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "EPSILON tensor not found in RMSNorm node");
+ ctx.epsilon_uid = eps_it->second->get_uid();
+
+ // Output Z tensor (output of SiLU, not RMSNorm)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !swish_output, error_code_t::GRAPH_NOT_SUPPORTED, "Output tensor not found in SiLU node");
+ ctx.y_uid = swish_output->get_uid();
+
+ // Determine output dtype from the output tensor
+ auto out_dtype = swish_output->get_data_type();
+ if (out_dtype == DataType_t::BFLOAT16) {
+ ctx.output_dtype = experimental::RmsNormSiluDtype::BF16;
+ } else if (out_dtype == DataType_t::FP8_E4M3) {
+ ctx.output_dtype = experimental::RmsNormSiluDtype::FP8;
+ } else if (out_dtype == DataType_t::FP4_E2M1) {
+ ctx.output_dtype = experimental::RmsNormSiluDtype::NVFP4;
+ } else {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "OSS RmsNorm+SiLU engine supports BFLOAT16, FP8_E4M3, or FP4_E2M1 output"};
+ }
+
+ // Detect SM version and instantiate the appropriate OSS engine
+ int oss_device_ordinal = 0;
+ experimental::detail::cuda_get_device(&oss_device_ordinal);
+ cudaDeviceProp oss_dev_prop;
+ experimental::detail::cuda_get_device_properties(&oss_dev_prop, oss_device_ordinal);
+ int oss_sm = oss_dev_prop.major * 10 + oss_dev_prop.minor;
+
+ std::shared_ptr<experimental::IOssNormEngine> engine;
+ if (oss_sm >= 80) {
+ engine = std::make_shared<experimental::Sm100RmsNormSiluEngine>();
+ } else {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "RmsNorm+SiLU OSS engine requires SM80+, got SM" + std::to_string(oss_sm)};
+ }
+
+ plans.set_oss_rms_norm_silu_engine(engine);
+ plans.set_oss_rms_norm_silu_context(std::move(ctx));
+
+ return {error_code_t::OK, ""};
+ }
+
+ public:
+ Graph() : INode(detail::Context{}) {
+ static std::atomic<uint64_t> next_graph_uid{1};
+ graph_uid = next_graph_uid.fetch_add(1, std::memory_order_relaxed);
+ }
+
+ error_t
+ update_cuda_graph(cudnnHandle_t handle,
+ std::unordered_map<std::shared_ptr<Tensor_attributes>, void *> &tensor_to_pointer_map,
+ void *workspace,
+ cudaGraph_t cudnn_cuda_graph) {
+ // First get all the uids from the map
+ std::unordered_map<Tensor_attributes::uid_t, void *> tensor_uid_to_pointer_map;
+ tensor_uid_to_pointer_map.reserve(tensor_to_pointer_map.size());
+ for (auto const &[tensor, pointer] : tensor_to_pointer_map) {
+ tensor_uid_to_pointer_map.emplace(tensor->get_uid(), pointer);
+ }
+
+ return update_cuda_graph(handle, tensor_uid_to_pointer_map, workspace, cudnn_cuda_graph);
+ }
+
+ error_t
+ update_cuda_graph(cudnnHandle_t handle,
+ std::unordered_map<Tensor_attributes::uid_t, void *> &uid_to_device_ptrs,
+ void *workspace,
+ cudaGraph_t cudnn_cuda_graph) {
+ // Initializes this cudnn graph
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cudnn_cuda_graph == nullptr, error_code_t::INVALID_VALUE, "cudnn_cuda_graph should not be a nullptr");
+
+ size_t num_root_nodes;
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_get_root_nodes(cudnn_cuda_graph, nullptr, &num_root_nodes));
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ num_root_nodes != 1, error_code_t::INVALID_VALUE, "cudnn_cuda_graph should have exactly 1 root node.");
+
+ cudaGraphNode_t current_node = nullptr;
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_get_root_nodes(cudnn_cuda_graph, &current_node, &num_root_nodes));
+
+ ///////////////////////////////////////
+ //// PASS BY VALUE TENSOR HANDLING ////
+ ///////////////////////////////////////
+ // Add pass_by_value data pointers to uid_to_pointer map.
+ // Using cached values to avoid repeated tree traversal overhead.
+ // cuda graph will keep a copy of the kernel parameters, meaning that at the time of
+ // launching the cuda_graph executable, cached values being deallocated does not affect these cpu values.
+ // No cuda graph nodes are required for handling fe owned pass by value tensors.
+ CHECK_CUDNN_FRONTEND_ERROR(
+ extend_tensor_map_with_pass_by_value_tensors_(uid_to_device_ptrs, cached_pass_by_value));
+
+ ////////////////////////////
+ //// WORKSPACE HANDLING ////
+ ////////////////////////////
+ // Using cached workspace modifications to avoid repeated tree traversal.
+ for (auto const &[uid, data] : cached_workspace_modifications) {
+ const auto &[operation_type, offset, vec_data] = data;
+ uid_to_device_ptrs[uid] = static_cast<char *>(workspace) + offset;
+
+ // 0 means memcpy
+ if (operation_type == 0) {
+ _CUDNN_CHECK_CUDA_ERROR(
+ detail::cuda_graph_add_memcpy_node_set_params_1D(current_node,
+ static_cast<char *>(workspace) + offset,
+ vec_data.data(),
+ vec_data.size() * sizeof(float),
+ cudaMemcpyHostToDevice));
+ }
+ // 1 means memset
+ else if (operation_type == 1) {
+ // offset from workspace
+ void *device_ptr = static_cast<char *>(workspace) + offset;
+ int64_t memset_size = static_cast<int64_t>(vec_data[0]);
+
+ cudaMemsetParams params;
+ params.dst = device_ptr;
+ params.elementSize = sizeof(char);
+ params.value = 0x0;
+ params.width = memset_size;
+ params.height = 1; // 1D memset currently
+ params.pitch = 0; // unused
+
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_add_memset_node_set_params(current_node, &params));
+ }
+ // Other values do not correspond to CUDA graph nodes
+ else {
+ continue;
+ }
+
+ size_t num_dependent_nodes;
+ _CUDNN_CHECK_CUDA_ERROR(
+ detail::cuda_graph_node_get_dependent_nodes(current_node, nullptr, &num_dependent_nodes));
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ num_dependent_nodes != 1,
+ error_code_t::INVALID_VALUE,
+ "Each node of cudnn_cuda_graph before the backend graph node should have exactly 1 dependent node.");
+ _CUDNN_CHECK_CUDA_ERROR(
+ detail::cuda_graph_node_get_dependent_nodes(current_node, &current_node, &num_dependent_nodes));
+ }
+
+ // Make sure device pointer is provided for all uids expected for this plan
+ std::vector<void *> device_ptrs;
+ std::vector<uid_t> uids;
+
+ device_ptrs.reserve(variant_pack_uids.size());
+ uids.reserve(variant_pack_uids.size());
+
+ for (auto const &uid : variant_pack_uids) {
+ auto search = uid_to_device_ptrs.find(uid);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(search == uid_to_device_ptrs.end(),
+ error_code_t::INVALID_VARIANT_PACK,
+ "Uid " + std::to_string(uid) + " does not exist in variant pack.");
+ device_ptrs.push_back(search->second);
+ uids.push_back(uid);
+ }
+
+ ///////////////////
+ //// BE GRAPH ////
+ ///////////////////
+ cudaGraph_t backend_cuda_graph;
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_child_graph_node_get_graph(current_node, &backend_cuda_graph));
+
+ detail::backend_descriptor variant_pack_descriptor(CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(variant_pack_descriptor.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create variant pack's backend descriptor.");
+
+ // offset workspace by the already used fe graph workspace
+ // this is where cudnn backend can start using workspace for its execution plans
+ void *cudnn_workspace = static_cast<char *>(workspace) + fe_workspace_size;
+ CHECK_CUDNN_FRONTEND_ERROR(create_variant_pack(variant_pack_descriptor, device_ptrs, uids, cudnn_workspace));
+
+ int64_t candidate = plans.candidate;
+ CHECK_CUDNN_FRONTEND_ERROR(plans.is_plan_index_executable(candidate));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::update_cuda_graph(handle,
+ plans.execution_plans[candidate]->get_raw_desc(),
+ variant_pack_descriptor.get_ptr(),
+ backend_cuda_graph));
+
+ // There should be nothing after the backend graph
+ size_t num_dependent_nodes;
+ _CUDNN_CHECK_CUDA_ERROR(
+ detail::cuda_graph_node_get_dependent_nodes(current_node, nullptr, &num_dependent_nodes));
+ RETURN_CUDNN_FRONTEND_ERROR_IF(num_dependent_nodes != 0,
+ error_code_t::INVALID_VALUE,
+ "cudnn_cuda_graph should have no graph nodes after the backend graph node.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ populate_cuda_graph(cudnnHandle_t handle,
+ std::unordered_map<std::shared_ptr<Tensor_attributes>, void *> &tensor_to_pointer_map,
+ void *workspace,
+ cudaGraph_t cudnn_cuda_graph) {
+ // First get all the uids from the map
+ std::unordered_map<Tensor_attributes::uid_t, void *> tensor_uid_to_pointer_map;
+ tensor_uid_to_pointer_map.reserve(tensor_to_pointer_map.size());
+ for (auto const &[tensor, pointer] : tensor_to_pointer_map) {
+ tensor_uid_to_pointer_map.emplace(tensor->get_uid(), pointer);
+ }
+
+ return populate_cuda_graph(handle, tensor_uid_to_pointer_map, workspace, cudnn_cuda_graph);
+ }
+
+ error_t
+ populate_cuda_graph(cudnnHandle_t handle,
+ std::unordered_map<Tensor_attributes::uid_t, void *> &uid_to_device_ptrs,
+ void *workspace,
+ cudaGraph_t cudnn_cuda_graph) {
+ // Check if the cuda graph is empty
+ size_t numNodes = 0;
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_get_nodes(cudnn_cuda_graph, nullptr, &numNodes));
+ RETURN_CUDNN_FRONTEND_ERROR_IF(numNodes != 0,
+ error_code_t::INVALID_VALUE,
+ "cuda graph provided to populate is not empty. cuDNN requires it to be empty "
+ "for the corresponding update APIs to work correctly.");
+
+ // This function makes linear cuda graphs. And that makes it easy to walk
+ // the graph when updating it.
+ // So just keeping track of the last node in the cuda graph is sufficient.
+ cudaGraphNode_t last_node = nullptr;
+
+ ///////////////////////////////////////
+ //// PASS BY VALUE TENSOR HANDLING ////
+ ///////////////////////////////////////
+ // Add pass_by_value data pointers to uid_to_pointer map.
+ // Using cached values to avoid repeated tree traversal overhead.
+ // cuda graph will keep a copy of the kernel parameters, meaning that at the time of
+ // launching the cuda_graph executable, cached values being deallocated does not affect these cpu values.
+ // No cuda graph nodes are required for handling fe owned pass by value tensors.
+ CHECK_CUDNN_FRONTEND_ERROR(
+ extend_tensor_map_with_pass_by_value_tensors_(uid_to_device_ptrs, cached_pass_by_value));
+
+ /////////////////////////////////
+ //// WORKSPACE HANDLING ////
+ /////////////////////////////////
+ // Using cached workspace modifications to avoid repeated tree traversal.
+ for (auto const &[uid, data] : cached_workspace_modifications) {
+ const auto &[operation_type, offset, vec_data] = data;
+ uid_to_device_ptrs[uid] = static_cast<char *>(workspace) + offset;
+
+ cudaGraphNode_t node = nullptr;
+
+ // 0 means memcpy
+ if (operation_type == 0) {
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_add_memcpy_node_1D(&node,
+ cudnn_cuda_graph,
+ &last_node,
+ last_node != nullptr,
+ static_cast<char *>(workspace) + offset,
+ vec_data.data(),
+ vec_data.size() * sizeof(float),
+ cudaMemcpyHostToDevice));
+ }
+ // 1 means memset
+ else if (operation_type == 1) {
+ // offset from workspace
+ void *device_ptr = static_cast<char *>(workspace) + offset;
+ int64_t memset_size = static_cast<int64_t>(vec_data[0]);
+
+ cudaMemsetParams params;
+ params.dst = device_ptr;
+ params.elementSize = sizeof(char);
+ params.value = 0x0;
+ params.width = memset_size;
+ params.height = 1; // 1D memset currently
+ params.pitch = 0; // unused
+
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_add_memset_node(
+ &node, cudnn_cuda_graph, &last_node, last_node != nullptr, &params));
+ }
+ // Other values do not correspond to CUDA graph nodes
+ else {
+ continue;
+ }
+
+ last_node = node;
+ }
+
+ //////////////
+ // BE graph //
+ //////////////
+
+ // Get the BE's cuda graph
+
+ // Make sure device pointer is provided for all uids expected for this plan
+ std::vector<void *> device_ptrs;
+ device_ptrs.reserve(variant_pack_uids.size());
+ std::vector<uid_t> uids;
+ uids.reserve(variant_pack_uids.size());
+ for (auto const &uid : variant_pack_uids) {
+ auto search = uid_to_device_ptrs.find(uid);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(search == uid_to_device_ptrs.end(),
+ error_code_t::INVALID_VARIANT_PACK,
+ "Uid " + std::to_string(uid) + " does not exist in variant pack.");
+ device_ptrs.push_back(search->second);
+ uids.push_back(uid);
+ }
+
+ // Create the variant pack to pass to backend
+ detail::backend_descriptor variant_pack_descriptor(CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(variant_pack_descriptor.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create variant pack's backend descriptor.");
+
+ // offset workspace by the already used fe graph workspace
+ // this is where cudnn backend can start using workspace for its execution plans
+ void *cudnn_workspace = static_cast<char *>(workspace) + fe_workspace_size;
+ CHECK_CUDNN_FRONTEND_ERROR(create_variant_pack(variant_pack_descriptor, device_ptrs, uids, cudnn_workspace));
+
+ // Get the plan candidate. It only makes to sense to make cuda graph after execution plan has been built.
+ // And in that case the candidate would have been set.
+ int64_t candidate = plans.candidate;
+ CHECK_CUDNN_FRONTEND_ERROR(plans.is_plan_index_executable(candidate));
+
+ // Finally get the backend cuda graph.
+ cudaGraph_t backend_cuda_graph;
+ // Initialize the cudnn cuda graph.
+ // The responsibility to destroy is on the user.
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_create(&backend_cuda_graph, 0));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::populate_cuda_graph(handle,
+ plans.execution_plans[candidate]->get_raw_desc(),
+ variant_pack_descriptor.get_ptr(),
+ backend_cuda_graph));
+
+ // Clone BE graph into a graph_node
+ // This same call also places the newly created into FE's graph
+ // TODO: BE graph is at the end, so put in appropriate dependencies
+ cudaGraphNode_t backend_cuda_graph_node;
+ detail::cuda_graph_add_child_graph_node(
+ &backend_cuda_graph_node, cudnn_cuda_graph, &last_node, last_node != nullptr, backend_cuda_graph);
+
+ // Destroy the BE graph as it now has been cloned into a node
+ // It was initialized by internals of backend, but the responsibility to destroy it is on FE.
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_destroy(backend_cuda_graph));
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ validate() {
+ CUDNN_FE_LOG_BANNER(" VALIDATING GRAPH ");
+ CUDNN_FE_LOG(*this << std::endl;);
+
+ // First validate all inputs that the user set.
+ for (auto const &input : full_graph_inputs) {
+ CHECK_CUDNN_FRONTEND_ERROR(input->validate());
+ }
+
+ // Validate the nodes, which in turn also infers missing tensor attributes.
+ CHECK_CUDNN_FRONTEND_ERROR(validate_subtree());
+ // Validate all outputs, which should now have everything set to be lowered to backend.
+ for (auto const &output : full_graph_outputs) {
+ CHECK_CUDNN_FRONTEND_ERROR(output->validate());
+ }
+
+ // Get all the pre assigned uids
+ CHECK_CUDNN_FRONTEND_ERROR(get_pre_assigned_uids(used_uids));
+ // Clear state
+ used_uids.clear();
+
+ CUDNN_FE_LOG_BANNER(" VALIDATED ALL OK ");
+
+ return {error_code_t::OK, ""};
+ }
+
+ // overload for deviceless AoT compilation
+ error_t
+ build_operation_graph() {
+ CUDNN_FE_LOG_BANNER(" BUILD OP GRAPH WITHOUT HANDLE ");
+
+ if (device_properties == nullptr) {
+ return {error_code_t::ATTRIBUTE_NOT_SET, "Device properties are not set."};
+ }
+ CUDNN_FE_LOG_BANNER(" BUILT OP GRAPH WITHOUT HANDLE ");
+ return build_operation_graph(nullptr);
+ }
+
+ error_t
+ build_operation_graph(cudnnHandle_t handle) {
+ CUDNN_FE_LOG_BANNER(" BUILD OP GRAPH ");
+
+ CUDNN_FE_LOG_BANNER(" 1/4 INFER PROPERTIES OF NODES ");
+
+ // expand composite nodes
+ CHECK_CUDNN_FRONTEND_ERROR(expand_subtree());
+
+ // Get all the pre assigned uids
+ CHECK_CUDNN_FRONTEND_ERROR(get_pre_assigned_uids(used_uids));
+
+ CUDNN_FE_LOG_BANNER(" 2/4 CREATE TENSORS ");
+
+ Tensor_attributes::uid_t start_uid = 1;
+ CHECK_CUDNN_FRONTEND_ERROR(create_cudnn_tensors_subtree(uid_to_tensors, start_uid, used_uids));
+ tensors_to_dump.clear();
+ CHECK_CUDNN_FRONTEND_ERROR(collect_tensors_to_dump_subtree(tensors_to_dump));
+
+ CUDNN_FE_LOG_BANNER(" 3/4 CREATE OPERATIONS ");
+ // INode keeps track of all uids that an operation graph uses.
+ // This helps to return errors to user during execution, without relying on backend to do so.
+ // Also, as uid in a variant pack have to be unique, keep a set of them.
+ CHECK_CUDNN_FRONTEND_ERROR(
+ create_cudnn_operations(variant_pack_uids, operations, raw_operations, uid_to_tensors));
+
+ // Collect variant pack modifiers when lowering to backend.
+ // The collected map is used everytime when execute is called.
+ CHECK_CUDNN_FRONTEND_ERROR(collect_variant_pack_replacements_subtree(variant_pack_replacements));
+
+ fe_workspace_size = get_fe_workspace_size_subtree();
+
+ // Cache pass_by_value tensors and workspace modifications for fast execution.
+ // These are collected once here and reused in every execute() call to avoid
+ // repeated tree traversal and map allocation overhead.
+ CHECK_CUDNN_FRONTEND_ERROR(collect_pass_by_value_tensors_subtree(cached_pass_by_value));
+ {
+ int64_t temp_offset = 0;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ collect_tensors_in_workspace_subtree(cached_workspace_modifications, temp_offset));
+ }
+
+ CUDNN_FE_LOG_BANNER(" 4/4 LOWERING TO BACKEND OPERATION GRAPH ");
+
+ // The method here fuses all operations. There will be 1 operation graph in total.
+ CHECK_CUDNN_FRONTEND_ERROR(create_cudnn_operation_graph(handle));
+
+ if (context.get_dynamic_shape_enabled() && kernel_cache && !kernel_cache->is_finalized()) {
+ CUDNN_FE_LOG_BANNER(" BUILD KERNEL CACHE ");
+ CHECK_CUDNN_FRONTEND_ERROR(kernel_cache->build(operation_graph->get_raw_desc()));
+ }
+
+ CUDNN_FE_LOG_BANNER(" BUILD OP GRAPH ALL OK === ");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ get_plan_name(std::string &name) const {
+ return get_plan_name_at_index(plans.candidate, name);
+ }
+
+ error_t
+ get_plan_name_at_index(int64_t plan_index, std::string &name) const {
+ auto ret_val = plans.get_name_at_index(plan_index, name);
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: get_plan_name_at_index(" << plan_index << ") is " + name);
+ return ret_val;
+ }
+
+ // Structured counterpart of get_plan_name_at_index(): engine index + knob
+ // choices, for replay via create_execution_plan().
+ error_t
+ get_engine_and_knobs_at_index(int64_t plan_index,
+ int64_t &engine_id,
+ std::unordered_map<KnobType_t, int64_t> &knobs) const {
+ return plans.get_engine_and_knobs_at_index(plan_index, engine_id, knobs);
+ }
+
+ error_t
+ get_workspace_size(int64_t &cudnn_workspace_size) const {
+ return get_workspace_size_plan_at_index(plans.candidate, cudnn_workspace_size);
+ }
+
+ error_t
+ get_workspace_size(cudnnHandle_t handle,
+ int64_t &cudnn_workspace_size,
+ std::vector<int64_t> const &override_uids,
+ std::vector<std::vector<int64_t>> const &override_shapes,
+ std::vector<std::vector<int64_t>> const &override_strides) const {
+ return get_workspace_size_plan_at_index(
+ handle, plans.candidate, cudnn_workspace_size, override_uids, override_shapes, override_strides);
+ }
+
+ error_t
+ get_workspace_size_plan_at_index(int64_t plan_index, int64_t &cudnn_workspace_size) const {
+ // OSS SDPA engine workspace: 16 bytes for tile_id_counter
+ if (plan_index == graph::Execution_plan_list::OSS_SDPA_ENGINE_CANDIDATE) {
+ cudnn_workspace_size = fe_workspace_size + experimental::Sm90SdpaPrefillEngine::get_workspace_size();
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: get_workspace_size() is " << cudnn_workspace_size << " (OSS SDPA engine)");
+ return {error_code_t::OK, ""};
+ }
+
+ // OSS RmsNorm+SiLU engine workspace
+ if (plan_index == graph::Execution_plan_list::OSS_RMS_NORM_SILU_ENGINE_CANDIDATE) {
+ cudnn_workspace_size = fe_workspace_size + plans.get_oss_rms_norm_silu_workspace_size();
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: get_workspace_size() is " << cudnn_workspace_size
+ << " (OSS RmsNorm+SiLU engine)");
+ return {error_code_t::OK, ""};
+ }
+
+ // There are two workspaces:
+ // - cudnn execution plan workspace
+ // - FE node workspace (example: alibiSlope for fmha)
+ int64_t cudnn_ws = 0;
+ CHECK_CUDNN_FRONTEND_ERROR(get_cudnn_workspace_size_node(plan_index, cudnn_ws));
+ cudnn_workspace_size = cudnn_ws + fe_workspace_size;
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: get_workspace_size() is " << cudnn_workspace_size);
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ get_workspace_size_plan_at_index(cudnnHandle_t handle,
+ int64_t plan_index,
+ int64_t &cudnn_workspace_size,
+ std::vector<int64_t> const &override_uids,
+ std::vector<std::vector<int64_t>> const &override_shapes,
+ std::vector<std::vector<int64_t>> const &override_strides) const {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(override_uids.size() != override_shapes.size(),
+ error_code_t::INVALID_VALUE,
+ "override_uids and override_shapes must have the same size.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(override_uids.size() != override_strides.size(),
+ error_code_t::INVALID_VALUE,
+ "override_uids and override_strides must have the same size.");
+
+ if (override_uids.empty()) {
+ return get_workspace_size_plan_at_index(plan_index, cudnn_workspace_size);
+ }
+
+ // OSS engines are not backed by cuDNN execution plans, so their workspace stays frontend-owned.
+ if (plan_index == graph::Execution_plan_list::OSS_SDPA_ENGINE_CANDIDATE ||
+ plan_index == graph::Execution_plan_list::OSS_RMS_NORM_SILU_ENGINE_CANDIDATE) {
+ return get_workspace_size_plan_at_index(plan_index, cudnn_workspace_size);
+ }
+
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED,
+ "Runtime workspace query with override shapes requires cuDNN v9.23.0"};
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92300, cudnn_ver_error);
+
+#if (CUDNN_VERSION < 92300)
+ return cudnn_ver_error;
+#endif
+
+ CHECK_CUDNN_FRONTEND_ERROR(plans.is_plan_index_executable(plan_index));
+
+ detail::backend_descriptor variant_pack_descriptor(CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(variant_pack_descriptor.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create variant pack's backend descriptor.");
+
+#if (CUDNN_VERSION >= 92100)
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(variant_pack_descriptor.get_ptr(),
+ CUDNN_ATTR_VARIANT_PACK_OVERRIDE_UNIQUE_IDS,
+ CUDNN_TYPE_INT64,
+ override_uids.size(),
+ override_uids.data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(variant_pack_descriptor.get_ptr(),
+ CUDNN_ATTR_VARIANT_PACK_OVERRIDE_SHAPES,
+ CUDNN_TYPE_VOID_PTR,
+ 1,
+ (void *)&override_shapes));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(variant_pack_descriptor.get_ptr(),
+ CUDNN_ATTR_VARIANT_PACK_OVERRIDE_STRIDES,
+ CUDNN_TYPE_VOID_PTR,
+ 1,
+ (void *)&override_strides));
+#else
+ CUDNN_FRONTEND_UNUSED(override_uids);
+ CUDNN_FRONTEND_UNUSED(override_shapes);
+ CUDNN_FRONTEND_UNUSED(override_strides);
+#endif
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(variant_pack_descriptor.get_ptr()));
+
+ size_t cudnn_ws = 0;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_execution_plan_workspace_size(
+ handle, plans.execution_plans[plan_index]->get_raw_desc(), variant_pack_descriptor.get_ptr(), &cudnn_ws));
+ cudnn_workspace_size = cudnn_ws + fe_workspace_size;
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: get_workspace_size() is " << cudnn_workspace_size
+ << " (runtime override shape)");
+ return {error_code_t::OK, ""};
+ }
+
+ int64_t
+ get_workspace_size() const {
+ return get_workspace_size_plan_at_index(plans.candidate);
+ }
+
+ int64_t
+ get_workspace_size(cudnnHandle_t handle,
+ std::vector<int64_t> const &override_uids,
+ std::vector<std::vector<int64_t>> const &override_shapes,
+ std::vector<std::vector<int64_t>> const &override_strides) const {
+ int64_t cudnn_workspace = 0;
+ auto status = get_workspace_size(handle, cudnn_workspace, override_uids, override_shapes, override_strides);
+ if (status.is_bad()) {
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: Querying workspace failed.");
+ }
+ return cudnn_workspace;
+ }
+
+ int64_t
+ get_workspace_size_plan_at_index(int64_t plan_index) const {
+ int64_t cudnn_workspace = 0;
+ auto status = get_workspace_size_plan_at_index(plan_index, cudnn_workspace);
+ if (status.is_bad()) {
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: Querying workspace failed.");
+ }
+ return cudnn_workspace;
+ }
+
+ int64_t
+ get_workspace_size_plan_at_index(cudnnHandle_t handle,
+ int64_t plan_index,
+ std::vector<int64_t> const &override_uids,
+ std::vector<std::vector<int64_t>> const &override_shapes,
+ std::vector<std::vector<int64_t>> const &override_strides) const {
+ int64_t cudnn_workspace = 0;
+ auto status = get_workspace_size_plan_at_index(
+ handle, plan_index, cudnn_workspace, override_uids, override_shapes, override_strides);
+ if (status.is_bad()) {
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: Querying workspace failed.");
+ }
+ return cudnn_workspace;
+ }
+
+ int64_t
+ get_autotune_workspace_size() const {
+ // There are two workspaces:
+ // - cudnn execution plan workspace
+ // - FE node workspace (example: alibiSlope for fmha)
+ return fe_workspace_size + get_max_cudnn_workspace_size();
+ }
+
+ error_t
+ autotune(cudnnHandle_t handle,
+ std::unordered_map<int64_t, void *> &tensor_uid_to_pointer_map,
+ void *workspace,
+ void *user_impl = nullptr) {
+ (void)user_impl; // reserved for future use
+
+ const int maxIterCount = 100;
+ const float threshold = 0.95f;
+
+ auto plan_cmp = [](std::shared_ptr<ExecutionPlan> a, std::shared_ptr<ExecutionPlan> b) {
+ return a->getExecutionTime() < b->getExecutionTime();
+ };
+ std::multiset<std::shared_ptr<ExecutionPlan>, decltype(plan_cmp)> timed_plans(plan_cmp);
+
+ cudaEvent_t start, stop;
+ detail::cuda_event_create(&start);
+ detail::cuda_event_create(&stop);
+ detail::cuda_device_synchronize();
+
+ cudaStream_t stream = nullptr;
+ detail::get_stream(handle, &stream);
+
+ uint64_t successful_plan_count = 0;
+ for (int64_t i = 0; i < static_cast<int64_t>(plans.execution_plans.size()); i++) {
+ if (plans.execution_plans[i] == nullptr) continue;
+
+ // Warm-up run
+ auto warmup_status = execute_plan_at_index(handle, tensor_uid_to_pointer_map, workspace, i);
+ if (warmup_status.is_bad()) {
+ CUDNN_FE_LOG_LABEL_ENDL("WARN: Plan " << i << " failed warmup, skipping.");
+ continue;
+ }
+ successful_plan_count++;
+ detail::cuda_device_synchronize();
+
+ float min_time_ms = std::numeric_limits<float>::max();
+ for (int iter = 0; iter < maxIterCount; iter++) {
+ detail::cuda_event_record(start, stream);
+ auto iter_status = execute_plan_at_index(handle, tensor_uid_to_pointer_map, workspace, i);
+ detail::cuda_event_record(stop, stream);
+ detail::cuda_event_synchronize(stop);
+
+ if (iter_status.is_bad()) {
+ CUDNN_FE_LOG_LABEL_ENDL("WARN: Plan " << i << " failed at iter " << iter << ", skipping time.");
+ continue;
+ }
+
+ float time_ms = 0.0f;
+ detail::cuda_event_elapsed_time(&time_ms, start, stop);
+ float new_min = std::min(min_time_ms, time_ms);
+ if (time_ms / min_time_ms < threshold) {
+ min_time_ms = new_min;
+ } else {
+ break;
+ }
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL("Plan " << plans.execution_plans[i]->getTag() << " took " << std::setw(10)
+ << min_time_ms);
+ plans.execution_plans[i]->setExecutionTime(min_time_ms);
+ timed_plans.insert(plans.execution_plans[i]);
+ }
+
+ // Re-order plans by measured time, winner at index 0
+ plans.execution_plans.clear();
+ for (auto sorted_plan : timed_plans) {
+ plans.execution_plans.push_back(sorted_plan);
+ }
+ plans.candidate = 0;
+
+ // Re-prepare OSS slot indices to match the new plan ordering
+ apply_oss_slot_indices_to_plans();
+
+ detail::cuda_event_destroy(start);
+ detail::cuda_event_destroy(stop);
+
+ CUDNN_FE_LOG_LABEL_ENDL("Autotuned " << successful_plan_count << " plans.");
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ autotune(cudnnHandle_t handle,
+ std::unordered_map<std::shared_ptr<Tensor_attributes>, void *> &tensor_to_pointer_map,
+ void *workspace,
+ void *user_impl = nullptr) {
+ std::unordered_map<int64_t, void *> uid_map;
+ for (auto const &[tensor, pointer] : tensor_to_pointer_map) {
+ uid_map.emplace(tensor->get_uid(), pointer);
+ }
+ return autotune(handle, uid_map, workspace, user_impl);
+ }
+
+ // -----------------------------------------------------------------------
+ // Execute overloads.
+ // All roads lead to execute_plan_at_index(handle, sorted_ptrs, n, ws, plan_index).
+ // -----------------------------------------------------------------------
+
+ // --- Convenience wrappers: convert key types, use default plan index ---
+
+ error_t
+ execute(cudnnHandle_t handle,
+ std::unordered_map<std::shared_ptr<Tensor_attributes>, void *> &tensor_to_pointer_map,
+ void *workspace) const {
+ std::unordered_map<int64_t, void *> uid_map;
+ for (auto const &[tensor, pointer] : tensor_to_pointer_map) {
+ uid_map.emplace(tensor->get_uid(), pointer);
+ }
+ return execute(handle, uid_map, workspace);
+ }
+
+ error_t
+ execute(cudnnHandle_t handle,
+ std::unordered_map<int64_t, void *> &tensor_uid_to_pointer_map,
+ void *workspace) const {
+ return execute_plan_at_index(handle, tensor_uid_to_pointer_map, workspace, plans.candidate);
+ }
+
+ error_t
+ execute(cudnnHandle_t handle,
+ std::unordered_map<int64_t, void *> &tensor_uid_to_pointer_map,
+ void *workspace,
+ std::vector<int64_t> const &override_uids,
+ std::vector<std::vector<int64_t>> const &override_shapes,
+ std::vector<std::vector<int64_t>> const &override_strides) const {
+ return execute_plan_at_index(handle,
+ tensor_uid_to_pointer_map,
+ workspace,
+ plans.candidate,
+ override_uids,
+ override_shapes,
+ override_strides);
+ }
+
+ error_t
+ execute(cudnnHandle_t handle, void **sorted_user_ptrs, int n_user, void *workspace) const {
+ return execute_plan_at_index(handle, sorted_user_ptrs, n_user, workspace, plans.candidate);
+ }
+
+ // --- execute_plan_at_index: convert key types ---
+
+ error_t
+ execute_plan_at_index(cudnnHandle_t handle,
+ std::unordered_map<std::shared_ptr<Tensor_attributes>, void *> &tensor_to_pointer_map,
+ void *workspace,
+ int64_t plan_index) const {
+ std::unordered_map<int64_t, void *> uid_map;
+ for (auto const &[tensor, pointer] : tensor_to_pointer_map) {
+ uid_map.emplace(tensor->get_uid(), pointer);
+ }
+ return execute_plan_at_index(handle, uid_map, workspace, plan_index);
+ }
+
+ // uid map → extract sorted ptrs, delegate to the sorted_ptrs implementation
+ error_t
+ execute_plan_at_index(cudnnHandle_t handle,
+ std::unordered_map<int64_t, void *> &tensor_uid_to_pointer_map,
+ void *workspace,
+ int64_t plan_index,
+ std::vector<int64_t> const &override_uids = {},
+ std::vector<std::vector<int64_t>> const &override_shapes = {},
+ std::vector<std::vector<int64_t>> const &override_strides = {}) const {
+ if (!varpack_prep_state->prepared.load(std::memory_order_acquire)) {
+ CHECK_CUDNN_FRONTEND_ERROR(const_cast<Graph *>(this)->prepare_variant_pack_template());
+ }
+ const int n_user = (int)varpack_template.user_slots.size();
+ constexpr int STACK_MAX = 32;
+ void *stack_ptrs[STACK_MAX];
+ std::vector<void *> heap_ptrs;
+ void **user_ptrs = (n_user <= STACK_MAX) ? stack_ptrs : (heap_ptrs.resize(n_user), heap_ptrs.data());
+ for (int i = 0; i < n_user; i++) {
+ int64_t uid = varpack_template.all_uids[varpack_template.user_slots[i]];
+ auto it = tensor_uid_to_pointer_map.find(uid);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(it == tensor_uid_to_pointer_map.end(),
+ error_code_t::INVALID_VARIANT_PACK,
+ "Uid " + std::to_string(uid) + " not found in variant pack.");
+ user_ptrs[i] = it->second;
+ }
+ return execute_plan_at_index(
+ handle, user_ptrs, n_user, workspace, plan_index, override_uids, override_shapes, override_strides);
+ }
+
+ // --- THE implementation: sorted pointer array + plan index + optional overrides ---
+ // Thread-safe: copies the pre-built template to stack, patches user pointers, dispatches.
+ error_t
+ execute_plan_at_index(cudnnHandle_t handle,
+ void **sorted_user_ptrs,
+ int n_user,
+ void *workspace,
+ int64_t plan_index,
+ std::vector<int64_t> const &override_uids = {},
+ std::vector<std::vector<int64_t>> const &override_shapes = {},
+ std::vector<std::vector<int64_t>> const &override_strides = {}) const {
+ // Lazy init: prepare template if not done (e.g. deserialized graphs, build_plan_at_index)
+ if (!varpack_prep_state->prepared.load(std::memory_order_acquire)) {
+ CHECK_CUDNN_FRONTEND_ERROR(const_cast<Graph *>(this)->prepare_variant_pack_template());
+ }
+
+ CHECK_CUDNN_FRONTEND_ERROR(plans.is_plan_index_executable(plan_index));
+
+ // Validate n_user matches expected user slot count
+ RETURN_CUDNN_FRONTEND_ERROR_IF(n_user != static_cast<int>(varpack_template.user_slots.size()),
+ error_code_t::INVALID_VARIANT_PACK,
+ "n_user (" + std::to_string(n_user) +
+ ") does not match expected user slot count (" +
+ std::to_string(varpack_template.user_slots.size()) + ").");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ n_user > 0 && sorted_user_ptrs == nullptr, error_code_t::INVALID_VARIANT_PACK, "sorted_user_ptrs is null.");
+
+ // Thread-safe: copy template to local stack, then patch.
+ const int N = (int)varpack_template.all_uids.size();
+ constexpr int STACK_MAX = 32;
+ void *stack_ptrs[STACK_MAX];
+ std::vector<void *> heap_ptrs;
+ void **ptrs;
+ if (N <= STACK_MAX) {
+ std::memcpy(stack_ptrs, varpack_template.template_ptrs.data(), N * sizeof(void *));
+ ptrs = stack_ptrs;
+ } else {
+ heap_ptrs = varpack_template.template_ptrs;
+ ptrs = heap_ptrs.data();
+ }
+
+ // 1. Patch user pointers
+ for (int i = 0; i < n_user; i++) {
+ ptrs[varpack_template.user_slots[i]] = sorted_user_ptrs[i];
+ }
+
+ // 2. Update workspace-relative pointers (pre-computed slot indices)
+ for (auto const &[slot, offset] : varpack_template.workspace_slots) {
+ ptrs[slot] = static_cast<char *>(workspace) + offset;
+ }
+
+ // 3. Re-apply replacements (currently only Slice nodes)
+ for (auto const &[dst_slot, src_info] : varpack_template.replacement_slots) {
+ ptrs[dst_slot] = static_cast<char *>(ptrs[src_info.first]) + src_info.second;
+ }
+
+ // 4. Run auxiliary kernels (e.g. SDPA reduction accumulator init)
+ CHECK_CUDNN_FRONTEND_ERROR(run_auxiliary_kernels(handle, workspace, cached_workspace_modifications));
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executing graph_uid " << graph_uid);
+
+ // 5. Dispatch
+ void *engine_workspace = static_cast<char *>(workspace) + fe_workspace_size;
+
+ if (plan_index == graph::Execution_plan_list::OSS_SDPA_ENGINE_CANDIDATE) {
+ cudaStream_t stream = nullptr;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_stream(handle, &stream));
+ int device_ordinal = 0;
+ detail::cuda_get_device(&device_ordinal);
+ if (override_uids.empty()) {
+ CHECK_CUDNN_FRONTEND_ERROR(
+ plans.execute_oss_sdpa_engine(ptrs, engine_workspace, device_ordinal, stream));
+ } else {
+ CHECK_CUDNN_FRONTEND_ERROR(plans.execute_oss_sdpa_engine(
+ ptrs, engine_workspace, device_ordinal, stream, override_uids, override_shapes, override_strides));
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ if (plan_index == graph::Execution_plan_list::OSS_RMS_NORM_SILU_ENGINE_CANDIDATE) {
+ cudaStream_t stream = nullptr;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_stream(handle, &stream));
+ int device_ordinal = 0;
+ detail::cuda_get_device(&device_ordinal);
+ CHECK_CUDNN_FRONTEND_ERROR(
+ plans.execute_oss_rms_norm_silu_engine(ptrs, engine_workspace, device_ordinal, stream));
+ return {error_code_t::OK, ""};
+ }
+
+ // Backend path
+ if (override_uids.empty()) {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::execute(
+ handle, plans.execution_plans[plan_index].get(), ptrs, varpack_template.all_uids, engine_workspace));
+ } else {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::execute(handle,
+ plans.execution_plans[plan_index].get(),
+ ptrs,
+ varpack_template.all_uids,
+ engine_workspace,
+ override_uids,
+ override_shapes,
+ override_strides));
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ warmup(cudnnHandle_t handle) {
+ cudaStream_t fake_stream;
+
+ cudaStream_t original_stream;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_stream(handle, &original_stream));
+
+ CUDNN_FE_LOG_BANNER("WARMUP (BEGIN FAKE GRAPH CAPTURE) ");
+
+ if (original_stream == nullptr) {
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_stream_create(&fake_stream));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_stream(handle, fake_stream));
+ } else {
+ fake_stream = original_stream;
+ }
+
+ cudaGraph_t graph_obj;
+
+ cudaStreamCaptureStatus capture_status;
+
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_stream_is_capturing(fake_stream, &capture_status));
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: capture_status "
+ << capture_status << " original_stream "
+ << ((original_stream == nullptr) ? "DEFAULT (NULL) Stream" : "NON-DEFAULT Stream"));
+
+ if (capture_status != cudaStreamCaptureStatusNone) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: cuda graph capture active, aborting warmup");
+ return {error_code_t::OK, "cuda graph capture active, aborting warmup"};
+ }
+
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_begin_capture(fake_stream, cudaStreamCaptureModeRelaxed));
+
+ std::unordered_map<int64_t, void *> tensor_uid_to_pointer_map;
+
+ void *tmp_pointer = reinterpret_cast<void *>(0x7f0000000000llu);
+
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_malloc((void **)&tmp_pointer, 1024 * 1024));
+
+ float tmp_double = 1.0f;
+ void *cpu_pointer = reinterpret_cast<void *>(&tmp_double);
+
+ for (auto const &tensor : deserialized_tensor_properties) {
+ if (tensor->get_is_virtual() == false) {
+ if (tensor->get_is_pass_by_value() == false) {
+ tensor_uid_to_pointer_map.emplace(tensor->get_uid(), tmp_pointer);
+ } else {
+ tensor_uid_to_pointer_map.emplace(tensor->get_uid(), cpu_pointer);
+ }
+ }
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: full_graph_inputs: " << full_graph_inputs.size() << " elements");
+ for (auto const &tensor : full_graph_inputs) {
+ CUDNN_FE_LOG_LABEL_ENDL("\tuid: " << tensor->get_uid()
+ << ", is_pass_by_value = " << tensor->get_is_pass_by_value());
+ if (tensor->get_is_pass_by_value() == false) {
+ tensor_uid_to_pointer_map.emplace(tensor->get_uid(), tmp_pointer);
+ } else {
+ tensor_uid_to_pointer_map.emplace(tensor->get_uid(), cpu_pointer);
+ }
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: full_graph_outputs: " << full_graph_outputs.size() << " elements");
+ for (auto const &tensor : full_graph_outputs) {
+ CUDNN_FE_LOG_LABEL_ENDL("\tuid: " << tensor->get_uid());
+ tensor_uid_to_pointer_map.emplace(tensor->get_uid(), tmp_pointer);
+ }
+
+ CHECK_CUDNN_FRONTEND_ERROR(
+ extend_tensor_map_with_pass_by_value_tensors_(tensor_uid_to_pointer_map, deserialized_pass_by_value));
+
+ auto cudnn_status = execute(handle, tensor_uid_to_pointer_map, tmp_pointer);
+ (void)cudnn_status; // No need to check bad executes
+
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_end_capture(fake_stream, &graph_obj));
+
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_graph_destroy(graph_obj));
+
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_free(tmp_pointer));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_stream(handle, original_stream));
+
+ if (original_stream == nullptr) {
+ _CUDNN_CHECK_CUDA_ERROR(detail::cuda_stream_destroy(fake_stream));
+ }
+
+ CUDNN_FE_LOG_BANNER("WARMUP (END FAKE GRAPH CAPTURE) ");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ serialize(std::vector<uint8_t> &data) const {
+ CUDNN_FE_LOG_BANNER(" SERIALIZE PLAN ");
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ json j;
+ serialize(j);
+
+ auto const candidate = plans.candidate;
+ auto execution_plan = plans.execution_plans[candidate];
+ if (execution_plan != nullptr) {
+ auto serialized_plan = execution_plan->getJsonRepresentation();
+ j["cudnn_backend_data"] = serialized_plan;
+ j["variant_pack_uids"] = variant_pack_uids;
+ }
+
+ j["behavior_notes"] = plans.behavior_notes;
+
+ std::unordered_map<uid_t, pass_by_values_t> tensor_to_pass_by_value;
+ CHECK_CUDNN_FRONTEND_ERROR(collect_pass_by_value_tensors_subtree(tensor_to_pass_by_value));
+
+ // Convert pass_by_values to JSON (unordered_map with numeric keys needs manual conversion)
+ json pass_by_values_json = json::object();
+ for (const auto &[uid, variant_value] : tensor_to_pass_by_value) {
+ json variant_json;
+ variant_json = variant_value;
+ pass_by_values_json[std::to_string(uid)] = variant_json;
+ }
+ j["pass_by_values"] = pass_by_values_json;
+
+ std::unordered_map<uid_t, std::tuple<int64_t, int64_t, std::vector<float>>> workspace_modifications;
+ int64_t workspace_offset = 0;
+ CHECK_CUDNN_FRONTEND_ERROR(collect_tensors_in_workspace_subtree(workspace_modifications, workspace_offset));
+
+ // Convert workspace_modifications to JSON (nlohmann::json doesn't support std::tuple directly)
+ json workspace_modifications_json = json::object();
+ for (const auto &[uid, tuple_value] : workspace_modifications) {
+ json tuple_json = json::array();
+ tuple_json.push_back(std::get<0>(tuple_value));
+ tuple_json.push_back(std::get<1>(tuple_value));
+ tuple_json.push_back(std::get<2>(tuple_value));
+ workspace_modifications_json[std::to_string(uid)] = tuple_json;
+ }
+ j["workspace_modifications"] = workspace_modifications_json;
+
+ j["variant_pack_replacements"] = variant_pack_replacements;
+
+ j["fe_workspace_size"] = fe_workspace_size;
+
+ std::vector<std::pair<uid_t, char>> tensors_to_dump_uids;
+ for (auto const &[tensor, fmt] : tensors_to_dump) {
+ tensors_to_dump_uids.emplace_back(tensor->get_uid(), fmt);
+ }
+ j["tensors_to_dump"] = tensors_to_dump_uids;
+
+ data = json::to_ubjson(j);
+ CUDNN_FE_LOG_BANNER(" SERIALIZE PLAN (ALL OK) ");
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(data);
+ return {error_code_t::GRAPH_NOT_SUPPORTED, "unavailable when compiled with CUDNN_FRONTEND_SKIP_JSON_LIB"};
+#endif
+ }
+
+ /**
+ * @brief Deserialize an execution plan from a serialized byte blob.
+ *
+ * Parses @p data with from_ubjson and delegates to the json overload. Callers that
+ * have already parsed the blob should call the json overload directly to avoid a
+ * second parse.
+ *
+ * @param handle cuDNN handle used to rebuild the execution plan.
+ * @param data UBJSON blob previously produced by serialize().
+ * @param enforce_precompiled When true, fail unless the blob carries a precompiled plan.
+ * @param run_warmup When false, skip the throwaway warmup capture.
+ * @return error_t OK on success, otherwise an error code describing the failure.
+ */
+ error_t
+ deserialize(cudnnHandle_t handle,
+ std::vector<uint8_t> const &data,
+ bool const enforce_precompiled = false,
+ bool run_warmup = true) {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ return deserialize(handle, json::from_ubjson(data), enforce_precompiled, run_warmup);
+#else
+ CUDNN_FRONTEND_UNUSED(handle);
+ CUDNN_FRONTEND_UNUSED(data);
+ CUDNN_FRONTEND_UNUSED(enforce_precompiled);
+ CUDNN_FRONTEND_UNUSED(run_warmup);
+ return {error_code_t::GRAPH_NOT_SUPPORTED, "unavailable when compiled with CUDNN_FRONTEND_SKIP_JSON_LIB"};
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ /**
+ * @brief Deserialize an execution plan from an already-parsed json.
+ *
+ * Avoids a second from_ubjson parse. run_warmup=false skips the throwaway warmup capture.
+ *
+ * @param handle cuDNN handle used to rebuild the execution plan.
+ * @param j Parsed json graph, as produced by serialize().
+ * @param enforce_precompiled When true, fail unless the json carries a precompiled plan.
+ * @param run_warmup When false, skip the throwaway warmup capture.
+ * @return error_t OK on success, otherwise an error code describing the failure.
+ */
+ error_t
+ deserialize(cudnnHandle_t handle, json const &j, bool const enforce_precompiled = false, bool run_warmup = true) {
+ CUDNN_FE_LOG_BANNER(" DESERIALIZE PLAN WITH HANDLE ");
+
+ // Clear deserialize-owned containers so a re-deserialize on the same Graph
+ // does not feed prepare_variant_pack_template() with stale entries from a
+ // prior deserialize(handle, old_data).
+ deserialized_tensor_properties.clear();
+ deserialized_pass_by_value.clear();
+ deserialized_workspace_modifications.clear();
+ tensors_to_dump.clear();
+
+ if (j.contains("graph_uid") && !j["graph_uid"].is_null()) {
+ graph_uid = j["graph_uid"].get<uint64_t>();
+ }
+
+ // Resolve tensor UIDs with deserialized_tensor_properties.
+ if (j.contains("tensors")) {
+ auto tensor_map = j["tensors"].get<std::unordered_map<std::string, json>>();
+ for (const auto &tensor_info : tensor_map) {
+ auto tensor_attributes = std::make_shared<Tensor_attributes>();
+ from_json(tensor_info.second, *tensor_attributes);
+ deserialized_tensor_properties.insert(tensor_attributes);
+ }
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ enforce_precompiled && !j.contains("cudnn_backend_data"),
+ error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "enforce_precompiled requested, but serialized graph has no precompiled execution plan");
+
+ auto serialized_plan = j["cudnn_backend_data"];
+ CHECK_CUDNN_FRONTEND_ERROR(plans.build_plans(handle, serialized_plan));
+
+ plans.behavior_notes = j["behavior_notes"].get<std::vector<std::vector<BehaviorNote_t>>>();
+
+ variant_pack_uids = j["variant_pack_uids"].get<std::unordered_set<graph::Tensor_attributes::uid_t>>();
+
+ // Deserialize pass_by_values from JSON
+ if (j.contains("pass_by_values")) {
+ auto pass_by_values_json = j["pass_by_values"];
+ for (auto it = pass_by_values_json.begin(); it != pass_by_values_json.end(); ++it) {
+ uid_t uid = std::stoll(it.key());
+ pass_by_values_t value = it.value().get<pass_by_values_t>();
+ deserialized_pass_by_value[uid] = value;
+ }
+ }
+
+ // Deserialize workspace_modifications from JSON
+ if (j.contains("workspace_modifications")) {
+ auto workspace_modifications_json = j["workspace_modifications"];
+ for (auto it = workspace_modifications_json.begin(); it != workspace_modifications_json.end(); ++it) {
+ uid_t uid = std::stoll(it.key());
+ auto tuple_json = it.value();
+ auto tuple_value = std::make_tuple(tuple_json[0].get<int64_t>(),
+ tuple_json[1].get<int64_t>(),
+ tuple_json[2].get<std::vector<float>>());
+ deserialized_workspace_modifications[uid] = tuple_value;
+ }
+ }
+
+ variant_pack_replacements = j["variant_pack_replacements"];
+
+ fe_workspace_size = j["fe_workspace_size"];
+
+ // Initialize the execution caches from deserialized data
+ cached_pass_by_value = deserialized_pass_by_value;
+ cached_workspace_modifications = deserialized_workspace_modifications;
+
+ // Reset prep state in case this Graph is being re-deserialized; otherwise the
+ // eager prep below would early-return with the old slot layout.
+ varpack_prep_state->prepared.store(false, std::memory_order_release);
+ varpack_template = {};
+
+ // Eager prep, matching what build_plans() does for fresh-build graphs.
+ CHECK_CUDNN_FRONTEND_ERROR(prepare_variant_pack_template());
+
+ if (j.contains("tensors_to_dump")) {
+ auto dump_uids = j["tensors_to_dump"].get<std::vector<std::pair<uid_t, char>>>();
+ for (auto const &[uid, fmt] : dump_uids) {
+ for (auto const &tensor : deserialized_tensor_properties) {
+ if (tensor->get_uid() == uid) {
+ tensors_to_dump.emplace_back(tensor, fmt);
+ break;
+ }
+ }
+ }
+ }
+
+ if (run_warmup) {
+ CHECK_CUDNN_FRONTEND_ERROR(warmup(handle));
+ }
+
+ CUDNN_FE_LOG_BANNER(" DESERIALIZE PLAN WITH HANDLE (ALL OK) ");
+
+ return {error_code_t::OK, ""};
+ }
+#endif
+
+ Type
+ getType() override {
+ return Type::COMPOSITE;
+ }
+
+ Graph &
+ set_intermediate_data_type(DataType_t type);
+ Graph &
+ set_io_data_type(DataType_t type);
+ Graph &
+ set_compute_data_type(DataType_t type);
+ Graph &
+ set_dynamic_shape_enabled(bool is_enabled);
+ Graph &
+ set_override_shape_enabled(bool is_enabled);
+ Graph &
+ set_sm_count(int32_t type);
+ Graph &
+ set_sm_version(int32_t version);
+ Graph &
+ set_kernel_cache(std::shared_ptr<KernelCache> cache);
+ Graph &
+ set_device_properties(std::shared_ptr<const DeviceProperties> device_prop);
+
+ Graph &
+ set_name(std::string const &name) {
+ context.set_name(name);
+ return *this;
+ }
+
+ error_t
+ query_tensor_attributes_of_uid(int64_t const uid, Tensor_attributes &tensor) const;
+
+ std::shared_ptr<Tensor_attributes>
+ tensor(Tensor_attributes const &tensor);
+
+ // Overloaded tensor() methods for compile-time constants
+ std::shared_ptr<Tensor_attributes>
+ tensor(float const &scalar, ScalarType scalar_type);
+
+ std::shared_ptr<Tensor_attributes>
+ tensor(half const &scalar, ScalarType scalar_type);
+
+ std::shared_ptr<Tensor_attributes>
+ tensor(nv_bfloat16 const &scalar, ScalarType scalar_type);
+
+ std::shared_ptr<Tensor_attributes>
+ tensor(int32_t const &scalar, ScalarType scalar_type);
+
+ std::shared_ptr<Tensor_attributes>
+ tensor(int64_t const &scalar, ScalarType scalar_type);
+
+ std::shared_ptr<Tensor_attributes>
+ tensor(double const &scalar, ScalarType scalar_type);
+
+ std::shared_ptr<Tensor_attributes>
+ tensor_like(std::shared_ptr<Tensor_attributes> const &tensor, std::string const &name = std::string{});
+
+ std::array<std::shared_ptr<Tensor_attributes>, 3> layernorm(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Layernorm_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 3> adalayernorm(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ AdaLayernorm_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 3> instancenorm(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Instancenorm_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 5> batchnorm(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Batchnorm_attributes);
+
+ std::shared_ptr<Tensor_attributes> batchnorm_inference(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Batchnorm_inference_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 6> bn_finalize(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ BN_finalize_attributes);
+
+ std::shared_ptr<Tensor_attributes> conv_fprop(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Conv_fprop_attributes);
+
+ std::shared_ptr<Tensor_attributes> conv_dgrad(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Conv_dgrad_attributes);
+
+ std::shared_ptr<Tensor_attributes> conv_wgrad(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Conv_wgrad_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 5> dbn_weight(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ DBN_weight_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 3> batchnorm_backward(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Batchnorm_backward_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 3> layernorm_backward(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Layernorm_backward_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 3> adalayernorm_backward(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ AdaLayernorm_backward_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 3> instancenorm_backward(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Instancenorm_backward_attributes);
+ std::array<std::shared_ptr<Tensor_attributes>, 2> genstats(std::shared_ptr<Tensor_attributes>, Genstats_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 2> rmsnorm(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Rmsnorm_attributes);
+
+ std::shared_ptr<Tensor_attributes> rope(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ RoPE_attributes);
+
+ std::shared_ptr<Tensor_attributes> rope_backward(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ RoPE_backward_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 3> rmsnorm_backward(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Rmsnorm_backward_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 2> sdpa(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ SDPA_attributes);
+
+ // FP8 version
+ std::array<std::shared_ptr<Tensor_attributes>, 4> sdpa_fp8(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ SDPA_fp8_attributes);
+
+ // MXFP8 version
+ std::array<std::shared_ptr<Tensor_attributes>, 3> sdpa_fp8(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ SDPA_fp8_attributes);
+
+ inline std::array<std::shared_ptr<Tensor_attributes>, 7> sdpa_fp8_backward(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ SDPA_fp8_backward_attributes);
+
+ // MXFP8 version
+ std::array<std::shared_ptr<Tensor_attributes>, 6> sdpa_fp8_backward(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ SDPA_fp8_backward_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 3> sdpa_backward(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ SDPA_backward_attributes);
+
+ std::shared_ptr<Tensor_attributes> slice(std::shared_ptr<Tensor_attributes>, Slice_attributes);
+
+ std::shared_ptr<Tensor_attributes> transpose(std::shared_ptr<Tensor_attributes>, Transpose_attributes);
+
+ std::array<std::shared_ptr<Tensor_attributes>, 2> block_scale_quantize(std::shared_ptr<Tensor_attributes>,
+ Block_scale_quantize_attributes);
+
+ std::shared_ptr<Tensor_attributes> block_scale_dequantize(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Block_scale_dequantize_attributes);
+
+ std::shared_ptr<Tensor_attributes> concatenate(std::vector<std::shared_ptr<Tensor_attributes>>,
+ Concatenate_attributes);
+
+ std::shared_ptr<Tensor_attributes> moe_grouped_matmul(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Moe_grouped_matmul_attributes);
+
+ std::shared_ptr<Tensor_attributes> moe_grouped_matmul_bwd(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Moe_grouped_matmul_bwd_attributes);
+
+ [[deprecated]] std::array<std::shared_ptr<Tensor_attributes>, 2>
+ scaled_dot_product_flash_attention(std::shared_ptr<Tensor_attributes> q,
+ std::shared_ptr<Tensor_attributes> k,
+ std::shared_ptr<Tensor_attributes> v,
+ SDPA_attributes attributes) {
+ return sdpa(q, k, v, attributes);
+ }
+ [[deprecated]] std::array<std::shared_ptr<Tensor_attributes>, 3>
+ scaled_dot_product_flash_attention_backward(std::shared_ptr<Tensor_attributes> q,
+ std::shared_ptr<Tensor_attributes> k,
+ std::shared_ptr<Tensor_attributes> v,
+ std::shared_ptr<Tensor_attributes> o,
+ std::shared_ptr<Tensor_attributes> dO,
+ std::shared_ptr<Tensor_attributes> stats,
+ SDPA_backward_attributes attributes) {
+ return sdpa_backward(q, k, v, o, dO, stats, attributes);
+ }
+
+ error_t
+ create_execution_plans(std::vector<HeurMode_t> const &mode);
+
+ error_t
+ create_execution_plan(int64_t const engine_id, std::unordered_map<KnobType_t, int64_t> const &knobs);
+
+ int64_t
+ get_execution_plan_count() const;
+
+ inline error_t
+ get_engine_count(int64_t &count);
+
+ inline error_t
+ get_knobs_for_engine(int64_t const engine, std::vector<Knob> &);
+
+ error_t
+ check_support(cudnnHandle_t h) {
+ // handle not required anymore
+ // TODO: remove this function in next release
+ (void)h;
+ return check_support();
+ }
+
+ // overload for deviceless AoT compilation
+ error_t
+ check_support() {
+ // Check OSS engine first if registered
+
+ CHECK_CUDNN_FRONTEND_ERROR(context.populate_sm_version_from_device());
+ auto sm_version = context.get_sm_version();
+
+ // Check OSS SDPA engine
+ if (plans.has_oss_sdpa_engine()) {
+ auto oss_status = plans.check_oss_sdpa_engine_support(sm_version);
+ if (oss_status.is_good()) {
+ return {error_code_t::OK, ""};
+ }
+ // Fall through to check other engines
+ }
+
+ // Check OSS RmsNorm+SiLU engine
+ if (plans.has_oss_rms_norm_silu_engine()) {
+ auto oss_status = plans.check_oss_rms_norm_silu_support(sm_version);
+ if (oss_status.is_good()) {
+ return {error_code_t::OK, ""};
+ }
+ // Fall through to check cuDNN plans
+ }
+
+ CHECK_CUDNN_FRONTEND_ERROR(plans.check_support());
+ return {error_code_t::OK, ""};
+ }
+
+ // TODO: remove this function in next release
+ error_t
+ build(cudnnHandle_t const &handle,
+ std::vector<HeurMode_t> const &mode,
+ BuildPlanPolicy_t const policy = BuildPlanPolicy_t::HEURISTICS_CHOICE,
+ bool const do_multithreaded_builds = false);
+
+ // overload for deviceless AoT compilation
+ error_t
+ build(std::vector<HeurMode_t> const &mode,
+ BuildPlanPolicy_t const policy = BuildPlanPolicy_t::HEURISTICS_CHOICE,
+ bool const do_multithreaded_builds = false);
+
+ // -----------------------------------------------------------------------
+ // Variant pack template: pre-indexed flat array built at build_plans() time.
+ // Eliminates per-call map operations in execute().
+ // -----------------------------------------------------------------------
+
+ struct VariantPackTemplate {
+ std::vector<int64_t> all_uids; // all UIDs in sorted order (user + internal)
+ std::vector<void *> template_ptrs; // pre-filled: pass_by_value entries, nullptr for user/workspace slots
+ std::vector<int> user_slots; // indices into template_ptrs that the user fills (sorted UID order)
+
+ // Pre-computed slot indices for per-call updates (avoid linear scans at execute time)
+ std::vector<std::pair<int, int64_t>> workspace_slots; // (slot, byte_offset)
+ std::vector<std::pair<int, std::pair<int, int64_t>>>
+ replacement_slots; // (dst_slot, (src_slot, offset)) — only used by Slice nodes
+ };
+
+ VariantPackTemplate varpack_template;
+
+ // Per-Graph sync state for lazy varpack-template prep. Wrapped in a box so
+ // Graph stays default-copy/move-constructible (samples build Graphs into
+ // std::tuple by copy).
+ struct VarpackPrepState {
+ std::atomic<bool> prepared{false};
+ std::mutex mu;
+ };
+ struct VarpackPrepStateBox {
+ std::unique_ptr<VarpackPrepState> ptr = std::make_unique<VarpackPrepState>();
+ VarpackPrepStateBox() = default;
+ VarpackPrepStateBox(VarpackPrepStateBox &&) noexcept = default;
+ VarpackPrepStateBox &
+ operator=(VarpackPrepStateBox &&) noexcept = default;
+ // Copy semantics: never copy the prepared flag. The cached template_ptrs
+ // store raw addresses into the source Graph's pass-by-value storage; a
+ // copied Graph must rebuild its own template on first use.
+ VarpackPrepStateBox(VarpackPrepStateBox const & /*other*/) : ptr(std::make_unique<VarpackPrepState>()) {}
+ VarpackPrepStateBox &
+ operator=(VarpackPrepStateBox const &other) {
+ if (this != &other) {
+ ptr = std::make_unique<VarpackPrepState>();
+ }
+ return *this;
+ }
+ VarpackPrepState *
+ operator->() const {
+ return ptr.get();
+ }
+ };
+ mutable VarpackPrepStateBox varpack_prep_state;
+
+ // Prepares the variant pack template. Called automatically at the end of build_plans().
+ error_t
+ prepare_variant_pack_template() {
+ std::lock_guard<std::mutex> lk(varpack_prep_state->mu);
+ if (varpack_prep_state->prepared.load(std::memory_order_relaxed)) {
+ return {error_code_t::OK, ""};
+ }
+
+ VariantPackTemplate t;
+
+ // 1. Start with variant_pack_uids + any replacement source UIDs not already included.
+ // Replacement sources (e.g. slice input on cuDNN < 9.22 pointer-arithmetic fallback) may not
+ // be in variant_pack_uids; we still need a slot for the source pointer when replacements apply.
+ t.all_uids.assign(variant_pack_uids.begin(), variant_pack_uids.end());
+ for (auto const &[from_uid, value] : variant_pack_replacements) {
+ if (variant_pack_uids.find(from_uid) == variant_pack_uids.end()) {
+ t.all_uids.push_back(from_uid);
+ }
+ }
+ std::sort(t.all_uids.begin(), t.all_uids.end());
+ t.template_ptrs.assign(t.all_uids.size(), nullptr);
+
+ // 2. Build UID → slot index
+ std::unordered_map<int64_t, int> uid_to_slot;
+ for (int i = 0; i < (int)t.all_uids.size(); i++) {
+ uid_to_slot[t.all_uids[i]] = i;
+ }
+
+ // 3. Pre-fill pass_by_value entries (scalars like epsilon, alpha, beta)
+ std::unordered_map<int64_t, void *> pbv_ptrs;
+ CHECK_CUDNN_FRONTEND_ERROR(extend_tensor_map_with_pass_by_value_tensors_(pbv_ptrs, cached_pass_by_value));
+ for (auto const &[uid, ptr] : pbv_ptrs) {
+ auto it = uid_to_slot.find(uid);
+ if (it != uid_to_slot.end()) {
+ t.template_ptrs[it->second] = ptr;
+ } else {
+ int slot = (int)t.all_uids.size();
+ t.all_uids.push_back(uid);
+ t.template_ptrs.push_back(ptr);
+ uid_to_slot[uid] = slot;
+ }
+ }
+
+ // 4. Register workspace entries (slots allocated, pointers filled at execute time)
+ for (auto const &[uid, data] : cached_workspace_modifications) {
+ auto it = uid_to_slot.find(uid);
+ if (it == uid_to_slot.end()) {
+ int slot = (int)t.all_uids.size();
+ t.all_uids.push_back(uid);
+ t.template_ptrs.push_back(nullptr); // filled at execute time
+ uid_to_slot[uid] = slot;
+ }
+ }
+
+ // 5. Identify user-fillable slots: nullptr entries that are NOT workspace/replacement targets
+ std::unordered_set<int64_t> workspace_uids;
+ for (auto const &[uid, data] : cached_workspace_modifications) {
+ workspace_uids.insert(uid);
+ }
+ std::unordered_set<int64_t> replacement_dst_uids;
+ for (auto const &[from_uid, value] : variant_pack_replacements) {
+ (void)from_uid;
+ replacement_dst_uids.insert(value.first); // value.first = to_uid (the destination)
+ }
+ for (int i = 0; i < (int)t.template_ptrs.size(); i++) {
+ int64_t uid = t.all_uids[i];
+ if (t.template_ptrs[i] == nullptr && workspace_uids.find(uid) == workspace_uids.end() &&
+ replacement_dst_uids.find(uid) == replacement_dst_uids.end()) {
+ t.user_slots.push_back(i);
+ }
+ }
+
+ // 6. Pre-compute workspace slot indices
+ for (auto const &[uid, data] : cached_workspace_modifications) {
+ const auto &[operation_type, offset, vec_data] = data;
+ auto it = uid_to_slot.find(uid);
+ if (it != uid_to_slot.end()) {
+ t.workspace_slots.emplace_back(it->second, offset);
+ }
+ }
+
+ // 7. Pre-compute replacement slot indices
+ // variant_pack_replacements: key = from_uid (source), value = {to_uid (destination), byte_offset}
+ // Meaning: ptr[to_uid] = ptr[from_uid] + byte_offset (e.g. legacy slice fallback on cuDNN < 9.22)
+ for (auto const &[from_uid, value] : variant_pack_replacements) {
+ const auto &[to_uid, byte_offset] = value;
+ auto it_src = uid_to_slot.find(from_uid);
+ auto it_dst = uid_to_slot.find(to_uid);
+ // Replacement: dst_ptr = src_ptr + byte_offset
+ if (it_src != uid_to_slot.end() && it_dst != uid_to_slot.end()) {
+ t.replacement_slots.emplace_back(it_dst->second, std::make_pair(it_src->second, byte_offset));
+ }
+ }
+
+ varpack_template = std::move(t);
+ // Apply OSS slot indices before the release-store so a reader that
+ // observes prepared=true also sees the slot writes.
+ apply_oss_slot_indices_to_plans();
+ varpack_prep_state->prepared.store(true, std::memory_order_release);
+
+ return {error_code_t::OK, ""};
+ }
+
+ // Depends on plans.candidate; kept separate so autotune can re-apply without
+ // rebuilding the (candidate-independent) variant pack template.
+ void
+ apply_oss_slot_indices_to_plans() {
+ plans.set_oss_slot_indices([this](int64_t uid) -> int {
+ if (uid < 0) return -1;
+ for (size_t i = 0; i < varpack_template.all_uids.size(); ++i) {
+ if (varpack_template.all_uids[i] == uid) return static_cast<int>(i);
+ }
+ return -1;
+ });
+ }
+
+ std::vector<int64_t>
+ get_variant_pack_uids_sorted() const {
+ std::vector<int64_t> user_uids;
+ for (int slot : varpack_template.user_slots) {
+ user_uids.push_back(varpack_template.all_uids[slot]);
+ }
+ return user_uids;
+ }
+
+ error_t
+ build_plans(cudnnHandle_t const &handle,
+ BuildPlanPolicy_t const policy = BuildPlanPolicy_t::HEURISTICS_CHOICE,
+ bool const do_multithreaded_builds = false) {
+ // handle not required anymore
+ // TODO: remove this function in next release
+ (void)handle;
+ return build_plans(policy, do_multithreaded_builds);
+ }
+
+ // overload for deviceless AoT compilation
+ error_t
+ build_plans(BuildPlanPolicy_t const policy = BuildPlanPolicy_t::HEURISTICS_CHOICE,
+ bool const do_multithreaded_builds = false);
+
+ error_t
+ build_plan_at_index(cudnnHandle_t const &handle, int64_t index) {
+ // handle not required anymore
+ // TODO: remove this function in next release
+ (void)handle;
+ return build_plan_at_index(index);
+ }
+
+ // overload for deviceless AoT compilation
+ error_t
+ build_plan_at_index(int64_t index);
+
+ Graph &
+ deselect_workspace_greater_than(int64_t const workspace) {
+ plans.set_max_workspace_allowed(workspace);
+ return *this;
+ }
+
+ Graph &
+ deselect_shared_mem_greater_than(int64_t const workspace) {
+ plans.set_max_shared_mem_allowed(workspace);
+ return *this;
+ }
+
+ Graph &
+ deselect_engines(std::vector<std::string> const &engine_names) {
+ plans.set_barred_names(engine_names);
+ return *this;
+ }
+
+ Graph &
+ select_behavior_notes(std::vector<BehaviorNote_t> const &notes) {
+ auto status = plans.filter_behavior_notes(notes, true);
+ if (status.is_bad()) {
+ CUDNN_FE_LOG(status.get_message() << std::endl);
+ }
+ return *this;
+ }
+
+ Graph &
+ select_numeric_notes(std::vector<NumericalNote_t> const &notes) {
+ auto status = plans.filter_numeric_notes(notes, true);
+ if (status.is_bad()) {
+ CUDNN_FE_LOG(status.get_message() << std::endl);
+ }
+ return *this;
+ }
+
+ Graph &
+ deselect_behavior_notes(std::vector<BehaviorNote_t> const &notes) {
+ auto status = plans.filter_behavior_notes(notes, false);
+ if (status.is_bad()) {
+ CUDNN_FE_LOG(status.get_message() << std::endl);
+ }
+ return *this;
+ }
+
+ Graph &
+ deselect_numeric_notes(std::vector<NumericalNote_t> const &notes) {
+ auto status = plans.filter_numeric_notes(notes, false);
+ if (status.is_bad()) {
+ CUDNN_FE_LOG(status.get_message() << std::endl);
+ }
+ return *this;
+ }
+
+ error_t
+ get_behavior_notes_for_plan_at_index(int64_t const index, std::vector<BehaviorNote_t> &notes) const;
+
+ error_t
+ get_behavior_notes(std::vector<BehaviorNote_t> &notes) const;
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json &j) const override final {
+ // Different from serialization of other INodes.
+ // Go over each subnode and serialize them.
+ json full_json;
+
+ full_json["context"]["name"] = context.get_name();
+ full_json["context"]["compute_data_type"] = context.get_compute_data_type();
+ full_json["context"]["intermediate_data_type"] = context.get_intermediate_data_type();
+ full_json["context"]["io_data_type"] = context.get_io_data_type();
+ full_json["context"]["sm_count"] = context.get_target_sm_count();
+ full_json["context"]["is_dynamic_shape_enabled"] = context.get_dynamic_shape_enabled();
+ full_json["context"]["is_override_shape_enabled"] = context.get_override_shape_enabled();
+ full_json["graph_uid"] = graph_uid;
+
+ full_json.update(R"( {"tag": "GRAPH"})"_json);
+ full_json["nodes"];
+ for (auto const &sub_node : sub_nodes) {
+ json j_sub_node;
+ sub_node->serialize(j_sub_node);
+ full_json["nodes"].push_back(j_sub_node);
+ }
+
+ j["context"] = full_json["context"];
+ j["graph_uid"] = full_json["graph_uid"];
+
+ j["json_version"] = "1.0";
+ j["cudnn_backend_version"] = detail::get_backend_version_string();
+ j["cudnn_frontend_version"] = CUDNN_FRONTEND_VERSION;
+ j["nodes"];
+ j["tensors"];
+ std::unordered_set<std::string> tensors;
+ for (const auto &sub_node : full_json["nodes"]) {
+ // Create a short version of the node
+ auto short_node = sub_node;
+ short_node["inputs"] = {};
+ short_node["outputs"] = {};
+
+ auto node_name = sub_node["tag"].get<std::string>();
+ auto i = 0;
+ // Process node inputs
+ for (const auto &input : sub_node["inputs"]) {
+ std::string port_name;
+ json tensor_info;
+
+ if (node_name == "CONCATENATE") {
+ // Extract port_name and tensor_name
+ port_name = std::to_string(i);
+ tensor_info = input;
+ i++;
+ } else {
+ // Extract port_name and tensor_name
+ port_name = input[0].get<std::string>();
+ tensor_info = input[1];
+ }
+
+ if (tensor_info.is_null()) {
+ continue;
+ }
+
+ // Determine the key to use for this tensor
+ std::string tensor_key;
+ json tensor_ref;
+ bool uid_assigned = tensor_info.contains("uid_assigned") && tensor_info["uid_assigned"].get<bool>();
+
+ if (uid_assigned && tensor_info.contains("uid") && tensor_info["uid"].is_number_integer()) {
+ // Use numeric UID if it was explicitly assigned
+ int64_t tensor_uid = tensor_info["uid"].get<int64_t>();
+ tensor_key = std::to_string(tensor_uid);
+ tensor_ref = json(tensor_uid);
+ } else if (tensor_info.contains("name")) {
+ // Fall back to tensor name if UID not assigned
+ tensor_key = tensor_info["name"].get<std::string>();
+ tensor_ref = tensor_key;
+ } else {
+ continue;
+ }
+
+ // Update short_node inputs
+ short_node["inputs"][port_name] = tensor_ref;
+
+ // Check if the tensor is already in the tensors map
+ if (tensors.find(tensor_key) == tensors.end()) {
+ // If not, add it to the j["tensors"]
+ j["tensors"][tensor_key] = tensor_info;
+ }
+ }
+
+ // Process node outputs
+ for (const auto &output : sub_node["outputs"]) {
+ // Extract port_name and tensor_name
+ auto port_name = output[0].get<std::string>();
+ auto tensor_info = output[1];
+
+ if (tensor_info.is_null()) {
+ continue;
+ }
+
+ // Determine the key to use for this tensor
+ std::string tensor_key;
+ json tensor_ref;
+ bool uid_assigned = tensor_info.contains("uid_assigned") && tensor_info["uid_assigned"].get<bool>();
+
+ if (uid_assigned && tensor_info.contains("uid") && tensor_info["uid"].is_number_integer()) {
+ // Use numeric UID if it was explicitly assigned
+ int64_t tensor_uid = tensor_info["uid"].get<int64_t>();
+ tensor_key = std::to_string(tensor_uid);
+ tensor_ref = json(tensor_uid);
+ } else if (tensor_info.contains("name")) {
+ // Fall back to tensor name if UID not assigned
+ tensor_key = tensor_info["name"].get<std::string>();
+ tensor_ref = tensor_key;
+ } else {
+ continue;
+ }
+
+ // Update short_node outputs
+ short_node["outputs"][port_name] = tensor_ref;
+
+ // Check if the tensor is already in the tensors map
+ if (tensors.find(tensor_key) == tensors.end()) {
+ // If not, add it to the j["tensors"]
+ j["tensors"][tensor_key] = tensor_info;
+ }
+ }
+
+ // Add the short_node to j["nodes"]
+ j["nodes"].push_back(short_node);
+ }
+ };
+#endif
+
+ size_t
+ key() override final {
+ return key(context.get_dynamic_shape_enabled());
+ }
+
+ // TODO: temparorily placed in graphs class. This function needs to be a free standing function.
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ error_t
+ deserialize(const json &j, bool const enforce_precompiled = false) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ enforce_precompiled,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "enforce_precompiled requires plan serialization; JSON deserialization reconstructs the graph");
+
+ if (j.contains("context")) {
+ const auto &j_context = j["context"];
+ if (j_context.contains("compute_data_type") && !j_context["compute_data_type"].is_null()) {
+ context.set_compute_data_type(j_context["compute_data_type"].get<DataType_t>());
+ }
+ if (j_context.contains("intermediate_data_type") && !j_context["intermediate_data_type"].is_null()) {
+ context.set_intermediate_data_type(j_context["intermediate_data_type"].get<DataType_t>());
+ }
+ if (j_context.contains("io_data_type") && !j_context["io_data_type"].is_null()) {
+ context.set_io_data_type(j_context["io_data_type"].get<DataType_t>());
+ }
+ if (j_context.contains("name") && !j_context["name"].is_null()) {
+ context.set_name(j_context["name"].get<std::string>());
+ }
+ if (j_context.contains("sm_count") && !j_context["sm_count"].is_null()) {
+ context.set_target_sm_count(j_context["sm_count"].get<int32_t>());
+ }
+ if (j_context.contains("is_dynamic_shape_enabled") && !j_context["is_dynamic_shape_enabled"].is_null()) {
+ context.set_dynamic_shape_enabled(j_context["is_dynamic_shape_enabled"].get<bool>());
+ }
+ if (j_context.contains("is_override_shape_enabled") && !j_context["is_override_shape_enabled"].is_null()) {
+ context.set_override_shape_enabled(j_context["is_override_shape_enabled"].get<bool>());
+ }
+ }
+
+ if (j.contains("graph_uid") && !j["graph_uid"].is_null()) {
+ graph_uid = j["graph_uid"].get<uint64_t>();
+ }
+
+ std::map<std::string, std::shared_ptr<Tensor_attributes>> created_tensors;
+ // Iterate through each sub-node in the full JSON
+ if (j.contains("nodes") && j["nodes"].is_array()) {
+ for (auto j_sub_node : j["nodes"]) {
+ // Create a JSON object for inputs
+ json inputs;
+
+ // Iterate through each input of the sub-node
+ if (j_sub_node.contains("inputs") && j_sub_node["inputs"].is_object()) {
+ for (auto &[port_name, tensor_ref] : j_sub_node["inputs"].items()) {
+ // Convert tensor reference (either numeric UID or string name) to string key
+ std::string tensor_key = tensor_ref.is_number_integer()
+ ? std::to_string(tensor_ref.get<int64_t>())
+ : tensor_ref.get<std::string>();
+
+ if (j.contains("tensors") && j["tensors"].contains(tensor_key)) {
+ // Add the input to the inputs JSON object
+ inputs.push_back({port_name, j["tensors"][tensor_key]});
+ }
+ }
+ }
+
+ // Create a JSON object for outputs
+ json outputs;
+
+ // Iterate through each output of the sub-node
+ if (j_sub_node.contains("outputs") && j_sub_node["outputs"].is_object()) {
+ for (auto &[port_name, tensor_ref] : j_sub_node["outputs"].items()) {
+ // Convert tensor reference (either numeric UID or string name) to string key
+ std::string tensor_key = tensor_ref.is_number_integer()
+ ? std::to_string(tensor_ref.get<int64_t>())
+ : tensor_ref.get<std::string>();
+
+ if (j.contains("tensors") && j["tensors"].contains(tensor_key)) {
+ // Add the output to the outputs JSON object
+ outputs.push_back({port_name, j["tensors"][tensor_key]});
+ }
+ }
+ }
+
+ // Replace the original inputs and outputs of the sub-node with the new JSON objects
+ j_sub_node["inputs"] = inputs;
+ j_sub_node["outputs"] = outputs;
+
+ auto check_if_pre_created_tensor = [&created_tensors](std::shared_ptr<Tensor_attributes> t) {
+ if (t == nullptr) {
+ return t;
+ }
+
+ if (created_tensors.find(t->get_name()) == created_tensors.end()) {
+ created_tensors.insert({t->get_name(), t});
+ return t;
+ } else {
+ return created_tensors[t->get_name()];
+ }
+ };
+
+#define CHECK_TENSORS(attributes) \
+ for (const auto &[key, tensor] : attributes.inputs) { \
+ attributes.inputs[key] = check_if_pre_created_tensor(tensor); \
+ } \
+ for (const auto &[key, tensor] : attributes.outputs) { \
+ attributes.outputs[key] = check_if_pre_created_tensor(tensor); \
+ }
+
+#define FILL_GLOBAL_IO_TENSOR_MAP(attributes) \
+ for (auto input_name_to_attr_pair : attributes.inputs) { \
+ if (input_name_to_attr_pair.second != nullptr && \
+ (input_name_to_attr_pair.second->get_is_virtual() == false)) { \
+ full_graph_inputs.emplace(input_name_to_attr_pair.second); \
+ } \
+ } \
+ for (auto output_name_to_attr_pair : attributes.outputs) { \
+ if (output_name_to_attr_pair.second != nullptr) { \
+ full_graph_outputs.emplace(output_name_to_attr_pair.second); \
+ } \
+ }
+ if (j_sub_node.contains("tag") && j_sub_node["tag"].is_string()) {
+ auto tag = j_sub_node["tag"].get<std::string>();
+ if (tag == "CONV_FPROP") {
+ auto conv_fprop_attributes = j_sub_node.get<Conv_fprop_attributes>();
+ CHECK_TENSORS(conv_fprop_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(conv_fprop_attributes);
+ sub_nodes.emplace_back(
+ std::make_unique<ConvolutionNode>(std::move(conv_fprop_attributes), context));
+ } else if (tag == "POINTWISE") {
+ auto pointwise_attributes = j_sub_node.get<Pointwise_attributes>();
+ CHECK_TENSORS(pointwise_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(pointwise_attributes);
+ sub_nodes.emplace_back(
+ std::make_unique<PointwiseNode>(std::move(pointwise_attributes), context));
+ } else if (tag == "REDUCTION") {
+ auto reduction_attributes = j_sub_node.get<Reduction_attributes>();
+ CHECK_TENSORS(reduction_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(reduction_attributes);
+ sub_nodes.emplace_back(
+ std::make_unique<ReductionNode>(std::move(reduction_attributes), context));
+ } else if (tag == "SDPA") {
+ auto sdpa_attributes = j_sub_node.get<SDPA_attributes>();
+ CHECK_TENSORS(sdpa_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(sdpa_attributes);
+ switch (sdpa_attributes.implementation) {
+ case AttentionImplementation_t::AUTO:
+ return {error_code_t::INVALID_VALUE,
+ "Implementation cannot be AUTO in serialized form"};
+ case AttentionImplementation_t::COMPOSITE:
+ sub_nodes.emplace_back(
+ std::make_unique<CompositeSDPANode>(std::move(sdpa_attributes), context));
+ break;
+ case AttentionImplementation_t::UNIFIED:
+ sub_nodes.emplace_back(
+ std::make_unique<UnifiedSDPANode>(std::move(sdpa_attributes), context));
+ }
+ } else if (tag == "SDPA_BWD") {
+ auto sdpa_bwd_attributes = j_sub_node.get<SDPA_backward_attributes>();
+ CHECK_TENSORS(sdpa_bwd_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(sdpa_bwd_attributes);
+ sub_nodes.emplace_back(
+ std::make_unique<CompositeSDPABackwardNode>(std::move(sdpa_bwd_attributes), context));
+ } else if (tag == "MATMUL") {
+ auto matmul_attributes = j_sub_node.get<Matmul_attributes>();
+ CHECK_TENSORS(matmul_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(matmul_attributes);
+ sub_nodes.emplace_back(std::make_unique<MatmulNode>(std::move(matmul_attributes), context));
+ } else if (tag == "SLICE") {
+ auto slice_attributes = j_sub_node.get<Slice_attributes>();
+ CHECK_TENSORS(slice_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(slice_attributes);
+ sub_nodes.emplace_back(std::make_unique<SliceNode>(std::move(slice_attributes), context));
+ } else if (tag == "TRANSPOSE") {
+ auto transpose_attributes = j_sub_node.get<Transpose_attributes>();
+ CHECK_TENSORS(transpose_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(transpose_attributes);
+ sub_nodes.emplace_back(
+ std::make_unique<TransposeNode>(std::move(transpose_attributes), context));
+ } else if (tag == "RESAMPLE") {
+ auto resample_attributes = j_sub_node.get<Resample_attributes>();
+ CHECK_TENSORS(resample_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(resample_attributes);
+ sub_nodes.emplace_back(std::make_unique<ResampleNode>(std::move(resample_attributes), context));
+ } else if (tag == "CONV_DGRAD") {
+ auto dgrad_attributes = j_sub_node.get<Conv_dgrad_attributes>();
+ CHECK_TENSORS(dgrad_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(dgrad_attributes);
+ sub_nodes.emplace_back(std::make_unique<DgradNode>(std::move(dgrad_attributes), context));
+ } else if (tag == "CONV_WGRAD") {
+ auto wgrad_attributes = j_sub_node.get<Conv_wgrad_attributes>();
+ CHECK_TENSORS(wgrad_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(wgrad_attributes);
+ sub_nodes.emplace_back(std::make_unique<WgradNode>(std::move(wgrad_attributes), context));
+ } else if (tag == "MOE_GROUPED_MATMUL") {
+ auto moe_grouped_matmul_attributes = j_sub_node.get<Moe_grouped_matmul_attributes>();
+ CHECK_TENSORS(moe_grouped_matmul_attributes);
+ FILL_GLOBAL_IO_TENSOR_MAP(moe_grouped_matmul_attributes);
+ sub_nodes.emplace_back(
+ std::make_unique<MoeGroupedMatmulNode>(std::move(moe_grouped_matmul_attributes), context));
+ }
+ }
+#undef CHECK_TENSORS
+ }
+ }
+
+ return {error_code_t::OK, ""};
+ }
+#endif
+
+ std::string
+ print(void) const {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ std::stringstream ss;
+ json j = *this;
+ ss << j;
+ return ss.str();
+#else
+ return "print is unavailable when compiled with CUDNN_FRONTEND_SKIP_JSON_LIB";
+#endif
+ }
+};
+
+inline error_t
+Graph::get_behavior_notes_for_plan_at_index(int64_t const index, std::vector<BehaviorNote_t> &notes) const {
+ CHECK_CUDNN_FRONTEND_ERROR(plans.get_behavior_notes_at_index(index, notes));
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+Graph::get_behavior_notes(std::vector<BehaviorNote_t> &notes) const {
+ int64_t const candidate = plans.candidate;
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ candidate == -1,
+ error_code_t::INVALID_VALUE,
+ "No candiate plan set for the graph. You can set one by building a plan, which in turn sets the "
+ "candidate internally. Do note that you also query behaviour notes for a created-but-not-built plan by using "
+ "get_behavior_notes_for_plan_at_index API.");
+
+ CHECK_CUDNN_FRONTEND_ERROR(get_behavior_notes_for_plan_at_index(candidate, notes));
+ return {error_code_t::OK, ""};
+}
+
+inline int64_t
+Graph::get_execution_plan_count() const {
+ return plans.execution_plans.size();
+}
+
+inline error_t
+Graph::get_engine_count(int64_t &count) {
+ _CUDNN_CHECK_CUDNN_ERROR(detail::get_attribute(operation_graph->get_raw_desc(),
+ CUDNN_ATTR_OPERATIONGRAPH_ENGINE_GLOBAL_COUNT,
+ CUDNN_TYPE_INT64,
+ 1,
+ nullptr,
+ &count));
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+Graph::get_knobs_for_engine(int64_t const engine, std::vector<Knob> &knobs) {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::query_knobs(engine, operation_graph->get_raw_desc(), knobs));
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+Graph::create_execution_plans(std::vector<HeurMode_t> const &mode) {
+ CUDNN_FE_LOG_BANNER(" CREATE EXECUTION PLANS (HEURISTICS QUERY) ");
+
+ // CHECK IF NEED TO OVERRIDE HEURISTICS QUERY
+ for (auto &sub_node : sub_nodes) {
+ if (auto [engine_id, user_knobs] = sub_node->override_heuristics_query(); engine_id != -1) {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Overriding heuristics query with engine ID "
+ << engine_id << " and user knobs " << nlohmann::json(user_knobs).dump());
+#else
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Overriding heuristics query with engine ID "
+ << engine_id << " and user knobs " << static_cast<int>(user_knobs.size()));
+#endif
+ CHECK_CUDNN_FRONTEND_ERROR(create_execution_plan(engine_id, user_knobs));
+ return {error_code_t::OK, ""};
+ }
+ }
+
+ // Separate OPENSOURCE from cuDNN modes
+ bool has_opensource = false;
+ std::vector<HeurMode_t> cudnn_modes;
+ for (auto const &m : mode) {
+ if (m == HeurMode_t::OPENSOURCE) {
+ has_opensource = true;
+ } else {
+ cudnn_modes.push_back(m);
+ }
+ }
+
+ // Register OSS engines if OPENSOURCE mode requested
+ if (has_opensource) {
+ // Try SDPA OSS engine
+ auto oss_sdpa_status = register_oss_engine_();
+ if (oss_sdpa_status.is_good()) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Registered OSS SDPA prefill engine");
+ }
+
+ // Try RmsNorm+SiLU OSS engine
+ auto oss_norm_status = register_oss_rms_norm_silu_engine_();
+ if (oss_norm_status.is_good()) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Registered OSS RmsNorm+SiLU engine");
+ }
+
+ if (oss_sdpa_status.is_bad() && oss_norm_status.is_bad()) {
+ CUDNN_FE_LOG_LABEL_ENDL("WARN: No OSS engine matched the graph pattern");
+ }
+ }
+
+ // Query cuDNN heuristics for non-OPENSOURCE modes
+ if (!cudnn_modes.empty()) {
+ EngineConfigList op_graph_to_configs;
+ CHECK_CUDNN_FRONTEND_ERROR(detail::query_cudnn_heuristics_impl(
+ operation_graph, op_graph_to_configs, cudnn_modes, context.get_target_sm_count(), device_properties));
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Extracting engine configs.");
+
+ plans.set_tag(operation_graph->getTag());
+ plans.enqueue_engine_configs(op_graph_to_configs);
+ plans.set_kernel_cache(kernel_cache);
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Querying engine config properties.");
+ CHECK_CUDNN_FRONTEND_ERROR(plans.query_properties());
+ }
+
+ CUDNN_FE_LOG_BANNER(" HEURISTICS QUERY ALL OK ");
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+Graph::create_execution_plan(int64_t const engine_id, std::unordered_map<KnobType_t, int64_t> const &user_knobs) {
+ // first create the engine
+ // this just uses the global engine id and operation graph
+ CUDNN_FE_LOG_BANNER(" CREATE EXECUTION PLAN for engine id " << engine_id << " ");
+ detail::backend_descriptor engine(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(engine.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create engine's backend descriptor.");
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::create_engine(engine, engine_id, operation_graph->get_raw_desc(), device_properties));
+
+ // Create an array of knob choices
+ std::vector<detail::backend_descriptor> knob_choices;
+ CHECK_CUDNN_FRONTEND_ERROR(detail::set_knob_choices(user_knobs, knob_choices));
+
+ auto engine_config = make_shared_backend_pointer((cudnnBackendDescriptorType_t)CUDNN_BACKEND_ENGINECFG_DESCRIPTOR);
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_engine_config(engine_config, engine, knob_choices));
+ plans.enqueue_engine_configs({engine_config});
+ CHECK_CUDNN_FRONTEND_ERROR(plans.query_properties());
+
+ CUDNN_FE_LOG_BANNER(" CREATE EXECUTION PLAN ALL OK ");
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+Graph::build_plan_at_index(int64_t plan_index) {
+ CHECK_CUDNN_FRONTEND_ERROR(plans.build_plan_at_index(plan_index));
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+Graph::build_plans(BuildPlanPolicy_t const policy, bool const do_multithreaded_builds) {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ CUDNN_FE_LOG_BANNER(" BUILD PLANS for policy " << nlohmann::json(policy).dump() << " ");
+#else
+ CUDNN_FE_LOG_BANNER(" BUILD PLANS for policy " << static_cast<int>(policy) << " ");
+#endif
+
+ // Build OSS SDPA engine if it passed check_support
+ if (plans.has_oss_sdpa_engine()) {
+ auto oss_status = plans.build_oss_sdpa_engine();
+ if (oss_status.is_good()) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: OSS SDPA engine built successfully (NVRTC compilation done)");
+ if (policy == BuildPlanPolicy_t::HEURISTICS_CHOICE) {
+ CUDNN_FE_LOG_BANNER(" BUILD PLANS ALL OK (OSS SDPA engine) ");
+ return {error_code_t::OK, ""};
+ }
+ } else {
+ CUDNN_FE_LOG_LABEL_ENDL("WARN: OSS SDPA engine build failed: " << oss_status.get_message());
+ }
+ }
+
+ // Build OSS RmsNorm+SiLU engine if it passed check_support
+ if (plans.has_oss_rms_norm_silu_engine()) {
+ auto oss_status = plans.build_oss_rms_norm_silu_engine();
+ if (oss_status.is_good()) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: OSS RmsNorm+SiLU engine built successfully (NVRTC compilation done)");
+ if (policy == BuildPlanPolicy_t::HEURISTICS_CHOICE) {
+ CUDNN_FE_LOG_BANNER(" BUILD PLANS ALL OK (OSS RmsNorm+SiLU engine) ");
+ return {error_code_t::OK, ""};
+ }
+ } else {
+ CUDNN_FE_LOG_LABEL_ENDL("WARN: OSS RmsNorm+SiLU engine build failed: " << oss_status.get_message());
+ }
+ }
+
+ CHECK_CUDNN_FRONTEND_ERROR(plans.build_plans(policy, do_multithreaded_builds));
+
+ // Prepare the variant pack template for fast execution.
+ // This pre-computes slot indices so execute() can skip map operations.
+ CHECK_CUDNN_FRONTEND_ERROR(prepare_variant_pack_template());
+
+ CUDNN_FE_LOG_BANNER(" BUILD PLANS ALL OK ");
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+Graph::build(cudnnHandle_t const &handle,
+ std::vector<HeurMode_t> const &modes,
+ BuildPlanPolicy_t const policy,
+ bool const do_multithreaded_builds) {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ CUDNN_FE_LOG_BANNER(" BUILD with handle " << nlohmann::json(policy).dump());
+#else
+ CUDNN_FE_LOG_BANNER(" BUILD with handle " << static_cast<int>(policy) << " ");
+#endif
+ CHECK_CUDNN_FRONTEND_ERROR(this->validate());
+ CHECK_CUDNN_FRONTEND_ERROR(this->build_operation_graph(handle));
+ CHECK_CUDNN_FRONTEND_ERROR(this->create_execution_plans(modes));
+ CHECK_CUDNN_FRONTEND_ERROR(this->check_support());
+ CHECK_CUDNN_FRONTEND_ERROR(this->build_plans(policy, do_multithreaded_builds));
+ CUDNN_FE_LOG_BANNER(" BUILD ALL OK (with handle) ");
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+Graph::build(std::vector<HeurMode_t> const &modes, BuildPlanPolicy_t const policy, bool const do_multithreaded_builds) {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ CUDNN_FE_LOG_BANNER(" BUILD PLANS without handle " << nlohmann::json(policy).dump() << " ");
+#else
+ CUDNN_FE_LOG_BANNER(" BUILD PLANS without handle " << static_cast<int>(policy) << " ");
+#endif
+ CHECK_CUDNN_FRONTEND_ERROR(this->validate());
+ CHECK_CUDNN_FRONTEND_ERROR(this->build_operation_graph());
+ CHECK_CUDNN_FRONTEND_ERROR(this->create_execution_plans(modes));
+ CHECK_CUDNN_FRONTEND_ERROR(this->check_support());
+ CHECK_CUDNN_FRONTEND_ERROR(this->build_plans(policy, do_multithreaded_builds));
+ CUDNN_FE_LOG_BANNER(" BUILD PLANS ALL OK (no handle) ");
+ return {error_code_t::OK, ""};
+}
+
+inline Graph &
+Graph::set_intermediate_data_type(DataType_t const type) {
+ context.set_intermediate_data_type(type);
+ return *this;
+}
+
+inline Graph &
+Graph::set_io_data_type(DataType_t const type) {
+ context.set_io_data_type(type);
+ return *this;
+}
+
+inline Graph &
+Graph::set_compute_data_type(DataType_t const type) {
+ context.set_compute_data_type(type);
+ return *this;
+}
+
+inline Graph &
+Graph::set_dynamic_shape_enabled(bool is_enabled) {
+ context.set_dynamic_shape_enabled(is_enabled);
+ this->is_dynamic_shape_enabled = is_enabled;
+ return *this;
+}
+
+inline Graph &
+Graph::set_override_shape_enabled(bool is_enabled) {
+ context.set_override_shape_enabled(is_enabled);
+ this->is_override_shape_enabled = is_enabled;
+ return *this;
+}
+
+inline Graph &
+Graph::set_kernel_cache(std::shared_ptr<KernelCache> cache) {
+ kernel_cache = cache;
+ return *this;
+}
+
+inline Graph &
+Graph::set_device_properties(std::shared_ptr<const DeviceProperties> device_prop) {
+ device_properties = device_prop;
+ return *this;
+}
+
+inline Graph &
+Graph::set_sm_count(int32_t count) {
+ context.set_target_sm_count(count);
+ return *this;
+}
+
+inline Graph &
+Graph::set_sm_version(int32_t version) {
+ context.set_sm_version(version);
+ return *this;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::tensor(Tensor_attributes const &tensor) {
+ auto tensor_ptr = std::make_shared<Tensor_attributes>(tensor);
+ full_graph_inputs.emplace(tensor_ptr);
+ return tensor_ptr;
+}
+
+// Overloaded tensor() methods for compile-time constants
+inline std::shared_ptr<Tensor_attributes>
+Graph::tensor(float const &scalar, ScalarType scalar_type) {
+ auto tensor_ptr = std::make_shared<Tensor_attributes>(scalar, scalar_type);
+ full_graph_inputs.emplace(tensor_ptr);
+ return tensor_ptr;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::tensor(half const &scalar, ScalarType scalar_type) {
+ auto tensor_ptr = std::make_shared<Tensor_attributes>(scalar, scalar_type);
+ full_graph_inputs.emplace(tensor_ptr);
+ return tensor_ptr;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::tensor(nv_bfloat16 const &scalar, ScalarType scalar_type) {
+ auto tensor_ptr = std::make_shared<Tensor_attributes>(scalar, scalar_type);
+ full_graph_inputs.emplace(tensor_ptr);
+ return tensor_ptr;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::tensor(int32_t const &scalar, ScalarType scalar_type) {
+ auto tensor_ptr = std::make_shared<Tensor_attributes>(scalar, scalar_type);
+ full_graph_inputs.emplace(tensor_ptr);
+ return tensor_ptr;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::tensor(int64_t const &scalar, ScalarType scalar_type) {
+ auto tensor_ptr = std::make_shared<Tensor_attributes>(scalar, scalar_type);
+ full_graph_inputs.emplace(tensor_ptr);
+ return tensor_ptr;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::tensor(double const &scalar, ScalarType scalar_type) {
+ auto tensor_ptr = std::make_shared<Tensor_attributes>(scalar, scalar_type);
+ full_graph_inputs.emplace(tensor_ptr);
+ return tensor_ptr;
+}
+
+inline error_t
+Graph::query_tensor_attributes_of_uid(int64_t const uid, Tensor_attributes &tensor) const {
+ for (auto const &o_tensor : full_graph_outputs) {
+ if (uid == o_tensor->get_uid()) {
+ tensor = *o_tensor;
+ return {error_code_t::OK, ""};
+ }
+ }
+
+ for (auto const &i_tensor : full_graph_inputs) {
+ if (uid == i_tensor->get_uid()) {
+ tensor = *i_tensor;
+ return {error_code_t::OK, ""};
+ }
+ }
+
+ for (auto const &d_tensor : deserialized_tensor_properties) {
+ if (uid == d_tensor->get_uid()) {
+ tensor = *d_tensor;
+ return {error_code_t::OK, ""};
+ }
+ }
+
+ return {error_code_t::INVALID_VALUE, "No matching tensor for this UID"};
+}
+
+// tensor_like is meant to create "useable" copies of a tensor.
+// By usable, it means not copying over the uids, as uids are FE-level(internal) detail.
+// It also means not copying over names, which are user-level(external) detail. But user is given option to provide a
+// new name.
+inline std::shared_ptr<Tensor_attributes>
+Graph::tensor_like(std::shared_ptr<Tensor_attributes> const &tensor, std::string const &name) {
+ auto tensor_ptr = std::make_shared<Tensor_attributes>(*tensor);
+
+ // reset the uid of the cloned tensor
+ // uids are not meant to be copied by tensor_like
+ // When lowering to cudnn backend, both tensors involved here will get unique uids.
+ tensor_ptr->clear_uid();
+
+ // reset the name too. Defaults to empty string.
+ tensor_ptr->set_name(name);
+ full_graph_inputs.emplace(tensor_ptr);
+
+ return tensor_ptr;
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 6>
+Graph::bn_finalize(std::shared_ptr<Tensor_attributes> sum,
+ std::shared_ptr<Tensor_attributes> sq_sum,
+ std::shared_ptr<Tensor_attributes> scale,
+ std::shared_ptr<Tensor_attributes> bias,
+ std::shared_ptr<Tensor_attributes> epsilon,
+ std::shared_ptr<Tensor_attributes> accum_count,
+ BN_finalize_attributes attributes) {
+ // Set outputs
+ auto EQ_SCALE = attributes.outputs[BN_finalize_attributes::output_names::EQ_SCALE] =
+ output_tensor(attributes.name + "::EQ_SCALE");
+ auto EQ_BIAS = attributes.outputs[BN_finalize_attributes::output_names::EQ_BIAS] =
+ output_tensor(attributes.name + "::EQ_BIAS");
+ auto MEAN = attributes.outputs[BN_finalize_attributes::output_names::MEAN] =
+ output_tensor(attributes.name + "::MEAN");
+ auto INV_VARIANCE = attributes.outputs[BN_finalize_attributes::output_names::INV_VARIANCE] =
+ output_tensor(attributes.name + "::INV_VARIANCE");
+ std::shared_ptr<Tensor_attributes> NEXT_RUNNING_MEAN = nullptr;
+ std::shared_ptr<Tensor_attributes> NEXT_RUNNING_VAR = nullptr;
+ if (attributes.inputs[BN_finalize_attributes::input_names::PREV_RUNNING_MEAN] &&
+ attributes.inputs[BN_finalize_attributes::input_names::PREV_RUNNING_VAR] &&
+ attributes.inputs[BN_finalize_attributes::input_names::MOMENTUM]) {
+ NEXT_RUNNING_MEAN = output_tensor(attributes.name + "::NEXT_RUNNING_MEAN");
+ NEXT_RUNNING_VAR = output_tensor(attributes.name + "::NEXT_RUNNING_VAR");
+ }
+ attributes.outputs[BN_finalize_attributes::output_names::NEXT_RUNNING_MEAN] = NEXT_RUNNING_MEAN;
+ attributes.outputs[BN_finalize_attributes::output_names::NEXT_RUNNING_VAR] = NEXT_RUNNING_VAR;
+
+ // Set inputs
+ attributes.inputs[BN_finalize_attributes::input_names::SUM] = sum;
+ attributes.inputs[BN_finalize_attributes::input_names::SQ_SUM] = sq_sum;
+ attributes.inputs[BN_finalize_attributes::input_names::SCALE] = scale;
+ attributes.inputs[BN_finalize_attributes::input_names::BIAS] = bias;
+ attributes.inputs[BN_finalize_attributes::input_names::EPSILON] = epsilon;
+ attributes.inputs[BN_finalize_attributes::input_names::ACCUM_COUNT] = accum_count;
+
+ sub_nodes.emplace_back(std::make_unique<BatchNormFinalizeNode>(std::move(attributes), context));
+
+ return {EQ_SCALE, EQ_BIAS, MEAN, INV_VARIANCE, NEXT_RUNNING_MEAN, NEXT_RUNNING_VAR};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::layernorm(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ std::shared_ptr<Tensor_attributes> bias,
+ Layernorm_attributes attributes) {
+ // Set outputs
+ auto Y = attributes.outputs[Layernorm_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+ std::shared_ptr<Tensor_attributes> MEAN = nullptr;
+ std::shared_ptr<Tensor_attributes> INV_VARIANCE = nullptr;
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ MEAN = attributes.outputs[Layernorm_attributes::output_names::MEAN] = output_tensor(attributes.name + "::MEAN");
+ INV_VARIANCE = attributes.outputs[Layernorm_attributes::output_names::INV_VARIANCE] =
+ output_tensor(attributes.name + "::INV_VARIANCE");
+ }
+ // Set inputs
+ attributes.inputs[Layernorm_attributes::input_names::X] = x;
+ attributes.inputs[Layernorm_attributes::input_names::SCALE] = scale;
+ attributes.inputs[Layernorm_attributes::input_names::BIAS] = bias;
+
+ sub_nodes.emplace_back(std::make_unique<LayerNormNode>(std::move(attributes), context));
+
+ return {Y, MEAN, INV_VARIANCE};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::adalayernorm(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ std::shared_ptr<Tensor_attributes> bias,
+ AdaLayernorm_attributes attributes) {
+ // Set outputs
+ auto Y = attributes.outputs[AdaLayernorm_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+ std::shared_ptr<Tensor_attributes> MEAN = nullptr;
+ std::shared_ptr<Tensor_attributes> INV_VARIANCE = nullptr;
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ MEAN = attributes.outputs[AdaLayernorm_attributes::output_names::MEAN] =
+ output_tensor(attributes.name + "::MEAN");
+ INV_VARIANCE = attributes.outputs[AdaLayernorm_attributes::output_names::INV_VARIANCE] =
+ output_tensor(attributes.name + "::INV_VARIANCE");
+ }
+ // Set inputs
+ attributes.inputs[AdaLayernorm_attributes::input_names::X] = x;
+ attributes.inputs[AdaLayernorm_attributes::input_names::SCALE] = scale;
+ attributes.inputs[AdaLayernorm_attributes::input_names::BIAS] = bias;
+
+ sub_nodes.emplace_back(std::make_unique<AdaLayerNormNode>(std::move(attributes), context));
+
+ return {std::move(Y), std::move(MEAN), std::move(INV_VARIANCE)};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::instancenorm(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ std::shared_ptr<Tensor_attributes> bias,
+ Instancenorm_attributes attributes) {
+ // Set outputs
+ auto Y = attributes.outputs[Instancenorm_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+ std::shared_ptr<Tensor_attributes> MEAN = nullptr;
+ std::shared_ptr<Tensor_attributes> INV_VARIANCE = nullptr;
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ MEAN = attributes.outputs[Instancenorm_attributes::output_names::MEAN] =
+ output_tensor(attributes.name + "::MEAN");
+ INV_VARIANCE = attributes.outputs[Instancenorm_attributes::output_names::INV_VARIANCE] =
+ output_tensor(attributes.name + "::INV_VARIANCE");
+ }
+ // Set inputs
+ attributes.inputs[Instancenorm_attributes::input_names::X] = x;
+ attributes.inputs[Instancenorm_attributes::input_names::SCALE] = scale;
+ attributes.inputs[Instancenorm_attributes::input_names::BIAS] = bias;
+
+ sub_nodes.emplace_back(std::make_unique<InstanceNormNode>(std::move(attributes), context));
+
+ return {Y, MEAN, INV_VARIANCE};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 5>
+Graph::batchnorm(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ std::shared_ptr<Tensor_attributes> bias,
+ Batchnorm_attributes attributes) {
+ // Set outputs
+ auto Y = attributes.outputs[Batchnorm_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+ auto MEAN = attributes.outputs[Batchnorm_attributes::output_names::MEAN] =
+ output_tensor(attributes.name + "::MEAN");
+ auto INV_VARIANCE = attributes.outputs[Batchnorm_attributes::output_names::INV_VARIANCE] =
+ output_tensor(attributes.name + "::INV_VARIANCE");
+ std::shared_ptr<Tensor_attributes> NEXT_RUNNING_MEAN = nullptr;
+ std::shared_ptr<Tensor_attributes> NEXT_RUNNING_VAR = nullptr;
+ if (attributes.inputs[Batchnorm_attributes::input_names::PREV_RUNNING_MEAN] &&
+ attributes.inputs[Batchnorm_attributes::input_names::PREV_RUNNING_VAR] &&
+ attributes.inputs[Batchnorm_attributes::input_names::MOMENTUM]) {
+ NEXT_RUNNING_MEAN = output_tensor(attributes.name + "::NEXT_RUNNING_MEAN");
+ NEXT_RUNNING_VAR = output_tensor(attributes.name + "::NEXT_RUNNING_VAR");
+ }
+ attributes.outputs[Batchnorm_attributes::output_names::NEXT_RUNNING_MEAN] = NEXT_RUNNING_MEAN;
+ attributes.outputs[Batchnorm_attributes::output_names::NEXT_RUNNING_VAR] = NEXT_RUNNING_VAR;
+
+ // Set inputs
+ attributes.inputs[Batchnorm_attributes::input_names::X] = x;
+ attributes.inputs[Batchnorm_attributes::input_names::SCALE] = scale;
+ attributes.inputs[Batchnorm_attributes::input_names::BIAS] = bias;
+
+ sub_nodes.emplace_back(std::make_unique<BatchNormNode>(std::move(attributes), context));
+
+ return {Y, MEAN, INV_VARIANCE, NEXT_RUNNING_MEAN, NEXT_RUNNING_VAR};
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::batchnorm_inference(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> mean,
+ std::shared_ptr<Tensor_attributes> inv_variance,
+ std::shared_ptr<Tensor_attributes> scale,
+ std::shared_ptr<Tensor_attributes> bias,
+ Batchnorm_inference_attributes attributes) {
+ // Set outputs
+ auto Y = attributes.outputs[Batchnorm_inference_attributes::output_names::Y] =
+ output_tensor(attributes.name + "::Y");
+
+ // Set inputs
+ attributes.inputs[Batchnorm_inference_attributes::input_names::X] = x;
+ attributes.inputs[Batchnorm_inference_attributes::input_names::MEAN] = mean;
+ attributes.inputs[Batchnorm_inference_attributes::input_names::INV_VARIANCE] = inv_variance;
+ attributes.inputs[Batchnorm_inference_attributes::input_names::SCALE] = scale;
+ attributes.inputs[Batchnorm_inference_attributes::input_names::BIAS] = bias;
+
+ sub_nodes.emplace_back(std::make_unique<BatchnormInferenceNode>(std::move(attributes), context));
+
+ return Y;
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::batchnorm_backward(std::shared_ptr<Tensor_attributes> dy,
+ std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ Batchnorm_backward_attributes attributes) {
+ // Set outputs
+ auto DX = attributes.outputs[Batchnorm_backward_attributes::output_names::DX] =
+ output_tensor(attributes.name + "::DX");
+ auto DSCALE = attributes.outputs[Batchnorm_backward_attributes::output_names::DSCALE] =
+ output_tensor(attributes.name + "::DSCALE");
+ auto DBIAS = attributes.outputs[Batchnorm_backward_attributes::output_names::DBIAS] =
+ output_tensor(attributes.name + "::DBIAS");
+
+ // Set inputs
+ attributes.inputs[Batchnorm_backward_attributes::input_names::DY] = dy;
+ attributes.inputs[Batchnorm_backward_attributes::input_names::X] = x;
+ attributes.inputs[Batchnorm_backward_attributes::input_names::SCALE] = scale;
+
+ sub_nodes.emplace_back(std::make_unique<DBNNode>(std::move(attributes), context));
+
+ return {DX, DSCALE, DBIAS};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::instancenorm_backward(std::shared_ptr<Tensor_attributes> dy,
+ std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ Instancenorm_backward_attributes attributes) {
+ // Set outputs
+ auto DX = attributes.outputs[Instancenorm_backward_attributes::output_names::DX] =
+ output_tensor(attributes.name + "::DX");
+ auto DSCALE = attributes.outputs[Instancenorm_backward_attributes::output_names::DSCALE] =
+ output_tensor(attributes.name + "::DSCALE");
+ auto DBIAS = attributes.outputs[Instancenorm_backward_attributes::output_names::DBIAS] =
+ output_tensor(attributes.name + "::DBIAS");
+
+ // Set inputs
+ attributes.inputs[Instancenorm_backward_attributes::input_names::DY] = dy;
+ attributes.inputs[Instancenorm_backward_attributes::input_names::X] = x;
+ attributes.inputs[Instancenorm_backward_attributes::input_names::SCALE] = scale;
+
+ sub_nodes.emplace_back(std::make_unique<DINNode>(std::move(attributes), context));
+
+ return {DX, DSCALE, DBIAS};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::layernorm_backward(std::shared_ptr<Tensor_attributes> dy,
+ std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ Layernorm_backward_attributes attributes) {
+ // Set outputs
+ auto DX = attributes.outputs[Layernorm_backward_attributes::output_names::DX] =
+ output_tensor(attributes.name + "::DX");
+ auto DSCALE = attributes.outputs[Layernorm_backward_attributes::output_names::DSCALE] =
+ output_tensor(attributes.name + "::DSCALE");
+ auto DBIAS = attributes.outputs[Layernorm_backward_attributes::output_names::DBIAS] =
+ output_tensor(attributes.name + "::DBIAS");
+
+ // Set inputs
+ attributes.inputs[Layernorm_backward_attributes::input_names::DY] = dy;
+ attributes.inputs[Layernorm_backward_attributes::input_names::X] = x;
+ attributes.inputs[Layernorm_backward_attributes::input_names::SCALE] = scale;
+
+ sub_nodes.emplace_back(std::make_unique<DLNNode>(std::move(attributes), context));
+
+ return {DX, DSCALE, DBIAS};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::adalayernorm_backward(std::shared_ptr<Tensor_attributes> dy,
+ std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ AdaLayernorm_backward_attributes attributes) {
+ // Set outputs
+ auto DX = attributes.outputs[AdaLayernorm_backward_attributes::output_names::DX] =
+ output_tensor(attributes.name + "::DX");
+ auto DSCALE = attributes.outputs[AdaLayernorm_backward_attributes::output_names::DSCALE] =
+ output_tensor(attributes.name + "::DSCALE");
+ auto DBIAS = attributes.outputs[AdaLayernorm_backward_attributes::output_names::DBIAS] =
+ output_tensor(attributes.name + "::DBIAS");
+ // Set inputs
+ attributes.inputs[AdaLayernorm_backward_attributes::input_names::DY] = dy;
+ attributes.inputs[AdaLayernorm_backward_attributes::input_names::X] = x;
+ attributes.inputs[AdaLayernorm_backward_attributes::input_names::SCALE] = scale;
+
+ sub_nodes.emplace_back(std::make_unique<DAdaLayerNormNode>(std::move(attributes), context));
+
+ return {std::move(DX), std::move(DSCALE), std::move(DBIAS)};
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::conv_fprop(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> w,
+ Conv_fprop_attributes attributes) {
+ // Make required output tensors
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+ auto Y = output_tensor(attributes.name + "::Y");
+ attributes.outputs[Conv_fprop_attributes::output_names::Y] = Y;
+
+ // Set inputs
+ attributes.inputs[Conv_fprop_attributes::input_names::X] = x;
+ attributes.inputs[Conv_fprop_attributes::input_names::W] = w;
+
+ sub_nodes.emplace_back(std::make_unique<ConvolutionNode>(std::move(attributes), context));
+
+ return Y;
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 5>
+Graph::dbn_weight(std::shared_ptr<Tensor_attributes> dy,
+ std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> mean,
+ std::shared_ptr<Tensor_attributes> inv_variance,
+ std::shared_ptr<Tensor_attributes> scale,
+ DBN_weight_attributes attributes) {
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+ // Make required output tensors
+ auto DBIAS = attributes.outputs[DBN_weight_attributes::output_names::DBIAS] =
+ output_tensor(attributes.name + "::DBIAS");
+ auto DSCALE = attributes.outputs[DBN_weight_attributes::output_names::DSCALE] =
+ output_tensor(attributes.name + "::DSCALE");
+ auto EQ_BIAS = attributes.outputs[DBN_weight_attributes::output_names::EQ_BIAS] =
+ output_tensor(attributes.name + "::EQ_BIAS");
+ auto EQ_SCALE_DY = attributes.outputs[DBN_weight_attributes::output_names::EQ_SCALE_DY] =
+ output_tensor(attributes.name + "::EQ_SCALE_DY");
+ auto EQ_SCALE_X = attributes.outputs[DBN_weight_attributes::output_names::EQ_SCALE_X] =
+ output_tensor(attributes.name + "::EQ_SCALE_X");
+
+ // Set inputs
+ attributes.inputs[DBN_weight_attributes::input_names::DY] = dy;
+ attributes.inputs[DBN_weight_attributes::input_names::X] = x;
+ attributes.inputs[DBN_weight_attributes::input_names::SCALE] = scale;
+ attributes.inputs[DBN_weight_attributes::input_names::MEAN] = mean;
+ attributes.inputs[DBN_weight_attributes::input_names::INV_VARIANCE] = inv_variance;
+
+ sub_nodes.emplace_back(std::make_unique<DBNWeightNode>(std::move(attributes), context));
+
+ return {DSCALE, DBIAS, EQ_SCALE_DY, EQ_SCALE_X, EQ_BIAS};
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::conv_dgrad(std::shared_ptr<Tensor_attributes> dy,
+ std::shared_ptr<Tensor_attributes> w,
+ Conv_dgrad_attributes attributes) {
+ // Make required output tensors
+ auto DX = attributes.outputs[Conv_dgrad_attributes::output_names::DX] = output_tensor(attributes.name + "::DX");
+
+ // Set inputs
+ attributes.inputs[Conv_dgrad_attributes::input_names::DY] = dy;
+ attributes.inputs[Conv_dgrad_attributes::input_names::W] = w;
+
+ sub_nodes.emplace_back(std::make_unique<DgradNode>(std::move(attributes), context));
+
+ return DX;
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 2>
+Graph::genstats(std::shared_ptr<Tensor_attributes> x, Genstats_attributes attributes) {
+ // Set outputs
+ auto SUM = attributes.outputs[Genstats_attributes::output_names::SUM] =
+ output_tensor(attributes.name + "_sum_output");
+ auto SQ_SUM = attributes.outputs[Genstats_attributes::output_names::SQ_SUM] =
+ output_tensor(attributes.name + "_sq_sum_output");
+
+ // Set inputs
+ attributes.inputs[Genstats_attributes::input_names::X] = x;
+
+ sub_nodes.emplace_back(std::make_unique<GenstatsNode>(std::move(attributes), context));
+
+ return {SUM, SQ_SUM};
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::conv_wgrad(std::shared_ptr<Tensor_attributes> dy,
+ std::shared_ptr<Tensor_attributes> x,
+ Conv_wgrad_attributes attributes) {
+ // Make required output tensors
+ auto DW = attributes.outputs[Conv_wgrad_attributes::output_names::DW] = output_tensor(attributes.name + "::DW");
+
+ // Set inputs
+ attributes.inputs[Conv_wgrad_attributes::input_names::X] = x;
+ attributes.inputs[Conv_wgrad_attributes::input_names::DY] = dy;
+
+ sub_nodes.emplace_back(std::make_unique<WgradNode>(std::move(attributes), context));
+
+ return DW;
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 2>
+Graph::rmsnorm(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ Rmsnorm_attributes attributes) {
+ // Set outputs
+ auto Y = attributes.outputs[Rmsnorm_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+ std::shared_ptr<Tensor_attributes> INV_VARIANCE = nullptr;
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ INV_VARIANCE = attributes.outputs[Rmsnorm_attributes::output_names::INV_VARIANCE] =
+ output_tensor(attributes.name + "::INV_VARIANCE");
+ }
+ // Set inputs
+ attributes.inputs[Rmsnorm_attributes::input_names::X] = x;
+ attributes.inputs[Rmsnorm_attributes::input_names::SCALE] = scale;
+
+ sub_nodes.emplace_back(std::make_unique<RMSNormNode>(std::move(attributes), context));
+
+ return {Y, INV_VARIANCE};
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::rope(std::shared_ptr<Tensor_attributes> input,
+ std::shared_ptr<Tensor_attributes> freqs,
+ RoPE_attributes attributes) {
+ // RoPE writes to a user-bound buffer (no longer a virtual workspace tensor),
+ // because the rotated Q/K need to be saved across fwd→bwd for the bwd to consume them
+ // as inputs to SDPA bwd.
+ auto OUTPUT = attributes.outputs[RoPE_attributes::output_names::OUTPUT] =
+ output_tensor(attributes.name + "::OUTPUT");
+ OUTPUT->set_is_virtual(false);
+
+ // Set inputs
+ attributes.inputs[RoPE_attributes::input_names::INPUT] = input;
+ attributes.inputs[RoPE_attributes::input_names::FREQS] = freqs;
+
+ sub_nodes.emplace_back(std::make_unique<RoPENode>(std::move(attributes), context));
+
+ return OUTPUT;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::rope_backward(std::shared_ptr<Tensor_attributes> dy,
+ std::shared_ptr<Tensor_attributes> freqs,
+ RoPE_backward_attributes attributes) {
+ // dX is a real (user-bound) tensor by default — symmetric to fwd RoPE's Y output.
+ auto DX = attributes.outputs[RoPE_backward_attributes::output_names::DX] = output_tensor(attributes.name + "::DX");
+ DX->set_is_virtual(false);
+
+ attributes.inputs[RoPE_backward_attributes::input_names::DY] = dy;
+ attributes.inputs[RoPE_backward_attributes::input_names::FREQS] = freqs;
+
+ sub_nodes.emplace_back(std::make_unique<RoPEBackwardNode>(std::move(attributes), context));
+
+ return DX;
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::rmsnorm_backward(std::shared_ptr<Tensor_attributes> dy,
+ std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ std::shared_ptr<Tensor_attributes> inv_variance,
+ Rmsnorm_backward_attributes attributes) {
+ // Set outputs
+ auto DX = attributes.outputs[Rmsnorm_backward_attributes::output_names::DX] =
+ output_tensor(attributes.name + "::DX");
+ auto DScale = attributes.outputs[Rmsnorm_backward_attributes::output_names::DSCALE] =
+ output_tensor(attributes.name + "::Dscale");
+ std::shared_ptr<Tensor_attributes> DBias = nullptr;
+ if (attributes.use_dbias.value_or(true)) {
+ DBias = attributes.outputs[Rmsnorm_backward_attributes::output_names::DBIAS] =
+ output_tensor(attributes.name + "::Dbias");
+ }
+
+ // Set inputs
+ attributes.inputs[Rmsnorm_backward_attributes::input_names::DY] = dy;
+ attributes.inputs[Rmsnorm_backward_attributes::input_names::X] = x;
+ attributes.inputs[Rmsnorm_backward_attributes::input_names::SCALE] = scale;
+ attributes.inputs[Rmsnorm_backward_attributes::input_names::INV_VARIANCE] = inv_variance;
+
+ sub_nodes.emplace_back(std::make_unique<DRMSNormNode>(std::move(attributes), context));
+
+ return {DX, DScale, DBias};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 2>
+Graph::sdpa(std::shared_ptr<Tensor_attributes> q,
+ std::shared_ptr<Tensor_attributes> k,
+ std::shared_ptr<Tensor_attributes> v,
+ SDPA_attributes attributes) {
+ if (attributes.mma_core_mode == DataType_t::NOT_SET) {
+ attributes._set_mma_core_mode(DataType_t::HALF);
+ }
+
+ // Call internal implementation and return only the O and Stats outputs for backward compatibility
+ auto internal_result = sdpa_internal(q, k, v, std::move(attributes));
+ return {internal_result.O, internal_result.Stats};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 4>
+Graph::sdpa_fp8(std::shared_ptr<Tensor_attributes> q,
+ std::shared_ptr<Tensor_attributes> k,
+ std::shared_ptr<Tensor_attributes> v,
+ std::shared_ptr<Tensor_attributes> descale_q,
+ std::shared_ptr<Tensor_attributes> descale_k,
+ std::shared_ptr<Tensor_attributes> descale_v,
+ std::shared_ptr<Tensor_attributes> descale_s,
+ std::shared_ptr<Tensor_attributes> scale_s,
+ std::shared_ptr<Tensor_attributes> scale_o,
+ SDPA_fp8_attributes attributes) {
+ if (attributes.mma_core_mode == DataType_t::NOT_SET) {
+ attributes._set_mma_core_mode(DataType_t::FP8_E4M3);
+ }
+
+ // Set FP8 scaling inputs
+ attributes.inputs[SDPA_fp8_attributes::input_names::Descale_Q] = descale_q;
+ attributes.inputs[SDPA_fp8_attributes::input_names::Descale_K] = descale_k;
+ attributes.inputs[SDPA_fp8_attributes::input_names::Descale_V] = descale_v;
+ attributes.inputs[SDPA_fp8_attributes::input_names::Descale_S] = descale_s;
+ attributes.inputs[SDPA_fp8_attributes::input_names::Scale_S] = scale_s;
+ attributes.inputs[SDPA_fp8_attributes::input_names::Scale_O] = scale_o;
+
+ // Call internal implementation and return {Output, Stats, Amax_S, Amax_O} as array for backward compatibility
+ auto internal_result = sdpa_internal(q, k, v, std::move(attributes));
+ return {internal_result.O, internal_result.Stats, internal_result.Amax_S, internal_result.Amax_O};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::sdpa_fp8(std::shared_ptr<Tensor_attributes> q,
+ std::shared_ptr<Tensor_attributes> k,
+ std::shared_ptr<Tensor_attributes> v,
+ std::shared_ptr<Tensor_attributes> descale_q,
+ std::shared_ptr<Tensor_attributes> descale_k,
+ std::shared_ptr<Tensor_attributes> descale_v,
+ SDPA_fp8_attributes attributes) {
+ if (attributes.mma_core_mode == DataType_t::NOT_SET) {
+ attributes._set_mma_core_mode(DataType_t::FP8_E4M3);
+ }
+
+ // Set FP8 scaling inputs
+ attributes.inputs[SDPA_fp8_attributes::input_names::Descale_Q] = descale_q;
+ attributes.inputs[SDPA_fp8_attributes::input_names::Descale_K] = descale_k;
+ attributes.inputs[SDPA_fp8_attributes::input_names::Descale_V] = descale_v;
+
+ // Call internal implementation and return {Output, Stats, Amax_O} as array for backward compatibility
+ auto internal_result = sdpa_internal(q, k, v, std::move(attributes));
+ return {internal_result.O, internal_result.Stats, internal_result.Amax_O};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 7>
+Graph::sdpa_fp8_backward(std::shared_ptr<Tensor_attributes> q,
+ std::shared_ptr<Tensor_attributes> k,
+ std::shared_ptr<Tensor_attributes> v,
+ std::shared_ptr<Tensor_attributes> o,
+ std::shared_ptr<Tensor_attributes> dO,
+ std::shared_ptr<Tensor_attributes> Stats,
+ std::shared_ptr<Tensor_attributes> descale_q,
+ std::shared_ptr<Tensor_attributes> descale_k,
+ std::shared_ptr<Tensor_attributes> descale_v,
+ std::shared_ptr<Tensor_attributes> descale_o,
+ std::shared_ptr<Tensor_attributes> descale_do,
+ std::shared_ptr<Tensor_attributes> descale_s,
+ std::shared_ptr<Tensor_attributes> descale_dp,
+ std::shared_ptr<Tensor_attributes> scale_s,
+ std::shared_ptr<Tensor_attributes> scale_dq,
+ std::shared_ptr<Tensor_attributes> scale_dk,
+ std::shared_ptr<Tensor_attributes> scale_dv,
+ std::shared_ptr<Tensor_attributes> scale_dp,
+ SDPA_fp8_backward_attributes attributes) {
+ // Make required output tensors
+ auto dQ = attributes.outputs[SDPA_fp8_backward_attributes::output_names::dQ] =
+ output_tensor(attributes.name + "::dQ");
+ auto dK = attributes.outputs[SDPA_fp8_backward_attributes::output_names::dK] =
+ output_tensor(attributes.name + "::dK");
+ auto dV = attributes.outputs[SDPA_fp8_backward_attributes::output_names::dV] =
+ output_tensor(attributes.name + "::dV");
+ auto Amax_dQ = attributes.outputs[SDPA_fp8_backward_attributes::output_names::Amax_dQ] =
+ output_tensor(attributes.name + "::Amax_dQ");
+ auto Amax_dK = attributes.outputs[SDPA_fp8_backward_attributes::output_names::Amax_dK] =
+ output_tensor(attributes.name + "::Amax_dK");
+ auto Amax_dV = attributes.outputs[SDPA_fp8_backward_attributes::output_names::Amax_dV] =
+ output_tensor(attributes.name + "::Amax_dV");
+ auto Amax_dP = attributes.outputs[SDPA_fp8_backward_attributes::output_names::Amax_dP] =
+ output_tensor(attributes.name + "::Amax_dP");
+
+ // Set inputs
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Q] = q;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::K] = k;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::V] = v;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::O] = o;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Stats] = Stats;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::dO] = dO;
+
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_Q] = descale_q;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_K] = descale_k;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_V] = descale_v;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_S] = descale_s;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_O] = descale_o;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_dO] = descale_do;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_dP] = descale_dp;
+
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Scale_dQ] = scale_dq;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Scale_dK] = scale_dk;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Scale_dV] = scale_dv;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Scale_S] = scale_s;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Scale_dP] = scale_dp;
+
+ sub_nodes.emplace_back(std::make_unique<SDPAFP8BackwardNode>(std::move(attributes), context));
+
+ return {dQ, dK, dV, Amax_dQ, Amax_dK, Amax_dV, Amax_dP};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 6>
+Graph::sdpa_fp8_backward(std::shared_ptr<Tensor_attributes> q,
+ std::shared_ptr<Tensor_attributes> q_T,
+ std::shared_ptr<Tensor_attributes> k,
+ std::shared_ptr<Tensor_attributes> k_T,
+ std::shared_ptr<Tensor_attributes> v,
+ std::shared_ptr<Tensor_attributes> o_f16,
+ std::shared_ptr<Tensor_attributes> dO_f16,
+ std::shared_ptr<Tensor_attributes> dO,
+ std::shared_ptr<Tensor_attributes> dO_T,
+ std::shared_ptr<Tensor_attributes> Stats,
+ std::shared_ptr<Tensor_attributes> descale_q,
+ std::shared_ptr<Tensor_attributes> descale_q_T,
+ std::shared_ptr<Tensor_attributes> descale_k,
+ std::shared_ptr<Tensor_attributes> descale_k_T,
+ std::shared_ptr<Tensor_attributes> descale_v,
+ std::shared_ptr<Tensor_attributes> descale_dO,
+ std::shared_ptr<Tensor_attributes> descale_dO_T,
+ SDPA_fp8_backward_attributes attributes) {
+ // Make required output tensors
+ auto dQ = attributes.outputs[SDPA_fp8_backward_attributes::output_names::dQ] =
+ output_tensor(attributes.name + "::dQ");
+ auto dK = attributes.outputs[SDPA_fp8_backward_attributes::output_names::dK] =
+ output_tensor(attributes.name + "::dK");
+ auto dV = attributes.outputs[SDPA_fp8_backward_attributes::output_names::dV] =
+ output_tensor(attributes.name + "::dV");
+ auto Amax_dQ = attributes.outputs[SDPA_fp8_backward_attributes::output_names::Amax_dQ] =
+ output_tensor(attributes.name + "::Amax_dQ");
+ auto Amax_dK = attributes.outputs[SDPA_fp8_backward_attributes::output_names::Amax_dK] =
+ output_tensor(attributes.name + "::Amax_dK");
+ auto Amax_dV = attributes.outputs[SDPA_fp8_backward_attributes::output_names::Amax_dV] =
+ output_tensor(attributes.name + "::Amax_dV");
+
+ // Set inputs
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Q] = q;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::K] = k;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::V] = v;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Q_T] = q_T;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::K_T] = k_T;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::O] = o_f16;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::dO_f16] = dO_f16;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::dO_T] = dO_T;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Stats] = Stats;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::dO] = dO;
+
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_Q] = descale_q;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_Q_T] = descale_q_T;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_K] = descale_k;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_K_T] = descale_k_T;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_V] = descale_v;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_dO] = descale_dO;
+ attributes.inputs[SDPA_fp8_backward_attributes::input_names::Descale_dO_T] = descale_dO_T;
+
+ sub_nodes.emplace_back(std::make_unique<SDPAFP8BackwardNode>(std::move(attributes), context));
+
+ return {dQ, dK, dV, Amax_dQ, Amax_dK, Amax_dV};
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 3>
+Graph::sdpa_backward(std::shared_ptr<Tensor_attributes> q,
+ std::shared_ptr<Tensor_attributes> k,
+ std::shared_ptr<Tensor_attributes> v,
+ std::shared_ptr<Tensor_attributes> o,
+ std::shared_ptr<Tensor_attributes> dO,
+ std::shared_ptr<Tensor_attributes> stats,
+ SDPA_backward_attributes attributes) {
+ // Set inputs
+ attributes.inputs[SDPA_backward_attributes::input_names::Q] = q;
+ attributes.inputs[SDPA_backward_attributes::input_names::K] = k;
+ attributes.inputs[SDPA_backward_attributes::input_names::V] = v;
+ attributes.inputs[SDPA_backward_attributes::input_names::O] = o;
+ attributes.inputs[SDPA_backward_attributes::input_names::dO] = dO;
+ attributes.inputs[SDPA_backward_attributes::input_names::Stats] = stats;
+
+ // Make required output tensors
+ auto dQ = attributes.outputs[SDPA_backward_attributes::output_names::dQ] = output_tensor(attributes.name + "::dQ");
+ auto dK = attributes.outputs[SDPA_backward_attributes::output_names::dK] = output_tensor(attributes.name + "::dK");
+ auto dV = attributes.outputs[SDPA_backward_attributes::output_names::dV] = output_tensor(attributes.name + "::dV");
+
+ sub_nodes.emplace_back(std::make_unique<CompositeSDPABackwardNode>(std::move(attributes), context));
+
+ return {dQ, dK, dV};
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::slice(std::shared_ptr<Tensor_attributes> input, Slice_attributes attributes) {
+ attributes.inputs[Slice_attributes::input_names::X] = input;
+ auto Y = attributes.outputs[Slice_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+
+ sub_nodes.emplace_back(std::make_unique<SliceNode>(std::move(attributes), context));
+ return Y;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::transpose(std::shared_ptr<Tensor_attributes> input, Transpose_attributes attributes) {
+ attributes.inputs[Transpose_attributes::input_names::X] = input;
+ auto Y = attributes.outputs[Transpose_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+
+ sub_nodes.emplace_back(std::make_unique<TransposeNode>(std::move(attributes), context));
+ return Y;
+}
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 2>
+Graph::block_scale_quantize(std::shared_ptr<Tensor_attributes> x, Block_scale_quantize_attributes attributes) {
+ // Set outputs
+ auto Y = attributes.outputs[Block_scale_quantize_attributes::output_names::Y] =
+ output_tensor(attributes.name + "::Y");
+ auto scale = attributes.outputs[Block_scale_quantize_attributes::output_names::scale] =
+ output_tensor(attributes.name + "::scale");
+
+ // Set inputs
+ attributes.inputs[Block_scale_quantize_attributes::input_names::X] = x;
+
+ sub_nodes.emplace_back(std::make_unique<BlockScaleQuantizeNode>(std::move(attributes), context));
+
+ return {Y, scale};
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::block_scale_dequantize(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ Block_scale_dequantize_attributes attributes) {
+ // Set outputs
+ auto Y = attributes.outputs[Block_scale_dequantize_attributes::output_names::Y] =
+ output_tensor(attributes.name + "::Y");
+
+ // Set inputs
+ attributes.inputs[Block_scale_dequantize_attributes::input_names::X] = x;
+ attributes.inputs[Block_scale_dequantize_attributes::input_names::scale] = scale;
+
+ sub_nodes.emplace_back(std::make_unique<BlockScaleDequantizeNode>(std::move(attributes), context));
+
+ return Y;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::concatenate(std::vector<std::shared_ptr<Tensor_attributes>> x, Concatenate_attributes attributes) {
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+
+ // Set outputs
+ auto Y = attributes.outputs[Concatenate_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+
+ // Set inputs
+ for (auto &element : x) {
+ attributes.inputs.push_back(element);
+ }
+
+ sub_nodes.emplace_back(std::make_unique<ConcatenateNode>(std::move(attributes), context));
+
+ return Y;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::moe_grouped_matmul(std::shared_ptr<Tensor_attributes> token,
+ std::shared_ptr<Tensor_attributes> weight,
+ std::shared_ptr<Tensor_attributes> first_token_offset,
+ std::shared_ptr<Tensor_attributes> token_index,
+ std::shared_ptr<Tensor_attributes> token_ks,
+ Moe_grouped_matmul_attributes attributes) {
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+
+ auto output = attributes.outputs[Moe_grouped_matmul_attributes::output_names::Output] =
+ output_tensor(attributes.name + "::Output");
+
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::Token] = token;
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::Weight] = weight;
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::FirstTokenOffset] = first_token_offset;
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::TokenIndex] = token_index;
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::TokenKs] = token_ks;
+
+ sub_nodes.emplace_back(std::make_unique<MoeGroupedMatmulNode>(std::move(attributes), context));
+
+ return output;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+Graph::moe_grouped_matmul_bwd(std::shared_ptr<Tensor_attributes> doutput,
+ std::shared_ptr<Tensor_attributes> token,
+ std::shared_ptr<Tensor_attributes> first_token_offset,
+ Moe_grouped_matmul_bwd_attributes attributes) {
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+
+ auto dweight = attributes.outputs[Moe_grouped_matmul_bwd_attributes::output_names::DWeight] =
+ output_tensor(attributes.name + "::DWeight");
+
+ attributes.inputs[Moe_grouped_matmul_bwd_attributes::input_names::DOutput] = doutput;
+ attributes.inputs[Moe_grouped_matmul_bwd_attributes::input_names::Token] = token;
+ attributes.inputs[Moe_grouped_matmul_bwd_attributes::input_names::FirstTokenOffset] = first_token_offset;
+
+ sub_nodes.emplace_back(std::make_unique<MoeGroupedMatmulBwdNode>(std::move(attributes), context));
+
+ return dweight;
+}
+
+static inline std::ostream &
+operator<<(std::ostream &os, Graph const &graph) {
+ os << graph.print();
+ return os;
+}
+
+} // namespace cudnn_frontend::graph
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/graph_properties.h b/deps/cudnn-frontend/include/cudnn_frontend/graph_properties.h
new file mode 100644
index 0000000..c5dd2a4
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/graph_properties.h
@@ -0,0 +1,3143 @@
+
+#pragma once
+
+#include <cerrno>
+#include <cstdlib>
+#include <iostream>
+#include <memory>
+#include <numeric>
+#include <optional>
+#include <unordered_map>
+#include <vector>
+#include <limits.h>
+
+#include "context.h"
+
+#include "../cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+inline std::optional<float>
+get_rescale_threshold_from_env() {
+ auto const* env_value = get_environment("CUDNN_RESCALE_THRESHOLD");
+ if (env_value == nullptr || env_value[0] == '\0') {
+ return std::nullopt;
+ }
+
+ errno = 0;
+ char* end = nullptr;
+ auto value = std::strtof(env_value, &end);
+ if (env_value == end || (end != nullptr && *end != '\0') || errno == ERANGE) {
+ return std::nullopt;
+ }
+
+ return value;
+}
+
+using managed_backend_descriptor_t = std::vector<ManagedOpaqueDescriptor>;
+
+// Enum to distinguish between runtime parameters and compile-time constants
+enum class ScalarType {
+ RUNTIME_PARAM, // Value provided at execution time (can change)
+ COMPILE_TIME_CONST // Value baked into graph (fixed, optimizable)
+};
+
+// simple structure to hold all properties of a tensor.
+// Each property has a getter setter.
+class Tensor_attributes {
+ public:
+ using uid_t = int64_t;
+
+ // There are two usecases of pass by value tensors:
+ // 1. Fused scalar constants
+ // 2. Scalar passed during execution
+ // In approach 1, users provide a value to embed into the graph.
+ // In approach 2, users set is_pass_by_value boolean and then pass a pointer to scalar value with execute() API.
+ // A closed set of types that are allowed to be passed by value.
+ using pass_by_values_t = std::variant<int64_t, int32_t, half, float, double, nv_bfloat16>;
+
+ error_t
+ validate() const {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ dim.empty(), error_code_t::ATTRIBUTE_NOT_SET, "Tensor '" + name + "' dims not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ stride.empty(), error_code_t::ATTRIBUTE_NOT_SET, "Tensor '" + name + "' strides not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(dim.size() != stride.size(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Tensor '" + name + "' does not equal dimensionality in dim and stride.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ is_virtual && is_pass_by_value,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Tensor '" + name + "' can't be both virutal and pass_by_value at the same time.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ pass_by_value.has_value() & (!is_pass_by_value),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Tensor '" + name + "' can't be a fused scalar and not a pass_by_value tensor at the same time.");
+
+ // Validate compile-time constant constraints
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ has_compile_time_constant && !is_pass_by_value,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Tensor '" + name + "' with compile-time constant must have is_pass_by_value=true.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_compile_time_constant && is_virtual,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Tensor '" + name + "' can't be both compile-time constant and virtual.");
+
+ // Can't have both compile-time constant and runtime parameter
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ has_compile_time_constant && pass_by_value.has_value(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Tensor '" + name + "' can't have both compile-time constant and runtime pass_by_value.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ has_ragged_offset_multiplier() && !ragged_offset,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Tensor '" + name + "' with ragged offset multiplier must also have a ragged offset tensor.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(ragged_offset_multiplier <= 0,
+ error_code_t::INVALID_VALUE,
+ "Tensor '" + name + "' ragged offset multiplier must be positive.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ private:
+ template <typename>
+ friend class Attributes;
+
+ std::string name;
+ DataType_t data_type = DataType_t::NOT_SET;
+ std::vector<int64_t> dim = {};
+ std::vector<int64_t> stride = {};
+ bool is_virtual = false;
+
+ std::optional<pass_by_values_t> pass_by_value = std::nullopt;
+ bool is_pass_by_value = false;
+
+ // Compile-time constant support (distinct from pass_by_value, which is for runtime parameters)
+ bool has_compile_time_constant = false;
+ std::optional<pass_by_values_t> compile_time_constant_value = std::nullopt;
+
+ TensorReordering_t reordering_type = TensorReordering_t::NONE;
+ uid_t uid = 0;
+ bool uid_assigned = false;
+
+ std::shared_ptr<Tensor_attributes> ragged_offset;
+ int64_t ragged_offset_multiplier = 1;
+ int64_t alignment = 16; // Default to 16 bytes
+ int64_t vector_count = 1; // Default to 1 (no vectorization)
+ int64_t vector_dimension = -1; // Default to -1 (not set)
+
+ auto
+ fill_from_context(detail::Context const& context) -> Tensor_attributes& {
+ if (get_data_type() == DataType_t::NOT_SET) {
+ if (get_is_virtual()) {
+ set_data_type(context.get_intermediate_data_type());
+ } else {
+ set_data_type(context.get_io_data_type());
+ }
+ }
+ return *this;
+ }
+
+ public:
+ // Serialization functions
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ friend void
+ to_json(nlohmann::json& j, const Tensor_attributes& ta);
+ friend void
+ from_json(const nlohmann::json& j, Tensor_attributes& ta);
+#endif
+
+ Tensor_attributes() = default;
+
+ Tensor_attributes(float const& scalar) {
+ pass_by_value = scalar;
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::FLOAT;
+ }
+
+ Tensor_attributes(half const& scalar) {
+ pass_by_value = scalar;
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::HALF;
+ }
+
+ Tensor_attributes(nv_bfloat16 const& scalar) {
+ pass_by_value = scalar;
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::BFLOAT16;
+ }
+
+ Tensor_attributes(int32_t const& scalar) {
+ pass_by_value = scalar;
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::INT32;
+ }
+
+ Tensor_attributes(int64_t const& scalar) {
+ pass_by_value = scalar;
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::INT64;
+ }
+
+ Tensor_attributes(double const& scalar) {
+ pass_by_value = scalar;
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::DOUBLE;
+ }
+
+ // Constructors with ScalarType for compile-time constant or runtime parameter control
+ Tensor_attributes(float const& scalar, ScalarType scalar_type) {
+ if (scalar_type == ScalarType::COMPILE_TIME_CONST) {
+ compile_time_constant_value = scalar;
+ has_compile_time_constant = true;
+ } else {
+ pass_by_value = scalar;
+ }
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::FLOAT;
+ }
+
+ Tensor_attributes(half const& scalar, ScalarType scalar_type) {
+ if (scalar_type == ScalarType::COMPILE_TIME_CONST) {
+ compile_time_constant_value = scalar;
+ has_compile_time_constant = true;
+ } else {
+ pass_by_value = scalar;
+ }
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::HALF;
+ }
+
+ Tensor_attributes(nv_bfloat16 const& scalar, ScalarType scalar_type) {
+ if (scalar_type == ScalarType::COMPILE_TIME_CONST) {
+ compile_time_constant_value = scalar;
+ has_compile_time_constant = true;
+ } else {
+ pass_by_value = scalar;
+ }
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::BFLOAT16;
+ }
+
+ Tensor_attributes(int32_t const& scalar, ScalarType scalar_type) {
+ if (scalar_type == ScalarType::COMPILE_TIME_CONST) {
+ compile_time_constant_value = scalar;
+ has_compile_time_constant = true;
+ } else {
+ pass_by_value = scalar;
+ }
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::INT32;
+ }
+
+ Tensor_attributes(int64_t const& scalar, ScalarType scalar_type) {
+ if (scalar_type == ScalarType::COMPILE_TIME_CONST) {
+ compile_time_constant_value = scalar;
+ has_compile_time_constant = true;
+ } else {
+ pass_by_value = scalar;
+ }
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::INT64;
+ }
+
+ Tensor_attributes(double const& scalar, ScalarType scalar_type) {
+ if (scalar_type == ScalarType::COMPILE_TIME_CONST) {
+ compile_time_constant_value = scalar;
+ has_compile_time_constant = true;
+ } else {
+ pass_by_value = scalar;
+ }
+ is_pass_by_value = true;
+ dim = stride = {1};
+ data_type = DataType_t::DOUBLE;
+ }
+
+ std::string
+ get_name() const {
+ return name;
+ }
+
+ auto
+ set_name(std::string const& value) -> Tensor_attributes& {
+ name = value;
+ return *this;
+ }
+
+ DataType_t
+ get_data_type() const {
+ return data_type;
+ }
+
+ auto
+ set_data_type(DataType_t const value) -> Tensor_attributes& {
+ data_type = value;
+ return *this;
+ }
+
+ std::vector<int64_t>
+ get_dim() const {
+ return dim;
+ }
+
+ auto
+ set_dim(std::vector<int64_t> const& value) -> Tensor_attributes& {
+ dim = value;
+ return *this;
+ }
+
+ int64_t
+ get_volume() const {
+ int64_t volume = 1ul;
+ for (int64_t d : dim) {
+ volume *= d;
+ }
+ return volume;
+ }
+
+ std::vector<int64_t>
+ get_stride() const {
+ return stride;
+ }
+
+ auto
+ set_stride(std::vector<int64_t> const& value) -> Tensor_attributes& {
+ stride = value;
+ return *this;
+ }
+
+ bool
+ get_is_virtual() const {
+ return is_virtual;
+ }
+
+ std::shared_ptr<Tensor_attributes>
+ get_ragged_offset() {
+ return ragged_offset;
+ }
+
+ int64_t
+ get_ragged_offset_multiplier() const {
+ return ragged_offset_multiplier;
+ }
+
+ bool
+ has_ragged_offset_multiplier() const {
+ return ragged_offset_multiplier != 1;
+ }
+
+ auto
+ set_is_virtual(bool const value) -> Tensor_attributes& {
+ is_virtual = value;
+ return *this;
+ }
+
+ auto
+ set_output(bool const value) -> Tensor_attributes& {
+ return set_is_virtual(!value);
+ }
+
+ std::optional<pass_by_values_t>
+ get_pass_by_value() const {
+ return pass_by_value;
+ }
+
+ bool
+ get_is_pass_by_value() const {
+ return is_pass_by_value;
+ }
+
+ auto
+ set_is_pass_by_value(bool const value) -> Tensor_attributes& {
+ is_pass_by_value = value;
+ return *this;
+ }
+
+ // Compile-time constant accessors
+ bool
+ get_has_compile_time_constant() const {
+ return has_compile_time_constant;
+ }
+
+ std::optional<pass_by_values_t>
+ get_compile_time_constant() const {
+ return compile_time_constant_value;
+ }
+
+ auto
+ set_compile_time_constant(pass_by_values_t const& value) -> Tensor_attributes& {
+ compile_time_constant_value = value;
+ has_compile_time_constant = true;
+ if (!is_pass_by_value) {
+ is_pass_by_value = true;
+ }
+ return *this;
+ }
+
+ auto
+ set_as_runtime_parameter() -> Tensor_attributes& {
+ is_pass_by_value = true;
+ has_compile_time_constant = false;
+ compile_time_constant_value = std::nullopt;
+ return *this;
+ }
+
+ TensorReordering_t
+ get_reordering_type() const {
+ return reordering_type;
+ }
+
+ auto
+ set_reordering_type(TensorReordering_t const value) -> Tensor_attributes& {
+ reordering_type = value;
+ return *this;
+ }
+
+ int64_t
+ get_alignment() const {
+ return alignment;
+ }
+
+ auto
+ set_alignment(int64_t const value) -> Tensor_attributes& {
+ alignment = value;
+ return *this;
+ }
+
+ int64_t
+ get_vector_count() const {
+ return vector_count;
+ }
+
+ int64_t
+ get_vector_dimension() const {
+ return vector_dimension;
+ }
+
+ auto
+ set_vector_count_and_dimension(int64_t const count, int64_t const dimension) -> Tensor_attributes& {
+ vector_count = count;
+ vector_dimension = dimension;
+ return *this;
+ }
+
+ uid_t
+ get_uid() const {
+ return uid;
+ }
+
+ uid_t
+ has_uid() const {
+ return uid_assigned;
+ }
+
+ auto
+ clear_uid(void) -> Tensor_attributes& {
+ uid = 0;
+ uid_assigned = false;
+ return *this;
+ }
+
+ auto
+ set_uid(uid_t value) -> Tensor_attributes& {
+ uid = value;
+ uid_assigned = true;
+ return *this;
+ }
+
+ auto
+ set_ragged_offset(std::shared_ptr<Tensor_attributes> const& value) -> Tensor_attributes& {
+ ragged_offset = value;
+ return *this;
+ }
+
+ auto
+ set_ragged_offset_multiplier(int64_t value) -> Tensor_attributes& {
+ ragged_offset_multiplier = value;
+ return *this;
+ }
+};
+
+class Batchnorm_attributes;
+class Batchnorm_backward_attributes;
+class Concatenate_attributes;
+
+template <typename DerivedT>
+class Attributes {
+ DerivedT&
+ self() {
+ return *static_cast<DerivedT*>(this);
+ }
+ DerivedT const&
+ self() const {
+ return *static_cast<DerivedT const*>(this);
+ }
+
+ protected:
+ std::vector<int64_t>
+ get_non_virtual_uids() const {
+ std::vector<int64_t> non_virtual_uids;
+ auto derived = static_cast<DerivedT const*>(this);
+
+ // Compile-time constants are excluded from the variant pack
+ auto should_be_in_variant_pack = [](std::shared_ptr<Tensor_attributes> const& tensor) {
+ return tensor && tensor->get_is_virtual() == false && !tensor->get_has_compile_time_constant();
+ };
+
+ if constexpr (std::is_same_v<DerivedT, Concatenate_attributes>) {
+ for (auto tensor : derived->inputs) {
+ if (should_be_in_variant_pack(tensor)) {
+ non_virtual_uids.push_back(tensor->get_uid());
+ if (auto ragged_offset = tensor->get_ragged_offset()) {
+ non_virtual_uids.push_back(ragged_offset->get_uid());
+ }
+ }
+ }
+ } else {
+ for (auto& [name, tensor] : derived->inputs) {
+ (void)name;
+ if (should_be_in_variant_pack(tensor)) {
+ non_virtual_uids.push_back(tensor->get_uid());
+ if (auto ragged_offset = tensor->get_ragged_offset()) {
+ non_virtual_uids.push_back(ragged_offset->get_uid());
+ }
+ }
+ }
+ }
+
+ for (auto& [name, tensor] : derived->outputs) {
+ (void)name;
+ if (should_be_in_variant_pack(tensor)) {
+ non_virtual_uids.push_back(tensor->get_uid());
+ if (auto ragged_offset = tensor->get_ragged_offset()) {
+ non_virtual_uids.push_back(ragged_offset->get_uid());
+ }
+ }
+ }
+
+ // Handle special case of BN where peer_stats is also an input
+ if constexpr (std::is_same_v<DerivedT, Batchnorm_attributes> ||
+ std::is_same_v<DerivedT, Batchnorm_backward_attributes>) {
+ for (auto& tensor : derived->peer_stats) {
+ if (should_be_in_variant_pack(tensor)) {
+ non_virtual_uids.push_back(tensor->get_uid());
+ if (auto ragged_offset = tensor->get_ragged_offset()) {
+ non_virtual_uids.push_back(ragged_offset->get_uid());
+ }
+ }
+ }
+ }
+
+ return non_virtual_uids;
+ }
+
+ public:
+ error_t
+ fill_pass_by_value(std::unordered_map<Tensor_attributes::uid_t, Tensor_attributes::pass_by_values_t>&
+ tensor_to_pass_by_value) const {
+ auto derived = static_cast<DerivedT const*>(this);
+ if constexpr (std::is_same_v<DerivedT, Concatenate_attributes>) {
+ for (auto& tensor : derived->inputs) {
+ if (tensor && tensor->get_pass_by_value().has_value()) {
+ tensor_to_pass_by_value.emplace(tensor->get_uid(), tensor->get_pass_by_value().value());
+ }
+ }
+ } else {
+ for (auto& [name, tensor] : derived->inputs) {
+ (void)name;
+ if (tensor && tensor->get_pass_by_value().has_value()) {
+ tensor_to_pass_by_value.emplace(tensor->get_uid(), tensor->get_pass_by_value().value());
+ }
+ }
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ void
+ fill_from_context(detail::Context const& context) {
+ auto derived = static_cast<DerivedT const*>(this);
+
+ if constexpr (std::is_same_v<DerivedT, Concatenate_attributes>) {
+ for (auto& tensor : derived->inputs) {
+ if (tensor) {
+ tensor->fill_from_context(context);
+ }
+ }
+ } else {
+ for (auto& [name, tensor] : derived->inputs) {
+ (void)name;
+ if (tensor) {
+ tensor->fill_from_context(context);
+ }
+ }
+ }
+ for (auto& [name, tensor] : derived->outputs) {
+ (void)name;
+ if (tensor) {
+ tensor->fill_from_context(context);
+ }
+ }
+ // Handle special case of BN where peer_stats is also an input
+ if constexpr (std::is_same_v<DerivedT, Batchnorm_attributes> ||
+ std::is_same_v<DerivedT, Batchnorm_backward_attributes>) {
+ for (auto& tensor : derived->peer_stats) {
+ if (tensor) {
+ tensor->fill_from_context(context);
+ }
+ }
+ }
+
+ if (compute_data_type == DataType_t::NOT_SET) {
+ set_compute_data_type(context.get_compute_data_type());
+ }
+
+ // Infer shape and stride for fused scalars (runtime params and compile-time constants).
+ // Fused scalars expand to match the dimensionality of non-scalar tensors; if all are scalars, keep 1D.
+ auto is_fused_scalar = [](std::shared_ptr<Tensor_attributes> const& tensor) {
+ return tensor && (tensor->get_pass_by_value().has_value() || tensor->get_has_compile_time_constant());
+ };
+
+ int64_t number_of_dims = 1;
+ if constexpr (std::is_same_v<DerivedT, Concatenate_attributes>) {
+ for (auto tensor : derived->inputs) {
+ if (tensor && !is_fused_scalar(tensor)) {
+ number_of_dims = tensor->get_dim().size();
+ break;
+ }
+ }
+ } else {
+ for (auto [name, tensor] : derived->inputs) {
+ (void)name;
+ if (tensor && !is_fused_scalar(tensor)) {
+ number_of_dims = tensor->get_dim().size();
+ break;
+ }
+ }
+ }
+
+ // If number of dims is still 1, try to see if user set output dims.
+ if (number_of_dims == 1) {
+ for (auto [name, tensor] : derived->outputs) {
+ (void)name;
+ if (tensor && !is_fused_scalar(tensor)) {
+ number_of_dims = tensor->get_dim().size();
+ break;
+ }
+ }
+ }
+
+ // Expand fused scalar dimensions to match the number of dims of non-scalar tensors
+ if constexpr (std::is_same_v<DerivedT, Concatenate_attributes>) {
+ for (auto tensor : derived->inputs) {
+ if (is_fused_scalar(tensor)) {
+ tensor->set_dim(std::vector<int64_t>(number_of_dims, 1));
+ tensor->set_stride(std::vector<int64_t>(number_of_dims, 1));
+ }
+ }
+ } else {
+ for (auto [name, tensor] : derived->inputs) {
+ (void)name;
+ if (is_fused_scalar(tensor)) {
+ tensor->set_dim(std::vector<int64_t>(number_of_dims, 1));
+ tensor->set_stride(std::vector<int64_t>(number_of_dims, 1));
+ }
+ }
+ }
+ }
+
+ std::string name;
+ DataType_t compute_data_type = DataType_t::NOT_SET;
+
+ DerivedT&
+ set_name(std::string const& value) {
+ name = value;
+ return self();
+ }
+
+ DerivedT&
+ set_compute_data_type(DataType_t value) {
+ compute_data_type = value;
+ return self();
+ }
+};
+
+class BN_finalize_attributes : public Attributes<BN_finalize_attributes> {
+ friend class Attributes<BN_finalize_attributes>;
+ friend class BatchNormFinalizeNode;
+ friend class Graph;
+
+ public:
+ enum class input_names {
+ SUM,
+ SQ_SUM,
+ SCALE,
+ BIAS,
+ EPSILON,
+ ACCUM_COUNT,
+ PREV_RUNNING_MEAN,
+ PREV_RUNNING_VAR,
+ MOMENTUM
+ };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { EQ_SCALE, EQ_BIAS, MEAN, INV_VARIANCE, NEXT_RUNNING_MEAN, NEXT_RUNNING_VAR };
+
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(BN_finalize_attributes, name, compute_data_type, inputs, outputs)
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+
+ BN_finalize_attributes&
+ set_previous_running_stats(std::shared_ptr<Tensor_attributes>& mean,
+ std::shared_ptr<Tensor_attributes>& variance,
+ std::shared_ptr<Tensor_attributes>& momentum) {
+ inputs[BN_finalize_attributes::input_names::PREV_RUNNING_MEAN] = mean;
+ inputs[BN_finalize_attributes::input_names::PREV_RUNNING_VAR] = variance;
+ inputs[BN_finalize_attributes::input_names::MOMENTUM] = momentum;
+ return *this;
+ }
+};
+
+class Genstats_attributes : public Attributes<Genstats_attributes> {
+ friend class Attributes<Genstats_attributes>;
+ friend class GenstatsNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { X };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+
+ enum class output_names { SUM, SQ_SUM };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Genstats_attributes, name, compute_data_type, inputs, outputs)
+};
+
+class Conv_fprop_attributes : public Attributes<Conv_fprop_attributes> {
+ friend class Attributes<Conv_fprop_attributes>;
+ friend class ConvolutionNode;
+ friend class Graph;
+
+ std::vector<int64_t> pre_padding;
+ std::vector<int64_t> post_padding;
+ std::vector<int64_t> stride;
+ std::vector<int64_t> dilation;
+
+ ConvolutionMode_t math_mode = ConvolutionMode_t::CROSS_CORRELATION;
+
+ public:
+ enum class input_names { X, W };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Conv_fprop_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ pre_padding,
+ post_padding,
+ stride,
+ dilation,
+ math_mode)
+
+ ConvolutionMode_t
+ get_convolution_mode() const {
+ return math_mode;
+ }
+
+ std::vector<int64_t>
+ get_pre_padding() const {
+ return pre_padding;
+ }
+
+ std::vector<int64_t>
+ get_post_padding() const {
+ return post_padding;
+ }
+
+ Conv_fprop_attributes&
+ set_padding(std::vector<int64_t> value) {
+ pre_padding = value;
+ post_padding = value;
+ return *this;
+ }
+
+ Conv_fprop_attributes&
+ set_pre_padding(std::vector<int64_t> value) {
+ pre_padding = value;
+ return *this;
+ }
+
+ Conv_fprop_attributes&
+ set_post_padding(std::vector<int64_t> value) {
+ post_padding = value;
+ return *this;
+ }
+
+ Conv_fprop_attributes&
+ set_convolution_mode(ConvolutionMode_t mode_) {
+ math_mode = mode_;
+ return *this;
+ }
+
+ std::vector<int64_t>
+ get_stride() const {
+ return stride;
+ }
+
+ Conv_fprop_attributes&
+ set_stride(std::vector<int64_t> value) {
+ stride = value;
+ return *this;
+ }
+
+ std::vector<int64_t>
+ get_dilation() const {
+ return dilation;
+ }
+
+ Conv_fprop_attributes&
+ set_dilation(std::vector<int64_t> value) {
+ dilation = value;
+ return *this;
+ }
+};
+
+class Batchnorm_backward_attributes : public Attributes<Batchnorm_backward_attributes> {
+ friend class Attributes<Batchnorm_backward_attributes>;
+ friend class DBNNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { DY, X, SCALE, MEAN, INV_VARIANCE };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ // Only special case where one of the inputs is a vector.
+ std::vector<std::shared_ptr<Tensor_attributes>> peer_stats;
+ enum class output_names { DX, DSCALE, DBIAS };
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Batchnorm_backward_attributes, name, compute_data_type, inputs, peer_stats, outputs)
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+
+ Batchnorm_backward_attributes&
+ set_saved_mean_and_inv_variance(std::shared_ptr<Tensor_attributes> mean,
+ std::shared_ptr<Tensor_attributes> inv_variance) {
+ inputs[Batchnorm_backward_attributes::input_names::MEAN] = mean;
+ inputs[Batchnorm_backward_attributes::input_names::INV_VARIANCE] = inv_variance;
+ return *this;
+ }
+
+ Batchnorm_backward_attributes&
+ set_peer_stats(std::vector<std::shared_ptr<Tensor_attributes>> const& input_peer_stats) {
+ peer_stats = input_peer_stats;
+ return *this;
+ }
+};
+
+class DBN_weight_attributes : public Attributes<DBN_weight_attributes> {
+ friend class Attributes<DBN_weight_attributes>;
+ friend class DBNWeightNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { DY, X, SCALE, MEAN, INV_VARIANCE };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { DSCALE, DBIAS, EQ_BIAS, EQ_SCALE_DY, EQ_SCALE_X };
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(DBN_weight_attributes, name, compute_data_type, inputs, outputs)
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+};
+
+class Conv_dgrad_attributes : public Attributes<Conv_dgrad_attributes> {
+ friend class Attributes<Conv_dgrad_attributes>;
+ friend class DgradNode;
+ friend class Graph;
+
+ std::vector<int64_t> pre_padding;
+ std::vector<int64_t> post_padding;
+ std::vector<int64_t> stride;
+ std::vector<int64_t> dilation;
+
+ ConvolutionMode_t math_mode = ConvolutionMode_t::CROSS_CORRELATION;
+
+ public:
+ enum class input_names { DY, W };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { DX };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Conv_dgrad_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ pre_padding,
+ post_padding,
+ stride,
+ dilation,
+ math_mode)
+
+ ConvolutionMode_t
+ get_convolution_mode() const {
+ return math_mode;
+ }
+
+ std::vector<int64_t>
+ get_pre_padding() const {
+ return pre_padding;
+ }
+
+ std::vector<int64_t>
+ get_post_padding() const {
+ return post_padding;
+ }
+
+ Conv_dgrad_attributes&
+ set_padding(std::vector<int64_t> value) {
+ pre_padding = value;
+ post_padding = value;
+ return *this;
+ }
+
+ Conv_dgrad_attributes&
+ set_pre_padding(std::vector<int64_t> value) {
+ pre_padding = value;
+ return *this;
+ }
+
+ Conv_dgrad_attributes&
+ set_post_padding(std::vector<int64_t> value) {
+ post_padding = value;
+ return *this;
+ }
+
+ std::vector<int64_t>
+ get_stride() const {
+ return stride;
+ }
+
+ Conv_dgrad_attributes&
+ set_convolution_mode(ConvolutionMode_t mode_) {
+ math_mode = mode_;
+ ;
+ return *this;
+ }
+
+ Conv_dgrad_attributes&
+ set_stride(std::vector<int64_t> value) {
+ stride = value;
+ return *this;
+ }
+
+ std::vector<int64_t>
+ get_dilation() const {
+ return dilation;
+ }
+
+ Conv_dgrad_attributes&
+ set_dilation(std::vector<int64_t> value) {
+ dilation = value;
+ return *this;
+ }
+};
+
+class Matmul_fp8_attributes : public Attributes<Matmul_fp8_attributes> {
+ friend class Attributes<Matmul_fp8_attributes>;
+ friend class MatmulFP8Node;
+ friend class INode;
+
+ double padding_value = 0.0;
+
+ public:
+ enum class input_names { Descale_A, Descale_B, A, B, M_override, N_override, K_override, Scale_C };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { C, Amax_C };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Matmul_fp8_attributes, name, compute_data_type, inputs, outputs)
+
+ Matmul_fp8_attributes&
+ set_m_override(std::shared_ptr<Tensor_attributes> const& value) {
+ inputs[input_names::M_override] = value;
+ return *this;
+ }
+
+ Matmul_fp8_attributes&
+ set_n_override(std::shared_ptr<Tensor_attributes> const& value) {
+ inputs[input_names::N_override] = value;
+ return *this;
+ }
+
+ Matmul_fp8_attributes&
+ set_k_override(std::shared_ptr<Tensor_attributes> const& value) {
+ inputs[input_names::K_override] = value;
+ return *this;
+ }
+
+ Matmul_fp8_attributes&
+ set_padding(double const padding_val) {
+ padding_value = padding_val;
+ return *this;
+ }
+
+ double
+ get_padding() const {
+ return padding_value;
+ }
+};
+
+class Matmul_attributes : public Attributes<Matmul_attributes> {
+ friend class Attributes<Matmul_attributes>;
+ friend class MatmulNode;
+ friend class INode;
+
+ double padding_value = 0.0;
+
+ public:
+ enum class input_names { A, B, M_override, N_override, K_override };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { C };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Matmul_attributes, name, compute_data_type, inputs, outputs, padding_value)
+
+ Matmul_attributes&
+ clone_fp8_attributes(Matmul_fp8_attributes const& attributes) {
+ auto m_override = attributes.inputs.find(Matmul_fp8_attributes::input_names::M_override);
+ if (m_override != attributes.inputs.end()) {
+ set_m_override(m_override->second);
+ }
+ auto n_override = attributes.inputs.find(Matmul_fp8_attributes::input_names::N_override);
+ if (n_override != attributes.inputs.end()) {
+ set_n_override(n_override->second);
+ }
+ auto k_override = attributes.inputs.find(Matmul_fp8_attributes::input_names::K_override);
+ if (k_override != attributes.inputs.end()) {
+ set_k_override(k_override->second);
+ }
+
+ set_padding(attributes.get_padding());
+
+ return *this;
+ }
+
+ Matmul_attributes&
+ set_m_override(std::shared_ptr<Tensor_attributes> const& value) {
+ inputs[input_names::M_override] = value;
+ return *this;
+ }
+
+ Matmul_attributes&
+ set_n_override(std::shared_ptr<Tensor_attributes> const& value) {
+ inputs[input_names::N_override] = value;
+ return *this;
+ }
+
+ Matmul_attributes&
+ set_k_override(std::shared_ptr<Tensor_attributes> const& value) {
+ inputs[input_names::K_override] = value;
+ return *this;
+ }
+
+ Matmul_attributes&
+ set_padding(double const padding_val) {
+ padding_value = padding_val;
+ return *this;
+ }
+};
+
+class Pointwise_attributes : public Attributes<Pointwise_attributes> {
+ friend class Attributes<Pointwise_attributes>;
+ friend class PointwiseNode;
+ friend class CompositeSoftmaxNode;
+ friend class INode;
+
+ PointwiseMode_t mode = PointwiseMode_t::NOT_SET;
+
+ std::optional<int64_t> axis;
+
+ std::optional<float> relu_lower_clip;
+ std::optional<float> relu_upper_clip;
+ std::optional<float> relu_lower_clip_slope;
+
+ std::optional<float> swish_beta;
+ std::optional<float> elu_alpha;
+ std::optional<float> softplus_beta;
+
+ public:
+ enum class input_names { IN_0, IN_1, IN_2 };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { OUT_0 };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Pointwise_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ mode,
+ axis,
+ relu_lower_clip,
+ relu_upper_clip,
+ relu_lower_clip_slope,
+ swish_beta,
+ elu_alpha,
+ softplus_beta)
+
+ Pointwise_attributes&
+ set_mode(PointwiseMode_t const value) {
+ mode = value;
+ return *this;
+ }
+
+ PointwiseMode_t
+ get_mode() const {
+ return mode;
+ }
+
+ std::optional<int64_t>
+ get_axis() const {
+ return axis;
+ }
+
+ Pointwise_attributes&
+ set_axis(int64_t const axis) {
+ this->axis = axis;
+ return *this;
+ }
+
+ Pointwise_attributes&
+ set_relu_lower_clip_slope(float const negative_slope) {
+ this->relu_lower_clip_slope = negative_slope;
+ return *this;
+ }
+
+ Pointwise_attributes&
+ set_relu_lower_clip(float const value) {
+ this->relu_lower_clip = value;
+ return *this;
+ }
+
+ Pointwise_attributes&
+ set_relu_upper_clip(float const value) {
+ this->relu_upper_clip = value;
+ return *this;
+ }
+
+ Pointwise_attributes&
+ set_swish_beta(float const value) {
+ this->swish_beta = value;
+ return *this;
+ }
+
+ std::optional<float>
+ get_swish_beta() const {
+ return swish_beta;
+ }
+
+ Pointwise_attributes&
+ set_elu_alpha(float const value) {
+ this->elu_alpha = value;
+ return *this;
+ }
+
+ Pointwise_attributes&
+ set_softplus_beta(float const value) {
+ this->softplus_beta = value;
+ return *this;
+ }
+};
+
+class Instancenorm_backward_attributes : public Attributes<Instancenorm_backward_attributes> {
+ friend class Attributes<Instancenorm_backward_attributes>;
+ friend class DINNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { DY, X, SCALE, MEAN, INV_VARIANCE };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { DX, DSCALE, DBIAS };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Instancenorm_backward_attributes, name, compute_data_type, inputs, outputs)
+
+ Instancenorm_backward_attributes&
+ set_saved_mean_and_inv_variance(std::shared_ptr<Tensor_attributes> mean,
+ std::shared_ptr<Tensor_attributes> inv_variance) {
+ inputs[Instancenorm_backward_attributes::input_names::MEAN] = mean;
+ inputs[Instancenorm_backward_attributes::input_names::INV_VARIANCE] = inv_variance;
+ return *this;
+ }
+};
+
+class Layernorm_backward_attributes : public Attributes<Layernorm_backward_attributes> {
+ friend class Attributes<Layernorm_backward_attributes>;
+ friend class DLNNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { DY, X, SCALE, MEAN, INV_VARIANCE, EPSILON };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { DX, DSCALE, DBIAS };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Layernorm_backward_attributes, name, compute_data_type, inputs, outputs)
+
+ Layernorm_backward_attributes&
+ set_saved_mean_and_inv_variance(std::shared_ptr<Tensor_attributes> mean,
+ std::shared_ptr<Tensor_attributes> inv_variance) {
+ inputs[Layernorm_backward_attributes::input_names::MEAN] = mean;
+ inputs[Layernorm_backward_attributes::input_names::INV_VARIANCE] = inv_variance;
+ return *this;
+ }
+};
+
+class Layernorm_attributes : public Attributes<Layernorm_attributes> {
+ friend class Attributes<Layernorm_attributes>;
+ friend class LayerNormNode;
+ friend class Graph;
+
+ NormFwdPhase_t forward_phase = NormFwdPhase_t::NOT_SET;
+
+ public:
+ enum class input_names { X, SCALE, BIAS, EPSILON };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y, MEAN, INV_VARIANCE };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Layernorm_attributes, name, compute_data_type, inputs, outputs, forward_phase)
+
+ Layernorm_attributes&
+ set_forward_phase(NormFwdPhase_t const value) {
+ forward_phase = value;
+ return *this;
+ }
+
+ Layernorm_attributes&
+ set_epsilon(std::shared_ptr<Tensor_attributes>& value) {
+ inputs[Layernorm_attributes::input_names::EPSILON] = value;
+ return *this;
+ }
+
+ Layernorm_attributes&
+ set_epsilon(float const value) {
+ inputs[Layernorm_attributes::input_names::EPSILON] = std::make_shared<Tensor_attributes>(value);
+ return *this;
+ }
+};
+
+class AdaLayernorm_attributes : public Attributes<AdaLayernorm_attributes> {
+ friend class Attributes<AdaLayernorm_attributes>;
+ friend class AdaLayerNormNode;
+ friend class Graph;
+
+ NormFwdPhase_t forward_phase = NormFwdPhase_t::NOT_SET;
+
+ public:
+ enum class input_names { X, SCALE, BIAS, EPSILON };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y, MEAN, INV_VARIANCE };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(AdaLayernorm_attributes, name, compute_data_type, inputs, outputs, forward_phase)
+
+ AdaLayernorm_attributes&
+ set_forward_phase(NormFwdPhase_t const value) {
+ forward_phase = value;
+ return *this;
+ }
+
+ AdaLayernorm_attributes&
+ set_epsilon(std::shared_ptr<Tensor_attributes> value) {
+ inputs[AdaLayernorm_attributes::input_names::EPSILON] = std::move(value);
+ return *this;
+ }
+};
+
+class AdaLayernorm_backward_attributes : public Attributes<AdaLayernorm_backward_attributes> {
+ friend class Attributes<AdaLayernorm_backward_attributes>;
+ friend class DAdaLayerNormNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { DY, X, SCALE, MEAN, INV_VARIANCE, EPSILON };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { DX, DSCALE, DBIAS };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(AdaLayernorm_backward_attributes, name, compute_data_type, inputs, outputs)
+
+ AdaLayernorm_backward_attributes&
+ set_saved_mean_and_inv_variance(std::shared_ptr<Tensor_attributes> mean,
+ std::shared_ptr<Tensor_attributes> inv_variance) {
+ inputs[AdaLayernorm_backward_attributes::input_names::MEAN] = mean;
+ inputs[AdaLayernorm_backward_attributes::input_names::INV_VARIANCE] = inv_variance;
+ return *this;
+ }
+};
+
+class Instancenorm_attributes : public Attributes<Instancenorm_attributes> {
+ friend class Attributes<Instancenorm_attributes>;
+ friend class InstanceNormNode;
+ friend class Graph;
+
+ NormFwdPhase_t forward_phase = NormFwdPhase_t::NOT_SET;
+
+ public:
+ enum class input_names { X, SCALE, BIAS, EPSILON };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y, MEAN, INV_VARIANCE };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Instancenorm_attributes, name, compute_data_type, inputs, outputs, forward_phase)
+
+ Instancenorm_attributes&
+ set_forward_phase(NormFwdPhase_t const value) {
+ forward_phase = value;
+ return *this;
+ }
+
+ Instancenorm_attributes&
+ set_epsilon(std::shared_ptr<Tensor_attributes>& value) {
+ inputs[Instancenorm_attributes::input_names::EPSILON] = value;
+ return *this;
+ }
+};
+
+class Batchnorm_attributes : public Attributes<Batchnorm_attributes> {
+ friend class Attributes<Batchnorm_attributes>;
+ friend class BatchNormNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { X, SCALE, BIAS, PREV_RUNNING_MEAN, PREV_RUNNING_VAR, EPSILON, MOMENTUM };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ // Only special case where one of the inputs is a vector.
+ std::vector<std::shared_ptr<Tensor_attributes>> peer_stats;
+ enum class output_names { Y, MEAN, INV_VARIANCE, NEXT_RUNNING_MEAN, NEXT_RUNNING_VAR };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Batchnorm_attributes, name, compute_data_type, inputs, peer_stats, outputs)
+
+ Batchnorm_attributes&
+ set_previous_running_stats(std::shared_ptr<Tensor_attributes>& mean,
+ std::shared_ptr<Tensor_attributes>& variance,
+ std::shared_ptr<Tensor_attributes>& momentum) {
+ inputs[input_names::PREV_RUNNING_MEAN] = mean;
+ inputs[input_names::PREV_RUNNING_VAR] = variance;
+ inputs[input_names::MOMENTUM] = momentum;
+ return *this;
+ }
+
+ Batchnorm_attributes&
+ set_epsilon(std::shared_ptr<Tensor_attributes>& value) {
+ inputs[input_names::EPSILON] = value;
+ return *this;
+ }
+
+ Batchnorm_attributes&
+ set_peer_stats(std::vector<std::shared_ptr<Tensor_attributes>> const& input_peer_stats) {
+ peer_stats = input_peer_stats;
+ return *this;
+ }
+};
+
+class Batchnorm_inference_attributes : public Attributes<Batchnorm_inference_attributes> {
+ friend class Attributes<Batchnorm_inference_attributes>;
+ friend class BatchnormInferenceNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { X, MEAN, INV_VARIANCE, SCALE, BIAS };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Batchnorm_inference_attributes, name, compute_data_type, inputs, outputs)
+};
+
+class Reduction_attributes : public Attributes<Reduction_attributes> {
+ friend class Attributes<Reduction_attributes>;
+ friend class ReductionNode;
+ friend class INode;
+
+ std::optional<ReductionMode_t> mode;
+ bool is_deterministic = false;
+
+ public:
+ enum class input_names { X, Group_offset };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Reduction_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ mode,
+ is_deterministic)
+
+ std::optional<ReductionMode_t>
+ get_mode() const {
+ return mode;
+ }
+
+ Reduction_attributes&
+ set_mode(ReductionMode_t value) {
+ mode = value;
+ return *this;
+ }
+
+ bool
+ get_is_deterministic() const {
+ return is_deterministic;
+ }
+
+ Reduction_attributes&
+ set_is_deterministic(bool value) {
+ is_deterministic = value;
+ return *this;
+ }
+
+ Reduction_attributes&
+ set_group_offset(std::shared_ptr<Tensor_attributes> value) {
+ inputs[input_names::Group_offset] = std::move(value);
+ return *this;
+ }
+};
+
+class Rng_attributes : public Attributes<Rng_attributes> {
+ friend class Attributes<Rng_attributes>;
+ friend class RngNode;
+ friend class INode;
+
+ RngDistribution_t distribution = RngDistribution_t::NOT_SET;
+ std::vector<int64_t> dim = {};
+ std::vector<int64_t> stride = {};
+ std::optional<int64_t> seed;
+ std::optional<double> bernoulli_probability;
+
+ public:
+ enum class input_names { Seed, Offset };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Rng_attributes,
+ name,
+ inputs,
+ outputs,
+ distribution,
+ dim,
+ stride,
+ seed,
+ bernoulli_probability)
+
+ std::vector<int64_t>
+ get_dim() const {
+ return dim;
+ }
+
+ auto
+ set_dim(std::vector<int64_t> const& value) -> Rng_attributes& {
+ dim = value;
+ return *this;
+ }
+
+ std::vector<int64_t>
+ get_stride() const {
+ return stride;
+ }
+
+ auto
+ set_stride(std::vector<int64_t> const& value) -> Rng_attributes& {
+ stride = value;
+ return *this;
+ }
+
+ RngDistribution_t
+ get_distribution() const {
+ return distribution;
+ }
+
+ Rng_attributes&
+ set_distribution(RngDistribution_t value) {
+ distribution = value;
+ return *this;
+ }
+
+ std::optional<int64_t>
+ get_seed() const {
+ return seed;
+ }
+
+ Rng_attributes&
+ set_seed(std::optional<int64_t> value) {
+ seed = value;
+ return *this;
+ }
+
+ std::optional<double>
+ get_bernoulli_probability() const {
+ return bernoulli_probability;
+ }
+
+ Rng_attributes&
+ set_bernoulli_probability(std::optional<double> value) {
+ bernoulli_probability = value;
+ return *this;
+ }
+};
+
+class Resample_attributes : public Attributes<Resample_attributes> {
+ friend class Attributes<Resample_attributes>;
+ friend class ResampleNode;
+ friend class INode;
+
+ std::optional<bool> generate_index;
+ ResampleMode_t resample_mode;
+ PaddingMode_t padding_mode;
+ std::vector<cudnnFraction_t> pre_padding;
+ std::vector<cudnnFraction_t> post_padding;
+ std::vector<cudnnFraction_t> stride;
+ std::vector<cudnnFraction_t> window;
+
+ public:
+ enum class input_names { X };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+
+ enum class output_names { Y, Index };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Resample_attributes,
+ name,
+ inputs,
+ outputs,
+ generate_index,
+ resample_mode,
+ padding_mode,
+ pre_padding,
+ post_padding,
+ stride,
+ window)
+
+ auto
+ set_resampling_mode(ResampleMode_t const& value) -> Resample_attributes& {
+ resample_mode = value;
+ return *this;
+ }
+
+ auto
+ set_padding_mode(PaddingMode_t const& value) -> Resample_attributes& {
+ padding_mode = value;
+ return *this;
+ }
+
+ auto
+ set_window(std::vector<int64_t> const& value) -> Resample_attributes& {
+ window.resize(value.size());
+ for (auto i = 0u; i < value.size(); i++) {
+ window[i].numerator = value[i];
+ window[i].denominator = 1;
+ }
+ return *this;
+ }
+
+ auto
+ set_window(std::vector<cudnnFraction_t> const& value) -> Resample_attributes& {
+ window = value;
+ return *this;
+ }
+
+ auto
+ set_stride(std::vector<int64_t> const& value) -> Resample_attributes& {
+ stride.resize(value.size());
+ for (auto i = 0u; i < value.size(); i++) {
+ stride[i].numerator = value[i];
+ stride[i].denominator = 1;
+ }
+ return *this;
+ }
+
+ auto
+ set_stride(std::vector<cudnnFraction_t> const& value) -> Resample_attributes& {
+ stride = value;
+ return *this;
+ }
+
+ auto
+ set_pre_padding(std::vector<int64_t> const& value) -> Resample_attributes& {
+ pre_padding.resize(value.size());
+ for (auto i = 0u; i < value.size(); i++) {
+ pre_padding[i].numerator = value[i];
+ pre_padding[i].denominator = 1;
+ }
+ return *this;
+ }
+
+ auto
+ set_pre_padding(std::vector<cudnnFraction_t> const& value) -> Resample_attributes& {
+ pre_padding = value;
+ return *this;
+ }
+
+ auto
+ set_post_padding(std::vector<int64_t> const& value) -> Resample_attributes& {
+ post_padding.resize(value.size());
+ for (auto i = 0u; i < value.size(); i++) {
+ post_padding[i].numerator = value[i];
+ post_padding[i].denominator = 1;
+ }
+ return *this;
+ }
+
+ auto
+ set_post_padding(std::vector<cudnnFraction_t> const& value) -> Resample_attributes& {
+ post_padding = value;
+ return *this;
+ }
+
+ auto
+ set_generate_index(bool const value) -> Resample_attributes& {
+ generate_index = value;
+ return *this;
+ }
+
+ [[deprecated]] auto
+ set_is_inference(bool const value) -> Resample_attributes& {
+ return set_generate_index(!value);
+ }
+};
+
+class Reshape_attributes : public Attributes<Reshape_attributes> {
+ friend class Attributes<Reshape_attributes>;
+ friend class ReshapeNode;
+ friend class INode;
+
+ std::vector<int64_t> dim = {};
+ std::vector<int64_t> stride = {};
+ ReshapeMode_t reshape_mode = ReshapeMode_t::VIEW_ONLY;
+
+ public:
+ enum class input_names { X };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Reshape_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ dim,
+ stride,
+ reshape_mode)
+
+ std::vector<int64_t>
+ get_dim() const {
+ return dim;
+ }
+
+ auto
+ set_dim(std::vector<int64_t> const& value) -> Reshape_attributes& {
+ dim = value;
+ return *this;
+ }
+
+ std::vector<int64_t>
+ get_stride() const {
+ return stride;
+ }
+
+ auto
+ set_stride(std::vector<int64_t> const& value) -> Reshape_attributes& {
+ stride = value;
+ return *this;
+ }
+
+ ReshapeMode_t
+ get_reshape_mode() const {
+ return reshape_mode;
+ }
+
+ auto
+ set_reshape_mode(ReshapeMode_t const& value) -> Reshape_attributes& {
+ reshape_mode = value;
+ return *this;
+ }
+};
+
+class Transpose_attributes : public Attributes<Transpose_attributes> {
+ friend class Attributes<Transpose_attributes>;
+ friend class TransposeNode;
+ friend class Graph;
+
+ std::vector<int64_t> permutation;
+
+ public:
+ std::string
+ get_name() const {
+ return name;
+ }
+
+ auto
+ set_name(std::string const& value) -> Transpose_attributes& {
+ name = value;
+ return *this;
+ }
+
+ enum class input_names { X };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Transpose_attributes, name, compute_data_type, inputs, outputs, permutation)
+
+ std::vector<int64_t>
+ get_permutation() const {
+ return permutation;
+ }
+
+ auto
+ set_permutation(std::vector<int64_t> const& value) -> Transpose_attributes& {
+ permutation = value;
+ return *this;
+ }
+};
+
+class Rmsnorm_attributes : public Attributes<Rmsnorm_attributes> {
+ friend class Attributes<Rmsnorm_attributes>;
+ friend class RMSNormNode;
+ friend class Graph;
+
+ NormFwdPhase_t forward_phase = NormFwdPhase_t::NOT_SET;
+
+ public:
+ enum class input_names { X, SCALE, BIAS, EPSILON };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y, INV_VARIANCE };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Rmsnorm_attributes, name, compute_data_type, inputs, outputs, forward_phase)
+
+ Rmsnorm_attributes&
+ set_forward_phase(NormFwdPhase_t const value) {
+ forward_phase = value;
+ return *this;
+ }
+
+ Rmsnorm_attributes&
+ set_bias(std::shared_ptr<Tensor_attributes>& value) {
+ inputs[Rmsnorm_attributes::input_names::BIAS] = value;
+ return *this;
+ }
+
+ Rmsnorm_attributes&
+ set_epsilon(std::shared_ptr<Tensor_attributes>& value) {
+ inputs[Rmsnorm_attributes::input_names::EPSILON] = value;
+ return *this;
+ }
+};
+
+class RoPE_attributes : public Attributes<RoPE_attributes> {
+ friend class Attributes<RoPE_attributes>;
+ friend class RoPENode;
+ friend class Graph;
+
+ public:
+ enum class input_names { INPUT, FREQS };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { OUTPUT };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+
+ // Host-side scalar multiplied into cos/sin. Default 1.0 (identity).
+ // Use this to fold YARN mscale and/or attn_scale into RoPE so SDPA can skip its scale multiply.
+ float output_scale = 1.0f;
+
+ // Rotation width (last K dims). 0 = use input's head_dim (full rotation).
+ // When < head_dim, the kernel rotates the last rope_dim dims and scaled-pass-through
+ // copies the first (head_dim - rope_dim) dims. The freqs tensor's last dim must equal
+ // rope_dim (not head_dim). Used for DSv3-style MLA (rope_dim=64, head_dim=192).
+ int64_t rope_dim = 0;
+
+ RoPE_attributes&
+ set_output_scale(float scale) {
+ output_scale = scale;
+ return *this;
+ }
+
+ RoPE_attributes&
+ set_rope_dim(int64_t dim) {
+ rope_dim = dim;
+ return *this;
+ }
+
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(RoPE_attributes, name, compute_data_type, inputs, outputs, output_scale, rope_dim)
+};
+
+class RoPE_backward_attributes : public Attributes<RoPE_backward_attributes> {
+ friend class Attributes<RoPE_backward_attributes>;
+ friend class RoPEBackwardNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { DY, FREQS };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { DX };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+
+ // Same semantics as fwd: cos/sin pre-multiplied by output_scale, and the nope
+ // segment (head_dim - rope_dim) is scaled-pass-through. Should match the fwd's
+ // values for correct gradient flow.
+ float output_scale = 1.0f;
+ int64_t rope_dim = 0;
+
+ RoPE_backward_attributes&
+ set_output_scale(float scale) {
+ output_scale = scale;
+ return *this;
+ }
+
+ RoPE_backward_attributes&
+ set_rope_dim(int64_t dim) {
+ rope_dim = dim;
+ return *this;
+ }
+
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(RoPE_backward_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ output_scale,
+ rope_dim)
+};
+
+class Rmsnorm_backward_attributes : public Attributes<Rmsnorm_backward_attributes> {
+ friend class Attributes<Rmsnorm_backward_attributes>;
+ friend class DRMSNormNode;
+ friend class Graph;
+
+ std::optional<bool> use_dbias;
+
+ public:
+ enum class input_names { DY, X, SCALE, INV_VARIANCE };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { DX, DSCALE, DBIAS };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Rmsnorm_backward_attributes, name, compute_data_type, inputs, outputs)
+
+ Rmsnorm_backward_attributes&
+ has_dbias(bool value) {
+ use_dbias = value;
+ return *this;
+ }
+};
+
+// class Scaled_dot_product_attention_attributes : public Operation {
+// public:
+// struct Inputs {
+// std::shared_ptr<Tensor_attributes> Q;
+// std::shared_ptr<Tensor_attributes> K;
+// std::shared_ptr<Tensor_attributes> Attn_scale;
+// std::shared_ptr<Tensor_attributes> Bias; // Optional bias after bmm1
+// std::shared_ptr<Tensor_attributes> V;
+// std::shared_ptr<Tensor_attributes> SEQ_LEN_Q;
+// std::shared_ptr<Tensor_attributes> SEQ_LEN_KV;
+// std::shared_ptr<Tensor_attributes> Mask;
+// std::shared_ptr<Tensor_attributes> Dropout_mask;
+// std::shared_ptr<Tensor_attributes> Dropout_scale;
+// } inputs;
+
+// struct Outputs {
+// std::shared_ptr<Tensor_attributes> O;
+// std::shared_ptr<Tensor_attributes>
+// S; // softmax output dumped when is_inference false. Users first need to check whether its nullptr.
+// } outputs;
+
+// std::optional<bool> is_inference;
+// bool padding_mask = false;
+// bool causal_mask = false;
+// std::optional<float> dropout_probability;
+// int64_t seed;
+// float dropout_scale = 1.f;
+
+// public:
+// Scaled_dot_product_attention_attributes() : Operation(Tag::Scaled_dot_product_attention), is_inference(false) {}
+
+// Scaled_dot_product_attention_attributes&
+// set_is_inference(bool const value) {
+// is_inference = value;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_seq_len_q(std::shared_ptr<Tensor_attributes> value) {
+// inputs.SEQ_LEN_Q = value;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_seq_len_kv(std::shared_ptr<Tensor_attributes> value) {
+// inputs.SEQ_LEN_KV = value;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_padding_mask(bool const value) {
+// padding_mask = value;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_causal_mask(bool const value) {
+// causal_mask = value;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_attn_scale(std::shared_ptr<Tensor_attributes> value) {
+// inputs.Attn_scale = value;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_bias(std::shared_ptr<Tensor_attributes> bias) {
+// inputs.Bias = bias;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_dropout(float const probability, int64_t const seed_) {
+// dropout_probability = probability;
+// seed = seed_;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_dropout(std::shared_ptr<Tensor_attributes> mask, std::shared_ptr<Tensor_attributes> scale) {
+// inputs.Dropout_mask = mask;
+// inputs.Dropout_scale = scale;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_compute_data_type(DataType_t const value) {
+// compute_data_type = value;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// set_name(std::string const& value) {
+// name = value;
+// return *this;
+// }
+
+// Scaled_dot_product_attention_attributes&
+// fill_from_context(detail::Context const& context) {
+// // Fill node's tensors
+// inputs.Q->fill_from_context(context);
+// inputs.K->fill_from_context(context);
+// inputs.V->fill_from_context(context);
+// inputs.SEQ_LEN_Q->fill_from_context(context);
+// inputs.SEQ_LEN_KV->fill_from_context(context);
+// outputs.O->fill_from_context(context);
+
+// // Fill this node
+// if (get_compute_data_type() == DataType_t::NOT_SET) {
+// set_compute_data_type(context.get_compute_data_type());
+// }
+// return *this;
+// }
+// };
+template <typename DerivedClass>
+class SDPANodeBase;
+class CompositeSDPANode;
+class UnifiedSDPANode;
+
+class SDPA_attributes : public Attributes<SDPA_attributes> {
+ friend class Attributes<SDPA_attributes>;
+ friend class SDPANodeBase<CompositeSDPANode>;
+ friend class CompositeSDPANode;
+ friend class SDPANodeBase<UnifiedSDPANode>;
+ friend class UnifiedSDPANode;
+ friend class Graph;
+
+ using Tensor_t = std::shared_ptr<Tensor_attributes>;
+ using Graph_t = std::shared_ptr<Graph>;
+
+ using AttentionScoreModifier_t =
+ std::function<Tensor_t(std::shared_ptr<Graph>, std::shared_ptr<Tensor_attributes>)>;
+
+ std::optional<bool> generate_stats;
+ bool alibi_mask = false;
+ bool padding_mask = false;
+ std::optional<int64_t> left_bound;
+ std::optional<int64_t> right_bound;
+ DiagonalAlignment_t diagonal_alignment = DiagonalAlignment_t::TOP_LEFT;
+ std::optional<float> dropout_probability;
+ std::optional<float> attn_scale_value;
+ std::optional<int> max_seq_len_kv;
+ AttentionScoreModifier_t attention_score_modifier = nullptr;
+ DataType_t mma_core_mode = DataType_t::NOT_SET;
+
+ AttentionImplementation_t implementation = AttentionImplementation_t::AUTO;
+
+ bool unfuse_fma = false; // For SM100: use __fmul_rn + __fadd_rn instead of ffma2 in softmax
+
+ bool
+ has_bias() const {
+ return inputs.find(input_names::Bias) != inputs.end() && inputs.at(input_names::Bias) != nullptr;
+ }
+
+ bool
+ has_causal_like_masking() const {
+ return right_bound.has_value();
+ }
+
+ bool
+ has_causal_mask_bottom_right() const {
+ return right_bound.has_value() && diagonal_alignment == DiagonalAlignment_t::BOTTOM_RIGHT;
+ }
+
+ bool
+ has_sink_token() const {
+ return inputs.find(input_names::SINK_TOKEN) != inputs.end() && inputs.at(input_names::SINK_TOKEN) != nullptr;
+ }
+
+ public:
+ enum class input_names {
+ Q,
+ K,
+ V,
+ Attn_scale,
+ Bias,
+ SEQ_LEN_Q,
+ SEQ_LEN_KV,
+ CU_SEQ_LEN_Q,
+ CU_SEQ_LEN_KV,
+ Seed,
+ Offset,
+ Dropout_mask,
+ Dropout_scale,
+ Page_table_K,
+ Page_table_V,
+ Block_mask,
+ // FP8-specific scaling inputs
+ Descale_Q,
+ Descale_K,
+ Descale_V,
+ Descale_S,
+ Scale_S,
+ Scale_O,
+ SINK_TOKEN,
+ };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { O, Stats, Max, Sum_exp, RNG_DUMP, Amax_S, Amax_O };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ // Convenience struct for named access to SDPA outputs
+ struct SDPA_outputs {
+ std::shared_ptr<Tensor_attributes> O; ///< Main attention output tensor
+ std::shared_ptr<Tensor_attributes> Stats; ///< Statistics/softmax output (when generate_stats=true)
+ std::shared_ptr<Tensor_attributes> Max; ///< Max output tensor
+ std::shared_ptr<Tensor_attributes> Sum_exp; ///< Sum_exp output tensor
+ std::shared_ptr<Tensor_attributes> RNG_DUMP; ///< Random number generator dump for dropout
+ ///< check why we don't return RNG_DUMP this way
+ std::shared_ptr<Tensor_attributes> Amax_S; ///< FP8 absolute maximum for attention scores
+ std::shared_ptr<Tensor_attributes> Amax_O; ///< FP8 absolute maximum for output tensor
+ };
+
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(SDPA_attributes,
+ name,
+ inputs,
+ outputs,
+ generate_stats,
+ alibi_mask,
+ padding_mask,
+ dropout_probability,
+ attn_scale_value,
+ max_seq_len_kv,
+ mma_core_mode,
+ left_bound,
+ right_bound,
+ diagonal_alignment,
+ implementation)
+
+ SDPA_attributes&
+ set_generate_stats(bool const value) {
+ generate_stats = value;
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_logit_max(std::shared_ptr<Tensor_attributes> value) {
+ outputs[SDPA_attributes::output_names::Max] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_score_sum_exp(std::shared_ptr<Tensor_attributes> value) {
+ outputs[SDPA_attributes::output_names::Sum_exp] = std::move(value);
+ return *this;
+ }
+
+ [[deprecated]] SDPA_attributes&
+ set_is_inference(bool const value) {
+ return set_generate_stats(!value);
+ }
+
+ SDPA_attributes&
+ set_attn_scale(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::Attn_scale] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_attn_scale(float const value) {
+ attn_scale_value = value;
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_bias(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::Bias] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_block_mask(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::Block_mask] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_alibi_mask(bool const value) {
+ alibi_mask = value;
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_padding_mask(bool const value) {
+ padding_mask = value;
+ return *this;
+ }
+
+ // Internal function - do not use directly in application code
+ SDPA_attributes&
+ _set_mma_core_mode(DataType_t const value) {
+ mma_core_mode = value;
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_seq_len_q(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::SEQ_LEN_Q] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_seq_len_kv(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::SEQ_LEN_KV] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_cu_seq_len_q(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::CU_SEQ_LEN_Q] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_cu_seq_len_kv(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::CU_SEQ_LEN_KV] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_diagonal_alignment(DiagonalAlignment_t const alignment) {
+ diagonal_alignment = alignment;
+ return *this;
+ }
+
+ // Sets the diagonal position to top left and
+ // calls set_diagonal_band_right_bound(0) if no right_bound was specified
+ // TODO: Deprecate
+ SDPA_attributes&
+ set_causal_mask(bool const value) {
+ if (value) {
+ set_diagonal_alignment(DiagonalAlignment_t::TOP_LEFT);
+ set_diagonal_band_right_bound(0);
+ }
+ return *this;
+ }
+
+ // Sets the diagonal position to the bottom right (on a per-sequence basis)
+ // and calls set_diagonal_band_right_bound(0) if no right_bound was specified
+ // TODO: Deprecate
+ SDPA_attributes&
+ set_causal_mask_bottom_right(bool const value) {
+ if (value) {
+ set_diagonal_alignment(DiagonalAlignment_t::BOTTOM_RIGHT);
+ set_diagonal_band_right_bound(0);
+ }
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_score_mod(AttentionScoreModifier_t fn) {
+ attention_score_modifier = std::move(fn);
+ return *this;
+ }
+
+ // calls set_diagonal_band_left_bound(value)
+ // TODO: Deprecate
+ SDPA_attributes&
+ set_sliding_window_length(int const value) {
+ return set_diagonal_band_left_bound(value);
+ }
+
+ SDPA_attributes&
+ set_diagonal_band_left_bound(int const value) {
+ left_bound = value;
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_diagonal_band_right_bound(int const value) {
+ right_bound = value;
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_dropout(float const probability,
+ std::shared_ptr<Tensor_attributes> seed,
+ std::shared_ptr<Tensor_attributes> offset) {
+ dropout_probability = probability;
+ inputs[SDPA_attributes::input_names::Seed] = std::move(seed);
+ inputs[SDPA_attributes::input_names::Offset] = std::move(offset);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_dropout(std::shared_ptr<Tensor_attributes> mask, std::shared_ptr<Tensor_attributes> scale) {
+ inputs[SDPA_attributes::input_names::Dropout_mask] = std::move(mask);
+ inputs[SDPA_attributes::input_names::Dropout_scale] = std::move(scale);
+ return *this;
+ }
+
+ // For debugging purposes only.
+ SDPA_attributes&
+ set_rng_dump(std::shared_ptr<Tensor_attributes> value) {
+ outputs[SDPA_attributes::output_names::RNG_DUMP] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_paged_attention_k_table(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::Page_table_K] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_paged_attention_v_table(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::Page_table_V] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_paged_attention_max_seq_len_kv(int const value) {
+ max_seq_len_kv = value;
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_sink_token(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_attributes::input_names::SINK_TOKEN] = std::move(value);
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_implementation(AttentionImplementation_t value) {
+ implementation = value;
+ return *this;
+ }
+
+ SDPA_attributes&
+ set_unfuse_fma(bool value) {
+ unfuse_fma = value;
+ return *this;
+ }
+
+ // Implementation is in sdpa_support_surface.h
+ error_t
+ validate_sdpa_support_surface(const detail::Context& context, int64_t s_kv, bool is_paged_k, bool is_paged_v) const;
+
+ // Internal function - do not use directly in application code
+ void
+ _auto_select_implementation(const detail::Context& context) {
+ if (verify_sdpa_support_surface_for_implementation(context, AttentionImplementation_t::UNIFIED).is_good()) {
+ implementation = AttentionImplementation_t::UNIFIED;
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Auto-selected SDPA implementation UNIFIED");
+ } else if (verify_sdpa_support_surface_for_implementation(context, AttentionImplementation_t::COMPOSITE)
+ .is_good()) {
+ implementation = AttentionImplementation_t::COMPOSITE;
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Auto-selected SDPA implementation COMPOSITE");
+ } else {
+ // Leave `implementation` with its previous value (usually AUTO).
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: No suitable SDPA implementation for given SDPA_attributes");
+ }
+ }
+
+ private:
+ // Check whether implementation `impl` supports the requested features. `impl` must not be AUTO.
+ // (The `implementation` member variable is ignored.)
+ error_t
+ verify_sdpa_support_surface_for_implementation(const detail::Context& context,
+ AttentionImplementation_t impl) const;
+};
+
+// Type alias for backward compatibility - SDPA_fp8_attributes is now an alias to SDPA_attributes
+// All FP8 functionality is unified in SDPA_attributes with the mma_core_mode field
+using SDPA_fp8_attributes = SDPA_attributes;
+
+class SDPA_backward_attributes : public Attributes<SDPA_backward_attributes> {
+ friend class Attributes<SDPA_backward_attributes>;
+ friend class CompositeSDPABackwardNode;
+ friend class Graph;
+ using Tensor_t = std::shared_ptr<Tensor_attributes>;
+ using Graph_t = std::shared_ptr<Graph>;
+
+ using AttentionScoreModifier_t =
+ std::function<Tensor_t(std::shared_ptr<Graph>, std::shared_ptr<Tensor_attributes>)>;
+
+ bool alibi_mask = false;
+ bool padding_mask = false;
+ std::optional<int64_t> left_bound;
+ std::optional<int64_t> right_bound;
+ DiagonalAlignment_t diagonal_alignment = DiagonalAlignment_t::TOP_LEFT;
+
+ std::optional<float> dropout_probability;
+ std::optional<float> attn_scale_value;
+
+ std::optional<int64_t> max_total_seq_len_q;
+ std::optional<int64_t> max_total_seq_len_kv;
+
+ bool is_deterministic_algorithm = false;
+ AttentionScoreModifier_t attention_score_modifier = nullptr;
+ AttentionScoreModifier_t attention_score_modifier_bprop = nullptr;
+
+ bool
+ has_causal_like_masking() const {
+ return right_bound.has_value();
+ }
+
+ bool
+ has_causal_mask_bottom_right() const {
+ return right_bound.has_value() && diagonal_alignment == DiagonalAlignment_t::BOTTOM_RIGHT;
+ }
+
+ public:
+ enum class input_names {
+ Q,
+ K,
+ V,
+ O,
+ dO,
+ Stats,
+ Attn_scale,
+ Bias,
+ SEQ_LEN_Q,
+ SEQ_LEN_KV,
+ Seed,
+ Offset,
+ Dropout_mask,
+ Dropout_scale,
+ Dropout_scale_inv,
+ SINK_TOKEN,
+ };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { dQ, dK, dV, dBias, RNG_DUMP, DSINK_TOKEN };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(SDPA_backward_attributes,
+ name,
+ inputs,
+ outputs,
+ alibi_mask,
+ padding_mask,
+ dropout_probability,
+ attn_scale_value,
+ left_bound,
+ right_bound,
+ diagonal_alignment,
+ max_total_seq_len_q,
+ max_total_seq_len_kv,
+ is_deterministic_algorithm)
+
+ SDPA_backward_attributes&
+ set_attn_scale(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_backward_attributes::input_names::Attn_scale] = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_attn_scale(float const value) {
+ attn_scale_value = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_bias(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_backward_attributes::input_names::Bias] = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_dbias(std::shared_ptr<Tensor_attributes> value) {
+ outputs[SDPA_backward_attributes::output_names::dBias] = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_alibi_mask(bool const value) {
+ alibi_mask = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_padding_mask(bool const value) {
+ padding_mask = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_score_mod(AttentionScoreModifier_t fn) {
+ attention_score_modifier = std::move(fn);
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_score_mod_bprop(AttentionScoreModifier_t fn) {
+ attention_score_modifier_bprop = std::move(fn);
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_seq_len_q(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_backward_attributes::input_names::SEQ_LEN_Q] = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_seq_len_kv(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_backward_attributes::input_names::SEQ_LEN_KV] = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_max_total_seq_len_q(int64_t const value) {
+ max_total_seq_len_q = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_max_total_seq_len_kv(int64_t const value) {
+ max_total_seq_len_kv = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_diagonal_alignment(DiagonalAlignment_t const alignment) {
+ diagonal_alignment = alignment;
+ return *this;
+ }
+
+ // Sets the diagonal position to top left and
+ // calls set_diagonal_band_right_bound(0) if no right_bound was specified
+ // TODO: Deprecate
+ SDPA_backward_attributes&
+ set_causal_mask(bool const value) {
+ if (value) {
+ set_diagonal_alignment(DiagonalAlignment_t::TOP_LEFT);
+ set_diagonal_band_right_bound(0);
+ }
+ return *this;
+ }
+
+ // Sets the diagonal position to the bottom right (on a per-sequence basis)
+ // and calls set_diagonal_band_right_bound(0) if no right_bound was specified
+ // TODO: Deprecate
+ SDPA_backward_attributes&
+ set_causal_mask_bottom_right(bool const value) {
+ if (value) {
+ set_diagonal_alignment(DiagonalAlignment_t::BOTTOM_RIGHT);
+ set_diagonal_band_right_bound(0);
+ }
+ return *this;
+ }
+
+ // calls set_diagonal_band_left_bound(value)
+ // TODO: Deprecate
+ SDPA_backward_attributes&
+ set_sliding_window_length(int const value) {
+ return set_diagonal_band_left_bound(value);
+ }
+
+ SDPA_backward_attributes&
+ set_diagonal_band_left_bound(int const value) {
+ left_bound = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_diagonal_band_right_bound(int const value) {
+ right_bound = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_dropout(float const probability,
+ std::shared_ptr<Tensor_attributes> seed,
+ std::shared_ptr<Tensor_attributes> offset) {
+ dropout_probability = probability;
+ inputs[SDPA_backward_attributes::input_names::Seed] = seed;
+ inputs[SDPA_backward_attributes::input_names::Offset] = offset;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_dropout(std::shared_ptr<Tensor_attributes> mask,
+ std::shared_ptr<Tensor_attributes> scale,
+ std::shared_ptr<Tensor_attributes> scale_inv) {
+ inputs[SDPA_backward_attributes::input_names::Dropout_mask] = mask;
+ inputs[SDPA_backward_attributes::input_names::Dropout_scale] = scale;
+ inputs[SDPA_backward_attributes::input_names::Dropout_scale_inv] = scale_inv;
+ return *this;
+ }
+
+ // For debugging purposes only.
+ SDPA_backward_attributes&
+ set_rng_dump(std::shared_ptr<Tensor_attributes> value) {
+ outputs[SDPA_backward_attributes::output_names::RNG_DUMP] = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_deterministic_algorithm(bool const value) {
+ is_deterministic_algorithm = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_sink_token(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_backward_attributes::input_names::SINK_TOKEN] = value;
+ return *this;
+ }
+
+ SDPA_backward_attributes&
+ set_dsink_token(std::shared_ptr<Tensor_attributes> value) {
+ outputs[SDPA_backward_attributes::output_names::DSINK_TOKEN] = value;
+ return *this;
+ }
+};
+
+class SDPA_fp8_backward_attributes : public Attributes<SDPA_fp8_backward_attributes> {
+ friend class Attributes<SDPA_fp8_backward_attributes>;
+ friend class SDPAFP8BackwardNode;
+ friend class Graph;
+
+ bool padding_mask = false;
+ bool is_deterministic_algorithm = false;
+ std::optional<int64_t> left_bound;
+ std::optional<int64_t> right_bound;
+ DiagonalAlignment_t diagonal_alignment = DiagonalAlignment_t::TOP_LEFT;
+
+ std::optional<float> dropout_probability;
+ std::optional<float> attn_scale_value;
+
+ public:
+ enum class input_names {
+ Q,
+ Q_T,
+ K,
+ K_T,
+ V,
+ O,
+ dO,
+ dO_T,
+ dO_f16,
+ Stats,
+ Attn_scale,
+ Bias,
+ SEQ_LEN_Q,
+ SEQ_LEN_KV,
+ Seed,
+ Offset,
+ Dropout_mask,
+ Dropout_scale,
+ Dropout_scale_inv,
+
+ Descale_Q,
+ Descale_K,
+ Descale_V,
+ Descale_O,
+ Descale_dO,
+ Descale_dO_T,
+ Descale_K_T,
+ Descale_Q_T,
+ Descale_S,
+ Descale_dP,
+ Scale_dQ,
+ Scale_dK,
+ Scale_dV,
+ Scale_S,
+ Scale_dP,
+ SINK_TOKEN,
+ };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+
+ enum class output_names { dQ, dK, dV, Amax_dQ, Amax_dK, Amax_dV, Amax_dP, DSINK_TOKEN };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(SDPA_fp8_backward_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ padding_mask,
+ dropout_probability,
+ left_bound,
+ right_bound,
+ diagonal_alignment,
+ attn_scale_value,
+ is_deterministic_algorithm)
+
+ SDPA_fp8_backward_attributes&
+ set_attn_scale(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_fp8_backward_attributes::input_names::Attn_scale] = value;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_attn_scale(float const value) {
+ attn_scale_value = value;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_bias(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_fp8_backward_attributes::input_names::Bias] = value;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_padding_mask(bool const value) {
+ padding_mask = value;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_seq_len_q(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_fp8_backward_attributes::input_names::SEQ_LEN_Q] = value;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_seq_len_kv(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_fp8_backward_attributes::input_names::SEQ_LEN_KV] = value;
+ return *this;
+ }
+
+ bool
+ has_causal_like_masking() const {
+ return right_bound.has_value();
+ }
+
+ bool
+ has_causal_mask_bottom_right() const {
+ return right_bound.has_value() && diagonal_alignment == DiagonalAlignment_t::BOTTOM_RIGHT;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_causal_mask(bool const value) {
+ if (value) {
+ set_diagonal_alignment(DiagonalAlignment_t::TOP_LEFT);
+ set_diagonal_band_right_bound(0);
+ }
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_causal_mask_bottom_right(bool const value) {
+ if (value) {
+ set_diagonal_alignment(DiagonalAlignment_t::BOTTOM_RIGHT);
+ set_diagonal_band_right_bound(0);
+ }
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_diagonal_alignment(DiagonalAlignment_t const alignment) {
+ diagonal_alignment = alignment;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_diagonal_band_right_bound(int const value) {
+ right_bound = value;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_diagonal_band_left_bound(int const value) {
+ left_bound = value;
+ return *this;
+ }
+
+ bool
+ has_sliding_window() const {
+ return left_bound.has_value();
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_dropout(float const probability,
+ std::shared_ptr<Tensor_attributes> seed,
+ std::shared_ptr<Tensor_attributes> offset) {
+ dropout_probability = probability;
+ inputs[SDPA_fp8_backward_attributes::input_names::Seed] = seed;
+ inputs[SDPA_fp8_backward_attributes::input_names::Offset] = offset;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_dropout(std::shared_ptr<Tensor_attributes> mask,
+ std::shared_ptr<Tensor_attributes> scale,
+ std::shared_ptr<Tensor_attributes> scale_inv) {
+ inputs[SDPA_fp8_backward_attributes::input_names::Dropout_mask] = mask;
+ inputs[SDPA_fp8_backward_attributes::input_names::Dropout_scale] = scale;
+ inputs[SDPA_fp8_backward_attributes::input_names::Dropout_scale_inv] = scale_inv;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_deterministic_algorithm(bool const value) {
+ is_deterministic_algorithm = value;
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_sink_token(std::shared_ptr<Tensor_attributes> value) {
+ inputs[SDPA_fp8_backward_attributes::input_names::SINK_TOKEN] = std::move(value);
+ return *this;
+ }
+
+ SDPA_fp8_backward_attributes&
+ set_dsink_token(std::shared_ptr<Tensor_attributes> value) {
+ outputs[SDPA_fp8_backward_attributes::output_names::DSINK_TOKEN] = std::move(value);
+ return *this;
+ }
+
+ bool
+ has_sink_token() const {
+ return inputs.find(input_names::SINK_TOKEN) != inputs.end() && inputs.at(input_names::SINK_TOKEN) != nullptr;
+ }
+};
+
+using Scaled_dot_product_flash_attention_attributes [[deprecated]] = SDPA_attributes;
+using Scaled_dot_product_flash_attention_backward_attributes [[deprecated]] = SDPA_backward_attributes;
+
+class CompositeSoftmaxNode;
+class UnifiedSoftmaxNode;
+
+class Softmax_attributes : public Attributes<Softmax_attributes> {
+ friend class Attributes<Softmax_attributes>;
+ friend class CompositeSoftmaxNode;
+ friend class UnifiedSoftmaxNode;
+ friend class INode;
+
+ public:
+ enum class input_names { P, SINK };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { S, Stats, Max, Sum_exp };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Softmax_attributes, name, compute_data_type, inputs, outputs)
+
+ Softmax_attributes&
+ set_sink(std::shared_ptr<Tensor_attributes> value) {
+ inputs[Softmax_attributes::input_names::SINK] = value;
+ return *this;
+ }
+};
+
+template <typename DerivedClass>
+class DiagonalBandMaskNodeBase;
+class CompositeDiagonalBandMaskNode;
+class UnifiedDiagonalBandMaskNode;
+
+// Diagonal band mask attributes.
+// A diagonal band mask is *either* a left-bound mask or a right-bound mask.
+// LeftBound and ShiftRightBound cannot both be set at the same time.
+// If neither LeftBound nor ShiftRightBound is set, a right-bound mask is assumed.
+class DiagonalBandMask_attributes : public Attributes<DiagonalBandMask_attributes> {
+ friend class Attributes<DiagonalBandMask_attributes>;
+ friend class CompositeDiagonalBandMaskNode;
+ friend class UnifiedDiagonalBandMaskNode;
+
+ PointwiseMode_t comparison_mode = PointwiseMode_t::CMP_GT;
+
+ public:
+ enum class input_names { X, SEQ_LEN_Q, SEQ_LEN_KV, CU_SEQ_LEN_Q, CU_SEQ_LEN_KV, LeftBound, ShiftRightBound, B };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(DiagonalBandMask_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ comparison_mode)
+
+ PointwiseMode_t
+ get_comparison_mode() const {
+ return comparison_mode;
+ }
+
+ DiagonalBandMask_attributes&
+ set_comparison_mode(PointwiseMode_t value) {
+ comparison_mode = value;
+ return *this;
+ }
+};
+
+class Conv_wgrad_attributes : public Attributes<Conv_wgrad_attributes> {
+ friend class Attributes<Conv_wgrad_attributes>;
+ friend class WgradNode;
+ friend class Graph;
+
+ std::vector<int64_t> pre_padding;
+ std::vector<int64_t> post_padding;
+ std::vector<int64_t> stride;
+ std::vector<int64_t> dilation;
+ ConvolutionMode_t math_mode = ConvolutionMode_t::CROSS_CORRELATION;
+
+ public:
+ enum class input_names { DY, X };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+
+ enum class output_names { DW };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Conv_wgrad_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ pre_padding,
+ post_padding,
+ stride,
+ dilation,
+ math_mode)
+
+ ConvolutionMode_t
+ get_convolution_mode() const {
+ return math_mode;
+ }
+
+ std::vector<int64_t>
+ get_pre_padding() const {
+ return pre_padding;
+ }
+
+ std::vector<int64_t>
+ get_post_padding() const {
+ return post_padding;
+ }
+
+ Conv_wgrad_attributes&
+ set_convolution_mode(ConvolutionMode_t mode_) {
+ math_mode = mode_;
+ ;
+ return *this;
+ }
+
+ Conv_wgrad_attributes&
+ set_padding(std::vector<int64_t> value) {
+ pre_padding = value;
+ post_padding = value;
+ return *this;
+ }
+
+ Conv_wgrad_attributes&
+ set_pre_padding(std::vector<int64_t> value) {
+ pre_padding = value;
+ return *this;
+ }
+
+ Conv_wgrad_attributes&
+ set_post_padding(std::vector<int64_t> value) {
+ post_padding = value;
+ return *this;
+ }
+
+ std::vector<int64_t>
+ get_stride() const {
+ return stride;
+ }
+
+ Conv_wgrad_attributes&
+ set_stride(std::vector<int64_t> value) {
+ stride = value;
+ return *this;
+ }
+
+ std::vector<int64_t>
+ get_dilation() const {
+ return dilation;
+ }
+
+ Conv_wgrad_attributes&
+ set_dilation(std::vector<int64_t> value) {
+ dilation = value;
+ return *this;
+ }
+};
+
+class Slice_attributes : public Attributes<Slice_attributes> {
+ friend class Attributes<Slice_attributes>;
+ friend class SliceNode;
+ friend class INode;
+
+ std::vector<std::pair<int64_t, int64_t>> slices;
+ std::vector<int64_t> slice_strides = {1};
+
+ public:
+ enum class input_names { X };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Slice_attributes, name, compute_data_type, inputs, outputs, slices, slice_strides)
+
+ Slice_attributes&
+ set_slices(std::vector<std::pair<int64_t, int64_t>> const value) {
+ slices = value;
+ return *this;
+ }
+
+ Slice_attributes&
+ set_strides(std::vector<int64_t> const value) {
+ slice_strides = value;
+ return *this;
+ }
+
+ int64_t
+ get_offset() const {
+ auto& input = inputs.at(input_names::X);
+ auto const input_stride = input->get_stride();
+
+ int64_t offset = 0;
+
+ // Get number of elements to skip
+ for (size_t i = 0; i < slices.size(); ++i) {
+ offset += slices[i].first * input_stride[i];
+ }
+
+ // multiply by element size to get offset in bytes
+ offset *= detail::get_data_type_size(input->get_data_type());
+ return offset;
+ }
+};
+
+class PagedCacheLoad_attributes : public Attributes<PagedCacheLoad_attributes> {
+ friend class Attributes<PagedCacheLoad_attributes>;
+ friend class PagedCacheLoadNode;
+ friend class INode;
+
+ public:
+ enum class input_names { container, seqLen, pageTable };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { yOut };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(PagedCacheLoad_attributes, name, compute_data_type, inputs, outputs)
+};
+
+class Block_scale_quantize_attributes : public Attributes<Block_scale_quantize_attributes> {
+ friend class Attributes<Block_scale_quantize_attributes>;
+ friend class BlockScaleQuantizeNode;
+ friend class Graph;
+
+ std::optional<int32_t> block_size;
+ std::optional<int64_t> axis;
+ bool transpose = false;
+
+ public:
+ enum class input_names { X };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y, scale };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Block_scale_quantize_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ block_size,
+ axis)
+
+ Block_scale_quantize_attributes&
+ set_block_size(int32_t const value) {
+ block_size = value;
+ return *this;
+ }
+
+ Block_scale_quantize_attributes&
+ set_axis(int64_t const value) {
+ axis = value;
+ return *this;
+ }
+
+ Block_scale_quantize_attributes&
+ set_transpose(bool const value) {
+ transpose = value;
+ return *this;
+ }
+};
+
+class Block_scale_dequantize_attributes : public Attributes<Block_scale_dequantize_attributes> {
+ friend class Attributes<Block_scale_dequantize_attributes>;
+ friend class BlockScaleDequantizeNode;
+ friend class Graph;
+
+ std::vector<int32_t> block_size;
+ bool is_negative_scale;
+
+ public:
+ enum class input_names { X, scale };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Block_scale_dequantize_attributes,
+ name,
+ compute_data_type,
+ inputs,
+ outputs,
+ block_size,
+ is_negative_scale)
+
+ Block_scale_dequantize_attributes&
+ set_block_size(int32_t const value, int32_t idx = 0) {
+ if (idx < 0) {
+ return *this;
+ }
+ if (static_cast<int32_t>(block_size.size()) < idx + 1) {
+ block_size.resize(idx + 1, 1);
+ }
+ block_size[idx] = value;
+ return *this;
+ }
+
+ Block_scale_dequantize_attributes&
+ set_block_size(const int32_t* values, int32_t len = 1) {
+ if (len < 1) {
+ return *this;
+ }
+ if (static_cast<int32_t>(block_size.size()) < len) {
+ block_size.resize(len);
+ }
+ std::copy(values, values + len, block_size.begin());
+ return *this;
+ }
+
+ Block_scale_dequantize_attributes&
+ set_block_size(const std::vector<int32_t>& values) {
+ block_size = values;
+ return *this;
+ }
+
+ bool
+ get_is_negative_scale() const {
+ return is_negative_scale;
+ }
+
+ Block_scale_dequantize_attributes&
+ set_is_negative_scale(bool value) {
+ is_negative_scale = value;
+ return *this;
+ }
+};
+
+#if 0
+class Concatenate_string {
+ friend class Attributes<Concatenate_attributes>;
+ friend class ConcatenateNode;
+ friend class Graph;
+public:
+std::string str;
+NLOHMANN_DEFINE_TYPE_INTRUSIVE(Concatenate_string, str)
+};
+#endif
+
+class Concatenate_attributes : public Attributes<Concatenate_attributes> {
+ friend class Attributes<Concatenate_attributes>;
+ friend class ConcatenateNode;
+ friend class Graph;
+
+ std::optional<int64_t> axis;
+ std::optional<int64_t> in_place_index;
+
+ public:
+ std::vector<std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Y };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Concatenate_attributes, name, inputs, outputs, axis, in_place_index)
+
+ Concatenate_attributes&
+ set_axis(int64_t const value) {
+ axis = value;
+ return *this;
+ }
+
+ Concatenate_attributes&
+ set_in_place_index(int64_t const value) {
+ in_place_index = value;
+ return *this;
+ }
+};
+
+class Moe_grouped_matmul_attributes : public Attributes<Moe_grouped_matmul_attributes> {
+ friend class Attributes<Moe_grouped_matmul_attributes>;
+ friend class MoeGroupedMatmulNode;
+ friend class Graph;
+
+ MoeGroupedMatmulMode_t mode = MoeGroupedMatmulMode_t::NONE;
+
+ int32_t top_k = 0;
+
+ public:
+ enum class input_names { Token, Weight, FirstTokenOffset, TokenIndex, TokenKs };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { Output };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Moe_grouped_matmul_attributes, name, inputs, outputs, mode, top_k)
+
+ Moe_grouped_matmul_attributes&
+ set_mode(MoeGroupedMatmulMode_t mode) {
+ this->mode = mode;
+ return *this;
+ }
+
+ Moe_grouped_matmul_attributes&
+ set_top_k(int32_t top_k) {
+ this->top_k = top_k;
+ return *this;
+ }
+};
+
+class Moe_grouped_matmul_bwd_attributes : public Attributes<Moe_grouped_matmul_bwd_attributes> {
+ friend class Attributes<Moe_grouped_matmul_bwd_attributes>;
+ friend class MoeGroupedMatmulBwdNode;
+ friend class Graph;
+
+ public:
+ enum class input_names { DOutput, Token, FirstTokenOffset };
+ std::unordered_map<input_names, std::shared_ptr<Tensor_attributes>> inputs;
+ enum class output_names { DWeight };
+ std::unordered_map<output_names, std::shared_ptr<Tensor_attributes>> outputs;
+ NLOHMANN_DEFINE_TYPE_INTRUSIVE(Moe_grouped_matmul_bwd_attributes, name, inputs, outputs)
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/knobs.h b/deps/cudnn-frontend/include/cudnn_frontend/knobs.h
new file mode 100644
index 0000000..559643a
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/knobs.h
@@ -0,0 +1,254 @@
+#pragma once
+
+namespace cudnn_frontend {
+
+enum class KnobType_t {
+ NOT_SET,
+
+ SWIZZLE,
+ TILE_SIZE,
+ EDGE,
+ MULTIPLY,
+ SPLIT_K_BUF,
+ TILEK,
+ STAGES,
+ REDUCTION_MODE,
+ SPLIT_K_SLC,
+ IDX_MODE,
+ SPECFILT,
+ KERNEL_CFG,
+ WORKSPACE,
+ TILE_CGA_M,
+ TILE_CGA_N,
+ BLOCK_SIZE,
+ OCCUPANCY,
+ ARRAY_SIZE_PER_THREAD,
+ SPLIT_COLS,
+ TILE_ROWS,
+ TILE_COLS,
+ LOAD_SIZE,
+ CTA_COUNT,
+ STREAM_K,
+ SPLIT_P_SLC,
+ TILE_M,
+ TILE_N,
+ WARP_SPEC_CFG,
+ SWAP_AB,
+ INPUT_TMA_ENABLE,
+ OUTPUT_TMA_ENABLE,
+};
+
+class Knob {
+ public:
+ KnobType_t type = KnobType_t::NOT_SET;
+ int64_t maxValue = 0;
+ int64_t minValue = 0;
+ int64_t stride = 0;
+
+ Knob(KnobType_t type, int64_t max, int64_t min, int64_t str)
+ : type(type), maxValue(max), minValue(min), stride(str) {}
+};
+
+static inline cudnnStatus_t
+convert_to_backend_knob_type(KnobType_t const knob_type, cudnnBackendKnobType_t& cudnn_knob_type) {
+ switch (knob_type) {
+ case KnobType_t::SWIZZLE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_SWIZZLE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::TILE_SIZE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_TILE_SIZE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::EDGE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_EDGE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::MULTIPLY:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_MULTIPLY;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::SPLIT_K_BUF:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_SPLIT_K_BUF;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::TILEK:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_TILEK;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::STAGES:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_STAGES;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::REDUCTION_MODE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_REDUCTION_MODE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::SPLIT_K_SLC:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_SPLIT_K_SLC;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::IDX_MODE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_IDX_MODE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::SPECFILT:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_SPECFILT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::KERNEL_CFG:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_KERNEL_CFG;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::WORKSPACE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_WORKSPACE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#if (CUDNN_VERSION >= 8600)
+ case KnobType_t::TILE_CGA_M:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_TILE_CGA_M;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::TILE_CGA_N:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_TILE_CGA_N;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#if (CUDNN_VERSION >= 8800)
+ case KnobType_t::BLOCK_SIZE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_BLOCK_SIZE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#if (CUDNN_VERSION >= 8900)
+ case KnobType_t::OCCUPANCY:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_OCCUPANCY;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::ARRAY_SIZE_PER_THREAD:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_ARRAY_SIZE_PER_THREAD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#if (CUDNN_VERSION >= 8905)
+ case KnobType_t::SPLIT_COLS:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_SPLIT_COLS;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::TILE_ROWS:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_TILE_ROWS;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::TILE_COLS:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_TILE_COLS;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::LOAD_SIZE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_LOAD_SIZE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#if (CUDNN_VERSION >= 90700)
+ case KnobType_t::CTA_COUNT:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_CTA_COUNT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::STREAM_K:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_STREAM_K;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::SPLIT_P_SLC:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_SPLIT_P_SLC;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::TILE_M:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_TILE_M;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::TILE_N:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_TILE_N;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::WARP_SPEC_CFG:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_WARP_SPEC_CFG;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#if (CUDNN_VERSION >= 91800)
+ case KnobType_t::SWAP_AB:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_SWAP_AB;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#if (CUDNN_VERSION >= 92200)
+ case KnobType_t::INPUT_TMA_ENABLE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_INPUT_TMA_ENABLE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case KnobType_t::OUTPUT_TMA_ENABLE:
+ cudnn_knob_type = CUDNN_KNOB_TYPE_OUTPUT_TMA_ENABLE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+inline KnobType_t
+convert_from_backend_knob_type(cudnnBackendKnobType_t cudnn_knob_type) {
+ switch (cudnn_knob_type) {
+ case CUDNN_KNOB_TYPE_SWIZZLE:
+ return KnobType_t::SWIZZLE;
+ case CUDNN_KNOB_TYPE_TILE_SIZE:
+ return KnobType_t::TILE_SIZE;
+ case CUDNN_KNOB_TYPE_EDGE:
+ return KnobType_t::EDGE;
+ case CUDNN_KNOB_TYPE_MULTIPLY:
+ return KnobType_t::MULTIPLY;
+ case CUDNN_KNOB_TYPE_SPLIT_K_BUF:
+ return KnobType_t::SPLIT_K_BUF;
+ case CUDNN_KNOB_TYPE_TILEK:
+ return KnobType_t::TILEK;
+ case CUDNN_KNOB_TYPE_STAGES:
+ return KnobType_t::STAGES;
+ case CUDNN_KNOB_TYPE_REDUCTION_MODE:
+ return KnobType_t::REDUCTION_MODE;
+ case CUDNN_KNOB_TYPE_SPLIT_K_SLC:
+ return KnobType_t::SPLIT_K_SLC;
+ case CUDNN_KNOB_TYPE_IDX_MODE:
+ return KnobType_t::IDX_MODE;
+ case CUDNN_KNOB_TYPE_SPECFILT:
+ return KnobType_t::SPECFILT;
+ case CUDNN_KNOB_TYPE_KERNEL_CFG:
+ return KnobType_t::KERNEL_CFG;
+ case CUDNN_KNOB_TYPE_WORKSPACE:
+ return KnobType_t::WORKSPACE;
+#if (CUDNN_VERSION >= 8600)
+ case CUDNN_KNOB_TYPE_TILE_CGA_M:
+ return KnobType_t::TILE_CGA_M;
+ case CUDNN_KNOB_TYPE_TILE_CGA_N:
+ return KnobType_t::TILE_CGA_N;
+#endif
+#if (CUDNN_VERSION >= 8800)
+ case CUDNN_KNOB_TYPE_BLOCK_SIZE:
+ return KnobType_t::BLOCK_SIZE;
+#endif
+#if (CUDNN_VERSION >= 8900)
+ case CUDNN_KNOB_TYPE_OCCUPANCY:
+ return KnobType_t::OCCUPANCY;
+ case CUDNN_KNOB_TYPE_ARRAY_SIZE_PER_THREAD:
+ return KnobType_t::ARRAY_SIZE_PER_THREAD;
+#endif
+#if (CUDNN_VERSION >= 8905)
+ case CUDNN_KNOB_TYPE_SPLIT_COLS:
+ return KnobType_t::SPLIT_COLS;
+ case CUDNN_KNOB_TYPE_TILE_ROWS:
+ return KnobType_t::TILE_ROWS;
+ case CUDNN_KNOB_TYPE_TILE_COLS:
+ return KnobType_t::TILE_COLS;
+ case CUDNN_KNOB_TYPE_LOAD_SIZE:
+ return KnobType_t::LOAD_SIZE;
+#endif
+#if (CUDNN_VERSION >= 90700)
+ case CUDNN_KNOB_TYPE_CTA_COUNT:
+ return KnobType_t::CTA_COUNT;
+ case CUDNN_KNOB_TYPE_STREAM_K:
+ return KnobType_t::STREAM_K;
+ case CUDNN_KNOB_TYPE_SPLIT_P_SLC:
+ return KnobType_t::SPLIT_P_SLC;
+ case CUDNN_KNOB_TYPE_TILE_M:
+ return KnobType_t::TILE_M;
+ case CUDNN_KNOB_TYPE_TILE_N:
+ return KnobType_t::TILE_N;
+ case CUDNN_KNOB_TYPE_WARP_SPEC_CFG:
+ return KnobType_t::WARP_SPEC_CFG;
+#endif
+#if (CUDNN_VERSION >= 91800)
+ case CUDNN_KNOB_TYPE_SWAP_AB:
+ return KnobType_t::SWAP_AB;
+#endif
+#if (CUDNN_VERSION >= 92200)
+ case CUDNN_KNOB_TYPE_INPUT_TMA_ENABLE:
+ return KnobType_t::INPUT_TMA_ENABLE;
+ case CUDNN_KNOB_TYPE_OUTPUT_TMA_ENABLE:
+ return KnobType_t::OUTPUT_TMA_ENABLE;
+#endif
+ default:
+ return KnobType_t::NOT_SET;
+ }
+}
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/adaptive_layernorm.h b/deps/cudnn-frontend/include/cudnn_frontend/node/adaptive_layernorm.h
new file mode 100644
index 0000000..86eaa6d
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/adaptive_layernorm.h
@@ -0,0 +1,454 @@
+#pragma once
+
+#include "../../cudnn_frontend_Heuristics.h"
+#include "../../cudnn_frontend_Logging.h"
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+class AdaLayerNormNode : public NodeCRTP<AdaLayerNormNode> {
+ public:
+ AdaLayernorm_attributes attributes;
+
+ AdaLayerNormNode(AdaLayernorm_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::ADALAYERNORM;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for adalayernorm node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto X = attributes.inputs[AdaLayernorm_attributes::input_names::X];
+ auto Y = attributes.outputs[AdaLayernorm_attributes::output_names::Y];
+
+ // Only infer dims and strides if user did not set them
+ if (Y->get_dim().empty()) {
+ Y->set_dim(X->get_dim());
+ }
+ if (Y->get_stride().empty()) {
+ Y->set_stride(X->get_stride());
+ }
+
+ // scale_bias dim is 1,c,h,w
+ auto scale_bias_dim = X->get_dim();
+ scale_bias_dim[0] = 1;
+
+ auto scale = attributes.inputs[AdaLayernorm_attributes::input_names::SCALE];
+ // Only infer dims and strides if user did not set them
+ if (scale->get_dim().empty()) {
+ scale->set_dim(scale_bias_dim);
+ }
+ if (scale->get_stride().empty()) {
+ auto const& scale_dim = scale->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), scale_dim.size(), stride_order));
+ scale->set_stride(detail::generate_stride(scale_dim, stride_order));
+ }
+
+ auto bias = attributes.inputs[AdaLayernorm_attributes::input_names::BIAS];
+ // Only infer dims and strides if user did not set them
+ if (bias->get_dim().empty()) {
+ bias->set_dim(scale_bias_dim);
+ }
+ if (bias->get_stride().empty()) {
+ auto const& bias_dim = bias->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), bias_dim.size(), stride_order));
+ bias->set_stride(detail::generate_stride(bias_dim, stride_order));
+ }
+
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ // stats dim is x where scale == 1 else 1
+ auto stats_dim = X->get_dim();
+ for (size_t i = 1; i < stats_dim.size(); i++) {
+ if (scale->get_dim()[i] != 1) {
+ stats_dim[i] = 1;
+ }
+ }
+
+ auto mean = attributes.outputs[AdaLayernorm_attributes::output_names::MEAN];
+ // Only infer dims and strides if user did not set them
+ if (mean->get_dim().empty()) {
+ mean->set_dim(stats_dim);
+ }
+ if (mean->get_stride().empty()) {
+ auto const& mean_dim = mean->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), mean_dim.size(), stride_order));
+ mean->set_stride(detail::generate_stride(mean_dim, stride_order));
+ }
+
+ auto inv_var = attributes.outputs[AdaLayernorm_attributes::output_names::INV_VARIANCE];
+ // Only infer dims and strides if user did not set them
+ if (inv_var->get_dim().empty()) {
+ inv_var->set_dim(stats_dim);
+ }
+ if (inv_var->get_stride().empty()) {
+ auto const& inv_var_dim = inv_var->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), inv_var_dim.size(), stride_order));
+ inv_var->set_stride(detail::generate_stride(inv_var_dim, stride_order));
+ }
+ }
+
+ // Set scalar tensors
+ std::vector<int64_t> ones(X->get_dim().size(), 1);
+ auto infer_scalar_tensors = [&ones](std::shared_ptr<Tensor_attributes>& T) {
+ // Only infer dims and strides if user did not set them
+ if (T->get_dim().empty()) {
+ T->set_dim(ones);
+ }
+ if (T->get_stride().empty()) {
+ T->set_stride(ones);
+ }
+ };
+ infer_scalar_tensors(attributes.inputs[AdaLayernorm_attributes::input_names::EPSILON]);
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: " << "Validating AdaLayerNormNode " << attributes.name);
+ // Norm forward phase should be set
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.forward_phase == NormFwdPhase_t::NOT_SET,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Forward phase not set of adalayernorm node.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Building AdaLayernorm operations " << attributes.name << std::endl;
+
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "AdaLN fwd requires cuDNN v9.9.0"};
+#if (CUDNN_VERSION >= 90900)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90900, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+ auto adalayernorm_operation =
+ make_shared_backend_pointer((cudnnBackendDescriptorType_t)CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR);
+
+ cudnnBackendNormMode_t cudnn_norm_mode;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::ADA_LAYER_NORM, cudnn_norm_mode));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ cudnnBackendNormFwdPhase_t cudnn_norm_fwd_phase;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.forward_phase, cudnn_norm_fwd_phase));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_PHASE,
+ CUDNN_TYPE_NORM_FWD_PHASE,
+ 1,
+ &cudnn_norm_fwd_phase));
+
+ auto X = attributes.inputs.find(AdaLayernorm_attributes::input_names::X)->second;
+ auto backend_x = tensors[X->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_x));
+
+ auto Scale = attributes.inputs.find(AdaLayernorm_attributes::input_names::SCALE)->second;
+ auto backend_scale = tensors[Scale->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_scale));
+
+ auto Bias_iter = attributes.inputs.find(AdaLayernorm_attributes::input_names::BIAS);
+ if (Bias_iter != attributes.inputs.end() && Bias_iter->second->get_is_virtual() == false) {
+ auto backend_bias = tensors[Bias_iter->second->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_BIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_bias));
+ }
+
+ auto Epsilon = attributes.inputs.find(AdaLayernorm_attributes::input_names::EPSILON)->second;
+ auto backend_epsilon = tensors[Epsilon->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_EPSILON_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_epsilon));
+
+ auto Y = attributes.outputs.find(AdaLayernorm_attributes::output_names::Y)->second;
+ auto backend_y = tensors[Y->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_y));
+
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ auto Mean = attributes.outputs.find(AdaLayernorm_attributes::output_names::MEAN)->second;
+ auto backend_mean = tensors[Mean->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_mean));
+
+ auto Inv_variance = attributes.outputs.find(AdaLayernorm_attributes::output_names::INV_VARIANCE)->second;
+ auto backend_inv_variance = tensors[Inv_variance->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_inv_variance));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(adalayernorm_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(adalayernorm_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "ADA_LAYER_NORM"})"_json);
+ }
+#endif
+};
+
+/*******/
+
+class DAdaLayerNormNode : public NodeCRTP<DAdaLayerNormNode> {
+ public:
+ AdaLayernorm_backward_attributes attributes;
+
+ DAdaLayerNormNode(AdaLayernorm_backward_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::DADALAYERNORM;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for DAdaLayerNorm node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // TODO: Only inferencing from X works today.
+ auto X = attributes.inputs[AdaLayernorm_backward_attributes::input_names::X];
+ auto const x_tensor_dim = X->get_dim();
+
+ auto DY = attributes.inputs[AdaLayernorm_backward_attributes::input_names::DY];
+ auto dy_tensor_dim = DY->get_dim();
+
+ // Only infer dims and strides if user did not set them
+ if (dy_tensor_dim.empty()) {
+ dy_tensor_dim.resize(x_tensor_dim.size());
+ DY->set_dim(x_tensor_dim);
+ }
+ if (DY->get_stride().empty()) {
+ auto const& DY_dim = DY->get_dim();
+ // Default to NCHW
+ auto const& stride_order = detail::generate_row_major_stride_order(DY_dim.size());
+ DY->set_stride(detail::generate_stride(DY_dim, stride_order));
+ }
+
+ auto DX = attributes.outputs[AdaLayernorm_backward_attributes::output_names::DX];
+ auto dx_tensor_dim = DX->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (dx_tensor_dim.empty()) {
+ dx_tensor_dim.resize(x_tensor_dim.size());
+ DX->set_dim(x_tensor_dim);
+ }
+ if (DX->get_stride().empty()) {
+ auto const& DX_dim = DX->get_dim();
+ // Default to NCHW
+ auto const& stride_order = detail::generate_row_major_stride_order(DX_dim.size());
+ DX->set_stride(detail::generate_stride(DX_dim, stride_order));
+ }
+
+ auto SCALE = attributes.inputs[AdaLayernorm_backward_attributes::input_names::SCALE];
+ auto scale_bias_dim = SCALE->get_dim();
+
+ // Set channel length tensors
+ auto infer_scale_bias_tensors = [&scale_bias_dim](std::shared_ptr<Tensor_attributes>& T) {
+ auto tensor_dim = T->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (tensor_dim.empty()) {
+ T->set_dim(scale_bias_dim);
+ }
+ if (T->get_stride().empty()) {
+ auto const& T_dim = T->get_dim();
+ // Default to NCHW
+ auto const& stride_order = detail::generate_row_major_stride_order(T_dim.size());
+ T->set_stride(detail::generate_stride(T_dim, stride_order));
+ }
+ };
+
+ infer_scale_bias_tensors(attributes.outputs[AdaLayernorm_backward_attributes::output_names::DSCALE]);
+ auto DBIAS = attributes.outputs.at(AdaLayernorm_backward_attributes::output_names::DBIAS);
+ if (DBIAS->get_is_virtual() == false) {
+ infer_scale_bias_tensors(DBIAS);
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating DAdaLayerNormNode node " << attributes.name);
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Building DAdaLayerNormNode operations " << attributes.name
+ << std::endl;
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "AdaLN bwd requires cuDNN v9.9.0"};
+#if (CUDNN_VERSION >= 90900)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90900, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+ auto adalayernorm_operation =
+ make_shared_backend_pointer((cudnnBackendDescriptorType_t)CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR);
+
+ cudnnBackendNormMode_t cudnn_norm_mode;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::ADA_LAYER_NORM, cudnn_norm_mode));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ auto X = attributes.inputs.find(AdaLayernorm_backward_attributes::input_names::X)->second;
+ auto backend_x = tensors[X->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_x));
+
+ auto Mean = attributes.inputs.find(AdaLayernorm_backward_attributes::input_names::MEAN)->second;
+ auto backend_mean = tensors[Mean->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_mean));
+
+ auto Inv_variance = attributes.inputs.find(AdaLayernorm_backward_attributes::input_names::INV_VARIANCE)->second;
+ auto backend_inv_variance = tensors[Inv_variance->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_inv_variance));
+
+ auto Dy = attributes.inputs.find(AdaLayernorm_backward_attributes::input_names::DY)->second;
+ auto backend_dy = tensors[Dy->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DYDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_dy));
+
+ auto Scale = attributes.inputs.find(AdaLayernorm_backward_attributes::input_names::SCALE)->second;
+ auto backend_scale = tensors[Scale->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_scale));
+
+ auto Dx = attributes.outputs.find(AdaLayernorm_backward_attributes::output_names::DX)->second;
+ auto backend_dx = tensors[Dx->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_dx));
+
+ auto Dscale = attributes.outputs.find(AdaLayernorm_backward_attributes::output_names::DSCALE)->second;
+ auto backend_dscale = tensors[Dscale->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DSCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_dscale));
+
+ auto Dbias_iter = attributes.outputs.find(AdaLayernorm_backward_attributes::output_names::DBIAS);
+ if (Dbias_iter != attributes.outputs.end() && Dbias_iter->second->get_is_virtual() == false) {
+ auto backend_dbias = tensors[Dbias_iter->second->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(adalayernorm_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DBIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_dbias));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(adalayernorm_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(adalayernorm_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "ADA_LAYER_NORM_BPROP"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/batchnorm.h b/deps/cudnn-frontend/include/cudnn_frontend/node/batchnorm.h
new file mode 100644
index 0000000..69d232b
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/batchnorm.h
@@ -0,0 +1,268 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+class BatchNormNode : public NodeCRTP<BatchNormNode> {
+ public:
+ Batchnorm_attributes attributes;
+
+ BatchNormNode(Batchnorm_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::BATCHNORM;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for batchnorm node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto X = attributes.inputs[Batchnorm_attributes::input_names::X];
+ auto Y = attributes.outputs[Batchnorm_attributes::output_names::Y];
+ // Only infer dims and strides if user did not set them
+ if (Y->get_dim().empty()) {
+ Y->set_dim(X->get_dim());
+ }
+ if (Y->get_stride().empty()) {
+ Y->set_stride(X->get_stride());
+ }
+
+ // Set channel length tensors
+ auto const x_tensor_dim = X->get_dim();
+ auto infer_per_channel_tensors = [&x_tensor_dim](std::shared_ptr<Tensor_attributes>& T) {
+ auto tensor_dim = T->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (tensor_dim.empty()) {
+ tensor_dim.resize(x_tensor_dim.size(), 1);
+ tensor_dim[1] = x_tensor_dim[1];
+ T->set_dim(tensor_dim);
+ }
+ if (T->get_stride().empty()) {
+ auto const& T_dim = T->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(T_dim.size());
+ T->set_stride(detail::generate_stride(T_dim, stride_order));
+ }
+ };
+ infer_per_channel_tensors(attributes.outputs[Batchnorm_attributes::output_names::MEAN]);
+ infer_per_channel_tensors(attributes.outputs[Batchnorm_attributes::output_names::INV_VARIANCE]);
+
+ auto has_running_stats = attributes.inputs[Batchnorm_attributes::input_names::PREV_RUNNING_MEAN] ||
+ attributes.inputs[Batchnorm_attributes::input_names::PREV_RUNNING_VAR];
+
+ if (has_running_stats) {
+ infer_per_channel_tensors(attributes.outputs[Batchnorm_attributes::output_names::NEXT_RUNNING_MEAN]);
+ infer_per_channel_tensors(attributes.outputs[Batchnorm_attributes::output_names::NEXT_RUNNING_VAR]);
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building BatchNormNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 batchnorm_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ batchnorm_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR));
+
+ // Set norm mode to BATCH_NORM
+ cudnnBackendNormMode_t cudnn_norm_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::BATCH_NORM, cudnn_norm_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ // Set forward phase to TRAINING
+ cudnnBackendNormFwdPhase_t cudnn_norm_fwd_phase;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormFwdPhase_t::TRAINING, cudnn_norm_fwd_phase));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_PHASE,
+ CUDNN_TYPE_NORM_FWD_PHASE,
+ 1,
+ &cudnn_norm_fwd_phase));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Batchnorm_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set saved mean and inv_variance
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(MEAN, Batchnorm_attributes::output_names::MEAN);
+ auto mean_desc = tensors.at(MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &mean_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(INV_VARIANCE, Batchnorm_attributes::output_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+
+ // Set scale and bias tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, Batchnorm_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(BIAS, Batchnorm_attributes::input_names::BIAS);
+ auto bias_desc = tensors.at(BIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_BIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &bias_desc));
+
+ // Set epsilon tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(EPSILON, Batchnorm_attributes::input_names::EPSILON);
+ auto epsilon_desc = tensors.at(EPSILON->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_EPSILON_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &epsilon_desc));
+
+ // Check for running stats
+ bool has_running_stats = true;
+ auto it = attributes.inputs.find(Batchnorm_attributes::input_names::PREV_RUNNING_MEAN);
+ if (it == attributes.inputs.end() || it->second == nullptr) {
+ has_running_stats = false;
+ }
+
+ if (has_running_stats) {
+ // Set momentum (exp decay factor)
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(MOMENTUM, Batchnorm_attributes::input_names::MOMENTUM);
+ auto momentum_desc = tensors.at(MOMENTUM->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_EXP_AVG_FACTOR_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &momentum_desc));
+
+ // Set prev running mean and var
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(PREV_RUNNING_MEAN,
+ Batchnorm_attributes::input_names::PREV_RUNNING_MEAN);
+ auto prev_mean_desc = tensors.at(PREV_RUNNING_MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_INPUT_RUNNING_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &prev_mean_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(PREV_RUNNING_VAR,
+ Batchnorm_attributes::input_names::PREV_RUNNING_VAR);
+ auto prev_var_desc = tensors.at(PREV_RUNNING_VAR->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_INPUT_RUNNING_VAR_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &prev_var_desc));
+
+ // Set next running mean and var
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(NEXT_RUNNING_MEAN,
+ Batchnorm_attributes::output_names::NEXT_RUNNING_MEAN);
+ auto next_mean_desc = tensors.at(NEXT_RUNNING_MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_OUTPUT_RUNNING_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &next_mean_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(NEXT_RUNNING_VAR,
+ Batchnorm_attributes::output_names::NEXT_RUNNING_VAR);
+ auto next_var_desc = tensors.at(NEXT_RUNNING_VAR->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_OUTPUT_RUNNING_VAR_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &next_var_desc));
+ }
+
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Batchnorm_attributes::output_names::Y);
+ auto y_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ // Set peer stat tensors if any
+ if (!attributes.peer_stats.empty()) {
+ std::vector<cudnnBackendDescriptor_t> peer_stat_descs;
+ for (auto const& peer_stat : attributes.peer_stats) {
+ peer_stat_descs.push_back(tensors.at(peer_stat->get_uid())->get_raw_desc());
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_PEER_STAT_DESCS,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ peer_stat_descs.size(),
+ peer_stat_descs.data()));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(batchnorm_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(batchnorm_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "BATCHNORM"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/batchnorm_inference.h b/deps/cudnn-frontend/include/cudnn_frontend/node/batchnorm_inference.h
new file mode 100644
index 0000000..9fb433f
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/batchnorm_inference.h
@@ -0,0 +1,156 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+class BatchnormInferenceNode : public NodeCRTP<BatchnormInferenceNode> {
+ public:
+ Batchnorm_inference_attributes attributes;
+
+ BatchnormInferenceNode(Batchnorm_inference_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::BATCHNORM_INFERENCE;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for batchnorm inference node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto X = attributes.inputs[Batchnorm_inference_attributes::input_names::X];
+ auto Y = attributes.outputs[Batchnorm_inference_attributes::output_names::Y];
+ // Only infer dims and strides if user did not set them
+ if (Y->get_dim().empty()) {
+ Y->set_dim(X->get_dim());
+ }
+ if (Y->get_stride().empty()) {
+ Y->set_stride(X->get_stride());
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building BatchnormInferenceNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 batchnorm_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ batchnorm_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR));
+
+ // Set norm mode to BATCH_NORM
+ cudnnBackendNormMode_t cudnn_norm_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::BATCH_NORM, cudnn_norm_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ // Set forward phase to INFERENCE
+ cudnnBackendNormFwdPhase_t cudnn_norm_fwd_phase;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormFwdPhase_t::INFERENCE, cudnn_norm_fwd_phase));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_PHASE,
+ CUDNN_TYPE_NORM_FWD_PHASE,
+ 1,
+ &cudnn_norm_fwd_phase));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Batchnorm_inference_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set mean and inv_variance (as inputs for inference)
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(MEAN, Batchnorm_inference_attributes::input_names::MEAN);
+ auto mean_desc = tensors.at(MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &mean_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(INV_VARIANCE,
+ Batchnorm_inference_attributes::input_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+
+ // Set scale and bias tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, Batchnorm_inference_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(BIAS, Batchnorm_inference_attributes::input_names::BIAS);
+ auto bias_desc = tensors.at(BIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_BIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &bias_desc));
+
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Batchnorm_inference_attributes::output_names::Y);
+ auto y_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(batchnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(batchnorm_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(batchnorm_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "BATCHNORM_INFERENCE"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/block_scale_dequantize.h b/deps/cudnn-frontend/include/cudnn_frontend/node/block_scale_dequantize.h
new file mode 100644
index 0000000..bbaa2bf
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/block_scale_dequantize.h
@@ -0,0 +1,169 @@
+#pragma once
+
+#include "../../cudnn_frontend_Logging.h"
+#include "../../cudnn_frontend_shim.h"
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+class BlockScaleDequantizeNode : public NodeCRTP<BlockScaleDequantizeNode> {
+ public:
+ Block_scale_dequantize_attributes attributes;
+
+ BlockScaleDequantizeNode(Block_scale_dequantize_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::BLOCK_SCALE_DEQUANTIZE;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ getLogger() << "[cudnn_frontend] INFO: "
+ << "Validating BlockScaleDequantizeNode " << attributes.name << std::endl;
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.block_size.empty(), error_code_t::ATTRIBUTE_NOT_SET, "Block size not set\n");
+
+ auto Y = attributes.outputs.at(Block_scale_dequantize_attributes::output_names::Y);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!(Y->get_is_virtual()),
+ error_code_t::INVALID_VALUE,
+ "Output tensor of dequantize node should be virtual\n");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ getLogger() << "[cudnn_frontend] INFO: Inferencing properties for BlockScaleDequantizeNode " << attributes.name
+ << std::endl;
+
+ attributes.fill_from_context(context);
+
+ auto X = attributes.inputs[Block_scale_dequantize_attributes::input_names::X];
+ auto scale = attributes.inputs[Block_scale_dequantize_attributes::input_names::scale];
+ auto Y = attributes.outputs[Block_scale_dequantize_attributes::output_names::Y];
+
+ // Only infer dims and strides if user did not set them
+ if (Y->get_dim().empty()) {
+ Y->set_dim(X->get_dim());
+ }
+
+ if (Y->get_stride().empty()) {
+ Y->set_stride(X->get_stride());
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: "
+ << "Building BlockScaleDequantizeNode operations " << attributes.name << std::endl;
+ auto cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Block scale dequantize requires cuDNN v9.7.0"};
+
+#if (CUDNN_VERSION >= 90700) // TODO: v9.99 is new feature branch; switch to release branch when ready
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90700, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+ auto block_scale_dequantize_operation = make_shared_backend_pointer(
+ (cudnnBackendDescriptorType_t)CUDNN_BACKEND_OPERATION_BLOCK_SCALE_DEQUANTIZE_DESCRIPTOR);
+
+ auto X = attributes.inputs.find(Block_scale_dequantize_attributes::input_names::X)->second;
+ auto backend_x = tensors[X->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_dequantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_DEQUANTIZE_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_x));
+
+ auto scale = attributes.inputs.find(Block_scale_dequantize_attributes::input_names::scale)->second;
+ auto backend_scale = tensors[scale->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_dequantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_DEQUANTIZE_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_scale));
+
+ auto Y = attributes.outputs.find(Block_scale_dequantize_attributes::output_names::Y)->second;
+ auto backend_y = tensors[Y->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_dequantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_DEQUANTIZE_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_y));
+
+ cudnnDataType_t cudnn_data_type;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_dequantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_DEQUANTIZE_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ const int32_t* block_size = attributes.block_size.data();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_dequantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_DEQUANTIZE_BLOCK_SIZE,
+ CUDNN_TYPE_INT32,
+ attributes.block_size.size(),
+ block_size));
+
+#if (CUDNN_VERSION >= 91400)
+ if (detail::get_backend_version() >= 91400) {
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_dequantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_DEQUANTIZE_NEG_SCALE,
+ CUDNN_TYPE_BOOLEAN,
+ 1,
+ &attributes.is_negative_scale));
+ }
+#endif
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(block_scale_dequantize_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(block_scale_dequantize_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "BLOCK_SCALE_DEQUANTIZE"})"_json);
+ }
+#endif
+};
+
+inline void
+INode::block_scale_dequantize(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ Block_scale_dequantize_attributes attributes,
+ std::shared_ptr<Tensor_attributes> y) {
+ attributes.inputs[Block_scale_dequantize_attributes::input_names::X] = x;
+ attributes.inputs[Block_scale_dequantize_attributes::input_names::scale] = scale;
+ attributes.outputs[Block_scale_dequantize_attributes::output_names::Y] = y;
+ sub_nodes.emplace_back(std::make_unique<BlockScaleDequantizeNode>(std::move(attributes), context));
+}
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/block_scale_quantize.h b/deps/cudnn-frontend/include/cudnn_frontend/node/block_scale_quantize.h
new file mode 100644
index 0000000..494ea14
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/block_scale_quantize.h
@@ -0,0 +1,205 @@
+#pragma once
+
+#include "../../cudnn_frontend_Logging.h"
+#include "../../cudnn_frontend_shim.h"
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+class BlockScaleQuantizeNode : public NodeCRTP<BlockScaleQuantizeNode> {
+ public:
+ Block_scale_quantize_attributes attributes;
+
+ BlockScaleQuantizeNode(Block_scale_quantize_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::BLOCK_SCALE_QUANTIZE;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Validating BlockScaleQuantizeNode " << attributes.name
+ << std::endl;
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !attributes.block_size.has_value(), error_code_t::ATTRIBUTE_NOT_SET, "Block size not set.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ getLogger() << "[cudnn_frontend] INFO: Inferencing properties for BlockScaleQuantizeNode " << attributes.name
+ << std::endl;
+
+ attributes.fill_from_context(context);
+
+ auto X = attributes.inputs[Block_scale_quantize_attributes::input_names::X];
+ auto Y = attributes.outputs[Block_scale_quantize_attributes::output_names::Y];
+ auto scale = attributes.outputs[Block_scale_quantize_attributes::output_names::scale];
+
+ // Block scale quantize requires the block scale axis to be packed
+ auto infer_strides_transposed = [&X](std::shared_ptr<Tensor_attributes>& T,
+ std::optional<int64_t> const& axis) {
+ auto const& dim = T->get_dim();
+ auto const& X_dim = X->get_dim();
+ auto const& X_stride = X->get_stride();
+
+ std::vector<int64_t> indices(X_stride.size());
+ std::iota(indices.begin(), indices.end(), 0);
+ // Sort indices based on stride values in descending order
+ std::sort(indices.begin(), indices.end(), [&X_dim, &X_stride](int64_t i, int64_t j) {
+ // Prioritize singleton dimensions
+ if (X_stride[i] == X_stride[j]) {
+ return (X_dim[i] == 1) && (X_dim[j] != 1);
+ }
+ return X_stride[i] < X_stride[j];
+ });
+ if (axis) {
+ // Rotate left until the axis is the packed dim
+ std::rotate(indices.begin(), std::find(indices.begin(), indices.end(), axis.value()), indices.end());
+ }
+ std::vector<int64_t> stride_order(X_stride.size());
+ for (size_t i = 0; i < indices.size(); ++i) {
+ stride_order[indices[i]] = i;
+ }
+ T->set_stride(detail::generate_stride(dim, stride_order));
+ };
+
+ // Only infer dims and strides if user did not set them
+ if (Y->get_dim().empty()) {
+ Y->set_dim(X->get_dim());
+ }
+ if (Y->get_stride().empty()) {
+ if (attributes.transpose) {
+ infer_strides_transposed(Y, attributes.axis);
+ } else {
+ Y->set_stride(X->get_stride());
+ }
+ }
+
+ // Only infer dims and strides if user did not set them
+ if (scale->get_dim().empty()) {
+ auto scale_dim = X->get_dim();
+ if (attributes.axis) {
+ scale_dim[attributes.axis.value()] /= attributes.block_size.value();
+ } else {
+ scale_dim.back() /= attributes.block_size.value();
+ }
+ scale->set_dim(scale_dim);
+ }
+ if (scale->get_stride().empty()) {
+ if (attributes.transpose) {
+ infer_strides_transposed(scale, attributes.axis);
+ } else {
+ auto const& scale_dim = scale->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), scale_dim.size(), stride_order));
+ scale->set_stride(detail::generate_stride(scale_dim, stride_order));
+ }
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Building BlockScaleQuantizeNode operations " << attributes.name
+ << std::endl;
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Block scale quantize requires cuDNN v9.7.0"};
+
+#if (CUDNN_VERSION >= 90700) // TODO: v9.99 is new feature branch; switch to release branch when ready
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90700, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+ auto block_scale_quantize_operation = make_shared_backend_pointer(
+ (cudnnBackendDescriptorType_t)CUDNN_BACKEND_OPERATION_BLOCK_SCALE_QUANTIZE_DESCRIPTOR);
+
+ auto X = attributes.inputs.find(Block_scale_quantize_attributes::input_names::X)->second;
+ auto backend_x = tensors[X->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_quantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_QUANTIZE_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_x));
+
+ auto Y = attributes.outputs.find(Block_scale_quantize_attributes::output_names::Y)->second;
+ auto backend_y = tensors[Y->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_quantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_QUANTIZE_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_y));
+
+ auto scale = attributes.outputs.find(Block_scale_quantize_attributes::output_names::scale)->second;
+ auto backend_scale = tensors[scale->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_quantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_QUANTIZE_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_scale));
+
+ cudnnDataType_t cudnn_data_type;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_quantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_QUANTIZE_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ int32_t block_size = attributes.block_size.value();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(block_scale_quantize_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BLOCK_SCALE_QUANTIZE_BLOCK_SIZE,
+ CUDNN_TYPE_INT32,
+ 1,
+ &block_size));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(block_scale_quantize_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(block_scale_quantize_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "BLOCK_SCALE_QUANTIZE"})"_json);
+ }
+#endif
+};
+
+inline void
+INode::block_scale_quantize(std::shared_ptr<Tensor_attributes> x,
+ Block_scale_quantize_attributes attributes,
+ std::shared_ptr<Tensor_attributes> y,
+ std::shared_ptr<Tensor_attributes> scale) {
+ attributes.inputs[Block_scale_quantize_attributes::input_names::X] = x;
+ attributes.outputs[Block_scale_quantize_attributes::output_names::Y] = y;
+ attributes.outputs[Block_scale_quantize_attributes::output_names::scale] = scale;
+ sub_nodes.emplace_back(std::make_unique<BlockScaleQuantizeNode>(std::move(attributes), context));
+}
+
+} // namespace graph
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/bn_finalize.h b/deps/cudnn-frontend/include/cudnn_frontend/node/bn_finalize.h
new file mode 100644
index 0000000..99d3ec0
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/bn_finalize.h
@@ -0,0 +1,263 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+class BatchNormFinalizeNode : public NodeCRTP<BatchNormFinalizeNode> {
+ public:
+ BN_finalize_attributes attributes;
+
+ BatchNormFinalizeNode(BN_finalize_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::BN_FINALIZE;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO:Inferencing properties for batchnorm finalize node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto SUM = attributes.inputs[BN_finalize_attributes::input_names::SUM];
+ auto const sum_tensor_dim = SUM->get_dim();
+
+ // Set channel length tensors
+ auto infer_per_channel_tensors = [&sum_tensor_dim](std::shared_ptr<Tensor_attributes>& T) {
+ auto tensor_dim = T->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (tensor_dim.empty()) {
+ tensor_dim = sum_tensor_dim;
+ T->set_dim(tensor_dim);
+ }
+ if (T->get_stride().empty()) {
+ auto const& T_dim = T->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(T_dim.size());
+ T->set_stride(detail::generate_stride(T_dim, stride_order));
+ }
+ };
+ infer_per_channel_tensors(attributes.outputs[BN_finalize_attributes::output_names::EQ_BIAS]);
+ infer_per_channel_tensors(attributes.outputs[BN_finalize_attributes::output_names::EQ_SCALE]);
+ infer_per_channel_tensors(attributes.outputs[BN_finalize_attributes::output_names::MEAN]);
+ infer_per_channel_tensors(attributes.outputs[BN_finalize_attributes::output_names::INV_VARIANCE]);
+ infer_per_channel_tensors(attributes.outputs[BN_finalize_attributes::output_names::NEXT_RUNNING_MEAN]);
+ infer_per_channel_tensors(attributes.outputs[BN_finalize_attributes::output_names::NEXT_RUNNING_VAR]);
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building BatchNormFinalizeNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 bn_finalize_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(bn_finalize_operation.initialize_managed_backend_pointer(
+ CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR));
+
+ // Set BN finalize mode
+ cudnnBnFinalizeStatsMode_t bn_finalize_mode = CUDNN_BN_FINALIZE_STATISTICS_TRAINING;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_STATS_MODE,
+ CUDNN_TYPE_BN_FINALIZE_STATS_MODE,
+ 1,
+ &bn_finalize_mode));
+
+ // Set compute type (math precision)
+ cudnnDataType_t compute_type = CUDNN_DATA_FLOAT;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &compute_type));
+
+ // Set SUM input tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SUM, BN_finalize_attributes::input_names::SUM);
+ auto sum_desc = tensors.at(SUM->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_Y_SUM_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &sum_desc));
+
+ // Set SQ_SUM input tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SQ_SUM, BN_finalize_attributes::input_names::SQ_SUM);
+ auto sq_sum_desc = tensors.at(SQ_SUM->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_Y_SQ_SUM_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &sq_sum_desc));
+
+ // Set SCALE input tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, BN_finalize_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ // Set BIAS input tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(BIAS, BN_finalize_attributes::input_names::BIAS);
+ auto bias_desc = tensors.at(BIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_BIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &bias_desc));
+
+ // Set EQ_SCALE output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(EQ_SCALE, BN_finalize_attributes::output_names::EQ_SCALE);
+ auto eq_scale_desc = tensors.at(EQ_SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EQ_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &eq_scale_desc));
+
+ // Set EQ_BIAS output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(EQ_BIAS, BN_finalize_attributes::output_names::EQ_BIAS);
+ auto eq_bias_desc = tensors.at(EQ_BIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EQ_BIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &eq_bias_desc));
+
+ // Set PREV_RUNNING_MEAN input tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(PREV_RUNNING_MEAN,
+ BN_finalize_attributes::input_names::PREV_RUNNING_MEAN);
+ auto prev_running_mean_desc = tensors.at(PREV_RUNNING_MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_PREV_RUNNING_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &prev_running_mean_desc));
+
+ // Set PREV_RUNNING_VAR input tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(PREV_RUNNING_VAR,
+ BN_finalize_attributes::input_names::PREV_RUNNING_VAR);
+ auto prev_running_var_desc = tensors.at(PREV_RUNNING_VAR->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_PREV_RUNNING_VAR_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &prev_running_var_desc));
+
+ // Set NEXT_RUNNING_MEAN output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(NEXT_RUNNING_MEAN,
+ BN_finalize_attributes::output_names::NEXT_RUNNING_MEAN);
+ auto next_running_mean_desc = tensors.at(NEXT_RUNNING_MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_UPDATED_RUNNING_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &next_running_mean_desc));
+
+ // Set NEXT_RUNNING_VAR output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(NEXT_RUNNING_VAR,
+ BN_finalize_attributes::output_names::NEXT_RUNNING_VAR);
+ auto next_running_var_desc = tensors.at(NEXT_RUNNING_VAR->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_UPDATED_RUNNING_VAR_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &next_running_var_desc));
+
+ // Set MEAN output tensor (saved mean)
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(MEAN, BN_finalize_attributes::output_names::MEAN);
+ auto mean_desc = tensors.at(MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_SAVED_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &mean_desc));
+
+ // Set INV_VARIANCE output tensor (saved inv std)
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(INV_VARIANCE, BN_finalize_attributes::output_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_SAVED_INV_STD_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+
+ // Set EPSILON tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(EPSILON, BN_finalize_attributes::input_names::EPSILON);
+ auto epsilon_desc = tensors.at(EPSILON->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EPSILON_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &epsilon_desc));
+
+ // Set MOMENTUM tensor (exp average factor)
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(MOMENTUM, BN_finalize_attributes::input_names::MOMENTUM);
+ auto momentum_desc = tensors.at(MOMENTUM->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EXP_AVERATE_FACTOR_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &momentum_desc));
+
+ // Set ACCUM_COUNT tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(ACCUM_COUNT, BN_finalize_attributes::input_names::ACCUM_COUNT);
+ auto accum_count_desc = tensors.at(ACCUM_COUNT->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_finalize_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_ACCUM_COUNT_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &accum_count_desc));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(bn_finalize_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(bn_finalize_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "BN_FINALIZE"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/concatenate.h b/deps/cudnn-frontend/include/cudnn_frontend/node/concatenate.h
new file mode 100644
index 0000000..5f62589
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/concatenate.h
@@ -0,0 +1,163 @@
+#pragma once
+
+#include "../../cudnn_frontend_Logging.h"
+#include "../../cudnn_frontend_shim.h"
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+#include <string>
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+class ConcatenateNode : public NodeCRTP<ConcatenateNode> {
+ public:
+ Concatenate_attributes attributes;
+
+ ConcatenateNode(Concatenate_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::CONCATENATE;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Validating ConcatenateNode " << attributes.name << std::endl;
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!attributes.axis.has_value(), error_code_t::ATTRIBUTE_NOT_SET, "Axis not set\n");
+
+ auto X = attributes.inputs;
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (X.size() == 0), error_code_t::INVALID_VALUE, "Input size of the concatenate node cannot be zero\n");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ getLogger() << "[cudnn_frontend] INFO: Inferring properties for ConcatenateNode " << attributes.name
+ << std::endl;
+
+ attributes.fill_from_context(context);
+
+ auto Y = attributes.outputs[Concatenate_attributes::output_names::Y];
+
+ // Infer dims and strides only if user did not set them
+ int64_t dim_sum = 0;
+ for (const auto& input : attributes.inputs) {
+ dim_sum += input->get_dim()[attributes.axis.value()];
+ }
+
+ auto X = attributes.inputs[0];
+ auto dims = X->get_dim();
+ dims[attributes.axis.value()] = dim_sum;
+
+ if (Y->get_dim().empty()) {
+ Y->set_dim(dims);
+ Y->set_dim(dims);
+ }
+
+ if (Y->get_stride().empty()) {
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), dims.size(), stride_order));
+ Y->set_stride(detail::generate_stride(dims, stride_order));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Building ConcatenateNode operations " << attributes.name
+ << std::endl;
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Concatenate requires cuDNN v9.7.0"};
+
+#if (CUDNN_VERSION >= 90700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90700, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+ auto concatenate_operation = make_shared_backend_pointer(CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR);
+
+ std::vector<void*> backend_x(attributes.inputs.size());
+ size_t index = 0;
+ for (const auto& input : attributes.inputs) {
+ backend_x[index] = tensors[input->get_uid()]->get_desc()->get_backend_descriptor();
+ index++;
+ }
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(concatenate_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONCAT_INPUT_DESCS,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ attributes.inputs.size(),
+ backend_x.data()));
+
+ auto Y = attributes.outputs.find(Concatenate_attributes::output_names::Y)->second;
+ auto backend_y = tensors[Y->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(concatenate_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONCAT_OUTPUT_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_y));
+
+ int64_t axis = attributes.axis.value();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(concatenate_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONCAT_AXIS,
+ CUDNN_TYPE_INT64,
+ 1,
+ &axis));
+
+ if (attributes.in_place_index.has_value()) {
+ int64_t in_place_index = attributes.in_place_index.value();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(concatenate_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONCAT_INPLACE_INDEX,
+ CUDNN_TYPE_INT64,
+ 1,
+ &in_place_index));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(concatenate_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(concatenate_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "CONCATENATE"})"_json);
+ }
+#endif
+};
+
+inline void
+INode::concatenate(std::vector<std::shared_ptr<Tensor_attributes>> x,
+ Concatenate_attributes attributes,
+ std::shared_ptr<Tensor_attributes> y) {
+ for (auto& element : x) {
+ attributes.inputs.push_back(element);
+ }
+ attributes.outputs[Concatenate_attributes::output_names::Y] = y;
+ sub_nodes.emplace_back(std::make_unique<ConcatenateNode>(std::move(attributes), context));
+}
+
+} // namespace graph
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/conv_dgrad.h b/deps/cudnn-frontend/include/cudnn_frontend/node/conv_dgrad.h
new file mode 100644
index 0000000..a2e2e4e
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/conv_dgrad.h
@@ -0,0 +1,205 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class DgradNode : public NodeCRTP<DgradNode> {
+ public:
+ Conv_dgrad_attributes attributes;
+
+ DgradNode(Conv_dgrad_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::DGRAD;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating Node Type::DGRAD " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_pre_padding().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Pre padding not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_post_padding().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Post padding not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_stride().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Conv strides not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_dilation().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Conv dilation not set.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for dgrad node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // TODO: Only inferrencing from (X, DY) -> DW works today.
+ auto DX = attributes.outputs.find(Conv_dgrad_attributes::output_names::DX)->second;
+ auto W = attributes.inputs.find(Conv_dgrad_attributes::input_names::W)->second;
+ auto DY = attributes.inputs.find(Conv_dgrad_attributes::input_names::DY)->second;
+
+ auto const w_tensor_dim = W->get_dim();
+ auto const dy_tensor_dim = DY->get_dim();
+ auto dx_tensor_dim = DX->get_dim();
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(DX->get_dim().empty(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "For dgrad node, output dimension inferencing is not possible.");
+
+ // No dim inferencing as inverse mapping from DY, W to DX is not unique.
+ // Only infer strides if user did not set them
+ if (DX->get_stride().empty()) {
+ auto const& DX_dim = DX->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(DX_dim.size());
+ DX->set_stride(detail::generate_stride(DX_dim, stride_order));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building DgradNode operations " << attributes.name << " ");
+
+ // Create dgrad descriptor by directly calling cuDNN backend API
+ ConvDesc_v8 dgrad_descriptor;
+ int64_t const spatial_dim_count = attributes.get_pre_padding().size();
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ dgrad_descriptor.initialize_managed_backend_pointer(CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR));
+
+ cudnnDataType_t cudnn_data_type;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_COMP_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ cudnnConvolutionMode_t mode = detail::convert_to_cudnn_type(attributes.math_mode);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ dgrad_descriptor.get_raw_desc(), CUDNN_ATTR_CONVOLUTION_CONV_MODE, CUDNN_TYPE_CONVOLUTION_MODE, 1, &mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_SPATIAL_DIMS,
+ CUDNN_TYPE_INT64,
+ 1,
+ &spatial_dim_count));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_PRE_PADDINGS,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_pre_padding().data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_POST_PADDINGS,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_post_padding().data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_DILATIONS,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_dilation().data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_FILTER_STRIDES,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_stride().data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(dgrad_descriptor.get_raw_desc()));
+ CUDNN_FE_LOG_LABEL_ENDL(dgrad_descriptor);
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 dgrad_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(dgrad_operation.initialize_managed_backend_pointer(
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DX, Conv_dgrad_attributes::output_names::DX);
+ auto dx_desc = tensors.at(DX->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_DX,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dx_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(W, Conv_dgrad_attributes::input_names::W);
+ auto w_desc = tensors.at(W->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_W,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &w_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(DY, Conv_dgrad_attributes::input_names::DY);
+ auto dy_desc = tensors.at(DY->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_DY,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dy_desc));
+
+ auto conv_desc_ptr = dgrad_descriptor.get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_CONV_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &conv_desc_ptr));
+
+ float alpha = 1.0f;
+ float beta = 0.0f;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_ALPHA,
+ CUDNN_TYPE_FLOAT,
+ 1,
+ &alpha));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_BETA,
+ CUDNN_TYPE_FLOAT,
+ 1,
+ &beta));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(dgrad_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(dgrad_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "CONV_DGRAD"})"_json);
+ }
+#endif
+};
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/conv_fprop.h b/deps/cudnn-frontend/include/cudnn_frontend/node/conv_fprop.h
new file mode 100644
index 0000000..34acf55
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/conv_fprop.h
@@ -0,0 +1,254 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+class ConvolutionNode : public NodeCRTP<ConvolutionNode> {
+ public:
+ Conv_fprop_attributes attributes;
+
+ ConvolutionNode(Conv_fprop_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::CONVOLUTION;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating Node Type::CONVOLUTION " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_pre_padding().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Pre padding not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_post_padding().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Post padding not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_stride().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Conv strides not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_dilation().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Conv dilation not set.");
+
+ // Implicit GEMM kernels compute B_offset as int32. When the product of all filter
+ // dimensions (K * C * spatial...) exceeds INT32_MAX the offset overflows, causing IMA or
+ // silent NaN. Conservative upper bound — exact check requires kernel tiling params not
+ // available at graph-validate time. Applies to 2D (4D filter) and 3D (5D filter) fprop.
+ auto W_it = attributes.inputs.find(Conv_fprop_attributes::input_names::W);
+ if (W_it != attributes.inputs.end() && W_it->second) {
+ auto const& w_dim = W_it->second->get_dim();
+ if (w_dim.size() == 4 || w_dim.size() == 5) {
+ int64_t filter_elements = 1;
+ for (auto d : w_dim) filter_elements *= d;
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ filter_elements > static_cast<int64_t>(std::numeric_limits<int32_t>::max()),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Conv filter total elements exceed INT32_MAX.");
+ }
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for conv node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // TODO: Only inferrencing from (X, W) -> Y works today.
+ auto& X = attributes.inputs.find(Conv_fprop_attributes::input_names::X)->second;
+ auto& W = attributes.inputs.find(Conv_fprop_attributes::input_names::W)->second;
+ auto& Y = attributes.outputs.find(Conv_fprop_attributes::output_names::Y)->second;
+
+ auto const x_tensor_dim = X->get_dim();
+ auto const w_tensor_dim = W->get_dim();
+ auto y_tensor_dim = Y->get_dim();
+
+ // Only infer dims and strides if user did not set them
+ if (y_tensor_dim.empty()) {
+ y_tensor_dim.resize(x_tensor_dim.size());
+ auto const& pre_padding = attributes.get_pre_padding();
+ auto const& post_padding = attributes.get_post_padding();
+ auto const& stride = attributes.get_stride();
+ auto const& dilation = attributes.get_dilation();
+ // N
+ y_tensor_dim[0] = x_tensor_dim[0];
+ // PQ
+ for (size_t dim = 2; dim < x_tensor_dim.size(); ++dim) {
+ y_tensor_dim[dim] = 1 + (x_tensor_dim[dim] - dilation[dim - 2] * (w_tensor_dim[dim] - 1) - 1 +
+ pre_padding[dim - 2] + post_padding[dim - 2]) /
+ stride[dim - 2];
+ }
+ // K
+ y_tensor_dim[1] = w_tensor_dim[0];
+ Y->set_dim(y_tensor_dim);
+ }
+ if (Y->get_stride().empty()) {
+ auto const& Y_dim = Y->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(Y_dim.size());
+ Y->set_stride(detail::generate_stride(Y_dim, stride_order));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building ConvolutionNode operations " << attributes.name << " ");
+
+ // Create convolution descriptor by directly calling cuDNN backend API
+ ConvDesc_v8 convolution_descriptor;
+ int64_t const spatial_dim_count = attributes.get_pre_padding().size();
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ convolution_descriptor.initialize_managed_backend_pointer(CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR));
+
+ // Set compute type
+ cudnnDataType_t cudnn_data_type;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_COMP_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ // Set convolution mode
+ cudnnConvolutionMode_t mode = detail::convert_to_cudnn_type(attributes.math_mode);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_CONV_MODE,
+ CUDNN_TYPE_CONVOLUTION_MODE,
+ 1,
+ &mode));
+
+ // Set spatial dimensions
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_SPATIAL_DIMS,
+ CUDNN_TYPE_INT64,
+ 1,
+ &spatial_dim_count));
+
+ // Set pre-padding
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_PRE_PADDINGS,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_pre_padding().data()));
+
+ // Set post-padding
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_POST_PADDINGS,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_post_padding().data()));
+
+ // Set dilation
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_DILATIONS,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_dilation().data()));
+
+ // Set strides
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_FILTER_STRIDES,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_stride().data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(convolution_descriptor.get_raw_desc()));
+ CUDNN_FE_LOG_LABEL_ENDL(convolution_descriptor);
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 convolution_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(convolution_operation.initialize_managed_backend_pointer(
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Conv_fprop_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_X,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set weight tensor W
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(W, Conv_fprop_attributes::input_names::W);
+ auto w_desc = tensors.at(W->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_W,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &w_desc));
+
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Conv_fprop_attributes::output_names::Y);
+ auto y_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_Y,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ // Set convolution descriptor
+ auto conv_desc_ptr = convolution_descriptor.get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_CONV_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &conv_desc_ptr));
+
+ // Set alpha and beta
+ float alpha = 1.0f;
+ float beta = 0.0f;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_ALPHA,
+ CUDNN_TYPE_FLOAT,
+ 1,
+ &alpha));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(convolution_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_BETA,
+ CUDNN_TYPE_FLOAT,
+ 1,
+ &beta));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(convolution_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(convolution_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"({"tag": "CONV_FPROP"})"_json);
+ }
+#endif
+};
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/conv_wgrad.h b/deps/cudnn-frontend/include/cudnn_frontend/node/conv_wgrad.h
new file mode 100644
index 0000000..2f9b478
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/conv_wgrad.h
@@ -0,0 +1,201 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class WgradNode : public NodeCRTP<WgradNode> {
+ public:
+ Conv_wgrad_attributes attributes;
+
+ WgradNode(Conv_wgrad_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::WGRAD;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating Node Type::WGRAD " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_pre_padding().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Pre padding not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_post_padding().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Post padding not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_stride().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Conv strides not set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.get_dilation().empty(), error_code_t::ATTRIBUTE_NOT_SET, "Conv dilation not set.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for conv node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // TODO: Only inferrencing from (X, DY) -> DW works today.
+ auto X = attributes.inputs[Conv_wgrad_attributes::input_names::X];
+ auto DW = attributes.outputs[Conv_wgrad_attributes::output_names::DW];
+ auto DY = attributes.inputs[Conv_wgrad_attributes::input_names::DY];
+
+ auto const x_tensor_dim = X->get_dim();
+ auto const dy_tensor_dim = DY->get_dim();
+ auto dw_tensor_dim = DW->get_dim();
+
+ // No dim inferencing as inverse mapping from DY, X to DX is not unique.
+ // Only infer strides if user did not set them
+ if (DW->get_stride().empty()) {
+ auto const& DW_dim = DW->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(DW_dim.size());
+ DW->set_stride(detail::generate_stride(DW_dim, stride_order));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building WgradNode operations " << attributes.name << " ");
+
+ // Create wgrad descriptor by directly calling cuDNN backend API
+ ConvDesc_v8 wgrad_descriptor;
+ int64_t const spatial_dim_count = attributes.get_pre_padding().size();
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ wgrad_descriptor.initialize_managed_backend_pointer(CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR));
+
+ cudnnDataType_t cudnn_data_type;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_COMP_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ cudnnConvolutionMode_t mode = detail::convert_to_cudnn_type(attributes.math_mode);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ wgrad_descriptor.get_raw_desc(), CUDNN_ATTR_CONVOLUTION_CONV_MODE, CUDNN_TYPE_CONVOLUTION_MODE, 1, &mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_SPATIAL_DIMS,
+ CUDNN_TYPE_INT64,
+ 1,
+ &spatial_dim_count));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_PRE_PADDINGS,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_pre_padding().data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_POST_PADDINGS,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_post_padding().data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_DILATIONS,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_dilation().data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_descriptor.get_raw_desc(),
+ CUDNN_ATTR_CONVOLUTION_FILTER_STRIDES,
+ CUDNN_TYPE_INT64,
+ spatial_dim_count,
+ attributes.get_stride().data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(wgrad_descriptor.get_raw_desc()));
+ CUDNN_FE_LOG_LABEL_ENDL(wgrad_descriptor);
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 wgrad_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(wgrad_operation.initialize_managed_backend_pointer(
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Conv_wgrad_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_X,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(DY, Conv_wgrad_attributes::input_names::DY);
+ auto dy_desc = tensors.at(DY->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_DY,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dy_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DW, Conv_wgrad_attributes::output_names::DW);
+ auto dw_desc = tensors.at(DW->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_DW,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dw_desc));
+
+ auto conv_desc_ptr = wgrad_descriptor.get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_CONV_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &conv_desc_ptr));
+
+ float alpha = 1.0f;
+ float beta = 0.0f;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_ALPHA,
+ CUDNN_TYPE_FLOAT,
+ 1,
+ &alpha));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(wgrad_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_BETA,
+ CUDNN_TYPE_FLOAT,
+ 1,
+ &beta));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(wgrad_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(wgrad_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "CONV_WGRAD"})"_json);
+ }
+#endif
+};
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/dbn.h b/deps/cudnn-frontend/include/cudnn_frontend/node/dbn.h
new file mode 100644
index 0000000..9f2a23e
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/dbn.h
@@ -0,0 +1,206 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+class DBNNode : public NodeCRTP<DBNNode> {
+ public:
+ Batchnorm_backward_attributes attributes;
+
+ DBNNode(Batchnorm_backward_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::DBN;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for DBN node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // TODO: Only inferencing from X works today.
+ auto X = attributes.inputs[Batchnorm_backward_attributes::input_names::X];
+ auto const x_tensor_dim = X->get_dim();
+
+ auto DX = attributes.outputs[Batchnorm_backward_attributes::output_names::DX];
+ auto dx_tensor_dim = DX->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (dx_tensor_dim.empty()) {
+ dx_tensor_dim.resize(x_tensor_dim.size());
+ DX->set_dim(x_tensor_dim);
+ }
+ if (DX->get_stride().empty()) {
+ auto const& DX_dim = DX->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(DX_dim.size());
+ DX->set_stride(detail::generate_stride(DX_dim, stride_order));
+ }
+
+ // Set channel length tensors
+ auto infer_per_channel_tensors = [&x_tensor_dim](std::shared_ptr<Tensor_attributes>& T) {
+ auto tensor_dim = T->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (tensor_dim.empty()) {
+ tensor_dim.resize(x_tensor_dim.size(), 1);
+ tensor_dim[1] = x_tensor_dim[1];
+ T->set_dim(tensor_dim);
+ }
+ if (T->get_stride().empty()) {
+ auto const& T_dim = T->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(T_dim.size());
+ T->set_stride(detail::generate_stride(T_dim, stride_order));
+ }
+ };
+ infer_per_channel_tensors(attributes.outputs[Batchnorm_backward_attributes::output_names::DSCALE]);
+ infer_per_channel_tensors(attributes.outputs[Batchnorm_backward_attributes::output_names::DBIAS]);
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building DBNNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 dbn_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ dbn_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR));
+
+ // Set norm mode to BATCH_NORM
+ cudnnBackendNormMode_t cudnn_norm_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::BATCH_NORM, cudnn_norm_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Batchnorm_backward_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set DY tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(DY, Batchnorm_backward_attributes::input_names::DY);
+ auto dy_desc = tensors.at(DY->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DYDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dy_desc));
+
+ // Set scale tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, Batchnorm_backward_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ // Set mean and inv_variance tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(MEAN, Batchnorm_backward_attributes::input_names::MEAN);
+ auto mean_desc = tensors.at(MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &mean_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(INV_VARIANCE,
+ Batchnorm_backward_attributes::input_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+
+ // Set DSCALE and DBIAS output tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DSCALE, Batchnorm_backward_attributes::output_names::DSCALE);
+ auto dscale_desc = tensors.at(DSCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DSCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dscale_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DBIAS, Batchnorm_backward_attributes::output_names::DBIAS);
+ auto dbias_desc = tensors.at(DBIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DBIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dbias_desc));
+
+ // Set DX output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DX, Batchnorm_backward_attributes::output_names::DX);
+ auto dx_desc = tensors.at(DX->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dx_desc));
+
+ // Set peer stat tensors if any
+ if (!attributes.peer_stats.empty()) {
+ std::vector<cudnnBackendDescriptor_t> peer_stat_descs;
+ for (auto const& peer_stat : attributes.peer_stats) {
+ peer_stat_descs.push_back(tensors.at(peer_stat->get_uid())->get_raw_desc());
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dbn_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_PEER_STAT_DESCS,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ peer_stat_descs.size(),
+ peer_stat_descs.data()));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(dbn_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(dbn_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "DBN"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/dbn_weight.h b/deps/cudnn-frontend/include/cudnn_frontend/node/dbn_weight.h
new file mode 100644
index 0000000..bfad0df
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/dbn_weight.h
@@ -0,0 +1,215 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+class DBNWeightNode : public NodeCRTP<DBNWeightNode> {
+ public:
+ DBN_weight_attributes attributes;
+
+ DBNWeightNode(DBN_weight_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::DBN_WEIGHT;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for batchnorm finalize node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // TODO: Only inferencing from DY works today.
+ auto DY = attributes.inputs[DBN_weight_attributes::input_names::DY];
+ auto const dy_tensor_dim = DY->get_dim();
+
+ auto X = attributes.inputs[DBN_weight_attributes::input_names::X];
+ auto x_tensor_dim = X->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (x_tensor_dim.empty()) {
+ x_tensor_dim.resize(dy_tensor_dim.size());
+ X->set_dim(dy_tensor_dim);
+ }
+ if (X->get_stride().empty()) {
+ auto const& X_dim = X->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(X_dim.size());
+ X->set_stride(detail::generate_stride(X_dim, stride_order));
+ }
+
+ // Set channel length tensors
+ auto infer_per_channel_tensors = [&dy_tensor_dim](std::shared_ptr<Tensor_attributes> const& T) {
+ auto tensor_dim = T->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (T->get_dim().empty()) {
+ tensor_dim.resize(dy_tensor_dim.size(), 1);
+ tensor_dim[1] = dy_tensor_dim[1];
+ T->set_dim(tensor_dim);
+ }
+ if (T->get_stride().empty()) {
+ auto const& T_dim = T->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(T_dim.size());
+ T->set_stride(detail::generate_stride(T_dim, stride_order));
+ }
+ };
+ infer_per_channel_tensors(attributes.outputs[DBN_weight_attributes::output_names::DBIAS]);
+ infer_per_channel_tensors(attributes.outputs[DBN_weight_attributes::output_names::DSCALE]);
+ infer_per_channel_tensors(attributes.outputs[DBN_weight_attributes::output_names::EQ_BIAS]);
+ infer_per_channel_tensors(attributes.outputs[DBN_weight_attributes::output_names::EQ_SCALE_DY]);
+ infer_per_channel_tensors(attributes.outputs[DBN_weight_attributes::output_names::EQ_SCALE_X]);
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building DBNWeightNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 bn_bwd_weight_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(bn_bwd_weight_operation.initialize_managed_backend_pointer(
+ CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR));
+
+ // Set compute type (math precision)
+ cudnnDataType_t compute_type = CUDNN_DATA_FLOAT;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &compute_type));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, DBN_weight_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_X_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set DY tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(DY, DBN_weight_attributes::input_names::DY);
+ auto dy_desc = tensors.at(DY->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DY_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dy_desc));
+
+ // Set mean tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(MEAN, DBN_weight_attributes::input_names::MEAN);
+ auto mean_desc = tensors.at(MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &mean_desc));
+
+ // Set inv_variance tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(INV_VARIANCE, DBN_weight_attributes::input_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_INVSTD_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+
+ // Set scale tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, DBN_weight_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_BN_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ // Set DSCALE output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DSCALE, DBN_weight_attributes::output_names::DSCALE);
+ auto dscale_desc = tensors.at(DSCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DBN_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dscale_desc));
+
+ // Set DBIAS output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DBIAS, DBN_weight_attributes::output_names::DBIAS);
+ auto dbias_desc = tensors.at(DBIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DBN_BIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dbias_desc));
+
+ // Set EQ_SCALE_DY output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(EQ_SCALE_DY, DBN_weight_attributes::output_names::EQ_SCALE_DY);
+ auto eq_scale_dy_desc = tensors.at(EQ_SCALE_DY->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_DY_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &eq_scale_dy_desc));
+
+ // Set EQ_SCALE_X output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(EQ_SCALE_X, DBN_weight_attributes::output_names::EQ_SCALE_X);
+ auto eq_scale_x_desc = tensors.at(EQ_SCALE_X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_X_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &eq_scale_x_desc));
+
+ // Set EQ_BIAS output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(EQ_BIAS, DBN_weight_attributes::output_names::EQ_BIAS);
+ auto eq_bias_desc = tensors.at(EQ_BIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(bn_bwd_weight_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_BIAS,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &eq_bias_desc));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(bn_bwd_weight_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(bn_bwd_weight_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "DBN_WEIGHT"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/diagonal_band_mask.h b/deps/cudnn-frontend/include/cudnn_frontend/node/diagonal_band_mask.h
new file mode 100644
index 0000000..243d1e3
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/diagonal_band_mask.h
@@ -0,0 +1,474 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+#include "pointwise.h"
+#include "reduction.h"
+
+namespace cudnn_frontend::graph {
+
+// Base class for nodes that represent a diagonal band mask operation
+// (which is either a left-bound or a right-bound mask, but not both at the same time).
+template <typename DerivedT>
+class DiagonalBandMaskNodeBase : public NodeCRTP<DerivedT> {
+ protected:
+ using input_names = DiagonalBandMask_attributes::input_names;
+ using output_names = DiagonalBandMask_attributes::output_names;
+
+ public:
+ DiagonalBandMask_attributes attributes;
+
+ DiagonalBandMaskNodeBase(DiagonalBandMask_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP<DerivedT>(context), attributes(std::move(attributes_)) {}
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating DiagonalBandMaskNode " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_left_bound() && has_shift_right_bound(),
+ error_code_t::INVALID_VALUE,
+ "DiagonalBandMaskNode cannot have both left_bound and shift_right_bound");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (has_seq_len_q() || has_seq_len_kv()) && (has_cu_seq_len_q() || has_cu_seq_len_kv()),
+ error_code_t::INVALID_VALUE,
+ "SEQ_LEN_Q / SEQ_LEN_KV and CU_SEQ_LEN_Q / CU_SEQ_LEN_KV are mutually exclusive");
+
+ return pre_validate_node_extra();
+ }
+
+ virtual error_t
+ pre_validate_node_extra() const {
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for DiagonalBandMask node " << attributes.name);
+
+ attributes.fill_from_context(this->context);
+
+ auto input_tensor = attributes.inputs.at(DiagonalBandMask_attributes::input_names::X);
+ auto output_tensor = attributes.outputs.at(DiagonalBandMask_attributes::output_names::Y);
+
+ // Only infer dims and strides if user did not set them
+ if (output_tensor->get_dim().empty()) {
+ output_tensor->set_dim(input_tensor->get_dim());
+ }
+
+ if (output_tensor->get_stride().empty()) {
+ output_tensor->set_stride(input_tensor->get_stride());
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ protected:
+ bool
+ has_seq_len_q() const {
+ auto seq_len_Q_it = attributes.inputs.find(DiagonalBandMask_attributes::input_names::SEQ_LEN_Q);
+ return ((seq_len_Q_it) != attributes.inputs.end() && seq_len_Q_it->second != nullptr);
+ }
+
+ bool
+ has_seq_len_kv() const {
+ auto seq_len_KV_it = attributes.inputs.find(DiagonalBandMask_attributes::input_names::SEQ_LEN_KV);
+ return ((seq_len_KV_it) != attributes.inputs.end() && seq_len_KV_it->second != nullptr);
+ }
+
+ bool
+ has_cu_seq_len_q() const {
+ auto cu_seq_len_Q_it = attributes.inputs.find(DiagonalBandMask_attributes::input_names::CU_SEQ_LEN_Q);
+ return ((cu_seq_len_Q_it) != attributes.inputs.end() && cu_seq_len_Q_it->second != nullptr);
+ }
+
+ bool
+ has_cu_seq_len_kv() const {
+ auto cu_seq_len_KV_it = attributes.inputs.find(DiagonalBandMask_attributes::input_names::CU_SEQ_LEN_KV);
+ return ((cu_seq_len_KV_it) != attributes.inputs.end() && cu_seq_len_KV_it->second != nullptr);
+ }
+
+ bool
+ has_left_bound() const {
+ auto left_bound_it = attributes.inputs.find(DiagonalBandMask_attributes::input_names::LeftBound);
+ return ((left_bound_it) != attributes.inputs.end() && left_bound_it->second != nullptr);
+ }
+
+ bool
+ has_right_bound() const {
+ return !has_left_bound();
+ }
+
+ bool
+ has_shift_right_bound() const {
+ auto shift_right_bound_it = attributes.inputs.find(DiagonalBandMask_attributes::input_names::ShiftRightBound);
+ return ((shift_right_bound_it) != attributes.inputs.end() && shift_right_bound_it->second != nullptr);
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ }
+#endif
+};
+
+// Fallback implementation of diagonal band mask node that represents the mask as a series of pointwise operations.
+// This is used for cuDNN versions before v9.21.0.
+// Note: the individual masks can be constructed in different ways as well that yield functionally
+// correct results. However, for performance reasons in the cuDNN backend they are organized as they are. Be
+// cautious of performance when editing.
+class CompositeDiagonalBandMaskNode : public DiagonalBandMaskNodeBase<CompositeDiagonalBandMaskNode> {
+ public:
+ CompositeDiagonalBandMaskNode(DiagonalBandMask_attributes&& attributes_, detail::Context const& context)
+ : DiagonalBandMaskNodeBase(std::move(attributes_), context) {}
+
+ Type
+ getType() override final {
+ return Type::COMPOSITE;
+ }
+
+ error_t
+ pre_validate_node_extra() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating CompositeDiagonalBandMaskNode " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_cu_seq_len_q() || has_cu_seq_len_kv(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "CompositeDiagonalBandMaskNode does not support CU_SEQ_LEN_Q or CU_SEQ_LEN_KV");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ expand_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for CompositeDiagonalBandMaskNode "
+ << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto attention_score = attributes.inputs[DiagonalBandMask_attributes::input_names::X];
+ auto negative_inf_value = attributes.inputs[DiagonalBandMask_attributes::input_names::B];
+
+ auto row_index = pointwise(
+ attention_score,
+ Pointwise_attributes().set_name("gen_row_index").set_mode(PointwiseMode_t::GEN_INDEX).set_axis(2));
+ row_index->set_data_type(DataType_t::INT32);
+ auto col_index = pointwise(
+ attention_score,
+ Pointwise_attributes().set_name("gen_col_index").set_mode(PointwiseMode_t::GEN_INDEX).set_axis(3));
+ col_index->set_data_type(DataType_t::INT32);
+
+ std::shared_ptr<Tensor_attributes> swa_comparison_output;
+
+ if (has_right_bound()) {
+ std::string row_index_name = "row";
+
+ if (has_seq_len_kv()) {
+ auto seq_len_kv = attributes.inputs[DiagonalBandMask_attributes::input_names::SEQ_LEN_KV];
+ row_index = pointwise(row_index,
+ seq_len_kv,
+ Pointwise_attributes()
+ .set_name(row_index_name += "+skv")
+ .set_mode(PointwiseMode_t::ADD)
+ .set_compute_data_type(DataType_t::INT32)
+ .set_axis(3));
+ row_index->set_data_type(DataType_t::INT32);
+ }
+
+ if (has_seq_len_q()) {
+ auto seq_len_q = attributes.inputs[DiagonalBandMask_attributes::input_names::SEQ_LEN_Q];
+ row_index = pointwise(row_index,
+ seq_len_q,
+ Pointwise_attributes()
+ .set_name(row_index_name += "-sq")
+ .set_mode(PointwiseMode_t::SUB)
+ .set_compute_data_type(DataType_t::INT32)
+ .set_axis(3));
+ row_index->set_data_type(DataType_t::INT32);
+ }
+
+ if (has_shift_right_bound()) {
+ auto shift_right_bound = attributes.inputs[DiagonalBandMask_attributes::input_names::ShiftRightBound];
+ // Use shift_right_bound's data type
+ row_index = pointwise(row_index,
+ shift_right_bound,
+ Pointwise_attributes()
+ .set_name(row_index_name += "+window")
+ .set_mode(PointwiseMode_t::ADD)
+ .set_compute_data_type(shift_right_bound->get_data_type())
+ .set_axis(3));
+ row_index->set_data_type(shift_right_bound->get_data_type());
+ }
+
+ swa_comparison_output = pointwise(row_index,
+ col_index,
+ Pointwise_attributes()
+ .set_name(row_index_name += ">col")
+ .set_mode(attributes.comparison_mode)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ swa_comparison_output->set_data_type(DataType_t::BOOLEAN);
+ }
+
+ // Set the left bound
+ else if (has_left_bound()) {
+ auto left_bound = attributes.inputs[DiagonalBandMask_attributes::input_names::LeftBound];
+ std::string col_index_name = "col";
+
+ // Use left_bound's data type
+ col_index = pointwise(col_index,
+ left_bound,
+ Pointwise_attributes()
+ .set_name(col_index_name += "+window")
+ .set_mode(PointwiseMode_t::ADD)
+ .set_compute_data_type(left_bound->get_data_type())
+ .set_axis(3));
+ col_index->set_data_type(left_bound->get_data_type());
+
+ if (has_seq_len_kv()) {
+ auto seq_len_kv = attributes.inputs[DiagonalBandMask_attributes::input_names::SEQ_LEN_KV];
+ col_index = pointwise(col_index,
+ seq_len_kv,
+ Pointwise_attributes()
+ .set_name(col_index_name += "-skv")
+ .set_mode(PointwiseMode_t::SUB)
+ .set_compute_data_type(DataType_t::INT32)
+ .set_axis(3));
+ col_index->set_data_type(DataType_t::INT32);
+ }
+
+ if (has_seq_len_q()) {
+ auto seq_len_q = attributes.inputs[DiagonalBandMask_attributes::input_names::SEQ_LEN_Q];
+ col_index = pointwise(col_index,
+ seq_len_q,
+ Pointwise_attributes()
+ .set_name(col_index_name += "+sq")
+ .set_mode(PointwiseMode_t::ADD)
+ .set_compute_data_type(DataType_t::INT32)
+ .set_axis(3));
+ col_index->set_data_type(DataType_t::INT32);
+ }
+
+ swa_comparison_output = pointwise(col_index,
+ row_index,
+ Pointwise_attributes()
+ .set_name(col_index_name += ">row")
+ .set_mode(attributes.comparison_mode)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ swa_comparison_output->set_data_type(DataType_t::BOOLEAN);
+ } else {
+ // This should not be reached (since one of has_left_bound() or has_right_bound() is always true by
+ // construction), just here for completeness.
+ return {error_code_t::INVALID_VALUE,
+ "CompositeDiagonalBandMaskNode must have a left bound or a right bound"};
+ }
+
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ pointwise(attention_score,
+ negative_inf_value,
+ swa_comparison_output,
+ Pointwise_attributes().set_name("binary_select").set_mode(PointwiseMode_t::BINARY_SELECT),
+ attributes.outputs[DiagonalBandMask_attributes::output_names::Y]);
+
+ return {error_code_t::OK, ""};
+ }
+};
+
+// Newer implementation of diagonal band mask node that represents the mask as a single operation.
+// This is used for cuDNN versions v9.21.0 and later.
+class UnifiedDiagonalBandMaskNode : public DiagonalBandMaskNodeBase<UnifiedDiagonalBandMaskNode> {
+ public:
+ UnifiedDiagonalBandMaskNode(DiagonalBandMask_attributes&& attributes_, detail::Context const& context)
+ : DiagonalBandMaskNodeBase(std::move(attributes_), context) {}
+
+ Type
+ getType() override final {
+ return Type::DIAGONAL_BAND_MASK;
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Building UnifiedDiagonalBandMaskNode operations "
+ << attributes.name << std::endl;
+ auto cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED, "UnifiedDiagonalBandMaskNode requires cuDNN v9.21.0"};
+
+#if (CUDNN_VERSION >= 92100)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92100, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+ auto diagonal_band_mask_operation = make_shared_backend_pointer(
+ (cudnnBackendDescriptorType_t)CUDNN_BACKEND_OPERATION_DIAGONAL_BAND_MASK_DESCRIPTOR);
+
+ auto X = attributes.inputs.find(DiagonalBandMask_attributes::input_names::X)->second;
+ auto backend_x = tensors[X->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_x));
+
+ auto B = attributes.inputs.find(DiagonalBandMask_attributes::input_names::B)->second;
+ auto backend_b = tensors[B->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_BDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_b));
+
+ if (has_seq_len_q()) {
+ auto seq_len_Q = attributes.inputs.find(DiagonalBandMask_attributes::input_names::SEQ_LEN_Q)->second;
+ auto backend_seq_len_Q = tensors[seq_len_Q->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_SEQ_LEN_QDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_seq_len_Q));
+ }
+
+ if (has_seq_len_kv()) {
+ auto seq_len_KV = attributes.inputs.find(DiagonalBandMask_attributes::input_names::SEQ_LEN_KV)->second;
+ auto backend_seq_len_KV = tensors[seq_len_KV->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_SEQ_LEN_KVDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_seq_len_KV));
+ }
+
+ if (has_cu_seq_len_q() || has_cu_seq_len_kv()) {
+ auto cu_seq_len_cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED,
+ "Cumulative sequence length tensors in unified DiagonalBandMask node require cuDNN 9.24.0"};
+#if (CUDNN_VERSION >= 92400)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92400, cu_seq_len_cudnn_ver_error);
+
+ if (has_cu_seq_len_q()) {
+ auto cu_seq_len_Q =
+ attributes.inputs.find(DiagonalBandMask_attributes::input_names::CU_SEQ_LEN_Q)->second;
+ auto backend_cu_seq_len_Q = tensors[cu_seq_len_Q->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_CU_SEQ_LEN_QDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_cu_seq_len_Q));
+ }
+
+ if (has_cu_seq_len_kv()) {
+ auto cu_seq_len_KV =
+ attributes.inputs.find(DiagonalBandMask_attributes::input_names::CU_SEQ_LEN_KV)->second;
+ auto backend_cu_seq_len_KV = tensors[cu_seq_len_KV->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(
+ detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_CU_SEQ_LEN_KVDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_cu_seq_len_KV));
+ }
+#else
+ return cu_seq_len_cudnn_ver_error;
+#endif
+ }
+
+ if (has_left_bound()) {
+ auto left_bound = attributes.inputs.find(DiagonalBandMask_attributes::input_names::LeftBound)->second;
+ auto backend_left_bound = tensors[left_bound->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_LEFT_BOUND_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_left_bound));
+ }
+
+ if (has_shift_right_bound()) {
+ auto shift_right_bound =
+ attributes.inputs.find(DiagonalBandMask_attributes::input_names::ShiftRightBound)->second;
+ auto backend_shift_right_bound =
+ tensors[shift_right_bound->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(
+ detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_SHIFT_RIGHT_BOUND_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_shift_right_bound));
+ }
+
+ auto Y = attributes.outputs.find(DiagonalBandMask_attributes::output_names::Y)->second;
+ auto backend_y = tensors[Y->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_y));
+
+ cudnnPointwiseMode_t cudnn_pointwise_mode;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.comparison_mode, cudnn_pointwise_mode));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(diagonal_band_mask_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_DIAGONAL_BAND_MASK_COMPARISON_MODE,
+ CUDNN_TYPE_POINTWISE_MODE,
+ 1,
+ &cudnn_pointwise_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(diagonal_band_mask_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(diagonal_band_mask_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif // CUDNN_VERSION >= 92100
+ }
+};
+
+// Factory function to create a diagonal band mask node.
+// This function will create the appropriate node based on the cuDNN version.
+inline std::shared_ptr<Tensor_attributes>
+INode::diagonal_band_mask(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> b,
+ std::shared_ptr<Tensor_attributes> seq_len_q,
+ std::shared_ptr<Tensor_attributes> seq_len_kv,
+ std::shared_ptr<Tensor_attributes> cu_seq_len_q,
+ std::shared_ptr<Tensor_attributes> cu_seq_len_kv,
+ std::shared_ptr<Tensor_attributes> left_bound,
+ std::shared_ptr<Tensor_attributes> shift_right_bound,
+ DiagonalBandMask_attributes attributes) {
+ attributes.inputs[DiagonalBandMask_attributes::input_names::X] = x;
+ attributes.inputs[DiagonalBandMask_attributes::input_names::B] = b;
+ if (seq_len_q) {
+ attributes.inputs[DiagonalBandMask_attributes::input_names::SEQ_LEN_Q] = seq_len_q;
+ }
+ if (seq_len_kv) {
+ attributes.inputs[DiagonalBandMask_attributes::input_names::SEQ_LEN_KV] = seq_len_kv;
+ }
+ if (cu_seq_len_q) {
+ attributes.inputs[DiagonalBandMask_attributes::input_names::CU_SEQ_LEN_Q] = cu_seq_len_q;
+ }
+ if (cu_seq_len_kv) {
+ attributes.inputs[DiagonalBandMask_attributes::input_names::CU_SEQ_LEN_KV] = cu_seq_len_kv;
+ }
+ if (left_bound) {
+ attributes.inputs[DiagonalBandMask_attributes::input_names::LeftBound] = left_bound;
+ }
+ if (shift_right_bound) {
+ attributes.inputs[DiagonalBandMask_attributes::input_names::ShiftRightBound] = shift_right_bound;
+ }
+ auto y = attributes.outputs[DiagonalBandMask_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+
+ // Newer versions of cuDNN can represent the diagonal band mask as a single operation.
+ if (std::min(detail::get_compiled_version(), detail::get_backend_version()) >= 92100) {
+ sub_nodes.emplace_back(std::make_unique<UnifiedDiagonalBandMaskNode>(std::move(attributes), context));
+ } else {
+ sub_nodes.emplace_back(std::make_unique<CompositeDiagonalBandMaskNode>(std::move(attributes), context));
+ }
+ return y;
+}
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/dln.h b/deps/cudnn-frontend/include/cudnn_frontend/node/dln.h
new file mode 100644
index 0000000..ad7ad1f
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/dln.h
@@ -0,0 +1,226 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+class DLNNode : public NodeCRTP<DLNNode> {
+ public:
+ Layernorm_backward_attributes attributes;
+
+ DLNNode(Layernorm_backward_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::DLN;
+ }
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for DLN node " << attributes.name);
+
+ if (detail::get_backend_version() < 8906) {
+ attributes.inputs[Layernorm_backward_attributes::input_names::EPSILON] =
+ std::make_shared<Tensor_attributes>(0.0f);
+ }
+
+ attributes.fill_from_context(context);
+
+ // TODO: Only inferencing from X works today.
+ auto X = attributes.inputs[Layernorm_backward_attributes::input_names::X];
+ auto const x_tensor_dim = X->get_dim();
+
+ auto DY = attributes.inputs[Layernorm_backward_attributes::input_names::DY];
+ auto dy_tensor_dim = DY->get_dim();
+
+ // Only infer dims and strides if user did not set them
+ if (dy_tensor_dim.empty()) {
+ dy_tensor_dim.resize(x_tensor_dim.size());
+ DY->set_dim(x_tensor_dim);
+ }
+ if (DY->get_stride().empty()) {
+ auto const& DY_dim = DY->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(DY_dim.size());
+ DY->set_stride(detail::generate_stride(DY_dim, stride_order));
+ }
+
+ auto DX = attributes.outputs[Layernorm_backward_attributes::output_names::DX];
+ auto dx_tensor_dim = DX->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (dx_tensor_dim.empty()) {
+ dx_tensor_dim.resize(x_tensor_dim.size());
+ DX->set_dim(x_tensor_dim);
+ }
+ if (DX->get_stride().empty()) {
+ auto const& DX_dim = DX->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(DX_dim.size());
+ DX->set_stride(detail::generate_stride(DX_dim, stride_order));
+ }
+
+ auto scale_bias_dim = X->get_dim();
+ scale_bias_dim[0] = 1;
+
+ // Set channel length tensors
+ auto infer_scale_bias_tensors = [&scale_bias_dim](std::shared_ptr<Tensor_attributes>& T) {
+ auto tensor_dim = T->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (tensor_dim.empty()) {
+ T->set_dim(scale_bias_dim);
+ }
+ if (T->get_stride().empty()) {
+ auto const& T_dim = T->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(T_dim.size());
+ T->set_stride(detail::generate_stride(T_dim, stride_order));
+ }
+ };
+
+ infer_scale_bias_tensors(attributes.outputs[Layernorm_backward_attributes::output_names::DSCALE]);
+ infer_scale_bias_tensors(attributes.outputs[Layernorm_backward_attributes::output_names::DBIAS]);
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building DLNNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 dln_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ dln_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR));
+
+ // Set norm mode to LAYER_NORM
+ cudnnBackendNormMode_t cudnn_norm_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::LAYER_NORM, cudnn_norm_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Layernorm_backward_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set DY tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(DY, Layernorm_backward_attributes::input_names::DY);
+ auto dy_desc = tensors.at(DY->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DYDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dy_desc));
+
+ // Set scale tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, Layernorm_backward_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ // Set mean and inv_variance tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(MEAN, Layernorm_backward_attributes::input_names::MEAN);
+ auto mean_desc = tensors.at(MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &mean_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(INV_VARIANCE,
+ Layernorm_backward_attributes::input_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+
+ // Set DSCALE and DBIAS output tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DSCALE, Layernorm_backward_attributes::output_names::DSCALE);
+ auto dscale_desc = tensors.at(DSCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DSCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dscale_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DBIAS, Layernorm_backward_attributes::output_names::DBIAS);
+ auto dbias_desc = tensors.at(DBIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DBIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dbias_desc));
+
+ // Set DX output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DX, Layernorm_backward_attributes::output_names::DX);
+ auto dx_desc = tensors.at(DX->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dx_desc));
+
+ // Set epsilon tensor for older backend versions
+ if (detail::get_backend_version() < 8906) {
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(EPSILON, Layernorm_backward_attributes::input_names::EPSILON);
+ auto epsilon_desc = tensors.at(EPSILON->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(dln_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_EPSILON_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &epsilon_desc));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(dln_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(dln_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "LAYER_NORM_BPROP"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/genstats.h b/deps/cudnn-frontend/include/cudnn_frontend/node/genstats.h
new file mode 100644
index 0000000..8f91897
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/genstats.h
@@ -0,0 +1,147 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+class GenstatsNode : public NodeCRTP<GenstatsNode> {
+ public:
+ Genstats_attributes attributes;
+
+ GenstatsNode(Genstats_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::GENSTATS;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ attributes.fill_from_context(context);
+
+ // Only inferrencing from X works today.
+ auto X = attributes.inputs[Genstats_attributes::input_names::X];
+ auto SUM = attributes.outputs[Genstats_attributes::output_names::SUM];
+ auto SQ_SUM = attributes.outputs[Genstats_attributes::output_names::SQ_SUM];
+
+ auto const x_tensor_dim = X->get_dim();
+ auto sum_tensor_dim = SUM->get_dim();
+ auto sq_sum_tensor_dim = SQ_SUM->get_dim();
+
+ // Only infer dims and strides if user did not set them
+ if (sum_tensor_dim.empty()) {
+ sum_tensor_dim.resize(x_tensor_dim.size(), 1);
+ sum_tensor_dim[1] = x_tensor_dim[1];
+ SUM->set_dim(sum_tensor_dim);
+ }
+ if (SUM->get_stride().empty()) {
+ auto const& SUM_dim = SUM->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(SUM_dim.size());
+ SUM->set_stride(detail::generate_stride(SUM_dim, stride_order));
+ }
+
+ // Only infer dims and strides if user did not set them
+ if (sq_sum_tensor_dim.empty()) {
+ sq_sum_tensor_dim.resize(x_tensor_dim.size(), 1);
+ sq_sum_tensor_dim[1] = x_tensor_dim[1];
+ SQ_SUM->set_dim(sq_sum_tensor_dim);
+ }
+ if (SQ_SUM->get_stride().empty()) {
+ auto const& SQ_SUM_dim = SQ_SUM->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(SQ_SUM_dim.size());
+ SQ_SUM->set_stride(detail::generate_stride(SQ_SUM_dim, stride_order));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building GenstatsNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 genstats_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ genstats_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Genstats_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(genstats_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_GENSTATS_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set gen stats mode
+ cudnnGenStatsMode_t genstats_mode = CUDNN_GENSTATS_SUM_SQSUM;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(genstats_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_GENSTATS_MODE,
+ CUDNN_TYPE_GENSTATS_MODE,
+ 1,
+ &genstats_mode));
+
+ // Set math precision based on X tensor data type
+ cudnnDataType_t math_prec = static_cast<cudnnDataType_t>(tensors.at(X->second->get_uid())->getDataType());
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(genstats_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_GENSTATS_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &math_prec));
+
+ // Set SUM output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(SUM, Genstats_attributes::output_names::SUM);
+ auto sum_desc = tensors.at(SUM->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(genstats_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_GENSTATS_SUMDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &sum_desc));
+
+ // Set SQ_SUM output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(SQ_SUM, Genstats_attributes::output_names::SQ_SUM);
+ auto sq_sum_desc = tensors.at(SQ_SUM->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(genstats_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_GENSTATS_SQSUMDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &sq_sum_desc));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(genstats_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(genstats_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "GENSTATS"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/instancenorm.h b/deps/cudnn-frontend/include/cudnn_frontend/node/instancenorm.h
new file mode 100644
index 0000000..1b71f4a
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/instancenorm.h
@@ -0,0 +1,414 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+class InstanceNormNode : public NodeCRTP<InstanceNormNode> {
+ public:
+ Instancenorm_attributes attributes;
+
+ InstanceNormNode(Instancenorm_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::INSTANCENORM;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for instancenorm node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto X = attributes.inputs[Instancenorm_attributes::input_names::X];
+ auto Y = attributes.outputs[Instancenorm_attributes::output_names::Y];
+
+ // Only infer dims and strides if user did not set them
+ if (Y->get_dim().empty()) {
+ Y->set_dim(X->get_dim());
+ }
+ if (Y->get_stride().empty()) {
+ Y->set_stride(X->get_stride());
+ }
+
+ // mean inv_var dim is n,c,1,1
+ auto stats_dim = X->get_dim();
+ for (size_t i = 2; i < stats_dim.size(); i++) {
+ stats_dim[i] = 1;
+ }
+
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ auto mean = attributes.outputs[Instancenorm_attributes::output_names::MEAN];
+ if (mean->get_dim().empty()) {
+ mean->set_dim(stats_dim);
+ }
+ if (mean->get_stride().empty()) {
+ auto const& mean_dim = mean->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(mean_dim.size());
+ mean->set_stride(detail::generate_stride(mean_dim, stride_order));
+ }
+
+ auto inv_var = attributes.outputs[Instancenorm_attributes::output_names::INV_VARIANCE];
+ if (inv_var->get_dim().empty()) {
+ inv_var->set_dim(stats_dim);
+ }
+ if (inv_var->get_stride().empty()) {
+ auto const& inv_var_dim = inv_var->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(inv_var_dim.size());
+ inv_var->set_stride(detail::generate_stride(inv_var_dim, stride_order));
+ }
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating InstanceNormNode " << attributes.name);
+
+ // Norm forward phase should be set
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.forward_phase == NormFwdPhase_t::NOT_SET,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Forward phase not set of instancenorm node.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building InstanceNormNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 instancenorm_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ instancenorm_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR));
+
+ // Set norm mode to INSTANCE_NORM
+ cudnnBackendNormMode_t cudnn_norm_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::INSTANCE_NORM, cudnn_norm_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(instancenorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ // Set forward phase
+ cudnnBackendNormFwdPhase_t cudnn_norm_fwd_phase;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.forward_phase, cudnn_norm_fwd_phase));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(instancenorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_PHASE,
+ CUDNN_TYPE_NORM_FWD_PHASE,
+ 1,
+ &cudnn_norm_fwd_phase));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Instancenorm_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(instancenorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set scale and bias tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, Instancenorm_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(instancenorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(BIAS, Instancenorm_attributes::input_names::BIAS);
+ auto bias_desc = tensors.at(BIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(instancenorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_BIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &bias_desc));
+
+ // Set epsilon tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(EPSILON, Instancenorm_attributes::input_names::EPSILON);
+ auto epsilon_desc = tensors.at(EPSILON->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(instancenorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_EPSILON_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &epsilon_desc));
+
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Instancenorm_attributes::output_names::Y);
+ auto y_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(instancenorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ // Set mean and inv_variance for training phase
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(MEAN, Instancenorm_attributes::output_names::MEAN);
+ auto mean_desc = tensors.at(MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(instancenorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &mean_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(INV_VARIANCE,
+ Instancenorm_attributes::output_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(instancenorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(instancenorm_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(instancenorm_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "INSTANCE_NORM"})"_json);
+ }
+#endif
+};
+
+class DINNode : public NodeCRTP<DINNode> {
+ public:
+ Instancenorm_backward_attributes attributes;
+
+ DINNode(Instancenorm_backward_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::DIN;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for DIN node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // TODO: Only inferencing from X works today.
+ auto X = attributes.inputs[Instancenorm_backward_attributes::input_names::X];
+ auto const x_tensor_dim = X->get_dim();
+
+ auto DY = attributes.inputs[Instancenorm_backward_attributes::input_names::DY];
+ auto dy_tensor_dim = DY->get_dim();
+
+ // Only infer dims and strides if user did not set them
+ if (dy_tensor_dim.empty()) {
+ dy_tensor_dim.resize(x_tensor_dim.size());
+ DY->set_dim(x_tensor_dim);
+ }
+ if (DY->get_stride().empty()) {
+ auto const& DY_dim = DY->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(DY_dim.size());
+ DY->set_stride(detail::generate_stride(DY_dim, stride_order));
+ }
+
+ auto DX = attributes.outputs[Instancenorm_backward_attributes::output_names::DX];
+ auto dx_tensor_dim = DX->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (dx_tensor_dim.empty()) {
+ dx_tensor_dim.resize(x_tensor_dim.size());
+ DX->set_dim(x_tensor_dim);
+ }
+ if (DX->get_stride().empty()) {
+ auto const& DX_dim = DX->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(DX_dim.size());
+ DX->set_stride(detail::generate_stride(DX_dim, stride_order));
+ }
+
+ // scale_bias dim is 1,c,1,1
+ // mean inv_var dim is n,c,1,1
+ auto scale_bias_dim = X->get_dim();
+ for (size_t i = 0; i < scale_bias_dim.size(); i++) {
+ if (i != 1) {
+ scale_bias_dim[i] = 1;
+ }
+ }
+
+ // Set channel length tensors
+ auto infer_scale_bias_tensors = [&scale_bias_dim](std::shared_ptr<Tensor_attributes>& T) {
+ auto tensor_dim = T->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (tensor_dim.empty()) {
+ T->set_dim(scale_bias_dim);
+ }
+ if (T->get_stride().empty()) {
+ auto const& T_dim = T->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(T_dim.size());
+ T->set_stride(detail::generate_stride(T_dim, stride_order));
+ }
+ };
+
+ infer_scale_bias_tensors(attributes.outputs[Instancenorm_backward_attributes::output_names::DSCALE]);
+ infer_scale_bias_tensors(attributes.outputs[Instancenorm_backward_attributes::output_names::DBIAS]);
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building DINNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 din_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ din_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR));
+
+ // Set norm mode to INSTANCE_NORM
+ cudnnBackendNormMode_t cudnn_norm_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::INSTANCE_NORM, cudnn_norm_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(din_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Instancenorm_backward_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(din_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set DY tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(DY, Instancenorm_backward_attributes::input_names::DY);
+ auto dy_desc = tensors.at(DY->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(din_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DYDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dy_desc));
+
+ // Set scale tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, Instancenorm_backward_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(din_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ // Set mean and inv_variance tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(MEAN, Instancenorm_backward_attributes::input_names::MEAN);
+ auto mean_desc = tensors.at(MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(din_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &mean_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(INV_VARIANCE,
+ Instancenorm_backward_attributes::input_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(din_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+
+ // Set DSCALE and DBIAS output tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DSCALE, Instancenorm_backward_attributes::output_names::DSCALE);
+ auto dscale_desc = tensors.at(DSCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(din_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DSCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dscale_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DBIAS, Instancenorm_backward_attributes::output_names::DBIAS);
+ auto dbias_desc = tensors.at(DBIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(din_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DBIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dbias_desc));
+
+ // Set DX output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DX, Instancenorm_backward_attributes::output_names::DX);
+ auto dx_desc = tensors.at(DX->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(din_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dx_desc));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(din_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(din_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "INSTANCE_NORM_BPROP"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/layernorm.h b/deps/cudnn-frontend/include/cudnn_frontend/node/layernorm.h
new file mode 100644
index 0000000..46420aa
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/layernorm.h
@@ -0,0 +1,259 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+class LayerNormNode : public NodeCRTP<LayerNormNode> {
+ public:
+ Layernorm_attributes attributes;
+
+ LayerNormNode(Layernorm_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::LAYERNORM;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for layernorm node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto X = attributes.inputs[Layernorm_attributes::input_names::X];
+ auto Y = attributes.outputs[Layernorm_attributes::output_names::Y];
+
+ // Only infer dims and strides if user did not set them
+ if (Y->get_dim().empty()) {
+ Y->set_dim(X->get_dim());
+ }
+ if (Y->get_stride().empty()) {
+ Y->set_stride(X->get_stride());
+ }
+
+ // scale_bias dim is 1,c,h,w
+ auto scale_bias_dim = X->get_dim();
+ scale_bias_dim[0] = 1;
+
+ auto scale = attributes.inputs[Layernorm_attributes::input_names::SCALE];
+ // Only infer dims and strides if user did not set them
+ if (scale->get_dim().empty()) {
+ scale->set_dim(scale_bias_dim);
+ }
+ if (scale->get_stride().empty()) {
+ auto const& scale_dim = scale->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), scale_dim.size(), stride_order));
+ scale->set_stride(detail::generate_stride(scale_dim, stride_order));
+ }
+
+ auto bias = attributes.inputs[Layernorm_attributes::input_names::BIAS];
+ // Only infer dims and strides if user did not set them
+ if (bias->get_dim().empty()) {
+ bias->set_dim(scale_bias_dim);
+ }
+ if (bias->get_stride().empty()) {
+ auto const& bias_dim = bias->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), bias_dim.size(), stride_order));
+ bias->set_stride(detail::generate_stride(bias_dim, stride_order));
+ }
+
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ // stats dim is x where scale == 1 else 1
+ auto stats_dim = X->get_dim();
+ for (size_t i = 0; i < stats_dim.size(); i++) {
+ if (scale->get_dim()[i] != 1) {
+ stats_dim[i] = 1;
+ }
+ }
+
+ auto mean = attributes.outputs[Layernorm_attributes::output_names::MEAN];
+ // Only infer dims and strides if user did not set them
+ if (mean->get_dim().empty()) {
+ mean->set_dim(stats_dim);
+ }
+ if (mean->get_stride().empty()) {
+ auto const& mean_dim = mean->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), mean_dim.size(), stride_order));
+ mean->set_stride(detail::generate_stride(mean_dim, stride_order));
+ }
+
+ auto inv_var = attributes.outputs[Layernorm_attributes::output_names::INV_VARIANCE];
+ // Only infer dims and strides if user did not set them
+ if (inv_var->get_dim().empty()) {
+ inv_var->set_dim(stats_dim);
+ }
+ if (inv_var->get_stride().empty()) {
+ auto const& inv_var_dim = inv_var->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), inv_var_dim.size(), stride_order));
+ inv_var->set_stride(detail::generate_stride(inv_var_dim, stride_order));
+ }
+ }
+
+ // Set scalar tensors
+ std::vector<int64_t> ones(X->get_dim().size(), 1);
+ auto infer_scalar_tensors = [&ones](std::shared_ptr<Tensor_attributes>& T) {
+ // Only infer dims and strides if user did not set them
+ if (T->get_dim().empty()) {
+ T->set_dim(ones);
+ }
+ if (T->get_stride().empty()) {
+ T->set_stride(ones);
+ }
+ };
+ infer_scalar_tensors(attributes.inputs[Layernorm_attributes::input_names::EPSILON]);
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: " << "Validating LayerNormNode " << attributes.name);
+
+ // Norm forward phase should be set
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.forward_phase == NormFwdPhase_t::NOT_SET,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Forward phase not set of layernorm node.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building LayerNormNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 layernorm_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ layernorm_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR));
+
+ // Set norm mode
+ cudnnBackendNormMode_t cudnn_norm_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::LAYER_NORM, cudnn_norm_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(layernorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ // Set forward phase
+ cudnnBackendNormFwdPhase_t cudnn_norm_fwd_phase;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.forward_phase, cudnn_norm_fwd_phase));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(layernorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_PHASE,
+ CUDNN_TYPE_NORM_FWD_PHASE,
+ 1,
+ &cudnn_norm_fwd_phase));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Layernorm_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(layernorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set scale and bias tensors
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, Layernorm_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(layernorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(BIAS, Layernorm_attributes::input_names::BIAS);
+ auto bias_desc = tensors.at(BIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(layernorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_BIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &bias_desc));
+
+ // Set epsilon tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(EPSILON, Layernorm_attributes::input_names::EPSILON);
+ auto epsilon_desc = tensors.at(EPSILON->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(layernorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_EPSILON_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &epsilon_desc));
+
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Layernorm_attributes::output_names::Y);
+ auto y_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(layernorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ // Set mean and inv_variance for training phase
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(MEAN, Layernorm_attributes::output_names::MEAN);
+ auto mean_desc = tensors.at(MEAN->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(layernorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MEAN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &mean_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(INV_VARIANCE, Layernorm_attributes::output_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(layernorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(layernorm_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(layernorm_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "LAYER_NORM"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/matmul.h b/deps/cudnn-frontend/include/cudnn_frontend/node/matmul.h
new file mode 100644
index 0000000..f09d341
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/matmul.h
@@ -0,0 +1,253 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class MatmulNode : public NodeCRTP<MatmulNode> {
+ public:
+ Matmul_attributes attributes;
+
+ MatmulNode(Matmul_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::MATMUL;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for matmul node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // Only inferrencing from (A, B) -> C works today.
+ auto a_tensor = attributes.inputs[Matmul_attributes::input_names::A];
+ auto b_tensor = attributes.inputs[Matmul_attributes::input_names::B];
+ auto c_tensor = attributes.outputs[Matmul_attributes::output_names::C];
+
+ auto const a_tensor_dim = a_tensor->get_dim();
+ auto const b_tensor_dim = b_tensor->get_dim();
+ auto c_tensor_dim = c_tensor->get_dim();
+
+ // Only infer dims and strides if user did not set them
+ if (c_tensor_dim.empty()) {
+ // CHECK_CUDNN_FRONTEND_ERROR(detail::generate_matmul_output_dim(a_tensor_dim, b_tensor_dim, c_tensor_dim));
+
+ c_tensor_dim.resize(a_tensor_dim.size());
+ int64_t gemm_start_dim = a_tensor_dim.size() - 2;
+ c_tensor_dim[gemm_start_dim] = a_tensor_dim[gemm_start_dim]; // M
+ c_tensor_dim[gemm_start_dim + 1] = b_tensor_dim[gemm_start_dim + 1]; // N
+
+ // Broadcast the batches
+ for (int64_t i = 0; i < gemm_start_dim; ++i) {
+ c_tensor_dim[i] = std::max(a_tensor_dim[i], b_tensor_dim[i]);
+ }
+
+ c_tensor->set_dim(c_tensor_dim);
+ }
+ if (c_tensor->get_stride().empty()) {
+ auto const& c_dim = c_tensor->get_dim();
+ // Default to Col major
+ auto const& stride_order = detail::generate_row_major_stride_order(c_dim.size());
+ c_tensor->set_stride(detail::generate_stride(c_dim, stride_order));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building MatmulNode operations " << attributes.name << " ");
+
+ // Create matmul descriptor by directly calling cuDNN backend API
+ MatMulDesc_v8 matmul_descriptor;
+
+ _CUDNN_CHECK_CUDNN_ERROR(matmul_descriptor.initialize_managed_backend_pointer(CUDNN_BACKEND_MATMUL_DESCRIPTOR));
+
+ // Set compute type
+ cudnnDataType_t cudnn_data_type;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ matmul_descriptor.get_raw_desc(), CUDNN_ATTR_MATMUL_COMP_TYPE, CUDNN_TYPE_DATA_TYPE, 1, &cudnn_data_type));
+
+ // Set padding value if specified
+#if (CUDNN_VERSION >= 8900)
+ if (attributes.padding_value != 0.0) {
+ double padding_value = attributes.padding_value;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(matmul_descriptor.get_raw_desc(),
+ CUDNN_ATTR_MATMUL_PADDING_VALUE,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &padding_value));
+ }
+#endif
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(matmul_descriptor.get_raw_desc()));
+ CUDNN_FE_LOG_LABEL_ENDL(matmul_descriptor);
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 matmul_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ matmul_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR));
+
+ // Set input tensor A
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(A, Matmul_attributes::input_names::A);
+ auto a_desc = tensors.at(A->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(matmul_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_MATMUL_ADESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &a_desc));
+
+ // Set input tensor B
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(B, Matmul_attributes::input_names::B);
+ auto b_desc = tensors.at(B->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(matmul_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_MATMUL_BDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &b_desc));
+
+ // Set output tensor C
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(C, Matmul_attributes::output_names::C);
+ auto c_desc = tensors.at(C->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(matmul_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_MATMUL_CDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &c_desc));
+
+ // Set matmul descriptor
+ auto matmul_desc_ptr = matmul_descriptor.get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(matmul_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_MATMUL_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &matmul_desc_ptr));
+
+ // Set optional override tensors
+ auto M_override = attributes.inputs.find(Matmul_attributes::input_names::M_override);
+ if ((M_override != attributes.inputs.end()) && (M_override->second != nullptr)) {
+ auto m_override_desc = tensors.at(M_override->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(matmul_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_MATMUL_GEMM_M_OVERRIDE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &m_override_desc));
+ }
+
+ auto N_override = attributes.inputs.find(Matmul_attributes::input_names::N_override);
+ if ((N_override != attributes.inputs.end()) && (N_override->second != nullptr)) {
+ auto n_override_desc = tensors.at(N_override->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(matmul_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_MATMUL_GEMM_N_OVERRIDE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &n_override_desc));
+ }
+
+ auto K_override = attributes.inputs.find(Matmul_attributes::input_names::K_override);
+ if ((K_override != attributes.inputs.end()) && (K_override->second != nullptr)) {
+ auto k_override_desc = tensors.at(K_override->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(matmul_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_MATMUL_GEMM_K_OVERRIDE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &k_override_desc));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(matmul_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(matmul_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "MATMUL"})"_json);
+ }
+#endif
+};
+
+inline void
+INode::matmul(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ Matmul_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c) {
+ attributes.inputs[Matmul_attributes::input_names::A] = a;
+ attributes.inputs[Matmul_attributes::input_names::B] = b;
+ attributes.outputs[Matmul_attributes::output_names::C] = c;
+ sub_nodes.emplace_back(std::make_unique<MatmulNode>(std::move(attributes), context));
+}
+
+inline std::shared_ptr<Tensor_attributes>
+INode::matmul(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ Matmul_attributes attributes) {
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+ attributes.inputs[Matmul_attributes::input_names::A] = a;
+ attributes.inputs[Matmul_attributes::input_names::B] = b;
+
+ if (a->get_name().empty()) {
+ a->set_name(attributes.name + "::A");
+ };
+ if (b->get_name().empty()) {
+ b->set_name(attributes.name + "::B");
+ };
+
+ auto m_override = attributes.inputs.find(Matmul_attributes::input_names::M_override);
+ auto n_override = attributes.inputs.find(Matmul_attributes::input_names::N_override);
+ auto k_override = attributes.inputs.find(Matmul_attributes::input_names::K_override);
+
+ if (m_override != attributes.inputs.end()) {
+ auto tensor = m_override->second;
+ if (tensor && tensor->get_name().empty()) {
+ tensor->set_name(attributes.name + "::M_override");
+ }
+ }
+ if (n_override != attributes.inputs.end()) {
+ auto tensor = n_override->second;
+ if (tensor && tensor->get_name().empty()) {
+ tensor->set_name(attributes.name + "::N_override");
+ }
+ }
+ if (k_override != attributes.inputs.end()) {
+ auto tensor = k_override->second;
+ if (tensor && tensor->get_name().empty()) {
+ tensor->set_name(attributes.name + "::K_override");
+ }
+ }
+
+ auto C = attributes.outputs[Matmul_attributes::output_names::C] = output_tensor(attributes.name + "::C");
+
+ sub_nodes.emplace_back(std::make_unique<MatmulNode>(std::move(attributes), context));
+ return C;
+}
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/matmul_fp8.h b/deps/cudnn-frontend/include/cudnn_frontend/node/matmul_fp8.h
new file mode 100644
index 0000000..d3fe5e5
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/matmul_fp8.h
@@ -0,0 +1,104 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class MatmulFP8Node : public NodeCRTP<MatmulFP8Node> {
+ public:
+ Matmul_fp8_attributes attributes;
+
+ MatmulFP8Node(Matmul_fp8_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::MATMUL;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for matmul fp8 node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto const& a_dim = attributes.inputs.at(Matmul_fp8_attributes::input_names::A)->get_dim();
+ auto const& b_dim = attributes.inputs.at(Matmul_fp8_attributes::input_names::B)->get_dim();
+ auto const& c_dim = attributes.outputs.at(Matmul_fp8_attributes::output_names::C)->get_dim();
+
+ std::shared_ptr<Tensor_attributes> last_output;
+
+ // Matmul
+
+ auto matmul_attributes = Matmul_attributes();
+ matmul_attributes.clone_fp8_attributes(attributes);
+ matmul_attributes.set_name("matmul");
+
+ last_output = matmul(attributes.inputs.at(Matmul_fp8_attributes::input_names::A),
+ attributes.inputs.at(Matmul_fp8_attributes::input_names::B),
+ matmul_attributes);
+
+ // Reduction if GQA for head dimension
+ if (a_dim.size() == 4 && b_dim.size() == 4 && c_dim.size() == 4 && a_dim[1] == b_dim[1] &&
+ a_dim[1] != c_dim[1] && (a_dim[1] % c_dim[1] == 0)) {
+ auto gqa_attributes = Reduction_attributes().set_name("gqa_c").set_mode(ReductionMode_t::ADD);
+ last_output = reduction(last_output, gqa_attributes);
+ last_output->set_dim(c_dim);
+ }
+
+ //// Scale Descales
+ auto mul_attributes = Pointwise_attributes().set_mode(PointwiseMode_t::MUL);
+ // Descale A
+ mul_attributes.set_name("descale_a");
+ last_output =
+ pointwise(last_output, attributes.inputs.at(Matmul_fp8_attributes::input_names::Descale_A), mul_attributes);
+
+ // Descale B
+ mul_attributes.set_name("descale_b");
+ last_output =
+ pointwise(last_output, attributes.inputs.at(Matmul_fp8_attributes::input_names::Descale_B), mul_attributes);
+
+ // Scale C
+ mul_attributes.set_name("scale_c");
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ pointwise(last_output,
+ attributes.inputs.at(Matmul_fp8_attributes::input_names::Scale_C),
+ mul_attributes,
+ attributes.outputs.at(Matmul_fp8_attributes::output_names::C));
+
+ // Amax C
+ auto amax_attributes = Reduction_attributes().set_name("amax_c").set_mode(ReductionMode_t::AMAX);
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ reduction(last_output, amax_attributes, attributes.outputs.at(Matmul_fp8_attributes::output_names::Amax_C));
+
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "MATMUL_FP8"})"_json);
+ }
+#endif
+};
+inline void
+INode::matmul_fp8(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ std::shared_ptr<Tensor_attributes> descale_a,
+ std::shared_ptr<Tensor_attributes> descale_b,
+ std::shared_ptr<Tensor_attributes> scale_c,
+ Matmul_fp8_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c,
+ std::shared_ptr<Tensor_attributes> amax_c) {
+ attributes.inputs[Matmul_fp8_attributes::input_names::A] = a;
+ attributes.inputs[Matmul_fp8_attributes::input_names::B] = b;
+ attributes.inputs[Matmul_fp8_attributes::input_names::Descale_A] = descale_a;
+ attributes.inputs[Matmul_fp8_attributes::input_names::Descale_B] = descale_b;
+ attributes.inputs[Matmul_fp8_attributes::input_names::Scale_C] = scale_c;
+ attributes.outputs[Matmul_fp8_attributes::output_names::C] = c;
+ attributes.outputs[Matmul_fp8_attributes::output_names::Amax_C] = amax_c;
+ sub_nodes.emplace_back(std::make_unique<MatmulFP8Node>(std::move(attributes), context));
+}
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/moe_grouped_matmul.h b/deps/cudnn-frontend/include/cudnn_frontend/node/moe_grouped_matmul.h
new file mode 100644
index 0000000..d05d75d
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/moe_grouped_matmul.h
@@ -0,0 +1,221 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class MoeGroupedMatmulNode : public NodeCRTP<MoeGroupedMatmulNode> {
+ public:
+ Moe_grouped_matmul_attributes attributes;
+
+ MoeGroupedMatmulNode(Moe_grouped_matmul_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::MOE_GROUPED_MATMUL;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating MoeGroupedMatmulNode " << attributes.name);
+
+ auto const token_it = attributes.inputs.find(Moe_grouped_matmul_attributes::input_names::Token);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(token_it == attributes.inputs.end() || token_it->second == nullptr,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MoeGroupedMatmul input Token not set.");
+
+ auto const weight_it = attributes.inputs.find(Moe_grouped_matmul_attributes::input_names::Weight);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(weight_it == attributes.inputs.end() || weight_it->second == nullptr,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MoeGroupedMatmul input Weight not set.");
+
+ auto const first_token_offset_it =
+ attributes.inputs.find(Moe_grouped_matmul_attributes::input_names::FirstTokenOffset);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ first_token_offset_it == attributes.inputs.end() || first_token_offset_it->second == nullptr,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MoeGroupedMatmul input FirstTokenOffset not set.");
+
+ auto const output_it = attributes.outputs.find(Moe_grouped_matmul_attributes::output_names::Output);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(output_it == attributes.outputs.end() || output_it->second == nullptr,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MoeGroupedMatmul output Output not set.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for moe grouped matmul node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto token_tensor = attributes.inputs[Moe_grouped_matmul_attributes::input_names::Token];
+ auto weight_tensor = attributes.inputs[Moe_grouped_matmul_attributes::input_names::Weight];
+ auto token_index_tensor = attributes.inputs[Moe_grouped_matmul_attributes::input_names::TokenIndex];
+ auto output_tensor = attributes.outputs[Moe_grouped_matmul_attributes::output_names::Output];
+
+ auto const token_tensor_dim = token_tensor->get_dim();
+ auto const weight_tensor_dim = weight_tensor->get_dim();
+ auto output_tensor_dim = output_tensor->get_dim();
+
+ if (output_tensor_dim.empty()) {
+ output_tensor_dim.resize(3);
+ output_tensor_dim[0] = 1;
+ output_tensor_dim[2] = weight_tensor_dim[2];
+ if (attributes.mode == MoeGroupedMatmulMode_t::GATHER) {
+ output_tensor_dim[1] = token_index_tensor->get_dim()[1];
+ } else {
+ output_tensor_dim[1] = token_tensor_dim[1];
+ }
+ output_tensor_dim.resize(3);
+
+ output_tensor->set_dim(output_tensor_dim);
+ }
+
+ if (output_tensor->get_stride().empty()) {
+ auto const& output_dim = output_tensor->get_dim();
+ auto const& stride_order = detail::generate_row_major_stride_order(output_dim.size());
+ output_tensor->set_stride(detail::generate_stride(output_dim, stride_order));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: "
+ << "Building MoeGroupedMatmulNode operations " << attributes.name << std::endl;
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Moe grouped matmul requires cuDNN v9.15.0"};
+
+#if (CUDNN_VERSION >= 91500)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91500, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+
+ auto moe_grouped_matmul_operation =
+ make_shared_backend_pointer(CUDNN_BACKEND_OPERATION_MOE_GROUPED_MATMUL_DESCRIPTOR);
+
+ cudnnMoeGroupedMatmulMode_t moe_grouped_matmul_mode;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.mode, moe_grouped_matmul_mode));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_MODE,
+ CUDNN_TYPE_MOE_GROUPED_MATMUL_MODE,
+ 1,
+ &moe_grouped_matmul_mode));
+
+ cudnnDataType_t cudnn_data_type;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ auto token = attributes.inputs.find(Moe_grouped_matmul_attributes::input_names::Token)->second;
+ auto backend_token = tensors[token->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_TOKEN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_token));
+
+ auto weight = attributes.inputs.find(Moe_grouped_matmul_attributes::input_names::Weight)->second;
+ auto backend_weight = tensors[weight->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_WEIGHT_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_weight));
+
+ auto first_token_offset =
+ attributes.inputs.find(Moe_grouped_matmul_attributes::input_names::FirstTokenOffset)->second;
+ auto backend_first_token_offset = tensors[first_token_offset->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_FIRST_TOKEN_OFFSET_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_first_token_offset));
+
+ auto output = attributes.outputs.find(Moe_grouped_matmul_attributes::output_names::Output)->second;
+ auto backend_output = tensors[output->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_OUTPUT_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_output));
+
+ if (attributes.mode == MoeGroupedMatmulMode_t::GATHER || attributes.mode == MoeGroupedMatmulMode_t::SCATTER) {
+ auto token_index = attributes.inputs.find(Moe_grouped_matmul_attributes::input_names::TokenIndex)->second;
+ auto backend_token_index = tensors[token_index->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_TOKEN_INDEX_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_token_index));
+ }
+
+ if (attributes.mode == MoeGroupedMatmulMode_t::SCATTER) {
+ auto token_ks = attributes.inputs.find(Moe_grouped_matmul_attributes::input_names::TokenKs)->second;
+ auto backend_token_ks = tensors[token_ks->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_TOKEN_KS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_token_ks));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_TOP_K,
+ CUDNN_TYPE_INT32,
+ 1,
+ &(attributes.top_k)));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(moe_grouped_matmul_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(moe_grouped_matmul_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "MOE_GROUPED_MATMUL"})"_json);
+ }
+#endif
+};
+
+inline void
+INode::moe_grouped_matmul(std::shared_ptr<Tensor_attributes> token,
+ std::shared_ptr<Tensor_attributes> weight,
+ std::shared_ptr<Tensor_attributes> first_token_offset,
+ std::shared_ptr<Tensor_attributes> token_index,
+ std::shared_ptr<Tensor_attributes> token_ks,
+ Moe_grouped_matmul_attributes attributes,
+ std::shared_ptr<Tensor_attributes> output) {
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::Token] = token;
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::Weight] = weight;
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::FirstTokenOffset] = first_token_offset;
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::TokenIndex] = token_index;
+ attributes.inputs[Moe_grouped_matmul_attributes::input_names::TokenKs] = token_ks;
+ attributes.outputs[Moe_grouped_matmul_attributes::output_names::Output] = output;
+ sub_nodes.emplace_back(std::make_unique<MoeGroupedMatmulNode>(std::move(attributes), context));
+}
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/moe_grouped_matmul_bwd.h b/deps/cudnn-frontend/include/cudnn_frontend/node/moe_grouped_matmul_bwd.h
new file mode 100644
index 0000000..2076203
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/moe_grouped_matmul_bwd.h
@@ -0,0 +1,181 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class MoeGroupedMatmulBwdNode : public NodeCRTP<MoeGroupedMatmulBwdNode> {
+ public:
+ Moe_grouped_matmul_bwd_attributes attributes;
+
+ MoeGroupedMatmulBwdNode(Moe_grouped_matmul_bwd_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::MOE_GROUPED_MATMUL_BWD;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating MoeGroupedMatmulBwdNode " << attributes.name);
+
+ auto const doutput_it = attributes.inputs.find(Moe_grouped_matmul_bwd_attributes::input_names::DOutput);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(doutput_it == attributes.inputs.end() || doutput_it->second == nullptr,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MoeGroupedMatmulBwd input DOutput not set.");
+
+ auto const token_it = attributes.inputs.find(Moe_grouped_matmul_bwd_attributes::input_names::Token);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(token_it == attributes.inputs.end() || token_it->second == nullptr,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MoeGroupedMatmulBwd input Token not set.");
+
+ auto const first_token_offset_it =
+ attributes.inputs.find(Moe_grouped_matmul_bwd_attributes::input_names::FirstTokenOffset);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ first_token_offset_it == attributes.inputs.end() || first_token_offset_it->second == nullptr,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MoeGroupedMatmulBwd input FirstTokenOffset not set.");
+
+ auto const dweight_it = attributes.outputs.find(Moe_grouped_matmul_bwd_attributes::output_names::DWeight);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(dweight_it == attributes.outputs.end() || dweight_it->second == nullptr,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MoeGroupedMatmulBwd output DWeight not set.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for moe grouped matmul bwd node "
+ << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto doutput_tensor = attributes.inputs[Moe_grouped_matmul_bwd_attributes::input_names::DOutput];
+ auto token_tensor = attributes.inputs[Moe_grouped_matmul_bwd_attributes::input_names::Token];
+ auto token_index_tensor = attributes.inputs[Moe_grouped_matmul_bwd_attributes::input_names::FirstTokenOffset];
+ auto dweight_tensor = attributes.outputs[Moe_grouped_matmul_bwd_attributes::output_names::DWeight];
+
+ auto const doutput_tensor_dim = doutput_tensor->get_dim();
+ auto const token_tensor_dim = token_tensor->get_dim();
+ auto const token_index_tensor_dim = token_index_tensor->get_dim();
+ auto dweight_tensor_dim = dweight_tensor->get_dim();
+
+ if (dweight_tensor_dim.empty()) {
+ dweight_tensor_dim.resize(3);
+ dweight_tensor_dim[0] = token_index_tensor_dim[0];
+ dweight_tensor_dim[1] = token_tensor_dim[2];
+ dweight_tensor_dim[2] = doutput_tensor_dim[2];
+ dweight_tensor->set_dim(dweight_tensor_dim);
+ }
+
+ if (dweight_tensor->get_stride().empty()) {
+ auto const& dweight_dim = dweight_tensor->get_dim();
+ auto const& stride_order = detail::generate_column_major_stride_order(dweight_dim.size());
+ dweight_tensor->set_stride(detail::generate_stride(dweight_dim, stride_order));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: "
+ << "Building MoeGroupedMatmulBwdNode operations " << attributes.name << std::endl;
+ auto cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Moe grouped matmul bwd requires cuDNN v9.22.0"};
+
+#if (CUDNN_VERSION >= 92200)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92200, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+
+ auto moe_grouped_matmul_bwd_operation =
+ make_shared_backend_pointer(CUDNN_BACKEND_OPERATION_MOE_GROUPED_MATMUL_BWD_DESCRIPTOR);
+
+ cudnnDataType_t cudnn_data_type;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_BWD_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ auto token = attributes.inputs.find(Moe_grouped_matmul_bwd_attributes::input_names::Token)->second;
+ auto backend_token = tensors[token->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_BWD_TOKEN_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_token));
+
+ auto dweight = attributes.outputs.find(Moe_grouped_matmul_bwd_attributes::output_names::DWeight)->second;
+ auto backend_dweight = tensors[dweight->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_BWD_DWEIGHT_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_dweight));
+
+ auto first_token_offset =
+ attributes.inputs.find(Moe_grouped_matmul_bwd_attributes::input_names::FirstTokenOffset)->second;
+ auto backend_first_token_offset = tensors[first_token_offset->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(
+ detail::set_attribute(moe_grouped_matmul_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_BWD_FIRST_TOKEN_OFFSET_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_first_token_offset));
+
+ auto doutput = attributes.inputs.find(Moe_grouped_matmul_bwd_attributes::input_names::DOutput)->second;
+ auto backend_doutput = tensors[doutput->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(moe_grouped_matmul_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MOE_GROUPED_MATMUL_BWD_DOUTPUT_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_doutput));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(moe_grouped_matmul_bwd_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(moe_grouped_matmul_bwd_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "MOE_GROUPED_MATMUL_BWD"})"_json);
+ }
+#endif
+};
+
+inline void
+INode::moe_grouped_matmul_bwd(std::shared_ptr<Tensor_attributes> doutput,
+ std::shared_ptr<Tensor_attributes> token,
+ std::shared_ptr<Tensor_attributes> first_token_offset,
+ Moe_grouped_matmul_bwd_attributes attributes,
+ std::shared_ptr<Tensor_attributes> dweight) {
+ attributes.inputs[Moe_grouped_matmul_bwd_attributes::input_names::DOutput] = doutput;
+ attributes.inputs[Moe_grouped_matmul_bwd_attributes::input_names::Token] = token;
+ attributes.inputs[Moe_grouped_matmul_bwd_attributes::input_names::FirstTokenOffset] = first_token_offset;
+ attributes.outputs[Moe_grouped_matmul_bwd_attributes::output_names::DWeight] = dweight;
+ sub_nodes.emplace_back(std::make_unique<MoeGroupedMatmulBwdNode>(std::move(attributes), context));
+}
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/paged_cache_load.h b/deps/cudnn-frontend/include/cudnn_frontend/node/paged_cache_load.h
new file mode 100644
index 0000000..9fc8610
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/paged_cache_load.h
@@ -0,0 +1,153 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+#include "pointwise.h"
+#include "reduction.h"
+
+namespace cudnn_frontend::graph {
+
+class PagedCacheLoadNode : public NodeCRTP<PagedCacheLoadNode> {
+ public:
+ PagedCacheLoad_attributes attributes;
+
+ PagedCacheLoadNode(PagedCacheLoad_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::PAGED_CACHE_LOAD;
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building PagedCacheLoadNode operations " << attributes.name << " ");
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Paged cache load requires cuDNN v9.5.0"};
+
+#if (CUDNN_VERSION >= 90500)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90500, cudnn_ver_error);
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 paged_cache_load_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(paged_cache_load_operation.initialize_managed_backend_pointer(
+ CUDNN_BACKEND_OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR));
+
+ // Set container tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(container, PagedCacheLoad_attributes::input_names::container);
+ auto container_desc = tensors.at(container->second->get_uid())->get_raw_desc();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(paged_cache_load_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_CONTAINER_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &container_desc));
+
+ // Set page table tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(pageTable, PagedCacheLoad_attributes::input_names::pageTable);
+ auto page_table_desc = tensors.at(pageTable->second->get_uid())->get_raw_desc();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(paged_cache_load_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_PAGE_TABLE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &page_table_desc));
+
+ // Set sequence length tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(seqLen, PagedCacheLoad_attributes::input_names::seqLen);
+ auto seq_len_desc = tensors.at(seqLen->second->get_uid())->get_raw_desc();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(paged_cache_load_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_SEQUENCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &seq_len_desc));
+
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(yOut, PagedCacheLoad_attributes::output_names::yOut);
+ auto y_desc = tensors.at(yOut->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(paged_cache_load_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(paged_cache_load_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(paged_cache_load_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating PagedCacheLoadNode " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90500 || detail::get_compiled_version() < 90500,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "The cuDNN backend version must be at least 9.5.0 at compile time and runtime "
+ "in order to use PagedCacheLoadNode.");
+
+ auto const yOut_dims = attributes.outputs.at(PagedCacheLoad_attributes::output_names::yOut)->get_dim();
+ auto const yOut_strides = attributes.outputs.at(PagedCacheLoad_attributes::output_names::yOut)->get_stride();
+ auto const container_dims = attributes.inputs.at(PagedCacheLoad_attributes::input_names::container)->get_dim();
+ auto const blockTable_dims = attributes.inputs.at(PagedCacheLoad_attributes::input_names::pageTable)->get_dim();
+
+ // In the backend, the k-cache is passed as K^T and has dims [B,H,D,S], while v-cache has dims [B,H,S,D]
+ // Use the strides to distinguish.
+ auto yIsTransposed = yOut_strides[2] == 1;
+ auto s_kv = !yIsTransposed ? yOut_dims[2] : yOut_dims[3];
+
+ auto block_size = container_dims[2];
+ auto block_table_size = blockTable_dims[2];
+ bool is_block_table_packed =
+ attributes.inputs.at(PagedCacheLoad_attributes::input_names::pageTable)->get_ragged_offset() != nullptr;
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !is_block_table_packed && (s_kv + (block_size - 1)) / block_size != block_table_size,
+ error_code_t::INVALID_VALUE,
+ "Paged cache load: block table size must equal ceil(s_kv/block_size), except when using packed block "
+ "tables");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ }
+#endif
+};
+
+inline void
+INode::paged_cache_load(std::shared_ptr<Tensor_attributes> container,
+ std::shared_ptr<Tensor_attributes> seqLen,
+ std::shared_ptr<Tensor_attributes> pageTable,
+ PagedCacheLoad_attributes attributes,
+ std::shared_ptr<Tensor_attributes> yOut) {
+ attributes.inputs[PagedCacheLoad_attributes::input_names::container] = std::move(container);
+ attributes.inputs[PagedCacheLoad_attributes::input_names::seqLen] = std::move(seqLen);
+ attributes.inputs[PagedCacheLoad_attributes::input_names::pageTable] = std::move(pageTable);
+ attributes.outputs[PagedCacheLoad_attributes::output_names::yOut] = std::move(yOut);
+ sub_nodes.emplace_back(std::make_unique<PagedCacheLoadNode>(std::move(attributes), context));
+}
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/pointwise.h b/deps/cudnn-frontend/include/cudnn_frontend/node/pointwise.h
new file mode 100644
index 0000000..6d2da14
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/pointwise.h
@@ -0,0 +1,390 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class PointwiseNode : public NodeCRTP<PointwiseNode> {
+ public:
+ Pointwise_attributes attributes;
+
+ PointwiseNode(Pointwise_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::POINTWISE;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for pointwise node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto out_0_tensor = attributes.outputs.at(Pointwise_attributes::output_names::OUT_0);
+
+ auto output_dim = out_0_tensor->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (output_dim.empty()) {
+ std::vector<std::vector<int64_t>> input_shapes;
+ for (const auto& [input_name, input_tensor] : attributes.inputs) {
+ if (!input_tensor) {
+ continue;
+ }
+ input_shapes.push_back(input_tensor->get_dim());
+ }
+
+ CHECK_CUDNN_FRONTEND_ERROR(detail::compute_broadcast_shape(input_shapes, output_dim));
+ out_0_tensor->set_dim(output_dim);
+ }
+
+ if (out_0_tensor->get_stride().empty()) {
+ for (const auto& [input_name, input_tensor] : attributes.inputs) {
+ if (input_tensor == nullptr) {
+ continue;
+ }
+ if (input_tensor->get_dim() == out_0_tensor->get_dim()) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO:" << " " << out_0_tensor->get_name()
+ << " stride computed from " << input_tensor->get_name());
+ out_0_tensor->set_stride(input_tensor->get_stride());
+ break;
+ }
+ }
+ if (out_0_tensor->get_stride().empty() && out_0_tensor->get_is_virtual()) {
+ // If the tensor is virtual the strides are immaterial
+ auto input_stride = attributes.inputs.at(Pointwise_attributes::input_names::IN_0)->get_stride();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(input_stride, output_dim.size(), stride_order));
+ out_0_tensor->set_stride(detail::generate_stride(output_dim, stride_order));
+ }
+ RETURN_CUDNN_FRONTEND_ERROR_IF(out_0_tensor->get_stride().empty(),
+ error_code_t::SHAPE_DEDUCTION_FAILED,
+ "Pointwise output strides could not be computed");
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building PointwiseNode operations " << attributes.name << " ");
+
+ // Create pointwise descriptor by directly calling cuDNN backend API
+ PointWiseDesc_v8 pointwise_descriptor;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ pointwise_descriptor.initialize_managed_backend_pointer(CUDNN_BACKEND_POINTWISE_DESCRIPTOR));
+
+ // Set pointwise mode
+ cudnnPointwiseMode_t cudnn_pointwise_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.mode, cudnn_pointwise_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_descriptor.get_raw_desc(),
+ CUDNN_ATTR_POINTWISE_MODE,
+ CUDNN_TYPE_POINTWISE_MODE,
+ 1,
+ &cudnn_pointwise_mode));
+
+ // Set compute type
+ cudnnDataType_t cudnn_data_type;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_descriptor.get_raw_desc(),
+ CUDNN_ATTR_POINTWISE_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ // Set mode-specific attributes
+ if (attributes.mode == PointwiseMode_t::RELU_FWD || attributes.mode == PointwiseMode_t::RELU_BWD) {
+ cudnnNanPropagation_t nan_propagation = CUDNN_PROPAGATE_NAN;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_descriptor.get_raw_desc(),
+ CUDNN_ATTR_POINTWISE_NAN_PROPAGATION,
+ CUDNN_TYPE_NAN_PROPOGATION,
+ 1,
+ &nan_propagation));
+
+ double lower_clip = attributes.relu_lower_clip.value_or(0.0);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_descriptor.get_raw_desc(),
+ CUDNN_ATTR_POINTWISE_RELU_LOWER_CLIP,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &lower_clip));
+
+ double upper_clip = attributes.relu_upper_clip.value_or(std::numeric_limits<double>::max());
+ if (attributes.compute_data_type == DataType_t::FLOAT) {
+ upper_clip = std::min<double>(upper_clip, std::numeric_limits<float>::max());
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_descriptor.get_raw_desc(),
+ CUDNN_ATTR_POINTWISE_RELU_UPPER_CLIP,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &upper_clip));
+
+ double lower_clip_slope = attributes.relu_lower_clip_slope.value_or(0.0);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_descriptor.get_raw_desc(),
+ CUDNN_ATTR_POINTWISE_RELU_LOWER_CLIP_SLOPE,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &lower_clip_slope));
+ } else if (attributes.mode == PointwiseMode_t::ELU_FWD || attributes.mode == PointwiseMode_t::ELU_BWD) {
+ double elu_alpha = attributes.elu_alpha.value_or(1.0);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ pointwise_descriptor.get_raw_desc(), CUDNN_ATTR_POINTWISE_ELU_ALPHA, CUDNN_TYPE_DOUBLE, 1, &elu_alpha));
+ } else if (attributes.mode == PointwiseMode_t::SOFTPLUS_FWD ||
+ attributes.mode == PointwiseMode_t::SOFTPLUS_BWD) {
+ double softplus_beta = attributes.softplus_beta.value_or(1.0);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_descriptor.get_raw_desc(),
+ CUDNN_ATTR_POINTWISE_SOFTPLUS_BETA,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &softplus_beta));
+ } else if (attributes.mode == PointwiseMode_t::SWISH_FWD || attributes.mode == PointwiseMode_t::SWISH_BWD) {
+ double swish_beta = attributes.swish_beta.value_or(1.0);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_descriptor.get_raw_desc(),
+ CUDNN_ATTR_POINTWISE_SWISH_BETA,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &swish_beta));
+ } else if (attributes.mode == PointwiseMode_t::GEN_INDEX) {
+ int64_t axis = attributes.get_axis().value_or(-1);
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ pointwise_descriptor.get_raw_desc(), CUDNN_ATTR_POINTWISE_AXIS, CUDNN_TYPE_INT64, 1, &axis));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(pointwise_descriptor.get_raw_desc()));
+ CUDNN_FE_LOG_LABEL_ENDL(pointwise_descriptor);
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 pointwise_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ pointwise_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR));
+
+ // Set the pointwise descriptor
+ auto pw_desc_ptr = pointwise_descriptor.get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_POINTWISE_PW_DESCRIPTOR,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &pw_desc_ptr));
+
+ auto const port_count = get_pointwise_mode_port_count(attributes.mode);
+ bool const is_activation_bwd = detail::is_activation_backward_mode(attributes.mode);
+
+ if (is_activation_bwd) {
+ // Backward mode: IN_0 is dy, IN_1 is x, OUT_0 is dx
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(IN_0, Pointwise_attributes::input_names::IN_0);
+ auto dy_desc = tensors.at(IN_0->second->get_uid())->get_raw_desc();
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(IN_1, Pointwise_attributes::input_names::IN_1);
+ auto x_desc = tensors.at(IN_1->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_POINTWISE_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_POINTWISE_DYDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dy_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(OUT_0, Pointwise_attributes::output_names::OUT_0);
+ auto dx_desc = tensors.at(OUT_0->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_POINTWISE_DXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dx_desc));
+ } else {
+ // Forward mode
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(IN_0, Pointwise_attributes::input_names::IN_0);
+ auto x_desc = tensors.at(IN_0->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_POINTWISE_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(OUT_0, Pointwise_attributes::output_names::OUT_0);
+ auto y_desc = tensors.at(OUT_0->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_POINTWISE_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ if (port_count >= 3) {
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(IN_1, Pointwise_attributes::input_names::IN_1);
+ auto b_desc = tensors.at(IN_1->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_POINTWISE_BDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &b_desc));
+ }
+
+ if (port_count >= 4) {
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(IN_2, Pointwise_attributes::input_names::IN_2);
+ auto t_desc = tensors.at(IN_2->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(pointwise_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_POINTWISE_TDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &t_desc));
+ }
+ }
+
+ // Set alpha scaling factors (always set to 1.0)
+ float alpha1 = 1.0f;
+ float alpha2 = 1.0f;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ pointwise_operation.get_raw_desc(), CUDNN_ATTR_OPERATION_POINTWISE_ALPHA1, CUDNN_TYPE_FLOAT, 1, &alpha1));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ pointwise_operation.get_raw_desc(), CUDNN_ATTR_OPERATION_POINTWISE_ALPHA2, CUDNN_TYPE_FLOAT, 1, &alpha2));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(pointwise_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(pointwise_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"({"tag": "POINTWISE"})"_json);
+ }
+#endif
+};
+
+inline void
+INode::pointwise(std::shared_ptr<Tensor_attributes> a,
+ Pointwise_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c) {
+ attributes.inputs[Pointwise_attributes::input_names::IN_0] = a;
+ attributes.outputs[Pointwise_attributes::output_names::OUT_0] = c;
+ sub_nodes.emplace_back(std::make_unique<PointwiseNode>(std::move(attributes), context));
+}
+
+inline void
+INode::pointwise(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ Pointwise_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c) {
+ attributes.inputs[Pointwise_attributes::input_names::IN_0] = a;
+ attributes.inputs[Pointwise_attributes::input_names::IN_1] = b;
+ attributes.outputs[Pointwise_attributes::output_names::OUT_0] = c;
+ sub_nodes.emplace_back(std::make_unique<PointwiseNode>(std::move(attributes), context));
+}
+
+inline void
+INode::pointwise(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ std::shared_ptr<Tensor_attributes> c,
+ Pointwise_attributes attributes,
+ std::shared_ptr<Tensor_attributes> d) {
+ attributes.inputs[Pointwise_attributes::input_names::IN_0] = a;
+ attributes.inputs[Pointwise_attributes::input_names::IN_1] = b;
+ attributes.inputs[Pointwise_attributes::input_names::IN_2] = c;
+ attributes.outputs[Pointwise_attributes::output_names::OUT_0] = d;
+ sub_nodes.emplace_back(std::make_unique<PointwiseNode>(std::move(attributes), context));
+}
+
+inline std::shared_ptr<Tensor_attributes>
+INode::pointwise(std::shared_ptr<Tensor_attributes> a, Pointwise_attributes attributes) {
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+ attributes.inputs[Pointwise_attributes::input_names::IN_0] = a;
+ if (a->get_name().empty()) {
+ a->set_name(attributes.name + "::IN_0");
+ };
+ auto OUT_0 = attributes.outputs[Pointwise_attributes::output_names::OUT_0] =
+ output_tensor(attributes.name + "::OUT_0");
+
+ sub_nodes.emplace_back(std::make_unique<PointwiseNode>(std::move(attributes), context));
+ return OUT_0;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+INode::pointwise(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ Pointwise_attributes attributes) {
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+ attributes.inputs[Pointwise_attributes::input_names::IN_0] = a;
+ attributes.inputs[Pointwise_attributes::input_names::IN_1] = b;
+ if (a->get_name().empty()) {
+ a->set_name(attributes.name + "::IN_0");
+ };
+ if (b->get_name().empty()) {
+ b->set_name(attributes.name + "::IN_1");
+ };
+ auto OUT_0 = attributes.outputs[Pointwise_attributes::output_names::OUT_0] =
+ output_tensor(attributes.name + "::OUT_0");
+
+ sub_nodes.emplace_back(std::make_unique<PointwiseNode>(std::move(attributes), context));
+ return OUT_0;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+INode::pointwise(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ std::shared_ptr<Tensor_attributes> c,
+ Pointwise_attributes attributes) {
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+ attributes.inputs[Pointwise_attributes::input_names::IN_0] = a;
+ attributes.inputs[Pointwise_attributes::input_names::IN_1] = b;
+ attributes.inputs[Pointwise_attributes::input_names::IN_2] = c;
+ if (a->get_name().empty()) {
+ a->set_name(attributes.name + "::IN_0");
+ };
+ if (b->get_name().empty()) {
+ b->set_name(attributes.name + "::IN_1");
+ };
+ if (c->get_name().empty()) {
+ c->set_name(attributes.name + "::IN_2");
+ };
+ auto OUT_0 = attributes.outputs[Pointwise_attributes::output_names::OUT_0] =
+ output_tensor(attributes.name + "::OUT_0");
+
+ sub_nodes.emplace_back(std::make_unique<PointwiseNode>(std::move(attributes), context));
+ return OUT_0;
+}
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/reduction.h b/deps/cudnn-frontend/include/cudnn_frontend/node/reduction.h
new file mode 100644
index 0000000..5944b69
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/reduction.h
@@ -0,0 +1,232 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class ReductionNode : public NodeCRTP<ReductionNode> {
+ public:
+ Reduction_attributes attributes;
+
+ ReductionNode(Reduction_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::REDUCTION;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating ReductionNode " << attributes.name);
+
+ if (attributes.get_is_deterministic() && detail::get_backend_version() < 91100) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED, "DETERMINISTIC mode is not supported in cudnn version < 9.11.0"};
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for reduction node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // Only inferrencing from IN_0 to OUT_0 works today.
+ auto x_tensor = attributes.inputs[Reduction_attributes::input_names::X];
+ auto y_tensor = attributes.outputs[Reduction_attributes::output_names::Y];
+
+ auto const& x_tensor_dim = x_tensor->get_dim();
+ auto y_tensor_dim = y_tensor->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (y_tensor_dim.empty()) {
+ y_tensor->set_dim(x_tensor_dim);
+ }
+ if (y_tensor->get_stride().empty()) {
+ auto const& y_dim = y_tensor->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(y_dim.size());
+ y_tensor->set_stride(detail::generate_stride(y_dim, stride_order));
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building ReductionNode operations " << attributes.name << " ");
+
+ // Create reduction descriptor by directly calling cuDNN backend API
+ ReductionDesc_v8 reduction_descriptor;
+
+ // 1. Create the backend descriptor
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ reduction_descriptor.initialize_managed_backend_pointer(CUDNN_BACKEND_REDUCTION_DESCRIPTOR));
+
+ // 2. Set compute type attribute
+ cudnnDataType_t cudnn_data_type;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reduction_descriptor.get_raw_desc(),
+ CUDNN_ATTR_REDUCTION_COMP_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ // 3. Set reduction operator attribute
+ cudnnReduceTensorOp_t cudnn_reduction_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.get_mode().value(), cudnn_reduction_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reduction_descriptor.get_raw_desc(),
+ CUDNN_ATTR_REDUCTION_OPERATOR,
+ CUDNN_TYPE_REDUCTION_OPERATOR_TYPE,
+ 1,
+ &cudnn_reduction_mode));
+
+ // 4. Set deterministic mode if supported
+#if (CUDNN_VERSION >= 91100)
+ if (detail::get_backend_version() >= 91100) {
+ bool is_deterministic = attributes.get_is_deterministic();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reduction_descriptor.get_raw_desc(),
+ CUDNN_ATTR_REDUCTION_IS_DETERMINISTIC,
+ CUDNN_TYPE_BOOLEAN,
+ 1,
+ &is_deterministic));
+ }
+#endif
+
+ // 5. Finalize the descriptor
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(reduction_descriptor.get_raw_desc()));
+ CUDNN_FE_LOG_LABEL_ENDL(reduction_descriptor);
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 reduction_operation;
+
+ // Validate input tensors are set
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Reduction_attributes::input_names::X);
+ auto Group_offset = attributes.inputs.find(Reduction_attributes::input_names::Group_offset);
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Reduction_attributes::output_names::Y);
+
+ // 1. Create the backend operation descriptor
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ reduction_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR));
+
+ // 2. Set the reduction descriptor attribute
+ auto reduction_desc_ptr = reduction_descriptor.get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reduction_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_REDUCTION_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &reduction_desc_ptr));
+
+ // 3. Set the input tensor (X) descriptor attribute
+ auto x_backend_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reduction_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_REDUCTION_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_backend_desc));
+
+ // 4. Set the output tensor (Y) descriptor attribute
+ auto y_backend_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reduction_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_REDUCTION_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_backend_desc));
+
+ // 5. Set the optional group offset tensor descriptor
+ if (Group_offset != attributes.inputs.end() && Group_offset->second != nullptr) {
+#if (CUDNN_VERSION >= 92400)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 92400,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Reduction group_offset is not supported in cudnn version < 9.24.0");
+ auto group_offset_backend_desc = tensors.at(Group_offset->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reduction_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_REDUCTION_GROUP_OFFSET_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &group_offset_backend_desc));
+#else
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "Reduction group_offset is not supported in cudnn version < 9.24.0"};
+#endif
+ }
+
+ // 6. Finalize the operation descriptor
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(reduction_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(reduction_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"({"tag": "REDUCTION"})"_json);
+ }
+#endif
+};
+
+inline void
+INode::reduction(std::shared_ptr<Tensor_attributes> a,
+ Reduction_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c) {
+ attributes.inputs[Reduction_attributes::input_names::X] = a;
+ attributes.outputs[Reduction_attributes::output_names::Y] = c;
+ sub_nodes.emplace_back(std::make_unique<ReductionNode>(std::move(attributes), context));
+}
+
+inline void
+INode::reduction(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> group_offset,
+ Reduction_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c) {
+ attributes.inputs[Reduction_attributes::input_names::X] = a;
+ attributes.inputs[Reduction_attributes::input_names::Group_offset] = group_offset;
+ attributes.outputs[Reduction_attributes::output_names::Y] = c;
+ sub_nodes.emplace_back(std::make_unique<ReductionNode>(std::move(attributes), context));
+}
+
+inline std::shared_ptr<Tensor_attributes>
+INode::reduction(std::shared_ptr<Tensor_attributes> input, Reduction_attributes attributes) {
+ attributes.inputs[Reduction_attributes::input_names::X] = input;
+ auto Y = attributes.outputs[Reduction_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+
+ sub_nodes.emplace_back(std::make_unique<ReductionNode>(std::move(attributes), context));
+ return Y;
+}
+
+inline std::shared_ptr<Tensor_attributes>
+INode::reduction(std::shared_ptr<Tensor_attributes> input,
+ std::shared_ptr<Tensor_attributes> group_offset,
+ Reduction_attributes attributes) {
+ attributes.inputs[Reduction_attributes::input_names::X] = input;
+ attributes.inputs[Reduction_attributes::input_names::Group_offset] = group_offset;
+ auto Y = attributes.outputs[Reduction_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+
+ sub_nodes.emplace_back(std::make_unique<ReductionNode>(std::move(attributes), context));
+ return Y;
+}
+} // namespace cudnn_frontend::graph
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/resample.h b/deps/cudnn-frontend/include/cudnn_frontend/node/resample.h
new file mode 100644
index 0000000..34e6031
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/resample.h
@@ -0,0 +1,291 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class ResampleNode : public NodeCRTP<ResampleNode> {
+ public:
+ Resample_attributes attributes;
+
+ ResampleNode(Resample_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::RESAMPLE;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: " << "Validating ResampleNode " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.generate_index.has_value() == false,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "generate_index attribute not set");
+
+ if (attributes.generate_index.value() == true && attributes.resample_mode == ResampleMode_t::MAXPOOL) {
+ CUDNN_FE_VALIDATE_OUTPUT_TENSOR(Resample_attributes::output_names::Index);
+ }
+
+ // Make sure that the mode can be lowered to BE
+ cudnnResampleMode_t dummy;
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::convert_to_cudnn_type(attributes.resample_mode, dummy) != CUDNN_STATUS_SUCCESS,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Invalid resample mode.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for resample node " << attributes.name);
+
+ auto y_tensor = attributes.outputs[Resample_attributes::output_names::Y];
+ auto x_tensor = attributes.inputs[Resample_attributes::input_names::X];
+
+ attributes.fill_from_context(context);
+
+ // If user does not set shape and layout of the output tensor,
+ // Get it from node attributes
+ if (y_tensor->get_dim().empty()) {
+ auto const x_dim = x_tensor->get_dim();
+ auto y_dim = y_tensor->get_dim();
+ y_dim = x_dim;
+
+ // 2 cause first two dimensions are batch and channels
+ for (auto dim = 2u; dim < x_dim.size(); ++dim) {
+ auto spatial_dim = dim - 2u;
+ y_dim[dim] =
+ 1 + (x_dim[dim] + attributes.pre_padding[spatial_dim].numerator +
+ attributes.post_padding[spatial_dim].numerator - attributes.window[spatial_dim].numerator) /
+ attributes.stride[spatial_dim].numerator;
+ }
+
+ y_tensor->set_dim(y_dim);
+ }
+
+ // If layout is not set, generate the strides from layout
+ if (y_tensor->get_stride().empty()) {
+ auto const& y_dim = y_tensor->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(y_dim.size());
+ y_tensor->set_stride(detail::generate_stride(y_dim, stride_order));
+ }
+
+ if (attributes.outputs[Resample_attributes::output_names::Index]) {
+ auto index_tensor = attributes.outputs[Resample_attributes::output_names::Index];
+ index_tensor->set_dim(y_tensor->get_dim());
+
+ // If layout is not set, generate the strides from layout
+ if (index_tensor->get_stride().empty()) {
+ auto const& index_dim = index_tensor->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(index_dim.size());
+ index_tensor->set_stride(detail::generate_stride(index_dim, stride_order));
+ }
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building ResampleNode operations " << attributes.name << " ");
+
+ auto number_of_spatial_dim = static_cast<int64_t>(attributes.window.size());
+
+ // Create resample descriptor by directly calling cuDNN backend API
+ ResampleDesc_v8 resample_descriptor;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ resample_descriptor.initialize_managed_backend_pointer(CUDNN_BACKEND_RESAMPLE_DESCRIPTOR));
+
+ // Set resample mode
+ cudnnResampleMode_t cudnn_resample_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.resample_mode, cudnn_resample_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RESAMPLE_MODE,
+ CUDNN_TYPE_RESAMPLE_MODE,
+ 1,
+ &cudnn_resample_mode));
+
+ // Set compute type
+ cudnnDataType_t cudnn_data_type;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.compute_data_type, cudnn_data_type));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RESAMPLE_COMP_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type));
+
+ // Set nan propagation
+ cudnnNanPropagation_t nan_opt = CUDNN_PROPAGATE_NAN;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RESAMPLE_NAN_PROPAGATION,
+ CUDNN_TYPE_NAN_PROPOGATION,
+ 1,
+ &nan_opt));
+
+ // Set padding mode
+ cudnnPaddingMode_t cudnn_padding_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.padding_mode, cudnn_padding_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RESAMPLE_PADDING_MODE,
+ CUDNN_TYPE_PADDING_MODE,
+ 1,
+ &cudnn_padding_mode));
+
+ // Set spatial dimensions
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RESAMPLE_SPATIAL_DIMS,
+ CUDNN_TYPE_INT64,
+ 1,
+ &number_of_spatial_dim));
+
+ // Set window dimensions
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RESAMPLE_WINDOW_DIMS,
+ CUDNN_TYPE_FRACTION,
+ number_of_spatial_dim,
+ attributes.window.data()));
+
+ // Set pre padding
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RESAMPLE_PRE_PADDINGS,
+ CUDNN_TYPE_FRACTION,
+ number_of_spatial_dim,
+ attributes.pre_padding.data()));
+
+ // Set post padding
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RESAMPLE_POST_PADDINGS,
+ CUDNN_TYPE_FRACTION,
+ number_of_spatial_dim,
+ attributes.post_padding.data()));
+
+ // Set strides
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RESAMPLE_STRIDES,
+ CUDNN_TYPE_FRACTION,
+ number_of_spatial_dim,
+ attributes.stride.data()));
+
+ // Finalize the descriptor
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(resample_descriptor.get_raw_desc()));
+ CUDNN_FE_LOG_LABEL_ENDL(resample_descriptor);
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 resample_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ resample_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Resample_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Resample_attributes::output_names::Y);
+ auto y_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ // Set alpha and beta
+ double alpha = 1.0;
+ double beta = 0.0;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ resample_operation.get_raw_desc(), CUDNN_ATTR_OPERATION_RESAMPLE_FWD_ALPHA, CUDNN_TYPE_DOUBLE, 1, &alpha));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ resample_operation.get_raw_desc(), CUDNN_ATTR_OPERATION_RESAMPLE_FWD_BETA, CUDNN_TYPE_DOUBLE, 1, &beta));
+
+ // Set resample descriptor
+ auto resample_raw_desc = resample_descriptor.get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &resample_raw_desc));
+
+ // Set index tensor if available
+ auto index = attributes.outputs.find(Resample_attributes::output_names::Index);
+ if ((index != attributes.outputs.end()) && (index->second != nullptr)) {
+ auto idx_desc = tensors.at(index->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(resample_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_IDXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &idx_desc));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(resample_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(resample_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "RESAMPLE"})"_json);
+ }
+#endif
+};
+
+inline std::array<std::shared_ptr<Tensor_attributes>, 2>
+INode::resample(std::shared_ptr<Tensor_attributes> input, Resample_attributes attributes) {
+ if (attributes.name.empty()) {
+ attributes.name += std::to_string(sub_nodes.size());
+ }
+ attributes.inputs[Resample_attributes::input_names::X] = input;
+ auto Y = attributes.outputs[Resample_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+ std::shared_ptr<Tensor_attributes> Index = nullptr;
+ if (attributes.generate_index.has_value() && attributes.generate_index.value() == true &&
+ attributes.resample_mode == ResampleMode_t::MAXPOOL) {
+ Index = attributes.outputs[Resample_attributes::output_names::Index] =
+ output_tensor(attributes.name + "::Index");
+ }
+
+ sub_nodes.emplace_back(std::make_unique<ResampleNode>(std::move(attributes), context));
+ return {Y, Index};
+}
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/reshape.h b/deps/cudnn-frontend/include/cudnn_frontend/node/reshape.h
new file mode 100644
index 0000000..e2b5546
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/reshape.h
@@ -0,0 +1,156 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class ReshapeNode : public NodeCRTP<ReshapeNode> {
+ public:
+ Reshape_attributes attributes;
+
+ ReshapeNode(Reshape_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::RESHAPE;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for reshape node " << attributes.name);
+
+ auto y_tensor = attributes.outputs[Reshape_attributes::output_names::Y];
+
+ attributes.fill_from_context(context);
+
+ // If user does not set shape and layout of the output tensor,
+ // Get it from node attributes
+ // If layout is not set, generate the strides from layout
+
+ if (y_tensor->get_dim().empty() && attributes.get_dim().size()) {
+ y_tensor->set_dim(attributes.dim);
+ }
+
+ // Graph producers may represent scalar reshape outputs
+ // as rank-0 tensors (dim={}). Without promotion, stride inference below
+ // would call generate_NHWC_stride_order(0), which is UB, and the cuDNN
+ // backend rejects rank-0 descriptors regardless. Promote to canonical
+ // rank-1 length-1 -- value-preserving because a scalar has volume 1 --
+ // while keeping the normalization node-local so downstream broadcast/shape
+ // inference remains intact.
+ if (y_tensor->get_dim().empty()) {
+ y_tensor->set_dim({1});
+ if (y_tensor->get_stride().empty()) {
+ y_tensor->set_stride({1});
+ }
+ }
+
+ if (y_tensor->get_stride().empty()) {
+ if (attributes.get_stride().size()) {
+ y_tensor->set_stride(attributes.get_stride());
+ } else {
+ auto const& y_dim = y_tensor->get_dim();
+ // Default to NHWC for multi-axis tensors. generate_NHWC_stride_order
+ // indexes stride_order[1] and assumes num_dims >= 2; use row-major
+ // for scalars (0-D) and vectors (1-D).
+ const int64_t rank = static_cast<int64_t>(y_dim.size());
+ std::vector<int64_t> const stride_order =
+ rank < 2 ? detail::generate_row_major_stride_order(rank) : detail::generate_NHWC_stride_order(rank);
+ y_tensor->set_stride(detail::generate_stride(y_dim, stride_order));
+ }
+ }
+
+ if (y_tensor->get_dim().empty() || y_tensor->get_stride().empty()) {
+ return {error_code_t::SHAPE_DEDUCTION_FAILED, "Reshape node output shape deduction failed"};
+ }
+
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Reshape_attributes::input_names::X);
+ auto const& input_data_type = X->second->get_data_type();
+ if (y_tensor->get_data_type() == DataType_t::NOT_SET) {
+ y_tensor->set_data_type(input_data_type);
+ } else if (attributes.get_reshape_mode() == ReshapeMode_t::LOGICAL) {
+ // Lexicographic reshape preserves element type; reject inconsistent metadata.
+ // VIEW_ONLY paths (e.g. SDPA backward) may set Y dtype after reshape to match a consumer.
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ y_tensor->get_data_type() != input_data_type,
+ error_code_t::INVALID_VALUE,
+ "Output and input tensor data types must match for LOGICAL reshape operation.");
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building ReshapeNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 reshape_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ reshape_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_RESHAPE_DESCRIPTOR));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Reshape_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reshape_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RESHAPE_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+#if (CUDNN_VERSION >= 92200)
+ // Set reshape mode
+ cudnnBackendReshapeMode_t cudnn_reshape_mode;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.get_reshape_mode(), cudnn_reshape_mode));
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reshape_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RESHAPE_MODE,
+ CUDNN_TYPE_RESHAPE_MODE,
+ 1,
+ &cudnn_reshape_mode));
+#endif
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Reshape_attributes::output_names::Y);
+ auto y_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(reshape_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RESHAPE_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(reshape_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(reshape_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "RESHAPE"})"_json);
+ }
+#endif
+};
+
+inline std::shared_ptr<Tensor_attributes>
+INode::reshape(std::shared_ptr<Tensor_attributes> input, Reshape_attributes attributes) {
+ attributes.inputs[Reshape_attributes::input_names::X] = input;
+ auto Y = attributes.outputs[Reshape_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+
+ sub_nodes.emplace_back(std::make_unique<ReshapeNode>(std::move(attributes), context));
+ return Y;
+}
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/rmsnorm.h b/deps/cudnn-frontend/include/cudnn_frontend/node/rmsnorm.h
new file mode 100644
index 0000000..bc1f37d
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/rmsnorm.h
@@ -0,0 +1,406 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+class RMSNormNode : public NodeCRTP<RMSNormNode> {
+ public:
+ Rmsnorm_attributes attributes;
+
+ RMSNormNode(Rmsnorm_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::RMSNORM;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for rmsnorm node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto X = attributes.inputs[Rmsnorm_attributes::input_names::X];
+ auto Y = attributes.outputs[Rmsnorm_attributes::output_names::Y];
+
+ // Only infer dims and strides if user did not set them
+ if (Y->get_dim().empty()) {
+ Y->set_dim(X->get_dim());
+ }
+ if (Y->get_stride().empty()) {
+ Y->set_stride(X->get_stride());
+ }
+
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ auto inv_var = attributes.outputs[Rmsnorm_attributes::output_names::INV_VARIANCE];
+ // Only infer dims and strides if user did not set them
+ if (inv_var->get_dim().empty()) {
+ auto inv_var_dim = X->get_dim();
+ auto scale = attributes.inputs[Rmsnorm_attributes::input_names::SCALE];
+ if (scale->get_dim().empty()) {
+ // mean inv_var dim is n,1,1,1
+ for (size_t i = 1; i < inv_var_dim.size(); i++) {
+ inv_var_dim[i] = 1;
+ }
+ } else {
+ for (size_t i = 0; i < inv_var_dim.size(); i++) {
+ if (scale->get_dim()[i] != 1) {
+ inv_var_dim[i] = 1;
+ }
+ }
+ }
+ inv_var->set_dim(inv_var_dim);
+ }
+ if (inv_var->get_stride().empty()) {
+ auto const& inv_var_dim = inv_var->get_dim();
+ std::vector<int64_t> stride_order;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ detail::generate_stride_order_preserving_format(X->get_stride(), inv_var_dim.size(), stride_order));
+ inv_var->set_stride(detail::generate_stride(inv_var_dim, stride_order));
+ }
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating RMSNormNode " << attributes.name);
+
+ // Norm forward phase should be set
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.forward_phase == NormFwdPhase_t::NOT_SET,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Forward phase not set of rmsnorm node.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building RMSNormNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 rmsnorm_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ rmsnorm_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR));
+
+ // Set norm mode to RMS_NORM
+ cudnnBackendNormMode_t cudnn_norm_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::RMS_NORM, cudnn_norm_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ // Set forward phase
+ cudnnBackendNormFwdPhase_t cudnn_norm_fwd_phase;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.forward_phase, cudnn_norm_fwd_phase));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_PHASE,
+ CUDNN_TYPE_NORM_FWD_PHASE,
+ 1,
+ &cudnn_norm_fwd_phase));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Rmsnorm_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set scale tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, Rmsnorm_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ // Set epsilon tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(EPSILON, Rmsnorm_attributes::input_names::EPSILON);
+ auto epsilon_desc = tensors.at(EPSILON->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_EPSILON_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &epsilon_desc));
+
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Rmsnorm_attributes::output_names::Y);
+ auto y_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &y_desc));
+
+ // Set inv_variance for training phase
+ if (attributes.forward_phase == NormFwdPhase_t::TRAINING) {
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(INV_VARIANCE, Rmsnorm_attributes::output_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+ }
+
+ // Set optional bias tensor
+ auto BIAS = attributes.inputs.find(Rmsnorm_attributes::input_names::BIAS);
+ if ((BIAS != attributes.inputs.end()) && (BIAS->second != nullptr)) {
+ auto bias_desc = tensors.at(BIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_BIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &bias_desc));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(rmsnorm_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(rmsnorm_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "RMS_NORM"})"_json);
+ }
+#endif
+};
+
+class DRMSNormNode : public NodeCRTP<DRMSNormNode> {
+ public:
+ Rmsnorm_backward_attributes attributes;
+
+ DRMSNormNode(Rmsnorm_backward_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::DRMSNorm;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating DRMSNormNode node " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.use_dbias.has_value() == false,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "DRMSNormNode node needs has_bias(bool) to be called.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for DRMSNorm node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // TODO: Only inferencing from X works today.
+ auto X = attributes.inputs[Rmsnorm_backward_attributes::input_names::X];
+ auto const x_tensor_dim = X->get_dim();
+
+ auto DY = attributes.inputs[Rmsnorm_backward_attributes::input_names::DY];
+ auto dy_tensor_dim = DY->get_dim();
+
+ // Only infer dims and strides if user did not set them
+ if (dy_tensor_dim.empty()) {
+ dy_tensor_dim.resize(x_tensor_dim.size());
+ DY->set_dim(x_tensor_dim);
+ }
+ if (DY->get_stride().empty()) {
+ auto const& DY_dim = DY->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(DY_dim.size());
+ DY->set_stride(detail::generate_stride(DY_dim, stride_order));
+ }
+
+ auto DX = attributes.outputs[Rmsnorm_backward_attributes::output_names::DX];
+ auto dx_tensor_dim = DX->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (dx_tensor_dim.empty()) {
+ dx_tensor_dim.resize(x_tensor_dim.size());
+ DX->set_dim(x_tensor_dim);
+ }
+ if (DX->get_stride().empty()) {
+ auto const& DX_dim = DX->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(DX_dim.size());
+ DX->set_stride(detail::generate_stride(DX_dim, stride_order));
+ }
+
+ auto scale_bias_dim = X->get_dim();
+ scale_bias_dim[0] = 1;
+
+ // Set channel length tensors
+ auto infer_scale_bias_tensors = [&scale_bias_dim](std::shared_ptr<Tensor_attributes>& T) {
+ auto tensor_dim = T->get_dim();
+ // Only infer dims and strides if user did not set them
+ if (tensor_dim.empty()) {
+ T->set_dim(scale_bias_dim);
+ }
+ if (T->get_stride().empty()) {
+ auto const& T_dim = T->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(T_dim.size());
+ T->set_stride(detail::generate_stride(T_dim, stride_order));
+ }
+ };
+
+ infer_scale_bias_tensors(attributes.outputs[Rmsnorm_backward_attributes::output_names::DSCALE]);
+ if (attributes.use_dbias.value()) {
+ infer_scale_bias_tensors(attributes.outputs[Rmsnorm_backward_attributes::output_names::DBIAS]);
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building DRMSNormNode operations " << attributes.name << " ");
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 drmsnorm_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ drmsnorm_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR));
+
+ // Set norm mode to RMS_NORM
+ cudnnBackendNormMode_t cudnn_norm_mode;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(NormMode_t::RMS_NORM, cudnn_norm_mode));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(drmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode));
+
+ // Set input tensor X
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(X, Rmsnorm_backward_attributes::input_names::X);
+ auto x_desc = tensors.at(X->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(drmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &x_desc));
+
+ // Set DY tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(DY, Rmsnorm_backward_attributes::input_names::DY);
+ auto dy_desc = tensors.at(DY->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(drmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DYDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dy_desc));
+
+ // Set scale tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(SCALE, Rmsnorm_backward_attributes::input_names::SCALE);
+ auto scale_desc = tensors.at(SCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(drmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_SCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &scale_desc));
+
+ // Set inv_variance tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(INV_VARIANCE, Rmsnorm_backward_attributes::input_names::INV_VARIANCE);
+ auto inv_var_desc = tensors.at(INV_VARIANCE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(drmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_INV_VARIANCE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &inv_var_desc));
+
+ // Set DSCALE output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DSCALE, Rmsnorm_backward_attributes::output_names::DSCALE);
+ auto dscale_desc = tensors.at(DSCALE->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(drmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DSCALE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dscale_desc));
+
+ // Set optional DBIAS output tensor
+ if (attributes.use_dbias.value()) {
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DBIAS, Rmsnorm_backward_attributes::output_names::DBIAS);
+ auto dbias_desc = tensors.at(DBIAS->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(drmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DBIAS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dbias_desc));
+ }
+
+ // Set DX output tensor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(DX, Rmsnorm_backward_attributes::output_names::DX);
+ auto dx_desc = tensors.at(DX->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(drmsnorm_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_NORM_BWD_DXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &dx_desc));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(drmsnorm_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(drmsnorm_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "RMS_NORM_BPROP"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/rng.h b/deps/cudnn-frontend/include/cudnn_frontend/node/rng.h
new file mode 100644
index 0000000..09b762d
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/rng.h
@@ -0,0 +1,187 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class RngNode : public NodeCRTP<RngNode> {
+ public:
+ Rng_attributes attributes;
+
+ RngNode(Rng_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::RNG;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for rng node " << attributes.name);
+
+ auto y_tensor = attributes.outputs[Rng_attributes::output_names::Y];
+
+ attributes.fill_from_context(context);
+
+ // If user does not set shape and layout of the generated tensor,
+ // Get it from node attributes
+ // If layout is not set, generate the strides from layout
+
+ if (y_tensor->get_dim().empty() && attributes.get_dim().size()) {
+ y_tensor->set_dim(attributes.dim);
+ }
+
+ if (y_tensor->get_stride().empty()) {
+ if (attributes.get_stride().size()) {
+ y_tensor->set_stride(attributes.get_stride());
+ } else {
+ auto const& y_dim = y_tensor->get_dim();
+ // Default to NHWC
+ auto const& stride_order = detail::generate_NHWC_stride_order(y_dim.size());
+ y_tensor->set_stride(detail::generate_stride(y_dim, stride_order));
+ }
+ }
+
+ if (y_tensor->get_dim().empty() || y_tensor->get_stride().empty()) {
+ return {error_code_t::SHAPE_DEDUCTION_FAILED, "RNG node output shape deduction failed"};
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FE_LOG_LABEL("INFO: " << "Building RngNode operations " << attributes.name << " ");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.get_distribution() != RngDistribution_t::BERNOULLI,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "no other distribution except bernoulli supported.");
+
+ // Create RNG descriptor by directly calling cuDNN backend API
+ RngDesc_v8 rng_descriptor;
+
+ _CUDNN_CHECK_CUDNN_ERROR(rng_descriptor.initialize_managed_backend_pointer(CUDNN_BACKEND_RNG_DESCRIPTOR));
+
+ // Set distribution type
+ cudnnRngDistribution_t cudnn_rng_distribution;
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::convert_to_cudnn_type(attributes.get_distribution(), cudnn_rng_distribution));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rng_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RNG_DISTRIBUTION,
+ CUDNN_TYPE_RNG_DISTRIBUTION,
+ 1,
+ &cudnn_rng_distribution));
+
+ // Set Bernoulli distribution probability
+ double bernoulli_prob = attributes.get_bernoulli_probability().value();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rng_descriptor.get_raw_desc(),
+ CUDNN_ATTR_RNG_BERNOULLI_DIST_PROBABILITY,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &bernoulli_prob));
+
+ // Finalize the descriptor
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(rng_descriptor.get_raw_desc()));
+ CUDNN_FE_LOG_LABEL_ENDL(rng_descriptor);
+
+ // Create operation by directly calling cuDNN backend API
+ Operation_v8 rng_operation;
+
+ _CUDNN_CHECK_CUDNN_ERROR(
+ rng_operation.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATION_RNG_DESCRIPTOR));
+
+ // Set output tensor Y
+ CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(Y, Rng_attributes::output_names::Y);
+ auto y_desc = tensors.at(Y->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ rng_operation.get_raw_desc(), CUDNN_ATTR_OPERATION_RNG_YDESC, CUDNN_TYPE_BACKEND_DESCRIPTOR, 1, &y_desc));
+
+ // Set RNG descriptor
+ auto rng_raw_desc = rng_descriptor.get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rng_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RNG_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &rng_raw_desc));
+
+ if (attributes.seed.has_value()) {
+ // Set seed as int64_t value
+ int64_t seed_value = attributes.get_seed().value();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(
+ rng_operation.get_raw_desc(), CUDNN_ATTR_OPERATION_RNG_SEED, CUDNN_TYPE_INT64, 1, &seed_value));
+ } else {
+ // Set seed tensor descriptor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(Seed, Rng_attributes::input_names::Seed);
+ auto seed_desc = tensors.at(Seed->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rng_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RNG_SEED,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &seed_desc));
+
+ // Set offset tensor descriptor
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(Offset, Rng_attributes::input_names::Offset);
+ auto offset_desc = tensors.at(Offset->second->get_uid())->get_raw_desc();
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rng_operation.get_raw_desc(),
+ CUDNN_ATTR_OPERATION_RNG_OFFSET_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &offset_desc));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(rng_operation.get_raw_desc()));
+
+ operations.push_back(std::make_shared<Operation_v8>(std::move(rng_operation)));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "RNG"})"_json);
+ }
+#endif
+};
+
+inline void
+INode::rng(std::shared_ptr<Tensor_attributes> seed,
+ std::shared_ptr<Tensor_attributes> offset,
+ Rng_attributes attributes,
+ std::shared_ptr<Tensor_attributes> y) {
+ attributes.inputs[Rng_attributes::input_names::Seed] = seed;
+ attributes.inputs[Rng_attributes::input_names::Offset] = offset;
+ attributes.outputs[Rng_attributes::output_names::Y] = y;
+ sub_nodes.emplace_back(std::make_unique<RngNode>(std::move(attributes), context));
+}
+
+inline std::shared_ptr<Tensor_attributes>
+INode::rng(std::shared_ptr<Tensor_attributes> seed,
+ std::shared_ptr<Tensor_attributes> offset,
+ Rng_attributes attributes) {
+ attributes.inputs[Rng_attributes::input_names::Seed] = seed;
+ attributes.inputs[Rng_attributes::input_names::Offset] = offset;
+ auto Y = attributes.outputs[Rng_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+
+ sub_nodes.emplace_back(std::make_unique<RngNode>(std::move(attributes), context));
+ return Y;
+}
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/rope.h b/deps/cudnn-frontend/include/cudnn_frontend/node/rope.h
new file mode 100644
index 0000000..01b05c4
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/rope.h
@@ -0,0 +1,146 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+class RoPENode : public NodeCRTP<RoPENode> {
+ public:
+ RoPE_attributes attributes;
+
+ RoPENode(RoPE_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::ROPE;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for RoPE node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto INPUT = attributes.inputs[RoPE_attributes::input_names::INPUT];
+ auto OUTPUT = attributes.outputs[RoPE_attributes::output_names::OUTPUT];
+
+ if (OUTPUT->get_dim().empty()) {
+ OUTPUT->set_dim(INPUT->get_dim());
+ }
+ if (OUTPUT->get_stride().empty()) {
+ OUTPUT->set_stride(INPUT->get_stride());
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating RoPENode " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.inputs.find(RoPE_attributes::input_names::INPUT) == attributes.inputs.end(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "RoPE node requires INPUT tensor.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.inputs.find(RoPE_attributes::input_names::FREQS) == attributes.inputs.end(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "RoPE node requires FREQS tensor.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building RoPENode operations " << attributes.name << " ");
+
+#if (CUDNN_VERSION >= 92400)
+ // Compile- and run-time checks: RoPE op was added in cuDNN 9.24.
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::get_backend_version() < 92400,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION_ROPE_FWD_DESCRIPTOR is only available starting cuDNN 9.24.");
+
+ auto rope_operation =
+ make_shared_backend_pointer((cudnnBackendDescriptorType_t)CUDNN_BACKEND_OPERATION_ROPE_FWD_DESCRIPTOR);
+
+ // Set input X
+ auto X = attributes.inputs.find(RoPE_attributes::input_names::INPUT)->second;
+ auto backend_x = tensors[X->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_FWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_x));
+
+ // Set freqs
+ auto FREQS = attributes.inputs.find(RoPE_attributes::input_names::FREQS)->second;
+ auto backend_freqs = tensors[FREQS->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_FWD_FREQSDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_freqs));
+
+ // Set output Y
+ auto Y = attributes.outputs.find(RoPE_attributes::output_names::OUTPUT)->second;
+ auto backend_y = tensors[Y->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_FWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_y));
+
+ // Set output_scale (host fp32 scalar; default 1.0)
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_FWD_OUTPUT_SCALE,
+ CUDNN_TYPE_FLOAT,
+ 1,
+ &attributes.output_scale));
+
+ // Set rope_dim (int64; 0 = full rotation = input's head_dim)
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_FWD_ROPE_DIM,
+ CUDNN_TYPE_INT64,
+ 1,
+ &attributes.rope_dim));
+
+ // Finalize
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(rope_operation->get_backend_descriptor()));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+
+ raw_operations.push_back(rope_operation);
+
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION_ROPE_FWD_DESCRIPTOR is only available starting cuDNN 9.24."};
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"({"tag": "ROPE"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/rope_backward.h b/deps/cudnn-frontend/include/cudnn_frontend/node/rope_backward.h
new file mode 100644
index 0000000..fd7bf4f
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/rope_backward.h
@@ -0,0 +1,143 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+class RoPEBackwardNode : public NodeCRTP<RoPEBackwardNode> {
+ public:
+ RoPE_backward_attributes attributes;
+
+ RoPEBackwardNode(RoPE_backward_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::ROPE_BWD;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferencing properties for RoPE backward node " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ auto DY = attributes.inputs[RoPE_backward_attributes::input_names::DY];
+ auto DX = attributes.outputs[RoPE_backward_attributes::output_names::DX];
+
+ if (DX->get_dim().empty()) {
+ DX->set_dim(DY->get_dim());
+ }
+ if (DX->get_stride().empty()) {
+ DX->set_stride(DY->get_stride());
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating RoPEBackwardNode " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.inputs.find(RoPE_backward_attributes::input_names::DY) == attributes.inputs.end(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "RoPE backward node requires DY (input gradient) tensor.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.inputs.find(RoPE_backward_attributes::input_names::FREQS) == attributes.inputs.end(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "RoPE backward node requires FREQS tensor.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building RoPEBackwardNode operations " << attributes.name << " ");
+
+#if (CUDNN_VERSION >= 92400)
+ // Compile- and run-time checks: RoPE bwd op was added in cuDNN 9.24.
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::get_backend_version() < 92400,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION_ROPE_BWD_DESCRIPTOR is only available starting cuDNN 9.24.");
+
+ auto rope_bwd_operation =
+ make_shared_backend_pointer((cudnnBackendDescriptorType_t)CUDNN_BACKEND_OPERATION_ROPE_BWD_DESCRIPTOR);
+
+ // Set DY (input gradient)
+ auto DY = attributes.inputs.find(RoPE_backward_attributes::input_names::DY)->second;
+ auto backend_dy = tensors[DY->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_BWD_DYDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_dy));
+
+ // Set freqs
+ auto FREQS = attributes.inputs.find(RoPE_backward_attributes::input_names::FREQS)->second;
+ auto backend_freqs = tensors[FREQS->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_BWD_FREQSDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_freqs));
+
+ // Set DX (output gradient)
+ auto DX = attributes.outputs.find(RoPE_backward_attributes::output_names::DX)->second;
+ auto backend_dx = tensors[DX->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_BWD_DXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_dx));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_BWD_OUTPUT_SCALE,
+ CUDNN_TYPE_FLOAT,
+ 1,
+ &attributes.output_scale));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(rope_bwd_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_ROPE_BWD_ROPE_DIM,
+ CUDNN_TYPE_INT64,
+ 1,
+ &attributes.rope_dim));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(rope_bwd_operation->get_backend_descriptor()));
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+
+ raw_operations.push_back(rope_bwd_operation);
+
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION_ROPE_BWD_DESCRIPTOR is only available starting cuDNN 9.24."};
+#endif
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"({"tag": "ROPE_BWD"})"_json);
+ }
+#endif
+};
+
+} // namespace graph
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/scaled_dot_product_flash_attention.h b/deps/cudnn-frontend/include/cudnn_frontend/node/scaled_dot_product_flash_attention.h
new file mode 100644
index 0000000..c3c37c5
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/scaled_dot_product_flash_attention.h
@@ -0,0 +1,2730 @@
+
+#pragma once
+
+#include <cstdlib>
+#include <unordered_set>
+
+#include "../../cudnn_frontend_Heuristics.h"
+#include "../../cudnn_frontend_Logging.h"
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+#include "diagonal_band_mask.h"
+#include "matmul.h"
+#include "pointwise.h"
+#include "reduction.h"
+#include "rng.h"
+#include "softmax.h"
+#include "paged_cache_load.h"
+#include "block_scale_dequantize.h"
+#include "sdpa_support_surface.h"
+
+namespace cudnn_frontend::graph {
+
+// If a 1-D length/offset index tensor [n] is supplied, promote it to the 4-D
+// [n, 1, 1, 1] form that the cuDNN backend requires for seq_len / cu_seq_len and
+// ragged-offset tensors. No-op if the tensor is unset or is not 1-D.
+inline void
+promote_1d_index_tensor_to_4d(std::shared_ptr<Tensor_attributes> const& tensor) {
+ if (tensor == nullptr) {
+ return;
+ }
+ auto const& dim = tensor->get_dim();
+ auto const& stride = tensor->get_stride();
+ if (dim.size() == 1) {
+ int64_t const n = dim[0];
+ int64_t const leading_stride = (stride.size() == 1) ? stride[0] : 1;
+ tensor->set_dim({n, 1, 1, 1}).set_stride({leading_stride, 1, 1, 1});
+ }
+}
+
+namespace attn::score_modifiers {
+
+// clang-format off
+inline float get_negative_inf_value();
+
+inline std::shared_ptr<Tensor_attributes> causal_mask(
+ std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score
+);
+
+inline std::shared_ptr<Tensor_attributes> bias(
+ std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ std::shared_ptr<Tensor_attributes> bias_tensor
+);
+
+inline std::shared_ptr<Tensor_attributes> causal_mask_bottom_right(
+ std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ std::shared_ptr<Tensor_attributes> seq_len_q,
+ std::shared_ptr<Tensor_attributes> seq_len_kv
+);
+
+inline std::shared_ptr<Tensor_attributes> padding_mask(
+ std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ std::shared_ptr<Tensor_attributes> seq_len_kv,
+ std::shared_ptr<Tensor_attributes> seq_len_q
+);
+
+inline std::shared_ptr<Tensor_attributes> sliding_window_mask(
+ std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ DiagonalAlignment_t diagonal_alignment,
+ std::optional<int64_t> left_window,
+ std::optional<int64_t> right_window,
+ int64_t s_q,
+ int64_t s_kv,
+ std::shared_ptr<Tensor_attributes> s_q_ptr,
+ std::shared_ptr<Tensor_attributes> s_kv_ptr,
+ std::shared_ptr<Tensor_attributes> cu_s_q_ptr = nullptr,
+ std::shared_ptr<Tensor_attributes> cu_s_kv_ptr = nullptr
+);
+
+inline std::shared_ptr<Tensor_attributes> alibi_mask(
+ std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ std::shared_ptr<Tensor_attributes>& alibi_slopes,
+ int64_t h_q,
+ int64_t& alibi_slopes_size
+);
+
+inline error_t build_operation_subgraph(std::shared_ptr<Graph> graph);
+// clang-format on
+
+} // namespace attn::score_modifiers
+
+template <typename DerivedT>
+class SDPANodeBase : public NodeCRTP<DerivedT> {
+ protected:
+ using input_names = SDPA_attributes::input_names;
+ using output_names = SDPA_attributes::output_names;
+
+ std::shared_ptr<Tensor_attributes> rng_output;
+ std::shared_ptr<Tensor_attributes> alibi_slopes;
+ int64_t alibi_slopes_size = 0;
+
+ // Promote any 1-D seq_len / cu_seq_len / ragged-offset index tensors to the 4-D
+ // [n, 1, 1, 1] form the cuDNN backend requires (see promote_1d_index_tensor_to_4d).
+ void
+ promote_index_tensors_to_4d() {
+ for (auto& key :
+ {input_names::SEQ_LEN_Q, input_names::SEQ_LEN_KV, input_names::CU_SEQ_LEN_Q, input_names::CU_SEQ_LEN_KV}) {
+ auto const it = attributes.inputs.find(key);
+ if (it != attributes.inputs.end()) {
+ promote_1d_index_tensor_to_4d(it->second);
+ }
+ }
+ for (auto& [key, value] : attributes.inputs) {
+ CUDNN_FRONTEND_UNUSED(key);
+ if (value != nullptr) {
+ promote_1d_index_tensor_to_4d(value->get_ragged_offset());
+ }
+ }
+ for (auto& [key, value] : attributes.outputs) {
+ CUDNN_FRONTEND_UNUSED(key);
+ if (value != nullptr) {
+ promote_1d_index_tensor_to_4d(value->get_ragged_offset());
+ }
+ }
+ }
+
+ public:
+ SDPA_attributes attributes;
+
+ SDPANodeBase(SDPA_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP<DerivedT>(context), attributes(std::move(attributes_)) {}
+
+ bool
+ is_paged_v() const {
+ auto page_table_v_it = attributes.inputs.find(input_names::Page_table_V);
+ return ((page_table_v_it) != attributes.inputs.end() && page_table_v_it->second != nullptr);
+ }
+
+ bool
+ is_paged_k() const {
+ auto page_table_k_it = attributes.inputs.find(input_names::Page_table_K);
+ return ((page_table_k_it) != attributes.inputs.end() && page_table_k_it->second != nullptr);
+ }
+
+ bool
+ has_seq_len_q() const {
+ auto seq_len_Q_it = attributes.inputs.find(SDPA_attributes::input_names::SEQ_LEN_Q);
+ return ((seq_len_Q_it) != attributes.inputs.end() && seq_len_Q_it->second != nullptr);
+ }
+
+ bool
+ has_seq_len_kv() const {
+ auto seq_len_KV_it = attributes.inputs.find(SDPA_attributes::input_names::SEQ_LEN_KV);
+ return ((seq_len_KV_it) != attributes.inputs.end() && seq_len_KV_it->second != nullptr);
+ }
+
+ bool
+ has_cu_seq_len_q() const {
+ auto cu_seq_len_Q_it = attributes.inputs.find(SDPA_attributes::input_names::CU_SEQ_LEN_Q);
+ return ((cu_seq_len_Q_it) != attributes.inputs.end() && cu_seq_len_Q_it->second != nullptr);
+ }
+
+ bool
+ has_cu_seq_len_kv() const {
+ auto cu_seq_len_KV_it = attributes.inputs.find(SDPA_attributes::input_names::CU_SEQ_LEN_KV);
+ return ((cu_seq_len_KV_it) != attributes.inputs.end() && cu_seq_len_KV_it->second != nullptr);
+ }
+
+ // Helper function to detect MXFP8 (microscaling FP8) mode
+ // MXFP8 uses block-wise scale factors with E8M0 data type and F8_128x4 reordering
+ // When detected, we use block_scale_dequantize before matmuls instead of pointwise descale after
+ bool
+ is_mxfp8_scaling() const {
+ auto descale_q_it = attributes.inputs.find(input_names::Descale_Q);
+ if (descale_q_it == attributes.inputs.end() || descale_q_it->second == nullptr) {
+ return false;
+ }
+ auto const& descale_q = descale_q_it->second;
+ return (descale_q->get_data_type() == DataType_t::FP8_E8M0 &&
+ descale_q->get_reordering_type() == TensorReordering_t::F8_128x4);
+ }
+
+ // Helper function to infer KV sequence length
+ // Note that it cannot be run as part of infer_properties_node as
+ // this is being used in pre_validate_node
+ int64_t
+ infer_s_kv() const {
+ int64_t s_kv = -1;
+
+ auto get_input_dim = [this](const SDPA_attributes::input_names& input_name) {
+ auto const input_it = attributes.inputs.find(input_name);
+ if (input_it != attributes.inputs.end()) {
+ return input_it->second->get_dim();
+ } else {
+ return std::vector<int64_t>({-1, -1, -1, -1});
+ }
+ };
+
+ auto const& k_dim = get_input_dim(input_names::K);
+ auto const& v_dim = get_input_dim(input_names::V);
+
+ // If s_kv was set explicitly, use that
+ if (attributes.max_seq_len_kv.has_value()) {
+ s_kv = attributes.max_seq_len_kv.value();
+ }
+ // When one of K or V cache are paged, s_kv can be extracted directly
+ else if (!is_paged_k()) {
+ s_kv = k_dim[2];
+
+ } else if (!is_paged_v()) {
+ s_kv = v_dim[2];
+ } else {
+ CUDNN_FE_LOG_LABEL_ENDL(
+ "WARNING: maximum kv sequence length is being inferred. To set it explicitly, please use "
+ "\"set_paged_attention_max_seq_len_kv\"");
+
+ auto bias_it = attributes.inputs.find(input_names::Bias);
+ auto rng_it = attributes.outputs.find(output_names::RNG_DUMP);
+
+ // If there is a bias, extract it from there
+ if (bias_it != attributes.inputs.end() && bias_it->second != nullptr) {
+ s_kv = get_input_dim(input_names::Bias)[3];
+ // If there is an rng_dump output, extract it from there
+ } else if (rng_it != attributes.outputs.end() && rng_it->second != nullptr) {
+ s_kv = rng_it->second->get_dim()[3];
+ // When both caches are paged, and the above failed, we need to infer s_kv from the page table and
+ // container
+ } else {
+ // [b, 1, ceil(s_kv/block_size), 1]
+ auto page_table_dim_k = get_input_dim(input_names::Page_table_K);
+ // [b, h_k, block_size, d_k]
+ auto const container_dim_k = get_input_dim(input_names::K);
+ int64_t s_k = page_table_dim_k[2] * container_dim_k[2];
+
+ // [b, 1, ceil(s_kv/block_size), 1]
+ auto page_table_dim_v = get_input_dim(input_names::Page_table_V);
+ // [b, h_v, block_size, d_v]
+ auto const container_dim_v = get_input_dim(input_names::V);
+ int64_t s_v = page_table_dim_v[2] * container_dim_v[2];
+
+ s_kv = std::min(s_k, s_v);
+ }
+ }
+
+ return s_kv;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating SDPANode " << attributes.name);
+
+ // check that Q, K, V, O tensors has been assigned
+ // check that dim and strides has been assigned and last stride is 1
+#define CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(port, port_map) \
+ { \
+ std::shared_ptr<Tensor_attributes> tensor_ptr = port_map.at(port); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF(tensor_ptr->get_dim().size() != 4, \
+ error_code_t::ATTRIBUTE_NOT_SET, \
+ "The dim for " + std::string(#port) + " is invalid"); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF(tensor_ptr->get_stride().size() != 4, \
+ error_code_t::ATTRIBUTE_NOT_SET, \
+ "The stride for " + std::string(#port) + " is invalid"); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF( \
+ tensor_ptr->get_stride()[3] != 1, \
+ error_code_t::GRAPH_NOT_SUPPORTED, \
+ "The stride for the last dimension corresponding to the embedding size per head should be 1 for " + \
+ std::string(#port)); \
+ }
+
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::Q, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::K, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::V, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(output_names::O, attributes.outputs);
+
+ if (attributes.generate_stats.value_or(false) == true) {
+ CUDNN_FE_VALIDATE_OUTPUT_TENSOR(output_names::Stats);
+ }
+
+ // If max is requested, validate that the output tensor is present
+ if (attributes.outputs.find(output_names::Max) != attributes.outputs.end() &&
+ attributes.outputs.at(output_names::Max) != nullptr) {
+ CUDNN_FE_VALIDATE_OUTPUT_TENSOR(output_names::Max);
+ }
+
+ // If sum_exp is requested, validate that the output tensor is present
+ if (attributes.outputs.find(output_names::Sum_exp) != attributes.outputs.end() &&
+ attributes.outputs.at(output_names::Sum_exp) != nullptr) {
+ CUDNN_FE_VALIDATE_OUTPUT_TENSOR(output_names::Sum_exp);
+ }
+
+#undef CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE
+
+ // validate backend limitations for the operation
+ auto validation_result =
+ attributes.validate_sdpa_support_surface(this->context, infer_s_kv(), is_paged_k(), is_paged_v());
+ if (validation_result.is_good() == false) {
+ return validation_result;
+ }
+
+ // return NOT_SET if sink_token present with 9.12 and below
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 91300 &&
+ attributes.inputs.find(input_names::SINK_TOKEN) != attributes.inputs.end(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "SDPA with sink_token is not supported before 9.13.");
+
+ // Validate MXFP8 scale factors if present
+ if (is_mxfp8_scaling()) {
+ // MXFP8 requires cuDNN 9.21.0 or later
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 92100,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "MXFP8 SDPA requires cuDNN 9.21.0 or later");
+
+ // Get device SM version from context
+ CHECK_CUDNN_FRONTEND_ERROR(this->context.populate_sm_version_from_device());
+ int32_t const sm_version = this->context.get_sm_version();
+ int32_t const prop_major = sm_version / 10;
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(10 != prop_major,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "MXFP8 SDPA is only supported on Blackwell Data Center architectures.");
+
+ auto const& q_dim = attributes.inputs.at(input_names::Q)->get_dim();
+ auto const& k_dim = attributes.inputs.at(input_names::K)->get_dim();
+ auto const& v_dim = attributes.inputs.at(input_names::V)->get_dim();
+ int64_t const b = q_dim[0];
+ int64_t const h_q = q_dim[1];
+ int64_t const s_q = q_dim[2];
+ int64_t const d = q_dim[3];
+ int64_t const h_k = k_dim[1];
+ int64_t const h_v = v_dim[1];
+ int64_t const s_kv = infer_s_kv();
+
+ // MXFP8 block size is fixed at 32
+ constexpr int64_t block_size = 32;
+ int64_t const d_scale = (d + block_size - 1) / block_size;
+ int64_t const s_scale = (s_kv + block_size - 1) / block_size;
+
+ // Validate Descale_Q
+ auto const& descale_q = attributes.inputs.at(input_names::Descale_Q);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_q->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_Q to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_q->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_Q to have F8_128x4 reordering");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ descale_q->get_stride()[3] != 1,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "MXFP8 SDPA requires Descale_Q to have contiguous d_scale dimension (stride[3] == 1)");
+
+ // Validate Descale_K
+ auto const& descale_k = attributes.inputs.at(input_names::Descale_K);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_k->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_K to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_k->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_K to have F8_128x4 reordering");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ descale_k->get_stride()[3] != 1,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "MXFP8 SDPA requires Descale_K to have contiguous d_scale dimension (stride[3] == 1)");
+
+ // Validate Descale_V
+ auto const& descale_v = attributes.inputs.at(input_names::Descale_V);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_v->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_V to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_v->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_V to have F8_128x4 reordering");
+ // // SF_V scales along s dimension (not d), so s_scale must be contiguous
+ // RETURN_CUDNN_FRONTEND_ERROR_IF(
+ // descale_v->get_stride()[2] != 1,
+ // error_code_t::GRAPH_NOT_SUPPORTED,
+ // "MXFP8 SDPA requires Descale_V to have contiguous s_scale dimension (stride[2] == 1)");
+
+ // Validate dimension consistency for SF_Q: [b, h_q, s_q_padded, d_scale_padded]
+ auto const& sf_q_dim = descale_q->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_q_dim[0] != b || sf_q_dim[1] != h_q,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_Q batch/head dimensions must match Q");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_q_dim[3] < d_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_Q d_scale dimension too small (expected >= " + std::to_string(d_scale) + ")");
+
+ // Validate dimension consistency for SF_K: [b, h_k, s_kv_padded, d_scale_padded]
+ auto const& sf_k_dim = descale_k->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_k_dim[0] != b || sf_k_dim[1] != h_k,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_K batch/head dimensions must match K");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_k_dim[3] < d_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_K d_scale dimension too small (expected >= " + std::to_string(d_scale) + ")");
+
+ // Validate dimension consistency for SF_V: [b, h_v, s_scale_padded, d_padded]
+ auto const& sf_v_dim = descale_v->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_v_dim[0] != b || sf_v_dim[1] != h_v,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_V batch/head dimensions must match V");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_v_dim[2] < s_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_V s_scale dimension too small (expected >= " + std::to_string(s_scale) + ")");
+
+ // Log MXFP8 configuration for debugging
+ getLogger() << "[cudnn_frontend] INFO: MXFP8 SDPA configuration validated:" << std::endl
+ << " Q dims: [" << b << ", " << h_q << ", " << s_q << ", " << d << "]" << std::endl
+ << " SF_Q dims: [" << sf_q_dim[0] << ", " << sf_q_dim[1] << ", " << sf_q_dim[2] << ", "
+ << sf_q_dim[3] << "]" << std::endl
+ << " SF_K dims: [" << sf_k_dim[0] << ", " << sf_k_dim[1] << ", " << sf_k_dim[2] << ", "
+ << sf_k_dim[3] << "]" << std::endl
+ << " SF_V dims: [" << sf_v_dim[0] << ", " << sf_v_dim[1] << ", " << sf_v_dim[2] << ", "
+ << sf_v_dim[3] << "]" << std::endl
+ << " Expected d_scale: " << d_scale << ", s_scale: " << s_scale << std::endl;
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ // If a 1-D length/offset index tensor [n] is supplied, promote it to the 4-D
+ // [n, 1, 1, 1] (contiguous) form the cuDNN backend requires.
+ promote_index_tensors_to_4d();
+
+ if (attributes.generate_stats.value_or(false)) {
+ auto stats = attributes.outputs.at(output_names::Stats);
+ auto stats_dim = stats->get_dim();
+
+ if (stats_dim.empty()) {
+ // Fill properties of virtual tensors
+ auto const& p_dim = attributes.inputs[input_names::Q]->get_dim();
+ auto b = p_dim[0];
+ auto h = p_dim[1];
+ auto s_q = p_dim[2];
+ stats->set_dim({b, h, s_q, 1}).set_stride({h * s_q, s_q, 1, 1});
+ }
+ }
+
+ if (attributes.outputs[output_names::Max] != nullptr) {
+ auto max = attributes.outputs.at(output_names::Max);
+
+ if (max->get_dim().empty()) {
+ // Fill properties of virtual tensors
+ auto const& p_dim = attributes.inputs[input_names::Q]->get_dim();
+ auto b = p_dim[0];
+ auto h = p_dim[1];
+ auto s_q = p_dim[2];
+ max->set_dim({b, h, s_q, 1}).set_stride({h * s_q, s_q, 1, 1});
+ }
+ }
+
+ if (attributes.outputs[output_names::Sum_exp] != nullptr) {
+ auto sum_exp = attributes.outputs.at(output_names::Sum_exp);
+
+ if (sum_exp->get_dim().empty()) {
+ // Fill properties of virtual tensors
+ auto const& p_dim = attributes.inputs[input_names::Q]->get_dim();
+ auto b = p_dim[0];
+ auto h = p_dim[1];
+ auto s_q = p_dim[2];
+ sum_exp->set_dim({b, h, s_q, 1}).set_stride({h * s_q, s_q, 1, 1});
+ }
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ post_validate_node() const override final {
+#define CUDNN_FE_VALIDATE_STRIDE(port, port_map) \
+ { \
+ auto const& t = port_map.find(port); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF( \
+ t->second->get_stride().back() != 1, \
+ error_code_t::GRAPH_NOT_SUPPORTED, \
+ "The stride for the last dimension corresponding to the embedding size per head should be 1 for " + \
+ std::string(#port)); \
+ }
+
+ CUDNN_FE_VALIDATE_STRIDE(output_names::O, attributes.outputs);
+
+#undef CUDNN_FE_VALIDATE_STRIDE
+
+ return {error_code_t::OK, ""};
+ }
+
+ virtual int64_t
+ get_fe_workspace_size_node() const override final {
+ int64_t size = 0;
+
+ // align alibi slopes memory to 16 bytes
+ size += ((alibi_slopes_size + 15) / 16 * 16);
+
+ return size;
+ }
+
+ virtual error_t
+ collect_tensors_in_workspace_node(
+ std::unordered_map<Tensor_attributes::uid_t, std::tuple<int64_t, int64_t, std::vector<float>>>&
+ workspace_modifications,
+ int64_t& offset) const override final {
+ if (attributes.alibi_mask) {
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(Q, input_names::Q);
+ int64_t const h_q = Q->second->get_dim()[1];
+ auto alibi_slopes_vec = detail::get_alibi_slope(h_q);
+ workspace_modifications.emplace(alibi_slopes->get_uid(), std::make_tuple(0, offset, alibi_slopes_vec));
+ int64_t alibi_slopes_size_padded = ((alibi_slopes_size + 15) / 16 * 16);
+ offset = offset + alibi_slopes_size_padded;
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ collect_tensors_to_dump_node(
+ std::vector<std::pair<std::shared_ptr<Tensor_attributes>, char>>& tensors_to_dump) const override final {
+ std::unordered_set<Tensor_attributes::uid_t> seen_uids;
+ auto add_tensor = [&tensors_to_dump, &seen_uids](std::shared_ptr<Tensor_attributes> const& tensor) {
+ if (tensor == nullptr) {
+ return;
+ }
+ if (seen_uids.insert(tensor->get_uid()).second) {
+ tensors_to_dump.emplace_back(tensor, 'd');
+ }
+ };
+
+ auto const seq_len_q_it = attributes.inputs.find(input_names::SEQ_LEN_Q);
+ if (seq_len_q_it != attributes.inputs.end()) {
+ add_tensor(seq_len_q_it->second);
+ }
+
+ auto const seq_len_kv_it = attributes.inputs.find(input_names::SEQ_LEN_KV);
+ if (seq_len_kv_it != attributes.inputs.end()) {
+ add_tensor(seq_len_kv_it->second);
+ }
+
+ auto const cu_seq_len_q_it = attributes.inputs.find(input_names::CU_SEQ_LEN_Q);
+ if (cu_seq_len_q_it != attributes.inputs.end()) {
+ add_tensor(cu_seq_len_q_it->second);
+ }
+
+ auto const cu_seq_len_kv_it = attributes.inputs.find(input_names::CU_SEQ_LEN_KV);
+ if (cu_seq_len_kv_it != attributes.inputs.end()) {
+ add_tensor(cu_seq_len_kv_it->second);
+ }
+
+ for (auto const& tensor : {attributes.inputs.at(input_names::Q),
+ attributes.inputs.at(input_names::K),
+ attributes.inputs.at(input_names::V),
+ attributes.outputs.at(output_names::O)}) {
+ if (tensor != nullptr) {
+ add_tensor(tensor->get_ragged_offset());
+ }
+ }
+
+ auto const stats_it = attributes.outputs.find(output_names::Stats);
+ if (stats_it != attributes.outputs.end() && stats_it->second != nullptr) {
+ add_tensor(stats_it->second->get_ragged_offset());
+ }
+
+ auto const max_it = attributes.outputs.find(output_names::Max);
+ if (max_it != attributes.outputs.end() && max_it->second != nullptr) {
+ add_tensor(max_it->second->get_ragged_offset());
+ }
+
+ auto const sum_exp_it = attributes.outputs.find(output_names::Sum_exp);
+ if (sum_exp_it != attributes.outputs.end() && sum_exp_it->second != nullptr) {
+ add_tensor(sum_exp_it->second->get_ragged_offset());
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j["is_mxfp8"] = is_mxfp8_scaling();
+ j["unfuse_fma"] = attributes.unfuse_fma;
+ if (auto const rescale_threshold = get_rescale_threshold_from_env(); rescale_threshold.has_value()) {
+ j["rescale_threshold"] = rescale_threshold.value();
+ }
+ if (is_mxfp8_scaling()) {
+ j.update(R"({"tag": "SDPA_MXFP8_FWD"})"_json);
+ } else if (attributes.mma_core_mode == DataType_t::FP8_E4M3 ||
+ attributes.mma_core_mode == DataType_t::FP8_E5M2) {
+ j.update(R"({"tag": "SDPA_FP8_FWD"})"_json);
+ } else {
+ j.update(R"({"tag": "SDPA"})"_json);
+ }
+ }
+#endif
+};
+
+class CompositeSDPANode : public SDPANodeBase<CompositeSDPANode> {
+ public:
+ CompositeSDPANode(SDPA_attributes&& attributes_, detail::Context const& context)
+ : SDPANodeBase(std::move(attributes_), context) {}
+
+ Type
+ getType() override final {
+ return Type::COMPOSITE;
+ }
+
+ error_t
+ expand_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for CompositeSDPANode node " << attributes.name);
+
+ // DO NOT REMOVE
+ // input data type is needed for:
+ // - aType of bmm2
+ // - dropout scale in pre 8.9.3
+ attributes.fill_from_context(this->context);
+
+ // Gather dim to fill properties of virtual tensors
+ auto const& q_dim = attributes.inputs[input_names::Q]->get_dim();
+ auto b = q_dim[0];
+ auto h_q = q_dim[1];
+ auto s_q = q_dim[2];
+ auto d_qk = q_dim[3];
+ auto const& k_dim = attributes.inputs[input_names::K]->get_dim();
+ auto h_k = k_dim[1];
+ auto const& v_dim = attributes.inputs[input_names::V]->get_dim();
+ auto h_v = v_dim[1];
+ auto d_v = v_dim[3];
+ // Infer s_kv
+ int64_t s_kv = infer_s_kv();
+
+ // Check if using MXFP8 (microscaling FP8) with block-wise scale factors
+ // Need to check this early because MXFP8 dequantization must happen before K transpose
+ bool const use_mxfp8 = is_mxfp8_scaling();
+
+ std::shared_ptr<Tensor_attributes> k_cache;
+ if (!is_paged_k()) {
+ if (use_mxfp8) {
+ // MXFP8: Transpose K and SF_K first, then dequantize
+ // The backend expects both K and its scale factor in transposed layout
+
+ // Step 1: Transpose K -> KT by swapping dims and strides
+ // K = {b, h_k, s_kv, d_qk} -> KT = {b, h_k, d_qk, s_kv}
+ std::vector<int64_t> kt_dim = attributes.inputs[input_names::K]->get_dim();
+ std::vector<int64_t> kt_stride = attributes.inputs[input_names::K]->get_stride();
+ std::swap(kt_dim[2], kt_dim[3]);
+ std::swap(kt_stride[2], kt_stride[3]);
+ attributes.inputs[input_names::K]->set_dim(kt_dim);
+ attributes.inputs[input_names::K]->set_stride(kt_stride);
+
+ // Step 2: Transpose SF_K similarly
+ // SF_K = {b, h_k, s_kv_scale, d_qk_scale} -> {b, h_k, d_qk_scale, s_kv_scale}
+ auto& sf_k = attributes.inputs[input_names::Descale_K];
+ std::vector<int64_t> sf_k_dim = sf_k->get_dim();
+ std::vector<int64_t> sf_k_stride = sf_k->get_stride();
+ std::swap(sf_k_dim[2], sf_k_dim[3]);
+ std::swap(sf_k_stride[2], sf_k_stride[3]);
+ sf_k->set_dim(sf_k_dim);
+ sf_k->set_stride(sf_k_stride);
+
+ // Step 3: Dequantize transposed K with transposed SF_K
+ auto dequant_k_attrs = Block_scale_dequantize_attributes()
+ .set_name("dequant_k")
+ .set_block_size({1, 32}); // Standard MXFP8 block size
+
+ auto k_dequant = std::make_shared<Tensor_attributes>();
+ k_dequant->set_is_virtual(true);
+ k_dequant->set_dim(kt_dim);
+ k_dequant->set_stride(kt_stride);
+
+ block_scale_dequantize(attributes.inputs[input_names::K], sf_k, dequant_k_attrs, k_dequant);
+
+ k_cache = k_dequant;
+ } else {
+ // Non-MXFP8: map K->KT directly
+ // cuDNN frontend API attention requires Q, K, V where
+ // Q = {b, h_q, s_q, d_qk}
+ // K = {b, h_k, s_kv, d_qk}
+ // V = {b, h_v, s_kv, d_v}
+ // but cuDNN backend API attention requires Q, KT, V
+ // Q = {b, h_q, s_q, d_qk}
+ // KT = {b, h_k, d_qk, s_kv}
+ // V = {b, h_v, s_kv, d_v}
+ // So the code below maps the K->KT
+ std::vector<int64_t> temp_vec;
+
+ temp_vec = attributes.inputs[input_names::K]->get_dim();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::K]->set_dim(temp_vec);
+
+ temp_vec = attributes.inputs[input_names::K]->get_stride();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::K]->set_stride(temp_vec);
+
+ k_cache = attributes.inputs[input_names::K];
+ }
+ } else {
+ // Create a paged cache load operation
+ auto paged_cache_load_attributes_k = PagedCacheLoad_attributes().set_name("paged_k_cache_operation");
+ // Need to create virtual tensor descriptor for yOut here as it cannot be inferred
+ // K-cache has BHDS layout
+ k_cache = std::make_shared<Tensor_attributes>();
+ k_cache->set_is_virtual(true);
+ k_cache->set_dim({b, h_k, d_qk, s_kv});
+ k_cache->set_stride({d_qk * s_kv * h_k, d_qk * s_kv, 1, d_qk});
+ k_cache->set_data_type(attributes.inputs[input_names::K]->get_data_type());
+ paged_cache_load(attributes.inputs[input_names::K],
+ attributes.inputs[input_names::SEQ_LEN_KV],
+ attributes.inputs[input_names::Page_table_K],
+ paged_cache_load_attributes_k,
+ k_cache);
+ }
+
+ // This tensor tracks the main chain of data flow
+ std::shared_ptr<Tensor_attributes> last_output;
+
+ // Prepare Q and K for first matmul
+ // For MXFP8: Q is dequantized here, K was dequantized above before transpose
+ // For regular FP8: use raw tensors, descale applied after matmul
+ std::shared_ptr<Tensor_attributes> q_for_bmm1;
+ std::shared_ptr<Tensor_attributes> k_for_bmm1;
+
+ if (use_mxfp8) {
+ // MXFP8: Dequantize Q using block scale factors
+ auto dequant_q_attrs = Block_scale_dequantize_attributes()
+ .set_name("dequant_q")
+ .set_block_size({1, 32}); // Standard MXFP8 block size
+ auto q_dequant = std::make_shared<Tensor_attributes>();
+ q_dequant->set_is_virtual(true);
+ q_dequant->set_dim(attributes.inputs[input_names::Q]->get_dim());
+ q_dequant->set_stride(attributes.inputs[input_names::Q]->get_stride());
+ block_scale_dequantize(attributes.inputs[input_names::Q],
+ attributes.inputs[input_names::Descale_Q],
+ dequant_q_attrs,
+ q_dequant);
+ q_for_bmm1 = q_dequant;
+
+ // K was already dequantized and transposed above
+ k_for_bmm1 = k_cache;
+ } else {
+ q_for_bmm1 = attributes.inputs[input_names::Q];
+ k_for_bmm1 = k_cache;
+ }
+
+ //// Q * K
+ auto bmm1_attributes = Matmul_attributes()
+ .set_name("bmm1")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_Q])
+ .set_n_override(attributes.inputs[input_names::SEQ_LEN_KV]);
+
+ if (attributes.padding_mask) {
+ bmm1_attributes.set_padding(0.0);
+ }
+
+ auto const& bmm1_output = matmul(q_for_bmm1, k_for_bmm1, bmm1_attributes);
+ // Setting dim and strides as pointwise op wont have knowledge of how to do it for mha.
+ bmm1_output->set_dim({b, h_q, s_q, s_kv}).set_stride({h_q * s_q * s_kv, s_q * s_kv, s_kv, 1});
+ last_output = bmm1_output;
+
+ //// Optional Attn scale
+ // In case user provided a scalar value, do a fused scalar.
+ if (attributes.attn_scale_value.has_value()) {
+ attributes.inputs[input_names::Attn_scale] =
+ std::make_shared<Tensor_attributes>(attributes.attn_scale_value.value());
+ }
+
+ // If attn scale present, add a pointwise mul node
+ if (attributes.inputs[input_names::Attn_scale]) {
+ Pointwise_attributes scale_attributes;
+ scale_attributes.set_name("attn_scale").set_mode(PointwiseMode_t::MUL);
+ auto const& attn_scale_output =
+ pointwise(last_output, attributes.inputs[input_names::Attn_scale], scale_attributes);
+ last_output = attn_scale_output;
+ }
+
+ // Descale Q (only for non-MXFP8 per-tensor scaling)
+ // For MXFP8, descaling was done via block_scale_dequantize before matmul
+ if (!use_mxfp8 && attributes.inputs.find(input_names::Descale_Q) != attributes.inputs.end() &&
+ attributes.inputs.at(input_names::Descale_Q) != nullptr) {
+ auto descale_q_attributes = Pointwise_attributes().set_mode(PointwiseMode_t::MUL).set_name("descale_q");
+ last_output = pointwise(last_output, attributes.inputs.at(input_names::Descale_Q), descale_q_attributes);
+ }
+
+ // Descale K (only for non-MXFP8 per-tensor scaling)
+ // For MXFP8, descaling was done via block_scale_dequantize before matmul
+ if (!use_mxfp8 && attributes.inputs.find(input_names::Descale_K) != attributes.inputs.end() &&
+ attributes.inputs.at(input_names::Descale_K) != nullptr) {
+ auto descale_k_attributes = Pointwise_attributes().set_mode(PointwiseMode_t::MUL).set_name("descale_k");
+ last_output = pointwise(last_output, attributes.inputs.at(input_names::Descale_K), descale_k_attributes);
+ }
+
+ if (attributes.attention_score_modifier != nullptr) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = this->context;
+ last_output = attributes.attention_score_modifier(graph_, last_output);
+ sub_nodes.emplace_back(node_);
+ }
+
+ // Optional bias
+ if (attributes.inputs.find(input_names::Bias) != attributes.inputs.end() &&
+ attributes.inputs[input_names::Bias]) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = this->context;
+ last_output = attn::score_modifiers::bias(graph_, last_output, attributes.inputs[input_names::Bias]);
+ sub_nodes.emplace_back(node_);
+ }
+
+ if (attributes.alibi_mask) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = this->context;
+ last_output = attn::score_modifiers::alibi_mask(graph_, last_output, alibi_slopes, h_q, alibi_slopes_size);
+ sub_nodes.emplace_back(node_);
+ }
+
+ // There are two cases of applying padding mask
+ // 1. when actual seq_len is less than or equal to max_seq_len
+ if (attributes.padding_mask) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = this->context;
+ last_output = attn::score_modifiers::padding_mask(graph_,
+ last_output,
+ attributes.inputs[input_names::SEQ_LEN_KV],
+ attributes.inputs[input_names::SEQ_LEN_Q]);
+ sub_nodes.emplace_back(node_);
+ }
+
+ // 2. (bug in cudnn backend) no padding with max_seq_len%64!=0
+ if ((s_kv % 64 != 0) && (!(attributes.padding_mask)) && (detail::get_backend_version() < 90000)) {
+ auto col_index_attributes =
+ Pointwise_attributes().set_name("gen_col_index").set_mode(PointwiseMode_t::GEN_INDEX).set_axis(3);
+ auto col_index_output = pointwise(last_output, col_index_attributes);
+ // scalar seq_kv only needs to be passed in case there in no padding mask and seq_kv is not multiple of 64.
+ // Also future versions of cudnn will not need it, hence tensor is pre-fixed.
+ auto scalar_max_seq_kv = std::make_shared<Tensor_attributes>(static_cast<int32_t>(s_kv));
+
+ auto col_less_seq_kv_attributes =
+ Pointwise_attributes().set_name("col_less_seq_kv").set_mode(PointwiseMode_t::CMP_LT);
+ auto col_less_seq_kv_output = pointwise(col_index_output, scalar_max_seq_kv, col_less_seq_kv_attributes);
+
+ // Lower attributes to binary select attributes
+ auto negative_inf_padding =
+ std::make_shared<Tensor_attributes>(attn::score_modifiers::get_negative_inf_value());
+ auto binary_select_attributes =
+ Pointwise_attributes().set_name("binary_select").set_mode(PointwiseMode_t::BINARY_SELECT);
+ auto padding_mask_output =
+ pointwise(last_output, negative_inf_padding, col_less_seq_kv_output, binary_select_attributes);
+ last_output = padding_mask_output;
+ }
+
+ // Apply (bottom-right) causal masking (with right bound) and/or set the left bound
+ if (attributes.left_bound.has_value() || attributes.right_bound.has_value()) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = this->context;
+
+ auto s_kv_ptr = attributes.inputs.find(input_names::SEQ_LEN_KV) != attributes.inputs.end()
+ ? attributes.inputs[input_names::SEQ_LEN_KV]
+ : nullptr;
+ auto s_q_ptr = attributes.inputs.find(input_names::SEQ_LEN_Q) != attributes.inputs.end()
+ ? attributes.inputs[input_names::SEQ_LEN_Q]
+ : nullptr;
+
+ last_output = attn::score_modifiers::sliding_window_mask(graph_,
+ last_output,
+ attributes.diagonal_alignment,
+ attributes.left_bound,
+ attributes.right_bound,
+ s_q,
+ s_kv,
+ s_q_ptr,
+ s_kv_ptr,
+ /*cu_s_q_ptr=*/nullptr,
+ /*cu_s_kv_ptr=*/nullptr);
+ sub_nodes.emplace_back(node_);
+ }
+
+ // Lower attributes to softmax attributes
+ auto softmax_output = std::make_shared<Tensor_attributes>();
+ softmax_output->set_is_virtual(true);
+
+ auto softmax_attributes = Softmax_attributes().set_name("softmax");
+ // Set sink for softmax if user has provided a sink tensor
+ if (attributes.inputs.find(input_names::SINK_TOKEN) != attributes.inputs.end()) {
+ softmax_attributes.set_sink(attributes.inputs[input_names::SINK_TOKEN]);
+ }
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ softmax(last_output,
+ softmax_attributes,
+ softmax_output,
+ attributes.outputs[output_names::Stats],
+ attributes.outputs[output_names::Max],
+ attributes.outputs[output_names::Sum_exp]);
+ last_output = softmax_output;
+
+ // Two cases for training: dropout present or not
+ bool dropout_present = false;
+ auto const& dropout_mask = attributes.inputs.find(input_names::Dropout_mask);
+ bool const is_dropout_custom = (dropout_mask != attributes.inputs.end()) && (dropout_mask->second != nullptr);
+ if (attributes.dropout_probability.has_value()) {
+ dropout_present = true;
+ // Special case: Skip dropout when 0.0 probability. Only do for 8.9.3 and up as rng isn't optional earlier.
+ if (detail::get_backend_version() > 8902 && attributes.dropout_probability.value() == 0.0) {
+ dropout_present = false;
+ }
+ } else if (is_dropout_custom) {
+ dropout_present = true;
+ }
+
+ if (dropout_present) {
+ if (is_dropout_custom) {
+ auto dropout_scale_attributes =
+ Pointwise_attributes().set_name("dropout_scale_mul").set_mode(PointwiseMode_t::MUL);
+ auto const& dropout_scale_output =
+ pointwise(last_output, attributes.inputs[input_names::Dropout_scale], dropout_scale_attributes);
+
+ auto mask_attributes =
+ Pointwise_attributes().set_name("dropout_mask_mul").set_mode(PointwiseMode_t::MUL);
+ auto const& dropout_mask_output =
+ pointwise(dropout_scale_output, dropout_mask->second, mask_attributes);
+ last_output = dropout_mask_output;
+ } else {
+ if (attributes.outputs[output_names::RNG_DUMP] != nullptr) {
+ rng_output = attributes.outputs[output_names::RNG_DUMP];
+ rng(attributes.inputs[input_names::Seed],
+ attributes.inputs[input_names::Offset],
+ Rng_attributes()
+ .set_name("rng")
+ .set_distribution(RngDistribution_t::BERNOULLI)
+ .set_bernoulli_probability(1.0 - attributes.dropout_probability.value()),
+ rng_output);
+ } else {
+ rng_output = rng(attributes.inputs[input_names::Seed],
+ attributes.inputs[input_names::Offset],
+ Rng_attributes()
+ .set_name("rng")
+ .set_distribution(RngDistribution_t::BERNOULLI)
+ .set_bernoulli_probability(1.0 - attributes.dropout_probability.value()));
+ rng_output
+ // Hard coding dim and strides as rng output can no inputs to infer it from.
+ ->set_dim({b, h_q, s_q, s_kv})
+ .set_stride({h_q * s_q * s_kv, s_q * s_kv, s_kv, 1});
+ }
+
+ auto mask_attributes =
+ Pointwise_attributes().set_name("dropout_mask_mul").set_mode(PointwiseMode_t::MUL);
+ auto const& dropout_mask_output = pointwise(last_output, rng_output, mask_attributes);
+ last_output = dropout_mask_output;
+
+ std::shared_ptr<cudnn_frontend::graph::Tensor_attributes> dropout_scale = nullptr;
+
+ if (detail::get_backend_version() < 8903) {
+ half dropout_scale_value = __float2half(1.0f / (1.0f - attributes.dropout_probability.value()));
+ dropout_scale = std::make_shared<Tensor_attributes>(dropout_scale_value);
+ } else {
+ float dropout_scale_value = (1.0f / (1.0f - attributes.dropout_probability.value()));
+ dropout_scale = std::make_shared<Tensor_attributes>(dropout_scale_value);
+ }
+
+ auto dropout_scale_attributes =
+ Pointwise_attributes().set_name("dropout_scale").set_mode(PointwiseMode_t::MUL);
+ auto const& dropout_scale_output = pointwise(last_output, dropout_scale, dropout_scale_attributes);
+ last_output = dropout_scale_output;
+ }
+ }
+
+ // Amax S
+ if (attributes.outputs.find(output_names::Amax_S) != attributes.outputs.end() &&
+ attributes.outputs.at(output_names::Amax_S) != nullptr) {
+ auto amax_attributes = Reduction_attributes().set_name("amax_s").set_mode(ReductionMode_t::AMAX);
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ reduction(last_output, amax_attributes, attributes.outputs.at(output_names::Amax_S));
+ }
+
+ // Scale S
+ if (attributes.inputs.find(input_names::Scale_S) != attributes.inputs.end() &&
+ attributes.inputs.at(input_names::Scale_S) != nullptr) {
+ auto scale_s_attributes = Pointwise_attributes().set_name("scale_s").set_mode(PointwiseMode_t::MUL);
+ last_output = pointwise(last_output, attributes.inputs.at(input_names::Scale_S), scale_s_attributes);
+ }
+
+ // Lower attributes to bmm2 attributes
+ // Requirement by cudnn backend to take in bmm2 aType as i/o type.
+ last_output->set_data_type(attributes.inputs[input_names::Q]->get_data_type());
+
+ auto const& seq_len_q = attributes.inputs[input_names::SEQ_LEN_Q];
+ auto const& seq_len_kv = attributes.inputs[input_names::SEQ_LEN_KV];
+ // auto const& V = attributes.inputs[input_names::V];
+ auto const& O = attributes.outputs[output_names::O];
+
+ std::shared_ptr<Tensor_attributes> v_cache;
+
+ if (!is_paged_v()) {
+ v_cache = attributes.inputs[input_names::V];
+ } else {
+ auto paged_cache_load_attributes_v = PagedCacheLoad_attributes().set_name("paged_v_cache_operation");
+ v_cache = std::make_shared<Tensor_attributes>();
+ v_cache->set_dim({b, h_v, s_kv, d_v})
+ .set_stride({d_v * s_kv * h_v, d_v * s_kv, d_v, 1})
+ .set_data_type(attributes.inputs[input_names::V]->get_data_type());
+ v_cache->set_is_virtual(true);
+ paged_cache_load(attributes.inputs[input_names::V],
+ attributes.inputs[input_names::SEQ_LEN_KV],
+ attributes.inputs[input_names::Page_table_V],
+ paged_cache_load_attributes_v,
+ v_cache);
+ }
+
+ //// S * V
+ if (attributes.mma_core_mode == DataType_t::HALF) {
+ auto bmm2_attributes =
+ Matmul_attributes().set_name("bmm2").set_m_override(seq_len_q).set_k_override(seq_len_kv);
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ matmul(last_output, v_cache, bmm2_attributes, O);
+ } else if (attributes.mma_core_mode == DataType_t::FP8_E4M3 ||
+ attributes.mma_core_mode == DataType_t::FP8_E5M2) {
+ if (use_mxfp8) {
+ // MXFP8: Dequantize V using block scale factors
+ // SF_V should be provided with dims [b, h, s_scale, d] where s is scaled
+ // (different from SF_Q/SF_K which have d scaled)
+ // No transformation needed - use SF_V as provided
+
+ // Dequantize V with SF_V
+ auto dequant_v_attrs = Block_scale_dequantize_attributes()
+ .set_name("dequant_v")
+ .set_block_size({1, 32}); // Standard MXFP8 block size
+ auto v_dequant = std::make_shared<Tensor_attributes>();
+ v_dequant->set_is_virtual(true);
+ v_dequant->set_dim(v_cache->get_dim());
+ v_dequant->set_stride(v_cache->get_stride());
+ block_scale_dequantize(v_cache, attributes.inputs[input_names::Descale_V], dequant_v_attrs, v_dequant);
+
+ // Use regular matmul with dequantized inputs
+ auto bmm2_attributes =
+ Matmul_attributes().set_name("bmm2").set_m_override(seq_len_q).set_k_override(seq_len_kv);
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ matmul(last_output, v_dequant, bmm2_attributes, O);
+
+ // Compute Amax_O for MXFP8
+ auto const& amax_o = attributes.outputs.at(output_names::Amax_O);
+ if (amax_o != nullptr) {
+ auto amax_attributes = Reduction_attributes().set_name("amax_o").set_mode(ReductionMode_t::AMAX);
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ reduction(O, amax_attributes, amax_o);
+ }
+ } else {
+ // Regular per-tensor FP8 scaling
+ auto const& descale_s = attributes.inputs.at(input_names::Descale_S);
+ auto const& descale_v = attributes.inputs.at(input_names::Descale_V);
+ auto const& scale_o = attributes.inputs.at(input_names::Scale_O);
+ auto const& amax_o = attributes.outputs.at(output_names::Amax_O);
+
+ auto bmm2_attributes =
+ Matmul_fp8_attributes().set_name("bmm2").set_m_override(seq_len_q).set_k_override(seq_len_kv);
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ matmul_fp8(last_output, v_cache, descale_s, descale_v, scale_o, bmm2_attributes, O, amax_o);
+ }
+ } else {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(true, error_code_t::GRAPH_NOT_SUPPORTED, "Unsupported MMA core mode");
+ }
+
+ return {error_code_t::OK, ""};
+ }
+};
+
+class CompositeSDPABackwardNode : public NodeCRTP<CompositeSDPABackwardNode> {
+ using input_names = SDPA_backward_attributes::input_names;
+ using output_names = SDPA_backward_attributes::output_names;
+
+ private:
+ // non-virtual node gpu tensors
+ std::shared_ptr<Tensor_attributes> dQ_accum;
+ int64_t dQ_accum_size = 0;
+ std::shared_ptr<Tensor_attributes> dK_fullhead;
+ int64_t dK_fullhead_size = 0;
+ std::shared_ptr<Tensor_attributes> dV_fullhead;
+ int64_t dV_fullhead_size = 0;
+ std::shared_ptr<Tensor_attributes> softmax_sum;
+ int64_t softmax_sum_size = 0;
+ std::shared_ptr<Tensor_attributes> alibi_slopes;
+ int64_t alibi_slopes_size = 0;
+
+ mutable bool has_workaround_padding_mask = false; // Will be edited in pre_validate_node()
+ mutable int32_t s_q_for_workaround_padding_mask = 0; // Will be edited in pre_validate_node()
+ mutable int32_t s_kv_for_workaround_padding_mask = 0; // Will be edited in pre_validate_node()
+ mutable std::shared_ptr<Tensor_attributes>
+ workaround_padding_mask_seq_len_q; // Will be edited in pre_validate_node()
+ mutable std::shared_ptr<Tensor_attributes>
+ workaround_padding_mask_seq_len_kv; // Will be edited in pre_validate_node()
+ mutable int64_t batch_size_for_workaround_padding_mask = 0; // Will be edited in pre_validate_node()
+ mutable bool is_deterministic_algorithm_supported_on_blackwell = false; // Will be edited in pre_validate_node()
+ mutable bool is_d256_on_blackwell = false; // Will be edited in pre_validate_node()
+
+ // Promote any 1-D seq_len / ragged-offset index tensors to the 4-D
+ // [n, 1, 1, 1] form the cuDNN backend requires (see promote_1d_index_tensor_to_4d).
+ void
+ promote_index_tensors_to_4d() {
+ // TODO: Handle CU_SEQ_LEN_Q and CU_SEQ_LEN_KV once bprop supports these.
+ for (auto& key : {input_names::SEQ_LEN_Q, input_names::SEQ_LEN_KV}) {
+ auto const it = attributes.inputs.find(key);
+ if (it != attributes.inputs.end()) {
+ promote_1d_index_tensor_to_4d(it->second);
+ }
+ }
+ for (auto& [key, value] : attributes.inputs) {
+ CUDNN_FRONTEND_UNUSED(key);
+ if (value != nullptr) {
+ promote_1d_index_tensor_to_4d(value->get_ragged_offset());
+ }
+ }
+ for (auto& [key, value] : attributes.outputs) {
+ CUDNN_FRONTEND_UNUSED(key);
+ if (value != nullptr) {
+ promote_1d_index_tensor_to_4d(value->get_ragged_offset());
+ }
+ }
+ }
+
+ public:
+ mutable SDPA_backward_attributes attributes; // Will be edited in pre_validate_node() for workaround padding mask
+
+ CompositeSDPABackwardNode(SDPA_backward_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::COMPOSITE;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating CompositeSDPABackwardNode" << attributes.name);
+
+ // check that Q, K, V, O, stats, dO, dQ, dK, dV tensors has been assigned
+ // check that dim and strides has been assigned and last stride is 1
+#define CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(port, port_map) \
+ { \
+ std::shared_ptr<Tensor_attributes> tensor_ptr = port_map.at(port); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF(tensor_ptr->get_dim().size() != 4, \
+ error_code_t::ATTRIBUTE_NOT_SET, \
+ "The dim for " + std::string(#port) + " is invalid"); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF(tensor_ptr->get_stride().size() != 4, \
+ error_code_t::ATTRIBUTE_NOT_SET, \
+ "The stride for " + std::string(#port) + " is invalid"); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF( \
+ tensor_ptr->get_stride()[3] != 1, \
+ error_code_t::GRAPH_NOT_SUPPORTED, \
+ "The stride for the last dimension corresponding to the embedding size per head should be 1 for " + \
+ std::string(#port)); \
+ }
+
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::Q, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::K, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::V, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::O, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::Stats, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::dO, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(output_names::dQ, attributes.outputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(output_names::dK, attributes.outputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(output_names::dV, attributes.outputs);
+
+#undef CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE
+
+ // validate backend limitations for the operation
+ // clang-format off
+ int64_t s_q = attributes.inputs.at(input_names::Q)->get_dim()[2];
+ int64_t s_kv = attributes.inputs.at(input_names::V)->get_dim()[2];
+ int64_t h_q = attributes.inputs.at(input_names::Q)->get_dim()[1];
+ int64_t h_k = attributes.inputs.at(input_names::K)->get_dim()[1];
+ int64_t h_v = attributes.inputs.at(input_names::V)->get_dim()[1];
+ int64_t d_qk = attributes.inputs.at(input_names::Q)->get_dim()[3];
+ int64_t d_v = attributes.inputs.at(input_names::V)->get_dim()[3];
+
+ bool const is_ragged = attributes.inputs.at(input_names::Q)->get_ragged_offset() ||
+ attributes.inputs.at(input_names::K)->get_ragged_offset() ||
+ attributes.inputs.at(input_names::V)->get_ragged_offset() ||
+ attributes.inputs.at(input_names::O)->get_ragged_offset();
+
+ auto const& bias_mask = attributes.inputs.find(input_names::Bias);
+ bool const is_bias = (bias_mask != attributes.inputs.end() && bias_mask->second != nullptr);
+ auto const& dbias_mask = attributes.outputs.find(output_names::dBias);
+ bool const is_dbias = (dbias_mask != attributes.outputs.end() && dbias_mask->second != nullptr);
+
+ auto const& dropout_mask = attributes.inputs.find(input_names::Dropout_mask);
+ bool const is_dropout_custom = (dropout_mask != attributes.inputs.end()) && (dropout_mask->second != nullptr);
+ bool const is_dropout = attributes.dropout_probability.has_value() || is_dropout_custom;
+
+ auto const& rng_tensor = attributes.outputs.find(output_names::RNG_DUMP);
+ bool const is_rng = (rng_tensor != attributes.outputs.end() && rng_tensor->second != nullptr);
+
+ // validation TODO:
+ // - validate stats has valid dims
+ // - validate Q and dQ have the same dims
+
+ // Stop s_q = S_kv = 1 from running
+ RETURN_CUDNN_FRONTEND_ERROR_IF(s_q == 1 && s_kv == 1,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "s_q = s_kv = 1 is not supported.");
+
+ // Bug workarounds for known problematic versions (TE constraint)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::get_backend_version() == 91000 || detail::get_backend_version() == 91001,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "SDPA FP16/BF16 backward is not supported on cuDNN 9.10.0/9.10.1 due to known bugs. "
+ "Please consider upgrading to 9.10.2 or newer.");
+
+ // 9.14.0 sliding window bug: non-causal + s_kv > 1024 + sliding window
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::get_backend_version() == 91400 && s_kv > 1024 && attributes.left_bound.has_value() &&
+ !attributes.has_causal_like_masking(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "cuDNN 9.14.0 has a known bug with non-causal + s_kv > 1024 + sliding window attention. "
+ "Please consider upgrading to 9.14.1 or newer.");
+
+ CHECK_CUDNN_FRONTEND_ERROR(context.populate_sm_version_from_device());
+ int32_t const sm_version = context.get_sm_version();
+ int32_t const prop_major = sm_version / 10;
+
+ if (prop_major == 9) {
+ // validate basic dimension requirements
+
+ if ((detail::get_backend_version() >= 91100) && (detail::get_backend_version() < 91300)) {
+
+ if ((128 < d_qk) && (d_qk <= 192) && (64 < d_v) && (d_v <= 128)) {
+
+ // DeepSeek case, 9.11 only supports 192 hidden dim
+ RETURN_CUDNN_FRONTEND_ERROR_IF( (d_v != 128) && (d_qk != 192),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Num hidden_dim d_v should be equal to 128 if d_qk is 192");
+ }
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF((d_qk > 256) || (d_qk % 8 != 0) || (d_v > 256) || (d_v % 8 != 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Num hidden_dim should be less than or equal to 256 and hidden_dim should be multiple of 8");
+
+ } else if (prop_major == 10 && detail::get_backend_version() >= 91100) {
+ // validate basic dimension requirements
+ if (d_qk == 192) { // special case for 192 hidden dim
+ RETURN_CUDNN_FRONTEND_ERROR_IF( (d_v != 128),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Num hidden_dim d_v should be equal to 128 if d_qk is 192");
+ } else if (detail::get_backend_version() >= 92300 && d_qk == 256 && d_v == 256) {
+ is_d256_on_blackwell = true;
+ attributes.is_deterministic_algorithm = true;
+ } else {
+ RETURN_CUDNN_FRONTEND_ERROR_IF((d_qk > 128) || (d_qk % 8 != 0) || (d_v > 128) || (d_v % 8 != 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Num hidden_dim should be less than or equal to 128 and hidden_dim should be multiple of 8 when d_qk != d_v");
+ }
+ } else {
+ // validate basic dimension requirements
+ RETURN_CUDNN_FRONTEND_ERROR_IF((d_qk > 128) || (d_qk % 8 != 0) || (d_v > 128) || (d_v % 8 != 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Num hidden_dim should be less than or equal to 128 and hidden_dim should be multiple of 8");
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF((attributes.attention_score_modifier != nullptr) &&
+ (attributes.alibi_mask || attributes.padding_mask || attributes.has_causal_like_masking() ||
+ attributes.left_bound.has_value()), error_code_t::GRAPH_NOT_SUPPORTED,"Attention score mod enabled and hence other subgraphs are disabled.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF((h_q % h_k != 0) || (h_q % h_v != 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "For group-query attention, number of heads for key and query must be a factor of number of heads for query");
+
+ // validate options for attn_scale
+ auto const& attn_scale = attributes.inputs.find(input_names::Attn_scale);
+ bool const has_attn_scale = (attn_scale != attributes.inputs.end()) && (attn_scale->second != nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_attn_scale && attributes.attn_scale_value.has_value(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "attn_scale with tensor and value cannot be set at the same time.");
+
+ // validate alibi requirements
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.alibi_mask && !(attributes.right_bound.has_value() && attributes.right_bound.value() == 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "When alibi mask is used, diagonal_band_right_bound needs to be set to 0.");
+
+ // validate options for bias mask
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_bias && (bias_mask->second->get_data_type() == DataType_t::BOOLEAN),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bias mask data type cannot be boolean");
+
+ if (s_kv % 128 != 0 && attributes.padding_mask == false && is_ragged == false && detail::get_backend_version() <= 91500) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Workaround padding mask is enabled for s_q % 128 != 0 and use_padding_mask == false and is_ragged == false");
+ has_workaround_padding_mask = true;
+ batch_size_for_workaround_padding_mask = attributes.inputs.at(input_names::Q)->get_dim()[0];
+ s_q_for_workaround_padding_mask = s_q;
+ s_kv_for_workaround_padding_mask = s_kv;
+ workaround_padding_mask_seq_len_q = std::make_shared<Tensor_attributes>();
+ workaround_padding_mask_seq_len_q->set_name("workaround_padding_mask_seq_len_q").set_dim({batch_size_for_workaround_padding_mask,1,1,1}).set_stride({1,1,1,1}).set_data_type(DataType_t::INT32);
+ workaround_padding_mask_seq_len_kv = std::make_shared<Tensor_attributes>();
+ workaround_padding_mask_seq_len_kv->set_name("workaround_padding_mask_seq_len_kv").set_dim({batch_size_for_workaround_padding_mask,1,1,1}).set_stride({1,1,1,1}).set_data_type(DataType_t::INT32);
+ attributes.set_padding_mask(true);
+ attributes.set_seq_len_q(workaround_padding_mask_seq_len_q).set_seq_len_kv(workaround_padding_mask_seq_len_kv);
+ }
+
+ // validate options for padding mask
+ auto const& seq_len_q = attributes.inputs.find(input_names::SEQ_LEN_Q);
+ bool const has_seq_len_q = (seq_len_q != attributes.inputs.end()) && (seq_len_q->second != nullptr);
+ auto const& seq_len_kv = attributes.inputs.find(input_names::SEQ_LEN_KV);
+ bool const has_seq_len_kv = (seq_len_kv != attributes.inputs.end()) && (seq_len_kv->second != nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.padding_mask && (!has_seq_len_q || !has_seq_len_kv),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Padding mask requires seq_len_q and seq_len_kv to be set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF((!attributes.padding_mask && !attributes.attention_score_modifier) && (has_seq_len_q || has_seq_len_kv),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "seq_len_q and seq_len_kv needs to be set only if padding mask is enabled.");
+
+ // validate options for max_total_seq_len
+ RETURN_CUDNN_FRONTEND_ERROR_IF((attributes.max_total_seq_len_q.has_value() || attributes.max_total_seq_len_kv.has_value()) && !is_ragged,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "max_total_seq_len_q is only supported with packed layout");
+
+ // validate options for bottom right causal mask
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.has_causal_mask_bottom_right() && (!attributes.padding_mask) && s_q > s_kv,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bottom right causal mask does not support max_s_q > max_s_kv. Please virtually slice the Q tensor and pass it as max_s_q == max_s_kv");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.has_causal_mask_bottom_right() && (is_bias || attributes.alibi_mask || (is_ragged && !attributes.padding_mask) || is_dropout),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bottom right causal mask is only supported with is_bias=False, is_alibi=False, is_dropout=False. Further is_ragged==True is only allowed when padding_mask=True.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.has_causal_mask_bottom_right() && (detail::get_backend_version() < 90600) && ((s_q % 64 != 0) || (s_kv % 64 != 0)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bottom right causal mask is only supported with s_q multiple of 64, and s_kv multiple of 64, for cudnn version below 9.6.0");
+
+ // validate options for sliding window length
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.left_bound.has_value() && attributes.left_bound.value() <= 0,
+ error_code_t::INVALID_VALUE,
+ "Left bound (Sliding window length) should be greater than or equals to zero when set.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.left_bound.has_value() && (s_q * attributes.left_bound.value() == s_kv * attributes.left_bound.value()) && (detail::get_backend_version() <= 90900) && (prop_major == 9) && attributes.has_causal_mask_bottom_right(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "On Hopper architecture, this specific combination of s_q, s_kv, and left_bound + right_bound + bottom right diagonal alignment is not supported for backend version 9.9 or below");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.left_bound.has_value() && (!attributes.padding_mask) && s_q > s_kv,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Sliding window attention is only supported with max_s_q <= max_s_kv.");
+
+ if ((detail::get_backend_version() >= 91002)) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF((attributes.left_bound.has_value() || attributes.right_bound.has_value()) && ((is_ragged && !attributes.padding_mask)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Left and right bounds with is_ragged==True is only allowed when padding_mask=True. And the diagonal alignment must be set.");
+ } else {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.left_bound.has_value() && (! attributes.has_causal_like_masking() || is_dropout || is_bias || (is_ragged && !attributes.padding_mask)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Left and right bounds are only supported with is_dropout=False, is_bias=False. Further is_ragged==True is only allowed when padding_mask=True. Lastly the diagonal alignment must be set.");
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.right_bound.has_value() && attributes.right_bound.value() < 0,
+ error_code_t::INVALID_VALUE,
+ "Right bound needs to be larger than or equal to zero");
+
+ // validate options for dropout mask
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.dropout_probability.has_value() && is_dropout_custom,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Using both, custom dropout mask and internal-mask generation using dropout probability, is ill-formed.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.dropout_probability.has_value() && attributes.dropout_probability.value() == 1.0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Dropout probability cannot be 1 as corresponding scale wont be well formed.");
+
+ // validate options for deterministic algorithm
+ if(attributes.is_deterministic_algorithm && (prop_major == 10)) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF( (detail::get_backend_version() < 91800),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Deterministic algorithm is not supported on blackwell architecture with cudnn version below 9.18.0");
+
+ // dbias bias rng/dropout alibi
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_dbias || is_rng || is_dropout || attributes.alibi_mask,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Deterministic algorithm is not supported on blackwell architecture when dbias, rng/dropout, alibi is enabled");
+
+ is_deterministic_algorithm_supported_on_blackwell = true;
+ }
+
+ if(detail::get_backend_version() >= 91801) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_ragged && (8 == prop_major || 12 == prop_major) && attributes.is_deterministic_algorithm,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Deterministic algorithm is not supported for bprop thd on SM8X and SM12X GPUs");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_ragged && (8 == prop_major || 12 == prop_major) && attributes.inputs[input_names::Stats]->get_ragged_offset(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Packed/ragged LSE is not supported for bprop thd on SM8X and SM12X GPUs");
+ }
+
+ // version specific validation
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90500 && is_dbias && attributes.padding_mask,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "For cuDNN version below 9.5.0, dBias with variable sequence lengths is not supported");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90500 && is_dbias && ((s_q % 64 != 0) || (s_kv % 64 != 0)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "For cuDNN version below 9.5.0, dBias not support s_q/s_kv which aren't multiple of 64");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90600 && is_ragged && ((h_q != h_k) || (h_q != h_v)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "For cuDNN version below 9.6.0, group-query attention with raggged offset is not supported");
+
+ // TODO add version check once fixed
+ RETURN_CUDNN_FRONTEND_ERROR_IF(prop_major == 10 && is_ragged && is_dbias,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "dbias with ragged is not supported for SM Major version 10");
+
+ // validate that datatype is set for the graph
+ RETURN_CUDNN_FRONTEND_ERROR_IF(this->context.get_intermediate_data_type() == DataType_t::NOT_SET,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Intermediate tensor data type needs to be set as internal tensors require it.");
+ // If dsink is set, sink also needs to be set
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.outputs.find(output_names::DSINK_TOKEN) != attributes.outputs.end() && attributes.inputs.find(input_names::SINK_TOKEN) == attributes.inputs.end(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "If dsink is set, sink also needs to be set.");
+ // clang-format on
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ // If a 1-D length/offset index tensor [n] is supplied, promote it to the 4-D
+ // [n, 1, 1, 1] (contiguous) form the cuDNN backend requires.
+ promote_index_tensors_to_4d();
+
+ // clang-format off
+ if (detail::get_backend_version() < 90600 && (attributes.max_total_seq_len_q.has_value() || attributes.max_total_seq_len_kv.has_value())) {
+ CUDNN_FE_LOG_LABEL_ENDL("WARNING: sdpa_backward.attributes.max_total_seq_len has been set, but cuDNN version is below 9.6.0 does not support max_total_seq_len_q. The workspace memory size required to execute this graph may be unexpectedly large");
+ attributes.max_total_seq_len_q.reset();
+ attributes.max_total_seq_len_kv.reset();
+ }
+
+ // TODO add version check once fixed
+ int64_t d_qk = attributes.inputs.at(input_names::Q)->get_dim()[3];
+ int64_t d_v = attributes.inputs.at(input_names::V)->get_dim()[3];
+ if ((attributes.max_total_seq_len_q.has_value() || attributes.max_total_seq_len_kv.has_value()) && (d_qk % 16 != 0 || d_v % 16 != 0)) {
+ CUDNN_FE_LOG_LABEL_ENDL("WARNING: sdpa_backward.attributes.max_total_seq_len has been set, but d is not a multiple of 16 has a known functional issue. The workspace memory size required to execute this graph may be unexpectedly large");
+ attributes.max_total_seq_len_q.reset();
+ attributes.max_total_seq_len_kv.reset();
+ }
+
+
+ if(detail::get_backend_version() >= 91801) {
+ int32_t const prop_major = context.get_sm_version() / 10;
+ if(8 == prop_major || 12 == prop_major) {
+ if(attributes.max_total_seq_len_q.has_value() || attributes.max_total_seq_len_kv.has_value()) {
+ attributes.max_total_seq_len_q.reset();
+ attributes.max_total_seq_len_kv.reset();
+ CUDNN_FE_LOG_LABEL_ENDL("WARNING: sdpa_backward.attributes.max_total_seq_len has been set, but ampere style kernels have a known functional issue. The workspace memory size required to execute this graph may be unexpectedly large");
+
+ }
+ }
+ }
+ // clang-format on
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ expand_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for CompositeSDPABackwardNode " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // Gather dim to fill properties of virtual tensors
+ auto const& q_dim = attributes.inputs[input_names::Q]->get_dim();
+ auto b = q_dim[0];
+ auto h_q = q_dim[1];
+ auto s_q = q_dim[2];
+ auto d_qk = q_dim[3];
+ auto const& k_dim = attributes.inputs[input_names::K]->get_dim();
+ auto h_k = k_dim[1];
+ auto s_kv = k_dim[2];
+ auto const& v_dim = attributes.inputs[input_names::V]->get_dim();
+ auto h_v = v_dim[1];
+ auto d_v = v_dim[3];
+
+ // cuDNN frontend API attention requires Q, K, V where
+ // Q = {b, h_q, s_q, d_qk}
+ // K = {b, h_k, s_kv, d_qk}
+ // V = {b, h_v, s_kv, d_v}
+ // but cuDNN backend API attention requires Q, KT, VT
+ // Q = {b, h_q, s_q, d_qk}
+ // KT = {b, h_k, d_qk, s_kv}
+ // VT = {b, h_v, d_v, s_kv}
+ // So the code below maps the K->KT and V->VT
+ std::vector<int64_t> temp_vec;
+
+ temp_vec = attributes.inputs[input_names::K]->get_dim();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::K]->set_dim(temp_vec);
+
+ temp_vec = attributes.inputs[input_names::K]->get_stride();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::K]->set_stride(temp_vec);
+
+ temp_vec = attributes.inputs[input_names::V]->get_dim();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::V]->set_dim(temp_vec);
+
+ temp_vec = attributes.inputs[input_names::V]->get_stride();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::V]->set_stride(temp_vec);
+
+ std::shared_ptr<Tensor_attributes> last_output, exp_s_output, dS_output, rng_output;
+
+ // --------------Initialize and create tensors before creating nodes--------------------
+ // one_tensor is needed for non-dropout graphs
+ // one_tensor is passed by the node
+ auto one_tensor = std::make_shared<Tensor_attributes>(1.0f);
+
+ if (attributes.attn_scale_value.has_value()) {
+ attributes.inputs[input_names::Attn_scale] =
+ std::make_shared<Tensor_attributes>(attributes.attn_scale_value.value());
+ }
+
+ // if dropout_mask is used, then the user passes scale and scale_inverse
+ bool is_dropout_prob = (attributes.dropout_probability.has_value());
+ bool is_dropout_mask = (attributes.inputs[input_names::Dropout_mask] != nullptr);
+ if (is_dropout_prob) {
+ float dropout_scale_value = 1.0f / (1.0f - attributes.dropout_probability.value());
+ float dropout_scale_inv_value = (1.0f - attributes.dropout_probability.value());
+
+ attributes.inputs[input_names::Dropout_scale] = std::make_shared<Tensor_attributes>(dropout_scale_value);
+ attributes.inputs[input_names::Dropout_scale_inv] =
+ std::make_shared<Tensor_attributes>(dropout_scale_inv_value);
+ }
+
+ // ---------------------input tensor workarounds---------------------------
+
+ bool use_dp_workspace = false;
+
+ int32_t const prop_major = context.get_sm_version() / 10;
+
+ if (detail::get_backend_version() >= 8905 && detail::get_backend_version() < 90000) {
+ // workspace optimization is enabled by default when:
+ // 8.9.5 <= cudnn version < 9.0.0
+ // device >= hopper
+ // batch * num_heads * seq_len_q * seq_len_kv * 2 <= dP workspace limit
+ //
+ // This following environment variable allows you to control the dP workspace limit.
+ // From cuDNN version 9.0.0, this option is obsolete will be ignored.
+ // CUDNN_FRONTEND_ATTN_DP_WORKSPACE_LIMIT=unset - enable workspace opt. until the default 256MB limit.
+ // CUDNN_FRONTEND_ATTN_DP_WORKSPACE_LIMIT=-1 - always enable workspace opt.
+ // CUDNN_FRONTEND_ATTN_DP_WORKSPACE_LIMIT=0 - always disable workspace opt.
+ // CUDNN_FRONTEND_ATTN_DP_WORKSPACE_LIMIT=n - enable workspace opt. until the n byte limit
+
+ // hopper or above
+ if (prop_major >= 9) {
+ // default upper limit for workspace 256MB
+ int64_t max_dp_workspace_bytes = 256 * 1024 * 1024;
+
+ // allow setting the upper limit with envvars
+ const char* env_dp_workspace_limit_char = get_environment("CUDNN_FRONTEND_ATTN_DP_WORKSPACE_LIMIT");
+ if (env_dp_workspace_limit_char) {
+ char* end_ptr = nullptr;
+ max_dp_workspace_bytes = std::strtoll(env_dp_workspace_limit_char, &end_ptr, 10);
+
+ if (*end_ptr != '\0') {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(true,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Invalid argument for CUDNN_FRONTEND_ATTN_DP_WORKSPACE_LIMIT "
+ "(int64_t; in bytes)");
+ }
+ }
+
+ int64_t workspace_s_q = ((s_q + 64 - 1) / 64) * 64;
+ int64_t workspace_s_kv = ((s_kv + 64 - 1) / 64) * 64;
+ int64_t required_dp_workspace_bytes = b * h_q * workspace_s_q * workspace_s_kv * 2;
+
+ if (max_dp_workspace_bytes == -1) {
+ use_dp_workspace = true;
+ } else if (max_dp_workspace_bytes == 0) {
+ use_dp_workspace = false;
+ } else {
+ use_dp_workspace = (required_dp_workspace_bytes <= max_dp_workspace_bytes);
+ }
+ }
+ }
+
+ // Force dP workspace implementation if:
+ // - dBias is enabled (dBias is only supported on workspace implementation)
+ // - the user force requests deterministic algorithm on hopper
+ if (attributes.outputs[output_names::dBias] || attributes.is_deterministic_algorithm) {
+ use_dp_workspace = true;
+ }
+
+ // --------------RNG node--------------------
+
+ if (is_dropout_prob) {
+ if (attributes.outputs[output_names::RNG_DUMP] != nullptr) {
+ rng_output = attributes.outputs[output_names::RNG_DUMP];
+ rng(attributes.inputs[input_names::Seed],
+ attributes.inputs[input_names::Offset],
+ Rng_attributes()
+ .set_name("rng")
+ .set_distribution(RngDistribution_t::BERNOULLI)
+ .set_bernoulli_probability(1.0f - attributes.dropout_probability.value()),
+ rng_output);
+ } else {
+ rng_output = rng(attributes.inputs[input_names::Seed],
+ attributes.inputs[input_names::Offset],
+ Rng_attributes()
+ .set_name("rng")
+ .set_distribution(RngDistribution_t::BERNOULLI)
+ .set_bernoulli_probability(1.0f - attributes.dropout_probability.value()));
+ rng_output->set_dim({b, h_q, s_q, s_kv}).set_stride({h_q * s_q * s_kv, s_q * s_kv, s_kv, 1});
+ }
+ } else if (is_dropout_mask) {
+ rng_output = attributes.inputs[input_names::Dropout_mask];
+ }
+
+ // --------------"dO * o => softmax_sum" chain--------------------
+
+ // last_output = dO * O
+ last_output = pointwise(attributes.inputs[input_names::dO],
+ attributes.inputs[input_names::O],
+ Pointwise_attributes().set_name("mul_dO_O").set_mode(PointwiseMode_t::MUL));
+ last_output->set_dim({b, h_q, s_q, d_v}).set_stride({h_q * s_q * d_v, s_q * d_v, h_q * d_v, 1});
+
+ // last_output = reduce(last_output, "b hq sq dv -> b hq sq 1")
+ last_output =
+ reduction(last_output, Reduction_attributes().set_name("reduce_dO_o").set_mode(ReductionMode_t::ADD));
+ last_output->set_dim({b, h_q, s_q, 1}).set_stride({h_q * s_q, s_q, 1, 1});
+
+ if (attributes.outputs.find(output_names::DSINK_TOKEN) != attributes.outputs.end()) {
+ // sub_sink = sink - stats
+ auto sub_sink = pointwise(attributes.inputs[input_names::SINK_TOKEN],
+ attributes.inputs[input_names::Stats],
+ Pointwise_attributes().set_name("sub_sink").set_mode(PointwiseMode_t::SUB));
+
+ // exp_sink = exp(sub_sink)
+ auto exp_sink =
+ pointwise(sub_sink, Pointwise_attributes().set_name("exp_sink").set_mode(PointwiseMode_t::EXP));
+
+ // per_token_grad = exp_sink * last_output
+ auto per_token_grad =
+ pointwise(exp_sink,
+ last_output,
+ Pointwise_attributes().set_name("mul_exp_sink_last_output").set_mode(PointwiseMode_t::MUL));
+
+ // dSink = redduce(per_token_grad)
+ reduction(per_token_grad,
+ Reduction_attributes().set_name("reduce_per_token_grad").set_mode(ReductionMode_t::ADD),
+ attributes.outputs[output_names::DSINK_TOKEN]);
+ }
+
+ // softmax_sum = last_output * dropout_scale
+ last_output = pointwise(last_output,
+ attributes.inputs[input_names::Dropout_scale_inv]
+ ? attributes.inputs[input_names::Dropout_scale_inv]
+ : one_tensor,
+ Pointwise_attributes().set_name("scale_dropout_inv").set_mode(PointwiseMode_t::MUL));
+ last_output->set_dim({b, h_q, s_q, 1}).set_stride({h_q * s_q, s_q, 1, 1});
+
+ softmax_sum = last_output;
+ softmax_sum->set_is_virtual(false);
+ softmax_sum->set_dim({b, h_q, s_q, 1});
+ softmax_sum->set_data_type(DataType_t::FLOAT);
+
+ if (attributes.inputs[input_names::Stats]->get_ragged_offset() && attributes.max_total_seq_len_q.has_value()) {
+ // sized TH1 softmax_sum
+ softmax_sum->set_stride(attributes.inputs[input_names::Stats]->get_stride());
+ softmax_sum->set_ragged_offset(attributes.inputs[input_names::Stats]->get_ragged_offset());
+ softmax_sum_size = attributes.max_total_seq_len_q.value() *
+ (attributes.inputs[input_names::Stats]->get_stride())[2] * sizeof(float);
+ } else {
+ // sized BHS1 softmax_sum
+ softmax_sum->set_stride({h_q * s_q, s_q, 1, 1});
+ softmax_sum_size = b * h_q * s_q * 1 * sizeof(float);
+ }
+
+ // --------------"Q @ KT => exp_softmax => dV" chain--------------------
+
+ // s = einsum(q, k, "b hq sq dqk, b (hk g) skv dqk -> b hq sq skv", g=hq//hk)
+ last_output = matmul(attributes.inputs[input_names::Q],
+ attributes.inputs[input_names::K],
+ Matmul_attributes()
+ .set_name("matmul_Q_KT")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_Q])
+ .set_n_override(attributes.inputs[input_names::SEQ_LEN_KV]));
+ last_output->set_dim({b, h_q, s_q, s_kv}).set_stride({h_q * s_q * s_kv, s_q * s_kv, s_kv, 1});
+
+ // last_output = last_output * attention_scale
+ if (attributes.inputs[input_names::Attn_scale]) {
+ last_output = pointwise(last_output,
+ attributes.inputs[input_names::Attn_scale],
+ Pointwise_attributes().set_name("mul_s_attn_scale").set_mode(PointwiseMode_t::MUL));
+ }
+
+ if (attributes.attention_score_modifier != nullptr) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = context;
+ last_output = attributes.attention_score_modifier(graph_, last_output);
+ sub_nodes.emplace_back(node_);
+ }
+
+ // (optional) last_output = last_output + bias
+ if (attributes.inputs.find(input_names::Bias) != attributes.inputs.end() &&
+ attributes.inputs[input_names::Bias]) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = context;
+ last_output = attn::score_modifiers::bias(graph_, last_output, attributes.inputs[input_names::Bias]);
+ sub_nodes.emplace_back(node_);
+ }
+
+ // (optional) last_output = last_output + alibi_mask
+ if (attributes.alibi_mask) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = context;
+ last_output = attn::score_modifiers::alibi_mask(graph_, last_output, alibi_slopes, h_q, alibi_slopes_size);
+ sub_nodes.emplace_back(node_);
+ }
+
+ // last_output = last_output - stats
+ last_output = pointwise(last_output,
+ attributes.inputs[input_names::Stats],
+ Pointwise_attributes().set_name("sub_s_m").set_mode(PointwiseMode_t::SUB));
+
+ // (optional) Apply padding mask
+ if (attributes.padding_mask) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = context;
+ last_output = attn::score_modifiers::padding_mask(graph_,
+ last_output,
+ attributes.inputs[input_names::SEQ_LEN_KV],
+ attributes.inputs[input_names::SEQ_LEN_Q]);
+ sub_nodes.emplace_back(node_);
+ }
+
+ // Explicitly put the padding value again after the stats have been loaded
+ if (attributes.padding_mask && detail::get_backend_version() >= 90000 &&
+ detail::get_backend_version() < 91000) {
+ auto row_idx_output = pointwise(last_output,
+ Pointwise_attributes()
+ .set_name("gen_row_idx_2nd_padding")
+ .set_mode(PointwiseMode_t::GEN_INDEX)
+ .set_axis(2)
+ .set_compute_data_type(DataType_t::INT32));
+ row_idx_output->set_data_type(DataType_t::INT32);
+
+ auto col_idx_output = pointwise(last_output,
+ Pointwise_attributes()
+ .set_name("gen_col_idx_2nd_padding")
+ .set_mode(PointwiseMode_t::GEN_INDEX)
+ .set_axis(3)
+ .set_compute_data_type(DataType_t::INT32));
+ col_idx_output->set_data_type(DataType_t::INT32);
+
+ auto row_mask_output = pointwise(row_idx_output,
+ attributes.inputs[input_names::SEQ_LEN_Q],
+ Pointwise_attributes()
+ .set_name("lt_row_sq_2nd_padding")
+ .set_mode(PointwiseMode_t::CMP_LT)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ row_mask_output->set_data_type(DataType_t::BOOLEAN);
+
+ auto col_mask_output = pointwise(col_idx_output,
+ attributes.inputs[input_names::SEQ_LEN_KV],
+ Pointwise_attributes()
+ .set_name("lt_col_skv_2nd_padding")
+ .set_mode(PointwiseMode_t::CMP_LT)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ col_mask_output->set_data_type(DataType_t::BOOLEAN);
+
+ auto padding_mask_output = pointwise(row_mask_output,
+ col_mask_output,
+ Pointwise_attributes()
+ .set_name("and_row_col_2nd_padding")
+ .set_mode(PointwiseMode_t::LOGICAL_AND)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ padding_mask_output->set_data_type(DataType_t::BOOLEAN);
+ auto negative_inf_padding =
+ std::make_shared<Tensor_attributes>(attn::score_modifiers::get_negative_inf_value());
+
+ last_output = pointwise(
+ last_output,
+ negative_inf_padding,
+ padding_mask_output,
+ Pointwise_attributes().set_name("select_2nd_padding").set_mode(PointwiseMode_t::BINARY_SELECT));
+ }
+
+ // Apply (bottom-right) causal masking (with right bound) and/or set the left bound
+ if (attributes.left_bound.has_value() || attributes.right_bound.has_value()) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = context;
+
+ auto s_kv_ptr = attributes.inputs.find(input_names::SEQ_LEN_KV) != attributes.inputs.end()
+ ? attributes.inputs[input_names::SEQ_LEN_KV]
+ : nullptr;
+ auto s_q_ptr = attributes.inputs.find(input_names::SEQ_LEN_Q) != attributes.inputs.end()
+ ? attributes.inputs[input_names::SEQ_LEN_Q]
+ : nullptr;
+
+ last_output = attn::score_modifiers::sliding_window_mask(graph_,
+ last_output,
+ attributes.diagonal_alignment,
+ attributes.left_bound,
+ attributes.right_bound,
+ s_q,
+ s_kv,
+ s_q_ptr,
+ s_kv_ptr,
+ /*cu_s_q_ptr=*/nullptr,
+ /*cu_s_kv_ptr=*/nullptr);
+ sub_nodes.emplace_back(std::move(node_));
+ }
+
+ // last_output = exp(last_output)
+ last_output = pointwise(last_output, Pointwise_attributes().set_name("exp_s").set_mode(PointwiseMode_t::EXP));
+
+ exp_s_output = last_output;
+
+ // (optional) last_output = last_output * dropout rng_output
+ if (is_dropout_prob || is_dropout_mask) {
+ last_output =
+ pointwise(last_output,
+ rng_output,
+ Pointwise_attributes().set_name("mul_p_dropout_mask").set_mode(PointwiseMode_t::MUL));
+ }
+
+ // (optional) last_output = last_output * dropout_scale
+ if (attributes.inputs[input_names::Dropout_scale]) {
+ last_output =
+ pointwise(last_output,
+ attributes.inputs[input_names::Dropout_scale],
+ Pointwise_attributes().set_name("mul_p_dropout_scale").set_mode(PointwiseMode_t::MUL));
+ }
+
+ // dV = einsum(p, dO, "b hq sq skv", "b hq sq dv -> b hq skv dv")
+ // if GQA, then dV = reduce(dV, "b (hv g) skv dv -> b hv skv dv", g=hq//hv)
+ // as reshape + matmul
+ last_output = reshape(last_output, Reshape_attributes().set_name("reshape_p"));
+ last_output->set_dim({b, h_q, s_kv, s_q}).set_stride({h_q * s_q * s_kv, s_q * s_kv, 1, s_kv});
+ last_output->set_data_type(attributes.inputs[input_names::Q]->get_data_type());
+
+ if (h_q == h_v) {
+ // for MHA
+ matmul(last_output,
+ attributes.inputs[input_names::dO],
+ Matmul_attributes()
+ .set_name("matmul_pT_dO")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_KV])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_Q]),
+ attributes.outputs[output_names::dV]);
+ } else {
+ // for GQA and MQA
+ dV_fullhead = matmul(last_output,
+ attributes.inputs[input_names::dO],
+ Matmul_attributes()
+ .set_name("matmul_pT_dO")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_KV])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_Q]));
+
+ dV_fullhead->set_dim({b, h_q, s_kv, d_v});
+ dV_fullhead->set_data_type(attributes.inputs[input_names::Q]->get_data_type());
+
+ if (attributes.outputs[output_names::dV]->get_ragged_offset() &&
+ attributes.max_total_seq_len_kv.has_value()) {
+ // map dV strides to dV_fullhead strides
+ std::vector<int64_t> dV_fullhead_stride = attributes.outputs[output_names::dV]->get_stride();
+ dV_fullhead_stride[2] = dV_fullhead_stride[2] * (h_q / h_v); // sequence stride
+ dV_fullhead_stride[0] = dV_fullhead_stride[0] * (h_q / h_v); // batch stride
+ dV_fullhead->set_stride(dV_fullhead_stride);
+ // map dV ragged offset to dV_fullhead ragged offset with implicit multiplier
+ // implicit multiplier = h_q / h_v
+ dV_fullhead->set_ragged_offset(attributes.outputs[output_names::dV]->get_ragged_offset());
+ // non virtual dV full head
+ dV_fullhead->set_is_virtual(false);
+ dV_fullhead_size = attributes.max_total_seq_len_kv.value() * dV_fullhead_stride[2] * sizeof(float);
+ } else {
+ // sized BHSD dQ_accum
+ dV_fullhead->set_stride({h_q * s_kv * d_v, s_kv * d_v, d_v, 1});
+ }
+
+ reduction(dV_fullhead,
+ Reduction_attributes().set_name("red_dV_head").set_mode(ReductionMode_t::ADD),
+ attributes.outputs[output_names::dV]);
+ }
+
+ // --------------"dO @ VT => dS_output => dK" chain--------------------
+
+ // dP = einsum(dO, v, "b hq sq dv, b (hv g) skv dv -> b hq sq skv", g=hq//hv)
+ last_output = matmul(attributes.inputs[input_names::dO],
+ attributes.inputs[input_names::V],
+ Matmul_attributes()
+ .set_name("matmul_dO_VT")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_Q])
+ .set_n_override(attributes.inputs[input_names::SEQ_LEN_KV]));
+ last_output->set_dim({b, h_q, s_q, s_kv}).set_stride({h_q * s_q * s_kv, s_q * s_kv, s_kv, 1});
+
+ // last_output = last_output(dP) * mask
+ if (is_dropout_prob || is_dropout_mask) {
+ last_output = pointwise(last_output,
+ rng_output,
+ Pointwise_attributes().set_name("dP_dropout_mask").set_mode(PointwiseMode_t::MUL));
+ }
+
+ // last_output = last_output - softmax_sum
+ last_output = pointwise(last_output,
+ softmax_sum,
+ Pointwise_attributes().set_name("sub_dP_softmax_sum").set_mode(PointwiseMode_t::SUB));
+
+ // last_output = last_output * exp_s_output
+ last_output = pointwise(
+ last_output, exp_s_output, Pointwise_attributes().set_name("mul_dP_exp_s").set_mode(PointwiseMode_t::MUL));
+
+ // (optional) last_output = last_output * dropout_scale
+ if (attributes.inputs[input_names::Dropout_scale]) {
+ last_output =
+ pointwise(last_output,
+ attributes.inputs[input_names::Dropout_scale],
+ Pointwise_attributes().set_name("mul_dS_dropout_scale").set_mode(PointwiseMode_t::MUL));
+ }
+
+ if (attributes.outputs[output_names::dBias]) {
+ reduction(last_output,
+ Reduction_attributes().set_name("red_dP_dBias").set_mode(ReductionMode_t::ADD),
+ attributes.outputs[output_names::dBias]);
+ }
+
+ // apply the bprop of attention score modifier
+ if (attributes.attention_score_modifier_bprop != nullptr) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = context;
+ last_output = attributes.attention_score_modifier_bprop(graph_, last_output);
+ sub_nodes.emplace_back(node_);
+ }
+
+ // (optional) last_output = last_output * bmm_scale
+ if (attributes.inputs[input_names::Attn_scale]) {
+ last_output =
+ pointwise(last_output,
+ attributes.inputs[input_names::Attn_scale],
+ Pointwise_attributes().set_name("mul_dS_attn_scale").set_mode(PointwiseMode_t::MUL));
+ }
+
+ dS_output = last_output;
+
+ // dK = einsum(dS, Q, "b hq sq skv", "b hq sq dqk -> b hq skv dqk")
+ // if GQA, then dK = reduce(dK, "b (hk g) skv dqk -> b hk skv dqk", hq//hk)
+ // as reshape + matmul
+ last_output = reshape(last_output, Reshape_attributes().set_name("reshape_dS"));
+ last_output->set_dim({b, h_q, s_kv, s_q}).set_stride({h_q * s_q * s_kv, s_q * s_kv, 1, s_kv});
+ last_output->set_data_type(attributes.inputs[input_names::Q]->get_data_type());
+
+ if (h_q == h_k) {
+ // for MHA
+ matmul(last_output,
+ attributes.inputs[input_names::Q],
+ Matmul_attributes()
+ .set_name("matmul_dST_Q")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_KV])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_Q]),
+ attributes.outputs[output_names::dK]);
+ } else {
+ // for GQA and MQA
+ dK_fullhead = matmul(last_output,
+ attributes.inputs[input_names::Q],
+ Matmul_attributes()
+ .set_name("matmul_dST_Q")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_KV])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_Q]));
+
+ dK_fullhead->set_dim({b, h_q, s_kv, d_qk});
+ dK_fullhead->set_data_type(attributes.inputs[input_names::Q]->get_data_type());
+
+ if (attributes.outputs[output_names::dK]->get_ragged_offset() &&
+ attributes.max_total_seq_len_kv.has_value()) {
+ // sized THD dK_full_heads
+ // map dK strides to dK_fullhead strides
+ std::vector<int64_t> dK_fullhead_stride = attributes.outputs[output_names::dK]->get_stride();
+ dK_fullhead_stride[0] = dK_fullhead_stride[0] * (h_q / h_k); // batch stride
+ dK_fullhead_stride[2] = dK_fullhead_stride[2] * (h_q / h_k); // sequence stride
+ dK_fullhead->set_stride(dK_fullhead_stride);
+ // map dK ragged offset to dK_fullhead ragged offset with implicit multiplier
+ // implicit multiplier = h_q / h_k
+ dK_fullhead->set_ragged_offset(attributes.outputs[output_names::dK]->get_ragged_offset());
+ // non virtual dK full head
+ dK_fullhead->set_is_virtual(false);
+ dK_fullhead_size = attributes.max_total_seq_len_kv.value() * dK_fullhead_stride[2] * sizeof(float);
+ } else {
+ // sized BHSD dQ_accum
+ dK_fullhead->set_stride({h_q * s_kv * d_qk, s_kv * d_qk, d_qk, 1});
+ }
+
+ reduction(dK_fullhead,
+ Reduction_attributes().set_name("red_dK_head").set_mode(ReductionMode_t::ADD),
+ attributes.outputs[output_names::dK]);
+ }
+
+ // --------------"dp_scaled @ K => dQ" chain--------------------
+
+ auto const& kt_dim = attributes.inputs[input_names::K]->get_dim();
+ auto const& kt_stride = attributes.inputs[input_names::K]->get_stride();
+
+ // dQ = einsum(dS, K, "b hq sq skv, b (hk g) skv dqk -> b hq sq dqk", g=hq//hk)
+ // as reshape + matmul
+ last_output = reshape(attributes.inputs[input_names::K], Reshape_attributes().set_name("reshape_k"));
+ last_output->set_dim({kt_dim[0], kt_dim[1], kt_dim[3], kt_dim[2]})
+ .set_stride({kt_stride[0], kt_stride[1], kt_stride[3], kt_stride[2]});
+
+ if (attributes.inputs[input_names::K]->get_ragged_offset() != nullptr) {
+ last_output->set_ragged_offset(attributes.inputs[input_names::K]->get_ragged_offset());
+ }
+
+ if (!use_dp_workspace) {
+ dQ_accum = std::make_shared<Tensor_attributes>();
+ dQ_accum->set_is_virtual(false);
+ dQ_accum->set_dim({b, h_q, s_q, d_qk});
+ dQ_accum->set_data_type(DataType_t::FLOAT);
+
+ if (attributes.outputs[output_names::dQ]->get_ragged_offset() &&
+ attributes.max_total_seq_len_q.has_value()) {
+ // sized THD dQ_accum
+ dQ_accum->set_stride(attributes.outputs[output_names::dQ]->get_stride());
+ dQ_accum->set_ragged_offset(attributes.outputs[output_names::dQ]->get_ragged_offset());
+ dQ_accum_size = attributes.max_total_seq_len_q.value() *
+ (attributes.outputs[output_names::dQ]->get_stride())[2] * sizeof(float);
+ } else {
+ // sized BHSD dQ_accum
+ dQ_accum->set_stride({h_q * s_q * d_qk, s_q * d_qk, d_qk, 1});
+ dQ_accum_size = b * h_q * s_q * d_qk * sizeof(float);
+ }
+
+ matmul(dS_output,
+ last_output,
+ Matmul_attributes()
+ .set_name("matmul_dS_K")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_Q])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_KV]),
+ dQ_accum);
+
+ pointwise(dQ_accum,
+ Pointwise_attributes().set_name("identity_dQ").set_mode(PointwiseMode_t::IDENTITY),
+ attributes.outputs[output_names::dQ]);
+ } else {
+ matmul(dS_output,
+ last_output,
+ Matmul_attributes()
+ .set_name("matmul_dS_K")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_Q])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_KV]),
+ attributes.outputs[output_names::dQ]);
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ std::pair<int64_t, std::unordered_map<KnobType_t, int64_t>>
+ override_heuristics_query() const {
+ int32_t const sm_version = context.get_sm_version();
+ bool const use_new_knobs = detail::get_backend_version() >= 92300;
+ // {128,128} bprop: tileM=3, tileN=2, kernelCfg=2(bprop warp), streamK=0, cgaM=0
+ if (sm_version > 103 && (is_deterministic_algorithm_supported_on_blackwell)) {
+ if (use_new_knobs) {
+ return {17,
+ {{KnobType_t::TILE_M, 3},
+ {KnobType_t::TILE_N, 2},
+ {KnobType_t::KERNEL_CFG, 2},
+ {KnobType_t::STREAM_K, 0},
+ {KnobType_t::TILE_CGA_M, 0},
+ {KnobType_t::STAGES, is_d256_on_blackwell ? 3 : 2}}};
+ } else {
+ return {17, {{KnobType_t::KERNEL_CFG, 31}, {KnobType_t::STAGES, is_d256_on_blackwell ? 3 : 2}}};
+ }
+ } else if (is_deterministic_algorithm_supported_on_blackwell) {
+ if (use_new_knobs) {
+ return {5,
+ {{KnobType_t::TILE_M, 3},
+ {KnobType_t::TILE_N, 2},
+ {KnobType_t::KERNEL_CFG, 2},
+ {KnobType_t::STREAM_K, 0},
+ {KnobType_t::TILE_CGA_M, 0},
+ {KnobType_t::STAGES, is_d256_on_blackwell ? 3 : 2}}};
+ } else {
+ return {5, {{KnobType_t::KERNEL_CFG, 31}, {KnobType_t::STAGES, is_d256_on_blackwell ? 3 : 2}}};
+ }
+ } else {
+ return {-1, {}};
+ }
+ }
+
+ virtual int64_t
+ get_fe_workspace_size_node() const override final {
+ int64_t size = 0;
+
+ size += ((alibi_slopes_size + 15) / 16 * 16); // align alibi slopes memory to 16 bytes
+ size += dQ_accum_size;
+ size += dK_fullhead_size;
+ size += dV_fullhead_size;
+ size += softmax_sum_size;
+
+ if (has_workaround_padding_mask) {
+ size += batch_size_for_workaround_padding_mask * sizeof(int32_t) * 2;
+ }
+
+ return size;
+ }
+
+ virtual error_t
+ collect_tensors_in_workspace_node(
+ std::unordered_map<Tensor_attributes::uid_t, std::tuple<int64_t, int64_t, std::vector<float>>>&
+ workspace_modifications,
+ int64_t& offset) const override final {
+ if (attributes.alibi_mask) {
+ CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(Q, input_names::Q);
+ int64_t const h_q = Q->second->get_dim()[1];
+ auto alibi_slopes_vec = detail::get_alibi_slope(h_q);
+ workspace_modifications.emplace(alibi_slopes->get_uid(), std::make_tuple(0, offset, alibi_slopes_vec));
+ int64_t alibi_slopes_size_padded = ((alibi_slopes_size + 15) / 16 * 16);
+ offset = offset + alibi_slopes_size_padded;
+ }
+
+ if (dQ_accum && !dQ_accum->get_is_virtual()) {
+ if (detail::get_backend_version() < 90600) {
+ // prior to cuDNN 9.6.0, dQ_accum needed to be memset by frontend
+ workspace_modifications.emplace(dQ_accum->get_uid(),
+ std::make_tuple(1, offset, std::vector<float>{(float)dQ_accum_size}));
+ } else {
+ workspace_modifications.emplace(dQ_accum->get_uid(), std::make_tuple(2, offset, std::vector<float>()));
+ }
+ offset = offset + dQ_accum_size;
+ }
+
+ if (dK_fullhead && !dK_fullhead->get_is_virtual()) {
+ workspace_modifications.emplace(dK_fullhead->get_uid(), std::make_tuple(2, offset, std::vector<float>()));
+ offset = offset + dK_fullhead_size;
+ }
+
+ if (dV_fullhead && !dV_fullhead->get_is_virtual()) {
+ workspace_modifications.emplace(dV_fullhead->get_uid(), std::make_tuple(2, offset, std::vector<float>()));
+ offset = offset + dV_fullhead_size;
+ }
+
+ if (softmax_sum && !softmax_sum->get_is_virtual()) {
+ workspace_modifications.emplace(softmax_sum->get_uid(), std::make_tuple(2, offset, std::vector<float>()));
+ offset = offset + softmax_sum_size;
+ }
+
+ if (has_workaround_padding_mask) {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Collecting workaround padding mask tensors with batch size "
+ << batch_size_for_workaround_padding_mask << " with UIDs "
+ << workaround_padding_mask_seq_len_q->get_uid() << " and "
+ << workaround_padding_mask_seq_len_kv->get_uid());
+ std::vector<int32_t> workaround_padding_mask_seq_len_q_vec(batch_size_for_workaround_padding_mask,
+ s_q_for_workaround_padding_mask);
+ std::vector<int32_t> workaround_padding_mask_seq_len_kv_vec(batch_size_for_workaround_padding_mask,
+ s_kv_for_workaround_padding_mask);
+
+ // reinterpret_cast the int32_t vector data to float vector for workspace_modifications
+ std::vector<float> workaround_padding_mask_seq_len_q_vec_float(
+ reinterpret_cast<float*>(workaround_padding_mask_seq_len_q_vec.data()),
+ reinterpret_cast<float*>(workaround_padding_mask_seq_len_q_vec.data()) +
+ batch_size_for_workaround_padding_mask);
+ std::vector<float> workaround_padding_mask_seq_len_kv_vec_float(
+ reinterpret_cast<float*>(workaround_padding_mask_seq_len_kv_vec.data()),
+ reinterpret_cast<float*>(workaround_padding_mask_seq_len_kv_vec.data()) +
+ batch_size_for_workaround_padding_mask);
+
+ workspace_modifications.emplace(workaround_padding_mask_seq_len_q->get_uid(),
+ std::make_tuple(0, offset, workaround_padding_mask_seq_len_q_vec_float));
+ offset = offset + batch_size_for_workaround_padding_mask * sizeof(float);
+ workspace_modifications.emplace(workaround_padding_mask_seq_len_kv->get_uid(),
+ std::make_tuple(0, offset, workaround_padding_mask_seq_len_kv_vec_float));
+ offset = offset + batch_size_for_workaround_padding_mask * sizeof(float);
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"({"tag": "SDPA_BWD"})"_json);
+ }
+#endif
+};
+
+class UnifiedSDPANode : public SDPANodeBase<UnifiedSDPANode> {
+ public:
+ UnifiedSDPANode(SDPA_attributes&& attributes_, detail::Context const& context)
+ : SDPANodeBase(std::move(attributes_), context) {}
+
+ Type
+ getType() override final {
+ return Type::SDPA;
+ }
+
+ error_t
+ expand_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for UnifiedSDPANode node " << attributes.name);
+
+ // DO NOT REMOVE
+ // input data type is needed for:
+ // - aType of bmm2
+ // - dropout scale in pre 8.9.3
+ attributes.fill_from_context(this->context);
+
+ //// Optional Attn scale
+ // In case user provided a scalar value, do a fused scalar.
+ if (attributes.attn_scale_value.has_value()) {
+ attributes.inputs[input_names::Attn_scale] =
+ std::make_shared<Tensor_attributes>(attributes.attn_scale_value.value());
+ }
+
+ // Optional attention score modifier
+ if (attributes.attention_score_modifier != nullptr) {
+ if (!subgraph) init_subgraph();
+ subgraph_output = attributes.attention_score_modifier(subgraph, subgraph_output);
+ }
+
+ // Optional bias
+ if (attributes.inputs.find(input_names::Bias) != attributes.inputs.end() &&
+ attributes.inputs[input_names::Bias]) {
+ if (!subgraph) init_subgraph();
+ subgraph_output =
+ attn::score_modifiers::bias(subgraph, subgraph_output, attributes.inputs[input_names::Bias]);
+ }
+
+ // Optional alibi mask
+ if (attributes.alibi_mask) {
+ if (!subgraph) init_subgraph();
+ auto h_q = attributes.inputs[input_names::Q]->get_dim()[1];
+ subgraph_output =
+ attn::score_modifiers::alibi_mask(subgraph, subgraph_output, alibi_slopes, h_q, alibi_slopes_size);
+ }
+
+ // Optional casual masking
+ if (attributes.left_bound.has_value() || attributes.right_bound.has_value()) {
+ if (!subgraph) init_subgraph();
+
+ auto s_q = attributes.inputs[input_names::Q]->get_dim()[2];
+ auto s_kv = infer_s_kv();
+ auto s_kv_ptr = attributes.inputs.find(input_names::SEQ_LEN_KV) != attributes.inputs.end()
+ ? attributes.inputs[input_names::SEQ_LEN_KV]
+ : nullptr;
+ auto s_q_ptr = attributes.inputs.find(input_names::SEQ_LEN_Q) != attributes.inputs.end()
+ ? attributes.inputs[input_names::SEQ_LEN_Q]
+ : nullptr;
+ auto cu_s_kv_ptr = attributes.inputs.find(input_names::CU_SEQ_LEN_KV) != attributes.inputs.end()
+ ? attributes.inputs[input_names::CU_SEQ_LEN_KV]
+ : nullptr;
+ auto cu_s_q_ptr = attributes.inputs.find(input_names::CU_SEQ_LEN_Q) != attributes.inputs.end()
+ ? attributes.inputs[input_names::CU_SEQ_LEN_Q]
+ : nullptr;
+
+ subgraph_output = attn::score_modifiers::sliding_window_mask(subgraph,
+ subgraph_output,
+ attributes.diagonal_alignment,
+ attributes.left_bound,
+ attributes.right_bound,
+ s_q,
+ s_kv,
+ s_q_ptr,
+ s_kv_ptr,
+ cu_s_q_ptr,
+ cu_s_kv_ptr);
+ }
+
+ if (subgraph) {
+ subgraph_output->set_name(attributes.name + "::subgraph_output");
+ auto subgraph_node = std::static_pointer_cast<INode>(subgraph);
+ sub_nodes.emplace_back(subgraph_node);
+ }
+
+ // For BE >= 9.21, express softmax as a UnifiedSoftmaxNode whose backend descriptor
+ // will be set via CUDNN_ATTR_OPERATION_SDPA_FWD_SOFTMAX_DESC.
+ // For older versions, stats (if present) is set directly via CUDNN_ATTR_OPERATION_SDPA_FWD_STATSDESC.
+ auto effective_cudnn_ver = std::min(detail::get_compiled_version(), detail::get_backend_version());
+
+ auto has_output = [&](auto name) {
+ auto it = attributes.outputs.find(name);
+ return it != attributes.outputs.end() && it->second != nullptr;
+ };
+ bool has_softmax_features = has_output(output_names::Stats) || has_output(output_names::Max) ||
+ has_output(output_names::Sum_exp) || attributes.has_sink_token();
+
+ if (effective_cudnn_ver >= 92100 && has_softmax_features) {
+ auto b = attributes.inputs[input_names::Q]->get_dim()[0];
+ auto h_q = attributes.inputs[input_names::Q]->get_dim()[1];
+ auto s_q = attributes.inputs[input_names::Q]->get_dim()[2];
+ auto s_kv = infer_s_kv();
+
+ auto softmax_p = std::make_shared<Tensor_attributes>();
+ softmax_p->set_is_virtual(true);
+ softmax_p->set_name(attributes.name + "::softmax_P");
+ softmax_p->set_dim({b, h_q, s_q, s_kv});
+ softmax_p->set_stride({h_q * s_q * s_kv, s_q * s_kv, s_kv, 1});
+
+ auto softmax_s = std::make_shared<Tensor_attributes>();
+ softmax_s->set_is_virtual(true);
+ softmax_s->set_name(attributes.name + "::softmax_S");
+ softmax_s->set_dim({b, h_q, s_q, s_kv});
+ softmax_s->set_stride({h_q * s_q * s_kv, s_q * s_kv, s_kv, 1});
+
+ auto softmax_attrs = Softmax_attributes().set_name(attributes.name + "::softmax");
+ softmax_attrs.inputs[Softmax_attributes::input_names::P] = softmax_p;
+ softmax_attrs.outputs[Softmax_attributes::output_names::S] = softmax_s;
+
+ if (attributes.has_sink_token()) {
+ softmax_attrs.set_sink(attributes.inputs[input_names::SINK_TOKEN]);
+ }
+ if (has_output(output_names::Stats)) {
+ softmax_attrs.outputs[Softmax_attributes::output_names::Stats] =
+ attributes.outputs[output_names::Stats];
+ }
+ if (has_output(output_names::Max)) {
+ softmax_attrs.outputs[Softmax_attributes::output_names::Max] = attributes.outputs[output_names::Max];
+ }
+ if (has_output(output_names::Sum_exp)) {
+ softmax_attrs.outputs[Softmax_attributes::output_names::Sum_exp] =
+ attributes.outputs[output_names::Sum_exp];
+ }
+
+ softmax_node = std::make_shared<UnifiedSoftmaxNode>(std::move(softmax_attrs), context);
+ sub_nodes.emplace_back(softmax_node);
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FE_LOG_LABEL("INFO: Building UnifiedSDPANode operations " << attributes.name << " ");
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Unified SDPA node requires cuDNN 9.13.1"};
+
+#if (CUDNN_VERSION >= 91301)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91301, cudnn_ver_error);
+ auto unified_sdpa_operation =
+ make_shared_backend_pointer((cudnnBackendDescriptorType_t)CUDNN_BACKEND_OPERATION_SDPA_FWD_DESCRIPTOR);
+
+ auto Q = attributes.inputs.find(SDPA_attributes::input_names::Q)->second;
+ auto backend_q = tensors[Q->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_QDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_q));
+
+ auto K = attributes.inputs.find(SDPA_attributes::input_names::K)->second;
+ auto backend_k = tensors[K->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_KDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_k));
+
+ auto V = attributes.inputs.find(SDPA_attributes::input_names::V)->second;
+ auto backend_v = tensors[V->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_VDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_v));
+
+ auto O = attributes.outputs.find(SDPA_attributes::output_names::O)->second;
+ auto backend_o = tensors[O->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_ODESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_o));
+
+ if (softmax_node) {
+ auto softmax_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED, "SOFTMAX_DESC in unified SDPA node requires cuDNN 9.21.0"};
+#if (CUDNN_VERSION >= 92100)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92100, softmax_ver_error);
+
+ managed_backend_descriptor_t softmax_raw_ops;
+ std::unordered_set<Tensor_attributes::uid_t> softmax_uids;
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>> softmax_ops;
+ CHECK_CUDNN_FRONTEND_ERROR(
+ softmax_node->create_cudnn_operations(softmax_uids, softmax_ops, softmax_raw_ops, tensors));
+
+ auto backend_softmax = softmax_raw_ops[0]->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_SOFTMAX_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_softmax));
+
+ uids_involved_in_operations.insert(softmax_uids.begin(), softmax_uids.end());
+#else
+ return softmax_ver_error;
+#endif
+ } else {
+ auto stats_it = attributes.outputs.find(SDPA_attributes::output_names::Stats);
+ if (stats_it != attributes.outputs.end() && stats_it->second) {
+ auto backend_stats = tensors[stats_it->second->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_STATSDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_stats));
+ }
+ }
+
+ auto attn_scale_it = attributes.inputs.find(SDPA_attributes::input_names::Attn_scale);
+ if (attn_scale_it != attributes.inputs.end()) {
+ auto backend_scale = tensors[attn_scale_it->second->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_SCALEDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_scale));
+ }
+
+ auto block_mask_it = attributes.inputs.find(SDPA_attributes::input_names::Block_mask);
+ if (block_mask_it != attributes.inputs.end() && block_mask_it->second != nullptr) {
+ auto block_mask_cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Block mask in unified SDPA node requires cuDNN 9.14.0"};
+#if CUDNN_VERSION >= 91400
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91400, block_mask_cudnn_ver_error);
+ auto backend_block_mask = tensors[block_mask_it->second->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_BLOCK_MASK_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_block_mask));
+#else
+ return block_mask_cudnn_ver_error;
+#endif
+ }
+
+ // Variable-length and paged-attention attributes:
+ // - paged attention K/V page tables (needs cuDNN >= 9.15.0)
+ // - per-batch sequence-length tensors (SEQ_LEN_Q / SEQ_LEN_KV; needs cuDNN >= 9.15.0)
+ // - cumulative sequence-length tensors (CU_SEQ_LEN_Q / CU_SEQ_LEN_KV; needs cuDNN >= 9.24.0).
+ if (is_paged_k() || is_paged_v() || has_seq_len_q() || has_seq_len_kv() || has_cu_seq_len_q() ||
+ has_cu_seq_len_kv()) {
+ auto paged_cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED,
+ "Paged attention or per-batch sequence lengths in unified SDPA node require cuDNN 9.15.0"};
+#if (CUDNN_VERSION >= 91500)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91500, paged_cudnn_ver_error);
+
+ if (is_paged_k()) {
+ auto page_table_K = attributes.inputs.find(SDPA_attributes::input_names::Page_table_K)->second;
+ auto backend_page_table_K = tensors[page_table_K->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_PAGE_TABLE_KDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_page_table_K));
+ }
+
+ if (is_paged_v()) {
+ auto page_table_V = attributes.inputs.find(SDPA_attributes::input_names::Page_table_V)->second;
+ auto backend_page_table_V = tensors[page_table_V->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_PAGE_TABLE_VDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_page_table_V));
+ }
+
+ if (has_seq_len_q()) {
+ auto seq_len_Q = attributes.inputs.find(SDPA_attributes::input_names::SEQ_LEN_Q)->second;
+ auto backend_seq_len_Q = tensors[seq_len_Q->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_SEQ_LEN_QDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_seq_len_Q));
+ }
+
+ if (has_seq_len_kv()) {
+ auto seq_len_KV = attributes.inputs.find(SDPA_attributes::input_names::SEQ_LEN_KV)->second;
+ auto backend_seq_len_KV = tensors[seq_len_KV->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_SEQ_LEN_KVDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_seq_len_KV));
+ }
+
+ if (has_cu_seq_len_q() || has_cu_seq_len_kv()) {
+ auto cu_seq_len_cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED,
+ "Cumulative sequence length tensors in unified SDPA node require cuDNN 9.24.0"};
+#if (CUDNN_VERSION >= 92400)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92400, cu_seq_len_cudnn_ver_error);
+
+ if (has_cu_seq_len_q()) {
+ auto cu_seq_len_Q = attributes.inputs.find(SDPA_attributes::input_names::CU_SEQ_LEN_Q)->second;
+ auto backend_cu_seq_len_Q = tensors[cu_seq_len_Q->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_CU_SEQ_LEN_QDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_cu_seq_len_Q));
+ }
+
+ if (has_cu_seq_len_kv()) {
+ auto cu_seq_len_KV = attributes.inputs.find(SDPA_attributes::input_names::CU_SEQ_LEN_KV)->second;
+ auto backend_cu_seq_len_KV =
+ tensors[cu_seq_len_KV->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_CU_SEQ_LEN_KVDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_cu_seq_len_KV));
+ }
+#else
+ return cu_seq_len_cudnn_ver_error;
+#endif
+ }
+
+ // Ignore attributes.max_seq_len_kv, because unified engine doesn't need it (it's harmless if set).
+
+ // Ignore attributes.padding_mask, because unified engine already applies an implicit padding mask
+ // if either (seq_len_Q and seq_len_KV) or (cu_seq_len_Q and cu_seq_len_KV) are provided.
+ // We already checked in `SDPA_attributes::validate_sdpa_support_surface()` that padding_mask
+ // must be true if and only if one of those pairs is set, so we don't need to check it here.
+#else
+ return paged_cudnn_ver_error;
+#endif
+ }
+
+ // Subgraph attributes
+ if (subgraph) {
+ auto subgraph_cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED,
+ "Subgraph attributes in unified SDPA node requires cuDNN 9.21.0"};
+#if (CUDNN_VERSION >= 92100)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92100, subgraph_cudnn_ver_error);
+
+ CHECK_CUDNN_FRONTEND_ERROR(attn::score_modifiers::build_operation_subgraph(subgraph));
+ auto subgraph_cudnn = std::static_pointer_cast<ICudnn>(subgraph);
+ auto backend_subgraph = subgraph_cudnn->get_operation_graph()->get_raw_desc();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_SUBGRAPH,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_subgraph));
+
+ auto subgraph_input_uid = subgraph_input->get_uid();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_SUBGRAPH_INPUT_UID,
+ CUDNN_TYPE_INT64,
+ 1,
+ &subgraph_input_uid));
+
+ auto subgraph_output_uid = subgraph_output->get_uid();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_SUBGRAPH_OUTPUT_UID,
+ CUDNN_TYPE_INT64,
+ 1,
+ &subgraph_output_uid));
+
+ // Add non-virtual uids from subgraph to uids_involved_in_operations
+ uids_involved_in_operations.insert(subgraph_cudnn->variant_pack_uids.begin(),
+ subgraph_cudnn->variant_pack_uids.end());
+#else
+ return subgraph_cudnn_ver_error;
+#endif
+ }
+
+ // Set unfuse_fma attribute (for SM100: use __fmul_rn + __fadd_rn instead of ffma2 in softmax)
+ if (attributes.unfuse_fma) {
+ auto unfuse_fma_cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Unfuse FMA in unified SDPA node requires cuDNN 9.21.0"};
+#if CUDNN_VERSION >= 92100
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92100, unfuse_fma_cudnn_ver_error);
+ bool unfuse_fma_value = true;
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_UNFUSE_FMA,
+ CUDNN_TYPE_BOOLEAN,
+ 1,
+ &unfuse_fma_value));
+#else
+ return unfuse_fma_cudnn_ver_error;
+#endif
+ }
+
+ // Dropout attributes
+ if (attributes.dropout_probability.has_value() && attributes.dropout_probability.value() != 0.0f) {
+ auto dropout_cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Dropout in unified SDPA node requires cuDNN 9.21.0"};
+#if (CUDNN_VERSION >= 92100)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92100, dropout_cudnn_ver_error);
+
+ float dropout_prob = attributes.dropout_probability.value();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_DROPOUT_PROBABILITY,
+ CUDNN_TYPE_FLOAT,
+ 1,
+ &dropout_prob));
+
+ auto seed_it = attributes.inputs.find(SDPA_attributes::input_names::Seed);
+ if (seed_it != attributes.inputs.end() && seed_it->second != nullptr) {
+ auto backend_seed = tensors[seed_it->second->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_DROPOUT_SEED_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_seed));
+ }
+
+ auto offset_it = attributes.inputs.find(SDPA_attributes::input_names::Offset);
+ if (offset_it != attributes.inputs.end() && offset_it->second != nullptr) {
+ auto backend_offset = tensors[offset_it->second->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_DROPOUT_OFFSET_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_offset));
+ }
+
+ auto rng_dump_it = attributes.outputs.find(SDPA_attributes::output_names::RNG_DUMP);
+ if (rng_dump_it != attributes.outputs.end() && rng_dump_it->second != nullptr) {
+ auto backend_rng_dump = tensors[rng_dump_it->second->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SDPA_FWD_DROPOUT_RNG_DUMP_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_rng_dump));
+ }
+#else
+ return dropout_cudnn_ver_error;
+#endif
+ }
+
+ // FP8 per-tensor scaling attributes (descale Q/K/V/S, scale S/O inputs; amax S/O outputs).
+ if (attributes.mma_core_mode == DataType_t::FP8_E4M3 || attributes.mma_core_mode == DataType_t::FP8_E5M2) {
+ auto fp8_cudnn_ver_error =
+ error_t{error_code_t::GRAPH_NOT_SUPPORTED, "FP8/MXFP8 for the unified SDPA node requires cuDNN 9.30.0"};
+#if (CUDNN_VERSION >= 93000)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(93000, fp8_cudnn_ver_error);
+
+ // Wire an optional FP8 scaling/descaling tensor (from either the input or output map) to
+ // its backend descriptor, no-op if the caller did not provide it.
+ auto set_fp8_desc = [&](auto const& tensor_map, auto name, cudnnBackendAttributeName_t attr) -> error_t {
+ auto it = tensor_map.find(name);
+ if (it != tensor_map.end() && it->second != nullptr) {
+ auto backend_desc = tensors[it->second->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(unified_sdpa_operation->get_backend_descriptor(),
+ attr,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_desc));
+ }
+ return {error_code_t::OK, ""};
+ };
+
+ CHECK_CUDNN_FRONTEND_ERROR(set_fp8_desc(attributes.inputs,
+ SDPA_attributes::input_names::Descale_Q,
+ CUDNN_ATTR_OPERATION_SDPA_FWD_DESCALE_QDESC));
+ CHECK_CUDNN_FRONTEND_ERROR(set_fp8_desc(attributes.inputs,
+ SDPA_attributes::input_names::Descale_K,
+ CUDNN_ATTR_OPERATION_SDPA_FWD_DESCALE_KDESC));
+ CHECK_CUDNN_FRONTEND_ERROR(set_fp8_desc(attributes.inputs,
+ SDPA_attributes::input_names::Descale_V,
+ CUDNN_ATTR_OPERATION_SDPA_FWD_DESCALE_VDESC));
+ CHECK_CUDNN_FRONTEND_ERROR(set_fp8_desc(attributes.inputs,
+ SDPA_attributes::input_names::Descale_S,
+ CUDNN_ATTR_OPERATION_SDPA_FWD_DESCALE_SDESC));
+ CHECK_CUDNN_FRONTEND_ERROR(set_fp8_desc(
+ attributes.inputs, SDPA_attributes::input_names::Scale_S, CUDNN_ATTR_OPERATION_SDPA_FWD_SCALE_SDESC));
+ CHECK_CUDNN_FRONTEND_ERROR(set_fp8_desc(
+ attributes.inputs, SDPA_attributes::input_names::Scale_O, CUDNN_ATTR_OPERATION_SDPA_FWD_SCALE_ODESC));
+ CHECK_CUDNN_FRONTEND_ERROR(set_fp8_desc(
+ attributes.outputs, SDPA_attributes::output_names::Amax_S, CUDNN_ATTR_OPERATION_SDPA_FWD_AMAX_SDESC));
+ CHECK_CUDNN_FRONTEND_ERROR(set_fp8_desc(
+ attributes.outputs, SDPA_attributes::output_names::Amax_O, CUDNN_ATTR_OPERATION_SDPA_FWD_AMAX_ODESC));
+#else
+ return fp8_cudnn_ver_error;
+#endif // CUDNN_VERSION >= 93000
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(unified_sdpa_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(unified_sdpa_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif // CUDNN_VERSION >= 91301
+ }
+
+ protected:
+ std::shared_ptr<Graph> subgraph; // Pre-softmax subgraph
+ std::shared_ptr<Tensor_attributes> subgraph_input;
+ std::shared_ptr<Tensor_attributes> subgraph_output;
+ std::shared_ptr<UnifiedSoftmaxNode> softmax_node; // Softmax descriptor for BE >= 9.21
+
+ void
+ init_subgraph() {
+ subgraph = std::make_shared<Graph>();
+ auto subgraph_node = std::static_pointer_cast<INode>(subgraph);
+ subgraph_node->context = context;
+ subgraph_input = std::make_shared<Tensor_attributes>();
+ subgraph_input->set_is_virtual(true);
+ subgraph_input->set_name(attributes.name + "::subgraph_input");
+ auto b = attributes.inputs[input_names::Q]->get_dim()[0];
+ auto h_q = attributes.inputs[input_names::Q]->get_dim()[1];
+ auto s_q = attributes.inputs[input_names::Q]->get_dim()[2];
+ auto s_kv = infer_s_kv();
+ subgraph_input->set_dim({b, h_q, s_q, s_kv});
+ subgraph_input->set_stride({h_q * s_q * s_kv, s_q * s_kv, s_kv, 1});
+ subgraph_output = subgraph_input;
+ }
+};
+
+} // namespace cudnn_frontend::graph
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/sdpa_fp8_bwd.h b/deps/cudnn-frontend/include/cudnn_frontend/node/sdpa_fp8_bwd.h
new file mode 100644
index 0000000..0cec5a8
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/sdpa_fp8_bwd.h
@@ -0,0 +1,1172 @@
+#pragma once
+
+#include "../../cudnn_frontend_Heuristics.h"
+#include "../../cudnn_frontend_Logging.h"
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+#include "diagonal_band_mask.h"
+#include "matmul_fp8.h"
+#include "pointwise.h"
+#include "reduction.h"
+#include "softmax.h"
+#include "block_scale_dequantize.h"
+#include "scaled_dot_product_flash_attention.h" // For promote_1d_index_tensor_to_4d()
+
+namespace cudnn_frontend::graph {
+
+class SDPAFP8BackwardNode : public NodeCRTP<SDPAFP8BackwardNode> {
+ using input_names = SDPA_fp8_backward_attributes::input_names;
+ using output_names = SDPA_fp8_backward_attributes::output_names;
+
+ private:
+ mutable bool is_deterministic_algorithm_supported_on_blackwell = false; // Will be edited in pre_validate_node()
+
+ // Promote any 1-D seq_len / ragged-offset index tensors to the 4-D
+ // [n, 1, 1, 1] form the cuDNN backend requires (see promote_1d_index_tensor_to_4d).
+ void
+ promote_index_tensors_to_4d() {
+ // TODO: Handle CU_SEQ_LEN_Q and CU_SEQ_LEN_KV once fp8 bprop supports these.
+ for (auto& key : {input_names::SEQ_LEN_Q, input_names::SEQ_LEN_KV}) {
+ auto const it = attributes.inputs.find(key);
+ if (it != attributes.inputs.end()) {
+ promote_1d_index_tensor_to_4d(it->second);
+ }
+ }
+ for (auto& [key, value] : attributes.inputs) {
+ CUDNN_FRONTEND_UNUSED(key);
+ if (value != nullptr) {
+ promote_1d_index_tensor_to_4d(value->get_ragged_offset());
+ }
+ }
+ for (auto& [key, value] : attributes.outputs) {
+ CUDNN_FRONTEND_UNUSED(key);
+ if (value != nullptr) {
+ promote_1d_index_tensor_to_4d(value->get_ragged_offset());
+ }
+ }
+ }
+
+ public:
+ mutable SDPA_fp8_backward_attributes
+ attributes; // mutable to allow auto-routing to deterministic in pre_validate_node()
+
+ SDPAFP8BackwardNode(SDPA_fp8_backward_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::COMPOSITE;
+ }
+
+ // Helper function to detect MXFP8 (microscaling FP8) mode
+ // MXFP8 uses block-wise scale factors with E8M0 data type and F8_128x4 reordering
+ // When detected, we use block_scale_dequantize before matmuls instead of pointwise descale after
+ bool
+ is_mxfp8_scaling() const {
+ auto descale_q_it = attributes.inputs.find(input_names::Descale_Q);
+ if (descale_q_it == attributes.inputs.end() || descale_q_it->second == nullptr) {
+ return false;
+ }
+ auto const& descale_q = descale_q_it->second;
+ return (descale_q->get_data_type() == DataType_t::FP8_E8M0 &&
+ descale_q->get_reordering_type() == TensorReordering_t::F8_128x4);
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating SDPAFP8BackwardNode " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90100,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 backward operation is only supported starting cudnn 9.1.0. Please "
+ "consider upgrading your current version.");
+
+ // Bug workaround for 9.10.0 (TE constraint)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::get_backend_version() == 91000,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 backward operation is not supported on cudnn 9.10.0 due to known bugs. "
+ "Please consider upgrading to 9.10.2 or newer.");
+
+ CHECK_CUDNN_FRONTEND_ERROR(context.populate_sm_version_from_device());
+ int32_t const sm_version = context.get_sm_version();
+ int32_t const prop_major = sm_version / 10;
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ prop_major < 9,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 forward operation is only supported on Hopper architecture and newer. Please "
+ "consider using a newer architecture.");
+
+ // check that Q, K, V, O, stats, dO, dQ, dK, dV tensors has been assigned
+ // check that dim and strides has been assigned and last stride is 1
+#define CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(port, port_map) \
+ { \
+ std::shared_ptr<Tensor_attributes> tensor_ptr = port_map.at(port); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF(tensor_ptr->get_dim().size() != 4, \
+ error_code_t::ATTRIBUTE_NOT_SET, \
+ "The dim for " + std::string(#port) + " is invalid"); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF(tensor_ptr->get_stride().size() != 4, \
+ error_code_t::ATTRIBUTE_NOT_SET, \
+ "The stride for " + std::string(#port) + " is invalid"); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF( \
+ tensor_ptr->get_stride()[3] != 1, \
+ error_code_t::GRAPH_NOT_SUPPORTED, \
+ "The stride for the last dimension corresponding to the embedding size per head should be 1 for " + \
+ std::string(#port)); \
+ }
+
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::Q, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::K, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::V, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::O, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::Stats, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(input_names::dO, attributes.inputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(output_names::dQ, attributes.outputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(output_names::dK, attributes.outputs);
+ CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE(output_names::dV, attributes.outputs);
+
+#undef CUDNN_FE_SDPA_VALIDATE_DIM_STRIDE
+
+ // validate backend limitations for the operation
+ // clang-format off
+ int64_t s_q = attributes.inputs.at(input_names::Q)->get_dim()[2];
+ int64_t s_kv = attributes.inputs.at(input_names::K)->get_dim()[2];
+ int64_t h_q = attributes.inputs.at(input_names::Q)->get_dim()[1];
+ int64_t h_k = attributes.inputs.at(input_names::K)->get_dim()[1];
+ int64_t h_v = attributes.inputs.at(input_names::V)->get_dim()[1];
+ int64_t d_qk = attributes.inputs.at(input_names::Q)->get_dim()[3];
+ int64_t d_v = attributes.inputs.at(input_names::V)->get_dim()[3];
+
+ auto const& dq_tensor = attributes.outputs.at(output_names::dQ);
+ auto const& dq_data_type = dq_tensor->get_data_type();
+ auto const& dk_tensor = attributes.outputs.at(output_names::dK);
+ auto const& dk_data_type = dk_tensor->get_data_type();
+ auto const& dv_tensor = attributes.outputs.at(output_names::dV);
+ auto const& dv_data_type = dv_tensor->get_data_type();
+
+ auto const& bias_mask = attributes.inputs.find(input_names::Bias);
+ bool const is_bias = (bias_mask != attributes.inputs.end() && bias_mask->second != nullptr);
+
+ auto const& dropout_mask = attributes.inputs.find(input_names::Dropout_mask);
+ bool const is_dropout_custom = (dropout_mask != attributes.inputs.end()) && (dropout_mask->second != nullptr);
+ bool const is_dropout = attributes.dropout_probability.has_value();
+ bool const is_ragged =
+ attributes.inputs.at(input_names::Q)->get_ragged_offset() ||
+ attributes.inputs.at(input_names::K)->get_ragged_offset() ||
+ attributes.inputs.at(input_names::V)->get_ragged_offset() ||
+ attributes.inputs.at(input_names::O)->get_ragged_offset() ||
+ attributes.inputs.at(input_names::Stats)->get_ragged_offset() ||
+ attributes.inputs.at(input_names::dO)->get_ragged_offset() ||
+ attributes.outputs.at(output_names::dQ)->get_ragged_offset() ||
+ attributes.outputs.at(output_names::dK)->get_ragged_offset() ||
+ attributes.outputs.at(output_names::dV)->get_ragged_offset();
+
+ // validation TODO:
+ // - validate stats has valid dims
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF((prop_major == 9) && is_ragged,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 backward with THD is not supported on Hopper architecture.");
+
+ // validate basic dimension requirements
+ if(prop_major >= 10) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(((d_qk > 128) || (d_qk % 16 != 0)) && !(d_qk == 192 && d_v == 128),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "hidden_dim d_qk shoud be less than or equal to 128 and hidden_dim d_qk should be multiple of 16 unless d_qk == 192 and d_v == 128");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(((d_v > 128) || (d_v % 16 != 0)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "hidden_dim d_v shoud be less than or equal to 128 and hidden_dim d_v should be multiple of 16");
+ }
+ else {
+ RETURN_CUDNN_FRONTEND_ERROR_IF((d_qk != 128) || (d_qk % 16 != 0) || (d_v != 128) || (d_v % 16 != 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "hidden_dim shoud be equal to 128 and hidden_dim should be multiple of 16");
+ }
+ RETURN_CUDNN_FRONTEND_ERROR_IF((h_q % h_k != 0) || (h_q % h_v != 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "For group-query attention, number of heads for key and query must be a factor of number of heads for query");
+
+ // validate options for attn_scale
+ auto const& attn_scale = attributes.inputs.find(input_names::Attn_scale);
+ bool const has_attn_scale = (attn_scale != attributes.inputs.end()) && (attn_scale->second != nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_attn_scale && attributes.attn_scale_value.has_value(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "attn_scale with tensor and value cannot be set at the same time.");
+
+ // validate options for bias mask
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_bias && (bias_mask->second->get_data_type() == DataType_t::BOOLEAN),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bias mask data type cannot be boolean");
+
+ // validate options for padding mask
+ auto const& seq_len_q = attributes.inputs.find(input_names::SEQ_LEN_Q);
+ bool const has_seq_len_q = (seq_len_q != attributes.inputs.end()) && (seq_len_q->second != nullptr);
+ auto const& seq_len_kv = attributes.inputs.find(input_names::SEQ_LEN_KV);
+ bool const has_seq_len_kv = (seq_len_kv != attributes.inputs.end()) && (seq_len_kv->second != nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.padding_mask && (!has_seq_len_q || !has_seq_len_kv),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Padding mask requires seq_len_q and seq_len_kv to be set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF((!attributes.padding_mask) && (has_seq_len_q || has_seq_len_kv),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "seq_len_q and seq_len_kv needs to be set only if padding mask is enabled.");
+
+ // validate options for dropout mask
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.dropout_probability.has_value() && is_dropout_custom,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Using both, custom dropout mask and internal-mask generation using dropout probability, is ill-formed.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.dropout_probability.has_value() && attributes.dropout_probability.value() == 1.0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Dropout probability cannot be 1 as corresponding scale wont be well formed.");
+
+ // Validate options for causal_mask_bottom_right
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.has_causal_mask_bottom_right() && detail::get_backend_version() < 90700,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "For cuDNN version below 9.7.0, bottom right causal masking is not supported.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.has_causal_mask_bottom_right() && prop_major < 10,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 forward operation is only supported on Blackwell architecture and newer. Please "
+ "consider using a newer architecture.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.has_causal_mask_bottom_right() && s_q > s_kv,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bottom right causal mask does not support s_q > s_kv. Please virtually slice the Q tensor and pass it as s_q == s_kv");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.has_causal_mask_bottom_right() && (is_bias || is_dropout),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bottom right causal mask is only supported with is_bias=False, is_dropout=False.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(attributes.has_causal_mask_bottom_right() && ((s_q % 64 != 0) || (s_kv % 64 != 0)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bottom right causal mask is only supported with s_q multiple of 64, and s_kv multiple of 64");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.left_bound.has_value() && (!attributes.padding_mask) && s_q > s_kv,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Sliding window attention is only supported with max_s_q <= max_s_kv.");
+
+ // validate that datatype is set for the graph
+ RETURN_CUDNN_FRONTEND_ERROR_IF(context.get_intermediate_data_type() == DataType_t::NOT_SET,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Intermediate tensor data type needs to be set as internal tensors require it.");
+
+ // Auto-route to deterministic algorithm for cases where non-deterministic is not supported on Blackwell:
+ // 1. MXFP8 backward - requires deterministic (STAGES=2)
+ // 2. FP8 backward with d_qk <= 192 and d_v <= 128 - requires deterministic
+ bool const is_mxfp8 = is_mxfp8_scaling();
+ bool const is_supported_dims = (d_qk <= 192) && (d_v <= 128);
+ if ((prop_major == 10) && !attributes.is_deterministic_algorithm) {
+ if (is_mxfp8) {
+ getLogger() << "[cudnn_frontend] INFO: MXFP8 SDPA backward detected on Blackwell - "
+ << "auto-routing to deterministic algorithm (non-deterministic not supported for MXFP8)"
+ << std::endl;
+ attributes.is_deterministic_algorithm = true;
+ } else if (is_supported_dims) {
+ getLogger() << "[cudnn_frontend] INFO: FP8 SDPA backward with d_qk=" << d_qk << ", d_v=" << d_v
+ << " detected on Blackwell - auto-routing to deterministic algorithm"
+ << std::endl;
+ attributes.is_deterministic_algorithm = true;
+ }
+ }
+
+ // validate options for deterministic algorithm
+ if (attributes.is_deterministic_algorithm && (prop_major == 10)) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF((detail::get_backend_version() < 91900),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "FP8 deterministic algorithm (required for MXFP8 and d_qk=192/d_v=128) is not supported on Blackwell with cuDNN version below 9.19.0");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_dropout,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "FP8 deterministic algorithm (required for MXFP8 and d_qk=192/d_v=128) is not supported on Blackwell when dropout is enabled");
+
+ is_deterministic_algorithm_supported_on_blackwell = true;
+ }
+
+ // if output data type is half or bfloat16 for any of dq, dk, dv, and version is below 9.13 or is not blackwell, return NOT_SUPPORTED
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (dq_data_type == DataType_t::HALF || dq_data_type == DataType_t::BFLOAT16 ||
+ dk_data_type == DataType_t::HALF || dk_data_type == DataType_t::BFLOAT16 ||
+ dv_data_type == DataType_t::HALF || dv_data_type == DataType_t::BFLOAT16) &&
+ (detail::get_backend_version() < 91300 || prop_major < 10),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 backward with HALF/BFLOAT16 output is only supported on Blackwell architecture "
+ "with cuDNN version 9.13.0 and newer.");
+
+ // Validate MXFP8 scale factors if present
+ if (is_mxfp8_scaling()) {
+ // MXFP8 requires cuDNN 9.21.0 or later
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 92100,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "MXFP8 SDPA requires cuDNN 9.21.0 or later");
+ int64_t const b = attributes.inputs.at(input_names::Q)->get_dim()[0];
+
+ // MXFP8 block size is fixed at 32
+ constexpr int64_t block_size = 32;
+ int64_t const d_qk_scale = (d_qk + block_size - 1) / block_size;
+ int64_t const d_v_scale = (d_v + block_size - 1) / block_size;
+ int64_t const s_q_scale = (s_q + block_size - 1) / block_size;
+ int64_t const s_kv_scale = (s_kv + block_size - 1) / block_size;
+
+ // Validate Descale_Q
+ auto const& descale_q = attributes.inputs.at(input_names::Descale_Q);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_q->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_Q to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_q->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_Q to have F8_128x4 reordering");
+
+ // Validate Descale_Q_T
+ auto const& descale_q_T = attributes.inputs.at(input_names::Descale_Q_T);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_q_T->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_Q_T to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_q_T->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_Q_T to have F8_128x4 reordering");
+
+ // Validate Descale_K
+ auto const& descale_k = attributes.inputs.at(input_names::Descale_K);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_k->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_K to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_k->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_K to have F8_128x4 reordering");
+
+ // Validate Descale_K_T
+ auto const& descale_k_T = attributes.inputs.at(input_names::Descale_K_T);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_k_T->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_K_T to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_k_T->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_K_T to have F8_128x4 reordering");
+
+ // Validate Descale_V
+ auto const& descale_v = attributes.inputs.at(input_names::Descale_V);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_v->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_V to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_v->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_V to have F8_128x4 reordering");
+
+ // Validate Descale_dO
+ auto const& descale_do = attributes.inputs.at(input_names::Descale_dO);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_do->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_dO to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_do->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_dO to have F8_128x4 reordering");
+
+ // Validate Descale_dO_T
+ auto const& descale_do_T = attributes.inputs.at(input_names::Descale_dO_T);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_do_T->get_data_type() != DataType_t::FP8_E8M0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_dO_T to have FP8_E8M0 data type");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(descale_do_T->get_reordering_type() != TensorReordering_t::F8_128x4,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA requires Descale_dO_T to have F8_128x4 reordering");
+
+ // Validate dimension consistency for SF_Q: [b, h_q, s_q_padded, d_scale_padded]
+ auto const& sf_q_dim = descale_q->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_q_dim[0] != b || sf_q_dim[1] != h_q,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_Q batch/head dimensions must match Q");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_q_dim[3] < d_qk_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_Q d_scale dimension too small (expected >= " + std::to_string(d_qk_scale) + ")");
+
+ // Validate dimension consistency for SF_Q_T: [b, h_q, s_q_scale_padded, d_padded]
+ auto const& sf_q_T_dim = descale_q_T->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_q_T_dim[0] != b || sf_q_T_dim[1] != h_q,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_Q_T batch/head dimensions must match Q");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_q_T_dim[2] < s_q_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_Q_T s_scale dimension too small (expected >= " + std::to_string(s_q_scale) + ")");
+
+ // Validate dimension consistency for SF_K: [b, h_k, s_kv_padded, d_qk_scale_padded]
+ auto const& sf_k_dim = descale_k->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_k_dim[0] != b || sf_k_dim[1] != h_k,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_K batch/head dimensions must match K");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_k_dim[3] < d_qk_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_K d_scale dimension too small (expected >= " + std::to_string(d_qk_scale) + ")");
+
+ // Validate dimension consistency for SF_K_T: [b, h_k, s_kv_scale_padded, d_qk_padded]
+ auto const& sf_k_T_dim = descale_k_T->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_k_T_dim[0] != b || sf_k_T_dim[1] != h_k,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_K_T batch/head dimensions must match K");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_k_T_dim[2] < s_kv_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_K_T s_scale dimension too small (expected >= " + std::to_string(s_kv_scale) + ")");
+
+ // Validate dimension consistency for SF_V: [b, h_v, s_kv_scale_padded, d_v_padded]
+ auto const& sf_v_dim = descale_v->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_v_dim[0] != b || sf_v_dim[1] != h_v,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_V batch/head dimensions must match V");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_v_dim[2] < s_kv_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_V s_scale dimension too small (expected >= " + std::to_string(s_kv_scale) + ")");
+
+ // Validate dimension consistency for SF_dO: [b, h_q, s_q_padded, d_v_scale_padded]
+ auto const& sf_do_dim = descale_do->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_do_dim[0] != b || sf_do_dim[1] != h_q,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_dO batch/head dimensions must match dO");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_do_dim[3] < d_v_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_dO d_scale dimension too small (expected >= " + std::to_string(d_v_scale) + ")");
+
+ // Validate dimension consistency for SF_dO_T: [b, h_q, s_q_scale_padded, d_scale_padded]
+ auto const& sf_do_T_dim = descale_do_T->get_dim();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(sf_do_T_dim[0] != b || sf_do_T_dim[1] != h_q,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_dO_T batch/head dimensions must match dO");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sf_do_T_dim[2] < s_q_scale,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "MXFP8 SDPA: Descale_dO_T s_scale dimension too small (expected >= " + std::to_string(s_q_scale) + ")");
+
+ // Log MXFP8 configuration for debugging
+ getLogger() << "[cudnn_frontend] INFO: MXFP8 SDPA configuration validated:" << std::endl
+ << " SF_Q dims: [" << sf_q_dim[0] << ", " << sf_q_dim[1] << ", " << sf_q_dim[2] << ", "
+ << sf_q_dim[3] << "]" << std::endl
+ << " SF_Q_T dims: [" << sf_q_T_dim[0] << ", " << sf_q_T_dim[1] << ", " << sf_q_T_dim[2] << ", "
+ << sf_q_T_dim[3] << "]" << std::endl
+ << " SF_K dims: [" << sf_k_dim[0] << ", " << sf_k_dim[1] << ", " << sf_k_dim[2] << ", "
+ << sf_k_dim[3] << "]" << std::endl
+ << " SF_K_T dims: [" << sf_k_T_dim[0] << ", " << sf_k_T_dim[1] << ", " << sf_k_T_dim[2] << ", "
+ << sf_k_T_dim[3] << "]" << std::endl
+ << " SF_V dims: [" << sf_v_dim[0] << ", " << sf_v_dim[1] << ", " << sf_v_dim[2] << ", "
+ << sf_v_dim[3] << "]" << std::endl
+ << " SF_dO dims: [" << sf_do_dim[0] << ", " << sf_do_dim[1] << ", " << sf_do_dim[2] << ", "
+ << sf_do_dim[3] << "]" << std::endl
+ << " SF_dO_T dims: [" << sf_do_T_dim[0] << ", " << sf_do_T_dim[1] << ", " << sf_do_T_dim[2] << ", "
+ << sf_do_T_dim[3] << "]" << std::endl
+ << " Expected d_qk_scale: " << d_qk_scale << ", d_v_scale: " << d_v_scale
+ << ", s_q_scale: " << s_q_scale << ", s_kv_scale: " << s_kv_scale << std::endl;
+ }
+
+ // validate options for sink token
+ auto const& sink_token = attributes.inputs.find(input_names::SINK_TOKEN);
+ bool const has_sink_token = (sink_token != attributes.inputs.end()) && (sink_token->second != nullptr);
+ auto const& dsink_token = attributes.outputs.find(output_names::DSINK_TOKEN);
+ bool const has_dsink_token = (dsink_token != attributes.outputs.end()) && (dsink_token->second != nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_dsink_token && !has_sink_token,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "If dSink_token output is requested, sink_token input must also be set.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ infer_properties_node() override final {
+ // If a 1-D length/offset index tensor [n] is supplied, promote it to the 4-D
+ // [n, 1, 1, 1] form the cuDNN backend requires.
+ promote_index_tensors_to_4d();
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ expand_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for Scaled_dot_product_flash_attention node "
+ << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // Gather dim to fill properties of virtual tensors
+ auto const& q_dim = attributes.inputs[input_names::Q]->get_dim();
+ auto b = q_dim[0];
+ auto h_q = q_dim[1];
+ auto s_q = q_dim[2];
+ auto d_qk = q_dim[3];
+ auto const& k_dim = attributes.inputs[input_names::K]->get_dim();
+ auto h_k = k_dim[1];
+ auto s_kv = k_dim[2];
+ auto const& v_dim = attributes.inputs[input_names::V]->get_dim();
+ auto h_v = v_dim[1];
+ auto d_v = v_dim[3];
+
+ bool const use_mxfp8 = is_mxfp8_scaling();
+ std::shared_ptr<Tensor_attributes> eff_Q, eff_K, eff_V, eff_dO;
+
+ // cuDNN frontend API attention requires Q, K, V where
+ // Q = {b, h_q, s_q, d_qk}
+ // K = {b, h_k, s_kv, d_qk}
+ // V = {b, h_v, s_kv, d_v}
+ // but cuDNN backend API attention requires Q, KT, VT
+ // Q = {b, h_q, s_q, d_qk}
+ // KT = {b, h_k, d_qk, s_kv}
+ // VT = {b, h_v, d_v, s_kv}
+ // So the code below maps the K->KT and V->VT
+ if (use_mxfp8) {
+ // MXFP8 2-kernel bprop: Each tensor is dequantized separately for each matmul it participates in.
+ // Q, K, dO each need two dequantizations with different scale factors.
+ // O and dO are used directly (as f16) for the dO*O computation without dequantization.
+
+ // K for BMM1 (Q@K.T): Transpose K and SF_K, then dequantize
+ std::vector<int64_t> kt_dim = attributes.inputs[input_names::K]->get_dim();
+ std::vector<int64_t> kt_stride = attributes.inputs[input_names::K]->get_stride();
+ std::swap(kt_dim[2], kt_dim[3]);
+ std::swap(kt_stride[2], kt_stride[3]);
+ attributes.inputs[input_names::K]->set_dim(kt_dim);
+ attributes.inputs[input_names::K]->set_stride(kt_stride);
+
+ auto& sf_k = attributes.inputs[input_names::Descale_K];
+ std::vector<int64_t> sf_k_dim = sf_k->get_dim();
+ std::vector<int64_t> sf_k_stride = sf_k->get_stride();
+ std::swap(sf_k_dim[2], sf_k_dim[3]);
+ std::swap(sf_k_stride[2], sf_k_stride[3]);
+ sf_k->set_dim(sf_k_dim);
+ sf_k->set_stride(sf_k_stride);
+
+ auto dequant_k_dqk_attrs = Block_scale_dequantize_attributes()
+ .set_name("DQ_K_dqk")
+ .set_block_size({1, 32});
+ auto k_dqk_dequant = std::make_shared<Tensor_attributes>();
+ k_dqk_dequant->set_is_virtual(true);
+ k_dqk_dequant->set_dim(kt_dim);
+ k_dqk_dequant->set_stride(kt_stride);
+ block_scale_dequantize(attributes.inputs[input_names::K], sf_k, dequant_k_dqk_attrs, k_dqk_dequant);
+ eff_K = k_dqk_dequant;
+
+ // V for dO@V.T: Transpose V and SF_V, then dequantize
+ std::vector<int64_t> vt_dim = attributes.inputs[input_names::V]->get_dim();
+ std::vector<int64_t> vt_stride = attributes.inputs[input_names::V]->get_stride();
+ std::swap(vt_dim[2], vt_dim[3]);
+ std::swap(vt_stride[2], vt_stride[3]);
+ attributes.inputs[input_names::V]->set_dim(vt_dim);
+ attributes.inputs[input_names::V]->set_stride(vt_stride);
+
+ auto& sf_v = attributes.inputs[input_names::Descale_V];
+ std::vector<int64_t> sf_v_dim = sf_v->get_dim();
+ std::vector<int64_t> sf_v_stride = sf_v->get_stride();
+ std::swap(sf_v_dim[2], sf_v_dim[3]);
+ std::swap(sf_v_stride[2], sf_v_stride[3]);
+ sf_v->set_dim(sf_v_dim);
+ sf_v->set_stride(sf_v_stride);
+
+ auto dequant_v_dv_attrs = Block_scale_dequantize_attributes()
+ .set_name("DQ_V_dv")
+ .set_block_size({1, 32});
+ auto v_dv_dequant = std::make_shared<Tensor_attributes>();
+ v_dv_dequant->set_is_virtual(true);
+ v_dv_dequant->set_dim(vt_dim);
+ v_dv_dequant->set_stride(vt_stride);
+ block_scale_dequantize(attributes.inputs[input_names::V], sf_v, dequant_v_dv_attrs, v_dv_dequant);
+ eff_V = v_dv_dequant;
+
+ // Q for BMM1 (Q@K.T): Dequantize Q with Descale_Q
+ auto dequant_q_dqk_attrs = Block_scale_dequantize_attributes()
+ .set_name("DQ_Q_dqk")
+ .set_block_size({1, 32});
+ auto q_dqk_dequant = std::make_shared<Tensor_attributes>();
+ q_dqk_dequant->set_is_virtual(true);
+ q_dqk_dequant->set_dim(attributes.inputs[input_names::Q]->get_dim());
+ q_dqk_dequant->set_stride(attributes.inputs[input_names::Q]->get_stride());
+ block_scale_dequantize(attributes.inputs[input_names::Q],
+ attributes.inputs[input_names::Descale_Q],
+ dequant_q_dqk_attrs,
+ q_dqk_dequant);
+ eff_Q = q_dqk_dequant;
+
+ // dO for dO@V.T: Dequantize dO with Descale_dO
+ auto dequant_dO_dv_attrs = Block_scale_dequantize_attributes()
+ .set_name("DQ_dO_dv")
+ .set_block_size({1, 32});
+ auto dO_dv_dequant = std::make_shared<Tensor_attributes>();
+ dO_dv_dequant->set_is_virtual(true);
+ dO_dv_dequant->set_dim(attributes.inputs[input_names::dO]->get_dim());
+ dO_dv_dequant->set_stride(attributes.inputs[input_names::dO]->get_stride());
+ block_scale_dequantize(attributes.inputs[input_names::dO],
+ attributes.inputs[input_names::Descale_dO],
+ dequant_dO_dv_attrs,
+ dO_dv_dequant);
+ eff_dO = dO_dv_dequant;
+
+ // Note: O and dO for the dO*O computation are used as raw f16 inputs (no MXFP8 dequant).
+ // The separate dequantizations for dO_seq, K_seq, Q_seq are done inline at their usage sites.
+ } else {
+ // Non-MXFP8
+ std::vector<int64_t> temp_vec;
+
+ temp_vec = attributes.inputs[input_names::K]->get_dim();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::K]->set_dim(temp_vec);
+
+ temp_vec = attributes.inputs[input_names::K]->get_stride();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::K]->set_stride(temp_vec);
+
+ temp_vec = attributes.inputs[input_names::V]->get_dim();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::V]->set_dim(temp_vec);
+
+ temp_vec = attributes.inputs[input_names::V]->get_stride();
+ std::swap(temp_vec[2], temp_vec[3]);
+ attributes.inputs[input_names::V]->set_stride(temp_vec);
+
+ eff_Q = attributes.inputs[input_names::Q];
+ eff_K = attributes.inputs[input_names::K];
+ eff_V = attributes.inputs[input_names::V];
+ eff_dO = attributes.inputs[input_names::dO];
+ }
+
+ std::shared_ptr<Tensor_attributes> rng_output;
+
+ auto mul_attributes = Pointwise_attributes().set_mode(PointwiseMode_t::MUL);
+
+ // if dropout_prob is used, then the node passes scale and scale inverse
+ // if dropout_mask is used, then the user passes scale and scale_inverse
+ bool is_dropout_prob = (attributes.dropout_probability.has_value());
+ bool is_dropout_mask = (attributes.inputs[input_names::Dropout_mask] != nullptr);
+ if (is_dropout_prob) {
+ float dropout_scale_value = 1.0f / (1.0f - attributes.dropout_probability.value());
+ float dropout_scale_inv_value = (1.0f - attributes.dropout_probability.value());
+
+ attributes.inputs[input_names::Dropout_scale] = std::make_shared<Tensor_attributes>(dropout_scale_value);
+ attributes.inputs[input_names::Dropout_scale_inv] =
+ std::make_shared<Tensor_attributes>(dropout_scale_inv_value);
+ }
+
+ // --------------RNG node--------------------
+
+ if (is_dropout_prob) {
+ rng_output = rng(attributes.inputs[input_names::Seed],
+ attributes.inputs[input_names::Offset],
+ Rng_attributes()
+ .set_name("rng")
+ .set_distribution(RngDistribution_t::BERNOULLI)
+ .set_bernoulli_probability(1.0f - attributes.dropout_probability.value()));
+ rng_output->set_dim({b, h_q, s_q, s_kv}).set_stride({h_q * s_q * s_kv, s_q * s_kv, s_kv, 1});
+ } else if (is_dropout_mask) {
+ rng_output = attributes.inputs[input_names::Dropout_mask];
+ }
+
+ //// dO * O
+ // For MXFP8: dO_f16 and O (f16) are used directly (no block dequantization needed)
+ // For non-MXFP8 (17-arg API): dO and O (FP8) are used (per-tensor descale applied after reduction)
+ mul_attributes.set_name("mul_dO_O");
+ auto last_output = use_mxfp8
+ ? pointwise(attributes.inputs[input_names::dO_f16], attributes.inputs[input_names::O], mul_attributes)
+ : pointwise(attributes.inputs[input_names::dO], attributes.inputs[input_names::O], mul_attributes);
+
+ // reduce(dO)
+ last_output =
+ reduction(last_output, Reduction_attributes().set_name("reduce_dO").set_mode(ReductionMode_t::ADD));
+ last_output->set_dim({b, h_q, s_q, 1}).set_stride({h_q * s_q, s_q, 1, 1});
+
+ // Descale dO (only for non-MXFP8 per-tensor scaling)
+ if (!use_mxfp8) {
+ mul_attributes.set_name("descale_dO");
+ last_output = pointwise(last_output, attributes.inputs.at(input_names::Descale_dO), mul_attributes);
+ last_output->set_dim({b, h_q, s_q, 1}).set_stride({h_q * s_q, s_q, 1, 1});
+ }
+
+ // Descale O (only for non-MXFP8 per-tensor scaling)
+ if (!use_mxfp8) {
+ mul_attributes.set_name("descale_O");
+ last_output = pointwise(last_output, attributes.inputs.at(input_names::Descale_O), mul_attributes);
+ }
+
+ // dSink_token computation: dSink = sum(exp(sink - stats) * D) over batch and sequence
+ // Note: The backend kernel applies the negative sign internally.
+ auto const& sink_token_it = attributes.inputs.find(input_names::SINK_TOKEN);
+ auto const& dsink_token_it = attributes.outputs.find(output_names::DSINK_TOKEN);
+ if (dsink_token_it != attributes.outputs.end() && dsink_token_it->second != nullptr &&
+ sink_token_it != attributes.inputs.end() && sink_token_it->second != nullptr) {
+ // sub_sink = sink - stats
+ auto sub_sink = pointwise(sink_token_it->second,
+ attributes.inputs[input_names::Stats],
+ Pointwise_attributes().set_name("sub_sink_stats").set_mode(PointwiseMode_t::SUB));
+ sub_sink->set_dim({b, h_q, s_q, 1}).set_stride({h_q * s_q, s_q, 1, 1});
+
+ // exp_sink = exp(sub_sink)
+ auto exp_sink =
+ pointwise(sub_sink, Pointwise_attributes().set_name("exp_sink").set_mode(PointwiseMode_t::EXP));
+ exp_sink->set_dim({b, h_q, s_q, 1}).set_stride({h_q * s_q, s_q, 1, 1});
+
+ // per_token_grad = exp_sink * last_output (D)
+ auto per_token_grad = pointwise(
+ exp_sink, last_output, Pointwise_attributes().set_name("mul_exp_sink_D").set_mode(PointwiseMode_t::MUL));
+ per_token_grad->set_dim({b, h_q, s_q, 1}).set_stride({h_q * s_q, s_q, 1, 1});
+
+ // dSink = reduce(per_token_grad) over batch and sequence dimensions
+ reduction(per_token_grad,
+ Reduction_attributes().set_name("reduce_dSink").set_mode(ReductionMode_t::ADD),
+ dsink_token_it->second);
+ }
+
+ // softmax_sum = last_output * dropout_scale
+ // Note: When sink_token is enabled and dropout is NOT present, we still need a MUL operation
+ // in the softmax path so the backend pattern matcher (fortAttentionBackwardRuntimeFusionEngine)
+ // can correctly distinguish between the dSink chain (MUL→REDUCE) and the softmax path (MUL→SUB).
+ // Without this, the fallback at lines 3786-3796 incorrectly identifies dSink MUL as the softmax path.
+ bool const has_sink_token = (sink_token_it != attributes.inputs.end() && sink_token_it->second != nullptr);
+ if (attributes.inputs[input_names::Dropout_scale_inv]) {
+ last_output = pointwise(last_output,
+ attributes.inputs[input_names::Dropout_scale_inv],
+ Pointwise_attributes().set_name("scale_dropout_inv").set_mode(PointwiseMode_t::MUL));
+ } else if (has_sink_token) {
+ // Add identity MUL (multiply by 1) to create MUL→SUB pattern for pattern matcher
+ auto one_tensor = std::make_shared<Tensor_attributes>(1.0f);
+ last_output = pointwise(last_output,
+ one_tensor,
+ Pointwise_attributes().set_name("identity_for_sink").set_mode(PointwiseMode_t::MUL));
+ last_output->set_dim({b, h_q, s_q, 1}).set_stride({h_q * s_q, s_q, 1, 1});
+ }
+ auto softmax_sum = last_output;
+
+ //// Q * K
+ auto bmm_Q_K_attributes = Matmul_attributes().set_name("bmm_Q_K")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_Q])
+ .set_n_override(attributes.inputs[input_names::SEQ_LEN_KV]);
+ auto last_dV = matmul(eff_Q, eff_K, bmm_Q_K_attributes);
+
+ //// Optional Attn scale
+ // In case user provided a scalar value, do a fused scalar.
+ if (attributes.attn_scale_value.has_value()) {
+ attributes.inputs[input_names::Attn_scale] =
+ std::make_shared<Tensor_attributes>(attributes.attn_scale_value.value());
+ }
+
+ // If attn scale present, add a pointwise mul node
+ if (auto attn_scale_it = attributes.inputs.find(input_names::Attn_scale); attn_scale_it != attributes.inputs.end()) {
+ mul_attributes.set_name("attn_scale");
+ last_dV = pointwise(last_dV, attn_scale_it->second, mul_attributes);
+ }
+
+ // Descale Q (only for non-MXFP8 per-tensor scaling)
+ if (!use_mxfp8) {
+ mul_attributes.set_name("descale_q");
+ last_dV = pointwise(last_dV, attributes.inputs.at(input_names::Descale_Q), mul_attributes);
+ }
+
+ // Descale K (only for non-MXFP8 per-tensor scaling)
+ if (!use_mxfp8) {
+ mul_attributes.set_name("descale_k");
+ last_dV = pointwise(last_dV, attributes.inputs.at(input_names::Descale_K), mul_attributes);
+ }
+
+ // (optional) last_dV = last_dV + bias
+ if (auto bias_it = attributes.inputs.find(input_names::Bias); bias_it != attributes.inputs.end()) {
+ last_dV = pointwise(last_dV,
+ bias_it->second,
+ Pointwise_attributes().set_name("add_bias").set_mode(PointwiseMode_t::ADD));
+ }
+
+ // (optional) Apply padding mask
+ if (attributes.padding_mask) {
+ auto row_idx_output = pointwise(last_dV,
+ Pointwise_attributes()
+ .set_name("gen_row_idx_padding")
+ .set_mode(PointwiseMode_t::GEN_INDEX)
+ .set_axis(2)
+ .set_compute_data_type(DataType_t::INT32));
+ row_idx_output->set_data_type(DataType_t::INT32);
+
+ auto col_idx_output = pointwise(last_dV,
+ Pointwise_attributes()
+ .set_name("gen_col_idx_padding")
+ .set_mode(PointwiseMode_t::GEN_INDEX)
+ .set_axis(3)
+ .set_compute_data_type(DataType_t::INT32));
+ col_idx_output->set_data_type(DataType_t::INT32);
+
+ auto row_mask_output = pointwise(row_idx_output,
+ attributes.inputs[input_names::SEQ_LEN_Q],
+ Pointwise_attributes()
+ .set_name("lt_row_sq_padding")
+ .set_mode(PointwiseMode_t::CMP_LT)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ row_mask_output->set_data_type(DataType_t::BOOLEAN);
+
+ auto col_mask_output = pointwise(col_idx_output,
+ attributes.inputs[input_names::SEQ_LEN_KV],
+ Pointwise_attributes()
+ .set_name("lt_col_skv_padding")
+ .set_mode(PointwiseMode_t::CMP_LT)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ col_mask_output->set_data_type(DataType_t::BOOLEAN);
+
+ auto padding_mask_output = pointwise(row_mask_output,
+ col_mask_output,
+ Pointwise_attributes()
+ .set_name("and_row_col_padding")
+ .set_mode(PointwiseMode_t::LOGICAL_AND)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ padding_mask_output->set_data_type(DataType_t::BOOLEAN);
+
+ // Use a smaller value of neg infinity so that the softmax stats for rows that are fully padded dont
+ // go towards NaNs/Infs when multipled by the numerous scale/descale
+ auto negative_inf_padding = std::make_shared<Tensor_attributes>(attn::score_modifiers::get_negative_inf_value());
+
+ last_dV =
+ pointwise(last_dV,
+ negative_inf_padding,
+ padding_mask_output,
+ Pointwise_attributes().set_name("select_padding").set_mode(PointwiseMode_t::BINARY_SELECT));
+ }
+
+ // Apply (bottom-right) causal masking (with right bound) and/or set the left bound
+ if (attributes.left_bound.has_value() || attributes.right_bound.has_value()) {
+ auto graph_ = std::make_shared<Graph>();
+ std::shared_ptr<INode> node_ = std::static_pointer_cast<INode>(graph_);
+ node_->context = this->context;
+
+ auto s_kv_ptr = attributes.inputs.find(input_names::SEQ_LEN_KV) != attributes.inputs.end()
+ ? attributes.inputs[input_names::SEQ_LEN_KV]
+ : nullptr;
+ auto s_q_ptr = attributes.inputs.find(input_names::SEQ_LEN_Q) != attributes.inputs.end()
+ ? attributes.inputs[input_names::SEQ_LEN_Q]
+ : nullptr;
+
+ last_dV = attn::score_modifiers::sliding_window_mask(graph_,
+ last_dV,
+ attributes.diagonal_alignment,
+ attributes.left_bound,
+ attributes.right_bound,
+ s_q,
+ s_kv,
+ s_q_ptr,
+ s_kv_ptr,
+ /*cu_s_q_ptr=*/nullptr,
+ /*cu_s_kv_ptr=*/nullptr);
+ sub_nodes.emplace_back(std::move(node_));
+ }
+
+ //// Apply Softmax
+ // last_dV = last_dV - stats
+ last_dV = pointwise(last_dV,
+ attributes.inputs[input_names::Stats],
+ Pointwise_attributes().set_name("sub_dV_Stats").set_mode(PointwiseMode_t::SUB));
+
+ // last_dV = exp(last_dV)
+ last_dV = pointwise(last_dV, Pointwise_attributes().set_name("exp_dV").set_mode(PointwiseMode_t::EXP));
+ auto exp_S = last_dV;
+
+ // (optional) last_dV = last_dV * dropout rng_output
+ if (is_dropout_prob || is_dropout_mask) {
+ last_dV =
+ pointwise(last_dV,
+ rng_output,
+ Pointwise_attributes().set_name("mul_p_dropout_mask").set_mode(PointwiseMode_t::MUL));
+ }
+
+ // (optional) last_dV = last_dV * dropout_scale
+ if (attributes.inputs[input_names::Dropout_scale]) {
+ last_dV =
+ pointwise(last_dV,
+ attributes.inputs[input_names::Dropout_scale],
+ Pointwise_attributes().set_name("mul_dS_dropout_scale").set_mode(PointwiseMode_t::MUL));
+ }
+
+ // Scale S (only for non-MXFP8 per-tensor scaling; MXFP8 keeps P in fp32)
+ if (!use_mxfp8) {
+ mul_attributes.set_name("scale_S");
+ last_dV = pointwise(last_dV, attributes.inputs.at(input_names::Scale_S), mul_attributes);
+ last_dV->set_data_type(attributes.inputs.at(input_names::Q)->get_data_type());
+ }
+
+ // Reshape P
+ last_dV = reshape(last_dV, Reshape_attributes().set_name("S_transpose"));
+ last_dV->set_name("S_T").set_dim({b, h_q, s_kv, s_q}).set_stride({h_q * s_q * s_kv, s_q * s_kv, 1, s_kv});
+ if (!use_mxfp8) {
+ last_dV->set_data_type(attributes.inputs[input_names::Q]->get_data_type());
+ }
+
+ //// P.T @ dO -> dV
+ if (use_mxfp8) {
+ // MXFP8: Dequantize dO_T with Descale_dO_T for P.T@dO
+ auto dequant_dO_seq_attrs = Block_scale_dequantize_attributes()
+ .set_name("DQ_dO_seq")
+ .set_block_size({1, 32});
+ auto dO_seq_dequant = std::make_shared<Tensor_attributes>();
+ dO_seq_dequant->set_is_virtual(true);
+ dO_seq_dequant->set_dim(attributes.inputs[input_names::dO_T]->get_dim());
+ dO_seq_dequant->set_stride(attributes.inputs[input_names::dO_T]->get_stride());
+ block_scale_dequantize(attributes.inputs[input_names::dO_T],
+ attributes.inputs[input_names::Descale_dO_T],
+ dequant_dO_seq_attrs,
+ dO_seq_dequant);
+
+ auto bmm_S_T_dO_attributes = Matmul_attributes().set_name("bmm_S_T_dO")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_KV])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_Q]);
+ if (h_q == h_v) {
+ matmul(last_dV, dO_seq_dequant, bmm_S_T_dO_attributes, attributes.outputs[output_names::dV]);
+ } else {
+ auto dV_fullhead = matmul(last_dV, dO_seq_dequant, bmm_S_T_dO_attributes);
+ dV_fullhead->set_dim({b, h_q, s_kv, d_v});
+ dV_fullhead->set_stride({h_q * s_kv * d_v, s_kv * d_v, d_v, 1});
+ dV_fullhead->set_data_type(DataType_t::FLOAT);
+ reduction(dV_fullhead,
+ Reduction_attributes().set_name("red_dV_head").set_mode(ReductionMode_t::ADD),
+ attributes.outputs[output_names::dV]);
+ }
+
+ auto const& amax_dv = attributes.outputs.at(output_names::Amax_dV);
+ if (amax_dv != nullptr) {
+ auto amax_dv_attributes =
+ Reduction_attributes().set_name("amax_dV").set_mode(ReductionMode_t::AMAX);
+ reduction(attributes.outputs[output_names::dV], amax_dv_attributes, amax_dv);
+ }
+ } else {
+ matmul_fp8(last_dV,
+ attributes.inputs[input_names::dO],
+ attributes.inputs[input_names::Descale_S],
+ attributes.inputs[input_names::Descale_dO],
+ attributes.inputs[input_names::Scale_dV],
+ Matmul_fp8_attributes().set_name("bmm_S_T_dO")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_KV])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_Q]),
+ attributes.outputs[output_names::dV],
+ attributes.outputs[output_names::Amax_dV]);
+ }
+
+ //// dO * V_T
+ auto bmm_dO_V_T_attributes = Matmul_attributes().set_name("bmm_dO_V_T")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_Q])
+ .set_n_override(attributes.inputs[input_names::SEQ_LEN_KV]);
+ last_output = matmul(eff_dO, eff_V, bmm_dO_V_T_attributes);
+
+ // Descale dO (only for non-MXFP8 per-tensor scaling)
+ if (!use_mxfp8) {
+ mul_attributes.set_name("descale_dO");
+ last_output = pointwise(last_output, attributes.inputs.at(input_names::Descale_dO), mul_attributes);
+ }
+
+ // Descale V (only for non-MXFP8 per-tensor scaling)
+ if (!use_mxfp8) {
+ mul_attributes.set_name("descale_V");
+ last_output = pointwise(last_output, attributes.inputs.at(input_names::Descale_V), mul_attributes);
+ }
+
+ // dP = last_output - softmax_sum
+ auto dP = pointwise(last_output,
+ softmax_sum,
+ Pointwise_attributes().set_name("sub_dP_softmax_sum").set_mode(PointwiseMode_t::SUB));
+
+ // dP = dP * exp_S
+ mul_attributes.set_name("mul_dP_exp_S");
+ dP = pointwise(dP, exp_S, mul_attributes);
+
+ // (optional) dP = dP * dropout_scale
+ if (attributes.inputs[input_names::Dropout_scale]) {
+ dP =
+ pointwise(dP,
+ attributes.inputs[input_names::Dropout_scale],
+ Pointwise_attributes().set_name("mul_dS_dropout_scale").set_mode(PointwiseMode_t::MUL));
+ }
+
+ // if (attributes.outputs[output_names::dBias]) {
+ // reduction(dP,
+ // Reduction_attributes().set_name("red_dP_dBias").set_mode(ReductionMode_t::ADD),
+ // attributes.outputs[output_names::dBias]);
+ // }
+
+ // (optional) dP = dP * attn_scale
+ if (auto attn_scale_it = attributes.inputs.find(input_names::Attn_scale); attn_scale_it != attributes.inputs.end()) {
+ mul_attributes.set_name("mul_dS_attn_scale");
+ dP = pointwise(dP, attn_scale_it->second, mul_attributes);
+ }
+
+ // Amax dP and Scale dP (only for non-MXFP8 per-tensor scaling; MXFP8 keeps dS in fp32)
+ if (!use_mxfp8) {
+ auto amax_attributes = Reduction_attributes().set_name("amax_dP").set_mode(ReductionMode_t::AMAX);
+ reduction(dP, amax_attributes, attributes.outputs.at(output_names::Amax_dP));
+
+ mul_attributes.set_name("scale_dP");
+ dP = pointwise(dP, attributes.inputs.at(input_names::Scale_dP), mul_attributes);
+ dP->set_data_type(attributes.inputs.at(input_names::dO)->get_data_type());
+ }
+
+ //// dS @ K -> dQ
+ if (use_mxfp8) {
+ // MXFP8: Dequantize K_T with Descale_K_T (seq-dimension scaling) for dS@K -> dQ
+ auto dequant_K_seq_attrs = Block_scale_dequantize_attributes()
+ .set_name("DQ_K_seq")
+ .set_block_size({1, 32});
+ auto K_seq_dequant = std::make_shared<Tensor_attributes>();
+ K_seq_dequant->set_is_virtual(true);
+ K_seq_dequant->set_dim(attributes.inputs[input_names::K_T]->get_dim());
+ K_seq_dequant->set_stride(attributes.inputs[input_names::K_T]->get_stride());
+
+ int64_t s_kv_scale_padded = ((s_kv + 127) / 128) * 4;
+ auto& sf_k_T = attributes.inputs[input_names::Descale_K_T];
+ sf_k_T->set_stride({h_k * s_kv_scale_padded * 128, s_kv_scale_padded * 128, b * h_k * s_kv_scale_padded * 128, 1});
+
+ block_scale_dequantize(attributes.inputs[input_names::K_T],
+ attributes.inputs[input_names::Descale_K_T],
+ dequant_K_seq_attrs,
+ K_seq_dequant);
+
+ auto bmm_dS_K_attributes = Matmul_attributes().set_name("bmm_dS_K")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_Q])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_KV]);
+ matmul(dP, K_seq_dequant, bmm_dS_K_attributes, attributes.outputs[output_names::dQ]);
+
+ auto const& amax_dq = attributes.outputs.at(output_names::Amax_dQ);
+ if (amax_dq != nullptr) {
+ auto amax_dq_attributes =
+ Reduction_attributes().set_name("amax_dQ").set_mode(ReductionMode_t::AMAX);
+ reduction(attributes.outputs[output_names::dQ], amax_dq_attributes, amax_dq);
+ }
+ } else {
+ auto const& kt_dim = attributes.inputs[input_names::K]->get_dim();
+ auto const& kt_stride = attributes.inputs[input_names::K]->get_stride();
+
+ auto K = reshape(attributes.inputs[input_names::K], Reshape_attributes().set_name("reshape_K"));
+ K->set_dim({kt_dim[0], kt_dim[1], kt_dim[3], kt_dim[2]})
+ .set_stride({kt_stride[0], kt_stride[1], kt_stride[3], kt_stride[2]});
+
+ auto bmm_dP_K_attributes = Matmul_fp8_attributes().set_name("bmm_dP_K")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_Q])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_KV]);
+ matmul_fp8(dP,
+ K,
+ attributes.inputs[input_names::Descale_dP],
+ attributes.inputs[input_names::Descale_K],
+ attributes.inputs[input_names::Scale_dQ],
+ bmm_dP_K_attributes,
+ attributes.outputs[output_names::dQ],
+ attributes.outputs[output_names::Amax_dQ]);
+ }
+
+ //// dS.T * Q (transpose dS -> dS_reshape)
+ auto dP_T_attributes = Reshape_attributes().set_name("dP_T");
+ auto dP_T = reshape(dP, dP_T_attributes);
+ if (!use_mxfp8) {
+ dP_T->set_data_type(attributes.inputs.at(input_names::dO)->get_data_type());
+ }
+ dP_T->set_name("dP_T").set_dim({b, h_q, s_kv, s_q}).set_stride({h_q * s_q * s_kv, s_q * s_kv, 1, s_kv});
+
+ if (use_mxfp8) {
+ // MXFP8: Dequantize Q_T with Descale_Q_T (seq-dimension scaling) for dS.T@Q -> dK
+ auto dequant_Q_seq_attrs = Block_scale_dequantize_attributes()
+ .set_name("DQ_Q_seq")
+ .set_block_size({1, 32});
+ auto Q_seq_dequant = std::make_shared<Tensor_attributes>();
+ Q_seq_dequant->set_is_virtual(true);
+ Q_seq_dequant->set_dim(attributes.inputs[input_names::Q_T]->get_dim());
+ Q_seq_dequant->set_stride(attributes.inputs[input_names::Q_T]->get_stride());
+
+ int64_t s_q_scale_padded = ((s_q + 127) / 128) * 4;
+ auto& sf_q_T = attributes.inputs[input_names::Descale_Q_T];
+ sf_q_T->set_stride({h_q * s_q_scale_padded * 128, s_q_scale_padded * 128, b * h_q * s_q_scale_padded * 128, 1});
+
+ block_scale_dequantize(attributes.inputs[input_names::Q_T],
+ attributes.inputs[input_names::Descale_Q_T],
+ dequant_Q_seq_attrs,
+ Q_seq_dequant);
+
+ auto bmm_dS_T_Q_attributes = Matmul_attributes().set_name("bmm_dS_T_Q")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_KV])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_Q]);
+ if (h_q == h_k) {
+ matmul(dP_T, Q_seq_dequant, bmm_dS_T_Q_attributes, attributes.outputs[output_names::dK]);
+ } else {
+ auto dK_fullhead = matmul(dP_T, Q_seq_dequant, bmm_dS_T_Q_attributes);
+ dK_fullhead->set_dim({b, h_q, s_kv, d_qk});
+ dK_fullhead->set_stride({h_q * s_kv * d_qk, s_kv * d_qk, d_qk, 1});
+ dK_fullhead->set_data_type(DataType_t::FLOAT);
+ reduction(dK_fullhead,
+ Reduction_attributes().set_name("red_dK_head").set_mode(ReductionMode_t::ADD),
+ attributes.outputs[output_names::dK]);
+ }
+
+ auto const& amax_dk = attributes.outputs.at(output_names::Amax_dK);
+ if (amax_dk != nullptr) {
+ auto amax_dk_attributes =
+ Reduction_attributes().set_name("amax_dK").set_mode(ReductionMode_t::AMAX);
+ reduction(attributes.outputs[output_names::dK], amax_dk_attributes, amax_dk);
+ }
+ } else {
+ auto bmm_dP_T_Q_attributes = Matmul_fp8_attributes().set_name("bmm_dP_T_Q")
+ .set_m_override(attributes.inputs[input_names::SEQ_LEN_KV])
+ .set_k_override(attributes.inputs[input_names::SEQ_LEN_Q]);
+ matmul_fp8(dP_T,
+ attributes.inputs[input_names::Q],
+ attributes.inputs[input_names::Descale_dP],
+ attributes.inputs[input_names::Descale_Q],
+ attributes.inputs[input_names::Scale_dK],
+ bmm_dP_T_Q_attributes,
+ attributes.outputs[output_names::dK],
+ attributes.outputs[output_names::Amax_dK]);
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ std::pair<int64_t, std::unordered_map<KnobType_t, int64_t>>
+ override_heuristics_query() const {
+ int32_t const sm_version = context.get_sm_version();
+ bool const use_new_knobs = detail::get_backend_version() >= 92300;
+ // {128,128} bprop: tileM=3, tileN=2, kernelCfg=2(bprop warp), streamK=0, cgaM=0
+ if (sm_version > 103 && is_deterministic_algorithm_supported_on_blackwell) {
+ if (use_new_knobs) {
+ return {17,
+ {{KnobType_t::TILE_M, 3},
+ {KnobType_t::TILE_N, 2},
+ {KnobType_t::KERNEL_CFG, 2},
+ {KnobType_t::STREAM_K, 0},
+ {KnobType_t::TILE_CGA_M, 0},
+ {KnobType_t::STAGES, 2}}};
+ } else {
+ return {17, {{KnobType_t::KERNEL_CFG, 31}, {KnobType_t::STAGES, 2}}};
+ }
+ } else if (is_deterministic_algorithm_supported_on_blackwell) {
+ if (use_new_knobs) {
+ return {5,
+ {{KnobType_t::TILE_M, 3},
+ {KnobType_t::TILE_N, 2},
+ {KnobType_t::KERNEL_CFG, 2},
+ {KnobType_t::STREAM_K, 0},
+ {KnobType_t::TILE_CGA_M, 0},
+ {KnobType_t::STAGES, 2}}};
+ } else {
+ return {5, {{KnobType_t::KERNEL_CFG, 31}, {KnobType_t::STAGES, 2}}};
+ }
+ } else {
+ return {-1, {}};
+ }
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j["is_mxfp8"] = is_mxfp8_scaling();
+ if (auto const rescale_threshold = get_rescale_threshold_from_env(); rescale_threshold.has_value()) {
+ j["rescale_threshold"] = rescale_threshold.value();
+ }
+ if (is_mxfp8_scaling()) {
+ j.update(R"({"tag": "SDPA_MXFP8_BWD"})"_json);
+ } else {
+ j.update(R"({"tag": "SDPA_FP8_BWD"})"_json);
+ }
+ }
+#endif
+};
+
+} // namespace cudnn_frontend::graph
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/sdpa_support_surface.h b/deps/cudnn-frontend/include/cudnn_frontend/node/sdpa_support_surface.h
new file mode 100644
index 0000000..6b73f73
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/sdpa_support_surface.h
@@ -0,0 +1,553 @@
+#pragma once
+
+#include <cstdlib>
+#include <unordered_set>
+
+#include "../../cudnn_frontend_Heuristics.h"
+#include "../../cudnn_frontend_Logging.h"
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+inline error_t
+SDPA_attributes::validate_sdpa_support_surface(const detail::Context& context,
+ int64_t s_kv,
+ bool is_paged_k,
+ bool is_paged_v) const {
+ // Extract dimensions from tensors
+ int64_t s_q = inputs.at(SDPA_attributes::input_names::Q)->get_dim()[2];
+ // s_kv is passed in from the caller
+ int64_t h_q = inputs.at(SDPA_attributes::input_names::Q)->get_dim()[1];
+ int64_t h_k = inputs.at(SDPA_attributes::input_names::K)->get_dim()[1];
+ int64_t h_v = inputs.at(SDPA_attributes::input_names::V)->get_dim()[1];
+ int64_t d_qk = inputs.at(SDPA_attributes::input_names::Q)->get_dim()[3];
+ int64_t d_v = inputs.at(SDPA_attributes::input_names::V)->get_dim()[3];
+
+ bool const is_ragged = inputs.at(SDPA_attributes::input_names::Q)->get_ragged_offset() ||
+ inputs.at(SDPA_attributes::input_names::K)->get_ragged_offset() ||
+ inputs.at(SDPA_attributes::input_names::V)->get_ragged_offset() ||
+ outputs.at(SDPA_attributes::output_names::O)->get_ragged_offset();
+
+ auto const& output_tensor = outputs.at(SDPA_attributes::output_names::O);
+ auto const& output_data_type = output_tensor->get_data_type();
+
+ auto const& bias_mask = inputs.find(SDPA_attributes::input_names::Bias);
+ bool const is_bias = (bias_mask != inputs.end() && bias_mask->second != nullptr);
+
+ auto const& dropout_mask = inputs.find(SDPA_attributes::input_names::Dropout_mask);
+ bool const is_dropout_custom = (dropout_mask != inputs.end()) && (dropout_mask->second != nullptr);
+ bool const is_dropout = dropout_probability.has_value() || is_dropout_custom;
+
+ bool const is_paged = is_paged_k || is_paged_v;
+
+ auto const& rng_tensor = outputs.find(SDPA_attributes::output_names::RNG_DUMP);
+ bool const is_rng = (rng_tensor != outputs.end() && rng_tensor->second != nullptr);
+
+ bool const max_seq_kv_explicit = max_seq_len_kv.has_value();
+
+ auto const& attn_scale = inputs.find(SDPA_attributes::input_names::Attn_scale);
+ bool const has_attn_scale = (attn_scale != inputs.end()) && (attn_scale->second != nullptr);
+
+ auto const& seq_len_q = inputs.find(SDPA_attributes::input_names::SEQ_LEN_Q);
+ bool const has_seq_len_q = (seq_len_q != inputs.end()) && (seq_len_q->second != nullptr);
+ auto const& seq_len_kv = inputs.find(SDPA_attributes::input_names::SEQ_LEN_KV);
+ bool const has_seq_len_kv = (seq_len_kv != inputs.end()) && (seq_len_kv->second != nullptr);
+
+ auto const& cu_seq_len_q = inputs.find(SDPA_attributes::input_names::CU_SEQ_LEN_Q);
+ bool const has_cu_seq_len_q = (cu_seq_len_q != inputs.end()) && (cu_seq_len_q->second != nullptr);
+ auto const& cu_seq_len_kv = inputs.find(SDPA_attributes::input_names::CU_SEQ_LEN_KV);
+ bool const has_cu_seq_len_kv = (cu_seq_len_kv != inputs.end()) && (cu_seq_len_kv->second != nullptr);
+
+ // validation TODO:
+ // - validate stats has valid dims
+
+ // Get device SM version from context
+ CHECK_CUDNN_FRONTEND_ERROR(context.populate_sm_version_from_device());
+ int32_t const sm_version = context.get_sm_version();
+ int32_t const prop_major = sm_version / 10;
+
+ // Common FP16 and FP8 validation
+ // validate basic dimension requirements
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (h_q % h_k != 0) || (h_q % h_v != 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "For group-query attention, number of heads for key and query must be a factor of number of heads for query");
+
+ // validate options for attn_scale
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_attn_scale && attn_scale_value.has_value(),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "attn_scale with tensor and value cannot be set at the same time.");
+
+ // validate options for bias mask
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_bias && (bias_mask->second->get_data_type() == DataType_t::BOOLEAN),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bias mask data type cannot be boolean");
+
+ // validate options for padding mask: padding requires per-sequence length tensors,
+ // either as (SEQ_LEN_Q + SEQ_LEN_KV) or as (CU_SEQ_LEN_Q + CU_SEQ_LEN_KV).
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ padding_mask && (!has_seq_len_q || !has_seq_len_kv) && (!has_cu_seq_len_q || !has_cu_seq_len_kv),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Padding mask requires seq_len_q/seq_len_kv (or cu_seq_len_q/cu_seq_len_kv) to be set.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (!padding_mask && !attention_score_modifier) &&
+ (has_seq_len_q || has_seq_len_kv || has_cu_seq_len_q || has_cu_seq_len_kv),
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "seq_len_q/seq_len_kv (or cu_seq_len_q/cu_seq_len_kv) needs to be set only if padding mask is enabled.");
+
+ // Cumulative sequence length tensors must be set together, and are mutually
+ // exclusive with the (per-batch) seq_len tensors.
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_cu_seq_len_q != has_cu_seq_len_kv,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "cu_seq_len_q and cu_seq_len_kv must both be set or both unset.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF((has_cu_seq_len_q || has_cu_seq_len_kv) && (has_seq_len_q || has_seq_len_kv),
+ error_code_t::INVALID_VALUE,
+ "Cannot specify both seq_len tensors and cu_seq_len tensors.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_ragged && ((padding_mask == false) && (attention_score_modifier == nullptr)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Ragged offsets are only supported with padding mask.");
+
+ // validate options for dropout mask
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ dropout_probability.has_value() && is_dropout_custom,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Using both, custom dropout mask and internal-mask generation using dropout probability, is ill-formed.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(dropout_probability.has_value() && dropout_probability.value() == 1.0,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Dropout probability cannot be 1 as corresponding scale wont be well formed.");
+
+ // validate options for causal mask and bottom right causal mask
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ has_causal_mask_bottom_right() && (!padding_mask) && s_q > s_kv,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bottom right causal mask does not support max_s_q > max_s_kv. Please virtually slice the Q tensor and pass it "
+ "as max_s_q == max_s_kv");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ has_causal_mask_bottom_right() && (is_bias || alibi_mask || is_dropout),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bottom right causal mask is only supported with is_bias=False, is_alibi=False, is_dropout=False.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_causal_mask_bottom_right() && (detail::get_backend_version() < 90600) &&
+ ((s_q % 64 != 0) || (s_kv % 64 != 0)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Bottom right causal mask is only supported with s_q multiple of 64, and s_kv "
+ "multiple of 64, for cudnn version below 9.6.0");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90600 && left_bound.has_value() &&
+ has_causal_mask_bottom_right() && s_q != s_kv,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Sliding window attention with bottom right causal mask requires s_q == s_kv "
+ "for cuDNN version below 9.6.0");
+
+ // validate that datatype is set for the graph
+ RETURN_CUDNN_FRONTEND_ERROR_IF(context.get_intermediate_data_type() == DataType_t::NOT_SET,
+ error_code_t::ATTRIBUTE_NOT_SET,
+ "Intermediate tensor data type needs to be set as internal tensors require it.");
+
+ if (mma_core_mode == DataType_t::FP8_E4M3 || mma_core_mode == DataType_t::FP8_E5M2) {
+ // FP8 specific validation
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF((prop_major == 12) && is_ragged,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 with THD not supported for sm120 yet.");
+
+ // version specific validation
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90100,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 forward operation is only supported starting cudnn 9.1.0. Please "
+ "consider upgrading your current version.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() == 91000,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 forward operation is not supported on cudnn 9.10.0. Please "
+ "consider upgrading your current version.");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ prop_major < 9,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 forward operation is only supported on Hopper architecture and newer. Please "
+ "consider using a newer architecture.");
+
+ // FP8 does not support bias (TE constraint)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_bias, error_code_t::GRAPH_NOT_SUPPORTED, "SDPA FP8 does not support bias");
+
+ // validate basic dimension requirements
+ // d_qk=192 with d_v=128 is only supported starting from cuDNN 9.19
+ bool const d192_v128_supported = (detail::get_backend_version() >= 91900);
+ if (prop_major >= 10) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ ((d_qk > 128) || (d_qk % 16 != 0)) && !(d192_v128_supported && d_qk == 192 && d_v == 128),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "hidden_dim d_qk should be less than or equal to 128 and hidden_dim d_qk "
+ "should be multiple of 16 unless d_qk == 192 and d_v == 128 (requires cuDNN 9.19+)");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ ((d_v > 128) || (d_v % 16 != 0)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "hidden_dim d_v should be less than or equal to 128 and hidden_dim d_v should be multiple of 16");
+ } else {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (d_qk > 256) || (d_qk % 16 != 0) || (d_v > 256) || (d_v % 16 != 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "hidden_dim shoud be less than or equal to 256 and hidden_dim should be multiple of 16");
+ }
+
+ // Validate options for causal_mask_bottom_right
+ RETURN_CUDNN_FRONTEND_ERROR_IF(has_causal_mask_bottom_right() && detail::get_backend_version() < 90700,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "For cuDNN version below 9.7.0, bottom right causal masking is not supported.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ has_causal_mask_bottom_right() && prop_major < 10,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 forward operation is only supported on Blackwell architecture and newer. Please "
+ "consider using a newer architecture.");
+
+ // if output data type is half or bfloat16, and version is below 9.13 or is not blackwell, return NOT_SUPPORTED
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (output_data_type == DataType_t::HALF || output_data_type == DataType_t::BFLOAT16) &&
+ (detail::get_backend_version() < 91300 || prop_major < 10),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "sdpa fp8 forward with HALF/BFLOAT16 output is only supported on Blackwell architecture "
+ "with cuDNN version 9.13.0 and newer.");
+ } else if (mma_core_mode == DataType_t::HALF) {
+ // FP16 specific validation
+
+ // Bug workarounds for known problematic versions
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::get_backend_version() == 91000 || detail::get_backend_version() == 91001,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "SDPA FP16/BF16 forward is not supported on cuDNN 9.10.0/9.10.1 due to known bugs. "
+ "Please consider upgrading to 9.10.2 or newer.");
+
+ // 9.14.0 sliding window bug: non-causal + s_kv > 1024 + sliding window
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::get_backend_version() == 91400 && s_kv > 1024 && left_bound.has_value() &&
+ !has_causal_like_masking(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "cuDNN 9.14.0 has a known bug with non-causal + s_kv > 1024 + sliding window attention. "
+ "Please consider upgrading to 9.14.1 or newer.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (attention_score_modifier != nullptr) &&
+ (alibi_mask || has_causal_like_masking() || padding_mask || left_bound.has_value()),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Attention score mod enabled and hence other subgraphs are disabled.");
+
+ // validate basic dimension requirements
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (d_qk % 8 != 0) || (d_v % 8 != 0), error_code_t::GRAPH_NOT_SUPPORTED, "hidden_dim should be multiple of 8");
+
+ // validate alibi requirements
+ RETURN_CUDNN_FRONTEND_ERROR_IF(alibi_mask && !(right_bound.has_value() && right_bound.value() == 0),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "When alibi mask is used, diagonal_band_right_bound needs to be set to 0.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ left_bound.has_value() && left_bound.value() <= 0 && detail::get_backend_version() < 91000,
+ error_code_t::INVALID_VALUE,
+ "Left bound (Sliding window length) should be greater than zero when set.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(left_bound.has_value() && (!padding_mask) && s_q > s_kv,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Sliding window attention is only supported with max_s_q <= max_s_kv.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ left_bound.has_value() && (s_q * left_bound.value() == s_kv * left_bound.value()) &&
+ (detail::get_backend_version() <= 90900) && (prop_major == 9) && has_causal_mask_bottom_right(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "On Hopper architecture, this specific combination of s_q, s_kv, and left_bound + right_bound + bottom "
+ "right diagonal alignment is not supported for backend version 9.9 or below");
+
+ if ((detail::get_backend_version() < 91002)) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ left_bound.has_value() && (!has_causal_like_masking() || is_dropout || is_bias),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Left and right bounds are only supported with is_dropout=False, is_bias=False. And the diagonal "
+ "alignment must be set.");
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(right_bound.has_value() && right_bound.value() < 0,
+ error_code_t::INVALID_VALUE,
+ "Right bound needs to be larger than or equal to zero");
+
+ // Validate options for s_q == 1
+ const bool is_decode_only = (s_q == 1);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_decode_only && (prop_major == 10) && (d_qk > 128 || d_v > 128) &&
+ (detail::get_backend_version() <= 90900),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "decode only mode, i.e. s_q == 1 not supported for blackwell architecture with "
+ "d_qk or d_v > 128 for backend version 9.9 or below");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ is_decode_only && (detail::get_backend_version() <= 90900) && (right_bound.has_value()),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "decode only mode, i.e. s_q == 1, not supported with masking (right_bound is set) for backend version 9.9 "
+ "or below");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_decode_only && has_sink_token(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "decode only mode, i.e. s_q == 1, not supported with sink_token");
+
+ // validate options for paged attention
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ is_paged && (d_qk > 128 || d_v > 128) && detail::get_backend_version() <= 90900,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Paged attention only supported with d_qk and d_v <= 128 for backend version 9.9 or below");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_paged && is_ragged && detail::get_backend_version() < 90700,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Paged caches are not supported in combination with ragged offsets.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ is_paged && !((has_seq_len_q && has_seq_len_kv) || (has_cu_seq_len_q && has_cu_seq_len_kv)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Paged caches can only be used in combination with padding mask and variable sequence lengths "
+ "for both Q and KV (via seq_len_q/seq_len_kv or cu_seq_len_q/cu_seq_len_kv).");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !is_paged && max_seq_kv_explicit,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "When not using paged attention, there is no need to explicitly set max kv sequence length.");
+
+ if (max_seq_kv_explicit) {
+ auto max_seq_kv = max_seq_len_kv.value();
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_bias && (bias_mask->second->get_dim()[3] != max_seq_kv),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Value set through set_paged_attention_max_seq_len_kv is incompatible with "
+ "the sequence length of the bias");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(is_rng && rng_tensor->second->get_dim()[3] != max_seq_kv,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Value set through set_paged_attention_max_seq_len_kv is incompatible with "
+ "the sequence length of the RNG_DUMP");
+ }
+
+ // Additional validation for paged attention with packed page tables
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ ((is_paged_k && inputs.at(SDPA_attributes::input_names::Page_table_K)->get_ragged_offset()) ||
+ (is_paged_v && inputs.at(SDPA_attributes::input_names::Page_table_V)->get_ragged_offset())) &&
+ detail::get_backend_version() < 91002,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Paged attention with packed page tables only supported with cudnn version 9.10.2 and above");
+
+ // SM version check for SDPA
+ RETURN_CUDNN_FRONTEND_ERROR_IF(prop_major < 8,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "SDPA FP16/BF16 requires SM80 (Ampere) or newer architecture");
+
+ // version specific validation by architecture
+ if (prop_major == 8) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::get_backend_version() <= 90900 && ((d_qk > 128) || (d_v > 128)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "head_dim should be less than or equal to 128 for backend version 9.9 or below on ampere architecture");
+ }
+ if (prop_major == 9) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ detail::get_backend_version() <= 90900 && ((d_qk > 256) || (d_v > 256)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "head_dim should be less than or equal to 256 for backend version 9.9 or below on hopper architecture");
+ }
+ if (prop_major == 10) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF((detail::get_backend_version() < 90900) && ((d_qk > 128) || (d_v > 128)),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "head_dim should be less than or equal to 128 for backend version 9.8 or "
+ "below on blackwell architecture");
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(detail::get_backend_version() < 90500 && is_paged,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "For cuDNN version below 9.5.0, paged caches are not supported");
+
+ if (is_ragged) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF((context.get_sm_version() > 0 && context.get_sm_version() < 90 &&
+ detail::get_backend_version() < 91801),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "THD (ragged offset) is only supported in Hopper and above : " +
+ std::to_string(context.get_sm_version()));
+ }
+ } else {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(true, error_code_t::GRAPH_NOT_SUPPORTED, "Unsupported mma core mode");
+ }
+
+ // Check whether the selected implementation supports the requested features.
+ CHECK_CUDNN_FRONTEND_ERROR(verify_sdpa_support_surface_for_implementation(context, implementation));
+
+ return {error_code_t::OK, ""};
+}
+
+// Verify that the underlying implementation supports all the features in these attributes.
+// Unlike `validate_sdpa_support_surface()`, this may be called before validation, so:
+// * don't assume any particular keys already exist in `inputs` or `outputs`
+// * don't assume any tensor dims or strides are already set
+// We return error codes directly instead of using `RETURN_CUDNN_FRONTEND_ERROR_IF`
+// to avoid unneeded logging when this function is being called in a non-error-generating
+// situation (e.g. during auto-select of SDPA implementation).
+inline error_t
+SDPA_attributes::verify_sdpa_support_surface_for_implementation(const detail::Context& context,
+ AttentionImplementation_t impl) const {
+ switch (impl) {
+ case AttentionImplementation_t::AUTO:
+ // This function should not be called with AUTO.
+ return {error_code_t::INVALID_VALUE,
+ "Can't call verify_sdpa_support_surface_for_implementation with impl=AUTO"};
+ case AttentionImplementation_t::COMPOSITE:
+ for (const auto& [key, value] : inputs) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(key == input_names::Block_mask && value != nullptr,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Composite SDPA node doesn't support Block_mask input");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ (key == input_names::CU_SEQ_LEN_Q || key == input_names::CU_SEQ_LEN_KV) && value != nullptr,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Composite SDPA node doesn't support CU_SEQ_LEN_Q / CU_SEQ_LEN_KV inputs");
+ }
+ // The ragged offset multiplier is only supported by the unified forward engine.
+ // Reject it here so auto-select routes such graphs to the unified implementation.
+ for (const auto& [key, value] : inputs) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(value != nullptr && value->has_ragged_offset_multiplier(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Composite SDPA node doesn't support a ragged offset multiplier");
+ }
+ for (const auto& [key, value] : outputs) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(value != nullptr && value->has_ragged_offset_multiplier(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Composite SDPA node doesn't support a ragged offset multiplier");
+ }
+ break;
+ case AttentionImplementation_t::UNIFIED: {
+ auto effective_cudnn_ver = std::min(detail::get_backend_version(), detail::get_compiled_version());
+ RETURN_CUDNN_FRONTEND_ERROR_IF(effective_cudnn_ver < 91301,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Unified SDPA node requires cuDNN 9.13.1");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(context.get_dynamic_shape_enabled(),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Unified SDPA node doesn't yet support dynamic shape");
+
+ // TODO: Provide smarter error messages that provide the required cuDNN version for each input.
+ std::unordered_set<SDPA_attributes::input_names> allowed_input_names{
+ input_names::Q, input_names::K, input_names::V, input_names::Attn_scale};
+ std::string allowed_input_msg =
+ "Unified SDPA node doesn't yet support inputs other than Q, K, V, Attn_scale";
+
+ if (effective_cudnn_ver >= 91400) {
+ allowed_input_names.insert({input_names::Block_mask});
+ allowed_input_msg += ", Block_mask";
+ }
+
+ if (effective_cudnn_ver >= 91500) {
+ allowed_input_names.insert({input_names::Page_table_K,
+ input_names::Page_table_V,
+ input_names::SEQ_LEN_Q,
+ input_names::SEQ_LEN_KV});
+ allowed_input_msg += ", Page_table_K, Page_table_V, SEQ_LEN_Q, SEQ_LEN_KV";
+ }
+
+ if (effective_cudnn_ver >= 92100) {
+ // NOTE: For unified engine, we support dropout via Seed and Offset only.
+ // Custom dropout mask (via Dropout_mask, Dropout_scale) is not supported.
+ allowed_input_names.insert(
+ {input_names::Bias, input_names::Seed, input_names::Offset, input_names::SINK_TOKEN});
+ allowed_input_msg += ", Bias, Seed, Offset, SINK_TOKEN";
+ }
+
+ if (effective_cudnn_ver >= 92400) {
+ allowed_input_names.insert({input_names::CU_SEQ_LEN_Q, input_names::CU_SEQ_LEN_KV});
+ allowed_input_msg += ", CU_SEQ_LEN_Q, CU_SEQ_LEN_KV";
+ }
+
+ if (effective_cudnn_ver >= 93000) {
+ allowed_input_names.insert({input_names::Descale_Q,
+ input_names::Descale_K,
+ input_names::Descale_V,
+ input_names::Descale_S,
+ input_names::Scale_S,
+ input_names::Scale_O});
+ allowed_input_msg += ", Descale_Q, Descale_K, Descale_V, Descale_S, Scale_S, Scale_O";
+ }
+
+ for (const auto& [key, value] : inputs) {
+ if (allowed_input_names.find(key) == allowed_input_names.end() && value != nullptr) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED, allowed_input_msg};
+ }
+ }
+
+ std::unordered_set<SDPA_attributes::output_names> allowed_output_names{output_names::O,
+ output_names::Stats};
+ std::string allowed_output_msg = "Unified SDPA node doesn't yet support outputs other than O, Stats";
+
+ if (effective_cudnn_ver >= 92100) {
+ allowed_output_names.insert({output_names::RNG_DUMP, output_names::Max, output_names::Sum_exp});
+ allowed_output_msg += ", RNG_DUMP, Max, Sum_exp";
+ }
+
+ if (effective_cudnn_ver >= 93000) {
+ allowed_output_names.insert({output_names::Amax_S, output_names::Amax_O});
+ allowed_output_msg += ", Amax_S, Amax_O";
+ }
+
+ for (const auto& [key, value] : outputs) {
+ if (allowed_output_names.find(key) == allowed_output_names.end() && value != nullptr) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED, allowed_output_msg};
+ }
+ }
+
+ if (alibi_mask && effective_cudnn_ver < 92100) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "Alibi mask for unified SDPA node requires cuDNN 9.21.0 or above"};
+ }
+
+ if (padding_mask && effective_cudnn_ver < 91500) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "Padding mask for unified SDPA node requires cuDNN 9.15.0 or above"};
+ }
+
+ if ((left_bound.has_value() || right_bound.has_value()) && effective_cudnn_ver < 92100) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "Left bound or right bound for unified SDPA node requires cuDNN 9.21.0 or above"};
+ }
+
+ if (diagonal_alignment != DiagonalAlignment_t::TOP_LEFT && effective_cudnn_ver < 92100) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "Diagonal alignment for unified SDPA node requires cuDNN 9.21.0 or above"};
+ }
+
+ if (dropout_probability.has_value() && effective_cudnn_ver < 92200) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED, "Dropout for unified SDPA node requires cuDNN 9.22.0"};
+ }
+
+ if (dropout_probability.has_value() && generate_stats.value_or(false)) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "Dropout for unified SDPA node with generated stats is not supported"};
+ }
+
+ // Unified engine in cuDNN < 9.15 can't meaningfully support max sequence length,
+ // while versions >= 9.15 "support" it by ignoring it (unified engine doesn't need it).
+ if (max_seq_len_kv.has_value() && effective_cudnn_ver < 91500) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "Max sequence length for unified SDPA node cannot be set in cuDNN < 9.15.0"};
+ }
+
+ if (attention_score_modifier != nullptr && effective_cudnn_ver < 92100) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "Attention score modifier for unified SDPA node requires cuDNN 9.21.0 or above"};
+ }
+
+ if (mma_core_mode == DataType_t::FP8_E4M3 || mma_core_mode == DataType_t::FP8_E5M2) {
+ // Per-tensor FP8 and MXFP8 (block-scaled, E8M0 descales) are supported by the
+ // unified node starting from cuDNN 9.30.0.
+ if (effective_cudnn_ver < 93000) {
+ return {error_code_t::GRAPH_NOT_SUPPORTED,
+ "FP8/MXFP8 for the unified SDPA node requires cuDNN 9.30.0 or above"};
+ }
+ }
+ } break;
+ }
+
+ return {error_code_t::OK, ""};
+}
+
+} // namespace cudnn_frontend::graph
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/slice.h b/deps/cudnn-frontend/include/cudnn_frontend/node/slice.h
new file mode 100644
index 0000000..a1aafb1
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/slice.h
@@ -0,0 +1,224 @@
+#pragma once
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class SliceNode : public NodeCRTP<SliceNode> {
+ public:
+ Slice_attributes attributes;
+
+ SliceNode(Slice_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::SLICE;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ getLogger() << "[cudnn_frontend] INFO: Inferrencing properties for slice node " << attributes.name
+ << std::endl;
+
+ attributes.fill_from_context(context);
+
+ for (size_t i = 0; i < attributes.slice_strides.size(); ++i) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ attributes.slice_strides[i] <= 0,
+ error_code_t::INVALID_VALUE,
+ "Slice slice_strides[" + std::to_string(i) + "] must be strictly positive (got " +
+ std::to_string(attributes.slice_strides[i]) +
+ "). Non-positive strides break output dimension calculation and can cause division by zero.");
+ }
+
+ auto output = attributes.outputs.at(Slice_attributes::output_names::Y);
+ auto output_dim = output->get_dim();
+
+ if (output_dim.empty()) {
+ for (size_t i = 0; i < attributes.slices.size(); ++i) {
+ int64_t start = attributes.slices[i].first;
+ int64_t limit = attributes.slices[i].second;
+ int64_t stride = (!attributes.slice_strides.empty() && i < attributes.slice_strides.size())
+ ? attributes.slice_strides[i]
+ : 1;
+ // Output dimension = ceil((limit - start) / stride)
+ int64_t dim = (limit - start + stride - 1) / stride;
+ output_dim.push_back(dim);
+ }
+ output->set_dim(output_dim);
+ }
+
+ auto const input = attributes.inputs.at(Slice_attributes::input_names::X);
+ auto const input_data_type = input->get_data_type();
+ auto const output_data_type = output->get_data_type();
+ if (output_data_type == DataType_t::NOT_SET) {
+ output->set_data_type(input_data_type);
+ } else {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(output_data_type != input_data_type,
+ error_code_t::INVALID_VALUE,
+ "output and input tensor data types should match for slice operation.");
+ }
+
+ auto const input_stride = input->get_stride();
+ if (output->get_stride().empty()) {
+ // When slice strides > 1, output strides need to be multiplied accordingly
+ std::vector<int64_t> output_stride;
+ for (size_t i = 0; i < input_stride.size(); ++i) {
+ int64_t stride = (!attributes.slice_strides.empty() && i < attributes.slice_strides.size())
+ ? attributes.slice_strides[i]
+ : 1;
+ output_stride.push_back(input_stride[i] * stride);
+ }
+ output->set_stride(output_stride);
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_tensors_node(std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors,
+ int64_t& potential_uid,
+ std::unordered_set<int64_t> const& used_uids) const override final {
+ getLogger() << "[cudnn_frontend] INFO: Creating cudnn tensors for SliceNode " << attributes.name << std::endl;
+
+ auto const input = attributes.inputs.at(Slice_attributes::input_names::X);
+ auto const output = attributes.outputs.at(Slice_attributes::output_names::Y);
+
+ if (detail::get_backend_version() >= 92200 && detail::get_compiled_version() >= 92200) {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_cudnn_tensor(input, tensors, potential_uid, used_uids));
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_cudnn_tensor(output, tensors, potential_uid, used_uids));
+ return {error_code_t::OK, ""};
+ }
+
+ if (input->has_uid() == false) {
+ detail::assign_uid(input.get(), potential_uid, used_uids);
+ }
+ output->set_is_virtual(false);
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_cudnn_tensor(output, tensors, potential_uid, used_uids));
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Building SliceNode operations " << attributes.name << std::endl;
+
+#if (CUDNN_VERSION >= 92200)
+ // cuDNN >= 9.22.0: Use native backend slice operation
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Slice backend operation requires 9.22.0"};
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92200, cudnn_ver_error);
+
+ if (detail::get_backend_version() >= 92200) {
+ CUDNN_FRONTEND_UNUSED(operations);
+
+ auto slice_operation = make_shared_backend_pointer(CUDNN_BACKEND_OPERATION_SLICE_DESCRIPTOR);
+
+ // Set input tensor
+ auto X = attributes.inputs.at(Slice_attributes::input_names::X);
+ auto backend_x = tensors[X->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(slice_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SLICE_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_x));
+
+ // Set output tensor
+ auto Y = attributes.outputs.at(Slice_attributes::output_names::Y);
+ auto backend_y = tensors[Y->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(slice_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SLICE_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_y));
+
+ // Extract start and limit indices from slices
+ std::vector<int64_t> start_indices;
+ std::vector<int64_t> limit_indices;
+
+ for (const auto& slice : attributes.slices) {
+ start_indices.push_back(slice.first);
+ limit_indices.push_back(slice.second);
+ }
+
+ // Per-dimension strides: use user slice_strides[i] when set, else 1 (preserves partial configuration)
+ std::vector<int64_t> strides(attributes.slices.size());
+ for (size_t i = 0; i < strides.size(); ++i) {
+ strides[i] = (i < attributes.slice_strides.size()) ? attributes.slice_strides[i] : 1;
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(slice_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SLICE_START_INDICES,
+ CUDNN_TYPE_INT64,
+ start_indices.size(),
+ start_indices.data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(slice_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SLICE_LIMIT_INDICES,
+ CUDNN_TYPE_INT64,
+ limit_indices.size(),
+ limit_indices.data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(slice_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SLICE_STRIDES,
+ CUDNN_TYPE_INT64,
+ strides.size(),
+ strides.data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(slice_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(slice_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+ }
+#endif
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+
+ getLogger() << "[cudnn_frontend] INFO: " << "Using pointer arithmetic fallback for slice on cuDNN < 9.22.0"
+ << std::endl;
+
+ auto const output = attributes.outputs.at(Slice_attributes::output_names::Y);
+ if (output && output->get_is_virtual() == false) {
+ uids_involved_in_operations.insert(output->get_uid());
+ if (auto ragged_offset = output->get_ragged_offset()) {
+ uids_involved_in_operations.insert(ragged_offset->get_uid());
+ }
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ collect_variant_pack_replacements_node(
+ std::unordered_map<Tensor_attributes::uid_t, std::pair<Tensor_attributes::uid_t, int64_t>>&
+ variant_pack_replacements) const override final {
+ if (detail::get_backend_version() >= 92200 && detail::get_compiled_version() >= 92200) {
+ CUDNN_FRONTEND_UNUSED(variant_pack_replacements);
+ return {error_code_t::OK, ""};
+ }
+ auto const input = attributes.inputs.at(Slice_attributes::input_names::X);
+ auto const output = attributes.outputs.at(Slice_attributes::output_names::Y);
+
+ variant_pack_replacements[input->get_uid()] = {output->get_uid(), attributes.get_offset()};
+
+ return {error_code_t::OK, ""};
+ };
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "SLICE"})"_json);
+ }
+#endif
+};
+
+} // namespace cudnn_frontend::graph \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/softmax.h b/deps/cudnn-frontend/include/cudnn_frontend/node/softmax.h
new file mode 100644
index 0000000..1aa5689
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/softmax.h
@@ -0,0 +1,366 @@
+#pragma once
+
+#include "../../cudnn_frontend_Heuristics.h"
+#include "../../cudnn_frontend_Logging.h"
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+#include "pointwise.h"
+#include "reduction.h"
+
+namespace cudnn_frontend::graph {
+
+// Base class for nodes that represent a softmax operation.
+// This is either implemented as a composite of pointwise/reduction operations (CompositeSoftmaxNode)
+// or as a single unified backend operation (UnifiedSoftmaxNode).
+template <typename DerivedT>
+class SoftmaxNodeBase : public NodeCRTP<DerivedT> {
+ protected:
+ using input_names = Softmax_attributes::input_names;
+ using output_names = Softmax_attributes::output_names;
+
+ public:
+ Softmax_attributes attributes;
+
+ SoftmaxNodeBase(Softmax_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP<DerivedT>(context), attributes(std::move(attributes_)) {}
+
+ error_t
+ infer_properties_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for Softmax node " << attributes.name);
+
+ attributes.fill_from_context(this->context);
+
+ auto input_tensor = attributes.inputs.at(Softmax_attributes::input_names::P);
+ auto output_tensor = attributes.outputs.at(Softmax_attributes::output_names::S);
+
+ // Only infer dims and strides if user did not set them
+ if (output_tensor->get_dim().empty()) {
+ output_tensor->set_dim(input_tensor->get_dim());
+ }
+
+ if (output_tensor->get_stride().empty()) {
+ output_tensor->set_stride(input_tensor->get_stride());
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ protected:
+ bool
+ has_sink() const {
+ auto sink_it = attributes.inputs.find(Softmax_attributes::input_names::SINK);
+ return ((sink_it) != attributes.inputs.end() && sink_it->second != nullptr);
+ }
+
+ bool
+ has_stats() const {
+ auto stats_it = attributes.outputs.find(Softmax_attributes::output_names::Stats);
+ return ((stats_it) != attributes.outputs.end() && stats_it->second != nullptr);
+ }
+
+ bool
+ has_max() const {
+ auto max_it = attributes.outputs.find(Softmax_attributes::output_names::Max);
+ return ((max_it) != attributes.outputs.end() && max_it->second != nullptr);
+ }
+
+ bool
+ has_sum_exp() const {
+ auto sum_exp_it = attributes.outputs.find(Softmax_attributes::output_names::Sum_exp);
+ return ((sum_exp_it) != attributes.outputs.end() && sum_exp_it->second != nullptr);
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ void
+ serialize(json& j) const override final {
+ j = attributes;
+ }
+#endif
+};
+
+// Fallback implementation of softmax node that represents the operation as a series of pointwise and reduction
+// operations. This is used for cuDNN versions before v9.21.0.
+// Only certain combinations of outputs are allowed.
+class CompositeSoftmaxNode : public SoftmaxNodeBase<CompositeSoftmaxNode> {
+ public:
+ CompositeSoftmaxNode(Softmax_attributes&& attributes_, detail::Context const& context)
+ : SoftmaxNodeBase(std::move(attributes_), context) {}
+
+ Type
+ getType() override final {
+ return Type::COMPOSITE;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating CompositeSoftmaxNode " << attributes.name);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !((!has_stats() && !has_max() && !has_sum_exp()) || //
+ (has_stats() && !has_max() && !has_sum_exp()) || //
+ (!has_stats() && has_max() && has_sum_exp())),
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "CompositeSoftmaxNode can only output certain combinations of stats, max and sum_exp: "
+ "stats only, max and sum_exp only, or none of the above.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ expand_node() override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Inferrencing properties for CompositeSoftmaxNode " << attributes.name);
+
+ attributes.fill_from_context(context);
+
+ // Fill properties of virtual tensors
+ auto const p_dim = attributes.inputs[Softmax_attributes::input_names::P]->get_dim();
+ auto b = p_dim[0];
+ auto h = p_dim[1];
+ auto s_q = p_dim[2];
+
+ std::shared_ptr<Tensor_attributes> max_output;
+ if (has_max()) {
+ max_output = attributes.outputs[Softmax_attributes::output_names::Max];
+ } else {
+ max_output = std::make_shared<Tensor_attributes>();
+ max_output->set_is_virtual(true);
+ }
+ //////////////// TODO //////////////////////////
+ // Check Stride (Before setting dimension?)
+ if (max_output->get_dim().empty()) {
+ max_output->set_dim({b, h, s_q, 1});
+ }
+ if (max_output->get_stride().empty()) {
+ max_output->set_stride({h * s_q, s_q, 1, 1});
+ }
+
+ auto max_attributes = Reduction_attributes().set_name("Max").set_mode(ReductionMode_t::MAX);
+ // If sink tensor is present, we also need to take a pointwise max with sink
+ if (has_sink()) {
+ auto s_max = reduction(attributes.inputs[Softmax_attributes::input_names::P], max_attributes);
+ s_max->set_name("s_max");
+
+ auto sink_tensor = attributes.inputs[Softmax_attributes::input_names::SINK];
+ auto sink_attributes = Pointwise_attributes().set_name("max_sink").set_mode(PointwiseMode_t::MAX);
+ pointwise(s_max, sink_tensor, sink_attributes, max_output);
+ } else {
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ reduction(attributes.inputs[Softmax_attributes::input_names::P], max_attributes, max_output);
+ }
+
+ auto sub_attributes = Pointwise_attributes().set_name("sub").set_mode(PointwiseMode_t::SUB);
+ auto const& sub_output =
+ pointwise(attributes.inputs[Softmax_attributes::input_names::P], max_output, sub_attributes);
+ sub_output->set_name("sub_M");
+
+ auto exp_attributes = Pointwise_attributes().set_name("exp").set_mode(PointwiseMode_t::EXP);
+ auto const& exp_output = pointwise(sub_output, exp_attributes);
+ exp_output->set_name("exp_sub_M");
+
+ std::shared_ptr<Tensor_attributes> sum_output;
+ if (has_sum_exp()) {
+ sum_output = attributes.outputs[Softmax_attributes::output_names::Sum_exp];
+ } else {
+ sum_output = std::make_shared<Tensor_attributes>();
+ sum_output->set_is_virtual(true);
+ }
+ sum_output->set_name("SumExp");
+ if (sum_output->get_dim().empty()) {
+ sum_output->set_dim({b, h, s_q, 1});
+ }
+ if (sum_output->get_stride().empty()) {
+ sum_output->set_stride({h * s_q, s_q, 1, 1});
+ }
+ auto sum_attributes = Reduction_attributes().set_name("sum").set_mode(ReductionMode_t::ADD);
+ // If sink tensor is present, also subtract it and take its exp
+ if (has_sink()) {
+ auto sink_tensor = attributes.inputs[Softmax_attributes::input_names::SINK];
+ auto sub_sink = pointwise(sink_tensor, max_output, sub_attributes);
+ sub_sink->set_name("sub_sink");
+
+ auto exp_sink = pointwise(sub_sink, exp_attributes);
+ exp_sink->set_name("exp_sink");
+
+ auto temp_sum = reduction(exp_output, sum_attributes);
+ temp_sum->set_name("SumExp_elements").set_dim({b, h, s_q, 1}).set_stride({h * s_q, s_q, 1, 1});
+
+ auto add_attributes = Pointwise_attributes().set_name("add_sink").set_mode(PointwiseMode_t::ADD);
+ pointwise(temp_sum, exp_sink, add_attributes, sum_output);
+ } else {
+ reduction(exp_output, sum_attributes, sum_output);
+ }
+
+ // Set to virtual when:
+ // - softmax stats in not requested
+ // - max and sum_exp are not requested
+ if (!has_stats() && !has_max() && !has_sum_exp()) {
+ auto softmax_stats = std::make_shared<Tensor_attributes>();
+ softmax_stats->set_is_virtual(true);
+ attributes.outputs[Softmax_attributes::output_names::Stats] = softmax_stats;
+ }
+
+ if (has_stats()) {
+ auto log_attributes = Pointwise_attributes().set_name("log").set_mode(PointwiseMode_t::LOG);
+ auto const& log_output = pointwise(sum_output, log_attributes);
+ log_output->set_dim({b, h, s_q, 1}).set_stride({h * s_q, s_q, 1, 1});
+
+ auto add_attributes = Pointwise_attributes().set_name("add").set_mode(PointwiseMode_t::ADD);
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ pointwise(
+ max_output, log_output, add_attributes, attributes.outputs[Softmax_attributes::output_names::Stats]);
+ }
+
+ auto div_attributes = Pointwise_attributes().set_name("div").set_mode(PointwiseMode_t::DIV);
+ // Special non-functional-style call. Needed because output already created and provided to user.
+ pointwise(exp_output, sum_output, div_attributes, attributes.outputs[Softmax_attributes::output_names::S]);
+
+ return {error_code_t::OK, ""};
+ }
+};
+
+// Newer implementation of softmax node that represents the operation as a single backend operation.
+// This is used for cuDNN versions v9.21.0 and later.
+class UnifiedSoftmaxNode : public SoftmaxNodeBase<UnifiedSoftmaxNode> {
+ public:
+ UnifiedSoftmaxNode(Softmax_attributes&& attributes_, detail::Context const& context)
+ : SoftmaxNodeBase(std::move(attributes_), context) {}
+
+ Type
+ getType() override final {
+ return Type::SOFTMAX;
+ }
+
+ error_t
+ pre_validate_node() const override final {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Validating UnifiedSoftmaxNode " << attributes.name);
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Building UnifiedSoftmaxNode operations " << attributes.name
+ << std::endl;
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "UnifiedSoftmaxNode requires cuDNN v9.21.0"};
+
+#if (CUDNN_VERSION >= 92100)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92100, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+ auto softmax_operation =
+ make_shared_backend_pointer((cudnnBackendDescriptorType_t)CUDNN_BACKEND_OPERATION_SOFTMAX_DESCRIPTOR);
+
+ // Set input tensor P
+ auto P = attributes.inputs.find(Softmax_attributes::input_names::P)->second;
+ auto backend_p = tensors[P->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(softmax_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SOFTMAX_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_p));
+
+ // Set output tensor S
+ auto S = attributes.outputs.find(Softmax_attributes::output_names::S)->second;
+ auto backend_s = tensors[S->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(softmax_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SOFTMAX_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_s));
+
+ // Set optional SINK tensor if present
+ if (has_sink()) {
+ auto SINK = attributes.inputs.find(Softmax_attributes::input_names::SINK)->second;
+ auto backend_sink = tensors[SINK->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(softmax_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SOFTMAX_SINK_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_sink));
+ }
+
+ // Set optional Stats output tensor if present
+ if (has_stats()) {
+ auto Stats = attributes.outputs.find(Softmax_attributes::output_names::Stats)->second;
+ auto backend_stats = tensors[Stats->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(softmax_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SOFTMAX_STATS_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_stats));
+ }
+
+ // Set optional Max output tensor if present
+ if (has_max()) {
+ auto Max = attributes.outputs.find(Softmax_attributes::output_names::Max)->second;
+ auto backend_max = tensors[Max->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(softmax_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SOFTMAX_MAX_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_max));
+ }
+
+ // Set optional Sum_exp output tensor if present
+ if (has_sum_exp()) {
+ auto Sum_exp = attributes.outputs.find(Softmax_attributes::output_names::Sum_exp)->second;
+ auto backend_sum_exp = tensors[Sum_exp->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(softmax_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_SOFTMAX_SUM_EXP_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_sum_exp));
+ }
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(softmax_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(softmax_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+ return {error_code_t::OK, ""};
+#else
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ return cudnn_ver_error;
+#endif // CUDNN_VERSION >= 92100
+ }
+};
+
+// Factory function implementation for INode::softmax
+// This function will create the appropriate node based on the cuDNN version.
+inline void
+INode::softmax(std::shared_ptr<Tensor_attributes> p,
+ Softmax_attributes attributes,
+ std::shared_ptr<Tensor_attributes> s,
+ std::shared_ptr<Tensor_attributes> stats,
+ std::shared_ptr<Tensor_attributes> max,
+ std::shared_ptr<Tensor_attributes> sum_exp) {
+ attributes.inputs[Softmax_attributes::input_names::P] = p;
+ attributes.outputs[Softmax_attributes::output_names::S] = s;
+ if (stats) {
+ attributes.outputs[Softmax_attributes::output_names::Stats] = stats;
+ }
+ if (max) {
+ attributes.outputs[Softmax_attributes::output_names::Max] = max;
+ }
+ if (sum_exp) {
+ attributes.outputs[Softmax_attributes::output_names::Sum_exp] = sum_exp;
+ }
+
+ // Newer versions of cuDNN can represent the softmax as a single operation.
+ if (std::min(detail::get_compiled_version(), detail::get_backend_version()) >= 92100) {
+ sub_nodes.emplace_back(std::make_unique<UnifiedSoftmaxNode>(std::move(attributes), context));
+ } else {
+ sub_nodes.emplace_back(std::make_unique<CompositeSoftmaxNode>(std::move(attributes), context));
+ }
+}
+
+} // namespace cudnn_frontend::graph
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node/transpose.h b/deps/cudnn-frontend/include/cudnn_frontend/node/transpose.h
new file mode 100644
index 0000000..7f764be
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node/transpose.h
@@ -0,0 +1,164 @@
+#pragma once
+
+#include "../../cudnn_frontend_Logging.h"
+
+#include "../graph_helpers.h"
+#include "../node_interface.h"
+
+namespace cudnn_frontend::graph {
+
+class TransposeNode : public NodeCRTP<TransposeNode> {
+ public:
+ Transpose_attributes attributes;
+
+ TransposeNode(Transpose_attributes&& attributes_, detail::Context const& context)
+ : NodeCRTP(context), attributes(std::move(attributes_)) {}
+
+ Type
+ getType() override final {
+ return Type::TRANSPOSE;
+ }
+
+ error_t
+ infer_properties_node() override final {
+ getLogger() << "[cudnn_frontend] INFO: Inferrencing properties for transpose node " << attributes.name
+ << std::endl;
+
+ attributes.fill_from_context(context);
+
+ auto const& X_tensor = attributes.inputs[Transpose_attributes::input_names::X];
+ auto Y_tensor = attributes.outputs[Transpose_attributes::output_names::Y];
+
+ // Get input properties
+ auto const& input_dim = X_tensor->get_dim();
+ auto const& input_stride = X_tensor->get_stride();
+ auto const& input_data_type = X_tensor->get_data_type();
+ auto const& permutation = attributes.get_permutation();
+
+ // Validate permutation
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ permutation.empty(), error_code_t::ATTRIBUTE_NOT_SET, "Permutation must be set for transpose operation.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(permutation.size() != input_dim.size(),
+ error_code_t::INVALID_VALUE,
+ "Permutation size must match input tensor dimensionality.");
+
+ // Check that permutation is a valid permutation (contains each index 0 to n-1 exactly once)
+ std::vector<bool> seen(permutation.size(), false);
+ for (auto idx : permutation) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(idx < 0 || idx >= static_cast<int64_t>(permutation.size()),
+ error_code_t::INVALID_VALUE,
+ "Permutation indices must be in range [0, n-1].");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ seen[idx], error_code_t::INVALID_VALUE, "Permutation indices must be unique.");
+ seen[idx] = true;
+ }
+
+ // Infer output dimensions by permuting input dimensions
+ std::vector<int64_t> output_dim(input_dim.size());
+ for (size_t i = 0; i < permutation.size(); ++i) {
+ output_dim[i] = input_dim[permutation[i]];
+ }
+
+ // Infer output strides by permuting input strides
+ std::vector<int64_t> output_stride(input_stride.size());
+ for (size_t i = 0; i < permutation.size(); ++i) {
+ output_stride[i] = input_stride[permutation[i]];
+ }
+
+ // Set output tensor properties
+ if (Y_tensor->get_dim().empty()) {
+ Y_tensor->set_dim(output_dim);
+ }
+ if (Y_tensor->get_stride().empty()) {
+ Y_tensor->set_stride(output_stride);
+ }
+ if (Y_tensor->get_data_type() == DataType_t::NOT_SET) {
+ Y_tensor->set_data_type(input_data_type);
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(Y_tensor->get_data_type() != input_data_type,
+ error_code_t::INVALID_VALUE,
+ "Output and input tensor data types must match for transpose operation.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operations,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors) const override final {
+ getLogger() << "[cudnn_frontend] INFO: " << "Building TransposeNode operations " << attributes.name
+ << std::endl;
+
+#if (CUDNN_VERSION >= 92200)
+ // cuDNN >= 9.22.0: Use native backend transpose operation
+ auto cudnn_ver_error = error_t{error_code_t::GRAPH_NOT_SUPPORTED, "Transpose requires cuDNN v9.22.0"};
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92200, cudnn_ver_error);
+ CUDNN_FRONTEND_UNUSED(operations);
+
+ auto transpose_operation = make_shared_backend_pointer(CUDNN_BACKEND_OPERATION_TRANSPOSE_DESCRIPTOR);
+
+ // Set input tensor
+ auto X = attributes.inputs.at(Transpose_attributes::input_names::X);
+ auto backend_x = tensors[X->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(transpose_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_TRANSPOSE_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_x));
+
+ // Set output tensor
+ auto Y = attributes.outputs.at(Transpose_attributes::output_names::Y);
+ auto backend_y = tensors[Y->get_uid()]->get_desc()->get_backend_descriptor();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(transpose_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_TRANSPOSE_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &backend_y));
+
+ // Set permutation
+ auto permutation = attributes.get_permutation();
+ _CUDNN_CHECK_CUDNN_ERROR(detail::set_attribute(transpose_operation->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_TRANSPOSE_PERMUTATION,
+ CUDNN_TYPE_INT64,
+ permutation.size(),
+ permutation.data()));
+
+ _CUDNN_CHECK_CUDNN_ERROR(detail::finalize(transpose_operation->get_backend_descriptor()));
+
+ raw_operations.push_back(transpose_operation);
+
+ auto const& non_virtual_uids = attributes.get_non_virtual_uids();
+ uids_involved_in_operations.insert(non_virtual_uids.begin(), non_virtual_uids.end());
+#else
+ CUDNN_FRONTEND_UNUSED(operations);
+ CUDNN_FRONTEND_UNUSED(raw_operations);
+ CUDNN_FRONTEND_UNUSED(tensors);
+ CUDNN_FRONTEND_UNUSED(uids_involved_in_operations);
+ return {error_code_t::GRAPH_NOT_SUPPORTED, "Transpose operation requires cuDNN version >= 9.22.0"};
+#endif
+ return {error_code_t::OK, ""};
+ }
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const override final {
+ j = attributes;
+ j.update(R"( {"tag": "TRANSPOSE"})"_json);
+ }
+#endif
+};
+
+inline std::shared_ptr<Tensor_attributes>
+INode::transpose(std::shared_ptr<Tensor_attributes> input, Transpose_attributes attributes) {
+ attributes.inputs[Transpose_attributes::input_names::X] = input;
+ auto Y = attributes.outputs[Transpose_attributes::output_names::Y] = output_tensor(attributes.name + "::Y");
+
+ sub_nodes.emplace_back(std::make_unique<TransposeNode>(std::move(attributes), context));
+ return Y;
+}
+
+} // namespace cudnn_frontend::graph
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/node_interface.h b/deps/cudnn-frontend/include/cudnn_frontend/node_interface.h
new file mode 100644
index 0000000..8d46ece
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/node_interface.h
@@ -0,0 +1,557 @@
+#pragma once
+
+#include <memory>
+#include <vector>
+#include <unordered_map>
+#include <variant>
+#include <limits>
+
+#include <cuda_fp16.h>
+#include <cuda_bf16.h>
+
+#include "../cudnn_frontend_Tensor.h"
+#include "../cudnn_frontend_Operation.h"
+#include "../cudnn_frontend_OperationGraph.h"
+#include "../cudnn_frontend_ExecutionPlan.h"
+#include "../cudnn_frontend_VariantPack.h"
+#include "../cudnn_frontend_shim.h"
+
+#include "cudnn_interface.h"
+
+#include "graph_properties.h"
+
+namespace cudnn_frontend {
+
+namespace graph {
+
+class BatchNormNode;
+class DBNNode;
+class ConcatenateNode;
+class MatmulNode;
+class MatmulFP8Node;
+class PointwiseNode;
+class ReductionNode;
+class ResampleNode;
+class ReshapeNode;
+class RngNode;
+class CompositeSoftmaxNode;
+class UnifiedSoftmaxNode;
+class MoeGroupedMatmulNode;
+class UnifiedDiagonalBandMaskNode;
+class TransposeNode;
+class SliceNode;
+
+// Interface for all nodes to follow.
+class INode {
+ public:
+ // A closed set of types that are allowed to be passed by value today
+ using pass_by_values_t = Tensor_attributes::pass_by_values_t;
+
+ detail::Context context;
+
+ protected:
+ // Will eventually be moved to Graph class
+ std::unordered_set<std::shared_ptr<Tensor_attributes>> full_graph_outputs;
+ std::shared_ptr<Tensor_attributes>
+ output_tensor(std::string const& name) {
+ auto tensor = std::make_shared<Tensor_attributes>();
+ tensor->set_name(name).set_is_virtual(true);
+ full_graph_outputs.insert(tensor);
+ return tensor;
+ }
+
+ private:
+ virtual error_t
+ pre_validate_node() const {
+ return {error_code_t::OK, ""};
+ };
+
+ virtual error_t
+ infer_properties_node() = 0;
+
+ virtual error_t
+ expand_node() {
+ return {error_code_t::OK, ""};
+ };
+
+ virtual error_t
+ post_validate_node() const {
+ return {error_code_t::OK, ""};
+ };
+
+ virtual int64_t
+ get_fe_workspace_size_node() const {
+ return 0;
+ }
+
+ virtual error_t
+ collect_pass_by_value_tensors_node(std::unordered_map<Tensor_attributes::uid_t, pass_by_values_t>&) const {
+ return {error_code_t::OK, ""};
+ };
+
+ virtual error_t
+ collect_variant_pack_replacements_node(
+ std::unordered_map<Tensor_attributes::uid_t, std::pair<Tensor_attributes::uid_t, int64_t>>&) const {
+ return {error_code_t::OK, ""};
+ };
+
+ virtual error_t
+ collect_tensors_to_dump_node(std::vector<std::pair<std::shared_ptr<Tensor_attributes>, char>>&) const {
+ return {error_code_t::OK, ""};
+ };
+
+ virtual error_t
+ create_cudnn_tensors_node(
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& uid_to_backend_tensors,
+ int64_t& potential_uid,
+ std::unordered_set<int64_t> const& used_uids) const = 0;
+
+ virtual error_t
+ collect_tensors_in_workspace_node(
+ std::unordered_map<Tensor_attributes::uid_t, std::tuple<int64_t, int64_t, std::vector<float>>>&,
+ int64_t&) const {
+ return {error_code_t::OK, ""};
+ }
+
+ protected:
+ // Type of each node. Nodes can either be a composite (value COMPOSITE) or
+ // one of the other primitive types. Primitives types are nothing but
+ // cudnn operations.
+ enum class Type {
+ COMPOSITE,
+ BATCHNORM,
+ BATCHNORM_INFERENCE,
+ BN_FINALIZE,
+ CONVOLUTION,
+ DBN,
+ DBN_WEIGHT,
+ DLN,
+ DIN,
+ DGRAD,
+ DRMSNorm,
+ GENSTATS,
+ LAYERNORM,
+ INSTANCENORM,
+ MATMUL,
+ POINTWISE,
+ REDUCTION,
+ RESAMPLE,
+ RESHAPE,
+ RMSNORM,
+ RNG,
+ SLICE,
+ TRANSPOSE,
+ WGRAD,
+ PAGED_CACHE_LOAD,
+ BLOCK_SCALE_QUANTIZE,
+ BLOCK_SCALE_DEQUANTIZE,
+ CONCATENATE,
+ ADALAYERNORM,
+ DADALAYERNORM,
+ SDPA,
+ ROPE,
+ ROPE_BWD,
+ MOE_GROUPED_MATMUL,
+ MOE_GROUPED_MATMUL_BWD,
+ DIAGONAL_BAND_MASK,
+ SOFTMAX,
+ };
+ Type tag;
+
+ inline void
+ matmul(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ Matmul_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c);
+
+ void
+ matmul_fp8(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ std::shared_ptr<Tensor_attributes> descale_a,
+ std::shared_ptr<Tensor_attributes> descale_b,
+ std::shared_ptr<Tensor_attributes> scale_c,
+ Matmul_fp8_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c,
+ std::shared_ptr<Tensor_attributes> amax_c);
+
+ void
+ softmax(std::shared_ptr<Tensor_attributes> p,
+ Softmax_attributes attributes,
+ std::shared_ptr<Tensor_attributes> s,
+ std::shared_ptr<Tensor_attributes> stats,
+ std::shared_ptr<Tensor_attributes> max,
+ std::shared_ptr<Tensor_attributes> sum_exp);
+
+ void
+ softmax(std::shared_ptr<Tensor_attributes> p,
+ Softmax_attributes attributes,
+ std::shared_ptr<Tensor_attributes> s,
+ std::shared_ptr<Tensor_attributes> m,
+ std::shared_ptr<Tensor_attributes> zinv);
+
+ void
+ pointwise(std::shared_ptr<Tensor_attributes> a,
+ Pointwise_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c);
+
+ void
+ pointwise(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ Pointwise_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c);
+
+ void
+ pointwise(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> b,
+ std::shared_ptr<Tensor_attributes> c,
+ Pointwise_attributes attributes,
+ std::shared_ptr<Tensor_attributes> d);
+
+ void
+ reduction(std::shared_ptr<Tensor_attributes> a,
+ Reduction_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c);
+
+ void
+ reduction(std::shared_ptr<Tensor_attributes> a,
+ std::shared_ptr<Tensor_attributes> group_offset,
+ Reduction_attributes attributes,
+ std::shared_ptr<Tensor_attributes> c);
+
+ void
+ rng(std::shared_ptr<Tensor_attributes> seed,
+ std::shared_ptr<Tensor_attributes> offset,
+ Rng_attributes attributes,
+ std::shared_ptr<Tensor_attributes> y);
+
+ void
+ paged_cache_load(std::shared_ptr<Tensor_attributes> container,
+ std::shared_ptr<Tensor_attributes> seqLen,
+ std::shared_ptr<Tensor_attributes> pageTable,
+ PagedCacheLoad_attributes attributes,
+ std::shared_ptr<Tensor_attributes> yOut);
+
+ void
+ block_scale_quantize(std::shared_ptr<Tensor_attributes> x,
+ Block_scale_quantize_attributes attributes,
+ std::shared_ptr<Tensor_attributes> y,
+ std::shared_ptr<Tensor_attributes> scale);
+
+ void
+ block_scale_dequantize(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> scale,
+ Block_scale_dequantize_attributes attributes,
+ std::shared_ptr<Tensor_attributes> y);
+
+ void
+ concatenate(std::vector<std::shared_ptr<Tensor_attributes>> x,
+ Concatenate_attributes attributes,
+ std::shared_ptr<Tensor_attributes> y);
+
+ void
+ moe_grouped_matmul(std::shared_ptr<Tensor_attributes> token,
+ std::shared_ptr<Tensor_attributes> weight,
+ std::shared_ptr<Tensor_attributes> first_token_offset,
+ std::shared_ptr<Tensor_attributes> token_index,
+ std::shared_ptr<Tensor_attributes> token_ks,
+ Moe_grouped_matmul_attributes attributes,
+ std::shared_ptr<Tensor_attributes> output);
+
+ void
+ moe_grouped_matmul_bwd(std::shared_ptr<Tensor_attributes> doutput,
+ std::shared_ptr<Tensor_attributes> token,
+ std::shared_ptr<Tensor_attributes> first_token_offset,
+ Moe_grouped_matmul_bwd_attributes attributes,
+ std::shared_ptr<Tensor_attributes> dweight);
+
+ void
+ transpose(std::shared_ptr<Tensor_attributes> input,
+ Transpose_attributes attributes,
+ std::shared_ptr<Tensor_attributes> output);
+
+ void
+ slice(std::shared_ptr<Tensor_attributes> input,
+ Slice_attributes attributes,
+ std::shared_ptr<Tensor_attributes> output);
+ error_t
+ validate_subtree() {
+ // pre validate to catch errors early
+ // Otherwise code reability decreases in expand_and_infer
+ CHECK_CUDNN_FRONTEND_ERROR(pre_validate_node());
+ CHECK_CUDNN_FRONTEND_ERROR(infer_properties_node());
+ for (auto const& sub_node : sub_nodes) {
+ CHECK_CUDNN_FRONTEND_ERROR(sub_node->validate_subtree());
+ }
+ CHECK_CUDNN_FRONTEND_ERROR(post_validate_node());
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ expand_subtree() {
+ // Validate self
+ CHECK_CUDNN_FRONTEND_ERROR(pre_validate_node());
+ CHECK_CUDNN_FRONTEND_ERROR(infer_properties_node());
+ CHECK_CUDNN_FRONTEND_ERROR(expand_node());
+ for (auto const& sub_node : sub_nodes) {
+ CHECK_CUDNN_FRONTEND_ERROR(sub_node->expand_subtree());
+ }
+ CHECK_CUDNN_FRONTEND_ERROR(post_validate_node());
+ return {error_code_t::OK, ""};
+ }
+
+ // Creates cudnn tensors for each node (and its sub nodes)
+ error_t
+ create_cudnn_tensors_subtree(
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& uid_to_backend_tensors,
+ int64_t& potential_uid,
+ std::unordered_set<int64_t> const& used_uids) const {
+ CHECK_CUDNN_FRONTEND_ERROR(create_cudnn_tensors_node(uid_to_backend_tensors, potential_uid, used_uids));
+ for (auto const& sub_node : sub_nodes) {
+ CHECK_CUDNN_FRONTEND_ERROR(
+ sub_node->create_cudnn_tensors_subtree(uid_to_backend_tensors, potential_uid, used_uids));
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ collect_pass_by_value_tensors_subtree(
+ std::unordered_map<Tensor_attributes::uid_t, pass_by_values_t>& tensor_to_pass_by_value) const {
+ CHECK_CUDNN_FRONTEND_ERROR(collect_pass_by_value_tensors_node(tensor_to_pass_by_value));
+ for (auto const& sub_node : sub_nodes) {
+ CHECK_CUDNN_FRONTEND_ERROR(sub_node->collect_pass_by_value_tensors_subtree(tensor_to_pass_by_value));
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ collect_tensors_in_workspace_subtree(
+ std::unordered_map<Tensor_attributes::uid_t, std::tuple<int64_t, int64_t, std::vector<float>>>&
+ worskspace_modifications,
+ int64_t& offset) const {
+ CHECK_CUDNN_FRONTEND_ERROR(collect_tensors_in_workspace_node(worskspace_modifications, offset));
+ offset = get_fe_workspace_size_node();
+ for (auto const& sub_node : sub_nodes) {
+ CHECK_CUDNN_FRONTEND_ERROR(
+ sub_node->collect_tensors_in_workspace_subtree(worskspace_modifications, offset));
+ offset += sub_node->get_fe_workspace_size_node();
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ collect_variant_pack_replacements_subtree(
+ std::unordered_map<Tensor_attributes::uid_t, std::pair<Tensor_attributes::uid_t, int64_t>>& replacements)
+ const {
+ CHECK_CUDNN_FRONTEND_ERROR(collect_variant_pack_replacements_node(replacements));
+ for (auto const& sub_node : sub_nodes) {
+ CHECK_CUDNN_FRONTEND_ERROR(sub_node->collect_variant_pack_replacements_subtree(replacements));
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ collect_tensors_to_dump_subtree(
+ std::vector<std::pair<std::shared_ptr<Tensor_attributes>, char>>& tensors_to_dump) const {
+ CHECK_CUDNN_FRONTEND_ERROR(collect_tensors_to_dump_node(tensors_to_dump));
+ for (auto const& sub_node : sub_nodes) {
+ CHECK_CUDNN_FRONTEND_ERROR(sub_node->collect_tensors_to_dump_subtree(tensors_to_dump));
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ int64_t
+ get_fe_workspace_size_subtree() const {
+ int64_t fe_workspace_size = get_fe_workspace_size_node();
+ for (auto const& sub_node : sub_nodes) {
+ fe_workspace_size += sub_node->get_fe_workspace_size_subtree();
+ }
+ return fe_workspace_size;
+ }
+
+ // Creates cudnn operation for each node (and its sub nodes)
+ // Only INode that map to a primitive cudnn operation need to specialize.
+ virtual error_t
+ create_cudnn_operations(
+ std::unordered_set<Tensor_attributes::uid_t>& uids_involved_in_operation,
+ std::vector<std::shared_ptr<cudnn_frontend::Operation>>& backend_operations,
+ managed_backend_descriptor_t& raw_operations,
+ std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& uid_to_backend_tensors) const {
+ for (auto const& sub_node : sub_nodes) {
+ CHECK_CUDNN_FRONTEND_ERROR(sub_node->create_cudnn_operations(
+ uids_involved_in_operation, backend_operations, raw_operations, uid_to_backend_tensors));
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ // An implicitly topological-sorted vector of sub nodes.
+ // The sorted order is a side effect of functional API.
+ std::vector<std::shared_ptr<INode>> sub_nodes;
+
+ public:
+ virtual Type
+ getType() = 0;
+
+ virtual std::pair<int64_t, std::unordered_map<KnobType_t, int64_t>>
+ override_heuristics_query() const {
+ return {-1, {}};
+ }
+
+ std::shared_ptr<Tensor_attributes> matmul(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Matmul_attributes);
+
+ std::shared_ptr<Tensor_attributes> pointwise(std::shared_ptr<Tensor_attributes>, Pointwise_attributes);
+ std::shared_ptr<Tensor_attributes> pointwise(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Pointwise_attributes);
+ std::shared_ptr<Tensor_attributes> pointwise(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Pointwise_attributes);
+
+ std::shared_ptr<Tensor_attributes> reduction(std::shared_ptr<Tensor_attributes>, Reduction_attributes);
+ std::shared_ptr<Tensor_attributes> reduction(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Reduction_attributes);
+ std::array<std::shared_ptr<Tensor_attributes>, 2> resample(std::shared_ptr<Tensor_attributes>, Resample_attributes);
+ std::shared_ptr<Tensor_attributes> reshape(std::shared_ptr<Tensor_attributes>, Reshape_attributes);
+ std::shared_ptr<Tensor_attributes> transpose(std::shared_ptr<Tensor_attributes>, Transpose_attributes);
+ std::shared_ptr<Tensor_attributes> slice(std::shared_ptr<Tensor_attributes>, Slice_attributes);
+
+ std::shared_ptr<Tensor_attributes> rng(std::shared_ptr<Tensor_attributes>,
+ std::shared_ptr<Tensor_attributes>,
+ Rng_attributes);
+
+ std::shared_ptr<Tensor_attributes>
+ diagonal_band_mask(std::shared_ptr<Tensor_attributes> x,
+ std::shared_ptr<Tensor_attributes> b,
+ std::shared_ptr<Tensor_attributes> seq_len_q,
+ std::shared_ptr<Tensor_attributes> seq_len_kv,
+ std::shared_ptr<Tensor_attributes> cu_seq_len_q,
+ std::shared_ptr<Tensor_attributes> cu_seq_len_kv,
+ std::shared_ptr<Tensor_attributes> left_bound,
+ std::shared_ptr<Tensor_attributes> shift_right_bound,
+ DiagonalBandMask_attributes attributes);
+
+ INode(detail::Context const& context) : context(context) {}
+
+ // Make sure each node implements a public serialize function
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ virtual void
+ serialize(json& j) const = 0;
+#endif
+
+ virtual size_t
+ key() {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ json j;
+ serialize(j);
+ return std::hash<json>{}(j);
+#else
+ return 1;
+#endif
+ }
+
+ virtual ~INode() = default;
+};
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+[[maybe_unused]] static void
+to_json(json& j, const INode& p) {
+ p.serialize(j);
+}
+#endif
+
+template <typename DerivedT>
+class NodeCRTP : public INode {
+ DerivedT&
+ self() {
+ return *static_cast<DerivedT*>(this);
+ }
+ DerivedT const&
+ self() const {
+ return *static_cast<DerivedT const*>(this);
+ }
+
+ error_t
+ collect_pass_by_value_tensors_node(
+ std::unordered_map<Tensor_attributes::uid_t, pass_by_values_t>& tensor_to_pass_by_value) const override final {
+ CHECK_CUDNN_FRONTEND_ERROR(self().attributes.fill_pass_by_value(tensor_to_pass_by_value));
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ create_cudnn_tensors_node(std::unordered_map<int64_t, std::shared_ptr<cudnn_frontend::Tensor>>& tensors,
+ int64_t& potential_uid,
+ std::unordered_set<int64_t> const& used_uids) const override {
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Creating cudnn tensors for node named '" << self().attributes.name << "':");
+
+ if constexpr (std::is_same_v<DerivedT, ConcatenateNode>) {
+ for (auto const& tensor : self().attributes.inputs) {
+ if (tensor) {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_cudnn_tensor(tensor, tensors, potential_uid, used_uids));
+ }
+ }
+ } else {
+ for (auto const& [name, tensor] : self().attributes.inputs) {
+ (void)name;
+ if (tensor) {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_cudnn_tensor(tensor, tensors, potential_uid, used_uids));
+ }
+ }
+ }
+
+ for (auto const& [name, tensor] : self().attributes.outputs) {
+ (void)name;
+ if (tensor) {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_cudnn_tensor(tensor, tensors, potential_uid, used_uids));
+ }
+ }
+
+ // Handle special case of BN where peer_stats is also an input
+ if constexpr (std::is_same_v<DerivedT, DBNNode> || std::is_same_v<DerivedT, BatchNormNode>) {
+ // Special case in BN where peer stats is also an input but is not present in inputs map
+ for (auto const& tensor : self().attributes.peer_stats) {
+ if (tensor) {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_cudnn_tensor(tensor, tensors, potential_uid, used_uids));
+ }
+ }
+ }
+
+ return {error_code_t::OK, ""};
+ }
+
+ protected:
+ using INode::INode;
+};
+
+#define CUDNN_FE_VALIDATE_TENSOR_(port, map_) \
+ { \
+ auto t = map_.find(port); \
+ bool const has_t = (t != map_.end()) && (t->second != nullptr); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF( \
+ !has_t, error_code_t::ATTRIBUTE_NOT_SET, std::string("Tensor ") + #port + " not set"); \
+ }
+
+#define CUDNN_FE_VALIDATE_AND_ASSIGN_TENSOR_(tensor, port, map_) \
+ auto tensor = map_.find(port); \
+ { \
+ bool const has_t = (tensor != map_.end()) && (tensor->second != nullptr); \
+ RETURN_CUDNN_FRONTEND_ERROR_IF( \
+ !has_t, error_code_t::ATTRIBUTE_NOT_SET, std::string("Tensor ") + #port + " not set"); \
+ }
+
+#define CUDNN_FE_VALIDATE_INPUT_TENSOR(port) CUDNN_FE_VALIDATE_TENSOR_(port, attributes.inputs)
+
+#define CUDNN_FE_VALIDATE_OUTPUT_TENSOR(port) CUDNN_FE_VALIDATE_TENSOR_(port, attributes.outputs)
+
+#define CUDNN_FE_VALIDATE_AND_ASSIGN_INPUT_TENSOR(tensor, port) \
+ CUDNN_FE_VALIDATE_AND_ASSIGN_TENSOR_(tensor, port, attributes.inputs)
+
+#define CUDNN_FE_VALIDATE_AND_ASSIGN_OUTPUT_TENSOR(tensor, port) \
+ CUDNN_FE_VALIDATE_AND_ASSIGN_TENSOR_(tensor, port, attributes.outputs)
+
+} // namespace graph
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/plans.h b/deps/cudnn-frontend/include/cudnn_frontend/plans.h
new file mode 100644
index 0000000..de51929
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/plans.h
@@ -0,0 +1,1175 @@
+#pragma once
+
+#include <optional>
+#include <string>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "knobs.h"
+#include "../cudnn_frontend_EngineConfig.h"
+#include "../cudnn_frontend_Logging.h"
+#include "graph_helpers.h"
+
+#include "backend/execution_helpers.h"
+#include "backend/plan_helpers.h"
+#include "experimental/sm90_sdpa_prefill_engine.h"
+#include "experimental/sm100_sdpa_prefill_engine.h"
+#include "experimental/sm100_rms_norm_silu_engine.h"
+
+namespace cudnn_frontend {
+
+namespace detail {
+
+inline error_t
+execute(cudnnHandle_t handle,
+ ExecutionPlan* plan,
+ std::vector<void*>& device_ptrs,
+ std::vector<int64_t> const& uids,
+ void* workspace_ptr,
+ std::vector<int64_t> const& override_uids,
+ std::vector<std::vector<int64_t>> const& override_shapes,
+ std::vector<std::vector<int64_t>> const& override_strides) {
+ if (plan == nullptr) {
+ return {error_code_t::GRAPH_EXECUTION_FAILED, "No plan found to execute!"};
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executing " << plan->getTag() << "...");
+
+ backend_descriptor variant_pack_descriptor(CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(variant_pack_descriptor.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create variant pack's backend descriptor.");
+
+ CHECK_CUDNN_FRONTEND_ERROR(create_variant_pack(
+ variant_pack_descriptor, device_ptrs, uids, workspace_ptr, override_uids, override_shapes, override_strides));
+ _CUDNN_CHECK_CUDNN_ERROR(execute(handle, plan->get_raw_desc(), variant_pack_descriptor.get_ptr()));
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executed " << plan->getTag() << ".");
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+execute(cudnnHandle_t handle,
+ ExecutionPlan* plan,
+ std::vector<void*>& device_ptrs,
+ std::vector<int64_t> const& uids,
+ void* workspace_ptr) {
+ if (plan == nullptr) {
+ return {error_code_t::GRAPH_EXECUTION_FAILED, "No plan found to execute!"};
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executing " << plan->getTag() << "...");
+
+ backend_descriptor variant_pack_descriptor(CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(variant_pack_descriptor.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create variant pack's backend descriptor.");
+
+ CHECK_CUDNN_FRONTEND_ERROR(create_variant_pack(variant_pack_descriptor, device_ptrs, uids, workspace_ptr));
+ _CUDNN_CHECK_CUDNN_ERROR(execute(handle, plan->get_raw_desc(), variant_pack_descriptor.get_ptr()));
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executed " << plan->getTag() << ".");
+
+ return {error_code_t::OK, ""};
+}
+
+// Raw-pointer overloads. Array length is inferred from uids.size().
+
+inline error_t
+execute(cudnnHandle_t handle,
+ ExecutionPlan* plan,
+ void* const* device_ptrs,
+ std::vector<int64_t> const& uids,
+ void* workspace_ptr) {
+ if (plan == nullptr) {
+ return {error_code_t::GRAPH_EXECUTION_FAILED, "No plan found to execute!"};
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executing " << plan->getTag() << "...");
+
+ backend_descriptor variant_pack_descriptor(CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(variant_pack_descriptor.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create variant pack's backend descriptor.");
+
+ CHECK_CUDNN_FRONTEND_ERROR(create_variant_pack(variant_pack_descriptor, device_ptrs, uids, workspace_ptr));
+ _CUDNN_CHECK_CUDNN_ERROR(execute(handle, plan->get_raw_desc(), variant_pack_descriptor.get_ptr()));
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executed " << plan->getTag() << ".");
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+execute(cudnnHandle_t handle,
+ ExecutionPlan* plan,
+ void* const* device_ptrs,
+ std::vector<int64_t> const& uids,
+ void* workspace_ptr,
+ std::vector<int64_t> const& override_uids,
+ std::vector<std::vector<int64_t>> const& override_shapes,
+ std::vector<std::vector<int64_t>> const& override_strides) {
+ if (plan == nullptr) {
+ return {error_code_t::GRAPH_EXECUTION_FAILED, "No plan found to execute!"};
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executing " << plan->getTag() << "...");
+
+ backend_descriptor variant_pack_descriptor(CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(variant_pack_descriptor.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to create variant pack's backend descriptor.");
+
+ CHECK_CUDNN_FRONTEND_ERROR(create_variant_pack(
+ variant_pack_descriptor, device_ptrs, uids, workspace_ptr, override_uids, override_shapes, override_strides));
+ _CUDNN_CHECK_CUDNN_ERROR(execute(handle, plan->get_raw_desc(), variant_pack_descriptor.get_ptr()));
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Executed " << plan->getTag() << ".");
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+query_cudnn_heuristics_impl(std::shared_ptr<OperationGraph_v8> const& operation_graph,
+ cudnn_frontend::EngineConfigList& configs,
+ std::vector<HeurMode_t> const& modes,
+ int32_t sm_count,
+ std::shared_ptr<const DeviceProperties> device_properties = nullptr) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ operation_graph == nullptr,
+ error_code_t::HEURISTIC_QUERY_FAILED,
+ "Empty operation graph provided. Did you forget to call graph.build_operation_graph()?");
+
+ auto const& operation_graph_tag = operation_graph->getTag();
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: " << " Getting plan from heuristics for " << operation_graph_tag << " ...");
+
+ std::vector<cudnnStatus_t> statuses;
+#ifdef NV_CUDNN_DISABLE_EXCEPTION
+ // disable exception macro is defined. Calling build will not throw.
+ // Check status of desc and return error.
+ statuses = cudnn_frontend::get_heuristics_list(
+ modes, *operation_graph, allowAllConfig, configs, true, sm_count, device_properties);
+#else
+ // build() can throw
+ // wrap in try catch
+ try {
+ statuses = cudnn_frontend::get_heuristics_list(
+ modes, *operation_graph, allowAllConfig, configs, true, sm_count, device_properties);
+ } catch (cudnn_frontend::cudnnException& e) {
+ // Silly MSVC error that thinks below condition is constexpr
+ // RETURN_CUDNN_FRONTEND_ERROR_IF(
+ // e.getCudnnStatus() != CUDNN_STATUS_SUCCESS, error_code_t::HEURISTIC_QUERY_FAILED, e.what());
+ CUDNN_FE_LOG_LABEL("ERROR: " << e.what() << ". ");
+ CUDNN_FE_LOG(error_code_t::HEURISTIC_QUERY_FAILED << " because querying heuristics failed at " << __FILE__
+ << ":" << __LINE__ << "\n");
+ return {error_code_t::HEURISTIC_QUERY_FAILED, e.what()};
+ }
+#endif
+
+ CUDNN_FE_LOG_LABEL("INFO: get_heuristics_list statuses: ");
+ for (size_t i = 0; i < statuses.size(); i++) {
+ CUDNN_FE_LOG(cudnn_frontend::to_string(statuses[i]) << " ");
+ }
+ CUDNN_FE_LOG(std::endl);
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: config list has " << configs.size() << " configurations.");
+
+ if (configs.empty()) {
+ std::string err_msg = detail::get_last_error_string_();
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: No valid engine configs returned from heuristics.\n" << err_msg);
+ return {error_code_t::HEURISTIC_QUERY_FAILED,
+ "No valid engine configs for " + operation_graph_tag + "\n" + err_msg};
+ }
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+create_cudnn_execution_plan(std::shared_ptr<ExecutionPlan>& plan,
+ std::string const& serialized_data,
+ cudnnHandle_t handle) {
+ auto&& plan_builder = cudnn_frontend::ExecutionPlanBuilder();
+
+ plan_builder.setHandle(handle);
+
+#ifdef NV_CUDNN_DISABLE_EXCEPTION
+ // disable exception macro is defined. Calling build will not throw.
+ // Check status of desc and return error.
+ auto built_plan = plan_builder.loadFromJson(serialized_data);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(built_plan.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ built_plan.get_error());
+ plan = std::make_shared<ExecutionPlan>(std::move(built_plan));
+#else
+ // build() can throw
+ // wrap in try catch
+ try {
+ auto built_plan = plan_builder.loadFromJson(serialized_data);
+ plan = std::make_shared<ExecutionPlan>(std::move(built_plan));
+ } catch (cudnn_frontend::cudnnException& e) {
+ // Silly MSVC error that thinks below condition is constexpr
+ // RETURN_CUDNN_FRONTEND_ERROR_IF(
+ // e.getCudnnStatus() != CUDNN_STATUS_SUCCESS, error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ // e.what());
+ CUDNN_FE_LOG_LABEL(" ERROR: " << e.what() << ". ");
+ CUDNN_FE_LOG(error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED << " because plan building failed at "
+ << __FILE__ << ":" << __LINE__ << "\n");
+ return {error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED, e.what()};
+ }
+#endif
+
+ return {error_code_t::OK, ""};
+}
+
+inline error_t
+create_cudnn_execution_plan(std::shared_ptr<ExecutionPlan>& plan,
+ ManagedOpaqueDescriptor const& config,
+ std::string const& operation_graph_tag,
+ std::shared_ptr<KernelCache> kernel_cache) {
+ auto&& plan_builder = cudnn_frontend::ExecutionPlanBuilder();
+
+ plan_builder.setEngineConfig(config, operation_graph_tag).setKernelCache(kernel_cache);
+
+#ifdef NV_CUDNN_DISABLE_EXCEPTION
+ // disable exception macro is defined. Calling build will not throw.
+ // Check status of desc and return error.
+ auto built_plan = plan_builder.build();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(built_plan.get_status() != CUDNN_STATUS_SUCCESS,
+ error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ built_plan.get_error());
+ plan = std::make_shared<ExecutionPlan>(std::move(built_plan));
+#else
+ // build() can throw
+ // wrap in try catch
+ try {
+ auto built_plan = plan_builder.build();
+ plan = std::make_shared<ExecutionPlan>(std::move(built_plan));
+ } catch (cudnn_frontend::cudnnException& e) {
+ // Silly MSVC error that thinks below condition is constexpr
+ // RETURN_CUDNN_FRONTEND_ERROR_IF(
+ // e.getCudnnStatus() != CUDNN_STATUS_SUCCESS, error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ // e.what());
+ CUDNN_FE_LOG_LABEL("ERROR: " << e.what() << ". ");
+ CUDNN_FE_LOG(error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED << " because plan building failed at "
+ << __FILE__ << ":" << __LINE__ << "\n");
+ return {error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED, e.what()};
+ }
+#endif
+
+ return {error_code_t::OK, ""};
+}
+
+} // namespace detail
+
+namespace graph {
+class Execution_plan_list {
+ std::string operation_tag;
+
+ std::vector<bool> barred_indices;
+ std::shared_ptr<KernelCache> kernel_cache = nullptr;
+
+ int64_t max_workspace_allowed = std::numeric_limits<int64_t>::max();
+ int64_t max_shared_mem_allowed = 1024 * 1024 * 1024; // Crazy high number (2GB) which will never be hit
+
+ std::vector<std::string> barred_engine_names = {};
+ EngineConfigList engine_configs;
+
+ error_t
+ _build_plan_at_index_impl(int64_t index) {
+ if (execution_plans[index] == nullptr) {
+ CHECK_CUDNN_FRONTEND_ERROR(detail::create_cudnn_execution_plan(
+ execution_plans[index], engine_configs[index], operation_tag, kernel_cache));
+ }
+
+ auto is_blocked = [](std::string const& full_name, std::vector<std::string> const& blocked_names) -> bool {
+ for (auto const& blocked_name : blocked_names) {
+ if (full_name.find(blocked_name) != std::string::npos) {
+ return true;
+ }
+ }
+ return false;
+ };
+ auto const& plan_tag = execution_plans[index]->getTag();
+ if (is_blocked(plan_tag, barred_engine_names)) {
+ barred_indices[index] = true;
+
+ return {error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "[cudnn_frontend] Error: Deselecting execution plan with name " + plan_tag + " at position " +
+ std::to_string(index)};
+ }
+
+ // workspace check for 9.2+ is already done at engine config level
+ if (detail::get_backend_version() < 90200 || detail::get_compiled_version() < 90200) {
+ if (execution_plans[index]->getWorkspaceSize() > max_workspace_allowed) {
+ barred_indices[index] = true;
+ return {error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "[cudnn_frontend] Error: Workspace size is too large."};
+ }
+ }
+
+ // Sets candidate in case user does not call execute with plan_index later.
+ candidate = index;
+
+ return {error_code_t::OK, ""};
+ }
+
+ public:
+ std::vector<std::vector<NumericalNote_t>> numeric_notes;
+ std::vector<std::vector<BehaviorNote_t>> behavior_notes;
+
+ std::vector<std::shared_ptr<ExecutionPlan>>
+ execution_plans; // a built plan corresponding to each engine config, irrespective of whether config is
+ // selected or deselected.
+
+ // Stores position of best plan in above vector of execution plan
+ int64_t candidate = -1;
+
+ void
+ set_tag(std::string const& tag) {
+ operation_tag = tag;
+ }
+ void
+ enqueue_engine_configs(EngineConfigList list) {
+ std::move(list.begin(), list.end(), back_inserter(engine_configs));
+ }
+ void
+ set_kernel_cache(std::shared_ptr<KernelCache> kernel_cache_) {
+ kernel_cache = kernel_cache_;
+ }
+
+ std::vector<std::shared_ptr<ExecutionPlan>>&
+ get_execution_plans() {
+ return execution_plans;
+ }
+
+ error_t
+ query_properties() {
+ numeric_notes.reserve(engine_configs.size());
+ behavior_notes.reserve(engine_configs.size());
+
+ barred_indices.resize(engine_configs.size(), 0);
+ execution_plans.resize(engine_configs.size());
+
+ for (auto& engine_config : engine_configs) {
+ int64_t elem_count = 0;
+ std::vector<cudnnBackendNumericalNote_t> numeric;
+ std::vector<cudnnBackendBehaviorNote_t> behavior;
+
+ ManagedOpaqueDescriptor extractedEngine = make_shared_backend_pointer(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ cudnnBackendDescriptor_t extractedEngine_ = extractedEngine->get_backend_descriptor();
+ auto status = detail::get_attribute(engine_config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_ENGINE,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &elem_count,
+ &extractedEngine_);
+ RETURN_CUDNN_FRONTEND_ERROR_IF((status != CUDNN_STATUS_SUCCESS),
+ error_code_t::HEURISTIC_QUERY_FAILED,
+ "Heuristic query Engine failed.");
+
+ status = detail::get_attribute(extractedEngine_,
+ CUDNN_ATTR_ENGINE_NUMERICAL_NOTE,
+ CUDNN_TYPE_NUMERICAL_NOTE,
+ CUDNN_NUMERICAL_NOTE_TYPE_COUNT,
+ &elem_count,
+ nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF((status != CUDNN_STATUS_SUCCESS),
+ error_code_t::HEURISTIC_QUERY_FAILED,
+ "Heuristic query Numerical Note failed");
+
+ numeric.resize(static_cast<size_t>(elem_count));
+ status = detail::get_attribute(extractedEngine_,
+ CUDNN_ATTR_ENGINE_NUMERICAL_NOTE,
+ CUDNN_TYPE_NUMERICAL_NOTE,
+ CUDNN_NUMERICAL_NOTE_TYPE_COUNT,
+ &elem_count,
+ numeric.data());
+ RETURN_CUDNN_FRONTEND_ERROR_IF((status != CUDNN_STATUS_SUCCESS),
+ error_code_t::HEURISTIC_QUERY_FAILED,
+ "Heuristic query Numerical Note failed");
+ status = detail::get_attribute(extractedEngine_,
+ CUDNN_ATTR_ENGINE_BEHAVIOR_NOTE,
+ CUDNN_TYPE_BEHAVIOR_NOTE,
+ CUDNN_BEHAVIOR_NOTE_TYPE_COUNT,
+ &elem_count,
+ nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF((status != CUDNN_STATUS_SUCCESS),
+ error_code_t::HEURISTIC_QUERY_FAILED,
+ "Heuristic query Behavior Note failed");
+
+ behavior.resize(static_cast<size_t>(elem_count));
+ status = detail::get_attribute(extractedEngine_,
+ CUDNN_ATTR_ENGINE_BEHAVIOR_NOTE,
+ CUDNN_TYPE_BEHAVIOR_NOTE,
+ CUDNN_BEHAVIOR_NOTE_TYPE_COUNT,
+ &elem_count,
+ behavior.data());
+ RETURN_CUDNN_FRONTEND_ERROR_IF((status != CUDNN_STATUS_SUCCESS),
+ error_code_t::HEURISTIC_QUERY_FAILED,
+ "Heuristic query Behavior Note failed");
+
+ std::vector<NumericalNote_t> numerics;
+ numerics.resize(numeric.size());
+ for (auto& note : numeric) {
+ numerics.push_back(detail::convert_from_cudnn_type(note));
+ }
+ numeric_notes.emplace_back(std::move(numerics));
+
+ std::vector<BehaviorNote_t> behaviors;
+ behaviors.reserve(behaviors.size());
+ for (auto& note : behavior) {
+ behaviors.push_back(detail::convert_from_cudnn_type(note));
+ }
+ behavior_notes.emplace_back(std::move(behaviors));
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ filter_numeric_notes(std::vector<NumericalNote_t> const& notes, bool const keep) {
+ for (auto& note : notes) {
+ for (auto i = 0u; i < engine_configs.size(); i++) {
+ bool has_barred_note =
+ std::find(numeric_notes[i].begin(), numeric_notes[i].end(), note) != numeric_notes[i].end();
+
+ barred_indices[i] = barred_indices[i] || (has_barred_note ? !keep : keep);
+ }
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ filter_behavior_notes(std::vector<BehaviorNote_t> const& notes, bool const keep) {
+ for (auto& note : notes) {
+ for (auto i = 0u; i < engine_configs.size(); i++) {
+ bool has_barred_note =
+ std::find(behavior_notes[i].begin(), behavior_notes[i].end(), note) != behavior_notes[i].end();
+
+ barred_indices[i] = barred_indices[i] || (has_barred_note ? !keep : keep);
+ }
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ void
+ set_max_workspace_allowed(int64_t const workspace_allowed) {
+ max_workspace_allowed = workspace_allowed;
+ }
+
+ void
+ set_max_shared_mem_allowed(int64_t const smem_allowed) {
+ max_shared_mem_allowed = smem_allowed;
+ }
+
+ void
+ set_barred_names(std::vector<std::string> const& engine_names) {
+ barred_engine_names = engine_names;
+ }
+
+ EngineConfigList
+ get_barred_engine_configs() {
+ EngineConfigList barred_engine_configs;
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: " << " Filtering engine_configs ..." << engine_configs.size());
+ for (auto i = 0u; i < engine_configs.size(); i++) {
+ if (barred_indices[i] == false) {
+ barred_engine_configs.push_back(engine_configs[i]);
+ }
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: " << " barred engine_configs ..." << barred_engine_configs.size());
+ return barred_engine_configs;
+ }
+
+ error_t
+ get_name_at_index(int64_t index, std::string& name) const {
+ name = detail::get_engine_tag(engine_configs[index]);
+ return {error_code_t::OK, ""};
+ }
+
+ // Structured counterpart of get_name_at_index(): engine index + knob choices,
+ // suitable for replay via Graph::create_execution_plan(engine_id, knobs).
+ error_t
+ get_engine_and_knobs_at_index(int64_t index,
+ int64_t& engine_id,
+ std::unordered_map<KnobType_t, int64_t>& knobs) const {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(index < 0 || index >= static_cast<int64_t>(engine_configs.size()),
+ error_code_t::GRAPH_EXECUTION_FAILED,
+ "Plan index " + std::to_string(index) + " is invalid.");
+ std::vector<std::pair<cudnnBackendKnobType_t, int64_t>> backend_knobs;
+ auto status = detail::get_engine_id_and_knobs(engine_configs[index], engine_id, backend_knobs);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ status != CUDNN_STATUS_SUCCESS,
+ error_code_t::CUDNN_BACKEND_API_FAILED,
+ "Failed to query engine id / knob choices for plan at index " + std::to_string(index));
+ knobs.clear();
+ for (auto const& backend_knob : backend_knobs) {
+ knobs[convert_from_backend_knob_type(backend_knob.first)] = backend_knob.second;
+ }
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ check_support_at_index(int64_t index) {
+ // Ignore if the engine config was deselected.
+ // This usually happens when user deselects by numerical and behavioural notes.
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF((index < 0) || (static_cast<int64_t>(barred_indices.size()) <= index),
+ error_code_t::GRAPH_EXECUTION_FAILED,
+ "Plan index " + std::to_string(index) + " is invalid.");
+
+ if (barred_indices[index] == true) {
+ CUDNN_FE_LOG_LABEL_ENDL("Deselecting execution plan at position " << index);
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(barred_indices[index] == true,
+ error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "Deselecting execution plan");
+
+ // Ignore if engine name was specified to be ignored by the user.
+ auto is_blocked = [](std::string const& full_name, std::vector<std::string> const& blocked_names) -> bool {
+ for (auto const& blocked_name : blocked_names) {
+ if (full_name.find(blocked_name) != std::string::npos) {
+ return true;
+ }
+ }
+ return false;
+ };
+ auto cfg_tag = detail::get_engine_tag(engine_configs[index]);
+ if (is_blocked(cfg_tag, barred_engine_names)) {
+ barred_indices[index] = true;
+ return {error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "[cudnn_frontend] Error: Deselecting execution plan with name " + cfg_tag + " at position " +
+ std::to_string(index)};
+ }
+
+ if (detail::get_backend_version() >= 90200 && detail::get_compiled_version() >= 90200) {
+ // Ignore kernels that require larger than tolerable shared memory.
+ int32_t shared_memory_size = INT32_MAX;
+ auto status = detail::get_shared_memory_size(engine_configs[index], shared_memory_size);
+ if (status.is_bad()) {
+ CUDNN_FE_LOG_LABEL_ENDL("WARN: Unknown Shared memory size, so not deselecting plan at position "
+ << index);
+ } else if (shared_memory_size > max_shared_mem_allowed) {
+ barred_indices[index] = true;
+ return {error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "[cudnn_frontend] Error: Skipping plan since shared memory violation. Requires " +
+ std::to_string(shared_memory_size)};
+ }
+
+ // Filter by workspace can happen at this engine config stage itself.
+ int64_t workspace_size = INT64_MAX;
+ CHECK_CUDNN_FRONTEND_ERROR(detail::get_workspace_size(engine_configs[index], workspace_size));
+ if (workspace_size > max_workspace_allowed) {
+ barred_indices[index] = true;
+ return {error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "[cudnn_frontend] Error: Skipping plan since workspace violation. Requires " +
+ std::to_string(workspace_size)};
+ }
+ }
+ // Else we need to build the config. A successful execution plan build means that check_support succeeded.
+ else {
+ CHECK_CUDNN_FRONTEND_ERROR(_build_plan_at_index_impl(index));
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL("Check support for index " << index << " passed with cfg " << cfg_tag);
+ // All checks passed for this config, so return success.
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ check_support() {
+ // Go over each engine config and return true when you find the first one that is supported.
+ for (auto i = 0u; i < engine_configs.size(); i++) {
+ auto status = check_support_at_index(i);
+ if (status.is_good()) {
+ return {error_code_t::OK, ""};
+ }
+ }
+
+ std::string err_msg = detail::get_last_error_string_();
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: No valid engine configs returned from heuristics.\n" << err_msg);
+ return {error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "[cudnn_frontend] Error: No execution plans support the graph." + err_msg};
+ }
+
+ error_t
+ get_behavior_notes_at_index(int64_t const index, std::vector<BehaviorNote_t>& notes) const {
+ RETURN_CUDNN_FRONTEND_ERROR_IF((index < 0) || (static_cast<int64_t>(behavior_notes.size()) <= index),
+ error_code_t::GRAPH_EXECUTION_FAILED,
+ "Plan index " + std::to_string(index) + " is invalid.");
+
+ notes = behavior_notes[index];
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ build_plans(cudnnHandle_t handle, std::string const& json) {
+ execution_plans.resize(1);
+ auto const& fe_status = detail::create_cudnn_execution_plan(execution_plans[0], json, handle);
+
+ if (fe_status.is_good()) {
+ candidate = 0;
+ }
+
+ return fe_status;
+ }
+
+ error_t
+ build_plan_at_index(int64_t index) {
+ CHECK_CUDNN_FRONTEND_ERROR(check_support_at_index(index));
+ CHECK_CUDNN_FRONTEND_ERROR(_build_plan_at_index_impl(index));
+
+ return {error_code_t::OK, ""};
+ }
+
+ error_t
+ build_plans(BuildPlanPolicy_t const policy, bool const do_multithreaded_builds) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(do_multithreaded_builds,
+ error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "Doing multithreaded builds is not yet supported.");
+
+ // short circuit in case a plan was already created.
+ // This happens as check_support for v8 builds a plan.
+ if (policy == BuildPlanPolicy_t::HEURISTICS_CHOICE && candidate != -1) {
+ return {error_code_t::OK, ""};
+ }
+
+ for (auto i = 0u; i < engine_configs.size(); i++) {
+ auto status = build_plan_at_index(i);
+ if (status.is_bad()) {
+ CUDNN_FE_LOG_LABEL_ENDL("WARN: Failed to build plan at " << i);
+ continue;
+ }
+
+ // Only set the candidate the first time, as the order of iteration is from highest to lowest priority
+ if (candidate == -1) {
+ candidate = static_cast<int64_t>(i);
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: Candidate set as " << i);
+ }
+
+ // Return from this function as first successfully built plan is found.
+ if (policy == BuildPlanPolicy_t::HEURISTICS_CHOICE) {
+ return {error_code_t::OK, ""};
+ }
+ }
+
+ // Return an error if no execution plans could be built
+ RETURN_CUDNN_FRONTEND_ERROR_IF(candidate == -1,
+ error_code_t::GRAPH_EXECUTION_PLAN_CREATION_FAILED,
+ "[cudnn_frontend] Error: No valid execution plans built.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ int64_t
+ get_autotune_workspace() const {
+ int64_t max_size = 0;
+ for (auto& plan : execution_plans) {
+ max_size = std::max(max_size, plan->getWorkspaceSize());
+ }
+ return max_size;
+ }
+
+ static error_t
+ autotune_default_impl(std::vector<std::shared_ptr<ExecutionPlan>>& execution_plans,
+ cudnnHandle_t handle,
+ std::unordered_map<int64_t, void*> const& tensor_to_pointer_map,
+ void* workspace_ptr,
+ void*) {
+ // Create the variant pack for all the plans to use.
+ std::vector<int64_t> uids;
+ std::vector<void*> ptrs;
+ for (auto it : tensor_to_pointer_map) {
+ uids.push_back(it.first);
+ ptrs.push_back(it.second);
+ }
+
+ std::vector<std::shared_ptr<ExecutionPlan>> time_sorted_plans;
+
+ auto plan_cmp = [](std::shared_ptr<ExecutionPlan> a, std::shared_ptr<ExecutionPlan> b) {
+ return a->getExecutionTime() < b->getExecutionTime();
+ };
+
+ std::multiset<std::shared_ptr<ExecutionPlan>, decltype(plan_cmp)> timed_execution_plans(plan_cmp);
+
+ const int maxIterCount = 100;
+ const float threshhold = 0.95f;
+ uint64_t successful_plan_count = 0;
+ cudaEvent_t start, stop;
+ detail::cuda_event_create(&start);
+ detail::cuda_event_create(&stop);
+ detail::cuda_device_synchronize();
+
+ cudaStream_t stream = nullptr;
+ detail::get_stream(handle, &stream);
+
+ for (auto plan : execution_plans) {
+ float time_ms = 0.0f;
+ float final_time_ms = 0.0f;
+ float min_time_ms = std::numeric_limits<float>::max();
+
+ // Warm-up run
+ CHECK_CUDNN_FRONTEND_ERROR(detail::execute(handle, plan.get(), ptrs, uids, workspace_ptr));
+ successful_plan_count++;
+ detail::cuda_device_synchronize();
+
+ for (int i = 0; i < maxIterCount; i++) {
+ detail::cuda_event_record(start, stream);
+
+ auto status = detail::execute(handle, plan.get(), ptrs, uids, workspace_ptr);
+
+ detail::cuda_event_record(stop, stream);
+ detail::cuda_event_synchronize(stop);
+ detail::cuda_event_elapsed_time(&time_ms, start, stop);
+
+ final_time_ms = std::min(min_time_ms, time_ms);
+ if (time_ms / min_time_ms < threshhold) {
+ min_time_ms = final_time_ms;
+ } else {
+ break;
+ }
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL("Plan " << plan->getTag() << " took " << std::setw(10) << final_time_ms);
+ plan->setExecutionTime(final_time_ms);
+ timed_execution_plans.insert(plan);
+ }
+
+ execution_plans.clear();
+ for (auto sorted_plan : timed_execution_plans) {
+ execution_plans.push_back(sorted_plan);
+ }
+
+ detail::cuda_event_destroy(start);
+ detail::cuda_event_destroy(stop);
+
+ CUDNN_FE_LOG_LABEL_ENDL("Autotuned " << successful_plan_count << " plans.");
+ return {error_code_t::OK, ""};
+ }
+
+ std::function<error_t(std::vector<std::shared_ptr<ExecutionPlan>>&,
+ cudnnHandle_t,
+ std::unordered_map<int64_t, void*> const&,
+ void*,
+ void*)>
+ autotune_impl = &Execution_plan_list::autotune_default_impl;
+
+ error_t
+ autotune(cudnnHandle_t handle,
+ std::unordered_map<int64_t, void*> const& tensor_to_pointer_map,
+ void* workspace,
+ void* user_impl = nullptr) {
+ auto error = autotune_impl(execution_plans, handle, tensor_to_pointer_map, workspace, user_impl);
+ return error;
+ }
+
+ error_t
+ is_plan_index_executable(int64_t const index) const {
+ // OSS SDPA engine path
+ if (index == OSS_SDPA_ENGINE_CANDIDATE) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !oss_sdpa_engine_built_, error_code_t::GRAPH_EXECUTION_FAILED, "OSS SDPA engine not built.");
+ return {error_code_t::OK, ""};
+ }
+
+ // OSS RmsNorm+SiLU engine path
+ if (index == OSS_RMS_NORM_SILU_ENGINE_CANDIDATE) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !oss_rms_norm_silu_built_, error_code_t::GRAPH_EXECUTION_FAILED, "OSS RmsNorm+SiLU engine not built.");
+ return {error_code_t::OK, ""};
+ }
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF((index < 0) || (static_cast<int64_t>(execution_plans.size()) <= index),
+ error_code_t::GRAPH_EXECUTION_FAILED,
+ "Plan index " + std::to_string(index) + " is invalid.");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(execution_plans[index] == nullptr,
+ error_code_t::GRAPH_EXECUTION_FAILED,
+ "Plan index " + std::to_string(index) + " did not build.");
+
+ return {error_code_t::OK, ""};
+ }
+
+ // ================================================================
+ // Open-source NVRTC engine support
+ // ================================================================
+
+ static constexpr int64_t OSS_SDPA_ENGINE_CANDIDATE = -2;
+
+ // Context cached from the Graph for OSS engine execution
+ struct OssSdpaEngineContext {
+ int64_t batch = 0, heads_q = 0, heads_kv = 0, seq_q = 0, seq_kv = 0, d = 0;
+ int64_t q_uid = -1, k_uid = -1, v_uid = -1, o_uid = -1, max_uid = -1, sum_exp_uid = -1;
+ std::vector<int64_t> q_stride, k_stride, v_stride, o_stride;
+ std::vector<int64_t> max_stride, sum_exp_stride;
+ std::optional<float> attn_scale;
+ // Pre-computed slot indices into the variant pack template (set by prepare_variant_pack_template)
+ int q_slot = -1, k_slot = -1, v_slot = -1, o_slot = -1, max_slot = -1, sum_exp_slot = -1;
+ };
+
+ void
+ set_oss_sdpa_engine(std::shared_ptr<experimental::IOssSdpaEngine> engine) {
+ oss_sdpa_engine_ = std::move(engine);
+ }
+
+ void
+ set_oss_sdpa_engine_context(OssSdpaEngineContext ctx) {
+ oss_sdpa_ctx_ = std::move(ctx);
+ }
+
+ bool
+ has_oss_sdpa_engine() const {
+ return oss_sdpa_engine_ != nullptr;
+ }
+
+ bool
+ is_oss_sdpa_candidate() const {
+ return candidate == OSS_SDPA_ENGINE_CANDIDATE;
+ }
+
+ error_t
+ check_oss_sdpa_engine_support(int64_t sm_version) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !oss_sdpa_engine_, error_code_t::GRAPH_NOT_SUPPORTED, "No OSS engine registered");
+ cudnn_frontend::experimental::AttentionShape_t shape = {
+ static_cast<uint32_t>(oss_sdpa_ctx_.batch),
+ static_cast<uint32_t>(oss_sdpa_ctx_.heads_q),
+ static_cast<uint32_t>(oss_sdpa_ctx_.heads_kv),
+ static_cast<uint32_t>(oss_sdpa_ctx_.heads_kv),
+ static_cast<uint32_t>(oss_sdpa_ctx_.seq_q),
+ static_cast<uint32_t>(oss_sdpa_ctx_.seq_kv),
+ static_cast<uint32_t>(oss_sdpa_ctx_.d),
+ static_cast<uint32_t>(oss_sdpa_ctx_.d),
+ };
+ auto status = oss_sdpa_engine_->check_support(shape, sm_version);
+ if (status.is_good()) {
+ oss_sdpa_engine_supported_ = true;
+ candidate = OSS_SDPA_ENGINE_CANDIDATE;
+ }
+ return status;
+ }
+
+ error_t
+ build_oss_sdpa_engine() {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !oss_sdpa_engine_supported_, error_code_t::GRAPH_NOT_SUPPORTED, "OSS engine not supported");
+ auto status = oss_sdpa_engine_->build();
+ if (status.is_good()) {
+ oss_sdpa_engine_built_ = true;
+ candidate = OSS_SDPA_ENGINE_CANDIDATE;
+ }
+ return status;
+ }
+
+ // Flat-array execute: takes pre-indexed pointer array (from VariantPackTemplate)
+ error_t
+ execute_oss_sdpa_engine(void* const* ptrs, void* workspace, int device, cudaStream_t stream) const {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !oss_sdpa_engine_built_, error_code_t::GRAPH_EXECUTION_FAILED, "OSS engine not built");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ oss_sdpa_ctx_.q_slot < 0 || oss_sdpa_ctx_.k_slot < 0 || oss_sdpa_ctx_.v_slot < 0 ||
+ oss_sdpa_ctx_.o_slot < 0 || oss_sdpa_ctx_.max_slot < 0 || oss_sdpa_ctx_.sum_exp_slot < 0,
+ error_code_t::INVALID_VARIANT_PACK,
+ "OSS SDPA slot indices not initialized. Call prepare_variant_pack_template() first.");
+
+ void* q_ptr = ptrs[oss_sdpa_ctx_.q_slot];
+ void* k_ptr = ptrs[oss_sdpa_ctx_.k_slot];
+ void* v_ptr = ptrs[oss_sdpa_ctx_.v_slot];
+ void* o_ptr = ptrs[oss_sdpa_ctx_.o_slot];
+ void* max_ptr = ptrs[oss_sdpa_ctx_.max_slot];
+ void* sum_exp_ptr = ptrs[oss_sdpa_ctx_.sum_exp_slot];
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!q_ptr || !k_ptr || !v_ptr || !o_ptr,
+ error_code_t::INVALID_VARIANT_PACK,
+ "Missing Q/K/V/O pointers for OSS engine");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!max_ptr || !sum_exp_ptr,
+ error_code_t::INVALID_VARIANT_PACK,
+ "Missing max/sum_exp pointers for OSS engine");
+
+ return oss_sdpa_engine_->execute(static_cast<int>(oss_sdpa_ctx_.batch),
+ static_cast<int>(oss_sdpa_ctx_.heads_q),
+ static_cast<int>(oss_sdpa_ctx_.heads_kv),
+ static_cast<int>(oss_sdpa_ctx_.seq_q),
+ static_cast<int>(oss_sdpa_ctx_.seq_kv),
+ static_cast<int>(oss_sdpa_ctx_.d),
+ q_ptr,
+ oss_sdpa_ctx_.q_stride,
+ k_ptr,
+ oss_sdpa_ctx_.k_stride,
+ v_ptr,
+ oss_sdpa_ctx_.v_stride,
+ o_ptr,
+ oss_sdpa_ctx_.o_stride,
+ max_ptr,
+ oss_sdpa_ctx_.max_stride,
+ sum_exp_ptr,
+ oss_sdpa_ctx_.sum_exp_stride,
+ workspace,
+ device,
+ stream,
+ oss_sdpa_ctx_.attn_scale);
+ }
+
+ // Flat-array overload with dynamic shape overrides
+ error_t
+ execute_oss_sdpa_engine(void* const* ptrs,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ std::vector<int64_t> const& override_uids,
+ std::vector<std::vector<int64_t>> const& override_shapes,
+ std::vector<std::vector<int64_t>> const& override_strides) const {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !oss_sdpa_engine_built_, error_code_t::GRAPH_EXECUTION_FAILED, "OSS engine not built");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ override_uids.size() != override_shapes.size() || override_uids.size() != override_strides.size(),
+ error_code_t::INVALID_VALUE,
+ "override_uids/shapes/strides must have the same size");
+
+ // Build uid → index lookup for overrides
+ std::unordered_map<int64_t, size_t> uid_to_idx;
+ for (size_t i = 0; i < override_uids.size(); ++i) {
+ uid_to_idx[override_uids[i]] = i;
+ }
+ auto resolve_shape = [&](int64_t uid, std::vector<int64_t> const& def) -> std::vector<int64_t> const& {
+ auto it = uid_to_idx.find(uid);
+ return (it != uid_to_idx.end()) ? override_shapes[it->second] : def;
+ };
+ auto resolve_stride = [&](int64_t uid, std::vector<int64_t> const& def) -> std::vector<int64_t> const& {
+ auto it = uid_to_idx.find(uid);
+ return (it != uid_to_idx.end()) ? override_strides[it->second] : def;
+ };
+
+ // Resolve shapes
+ std::vector<int64_t> q_def = {oss_sdpa_ctx_.batch, oss_sdpa_ctx_.heads_q, oss_sdpa_ctx_.seq_q, oss_sdpa_ctx_.d};
+ auto const& q_shape = resolve_shape(oss_sdpa_ctx_.q_uid, q_def);
+ auto const& q_stride = resolve_stride(oss_sdpa_ctx_.q_uid, oss_sdpa_ctx_.q_stride);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(q_shape.size() < 4, error_code_t::INVALID_VALUE, "Q shape must have >=4 dims");
+ int64_t batch = q_shape[0], heads_q = q_shape[1], seq_q = q_shape[2], d = q_shape[3];
+ RETURN_CUDNN_FRONTEND_ERROR_IF(d != oss_sdpa_ctx_.d,
+ error_code_t::INVALID_VALUE,
+ "Cannot change d dynamically (compiled=" + std::to_string(oss_sdpa_ctx_.d) +
+ ", got=" + std::to_string(d) + ")");
+
+ std::vector<int64_t> k_def = {
+ oss_sdpa_ctx_.batch, oss_sdpa_ctx_.heads_kv, oss_sdpa_ctx_.seq_kv, oss_sdpa_ctx_.d};
+ auto const& k_shape = resolve_shape(oss_sdpa_ctx_.k_uid, k_def);
+ auto const& k_stride = resolve_stride(oss_sdpa_ctx_.k_uid, oss_sdpa_ctx_.k_stride);
+ int64_t heads_kv = k_shape[1], seq_kv = k_shape[2];
+
+ auto const& v_stride = resolve_stride(oss_sdpa_ctx_.v_uid, oss_sdpa_ctx_.v_stride);
+ auto const& o_stride = resolve_stride(oss_sdpa_ctx_.o_uid, oss_sdpa_ctx_.o_stride);
+ auto const& max_stride = resolve_stride(oss_sdpa_ctx_.max_uid, oss_sdpa_ctx_.max_stride);
+ auto const& se_stride = resolve_stride(oss_sdpa_ctx_.sum_exp_uid, oss_sdpa_ctx_.sum_exp_stride);
+
+ // Validate slot indices
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ oss_sdpa_ctx_.q_slot < 0 || oss_sdpa_ctx_.k_slot < 0 || oss_sdpa_ctx_.v_slot < 0 ||
+ oss_sdpa_ctx_.o_slot < 0 || oss_sdpa_ctx_.max_slot < 0 || oss_sdpa_ctx_.sum_exp_slot < 0,
+ error_code_t::INVALID_VARIANT_PACK,
+ "OSS SDPA slot indices not initialized. Call prepare_variant_pack_template() first.");
+
+ // Pointers from pre-indexed slots
+ void* q_ptr = ptrs[oss_sdpa_ctx_.q_slot];
+ void* k_ptr = ptrs[oss_sdpa_ctx_.k_slot];
+ void* v_ptr = ptrs[oss_sdpa_ctx_.v_slot];
+ void* o_ptr = ptrs[oss_sdpa_ctx_.o_slot];
+ void* max_ptr = ptrs[oss_sdpa_ctx_.max_slot];
+ void* sum_exp_ptr = ptrs[oss_sdpa_ctx_.sum_exp_slot];
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !q_ptr || !k_ptr || !v_ptr || !o_ptr, error_code_t::INVALID_VARIANT_PACK, "Missing Q/K/V/O pointers");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !max_ptr || !sum_exp_ptr, error_code_t::INVALID_VARIANT_PACK, "Missing max/sum_exp pointers");
+
+ return oss_sdpa_engine_->execute(static_cast<int>(batch),
+ static_cast<int>(heads_q),
+ static_cast<int>(heads_kv),
+ static_cast<int>(seq_q),
+ static_cast<int>(seq_kv),
+ static_cast<int>(d),
+ q_ptr,
+ q_stride,
+ k_ptr,
+ k_stride,
+ v_ptr,
+ v_stride,
+ o_ptr,
+ o_stride,
+ max_ptr,
+ max_stride,
+ sum_exp_ptr,
+ se_stride,
+ workspace,
+ device,
+ stream,
+ oss_sdpa_ctx_.attn_scale);
+ }
+
+ // ================================================================
+ // Open-source NVRTC engine support: RmsNorm + SiLU
+ // ================================================================
+
+ static constexpr int64_t OSS_RMS_NORM_SILU_ENGINE_CANDIDATE = -3;
+
+ // Context cached from the Graph for RmsNorm+SiLU engine execution
+ struct OssRmsNormSiluContext {
+ int64_t num_tokens = 0;
+ int64_t C = 0;
+
+ // Tensor UIDs for pointer lookup from variant pack
+ int64_t x_uid = -1; // input [num_tokens, C]
+ int64_t y_uid = -1; // output [num_tokens, C] (after SiLU)
+ int64_t scale_uid = -1; // gamma weights [C]
+ int64_t bias_uid = -1; // beta bias [C], optional (-1 if absent)
+ int64_t epsilon_uid = -1; // epsilon scalar
+
+ // FP8 output: optional scale/scale_inv/amax tensor UIDs
+ int64_t fp8_scale_uid = -1;
+ int64_t fp8_scale_inv_uid = -1;
+ int64_t fp8_amax_uid = -1;
+
+ // NVFP4 output: row-wise block-scale tensor UID
+ int64_t nvfp4_scale_row_uid = -1;
+
+ experimental::RmsNormSiluDtype output_dtype = experimental::RmsNormSiluDtype::BF16;
+
+ // Pre-computed slot indices into the variant pack template
+ int x_slot = -1, y_slot = -1, scale_slot = -1, bias_slot = -1, epsilon_slot = -1;
+ int fp8_scale_slot = -1, fp8_scale_inv_slot = -1, fp8_amax_slot = -1;
+ int nvfp4_scale_row_slot = -1;
+ };
+
+ void
+ set_oss_rms_norm_silu_engine(std::shared_ptr<experimental::IOssNormEngine> engine) {
+ oss_rms_norm_silu_engine_ = std::move(engine);
+ }
+
+ void
+ set_oss_rms_norm_silu_context(OssRmsNormSiluContext ctx) {
+ oss_rms_norm_silu_ctx_ = std::move(ctx);
+ }
+
+ bool
+ has_oss_rms_norm_silu_engine() const {
+ return oss_rms_norm_silu_engine_ != nullptr;
+ }
+
+ bool
+ is_oss_rms_norm_silu_candidate() const {
+ return candidate == OSS_RMS_NORM_SILU_ENGINE_CANDIDATE;
+ }
+
+ error_t
+ check_oss_rms_norm_silu_support(int64_t sm_version) {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !oss_rms_norm_silu_engine_, error_code_t::GRAPH_NOT_SUPPORTED, "No RmsNorm+SiLU OSS engine registered");
+ experimental::NormSiluShape_t shape;
+ shape.C = static_cast<int>(oss_rms_norm_silu_ctx_.C);
+ shape.num_tokens = static_cast<int>(oss_rms_norm_silu_ctx_.num_tokens);
+ shape.output_dtype = oss_rms_norm_silu_ctx_.output_dtype;
+ auto status = oss_rms_norm_silu_engine_->check_support(shape, static_cast<int>(sm_version));
+ if (status.is_good()) {
+ oss_rms_norm_silu_supported_ = true;
+ candidate = OSS_RMS_NORM_SILU_ENGINE_CANDIDATE;
+ }
+ return status;
+ }
+
+ error_t
+ build_oss_rms_norm_silu_engine() {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !oss_rms_norm_silu_supported_, error_code_t::GRAPH_NOT_SUPPORTED, "RmsNorm+SiLU OSS engine not supported");
+ auto status = oss_rms_norm_silu_engine_->build();
+ if (status.is_good()) {
+ oss_rms_norm_silu_built_ = true;
+ candidate = OSS_RMS_NORM_SILU_ENGINE_CANDIDATE;
+ }
+ return status;
+ }
+
+ int64_t
+ get_oss_rms_norm_silu_workspace_size() const {
+ if (!oss_rms_norm_silu_engine_) return 0;
+ return oss_rms_norm_silu_engine_->get_workspace_size();
+ }
+
+ // Set pre-computed slot indices for OSS engines (called by prepare_variant_pack_template)
+ void
+ set_oss_slot_indices(std::function<int(int64_t)> const& slot_for) {
+ if (is_oss_sdpa_candidate()) {
+ oss_sdpa_ctx_.q_slot = slot_for(oss_sdpa_ctx_.q_uid);
+ oss_sdpa_ctx_.k_slot = slot_for(oss_sdpa_ctx_.k_uid);
+ oss_sdpa_ctx_.v_slot = slot_for(oss_sdpa_ctx_.v_uid);
+ oss_sdpa_ctx_.o_slot = slot_for(oss_sdpa_ctx_.o_uid);
+ oss_sdpa_ctx_.max_slot = slot_for(oss_sdpa_ctx_.max_uid);
+ oss_sdpa_ctx_.sum_exp_slot = slot_for(oss_sdpa_ctx_.sum_exp_uid);
+ }
+ if (is_oss_rms_norm_silu_candidate()) {
+ oss_rms_norm_silu_ctx_.x_slot = slot_for(oss_rms_norm_silu_ctx_.x_uid);
+ oss_rms_norm_silu_ctx_.y_slot = slot_for(oss_rms_norm_silu_ctx_.y_uid);
+ oss_rms_norm_silu_ctx_.scale_slot = slot_for(oss_rms_norm_silu_ctx_.scale_uid);
+ oss_rms_norm_silu_ctx_.bias_slot = slot_for(oss_rms_norm_silu_ctx_.bias_uid);
+ oss_rms_norm_silu_ctx_.epsilon_slot = slot_for(oss_rms_norm_silu_ctx_.epsilon_uid);
+ oss_rms_norm_silu_ctx_.fp8_scale_slot = slot_for(oss_rms_norm_silu_ctx_.fp8_scale_uid);
+ oss_rms_norm_silu_ctx_.fp8_scale_inv_slot = slot_for(oss_rms_norm_silu_ctx_.fp8_scale_inv_uid);
+ oss_rms_norm_silu_ctx_.fp8_amax_slot = slot_for(oss_rms_norm_silu_ctx_.fp8_amax_uid);
+ oss_rms_norm_silu_ctx_.nvfp4_scale_row_slot = slot_for(oss_rms_norm_silu_ctx_.nvfp4_scale_row_uid);
+ }
+ }
+
+ // Flat-array overload for RmsNorm+SiLU
+ error_t
+ execute_oss_rms_norm_silu_engine(void* const* ptrs, void* workspace, int device, cudaStream_t stream) const {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !oss_rms_norm_silu_built_, error_code_t::GRAPH_EXECUTION_FAILED, "RmsNorm+SiLU OSS engine not built");
+
+ auto const& ctx = oss_rms_norm_silu_ctx_;
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ ctx.x_slot < 0 || ctx.y_slot < 0 || ctx.scale_slot < 0 || ctx.epsilon_slot < 0,
+ error_code_t::INVALID_VARIANT_PACK,
+ "OSS RmsNorm+SiLU slot indices not initialized. Call prepare_variant_pack_template() first.");
+
+ void* x_ptr = ptrs[ctx.x_slot];
+ void* y_ptr = ptrs[ctx.y_slot];
+ void* scale_ptr = ptrs[ctx.scale_slot];
+ void* bias_ptr = (ctx.bias_slot >= 0) ? ptrs[ctx.bias_slot] : nullptr;
+ void* eps_ptr = ptrs[ctx.epsilon_slot];
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!x_ptr || !y_ptr || !scale_ptr,
+ error_code_t::INVALID_VARIANT_PACK,
+ "Missing X/Y/SCALE pointers for RmsNorm+SiLU OSS engine");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !eps_ptr, error_code_t::INVALID_VARIANT_PACK, "Missing EPSILON pointer for RmsNorm+SiLU OSS engine");
+
+ float epsilon = *static_cast<float const*>(eps_ptr);
+
+ experimental::RmsNormSiluExtraParams extra;
+ auto slot_ptr = [&](int slot) -> void* { return (slot >= 0) ? ptrs[slot] : nullptr; };
+ extra.fp8_scale = slot_ptr(ctx.fp8_scale_slot);
+ extra.fp8_scale_inv = slot_ptr(ctx.fp8_scale_inv_slot);
+ extra.fp8_amax = slot_ptr(ctx.fp8_amax_slot);
+ extra.nvfp4_scale_row = slot_ptr(ctx.nvfp4_scale_row_slot);
+
+ return oss_rms_norm_silu_engine_->execute(x_ptr,
+ y_ptr,
+ scale_ptr,
+ bias_ptr,
+ static_cast<int>(ctx.num_tokens),
+ static_cast<int>(ctx.C),
+ epsilon,
+ workspace,
+ device,
+ stream,
+ extra);
+ }
+
+ private:
+ std::shared_ptr<experimental::IOssSdpaEngine> oss_sdpa_engine_;
+ bool oss_sdpa_engine_supported_ = false;
+ bool oss_sdpa_engine_built_ = false;
+ OssSdpaEngineContext oss_sdpa_ctx_;
+
+ std::shared_ptr<experimental::IOssNormEngine> oss_rms_norm_silu_engine_;
+ bool oss_rms_norm_silu_supported_ = false;
+ bool oss_rms_norm_silu_built_ = false;
+ OssRmsNormSiluContext oss_rms_norm_silu_ctx_;
+};
+
+} // namespace graph
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/thirdparty/nlohmann/LICENSE.MIT b/deps/cudnn-frontend/include/cudnn_frontend/thirdparty/nlohmann/LICENSE.MIT
new file mode 100644
index 0000000..1c1f7a6
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/thirdparty/nlohmann/LICENSE.MIT
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2013-2022 Niels Lohmann
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/thirdparty/nlohmann/json.hpp b/deps/cudnn-frontend/include/cudnn_frontend/thirdparty/nlohmann/json.hpp
new file mode 100644
index 0000000..85b4cdd
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/thirdparty/nlohmann/json.hpp
@@ -0,0 +1,26710 @@
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+/****************************************************************************\
+ * Note on documentation: The source files contain links to the online *
+ * documentation of the public API at https://json.nlohmann.me. This URL *
+ * contains the most recent documentation and should also be applicable to *
+ * previous versions; documentation for deprecated functions is not *
+ * removed, but marked deprecated. See "Generate documentation" section in *
+ * file docs/README.md. *
+\****************************************************************************/
+
+#ifndef INCLUDE_NLOHMANN_JSON_HPP_
+#define INCLUDE_NLOHMANN_JSON_HPP_
+
+#include <algorithm> // all_of, find, for_each
+#include <cstddef> // nullptr_t, ptrdiff_t, size_t
+#include <functional> // hash, less
+#include <initializer_list> // initializer_list
+#ifndef JSON_NO_IO
+#include <iosfwd> // istream, ostream
+#endif // JSON_NO_IO
+#include <iterator> // random_access_iterator_tag
+#include <memory> // unique_ptr
+#include <string> // string, stoi, to_string
+#include <utility> // declval, forward, move, pair, swap
+#include <vector> // vector
+
+// #include <nlohmann/adl_serializer.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <utility>
+
+// #include <nlohmann/detail/abi_macros.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+// This file contains all macro definitions affecting or depending on the ABI
+
+#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK
+#if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH)
+#if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 3
+#warning "Already included a different version of the library!"
+#endif
+#endif
+#endif
+
+#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum)
+#define NLOHMANN_JSON_VERSION_MINOR 11 // NOLINT(modernize-macro-to-enum)
+#define NLOHMANN_JSON_VERSION_PATCH 3 // NOLINT(modernize-macro-to-enum)
+
+#ifndef JSON_DIAGNOSTICS
+#define JSON_DIAGNOSTICS 0
+#endif
+
+#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
+#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0
+#endif
+
+#if JSON_DIAGNOSTICS
+#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag
+#else
+#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS
+#endif
+
+#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
+#define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp
+#else
+#define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON
+#endif
+
+#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION
+#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
+#endif
+
+// Construct the namespace ABI tags component
+#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi##a##b
+#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b)
+
+#define NLOHMANN_JSON_ABI_TAGS \
+ NLOHMANN_JSON_ABI_TAGS_CONCAT(NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \
+ NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON)
+
+// Construct the namespace version component
+#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) _v##major##_##minor##_##patch
+#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \
+ NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch)
+
+#if NLOHMANN_JSON_NAMESPACE_NO_VERSION
+#define NLOHMANN_JSON_NAMESPACE_VERSION
+#else
+#define NLOHMANN_JSON_NAMESPACE_VERSION \
+ NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT( \
+ NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH)
+#endif
+
+// Combine namespace components
+#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a##b
+#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b)
+
+#ifndef NLOHMANN_JSON_NAMESPACE
+#define NLOHMANN_JSON_NAMESPACE \
+ nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT(NLOHMANN_JSON_ABI_TAGS, NLOHMANN_JSON_NAMESPACE_VERSION)
+#endif
+
+#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN
+#define NLOHMANN_JSON_NAMESPACE_BEGIN \
+ namespace nlohmann { \
+ inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT(NLOHMANN_JSON_ABI_TAGS, NLOHMANN_JSON_NAMESPACE_VERSION) {
+#endif
+
+#ifndef NLOHMANN_JSON_NAMESPACE_END
+#define NLOHMANN_JSON_NAMESPACE_END \
+ } /* namespace (inline namespace) NOLINT(readability/namespace) */ \
+ } // namespace nlohmann
+#endif
+
+// #include <nlohmann/detail/conversions/from_json.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <algorithm> // transform
+#include <array> // array
+#include <forward_list> // forward_list
+#include <iterator> // inserter, front_inserter, end
+#include <map> // map
+#include <string> // string
+#include <tuple> // tuple, make_tuple
+#include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
+#include <unordered_map> // unordered_map
+#include <utility> // pair, declval
+#include <valarray> // valarray
+
+// #include <nlohmann/detail/exceptions.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstddef> // nullptr_t
+#include <exception> // exception
+#if JSON_DIAGNOSTICS
+#include <numeric> // accumulate
+#endif
+#include <stdexcept> // runtime_error
+#include <string> // to_string
+#include <vector> // vector
+
+// #include <nlohmann/detail/value_t.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <array> // array
+#include <cstddef> // size_t
+#include <cstdint> // uint8_t
+#include <string> // string
+
+// #include <nlohmann/detail/macro_scope.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <utility> // declval, pair
+// #include <nlohmann/detail/meta/detected.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <type_traits>
+
+// #include <nlohmann/detail/meta/void_t.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+template <typename... Ts>
+struct make_void {
+ using type = void;
+};
+template <typename... Ts>
+using void_t = typename make_void<Ts...>::type;
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+// https://en.cppreference.com/w/cpp/experimental/is_detected
+struct nonesuch {
+ nonesuch() = delete;
+ ~nonesuch() = delete;
+ nonesuch(nonesuch const&) = delete;
+ nonesuch(nonesuch const&&) = delete;
+ void
+ operator=(nonesuch const&) = delete;
+ void
+ operator=(nonesuch&&) = delete;
+};
+
+template <class Default, class AlwaysVoid, template <class...> class Op, class... Args>
+struct detector {
+ using value_t = std::false_type;
+ using type = Default;
+};
+
+template <class Default, template <class...> class Op, class... Args>
+struct detector<Default, void_t<Op<Args...>>, Op, Args...> {
+ using value_t = std::true_type;
+ using type = Op<Args...>;
+};
+
+template <template <class...> class Op, class... Args>
+using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
+
+template <template <class...> class Op, class... Args>
+struct is_detected_lazy : is_detected<Op, Args...> {};
+
+template <template <class...> class Op, class... Args>
+using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
+
+template <class Default, template <class...> class Op, class... Args>
+using detected_or = detector<Default, void, Op, Args...>;
+
+template <class Default, template <class...> class Op, class... Args>
+using detected_or_t = typename detected_or<Default, Op, Args...>::type;
+
+template <class Expected, template <class...> class Op, class... Args>
+using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
+
+template <class To, template <class...> class Op, class... Args>
+using is_detected_convertible = std::is_convertible<detected_t<Op, Args...>, To>;
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/thirdparty/hedley/hedley.hpp>
+
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-FileCopyrightText: 2016-2021 Evan Nemerson <evan@nemerson.com>
+// SPDX-License-Identifier: MIT
+
+/* Hedley - https://nemequ.github.io/hedley
+ * Created by Evan Nemerson <evan@nemerson.com>
+ */
+
+#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15)
+#if defined(JSON_HEDLEY_VERSION)
+#undef JSON_HEDLEY_VERSION
+#endif
+#define JSON_HEDLEY_VERSION 15
+
+#if defined(JSON_HEDLEY_STRINGIFY_EX)
+#undef JSON_HEDLEY_STRINGIFY_EX
+#endif
+#define JSON_HEDLEY_STRINGIFY_EX(x) #x
+
+#if defined(JSON_HEDLEY_STRINGIFY)
+#undef JSON_HEDLEY_STRINGIFY
+#endif
+#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
+
+#if defined(JSON_HEDLEY_CONCAT_EX)
+#undef JSON_HEDLEY_CONCAT_EX
+#endif
+#define JSON_HEDLEY_CONCAT_EX(a, b) a##b
+
+#if defined(JSON_HEDLEY_CONCAT)
+#undef JSON_HEDLEY_CONCAT
+#endif
+#define JSON_HEDLEY_CONCAT(a, b) JSON_HEDLEY_CONCAT_EX(a, b)
+
+#if defined(JSON_HEDLEY_CONCAT3_EX)
+#undef JSON_HEDLEY_CONCAT3_EX
+#endif
+#define JSON_HEDLEY_CONCAT3_EX(a, b, c) a##b##c
+
+#if defined(JSON_HEDLEY_CONCAT3)
+#undef JSON_HEDLEY_CONCAT3
+#endif
+#define JSON_HEDLEY_CONCAT3(a, b, c) JSON_HEDLEY_CONCAT3_EX(a, b, c)
+
+#if defined(JSON_HEDLEY_VERSION_ENCODE)
+#undef JSON_HEDLEY_VERSION_ENCODE
+#endif
+#define JSON_HEDLEY_VERSION_ENCODE(major, minor, revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
+
+#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
+#undef JSON_HEDLEY_VERSION_DECODE_MAJOR
+#endif
+#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
+
+#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
+#undef JSON_HEDLEY_VERSION_DECODE_MINOR
+#endif
+#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
+
+#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
+#undef JSON_HEDLEY_VERSION_DECODE_REVISION
+#endif
+#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
+
+#if defined(JSON_HEDLEY_GNUC_VERSION)
+#undef JSON_HEDLEY_GNUC_VERSION
+#endif
+#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
+#define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
+#elif defined(__GNUC__)
+#define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
+#undef JSON_HEDLEY_GNUC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_GNUC_VERSION)
+#define JSON_HEDLEY_GNUC_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_GNUC_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_MSVC_VERSION)
+#undef JSON_HEDLEY_MSVC_VERSION
+#endif
+#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL)
+#define JSON_HEDLEY_MSVC_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE( \
+ _MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
+#elif defined(_MSC_FULL_VER) && !defined(__ICL)
+#define JSON_HEDLEY_MSVC_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
+#elif defined(_MSC_VER) && !defined(__ICL)
+#define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
+#endif
+
+#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
+#undef JSON_HEDLEY_MSVC_VERSION_CHECK
+#endif
+#if !defined(JSON_HEDLEY_MSVC_VERSION)
+#define JSON_HEDLEY_MSVC_VERSION_CHECK(major, minor, patch) (0)
+#elif defined(_MSC_VER) && (_MSC_VER >= 1400)
+#define JSON_HEDLEY_MSVC_VERSION_CHECK(major, minor, patch) \
+ (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
+#elif defined(_MSC_VER) && (_MSC_VER >= 1200)
+#define JSON_HEDLEY_MSVC_VERSION_CHECK(major, minor, patch) \
+ (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
+#else
+#define JSON_HEDLEY_MSVC_VERSION_CHECK(major, minor, patch) (_MSC_VER >= ((major * 100) + (minor)))
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_VERSION)
+#undef JSON_HEDLEY_INTEL_VERSION
+#endif
+#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL)
+#define JSON_HEDLEY_INTEL_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
+#elif defined(__INTEL_COMPILER) && !defined(__ICL)
+#define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
+#undef JSON_HEDLEY_INTEL_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_INTEL_VERSION)
+#define JSON_HEDLEY_INTEL_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_INTEL_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_CL_VERSION)
+#undef JSON_HEDLEY_INTEL_CL_VERSION
+#endif
+#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL)
+#define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0)
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK)
+#undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_INTEL_CL_VERSION)
+#define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_PGI_VERSION)
+#undef JSON_HEDLEY_PGI_VERSION
+#endif
+#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
+#define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
+#endif
+
+#if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
+#undef JSON_HEDLEY_PGI_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_PGI_VERSION)
+#define JSON_HEDLEY_PGI_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_PGI_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_SUNPRO_VERSION)
+#undef JSON_HEDLEY_SUNPRO_VERSION
+#endif
+#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
+#define JSON_HEDLEY_SUNPRO_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), \
+ (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), \
+ (__SUNPRO_C & 0xf) * 10)
+#elif defined(__SUNPRO_C)
+#define JSON_HEDLEY_SUNPRO_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
+#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
+#define JSON_HEDLEY_SUNPRO_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), \
+ (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), \
+ (__SUNPRO_CC & 0xf) * 10)
+#elif defined(__SUNPRO_CC)
+#define JSON_HEDLEY_SUNPRO_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
+#endif
+
+#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
+#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_SUNPRO_VERSION)
+#define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
+#undef JSON_HEDLEY_EMSCRIPTEN_VERSION
+#endif
+#if defined(__EMSCRIPTEN__)
+#define JSON_HEDLEY_EMSCRIPTEN_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
+#endif
+
+#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
+#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
+#define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_ARM_VERSION)
+#undef JSON_HEDLEY_ARM_VERSION
+#endif
+#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
+#define JSON_HEDLEY_ARM_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, \
+ (__ARMCOMPILER_VERSION % 1000000) / 10000, \
+ (__ARMCOMPILER_VERSION % 10000) / 100)
+#elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
+#define JSON_HEDLEY_ARM_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE( \
+ __ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
+#endif
+
+#if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
+#undef JSON_HEDLEY_ARM_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_ARM_VERSION)
+#define JSON_HEDLEY_ARM_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_ARM_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_IBM_VERSION)
+#undef JSON_HEDLEY_IBM_VERSION
+#endif
+#if defined(__ibmxl__)
+#define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
+#elif defined(__xlC__) && defined(__xlC_ver__)
+#define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
+#elif defined(__xlC__)
+#define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
+#endif
+
+#if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
+#undef JSON_HEDLEY_IBM_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_IBM_VERSION)
+#define JSON_HEDLEY_IBM_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_IBM_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_VERSION)
+#undef JSON_HEDLEY_TI_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && \
+ (defined(__TMS470__) || defined(__TI_ARM__) || defined(__MSP430__) || defined(__TMS320C2000__))
+#if (__TI_COMPILER_VERSION__ >= 16000000)
+#define JSON_HEDLEY_TI_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, \
+ (__TI_COMPILER_VERSION__ % 1000000) / 1000, \
+ (__TI_COMPILER_VERSION__ % 1000))
+#endif
+#endif
+
+#if defined(JSON_HEDLEY_TI_VERSION_CHECK)
+#undef JSON_HEDLEY_TI_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_VERSION)
+#define JSON_HEDLEY_TI_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_TI_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL2000_VERSION)
+#undef JSON_HEDLEY_TI_CL2000_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__)
+#define JSON_HEDLEY_TI_CL2000_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, \
+ (__TI_COMPILER_VERSION__ % 1000000) / 1000, \
+ (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK)
+#undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CL2000_VERSION)
+#define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL430_VERSION)
+#undef JSON_HEDLEY_TI_CL430_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__)
+#define JSON_HEDLEY_TI_CL430_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, \
+ (__TI_COMPILER_VERSION__ % 1000000) / 1000, \
+ (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK)
+#undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CL430_VERSION)
+#define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
+#undef JSON_HEDLEY_TI_ARMCL_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__))
+#define JSON_HEDLEY_TI_ARMCL_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, \
+ (__TI_COMPILER_VERSION__ % 1000000) / 1000, \
+ (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK)
+#undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
+#define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL6X_VERSION)
+#undef JSON_HEDLEY_TI_CL6X_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__)
+#define JSON_HEDLEY_TI_CL6X_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, \
+ (__TI_COMPILER_VERSION__ % 1000000) / 1000, \
+ (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK)
+#undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CL6X_VERSION)
+#define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL7X_VERSION)
+#undef JSON_HEDLEY_TI_CL7X_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__)
+#define JSON_HEDLEY_TI_CL7X_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, \
+ (__TI_COMPILER_VERSION__ % 1000000) / 1000, \
+ (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK)
+#undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CL7X_VERSION)
+#define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
+#undef JSON_HEDLEY_TI_CLPRU_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__)
+#define JSON_HEDLEY_TI_CLPRU_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, \
+ (__TI_COMPILER_VERSION__ % 1000000) / 1000, \
+ (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK)
+#undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
+#define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_CRAY_VERSION)
+#undef JSON_HEDLEY_CRAY_VERSION
+#endif
+#if defined(_CRAYC)
+#if defined(_RELEASE_PATCHLEVEL)
+#define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
+#else
+#define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
+#endif
+#endif
+
+#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
+#undef JSON_HEDLEY_CRAY_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_CRAY_VERSION)
+#define JSON_HEDLEY_CRAY_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_CRAY_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_IAR_VERSION)
+#undef JSON_HEDLEY_IAR_VERSION
+#endif
+#if defined(__IAR_SYSTEMS_ICC__)
+#if __VER__ > 1000
+#define JSON_HEDLEY_IAR_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
+#else
+#define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0)
+#endif
+#endif
+
+#if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
+#undef JSON_HEDLEY_IAR_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_IAR_VERSION)
+#define JSON_HEDLEY_IAR_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_IAR_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TINYC_VERSION)
+#undef JSON_HEDLEY_TINYC_VERSION
+#endif
+#if defined(__TINYC__)
+#define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
+#endif
+
+#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
+#undef JSON_HEDLEY_TINYC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TINYC_VERSION)
+#define JSON_HEDLEY_TINYC_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_TINYC_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_DMC_VERSION)
+#undef JSON_HEDLEY_DMC_VERSION
+#endif
+#if defined(__DMC__)
+#define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
+#endif
+
+#if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
+#undef JSON_HEDLEY_DMC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_DMC_VERSION)
+#define JSON_HEDLEY_DMC_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_DMC_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_COMPCERT_VERSION)
+#undef JSON_HEDLEY_COMPCERT_VERSION
+#endif
+#if defined(__COMPCERT_VERSION__)
+#define JSON_HEDLEY_COMPCERT_VERSION \
+ JSON_HEDLEY_VERSION_ENCODE( \
+ __COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
+#endif
+
+#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
+#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_COMPCERT_VERSION)
+#define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_PELLES_VERSION)
+#undef JSON_HEDLEY_PELLES_VERSION
+#endif
+#if defined(__POCC__)
+#define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
+#endif
+
+#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
+#undef JSON_HEDLEY_PELLES_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_PELLES_VERSION)
+#define JSON_HEDLEY_PELLES_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_PELLES_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_MCST_LCC_VERSION)
+#undef JSON_HEDLEY_MCST_LCC_VERSION
+#endif
+#if defined(__LCC__) && defined(__LCC_MINOR__)
+#define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__)
+#endif
+
+#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK)
+#undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_MCST_LCC_VERSION)
+#define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_VERSION)
+#undef JSON_HEDLEY_GCC_VERSION
+#endif
+#if defined(JSON_HEDLEY_GNUC_VERSION) && !defined(__clang__) && !defined(JSON_HEDLEY_INTEL_VERSION) && \
+ !defined(JSON_HEDLEY_PGI_VERSION) && !defined(JSON_HEDLEY_ARM_VERSION) && !defined(JSON_HEDLEY_CRAY_VERSION) && \
+ !defined(JSON_HEDLEY_TI_VERSION) && !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \
+ !defined(JSON_HEDLEY_TI_CL430_VERSION) && !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \
+ !defined(JSON_HEDLEY_TI_CL6X_VERSION) && !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \
+ !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && !defined(__COMPCERT__) && !defined(JSON_HEDLEY_MCST_LCC_VERSION)
+#define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
+#endif
+
+#if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
+#undef JSON_HEDLEY_GCC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_GCC_VERSION)
+#define JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch) \
+ (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+#define JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
+#undef JSON_HEDLEY_HAS_ATTRIBUTE
+#endif
+#if defined(__has_attribute) && ((!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8, 5, 9)))
+#define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
+#else
+#define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
+#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
+#endif
+#if defined(__has_attribute)
+#define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute, major, minor, patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
+#else
+#define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute, major, minor, patch) \
+ JSON_HEDLEY_GNUC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
+#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
+#endif
+#if defined(__has_attribute)
+#define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute, major, minor, patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
+#else
+#define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute, major, minor, patch) JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
+#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
+#endif
+#if defined(__has_cpp_attribute) && defined(__cplusplus) && \
+ (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 15, 0))
+#define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
+#else
+#define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
+#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
+#endif
+#if !defined(__cplusplus) || !defined(__has_cpp_attribute)
+#define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns, attribute) (0)
+#elif !defined(JSON_HEDLEY_PGI_VERSION) && !defined(JSON_HEDLEY_IAR_VERSION) && \
+ (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 15, 0)) && \
+ (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19, 20, 0))
+#define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns, attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
+#else
+#define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns, attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
+#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
+#endif
+#if defined(__has_cpp_attribute) && defined(__cplusplus)
+#define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute, major, minor, patch) __has_cpp_attribute(attribute)
+#else
+#define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute, major, minor, patch) \
+ JSON_HEDLEY_GNUC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
+#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
+#endif
+#if defined(__has_cpp_attribute) && defined(__cplusplus)
+#define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute, major, minor, patch) __has_cpp_attribute(attribute)
+#else
+#define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute, major, minor, patch) \
+ JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_BUILTIN)
+#undef JSON_HEDLEY_HAS_BUILTIN
+#endif
+#if defined(__has_builtin)
+#define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
+#else
+#define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
+#undef JSON_HEDLEY_GNUC_HAS_BUILTIN
+#endif
+#if defined(__has_builtin)
+#define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin, major, minor, patch) __has_builtin(builtin)
+#else
+#define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin, major, minor, patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
+#undef JSON_HEDLEY_GCC_HAS_BUILTIN
+#endif
+#if defined(__has_builtin)
+#define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin, major, minor, patch) __has_builtin(builtin)
+#else
+#define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin, major, minor, patch) JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_FEATURE)
+#undef JSON_HEDLEY_HAS_FEATURE
+#endif
+#if defined(__has_feature)
+#define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
+#else
+#define JSON_HEDLEY_HAS_FEATURE(feature) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
+#undef JSON_HEDLEY_GNUC_HAS_FEATURE
+#endif
+#if defined(__has_feature)
+#define JSON_HEDLEY_GNUC_HAS_FEATURE(feature, major, minor, patch) __has_feature(feature)
+#else
+#define JSON_HEDLEY_GNUC_HAS_FEATURE(feature, major, minor, patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
+#undef JSON_HEDLEY_GCC_HAS_FEATURE
+#endif
+#if defined(__has_feature)
+#define JSON_HEDLEY_GCC_HAS_FEATURE(feature, major, minor, patch) __has_feature(feature)
+#else
+#define JSON_HEDLEY_GCC_HAS_FEATURE(feature, major, minor, patch) JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_EXTENSION)
+#undef JSON_HEDLEY_HAS_EXTENSION
+#endif
+#if defined(__has_extension)
+#define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
+#else
+#define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
+#undef JSON_HEDLEY_GNUC_HAS_EXTENSION
+#endif
+#if defined(__has_extension)
+#define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension, major, minor, patch) __has_extension(extension)
+#else
+#define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension, major, minor, patch) \
+ JSON_HEDLEY_GNUC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
+#undef JSON_HEDLEY_GCC_HAS_EXTENSION
+#endif
+#if defined(__has_extension)
+#define JSON_HEDLEY_GCC_HAS_EXTENSION(extension, major, minor, patch) __has_extension(extension)
+#else
+#define JSON_HEDLEY_GCC_HAS_EXTENSION(extension, major, minor, patch) JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
+#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
+#endif
+#if defined(__has_declspec_attribute)
+#define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
+#else
+#define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
+#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
+#endif
+#if defined(__has_declspec_attribute)
+#define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute, major, minor, patch) __has_declspec_attribute(attribute)
+#else
+#define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute, major, minor, patch) \
+ JSON_HEDLEY_GNUC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
+#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
+#endif
+#if defined(__has_declspec_attribute)
+#define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute, major, minor, patch) __has_declspec_attribute(attribute)
+#else
+#define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute, major, minor, patch) \
+ JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_WARNING)
+#undef JSON_HEDLEY_HAS_WARNING
+#endif
+#if defined(__has_warning)
+#define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
+#else
+#define JSON_HEDLEY_HAS_WARNING(warning) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
+#undef JSON_HEDLEY_GNUC_HAS_WARNING
+#endif
+#if defined(__has_warning)
+#define JSON_HEDLEY_GNUC_HAS_WARNING(warning, major, minor, patch) __has_warning(warning)
+#else
+#define JSON_HEDLEY_GNUC_HAS_WARNING(warning, major, minor, patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_WARNING)
+#undef JSON_HEDLEY_GCC_HAS_WARNING
+#endif
+#if defined(__has_warning)
+#define JSON_HEDLEY_GCC_HAS_WARNING(warning, major, minor, patch) __has_warning(warning)
+#else
+#define JSON_HEDLEY_GCC_HAS_WARNING(warning, major, minor, patch) JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || defined(__clang__) || \
+ JSON_HEDLEY_GCC_VERSION_CHECK(3, 0, 0) || JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || \
+ JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0) || JSON_HEDLEY_PGI_VERSION_CHECK(18, 4, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 7, 0) || JSON_HEDLEY_TI_CL430_VERSION_CHECK(2, 0, 1) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 1, 0) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 0, 0) || \
+ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || \
+ JSON_HEDLEY_CRAY_VERSION_CHECK(5, 0, 0) || JSON_HEDLEY_TINYC_VERSION_CHECK(0, 9, 17) || \
+ JSON_HEDLEY_SUNPRO_VERSION_CHECK(8, 0, 0) || \
+ (JSON_HEDLEY_IBM_VERSION_CHECK(10, 1, 0) && defined(__C99_PRAGMA_OPERATOR))
+#define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15, 0, 0)
+#define JSON_HEDLEY_PRAGMA(value) __pragma(value)
+#else
+#define JSON_HEDLEY_PRAGMA(value)
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
+#undef JSON_HEDLEY_DIAGNOSTIC_PUSH
+#endif
+#if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
+#undef JSON_HEDLEY_DIAGNOSTIC_POP
+#endif
+#if defined(__clang__)
+#define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
+#define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
+#define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4, 6, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
+#define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15, 0, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
+#define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
+#elif JSON_HEDLEY_ARM_VERSION_CHECK(5, 6, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
+#define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
+#elif JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 4, 0) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8, 1, 0) || \
+ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
+#define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2, 90, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
+#define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
+#else
+#define JSON_HEDLEY_DIAGNOSTIC_PUSH
+#define JSON_HEDLEY_DIAGNOSTIC_POP
+#endif
+
+/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
+ HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
+#endif
+#if defined(__cplusplus)
+#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
+#if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions")
+#if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions")
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
+ _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") xpr JSON_HEDLEY_DIAGNOSTIC_POP
+#else
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
+ xpr JSON_HEDLEY_DIAGNOSTIC_POP
+#endif
+#else
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") xpr JSON_HEDLEY_DIAGNOSTIC_POP
+#endif
+#endif
+#endif
+#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
+#endif
+
+#if defined(JSON_HEDLEY_CONST_CAST)
+#undef JSON_HEDLEY_CONST_CAST
+#endif
+#if defined(__cplusplus)
+#define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
+#elif JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || JSON_HEDLEY_GCC_VERSION_CHECK(4, 6, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0)
+#define JSON_HEDLEY_CONST_CAST(T, expr) \
+ (__extension__({ \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL((T)(expr)); \
+ JSON_HEDLEY_DIAGNOSTIC_POP \
+ }))
+#else
+#define JSON_HEDLEY_CONST_CAST(T, expr) ((T)(expr))
+#endif
+
+#if defined(JSON_HEDLEY_REINTERPRET_CAST)
+#undef JSON_HEDLEY_REINTERPRET_CAST
+#endif
+#if defined(__cplusplus)
+#define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
+#else
+#define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T)(expr))
+#endif
+
+#if defined(JSON_HEDLEY_STATIC_CAST)
+#undef JSON_HEDLEY_STATIC_CAST
+#endif
+#if defined(__cplusplus)
+#define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
+#else
+#define JSON_HEDLEY_STATIC_CAST(T, expr) ((T)(expr))
+#endif
+
+#if defined(JSON_HEDLEY_CPP_CAST)
+#undef JSON_HEDLEY_CPP_CAST
+#endif
+#if defined(__cplusplus)
+#if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast")
+#define JSON_HEDLEY_CPP_CAST(T, expr) \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ _Pragma("clang diagnostic ignored \"-Wold-style-cast\"")((T)(expr)) JSON_HEDLEY_DIAGNOSTIC_POP
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8, 3, 0)
+#define JSON_HEDLEY_CPP_CAST(T, expr) \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ _Pragma("diag_suppress=Pe137") JSON_HEDLEY_DIAGNOSTIC_POP
+#else
+#define JSON_HEDLEY_CPP_CAST(T, expr) ((T)(expr))
+#endif
+#else
+#define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
+#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable : 1478 1786))
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(20, 7, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445")
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(17, 10, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4, 3, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable : 4996))
+#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
+#elif JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 13, 0) && !defined(__cplusplus)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 13, 0) && defined(__cplusplus)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2, 90, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
+#else
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
+#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable : 161))
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(17, 10, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4, 3, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable : 4068))
+#elif JSON_HEDLEY_TI_VERSION_CHECK(16, 9, 0) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8, 0, 0) || \
+ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 3, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
+#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
+#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161")
+#else
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES \
+ _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4, 6, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES \
+ _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
+#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable : 1292))
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable : 5030))
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(20, 7, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098")
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(17, 10, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 14, 0) && defined(__cplusplus)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
+#elif JSON_HEDLEY_TI_VERSION_CHECK(18, 1, 0) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8, 3, 0) || \
+ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097")
+#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
+#else
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(3, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
+#else
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION)
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunused-function")
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(3, 4, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1, 0, 0)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable : 4505))
+#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142")
+#else
+#define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
+#endif
+
+#if defined(JSON_HEDLEY_DEPRECATED)
+#undef JSON_HEDLEY_DEPRECATED
+#endif
+#if defined(JSON_HEDLEY_DEPRECATED_FOR)
+#undef JSON_HEDLEY_DEPRECATED_FOR
+#endif
+#if JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " #since))
+#define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
+#elif (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
+ JSON_HEDLEY_GCC_VERSION_CHECK(4, 5, 0) || JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(5, 6, 0) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 13, 0) || \
+ JSON_HEDLEY_PGI_VERSION_CHECK(17, 10, 0) || JSON_HEDLEY_TI_VERSION_CHECK(18, 1, 0) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18, 1, 0) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8, 3, 0) || \
+ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 3, 0) || \
+ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
+#define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) \
+ __attribute__((__deprecated__("Since " #since "; use " #replacement)))
+#elif defined(__cplusplus) && (__cplusplus >= 201402L)
+#define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
+#define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) \
+ JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
+#elif JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 1, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10) || \
+ JSON_HEDLEY_IAR_VERSION_CHECK(8, 10, 0)
+#define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
+#define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(13, 10, 0) || JSON_HEDLEY_PELLES_VERSION_CHECK(6, 50, 0) || \
+ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
+#define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0)
+#define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
+#define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
+#else
+#define JSON_HEDLEY_DEPRECATED(since)
+#define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
+#endif
+
+#if defined(JSON_HEDLEY_UNAVAILABLE)
+#undef JSON_HEDLEY_UNAVAILABLE
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(warning) || JSON_HEDLEY_GCC_VERSION_CHECK(4, 3, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
+#else
+#define JSON_HEDLEY_UNAVAILABLE(available_since)
+#endif
+
+#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
+#undef JSON_HEDLEY_WARN_UNUSED_RESULT
+#endif
+#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG)
+#undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 4, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || \
+ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 15, 0) && defined(__cplusplus)) || \
+ JSON_HEDLEY_PGI_VERSION_CHECK(17, 10, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
+#define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__))
+#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L)
+#define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
+#define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]])
+#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard)
+#define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
+#define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
+#elif defined(_Check_return_) /* SAL */
+#define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
+#define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_
+#else
+#define JSON_HEDLEY_WARN_UNUSED_RESULT
+#define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg)
+#endif
+
+#if defined(JSON_HEDLEY_SENTINEL)
+#undef JSON_HEDLEY_SENTINEL
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || JSON_HEDLEY_GCC_VERSION_CHECK(4, 0, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_ARM_VERSION_CHECK(5, 4, 0) || \
+ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
+#else
+#define JSON_HEDLEY_SENTINEL(position)
+#endif
+
+#if defined(JSON_HEDLEY_NO_RETURN)
+#undef JSON_HEDLEY_NO_RETURN
+#endif
+#if JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0)
+#define JSON_HEDLEY_NO_RETURN __noreturn
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
+#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
+#define JSON_HEDLEY_NO_RETURN _Noreturn
+#elif defined(__cplusplus) && (__cplusplus >= 201103L)
+#define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
+#elif JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 2, 0) || \
+ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 11, 0) || JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || \
+ JSON_HEDLEY_IBM_VERSION_CHECK(10, 1, 0) || JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || JSON_HEDLEY_IAR_VERSION_CHECK(8, 10, 0)
+#define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 10, 0)
+#define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(13, 10, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
+#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6, 0, 0) && defined(__cplusplus)
+#define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
+#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3, 2, 0)
+#define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9, 0, 0)
+#define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
+#else
+#define JSON_HEDLEY_NO_RETURN
+#endif
+
+#if defined(JSON_HEDLEY_NO_ESCAPE)
+#undef JSON_HEDLEY_NO_ESCAPE
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
+#define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
+#else
+#define JSON_HEDLEY_NO_ESCAPE
+#endif
+
+#if defined(JSON_HEDLEY_UNREACHABLE)
+#undef JSON_HEDLEY_UNREACHABLE
+#endif
+#if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
+#undef JSON_HEDLEY_UNREACHABLE_RETURN
+#endif
+#if defined(JSON_HEDLEY_ASSUME)
+#undef JSON_HEDLEY_ASSUME
+#endif
+#if JSON_HEDLEY_MSVC_VERSION_CHECK(13, 10, 0) || JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || \
+ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_ASSUME(expr) __assume(expr)
+#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
+#define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
+#elif JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 2, 0) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4, 0, 0)
+#if defined(__cplusplus)
+#define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
+#else
+#define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
+#endif
+#endif
+#if (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
+ JSON_HEDLEY_GCC_VERSION_CHECK(4, 5, 0) || JSON_HEDLEY_PGI_VERSION_CHECK(18, 10, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(13, 1, 5) || \
+ JSON_HEDLEY_CRAY_VERSION_CHECK(10, 0, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
+#elif defined(JSON_HEDLEY_ASSUME)
+#define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
+#endif
+#if !defined(JSON_HEDLEY_ASSUME)
+#if defined(JSON_HEDLEY_UNREACHABLE)
+#define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1)))
+#else
+#define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr)
+#endif
+#endif
+#if defined(JSON_HEDLEY_UNREACHABLE)
+#if JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 2, 0) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4, 0, 0)
+#define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value))
+#else
+#define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
+#endif
+#else
+#define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value)
+#endif
+#if !defined(JSON_HEDLEY_UNREACHABLE)
+#define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
+#endif
+
+JSON_HEDLEY_DIAGNOSTIC_PUSH
+#if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
+#pragma clang diagnostic ignored "-Wpedantic"
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
+#pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
+#endif
+#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros", 4, 0, 0)
+#if defined(__clang__)
+#pragma clang diagnostic ignored "-Wvariadic-macros"
+#elif defined(JSON_HEDLEY_GCC_VERSION)
+#pragma GCC diagnostic ignored "-Wvariadic-macros"
+#endif
+#endif
+#if defined(JSON_HEDLEY_NON_NULL)
+#undef JSON_HEDLEY_NON_NULL
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 3, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0)
+#define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
+#else
+#define JSON_HEDLEY_NON_NULL(...)
+#endif
+JSON_HEDLEY_DIAGNOSTIC_POP
+
+#if defined(JSON_HEDLEY_PRINTF_FORMAT)
+#undef JSON_HEDLEY_PRINTF_FORMAT
+#endif
+#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format, 4, 4, 0) && !defined(__USE_MINGW_ANSI_STDIO)
+#define JSON_HEDLEY_PRINTF_FORMAT(string_idx, first_to_check) \
+ __attribute__((__format__(ms_printf, string_idx, first_to_check)))
+#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format, 4, 4, 0) && defined(__USE_MINGW_ANSI_STDIO)
+#define JSON_HEDLEY_PRINTF_FORMAT(string_idx, first_to_check) \
+ __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
+#elif JSON_HEDLEY_HAS_ATTRIBUTE(format) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 1, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_ARM_VERSION_CHECK(5, 6, 0) || \
+ JSON_HEDLEY_IBM_VERSION_CHECK(10, 1, 0) || JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_PRINTF_FORMAT(string_idx, first_to_check) \
+ __attribute__((__format__(__printf__, string_idx, first_to_check)))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6, 0, 0)
+#define JSON_HEDLEY_PRINTF_FORMAT(string_idx, first_to_check) __declspec(vaformat(printf, string_idx, first_to_check))
+#else
+#define JSON_HEDLEY_PRINTF_FORMAT(string_idx, first_to_check)
+#endif
+
+#if defined(JSON_HEDLEY_CONSTEXPR)
+#undef JSON_HEDLEY_CONSTEXPR
+#endif
+#if defined(__cplusplus)
+#if __cplusplus >= 201103L
+#define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
+#endif
+#endif
+#if !defined(JSON_HEDLEY_CONSTEXPR)
+#define JSON_HEDLEY_CONSTEXPR
+#endif
+
+#if defined(JSON_HEDLEY_PREDICT)
+#undef JSON_HEDLEY_PREDICT
+#endif
+#if defined(JSON_HEDLEY_LIKELY)
+#undef JSON_HEDLEY_LIKELY
+#endif
+#if defined(JSON_HEDLEY_UNLIKELY)
+#undef JSON_HEDLEY_UNLIKELY
+#endif
+#if defined(JSON_HEDLEY_UNPREDICTABLE)
+#undef JSON_HEDLEY_UNPREDICTABLE
+#endif
+#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
+#define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr))
+#endif
+#if (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
+ JSON_HEDLEY_GCC_VERSION_CHECK(9, 0, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability((expr), (value), (probability))
+#define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1, (probability))
+#define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0, (probability))
+#define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
+#define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
+#elif (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
+ JSON_HEDLEY_GCC_VERSION_CHECK(3, 0, 0) || JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || \
+ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 15, 0) && defined(__cplusplus)) || JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || \
+ JSON_HEDLEY_IBM_VERSION_CHECK(10, 1, 0) || JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 7, 0) || JSON_HEDLEY_TI_CL430_VERSION_CHECK(3, 1, 0) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 1, 0) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6, 1, 0) || \
+ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || \
+ JSON_HEDLEY_TINYC_VERSION_CHECK(0, 9, 27) || JSON_HEDLEY_CRAY_VERSION_CHECK(8, 1, 0) || \
+ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_PREDICT(expr, expected, probability) \
+ (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)))
+#define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
+ (__extension__({ \
+ double hedley_probability_ = (probability); \
+ ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) \
+ : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
+ }))
+#define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
+ (__extension__({ \
+ double hedley_probability_ = (probability); \
+ ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) \
+ : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
+ }))
+#define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
+#define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
+#else
+#define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))
+#define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
+#define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
+#define JSON_HEDLEY_LIKELY(expr) (!!(expr))
+#define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
+#endif
+#if !defined(JSON_HEDLEY_UNPREDICTABLE)
+#define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
+#endif
+
+#if defined(JSON_HEDLEY_MALLOC)
+#undef JSON_HEDLEY_MALLOC
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 1, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 11, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(12, 1, 0) || \
+ JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 10, 0)
+#define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_MALLOC __declspec(restrict)
+#else
+#define JSON_HEDLEY_MALLOC
+#endif
+
+#if defined(JSON_HEDLEY_PURE)
+#undef JSON_HEDLEY_PURE
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(pure) || JSON_HEDLEY_GCC_VERSION_CHECK(2, 96, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 11, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(10, 1, 0) || \
+ JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || JSON_HEDLEY_PGI_VERSION_CHECK(17, 10, 0) || \
+ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_PURE __attribute__((__pure__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 10, 0)
+#define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
+#elif defined(__cplusplus) && \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(2, 0, 1) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4, 0, 0) || \
+ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0))
+#define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
+#else
+#define JSON_HEDLEY_PURE
+#endif
+
+#if defined(JSON_HEDLEY_CONST)
+#undef JSON_HEDLEY_CONST
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(const) || JSON_HEDLEY_GCC_VERSION_CHECK(2, 5, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 11, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(10, 1, 0) || \
+ JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || JSON_HEDLEY_PGI_VERSION_CHECK(17, 10, 0) || \
+ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_CONST __attribute__((__const__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 10, 0)
+#define JSON_HEDLEY_CONST _Pragma("no_side_effect")
+#else
+#define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
+#endif
+
+#if defined(JSON_HEDLEY_RESTRICT)
+#undef JSON_HEDLEY_RESTRICT
+#endif
+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
+#define JSON_HEDLEY_RESTRICT restrict
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(3, 1, 0) || JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(10, 1, 0) || \
+ JSON_HEDLEY_PGI_VERSION_CHECK(17, 10, 0) || JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 2, 4) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8, 1, 0) || \
+ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 14, 0) && defined(__cplusplus)) || JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0) || \
+ defined(__clang__) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_RESTRICT __restrict
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 3, 0) && !defined(__cplusplus)
+#define JSON_HEDLEY_RESTRICT _Restrict
+#else
+#define JSON_HEDLEY_RESTRICT
+#endif
+
+#if defined(JSON_HEDLEY_INLINE)
+#undef JSON_HEDLEY_INLINE
+#endif
+#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L))
+#define JSON_HEDLEY_INLINE inline
+#elif defined(JSON_HEDLEY_GCC_VERSION) || JSON_HEDLEY_ARM_VERSION_CHECK(6, 2, 0)
+#define JSON_HEDLEY_INLINE __inline__
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(12, 0, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 1, 0) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(3, 1, 0) || JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 2, 0) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8, 0, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_INLINE __inline
+#else
+#define JSON_HEDLEY_INLINE
+#endif
+
+#if defined(JSON_HEDLEY_ALWAYS_INLINE)
+#undef JSON_HEDLEY_ALWAYS_INLINE
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || JSON_HEDLEY_GCC_VERSION_CHECK(4, 0, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 11, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(10, 1, 0) || \
+ JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10) || \
+ JSON_HEDLEY_IAR_VERSION_CHECK(8, 10, 0)
+#define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(12, 0, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_ALWAYS_INLINE __forceinline
+#elif defined(__cplusplus) && \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6, 1, 0) || \
+ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0))
+#define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0)
+#define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
+#else
+#define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
+#endif
+
+#if defined(JSON_HEDLEY_NEVER_INLINE)
+#undef JSON_HEDLEY_NEVER_INLINE
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || JSON_HEDLEY_GCC_VERSION_CHECK(4, 0, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 11, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(10, 1, 0) || \
+ JSON_HEDLEY_TI_VERSION_CHECK(15, 12, 0) || \
+ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4, 8, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5, 2, 0) || \
+ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6, 4, 0) || \
+ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 0, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4, 3, 0) || \
+ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0) || JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1, 2, 0) || \
+ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2, 1, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10) || \
+ JSON_HEDLEY_IAR_VERSION_CHECK(8, 10, 0)
+#define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(13, 10, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(10, 2, 0)
+#define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
+#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6, 0, 0) && defined(__cplusplus)
+#define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0)
+#define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
+#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3, 2, 0)
+#define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9, 0, 0)
+#define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
+#else
+#define JSON_HEDLEY_NEVER_INLINE
+#endif
+
+#if defined(JSON_HEDLEY_PRIVATE)
+#undef JSON_HEDLEY_PRIVATE
+#endif
+#if defined(JSON_HEDLEY_PUBLIC)
+#undef JSON_HEDLEY_PUBLIC
+#endif
+#if defined(JSON_HEDLEY_IMPORT)
+#undef JSON_HEDLEY_IMPORT
+#endif
+#if defined(_WIN32) || defined(__CYGWIN__)
+#define JSON_HEDLEY_PRIVATE
+#define JSON_HEDLEY_PUBLIC __declspec(dllexport)
+#define JSON_HEDLEY_IMPORT __declspec(dllimport)
+#else
+#if JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 3, 0) || \
+ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 11, 0) || JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(13, 1, 0) || \
+ (defined(__TI_EABI__) && ((JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 2, 0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7, 5, 0))) || \
+ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
+#define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
+#else
+#define JSON_HEDLEY_PRIVATE
+#define JSON_HEDLEY_PUBLIC
+#endif
+#define JSON_HEDLEY_IMPORT extern
+#endif
+
+#if defined(JSON_HEDLEY_NO_THROW)
+#undef JSON_HEDLEY_NO_THROW
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 3, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(13, 1, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0)
+#define JSON_HEDLEY_NO_THROW __declspec(nothrow)
+#else
+#define JSON_HEDLEY_NO_THROW
+#endif
+
+#if defined(JSON_HEDLEY_FALL_THROUGH)
+#undef JSON_HEDLEY_FALL_THROUGH
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || JSON_HEDLEY_GCC_VERSION_CHECK(7, 0, 0) || \
+ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
+#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang, fallthrough)
+#define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
+#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
+#define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
+#elif defined(__fallthrough) /* SAL */
+#define JSON_HEDLEY_FALL_THROUGH __fallthrough
+#else
+#define JSON_HEDLEY_FALL_THROUGH
+#endif
+
+#if defined(JSON_HEDLEY_RETURNS_NON_NULL)
+#undef JSON_HEDLEY_RETURNS_NON_NULL
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || JSON_HEDLEY_GCC_VERSION_CHECK(4, 9, 0) || \
+ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
+#elif defined(_Ret_notnull_) /* SAL */
+#define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
+#else
+#define JSON_HEDLEY_RETURNS_NON_NULL
+#endif
+
+#if defined(JSON_HEDLEY_ARRAY_PARAM)
+#undef JSON_HEDLEY_ARRAY_PARAM
+#endif
+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__STDC_NO_VLA__) && \
+ !defined(__cplusplus) && !defined(JSON_HEDLEY_PGI_VERSION) && !defined(JSON_HEDLEY_TINYC_VERSION)
+#define JSON_HEDLEY_ARRAY_PARAM(name) (name)
+#else
+#define JSON_HEDLEY_ARRAY_PARAM(name)
+#endif
+
+#if defined(JSON_HEDLEY_IS_CONSTANT)
+#undef JSON_HEDLEY_IS_CONSTANT
+#endif
+#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
+#undef JSON_HEDLEY_REQUIRE_CONSTEXPR
+#endif
+/* JSON_HEDLEY_IS_CONSTEXPR_ is for
+ HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
+#if defined(JSON_HEDLEY_IS_CONSTEXPR_)
+#undef JSON_HEDLEY_IS_CONSTEXPR_
+#endif
+#if JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 4, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_TINYC_VERSION_CHECK(0, 9, 19) || \
+ JSON_HEDLEY_ARM_VERSION_CHECK(4, 1, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(13, 1, 0) || \
+ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6, 1, 0) || \
+ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5, 10, 0) && !defined(__cplusplus)) || \
+ JSON_HEDLEY_CRAY_VERSION_CHECK(8, 1, 0) || JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1, 25, 10)
+#define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
+#endif
+#if !defined(__cplusplus)
+#if JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || JSON_HEDLEY_GCC_VERSION_CHECK(3, 4, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || JSON_HEDLEY_IBM_VERSION_CHECK(13, 1, 0) || \
+ JSON_HEDLEY_CRAY_VERSION_CHECK(8, 1, 0) || JSON_HEDLEY_ARM_VERSION_CHECK(5, 4, 0) || \
+ JSON_HEDLEY_TINYC_VERSION_CHECK(0, 9, 24)
+#if defined(__INTPTR_TYPE__)
+#define JSON_HEDLEY_IS_CONSTEXPR_(expr) \
+ __builtin_types_compatible_p(__typeof__((1 ? (void*)((__INTPTR_TYPE__)((expr) * 0)) : (int*)0)), int*)
+#else
+#include <stdint.h>
+#define JSON_HEDLEY_IS_CONSTEXPR_(expr) \
+ __builtin_types_compatible_p(__typeof__((1 ? (void*)((intptr_t)((expr) * 0)) : (int*)0)), int*)
+#endif
+#elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(JSON_HEDLEY_SUNPRO_VERSION) && \
+ !defined(JSON_HEDLEY_PGI_VERSION) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
+ (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
+ JSON_HEDLEY_GCC_VERSION_CHECK(4, 9, 0) || JSON_HEDLEY_INTEL_VERSION_CHECK(17, 0, 0) || \
+ JSON_HEDLEY_IBM_VERSION_CHECK(12, 1, 0) || JSON_HEDLEY_ARM_VERSION_CHECK(5, 3, 0)
+#if defined(__INTPTR_TYPE__)
+#define JSON_HEDLEY_IS_CONSTEXPR_(expr) \
+ _Generic((1 ? (void*)((__INTPTR_TYPE__)((expr) * 0)) : (int*)0), int*: 1, void*: 0)
+#else
+#include <stdint.h>
+#define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*)((intptr_t)*0) : (int*)0), int*: 1, void*: 0)
+#endif
+#elif defined(JSON_HEDLEY_GCC_VERSION) || defined(JSON_HEDLEY_INTEL_VERSION) || defined(JSON_HEDLEY_TINYC_VERSION) || \
+ defined(JSON_HEDLEY_TI_ARMCL_VERSION) || JSON_HEDLEY_TI_CL430_VERSION_CHECK(18, 12, 0) || \
+ defined(JSON_HEDLEY_TI_CL2000_VERSION) || defined(JSON_HEDLEY_TI_CL6X_VERSION) || \
+ defined(JSON_HEDLEY_TI_CL7X_VERSION) || defined(JSON_HEDLEY_TI_CLPRU_VERSION) || defined(__clang__)
+#define JSON_HEDLEY_IS_CONSTEXPR_(expr) \
+ (sizeof(void) != sizeof(*(1 ? ((void*)((expr) * 0L)) : ((struct { char v[sizeof(void) * 2]; }*)1))))
+#endif
+#endif
+#if defined(JSON_HEDLEY_IS_CONSTEXPR_)
+#if !defined(JSON_HEDLEY_IS_CONSTANT)
+#define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
+#endif
+#define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
+#else
+#if !defined(JSON_HEDLEY_IS_CONSTANT)
+#define JSON_HEDLEY_IS_CONSTANT(expr) (0)
+#endif
+#define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
+#endif
+
+#if defined(JSON_HEDLEY_BEGIN_C_DECLS)
+#undef JSON_HEDLEY_BEGIN_C_DECLS
+#endif
+#if defined(JSON_HEDLEY_END_C_DECLS)
+#undef JSON_HEDLEY_END_C_DECLS
+#endif
+#if defined(JSON_HEDLEY_C_DECL)
+#undef JSON_HEDLEY_C_DECL
+#endif
+#if defined(__cplusplus)
+#define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
+#define JSON_HEDLEY_END_C_DECLS }
+#define JSON_HEDLEY_C_DECL extern "C"
+#else
+#define JSON_HEDLEY_BEGIN_C_DECLS
+#define JSON_HEDLEY_END_C_DECLS
+#define JSON_HEDLEY_C_DECL
+#endif
+
+#if defined(JSON_HEDLEY_STATIC_ASSERT)
+#undef JSON_HEDLEY_STATIC_ASSERT
+#endif
+#if !defined(__cplusplus) && \
+ ((defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
+ (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
+ JSON_HEDLEY_GCC_VERSION_CHECK(6, 0, 0) || JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0) || defined(_Static_assert))
+#define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
+#elif (defined(__cplusplus) && (__cplusplus >= 201103L)) || JSON_HEDLEY_MSVC_VERSION_CHECK(16, 0, 0) || \
+ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_STATIC_ASSERT(expr, message) \
+ JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
+#else
+#define JSON_HEDLEY_STATIC_ASSERT(expr, message)
+#endif
+
+#if defined(JSON_HEDLEY_NULL)
+#undef JSON_HEDLEY_NULL
+#endif
+#if defined(__cplusplus)
+#if __cplusplus >= 201103L
+#define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
+#elif defined(NULL)
+#define JSON_HEDLEY_NULL NULL
+#else
+#define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
+#endif
+#elif defined(NULL)
+#define JSON_HEDLEY_NULL NULL
+#else
+#define JSON_HEDLEY_NULL ((void*)0)
+#endif
+
+#if defined(JSON_HEDLEY_MESSAGE)
+#undef JSON_HEDLEY_MESSAGE
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
+#define JSON_HEDLEY_MESSAGE(msg) \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
+ JSON_HEDLEY_PRAGMA(message msg) \
+ JSON_HEDLEY_DIAGNOSTIC_POP
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4, 4, 0) || JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0)
+#define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
+#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5, 0, 0)
+#define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8, 0, 0)
+#define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2, 0, 0)
+#define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
+#else
+#define JSON_HEDLEY_MESSAGE(msg)
+#endif
+
+#if defined(JSON_HEDLEY_WARNING)
+#undef JSON_HEDLEY_WARNING
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
+#define JSON_HEDLEY_WARNING(msg) \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
+ JSON_HEDLEY_PRAGMA(clang warning msg) \
+ JSON_HEDLEY_DIAGNOSTIC_POP
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4, 8, 0) || JSON_HEDLEY_PGI_VERSION_CHECK(18, 4, 0) || \
+ JSON_HEDLEY_INTEL_VERSION_CHECK(13, 0, 0)
+#define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15, 0, 0) || JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
+#else
+#define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
+#endif
+
+#if defined(JSON_HEDLEY_REQUIRE)
+#undef JSON_HEDLEY_REQUIRE
+#endif
+#if defined(JSON_HEDLEY_REQUIRE_MSG)
+#undef JSON_HEDLEY_REQUIRE_MSG
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
+#if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
+#define JSON_HEDLEY_REQUIRE(expr) \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
+ __attribute__((diagnose_if(!(expr), #expr, "error"))) JSON_HEDLEY_DIAGNOSTIC_POP
+#define JSON_HEDLEY_REQUIRE_MSG(expr, msg) \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
+ __attribute__((diagnose_if(!(expr), msg, "error"))) JSON_HEDLEY_DIAGNOSTIC_POP
+#else
+#define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
+#define JSON_HEDLEY_REQUIRE_MSG(expr, msg) __attribute__((diagnose_if(!(expr), msg, "error")))
+#endif
+#else
+#define JSON_HEDLEY_REQUIRE(expr)
+#define JSON_HEDLEY_REQUIRE_MSG(expr, msg)
+#endif
+
+#if defined(JSON_HEDLEY_FLAGS)
+#undef JSON_HEDLEY_FLAGS
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && \
+ (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion"))
+#define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
+#else
+#define JSON_HEDLEY_FLAGS
+#endif
+
+#if defined(JSON_HEDLEY_FLAGS_CAST)
+#undef JSON_HEDLEY_FLAGS_CAST
+#endif
+#if JSON_HEDLEY_INTEL_VERSION_CHECK(19, 0, 0)
+#define JSON_HEDLEY_FLAGS_CAST(T, expr) \
+ (__extension__({ \
+ JSON_HEDLEY_DIAGNOSTIC_PUSH \
+ _Pragma("warning(disable:188)")((T)(expr)); \
+ JSON_HEDLEY_DIAGNOSTIC_POP \
+ }))
+#else
+#define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
+#endif
+
+#if defined(JSON_HEDLEY_EMPTY_BASES)
+#undef JSON_HEDLEY_EMPTY_BASES
+#endif
+#if (JSON_HEDLEY_MSVC_VERSION_CHECK(19, 0, 23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20, 0, 0)) || \
+ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021, 1, 0)
+#define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
+#else
+#define JSON_HEDLEY_EMPTY_BASES
+#endif
+
+/* Remaining macros are deprecated. */
+
+#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
+#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
+#endif
+#if defined(__clang__)
+#define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major, minor, patch) (0)
+#else
+#define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major, minor, patch) JSON_HEDLEY_GCC_VERSION_CHECK(major, minor, patch)
+#endif
+
+#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
+#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
+#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
+#undef JSON_HEDLEY_CLANG_HAS_BUILTIN
+#endif
+#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
+#undef JSON_HEDLEY_CLANG_HAS_FEATURE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
+#undef JSON_HEDLEY_CLANG_HAS_EXTENSION
+#endif
+#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
+#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
+#undef JSON_HEDLEY_CLANG_HAS_WARNING
+#endif
+#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
+
+#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
+
+// This file contains all internal macro definitions (except those affecting ABI)
+// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+// exclude unsupported compilers
+#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
+#if defined(__clang__)
+#if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
+#error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
+#endif
+#elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
+#if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
+#error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
+#endif
+#endif
+#endif
+
+// C++ language standard detection
+// if the user manually specified the used c++ version this is skipped
+#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11)
+#if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)
+#define JSON_HAS_CPP_20
+#define JSON_HAS_CPP_17
+#define JSON_HAS_CPP_14
+#elif (defined(__cplusplus) && __cplusplus >= 201703L) || \
+ (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
+#define JSON_HAS_CPP_17
+#define JSON_HAS_CPP_14
+#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
+#define JSON_HAS_CPP_14
+#endif
+// the cpp 11 flag is always specified because it is the minimal required version
+#define JSON_HAS_CPP_11
+#endif
+
+#ifdef __has_include
+#if __has_include(<version>)
+#include <version>
+#endif
+#endif
+
+#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM)
+#ifdef JSON_HAS_CPP_17
+#if defined(__cpp_lib_filesystem)
+#define JSON_HAS_FILESYSTEM 1
+#elif defined(__cpp_lib_experimental_filesystem)
+#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
+#elif !defined(__has_include)
+#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
+#elif __has_include(<filesystem>)
+#define JSON_HAS_FILESYSTEM 1
+#elif __has_include(<experimental/filesystem>)
+#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
+#endif
+
+// std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/
+#if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8
+#undef JSON_HAS_FILESYSTEM
+#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#endif
+
+// no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support
+#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8
+#undef JSON_HAS_FILESYSTEM
+#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#endif
+
+// no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support
+#if defined(__clang_major__) && __clang_major__ < 7
+#undef JSON_HAS_FILESYSTEM
+#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#endif
+
+// no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support
+#if defined(_MSC_VER) && _MSC_VER < 1914
+#undef JSON_HAS_FILESYSTEM
+#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#endif
+
+// no filesystem support before iOS 13
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
+#undef JSON_HAS_FILESYSTEM
+#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#endif
+
+// no filesystem support before macOS Catalina
+#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
+#undef JSON_HAS_FILESYSTEM
+#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#endif
+#endif
+#endif
+
+#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0
+#endif
+
+#ifndef JSON_HAS_FILESYSTEM
+#define JSON_HAS_FILESYSTEM 0
+#endif
+
+#ifndef JSON_HAS_THREE_WAY_COMPARISON
+#if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L && \
+ defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L
+#define JSON_HAS_THREE_WAY_COMPARISON 1
+#else
+#define JSON_HAS_THREE_WAY_COMPARISON 0
+#endif
+#endif
+
+#ifndef JSON_HAS_RANGES
+// ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error
+#if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427
+#define JSON_HAS_RANGES 0
+#elif defined(__cpp_lib_ranges)
+#define JSON_HAS_RANGES 1
+#else
+#define JSON_HAS_RANGES 0
+#endif
+#endif
+
+#ifndef JSON_HAS_STATIC_RTTI
+#if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0
+#define JSON_HAS_STATIC_RTTI 1
+#else
+#define JSON_HAS_STATIC_RTTI 0
+#endif
+#endif
+
+#ifdef JSON_HAS_CPP_17
+#define JSON_INLINE_VARIABLE inline
+#else
+#define JSON_INLINE_VARIABLE
+#endif
+
+#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address)
+#define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]]
+#else
+#define JSON_NO_UNIQUE_ADDRESS
+#endif
+
+// disable documentation warnings on clang
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdocumentation"
+#pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
+#endif
+
+// allow disabling exceptions
+#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
+#define JSON_THROW(exception) throw exception
+#define JSON_TRY try
+#define JSON_CATCH(exception) catch (exception)
+#define JSON_INTERNAL_CATCH(exception) catch (exception)
+#else
+#include <cstdlib>
+#define JSON_THROW(exception) std::abort()
+#define JSON_TRY if (true)
+#define JSON_CATCH(exception) if (false)
+#define JSON_INTERNAL_CATCH(exception) if (false)
+#endif
+
+// override exception macros
+#if defined(JSON_THROW_USER)
+#undef JSON_THROW
+#define JSON_THROW JSON_THROW_USER
+#endif
+#if defined(JSON_TRY_USER)
+#undef JSON_TRY
+#define JSON_TRY JSON_TRY_USER
+#endif
+#if defined(JSON_CATCH_USER)
+#undef JSON_CATCH
+#define JSON_CATCH JSON_CATCH_USER
+#undef JSON_INTERNAL_CATCH
+#define JSON_INTERNAL_CATCH JSON_CATCH_USER
+#endif
+#if defined(JSON_INTERNAL_CATCH_USER)
+#undef JSON_INTERNAL_CATCH
+#define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
+#endif
+
+// allow overriding assert
+#if !defined(JSON_ASSERT)
+#include <cassert> // assert
+#define JSON_ASSERT(x) assert(x)
+#endif
+
+// allow to access some private functions (needed by the test suite)
+#if defined(JSON_TESTS_PRIVATE)
+#define JSON_PRIVATE_UNLESS_TESTED public
+#else
+#define JSON_PRIVATE_UNLESS_TESTED private
+#endif
+
+/*!
+@brief macro to briefly define a mapping between an enum and JSON
+@def NLOHMANN_JSON_SERIALIZE_ENUM
+@since version 3.4.0
+*/
+#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
+ template <typename BasicJsonType> \
+ inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) { \
+ static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
+ static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
+ auto it = \
+ std::find_if(std::begin(m), std::end(m), [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool { \
+ return ej_pair.first == e; \
+ }); \
+ j = ((it != std::end(m)) ? it : std::begin(m))->second; \
+ } \
+ template <typename BasicJsonType> \
+ inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) { \
+ static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
+ static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
+ auto it = std::find_if( \
+ std::begin(m), std::end(m), [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool { \
+ return ej_pair.second == j; \
+ }); \
+ e = ((it != std::end(m)) ? it : std::begin(m))->first; \
+ }
+
+// Ugly macros to avoid uglier copy-paste when specializing basic_json. They
+// may be removed in the future once the class is split.
+
+#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
+ template <template <typename, typename, typename...> class ObjectType, \
+ template <typename, typename...> class ArrayType, \
+ class StringType, \
+ class BooleanType, \
+ class NumberIntegerType, \
+ class NumberUnsignedType, \
+ class NumberFloatType, \
+ template <typename> class AllocatorType, \
+ template <typename, typename = void> class JSONSerializer, \
+ class BinaryType, \
+ class CustomBaseClass>
+
+#define NLOHMANN_BASIC_JSON_TPL \
+ basic_json<ObjectType, \
+ ArrayType, \
+ StringType, \
+ BooleanType, \
+ NumberIntegerType, \
+ NumberUnsignedType, \
+ NumberFloatType, \
+ AllocatorType, \
+ JSONSerializer, \
+ BinaryType, \
+ CustomBaseClass>
+
+// Macros to simplify conversion from/to types
+
+#define NLOHMANN_JSON_EXPAND(x) x
+#define NLOHMANN_JSON_GET_MACRO(_1, \
+ _2, \
+ _3, \
+ _4, \
+ _5, \
+ _6, \
+ _7, \
+ _8, \
+ _9, \
+ _10, \
+ _11, \
+ _12, \
+ _13, \
+ _14, \
+ _15, \
+ _16, \
+ _17, \
+ _18, \
+ _19, \
+ _20, \
+ _21, \
+ _22, \
+ _23, \
+ _24, \
+ _25, \
+ _26, \
+ _27, \
+ _28, \
+ _29, \
+ _30, \
+ _31, \
+ _32, \
+ _33, \
+ _34, \
+ _35, \
+ _36, \
+ _37, \
+ _38, \
+ _39, \
+ _40, \
+ _41, \
+ _42, \
+ _43, \
+ _44, \
+ _45, \
+ _46, \
+ _47, \
+ _48, \
+ _49, \
+ _50, \
+ _51, \
+ _52, \
+ _53, \
+ _54, \
+ _55, \
+ _56, \
+ _57, \
+ _58, \
+ _59, \
+ _60, \
+ _61, \
+ _62, \
+ _63, \
+ _64, \
+ NAME, \
+ ...) \
+ NAME
+#define NLOHMANN_JSON_PASTE(...) \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \
+ NLOHMANN_JSON_PASTE64, \
+ NLOHMANN_JSON_PASTE63, \
+ NLOHMANN_JSON_PASTE62, \
+ NLOHMANN_JSON_PASTE61, \
+ NLOHMANN_JSON_PASTE60, \
+ NLOHMANN_JSON_PASTE59, \
+ NLOHMANN_JSON_PASTE58, \
+ NLOHMANN_JSON_PASTE57, \
+ NLOHMANN_JSON_PASTE56, \
+ NLOHMANN_JSON_PASTE55, \
+ NLOHMANN_JSON_PASTE54, \
+ NLOHMANN_JSON_PASTE53, \
+ NLOHMANN_JSON_PASTE52, \
+ NLOHMANN_JSON_PASTE51, \
+ NLOHMANN_JSON_PASTE50, \
+ NLOHMANN_JSON_PASTE49, \
+ NLOHMANN_JSON_PASTE48, \
+ NLOHMANN_JSON_PASTE47, \
+ NLOHMANN_JSON_PASTE46, \
+ NLOHMANN_JSON_PASTE45, \
+ NLOHMANN_JSON_PASTE44, \
+ NLOHMANN_JSON_PASTE43, \
+ NLOHMANN_JSON_PASTE42, \
+ NLOHMANN_JSON_PASTE41, \
+ NLOHMANN_JSON_PASTE40, \
+ NLOHMANN_JSON_PASTE39, \
+ NLOHMANN_JSON_PASTE38, \
+ NLOHMANN_JSON_PASTE37, \
+ NLOHMANN_JSON_PASTE36, \
+ NLOHMANN_JSON_PASTE35, \
+ NLOHMANN_JSON_PASTE34, \
+ NLOHMANN_JSON_PASTE33, \
+ NLOHMANN_JSON_PASTE32, \
+ NLOHMANN_JSON_PASTE31, \
+ NLOHMANN_JSON_PASTE30, \
+ NLOHMANN_JSON_PASTE29, \
+ NLOHMANN_JSON_PASTE28, \
+ NLOHMANN_JSON_PASTE27, \
+ NLOHMANN_JSON_PASTE26, \
+ NLOHMANN_JSON_PASTE25, \
+ NLOHMANN_JSON_PASTE24, \
+ NLOHMANN_JSON_PASTE23, \
+ NLOHMANN_JSON_PASTE22, \
+ NLOHMANN_JSON_PASTE21, \
+ NLOHMANN_JSON_PASTE20, \
+ NLOHMANN_JSON_PASTE19, \
+ NLOHMANN_JSON_PASTE18, \
+ NLOHMANN_JSON_PASTE17, \
+ NLOHMANN_JSON_PASTE16, \
+ NLOHMANN_JSON_PASTE15, \
+ NLOHMANN_JSON_PASTE14, \
+ NLOHMANN_JSON_PASTE13, \
+ NLOHMANN_JSON_PASTE12, \
+ NLOHMANN_JSON_PASTE11, \
+ NLOHMANN_JSON_PASTE10, \
+ NLOHMANN_JSON_PASTE9, \
+ NLOHMANN_JSON_PASTE8, \
+ NLOHMANN_JSON_PASTE7, \
+ NLOHMANN_JSON_PASTE6, \
+ NLOHMANN_JSON_PASTE5, \
+ NLOHMANN_JSON_PASTE4, \
+ NLOHMANN_JSON_PASTE3, \
+ NLOHMANN_JSON_PASTE2, \
+ NLOHMANN_JSON_PASTE1)(__VA_ARGS__))
+#define NLOHMANN_JSON_PASTE2(func, v1) func(v1)
+#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2)
+#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3)
+#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4)
+#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5)
+#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6)
+#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7)
+#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8)
+#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9)
+#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10)
+#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11)
+#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12)
+#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13)
+#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) \
+ NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14)
+#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)
+#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16)
+#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17)
+#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18)
+#define NLOHMANN_JSON_PASTE20( \
+ func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19)
+#define NLOHMANN_JSON_PASTE21( \
+ func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20)
+#define NLOHMANN_JSON_PASTE22( \
+ func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE21( \
+ func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21)
+#define NLOHMANN_JSON_PASTE23( \
+ func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE22( \
+ func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22)
+#define NLOHMANN_JSON_PASTE24( \
+ func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE23( \
+ func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23)
+#define NLOHMANN_JSON_PASTE25(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE24(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24)
+#define NLOHMANN_JSON_PASTE26(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE25(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25)
+#define NLOHMANN_JSON_PASTE27(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE26(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26)
+#define NLOHMANN_JSON_PASTE28(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE27(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27)
+#define NLOHMANN_JSON_PASTE29(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE28(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28)
+#define NLOHMANN_JSON_PASTE30(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE29(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29)
+#define NLOHMANN_JSON_PASTE31(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE30(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30)
+#define NLOHMANN_JSON_PASTE32(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE31(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31)
+#define NLOHMANN_JSON_PASTE33(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE32(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32)
+#define NLOHMANN_JSON_PASTE34(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE33(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33)
+#define NLOHMANN_JSON_PASTE35(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE34(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34)
+#define NLOHMANN_JSON_PASTE36(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE35(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35)
+#define NLOHMANN_JSON_PASTE37(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE36(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36)
+#define NLOHMANN_JSON_PASTE38(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE37(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37)
+#define NLOHMANN_JSON_PASTE39(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE38(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38)
+#define NLOHMANN_JSON_PASTE40(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE39(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39)
+#define NLOHMANN_JSON_PASTE41(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE40(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40)
+#define NLOHMANN_JSON_PASTE42(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE41(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41)
+#define NLOHMANN_JSON_PASTE43(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE42(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42)
+#define NLOHMANN_JSON_PASTE44(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE43(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43)
+#define NLOHMANN_JSON_PASTE45(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE44(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44)
+#define NLOHMANN_JSON_PASTE46(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE45(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45)
+#define NLOHMANN_JSON_PASTE47(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE46(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46)
+#define NLOHMANN_JSON_PASTE48(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE47(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47)
+#define NLOHMANN_JSON_PASTE49(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE48(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48)
+#define NLOHMANN_JSON_PASTE50(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE49(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49)
+#define NLOHMANN_JSON_PASTE51(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE50(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50)
+#define NLOHMANN_JSON_PASTE52(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE51(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51)
+#define NLOHMANN_JSON_PASTE53(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE52(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52)
+#define NLOHMANN_JSON_PASTE54(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE53(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53)
+#define NLOHMANN_JSON_PASTE55(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE54(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54)
+#define NLOHMANN_JSON_PASTE56(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE55(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55)
+#define NLOHMANN_JSON_PASTE57(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE56(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56)
+#define NLOHMANN_JSON_PASTE58(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE57(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57)
+#define NLOHMANN_JSON_PASTE59(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE58(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58)
+#define NLOHMANN_JSON_PASTE60(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE59(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59)
+#define NLOHMANN_JSON_PASTE61(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59, \
+ v60) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE60(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59, \
+ v60)
+#define NLOHMANN_JSON_PASTE62(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59, \
+ v60, \
+ v61) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE61(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59, \
+ v60, \
+ v61)
+#define NLOHMANN_JSON_PASTE63(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59, \
+ v60, \
+ v61, \
+ v62) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE62(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59, \
+ v60, \
+ v61, \
+ v62)
+#define NLOHMANN_JSON_PASTE64(func, \
+ v1, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59, \
+ v60, \
+ v61, \
+ v62, \
+ v63) \
+ NLOHMANN_JSON_PASTE2(func, v1) \
+ NLOHMANN_JSON_PASTE63(func, \
+ v2, \
+ v3, \
+ v4, \
+ v5, \
+ v6, \
+ v7, \
+ v8, \
+ v9, \
+ v10, \
+ v11, \
+ v12, \
+ v13, \
+ v14, \
+ v15, \
+ v16, \
+ v17, \
+ v18, \
+ v19, \
+ v20, \
+ v21, \
+ v22, \
+ v23, \
+ v24, \
+ v25, \
+ v26, \
+ v27, \
+ v28, \
+ v29, \
+ v30, \
+ v31, \
+ v32, \
+ v33, \
+ v34, \
+ v35, \
+ v36, \
+ v37, \
+ v38, \
+ v39, \
+ v40, \
+ v41, \
+ v42, \
+ v43, \
+ v44, \
+ v45, \
+ v46, \
+ v47, \
+ v48, \
+ v49, \
+ v50, \
+ v51, \
+ v52, \
+ v53, \
+ v54, \
+ v55, \
+ v56, \
+ v57, \
+ v58, \
+ v59, \
+ v60, \
+ v61, \
+ v62, \
+ v63)
+
+#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1;
+#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1);
+#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) \
+ nlohmann_json_t.v1 = nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1);
+
+/*!
+@brief macro
+@def NLOHMANN_DEFINE_TYPE_INTRUSIVE
+@since version 3.9.0
+*/
+#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \
+ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) \
+ } \
+ friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) \
+ }
+
+#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \
+ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) \
+ } \
+ friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { \
+ const Type nlohmann_json_default_obj{}; \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) \
+ }
+
+#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \
+ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) \
+ }
+
+/*!
+@brief macro
+@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
+@since version 3.9.0
+*/
+#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \
+ inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) \
+ } \
+ inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) \
+ }
+
+#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \
+ inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) \
+ }
+
+#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \
+ inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) \
+ } \
+ inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { \
+ const Type nlohmann_json_default_obj{}; \
+ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) \
+ }
+
+// inspired from https://stackoverflow.com/a/26745591
+// allows to call any std function as if (e.g. with begin):
+// using std::begin; begin(x);
+//
+// it allows using the detected idiom to retrieve the return type
+// of such an expression
+#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \
+ namespace detail { \
+ using std::std_name; \
+ \
+ template <typename... T> \
+ using result_of_##std_name = decltype(std_name(std::declval<T>()...)); \
+ } \
+ \
+ namespace detail2 { \
+ struct std_name##_tag {}; \
+ \
+ template <typename... T> \
+ std_name##_tag \
+ std_name(T&&...); \
+ \
+ template <typename... T> \
+ using result_of_##std_name = decltype(std_name(std::declval<T>()...)); \
+ \
+ template <typename... T> \
+ struct would_call_std_##std_name { \
+ static constexpr auto const value = \
+ ::nlohmann::detail::is_detected_exact<std_name##_tag, result_of_##std_name, T...>::value; \
+ }; \
+ } /* namespace detail2 */ \
+ \
+ template <typename... T> \
+ struct would_call_std_##std_name : detail2::would_call_std_##std_name<T...> {}
+
+#ifndef JSON_USE_IMPLICIT_CONVERSIONS
+#define JSON_USE_IMPLICIT_CONVERSIONS 1
+#endif
+
+#if JSON_USE_IMPLICIT_CONVERSIONS
+#define JSON_EXPLICIT
+#else
+#define JSON_EXPLICIT explicit
+#endif
+
+#ifndef JSON_DISABLE_ENUM_SERIALIZATION
+#define JSON_DISABLE_ENUM_SERIALIZATION 0
+#endif
+
+#ifndef JSON_USE_GLOBAL_UDLS
+#define JSON_USE_GLOBAL_UDLS 1
+#endif
+
+#if JSON_HAS_THREE_WAY_COMPARISON
+#include <compare> // partial_ordering
+#endif
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+///////////////////////////
+// JSON type enumeration //
+///////////////////////////
+
+/*!
+@brief the JSON type enumeration
+
+This enumeration collects the different JSON types. It is internally used to
+distinguish the stored values, and the functions @ref basic_json::is_null(),
+@ref basic_json::is_object(), @ref basic_json::is_array(),
+@ref basic_json::is_string(), @ref basic_json::is_boolean(),
+@ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
+@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
+@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
+@ref basic_json::is_structured() rely on it.
+
+@note There are three enumeration entries (number_integer, number_unsigned, and
+number_float), because the library distinguishes these three types for numbers:
+@ref basic_json::number_unsigned_t is used for unsigned integers,
+@ref basic_json::number_integer_t is used for signed integers, and
+@ref basic_json::number_float_t is used for floating-point numbers or to
+approximate integers which do not fit in the limits of their respective type.
+
+@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON
+value with the default value for a given type
+
+@since version 1.0.0
+*/
+enum class value_t : std::uint8_t {
+ null, ///< null value
+ object, ///< object (unordered set of name/value pairs)
+ array, ///< array (ordered collection of values)
+ string, ///< string value
+ boolean, ///< boolean value
+ number_integer, ///< number value (signed integer)
+ number_unsigned, ///< number value (unsigned integer)
+ number_float, ///< number value (floating-point)
+ binary, ///< binary array (ordered collection of bytes)
+ discarded ///< discarded by the parser callback function
+};
+
+/*!
+@brief comparison operator for JSON types
+
+Returns an ordering that is similar to Python:
+- order: null < boolean < number < object < array < string < binary
+- furthermore, each type is not smaller than itself
+- discarded values are not comparable
+- binary is represented as a b"" string in python and directly comparable to a
+ string; however, making a binary array directly comparable with a string would
+ be surprising behavior in a JSON file.
+
+@since version 1.0.0
+*/
+#if JSON_HAS_THREE_WAY_COMPARISON
+inline std::partial_ordering
+operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD*
+#else
+inline bool
+operator<(const value_t lhs, const value_t rhs) noexcept
+#endif
+{
+ static constexpr std::array<std::uint8_t, 9> order = {{
+ 0 /* null */,
+ 3 /* object */,
+ 4 /* array */,
+ 5 /* string */,
+ 1 /* boolean */,
+ 2 /* integer */,
+ 2 /* unsigned */,
+ 2 /* float */,
+ 6 /* binary */
+ }};
+
+ const auto l_index = static_cast<std::size_t>(lhs);
+ const auto r_index = static_cast<std::size_t>(rhs);
+#if JSON_HAS_THREE_WAY_COMPARISON
+ if (l_index < order.size() && r_index < order.size()) {
+ return order[l_index] <=> order[r_index]; // *NOPAD*
+ }
+ return std::partial_ordering::unordered;
+#else
+ return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index];
+#endif
+}
+
+// GCC selects the built-in operator< over an operator rewritten from
+// a user-defined spaceship operator
+// Clang, MSVC, and ICC select the rewritten candidate
+// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200)
+#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__)
+inline bool
+operator<(const value_t lhs, const value_t rhs) noexcept {
+ return std::is_lt(lhs <=> rhs); // *NOPAD*
+}
+#endif
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/string_escape.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+/*!
+@brief replace all occurrences of a substring by another string
+
+@param[in,out] s the string to manipulate; changed so that all
+ occurrences of @a f are replaced with @a t
+@param[in] f the substring to replace with @a t
+@param[in] t the string to replace @a f
+
+@pre The search string @a f must not be empty. **This precondition is
+enforced with an assertion.**
+
+@since version 2.0.0
+*/
+template <typename StringType>
+inline void
+replace_substring(StringType& s, const StringType& f, const StringType& t) {
+ JSON_ASSERT(!f.empty());
+ for (auto pos = s.find(f); // find first occurrence of f
+ pos != StringType::npos; // make sure f was found
+ s.replace(pos, f.size(), t), // replace with t, and
+ pos = s.find(f, pos + t.size())) // find next occurrence of f
+ {
+ }
+}
+
+/*!
+ * @brief string escaping as described in RFC 6901 (Sect. 4)
+ * @param[in] s string to escape
+ * @return escaped string
+ *
+ * Note the order of escaping "~" to "~0" and "/" to "~1" is important.
+ */
+template <typename StringType>
+inline StringType
+escape(StringType s) {
+ replace_substring(s, StringType{"~"}, StringType{"~0"});
+ replace_substring(s, StringType{"/"}, StringType{"~1"});
+ return s;
+}
+
+/*!
+ * @brief string unescaping as described in RFC 6901 (Sect. 4)
+ * @param[in] s string to unescape
+ * @return unescaped string
+ *
+ * Note the order of escaping "~1" to "/" and "~0" to "~" is important.
+ */
+template <typename StringType>
+static void
+unescape(StringType& s) {
+ replace_substring(s, StringType{"~1"}, StringType{"/"});
+ replace_substring(s, StringType{"~0"}, StringType{"~"});
+}
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/input/position_t.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstddef> // size_t
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+/// struct to capture the start position of the current token
+struct position_t {
+ /// the total number of characters read
+ std::size_t chars_read_total = 0;
+ /// the number of characters read in the current line
+ std::size_t chars_read_current_line = 0;
+ /// the number of lines read
+ std::size_t lines_read = 0;
+
+ /// conversion to size_t to preserve SAX interface
+ constexpr
+ operator size_t() const {
+ return chars_read_total;
+ }
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-FileCopyrightText: 2018 The Abseil Authors
+// SPDX-License-Identifier: MIT
+
+#include <array> // array
+#include <cstddef> // size_t
+#include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
+#include <utility> // index_sequence, make_index_sequence, index_sequence_for
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+template <typename T>
+using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
+
+#ifdef JSON_HAS_CPP_14
+
+// the following utilities are natively available in C++14
+using std::enable_if_t;
+using std::index_sequence;
+using std::index_sequence_for;
+using std::make_index_sequence;
+
+#else
+
+// alias templates to reduce boilerplate
+template <bool B, typename T = void>
+using enable_if_t = typename std::enable_if<B, T>::type;
+
+// The following code is taken from
+// https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h which is
+// part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0.
+
+//// START OF CODE FROM GOOGLE ABSEIL
+
+// integer_sequence
+//
+// Class template representing a compile-time integer sequence. An instantiation
+// of `integer_sequence<T, Ints...>` has a sequence of integers encoded in its
+// type through its template arguments (which is a common need when
+// working with C++11 variadic templates). `absl::integer_sequence` is designed
+// to be a drop-in replacement for C++14's `std::integer_sequence`.
+//
+// Example:
+//
+// template< class T, T... Ints >
+// void user_function(integer_sequence<T, Ints...>);
+//
+// int main()
+// {
+// // user_function's `T` will be deduced to `int` and `Ints...`
+// // will be deduced to `0, 1, 2, 3, 4`.
+// user_function(make_integer_sequence<int, 5>());
+// }
+template <typename T, T... Ints>
+struct integer_sequence {
+ using value_type = T;
+ static constexpr std::size_t
+ size() noexcept {
+ return sizeof...(Ints);
+ }
+};
+
+// index_sequence
+//
+// A helper template for an `integer_sequence` of `size_t`,
+// `absl::index_sequence` is designed to be a drop-in replacement for C++14's
+// `std::index_sequence`.
+template <size_t... Ints>
+using index_sequence = integer_sequence<size_t, Ints...>;
+
+namespace utility_internal {
+
+template <typename Seq, size_t SeqSize, size_t Rem>
+struct Extend;
+
+// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency.
+template <typename T, T... Ints, size_t SeqSize>
+struct Extend<integer_sequence<T, Ints...>, SeqSize, 0> {
+ using type = integer_sequence<T, Ints..., (Ints + SeqSize)...>;
+};
+
+template <typename T, T... Ints, size_t SeqSize>
+struct Extend<integer_sequence<T, Ints...>, SeqSize, 1> {
+ using type = integer_sequence<T, Ints..., (Ints + SeqSize)..., 2 * SeqSize>;
+};
+
+// Recursion helper for 'make_integer_sequence<T, N>'.
+// 'Gen<T, N>::type' is an alias for 'integer_sequence<T, 0, 1, ... N-1>'.
+template <typename T, size_t N>
+struct Gen {
+ using type = typename Extend<typename Gen<T, N / 2>::type, N / 2, N % 2>::type;
+};
+
+template <typename T>
+struct Gen<T, 0> {
+ using type = integer_sequence<T>;
+};
+
+} // namespace utility_internal
+
+// Compile-time sequences of integers
+
+// make_integer_sequence
+//
+// This template alias is equivalent to
+// `integer_sequence<int, 0, 1, ..., N-1>`, and is designed to be a drop-in
+// replacement for C++14's `std::make_integer_sequence`.
+template <typename T, T N>
+using make_integer_sequence = typename utility_internal::Gen<T, N>::type;
+
+// make_index_sequence
+//
+// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`,
+// and is designed to be a drop-in replacement for C++14's
+// `std::make_index_sequence`.
+template <size_t N>
+using make_index_sequence = make_integer_sequence<size_t, N>;
+
+// index_sequence_for
+//
+// Converts a typename pack into an index sequence of the same length, and
+// is designed to be a drop-in replacement for C++14's
+// `std::index_sequence_for()`
+template <typename... Ts>
+using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
+
+//// END OF CODE FROM GOOGLE ABSEIL
+
+#endif
+
+// dispatch utility (taken from ranges-v3)
+template <unsigned N>
+struct priority_tag : priority_tag<N - 1> {};
+template <>
+struct priority_tag<0> {};
+
+// taken from ranges-v3
+template <typename T>
+struct static_const {
+ static JSON_INLINE_VARIABLE constexpr T value{};
+};
+
+#ifndef JSON_HAS_CPP_17
+template <typename T>
+constexpr T static_const<T>::value;
+#endif
+
+template <typename T, typename... Args>
+inline constexpr std::array<T, sizeof...(Args)>
+make_array(Args&&... args) {
+ return std::array<T, sizeof...(Args)>{{static_cast<T>(std::forward<Args>(args))...}};
+}
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <limits> // numeric_limits
+#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
+#include <utility> // declval
+#include <tuple> // tuple
+#include <string> // char_traits
+
+// #include <nlohmann/detail/iterators/iterator_traits.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <iterator> // random_access_iterator_tag
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+// #include <nlohmann/detail/meta/void_t.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+template <typename It, typename = void>
+struct iterator_types {};
+
+template <typename It>
+struct iterator_types<It,
+ void_t<typename It::difference_type,
+ typename It::value_type,
+ typename It::pointer,
+ typename It::reference,
+ typename It::iterator_category>> {
+ using difference_type = typename It::difference_type;
+ using value_type = typename It::value_type;
+ using pointer = typename It::pointer;
+ using reference = typename It::reference;
+ using iterator_category = typename It::iterator_category;
+};
+
+// This is required as some compilers implement std::iterator_traits in a way that
+// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
+template <typename T, typename = void>
+struct iterator_traits {};
+
+template <typename T>
+struct iterator_traits<T, enable_if_t<!std::is_pointer<T>::value>> : iterator_types<T> {};
+
+template <typename T>
+struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>> {
+ using iterator_category = std::random_access_iterator_tag;
+ using value_type = T;
+ using difference_type = ptrdiff_t;
+ using pointer = T*;
+ using reference = T&;
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/call_std/begin.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+
+NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin);
+
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/meta/call_std/end.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+
+NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end);
+
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/detected.hpp>
+
+// #include <nlohmann/json_fwd.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
+#define INCLUDE_NLOHMANN_JSON_FWD_HPP_
+
+#include <cstdint> // int64_t, uint64_t
+#include <map> // map
+#include <memory> // allocator
+#include <string> // string
+#include <vector> // vector
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+/*!
+@brief namespace for Niels Lohmann
+@see https://github.com/nlohmann
+@since version 1.0.0
+*/
+NLOHMANN_JSON_NAMESPACE_BEGIN
+
+/*!
+@brief default JSONSerializer template argument
+
+This serializer ignores the template arguments and uses ADL
+([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
+for serialization.
+*/
+template <typename T = void, typename SFINAE = void>
+struct adl_serializer;
+
+/// a class to store JSON values
+/// @sa https://json.nlohmann.me/api/basic_json/
+template <template <typename U, typename V, typename... Args> class ObjectType = std::map,
+ template <typename U, typename... Args> class ArrayType = std::vector,
+ class StringType = std::string,
+ class BooleanType = bool,
+ class NumberIntegerType = std::int64_t,
+ class NumberUnsignedType = std::uint64_t,
+ class NumberFloatType = double,
+ template <typename U> class AllocatorType = std::allocator,
+ template <typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,
+ class BinaryType = std::vector<std::uint8_t>, // cppcheck-suppress syntaxError
+ class CustomBaseClass = void>
+class basic_json;
+
+/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
+/// @sa https://json.nlohmann.me/api/json_pointer/
+template <typename RefStringType>
+class json_pointer;
+
+/*!
+@brief default specialization
+@sa https://json.nlohmann.me/api/json/
+*/
+using json = basic_json<>;
+
+/// @brief a minimal map-like container that preserves insertion order
+/// @sa https://json.nlohmann.me/api/ordered_map/
+template <class Key, class T, class IgnoredLess, class Allocator>
+struct ordered_map;
+
+/// @brief specialization that maintains the insertion order of object keys
+/// @sa https://json.nlohmann.me/api/ordered_json/
+using ordered_json = basic_json<nlohmann::ordered_map>;
+
+NLOHMANN_JSON_NAMESPACE_END
+
+#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+/*!
+@brief detail namespace with internal helper functions
+
+This namespace collects functions that should not be exposed,
+implementations of some @ref basic_json methods, and meta-programming helpers.
+
+@since version 2.1.0
+*/
+namespace detail {
+
+/////////////
+// helpers //
+/////////////
+
+// Note to maintainers:
+//
+// Every trait in this file expects a non CV-qualified type.
+// The only exceptions are in the 'aliases for detected' section
+// (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
+//
+// In this case, T has to be properly CV-qualified to constraint the function arguments
+// (e.g. to_json(BasicJsonType&, const T&))
+
+template <typename>
+struct is_basic_json : std::false_type {};
+
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
+
+// used by exceptions create() member functions
+// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t
+// false_type otherwise
+template <typename BasicJsonContext>
+struct is_basic_json_context
+ : std::integral_constant<
+ bool,
+ is_basic_json<typename std::remove_cv<typename std::remove_pointer<BasicJsonContext>::type>::type>::value ||
+ std::is_same<BasicJsonContext, std::nullptr_t>::value> {};
+
+//////////////////////
+// json_ref helpers //
+//////////////////////
+
+template <typename>
+class json_ref;
+
+template <typename>
+struct is_json_ref : std::false_type {};
+
+template <typename T>
+struct is_json_ref<json_ref<T>> : std::true_type {};
+
+//////////////////////////
+// aliases for detected //
+//////////////////////////
+
+template <typename T>
+using mapped_type_t = typename T::mapped_type;
+
+template <typename T>
+using key_type_t = typename T::key_type;
+
+template <typename T>
+using value_type_t = typename T::value_type;
+
+template <typename T>
+using difference_type_t = typename T::difference_type;
+
+template <typename T>
+using pointer_t = typename T::pointer;
+
+template <typename T>
+using reference_t = typename T::reference;
+
+template <typename T>
+using iterator_category_t = typename T::iterator_category;
+
+template <typename T, typename... Args>
+using to_json_function = decltype(T::to_json(std::declval<Args>()...));
+
+template <typename T, typename... Args>
+using from_json_function = decltype(T::from_json(std::declval<Args>()...));
+
+template <typename T, typename U>
+using get_template_function = decltype(std::declval<T>().template get<U>());
+
+// trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
+template <typename BasicJsonType, typename T, typename = void>
+struct has_from_json : std::false_type {};
+
+// trait checking if j.get<T> is valid
+// use this trait instead of std::is_constructible or std::is_convertible,
+// both rely on, or make use of implicit conversions, and thus fail when T
+// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958)
+template <typename BasicJsonType, typename T>
+struct is_getable {
+ static constexpr bool value = is_detected<get_template_function, const BasicJsonType&, T>::value;
+};
+
+template <typename BasicJsonType, typename T>
+struct has_from_json<BasicJsonType, T, enable_if_t<!is_basic_json<T>::value>> {
+ using serializer = typename BasicJsonType::template json_serializer<T, void>;
+
+ static constexpr bool value =
+ is_detected_exact<void, from_json_function, serializer, const BasicJsonType&, T&>::value;
+};
+
+// This trait checks if JSONSerializer<T>::from_json(json const&) exists
+// this overload is used for non-default-constructible user-defined-types
+template <typename BasicJsonType, typename T, typename = void>
+struct has_non_default_from_json : std::false_type {};
+
+template <typename BasicJsonType, typename T>
+struct has_non_default_from_json<BasicJsonType, T, enable_if_t<!is_basic_json<T>::value>> {
+ using serializer = typename BasicJsonType::template json_serializer<T, void>;
+
+ static constexpr bool value = is_detected_exact<T, from_json_function, serializer, const BasicJsonType&>::value;
+};
+
+// This trait checks if BasicJsonType::json_serializer<T>::to_json exists
+// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
+template <typename BasicJsonType, typename T, typename = void>
+struct has_to_json : std::false_type {};
+
+template <typename BasicJsonType, typename T>
+struct has_to_json<BasicJsonType, T, enable_if_t<!is_basic_json<T>::value>> {
+ using serializer = typename BasicJsonType::template json_serializer<T, void>;
+
+ static constexpr bool value = is_detected_exact<void, to_json_function, serializer, BasicJsonType&, T>::value;
+};
+
+template <typename T>
+using detect_key_compare = typename T::key_compare;
+
+template <typename T>
+struct has_key_compare : std::integral_constant<bool, is_detected<detect_key_compare, T>::value> {};
+
+// obtains the actual object key comparator
+template <typename BasicJsonType>
+struct actual_object_comparator {
+ using object_t = typename BasicJsonType::object_t;
+ using object_comparator_t = typename BasicJsonType::default_object_comparator_t;
+ using type = typename std::
+ conditional<has_key_compare<object_t>::value, typename object_t::key_compare, object_comparator_t>::type;
+};
+
+template <typename BasicJsonType>
+using actual_object_comparator_t = typename actual_object_comparator<BasicJsonType>::type;
+
+/////////////////
+// char_traits //
+/////////////////
+
+// Primary template of char_traits calls std char_traits
+template <typename T>
+struct char_traits : std::char_traits<T> {};
+
+// Explicitly define char traits for unsigned char since it is not standard
+template <>
+struct char_traits<unsigned char> : std::char_traits<char> {
+ using char_type = unsigned char;
+ using int_type = uint64_t;
+
+ // Redefine to_int_type function
+ static int_type
+ to_int_type(char_type c) noexcept {
+ return static_cast<int_type>(c);
+ }
+
+ static char_type
+ to_char_type(int_type i) noexcept {
+ return static_cast<char_type>(i);
+ }
+
+ static constexpr int_type
+ eof() noexcept {
+ return static_cast<int_type>(EOF);
+ }
+};
+
+// Explicitly define char traits for signed char since it is not standard
+template <>
+struct char_traits<signed char> : std::char_traits<char> {
+ using char_type = signed char;
+ using int_type = uint64_t;
+
+ // Redefine to_int_type function
+ static int_type
+ to_int_type(char_type c) noexcept {
+ return static_cast<int_type>(c);
+ }
+
+ static char_type
+ to_char_type(int_type i) noexcept {
+ return static_cast<char_type>(i);
+ }
+
+ static constexpr int_type
+ eof() noexcept {
+ return static_cast<int_type>(EOF);
+ }
+};
+
+///////////////////
+// is_ functions //
+///////////////////
+
+// https://en.cppreference.com/w/cpp/types/conjunction
+template <class...>
+struct conjunction : std::true_type {};
+template <class B>
+struct conjunction<B> : B {};
+template <class B, class... Bn>
+struct conjunction<B, Bn...> : std::conditional<static_cast<bool>(B::value), conjunction<Bn...>, B>::type {};
+
+// https://en.cppreference.com/w/cpp/types/negation
+template <class B>
+struct negation : std::integral_constant<bool, !B::value> {};
+
+// Reimplementation of is_constructible and is_default_constructible, due to them being broken for
+// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367).
+// This causes compile errors in e.g. clang 3.5 or gcc 4.9.
+template <typename T>
+struct is_default_constructible : std::is_default_constructible<T> {};
+
+template <typename T1, typename T2>
+struct is_default_constructible<std::pair<T1, T2>>
+ : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
+
+template <typename T1, typename T2>
+struct is_default_constructible<const std::pair<T1, T2>>
+ : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
+
+template <typename... Ts>
+struct is_default_constructible<std::tuple<Ts...>> : conjunction<is_default_constructible<Ts>...> {};
+
+template <typename... Ts>
+struct is_default_constructible<const std::tuple<Ts...>> : conjunction<is_default_constructible<Ts>...> {};
+
+template <typename T, typename... Args>
+struct is_constructible : std::is_constructible<T, Args...> {};
+
+template <typename T1, typename T2>
+struct is_constructible<std::pair<T1, T2>> : is_default_constructible<std::pair<T1, T2>> {};
+
+template <typename T1, typename T2>
+struct is_constructible<const std::pair<T1, T2>> : is_default_constructible<const std::pair<T1, T2>> {};
+
+template <typename... Ts>
+struct is_constructible<std::tuple<Ts...>> : is_default_constructible<std::tuple<Ts...>> {};
+
+template <typename... Ts>
+struct is_constructible<const std::tuple<Ts...>> : is_default_constructible<const std::tuple<Ts...>> {};
+
+template <typename T, typename = void>
+struct is_iterator_traits : std::false_type {};
+
+template <typename T>
+struct is_iterator_traits<iterator_traits<T>> {
+ private:
+ using traits = iterator_traits<T>;
+
+ public:
+ static constexpr auto value =
+ is_detected<value_type_t, traits>::value && is_detected<difference_type_t, traits>::value &&
+ is_detected<pointer_t, traits>::value && is_detected<iterator_category_t, traits>::value &&
+ is_detected<reference_t, traits>::value;
+};
+
+template <typename T>
+struct is_range {
+ private:
+ using t_ref = typename std::add_lvalue_reference<T>::type;
+
+ using iterator = detected_t<result_of_begin, t_ref>;
+ using sentinel = detected_t<result_of_end, t_ref>;
+
+ // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator
+ // and https://en.cppreference.com/w/cpp/iterator/sentinel_for
+ // but reimplementing these would be too much work, as a lot of other concepts are used underneath
+ static constexpr auto is_iterator_begin = is_iterator_traits<iterator_traits<iterator>>::value;
+
+ public:
+ static constexpr bool value =
+ !std::is_same<iterator, nonesuch>::value && !std::is_same<sentinel, nonesuch>::value && is_iterator_begin;
+};
+
+template <typename R>
+using iterator_t = enable_if_t<is_range<R>::value, result_of_begin<decltype(std::declval<R&>())>>;
+
+template <typename T>
+using range_value_t = value_type_t<iterator_traits<iterator_t<T>>>;
+
+// The following implementation of is_complete_type is taken from
+// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/
+// and is written by Xiang Fan who agreed to using it in this library.
+
+template <typename T, typename = void>
+struct is_complete_type : std::false_type {};
+
+template <typename T>
+struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
+
+template <typename BasicJsonType, typename CompatibleObjectType, typename = void>
+struct is_compatible_object_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename CompatibleObjectType>
+struct is_compatible_object_type_impl<BasicJsonType,
+ CompatibleObjectType,
+ enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value &&
+ is_detected<key_type_t, CompatibleObjectType>::value>> {
+ using object_t = typename BasicJsonType::object_t;
+
+ // macOS's is_constructible does not play well with nonesuch...
+ static constexpr bool value =
+ is_constructible<typename object_t::key_type, typename CompatibleObjectType::key_type>::value &&
+ is_constructible<typename object_t::mapped_type, typename CompatibleObjectType::mapped_type>::value;
+};
+
+template <typename BasicJsonType, typename CompatibleObjectType>
+struct is_compatible_object_type : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
+
+template <typename BasicJsonType, typename ConstructibleObjectType, typename = void>
+struct is_constructible_object_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename ConstructibleObjectType>
+struct is_constructible_object_type_impl<BasicJsonType,
+ ConstructibleObjectType,
+ enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value &&
+ is_detected<key_type_t, ConstructibleObjectType>::value>> {
+ using object_t = typename BasicJsonType::object_t;
+
+ static constexpr bool value =
+ (is_default_constructible<ConstructibleObjectType>::value &&
+ (std::is_move_assignable<ConstructibleObjectType>::value ||
+ std::is_copy_assignable<ConstructibleObjectType>::value) &&
+ (is_constructible<typename ConstructibleObjectType::key_type, typename object_t::key_type>::value &&
+ std::is_same<typename object_t::mapped_type, typename ConstructibleObjectType::mapped_type>::value)) ||
+ (has_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type>::value ||
+ has_non_default_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type>::value);
+};
+
+template <typename BasicJsonType, typename ConstructibleObjectType>
+struct is_constructible_object_type : is_constructible_object_type_impl<BasicJsonType, ConstructibleObjectType> {};
+
+template <typename BasicJsonType, typename CompatibleStringType>
+struct is_compatible_string_type {
+ static constexpr auto value = is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
+};
+
+template <typename BasicJsonType, typename ConstructibleStringType>
+struct is_constructible_string_type {
+ // launder type through decltype() to fix compilation failure on ICPC
+#ifdef __INTEL_COMPILER
+ using laundered_type = decltype(std::declval<ConstructibleStringType>());
+#else
+ using laundered_type = ConstructibleStringType;
+#endif
+
+ static constexpr auto value = conjunction<
+ is_constructible<laundered_type, typename BasicJsonType::string_t>,
+ is_detected_exact<typename BasicJsonType::string_t::value_type, value_type_t, laundered_type>>::value;
+};
+
+template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
+struct is_compatible_array_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename CompatibleArrayType>
+struct is_compatible_array_type_impl<
+ BasicJsonType,
+ CompatibleArrayType,
+ enable_if_t<is_detected<iterator_t, CompatibleArrayType>::value &&
+ is_iterator_traits<iterator_traits<detected_t<iterator_t, CompatibleArrayType>>>::value &&
+ // special case for types like std::filesystem::path whose iterator's value_type are themselves
+ // c.f. https://github.com/nlohmann/json/pull/3073
+ !std::is_same<CompatibleArrayType, detected_t<range_value_t, CompatibleArrayType>>::value>> {
+ static constexpr bool value = is_constructible<BasicJsonType, range_value_t<CompatibleArrayType>>::value;
+};
+
+template <typename BasicJsonType, typename CompatibleArrayType>
+struct is_compatible_array_type : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
+
+template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
+struct is_constructible_array_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename ConstructibleArrayType>
+struct is_constructible_array_type_impl<
+ BasicJsonType,
+ ConstructibleArrayType,
+ enable_if_t<std::is_same<ConstructibleArrayType, typename BasicJsonType::value_type>::value>> : std::true_type {};
+
+template <typename BasicJsonType, typename ConstructibleArrayType>
+struct is_constructible_array_type_impl<
+ BasicJsonType,
+ ConstructibleArrayType,
+ enable_if_t<!std::is_same<ConstructibleArrayType, typename BasicJsonType::value_type>::value &&
+ !is_compatible_string_type<BasicJsonType, ConstructibleArrayType>::value &&
+ is_default_constructible<ConstructibleArrayType>::value &&
+ (std::is_move_assignable<ConstructibleArrayType>::value ||
+ std::is_copy_assignable<ConstructibleArrayType>::value) &&
+ is_detected<iterator_t, ConstructibleArrayType>::value &&
+ is_iterator_traits<iterator_traits<detected_t<iterator_t, ConstructibleArrayType>>>::value &&
+ is_detected<range_value_t, ConstructibleArrayType>::value &&
+ // special case for types like std::filesystem::path whose iterator's value_type are themselves
+ // c.f. https://github.com/nlohmann/json/pull/3073
+ !std::is_same<ConstructibleArrayType, detected_t<range_value_t, ConstructibleArrayType>>::value &&
+ is_complete_type<detected_t<range_value_t, ConstructibleArrayType>>::value>> {
+ using value_type = range_value_t<ConstructibleArrayType>;
+
+ static constexpr bool value = std::is_same<value_type, typename BasicJsonType::array_t::value_type>::value ||
+ has_from_json<BasicJsonType, value_type>::value ||
+ has_non_default_from_json<BasicJsonType, value_type>::value;
+};
+
+template <typename BasicJsonType, typename ConstructibleArrayType>
+struct is_constructible_array_type : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
+
+template <typename RealIntegerType, typename CompatibleNumberIntegerType, typename = void>
+struct is_compatible_integer_type_impl : std::false_type {};
+
+template <typename RealIntegerType, typename CompatibleNumberIntegerType>
+struct is_compatible_integer_type_impl<
+ RealIntegerType,
+ CompatibleNumberIntegerType,
+ enable_if_t<std::is_integral<RealIntegerType>::value && std::is_integral<CompatibleNumberIntegerType>::value &&
+ !std::is_same<bool, CompatibleNumberIntegerType>::value>> {
+ // is there an assert somewhere on overflows?
+ using RealLimits = std::numeric_limits<RealIntegerType>;
+ using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
+
+ static constexpr auto value = is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value &&
+ CompatibleLimits::is_integer && RealLimits::is_signed == CompatibleLimits::is_signed;
+};
+
+template <typename RealIntegerType, typename CompatibleNumberIntegerType>
+struct is_compatible_integer_type : is_compatible_integer_type_impl<RealIntegerType, CompatibleNumberIntegerType> {};
+
+template <typename BasicJsonType, typename CompatibleType, typename = void>
+struct is_compatible_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename CompatibleType>
+struct is_compatible_type_impl<BasicJsonType, CompatibleType, enable_if_t<is_complete_type<CompatibleType>::value>> {
+ static constexpr bool value = has_to_json<BasicJsonType, CompatibleType>::value;
+};
+
+template <typename BasicJsonType, typename CompatibleType>
+struct is_compatible_type : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
+
+template <typename T1, typename T2>
+struct is_constructible_tuple : std::false_type {};
+
+template <typename T1, typename... Args>
+struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<is_constructible<T1, Args>...> {};
+
+template <typename BasicJsonType, typename T>
+struct is_json_iterator_of : std::false_type {};
+
+template <typename BasicJsonType>
+struct is_json_iterator_of<BasicJsonType, typename BasicJsonType::iterator> : std::true_type {};
+
+template <typename BasicJsonType>
+struct is_json_iterator_of<BasicJsonType, typename BasicJsonType::const_iterator> : std::true_type {};
+
+// checks if a given type T is a template specialization of Primary
+template <template <typename...> class Primary, typename T>
+struct is_specialization_of : std::false_type {};
+
+template <template <typename...> class Primary, typename... Args>
+struct is_specialization_of<Primary, Primary<Args...>> : std::true_type {};
+
+template <typename T>
+using is_json_pointer = is_specialization_of<::nlohmann::json_pointer, uncvref_t<T>>;
+
+// checks if A and B are comparable using Compare functor
+template <typename Compare, typename A, typename B, typename = void>
+struct is_comparable : std::false_type {};
+
+template <typename Compare, typename A, typename B>
+struct is_comparable<Compare,
+ A,
+ B,
+ void_t<decltype(std::declval<Compare>()(std::declval<A>(), std::declval<B>())),
+ decltype(std::declval<Compare>()(std::declval<B>(), std::declval<A>()))>> : std::true_type {
+};
+
+template <typename T>
+using detect_is_transparent = typename T::is_transparent;
+
+// type trait to check if KeyType can be used as object key (without a BasicJsonType)
+// see is_usable_as_basic_json_key_type below
+template <typename Comparator,
+ typename ObjectKeyType,
+ typename KeyTypeCVRef,
+ bool RequireTransparentComparator = true,
+ bool ExcludeObjectKeyType = RequireTransparentComparator,
+ typename KeyType = uncvref_t<KeyTypeCVRef>>
+using is_usable_as_key_type =
+ typename std::conditional<is_comparable<Comparator, ObjectKeyType, KeyTypeCVRef>::value &&
+ !(ExcludeObjectKeyType && std::is_same<KeyType, ObjectKeyType>::value) &&
+ (!RequireTransparentComparator ||
+ is_detected<detect_is_transparent, Comparator>::value) &&
+ !is_json_pointer<KeyType>::value,
+ std::true_type,
+ std::false_type>::type;
+
+// type trait to check if KeyType can be used as object key
+// true if:
+// - KeyType is comparable with BasicJsonType::object_t::key_type
+// - if ExcludeObjectKeyType is true, KeyType is not BasicJsonType::object_t::key_type
+// - the comparator is transparent or RequireTransparentComparator is false
+// - KeyType is not a JSON iterator or json_pointer
+template <typename BasicJsonType,
+ typename KeyTypeCVRef,
+ bool RequireTransparentComparator = true,
+ bool ExcludeObjectKeyType = RequireTransparentComparator,
+ typename KeyType = uncvref_t<KeyTypeCVRef>>
+using is_usable_as_basic_json_key_type =
+ typename std::conditional<is_usable_as_key_type<typename BasicJsonType::object_comparator_t,
+ typename BasicJsonType::object_t::key_type,
+ KeyTypeCVRef,
+ RequireTransparentComparator,
+ ExcludeObjectKeyType>::value &&
+ !is_json_iterator_of<BasicJsonType, KeyType>::value,
+ std::true_type,
+ std::false_type>::type;
+
+template <typename ObjectType, typename KeyType>
+using detect_erase_with_key_type = decltype(std::declval<ObjectType&>().erase(std::declval<KeyType>()));
+
+// type trait to check if object_t has an erase() member functions accepting KeyType
+template <typename BasicJsonType, typename KeyType>
+using has_erase_with_key_type =
+ typename std::conditional<is_detected<detect_erase_with_key_type, typename BasicJsonType::object_t, KeyType>::value,
+ std::true_type,
+ std::false_type>::type;
+
+// a naive helper to check if a type is an ordered_map (exploits the fact that
+// ordered_map inherits capacity() from std::vector)
+template <typename T>
+struct is_ordered_map {
+ using one = char;
+
+ struct two {
+ char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+ };
+
+ template <typename C>
+ static one
+ test(decltype(&C::capacity));
+ template <typename C>
+ static two
+ test(...);
+
+ enum {
+ value = sizeof(test<T>(nullptr)) == sizeof(char)
+ }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+};
+
+// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324)
+template <typename T, typename U, enable_if_t<!std::is_same<T, U>::value, int> = 0>
+T
+conditional_static_cast(U value) {
+ return static_cast<T>(value);
+}
+
+template <typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0>
+T
+conditional_static_cast(U value) {
+ return value;
+}
+
+template <typename... Types>
+using all_integral = conjunction<std::is_integral<Types>...>;
+
+template <typename... Types>
+using all_signed = conjunction<std::is_signed<Types>...>;
+
+template <typename... Types>
+using all_unsigned = conjunction<std::is_unsigned<Types>...>;
+
+// there's a disjunction trait in another PR; replace when merged
+template <typename... Types>
+using same_sign = std::integral_constant<bool, all_signed<Types...>::value || all_unsigned<Types...>::value>;
+
+template <typename OfType, typename T>
+using never_out_of_range = std::integral_constant<bool,
+ (std::is_signed<OfType>::value && (sizeof(T) < sizeof(OfType))) ||
+ (same_sign<OfType, T>::value && sizeof(OfType) == sizeof(T))>;
+
+template <typename OfType,
+ typename T,
+ bool OfTypeSigned = std::is_signed<OfType>::value,
+ bool TSigned = std::is_signed<T>::value>
+struct value_in_range_of_impl2;
+
+template <typename OfType, typename T>
+struct value_in_range_of_impl2<OfType, T, false, false> {
+ static constexpr bool
+ test(T val) {
+ using CommonType = typename std::common_type<OfType, T>::type;
+ return static_cast<CommonType>(val) <= static_cast<CommonType>((std::numeric_limits<OfType>::max)());
+ }
+};
+
+template <typename OfType, typename T>
+struct value_in_range_of_impl2<OfType, T, true, false> {
+ static constexpr bool
+ test(T val) {
+ using CommonType = typename std::common_type<OfType, T>::type;
+ return static_cast<CommonType>(val) <= static_cast<CommonType>((std::numeric_limits<OfType>::max)());
+ }
+};
+
+template <typename OfType, typename T>
+struct value_in_range_of_impl2<OfType, T, false, true> {
+ static constexpr bool
+ test(T val) {
+ using CommonType = typename std::common_type<OfType, T>::type;
+ return val >= 0 &&
+ static_cast<CommonType>(val) <= static_cast<CommonType>((std::numeric_limits<OfType>::max)());
+ }
+};
+
+template <typename OfType, typename T>
+struct value_in_range_of_impl2<OfType, T, true, true> {
+ static constexpr bool
+ test(T val) {
+ using CommonType = typename std::common_type<OfType, T>::type;
+ return static_cast<CommonType>(val) >= static_cast<CommonType>((std::numeric_limits<OfType>::min)()) &&
+ static_cast<CommonType>(val) <= static_cast<CommonType>((std::numeric_limits<OfType>::max)());
+ }
+};
+
+template <typename OfType,
+ typename T,
+ bool NeverOutOfRange = never_out_of_range<OfType, T>::value,
+ typename = detail::enable_if_t<all_integral<OfType, T>::value>>
+struct value_in_range_of_impl1;
+
+template <typename OfType, typename T>
+struct value_in_range_of_impl1<OfType, T, false> {
+ static constexpr bool
+ test(T val) {
+ return value_in_range_of_impl2<OfType, T>::test(val);
+ }
+};
+
+template <typename OfType, typename T>
+struct value_in_range_of_impl1<OfType, T, true> {
+ static constexpr bool
+ test(T /*val*/) {
+ return true;
+ }
+};
+
+template <typename OfType, typename T>
+inline constexpr bool
+value_in_range_of(T val) {
+ return value_in_range_of_impl1<OfType, T>::test(val);
+}
+
+template <bool Value>
+using bool_constant = std::integral_constant<bool, Value>;
+
+///////////////////////////////////////////////////////////////////////////////
+// is_c_string
+///////////////////////////////////////////////////////////////////////////////
+
+namespace impl {
+
+template <typename T>
+inline constexpr bool
+is_c_string() {
+ using TUnExt = typename std::remove_extent<T>::type;
+ using TUnCVExt = typename std::remove_cv<TUnExt>::type;
+ using TUnPtr = typename std::remove_pointer<T>::type;
+ using TUnCVPtr = typename std::remove_cv<TUnPtr>::type;
+ return (std::is_array<T>::value && std::is_same<TUnCVExt, char>::value) ||
+ (std::is_pointer<T>::value && std::is_same<TUnCVPtr, char>::value);
+}
+
+} // namespace impl
+
+// checks whether T is a [cv] char */[cv] char[] C string
+template <typename T>
+struct is_c_string : bool_constant<impl::is_c_string<T>()> {};
+
+template <typename T>
+using is_c_string_uncvref = is_c_string<uncvref_t<T>>;
+
+///////////////////////////////////////////////////////////////////////////////
+// is_transparent
+///////////////////////////////////////////////////////////////////////////////
+
+namespace impl {
+
+template <typename T>
+inline constexpr bool
+is_transparent() {
+ return is_detected<detect_is_transparent, T>::value;
+}
+
+} // namespace impl
+
+// checks whether T has a member named is_transparent
+template <typename T>
+struct is_transparent : bool_constant<impl::is_transparent<T>()> {};
+
+///////////////////////////////////////////////////////////////////////////////
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/string_concat.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstring> // strlen
+#include <string> // string
+#include <utility> // forward
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/detected.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+inline std::size_t
+concat_length() {
+ return 0;
+}
+
+template <typename... Args>
+inline std::size_t
+concat_length(const char* cstr, const Args&... rest);
+
+template <typename StringType, typename... Args>
+inline std::size_t
+concat_length(const StringType& str, const Args&... rest);
+
+template <typename... Args>
+inline std::size_t
+concat_length(const char /*c*/, const Args&... rest) {
+ return 1 + concat_length(rest...);
+}
+
+template <typename... Args>
+inline std::size_t
+concat_length(const char* cstr, const Args&... rest) {
+ // cppcheck-suppress ignoredReturnValue
+ return ::strlen(cstr) + concat_length(rest...);
+}
+
+template <typename StringType, typename... Args>
+inline std::size_t
+concat_length(const StringType& str, const Args&... rest) {
+ return str.size() + concat_length(rest...);
+}
+
+template <typename OutStringType>
+inline void
+concat_into(OutStringType& /*out*/) {}
+
+template <typename StringType, typename Arg>
+using string_can_append = decltype(std::declval<StringType&>().append(std::declval<Arg&&>()));
+
+template <typename StringType, typename Arg>
+using detect_string_can_append = is_detected<string_can_append, StringType, Arg>;
+
+template <typename StringType, typename Arg>
+using string_can_append_op = decltype(std::declval<StringType&>() += std::declval<Arg&&>());
+
+template <typename StringType, typename Arg>
+using detect_string_can_append_op = is_detected<string_can_append_op, StringType, Arg>;
+
+template <typename StringType, typename Arg>
+using string_can_append_iter =
+ decltype(std::declval<StringType&>().append(std::declval<const Arg&>().begin(), std::declval<const Arg&>().end()));
+
+template <typename StringType, typename Arg>
+using detect_string_can_append_iter = is_detected<string_can_append_iter, StringType, Arg>;
+
+template <typename StringType, typename Arg>
+using string_can_append_data =
+ decltype(std::declval<StringType&>().append(std::declval<const Arg&>().data(), std::declval<const Arg&>().size()));
+
+template <typename StringType, typename Arg>
+using detect_string_can_append_data = is_detected<string_can_append_data, StringType, Arg>;
+
+template <typename OutStringType,
+ typename Arg,
+ typename... Args,
+ enable_if_t<!detect_string_can_append<OutStringType, Arg>::value &&
+ detect_string_can_append_op<OutStringType, Arg>::value,
+ int> = 0>
+inline void
+concat_into(OutStringType& out, Arg&& arg, Args&&... rest);
+
+template <typename OutStringType,
+ typename Arg,
+ typename... Args,
+ enable_if_t<!detect_string_can_append<OutStringType, Arg>::value &&
+ !detect_string_can_append_op<OutStringType, Arg>::value &&
+ detect_string_can_append_iter<OutStringType, Arg>::value,
+ int> = 0>
+inline void
+concat_into(OutStringType& out, const Arg& arg, Args&&... rest);
+
+template <typename OutStringType,
+ typename Arg,
+ typename... Args,
+ enable_if_t<!detect_string_can_append<OutStringType, Arg>::value &&
+ !detect_string_can_append_op<OutStringType, Arg>::value &&
+ !detect_string_can_append_iter<OutStringType, Arg>::value &&
+ detect_string_can_append_data<OutStringType, Arg>::value,
+ int> = 0>
+inline void
+concat_into(OutStringType& out, const Arg& arg, Args&&... rest);
+
+template <typename OutStringType,
+ typename Arg,
+ typename... Args,
+ enable_if_t<detect_string_can_append<OutStringType, Arg>::value, int> = 0>
+inline void
+concat_into(OutStringType& out, Arg&& arg, Args&&... rest) {
+ out.append(std::forward<Arg>(arg));
+ concat_into(out, std::forward<Args>(rest)...);
+}
+
+template <typename OutStringType,
+ typename Arg,
+ typename... Args,
+ enable_if_t<!detect_string_can_append<OutStringType, Arg>::value &&
+ detect_string_can_append_op<OutStringType, Arg>::value,
+ int>>
+inline void
+concat_into(OutStringType& out, Arg&& arg, Args&&... rest) {
+ out += std::forward<Arg>(arg);
+ concat_into(out, std::forward<Args>(rest)...);
+}
+
+template <typename OutStringType,
+ typename Arg,
+ typename... Args,
+ enable_if_t<!detect_string_can_append<OutStringType, Arg>::value &&
+ !detect_string_can_append_op<OutStringType, Arg>::value &&
+ detect_string_can_append_iter<OutStringType, Arg>::value,
+ int>>
+inline void
+concat_into(OutStringType& out, const Arg& arg, Args&&... rest) {
+ out.append(arg.begin(), arg.end());
+ concat_into(out, std::forward<Args>(rest)...);
+}
+
+template <typename OutStringType,
+ typename Arg,
+ typename... Args,
+ enable_if_t<!detect_string_can_append<OutStringType, Arg>::value &&
+ !detect_string_can_append_op<OutStringType, Arg>::value &&
+ !detect_string_can_append_iter<OutStringType, Arg>::value &&
+ detect_string_can_append_data<OutStringType, Arg>::value,
+ int>>
+inline void
+concat_into(OutStringType& out, const Arg& arg, Args&&... rest) {
+ out.append(arg.data(), arg.size());
+ concat_into(out, std::forward<Args>(rest)...);
+}
+
+template <typename OutStringType = std::string, typename... Args>
+inline OutStringType
+concat(Args&&... args) {
+ OutStringType str;
+ str.reserve(concat_length(args...));
+ concat_into(str, std::forward<Args>(args)...);
+ return str;
+}
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+////////////////
+// exceptions //
+////////////////
+
+/// @brief general exception of the @ref basic_json class
+/// @sa https://json.nlohmann.me/api/basic_json/exception/
+class exception : public std::exception {
+ public:
+ /// returns the explanatory string
+ const char*
+ what() const noexcept override {
+ return m.what();
+ }
+
+ /// the id of the exception
+ const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
+
+ protected:
+ JSON_HEDLEY_NON_NULL(3)
+ exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing)
+
+ static std::string
+ name(const std::string& ename, int id_) {
+ return concat("[json.exception.", ename, '.', std::to_string(id_), "] ");
+ }
+
+ static std::string
+ diagnostics(std::nullptr_t /*leaf_element*/) {
+ return "";
+ }
+
+ template <typename BasicJsonType>
+ static std::string
+ diagnostics(const BasicJsonType* leaf_element) {
+#if JSON_DIAGNOSTICS
+ std::vector<std::string> tokens;
+ for (const auto* current = leaf_element; current != nullptr && current->m_parent != nullptr;
+ current = current->m_parent) {
+ switch (current->m_parent->type()) {
+ case value_t::array: {
+ for (std::size_t i = 0; i < current->m_parent->m_data.m_value.array->size(); ++i) {
+ if (&current->m_parent->m_data.m_value.array->operator[](i) == current) {
+ tokens.emplace_back(std::to_string(i));
+ break;
+ }
+ }
+ break;
+ }
+
+ case value_t::object: {
+ for (const auto& element : *current->m_parent->m_data.m_value.object) {
+ if (&element.second == current) {
+ tokens.emplace_back(element.first.c_str());
+ break;
+ }
+ }
+ break;
+ }
+
+ case value_t::null: // LCOV_EXCL_LINE
+ case value_t::string: // LCOV_EXCL_LINE
+ case value_t::boolean: // LCOV_EXCL_LINE
+ case value_t::number_integer: // LCOV_EXCL_LINE
+ case value_t::number_unsigned: // LCOV_EXCL_LINE
+ case value_t::number_float: // LCOV_EXCL_LINE
+ case value_t::binary: // LCOV_EXCL_LINE
+ case value_t::discarded: // LCOV_EXCL_LINE
+ default: // LCOV_EXCL_LINE
+ break; // LCOV_EXCL_LINE
+ }
+ }
+
+ if (tokens.empty()) {
+ return "";
+ }
+
+ auto str = std::accumulate(
+ tokens.rbegin(), tokens.rend(), std::string{}, [](const std::string& a, const std::string& b) {
+ return concat(a, '/', detail::escape(b));
+ });
+ return concat('(', str, ") ");
+#else
+ static_cast<void>(leaf_element);
+ return "";
+#endif
+ }
+
+ private:
+ /// an exception object as storage for error messages
+ std::runtime_error m;
+};
+
+/// @brief exception indicating a parse error
+/// @sa https://json.nlohmann.me/api/basic_json/parse_error/
+class parse_error : public exception {
+ public:
+ /*!
+ @brief create a parse error exception
+ @param[in] id_ the id of the exception
+ @param[in] pos the position where the error occurred (or with
+ chars_read_total=0 if the position cannot be
+ determined)
+ @param[in] what_arg the explanatory string
+ @return parse_error object
+ */
+ template <typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0>
+ static parse_error
+ create(int id_, const position_t& pos, const std::string& what_arg, BasicJsonContext context) {
+ const std::string w = concat(exception::name("parse_error", id_),
+ "parse error",
+ position_string(pos),
+ ": ",
+ exception::diagnostics(context),
+ what_arg);
+ return {id_, pos.chars_read_total, w.c_str()};
+ }
+
+ template <typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0>
+ static parse_error
+ create(int id_, std::size_t byte_, const std::string& what_arg, BasicJsonContext context) {
+ const std::string w = concat(exception::name("parse_error", id_),
+ "parse error",
+ (byte_ != 0 ? (concat(" at byte ", std::to_string(byte_))) : ""),
+ ": ",
+ exception::diagnostics(context),
+ what_arg);
+ return {id_, byte_, w.c_str()};
+ }
+
+ /*!
+ @brief byte index of the parse error
+
+ The byte index of the last read character in the input file.
+
+ @note For an input with n bytes, 1 is the index of the first character and
+ n+1 is the index of the terminating null byte or the end of file.
+ This also holds true when reading a byte vector (CBOR or MessagePack).
+ */
+ const std::size_t byte;
+
+ private:
+ parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {}
+
+ static std::string
+ position_string(const position_t& pos) {
+ return concat(
+ " at line ", std::to_string(pos.lines_read + 1), ", column ", std::to_string(pos.chars_read_current_line));
+ }
+};
+
+/// @brief exception indicating errors with iterators
+/// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/
+class invalid_iterator : public exception {
+ public:
+ template <typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0>
+ static invalid_iterator
+ create(int id_, const std::string& what_arg, BasicJsonContext context) {
+ const std::string w =
+ concat(exception::name("invalid_iterator", id_), exception::diagnostics(context), what_arg);
+ return {id_, w.c_str()};
+ }
+
+ private:
+ JSON_HEDLEY_NON_NULL(3)
+ invalid_iterator(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+
+/// @brief exception indicating executing a member function with a wrong type
+/// @sa https://json.nlohmann.me/api/basic_json/type_error/
+class type_error : public exception {
+ public:
+ template <typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0>
+ static type_error
+ create(int id_, const std::string& what_arg, BasicJsonContext context) {
+ const std::string w = concat(exception::name("type_error", id_), exception::diagnostics(context), what_arg);
+ return {id_, w.c_str()};
+ }
+
+ private:
+ JSON_HEDLEY_NON_NULL(3)
+ type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+
+/// @brief exception indicating access out of the defined range
+/// @sa https://json.nlohmann.me/api/basic_json/out_of_range/
+class out_of_range : public exception {
+ public:
+ template <typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0>
+ static out_of_range
+ create(int id_, const std::string& what_arg, BasicJsonContext context) {
+ const std::string w = concat(exception::name("out_of_range", id_), exception::diagnostics(context), what_arg);
+ return {id_, w.c_str()};
+ }
+
+ private:
+ JSON_HEDLEY_NON_NULL(3)
+ out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+
+/// @brief exception indicating other library errors
+/// @sa https://json.nlohmann.me/api/basic_json/other_error/
+class other_error : public exception {
+ public:
+ template <typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0>
+ static other_error
+ create(int id_, const std::string& what_arg, BasicJsonContext context) {
+ const std::string w = concat(exception::name("other_error", id_), exception::diagnostics(context), what_arg);
+ return {id_, w.c_str()};
+ }
+
+ private:
+ JSON_HEDLEY_NON_NULL(3)
+ other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/identity_tag.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+// dispatching helper struct
+template <class T>
+struct identity_tag {};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/meta/std_fs.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+#if JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#include <experimental/filesystem>
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+namespace std_fs = std::experimental::filesystem;
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+#elif JSON_HAS_FILESYSTEM
+#include <filesystem>
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+namespace std_fs = std::filesystem;
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+#endif
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/string_concat.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+template <typename BasicJsonType>
+inline void
+from_json(const BasicJsonType& j, typename std::nullptr_t& n) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_null())) {
+ JSON_THROW(type_error::create(302, concat("type must be null, but is ", j.type_name()), &j));
+ }
+ n = nullptr;
+}
+
+// overloads for basic_json template parameters
+template <typename BasicJsonType,
+ typename ArithmeticType,
+ enable_if_t<std::is_arithmetic<ArithmeticType>::value &&
+ !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
+ int> = 0>
+void
+get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) {
+ switch (static_cast<value_t>(j)) {
+ case value_t::number_unsigned: {
+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
+ break;
+ }
+ case value_t::number_integer: {
+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
+ break;
+ }
+ case value_t::number_float: {
+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
+ break;
+ }
+
+ case value_t::null:
+ case value_t::object:
+ case value_t::array:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::binary:
+ case value_t::discarded:
+ default:
+ JSON_THROW(type_error::create(302, concat("type must be number, but is ", j.type_name()), &j));
+ }
+}
+
+template <typename BasicJsonType>
+inline void
+from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) {
+ JSON_THROW(type_error::create(302, concat("type must be boolean, but is ", j.type_name()), &j));
+ }
+ b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
+}
+
+template <typename BasicJsonType>
+inline void
+from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_string())) {
+ JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j));
+ }
+ s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
+}
+
+template <typename BasicJsonType,
+ typename StringType,
+ enable_if_t<
+ std::is_assignable<StringType&, const typename BasicJsonType::string_t>::value &&
+ is_detected_exact<typename BasicJsonType::string_t::value_type, value_type_t, StringType>::value &&
+ !std::is_same<typename BasicJsonType::string_t, StringType>::value && !is_json_ref<StringType>::value,
+ int> = 0>
+inline void
+from_json(const BasicJsonType& j, StringType& s) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_string())) {
+ JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j));
+ }
+
+ s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
+}
+
+template <typename BasicJsonType>
+inline void
+from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) {
+ get_arithmetic_value(j, val);
+}
+
+template <typename BasicJsonType>
+inline void
+from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) {
+ get_arithmetic_value(j, val);
+}
+
+template <typename BasicJsonType>
+inline void
+from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) {
+ get_arithmetic_value(j, val);
+}
+
+#if !JSON_DISABLE_ENUM_SERIALIZATION
+template <typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0>
+inline void
+from_json(const BasicJsonType& j, EnumType& e) {
+ typename std::underlying_type<EnumType>::type val;
+ get_arithmetic_value(j, val);
+ e = static_cast<EnumType>(val);
+}
+#endif // JSON_DISABLE_ENUM_SERIALIZATION
+
+// forward_list doesn't have an insert method
+template <typename BasicJsonType,
+ typename T,
+ typename Allocator,
+ enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
+inline void
+from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_array())) {
+ JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
+ }
+ l.clear();
+ std::transform(
+ j.rbegin(), j.rend(), std::front_inserter(l), [](const BasicJsonType& i) { return i.template get<T>(); });
+}
+
+// valarray doesn't have an insert method
+template <typename BasicJsonType, typename T, enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
+inline void
+from_json(const BasicJsonType& j, std::valarray<T>& l) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_array())) {
+ JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
+ }
+ l.resize(j.size());
+ std::transform(j.begin(), j.end(), std::begin(l), [](const BasicJsonType& elem) { return elem.template get<T>(); });
+}
+
+template <typename BasicJsonType, typename T, std::size_t N>
+auto
+from_json(const BasicJsonType& j,
+ T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+ -> decltype(j.template get<T>(), void()) {
+ for (std::size_t i = 0; i < N; ++i) {
+ arr[i] = j.at(i).template get<T>();
+ }
+}
+
+template <typename BasicJsonType>
+inline void
+from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) {
+ arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
+}
+
+template <typename BasicJsonType, typename T, std::size_t N>
+auto
+from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
+ -> decltype(j.template get<T>(), void()) {
+ for (std::size_t i = 0; i < N; ++i) {
+ arr[i] = j.at(i).template get<T>();
+ }
+}
+
+template <typename BasicJsonType,
+ typename ConstructibleArrayType,
+ enable_if_t<std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value, int> = 0>
+auto
+from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
+ -> decltype(arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
+ j.template get<typename ConstructibleArrayType::value_type>(),
+ void()) {
+ using std::end;
+
+ ConstructibleArrayType ret;
+ ret.reserve(j.size());
+ std::transform(j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType& i) {
+ // get<BasicJsonType>() returns *this, this won't call a from_json
+ // method when value_type is BasicJsonType
+ return i.template get<typename ConstructibleArrayType::value_type>();
+ });
+ arr = std::move(ret);
+}
+
+template <typename BasicJsonType,
+ typename ConstructibleArrayType,
+ enable_if_t<std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value, int> = 0>
+inline void
+from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<0> /*unused*/) {
+ using std::end;
+
+ ConstructibleArrayType ret;
+ std::transform(j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType& i) {
+ // get<BasicJsonType>() returns *this, this won't call a from_json
+ // method when value_type is BasicJsonType
+ return i.template get<typename ConstructibleArrayType::value_type>();
+ });
+ arr = std::move(ret);
+}
+
+template <typename BasicJsonType,
+ typename ConstructibleArrayType,
+ enable_if_t<is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value &&
+ !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value &&
+ !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value &&
+ !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value &&
+ !is_basic_json<ConstructibleArrayType>::value,
+ int> = 0>
+auto
+from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
+ -> decltype(from_json_array_impl(j, arr, priority_tag<3>{}),
+ j.template get<typename ConstructibleArrayType::value_type>(),
+ void()) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_array())) {
+ JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
+ }
+
+ from_json_array_impl(j, arr, priority_tag<3>{});
+}
+
+template <typename BasicJsonType, typename T, std::size_t... Idx>
+std::array<T, sizeof...(Idx)>
+from_json_inplace_array_impl(BasicJsonType&& j,
+ identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/,
+ index_sequence<Idx...> /*unused*/) {
+ return {{std::forward<BasicJsonType>(j).at(Idx).template get<T>()...}};
+}
+
+template <typename BasicJsonType, typename T, std::size_t N>
+auto
+from_json(BasicJsonType&& j, identity_tag<std::array<T, N>> tag)
+ -> decltype(from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N>{})) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_array())) {
+ JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
+ }
+
+ return from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N>{});
+}
+
+template <typename BasicJsonType>
+inline void
+from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) {
+ JSON_THROW(type_error::create(302, concat("type must be binary, but is ", j.type_name()), &j));
+ }
+
+ bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
+}
+
+template <typename BasicJsonType,
+ typename ConstructibleObjectType,
+ enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
+inline void
+from_json(const BasicJsonType& j, ConstructibleObjectType& obj) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_object())) {
+ JSON_THROW(type_error::create(302, concat("type must be object, but is ", j.type_name()), &j));
+ }
+
+ ConstructibleObjectType ret;
+ const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
+ using value_type = typename ConstructibleObjectType::value_type;
+ std::transform(inner_object->begin(),
+ inner_object->end(),
+ std::inserter(ret, ret.begin()),
+ [](typename BasicJsonType::object_t::value_type const& p) {
+ return value_type(p.first,
+ p.second.template get<typename ConstructibleObjectType::mapped_type>());
+ });
+ obj = std::move(ret);
+}
+
+// overload for arithmetic types, not chosen for basic_json template arguments
+// (BooleanType, etc..); note: Is it really necessary to provide explicit
+// overloads for boolean_t etc. in case of a custom BooleanType which is not
+// an arithmetic type?
+template <typename BasicJsonType,
+ typename ArithmeticType,
+ enable_if_t<std::is_arithmetic<ArithmeticType>::value &&
+ !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value &&
+ !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value &&
+ !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value &&
+ !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
+ int> = 0>
+inline void
+from_json(const BasicJsonType& j, ArithmeticType& val) {
+ switch (static_cast<value_t>(j)) {
+ case value_t::number_unsigned: {
+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
+ break;
+ }
+ case value_t::number_integer: {
+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
+ break;
+ }
+ case value_t::number_float: {
+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
+ break;
+ }
+ case value_t::boolean: {
+ val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
+ break;
+ }
+
+ case value_t::null:
+ case value_t::object:
+ case value_t::array:
+ case value_t::string:
+ case value_t::binary:
+ case value_t::discarded:
+ default:
+ JSON_THROW(type_error::create(302, concat("type must be number, but is ", j.type_name()), &j));
+ }
+}
+
+template <typename BasicJsonType, typename... Args, std::size_t... Idx>
+std::tuple<Args...>
+from_json_tuple_impl_base(BasicJsonType&& j, index_sequence<Idx...> /*unused*/) {
+ return std::make_tuple(std::forward<BasicJsonType>(j).at(Idx).template get<Args>()...);
+}
+
+template <typename BasicJsonType, class A1, class A2>
+std::pair<A1, A2>
+from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/) {
+ return {std::forward<BasicJsonType>(j).at(0).template get<A1>(),
+ std::forward<BasicJsonType>(j).at(1).template get<A2>()};
+}
+
+template <typename BasicJsonType, typename A1, typename A2>
+inline void
+from_json_tuple_impl(BasicJsonType&& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/) {
+ p = from_json_tuple_impl(std::forward<BasicJsonType>(j), identity_tag<std::pair<A1, A2>>{}, priority_tag<0>{});
+}
+
+template <typename BasicJsonType, typename... Args>
+std::tuple<Args...>
+from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/) {
+ return from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j),
+ index_sequence_for<Args...>{});
+}
+
+template <typename BasicJsonType, typename... Args>
+inline void
+from_json_tuple_impl(BasicJsonType&& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/) {
+ t = from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j),
+ index_sequence_for<Args...>{});
+}
+
+template <typename BasicJsonType, typename TupleRelated>
+auto
+from_json(BasicJsonType&& j, TupleRelated&& t) -> decltype(from_json_tuple_impl(std::forward<BasicJsonType>(j),
+ std::forward<TupleRelated>(t),
+ priority_tag<3>{})) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_array())) {
+ JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
+ }
+
+ return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3>{});
+}
+
+template <typename BasicJsonType,
+ typename Key,
+ typename Value,
+ typename Compare,
+ typename Allocator,
+ typename = enable_if_t<!std::is_constructible<typename BasicJsonType::string_t, Key>::value>>
+inline void
+from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_array())) {
+ JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
+ }
+ m.clear();
+ for (const auto& p : j) {
+ if (JSON_HEDLEY_UNLIKELY(!p.is_array())) {
+ JSON_THROW(type_error::create(302, concat("type must be array, but is ", p.type_name()), &j));
+ }
+ m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
+ }
+}
+
+template <typename BasicJsonType,
+ typename Key,
+ typename Value,
+ typename Hash,
+ typename KeyEqual,
+ typename Allocator,
+ typename = enable_if_t<!std::is_constructible<typename BasicJsonType::string_t, Key>::value>>
+inline void
+from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_array())) {
+ JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
+ }
+ m.clear();
+ for (const auto& p : j) {
+ if (JSON_HEDLEY_UNLIKELY(!p.is_array())) {
+ JSON_THROW(type_error::create(302, concat("type must be array, but is ", p.type_name()), &j));
+ }
+ m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
+ }
+}
+
+#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
+template <typename BasicJsonType>
+inline void
+from_json(const BasicJsonType& j, std_fs::path& p) {
+ if (JSON_HEDLEY_UNLIKELY(!j.is_string())) {
+ JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j));
+ }
+ p = *j.template get_ptr<const typename BasicJsonType::string_t*>();
+}
+#endif
+
+struct from_json_fn {
+ template <typename BasicJsonType, typename T>
+ auto
+ operator()(const BasicJsonType& j, T&& val) const noexcept(noexcept(from_json(j, std::forward<T>(val))))
+ -> decltype(from_json(j, std::forward<T>(val))) {
+ return from_json(j, std::forward<T>(val));
+ }
+};
+
+} // namespace detail
+
+#ifndef JSON_HAS_CPP_17
+/// namespace to hold default `from_json` function
+/// to see why this is required:
+/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
+namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
+{
+#endif
+JSON_INLINE_VARIABLE constexpr const auto& from_json = // NOLINT(misc-definitions-in-headers)
+ detail::static_const<detail::from_json_fn>::value;
+#ifndef JSON_HAS_CPP_17
+} // namespace
+#endif
+
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/conversions/to_json.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <algorithm> // copy
+#include <iterator> // begin, end
+#include <string> // string
+#include <tuple> // tuple, get
+#include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
+#include <utility> // move, forward, declval, pair
+#include <valarray> // valarray
+#include <vector> // vector
+
+// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstddef> // size_t
+#include <iterator> // input_iterator_tag
+#include <string> // string, to_string
+#include <tuple> // tuple_size, get, tuple_element
+#include <utility> // move
+
+#if JSON_HAS_RANGES
+#include <ranges> // enable_borrowed_range
+#endif
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+template <typename string_type>
+void
+int_to_string(string_type& target, std::size_t value) {
+ // For ADL
+ using std::to_string;
+ target = to_string(value);
+}
+template <typename IteratorType>
+class iteration_proxy_value {
+ public:
+ using difference_type = std::ptrdiff_t;
+ using value_type = iteration_proxy_value;
+ using pointer = value_type*;
+ using reference = value_type&;
+ using iterator_category = std::input_iterator_tag;
+ using string_type = typename std::remove_cv<
+ typename std::remove_reference<decltype(std::declval<IteratorType>().key())>::type>::type;
+
+ private:
+ /// the iterator
+ IteratorType anchor{};
+ /// an index for arrays (used to create key names)
+ std::size_t array_index = 0;
+ /// last stringified array index
+ mutable std::size_t array_index_last = 0;
+ /// a string representation of the array index
+ mutable string_type array_index_str = "0";
+ /// an empty string (to return a reference for primitive values)
+ string_type empty_str{};
+
+ public:
+ explicit iteration_proxy_value() = default;
+ explicit iteration_proxy_value(IteratorType it, std::size_t array_index_ = 0) noexcept(
+ std::is_nothrow_move_constructible<IteratorType>::value &&
+ std::is_nothrow_default_constructible<string_type>::value)
+ : anchor(std::move(it)), array_index(array_index_) {}
+
+ iteration_proxy_value(iteration_proxy_value const&) = default;
+ iteration_proxy_value&
+ operator=(iteration_proxy_value const&) = default;
+ // older GCCs are a bit fussy and require explicit noexcept specifiers on defaulted functions
+ iteration_proxy_value(iteration_proxy_value&&) noexcept(std::is_nothrow_move_constructible<IteratorType>::value &&
+ std::is_nothrow_move_constructible<string_type>::value) =
+ default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations)
+ iteration_proxy_value&
+ operator=(iteration_proxy_value&&) noexcept(std::is_nothrow_move_assignable<IteratorType>::value &&
+ std::is_nothrow_move_assignable<string_type>::value) =
+ default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations)
+ ~iteration_proxy_value() = default;
+
+ /// dereference operator (needed for range-based for)
+ const iteration_proxy_value&
+ operator*() const {
+ return *this;
+ }
+
+ /// increment operator (needed for range-based for)
+ iteration_proxy_value&
+ operator++() {
+ ++anchor;
+ ++array_index;
+
+ return *this;
+ }
+
+ iteration_proxy_value
+ operator++(int) & // NOLINT(cert-dcl21-cpp)
+ {
+ auto tmp = iteration_proxy_value(anchor, array_index);
+ ++anchor;
+ ++array_index;
+ return tmp;
+ }
+
+ /// equality operator (needed for InputIterator)
+ bool
+ operator==(const iteration_proxy_value& o) const {
+ return anchor == o.anchor;
+ }
+
+ /// inequality operator (needed for range-based for)
+ bool
+ operator!=(const iteration_proxy_value& o) const {
+ return anchor != o.anchor;
+ }
+
+ /// return key of the iterator
+ const string_type&
+ key() const {
+ JSON_ASSERT(anchor.m_object != nullptr);
+
+ switch (anchor.m_object->type()) {
+ // use integer array index as key
+ case value_t::array: {
+ if (array_index != array_index_last) {
+ int_to_string(array_index_str, array_index);
+ array_index_last = array_index;
+ }
+ return array_index_str;
+ }
+
+ // use key from the object
+ case value_t::object:
+ return anchor.key();
+
+ // use an empty key for all primitive types
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default:
+ return empty_str;
+ }
+ }
+
+ /// return value of the iterator
+ typename IteratorType::reference
+ value() const {
+ return anchor.value();
+ }
+};
+
+/// proxy class for the items() function
+template <typename IteratorType>
+class iteration_proxy {
+ private:
+ /// the container to iterate
+ typename IteratorType::pointer container = nullptr;
+
+ public:
+ explicit iteration_proxy() = default;
+
+ /// construct iteration proxy from a container
+ explicit iteration_proxy(typename IteratorType::reference cont) noexcept : container(&cont) {}
+
+ iteration_proxy(iteration_proxy const&) = default;
+ iteration_proxy&
+ operator=(iteration_proxy const&) = default;
+ iteration_proxy(iteration_proxy&&) noexcept = default;
+ iteration_proxy&
+ operator=(iteration_proxy&&) noexcept = default;
+ ~iteration_proxy() = default;
+
+ /// return iterator begin (needed for range-based for)
+ iteration_proxy_value<IteratorType>
+ begin() const noexcept {
+ return iteration_proxy_value<IteratorType>(container->begin());
+ }
+
+ /// return iterator end (needed for range-based for)
+ iteration_proxy_value<IteratorType>
+ end() const noexcept {
+ return iteration_proxy_value<IteratorType>(container->end());
+ }
+};
+
+// Structured Bindings Support
+// For further reference see https://blog.tartanllama.xyz/structured-bindings/
+// And see https://github.com/nlohmann/json/pull/1391
+template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
+auto
+get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key()) {
+ return i.key();
+}
+// Structured Bindings Support
+// For further reference see https://blog.tartanllama.xyz/structured-bindings/
+// And see https://github.com/nlohmann/json/pull/1391
+template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
+auto
+get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value()) {
+ return i.value();
+}
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// The Addition to the STD Namespace is required to add
+// Structured Bindings Support to the iteration_proxy_value class
+// For further reference see https://blog.tartanllama.xyz/structured-bindings/
+// And see https://github.com/nlohmann/json/pull/1391
+namespace std {
+
+#if defined(__clang__)
+// Fix: https://github.com/nlohmann/json/issues/1401
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wmismatched-tags"
+#endif
+template <typename IteratorType>
+class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>> // NOLINT(cert-dcl58-cpp)
+ : public std::integral_constant<std::size_t, 2> {};
+
+template <std::size_t N, typename IteratorType>
+class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType>> // NOLINT(cert-dcl58-cpp)
+{
+ public:
+ using type = decltype(get<N>(std::declval<::nlohmann::detail::iteration_proxy_value<IteratorType>>()));
+};
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+} // namespace std
+
+#if JSON_HAS_RANGES
+template <typename IteratorType>
+inline constexpr bool ::std::ranges::enable_borrowed_range<::nlohmann::detail::iteration_proxy<IteratorType>> = true;
+#endif
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/std_fs.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+//////////////////
+// constructors //
+//////////////////
+
+/*
+ * Note all external_constructor<>::construct functions need to call
+ * j.m_data.m_value.destroy(j.m_data.m_type) to avoid a memory leak in case j contains an
+ * allocated value (e.g., a string). See bug issue
+ * https://github.com/nlohmann/json/issues/2865 for more information.
+ */
+
+template <value_t>
+struct external_constructor;
+
+template <>
+struct external_constructor<value_t::boolean> {
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::boolean;
+ j.m_data.m_value = b;
+ j.assert_invariant();
+ }
+};
+
+template <>
+struct external_constructor<value_t::string> {
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::string;
+ j.m_data.m_value = s;
+ j.assert_invariant();
+ }
+
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::string;
+ j.m_data.m_value = std::move(s);
+ j.assert_invariant();
+ }
+
+ template <typename BasicJsonType,
+ typename CompatibleStringType,
+ enable_if_t<!std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value, int> = 0>
+ static void
+ construct(BasicJsonType& j, const CompatibleStringType& str) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::string;
+ j.m_data.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
+ j.assert_invariant();
+ }
+};
+
+template <>
+struct external_constructor<value_t::binary> {
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::binary;
+ j.m_data.m_value = typename BasicJsonType::binary_t(b);
+ j.assert_invariant();
+ }
+
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::binary;
+ j.m_data.m_value = typename BasicJsonType::binary_t(std::move(b));
+ j.assert_invariant();
+ }
+};
+
+template <>
+struct external_constructor<value_t::number_float> {
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::number_float;
+ j.m_data.m_value = val;
+ j.assert_invariant();
+ }
+};
+
+template <>
+struct external_constructor<value_t::number_unsigned> {
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::number_unsigned;
+ j.m_data.m_value = val;
+ j.assert_invariant();
+ }
+};
+
+template <>
+struct external_constructor<value_t::number_integer> {
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::number_integer;
+ j.m_data.m_value = val;
+ j.assert_invariant();
+ }
+};
+
+template <>
+struct external_constructor<value_t::array> {
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::array;
+ j.m_data.m_value = arr;
+ j.set_parents();
+ j.assert_invariant();
+ }
+
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::array;
+ j.m_data.m_value = std::move(arr);
+ j.set_parents();
+ j.assert_invariant();
+ }
+
+ template <typename BasicJsonType,
+ typename CompatibleArrayType,
+ enable_if_t<!std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value, int> = 0>
+ static void
+ construct(BasicJsonType& j, const CompatibleArrayType& arr) {
+ using std::begin;
+ using std::end;
+
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::array;
+ j.m_data.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
+ j.set_parents();
+ j.assert_invariant();
+ }
+
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, const std::vector<bool>& arr) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::array;
+ j.m_data.m_value = value_t::array;
+ j.m_data.m_value.array->reserve(arr.size());
+ for (const bool x : arr) {
+ j.m_data.m_value.array->push_back(x);
+ j.set_parent(j.m_data.m_value.array->back());
+ }
+ j.assert_invariant();
+ }
+
+ template <typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
+ static void
+ construct(BasicJsonType& j, const std::valarray<T>& arr) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::array;
+ j.m_data.m_value = value_t::array;
+ j.m_data.m_value.array->resize(arr.size());
+ if (arr.size() > 0) {
+ std::copy(std::begin(arr), std::end(arr), j.m_data.m_value.array->begin());
+ }
+ j.set_parents();
+ j.assert_invariant();
+ }
+};
+
+template <>
+struct external_constructor<value_t::object> {
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::object;
+ j.m_data.m_value = obj;
+ j.set_parents();
+ j.assert_invariant();
+ }
+
+ template <typename BasicJsonType>
+ static void
+ construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) {
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::object;
+ j.m_data.m_value = std::move(obj);
+ j.set_parents();
+ j.assert_invariant();
+ }
+
+ template <typename BasicJsonType,
+ typename CompatibleObjectType,
+ enable_if_t<!std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
+ static void
+ construct(BasicJsonType& j, const CompatibleObjectType& obj) {
+ using std::begin;
+ using std::end;
+
+ j.m_data.m_value.destroy(j.m_data.m_type);
+ j.m_data.m_type = value_t::object;
+ j.m_data.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
+ j.set_parents();
+ j.assert_invariant();
+ }
+};
+
+/////////////
+// to_json //
+/////////////
+
+template <typename BasicJsonType,
+ typename T,
+ enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
+inline void
+to_json(BasicJsonType& j, T b) noexcept {
+ external_constructor<value_t::boolean>::construct(j, b);
+}
+
+template <typename BasicJsonType,
+ typename BoolRef,
+ enable_if_t<((std::is_same<std::vector<bool>::reference, BoolRef>::value &&
+ !std::is_same<std::vector<bool>::reference, typename BasicJsonType::boolean_t&>::value) ||
+ (std::is_same<std::vector<bool>::const_reference, BoolRef>::value &&
+ !std::is_same<detail::uncvref_t<std::vector<bool>::const_reference>,
+ typename BasicJsonType::boolean_t>::value)) &&
+ std::is_convertible<const BoolRef&, typename BasicJsonType::boolean_t>::value,
+ int> = 0>
+inline void
+to_json(BasicJsonType& j, const BoolRef& b) noexcept {
+ external_constructor<value_t::boolean>::construct(j, static_cast<typename BasicJsonType::boolean_t>(b));
+}
+
+template <typename BasicJsonType,
+ typename CompatibleString,
+ enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
+inline void
+to_json(BasicJsonType& j, const CompatibleString& s) {
+ external_constructor<value_t::string>::construct(j, s);
+}
+
+template <typename BasicJsonType>
+inline void
+to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) {
+ external_constructor<value_t::string>::construct(j, std::move(s));
+}
+
+template <typename BasicJsonType, typename FloatType, enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
+inline void
+to_json(BasicJsonType& j, FloatType val) noexcept {
+ external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
+}
+
+template <typename BasicJsonType,
+ typename CompatibleNumberUnsignedType,
+ enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t,
+ CompatibleNumberUnsignedType>::value,
+ int> = 0>
+inline void
+to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept {
+ external_constructor<value_t::number_unsigned>::construct(
+ j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
+}
+
+template <typename BasicJsonType,
+ typename CompatibleNumberIntegerType,
+ enable_if_t<
+ is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value,
+ int> = 0>
+inline void
+to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept {
+ external_constructor<value_t::number_integer>::construct(
+ j, static_cast<typename BasicJsonType::number_integer_t>(val));
+}
+
+#if !JSON_DISABLE_ENUM_SERIALIZATION
+template <typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0>
+inline void
+to_json(BasicJsonType& j, EnumType e) noexcept {
+ using underlying_type = typename std::underlying_type<EnumType>::type;
+ external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
+}
+#endif // JSON_DISABLE_ENUM_SERIALIZATION
+
+template <typename BasicJsonType>
+inline void
+to_json(BasicJsonType& j, const std::vector<bool>& e) {
+ external_constructor<value_t::array>::construct(j, e);
+}
+
+template <typename BasicJsonType,
+ typename CompatibleArrayType,
+ enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value &&
+ !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value &&
+ !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value &&
+ !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value &&
+ !is_basic_json<CompatibleArrayType>::value,
+ int> = 0>
+inline void
+to_json(BasicJsonType& j, const CompatibleArrayType& arr) {
+ external_constructor<value_t::array>::construct(j, arr);
+}
+
+template <typename BasicJsonType>
+inline void
+to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) {
+ external_constructor<value_t::binary>::construct(j, bin);
+}
+
+template <typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
+inline void
+to_json(BasicJsonType& j, const std::valarray<T>& arr) {
+ external_constructor<value_t::array>::construct(j, std::move(arr));
+}
+
+template <typename BasicJsonType>
+inline void
+to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) {
+ external_constructor<value_t::array>::construct(j, std::move(arr));
+}
+
+template <typename BasicJsonType,
+ typename CompatibleObjectType,
+ enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value &&
+ !is_basic_json<CompatibleObjectType>::value,
+ int> = 0>
+inline void
+to_json(BasicJsonType& j, const CompatibleObjectType& obj) {
+ external_constructor<value_t::object>::construct(j, obj);
+}
+
+template <typename BasicJsonType>
+inline void
+to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) {
+ external_constructor<value_t::object>::construct(j, std::move(obj));
+}
+
+template <
+ typename BasicJsonType,
+ typename T,
+ std::size_t N,
+ enable_if_t<!std::is_constructible<typename BasicJsonType::string_t,
+ const T (&)[N]>::
+ value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+ int> = 0>
+inline void
+to_json(BasicJsonType& j,
+ const T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+{
+ external_constructor<value_t::array>::construct(j, arr);
+}
+
+template <
+ typename BasicJsonType,
+ typename T1,
+ typename T2,
+ enable_if_t<std::is_constructible<BasicJsonType, T1>::value && std::is_constructible<BasicJsonType, T2>::value,
+ int> = 0>
+inline void
+to_json(BasicJsonType& j, const std::pair<T1, T2>& p) {
+ j = {p.first, p.second};
+}
+
+// for https://github.com/nlohmann/json/pull/1134
+template <typename BasicJsonType,
+ typename T,
+ enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
+inline void
+to_json(BasicJsonType& j, const T& b) {
+ j = {{b.key(), b.value()}};
+}
+
+template <typename BasicJsonType, typename Tuple, std::size_t... Idx>
+inline void
+to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/) {
+ j = {std::get<Idx>(t)...};
+}
+
+template <typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int> = 0>
+inline void
+to_json(BasicJsonType& j, const T& t) {
+ to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value>{});
+}
+
+#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
+template <typename BasicJsonType>
+inline void
+to_json(BasicJsonType& j, const std_fs::path& p) {
+ j = p.string();
+}
+#endif
+
+struct to_json_fn {
+ template <typename BasicJsonType, typename T>
+ auto
+ operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
+ -> decltype(to_json(j, std::forward<T>(val)), void()) {
+ return to_json(j, std::forward<T>(val));
+ }
+};
+} // namespace detail
+
+#ifndef JSON_HAS_CPP_17
+/// namespace to hold default `to_json` function
+/// to see why this is required:
+/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
+namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
+{
+#endif
+JSON_INLINE_VARIABLE constexpr const auto& to_json = // NOLINT(misc-definitions-in-headers)
+ detail::static_const<detail::to_json_fn>::value;
+#ifndef JSON_HAS_CPP_17
+} // namespace
+#endif
+
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/meta/identity_tag.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+
+/// @sa https://json.nlohmann.me/api/adl_serializer/
+template <typename ValueType, typename>
+struct adl_serializer {
+ /// @brief convert a JSON value to any value type
+ /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/
+ template <typename BasicJsonType, typename TargetType = ValueType>
+ static auto
+ from_json(BasicJsonType&& j,
+ TargetType& val) noexcept(noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
+ -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void()) {
+ ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
+ }
+
+ /// @brief convert a JSON value to any value type
+ /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/
+ template <typename BasicJsonType, typename TargetType = ValueType>
+ static auto
+ from_json(BasicJsonType&& j) noexcept(noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j),
+ detail::identity_tag<TargetType>{})))
+ -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType>{})) {
+ return ::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType>{});
+ }
+
+ /// @brief convert any value type to a JSON value
+ /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/
+ template <typename BasicJsonType, typename TargetType = ValueType>
+ static auto
+ to_json(BasicJsonType& j,
+ TargetType&& val) noexcept(noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
+ -> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void()) {
+ ::nlohmann::to_json(j, std::forward<TargetType>(val));
+ }
+};
+
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/byte_container_with_subtype.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstdint> // uint8_t, uint64_t
+#include <tuple> // tie
+#include <utility> // move
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+
+/// @brief an internal type for a backed binary type
+/// @sa https://json.nlohmann.me/api/byte_container_with_subtype/
+template <typename BinaryType>
+class byte_container_with_subtype : public BinaryType {
+ public:
+ using container_type = BinaryType;
+ using subtype_type = std::uint64_t;
+
+ /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+ byte_container_with_subtype() noexcept(noexcept(container_type())) : container_type() {}
+
+ /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+ byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) : container_type(b) {}
+
+ /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+ byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b))))
+ : container_type(std::move(b)) {}
+
+ /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+ byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b)))
+ : container_type(b), m_subtype(subtype_), m_has_subtype(true) {}
+
+ /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+ byte_container_with_subtype(container_type&& b,
+ subtype_type subtype_) noexcept(noexcept(container_type(std::move(b))))
+ : container_type(std::move(b)), m_subtype(subtype_), m_has_subtype(true) {}
+
+ bool
+ operator==(const byte_container_with_subtype& rhs) const {
+ return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) ==
+ std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype);
+ }
+
+ bool
+ operator!=(const byte_container_with_subtype& rhs) const {
+ return !(rhs == *this);
+ }
+
+ /// @brief sets the binary subtype
+ /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/
+ void
+ set_subtype(subtype_type subtype_) noexcept {
+ m_subtype = subtype_;
+ m_has_subtype = true;
+ }
+
+ /// @brief return the binary subtype
+ /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/
+ constexpr subtype_type
+ subtype() const noexcept {
+ return m_has_subtype ? m_subtype : static_cast<subtype_type>(-1);
+ }
+
+ /// @brief return whether the value has a subtype
+ /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/
+ constexpr bool
+ has_subtype() const noexcept {
+ return m_has_subtype;
+ }
+
+ /// @brief clears the binary subtype
+ /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/
+ void
+ clear_subtype() noexcept {
+ m_subtype = 0;
+ m_has_subtype = false;
+ }
+
+ private:
+ subtype_type m_subtype = 0;
+ bool m_has_subtype = false;
+};
+
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/conversions/from_json.hpp>
+
+// #include <nlohmann/detail/conversions/to_json.hpp>
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/hash.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstdint> // uint8_t
+#include <cstddef> // size_t
+#include <functional> // hash
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+// boost::hash_combine
+inline std::size_t
+combine(std::size_t seed, std::size_t h) noexcept {
+ seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U);
+ return seed;
+}
+
+/*!
+@brief hash a JSON value
+
+The hash function tries to rely on std::hash where possible. Furthermore, the
+type of the JSON value is taken into account to have different hash values for
+null, 0, 0U, and false, etc.
+
+@tparam BasicJsonType basic_json specialization
+@param j JSON value to hash
+@return hash value of j
+*/
+template <typename BasicJsonType>
+std::size_t
+hash(const BasicJsonType& j) {
+ using string_t = typename BasicJsonType::string_t;
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+
+ const auto type = static_cast<std::size_t>(j.type());
+ switch (j.type()) {
+ case BasicJsonType::value_t::null:
+ case BasicJsonType::value_t::discarded: {
+ return combine(type, 0);
+ }
+
+ case BasicJsonType::value_t::object: {
+ auto seed = combine(type, j.size());
+ for (const auto& element : j.items()) {
+ const auto h = std::hash<string_t>{}(element.key());
+ seed = combine(seed, h);
+ seed = combine(seed, hash(element.value()));
+ }
+ return seed;
+ }
+
+ case BasicJsonType::value_t::array: {
+ auto seed = combine(type, j.size());
+ for (const auto& element : j) {
+ seed = combine(seed, hash(element));
+ }
+ return seed;
+ }
+
+ case BasicJsonType::value_t::string: {
+ const auto h = std::hash<string_t>{}(j.template get_ref<const string_t&>());
+ return combine(type, h);
+ }
+
+ case BasicJsonType::value_t::boolean: {
+ const auto h = std::hash<bool>{}(j.template get<bool>());
+ return combine(type, h);
+ }
+
+ case BasicJsonType::value_t::number_integer: {
+ const auto h = std::hash<number_integer_t>{}(j.template get<number_integer_t>());
+ return combine(type, h);
+ }
+
+ case BasicJsonType::value_t::number_unsigned: {
+ const auto h = std::hash<number_unsigned_t>{}(j.template get<number_unsigned_t>());
+ return combine(type, h);
+ }
+
+ case BasicJsonType::value_t::number_float: {
+ const auto h = std::hash<number_float_t>{}(j.template get<number_float_t>());
+ return combine(type, h);
+ }
+
+ case BasicJsonType::value_t::binary: {
+ auto seed = combine(type, j.get_binary().size());
+ const auto h = std::hash<bool>{}(j.get_binary().has_subtype());
+ seed = combine(seed, h);
+ seed = combine(seed, static_cast<std::size_t>(j.get_binary().subtype()));
+ for (const auto byte : j.get_binary()) {
+ seed = combine(seed, std::hash<std::uint8_t>{}(byte));
+ }
+ return seed;
+ }
+
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ return 0; // LCOV_EXCL_LINE
+ }
+}
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/input/binary_reader.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <algorithm> // generate_n
+#include <array> // array
+#include <cmath> // ldexp
+#include <cstddef> // size_t
+#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
+#include <cstdio> // snprintf
+#include <cstring> // memcpy
+#include <iterator> // back_inserter
+#include <limits> // numeric_limits
+#include <string> // char_traits, string
+#include <utility> // make_pair, move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <array> // array
+#include <cstddef> // size_t
+#include <cstring> // strlen
+#include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
+#include <memory> // shared_ptr, make_shared, addressof
+#include <numeric> // accumulate
+#include <string> // string, char_traits
+#include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
+#include <utility> // pair, declval
+
+#ifndef JSON_NO_IO
+#include <cstdio> // FILE *
+#include <istream> // istream
+#endif // JSON_NO_IO
+
+// #include <nlohmann/detail/iterators/iterator_traits.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+/// the supported input formats
+enum class input_format_t { json, cbor, msgpack, ubjson, bson, bjdata };
+
+////////////////////
+// input adapters //
+////////////////////
+
+#ifndef JSON_NO_IO
+/*!
+Input adapter for stdio file access. This adapter read only 1 byte and do not use any
+ buffer. This adapter is a very low level adapter.
+*/
+class file_input_adapter {
+ public:
+ using char_type = char;
+
+ JSON_HEDLEY_NON_NULL(2)
+ explicit file_input_adapter(std::FILE* f) noexcept : m_file(f) { JSON_ASSERT(m_file != nullptr); }
+
+ // make class move-only
+ file_input_adapter(const file_input_adapter&) = delete;
+ file_input_adapter(file_input_adapter&&) noexcept = default;
+ file_input_adapter&
+ operator=(const file_input_adapter&) = delete;
+ file_input_adapter&
+ operator=(file_input_adapter&&) = delete;
+ ~file_input_adapter() = default;
+
+ std::char_traits<char>::int_type
+ get_character() noexcept {
+ return std::fgetc(m_file);
+ }
+
+ private:
+ /// the file pointer to read from
+ std::FILE* m_file;
+};
+
+/*!
+Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
+beginning of input. Does not support changing the underlying std::streambuf
+in mid-input. Maintains underlying std::istream and std::streambuf to support
+subsequent use of standard std::istream operations to process any input
+characters following those used in parsing the JSON input. Clears the
+std::istream flags; any input errors (e.g., EOF) will be detected by the first
+subsequent call for input from the std::istream.
+*/
+class input_stream_adapter {
+ public:
+ using char_type = char;
+
+ ~input_stream_adapter() {
+ // clear stream flags; we use underlying streambuf I/O, do not
+ // maintain ifstream flags, except eof
+ if (is != nullptr) {
+ is->clear(is->rdstate() & std::ios::eofbit);
+ }
+ }
+
+ explicit input_stream_adapter(std::istream& i) : is(&i), sb(i.rdbuf()) {}
+
+ // delete because of pointer members
+ input_stream_adapter(const input_stream_adapter&) = delete;
+ input_stream_adapter&
+ operator=(input_stream_adapter&) = delete;
+ input_stream_adapter&
+ operator=(input_stream_adapter&&) = delete;
+
+ input_stream_adapter(input_stream_adapter&& rhs) noexcept : is(rhs.is), sb(rhs.sb) {
+ rhs.is = nullptr;
+ rhs.sb = nullptr;
+ }
+
+ // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
+ // ensure that std::char_traits<char>::eof() and the character 0xFF do not
+ // end up as the same value, e.g. 0xFFFFFFFF.
+ std::char_traits<char>::int_type
+ get_character() {
+ auto res = sb->sbumpc();
+ // set eof manually, as we don't use the istream interface.
+ if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof())) {
+ is->clear(is->rdstate() | std::ios::eofbit);
+ }
+ return res;
+ }
+
+ private:
+ /// the associated input stream
+ std::istream* is = nullptr;
+ std::streambuf* sb = nullptr;
+};
+#endif // JSON_NO_IO
+
+// General-purpose iterator-based adapter. It might not be as fast as
+// theoretically possible for some containers, but it is extremely versatile.
+template <typename IteratorType>
+class iterator_input_adapter {
+ public:
+ using char_type = typename std::iterator_traits<IteratorType>::value_type;
+
+ iterator_input_adapter(IteratorType first, IteratorType last) : current(std::move(first)), end(std::move(last)) {}
+
+ typename char_traits<char_type>::int_type
+ get_character() {
+ if (JSON_HEDLEY_LIKELY(current != end)) {
+ auto result = char_traits<char_type>::to_int_type(*current);
+ std::advance(current, 1);
+ return result;
+ }
+
+ return char_traits<char_type>::eof();
+ }
+
+ private:
+ IteratorType current;
+ IteratorType end;
+
+ template <typename BaseInputAdapter, size_t T>
+ friend struct wide_string_input_helper;
+
+ bool
+ empty() const {
+ return current == end;
+ }
+};
+
+template <typename BaseInputAdapter, size_t T>
+struct wide_string_input_helper;
+
+template <typename BaseInputAdapter>
+struct wide_string_input_helper<BaseInputAdapter, 4> {
+ // UTF-32
+ static void
+ fill_buffer(BaseInputAdapter& input,
+ std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
+ size_t& utf8_bytes_index,
+ size_t& utf8_bytes_filled) {
+ utf8_bytes_index = 0;
+
+ if (JSON_HEDLEY_UNLIKELY(input.empty())) {
+ utf8_bytes[0] = std::char_traits<char>::eof();
+ utf8_bytes_filled = 1;
+ } else {
+ // get the current character
+ const auto wc = input.get_character();
+
+ // UTF-32 to UTF-8 encoding
+ if (wc < 0x80) {
+ utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+ utf8_bytes_filled = 1;
+ } else if (wc <= 0x7FF) {
+ utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(
+ 0xC0u | ((static_cast<unsigned int>(wc) >> 6u) & 0x1Fu));
+ utf8_bytes[1] =
+ static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+ utf8_bytes_filled = 2;
+ } else if (wc <= 0xFFFF) {
+ utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(
+ 0xE0u | ((static_cast<unsigned int>(wc) >> 12u) & 0x0Fu));
+ utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(
+ 0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
+ utf8_bytes[2] =
+ static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+ utf8_bytes_filled = 3;
+ } else if (wc <= 0x10FFFF) {
+ utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(
+ 0xF0u | ((static_cast<unsigned int>(wc) >> 18u) & 0x07u));
+ utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(
+ 0x80u | ((static_cast<unsigned int>(wc) >> 12u) & 0x3Fu));
+ utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(
+ 0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
+ utf8_bytes[3] =
+ static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+ utf8_bytes_filled = 4;
+ } else {
+ // unknown character
+ utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+ utf8_bytes_filled = 1;
+ }
+ }
+ }
+};
+
+template <typename BaseInputAdapter>
+struct wide_string_input_helper<BaseInputAdapter, 2> {
+ // UTF-16
+ static void
+ fill_buffer(BaseInputAdapter& input,
+ std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
+ size_t& utf8_bytes_index,
+ size_t& utf8_bytes_filled) {
+ utf8_bytes_index = 0;
+
+ if (JSON_HEDLEY_UNLIKELY(input.empty())) {
+ utf8_bytes[0] = std::char_traits<char>::eof();
+ utf8_bytes_filled = 1;
+ } else {
+ // get the current character
+ const auto wc = input.get_character();
+
+ // UTF-16 to UTF-8 encoding
+ if (wc < 0x80) {
+ utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+ utf8_bytes_filled = 1;
+ } else if (wc <= 0x7FF) {
+ utf8_bytes[0] =
+ static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u)));
+ utf8_bytes[1] =
+ static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+ utf8_bytes_filled = 2;
+ } else if (0xD800 > wc || wc >= 0xE000) {
+ utf8_bytes[0] =
+ static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u)));
+ utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(
+ 0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
+ utf8_bytes[2] =
+ static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+ utf8_bytes_filled = 3;
+ } else {
+ if (JSON_HEDLEY_UNLIKELY(!input.empty())) {
+ const auto wc2 = static_cast<unsigned int>(input.get_character());
+ const auto charcode =
+ 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
+ utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
+ utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
+ utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
+ utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
+ utf8_bytes_filled = 4;
+ } else {
+ utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+ utf8_bytes_filled = 1;
+ }
+ }
+ }
+ }
+};
+
+// Wraps another input adapter to convert wide character types into individual bytes.
+template <typename BaseInputAdapter, typename WideCharType>
+class wide_string_input_adapter {
+ public:
+ using char_type = char;
+
+ wide_string_input_adapter(BaseInputAdapter base) : base_adapter(base) {}
+
+ typename std::char_traits<char>::int_type
+ get_character() noexcept {
+ // check if buffer needs to be filled
+ if (utf8_bytes_index == utf8_bytes_filled) {
+ fill_buffer<sizeof(WideCharType)>();
+
+ JSON_ASSERT(utf8_bytes_filled > 0);
+ JSON_ASSERT(utf8_bytes_index == 0);
+ }
+
+ // use buffer
+ JSON_ASSERT(utf8_bytes_filled > 0);
+ JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled);
+ return utf8_bytes[utf8_bytes_index++];
+ }
+
+ private:
+ BaseInputAdapter base_adapter;
+
+ template <size_t T>
+ void
+ fill_buffer() {
+ wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(
+ base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
+ }
+
+ /// a buffer for UTF-8 bytes
+ std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
+
+ /// index to the utf8_codes array for the next valid byte
+ std::size_t utf8_bytes_index = 0;
+ /// number of valid bytes in the utf8_codes array
+ std::size_t utf8_bytes_filled = 0;
+};
+
+template <typename IteratorType, typename Enable = void>
+struct iterator_input_adapter_factory {
+ using iterator_type = IteratorType;
+ using char_type = typename std::iterator_traits<iterator_type>::value_type;
+ using adapter_type = iterator_input_adapter<iterator_type>;
+
+ static adapter_type
+ create(IteratorType first, IteratorType last) {
+ return adapter_type(std::move(first), std::move(last));
+ }
+};
+
+template <typename T>
+struct is_iterator_of_multibyte {
+ using value_type = typename std::iterator_traits<T>::value_type;
+ enum { value = sizeof(value_type) > 1 };
+};
+
+template <typename IteratorType>
+struct iterator_input_adapter_factory<IteratorType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>> {
+ using iterator_type = IteratorType;
+ using char_type = typename std::iterator_traits<iterator_type>::value_type;
+ using base_adapter_type = iterator_input_adapter<iterator_type>;
+ using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>;
+
+ static adapter_type
+ create(IteratorType first, IteratorType last) {
+ return adapter_type(base_adapter_type(std::move(first), std::move(last)));
+ }
+};
+
+// General purpose iterator-based input
+template <typename IteratorType>
+typename iterator_input_adapter_factory<IteratorType>::adapter_type
+input_adapter(IteratorType first, IteratorType last) {
+ using factory_type = iterator_input_adapter_factory<IteratorType>;
+ return factory_type::create(first, last);
+}
+
+// Convenience shorthand from container to iterator
+// Enables ADL on begin(container) and end(container)
+// Encloses the using declarations in namespace for not to leak them to outside scope
+
+namespace container_input_adapter_factory_impl {
+
+using std::begin;
+using std::end;
+
+template <typename ContainerType, typename Enable = void>
+struct container_input_adapter_factory {};
+
+template <typename ContainerType>
+struct container_input_adapter_factory<
+ ContainerType,
+ void_t<decltype(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))>> {
+ using adapter_type =
+ decltype(input_adapter(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>())));
+
+ static adapter_type
+ create(const ContainerType& container) {
+ return input_adapter(begin(container), end(container));
+ }
+};
+
+} // namespace container_input_adapter_factory_impl
+
+template <typename ContainerType>
+typename container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::adapter_type
+input_adapter(const ContainerType& container) {
+ return container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::create(container);
+}
+
+#ifndef JSON_NO_IO
+// Special cases with fast paths
+inline file_input_adapter
+input_adapter(std::FILE* file) {
+ return file_input_adapter(file);
+}
+
+inline input_stream_adapter
+input_adapter(std::istream& stream) {
+ return input_stream_adapter(stream);
+}
+
+inline input_stream_adapter
+input_adapter(std::istream&& stream) {
+ return input_stream_adapter(stream);
+}
+#endif // JSON_NO_IO
+
+using contiguous_bytes_input_adapter =
+ decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>()));
+
+// Null-delimited strings, and the like.
+template <typename CharT,
+ typename std::enable_if<std::is_pointer<CharT>::value && !std::is_array<CharT>::value &&
+ std::is_integral<typename std::remove_pointer<CharT>::type>::value &&
+ sizeof(typename std::remove_pointer<CharT>::type) == 1,
+ int>::type = 0>
+contiguous_bytes_input_adapter
+input_adapter(CharT b) {
+ auto length = std::strlen(reinterpret_cast<const char*>(b));
+ const auto* ptr = reinterpret_cast<const char*>(b);
+ return input_adapter(ptr, ptr + length);
+}
+
+template <typename T, std::size_t N>
+auto
+input_adapter(T (&array)[N]) -> decltype(input_adapter(
+ array,
+ array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+{
+ return input_adapter(array, array + N);
+}
+
+// This class only handles inputs of input_buffer_adapter type.
+// It's required so that expressions like {ptr, len} can be implicitly cast
+// to the correct adapter.
+class span_input_adapter {
+ public:
+ template <typename CharT,
+ typename std::enable_if<std::is_pointer<CharT>::value &&
+ std::is_integral<typename std::remove_pointer<CharT>::type>::value &&
+ sizeof(typename std::remove_pointer<CharT>::type) == 1,
+ int>::type = 0>
+ span_input_adapter(CharT b, std::size_t l)
+ : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {}
+
+ template <class IteratorType,
+ typename std::enable_if<std::is_same<typename iterator_traits<IteratorType>::iterator_category,
+ std::random_access_iterator_tag>::value,
+ int>::type = 0>
+ span_input_adapter(IteratorType first, IteratorType last) : ia(input_adapter(first, last)) {}
+
+ contiguous_bytes_input_adapter&&
+ get() {
+ return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg)
+ }
+
+ private:
+ contiguous_bytes_input_adapter ia;
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/input/json_sax.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstddef>
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/string_concat.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+
+/*!
+@brief SAX interface
+
+This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
+Each function is called in different situations while the input is parsed. The
+boolean return value informs the parser whether to continue processing the
+input.
+*/
+template <typename BasicJsonType>
+struct json_sax {
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using string_t = typename BasicJsonType::string_t;
+ using binary_t = typename BasicJsonType::binary_t;
+
+ /*!
+ @brief a null value was read
+ @return whether parsing should proceed
+ */
+ virtual bool
+ null() = 0;
+
+ /*!
+ @brief a boolean value was read
+ @param[in] val boolean value
+ @return whether parsing should proceed
+ */
+ virtual bool
+ boolean(bool val) = 0;
+
+ /*!
+ @brief an integer number was read
+ @param[in] val integer value
+ @return whether parsing should proceed
+ */
+ virtual bool
+ number_integer(number_integer_t val) = 0;
+
+ /*!
+ @brief an unsigned integer number was read
+ @param[in] val unsigned integer value
+ @return whether parsing should proceed
+ */
+ virtual bool
+ number_unsigned(number_unsigned_t val) = 0;
+
+ /*!
+ @brief a floating-point number was read
+ @param[in] val floating-point value
+ @param[in] s raw token value
+ @return whether parsing should proceed
+ */
+ virtual bool
+ number_float(number_float_t val, const string_t& s) = 0;
+
+ /*!
+ @brief a string value was read
+ @param[in] val string value
+ @return whether parsing should proceed
+ @note It is safe to move the passed string value.
+ */
+ virtual bool
+ string(string_t& val) = 0;
+
+ /*!
+ @brief a binary value was read
+ @param[in] val binary value
+ @return whether parsing should proceed
+ @note It is safe to move the passed binary value.
+ */
+ virtual bool
+ binary(binary_t& val) = 0;
+
+ /*!
+ @brief the beginning of an object was read
+ @param[in] elements number of object elements or -1 if unknown
+ @return whether parsing should proceed
+ @note binary formats may report the number of elements
+ */
+ virtual bool
+ start_object(std::size_t elements) = 0;
+
+ /*!
+ @brief an object key was read
+ @param[in] val object key
+ @return whether parsing should proceed
+ @note It is safe to move the passed string.
+ */
+ virtual bool
+ key(string_t& val) = 0;
+
+ /*!
+ @brief the end of an object was read
+ @return whether parsing should proceed
+ */
+ virtual bool
+ end_object() = 0;
+
+ /*!
+ @brief the beginning of an array was read
+ @param[in] elements number of array elements or -1 if unknown
+ @return whether parsing should proceed
+ @note binary formats may report the number of elements
+ */
+ virtual bool
+ start_array(std::size_t elements) = 0;
+
+ /*!
+ @brief the end of an array was read
+ @return whether parsing should proceed
+ */
+ virtual bool
+ end_array() = 0;
+
+ /*!
+ @brief a parse error occurred
+ @param[in] position the position in the input where the error occurs
+ @param[in] last_token the last read token
+ @param[in] ex an exception object describing the error
+ @return whether parsing should proceed (must return false)
+ */
+ virtual bool
+ parse_error(std::size_t position, const std::string& last_token, const detail::exception& ex) = 0;
+
+ json_sax() = default;
+ json_sax(const json_sax&) = default;
+ json_sax(json_sax&&) noexcept = default;
+ json_sax&
+ operator=(const json_sax&) = default;
+ json_sax&
+ operator=(json_sax&&) noexcept = default;
+ virtual ~json_sax() = default;
+};
+
+namespace detail {
+/*!
+@brief SAX implementation to create a JSON value from SAX events
+
+This class implements the @ref json_sax interface and processes the SAX events
+to create a JSON value which makes it basically a DOM parser. The structure or
+hierarchy of the JSON value is managed by the stack `ref_stack` which contains
+a pointer to the respective array or object for each recursion depth.
+
+After successful parsing, the value that is passed by reference to the
+constructor contains the parsed value.
+
+@tparam BasicJsonType the JSON type
+*/
+template <typename BasicJsonType>
+class json_sax_dom_parser {
+ public:
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using string_t = typename BasicJsonType::string_t;
+ using binary_t = typename BasicJsonType::binary_t;
+
+ /*!
+ @param[in,out] r reference to a JSON value that is manipulated while
+ parsing
+ @param[in] allow_exceptions_ whether parse errors yield exceptions
+ */
+ explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
+ : root(r), allow_exceptions(allow_exceptions_) {}
+
+ // make class move-only
+ json_sax_dom_parser(const json_sax_dom_parser&) = delete;
+ json_sax_dom_parser(json_sax_dom_parser&&) =
+ default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+ json_sax_dom_parser&
+ operator=(const json_sax_dom_parser&) = delete;
+ json_sax_dom_parser&
+ operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+ ~json_sax_dom_parser() = default;
+
+ bool
+ null() {
+ handle_value(nullptr);
+ return true;
+ }
+
+ bool
+ boolean(bool val) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ number_integer(number_integer_t val) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ number_unsigned(number_unsigned_t val) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ number_float(number_float_t val, const string_t& /*unused*/) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ string(string_t& val) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ binary(binary_t& val) {
+ handle_value(std::move(val));
+ return true;
+ }
+
+ bool
+ start_object(std::size_t len) {
+ ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
+
+ if (JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size())) {
+ JSON_THROW(
+ out_of_range::create(408, concat("excessive object size: ", std::to_string(len)), ref_stack.back()));
+ }
+
+ return true;
+ }
+
+ bool
+ key(string_t& val) {
+ JSON_ASSERT(!ref_stack.empty());
+ JSON_ASSERT(ref_stack.back()->is_object());
+
+ // add null at given key and store the reference for later
+ object_element = &(ref_stack.back()->m_data.m_value.object->operator[](val));
+ return true;
+ }
+
+ bool
+ end_object() {
+ JSON_ASSERT(!ref_stack.empty());
+ JSON_ASSERT(ref_stack.back()->is_object());
+
+ ref_stack.back()->set_parents();
+ ref_stack.pop_back();
+ return true;
+ }
+
+ bool
+ start_array(std::size_t len) {
+ ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
+
+ if (JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size())) {
+ JSON_THROW(
+ out_of_range::create(408, concat("excessive array size: ", std::to_string(len)), ref_stack.back()));
+ }
+
+ return true;
+ }
+
+ bool
+ end_array() {
+ JSON_ASSERT(!ref_stack.empty());
+ JSON_ASSERT(ref_stack.back()->is_array());
+
+ ref_stack.back()->set_parents();
+ ref_stack.pop_back();
+ return true;
+ }
+
+ template <class Exception>
+ bool
+ parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) {
+ errored = true;
+ static_cast<void>(ex);
+ if (allow_exceptions) {
+ JSON_THROW(ex);
+ }
+ return false;
+ }
+
+ constexpr bool
+ is_errored() const {
+ return errored;
+ }
+
+ private:
+ /*!
+ @invariant If the ref stack is empty, then the passed value will be the new
+ root.
+ @invariant If the ref stack contains a value, then it is an array or an
+ object to which we can add elements
+ */
+ template <typename Value>
+ JSON_HEDLEY_RETURNS_NON_NULL BasicJsonType*
+ handle_value(Value&& v) {
+ if (ref_stack.empty()) {
+ root = BasicJsonType(std::forward<Value>(v));
+ return &root;
+ }
+
+ JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
+
+ if (ref_stack.back()->is_array()) {
+ ref_stack.back()->m_data.m_value.array->emplace_back(std::forward<Value>(v));
+ return &(ref_stack.back()->m_data.m_value.array->back());
+ }
+
+ JSON_ASSERT(ref_stack.back()->is_object());
+ JSON_ASSERT(object_element);
+ *object_element = BasicJsonType(std::forward<Value>(v));
+ return object_element;
+ }
+
+ /// the parsed JSON value
+ BasicJsonType& root;
+ /// stack to model hierarchy of values
+ std::vector<BasicJsonType*> ref_stack{};
+ /// helper to hold the reference for the next object element
+ BasicJsonType* object_element = nullptr;
+ /// whether a syntax error occurred
+ bool errored = false;
+ /// whether to throw exceptions in case of errors
+ const bool allow_exceptions = true;
+};
+
+template <typename BasicJsonType>
+class json_sax_dom_callback_parser {
+ public:
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using string_t = typename BasicJsonType::string_t;
+ using binary_t = typename BasicJsonType::binary_t;
+ using parser_callback_t = typename BasicJsonType::parser_callback_t;
+ using parse_event_t = typename BasicJsonType::parse_event_t;
+
+ json_sax_dom_callback_parser(BasicJsonType& r, const parser_callback_t cb, const bool allow_exceptions_ = true)
+ : root(r), callback(cb), allow_exceptions(allow_exceptions_) {
+ keep_stack.push_back(true);
+ }
+
+ // make class move-only
+ json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
+ json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) =
+ default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+ json_sax_dom_callback_parser&
+ operator=(const json_sax_dom_callback_parser&) = delete;
+ json_sax_dom_callback_parser&
+ operator=(json_sax_dom_callback_parser&&) =
+ default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+ ~json_sax_dom_callback_parser() = default;
+
+ bool
+ null() {
+ handle_value(nullptr);
+ return true;
+ }
+
+ bool
+ boolean(bool val) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ number_integer(number_integer_t val) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ number_unsigned(number_unsigned_t val) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ number_float(number_float_t val, const string_t& /*unused*/) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ string(string_t& val) {
+ handle_value(val);
+ return true;
+ }
+
+ bool
+ binary(binary_t& val) {
+ handle_value(std::move(val));
+ return true;
+ }
+
+ bool
+ start_object(std::size_t len) {
+ // check callback for object start
+ const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
+ keep_stack.push_back(keep);
+
+ auto val = handle_value(BasicJsonType::value_t::object, true);
+ ref_stack.push_back(val.second);
+
+ // check object limit
+ if (ref_stack.back() &&
+ JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size())) {
+ JSON_THROW(
+ out_of_range::create(408, concat("excessive object size: ", std::to_string(len)), ref_stack.back()));
+ }
+
+ return true;
+ }
+
+ bool
+ key(string_t& val) {
+ BasicJsonType k = BasicJsonType(val);
+
+ // check callback for key
+ const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
+ key_keep_stack.push_back(keep);
+
+ // add discarded value at given key and store the reference for later
+ if (keep && ref_stack.back()) {
+ object_element = &(ref_stack.back()->m_data.m_value.object->operator[](val) = discarded);
+ }
+
+ return true;
+ }
+
+ bool
+ end_object() {
+ if (ref_stack.back()) {
+ if (!callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) {
+ // discard object
+ *ref_stack.back() = discarded;
+ } else {
+ ref_stack.back()->set_parents();
+ }
+ }
+
+ JSON_ASSERT(!ref_stack.empty());
+ JSON_ASSERT(!keep_stack.empty());
+ ref_stack.pop_back();
+ keep_stack.pop_back();
+
+ if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) {
+ // remove discarded value
+ for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) {
+ if (it->is_discarded()) {
+ ref_stack.back()->erase(it);
+ break;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ bool
+ start_array(std::size_t len) {
+ const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
+ keep_stack.push_back(keep);
+
+ auto val = handle_value(BasicJsonType::value_t::array, true);
+ ref_stack.push_back(val.second);
+
+ // check array limit
+ if (ref_stack.back() &&
+ JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size())) {
+ JSON_THROW(
+ out_of_range::create(408, concat("excessive array size: ", std::to_string(len)), ref_stack.back()));
+ }
+
+ return true;
+ }
+
+ bool
+ end_array() {
+ bool keep = true;
+
+ if (ref_stack.back()) {
+ keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
+ if (keep) {
+ ref_stack.back()->set_parents();
+ } else {
+ // discard array
+ *ref_stack.back() = discarded;
+ }
+ }
+
+ JSON_ASSERT(!ref_stack.empty());
+ JSON_ASSERT(!keep_stack.empty());
+ ref_stack.pop_back();
+ keep_stack.pop_back();
+
+ // remove discarded value
+ if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) {
+ ref_stack.back()->m_data.m_value.array->pop_back();
+ }
+
+ return true;
+ }
+
+ template <class Exception>
+ bool
+ parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) {
+ errored = true;
+ static_cast<void>(ex);
+ if (allow_exceptions) {
+ JSON_THROW(ex);
+ }
+ return false;
+ }
+
+ constexpr bool
+ is_errored() const {
+ return errored;
+ }
+
+ private:
+ /*!
+ @param[in] v value to add to the JSON value we build during parsing
+ @param[in] skip_callback whether we should skip calling the callback
+ function; this is required after start_array() and
+ start_object() SAX events, because otherwise we would call the
+ callback function with an empty array or object, respectively.
+
+ @invariant If the ref stack is empty, then the passed value will be the new
+ root.
+ @invariant If the ref stack contains a value, then it is an array or an
+ object to which we can add elements
+
+ @return pair of boolean (whether value should be kept) and pointer (to the
+ passed value in the ref_stack hierarchy; nullptr if not kept)
+ */
+ template <typename Value>
+ std::pair<bool, BasicJsonType*>
+ handle_value(Value&& v, const bool skip_callback = false) {
+ JSON_ASSERT(!keep_stack.empty());
+
+ // do not handle this value if we know it would be added to a discarded
+ // container
+ if (!keep_stack.back()) {
+ return {false, nullptr};
+ }
+
+ // create value
+ auto value = BasicJsonType(std::forward<Value>(v));
+
+ // check callback
+ const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
+
+ // do not handle this value if we just learnt it shall be discarded
+ if (!keep) {
+ return {false, nullptr};
+ }
+
+ if (ref_stack.empty()) {
+ root = std::move(value);
+ return {true, &root};
+ }
+
+ // skip this value if we already decided to skip the parent
+ // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
+ if (!ref_stack.back()) {
+ return {false, nullptr};
+ }
+
+ // we now only expect arrays and objects
+ JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
+
+ // array
+ if (ref_stack.back()->is_array()) {
+ ref_stack.back()->m_data.m_value.array->emplace_back(std::move(value));
+ return {true, &(ref_stack.back()->m_data.m_value.array->back())};
+ }
+
+ // object
+ JSON_ASSERT(ref_stack.back()->is_object());
+ // check if we should store an element for the current key
+ JSON_ASSERT(!key_keep_stack.empty());
+ const bool store_element = key_keep_stack.back();
+ key_keep_stack.pop_back();
+
+ if (!store_element) {
+ return {false, nullptr};
+ }
+
+ JSON_ASSERT(object_element);
+ *object_element = std::move(value);
+ return {true, object_element};
+ }
+
+ /// the parsed JSON value
+ BasicJsonType& root;
+ /// stack to model hierarchy of values
+ std::vector<BasicJsonType*> ref_stack{};
+ /// stack to manage which values to keep
+ std::vector<bool> keep_stack{};
+ /// stack to manage which object keys to keep
+ std::vector<bool> key_keep_stack{};
+ /// helper to hold the reference for the next object element
+ BasicJsonType* object_element = nullptr;
+ /// whether a syntax error occurred
+ bool errored = false;
+ /// callback function
+ const parser_callback_t callback = nullptr;
+ /// whether to throw exceptions in case of errors
+ const bool allow_exceptions = true;
+ /// a discarded value for the callback
+ BasicJsonType discarded = BasicJsonType::value_t::discarded;
+};
+
+template <typename BasicJsonType>
+class json_sax_acceptor {
+ public:
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using string_t = typename BasicJsonType::string_t;
+ using binary_t = typename BasicJsonType::binary_t;
+
+ bool
+ null() {
+ return true;
+ }
+
+ bool
+ boolean(bool /*unused*/) {
+ return true;
+ }
+
+ bool
+ number_integer(number_integer_t /*unused*/) {
+ return true;
+ }
+
+ bool
+ number_unsigned(number_unsigned_t /*unused*/) {
+ return true;
+ }
+
+ bool
+ number_float(number_float_t /*unused*/, const string_t& /*unused*/) {
+ return true;
+ }
+
+ bool
+ string(string_t& /*unused*/) {
+ return true;
+ }
+
+ bool
+ binary(binary_t& /*unused*/) {
+ return true;
+ }
+
+ bool
+ start_object(std::size_t /*unused*/ = static_cast<std::size_t>(-1)) {
+ return true;
+ }
+
+ bool
+ key(string_t& /*unused*/) {
+ return true;
+ }
+
+ bool
+ end_object() {
+ return true;
+ }
+
+ bool
+ start_array(std::size_t /*unused*/ = static_cast<std::size_t>(-1)) {
+ return true;
+ }
+
+ bool
+ end_array() {
+ return true;
+ }
+
+ bool
+ parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) {
+ return false;
+ }
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/input/lexer.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <array> // array
+#include <clocale> // localeconv
+#include <cstddef> // size_t
+#include <cstdio> // snprintf
+#include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
+#include <initializer_list> // initializer_list
+#include <string> // char_traits, string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+// #include <nlohmann/detail/input/position_t.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+///////////
+// lexer //
+///////////
+
+template <typename BasicJsonType>
+class lexer_base {
+ public:
+ /// token types for the parser
+ enum class token_type {
+ uninitialized, ///< indicating the scanner is uninitialized
+ literal_true, ///< the `true` literal
+ literal_false, ///< the `false` literal
+ literal_null, ///< the `null` literal
+ value_string, ///< a string -- use get_string() for actual value
+ value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
+ value_integer, ///< a signed integer -- use get_number_integer() for actual value
+ value_float, ///< an floating point number -- use get_number_float() for actual value
+ begin_array, ///< the character for array begin `[`
+ begin_object, ///< the character for object begin `{`
+ end_array, ///< the character for array end `]`
+ end_object, ///< the character for object end `}`
+ name_separator, ///< the name separator `:`
+ value_separator, ///< the value separator `,`
+ parse_error, ///< indicating a parse error
+ end_of_input, ///< indicating the end of the input buffer
+ literal_or_value ///< a literal or the begin of a value (only for diagnostics)
+ };
+
+ /// return name of values of type token_type (only used for errors)
+ JSON_HEDLEY_RETURNS_NON_NULL
+ JSON_HEDLEY_CONST
+ static const char*
+ token_type_name(const token_type t) noexcept {
+ switch (t) {
+ case token_type::uninitialized:
+ return "<uninitialized>";
+ case token_type::literal_true:
+ return "true literal";
+ case token_type::literal_false:
+ return "false literal";
+ case token_type::literal_null:
+ return "null literal";
+ case token_type::value_string:
+ return "string literal";
+ case token_type::value_unsigned:
+ case token_type::value_integer:
+ case token_type::value_float:
+ return "number literal";
+ case token_type::begin_array:
+ return "'['";
+ case token_type::begin_object:
+ return "'{'";
+ case token_type::end_array:
+ return "']'";
+ case token_type::end_object:
+ return "'}'";
+ case token_type::name_separator:
+ return "':'";
+ case token_type::value_separator:
+ return "','";
+ case token_type::parse_error:
+ return "<parse error>";
+ case token_type::end_of_input:
+ return "end of input";
+ case token_type::literal_or_value:
+ return "'[', '{', or a literal";
+ // LCOV_EXCL_START
+ default: // catch non-enum values
+ return "unknown token";
+ // LCOV_EXCL_STOP
+ }
+ }
+};
+/*!
+@brief lexical analysis
+
+This class organizes the lexical analysis during JSON deserialization.
+*/
+template <typename BasicJsonType, typename InputAdapterType>
+class lexer : public lexer_base<BasicJsonType> {
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using string_t = typename BasicJsonType::string_t;
+ using char_type = typename InputAdapterType::char_type;
+ using char_int_type = typename char_traits<char_type>::int_type;
+
+ public:
+ using token_type = typename lexer_base<BasicJsonType>::token_type;
+
+ explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept
+ : ia(std::move(adapter)),
+ ignore_comments(ignore_comments_),
+ decimal_point_char(static_cast<char_int_type>(get_decimal_point())) {}
+
+ // delete because of pointer members
+ lexer(const lexer&) = delete;
+ lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+ lexer&
+ operator=(lexer&) = delete;
+ lexer&
+ operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+ ~lexer() = default;
+
+ private:
+ /////////////////////
+ // locales
+ /////////////////////
+
+ /// return the locale-dependent decimal point
+ JSON_HEDLEY_PURE
+ static char
+ get_decimal_point() noexcept {
+ const auto* loc = localeconv();
+ JSON_ASSERT(loc != nullptr);
+ return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
+ }
+
+ /////////////////////
+ // scan functions
+ /////////////////////
+
+ /*!
+ @brief get codepoint from 4 hex characters following `\u`
+
+ For input "\u c1 c2 c3 c4" the codepoint is:
+ (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
+ = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
+
+ Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
+ must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
+ conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
+ between the ASCII value of the character and the desired integer value.
+
+ @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
+ non-hex character)
+ */
+ int
+ get_codepoint() {
+ // this function only makes sense after reading `\u`
+ JSON_ASSERT(current == 'u');
+ int codepoint = 0;
+
+ const auto factors = {12u, 8u, 4u, 0u};
+ for (const auto factor : factors) {
+ get();
+
+ if (current >= '0' && current <= '9') {
+ codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
+ } else if (current >= 'A' && current <= 'F') {
+ codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
+ } else if (current >= 'a' && current <= 'f') {
+ codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
+ } else {
+ return -1;
+ }
+ }
+
+ JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF);
+ return codepoint;
+ }
+
+ /*!
+ @brief check if the next byte(s) are inside a given range
+
+ Adds the current byte and, for each passed range, reads a new byte and
+ checks if it is inside the range. If a violation was detected, set up an
+ error message and return false. Otherwise, return true.
+
+ @param[in] ranges list of integers; interpreted as list of pairs of
+ inclusive lower and upper bound, respectively
+
+ @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
+ 1, 2, or 3 pairs. This precondition is enforced by an assertion.
+
+ @return true if and only if no range violation was detected
+ */
+ bool
+ next_byte_in_range(std::initializer_list<char_int_type> ranges) {
+ JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6);
+ add(current);
+
+ for (auto range = ranges.begin(); range != ranges.end(); ++range) {
+ get();
+ if (JSON_HEDLEY_LIKELY(*range <= current &&
+ current <= *(++range))) // NOLINT(bugprone-inc-dec-in-conditions)
+ {
+ add(current);
+ } else {
+ error_message = "invalid string: ill-formed UTF-8 byte";
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /*!
+ @brief scan a string literal
+
+ This function scans a string according to Sect. 7 of RFC 8259. While
+ scanning, bytes are escaped and copied into buffer token_buffer. Then the
+ function returns successfully, token_buffer is *not* null-terminated (as it
+ may contain \0 bytes), and token_buffer.size() is the number of bytes in the
+ string.
+
+ @return token_type::value_string if string could be successfully scanned,
+ token_type::parse_error otherwise
+
+ @note In case of errors, variable error_message contains a textual
+ description.
+ */
+ token_type
+ scan_string() {
+ // reset token_buffer (ignore opening quote)
+ reset();
+
+ // we entered the function by reading an open quote
+ JSON_ASSERT(current == '\"');
+
+ while (true) {
+ // get next character
+ switch (get()) {
+ // end of file while parsing string
+ case char_traits<char_type>::eof(): {
+ error_message = "invalid string: missing closing quote";
+ return token_type::parse_error;
+ }
+
+ // closing quote
+ case '\"': {
+ return token_type::value_string;
+ }
+
+ // escapes
+ case '\\': {
+ switch (get()) {
+ // quotation mark
+ case '\"':
+ add('\"');
+ break;
+ // reverse solidus
+ case '\\':
+ add('\\');
+ break;
+ // solidus
+ case '/':
+ add('/');
+ break;
+ // backspace
+ case 'b':
+ add('\b');
+ break;
+ // form feed
+ case 'f':
+ add('\f');
+ break;
+ // line feed
+ case 'n':
+ add('\n');
+ break;
+ // carriage return
+ case 'r':
+ add('\r');
+ break;
+ // tab
+ case 't':
+ add('\t');
+ break;
+
+ // unicode escapes
+ case 'u': {
+ const int codepoint1 = get_codepoint();
+ int codepoint = codepoint1; // start with codepoint1
+
+ if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) {
+ error_message = "invalid string: '\\u' must be followed by 4 hex digits";
+ return token_type::parse_error;
+ }
+
+ // check if code point is a high surrogate
+ if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) {
+ // expect next \uxxxx entry
+ if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) {
+ const int codepoint2 = get_codepoint();
+
+ if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) {
+ error_message = "invalid string: '\\u' must be followed by 4 hex digits";
+ return token_type::parse_error;
+ }
+
+ // check if codepoint2 is a low surrogate
+ if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) {
+ // overwrite codepoint
+ codepoint = static_cast<int>(
+ // high surrogate occupies the most significant 22 bits
+ (static_cast<unsigned int>(codepoint1) << 10u)
+ // low surrogate occupies the least significant 15 bits
+ + static_cast<unsigned int>(codepoint2)
+ // there is still the 0xD800, 0xDC00 and 0x10000 noise
+ // in the result, so we have to subtract with:
+ // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
+ - 0x35FDC00u);
+ } else {
+ error_message =
+ "invalid string: surrogate U+D800..U+DBFF must be followed by "
+ "U+DC00..U+DFFF";
+ return token_type::parse_error;
+ }
+ } else {
+ error_message =
+ "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
+ return token_type::parse_error;
+ }
+ } else {
+ if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) {
+ error_message =
+ "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
+ return token_type::parse_error;
+ }
+ }
+
+ // result of the above calculation yields a proper codepoint
+ JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF);
+
+ // translate codepoint into bytes
+ if (codepoint < 0x80) {
+ // 1-byte characters: 0xxxxxxx (ASCII)
+ add(static_cast<char_int_type>(codepoint));
+ } else if (codepoint <= 0x7FF) {
+ // 2-byte characters: 110xxxxx 10xxxxxx
+ add(static_cast<char_int_type>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
+ add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
+ } else if (codepoint <= 0xFFFF) {
+ // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
+ add(static_cast<char_int_type>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
+ add(static_cast<char_int_type>(0x80u |
+ ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
+ add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
+ } else {
+ // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+ add(static_cast<char_int_type>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
+ add(static_cast<char_int_type>(
+ 0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
+ add(static_cast<char_int_type>(0x80u |
+ ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
+ add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
+ }
+
+ break;
+ }
+
+ // other characters after escape
+ default:
+ error_message = "invalid string: forbidden character after backslash";
+ return token_type::parse_error;
+ }
+
+ break;
+ }
+
+ // invalid control characters
+ case 0x00: {
+ error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
+ return token_type::parse_error;
+ }
+
+ case 0x01: {
+ error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
+ return token_type::parse_error;
+ }
+
+ case 0x02: {
+ error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
+ return token_type::parse_error;
+ }
+
+ case 0x03: {
+ error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
+ return token_type::parse_error;
+ }
+
+ case 0x04: {
+ error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
+ return token_type::parse_error;
+ }
+
+ case 0x05: {
+ error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
+ return token_type::parse_error;
+ }
+
+ case 0x06: {
+ error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
+ return token_type::parse_error;
+ }
+
+ case 0x07: {
+ error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
+ return token_type::parse_error;
+ }
+
+ case 0x08: {
+ error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
+ return token_type::parse_error;
+ }
+
+ case 0x09: {
+ error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
+ return token_type::parse_error;
+ }
+
+ case 0x0A: {
+ error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
+ return token_type::parse_error;
+ }
+
+ case 0x0B: {
+ error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
+ return token_type::parse_error;
+ }
+
+ case 0x0C: {
+ error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
+ return token_type::parse_error;
+ }
+
+ case 0x0D: {
+ error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
+ return token_type::parse_error;
+ }
+
+ case 0x0E: {
+ error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
+ return token_type::parse_error;
+ }
+
+ case 0x0F: {
+ error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
+ return token_type::parse_error;
+ }
+
+ case 0x10: {
+ error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
+ return token_type::parse_error;
+ }
+
+ case 0x11: {
+ error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
+ return token_type::parse_error;
+ }
+
+ case 0x12: {
+ error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
+ return token_type::parse_error;
+ }
+
+ case 0x13: {
+ error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
+ return token_type::parse_error;
+ }
+
+ case 0x14: {
+ error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
+ return token_type::parse_error;
+ }
+
+ case 0x15: {
+ error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
+ return token_type::parse_error;
+ }
+
+ case 0x16: {
+ error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
+ return token_type::parse_error;
+ }
+
+ case 0x17: {
+ error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
+ return token_type::parse_error;
+ }
+
+ case 0x18: {
+ error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
+ return token_type::parse_error;
+ }
+
+ case 0x19: {
+ error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
+ return token_type::parse_error;
+ }
+
+ case 0x1A: {
+ error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
+ return token_type::parse_error;
+ }
+
+ case 0x1B: {
+ error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
+ return token_type::parse_error;
+ }
+
+ case 0x1C: {
+ error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
+ return token_type::parse_error;
+ }
+
+ case 0x1D: {
+ error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
+ return token_type::parse_error;
+ }
+
+ case 0x1E: {
+ error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
+ return token_type::parse_error;
+ }
+
+ case 0x1F: {
+ error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
+ return token_type::parse_error;
+ }
+
+ // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
+ case 0x20:
+ case 0x21:
+ case 0x23:
+ case 0x24:
+ case 0x25:
+ case 0x26:
+ case 0x27:
+ case 0x28:
+ case 0x29:
+ case 0x2A:
+ case 0x2B:
+ case 0x2C:
+ case 0x2D:
+ case 0x2E:
+ case 0x2F:
+ case 0x30:
+ case 0x31:
+ case 0x32:
+ case 0x33:
+ case 0x34:
+ case 0x35:
+ case 0x36:
+ case 0x37:
+ case 0x38:
+ case 0x39:
+ case 0x3A:
+ case 0x3B:
+ case 0x3C:
+ case 0x3D:
+ case 0x3E:
+ case 0x3F:
+ case 0x40:
+ case 0x41:
+ case 0x42:
+ case 0x43:
+ case 0x44:
+ case 0x45:
+ case 0x46:
+ case 0x47:
+ case 0x48:
+ case 0x49:
+ case 0x4A:
+ case 0x4B:
+ case 0x4C:
+ case 0x4D:
+ case 0x4E:
+ case 0x4F:
+ case 0x50:
+ case 0x51:
+ case 0x52:
+ case 0x53:
+ case 0x54:
+ case 0x55:
+ case 0x56:
+ case 0x57:
+ case 0x58:
+ case 0x59:
+ case 0x5A:
+ case 0x5B:
+ case 0x5D:
+ case 0x5E:
+ case 0x5F:
+ case 0x60:
+ case 0x61:
+ case 0x62:
+ case 0x63:
+ case 0x64:
+ case 0x65:
+ case 0x66:
+ case 0x67:
+ case 0x68:
+ case 0x69:
+ case 0x6A:
+ case 0x6B:
+ case 0x6C:
+ case 0x6D:
+ case 0x6E:
+ case 0x6F:
+ case 0x70:
+ case 0x71:
+ case 0x72:
+ case 0x73:
+ case 0x74:
+ case 0x75:
+ case 0x76:
+ case 0x77:
+ case 0x78:
+ case 0x79:
+ case 0x7A:
+ case 0x7B:
+ case 0x7C:
+ case 0x7D:
+ case 0x7E:
+ case 0x7F: {
+ add(current);
+ break;
+ }
+
+ // U+0080..U+07FF: bytes C2..DF 80..BF
+ case 0xC2:
+ case 0xC3:
+ case 0xC4:
+ case 0xC5:
+ case 0xC6:
+ case 0xC7:
+ case 0xC8:
+ case 0xC9:
+ case 0xCA:
+ case 0xCB:
+ case 0xCC:
+ case 0xCD:
+ case 0xCE:
+ case 0xCF:
+ case 0xD0:
+ case 0xD1:
+ case 0xD2:
+ case 0xD3:
+ case 0xD4:
+ case 0xD5:
+ case 0xD6:
+ case 0xD7:
+ case 0xD8:
+ case 0xD9:
+ case 0xDA:
+ case 0xDB:
+ case 0xDC:
+ case 0xDD:
+ case 0xDE:
+ case 0xDF: {
+ if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) {
+ return token_type::parse_error;
+ }
+ break;
+ }
+
+ // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
+ case 0xE0: {
+ if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) {
+ return token_type::parse_error;
+ }
+ break;
+ }
+
+ // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
+ // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
+ case 0xE1:
+ case 0xE2:
+ case 0xE3:
+ case 0xE4:
+ case 0xE5:
+ case 0xE6:
+ case 0xE7:
+ case 0xE8:
+ case 0xE9:
+ case 0xEA:
+ case 0xEB:
+ case 0xEC:
+ case 0xEE:
+ case 0xEF: {
+ if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) {
+ return token_type::parse_error;
+ }
+ break;
+ }
+
+ // U+D000..U+D7FF: bytes ED 80..9F 80..BF
+ case 0xED: {
+ if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) {
+ return token_type::parse_error;
+ }
+ break;
+ }
+
+ // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
+ case 0xF0: {
+ if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) {
+ return token_type::parse_error;
+ }
+ break;
+ }
+
+ // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
+ case 0xF1:
+ case 0xF2:
+ case 0xF3: {
+ if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) {
+ return token_type::parse_error;
+ }
+ break;
+ }
+
+ // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
+ case 0xF4: {
+ if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) {
+ return token_type::parse_error;
+ }
+ break;
+ }
+
+ // remaining bytes (80..C1 and F5..FF) are ill-formed
+ default: {
+ error_message = "invalid string: ill-formed UTF-8 byte";
+ return token_type::parse_error;
+ }
+ }
+ }
+ }
+
+ /*!
+ * @brief scan a comment
+ * @return whether comment could be scanned successfully
+ */
+ bool
+ scan_comment() {
+ switch (get()) {
+ // single-line comments skip input until a newline or EOF is read
+ case '/': {
+ while (true) {
+ switch (get()) {
+ case '\n':
+ case '\r':
+ case char_traits<char_type>::eof():
+ case '\0':
+ return true;
+
+ default:
+ break;
+ }
+ }
+ }
+
+ // multi-line comments skip input until */ is read
+ case '*': {
+ while (true) {
+ switch (get()) {
+ case char_traits<char_type>::eof():
+ case '\0': {
+ error_message = "invalid comment; missing closing '*/'";
+ return false;
+ }
+
+ case '*': {
+ switch (get()) {
+ case '/':
+ return true;
+
+ default: {
+ unget();
+ continue;
+ }
+ }
+ }
+
+ default:
+ continue;
+ }
+ }
+ }
+
+ // unexpected character after reading '/'
+ default: {
+ error_message = "invalid comment; expecting '/' or '*' after '/'";
+ return false;
+ }
+ }
+ }
+
+ JSON_HEDLEY_NON_NULL(2)
+ static void
+ strtof(float& f, const char* str, char** endptr) noexcept {
+ f = std::strtof(str, endptr);
+ }
+
+ JSON_HEDLEY_NON_NULL(2)
+ static void
+ strtof(double& f, const char* str, char** endptr) noexcept {
+ f = std::strtod(str, endptr);
+ }
+
+ JSON_HEDLEY_NON_NULL(2)
+ static void
+ strtof(long double& f, const char* str, char** endptr) noexcept {
+ f = std::strtold(str, endptr);
+ }
+
+ /*!
+ @brief scan a number literal
+
+ This function scans a string according to Sect. 6 of RFC 8259.
+
+ The function is realized with a deterministic finite state machine derived
+ from the grammar described in RFC 8259. Starting in state "init", the
+ input is read and used to determined the next state. Only state "done"
+ accepts the number. State "error" is a trap state to model errors. In the
+ table below, "anything" means any character but the ones listed before.
+
+ state | 0 | 1-9 | e E | + | - | . | anything
+ ---------|----------|----------|----------|---------|---------|----------|-----------
+ init | zero | any1 | [error] | [error] | minus | [error] | [error]
+ minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
+ zero | done | done | exponent | done | done | decimal1 | done
+ any1 | any1 | any1 | exponent | done | done | decimal1 | done
+ decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
+ decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
+ exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
+ sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
+ any2 | any2 | any2 | done | done | done | done | done
+
+ The state machine is realized with one label per state (prefixed with
+ "scan_number_") and `goto` statements between them. The state machine
+ contains cycles, but any cycle can be left when EOF is read. Therefore,
+ the function is guaranteed to terminate.
+
+ During scanning, the read bytes are stored in token_buffer. This string is
+ then converted to a signed integer, an unsigned integer, or a
+ floating-point number.
+
+ @return token_type::value_unsigned, token_type::value_integer, or
+ token_type::value_float if number could be successfully scanned,
+ token_type::parse_error otherwise
+
+ @note The scanner is independent of the current locale. Internally, the
+ locale's decimal point is used instead of `.` to work with the
+ locale-dependent converters.
+ */
+ token_type
+ scan_number() // lgtm [cpp/use-of-goto]
+ {
+ // reset token_buffer to store the number's bytes
+ reset();
+
+ // the type of the parsed number; initially set to unsigned; will be
+ // changed if minus sign, decimal point or exponent is read
+ token_type number_type = token_type::value_unsigned;
+
+ // state (init): we just found out we need to scan a number
+ switch (current) {
+ case '-': {
+ add(current);
+ goto scan_number_minus;
+ }
+
+ case '0': {
+ add(current);
+ goto scan_number_zero;
+ }
+
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ add(current);
+ goto scan_number_any1;
+ }
+
+ // all other characters are rejected outside scan_number()
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ }
+
+ scan_number_minus:
+ // state: we just parsed a leading minus sign
+ number_type = token_type::value_integer;
+ switch (get()) {
+ case '0': {
+ add(current);
+ goto scan_number_zero;
+ }
+
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ add(current);
+ goto scan_number_any1;
+ }
+
+ default: {
+ error_message = "invalid number; expected digit after '-'";
+ return token_type::parse_error;
+ }
+ }
+
+ scan_number_zero:
+ // state: we just parse a zero (maybe with a leading minus sign)
+ switch (get()) {
+ case '.': {
+ add(decimal_point_char);
+ goto scan_number_decimal1;
+ }
+
+ case 'e':
+ case 'E': {
+ add(current);
+ goto scan_number_exponent;
+ }
+
+ default:
+ goto scan_number_done;
+ }
+
+ scan_number_any1:
+ // state: we just parsed a number 0-9 (maybe with a leading minus sign)
+ switch (get()) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ add(current);
+ goto scan_number_any1;
+ }
+
+ case '.': {
+ add(decimal_point_char);
+ goto scan_number_decimal1;
+ }
+
+ case 'e':
+ case 'E': {
+ add(current);
+ goto scan_number_exponent;
+ }
+
+ default:
+ goto scan_number_done;
+ }
+
+ scan_number_decimal1:
+ // state: we just parsed a decimal point
+ number_type = token_type::value_float;
+ switch (get()) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ add(current);
+ goto scan_number_decimal2;
+ }
+
+ default: {
+ error_message = "invalid number; expected digit after '.'";
+ return token_type::parse_error;
+ }
+ }
+
+ scan_number_decimal2:
+ // we just parsed at least one number after a decimal point
+ switch (get()) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ add(current);
+ goto scan_number_decimal2;
+ }
+
+ case 'e':
+ case 'E': {
+ add(current);
+ goto scan_number_exponent;
+ }
+
+ default:
+ goto scan_number_done;
+ }
+
+ scan_number_exponent:
+ // we just parsed an exponent
+ number_type = token_type::value_float;
+ switch (get()) {
+ case '+':
+ case '-': {
+ add(current);
+ goto scan_number_sign;
+ }
+
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ add(current);
+ goto scan_number_any2;
+ }
+
+ default: {
+ error_message = "invalid number; expected '+', '-', or digit after exponent";
+ return token_type::parse_error;
+ }
+ }
+
+ scan_number_sign:
+ // we just parsed an exponent sign
+ switch (get()) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ add(current);
+ goto scan_number_any2;
+ }
+
+ default: {
+ error_message = "invalid number; expected digit after exponent sign";
+ return token_type::parse_error;
+ }
+ }
+
+ scan_number_any2:
+ // we just parsed a number after the exponent or exponent sign
+ switch (get()) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ add(current);
+ goto scan_number_any2;
+ }
+
+ default:
+ goto scan_number_done;
+ }
+
+ scan_number_done:
+ // unget the character after the number (we only read it to know that
+ // we are done scanning a number)
+ unget();
+
+ char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+ errno = 0;
+
+ // try to parse integers first and fall back to floats
+ if (number_type == token_type::value_unsigned) {
+ const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
+
+ // we checked the number format before
+ JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
+
+ if (errno == 0) {
+ value_unsigned = static_cast<number_unsigned_t>(x);
+ if (value_unsigned == x) {
+ return token_type::value_unsigned;
+ }
+ }
+ } else if (number_type == token_type::value_integer) {
+ const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
+
+ // we checked the number format before
+ JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
+
+ if (errno == 0) {
+ value_integer = static_cast<number_integer_t>(x);
+ if (value_integer == x) {
+ return token_type::value_integer;
+ }
+ }
+ }
+
+ // this code is reached if we parse a floating-point number or if an
+ // integer conversion above failed
+ strtof(value_float, token_buffer.data(), &endptr);
+
+ // we checked the number format before
+ JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
+
+ return token_type::value_float;
+ }
+
+ /*!
+ @param[in] literal_text the literal text to expect
+ @param[in] length the length of the passed literal text
+ @param[in] return_type the token type to return on success
+ */
+ JSON_HEDLEY_NON_NULL(2)
+ token_type
+ scan_literal(const char_type* literal_text, const std::size_t length, token_type return_type) {
+ JSON_ASSERT(char_traits<char_type>::to_char_type(current) == literal_text[0]);
+ for (std::size_t i = 1; i < length; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(char_traits<char_type>::to_char_type(get()) != literal_text[i])) {
+ error_message = "invalid literal";
+ return token_type::parse_error;
+ }
+ }
+ return return_type;
+ }
+
+ /////////////////////
+ // input management
+ /////////////////////
+
+ /// reset token_buffer; current character is beginning of token
+ void
+ reset() noexcept {
+ token_buffer.clear();
+ token_string.clear();
+ token_string.push_back(char_traits<char_type>::to_char_type(current));
+ }
+
+ /*
+ @brief get next character from the input
+
+ This function provides the interface to the used input adapter. It does
+ not throw in case the input reached EOF, but returns a
+ `char_traits<char>::eof()` in that case. Stores the scanned characters
+ for use in error messages.
+
+ @return character read from the input
+ */
+ char_int_type
+ get() {
+ ++position.chars_read_total;
+ ++position.chars_read_current_line;
+
+ if (next_unget) {
+ // just reset the next_unget variable and work with current
+ next_unget = false;
+ } else {
+ current = ia.get_character();
+ }
+
+ if (JSON_HEDLEY_LIKELY(current != char_traits<char_type>::eof())) {
+ token_string.push_back(char_traits<char_type>::to_char_type(current));
+ }
+
+ if (current == '\n') {
+ ++position.lines_read;
+ position.chars_read_current_line = 0;
+ }
+
+ return current;
+ }
+
+ /*!
+ @brief unget current character (read it again on next get)
+
+ We implement unget by setting variable next_unget to true. The input is not
+ changed - we just simulate ungetting by modifying chars_read_total,
+ chars_read_current_line, and token_string. The next call to get() will
+ behave as if the unget character is read again.
+ */
+ void
+ unget() {
+ next_unget = true;
+
+ --position.chars_read_total;
+
+ // in case we "unget" a newline, we have to also decrement the lines_read
+ if (position.chars_read_current_line == 0) {
+ if (position.lines_read > 0) {
+ --position.lines_read;
+ }
+ } else {
+ --position.chars_read_current_line;
+ }
+
+ if (JSON_HEDLEY_LIKELY(current != char_traits<char_type>::eof())) {
+ JSON_ASSERT(!token_string.empty());
+ token_string.pop_back();
+ }
+ }
+
+ /// add a character to token_buffer
+ void
+ add(char_int_type c) {
+ token_buffer.push_back(static_cast<typename string_t::value_type>(c));
+ }
+
+ public:
+ /////////////////////
+ // value getters
+ /////////////////////
+
+ /// return integer value
+ constexpr number_integer_t
+ get_number_integer() const noexcept {
+ return value_integer;
+ }
+
+ /// return unsigned integer value
+ constexpr number_unsigned_t
+ get_number_unsigned() const noexcept {
+ return value_unsigned;
+ }
+
+ /// return floating-point value
+ constexpr number_float_t
+ get_number_float() const noexcept {
+ return value_float;
+ }
+
+ /// return current string value (implicitly resets the token; useful only once)
+ string_t&
+ get_string() {
+ return token_buffer;
+ }
+
+ /////////////////////
+ // diagnostics
+ /////////////////////
+
+ /// return position of last read token
+ constexpr position_t
+ get_position() const noexcept {
+ return position;
+ }
+
+ /// return the last read token (for errors only). Will never contain EOF
+ /// (an arbitrary value that is not a valid char value, often -1), because
+ /// 255 may legitimately occur. May contain NUL, which should be escaped.
+ std::string
+ get_token_string() const {
+ // escape control characters
+ std::string result;
+ for (const auto c : token_string) {
+ if (static_cast<unsigned char>(c) <= '\x1F') {
+ // escape control characters
+ std::array<char, 9> cs{{}};
+ static_cast<void>((std::snprintf)(
+ cs.data(),
+ cs.size(),
+ "<U+%.4X>",
+ static_cast<unsigned char>(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+ result += cs.data();
+ } else {
+ // add character as is
+ result.push_back(static_cast<std::string::value_type>(c));
+ }
+ }
+
+ return result;
+ }
+
+ /// return syntax error message
+ JSON_HEDLEY_RETURNS_NON_NULL
+ constexpr const char*
+ get_error_message() const noexcept {
+ return error_message;
+ }
+
+ /////////////////////
+ // actual scanner
+ /////////////////////
+
+ /*!
+ @brief skip the UTF-8 byte order mark
+ @return true iff there is no BOM or the correct BOM has been skipped
+ */
+ bool
+ skip_bom() {
+ if (get() == 0xEF) {
+ // check if we completely parse the BOM
+ return get() == 0xBB && get() == 0xBF;
+ }
+
+ // the first character is not the beginning of the BOM; unget it to
+ // process is later
+ unget();
+ return true;
+ }
+
+ void
+ skip_whitespace() {
+ do {
+ get();
+ } while (current == ' ' || current == '\t' || current == '\n' || current == '\r');
+ }
+
+ token_type
+ scan() {
+ // initially, skip the BOM
+ if (position.chars_read_total == 0 && !skip_bom()) {
+ error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
+ return token_type::parse_error;
+ }
+
+ // read next character and ignore whitespace
+ skip_whitespace();
+
+ // ignore comments
+ while (ignore_comments && current == '/') {
+ if (!scan_comment()) {
+ return token_type::parse_error;
+ }
+
+ // skip following whitespace
+ skip_whitespace();
+ }
+
+ switch (current) {
+ // structural characters
+ case '[':
+ return token_type::begin_array;
+ case ']':
+ return token_type::end_array;
+ case '{':
+ return token_type::begin_object;
+ case '}':
+ return token_type::end_object;
+ case ':':
+ return token_type::name_separator;
+ case ',':
+ return token_type::value_separator;
+
+ // literals
+ case 't': {
+ std::array<char_type, 4> true_literal = {{static_cast<char_type>('t'),
+ static_cast<char_type>('r'),
+ static_cast<char_type>('u'),
+ static_cast<char_type>('e')}};
+ return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true);
+ }
+ case 'f': {
+ std::array<char_type, 5> false_literal = {{static_cast<char_type>('f'),
+ static_cast<char_type>('a'),
+ static_cast<char_type>('l'),
+ static_cast<char_type>('s'),
+ static_cast<char_type>('e')}};
+ return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false);
+ }
+ case 'n': {
+ std::array<char_type, 4> null_literal = {{static_cast<char_type>('n'),
+ static_cast<char_type>('u'),
+ static_cast<char_type>('l'),
+ static_cast<char_type>('l')}};
+ return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null);
+ }
+
+ // string
+ case '\"':
+ return scan_string();
+
+ // number
+ case '-':
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ return scan_number();
+
+ // end of input (the null byte is needed when parsing from
+ // string literals)
+ case '\0':
+ case char_traits<char_type>::eof():
+ return token_type::end_of_input;
+
+ // error
+ default:
+ error_message = "invalid literal";
+ return token_type::parse_error;
+ }
+ }
+
+ private:
+ /// input adapter
+ InputAdapterType ia;
+
+ /// whether comments should be ignored (true) or signaled as errors (false)
+ const bool ignore_comments = false;
+
+ /// the current character
+ char_int_type current = char_traits<char_type>::eof();
+
+ /// whether the next get() call should just return current
+ bool next_unget = false;
+
+ /// the start position of the current token
+ position_t position{};
+
+ /// raw input token string (for error messages)
+ std::vector<char_type> token_string{};
+
+ /// buffer for variable-length tokens (numbers, strings)
+ string_t token_buffer{};
+
+ /// a description of occurred lexer errors
+ const char* error_message = "";
+
+ // number values
+ number_integer_t value_integer = 0;
+ number_unsigned_t value_unsigned = 0;
+ number_float_t value_float = 0;
+
+ /// the decimal point
+ const char_int_type decimal_point_char = '.';
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/is_sax.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstdint> // size_t
+#include <utility> // declval
+#include <string> // string
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+// #include <nlohmann/detail/meta/detected.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+template <typename T>
+using null_function_t = decltype(std::declval<T&>().null());
+
+template <typename T>
+using boolean_function_t = decltype(std::declval<T&>().boolean(std::declval<bool>()));
+
+template <typename T, typename Integer>
+using number_integer_function_t = decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
+
+template <typename T, typename Unsigned>
+using number_unsigned_function_t = decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
+
+template <typename T, typename Float, typename String>
+using number_float_function_t =
+ decltype(std::declval<T&>().number_float(std::declval<Float>(), std::declval<const String&>()));
+
+template <typename T, typename String>
+using string_function_t = decltype(std::declval<T&>().string(std::declval<String&>()));
+
+template <typename T, typename Binary>
+using binary_function_t = decltype(std::declval<T&>().binary(std::declval<Binary&>()));
+
+template <typename T>
+using start_object_function_t = decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
+
+template <typename T, typename String>
+using key_function_t = decltype(std::declval<T&>().key(std::declval<String&>()));
+
+template <typename T>
+using end_object_function_t = decltype(std::declval<T&>().end_object());
+
+template <typename T>
+using start_array_function_t = decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
+
+template <typename T>
+using end_array_function_t = decltype(std::declval<T&>().end_array());
+
+template <typename T, typename Exception>
+using parse_error_function_t = decltype(std::declval<T&>().parse_error(std::declval<std::size_t>(),
+ std::declval<const std::string&>(),
+ std::declval<const Exception&>()));
+
+template <typename SAX, typename BasicJsonType>
+struct is_sax {
+ private:
+ static_assert(is_basic_json<BasicJsonType>::value, "BasicJsonType must be of type basic_json<...>");
+
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using string_t = typename BasicJsonType::string_t;
+ using binary_t = typename BasicJsonType::binary_t;
+ using exception_t = typename BasicJsonType::exception;
+
+ public:
+ static constexpr bool value =
+ is_detected_exact<bool, null_function_t, SAX>::value &&
+ is_detected_exact<bool, boolean_function_t, SAX>::value &&
+ is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value &&
+ is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value &&
+ is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value &&
+ is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
+ is_detected_exact<bool, binary_function_t, SAX, binary_t>::value &&
+ is_detected_exact<bool, start_object_function_t, SAX>::value &&
+ is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
+ is_detected_exact<bool, end_object_function_t, SAX>::value &&
+ is_detected_exact<bool, start_array_function_t, SAX>::value &&
+ is_detected_exact<bool, end_array_function_t, SAX>::value &&
+ is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
+};
+
+template <typename SAX, typename BasicJsonType>
+struct is_sax_static_asserts {
+ private:
+ static_assert(is_basic_json<BasicJsonType>::value, "BasicJsonType must be of type basic_json<...>");
+
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using string_t = typename BasicJsonType::string_t;
+ using binary_t = typename BasicJsonType::binary_t;
+ using exception_t = typename BasicJsonType::exception;
+
+ public:
+ static_assert(is_detected_exact<bool, null_function_t, SAX>::value, "Missing/invalid function: bool null()");
+ static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
+ "Missing/invalid function: bool boolean(bool)");
+ static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
+ "Missing/invalid function: bool boolean(bool)");
+ static_assert(is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value,
+ "Missing/invalid function: bool number_integer(number_integer_t)");
+ static_assert(is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value,
+ "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
+ static_assert(is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value,
+ "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
+ static_assert(is_detected_exact<bool, string_function_t, SAX, string_t>::value,
+ "Missing/invalid function: bool string(string_t&)");
+ static_assert(is_detected_exact<bool, binary_function_t, SAX, binary_t>::value,
+ "Missing/invalid function: bool binary(binary_t&)");
+ static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
+ "Missing/invalid function: bool start_object(std::size_t)");
+ static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
+ "Missing/invalid function: bool key(string_t&)");
+ static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
+ "Missing/invalid function: bool end_object()");
+ static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
+ "Missing/invalid function: bool start_array(std::size_t)");
+ static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
+ "Missing/invalid function: bool end_array()");
+ static_assert(is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
+ "Missing/invalid function: bool parse_error(std::size_t, const "
+ "std::string&, const exception&)");
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/string_concat.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+/// how to treat CBOR tags
+enum class cbor_tag_handler_t {
+ error, ///< throw a parse_error exception in case of a tag
+ ignore, ///< ignore tags
+ store ///< store tags as binary type
+};
+
+/*!
+@brief determine system byte order
+
+@return true if and only if system's byte order is little endian
+
+@note from https://stackoverflow.com/a/1001328/266378
+*/
+static inline bool
+little_endianness(int num = 1) noexcept {
+ return *reinterpret_cast<char*>(&num) == 1;
+}
+
+///////////////////
+// binary reader //
+///////////////////
+
+/*!
+@brief deserialization of CBOR, MessagePack, and UBJSON values
+*/
+template <typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
+class binary_reader {
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using string_t = typename BasicJsonType::string_t;
+ using binary_t = typename BasicJsonType::binary_t;
+ using json_sax_t = SAX;
+ using char_type = typename InputAdapterType::char_type;
+ using char_int_type = typename char_traits<char_type>::int_type;
+
+ public:
+ /*!
+ @brief create a binary reader
+
+ @param[in] adapter input adapter to read from
+ */
+ explicit binary_reader(InputAdapterType&& adapter, const input_format_t format = input_format_t::json) noexcept
+ : ia(std::move(adapter)), input_format(format) {
+ (void)detail::is_sax_static_asserts<SAX, BasicJsonType>{};
+ }
+
+ // make class move-only
+ binary_reader(const binary_reader&) = delete;
+ binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+ binary_reader&
+ operator=(const binary_reader&) = delete;
+ binary_reader&
+ operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+ ~binary_reader() = default;
+
+ /*!
+ @param[in] format the binary format to parse
+ @param[in] sax_ a SAX event processor
+ @param[in] strict whether to expect the input to be consumed completed
+ @param[in] tag_handler how to treat CBOR tags
+
+ @return whether parsing was successful
+ */
+ JSON_HEDLEY_NON_NULL(3)
+ bool
+ sax_parse(const input_format_t format,
+ json_sax_t* sax_,
+ const bool strict = true,
+ const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) {
+ sax = sax_;
+ bool result = false;
+
+ switch (format) {
+ case input_format_t::bson:
+ result = parse_bson_internal();
+ break;
+
+ case input_format_t::cbor:
+ result = parse_cbor_internal(true, tag_handler);
+ break;
+
+ case input_format_t::msgpack:
+ result = parse_msgpack_internal();
+ break;
+
+ case input_format_t::ubjson:
+ case input_format_t::bjdata:
+ result = parse_ubjson_internal();
+ break;
+
+ case input_format_t::json: // LCOV_EXCL_LINE
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ }
+
+ // strict mode: next byte must be EOF
+ if (result && strict) {
+ if (input_format == input_format_t::ubjson || input_format == input_format_t::bjdata) {
+ get_ignore_noop();
+ } else {
+ get();
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(current != char_traits<char_type>::eof())) {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ parse_error::create(
+ 110,
+ chars_read,
+ exception_message(
+ input_format, concat("expected end of input; last byte: 0x", get_token_string()), "value"),
+ nullptr));
+ }
+ }
+
+ return result;
+ }
+
+ private:
+ //////////
+ // BSON //
+ //////////
+
+ /*!
+ @brief Reads in a BSON-object and passes it to the SAX-parser.
+ @return whether a valid BSON-value was passed to the SAX parser
+ */
+ bool
+ parse_bson_internal() {
+ std::int32_t document_size{};
+ get_number<std::int32_t, true>(input_format_t::bson, document_size);
+
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast<std::size_t>(-1)))) {
+ return false;
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/ false))) {
+ return false;
+ }
+
+ return sax->end_object();
+ }
+
+ /*!
+ @brief Parses a C-style string from the BSON input.
+ @param[in,out] result A reference to the string variable where the read
+ string is to be stored.
+ @return `true` if the \x00-byte indicating the end of the string was
+ encountered before the EOF; false` indicates an unexpected EOF.
+ */
+ bool
+ get_bson_cstr(string_t& result) {
+ auto out = std::back_inserter(result);
+ while (true) {
+ get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) {
+ return false;
+ }
+ if (current == 0x00) {
+ return true;
+ }
+ *out++ = static_cast<typename string_t::value_type>(current);
+ }
+ }
+
+ /*!
+ @brief Parses a zero-terminated string of length @a len from the BSON
+ input.
+ @param[in] len The length (including the zero-byte at the end) of the
+ string to be read.
+ @param[in,out] result A reference to the string variable where the read
+ string is to be stored.
+ @tparam NumberType The type of the length @a len
+ @pre len >= 1
+ @return `true` if the string was successfully parsed
+ */
+ template <typename NumberType>
+ bool
+ get_bson_string(const NumberType len, string_t& result) {
+ if (JSON_HEDLEY_UNLIKELY(len < 1)) {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 112,
+ chars_read,
+ exception_message(input_format_t::bson,
+ concat("string length must be at least 1, is ", std::to_string(len)),
+ "string"),
+ nullptr));
+ }
+
+ return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) &&
+ get() != char_traits<char_type>::eof();
+ }
+
+ /*!
+ @brief Parses a byte array input of length @a len from the BSON input.
+ @param[in] len The length of the byte array to be read.
+ @param[in,out] result A reference to the binary variable where the read
+ array is to be stored.
+ @tparam NumberType The type of the length @a len
+ @pre len >= 0
+ @return `true` if the byte array was successfully parsed
+ */
+ template <typename NumberType>
+ bool
+ get_bson_binary(const NumberType len, binary_t& result) {
+ if (JSON_HEDLEY_UNLIKELY(len < 0)) {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 112,
+ chars_read,
+ exception_message(input_format_t::bson,
+ concat("byte array length cannot be negative, is ", std::to_string(len)),
+ "binary"),
+ nullptr));
+ }
+
+ // All BSON binary values have a subtype
+ std::uint8_t subtype{};
+ get_number<std::uint8_t>(input_format_t::bson, subtype);
+ result.set_subtype(subtype);
+
+ return get_binary(input_format_t::bson, len, result);
+ }
+
+ /*!
+ @brief Read a BSON document element of the given @a element_type.
+ @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
+ @param[in] element_type_parse_position The position in the input stream,
+ where the `element_type` was read.
+ @warning Not all BSON element types are supported yet. An unsupported
+ @a element_type will give rise to a parse_error.114:
+ Unsupported BSON record type 0x...
+ @return whether a valid BSON-object/array was passed to the SAX parser
+ */
+ bool
+ parse_bson_element_internal(const char_int_type element_type, const std::size_t element_type_parse_position) {
+ switch (element_type) {
+ case 0x01: // double
+ {
+ double number{};
+ return get_number<double, true>(input_format_t::bson, number) &&
+ sax->number_float(static_cast<number_float_t>(number), "");
+ }
+
+ case 0x02: // string
+ {
+ std::int32_t len{};
+ string_t value;
+ return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_string(len, value) &&
+ sax->string(value);
+ }
+
+ case 0x03: // object
+ {
+ return parse_bson_internal();
+ }
+
+ case 0x04: // array
+ {
+ return parse_bson_array();
+ }
+
+ case 0x05: // binary
+ {
+ std::int32_t len{};
+ binary_t value;
+ return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_binary(len, value) &&
+ sax->binary(value);
+ }
+
+ case 0x08: // boolean
+ {
+ return sax->boolean(get() != 0);
+ }
+
+ case 0x0A: // null
+ {
+ return sax->null();
+ }
+
+ case 0x10: // int32
+ {
+ std::int32_t value{};
+ return get_number<std::int32_t, true>(input_format_t::bson, value) && sax->number_integer(value);
+ }
+
+ case 0x12: // int64
+ {
+ std::int64_t value{};
+ return get_number<std::int64_t, true>(input_format_t::bson, value) && sax->number_integer(value);
+ }
+
+ default: // anything else not supported (yet)
+ {
+ std::array<char, 3> cr{{}};
+ static_cast<void>(
+ (std::snprintf)(cr.data(),
+ cr.size(),
+ "%.2hhX",
+ static_cast<unsigned char>(
+ element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+ const std::string cr_str{cr.data()};
+ return sax->parse_error(
+ element_type_parse_position,
+ cr_str,
+ parse_error::create(
+ 114, element_type_parse_position, concat("Unsupported BSON record type 0x", cr_str), nullptr));
+ }
+ }
+ }
+
+ /*!
+ @brief Read a BSON element list (as specified in the BSON-spec)
+
+ The same binary layout is used for objects and arrays, hence it must be
+ indicated with the argument @a is_array which one is expected
+ (true --> array, false --> object).
+
+ @param[in] is_array Determines if the element list being read is to be
+ treated as an object (@a is_array == false), or as an
+ array (@a is_array == true).
+ @return whether a valid BSON-object/array was passed to the SAX parser
+ */
+ bool
+ parse_bson_element_list(const bool is_array) {
+ string_t key;
+
+ while (auto element_type = get()) {
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) {
+ return false;
+ }
+
+ const std::size_t element_type_parse_position = chars_read;
+ if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) {
+ return false;
+ }
+
+ if (!is_array && !sax->key(key)) {
+ return false;
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) {
+ return false;
+ }
+
+ // get_bson_cstr only appends
+ key.clear();
+ }
+
+ return true;
+ }
+
+ /*!
+ @brief Reads an array from the BSON input and passes it to the SAX-parser.
+ @return whether a valid BSON-array was passed to the SAX parser
+ */
+ bool
+ parse_bson_array() {
+ std::int32_t document_size{};
+ get_number<std::int32_t, true>(input_format_t::bson, document_size);
+
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast<std::size_t>(-1)))) {
+ return false;
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/ true))) {
+ return false;
+ }
+
+ return sax->end_array();
+ }
+
+ //////////
+ // CBOR //
+ //////////
+
+ /*!
+ @param[in] get_char whether a new character should be retrieved from the
+ input (true) or whether the last read character should
+ be considered instead (false)
+ @param[in] tag_handler how CBOR tags should be treated
+
+ @return whether a valid CBOR value was passed to the SAX parser
+ */
+ bool
+ parse_cbor_internal(const bool get_char, const cbor_tag_handler_t tag_handler) {
+ switch (get_char ? get() : current) {
+ // EOF
+ case char_traits<char_type>::eof():
+ return unexpect_eof(input_format_t::cbor, "value");
+
+ // Integer 0x00..0x17 (0..23)
+ case 0x00:
+ case 0x01:
+ case 0x02:
+ case 0x03:
+ case 0x04:
+ case 0x05:
+ case 0x06:
+ case 0x07:
+ case 0x08:
+ case 0x09:
+ case 0x0A:
+ case 0x0B:
+ case 0x0C:
+ case 0x0D:
+ case 0x0E:
+ case 0x0F:
+ case 0x10:
+ case 0x11:
+ case 0x12:
+ case 0x13:
+ case 0x14:
+ case 0x15:
+ case 0x16:
+ case 0x17:
+ return sax->number_unsigned(static_cast<number_unsigned_t>(current));
+
+ case 0x18: // Unsigned integer (one-byte uint8_t follows)
+ {
+ std::uint8_t number{};
+ return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
+ }
+
+ case 0x19: // Unsigned integer (two-byte uint16_t follows)
+ {
+ std::uint16_t number{};
+ return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
+ }
+
+ case 0x1A: // Unsigned integer (four-byte uint32_t follows)
+ {
+ std::uint32_t number{};
+ return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
+ }
+
+ case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
+ {
+ std::uint64_t number{};
+ return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
+ }
+
+ // Negative integer -1-0x00..-1-0x17 (-1..-24)
+ case 0x20:
+ case 0x21:
+ case 0x22:
+ case 0x23:
+ case 0x24:
+ case 0x25:
+ case 0x26:
+ case 0x27:
+ case 0x28:
+ case 0x29:
+ case 0x2A:
+ case 0x2B:
+ case 0x2C:
+ case 0x2D:
+ case 0x2E:
+ case 0x2F:
+ case 0x30:
+ case 0x31:
+ case 0x32:
+ case 0x33:
+ case 0x34:
+ case 0x35:
+ case 0x36:
+ case 0x37:
+ return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
+
+ case 0x38: // Negative integer (one-byte uint8_t follows)
+ {
+ std::uint8_t number{};
+ return get_number(input_format_t::cbor, number) &&
+ sax->number_integer(static_cast<number_integer_t>(-1) - number);
+ }
+
+ case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
+ {
+ std::uint16_t number{};
+ return get_number(input_format_t::cbor, number) &&
+ sax->number_integer(static_cast<number_integer_t>(-1) - number);
+ }
+
+ case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
+ {
+ std::uint32_t number{};
+ return get_number(input_format_t::cbor, number) &&
+ sax->number_integer(static_cast<number_integer_t>(-1) - number);
+ }
+
+ case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
+ {
+ std::uint64_t number{};
+ return get_number(input_format_t::cbor, number) &&
+ sax->number_integer(static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(number));
+ }
+
+ // Binary data (0x00..0x17 bytes follow)
+ case 0x40:
+ case 0x41:
+ case 0x42:
+ case 0x43:
+ case 0x44:
+ case 0x45:
+ case 0x46:
+ case 0x47:
+ case 0x48:
+ case 0x49:
+ case 0x4A:
+ case 0x4B:
+ case 0x4C:
+ case 0x4D:
+ case 0x4E:
+ case 0x4F:
+ case 0x50:
+ case 0x51:
+ case 0x52:
+ case 0x53:
+ case 0x54:
+ case 0x55:
+ case 0x56:
+ case 0x57:
+ case 0x58: // Binary data (one-byte uint8_t for n follows)
+ case 0x59: // Binary data (two-byte uint16_t for n follow)
+ case 0x5A: // Binary data (four-byte uint32_t for n follow)
+ case 0x5B: // Binary data (eight-byte uint64_t for n follow)
+ case 0x5F: // Binary data (indefinite length)
+ {
+ binary_t b;
+ return get_cbor_binary(b) && sax->binary(b);
+ }
+
+ // UTF-8 string (0x00..0x17 bytes follow)
+ case 0x60:
+ case 0x61:
+ case 0x62:
+ case 0x63:
+ case 0x64:
+ case 0x65:
+ case 0x66:
+ case 0x67:
+ case 0x68:
+ case 0x69:
+ case 0x6A:
+ case 0x6B:
+ case 0x6C:
+ case 0x6D:
+ case 0x6E:
+ case 0x6F:
+ case 0x70:
+ case 0x71:
+ case 0x72:
+ case 0x73:
+ case 0x74:
+ case 0x75:
+ case 0x76:
+ case 0x77:
+ case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
+ case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
+ case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
+ case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
+ case 0x7F: // UTF-8 string (indefinite length)
+ {
+ string_t s;
+ return get_cbor_string(s) && sax->string(s);
+ }
+
+ // array (0x00..0x17 data items follow)
+ case 0x80:
+ case 0x81:
+ case 0x82:
+ case 0x83:
+ case 0x84:
+ case 0x85:
+ case 0x86:
+ case 0x87:
+ case 0x88:
+ case 0x89:
+ case 0x8A:
+ case 0x8B:
+ case 0x8C:
+ case 0x8D:
+ case 0x8E:
+ case 0x8F:
+ case 0x90:
+ case 0x91:
+ case 0x92:
+ case 0x93:
+ case 0x94:
+ case 0x95:
+ case 0x96:
+ case 0x97:
+ return get_cbor_array(conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu),
+ tag_handler);
+
+ case 0x98: // array (one-byte uint8_t for n follows)
+ {
+ std::uint8_t len{};
+ return get_number(input_format_t::cbor, len) &&
+ get_cbor_array(static_cast<std::size_t>(len), tag_handler);
+ }
+
+ case 0x99: // array (two-byte uint16_t for n follow)
+ {
+ std::uint16_t len{};
+ return get_number(input_format_t::cbor, len) &&
+ get_cbor_array(static_cast<std::size_t>(len), tag_handler);
+ }
+
+ case 0x9A: // array (four-byte uint32_t for n follow)
+ {
+ std::uint32_t len{};
+ return get_number(input_format_t::cbor, len) &&
+ get_cbor_array(conditional_static_cast<std::size_t>(len), tag_handler);
+ }
+
+ case 0x9B: // array (eight-byte uint64_t for n follow)
+ {
+ std::uint64_t len{};
+ return get_number(input_format_t::cbor, len) &&
+ get_cbor_array(conditional_static_cast<std::size_t>(len), tag_handler);
+ }
+
+ case 0x9F: // array (indefinite length)
+ return get_cbor_array(static_cast<std::size_t>(-1), tag_handler);
+
+ // map (0x00..0x17 pairs of data items follow)
+ case 0xA0:
+ case 0xA1:
+ case 0xA2:
+ case 0xA3:
+ case 0xA4:
+ case 0xA5:
+ case 0xA6:
+ case 0xA7:
+ case 0xA8:
+ case 0xA9:
+ case 0xAA:
+ case 0xAB:
+ case 0xAC:
+ case 0xAD:
+ case 0xAE:
+ case 0xAF:
+ case 0xB0:
+ case 0xB1:
+ case 0xB2:
+ case 0xB3:
+ case 0xB4:
+ case 0xB5:
+ case 0xB6:
+ case 0xB7:
+ return get_cbor_object(conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu),
+ tag_handler);
+
+ case 0xB8: // map (one-byte uint8_t for n follows)
+ {
+ std::uint8_t len{};
+ return get_number(input_format_t::cbor, len) &&
+ get_cbor_object(static_cast<std::size_t>(len), tag_handler);
+ }
+
+ case 0xB9: // map (two-byte uint16_t for n follow)
+ {
+ std::uint16_t len{};
+ return get_number(input_format_t::cbor, len) &&
+ get_cbor_object(static_cast<std::size_t>(len), tag_handler);
+ }
+
+ case 0xBA: // map (four-byte uint32_t for n follow)
+ {
+ std::uint32_t len{};
+ return get_number(input_format_t::cbor, len) &&
+ get_cbor_object(conditional_static_cast<std::size_t>(len), tag_handler);
+ }
+
+ case 0xBB: // map (eight-byte uint64_t for n follow)
+ {
+ std::uint64_t len{};
+ return get_number(input_format_t::cbor, len) &&
+ get_cbor_object(conditional_static_cast<std::size_t>(len), tag_handler);
+ }
+
+ case 0xBF: // map (indefinite length)
+ return get_cbor_object(static_cast<std::size_t>(-1), tag_handler);
+
+ case 0xC6: // tagged item
+ case 0xC7:
+ case 0xC8:
+ case 0xC9:
+ case 0xCA:
+ case 0xCB:
+ case 0xCC:
+ case 0xCD:
+ case 0xCE:
+ case 0xCF:
+ case 0xD0:
+ case 0xD1:
+ case 0xD2:
+ case 0xD3:
+ case 0xD4:
+ case 0xD8: // tagged item (1 bytes follow)
+ case 0xD9: // tagged item (2 bytes follow)
+ case 0xDA: // tagged item (4 bytes follow)
+ case 0xDB: // tagged item (8 bytes follow)
+ {
+ switch (tag_handler) {
+ case cbor_tag_handler_t::error: {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 112,
+ chars_read,
+ exception_message(
+ input_format_t::cbor, concat("invalid byte: 0x", last_token), "value"),
+ nullptr));
+ }
+
+ case cbor_tag_handler_t::ignore: {
+ // ignore binary subtype
+ switch (current) {
+ case 0xD8: {
+ std::uint8_t subtype_to_ignore{};
+ get_number(input_format_t::cbor, subtype_to_ignore);
+ break;
+ }
+ case 0xD9: {
+ std::uint16_t subtype_to_ignore{};
+ get_number(input_format_t::cbor, subtype_to_ignore);
+ break;
+ }
+ case 0xDA: {
+ std::uint32_t subtype_to_ignore{};
+ get_number(input_format_t::cbor, subtype_to_ignore);
+ break;
+ }
+ case 0xDB: {
+ std::uint64_t subtype_to_ignore{};
+ get_number(input_format_t::cbor, subtype_to_ignore);
+ break;
+ }
+ default:
+ break;
+ }
+ return parse_cbor_internal(true, tag_handler);
+ }
+
+ case cbor_tag_handler_t::store: {
+ binary_t b;
+ // use binary subtype and store in binary container
+ switch (current) {
+ case 0xD8: {
+ std::uint8_t subtype{};
+ get_number(input_format_t::cbor, subtype);
+ b.set_subtype(
+ detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
+ break;
+ }
+ case 0xD9: {
+ std::uint16_t subtype{};
+ get_number(input_format_t::cbor, subtype);
+ b.set_subtype(
+ detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
+ break;
+ }
+ case 0xDA: {
+ std::uint32_t subtype{};
+ get_number(input_format_t::cbor, subtype);
+ b.set_subtype(
+ detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
+ break;
+ }
+ case 0xDB: {
+ std::uint64_t subtype{};
+ get_number(input_format_t::cbor, subtype);
+ b.set_subtype(
+ detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
+ break;
+ }
+ default:
+ return parse_cbor_internal(true, tag_handler);
+ }
+ get();
+ return get_cbor_binary(b) && sax->binary(b);
+ }
+
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(
+ false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ return false; // LCOV_EXCL_LINE
+ }
+ }
+
+ case 0xF4: // false
+ return sax->boolean(false);
+
+ case 0xF5: // true
+ return sax->boolean(true);
+
+ case 0xF6: // null
+ return sax->null();
+
+ case 0xF9: // Half-Precision Float (two-byte IEEE 754)
+ {
+ const auto byte1_raw = get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) {
+ return false;
+ }
+ const auto byte2_raw = get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) {
+ return false;
+ }
+
+ const auto byte1 = static_cast<unsigned char>(byte1_raw);
+ const auto byte2 = static_cast<unsigned char>(byte2_raw);
+
+ // code from RFC 7049, Appendix D, Figure 3:
+ // As half-precision floating-point numbers were only added
+ // to IEEE 754 in 2008, today's programming platforms often
+ // still only have limited support for them. It is very
+ // easy to include at least decoding support for them even
+ // without such support. An example of a small decoder for
+ // half-precision floating-point numbers in the C language
+ // is shown in Fig. 3.
+ const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
+ const double val = [&half] {
+ const int exp = (half >> 10u) & 0x1Fu;
+ const unsigned int mant = half & 0x3FFu;
+ JSON_ASSERT(0 <= exp && exp <= 32);
+ JSON_ASSERT(mant <= 1024);
+ switch (exp) {
+ case 0:
+ return std::ldexp(mant, -24);
+ case 31:
+ return (mant == 0) ? std::numeric_limits<double>::infinity()
+ : std::numeric_limits<double>::quiet_NaN();
+ default:
+ return std::ldexp(mant + 1024, exp - 25);
+ }
+ }();
+ return sax->number_float(
+ (half & 0x8000u) != 0 ? static_cast<number_float_t>(-val) : static_cast<number_float_t>(val), "");
+ }
+
+ case 0xFA: // Single-Precision Float (four-byte IEEE 754)
+ {
+ float number{};
+ return get_number(input_format_t::cbor, number) &&
+ sax->number_float(static_cast<number_float_t>(number), "");
+ }
+
+ case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
+ {
+ double number{};
+ return get_number(input_format_t::cbor, number) &&
+ sax->number_float(static_cast<number_float_t>(number), "");
+ }
+
+ default: // anything else (0xFF is handled inside the other types)
+ {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 112,
+ chars_read,
+ exception_message(input_format_t::cbor, concat("invalid byte: 0x", last_token), "value"),
+ nullptr));
+ }
+ }
+ }
+
+ /*!
+ @brief reads a CBOR string
+
+ This function first reads starting bytes to determine the expected
+ string length and then copies this number of bytes into a string.
+ Additionally, CBOR's strings with indefinite lengths are supported.
+
+ @param[out] result created string
+
+ @return whether string creation completed
+ */
+ bool
+ get_cbor_string(string_t& result) {
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) {
+ return false;
+ }
+
+ switch (current) {
+ // UTF-8 string (0x00..0x17 bytes follow)
+ case 0x60:
+ case 0x61:
+ case 0x62:
+ case 0x63:
+ case 0x64:
+ case 0x65:
+ case 0x66:
+ case 0x67:
+ case 0x68:
+ case 0x69:
+ case 0x6A:
+ case 0x6B:
+ case 0x6C:
+ case 0x6D:
+ case 0x6E:
+ case 0x6F:
+ case 0x70:
+ case 0x71:
+ case 0x72:
+ case 0x73:
+ case 0x74:
+ case 0x75:
+ case 0x76:
+ case 0x77: {
+ return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
+ }
+
+ case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
+ {
+ std::uint8_t len{};
+ return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
+ }
+
+ case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
+ {
+ std::uint16_t len{};
+ return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
+ }
+
+ case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
+ {
+ std::uint32_t len{};
+ return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
+ }
+
+ case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
+ {
+ std::uint64_t len{};
+ return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
+ }
+
+ case 0x7F: // UTF-8 string (indefinite length)
+ {
+ while (get() != 0xFF) {
+ string_t chunk;
+ if (!get_cbor_string(chunk)) {
+ return false;
+ }
+ result.append(chunk);
+ }
+ return true;
+ }
+
+ default: {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(113,
+ chars_read,
+ exception_message(input_format_t::cbor,
+ concat("expected length specification (0x60-0x7B) or "
+ "indefinite string type (0x7F); last byte: 0x",
+ last_token),
+ "string"),
+ nullptr));
+ }
+ }
+ }
+
+ /*!
+ @brief reads a CBOR byte array
+
+ This function first reads starting bytes to determine the expected
+ byte array length and then copies this number of bytes into the byte array.
+ Additionally, CBOR's byte arrays with indefinite lengths are supported.
+
+ @param[out] result created byte array
+
+ @return whether byte array creation completed
+ */
+ bool
+ get_cbor_binary(binary_t& result) {
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) {
+ return false;
+ }
+
+ switch (current) {
+ // Binary data (0x00..0x17 bytes follow)
+ case 0x40:
+ case 0x41:
+ case 0x42:
+ case 0x43:
+ case 0x44:
+ case 0x45:
+ case 0x46:
+ case 0x47:
+ case 0x48:
+ case 0x49:
+ case 0x4A:
+ case 0x4B:
+ case 0x4C:
+ case 0x4D:
+ case 0x4E:
+ case 0x4F:
+ case 0x50:
+ case 0x51:
+ case 0x52:
+ case 0x53:
+ case 0x54:
+ case 0x55:
+ case 0x56:
+ case 0x57: {
+ return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
+ }
+
+ case 0x58: // Binary data (one-byte uint8_t for n follows)
+ {
+ std::uint8_t len{};
+ return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result);
+ }
+
+ case 0x59: // Binary data (two-byte uint16_t for n follow)
+ {
+ std::uint16_t len{};
+ return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result);
+ }
+
+ case 0x5A: // Binary data (four-byte uint32_t for n follow)
+ {
+ std::uint32_t len{};
+ return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result);
+ }
+
+ case 0x5B: // Binary data (eight-byte uint64_t for n follow)
+ {
+ std::uint64_t len{};
+ return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result);
+ }
+
+ case 0x5F: // Binary data (indefinite length)
+ {
+ while (get() != 0xFF) {
+ binary_t chunk;
+ if (!get_cbor_binary(chunk)) {
+ return false;
+ }
+ result.insert(result.end(), chunk.begin(), chunk.end());
+ }
+ return true;
+ }
+
+ default: {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(113,
+ chars_read,
+ exception_message(input_format_t::cbor,
+ concat("expected length specification (0x40-0x5B) or "
+ "indefinite binary array type (0x5F); last byte: 0x",
+ last_token),
+ "binary"),
+ nullptr));
+ }
+ }
+ }
+
+ /*!
+ @param[in] len the length of the array or static_cast<std::size_t>(-1) for an
+ array of indefinite size
+ @param[in] tag_handler how CBOR tags should be treated
+ @return whether array creation completed
+ */
+ bool
+ get_cbor_array(const std::size_t len, const cbor_tag_handler_t tag_handler) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) {
+ return false;
+ }
+
+ if (len != static_cast<std::size_t>(-1)) {
+ for (std::size_t i = 0; i < len; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) {
+ return false;
+ }
+ }
+ } else {
+ while (get() != 0xFF) {
+ if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) {
+ return false;
+ }
+ }
+ }
+
+ return sax->end_array();
+ }
+
+ /*!
+ @param[in] len the length of the object or static_cast<std::size_t>(-1) for an
+ object of indefinite size
+ @param[in] tag_handler how CBOR tags should be treated
+ @return whether object creation completed
+ */
+ bool
+ get_cbor_object(const std::size_t len, const cbor_tag_handler_t tag_handler) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) {
+ return false;
+ }
+
+ if (len != 0) {
+ string_t key;
+ if (len != static_cast<std::size_t>(-1)) {
+ for (std::size_t i = 0; i < len; ++i) {
+ get();
+ if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) {
+ return false;
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) {
+ return false;
+ }
+ key.clear();
+ }
+ } else {
+ while (get() != 0xFF) {
+ if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) {
+ return false;
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) {
+ return false;
+ }
+ key.clear();
+ }
+ }
+ }
+
+ return sax->end_object();
+ }
+
+ /////////////
+ // MsgPack //
+ /////////////
+
+ /*!
+ @return whether a valid MessagePack value was passed to the SAX parser
+ */
+ bool
+ parse_msgpack_internal() {
+ switch (get()) {
+ // EOF
+ case char_traits<char_type>::eof():
+ return unexpect_eof(input_format_t::msgpack, "value");
+
+ // positive fixint
+ case 0x00:
+ case 0x01:
+ case 0x02:
+ case 0x03:
+ case 0x04:
+ case 0x05:
+ case 0x06:
+ case 0x07:
+ case 0x08:
+ case 0x09:
+ case 0x0A:
+ case 0x0B:
+ case 0x0C:
+ case 0x0D:
+ case 0x0E:
+ case 0x0F:
+ case 0x10:
+ case 0x11:
+ case 0x12:
+ case 0x13:
+ case 0x14:
+ case 0x15:
+ case 0x16:
+ case 0x17:
+ case 0x18:
+ case 0x19:
+ case 0x1A:
+ case 0x1B:
+ case 0x1C:
+ case 0x1D:
+ case 0x1E:
+ case 0x1F:
+ case 0x20:
+ case 0x21:
+ case 0x22:
+ case 0x23:
+ case 0x24:
+ case 0x25:
+ case 0x26:
+ case 0x27:
+ case 0x28:
+ case 0x29:
+ case 0x2A:
+ case 0x2B:
+ case 0x2C:
+ case 0x2D:
+ case 0x2E:
+ case 0x2F:
+ case 0x30:
+ case 0x31:
+ case 0x32:
+ case 0x33:
+ case 0x34:
+ case 0x35:
+ case 0x36:
+ case 0x37:
+ case 0x38:
+ case 0x39:
+ case 0x3A:
+ case 0x3B:
+ case 0x3C:
+ case 0x3D:
+ case 0x3E:
+ case 0x3F:
+ case 0x40:
+ case 0x41:
+ case 0x42:
+ case 0x43:
+ case 0x44:
+ case 0x45:
+ case 0x46:
+ case 0x47:
+ case 0x48:
+ case 0x49:
+ case 0x4A:
+ case 0x4B:
+ case 0x4C:
+ case 0x4D:
+ case 0x4E:
+ case 0x4F:
+ case 0x50:
+ case 0x51:
+ case 0x52:
+ case 0x53:
+ case 0x54:
+ case 0x55:
+ case 0x56:
+ case 0x57:
+ case 0x58:
+ case 0x59:
+ case 0x5A:
+ case 0x5B:
+ case 0x5C:
+ case 0x5D:
+ case 0x5E:
+ case 0x5F:
+ case 0x60:
+ case 0x61:
+ case 0x62:
+ case 0x63:
+ case 0x64:
+ case 0x65:
+ case 0x66:
+ case 0x67:
+ case 0x68:
+ case 0x69:
+ case 0x6A:
+ case 0x6B:
+ case 0x6C:
+ case 0x6D:
+ case 0x6E:
+ case 0x6F:
+ case 0x70:
+ case 0x71:
+ case 0x72:
+ case 0x73:
+ case 0x74:
+ case 0x75:
+ case 0x76:
+ case 0x77:
+ case 0x78:
+ case 0x79:
+ case 0x7A:
+ case 0x7B:
+ case 0x7C:
+ case 0x7D:
+ case 0x7E:
+ case 0x7F:
+ return sax->number_unsigned(static_cast<number_unsigned_t>(current));
+
+ // fixmap
+ case 0x80:
+ case 0x81:
+ case 0x82:
+ case 0x83:
+ case 0x84:
+ case 0x85:
+ case 0x86:
+ case 0x87:
+ case 0x88:
+ case 0x89:
+ case 0x8A:
+ case 0x8B:
+ case 0x8C:
+ case 0x8D:
+ case 0x8E:
+ case 0x8F:
+ return get_msgpack_object(
+ conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
+
+ // fixarray
+ case 0x90:
+ case 0x91:
+ case 0x92:
+ case 0x93:
+ case 0x94:
+ case 0x95:
+ case 0x96:
+ case 0x97:
+ case 0x98:
+ case 0x99:
+ case 0x9A:
+ case 0x9B:
+ case 0x9C:
+ case 0x9D:
+ case 0x9E:
+ case 0x9F:
+ return get_msgpack_array(
+ conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
+
+ // fixstr
+ case 0xA0:
+ case 0xA1:
+ case 0xA2:
+ case 0xA3:
+ case 0xA4:
+ case 0xA5:
+ case 0xA6:
+ case 0xA7:
+ case 0xA8:
+ case 0xA9:
+ case 0xAA:
+ case 0xAB:
+ case 0xAC:
+ case 0xAD:
+ case 0xAE:
+ case 0xAF:
+ case 0xB0:
+ case 0xB1:
+ case 0xB2:
+ case 0xB3:
+ case 0xB4:
+ case 0xB5:
+ case 0xB6:
+ case 0xB7:
+ case 0xB8:
+ case 0xB9:
+ case 0xBA:
+ case 0xBB:
+ case 0xBC:
+ case 0xBD:
+ case 0xBE:
+ case 0xBF:
+ case 0xD9: // str 8
+ case 0xDA: // str 16
+ case 0xDB: // str 32
+ {
+ string_t s;
+ return get_msgpack_string(s) && sax->string(s);
+ }
+
+ case 0xC0: // nil
+ return sax->null();
+
+ case 0xC2: // false
+ return sax->boolean(false);
+
+ case 0xC3: // true
+ return sax->boolean(true);
+
+ case 0xC4: // bin 8
+ case 0xC5: // bin 16
+ case 0xC6: // bin 32
+ case 0xC7: // ext 8
+ case 0xC8: // ext 16
+ case 0xC9: // ext 32
+ case 0xD4: // fixext 1
+ case 0xD5: // fixext 2
+ case 0xD6: // fixext 4
+ case 0xD7: // fixext 8
+ case 0xD8: // fixext 16
+ {
+ binary_t b;
+ return get_msgpack_binary(b) && sax->binary(b);
+ }
+
+ case 0xCA: // float 32
+ {
+ float number{};
+ return get_number(input_format_t::msgpack, number) &&
+ sax->number_float(static_cast<number_float_t>(number), "");
+ }
+
+ case 0xCB: // float 64
+ {
+ double number{};
+ return get_number(input_format_t::msgpack, number) &&
+ sax->number_float(static_cast<number_float_t>(number), "");
+ }
+
+ case 0xCC: // uint 8
+ {
+ std::uint8_t number{};
+ return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
+ }
+
+ case 0xCD: // uint 16
+ {
+ std::uint16_t number{};
+ return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
+ }
+
+ case 0xCE: // uint 32
+ {
+ std::uint32_t number{};
+ return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
+ }
+
+ case 0xCF: // uint 64
+ {
+ std::uint64_t number{};
+ return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
+ }
+
+ case 0xD0: // int 8
+ {
+ std::int8_t number{};
+ return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
+ }
+
+ case 0xD1: // int 16
+ {
+ std::int16_t number{};
+ return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
+ }
+
+ case 0xD2: // int 32
+ {
+ std::int32_t number{};
+ return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
+ }
+
+ case 0xD3: // int 64
+ {
+ std::int64_t number{};
+ return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
+ }
+
+ case 0xDC: // array 16
+ {
+ std::uint16_t len{};
+ return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
+ }
+
+ case 0xDD: // array 32
+ {
+ std::uint32_t len{};
+ return get_number(input_format_t::msgpack, len) &&
+ get_msgpack_array(conditional_static_cast<std::size_t>(len));
+ }
+
+ case 0xDE: // map 16
+ {
+ std::uint16_t len{};
+ return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
+ }
+
+ case 0xDF: // map 32
+ {
+ std::uint32_t len{};
+ return get_number(input_format_t::msgpack, len) &&
+ get_msgpack_object(conditional_static_cast<std::size_t>(len));
+ }
+
+ // negative fixint
+ case 0xE0:
+ case 0xE1:
+ case 0xE2:
+ case 0xE3:
+ case 0xE4:
+ case 0xE5:
+ case 0xE6:
+ case 0xE7:
+ case 0xE8:
+ case 0xE9:
+ case 0xEA:
+ case 0xEB:
+ case 0xEC:
+ case 0xED:
+ case 0xEE:
+ case 0xEF:
+ case 0xF0:
+ case 0xF1:
+ case 0xF2:
+ case 0xF3:
+ case 0xF4:
+ case 0xF5:
+ case 0xF6:
+ case 0xF7:
+ case 0xF8:
+ case 0xF9:
+ case 0xFA:
+ case 0xFB:
+ case 0xFC:
+ case 0xFD:
+ case 0xFE:
+ case 0xFF:
+ return sax->number_integer(static_cast<std::int8_t>(current));
+
+ default: // anything else
+ {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 112,
+ chars_read,
+ exception_message(input_format_t::msgpack, concat("invalid byte: 0x", last_token), "value"),
+ nullptr));
+ }
+ }
+ }
+
+ /*!
+ @brief reads a MessagePack string
+
+ This function first reads starting bytes to determine the expected
+ string length and then copies this number of bytes into a string.
+
+ @param[out] result created string
+
+ @return whether string creation completed
+ */
+ bool
+ get_msgpack_string(string_t& result) {
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) {
+ return false;
+ }
+
+ switch (current) {
+ // fixstr
+ case 0xA0:
+ case 0xA1:
+ case 0xA2:
+ case 0xA3:
+ case 0xA4:
+ case 0xA5:
+ case 0xA6:
+ case 0xA7:
+ case 0xA8:
+ case 0xA9:
+ case 0xAA:
+ case 0xAB:
+ case 0xAC:
+ case 0xAD:
+ case 0xAE:
+ case 0xAF:
+ case 0xB0:
+ case 0xB1:
+ case 0xB2:
+ case 0xB3:
+ case 0xB4:
+ case 0xB5:
+ case 0xB6:
+ case 0xB7:
+ case 0xB8:
+ case 0xB9:
+ case 0xBA:
+ case 0xBB:
+ case 0xBC:
+ case 0xBD:
+ case 0xBE:
+ case 0xBF: {
+ return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
+ }
+
+ case 0xD9: // str 8
+ {
+ std::uint8_t len{};
+ return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
+ }
+
+ case 0xDA: // str 16
+ {
+ std::uint16_t len{};
+ return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
+ }
+
+ case 0xDB: // str 32
+ {
+ std::uint32_t len{};
+ return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
+ }
+
+ default: {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 113,
+ chars_read,
+ exception_message(
+ input_format_t::msgpack,
+ concat("expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x", last_token),
+ "string"),
+ nullptr));
+ }
+ }
+ }
+
+ /*!
+ @brief reads a MessagePack byte array
+
+ This function first reads starting bytes to determine the expected
+ byte array length and then copies this number of bytes into a byte array.
+
+ @param[out] result created byte array
+
+ @return whether byte array creation completed
+ */
+ bool
+ get_msgpack_binary(binary_t& result) {
+ // helper function to set the subtype
+ auto assign_and_return_true = [&result](std::int8_t subtype) {
+ result.set_subtype(static_cast<std::uint8_t>(subtype));
+ return true;
+ };
+
+ switch (current) {
+ case 0xC4: // bin 8
+ {
+ std::uint8_t len{};
+ return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result);
+ }
+
+ case 0xC5: // bin 16
+ {
+ std::uint16_t len{};
+ return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result);
+ }
+
+ case 0xC6: // bin 32
+ {
+ std::uint32_t len{};
+ return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result);
+ }
+
+ case 0xC7: // ext 8
+ {
+ std::uint8_t len{};
+ std::int8_t subtype{};
+ return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) &&
+ get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype);
+ }
+
+ case 0xC8: // ext 16
+ {
+ std::uint16_t len{};
+ std::int8_t subtype{};
+ return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) &&
+ get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype);
+ }
+
+ case 0xC9: // ext 32
+ {
+ std::uint32_t len{};
+ std::int8_t subtype{};
+ return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) &&
+ get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype);
+ }
+
+ case 0xD4: // fixext 1
+ {
+ std::int8_t subtype{};
+ return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 1, result) &&
+ assign_and_return_true(subtype);
+ }
+
+ case 0xD5: // fixext 2
+ {
+ std::int8_t subtype{};
+ return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 2, result) &&
+ assign_and_return_true(subtype);
+ }
+
+ case 0xD6: // fixext 4
+ {
+ std::int8_t subtype{};
+ return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 4, result) &&
+ assign_and_return_true(subtype);
+ }
+
+ case 0xD7: // fixext 8
+ {
+ std::int8_t subtype{};
+ return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 8, result) &&
+ assign_and_return_true(subtype);
+ }
+
+ case 0xD8: // fixext 16
+ {
+ std::int8_t subtype{};
+ return get_number(input_format_t::msgpack, subtype) &&
+ get_binary(input_format_t::msgpack, 16, result) && assign_and_return_true(subtype);
+ }
+
+ default: // LCOV_EXCL_LINE
+ return false; // LCOV_EXCL_LINE
+ }
+ }
+
+ /*!
+ @param[in] len the length of the array
+ @return whether array creation completed
+ */
+ bool
+ get_msgpack_array(const std::size_t len) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) {
+ return false;
+ }
+
+ for (std::size_t i = 0; i < len; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) {
+ return false;
+ }
+ }
+
+ return sax->end_array();
+ }
+
+ /*!
+ @param[in] len the length of the object
+ @return whether object creation completed
+ */
+ bool
+ get_msgpack_object(const std::size_t len) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) {
+ return false;
+ }
+
+ string_t key;
+ for (std::size_t i = 0; i < len; ++i) {
+ get();
+ if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) {
+ return false;
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) {
+ return false;
+ }
+ key.clear();
+ }
+
+ return sax->end_object();
+ }
+
+ ////////////
+ // UBJSON //
+ ////////////
+
+ /*!
+ @param[in] get_char whether a new character should be retrieved from the
+ input (true, default) or whether the last read
+ character should be considered instead
+
+ @return whether a valid UBJSON value was passed to the SAX parser
+ */
+ bool
+ parse_ubjson_internal(const bool get_char = true) {
+ return get_ubjson_value(get_char ? get_ignore_noop() : current);
+ }
+
+ /*!
+ @brief reads a UBJSON string
+
+ This function is either called after reading the 'S' byte explicitly
+ indicating a string, or in case of an object key where the 'S' byte can be
+ left out.
+
+ @param[out] result created string
+ @param[in] get_char whether a new character should be retrieved from the
+ input (true, default) or whether the last read
+ character should be considered instead
+
+ @return whether string creation completed
+ */
+ bool
+ get_ubjson_string(string_t& result, const bool get_char = true) {
+ if (get_char) {
+ get(); // TODO(niels): may we ignore N here?
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "value"))) {
+ return false;
+ }
+
+ switch (current) {
+ case 'U': {
+ std::uint8_t len{};
+ return get_number(input_format, len) && get_string(input_format, len, result);
+ }
+
+ case 'i': {
+ std::int8_t len{};
+ return get_number(input_format, len) && get_string(input_format, len, result);
+ }
+
+ case 'I': {
+ std::int16_t len{};
+ return get_number(input_format, len) && get_string(input_format, len, result);
+ }
+
+ case 'l': {
+ std::int32_t len{};
+ return get_number(input_format, len) && get_string(input_format, len, result);
+ }
+
+ case 'L': {
+ std::int64_t len{};
+ return get_number(input_format, len) && get_string(input_format, len, result);
+ }
+
+ case 'u': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ std::uint16_t len{};
+ return get_number(input_format, len) && get_string(input_format, len, result);
+ }
+
+ case 'm': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ std::uint32_t len{};
+ return get_number(input_format, len) && get_string(input_format, len, result);
+ }
+
+ case 'M': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ std::uint64_t len{};
+ return get_number(input_format, len) && get_string(input_format, len, result);
+ }
+
+ default:
+ break;
+ }
+ auto last_token = get_token_string();
+ std::string message;
+
+ if (input_format != input_format_t::bjdata) {
+ message = "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token;
+ } else {
+ message = "expected length type specification (U, i, u, I, m, l, M, L); last byte: 0x" + last_token;
+ }
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(113, chars_read, exception_message(input_format, message, "string"), nullptr));
+ }
+
+ /*!
+ @param[out] dim an integer vector storing the ND array dimensions
+ @return whether reading ND array size vector is successful
+ */
+ bool
+ get_ubjson_ndarray_size(std::vector<size_t>& dim) {
+ std::pair<std::size_t, char_int_type> size_and_type;
+ size_t dimlen = 0;
+ bool no_ndarray = true;
+
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type, no_ndarray))) {
+ return false;
+ }
+
+ if (size_and_type.first != npos) {
+ if (size_and_type.second != 0) {
+ if (size_and_type.second != 'N') {
+ for (std::size_t i = 0; i < size_and_type.first; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray, size_and_type.second))) {
+ return false;
+ }
+ dim.push_back(dimlen);
+ }
+ }
+ } else {
+ for (std::size_t i = 0; i < size_and_type.first; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray))) {
+ return false;
+ }
+ dim.push_back(dimlen);
+ }
+ }
+ } else {
+ while (current != ']') {
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray, current))) {
+ return false;
+ }
+ dim.push_back(dimlen);
+ get_ignore_noop();
+ }
+ }
+ return true;
+ }
+
+ /*!
+ @param[out] result determined size
+ @param[in,out] is_ndarray for input, `true` means already inside an ndarray vector
+ or ndarray dimension is not allowed; `false` means ndarray
+ is allowed; for output, `true` means an ndarray is found;
+ is_ndarray can only return `true` when its initial value
+ is `false`
+ @param[in] prefix type marker if already read, otherwise set to 0
+
+ @return whether size determination completed
+ */
+ bool
+ get_ubjson_size_value(std::size_t& result, bool& is_ndarray, char_int_type prefix = 0) {
+ if (prefix == 0) {
+ prefix = get_ignore_noop();
+ }
+
+ switch (prefix) {
+ case 'U': {
+ std::uint8_t number{};
+ if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) {
+ return false;
+ }
+ result = static_cast<std::size_t>(number);
+ return true;
+ }
+
+ case 'i': {
+ std::int8_t number{};
+ if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) {
+ return false;
+ }
+ if (number < 0) {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ parse_error::create(
+ 113,
+ chars_read,
+ exception_message(input_format, "count in an optimized container must be positive", "size"),
+ nullptr));
+ }
+ result = static_cast<std::size_t>(
+ number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char
+ return true;
+ }
+
+ case 'I': {
+ std::int16_t number{};
+ if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) {
+ return false;
+ }
+ if (number < 0) {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ parse_error::create(
+ 113,
+ chars_read,
+ exception_message(input_format, "count in an optimized container must be positive", "size"),
+ nullptr));
+ }
+ result = static_cast<std::size_t>(number);
+ return true;
+ }
+
+ case 'l': {
+ std::int32_t number{};
+ if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) {
+ return false;
+ }
+ if (number < 0) {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ parse_error::create(
+ 113,
+ chars_read,
+ exception_message(input_format, "count in an optimized container must be positive", "size"),
+ nullptr));
+ }
+ result = static_cast<std::size_t>(number);
+ return true;
+ }
+
+ case 'L': {
+ std::int64_t number{};
+ if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) {
+ return false;
+ }
+ if (number < 0) {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ parse_error::create(
+ 113,
+ chars_read,
+ exception_message(input_format, "count in an optimized container must be positive", "size"),
+ nullptr));
+ }
+ if (!value_in_range_of<std::size_t>(number)) {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ out_of_range::create(
+ 408, exception_message(input_format, "integer value overflow", "size"), nullptr));
+ }
+ result = static_cast<std::size_t>(number);
+ return true;
+ }
+
+ case 'u': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ std::uint16_t number{};
+ if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) {
+ return false;
+ }
+ result = static_cast<std::size_t>(number);
+ return true;
+ }
+
+ case 'm': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ std::uint32_t number{};
+ if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) {
+ return false;
+ }
+ result = conditional_static_cast<std::size_t>(number);
+ return true;
+ }
+
+ case 'M': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ std::uint64_t number{};
+ if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) {
+ return false;
+ }
+ if (!value_in_range_of<std::size_t>(number)) {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ out_of_range::create(
+ 408, exception_message(input_format, "integer value overflow", "size"), nullptr));
+ }
+ result = detail::conditional_static_cast<std::size_t>(number);
+ return true;
+ }
+
+ case '[': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ if (is_ndarray) // ndarray dimensional vector can only contain integers, and can not embed another
+ // array
+ {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ parse_error::create(
+ 113,
+ chars_read,
+ exception_message(input_format, "ndarray dimensional vector is not allowed", "size"),
+ nullptr));
+ }
+ std::vector<size_t> dim;
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_ndarray_size(dim))) {
+ return false;
+ }
+ if (dim.size() == 1 ||
+ (dim.size() == 2 && dim.at(0) == 1)) // return normal array size if 1D row vector
+ {
+ result = dim.at(dim.size() - 1);
+ return true;
+ }
+ if (!dim.empty()) // if ndarray, convert to an object in JData annotated array format
+ {
+ for (auto i : dim) // test if any dimension in an ndarray is 0, if so, return a 1D empty container
+ {
+ if (i == 0) {
+ result = 0;
+ return true;
+ }
+ }
+
+ string_t key = "_ArraySize_";
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_object(3) || !sax->key(key) ||
+ !sax->start_array(dim.size()))) {
+ return false;
+ }
+ result = 1;
+ for (auto i : dim) {
+ result *= i;
+ if (result == 0 || result == npos) // because dim elements shall not have zeros, result = 0
+ // means overflow happened; it also can't be npos as it is
+ // used to initialize size in get_ubjson_size_type()
+ {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ out_of_range::create(
+ 408,
+ exception_message(input_format, "excessive ndarray size caused overflow", "size"),
+ nullptr));
+ }
+ if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(static_cast<number_unsigned_t>(i)))) {
+ return false;
+ }
+ }
+ is_ndarray = true;
+ return sax->end_array();
+ }
+ result = 0;
+ return true;
+ }
+
+ default:
+ break;
+ }
+ auto last_token = get_token_string();
+ std::string message;
+
+ if (input_format != input_format_t::bjdata) {
+ message = "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token;
+ } else {
+ message =
+ "expected length type specification (U, i, u, I, m, l, M, L) after '#'; last byte: 0x" + last_token;
+ }
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(113, chars_read, exception_message(input_format, message, "size"), nullptr));
+ }
+
+ /*!
+ @brief determine the type and size for a container
+
+ In the optimized UBJSON format, a type and a size can be provided to allow
+ for a more compact representation.
+
+ @param[out] result pair of the size and the type
+ @param[in] inside_ndarray whether the parser is parsing an ND array dimensional vector
+
+ @return whether pair creation completed
+ */
+ bool
+ get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result, bool inside_ndarray = false) {
+ result.first = npos; // size
+ result.second = 0; // type
+ bool is_ndarray = false;
+
+ get_ignore_noop();
+
+ if (current == '$') {
+ result.second = get(); // must not ignore 'N', because 'N' maybe the type
+ if (input_format == input_format_t::bjdata &&
+ JSON_HEDLEY_UNLIKELY(std::binary_search(
+ bjd_optimized_type_markers.begin(), bjd_optimized_type_markers.end(), result.second))) {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 112,
+ chars_read,
+ exception_message(input_format,
+ concat("marker 0x", last_token, " is not a permitted optimized array type"),
+ "type"),
+ nullptr));
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "type"))) {
+ return false;
+ }
+
+ get_ignore_noop();
+ if (JSON_HEDLEY_UNLIKELY(current != '#')) {
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "value"))) {
+ return false;
+ }
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 112,
+ chars_read,
+ exception_message(input_format,
+ concat("expected '#' after type information; last byte: 0x", last_token),
+ "size"),
+ nullptr));
+ }
+
+ const bool is_error = get_ubjson_size_value(result.first, is_ndarray);
+ if (input_format == input_format_t::bjdata && is_ndarray) {
+ if (inside_ndarray) {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ parse_error::create(112,
+ chars_read,
+ exception_message(input_format, "ndarray can not be recursive", "size"),
+ nullptr));
+ }
+ result.second |=
+ (1 << 8); // use bit 8 to indicate ndarray, all UBJSON and BJData markers should be ASCII letters
+ }
+ return is_error;
+ }
+
+ if (current == '#') {
+ const bool is_error = get_ubjson_size_value(result.first, is_ndarray);
+ if (input_format == input_format_t::bjdata && is_ndarray) {
+ return sax->parse_error(
+ chars_read,
+ get_token_string(),
+ parse_error::create(112,
+ chars_read,
+ exception_message(input_format, "ndarray requires both type and size", "size"),
+ nullptr));
+ }
+ return is_error;
+ }
+
+ return true;
+ }
+
+ /*!
+ @param prefix the previously read or set type prefix
+ @return whether value creation completed
+ */
+ bool
+ get_ubjson_value(const char_int_type prefix) {
+ switch (prefix) {
+ case char_traits<char_type>::eof(): // EOF
+ return unexpect_eof(input_format, "value");
+
+ case 'T': // true
+ return sax->boolean(true);
+ case 'F': // false
+ return sax->boolean(false);
+
+ case 'Z': // null
+ return sax->null();
+
+ case 'U': {
+ std::uint8_t number{};
+ return get_number(input_format, number) && sax->number_unsigned(number);
+ }
+
+ case 'i': {
+ std::int8_t number{};
+ return get_number(input_format, number) && sax->number_integer(number);
+ }
+
+ case 'I': {
+ std::int16_t number{};
+ return get_number(input_format, number) && sax->number_integer(number);
+ }
+
+ case 'l': {
+ std::int32_t number{};
+ return get_number(input_format, number) && sax->number_integer(number);
+ }
+
+ case 'L': {
+ std::int64_t number{};
+ return get_number(input_format, number) && sax->number_integer(number);
+ }
+
+ case 'u': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ std::uint16_t number{};
+ return get_number(input_format, number) && sax->number_unsigned(number);
+ }
+
+ case 'm': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ std::uint32_t number{};
+ return get_number(input_format, number) && sax->number_unsigned(number);
+ }
+
+ case 'M': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ std::uint64_t number{};
+ return get_number(input_format, number) && sax->number_unsigned(number);
+ }
+
+ case 'h': {
+ if (input_format != input_format_t::bjdata) {
+ break;
+ }
+ const auto byte1_raw = get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "number"))) {
+ return false;
+ }
+ const auto byte2_raw = get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "number"))) {
+ return false;
+ }
+
+ const auto byte1 = static_cast<unsigned char>(byte1_raw);
+ const auto byte2 = static_cast<unsigned char>(byte2_raw);
+
+ // code from RFC 7049, Appendix D, Figure 3:
+ // As half-precision floating-point numbers were only added
+ // to IEEE 754 in 2008, today's programming platforms often
+ // still only have limited support for them. It is very
+ // easy to include at least decoding support for them even
+ // without such support. An example of a small decoder for
+ // half-precision floating-point numbers in the C language
+ // is shown in Fig. 3.
+ const auto half = static_cast<unsigned int>((byte2 << 8u) + byte1);
+ const double val = [&half] {
+ const int exp = (half >> 10u) & 0x1Fu;
+ const unsigned int mant = half & 0x3FFu;
+ JSON_ASSERT(0 <= exp && exp <= 32);
+ JSON_ASSERT(mant <= 1024);
+ switch (exp) {
+ case 0:
+ return std::ldexp(mant, -24);
+ case 31:
+ return (mant == 0) ? std::numeric_limits<double>::infinity()
+ : std::numeric_limits<double>::quiet_NaN();
+ default:
+ return std::ldexp(mant + 1024, exp - 25);
+ }
+ }();
+ return sax->number_float(
+ (half & 0x8000u) != 0 ? static_cast<number_float_t>(-val) : static_cast<number_float_t>(val), "");
+ }
+
+ case 'd': {
+ float number{};
+ return get_number(input_format, number) && sax->number_float(static_cast<number_float_t>(number), "");
+ }
+
+ case 'D': {
+ double number{};
+ return get_number(input_format, number) && sax->number_float(static_cast<number_float_t>(number), "");
+ }
+
+ case 'H': {
+ return get_ubjson_high_precision_number();
+ }
+
+ case 'C': // char
+ {
+ get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "char"))) {
+ return false;
+ }
+ if (JSON_HEDLEY_UNLIKELY(current > 127)) {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 113,
+ chars_read,
+ exception_message(
+ input_format,
+ concat("byte after 'C' must be in range 0x00..0x7F; last byte: 0x", last_token),
+ "char"),
+ nullptr));
+ }
+ string_t s(1, static_cast<typename string_t::value_type>(current));
+ return sax->string(s);
+ }
+
+ case 'S': // string
+ {
+ string_t s;
+ return get_ubjson_string(s) && sax->string(s);
+ }
+
+ case '[': // array
+ return get_ubjson_array();
+
+ case '{': // object
+ return get_ubjson_object();
+
+ default: // anything else
+ break;
+ }
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 112, chars_read, exception_message(input_format, "invalid byte: 0x" + last_token, "value"), nullptr));
+ }
+
+ /*!
+ @return whether array creation completed
+ */
+ bool
+ get_ubjson_array() {
+ std::pair<std::size_t, char_int_type> size_and_type;
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) {
+ return false;
+ }
+
+ // if bit-8 of size_and_type.second is set to 1, encode bjdata ndarray as an object in JData annotated array
+ // format (https://github.com/NeuroJSON/jdata):
+ // {"_ArrayType_" : "typeid", "_ArraySize_" : [n1, n2, ...], "_ArrayData_" : [v1, v2, ...]}
+
+ if (input_format == input_format_t::bjdata && size_and_type.first != npos &&
+ (size_and_type.second & (1 << 8)) != 0) {
+ size_and_type.second &=
+ ~(static_cast<char_int_type>(1)
+ << 8); // use bit 8 to indicate ndarray, here we remove the bit to restore the type marker
+ auto it = std::lower_bound(bjd_types_map.begin(),
+ bjd_types_map.end(),
+ size_and_type.second,
+ [](const bjd_type& p, char_int_type t) { return p.first < t; });
+ string_t key = "_ArrayType_";
+ if (JSON_HEDLEY_UNLIKELY(it == bjd_types_map.end() || it->first != size_and_type.second)) {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(112,
+ chars_read,
+ exception_message(input_format, "invalid byte: 0x" + last_token, "type"),
+ nullptr));
+ }
+
+ string_t type = it->second; // sax->string() takes a reference
+ if (JSON_HEDLEY_UNLIKELY(!sax->key(key) || !sax->string(type))) {
+ return false;
+ }
+
+ if (size_and_type.second == 'C') {
+ size_and_type.second = 'U';
+ }
+
+ key = "_ArrayData_";
+ if (JSON_HEDLEY_UNLIKELY(!sax->key(key) || !sax->start_array(size_and_type.first))) {
+ return false;
+ }
+
+ for (std::size_t i = 0; i < size_and_type.first; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) {
+ return false;
+ }
+ }
+
+ return (sax->end_array() && sax->end_object());
+ }
+
+ if (size_and_type.first != npos) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) {
+ return false;
+ }
+
+ if (size_and_type.second != 0) {
+ if (size_and_type.second != 'N') {
+ for (std::size_t i = 0; i < size_and_type.first; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) {
+ return false;
+ }
+ }
+ }
+ } else {
+ for (std::size_t i = 0; i < size_and_type.first; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) {
+ return false;
+ }
+ }
+ }
+ } else {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast<std::size_t>(-1)))) {
+ return false;
+ }
+
+ while (current != ']') {
+ if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) {
+ return false;
+ }
+ get_ignore_noop();
+ }
+ }
+
+ return sax->end_array();
+ }
+
+ /*!
+ @return whether object creation completed
+ */
+ bool
+ get_ubjson_object() {
+ std::pair<std::size_t, char_int_type> size_and_type;
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) {
+ return false;
+ }
+
+ // do not accept ND-array size in objects in BJData
+ if (input_format == input_format_t::bjdata && size_and_type.first != npos &&
+ (size_and_type.second & (1 << 8)) != 0) {
+ auto last_token = get_token_string();
+ return sax->parse_error(
+ chars_read,
+ last_token,
+ parse_error::create(
+ 112,
+ chars_read,
+ exception_message(
+ input_format, "BJData object does not support ND-array size in optimized format", "object"),
+ nullptr));
+ }
+
+ string_t key;
+ if (size_and_type.first != npos) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) {
+ return false;
+ }
+
+ if (size_and_type.second != 0) {
+ for (std::size_t i = 0; i < size_and_type.first; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) {
+ return false;
+ }
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) {
+ return false;
+ }
+ key.clear();
+ }
+ } else {
+ for (std::size_t i = 0; i < size_and_type.first; ++i) {
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) {
+ return false;
+ }
+ if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) {
+ return false;
+ }
+ key.clear();
+ }
+ }
+ } else {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast<std::size_t>(-1)))) {
+ return false;
+ }
+
+ while (current != '}') {
+ if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) {
+ return false;
+ }
+ if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) {
+ return false;
+ }
+ get_ignore_noop();
+ key.clear();
+ }
+ }
+
+ return sax->end_object();
+ }
+
+ // Note, no reader for UBJSON binary types is implemented because they do
+ // not exist
+
+ bool
+ get_ubjson_high_precision_number() {
+ // get size of following number string
+ std::size_t size{};
+ bool no_ndarray = true;
+ auto res = get_ubjson_size_value(size, no_ndarray);
+ if (JSON_HEDLEY_UNLIKELY(!res)) {
+ return res;
+ }
+
+ // get number string
+ std::vector<char> number_vector;
+ for (std::size_t i = 0; i < size; ++i) {
+ get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "number"))) {
+ return false;
+ }
+ number_vector.push_back(static_cast<char>(current));
+ }
+
+ // parse number string
+ using ia_type = decltype(detail::input_adapter(number_vector));
+ auto number_lexer = detail::lexer<BasicJsonType, ia_type>(detail::input_adapter(number_vector), false);
+ const auto result_number = number_lexer.scan();
+ const auto number_string = number_lexer.get_token_string();
+ const auto result_remainder = number_lexer.scan();
+
+ using token_type = typename detail::lexer_base<BasicJsonType>::token_type;
+
+ if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) {
+ return sax->parse_error(
+ chars_read,
+ number_string,
+ parse_error::create(115,
+ chars_read,
+ exception_message(input_format,
+ concat("invalid number text: ", number_lexer.get_token_string()),
+ "high-precision number"),
+ nullptr));
+ }
+
+ switch (result_number) {
+ case token_type::value_integer:
+ return sax->number_integer(number_lexer.get_number_integer());
+ case token_type::value_unsigned:
+ return sax->number_unsigned(number_lexer.get_number_unsigned());
+ case token_type::value_float:
+ return sax->number_float(number_lexer.get_number_float(), std::move(number_string));
+ case token_type::uninitialized:
+ case token_type::literal_true:
+ case token_type::literal_false:
+ case token_type::literal_null:
+ case token_type::value_string:
+ case token_type::begin_array:
+ case token_type::begin_object:
+ case token_type::end_array:
+ case token_type::end_object:
+ case token_type::name_separator:
+ case token_type::value_separator:
+ case token_type::parse_error:
+ case token_type::end_of_input:
+ case token_type::literal_or_value:
+ default:
+ return sax->parse_error(chars_read,
+ number_string,
+ parse_error::create(115,
+ chars_read,
+ exception_message(input_format,
+ concat("invalid number text: ",
+ number_lexer.get_token_string()),
+ "high-precision number"),
+ nullptr));
+ }
+ }
+
+ ///////////////////////
+ // Utility functions //
+ ///////////////////////
+
+ /*!
+ @brief get next character from the input
+
+ This function provides the interface to the used input adapter. It does
+ not throw in case the input reached EOF, but returns a -'ve valued
+ `char_traits<char_type>::eof()` in that case.
+
+ @return character read from the input
+ */
+ char_int_type
+ get() {
+ ++chars_read;
+ return current = ia.get_character();
+ }
+
+ /*!
+ @return character read from the input after ignoring all 'N' entries
+ */
+ char_int_type
+ get_ignore_noop() {
+ do {
+ get();
+ } while (current == 'N');
+
+ return current;
+ }
+
+ /*
+ @brief read a number from the input
+
+ @tparam NumberType the type of the number
+ @param[in] format the current format (for diagnostics)
+ @param[out] result number of type @a NumberType
+
+ @return whether conversion completed
+
+ @note This function needs to respect the system's endianness, because
+ bytes in CBOR, MessagePack, and UBJSON are stored in network order
+ (big endian) and therefore need reordering on little endian systems.
+ On the other hand, BSON and BJData use little endian and should reorder
+ on big endian systems.
+ */
+ template <typename NumberType, bool InputIsLittleEndian = false>
+ bool
+ get_number(const input_format_t format, NumberType& result) {
+ // step 1: read input into array with system's byte order
+ std::array<std::uint8_t, sizeof(NumberType)> vec{};
+ for (std::size_t i = 0; i < sizeof(NumberType); ++i) {
+ get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) {
+ return false;
+ }
+
+ // reverse byte order prior to conversion if necessary
+ if (is_little_endian != (InputIsLittleEndian || format == input_format_t::bjdata)) {
+ vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
+ } else {
+ vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
+ }
+ }
+
+ // step 2: convert array into number of type T and return
+ std::memcpy(&result, vec.data(), sizeof(NumberType));
+ return true;
+ }
+
+ /*!
+ @brief create a string by reading characters from the input
+
+ @tparam NumberType the type of the number
+ @param[in] format the current format (for diagnostics)
+ @param[in] len number of characters to read
+ @param[out] result string created by reading @a len bytes
+
+ @return whether string creation completed
+
+ @note We can not reserve @a len bytes for the result, because @a len
+ may be too large. Usually, @ref unexpect_eof() detects the end of
+ the input before we run out of string memory.
+ */
+ template <typename NumberType>
+ bool
+ get_string(const input_format_t format, const NumberType len, string_t& result) {
+ bool success = true;
+ for (NumberType i = 0; i < len; i++) {
+ get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) {
+ success = false;
+ break;
+ }
+ result.push_back(static_cast<typename string_t::value_type>(current));
+ }
+ return success;
+ }
+
+ /*!
+ @brief create a byte array by reading bytes from the input
+
+ @tparam NumberType the type of the number
+ @param[in] format the current format (for diagnostics)
+ @param[in] len number of bytes to read
+ @param[out] result byte array created by reading @a len bytes
+
+ @return whether byte array creation completed
+
+ @note We can not reserve @a len bytes for the result, because @a len
+ may be too large. Usually, @ref unexpect_eof() detects the end of
+ the input before we run out of memory.
+ */
+ template <typename NumberType>
+ bool
+ get_binary(const input_format_t format, const NumberType len, binary_t& result) {
+ bool success = true;
+ for (NumberType i = 0; i < len; i++) {
+ get();
+ if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) {
+ success = false;
+ break;
+ }
+ result.push_back(static_cast<std::uint8_t>(current));
+ }
+ return success;
+ }
+
+ /*!
+ @param[in] format the current format (for diagnostics)
+ @param[in] context further context information (for diagnostics)
+ @return whether the last read character is not EOF
+ */
+ JSON_HEDLEY_NON_NULL(3)
+ bool
+ unexpect_eof(const input_format_t format, const char* context) const {
+ if (JSON_HEDLEY_UNLIKELY(current == char_traits<char_type>::eof())) {
+ return sax->parse_error(
+ chars_read,
+ "<end of file>",
+ parse_error::create(
+ 110, chars_read, exception_message(format, "unexpected end of input", context), nullptr));
+ }
+ return true;
+ }
+
+ /*!
+ @return a string representation of the last read byte
+ */
+ std::string
+ get_token_string() const {
+ std::array<char, 3> cr{{}};
+ static_cast<void>((std::snprintf)(
+ cr.data(),
+ cr.size(),
+ "%.2hhX",
+ static_cast<unsigned char>(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+ return std::string{cr.data()};
+ }
+
+ /*!
+ @param[in] format the current format
+ @param[in] detail a detailed error message
+ @param[in] context further context information
+ @return a message string to use in the parse_error exceptions
+ */
+ std::string
+ exception_message(const input_format_t format, const std::string& detail, const std::string& context) const {
+ std::string error_msg = "syntax error while parsing ";
+
+ switch (format) {
+ case input_format_t::cbor:
+ error_msg += "CBOR";
+ break;
+
+ case input_format_t::msgpack:
+ error_msg += "MessagePack";
+ break;
+
+ case input_format_t::ubjson:
+ error_msg += "UBJSON";
+ break;
+
+ case input_format_t::bson:
+ error_msg += "BSON";
+ break;
+
+ case input_format_t::bjdata:
+ error_msg += "BJData";
+ break;
+
+ case input_format_t::json: // LCOV_EXCL_LINE
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ }
+
+ return concat(error_msg, ' ', context, ": ", detail);
+ }
+
+ private:
+ static JSON_INLINE_VARIABLE constexpr std::size_t npos = static_cast<std::size_t>(-1);
+
+ /// input adapter
+ InputAdapterType ia;
+
+ /// the current character
+ char_int_type current = char_traits<char_type>::eof();
+
+ /// the number of characters read
+ std::size_t chars_read = 0;
+
+ /// whether we can assume little endianness
+ const bool is_little_endian = little_endianness();
+
+ /// input format
+ const input_format_t input_format = input_format_t::json;
+
+ /// the SAX parser
+ json_sax_t* sax = nullptr;
+
+ // excluded markers in bjdata optimized type
+#define JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_ \
+ make_array<char_int_type>('F', 'H', 'N', 'S', 'T', 'Z', '[', '{')
+
+#define JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_ \
+ make_array<bjd_type>(bjd_type{'C', "char"}, \
+ bjd_type{'D', "double"}, \
+ bjd_type{'I', "int16"}, \
+ bjd_type{'L', "int64"}, \
+ bjd_type{'M', "uint64"}, \
+ bjd_type{'U', "uint8"}, \
+ bjd_type{'d', "single"}, \
+ bjd_type{'i', "int8"}, \
+ bjd_type{'l', "int32"}, \
+ bjd_type{'m', "uint32"}, \
+ bjd_type{'u', "uint16"})
+
+ JSON_PRIVATE_UNLESS_TESTED :
+ // lookup tables
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+ const decltype(JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_) bjd_optimized_type_markers =
+ JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_;
+
+ using bjd_type = std::pair<char_int_type, string_t>;
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
+ const decltype(JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_) bjd_types_map = JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_;
+
+#undef JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_
+#undef JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_
+};
+
+#ifndef JSON_HAS_CPP_17
+template <typename BasicJsonType, typename InputAdapterType, typename SAX>
+constexpr std::size_t binary_reader<BasicJsonType, InputAdapterType, SAX>::npos;
+#endif
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+// #include <nlohmann/detail/input/lexer.hpp>
+
+// #include <nlohmann/detail/input/parser.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cmath> // isfinite
+#include <cstdint> // uint8_t
+#include <functional> // function
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+// #include <nlohmann/detail/input/json_sax.hpp>
+
+// #include <nlohmann/detail/input/lexer.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/is_sax.hpp>
+
+// #include <nlohmann/detail/string_concat.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+////////////
+// parser //
+////////////
+
+enum class parse_event_t : std::uint8_t {
+ /// the parser read `{` and started to process a JSON object
+ object_start,
+ /// the parser read `}` and finished processing a JSON object
+ object_end,
+ /// the parser read `[` and started to process a JSON array
+ array_start,
+ /// the parser read `]` and finished processing a JSON array
+ array_end,
+ /// the parser read a key of a value in an object
+ key,
+ /// the parser finished reading a JSON value
+ value
+};
+
+template <typename BasicJsonType>
+using parser_callback_t = std::function<bool(int /*depth*/, parse_event_t /*event*/, BasicJsonType& /*parsed*/)>;
+
+/*!
+@brief syntax analysis
+
+This class implements a recursive descent parser.
+*/
+template <typename BasicJsonType, typename InputAdapterType>
+class parser {
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using string_t = typename BasicJsonType::string_t;
+ using lexer_t = lexer<BasicJsonType, InputAdapterType>;
+ using token_type = typename lexer_t::token_type;
+
+ public:
+ /// a parser reading from an input adapter
+ explicit parser(InputAdapterType&& adapter,
+ const parser_callback_t<BasicJsonType> cb = nullptr,
+ const bool allow_exceptions_ = true,
+ const bool skip_comments = false)
+ : callback(cb), m_lexer(std::move(adapter), skip_comments), allow_exceptions(allow_exceptions_) {
+ // read first token
+ get_token();
+ }
+
+ /*!
+ @brief public parser interface
+
+ @param[in] strict whether to expect the last token to be EOF
+ @param[in,out] result parsed JSON value
+
+ @throw parse_error.101 in case of an unexpected token
+ @throw parse_error.102 if to_unicode fails or surrogate error
+ @throw parse_error.103 if to_unicode fails
+ */
+ void
+ parse(const bool strict, BasicJsonType& result) {
+ if (callback) {
+ json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
+ sax_parse_internal(&sdp);
+
+ // in strict mode, input must be completely read
+ if (strict && (get_token() != token_type::end_of_input)) {
+ sdp.parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(
+ 101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), nullptr));
+ }
+
+ // in case of an error, return discarded value
+ if (sdp.is_errored()) {
+ result = value_t::discarded;
+ return;
+ }
+
+ // set top-level value to null if it was discarded by the callback
+ // function
+ if (result.is_discarded()) {
+ result = nullptr;
+ }
+ } else {
+ json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
+ sax_parse_internal(&sdp);
+
+ // in strict mode, input must be completely read
+ if (strict && (get_token() != token_type::end_of_input)) {
+ sdp.parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(
+ 101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), nullptr));
+ }
+
+ // in case of an error, return discarded value
+ if (sdp.is_errored()) {
+ result = value_t::discarded;
+ return;
+ }
+ }
+
+ result.assert_invariant();
+ }
+
+ /*!
+ @brief public accept interface
+
+ @param[in] strict whether to expect the last token to be EOF
+ @return whether the input is a proper JSON text
+ */
+ bool
+ accept(const bool strict = true) {
+ json_sax_acceptor<BasicJsonType> sax_acceptor;
+ return sax_parse(&sax_acceptor, strict);
+ }
+
+ template <typename SAX>
+ JSON_HEDLEY_NON_NULL(2)
+ bool sax_parse(SAX* sax, const bool strict = true) {
+ (void)detail::is_sax_static_asserts<SAX, BasicJsonType>{};
+ const bool result = sax_parse_internal(sax);
+
+ // strict mode: next byte must be EOF
+ if (result && strict && (get_token() != token_type::end_of_input)) {
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(
+ 101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), nullptr));
+ }
+
+ return result;
+ }
+
+ private:
+ template <typename SAX>
+ JSON_HEDLEY_NON_NULL(2)
+ bool sax_parse_internal(SAX* sax) {
+ // stack to remember the hierarchy of structured values we are parsing
+ // true = array; false = object
+ std::vector<bool> states;
+ // value to avoid a goto (see comment where set to true)
+ bool skip_to_state_evaluation = false;
+
+ while (true) {
+ if (!skip_to_state_evaluation) {
+ // invariant: get_token() was called before each iteration
+ switch (last_token) {
+ case token_type::begin_object: {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast<std::size_t>(-1)))) {
+ return false;
+ }
+
+ // closing } -> we are done
+ if (get_token() == token_type::end_object) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) {
+ return false;
+ }
+ break;
+ }
+
+ // parse key
+ if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) {
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(101,
+ m_lexer.get_position(),
+ exception_message(token_type::value_string, "object key"),
+ nullptr));
+ }
+ if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) {
+ return false;
+ }
+
+ // parse separator (:)
+ if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) {
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(101,
+ m_lexer.get_position(),
+ exception_message(token_type::name_separator, "object separator"),
+ nullptr));
+ }
+
+ // remember we are now inside an object
+ states.push_back(false);
+
+ // parse values
+ get_token();
+ continue;
+ }
+
+ case token_type::begin_array: {
+ if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast<std::size_t>(-1)))) {
+ return false;
+ }
+
+ // closing ] -> we are done
+ if (get_token() == token_type::end_array) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) {
+ return false;
+ }
+ break;
+ }
+
+ // remember we are now inside an array
+ states.push_back(true);
+
+ // parse values (no need to call get_token)
+ continue;
+ }
+
+ case token_type::value_float: {
+ const auto res = m_lexer.get_number_float();
+
+ if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) {
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ out_of_range::create(
+ 406,
+ concat("number overflow parsing '", m_lexer.get_token_string(), '\''),
+ nullptr));
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) {
+ return false;
+ }
+
+ break;
+ }
+
+ case token_type::literal_false: {
+ if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) {
+ return false;
+ }
+ break;
+ }
+
+ case token_type::literal_null: {
+ if (JSON_HEDLEY_UNLIKELY(!sax->null())) {
+ return false;
+ }
+ break;
+ }
+
+ case token_type::literal_true: {
+ if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) {
+ return false;
+ }
+ break;
+ }
+
+ case token_type::value_integer: {
+ if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) {
+ return false;
+ }
+ break;
+ }
+
+ case token_type::value_string: {
+ if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) {
+ return false;
+ }
+ break;
+ }
+
+ case token_type::value_unsigned: {
+ if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) {
+ return false;
+ }
+ break;
+ }
+
+ case token_type::parse_error: {
+ // using "uninitialized" to avoid "expected" message
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(101,
+ m_lexer.get_position(),
+ exception_message(token_type::uninitialized, "value"),
+ nullptr));
+ }
+ case token_type::end_of_input: {
+ if (JSON_HEDLEY_UNLIKELY(m_lexer.get_position().chars_read_total == 1)) {
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(101,
+ m_lexer.get_position(),
+ "attempting to parse an empty input; check that your input string "
+ "or stream contains the expected JSON",
+ nullptr));
+ }
+
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(101,
+ m_lexer.get_position(),
+ exception_message(token_type::literal_or_value, "value"),
+ nullptr));
+ }
+ case token_type::uninitialized:
+ case token_type::end_array:
+ case token_type::end_object:
+ case token_type::name_separator:
+ case token_type::value_separator:
+ case token_type::literal_or_value:
+ default: // the last token was unexpected
+ {
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(101,
+ m_lexer.get_position(),
+ exception_message(token_type::literal_or_value, "value"),
+ nullptr));
+ }
+ }
+ } else {
+ skip_to_state_evaluation = false;
+ }
+
+ // we reached this line after we successfully parsed a value
+ if (states.empty()) {
+ // empty stack: we reached the end of the hierarchy: done
+ return true;
+ }
+
+ if (states.back()) // array
+ {
+ // comma -> next value
+ if (get_token() == token_type::value_separator) {
+ // parse a new value
+ get_token();
+ continue;
+ }
+
+ // closing ]
+ if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) {
+ return false;
+ }
+
+ // We are done with this array. Before we can parse a
+ // new value, we need to evaluate the new state first.
+ // By setting skip_to_state_evaluation to false, we
+ // are effectively jumping to the beginning of this if.
+ JSON_ASSERT(!states.empty());
+ states.pop_back();
+ skip_to_state_evaluation = true;
+ continue;
+ }
+
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(
+ 101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), nullptr));
+ }
+
+ // states.back() is false -> object
+
+ // comma -> next value
+ if (get_token() == token_type::value_separator) {
+ // parse key
+ if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) {
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(101,
+ m_lexer.get_position(),
+ exception_message(token_type::value_string, "object key"),
+ nullptr));
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) {
+ return false;
+ }
+
+ // parse separator (:)
+ if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) {
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(101,
+ m_lexer.get_position(),
+ exception_message(token_type::name_separator, "object separator"),
+ nullptr));
+ }
+
+ // parse values
+ get_token();
+ continue;
+ }
+
+ // closing }
+ if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) {
+ if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) {
+ return false;
+ }
+
+ // We are done with this object. Before we can parse a
+ // new value, we need to evaluate the new state first.
+ // By setting skip_to_state_evaluation to false, we
+ // are effectively jumping to the beginning of this if.
+ JSON_ASSERT(!states.empty());
+ states.pop_back();
+ skip_to_state_evaluation = true;
+ continue;
+ }
+
+ return sax->parse_error(
+ m_lexer.get_position(),
+ m_lexer.get_token_string(),
+ parse_error::create(
+ 101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), nullptr));
+ }
+ }
+
+ /// get next token from lexer
+ token_type
+ get_token() {
+ return last_token = m_lexer.scan();
+ }
+
+ std::string
+ exception_message(const token_type expected, const std::string& context) {
+ std::string error_msg = "syntax error ";
+
+ if (!context.empty()) {
+ error_msg += concat("while parsing ", context, ' ');
+ }
+
+ error_msg += "- ";
+
+ if (last_token == token_type::parse_error) {
+ error_msg += concat(m_lexer.get_error_message(), "; last read: '", m_lexer.get_token_string(), '\'');
+ } else {
+ error_msg += concat("unexpected ", lexer_t::token_type_name(last_token));
+ }
+
+ if (expected != token_type::uninitialized) {
+ error_msg += concat("; expected ", lexer_t::token_type_name(expected));
+ }
+
+ return error_msg;
+ }
+
+ private:
+ /// callback function
+ const parser_callback_t<BasicJsonType> callback = nullptr;
+ /// the type of the last read token
+ token_type last_token = token_type::uninitialized;
+ /// the lexer
+ lexer_t m_lexer;
+ /// whether to throw exceptions in case of errors
+ const bool allow_exceptions = true;
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/iterators/internal_iterator.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstddef> // ptrdiff_t
+#include <limits> // numeric_limits
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+/*
+@brief an iterator for primitive JSON types
+
+This class models an iterator for primitive JSON types (boolean, number,
+string). It's only purpose is to allow the iterator/const_iterator classes
+to "iterate" over primitive values. Internally, the iterator is modeled by
+a `difference_type` variable. Value begin_value (`0`) models the begin,
+end_value (`1`) models past the end.
+*/
+class primitive_iterator_t {
+ private:
+ using difference_type = std::ptrdiff_t;
+ static constexpr difference_type begin_value = 0;
+ static constexpr difference_type end_value = begin_value + 1;
+
+ JSON_PRIVATE_UNLESS_TESTED :
+ /// iterator as signed integer type
+ difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
+
+ public:
+ constexpr difference_type
+ get_value() const noexcept {
+ return m_it;
+ }
+
+ /// set iterator to a defined beginning
+ void
+ set_begin() noexcept {
+ m_it = begin_value;
+ }
+
+ /// set iterator to a defined past the end
+ void
+ set_end() noexcept {
+ m_it = end_value;
+ }
+
+ /// return whether the iterator can be dereferenced
+ constexpr bool
+ is_begin() const noexcept {
+ return m_it == begin_value;
+ }
+
+ /// return whether the iterator is at end
+ constexpr bool
+ is_end() const noexcept {
+ return m_it == end_value;
+ }
+
+ friend constexpr bool
+ operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept {
+ return lhs.m_it == rhs.m_it;
+ }
+
+ friend constexpr bool
+ operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept {
+ return lhs.m_it < rhs.m_it;
+ }
+
+ primitive_iterator_t
+ operator+(difference_type n) noexcept {
+ auto result = *this;
+ result += n;
+ return result;
+ }
+
+ friend constexpr difference_type
+ operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept {
+ return lhs.m_it - rhs.m_it;
+ }
+
+ primitive_iterator_t&
+ operator++() noexcept {
+ ++m_it;
+ return *this;
+ }
+
+ primitive_iterator_t
+ operator++(int) & noexcept // NOLINT(cert-dcl21-cpp)
+ {
+ auto result = *this;
+ ++m_it;
+ return result;
+ }
+
+ primitive_iterator_t&
+ operator--() noexcept {
+ --m_it;
+ return *this;
+ }
+
+ primitive_iterator_t
+ operator--(int) & noexcept // NOLINT(cert-dcl21-cpp)
+ {
+ auto result = *this;
+ --m_it;
+ return result;
+ }
+
+ primitive_iterator_t&
+ operator+=(difference_type n) noexcept {
+ m_it += n;
+ return *this;
+ }
+
+ primitive_iterator_t&
+ operator-=(difference_type n) noexcept {
+ m_it -= n;
+ return *this;
+ }
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+/*!
+@brief an iterator value
+
+@note This structure could easily be a union, but MSVC currently does not allow
+unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
+*/
+template <typename BasicJsonType>
+struct internal_iterator {
+ /// iterator for JSON objects
+ typename BasicJsonType::object_t::iterator object_iterator{};
+ /// iterator for JSON arrays
+ typename BasicJsonType::array_t::iterator array_iterator{};
+ /// generic iterator for all other types
+ primitive_iterator_t primitive_iterator{};
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/iterators/iter_impl.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
+#include <type_traits> // conditional, is_const, remove_const
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/iterators/internal_iterator.hpp>
+
+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+// forward declare, to be able to friend it later on
+template <typename IteratorType>
+class iteration_proxy;
+template <typename IteratorType>
+class iteration_proxy_value;
+
+/*!
+@brief a template for a bidirectional iterator for the @ref basic_json class
+This class implements a both iterators (iterator and const_iterator) for the
+@ref basic_json class.
+@note An iterator is called *initialized* when a pointer to a JSON value has
+ been set (e.g., by a constructor or a copy assignment). If the iterator is
+ default-constructed, it is *uninitialized* and most methods are undefined.
+ **The library uses assertions to detect calls on uninitialized iterators.**
+@requirement The class satisfies the following concept requirements:
+-
+[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
+ The iterator that can be moved can be moved in both directions (i.e.
+ incremented and decremented).
+@since version 1.0.0, simplified in version 2.0.9, change to bidirectional
+ iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
+*/
+template <typename BasicJsonType>
+class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
+{
+ /// the iterator with BasicJsonType of different const-ness
+ using other_iter_impl = iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value,
+ typename std::remove_const<BasicJsonType>::type,
+ const BasicJsonType>::type>;
+ /// allow basic_json to access private members
+ friend other_iter_impl;
+ friend BasicJsonType;
+ friend iteration_proxy<iter_impl>;
+ friend iteration_proxy_value<iter_impl>;
+
+ using object_t = typename BasicJsonType::object_t;
+ using array_t = typename BasicJsonType::array_t;
+ // make sure BasicJsonType is basic_json or const basic_json
+ static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
+ "iter_impl only accepts (const) basic_json");
+ // superficial check for the LegacyBidirectionalIterator named requirement
+ static_assert(
+ std::is_base_of<std::bidirectional_iterator_tag, std::bidirectional_iterator_tag>::value &&
+ std::is_base_of<std::bidirectional_iterator_tag,
+ typename std::iterator_traits<typename array_t::iterator>::iterator_category>::value,
+ "basic_json iterator assumes array and object type iterators satisfy the LegacyBidirectionalIterator named "
+ "requirement.");
+
+ public:
+ /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
+ /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
+ /// A user-defined iterator should provide publicly accessible typedefs named
+ /// iterator_category, value_type, difference_type, pointer, and reference.
+ /// Note that value_type is required to be non-const, even for constant iterators.
+ using iterator_category = std::bidirectional_iterator_tag;
+
+ /// the type of the values when the iterator is dereferenced
+ using value_type = typename BasicJsonType::value_type;
+ /// a type to represent differences between iterators
+ using difference_type = typename BasicJsonType::difference_type;
+ /// defines a pointer to the type iterated over (value_type)
+ using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
+ typename BasicJsonType::const_pointer,
+ typename BasicJsonType::pointer>::type;
+ /// defines a reference to the type iterated over (value_type)
+ using reference = typename std::conditional<std::is_const<BasicJsonType>::value,
+ typename BasicJsonType::const_reference,
+ typename BasicJsonType::reference>::type;
+
+ iter_impl() = default;
+ ~iter_impl() = default;
+ iter_impl(iter_impl&&) noexcept = default;
+ iter_impl&
+ operator=(iter_impl&&) noexcept = default;
+
+ /*!
+ @brief constructor for a given JSON instance
+ @param[in] object pointer to a JSON object for this iterator
+ @pre object != nullptr
+ @post The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ explicit iter_impl(pointer object) noexcept : m_object(object) {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object: {
+ m_it.object_iterator = typename object_t::iterator();
+ break;
+ }
+
+ case value_t::array: {
+ m_it.array_iterator = typename array_t::iterator();
+ break;
+ }
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ m_it.primitive_iterator = primitive_iterator_t();
+ break;
+ }
+ }
+ }
+
+ /*!
+ @note The conventional copy constructor and copy assignment are implicitly
+ defined. Combined with the following converting constructor and
+ assignment, they support: (1) copy from iterator to iterator, (2)
+ copy from const iterator to const iterator, and (3) conversion from
+ iterator to const iterator. However conversion from const iterator
+ to iterator is not defined.
+ */
+
+ /*!
+ @brief const copy constructor
+ @param[in] other const iterator to copy from
+ @note This copy constructor had to be defined explicitly to circumvent a bug
+ occurring on msvc v19.0 compiler (VS 2015) debug build. For more
+ information refer to: https://github.com/nlohmann/json/issues/1608
+ */
+ iter_impl(const iter_impl<const BasicJsonType>& other) noexcept : m_object(other.m_object), m_it(other.m_it) {}
+
+ /*!
+ @brief converting assignment
+ @param[in] other const iterator to copy from
+ @return const/non-const iterator
+ @note It is not checked whether @a other is initialized.
+ */
+ iter_impl&
+ operator=(const iter_impl<const BasicJsonType>& other) noexcept {
+ if (&other != this) {
+ m_object = other.m_object;
+ m_it = other.m_it;
+ }
+ return *this;
+ }
+
+ /*!
+ @brief converting constructor
+ @param[in] other non-const iterator to copy from
+ @note It is not checked whether @a other is initialized.
+ */
+ iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
+ : m_object(other.m_object), m_it(other.m_it) {}
+
+ /*!
+ @brief converting assignment
+ @param[in] other non-const iterator to copy from
+ @return const/non-const iterator
+ @note It is not checked whether @a other is initialized.
+ */
+ iter_impl&
+ operator=(
+ const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept // NOLINT(cert-oop54-cpp)
+ {
+ m_object = other.m_object;
+ m_it = other.m_it;
+ return *this;
+ }
+
+ JSON_PRIVATE_UNLESS_TESTED :
+ /*!
+ @brief set the iterator to the first value
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ void
+ set_begin() noexcept {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object: {
+ m_it.object_iterator = m_object->m_data.m_value.object->begin();
+ break;
+ }
+
+ case value_t::array: {
+ m_it.array_iterator = m_object->m_data.m_value.array->begin();
+ break;
+ }
+
+ case value_t::null: {
+ // set to end so begin()==end() is true: null is empty
+ m_it.primitive_iterator.set_end();
+ break;
+ }
+
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ m_it.primitive_iterator.set_begin();
+ break;
+ }
+ }
+ }
+
+ /*!
+ @brief set the iterator past the last value
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ void
+ set_end() noexcept {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object: {
+ m_it.object_iterator = m_object->m_data.m_value.object->end();
+ break;
+ }
+
+ case value_t::array: {
+ m_it.array_iterator = m_object->m_data.m_value.array->end();
+ break;
+ }
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ m_it.primitive_iterator.set_end();
+ break;
+ }
+ }
+ }
+
+ public:
+ /*!
+ @brief return a reference to the value pointed to by the iterator
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ reference
+ operator*() const {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object: {
+ JSON_ASSERT(m_it.object_iterator != m_object->m_data.m_value.object->end());
+ return m_it.object_iterator->second;
+ }
+
+ case value_t::array: {
+ JSON_ASSERT(m_it.array_iterator != m_object->m_data.m_value.array->end());
+ return *m_it.array_iterator;
+ }
+
+ case value_t::null:
+ JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object));
+
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) {
+ return *m_object;
+ }
+
+ JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object));
+ }
+ }
+ }
+
+ /*!
+ @brief dereference the iterator
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ pointer
+ operator->() const {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object: {
+ JSON_ASSERT(m_it.object_iterator != m_object->m_data.m_value.object->end());
+ return &(m_it.object_iterator->second);
+ }
+
+ case value_t::array: {
+ JSON_ASSERT(m_it.array_iterator != m_object->m_data.m_value.array->end());
+ return &*m_it.array_iterator;
+ }
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) {
+ return m_object;
+ }
+
+ JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object));
+ }
+ }
+ }
+
+ /*!
+ @brief post-increment (it++)
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ iter_impl
+ operator++(int) & // NOLINT(cert-dcl21-cpp)
+ {
+ auto result = *this;
+ ++(*this);
+ return result;
+ }
+
+ /*!
+ @brief pre-increment (++it)
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ iter_impl&
+ operator++() {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object: {
+ std::advance(m_it.object_iterator, 1);
+ break;
+ }
+
+ case value_t::array: {
+ std::advance(m_it.array_iterator, 1);
+ break;
+ }
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ ++m_it.primitive_iterator;
+ break;
+ }
+ }
+
+ return *this;
+ }
+
+ /*!
+ @brief post-decrement (it--)
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ iter_impl
+ operator--(int) & // NOLINT(cert-dcl21-cpp)
+ {
+ auto result = *this;
+ --(*this);
+ return result;
+ }
+
+ /*!
+ @brief pre-decrement (--it)
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ iter_impl&
+ operator--() {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object: {
+ std::advance(m_it.object_iterator, -1);
+ break;
+ }
+
+ case value_t::array: {
+ std::advance(m_it.array_iterator, -1);
+ break;
+ }
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ --m_it.primitive_iterator;
+ break;
+ }
+ }
+
+ return *this;
+ }
+
+ /*!
+ @brief comparison: equal
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ template <typename IterImpl,
+ detail::enable_if_t<(std::is_same<IterImpl, iter_impl>::value ||
+ std::is_same<IterImpl, other_iter_impl>::value),
+ std::nullptr_t> = nullptr>
+ bool
+ operator==(const IterImpl& other) const {
+ // if objects are not the same, the comparison is undefined
+ if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) {
+ JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", m_object));
+ }
+
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object:
+ return (m_it.object_iterator == other.m_it.object_iterator);
+
+ case value_t::array:
+ return (m_it.array_iterator == other.m_it.array_iterator);
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default:
+ return (m_it.primitive_iterator == other.m_it.primitive_iterator);
+ }
+ }
+
+ /*!
+ @brief comparison: not equal
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ template <typename IterImpl,
+ detail::enable_if_t<(std::is_same<IterImpl, iter_impl>::value ||
+ std::is_same<IterImpl, other_iter_impl>::value),
+ std::nullptr_t> = nullptr>
+ bool
+ operator!=(const IterImpl& other) const {
+ return !operator==(other);
+ }
+
+ /*!
+ @brief comparison: smaller
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ bool
+ operator<(const iter_impl& other) const {
+ // if objects are not the same, the comparison is undefined
+ if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) {
+ JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", m_object));
+ }
+
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object:
+ JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", m_object));
+
+ case value_t::array:
+ return (m_it.array_iterator < other.m_it.array_iterator);
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default:
+ return (m_it.primitive_iterator < other.m_it.primitive_iterator);
+ }
+ }
+
+ /*!
+ @brief comparison: less than or equal
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ bool
+ operator<=(const iter_impl& other) const {
+ return !other.operator<(*this);
+ }
+
+ /*!
+ @brief comparison: greater than
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ bool
+ operator>(const iter_impl& other) const {
+ return !operator<=(other);
+ }
+
+ /*!
+ @brief comparison: greater than or equal
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ bool
+ operator>=(const iter_impl& other) const {
+ return !operator<(other);
+ }
+
+ /*!
+ @brief add to iterator
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ iter_impl&
+ operator+=(difference_type i) {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object:
+ JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", m_object));
+
+ case value_t::array: {
+ std::advance(m_it.array_iterator, i);
+ break;
+ }
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ m_it.primitive_iterator += i;
+ break;
+ }
+ }
+
+ return *this;
+ }
+
+ /*!
+ @brief subtract from iterator
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ iter_impl&
+ operator-=(difference_type i) {
+ return operator+=(-i);
+ }
+
+ /*!
+ @brief add to iterator
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ iter_impl
+ operator+(difference_type i) const {
+ auto result = *this;
+ result += i;
+ return result;
+ }
+
+ /*!
+ @brief addition of distance and iterator
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ friend iter_impl
+ operator+(difference_type i, const iter_impl& it) {
+ auto result = it;
+ result += i;
+ return result;
+ }
+
+ /*!
+ @brief subtract from iterator
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ iter_impl
+ operator-(difference_type i) const {
+ auto result = *this;
+ result -= i;
+ return result;
+ }
+
+ /*!
+ @brief return difference
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ difference_type
+ operator-(const iter_impl& other) const {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object:
+ JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", m_object));
+
+ case value_t::array:
+ return m_it.array_iterator - other.m_it.array_iterator;
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default:
+ return m_it.primitive_iterator - other.m_it.primitive_iterator;
+ }
+ }
+
+ /*!
+ @brief access to successor
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ reference
+ operator[](difference_type n) const {
+ JSON_ASSERT(m_object != nullptr);
+
+ switch (m_object->m_data.m_type) {
+ case value_t::object:
+ JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", m_object));
+
+ case value_t::array:
+ return *std::next(m_it.array_iterator, n);
+
+ case value_t::null:
+ JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object));
+
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) {
+ return *m_object;
+ }
+
+ JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object));
+ }
+ }
+ }
+
+ /*!
+ @brief return the key of an object iterator
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ const typename object_t::key_type&
+ key() const {
+ JSON_ASSERT(m_object != nullptr);
+
+ if (JSON_HEDLEY_LIKELY(m_object->is_object())) {
+ return m_it.object_iterator->first;
+ }
+
+ JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", m_object));
+ }
+
+ /*!
+ @brief return the value of an iterator
+ @pre The iterator is initialized; i.e. `m_object != nullptr`.
+ */
+ reference
+ value() const {
+ return operator*();
+ }
+
+ JSON_PRIVATE_UNLESS_TESTED :
+ /// associated JSON instance
+ pointer m_object = nullptr;
+ /// the actual iterator of the associated instance
+ internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it{};
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
+
+// #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <cstddef> // ptrdiff_t
+#include <iterator> // reverse_iterator
+#include <utility> // declval
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+//////////////////////
+// reverse_iterator //
+//////////////////////
+
+/*!
+@brief a template for a reverse iterator class
+
+@tparam Base the base iterator type to reverse. Valid types are @ref
+iterator (to create @ref reverse_iterator) and @ref const_iterator (to
+create @ref const_reverse_iterator).
+
+@requirement The class satisfies the following concept requirements:
+-
+[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
+ The iterator that can be moved can be moved in both directions (i.e.
+ incremented and decremented).
+- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
+ It is possible to write to the pointed-to element (only if @a Base is
+ @ref iterator).
+
+@since version 1.0.0
+*/
+template <typename Base>
+class json_reverse_iterator : public std::reverse_iterator<Base> {
+ public:
+ using difference_type = std::ptrdiff_t;
+ /// shortcut to the reverse iterator adapter
+ using base_iterator = std::reverse_iterator<Base>;
+ /// the reference type for the pointed-to element
+ using reference = typename Base::reference;
+
+ /// create reverse iterator from iterator
+ explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept : base_iterator(it) {}
+
+ /// create reverse iterator from base class
+ explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
+
+ /// post-increment (it++)
+ json_reverse_iterator
+ operator++(int) & // NOLINT(cert-dcl21-cpp)
+ {
+ return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
+ }
+
+ /// pre-increment (++it)
+ json_reverse_iterator&
+ operator++() {
+ return static_cast<json_reverse_iterator&>(base_iterator::operator++());
+ }
+
+ /// post-decrement (it--)
+ json_reverse_iterator
+ operator--(int) & // NOLINT(cert-dcl21-cpp)
+ {
+ return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
+ }
+
+ /// pre-decrement (--it)
+ json_reverse_iterator&
+ operator--() {
+ return static_cast<json_reverse_iterator&>(base_iterator::operator--());
+ }
+
+ /// add to iterator
+ json_reverse_iterator&
+ operator+=(difference_type i) {
+ return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
+ }
+
+ /// add to iterator
+ json_reverse_iterator
+ operator+(difference_type i) const {
+ return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
+ }
+
+ /// subtract from iterator
+ json_reverse_iterator
+ operator-(difference_type i) const {
+ return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
+ }
+
+ /// return difference
+ difference_type
+ operator-(const json_reverse_iterator& other) const {
+ return base_iterator(*this) - base_iterator(other);
+ }
+
+ /// access to successor
+ reference
+ operator[](difference_type n) const {
+ return *(this->operator+(n));
+ }
+
+ /// return the key of an object iterator
+ auto
+ key() const -> decltype(std::declval<Base>().key()) {
+ auto it = --this->base();
+ return it.key();
+ }
+
+ /// return the value of an iterator
+ reference
+ value() const {
+ auto it = --this->base();
+ return it.operator*();
+ }
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
+
+// #include <nlohmann/detail/json_custom_base_class.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <type_traits> // conditional, is_same
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+/*!
+@brief Default base class of the @ref basic_json class.
+
+So that the correct implementations of the copy / move ctors / assign operators
+of @ref basic_json do not require complex case distinctions
+(no base class / custom base class used as customization point),
+@ref basic_json always has a base class.
+By default, this class is used because it is empty and thus has no effect
+on the behavior of @ref basic_json.
+*/
+struct json_default_base {};
+
+template <class T>
+using json_base_class = typename std::conditional<std::is_same<T, void>::value, json_default_base, T>::type;
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/json_pointer.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <algorithm> // all_of
+#include <cctype> // isdigit
+#include <cerrno> // errno, ERANGE
+#include <cstdlib> // strtoull
+#ifndef JSON_NO_IO
+#include <iosfwd> // ostream
+#endif // JSON_NO_IO
+#include <limits> // max
+#include <numeric> // accumulate
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/string_concat.hpp>
+
+// #include <nlohmann/detail/string_escape.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+
+/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
+/// @sa https://json.nlohmann.me/api/json_pointer/
+template <typename RefStringType>
+class json_pointer {
+ // allow basic_json to access private members
+ NLOHMANN_BASIC_JSON_TPL_DECLARATION
+ friend class basic_json;
+
+ template <typename>
+ friend class json_pointer;
+
+ template <typename T>
+ struct string_t_helper {
+ using type = T;
+ };
+
+ NLOHMANN_BASIC_JSON_TPL_DECLARATION
+ struct string_t_helper<NLOHMANN_BASIC_JSON_TPL> {
+ using type = StringType;
+ };
+
+ public:
+ // for backwards compatibility accept BasicJsonType
+ using string_t = typename string_t_helper<RefStringType>::type;
+
+ /// @brief create JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/
+ explicit json_pointer(const string_t& s = "") : reference_tokens(split(s)) {}
+
+ /// @brief return a string representation of the JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/to_string/
+ string_t
+ to_string() const {
+ return std::accumulate(
+ reference_tokens.begin(), reference_tokens.end(), string_t{}, [](const string_t& a, const string_t& b) {
+ return detail::concat(a, '/', detail::escape(b));
+ });
+ }
+
+ /// @brief return a string representation of the JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0, to_string())
+ operator string_t() const { return to_string(); }
+
+#ifndef JSON_NO_IO
+ /// @brief write string representation of the JSON pointer to stream
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
+ friend std::ostream&
+ operator<<(std::ostream& o, const json_pointer& ptr) {
+ o << ptr.to_string();
+ return o;
+ }
+#endif
+
+ /// @brief append another JSON pointer at the end of this JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
+ json_pointer&
+ operator/=(const json_pointer& ptr) {
+ reference_tokens.insert(reference_tokens.end(), ptr.reference_tokens.begin(), ptr.reference_tokens.end());
+ return *this;
+ }
+
+ /// @brief append an unescaped reference token at the end of this JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
+ json_pointer&
+ operator/=(string_t token) {
+ push_back(std::move(token));
+ return *this;
+ }
+
+ /// @brief append an array index at the end of this JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
+ json_pointer&
+ operator/=(std::size_t array_idx) {
+ return *this /= std::to_string(array_idx);
+ }
+
+ /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
+ friend json_pointer
+ operator/(const json_pointer& lhs, const json_pointer& rhs) {
+ return json_pointer(lhs) /= rhs;
+ }
+
+ /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
+ friend json_pointer
+ operator/(const json_pointer& lhs, string_t token) // NOLINT(performance-unnecessary-value-param)
+ {
+ return json_pointer(lhs) /= std::move(token);
+ }
+
+ /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
+ friend json_pointer
+ operator/(const json_pointer& lhs, std::size_t array_idx) {
+ return json_pointer(lhs) /= array_idx;
+ }
+
+ /// @brief returns the parent of this JSON pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/
+ json_pointer
+ parent_pointer() const {
+ if (empty()) {
+ return *this;
+ }
+
+ json_pointer res = *this;
+ res.pop_back();
+ return res;
+ }
+
+ /// @brief remove last reference token
+ /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/
+ void
+ pop_back() {
+ if (JSON_HEDLEY_UNLIKELY(empty())) {
+ JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", nullptr));
+ }
+
+ reference_tokens.pop_back();
+ }
+
+ /// @brief return last reference token
+ /// @sa https://json.nlohmann.me/api/json_pointer/back/
+ const string_t&
+ back() const {
+ if (JSON_HEDLEY_UNLIKELY(empty())) {
+ JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", nullptr));
+ }
+
+ return reference_tokens.back();
+ }
+
+ /// @brief append an unescaped token at the end of the reference pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/push_back/
+ void
+ push_back(const string_t& token) {
+ reference_tokens.push_back(token);
+ }
+
+ /// @brief append an unescaped token at the end of the reference pointer
+ /// @sa https://json.nlohmann.me/api/json_pointer/push_back/
+ void
+ push_back(string_t&& token) {
+ reference_tokens.push_back(std::move(token));
+ }
+
+ /// @brief return whether pointer points to the root document
+ /// @sa https://json.nlohmann.me/api/json_pointer/empty/
+ bool
+ empty() const noexcept {
+ return reference_tokens.empty();
+ }
+
+ private:
+ /*!
+ @param[in] s reference token to be converted into an array index
+
+ @return integer representation of @a s
+
+ @throw parse_error.106 if an array index begins with '0'
+ @throw parse_error.109 if an array index begins not with a digit
+ @throw out_of_range.404 if string @a s could not be converted to an integer
+ @throw out_of_range.410 if an array index exceeds size_type
+ */
+ template <typename BasicJsonType>
+ static typename BasicJsonType::size_type
+ array_index(const string_t& s) {
+ using size_type = typename BasicJsonType::size_type;
+
+ // error condition (cf. RFC 6901, Sect. 4)
+ if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) {
+ JSON_THROW(detail::parse_error::create(
+ 106, 0, detail::concat("array index '", s, "' must not begin with '0'"), nullptr));
+ }
+
+ // error condition (cf. RFC 6901, Sect. 4)
+ if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) {
+ JSON_THROW(
+ detail::parse_error::create(109, 0, detail::concat("array index '", s, "' is not a number"), nullptr));
+ }
+
+ const char* p = s.c_str();
+ char* p_end = nullptr;
+ errno = 0; // strtoull doesn't reset errno
+ const unsigned long long res = std::strtoull(p, &p_end, 10); // NOLINT(runtime/int)
+ if (p == p_end // invalid input or empty string
+ || errno == ERANGE // out of range
+ || JSON_HEDLEY_UNLIKELY(static_cast<std::size_t>(p_end - p) != s.size())) // incomplete read
+ {
+ JSON_THROW(
+ detail::out_of_range::create(404, detail::concat("unresolved reference token '", s, "'"), nullptr));
+ }
+
+ // only triggered on special platforms (like 32bit), see also
+ // https://github.com/nlohmann/json/pull/2203
+ if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)())) // NOLINT(runtime/int)
+ {
+ JSON_THROW(detail::out_of_range::create(
+ 410, detail::concat("array index ", s, " exceeds size_type"), nullptr)); // LCOV_EXCL_LINE
+ }
+
+ return static_cast<size_type>(res);
+ }
+
+ JSON_PRIVATE_UNLESS_TESTED : json_pointer
+ top() const {
+ if (JSON_HEDLEY_UNLIKELY(empty())) {
+ JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", nullptr));
+ }
+
+ json_pointer result = *this;
+ result.reference_tokens = {reference_tokens[0]};
+ return result;
+ }
+
+ private:
+ /*!
+ @brief create and return a reference to the pointed to value
+
+ @complexity Linear in the number of reference tokens.
+
+ @throw parse_error.109 if array index is not a number
+ @throw type_error.313 if value cannot be unflattened
+ */
+ template <typename BasicJsonType>
+ BasicJsonType&
+ get_and_create(BasicJsonType& j) const {
+ auto* result = &j;
+
+ // in case no reference tokens exist, return a reference to the JSON value
+ // j which will be overwritten by a primitive value
+ for (const auto& reference_token : reference_tokens) {
+ switch (result->type()) {
+ case detail::value_t::null: {
+ if (reference_token == "0") {
+ // start a new array if reference token is 0
+ result = &result->operator[](0);
+ } else {
+ // start a new object otherwise
+ result = &result->operator[](reference_token);
+ }
+ break;
+ }
+
+ case detail::value_t::object: {
+ // create an entry in the object
+ result = &result->operator[](reference_token);
+ break;
+ }
+
+ case detail::value_t::array: {
+ // create an entry in the array
+ result = &result->operator[](array_index<BasicJsonType>(reference_token));
+ break;
+ }
+
+ /*
+ The following code is only reached if there exists a reference
+ token _and_ the current value is primitive. In this case, we have
+ an error situation, because primitive values may only occur as
+ single value; that is, with an empty list of reference tokens.
+ */
+ case detail::value_t::string:
+ case detail::value_t::boolean:
+ case detail::value_t::number_integer:
+ case detail::value_t::number_unsigned:
+ case detail::value_t::number_float:
+ case detail::value_t::binary:
+ case detail::value_t::discarded:
+ default:
+ JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", &j));
+ }
+ }
+
+ return *result;
+ }
+
+ /*!
+ @brief return a reference to the pointed to value
+
+ @note This version does not throw if a value is not present, but tries to
+ create nested values instead. For instance, calling this function
+ with pointer `"/this/that"` on a null value is equivalent to calling
+ `operator[]("this").operator[]("that")` on that value, effectively
+ changing the null value to an object.
+
+ @param[in] ptr a JSON value
+
+ @return reference to the JSON value pointed to by the JSON pointer
+
+ @complexity Linear in the length of the JSON pointer.
+
+ @throw parse_error.106 if an array index begins with '0'
+ @throw parse_error.109 if an array index was not a number
+ @throw out_of_range.404 if the JSON pointer can not be resolved
+ */
+ template <typename BasicJsonType>
+ BasicJsonType&
+ get_unchecked(BasicJsonType* ptr) const {
+ for (const auto& reference_token : reference_tokens) {
+ // convert null values to arrays or objects before continuing
+ if (ptr->is_null()) {
+ // check if reference token is a number
+ const bool nums = std::all_of(reference_token.begin(),
+ reference_token.end(),
+ [](const unsigned char x) { return std::isdigit(x); });
+
+ // change value to array for numbers or "-" or to object otherwise
+ *ptr = (nums || reference_token == "-") ? detail::value_t::array : detail::value_t::object;
+ }
+
+ switch (ptr->type()) {
+ case detail::value_t::object: {
+ // use unchecked object access
+ ptr = &ptr->operator[](reference_token);
+ break;
+ }
+
+ case detail::value_t::array: {
+ if (reference_token == "-") {
+ // explicitly treat "-" as index beyond the end
+ ptr = &ptr->operator[](ptr->m_data.m_value.array->size());
+ } else {
+ // convert array index to number; unchecked access
+ ptr = &ptr->operator[](array_index<BasicJsonType>(reference_token));
+ }
+ break;
+ }
+
+ case detail::value_t::null:
+ case detail::value_t::string:
+ case detail::value_t::boolean:
+ case detail::value_t::number_integer:
+ case detail::value_t::number_unsigned:
+ case detail::value_t::number_float:
+ case detail::value_t::binary:
+ case detail::value_t::discarded:
+ default:
+ JSON_THROW(detail::out_of_range::create(
+ 404, detail::concat("unresolved reference token '", reference_token, "'"), ptr));
+ }
+ }
+
+ return *ptr;
+ }
+
+ /*!
+ @throw parse_error.106 if an array index begins with '0'
+ @throw parse_error.109 if an array index was not a number
+ @throw out_of_range.402 if the array index '-' is used
+ @throw out_of_range.404 if the JSON pointer can not be resolved
+ */
+ template <typename BasicJsonType>
+ BasicJsonType&
+ get_checked(BasicJsonType* ptr) const {
+ for (const auto& reference_token : reference_tokens) {
+ switch (ptr->type()) {
+ case detail::value_t::object: {
+ // note: at performs range check
+ ptr = &ptr->at(reference_token);
+ break;
+ }
+
+ case detail::value_t::array: {
+ if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) {
+ // "-" always fails the range check
+ JSON_THROW(detail::out_of_range::create(
+ 402,
+ detail::concat("array index '-' (",
+ std::to_string(ptr->m_data.m_value.array->size()),
+ ") is out of range"),
+ ptr));
+ }
+
+ // note: at performs range check
+ ptr = &ptr->at(array_index<BasicJsonType>(reference_token));
+ break;
+ }
+
+ case detail::value_t::null:
+ case detail::value_t::string:
+ case detail::value_t::boolean:
+ case detail::value_t::number_integer:
+ case detail::value_t::number_unsigned:
+ case detail::value_t::number_float:
+ case detail::value_t::binary:
+ case detail::value_t::discarded:
+ default:
+ JSON_THROW(detail::out_of_range::create(
+ 404, detail::concat("unresolved reference token '", reference_token, "'"), ptr));
+ }
+ }
+
+ return *ptr;
+ }
+
+ /*!
+ @brief return a const reference to the pointed to value
+
+ @param[in] ptr a JSON value
+
+ @return const reference to the JSON value pointed to by the JSON
+ pointer
+
+ @throw parse_error.106 if an array index begins with '0'
+ @throw parse_error.109 if an array index was not a number
+ @throw out_of_range.402 if the array index '-' is used
+ @throw out_of_range.404 if the JSON pointer can not be resolved
+ */
+ template <typename BasicJsonType>
+ const BasicJsonType&
+ get_unchecked(const BasicJsonType* ptr) const {
+ for (const auto& reference_token : reference_tokens) {
+ switch (ptr->type()) {
+ case detail::value_t::object: {
+ // use unchecked object access
+ ptr = &ptr->operator[](reference_token);
+ break;
+ }
+
+ case detail::value_t::array: {
+ if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) {
+ // "-" cannot be used for const access
+ JSON_THROW(detail::out_of_range::create(
+ 402,
+ detail::concat("array index '-' (",
+ std::to_string(ptr->m_data.m_value.array->size()),
+ ") is out of range"),
+ ptr));
+ }
+
+ // use unchecked array access
+ ptr = &ptr->operator[](array_index<BasicJsonType>(reference_token));
+ break;
+ }
+
+ case detail::value_t::null:
+ case detail::value_t::string:
+ case detail::value_t::boolean:
+ case detail::value_t::number_integer:
+ case detail::value_t::number_unsigned:
+ case detail::value_t::number_float:
+ case detail::value_t::binary:
+ case detail::value_t::discarded:
+ default:
+ JSON_THROW(detail::out_of_range::create(
+ 404, detail::concat("unresolved reference token '", reference_token, "'"), ptr));
+ }
+ }
+
+ return *ptr;
+ }
+
+ /*!
+ @throw parse_error.106 if an array index begins with '0'
+ @throw parse_error.109 if an array index was not a number
+ @throw out_of_range.402 if the array index '-' is used
+ @throw out_of_range.404 if the JSON pointer can not be resolved
+ */
+ template <typename BasicJsonType>
+ const BasicJsonType&
+ get_checked(const BasicJsonType* ptr) const {
+ for (const auto& reference_token : reference_tokens) {
+ switch (ptr->type()) {
+ case detail::value_t::object: {
+ // note: at performs range check
+ ptr = &ptr->at(reference_token);
+ break;
+ }
+
+ case detail::value_t::array: {
+ if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) {
+ // "-" always fails the range check
+ JSON_THROW(detail::out_of_range::create(
+ 402,
+ detail::concat("array index '-' (",
+ std::to_string(ptr->m_data.m_value.array->size()),
+ ") is out of range"),
+ ptr));
+ }
+
+ // note: at performs range check
+ ptr = &ptr->at(array_index<BasicJsonType>(reference_token));
+ break;
+ }
+
+ case detail::value_t::null:
+ case detail::value_t::string:
+ case detail::value_t::boolean:
+ case detail::value_t::number_integer:
+ case detail::value_t::number_unsigned:
+ case detail::value_t::number_float:
+ case detail::value_t::binary:
+ case detail::value_t::discarded:
+ default:
+ JSON_THROW(detail::out_of_range::create(
+ 404, detail::concat("unresolved reference token '", reference_token, "'"), ptr));
+ }
+ }
+
+ return *ptr;
+ }
+
+ /*!
+ @throw parse_error.106 if an array index begins with '0'
+ @throw parse_error.109 if an array index was not a number
+ */
+ template <typename BasicJsonType>
+ bool
+ contains(const BasicJsonType* ptr) const {
+ for (const auto& reference_token : reference_tokens) {
+ switch (ptr->type()) {
+ case detail::value_t::object: {
+ if (!ptr->contains(reference_token)) {
+ // we did not find the key in the object
+ return false;
+ }
+
+ ptr = &ptr->operator[](reference_token);
+ break;
+ }
+
+ case detail::value_t::array: {
+ if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) {
+ // "-" always fails the range check
+ return false;
+ }
+ if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 &&
+ !("0" <= reference_token && reference_token <= "9"))) {
+ // invalid char
+ return false;
+ }
+ if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) {
+ if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) {
+ // first char should be between '1' and '9'
+ return false;
+ }
+ for (std::size_t i = 1; i < reference_token.size(); i++) {
+ if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) {
+ // other char should be between '0' and '9'
+ return false;
+ }
+ }
+ }
+
+ const auto idx = array_index<BasicJsonType>(reference_token);
+ if (idx >= ptr->size()) {
+ // index out of range
+ return false;
+ }
+
+ ptr = &ptr->operator[](idx);
+ break;
+ }
+
+ case detail::value_t::null:
+ case detail::value_t::string:
+ case detail::value_t::boolean:
+ case detail::value_t::number_integer:
+ case detail::value_t::number_unsigned:
+ case detail::value_t::number_float:
+ case detail::value_t::binary:
+ case detail::value_t::discarded:
+ default: {
+ // we do not expect primitive values if there is still a
+ // reference token to process
+ return false;
+ }
+ }
+ }
+
+ // no reference token left means we found a primitive value
+ return true;
+ }
+
+ /*!
+ @brief split the string input to reference tokens
+
+ @note This function is only called by the json_pointer constructor.
+ All exceptions below are documented there.
+
+ @throw parse_error.107 if the pointer is not empty or begins with '/'
+ @throw parse_error.108 if character '~' is not followed by '0' or '1'
+ */
+ static std::vector<string_t>
+ split(const string_t& reference_string) {
+ std::vector<string_t> result;
+
+ // special case: empty reference string -> no reference tokens
+ if (reference_string.empty()) {
+ return result;
+ }
+
+ // check if nonempty reference string begins with slash
+ if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) {
+ JSON_THROW(detail::parse_error::create(
+ 107,
+ 1,
+ detail::concat("JSON pointer must be empty or begin with '/' - was: '", reference_string, "'"),
+ nullptr));
+ }
+
+ // extract the reference tokens:
+ // - slash: position of the last read slash (or end of string)
+ // - start: position after the previous slash
+ for (
+ // search for the first slash after the first character
+ std::size_t slash = reference_string.find_first_of('/', 1),
+ // set the beginning of the first reference token
+ start = 1;
+ // we can stop if start == 0 (if slash == string_t::npos)
+ start != 0;
+ // set the beginning of the next reference token
+ // (will eventually be 0 if slash == string_t::npos)
+ start = (slash == string_t::npos) ? 0 : slash + 1,
+ // find next slash
+ slash = reference_string.find_first_of('/', start)) {
+ // use the text between the beginning of the reference token
+ // (start) and the last slash (slash).
+ auto reference_token = reference_string.substr(start, slash - start);
+
+ // check reference tokens are properly escaped
+ for (std::size_t pos = reference_token.find_first_of('~'); pos != string_t::npos;
+ pos = reference_token.find_first_of('~', pos + 1)) {
+ JSON_ASSERT(reference_token[pos] == '~');
+
+ // ~ must be followed by 0 or 1
+ if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 ||
+ (reference_token[pos + 1] != '0' && reference_token[pos + 1] != '1'))) {
+ JSON_THROW(detail::parse_error::create(
+ 108, 0, "escape character '~' must be followed with '0' or '1'", nullptr));
+ }
+ }
+
+ // finally, store the reference token
+ detail::unescape(reference_token);
+ result.push_back(reference_token);
+ }
+
+ return result;
+ }
+
+ private:
+ /*!
+ @param[in] reference_string the reference string to the current value
+ @param[in] value the value to consider
+ @param[in,out] result the result object to insert values to
+
+ @note Empty objects or arrays are flattened to `null`.
+ */
+ template <typename BasicJsonType>
+ static void
+ flatten(const string_t& reference_string, const BasicJsonType& value, BasicJsonType& result) {
+ switch (value.type()) {
+ case detail::value_t::array: {
+ if (value.m_data.m_value.array->empty()) {
+ // flatten empty array as null
+ result[reference_string] = nullptr;
+ } else {
+ // iterate array and use index as reference string
+ for (std::size_t i = 0; i < value.m_data.m_value.array->size(); ++i) {
+ flatten(detail::concat(reference_string, '/', std::to_string(i)),
+ value.m_data.m_value.array->operator[](i),
+ result);
+ }
+ }
+ break;
+ }
+
+ case detail::value_t::object: {
+ if (value.m_data.m_value.object->empty()) {
+ // flatten empty object as null
+ result[reference_string] = nullptr;
+ } else {
+ // iterate object and use keys as reference string
+ for (const auto& element : *value.m_data.m_value.object) {
+ flatten(detail::concat(reference_string, '/', detail::escape(element.first)),
+ element.second,
+ result);
+ }
+ }
+ break;
+ }
+
+ case detail::value_t::null:
+ case detail::value_t::string:
+ case detail::value_t::boolean:
+ case detail::value_t::number_integer:
+ case detail::value_t::number_unsigned:
+ case detail::value_t::number_float:
+ case detail::value_t::binary:
+ case detail::value_t::discarded:
+ default: {
+ // add primitive value with its reference string
+ result[reference_string] = value;
+ break;
+ }
+ }
+ }
+
+ /*!
+ @param[in] value flattened JSON
+
+ @return unflattened JSON
+
+ @throw parse_error.109 if array index is not a number
+ @throw type_error.314 if value is not an object
+ @throw type_error.315 if object values are not primitive
+ @throw type_error.313 if value cannot be unflattened
+ */
+ template <typename BasicJsonType>
+ static BasicJsonType
+ unflatten(const BasicJsonType& value) {
+ if (JSON_HEDLEY_UNLIKELY(!value.is_object())) {
+ JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", &value));
+ }
+
+ BasicJsonType result;
+
+ // iterate the JSON object values
+ for (const auto& element : *value.m_data.m_value.object) {
+ if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) {
+ JSON_THROW(detail::type_error::create(315, "values in object must be primitive", &element.second));
+ }
+
+ // assign value to reference pointed to by JSON pointer; Note that if
+ // the JSON pointer is "" (i.e., points to the whole value), function
+ // get_and_create returns a reference to result itself. An assignment
+ // will then create a primitive value.
+ json_pointer(element.first).get_and_create(result) = element.second;
+ }
+
+ return result;
+ }
+
+ // can't use conversion operator because of ambiguity
+ json_pointer<string_t>
+ convert() const& {
+ json_pointer<string_t> result;
+ result.reference_tokens = reference_tokens;
+ return result;
+ }
+
+ json_pointer<string_t>
+ convert() && {
+ json_pointer<string_t> result;
+ result.reference_tokens = std::move(reference_tokens);
+ return result;
+ }
+
+ public:
+#if JSON_HAS_THREE_WAY_COMPARISON
+ /// @brief compares two JSON pointers for equality
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/
+ template <typename RefStringTypeRhs>
+ bool
+ operator==(const json_pointer<RefStringTypeRhs>& rhs) const noexcept {
+ return reference_tokens == rhs.reference_tokens;
+ }
+
+ /// @brief compares JSON pointer and string for equality
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator==(json_pointer))
+ bool
+ operator==(const string_t& rhs) const {
+ return *this == json_pointer(rhs);
+ }
+
+ /// @brief 3-way compares two JSON pointers
+ template <typename RefStringTypeRhs>
+ std::strong_ordering
+ operator<=>(const json_pointer<RefStringTypeRhs>& rhs) const noexcept // *NOPAD*
+ {
+ return reference_tokens <=> rhs.reference_tokens; // *NOPAD*
+ }
+#else
+ /// @brief compares two JSON pointers for equality
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/
+ template <typename RefStringTypeLhs, typename RefStringTypeRhs>
+ // NOLINTNEXTLINE(readability-redundant-declaration)
+ friend bool
+ operator==(const json_pointer<RefStringTypeLhs>& lhs, const json_pointer<RefStringTypeRhs>& rhs) noexcept;
+
+ /// @brief compares JSON pointer and string for equality
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/
+ template <typename RefStringTypeLhs, typename StringType>
+ // NOLINTNEXTLINE(readability-redundant-declaration)
+ friend bool
+ operator==(const json_pointer<RefStringTypeLhs>& lhs, const StringType& rhs);
+
+ /// @brief compares string and JSON pointer for equality
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/
+ template <typename RefStringTypeRhs, typename StringType>
+ // NOLINTNEXTLINE(readability-redundant-declaration)
+ friend bool
+ operator==(const StringType& lhs, const json_pointer<RefStringTypeRhs>& rhs);
+
+ /// @brief compares two JSON pointers for inequality
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_ne/
+ template <typename RefStringTypeLhs, typename RefStringTypeRhs>
+ // NOLINTNEXTLINE(readability-redundant-declaration)
+ friend bool
+ operator!=(const json_pointer<RefStringTypeLhs>& lhs, const json_pointer<RefStringTypeRhs>& rhs) noexcept;
+
+ /// @brief compares JSON pointer and string for inequality
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_ne/
+ template <typename RefStringTypeLhs, typename StringType>
+ // NOLINTNEXTLINE(readability-redundant-declaration)
+ friend bool
+ operator!=(const json_pointer<RefStringTypeLhs>& lhs, const StringType& rhs);
+
+ /// @brief compares string and JSON pointer for inequality
+ /// @sa https://json.nlohmann.me/api/json_pointer/operator_ne/
+ template <typename RefStringTypeRhs, typename StringType>
+ // NOLINTNEXTLINE(readability-redundant-declaration)
+ friend bool
+ operator!=(const StringType& lhs, const json_pointer<RefStringTypeRhs>& rhs);
+
+ /// @brief compares two JSON pointer for less-than
+ template <typename RefStringTypeLhs, typename RefStringTypeRhs>
+ // NOLINTNEXTLINE(readability-redundant-declaration)
+ friend bool
+ operator<(const json_pointer<RefStringTypeLhs>& lhs, const json_pointer<RefStringTypeRhs>& rhs) noexcept;
+#endif
+
+ private:
+ /// the reference tokens
+ std::vector<string_t> reference_tokens;
+};
+
+#if !JSON_HAS_THREE_WAY_COMPARISON
+// functions cannot be defined inside class due to ODR violations
+template <typename RefStringTypeLhs, typename RefStringTypeRhs>
+inline bool
+operator==(const json_pointer<RefStringTypeLhs>& lhs, const json_pointer<RefStringTypeRhs>& rhs) noexcept {
+ return lhs.reference_tokens == rhs.reference_tokens;
+}
+
+template <typename RefStringTypeLhs, typename StringType = typename json_pointer<RefStringTypeLhs>::string_t>
+JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator==(json_pointer, json_pointer))
+inline bool
+operator==(const json_pointer<RefStringTypeLhs>& lhs, const StringType& rhs) {
+ return lhs == json_pointer<RefStringTypeLhs>(rhs);
+}
+
+template <typename RefStringTypeRhs, typename StringType = typename json_pointer<RefStringTypeRhs>::string_t>
+JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator==(json_pointer, json_pointer))
+inline bool
+operator==(const StringType& lhs, const json_pointer<RefStringTypeRhs>& rhs) {
+ return json_pointer<RefStringTypeRhs>(lhs) == rhs;
+}
+
+template <typename RefStringTypeLhs, typename RefStringTypeRhs>
+inline bool
+operator!=(const json_pointer<RefStringTypeLhs>& lhs, const json_pointer<RefStringTypeRhs>& rhs) noexcept {
+ return !(lhs == rhs);
+}
+
+template <typename RefStringTypeLhs, typename StringType = typename json_pointer<RefStringTypeLhs>::string_t>
+JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator!=(json_pointer, json_pointer))
+inline bool
+operator!=(const json_pointer<RefStringTypeLhs>& lhs, const StringType& rhs) {
+ return !(lhs == rhs);
+}
+
+template <typename RefStringTypeRhs, typename StringType = typename json_pointer<RefStringTypeRhs>::string_t>
+JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator!=(json_pointer, json_pointer))
+inline bool
+operator!=(const StringType& lhs, const json_pointer<RefStringTypeRhs>& rhs) {
+ return !(lhs == rhs);
+}
+
+template <typename RefStringTypeLhs, typename RefStringTypeRhs>
+inline bool
+operator<(const json_pointer<RefStringTypeLhs>& lhs, const json_pointer<RefStringTypeRhs>& rhs) noexcept {
+ return lhs.reference_tokens < rhs.reference_tokens;
+}
+#endif
+
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/json_ref.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <initializer_list>
+#include <utility>
+
+// #include <nlohmann/detail/abi_macros.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+template <typename BasicJsonType>
+class json_ref {
+ public:
+ using value_type = BasicJsonType;
+
+ json_ref(value_type&& value) : owned_value(std::move(value)) {}
+
+ json_ref(const value_type& value) : value_ref(&value) {}
+
+ json_ref(std::initializer_list<json_ref> init) : owned_value(init) {}
+
+ template <class... Args, enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0>
+ json_ref(Args&&... args) : owned_value(std::forward<Args>(args)...) {}
+
+ // class should be movable only
+ json_ref(json_ref&&) noexcept = default;
+ json_ref(const json_ref&) = delete;
+ json_ref&
+ operator=(const json_ref&) = delete;
+ json_ref&
+ operator=(json_ref&&) = delete;
+ ~json_ref() = default;
+
+ value_type
+ moved_or_copied() const {
+ if (value_ref == nullptr) {
+ return std::move(owned_value);
+ }
+ return *value_ref;
+ }
+
+ value_type const&
+ operator*() const {
+ return value_ref ? *value_ref : owned_value;
+ }
+
+ value_type const*
+ operator->() const {
+ return &**this;
+ }
+
+ private:
+ mutable value_type owned_value = nullptr;
+ value_type const* value_ref = nullptr;
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/string_concat.hpp>
+
+// #include <nlohmann/detail/string_escape.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/output/binary_writer.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <algorithm> // reverse
+#include <array> // array
+#include <map> // map
+#include <cmath> // isnan, isinf
+#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
+#include <cstring> // memcpy
+#include <limits> // numeric_limits
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/input/binary_reader.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/output/output_adapters.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <algorithm> // copy
+#include <cstddef> // size_t
+#include <iterator> // back_inserter
+#include <memory> // shared_ptr, make_shared
+#include <string> // basic_string
+#include <vector> // vector
+
+#ifndef JSON_NO_IO
+#include <ios> // streamsize
+#include <ostream> // basic_ostream
+#endif // JSON_NO_IO
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+/// abstract output adapter interface
+template <typename CharType>
+struct output_adapter_protocol {
+ virtual void
+ write_character(CharType c) = 0;
+ virtual void
+ write_characters(const CharType* s, std::size_t length) = 0;
+ virtual ~output_adapter_protocol() = default;
+
+ output_adapter_protocol() = default;
+ output_adapter_protocol(const output_adapter_protocol&) = default;
+ output_adapter_protocol(output_adapter_protocol&&) noexcept = default;
+ output_adapter_protocol&
+ operator=(const output_adapter_protocol&) = default;
+ output_adapter_protocol&
+ operator=(output_adapter_protocol&&) noexcept = default;
+};
+
+/// a type to simplify interfaces
+template <typename CharType>
+using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
+
+/// output adapter for byte vectors
+template <typename CharType, typename AllocatorType = std::allocator<CharType>>
+class output_vector_adapter : public output_adapter_protocol<CharType> {
+ public:
+ explicit output_vector_adapter(std::vector<CharType, AllocatorType>& vec) noexcept : v(vec) {}
+
+ void
+ write_character(CharType c) override {
+ v.push_back(c);
+ }
+
+ JSON_HEDLEY_NON_NULL(2)
+ void
+ write_characters(const CharType* s, std::size_t length) override {
+ v.insert(v.end(), s, s + length);
+ }
+
+ private:
+ std::vector<CharType, AllocatorType>& v;
+};
+
+#ifndef JSON_NO_IO
+/// output adapter for output streams
+template <typename CharType>
+class output_stream_adapter : public output_adapter_protocol<CharType> {
+ public:
+ explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept : stream(s) {}
+
+ void
+ write_character(CharType c) override {
+ stream.put(c);
+ }
+
+ JSON_HEDLEY_NON_NULL(2)
+ void
+ write_characters(const CharType* s, std::size_t length) override {
+ stream.write(s, static_cast<std::streamsize>(length));
+ }
+
+ private:
+ std::basic_ostream<CharType>& stream;
+};
+#endif // JSON_NO_IO
+
+/// output adapter for basic_string
+template <typename CharType, typename StringType = std::basic_string<CharType>>
+class output_string_adapter : public output_adapter_protocol<CharType> {
+ public:
+ explicit output_string_adapter(StringType& s) noexcept : str(s) {}
+
+ void
+ write_character(CharType c) override {
+ str.push_back(c);
+ }
+
+ JSON_HEDLEY_NON_NULL(2)
+ void
+ write_characters(const CharType* s, std::size_t length) override {
+ str.append(s, length);
+ }
+
+ private:
+ StringType& str;
+};
+
+template <typename CharType, typename StringType = std::basic_string<CharType>>
+class output_adapter {
+ public:
+ template <typename AllocatorType = std::allocator<CharType>>
+ output_adapter(std::vector<CharType, AllocatorType>& vec)
+ : oa(std::make_shared<output_vector_adapter<CharType, AllocatorType>>(vec)) {}
+
+#ifndef JSON_NO_IO
+ output_adapter(std::basic_ostream<CharType>& s) : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
+#endif // JSON_NO_IO
+
+ output_adapter(StringType& s) : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
+
+ operator output_adapter_t<CharType>() { return oa; }
+
+ private:
+ output_adapter_t<CharType> oa = nullptr;
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/string_concat.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+///////////////////
+// binary writer //
+///////////////////
+
+/*!
+@brief serialization to CBOR and MessagePack values
+*/
+template <typename BasicJsonType, typename CharType>
+class binary_writer {
+ using string_t = typename BasicJsonType::string_t;
+ using binary_t = typename BasicJsonType::binary_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+
+ public:
+ /*!
+ @brief create a binary writer
+
+ @param[in] adapter output adapter to write to
+ */
+ explicit binary_writer(output_adapter_t<CharType> adapter) : oa(std::move(adapter)) { JSON_ASSERT(oa); }
+
+ /*!
+ @param[in] j JSON value to serialize
+ @pre j.type() == value_t::object
+ */
+ void
+ write_bson(const BasicJsonType& j) {
+ switch (j.type()) {
+ case value_t::object: {
+ write_bson_object(*j.m_data.m_value.object);
+ break;
+ }
+
+ case value_t::null:
+ case value_t::array:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ JSON_THROW(type_error::create(
+ 317, concat("to serialize to BSON, top-level type must be object, but is ", j.type_name()), &j));
+ }
+ }
+ }
+
+ /*!
+ @param[in] j JSON value to serialize
+ */
+ void
+ write_cbor(const BasicJsonType& j) {
+ switch (j.type()) {
+ case value_t::null: {
+ oa->write_character(to_char_type(0xF6));
+ break;
+ }
+
+ case value_t::boolean: {
+ oa->write_character(j.m_data.m_value.boolean ? to_char_type(0xF5) : to_char_type(0xF4));
+ break;
+ }
+
+ case value_t::number_integer: {
+ if (j.m_data.m_value.number_integer >= 0) {
+ // CBOR does not differentiate between positive signed
+ // integers and unsigned integers. Therefore, we used the
+ // code from the value_t::number_unsigned case here.
+ if (j.m_data.m_value.number_integer <= 0x17) {
+ write_number(static_cast<std::uint8_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)()) {
+ oa->write_character(to_char_type(0x18));
+ write_number(static_cast<std::uint8_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)()) {
+ oa->write_character(to_char_type(0x19));
+ write_number(static_cast<std::uint16_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)()) {
+ oa->write_character(to_char_type(0x1A));
+ write_number(static_cast<std::uint32_t>(j.m_data.m_value.number_integer));
+ } else {
+ oa->write_character(to_char_type(0x1B));
+ write_number(static_cast<std::uint64_t>(j.m_data.m_value.number_integer));
+ }
+ } else {
+ // The conversions below encode the sign in the first
+ // byte, and the value is converted to a positive number.
+ const auto positive_number = -1 - j.m_data.m_value.number_integer;
+ if (j.m_data.m_value.number_integer >= -24) {
+ write_number(static_cast<std::uint8_t>(0x20 + positive_number));
+ } else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)()) {
+ oa->write_character(to_char_type(0x38));
+ write_number(static_cast<std::uint8_t>(positive_number));
+ } else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)()) {
+ oa->write_character(to_char_type(0x39));
+ write_number(static_cast<std::uint16_t>(positive_number));
+ } else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)()) {
+ oa->write_character(to_char_type(0x3A));
+ write_number(static_cast<std::uint32_t>(positive_number));
+ } else {
+ oa->write_character(to_char_type(0x3B));
+ write_number(static_cast<std::uint64_t>(positive_number));
+ }
+ }
+ break;
+ }
+
+ case value_t::number_unsigned: {
+ if (j.m_data.m_value.number_unsigned <= 0x17) {
+ write_number(static_cast<std::uint8_t>(j.m_data.m_value.number_unsigned));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)()) {
+ oa->write_character(to_char_type(0x18));
+ write_number(static_cast<std::uint8_t>(j.m_data.m_value.number_unsigned));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)()) {
+ oa->write_character(to_char_type(0x19));
+ write_number(static_cast<std::uint16_t>(j.m_data.m_value.number_unsigned));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)()) {
+ oa->write_character(to_char_type(0x1A));
+ write_number(static_cast<std::uint32_t>(j.m_data.m_value.number_unsigned));
+ } else {
+ oa->write_character(to_char_type(0x1B));
+ write_number(static_cast<std::uint64_t>(j.m_data.m_value.number_unsigned));
+ }
+ break;
+ }
+
+ case value_t::number_float: {
+ if (std::isnan(j.m_data.m_value.number_float)) {
+ // NaN is 0xf97e00 in CBOR
+ oa->write_character(to_char_type(0xF9));
+ oa->write_character(to_char_type(0x7E));
+ oa->write_character(to_char_type(0x00));
+ } else if (std::isinf(j.m_data.m_value.number_float)) {
+ // Infinity is 0xf97c00, -Infinity is 0xf9fc00
+ oa->write_character(to_char_type(0xf9));
+ oa->write_character(j.m_data.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
+ oa->write_character(to_char_type(0x00));
+ } else {
+ write_compact_float(j.m_data.m_value.number_float, detail::input_format_t::cbor);
+ }
+ break;
+ }
+
+ case value_t::string: {
+ // step 1: write control byte and the string length
+ const auto N = j.m_data.m_value.string->size();
+ if (N <= 0x17) {
+ write_number(static_cast<std::uint8_t>(0x60 + N));
+ } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) {
+ oa->write_character(to_char_type(0x78));
+ write_number(static_cast<std::uint8_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) {
+ oa->write_character(to_char_type(0x79));
+ write_number(static_cast<std::uint16_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) {
+ oa->write_character(to_char_type(0x7A));
+ write_number(static_cast<std::uint32_t>(N));
+ }
+ // LCOV_EXCL_START
+ else if (N <= (std::numeric_limits<std::uint64_t>::max)()) {
+ oa->write_character(to_char_type(0x7B));
+ write_number(static_cast<std::uint64_t>(N));
+ }
+ // LCOV_EXCL_STOP
+
+ // step 2: write the string
+ oa->write_characters(reinterpret_cast<const CharType*>(j.m_data.m_value.string->c_str()),
+ j.m_data.m_value.string->size());
+ break;
+ }
+
+ case value_t::array: {
+ // step 1: write control byte and the array size
+ const auto N = j.m_data.m_value.array->size();
+ if (N <= 0x17) {
+ write_number(static_cast<std::uint8_t>(0x80 + N));
+ } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) {
+ oa->write_character(to_char_type(0x98));
+ write_number(static_cast<std::uint8_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) {
+ oa->write_character(to_char_type(0x99));
+ write_number(static_cast<std::uint16_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) {
+ oa->write_character(to_char_type(0x9A));
+ write_number(static_cast<std::uint32_t>(N));
+ }
+ // LCOV_EXCL_START
+ else if (N <= (std::numeric_limits<std::uint64_t>::max)()) {
+ oa->write_character(to_char_type(0x9B));
+ write_number(static_cast<std::uint64_t>(N));
+ }
+ // LCOV_EXCL_STOP
+
+ // step 2: write each element
+ for (const auto& el : *j.m_data.m_value.array) {
+ write_cbor(el);
+ }
+ break;
+ }
+
+ case value_t::binary: {
+ if (j.m_data.m_value.binary->has_subtype()) {
+ if (j.m_data.m_value.binary->subtype() <= (std::numeric_limits<std::uint8_t>::max)()) {
+ write_number(static_cast<std::uint8_t>(0xd8));
+ write_number(static_cast<std::uint8_t>(j.m_data.m_value.binary->subtype()));
+ } else if (j.m_data.m_value.binary->subtype() <= (std::numeric_limits<std::uint16_t>::max)()) {
+ write_number(static_cast<std::uint8_t>(0xd9));
+ write_number(static_cast<std::uint16_t>(j.m_data.m_value.binary->subtype()));
+ } else if (j.m_data.m_value.binary->subtype() <= (std::numeric_limits<std::uint32_t>::max)()) {
+ write_number(static_cast<std::uint8_t>(0xda));
+ write_number(static_cast<std::uint32_t>(j.m_data.m_value.binary->subtype()));
+ } else if (j.m_data.m_value.binary->subtype() <= (std::numeric_limits<std::uint64_t>::max)()) {
+ write_number(static_cast<std::uint8_t>(0xdb));
+ write_number(static_cast<std::uint64_t>(j.m_data.m_value.binary->subtype()));
+ }
+ }
+
+ // step 1: write control byte and the binary array size
+ const auto N = j.m_data.m_value.binary->size();
+ if (N <= 0x17) {
+ write_number(static_cast<std::uint8_t>(0x40 + N));
+ } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) {
+ oa->write_character(to_char_type(0x58));
+ write_number(static_cast<std::uint8_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) {
+ oa->write_character(to_char_type(0x59));
+ write_number(static_cast<std::uint16_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) {
+ oa->write_character(to_char_type(0x5A));
+ write_number(static_cast<std::uint32_t>(N));
+ }
+ // LCOV_EXCL_START
+ else if (N <= (std::numeric_limits<std::uint64_t>::max)()) {
+ oa->write_character(to_char_type(0x5B));
+ write_number(static_cast<std::uint64_t>(N));
+ }
+ // LCOV_EXCL_STOP
+
+ // step 2: write each element
+ oa->write_characters(reinterpret_cast<const CharType*>(j.m_data.m_value.binary->data()), N);
+
+ break;
+ }
+
+ case value_t::object: {
+ // step 1: write control byte and the object size
+ const auto N = j.m_data.m_value.object->size();
+ if (N <= 0x17) {
+ write_number(static_cast<std::uint8_t>(0xA0 + N));
+ } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) {
+ oa->write_character(to_char_type(0xB8));
+ write_number(static_cast<std::uint8_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) {
+ oa->write_character(to_char_type(0xB9));
+ write_number(static_cast<std::uint16_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) {
+ oa->write_character(to_char_type(0xBA));
+ write_number(static_cast<std::uint32_t>(N));
+ }
+ // LCOV_EXCL_START
+ else if (N <= (std::numeric_limits<std::uint64_t>::max)()) {
+ oa->write_character(to_char_type(0xBB));
+ write_number(static_cast<std::uint64_t>(N));
+ }
+ // LCOV_EXCL_STOP
+
+ // step 2: write each element
+ for (const auto& el : *j.m_data.m_value.object) {
+ write_cbor(el.first);
+ write_cbor(el.second);
+ }
+ break;
+ }
+
+ case value_t::discarded:
+ default:
+ break;
+ }
+ }
+
+ /*!
+ @param[in] j JSON value to serialize
+ */
+ void
+ write_msgpack(const BasicJsonType& j) {
+ switch (j.type()) {
+ case value_t::null: // nil
+ {
+ oa->write_character(to_char_type(0xC0));
+ break;
+ }
+
+ case value_t::boolean: // true and false
+ {
+ oa->write_character(j.m_data.m_value.boolean ? to_char_type(0xC3) : to_char_type(0xC2));
+ break;
+ }
+
+ case value_t::number_integer: {
+ if (j.m_data.m_value.number_integer >= 0) {
+ // MessagePack does not differentiate between positive
+ // signed integers and unsigned integers. Therefore, we used
+ // the code from the value_t::number_unsigned case here.
+ if (j.m_data.m_value.number_unsigned < 128) {
+ // positive fixnum
+ write_number(static_cast<std::uint8_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)()) {
+ // uint 8
+ oa->write_character(to_char_type(0xCC));
+ write_number(static_cast<std::uint8_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)()) {
+ // uint 16
+ oa->write_character(to_char_type(0xCD));
+ write_number(static_cast<std::uint16_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)()) {
+ // uint 32
+ oa->write_character(to_char_type(0xCE));
+ write_number(static_cast<std::uint32_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)()) {
+ // uint 64
+ oa->write_character(to_char_type(0xCF));
+ write_number(static_cast<std::uint64_t>(j.m_data.m_value.number_integer));
+ }
+ } else {
+ if (j.m_data.m_value.number_integer >= -32) {
+ // negative fixnum
+ write_number(static_cast<std::int8_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)()) {
+ // int 8
+ oa->write_character(to_char_type(0xD0));
+ write_number(static_cast<std::int8_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)()) {
+ // int 16
+ oa->write_character(to_char_type(0xD1));
+ write_number(static_cast<std::int16_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)()) {
+ // int 32
+ oa->write_character(to_char_type(0xD2));
+ write_number(static_cast<std::int32_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)()) {
+ // int 64
+ oa->write_character(to_char_type(0xD3));
+ write_number(static_cast<std::int64_t>(j.m_data.m_value.number_integer));
+ }
+ }
+ break;
+ }
+
+ case value_t::number_unsigned: {
+ if (j.m_data.m_value.number_unsigned < 128) {
+ // positive fixnum
+ write_number(static_cast<std::uint8_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)()) {
+ // uint 8
+ oa->write_character(to_char_type(0xCC));
+ write_number(static_cast<std::uint8_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)()) {
+ // uint 16
+ oa->write_character(to_char_type(0xCD));
+ write_number(static_cast<std::uint16_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)()) {
+ // uint 32
+ oa->write_character(to_char_type(0xCE));
+ write_number(static_cast<std::uint32_t>(j.m_data.m_value.number_integer));
+ } else if (j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)()) {
+ // uint 64
+ oa->write_character(to_char_type(0xCF));
+ write_number(static_cast<std::uint64_t>(j.m_data.m_value.number_integer));
+ }
+ break;
+ }
+
+ case value_t::number_float: {
+ write_compact_float(j.m_data.m_value.number_float, detail::input_format_t::msgpack);
+ break;
+ }
+
+ case value_t::string: {
+ // step 1: write control byte and the string length
+ const auto N = j.m_data.m_value.string->size();
+ if (N <= 31) {
+ // fixstr
+ write_number(static_cast<std::uint8_t>(0xA0 | N));
+ } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) {
+ // str 8
+ oa->write_character(to_char_type(0xD9));
+ write_number(static_cast<std::uint8_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) {
+ // str 16
+ oa->write_character(to_char_type(0xDA));
+ write_number(static_cast<std::uint16_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) {
+ // str 32
+ oa->write_character(to_char_type(0xDB));
+ write_number(static_cast<std::uint32_t>(N));
+ }
+
+ // step 2: write the string
+ oa->write_characters(reinterpret_cast<const CharType*>(j.m_data.m_value.string->c_str()),
+ j.m_data.m_value.string->size());
+ break;
+ }
+
+ case value_t::array: {
+ // step 1: write control byte and the array size
+ const auto N = j.m_data.m_value.array->size();
+ if (N <= 15) {
+ // fixarray
+ write_number(static_cast<std::uint8_t>(0x90 | N));
+ } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) {
+ // array 16
+ oa->write_character(to_char_type(0xDC));
+ write_number(static_cast<std::uint16_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) {
+ // array 32
+ oa->write_character(to_char_type(0xDD));
+ write_number(static_cast<std::uint32_t>(N));
+ }
+
+ // step 2: write each element
+ for (const auto& el : *j.m_data.m_value.array) {
+ write_msgpack(el);
+ }
+ break;
+ }
+
+ case value_t::binary: {
+ // step 0: determine if the binary type has a set subtype to
+ // determine whether or not to use the ext or fixext types
+ const bool use_ext = j.m_data.m_value.binary->has_subtype();
+
+ // step 1: write control byte and the byte string length
+ const auto N = j.m_data.m_value.binary->size();
+ if (N <= (std::numeric_limits<std::uint8_t>::max)()) {
+ std::uint8_t output_type{};
+ bool fixed = true;
+ if (use_ext) {
+ switch (N) {
+ case 1:
+ output_type = 0xD4; // fixext 1
+ break;
+ case 2:
+ output_type = 0xD5; // fixext 2
+ break;
+ case 4:
+ output_type = 0xD6; // fixext 4
+ break;
+ case 8:
+ output_type = 0xD7; // fixext 8
+ break;
+ case 16:
+ output_type = 0xD8; // fixext 16
+ break;
+ default:
+ output_type = 0xC7; // ext 8
+ fixed = false;
+ break;
+ }
+
+ } else {
+ output_type = 0xC4; // bin 8
+ fixed = false;
+ }
+
+ oa->write_character(to_char_type(output_type));
+ if (!fixed) {
+ write_number(static_cast<std::uint8_t>(N));
+ }
+ } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) {
+ const std::uint8_t output_type = use_ext ? 0xC8 // ext 16
+ : 0xC5; // bin 16
+
+ oa->write_character(to_char_type(output_type));
+ write_number(static_cast<std::uint16_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) {
+ const std::uint8_t output_type = use_ext ? 0xC9 // ext 32
+ : 0xC6; // bin 32
+
+ oa->write_character(to_char_type(output_type));
+ write_number(static_cast<std::uint32_t>(N));
+ }
+
+ // step 1.5: if this is an ext type, write the subtype
+ if (use_ext) {
+ write_number(static_cast<std::int8_t>(j.m_data.m_value.binary->subtype()));
+ }
+
+ // step 2: write the byte string
+ oa->write_characters(reinterpret_cast<const CharType*>(j.m_data.m_value.binary->data()), N);
+
+ break;
+ }
+
+ case value_t::object: {
+ // step 1: write control byte and the object size
+ const auto N = j.m_data.m_value.object->size();
+ if (N <= 15) {
+ // fixmap
+ write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
+ } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) {
+ // map 16
+ oa->write_character(to_char_type(0xDE));
+ write_number(static_cast<std::uint16_t>(N));
+ } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) {
+ // map 32
+ oa->write_character(to_char_type(0xDF));
+ write_number(static_cast<std::uint32_t>(N));
+ }
+
+ // step 2: write each element
+ for (const auto& el : *j.m_data.m_value.object) {
+ write_msgpack(el.first);
+ write_msgpack(el.second);
+ }
+ break;
+ }
+
+ case value_t::discarded:
+ default:
+ break;
+ }
+ }
+
+ /*!
+ @param[in] j JSON value to serialize
+ @param[in] use_count whether to use '#' prefixes (optimized format)
+ @param[in] use_type whether to use '$' prefixes (optimized format)
+ @param[in] add_prefix whether prefixes need to be used for this value
+ @param[in] use_bjdata whether write in BJData format, default is false
+ */
+ void
+ write_ubjson(const BasicJsonType& j,
+ const bool use_count,
+ const bool use_type,
+ const bool add_prefix = true,
+ const bool use_bjdata = false) {
+ switch (j.type()) {
+ case value_t::null: {
+ if (add_prefix) {
+ oa->write_character(to_char_type('Z'));
+ }
+ break;
+ }
+
+ case value_t::boolean: {
+ if (add_prefix) {
+ oa->write_character(j.m_data.m_value.boolean ? to_char_type('T') : to_char_type('F'));
+ }
+ break;
+ }
+
+ case value_t::number_integer: {
+ write_number_with_ubjson_prefix(j.m_data.m_value.number_integer, add_prefix, use_bjdata);
+ break;
+ }
+
+ case value_t::number_unsigned: {
+ write_number_with_ubjson_prefix(j.m_data.m_value.number_unsigned, add_prefix, use_bjdata);
+ break;
+ }
+
+ case value_t::number_float: {
+ write_number_with_ubjson_prefix(j.m_data.m_value.number_float, add_prefix, use_bjdata);
+ break;
+ }
+
+ case value_t::string: {
+ if (add_prefix) {
+ oa->write_character(to_char_type('S'));
+ }
+ write_number_with_ubjson_prefix(j.m_data.m_value.string->size(), true, use_bjdata);
+ oa->write_characters(reinterpret_cast<const CharType*>(j.m_data.m_value.string->c_str()),
+ j.m_data.m_value.string->size());
+ break;
+ }
+
+ case value_t::array: {
+ if (add_prefix) {
+ oa->write_character(to_char_type('['));
+ }
+
+ bool prefix_required = true;
+ if (use_type && !j.m_data.m_value.array->empty()) {
+ JSON_ASSERT(use_count);
+ const CharType first_prefix = ubjson_prefix(j.front(), use_bjdata);
+ const bool same_prefix =
+ std::all_of(j.begin() + 1, j.end(), [this, first_prefix, use_bjdata](const BasicJsonType& v) {
+ return ubjson_prefix(v, use_bjdata) == first_prefix;
+ });
+
+ std::vector<CharType> bjdx = {
+ '[', '{', 'S', 'H', 'T', 'F', 'N', 'Z'}; // excluded markers in bjdata optimized type
+
+ if (same_prefix &&
+ !(use_bjdata && std::find(bjdx.begin(), bjdx.end(), first_prefix) != bjdx.end())) {
+ prefix_required = false;
+ oa->write_character(to_char_type('$'));
+ oa->write_character(first_prefix);
+ }
+ }
+
+ if (use_count) {
+ oa->write_character(to_char_type('#'));
+ write_number_with_ubjson_prefix(j.m_data.m_value.array->size(), true, use_bjdata);
+ }
+
+ for (const auto& el : *j.m_data.m_value.array) {
+ write_ubjson(el, use_count, use_type, prefix_required, use_bjdata);
+ }
+
+ if (!use_count) {
+ oa->write_character(to_char_type(']'));
+ }
+
+ break;
+ }
+
+ case value_t::binary: {
+ if (add_prefix) {
+ oa->write_character(to_char_type('['));
+ }
+
+ if (use_type && !j.m_data.m_value.binary->empty()) {
+ JSON_ASSERT(use_count);
+ oa->write_character(to_char_type('$'));
+ oa->write_character('U');
+ }
+
+ if (use_count) {
+ oa->write_character(to_char_type('#'));
+ write_number_with_ubjson_prefix(j.m_data.m_value.binary->size(), true, use_bjdata);
+ }
+
+ if (use_type) {
+ oa->write_characters(reinterpret_cast<const CharType*>(j.m_data.m_value.binary->data()),
+ j.m_data.m_value.binary->size());
+ } else {
+ for (size_t i = 0; i < j.m_data.m_value.binary->size(); ++i) {
+ oa->write_character(to_char_type('U'));
+ oa->write_character(j.m_data.m_value.binary->data()[i]);
+ }
+ }
+
+ if (!use_count) {
+ oa->write_character(to_char_type(']'));
+ }
+
+ break;
+ }
+
+ case value_t::object: {
+ if (use_bjdata && j.m_data.m_value.object->size() == 3 &&
+ j.m_data.m_value.object->find("_ArrayType_") != j.m_data.m_value.object->end() &&
+ j.m_data.m_value.object->find("_ArraySize_") != j.m_data.m_value.object->end() &&
+ j.m_data.m_value.object->find("_ArrayData_") != j.m_data.m_value.object->end()) {
+ if (!write_bjdata_ndarray(*j.m_data.m_value.object,
+ use_count,
+ use_type)) // decode bjdata ndarray in the JData format
+ // (https://github.com/NeuroJSON/jdata)
+ {
+ break;
+ }
+ }
+
+ if (add_prefix) {
+ oa->write_character(to_char_type('{'));
+ }
+
+ bool prefix_required = true;
+ if (use_type && !j.m_data.m_value.object->empty()) {
+ JSON_ASSERT(use_count);
+ const CharType first_prefix = ubjson_prefix(j.front(), use_bjdata);
+ const bool same_prefix =
+ std::all_of(j.begin(), j.end(), [this, first_prefix, use_bjdata](const BasicJsonType& v) {
+ return ubjson_prefix(v, use_bjdata) == first_prefix;
+ });
+
+ std::vector<CharType> bjdx = {
+ '[', '{', 'S', 'H', 'T', 'F', 'N', 'Z'}; // excluded markers in bjdata optimized type
+
+ if (same_prefix &&
+ !(use_bjdata && std::find(bjdx.begin(), bjdx.end(), first_prefix) != bjdx.end())) {
+ prefix_required = false;
+ oa->write_character(to_char_type('$'));
+ oa->write_character(first_prefix);
+ }
+ }
+
+ if (use_count) {
+ oa->write_character(to_char_type('#'));
+ write_number_with_ubjson_prefix(j.m_data.m_value.object->size(), true, use_bjdata);
+ }
+
+ for (const auto& el : *j.m_data.m_value.object) {
+ write_number_with_ubjson_prefix(el.first.size(), true, use_bjdata);
+ oa->write_characters(reinterpret_cast<const CharType*>(el.first.c_str()), el.first.size());
+ write_ubjson(el.second, use_count, use_type, prefix_required, use_bjdata);
+ }
+
+ if (!use_count) {
+ oa->write_character(to_char_type('}'));
+ }
+
+ break;
+ }
+
+ case value_t::discarded:
+ default:
+ break;
+ }
+ }
+
+ private:
+ //////////
+ // BSON //
+ //////////
+
+ /*!
+ @return The size of a BSON document entry header, including the id marker
+ and the entry name size (and its null-terminator).
+ */
+ static std::size_t
+ calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j) {
+ const auto it = name.find(static_cast<typename string_t::value_type>(0));
+ if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) {
+ JSON_THROW(out_of_range::create(
+ 409, concat("BSON key cannot contain code point U+0000 (at byte ", std::to_string(it), ")"), &j));
+ static_cast<void>(j);
+ }
+
+ return /*id*/ 1ul + name.size() + /*zero-terminator*/ 1u;
+ }
+
+ /*!
+ @brief Writes the given @a element_type and @a name to the output adapter
+ */
+ void
+ write_bson_entry_header(const string_t& name, const std::uint8_t element_type) {
+ oa->write_character(to_char_type(element_type)); // boolean
+ oa->write_characters(reinterpret_cast<const CharType*>(name.c_str()), name.size() + 1u);
+ }
+
+ /*!
+ @brief Writes a BSON element with key @a name and boolean value @a value
+ */
+ void
+ write_bson_boolean(const string_t& name, const bool value) {
+ write_bson_entry_header(name, 0x08);
+ oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
+ }
+
+ /*!
+ @brief Writes a BSON element with key @a name and double value @a value
+ */
+ void
+ write_bson_double(const string_t& name, const double value) {
+ write_bson_entry_header(name, 0x01);
+ write_number<double>(value, true);
+ }
+
+ /*!
+ @return The size of the BSON-encoded string in @a value
+ */
+ static std::size_t
+ calc_bson_string_size(const string_t& value) {
+ return sizeof(std::int32_t) + value.size() + 1ul;
+ }
+
+ /*!
+ @brief Writes a BSON element with key @a name and string value @a value
+ */
+ void
+ write_bson_string(const string_t& name, const string_t& value) {
+ write_bson_entry_header(name, 0x02);
+
+ write_number<std::int32_t>(static_cast<std::int32_t>(value.size() + 1ul), true);
+ oa->write_characters(reinterpret_cast<const CharType*>(value.c_str()), value.size() + 1);
+ }
+
+ /*!
+ @brief Writes a BSON element with key @a name and null value
+ */
+ void
+ write_bson_null(const string_t& name) {
+ write_bson_entry_header(name, 0x0A);
+ }
+
+ /*!
+ @return The size of the BSON-encoded integer @a value
+ */
+ static std::size_t
+ calc_bson_integer_size(const std::int64_t value) {
+ return (std::numeric_limits<std::int32_t>::min)() <= value &&
+ value <= (std::numeric_limits<std::int32_t>::max)()
+ ? sizeof(std::int32_t)
+ : sizeof(std::int64_t);
+ }
+
+ /*!
+ @brief Writes a BSON element with key @a name and integer @a value
+ */
+ void
+ write_bson_integer(const string_t& name, const std::int64_t value) {
+ if ((std::numeric_limits<std::int32_t>::min)() <= value &&
+ value <= (std::numeric_limits<std::int32_t>::max)()) {
+ write_bson_entry_header(name, 0x10); // int32
+ write_number<std::int32_t>(static_cast<std::int32_t>(value), true);
+ } else {
+ write_bson_entry_header(name, 0x12); // int64
+ write_number<std::int64_t>(static_cast<std::int64_t>(value), true);
+ }
+ }
+
+ /*!
+ @return The size of the BSON-encoded unsigned integer in @a j
+ */
+ static constexpr std::size_t
+ calc_bson_unsigned_size(const std::uint64_t value) noexcept {
+ return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) ? sizeof(std::int32_t)
+ : sizeof(std::int64_t);
+ }
+
+ /*!
+ @brief Writes a BSON element with key @a name and unsigned @a value
+ */
+ void
+ write_bson_unsigned(const string_t& name, const BasicJsonType& j) {
+ if (j.m_data.m_value.number_unsigned <=
+ static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) {
+ write_bson_entry_header(name, 0x10 /* int32 */);
+ write_number<std::int32_t>(static_cast<std::int32_t>(j.m_data.m_value.number_unsigned), true);
+ } else if (j.m_data.m_value.number_unsigned <=
+ static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)())) {
+ write_bson_entry_header(name, 0x12 /* int64 */);
+ write_number<std::int64_t>(static_cast<std::int64_t>(j.m_data.m_value.number_unsigned), true);
+ } else {
+ JSON_THROW(out_of_range::create(407,
+ concat("integer number ",
+ std::to_string(j.m_data.m_value.number_unsigned),
+ " cannot be represented by BSON as it does not fit int64"),
+ &j));
+ }
+ }
+
+ /*!
+ @brief Writes a BSON element with key @a name and object @a value
+ */
+ void
+ write_bson_object_entry(const string_t& name, const typename BasicJsonType::object_t& value) {
+ write_bson_entry_header(name, 0x03); // object
+ write_bson_object(value);
+ }
+
+ /*!
+ @return The size of the BSON-encoded array @a value
+ */
+ static std::size_t
+ calc_bson_array_size(const typename BasicJsonType::array_t& value) {
+ std::size_t array_index = 0ul;
+
+ const std::size_t embedded_document_size =
+ std::accumulate(std::begin(value),
+ std::end(value),
+ static_cast<std::size_t>(0),
+ [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type& el) {
+ return result + calc_bson_element_size(std::to_string(array_index++), el);
+ });
+
+ return sizeof(std::int32_t) + embedded_document_size + 1ul;
+ }
+
+ /*!
+ @return The size of the BSON-encoded binary array @a value
+ */
+ static std::size_t
+ calc_bson_binary_size(const typename BasicJsonType::binary_t& value) {
+ return sizeof(std::int32_t) + value.size() + 1ul;
+ }
+
+ /*!
+ @brief Writes a BSON element with key @a name and array @a value
+ */
+ void
+ write_bson_array(const string_t& name, const typename BasicJsonType::array_t& value) {
+ write_bson_entry_header(name, 0x04); // array
+ write_number<std::int32_t>(static_cast<std::int32_t>(calc_bson_array_size(value)), true);
+
+ std::size_t array_index = 0ul;
+
+ for (const auto& el : value) {
+ write_bson_element(std::to_string(array_index++), el);
+ }
+
+ oa->write_character(to_char_type(0x00));
+ }
+
+ /*!
+ @brief Writes a BSON element with key @a name and binary value @a value
+ */
+ void
+ write_bson_binary(const string_t& name, const binary_t& value) {
+ write_bson_entry_header(name, 0x05);
+
+ write_number<std::int32_t>(static_cast<std::int32_t>(value.size()), true);
+ write_number(value.has_subtype() ? static_cast<std::uint8_t>(value.subtype())
+ : static_cast<std::uint8_t>(0x00));
+
+ oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
+ }
+
+ /*!
+ @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
+ @return The calculated size for the BSON document entry for @a j with the given @a name.
+ */
+ static std::size_t
+ calc_bson_element_size(const string_t& name, const BasicJsonType& j) {
+ const auto header_size = calc_bson_entry_header_size(name, j);
+ switch (j.type()) {
+ case value_t::object:
+ return header_size + calc_bson_object_size(*j.m_data.m_value.object);
+
+ case value_t::array:
+ return header_size + calc_bson_array_size(*j.m_data.m_value.array);
+
+ case value_t::binary:
+ return header_size + calc_bson_binary_size(*j.m_data.m_value.binary);
+
+ case value_t::boolean:
+ return header_size + 1ul;
+
+ case value_t::number_float:
+ return header_size + 8ul;
+
+ case value_t::number_integer:
+ return header_size + calc_bson_integer_size(j.m_data.m_value.number_integer);
+
+ case value_t::number_unsigned:
+ return header_size + calc_bson_unsigned_size(j.m_data.m_value.number_unsigned);
+
+ case value_t::string:
+ return header_size + calc_bson_string_size(*j.m_data.m_value.string);
+
+ case value_t::null:
+ return header_size + 0ul;
+
+ // LCOV_EXCL_START
+ case value_t::discarded:
+ default:
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
+ return 0ul;
+ // LCOV_EXCL_STOP
+ }
+ }
+
+ /*!
+ @brief Serializes the JSON value @a j to BSON and associates it with the
+ key @a name.
+ @param name The name to associate with the JSON entity @a j within the
+ current BSON document
+ */
+ void
+ write_bson_element(const string_t& name, const BasicJsonType& j) {
+ switch (j.type()) {
+ case value_t::object:
+ return write_bson_object_entry(name, *j.m_data.m_value.object);
+
+ case value_t::array:
+ return write_bson_array(name, *j.m_data.m_value.array);
+
+ case value_t::binary:
+ return write_bson_binary(name, *j.m_data.m_value.binary);
+
+ case value_t::boolean:
+ return write_bson_boolean(name, j.m_data.m_value.boolean);
+
+ case value_t::number_float:
+ return write_bson_double(name, j.m_data.m_value.number_float);
+
+ case value_t::number_integer:
+ return write_bson_integer(name, j.m_data.m_value.number_integer);
+
+ case value_t::number_unsigned:
+ return write_bson_unsigned(name, j);
+
+ case value_t::string:
+ return write_bson_string(name, *j.m_data.m_value.string);
+
+ case value_t::null:
+ return write_bson_null(name);
+
+ // LCOV_EXCL_START
+ case value_t::discarded:
+ default:
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
+ return;
+ // LCOV_EXCL_STOP
+ }
+ }
+
+ /*!
+ @brief Calculates the size of the BSON serialization of the given
+ JSON-object @a j.
+ @param[in] value JSON value to serialize
+ @pre value.type() == value_t::object
+ */
+ static std::size_t
+ calc_bson_object_size(const typename BasicJsonType::object_t& value) {
+ const std::size_t document_size =
+ std::accumulate(value.begin(),
+ value.end(),
+ static_cast<std::size_t>(0),
+ [](size_t result, const typename BasicJsonType::object_t::value_type& el) {
+ return result += calc_bson_element_size(el.first, el.second);
+ });
+
+ return sizeof(std::int32_t) + document_size + 1ul;
+ }
+
+ /*!
+ @param[in] value JSON value to serialize
+ @pre value.type() == value_t::object
+ */
+ void
+ write_bson_object(const typename BasicJsonType::object_t& value) {
+ write_number<std::int32_t>(static_cast<std::int32_t>(calc_bson_object_size(value)), true);
+
+ for (const auto& el : value) {
+ write_bson_element(el.first, el.second);
+ }
+
+ oa->write_character(to_char_type(0x00));
+ }
+
+ //////////
+ // CBOR //
+ //////////
+
+ static constexpr CharType
+ get_cbor_float_prefix(float /*unused*/) {
+ return to_char_type(0xFA); // Single-Precision Float
+ }
+
+ static constexpr CharType
+ get_cbor_float_prefix(double /*unused*/) {
+ return to_char_type(0xFB); // Double-Precision Float
+ }
+
+ /////////////
+ // MsgPack //
+ /////////////
+
+ static constexpr CharType
+ get_msgpack_float_prefix(float /*unused*/) {
+ return to_char_type(0xCA); // float 32
+ }
+
+ static constexpr CharType
+ get_msgpack_float_prefix(double /*unused*/) {
+ return to_char_type(0xCB); // float 64
+ }
+
+ ////////////
+ // UBJSON //
+ ////////////
+
+ // UBJSON: write number (floating point)
+ template <typename NumberType, typename std::enable_if<std::is_floating_point<NumberType>::value, int>::type = 0>
+ void
+ write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix, const bool use_bjdata) {
+ if (add_prefix) {
+ oa->write_character(get_ubjson_float_prefix(n));
+ }
+ write_number(n, use_bjdata);
+ }
+
+ // UBJSON: write number (unsigned integer)
+ template <typename NumberType, typename std::enable_if<std::is_unsigned<NumberType>::value, int>::type = 0>
+ void
+ write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix, const bool use_bjdata) {
+ if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)())) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('i')); // int8
+ }
+ write_number(static_cast<std::uint8_t>(n), use_bjdata);
+ } else if (n <= (std::numeric_limits<std::uint8_t>::max)()) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('U')); // uint8
+ }
+ write_number(static_cast<std::uint8_t>(n), use_bjdata);
+ } else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)())) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('I')); // int16
+ }
+ write_number(static_cast<std::int16_t>(n), use_bjdata);
+ } else if (use_bjdata && n <= static_cast<uint64_t>((std::numeric_limits<uint16_t>::max)())) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('u')); // uint16 - bjdata only
+ }
+ write_number(static_cast<std::uint16_t>(n), use_bjdata);
+ } else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('l')); // int32
+ }
+ write_number(static_cast<std::int32_t>(n), use_bjdata);
+ } else if (use_bjdata && n <= static_cast<uint64_t>((std::numeric_limits<uint32_t>::max)())) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('m')); // uint32 - bjdata only
+ }
+ write_number(static_cast<std::uint32_t>(n), use_bjdata);
+ } else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)())) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('L')); // int64
+ }
+ write_number(static_cast<std::int64_t>(n), use_bjdata);
+ } else if (use_bjdata && n <= (std::numeric_limits<uint64_t>::max)()) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('M')); // uint64 - bjdata only
+ }
+ write_number(static_cast<std::uint64_t>(n), use_bjdata);
+ } else {
+ if (add_prefix) {
+ oa->write_character(to_char_type('H')); // high-precision number
+ }
+
+ const auto number = BasicJsonType(n).dump();
+ write_number_with_ubjson_prefix(number.size(), true, use_bjdata);
+ for (std::size_t i = 0; i < number.size(); ++i) {
+ oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
+ }
+ }
+ }
+
+ // UBJSON: write number (signed integer)
+ template <typename NumberType,
+ typename std::enable_if<std::is_signed<NumberType>::value && !std::is_floating_point<NumberType>::value,
+ int>::type = 0>
+ void
+ write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix, const bool use_bjdata) {
+ if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)()) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('i')); // int8
+ }
+ write_number(static_cast<std::int8_t>(n), use_bjdata);
+ } else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n &&
+ n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)())) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('U')); // uint8
+ }
+ write_number(static_cast<std::uint8_t>(n), use_bjdata);
+ } else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)()) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('I')); // int16
+ }
+ write_number(static_cast<std::int16_t>(n), use_bjdata);
+ } else if (use_bjdata && (static_cast<std::int64_t>((std::numeric_limits<std::uint16_t>::min)()) <= n &&
+ n <= static_cast<std::int64_t>((std::numeric_limits<std::uint16_t>::max)()))) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('u')); // uint16 - bjdata only
+ }
+ write_number(static_cast<uint16_t>(n), use_bjdata);
+ } else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)()) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('l')); // int32
+ }
+ write_number(static_cast<std::int32_t>(n), use_bjdata);
+ } else if (use_bjdata && (static_cast<std::int64_t>((std::numeric_limits<std::uint32_t>::min)()) <= n &&
+ n <= static_cast<std::int64_t>((std::numeric_limits<std::uint32_t>::max)()))) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('m')); // uint32 - bjdata only
+ }
+ write_number(static_cast<uint32_t>(n), use_bjdata);
+ } else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)()) {
+ if (add_prefix) {
+ oa->write_character(to_char_type('L')); // int64
+ }
+ write_number(static_cast<std::int64_t>(n), use_bjdata);
+ }
+ // LCOV_EXCL_START
+ else {
+ if (add_prefix) {
+ oa->write_character(to_char_type('H')); // high-precision number
+ }
+
+ const auto number = BasicJsonType(n).dump();
+ write_number_with_ubjson_prefix(number.size(), true, use_bjdata);
+ for (std::size_t i = 0; i < number.size(); ++i) {
+ oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
+ }
+ }
+ // LCOV_EXCL_STOP
+ }
+
+ /*!
+ @brief determine the type prefix of container values
+ */
+ CharType
+ ubjson_prefix(const BasicJsonType& j, const bool use_bjdata) const noexcept {
+ switch (j.type()) {
+ case value_t::null:
+ return 'Z';
+
+ case value_t::boolean:
+ return j.m_data.m_value.boolean ? 'T' : 'F';
+
+ case value_t::number_integer: {
+ if ((std::numeric_limits<std::int8_t>::min)() <= j.m_data.m_value.number_integer &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)()) {
+ return 'i';
+ }
+ if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_data.m_value.number_integer &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)()) {
+ return 'U';
+ }
+ if ((std::numeric_limits<std::int16_t>::min)() <= j.m_data.m_value.number_integer &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)()) {
+ return 'I';
+ }
+ if (use_bjdata && ((std::numeric_limits<std::uint16_t>::min)() <= j.m_data.m_value.number_integer &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())) {
+ return 'u';
+ }
+ if ((std::numeric_limits<std::int32_t>::min)() <= j.m_data.m_value.number_integer &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)()) {
+ return 'l';
+ }
+ if (use_bjdata && ((std::numeric_limits<std::uint32_t>::min)() <= j.m_data.m_value.number_integer &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())) {
+ return 'm';
+ }
+ if ((std::numeric_limits<std::int64_t>::min)() <= j.m_data.m_value.number_integer &&
+ j.m_data.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)()) {
+ return 'L';
+ }
+ // anything else is treated as high-precision number
+ return 'H'; // LCOV_EXCL_LINE
+ }
+
+ case value_t::number_unsigned: {
+ if (j.m_data.m_value.number_unsigned <=
+ static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)())) {
+ return 'i';
+ }
+ if (j.m_data.m_value.number_unsigned <=
+ static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)())) {
+ return 'U';
+ }
+ if (j.m_data.m_value.number_unsigned <=
+ static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)())) {
+ return 'I';
+ }
+ if (use_bjdata && j.m_data.m_value.number_unsigned <=
+ static_cast<std::uint64_t>((std::numeric_limits<std::uint16_t>::max)())) {
+ return 'u';
+ }
+ if (j.m_data.m_value.number_unsigned <=
+ static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) {
+ return 'l';
+ }
+ if (use_bjdata && j.m_data.m_value.number_unsigned <=
+ static_cast<std::uint64_t>((std::numeric_limits<std::uint32_t>::max)())) {
+ return 'm';
+ }
+ if (j.m_data.m_value.number_unsigned <=
+ static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)())) {
+ return 'L';
+ }
+ if (use_bjdata && j.m_data.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)()) {
+ return 'M';
+ }
+ // anything else is treated as high-precision number
+ return 'H'; // LCOV_EXCL_LINE
+ }
+
+ case value_t::number_float:
+ return get_ubjson_float_prefix(j.m_data.m_value.number_float);
+
+ case value_t::string:
+ return 'S';
+
+ case value_t::array: // fallthrough
+ case value_t::binary:
+ return '[';
+
+ case value_t::object:
+ return '{';
+
+ case value_t::discarded:
+ default: // discarded values
+ return 'N';
+ }
+ }
+
+ static constexpr CharType
+ get_ubjson_float_prefix(float /*unused*/) {
+ return 'd'; // float 32
+ }
+
+ static constexpr CharType
+ get_ubjson_float_prefix(double /*unused*/) {
+ return 'D'; // float 64
+ }
+
+ /*!
+ @return false if the object is successfully converted to a bjdata ndarray, true if the type or size is invalid
+ */
+ bool
+ write_bjdata_ndarray(const typename BasicJsonType::object_t& value, const bool use_count, const bool use_type) {
+ std::map<string_t, CharType> bjdtype = {{"uint8", 'U'},
+ {"int8", 'i'},
+ {"uint16", 'u'},
+ {"int16", 'I'},
+ {"uint32", 'm'},
+ {"int32", 'l'},
+ {"uint64", 'M'},
+ {"int64", 'L'},
+ {"single", 'd'},
+ {"double", 'D'},
+ {"char", 'C'}};
+
+ string_t key = "_ArrayType_";
+ auto it = bjdtype.find(static_cast<string_t>(value.at(key)));
+ if (it == bjdtype.end()) {
+ return true;
+ }
+ CharType dtype = it->second;
+
+ key = "_ArraySize_";
+ std::size_t len = (value.at(key).empty() ? 0 : 1);
+ for (const auto& el : value.at(key)) {
+ len *= static_cast<std::size_t>(el.m_data.m_value.number_unsigned);
+ }
+
+ key = "_ArrayData_";
+ if (value.at(key).size() != len) {
+ return true;
+ }
+
+ oa->write_character('[');
+ oa->write_character('$');
+ oa->write_character(dtype);
+ oa->write_character('#');
+
+ key = "_ArraySize_";
+ write_ubjson(value.at(key), use_count, use_type, true, true);
+
+ key = "_ArrayData_";
+ if (dtype == 'U' || dtype == 'C') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<std::uint8_t>(el.m_data.m_value.number_unsigned), true);
+ }
+ } else if (dtype == 'i') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<std::int8_t>(el.m_data.m_value.number_integer), true);
+ }
+ } else if (dtype == 'u') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<std::uint16_t>(el.m_data.m_value.number_unsigned), true);
+ }
+ } else if (dtype == 'I') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<std::int16_t>(el.m_data.m_value.number_integer), true);
+ }
+ } else if (dtype == 'm') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<std::uint32_t>(el.m_data.m_value.number_unsigned), true);
+ }
+ } else if (dtype == 'l') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<std::int32_t>(el.m_data.m_value.number_integer), true);
+ }
+ } else if (dtype == 'M') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<std::uint64_t>(el.m_data.m_value.number_unsigned), true);
+ }
+ } else if (dtype == 'L') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<std::int64_t>(el.m_data.m_value.number_integer), true);
+ }
+ } else if (dtype == 'd') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<float>(el.m_data.m_value.number_float), true);
+ }
+ } else if (dtype == 'D') {
+ for (const auto& el : value.at(key)) {
+ write_number(static_cast<double>(el.m_data.m_value.number_float), true);
+ }
+ }
+ return false;
+ }
+
+ ///////////////////////
+ // Utility functions //
+ ///////////////////////
+
+ /*
+ @brief write a number to output input
+ @param[in] n number of type @a NumberType
+ @param[in] OutputIsLittleEndian Set to true if output data is
+ required to be little endian
+ @tparam NumberType the type of the number
+
+ @note This function needs to respect the system's endianness, because bytes
+ in CBOR, MessagePack, and UBJSON are stored in network order (big
+ endian) and therefore need reordering on little endian systems.
+ On the other hand, BSON and BJData use little endian and should reorder
+ on big endian systems.
+ */
+ template <typename NumberType>
+ void
+ write_number(const NumberType n, const bool OutputIsLittleEndian = false) {
+ // step 1: write number to array of length NumberType
+ std::array<CharType, sizeof(NumberType)> vec{};
+ std::memcpy(vec.data(), &n, sizeof(NumberType));
+
+ // step 2: write array to output (with possible reordering)
+ if (is_little_endian != OutputIsLittleEndian) {
+ // reverse byte order prior to conversion if necessary
+ std::reverse(vec.begin(), vec.end());
+ }
+
+ oa->write_characters(vec.data(), sizeof(NumberType));
+ }
+
+ void
+ write_compact_float(const number_float_t n, detail::input_format_t format) {
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wfloat-equal"
+#endif
+ if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) &&
+ static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) &&
+ static_cast<double>(static_cast<float>(n)) == static_cast<double>(n)) {
+ oa->write_character(format == detail::input_format_t::cbor
+ ? get_cbor_float_prefix(static_cast<float>(n))
+ : get_msgpack_float_prefix(static_cast<float>(n)));
+ write_number(static_cast<float>(n));
+ } else {
+ oa->write_character(format == detail::input_format_t::cbor ? get_cbor_float_prefix(n)
+ : get_msgpack_float_prefix(n));
+ write_number(n);
+ }
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+ }
+
+ public:
+ // The following to_char_type functions are implement the conversion
+ // between uint8_t and CharType. In case CharType is not unsigned,
+ // such a conversion is required to allow values greater than 128.
+ // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
+ template <typename C = CharType, enable_if_t<std::is_signed<C>::value && std::is_signed<char>::value>* = nullptr>
+ static constexpr CharType
+ to_char_type(std::uint8_t x) noexcept {
+ return *reinterpret_cast<char*>(&x);
+ }
+
+ template <typename C = CharType, enable_if_t<std::is_signed<C>::value && std::is_unsigned<char>::value>* = nullptr>
+ static CharType
+ to_char_type(std::uint8_t x) noexcept {
+ static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
+ static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
+ CharType result;
+ std::memcpy(&result, &x, sizeof(x));
+ return result;
+ }
+
+ template <typename C = CharType, enable_if_t<std::is_unsigned<C>::value>* = nullptr>
+ static constexpr CharType
+ to_char_type(std::uint8_t x) noexcept {
+ return x;
+ }
+
+ template <typename InputCharType,
+ typename C = CharType,
+ enable_if_t<std::is_signed<C>::value && std::is_signed<char>::value &&
+ std::is_same<char, typename std::remove_cv<InputCharType>::type>::value>* = nullptr>
+ static constexpr CharType
+ to_char_type(InputCharType x) noexcept {
+ return x;
+ }
+
+ private:
+ /// whether we can assume little endianness
+ const bool is_little_endian = little_endianness();
+
+ /// the output
+ output_adapter_t<CharType> oa = nullptr;
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/output/output_adapters.hpp>
+
+// #include <nlohmann/detail/output/serializer.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2008-2009 Björn Hoehrmann <bjoern@hoehrmann.de>
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <algorithm> // reverse, remove, fill, find, none_of
+#include <array> // array
+#include <clocale> // localeconv, lconv
+#include <cmath> // labs, isfinite, isnan, signbit
+#include <cstddef> // size_t, ptrdiff_t
+#include <cstdint> // uint8_t
+#include <cstdio> // snprintf
+#include <limits> // numeric_limits
+#include <string> // string, char_traits
+#include <iomanip> // setfill, setw
+#include <type_traits> // is_same
+#include <utility> // move
+
+// #include <nlohmann/detail/conversions/to_chars.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2009 Florian Loitsch <https://florian.loitsch.com/>
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <array> // array
+#include <cmath> // signbit, isfinite
+#include <cstdint> // intN_t, uintN_t
+#include <cstring> // memcpy, memmove
+#include <limits> // numeric_limits
+#include <type_traits> // conditional
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+/*!
+@brief implements the Grisu2 algorithm for binary to decimal floating-point
+conversion.
+
+This implementation is a slightly modified version of the reference
+implementation which may be obtained from
+http://florian.loitsch.com/publications (bench.tar.gz).
+
+The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
+
+For a detailed description of the algorithm see:
+
+[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
+ Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
+ Language Design and Implementation, PLDI 2010
+[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
+ Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
+ Design and Implementation, PLDI 1996
+*/
+namespace dtoa_impl {
+
+template <typename Target, typename Source>
+Target
+reinterpret_bits(const Source source) {
+ static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
+
+ Target target;
+ std::memcpy(&target, &source, sizeof(Source));
+ return target;
+}
+
+struct diyfp // f * 2^e
+{
+ static constexpr int kPrecision = 64; // = q
+
+ std::uint64_t f = 0;
+ int e = 0;
+
+ constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
+
+ /*!
+ @brief returns x - y
+ @pre x.e == y.e and x.f >= y.f
+ */
+ static diyfp
+ sub(const diyfp& x, const diyfp& y) noexcept {
+ JSON_ASSERT(x.e == y.e);
+ JSON_ASSERT(x.f >= y.f);
+
+ return {x.f - y.f, x.e};
+ }
+
+ /*!
+ @brief returns x * y
+ @note The result is rounded. (Only the upper q bits are returned.)
+ */
+ static diyfp
+ mul(const diyfp& x, const diyfp& y) noexcept {
+ static_assert(kPrecision == 64, "internal error");
+
+ // Computes:
+ // f = round((x.f * y.f) / 2^q)
+ // e = x.e + y.e + q
+
+ // Emulate the 64-bit * 64-bit multiplication:
+ //
+ // p = u * v
+ // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
+ // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
+ // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
+ // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
+ // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
+ // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
+ // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
+ //
+ // (Since Q might be larger than 2^32 - 1)
+ //
+ // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
+ //
+ // (Q_hi + H does not overflow a 64-bit int)
+ //
+ // = p_lo + 2^64 p_hi
+
+ const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
+ const std::uint64_t u_hi = x.f >> 32u;
+ const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
+ const std::uint64_t v_hi = y.f >> 32u;
+
+ const std::uint64_t p0 = u_lo * v_lo;
+ const std::uint64_t p1 = u_lo * v_hi;
+ const std::uint64_t p2 = u_hi * v_lo;
+ const std::uint64_t p3 = u_hi * v_hi;
+
+ const std::uint64_t p0_hi = p0 >> 32u;
+ const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
+ const std::uint64_t p1_hi = p1 >> 32u;
+ const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
+ const std::uint64_t p2_hi = p2 >> 32u;
+
+ std::uint64_t Q = p0_hi + p1_lo + p2_lo;
+
+ // The full product might now be computed as
+ //
+ // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
+ // p_lo = p0_lo + (Q << 32)
+ //
+ // But in this particular case here, the full p_lo is not required.
+ // Effectively we only need to add the highest bit in p_lo to p_hi (and
+ // Q_hi + 1 does not overflow).
+
+ Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
+
+ const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
+
+ return {h, x.e + y.e + 64};
+ }
+
+ /*!
+ @brief normalize x such that the significand is >= 2^(q-1)
+ @pre x.f != 0
+ */
+ static diyfp
+ normalize(diyfp x) noexcept {
+ JSON_ASSERT(x.f != 0);
+
+ while ((x.f >> 63u) == 0) {
+ x.f <<= 1u;
+ x.e--;
+ }
+
+ return x;
+ }
+
+ /*!
+ @brief normalize x such that the result has the exponent E
+ @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
+ */
+ static diyfp
+ normalize_to(const diyfp& x, const int target_exponent) noexcept {
+ const int delta = x.e - target_exponent;
+
+ JSON_ASSERT(delta >= 0);
+ JSON_ASSERT(((x.f << delta) >> delta) == x.f);
+
+ return {x.f << delta, target_exponent};
+ }
+};
+
+struct boundaries {
+ diyfp w;
+ diyfp minus;
+ diyfp plus;
+};
+
+/*!
+Compute the (normalized) diyfp representing the input number 'value' and its
+boundaries.
+
+@pre value must be finite and positive
+*/
+template <typename FloatType>
+boundaries
+compute_boundaries(FloatType value) {
+ JSON_ASSERT(std::isfinite(value));
+ JSON_ASSERT(value > 0);
+
+ // Convert the IEEE representation into a diyfp.
+ //
+ // If v is denormal:
+ // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
+ // If v is normalized:
+ // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
+
+ static_assert(std::numeric_limits<FloatType>::is_iec559,
+ "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
+
+ constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
+ constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
+ constexpr int kMinExp = 1 - kBias;
+ constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
+
+ using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t>::type;
+
+ const auto bits = static_cast<std::uint64_t>(reinterpret_bits<bits_type>(value));
+ const std::uint64_t E = bits >> (kPrecision - 1);
+ const std::uint64_t F = bits & (kHiddenBit - 1);
+
+ const bool is_denormal = E == 0;
+ const diyfp v = is_denormal ? diyfp(F, kMinExp) : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
+
+ // Compute the boundaries m- and m+ of the floating-point value
+ // v = f * 2^e.
+ //
+ // Determine v- and v+, the floating-point predecessor and successor if v,
+ // respectively.
+ //
+ // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
+ // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
+ //
+ // v+ = v + 2^e
+ //
+ // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
+ // between m- and m+ round to v, regardless of how the input rounding
+ // algorithm breaks ties.
+ //
+ // ---+-------------+-------------+-------------+-------------+--- (A)
+ // v- m- v m+ v+
+ //
+ // -----------------+------+------+-------------+-------------+--- (B)
+ // v- m- v m+ v+
+
+ const bool lower_boundary_is_closer = F == 0 && E > 1;
+ const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
+ const diyfp m_minus = lower_boundary_is_closer ? diyfp(4 * v.f - 1, v.e - 2) // (B)
+ : diyfp(2 * v.f - 1, v.e - 1); // (A)
+
+ // Determine the normalized w+ = m+.
+ const diyfp w_plus = diyfp::normalize(m_plus);
+
+ // Determine w- = m- such that e_(w-) = e_(w+).
+ const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
+
+ return {diyfp::normalize(v), w_minus, w_plus};
+}
+
+// Given normalized diyfp w, Grisu needs to find a (normalized) cached
+// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
+// within a certain range [alpha, gamma] (Definition 3.2 from [1])
+//
+// alpha <= e = e_c + e_w + q <= gamma
+//
+// or
+//
+// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
+// <= f_c * f_w * 2^gamma
+//
+// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
+//
+// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
+//
+// or
+//
+// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
+//
+// The choice of (alpha,gamma) determines the size of the table and the form of
+// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
+// in practice:
+//
+// The idea is to cut the number c * w = f * 2^e into two parts, which can be
+// processed independently: An integral part p1, and a fractional part p2:
+//
+// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
+// = (f div 2^-e) + (f mod 2^-e) * 2^e
+// = p1 + p2 * 2^e
+//
+// The conversion of p1 into decimal form requires a series of divisions and
+// modulos by (a power of) 10. These operations are faster for 32-bit than for
+// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
+// achieved by choosing
+//
+// -e >= 32 or e <= -32 := gamma
+//
+// In order to convert the fractional part
+//
+// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
+//
+// into decimal form, the fraction is repeatedly multiplied by 10 and the digits
+// d[-i] are extracted in order:
+//
+// (10 * p2) div 2^-e = d[-1]
+// (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
+//
+// The multiplication by 10 must not overflow. It is sufficient to choose
+//
+// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
+//
+// Since p2 = f mod 2^-e < 2^-e,
+//
+// -e <= 60 or e >= -60 := alpha
+
+constexpr int kAlpha = -60;
+constexpr int kGamma = -32;
+
+struct cached_power // c = f * 2^e ~= 10^k
+{
+ std::uint64_t f;
+ int e;
+ int k;
+};
+
+/*!
+For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
+power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
+satisfies (Definition 3.2 from [1])
+
+ alpha <= e_c + e + q <= gamma.
+*/
+inline cached_power
+get_cached_power_for_binary_exponent(int e) {
+ // Now
+ //
+ // alpha <= e_c + e + q <= gamma (1)
+ // ==> f_c * 2^alpha <= c * 2^e * 2^q
+ //
+ // and since the c's are normalized, 2^(q-1) <= f_c,
+ //
+ // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
+ // ==> 2^(alpha - e - 1) <= c
+ //
+ // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
+ //
+ // k = ceil( log_10( 2^(alpha - e - 1) ) )
+ // = ceil( (alpha - e - 1) * log_10(2) )
+ //
+ // From the paper:
+ // "In theory the result of the procedure could be wrong since c is rounded,
+ // and the computation itself is approximated [...]. In practice, however,
+ // this simple function is sufficient."
+ //
+ // For IEEE double precision floating-point numbers converted into
+ // normalized diyfp's w = f * 2^e, with q = 64,
+ //
+ // e >= -1022 (min IEEE exponent)
+ // -52 (p - 1)
+ // -52 (p - 1, possibly normalize denormal IEEE numbers)
+ // -11 (normalize the diyfp)
+ // = -1137
+ //
+ // and
+ //
+ // e <= +1023 (max IEEE exponent)
+ // -52 (p - 1)
+ // -11 (normalize the diyfp)
+ // = 960
+ //
+ // This binary exponent range [-1137,960] results in a decimal exponent
+ // range [-307,324]. One does not need to store a cached power for each
+ // k in this range. For each such k it suffices to find a cached power
+ // such that the exponent of the product lies in [alpha,gamma].
+ // This implies that the difference of the decimal exponents of adjacent
+ // table entries must be less than or equal to
+ //
+ // floor( (gamma - alpha) * log_10(2) ) = 8.
+ //
+ // (A smaller distance gamma-alpha would require a larger table.)
+
+ // NB:
+ // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
+
+ constexpr int kCachedPowersMinDecExp = -300;
+ constexpr int kCachedPowersDecStep = 8;
+
+ static constexpr std::array<cached_power, 79> kCachedPowers = {{
+ {0xAB70FE17C79AC6CA, -1060, -300}, {0xFF77B1FCBEBCDC4F, -1034, -292}, {0xBE5691EF416BD60C, -1007, -284},
+ {0x8DD01FAD907FFC3C, -980, -276}, {0xD3515C2831559A83, -954, -268}, {0x9D71AC8FADA6C9B5, -927, -260},
+ {0xEA9C227723EE8BCB, -901, -252}, {0xAECC49914078536D, -874, -244}, {0x823C12795DB6CE57, -847, -236},
+ {0xC21094364DFB5637, -821, -228}, {0x9096EA6F3848984F, -794, -220}, {0xD77485CB25823AC7, -768, -212},
+ {0xA086CFCD97BF97F4, -741, -204}, {0xEF340A98172AACE5, -715, -196}, {0xB23867FB2A35B28E, -688, -188},
+ {0x84C8D4DFD2C63F3B, -661, -180}, {0xC5DD44271AD3CDBA, -635, -172}, {0x936B9FCEBB25C996, -608, -164},
+ {0xDBAC6C247D62A584, -582, -156}, {0xA3AB66580D5FDAF6, -555, -148}, {0xF3E2F893DEC3F126, -529, -140},
+ {0xB5B5ADA8AAFF80B8, -502, -132}, {0x87625F056C7C4A8B, -475, -124}, {0xC9BCFF6034C13053, -449, -116},
+ {0x964E858C91BA2655, -422, -108}, {0xDFF9772470297EBD, -396, -100}, {0xA6DFBD9FB8E5B88F, -369, -92},
+ {0xF8A95FCF88747D94, -343, -84}, {0xB94470938FA89BCF, -316, -76}, {0x8A08F0F8BF0F156B, -289, -68},
+ {0xCDB02555653131B6, -263, -60}, {0x993FE2C6D07B7FAC, -236, -52}, {0xE45C10C42A2B3B06, -210, -44},
+ {0xAA242499697392D3, -183, -36}, {0xFD87B5F28300CA0E, -157, -28}, {0xBCE5086492111AEB, -130, -20},
+ {0x8CBCCC096F5088CC, -103, -12}, {0xD1B71758E219652C, -77, -4}, {0x9C40000000000000, -50, 4},
+ {0xE8D4A51000000000, -24, 12}, {0xAD78EBC5AC620000, 3, 20}, {0x813F3978F8940984, 30, 28},
+ {0xC097CE7BC90715B3, 56, 36}, {0x8F7E32CE7BEA5C70, 83, 44}, {0xD5D238A4ABE98068, 109, 52},
+ {0x9F4F2726179A2245, 136, 60}, {0xED63A231D4C4FB27, 162, 68}, {0xB0DE65388CC8ADA8, 189, 76},
+ {0x83C7088E1AAB65DB, 216, 84}, {0xC45D1DF942711D9A, 242, 92}, {0x924D692CA61BE758, 269, 100},
+ {0xDA01EE641A708DEA, 295, 108}, {0xA26DA3999AEF774A, 322, 116}, {0xF209787BB47D6B85, 348, 124},
+ {0xB454E4A179DD1877, 375, 132}, {0x865B86925B9BC5C2, 402, 140}, {0xC83553C5C8965D3D, 428, 148},
+ {0x952AB45CFA97A0B3, 455, 156}, {0xDE469FBD99A05FE3, 481, 164}, {0xA59BC234DB398C25, 508, 172},
+ {0xF6C69A72A3989F5C, 534, 180}, {0xB7DCBF5354E9BECE, 561, 188}, {0x88FCF317F22241E2, 588, 196},
+ {0xCC20CE9BD35C78A5, 614, 204}, {0x98165AF37B2153DF, 641, 212}, {0xE2A0B5DC971F303A, 667, 220},
+ {0xA8D9D1535CE3B396, 694, 228}, {0xFB9B7CD9A4A7443C, 720, 236}, {0xBB764C4CA7A44410, 747, 244},
+ {0x8BAB8EEFB6409C1A, 774, 252}, {0xD01FEF10A657842C, 800, 260}, {0x9B10A4E5E9913129, 827, 268},
+ {0xE7109BFBA19C0C9D, 853, 276}, {0xAC2820D9623BF429, 880, 284}, {0x80444B5E7AA7CF85, 907, 292},
+ {0xBF21E44003ACDD2D, 933, 300}, {0x8E679C2F5E44FF8F, 960, 308}, {0xD433179D9C8CB841, 986, 316},
+ {0x9E19DB92B4E31BA9, 1013, 324},
+ }};
+
+ // This computation gives exactly the same results for k as
+ // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
+ // for |e| <= 1500, but doesn't require floating-point operations.
+ // NB: log_10(2) ~= 78913 / 2^18
+ JSON_ASSERT(e >= -1500);
+ JSON_ASSERT(e <= 1500);
+ const int f = kAlpha - e - 1;
+ const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
+
+ const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
+ JSON_ASSERT(index >= 0);
+ JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size());
+
+ const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
+ JSON_ASSERT(kAlpha <= cached.e + e + 64);
+ JSON_ASSERT(kGamma >= cached.e + e + 64);
+
+ return cached;
+}
+
+/*!
+For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
+For n == 0, returns 1 and sets pow10 := 1.
+*/
+inline int
+find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) {
+ // LCOV_EXCL_START
+ if (n >= 1000000000) {
+ pow10 = 1000000000;
+ return 10;
+ }
+ // LCOV_EXCL_STOP
+ if (n >= 100000000) {
+ pow10 = 100000000;
+ return 9;
+ }
+ if (n >= 10000000) {
+ pow10 = 10000000;
+ return 8;
+ }
+ if (n >= 1000000) {
+ pow10 = 1000000;
+ return 7;
+ }
+ if (n >= 100000) {
+ pow10 = 100000;
+ return 6;
+ }
+ if (n >= 10000) {
+ pow10 = 10000;
+ return 5;
+ }
+ if (n >= 1000) {
+ pow10 = 1000;
+ return 4;
+ }
+ if (n >= 100) {
+ pow10 = 100;
+ return 3;
+ }
+ if (n >= 10) {
+ pow10 = 10;
+ return 2;
+ }
+
+ pow10 = 1;
+ return 1;
+}
+
+inline void
+grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, std::uint64_t rest, std::uint64_t ten_k) {
+ JSON_ASSERT(len >= 1);
+ JSON_ASSERT(dist <= delta);
+ JSON_ASSERT(rest <= delta);
+ JSON_ASSERT(ten_k > 0);
+
+ // <--------------------------- delta ---->
+ // <---- dist --------->
+ // --------------[------------------+-------------------]--------------
+ // M- w M+
+ //
+ // ten_k
+ // <------>
+ // <---- rest ---->
+ // --------------[------------------+----+--------------]--------------
+ // w V
+ // = buf * 10^k
+ //
+ // ten_k represents a unit-in-the-last-place in the decimal representation
+ // stored in buf.
+ // Decrement buf by ten_k while this takes buf closer to w.
+
+ // The tests are written in this order to avoid overflow in unsigned
+ // integer arithmetic.
+
+ while (rest < dist && delta - rest >= ten_k && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) {
+ JSON_ASSERT(buf[len - 1] != '0');
+ buf[len - 1]--;
+ rest += ten_k;
+ }
+}
+
+/*!
+Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
+M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
+*/
+inline void
+grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, diyfp M_minus, diyfp w, diyfp M_plus) {
+ static_assert(kAlpha >= -60, "internal error");
+ static_assert(kGamma <= -32, "internal error");
+
+ // Generates the digits (and the exponent) of a decimal floating-point
+ // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
+ // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
+ //
+ // <--------------------------- delta ---->
+ // <---- dist --------->
+ // --------------[------------------+-------------------]--------------
+ // M- w M+
+ //
+ // Grisu2 generates the digits of M+ from left to right and stops as soon as
+ // V is in [M-,M+].
+
+ JSON_ASSERT(M_plus.e >= kAlpha);
+ JSON_ASSERT(M_plus.e <= kGamma);
+
+ std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
+ std::uint64_t dist = diyfp::sub(M_plus, w).f; // (significand of (M+ - w ), implicit exponent is e)
+
+ // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
+ //
+ // M+ = f * 2^e
+ // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
+ // = ((p1 ) * 2^-e + (p2 )) * 2^e
+ // = p1 + p2 * 2^e
+
+ const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
+
+ auto p1 =
+ static_cast<std::uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
+ std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
+
+ // 1)
+ //
+ // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
+
+ JSON_ASSERT(p1 > 0);
+
+ std::uint32_t pow10{};
+ const int k = find_largest_pow10(p1, pow10);
+
+ // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
+ //
+ // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
+ // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
+ //
+ // M+ = p1 + p2 * 2^e
+ // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
+ // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
+ // = d[k-1] * 10^(k-1) + ( rest) * 2^e
+ //
+ // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
+ //
+ // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
+ //
+ // but stop as soon as
+ //
+ // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
+
+ int n = k;
+ while (n > 0) {
+ // Invariants:
+ // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
+ // pow10 = 10^(n-1) <= p1 < 10^n
+ //
+ const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
+ const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
+ //
+ // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
+ // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
+ //
+ JSON_ASSERT(d <= 9);
+ buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
+ //
+ // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
+ //
+ p1 = r;
+ n--;
+ //
+ // M+ = buffer * 10^n + (p1 + p2 * 2^e)
+ // pow10 = 10^n
+ //
+
+ // Now check if enough digits have been generated.
+ // Compute
+ //
+ // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
+ //
+ // Note:
+ // Since rest and delta share the same exponent e, it suffices to
+ // compare the significands.
+ const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
+ if (rest <= delta) {
+ // V = buffer * 10^n, with M- <= V <= M+.
+
+ decimal_exponent += n;
+
+ // We may now just stop. But instead look if the buffer could be
+ // decremented to bring V closer to w.
+ //
+ // pow10 = 10^n is now 1 ulp in the decimal representation V.
+ // The rounding procedure works with diyfp's with an implicit
+ // exponent of e.
+ //
+ // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
+ //
+ const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
+ grisu2_round(buffer, length, dist, delta, rest, ten_n);
+
+ return;
+ }
+
+ pow10 /= 10;
+ //
+ // pow10 = 10^(n-1) <= p1 < 10^n
+ // Invariants restored.
+ }
+
+ // 2)
+ //
+ // The digits of the integral part have been generated:
+ //
+ // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
+ // = buffer + p2 * 2^e
+ //
+ // Now generate the digits of the fractional part p2 * 2^e.
+ //
+ // Note:
+ // No decimal point is generated: the exponent is adjusted instead.
+ //
+ // p2 actually represents the fraction
+ //
+ // p2 * 2^e
+ // = p2 / 2^-e
+ // = d[-1] / 10^1 + d[-2] / 10^2 + ...
+ //
+ // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
+ //
+ // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
+ // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
+ //
+ // using
+ //
+ // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
+ // = ( d) * 2^-e + ( r)
+ //
+ // or
+ // 10^m * p2 * 2^e = d + r * 2^e
+ //
+ // i.e.
+ //
+ // M+ = buffer + p2 * 2^e
+ // = buffer + 10^-m * (d + r * 2^e)
+ // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
+ //
+ // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
+
+ JSON_ASSERT(p2 > delta);
+
+ int m = 0;
+ for (;;) {
+ // Invariant:
+ // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
+ // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
+ // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
+ // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
+ //
+ JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
+ p2 *= 10;
+ const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
+ const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
+ //
+ // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
+ // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
+ // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
+ //
+ JSON_ASSERT(d <= 9);
+ buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
+ //
+ // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
+ //
+ p2 = r;
+ m++;
+ //
+ // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
+ // Invariant restored.
+
+ // Check if enough digits have been generated.
+ //
+ // 10^-m * p2 * 2^e <= delta * 2^e
+ // p2 * 2^e <= 10^m * delta * 2^e
+ // p2 <= 10^m * delta
+ delta *= 10;
+ dist *= 10;
+ if (p2 <= delta) {
+ break;
+ }
+ }
+
+ // V = buffer * 10^-m, with M- <= V <= M+.
+
+ decimal_exponent -= m;
+
+ // 1 ulp in the decimal representation is now 10^-m.
+ // Since delta and dist are now scaled by 10^m, we need to do the
+ // same with ulp in order to keep the units in sync.
+ //
+ // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
+ //
+ const std::uint64_t ten_m = one.f;
+ grisu2_round(buffer, length, dist, delta, p2, ten_m);
+
+ // By construction this algorithm generates the shortest possible decimal
+ // number (Loitsch, Theorem 6.2) which rounds back to w.
+ // For an input number of precision p, at least
+ //
+ // N = 1 + ceil(p * log_10(2))
+ //
+ // decimal digits are sufficient to identify all binary floating-point
+ // numbers (Matula, "In-and-Out conversions").
+ // This implies that the algorithm does not produce more than N decimal
+ // digits.
+ //
+ // N = 17 for p = 53 (IEEE double precision)
+ // N = 9 for p = 24 (IEEE single precision)
+}
+
+/*!
+v = buf * 10^decimal_exponent
+len is the length of the buffer (number of decimal digits)
+The buffer must be large enough, i.e. >= max_digits10.
+*/
+JSON_HEDLEY_NON_NULL(1)
+inline void
+grisu2(char* buf, int& len, int& decimal_exponent, diyfp m_minus, diyfp v, diyfp m_plus) {
+ JSON_ASSERT(m_plus.e == m_minus.e);
+ JSON_ASSERT(m_plus.e == v.e);
+
+ // --------(-----------------------+-----------------------)-------- (A)
+ // m- v m+
+ //
+ // --------------------(-----------+-----------------------)-------- (B)
+ // m- v m+
+ //
+ // First scale v (and m- and m+) such that the exponent is in the range
+ // [alpha, gamma].
+
+ const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
+
+ const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
+
+ // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
+ const diyfp w = diyfp::mul(v, c_minus_k);
+ const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
+ const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
+
+ // ----(---+---)---------------(---+---)---------------(---+---)----
+ // w- w w+
+ // = c*m- = c*v = c*m+
+ //
+ // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
+ // w+ are now off by a small amount.
+ // In fact:
+ //
+ // w - v * 10^k < 1 ulp
+ //
+ // To account for this inaccuracy, add resp. subtract 1 ulp.
+ //
+ // --------+---[---------------(---+---)---------------]---+--------
+ // w- M- w M+ w+
+ //
+ // Now any number in [M-, M+] (bounds included) will round to w when input,
+ // regardless of how the input rounding algorithm breaks ties.
+ //
+ // And digit_gen generates the shortest possible such number in [M-, M+].
+ // Note that this does not mean that Grisu2 always generates the shortest
+ // possible number in the interval (m-, m+).
+ const diyfp M_minus(w_minus.f + 1, w_minus.e);
+ const diyfp M_plus(w_plus.f - 1, w_plus.e);
+
+ decimal_exponent = -cached.k; // = -(-k) = k
+
+ grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
+}
+
+/*!
+v = buf * 10^decimal_exponent
+len is the length of the buffer (number of decimal digits)
+The buffer must be large enough, i.e. >= max_digits10.
+*/
+template <typename FloatType>
+JSON_HEDLEY_NON_NULL(1)
+void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) {
+ static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
+ "internal error: not enough precision");
+
+ JSON_ASSERT(std::isfinite(value));
+ JSON_ASSERT(value > 0);
+
+ // If the neighbors (and boundaries) of 'value' are always computed for double-precision
+ // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
+ // decimal representations are not exactly "short".
+ //
+ // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
+ // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
+ // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars'
+ // does.
+ // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
+ // representation using the corresponding std::from_chars function recovers value exactly". That
+ // indicates that single precision floating-point numbers should be recovered using
+ // 'std::strtof'.
+ //
+ // NB: If the neighbors are computed for single-precision numbers, there is a single float
+ // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
+ // value is off by 1 ulp.
+#if 0 // NOLINT(readability-avoid-unconditional-preprocessor-if)
+ const boundaries w = compute_boundaries(static_cast<double>(value));
+#else
+ const boundaries w = compute_boundaries(value);
+#endif
+
+ grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
+}
+
+/*!
+@brief appends a decimal representation of e to buf
+@return a pointer to the element following the exponent.
+@pre -1000 < e < 1000
+*/
+JSON_HEDLEY_NON_NULL(1)
+JSON_HEDLEY_RETURNS_NON_NULL
+inline char*
+append_exponent(char* buf, int e) {
+ JSON_ASSERT(e > -1000);
+ JSON_ASSERT(e < 1000);
+
+ if (e < 0) {
+ e = -e;
+ *buf++ = '-';
+ } else {
+ *buf++ = '+';
+ }
+
+ auto k = static_cast<std::uint32_t>(e);
+ if (k < 10) {
+ // Always print at least two digits in the exponent.
+ // This is for compatibility with printf("%g").
+ *buf++ = '0';
+ *buf++ = static_cast<char>('0' + k);
+ } else if (k < 100) {
+ *buf++ = static_cast<char>('0' + k / 10);
+ k %= 10;
+ *buf++ = static_cast<char>('0' + k);
+ } else {
+ *buf++ = static_cast<char>('0' + k / 100);
+ k %= 100;
+ *buf++ = static_cast<char>('0' + k / 10);
+ k %= 10;
+ *buf++ = static_cast<char>('0' + k);
+ }
+
+ return buf;
+}
+
+/*!
+@brief prettify v = buf * 10^decimal_exponent
+
+If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
+notation. Otherwise it will be printed in exponential notation.
+
+@pre min_exp < 0
+@pre max_exp > 0
+*/
+JSON_HEDLEY_NON_NULL(1)
+JSON_HEDLEY_RETURNS_NON_NULL
+inline char*
+format_buffer(char* buf, int len, int decimal_exponent, int min_exp, int max_exp) {
+ JSON_ASSERT(min_exp < 0);
+ JSON_ASSERT(max_exp > 0);
+
+ const int k = len;
+ const int n = len + decimal_exponent;
+
+ // v = buf * 10^(n-k)
+ // k is the length of the buffer (number of decimal digits)
+ // n is the position of the decimal point relative to the start of the buffer.
+
+ if (k <= n && n <= max_exp) {
+ // digits[000]
+ // len <= max_exp + 2
+
+ std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
+ // Make it look like a floating-point number (#362, #378)
+ buf[n + 0] = '.';
+ buf[n + 1] = '0';
+ return buf + (static_cast<size_t>(n) + 2);
+ }
+
+ if (0 < n && n <= max_exp) {
+ // dig.its
+ // len <= max_digits10 + 1
+
+ JSON_ASSERT(k > n);
+
+ std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
+ buf[n] = '.';
+ return buf + (static_cast<size_t>(k) + 1U);
+ }
+
+ if (min_exp < n && n <= 0) {
+ // 0.[000]digits
+ // len <= 2 + (-min_exp - 1) + max_digits10
+
+ std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
+ buf[0] = '0';
+ buf[1] = '.';
+ std::memset(buf + 2, '0', static_cast<size_t>(-n));
+ return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
+ }
+
+ if (k == 1) {
+ // dE+123
+ // len <= 1 + 5
+
+ buf += 1;
+ } else {
+ // d.igitsE+123
+ // len <= max_digits10 + 1 + 5
+
+ std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
+ buf[1] = '.';
+ buf += 1 + static_cast<size_t>(k);
+ }
+
+ *buf++ = 'e';
+ return append_exponent(buf, n - 1);
+}
+
+} // namespace dtoa_impl
+
+/*!
+@brief generates a decimal representation of the floating-point number value in [first, last).
+
+The format of the resulting decimal representation is similar to printf's %g
+format. Returns an iterator pointing past-the-end of the decimal representation.
+
+@note The input number must be finite, i.e. NaN's and Inf's are not supported.
+@note The buffer must be large enough.
+@note The result is NOT null-terminated.
+*/
+template <typename FloatType>
+JSON_HEDLEY_NON_NULL(1, 2)
+JSON_HEDLEY_RETURNS_NON_NULL char* to_chars(char* first, const char* last, FloatType value) {
+ static_cast<void>(last); // maybe unused - fix warning
+ JSON_ASSERT(std::isfinite(value));
+
+ // Use signbit(value) instead of (value < 0) since signbit works for -0.
+ if (std::signbit(value)) {
+ value = -value;
+ *first++ = '-';
+ }
+
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wfloat-equal"
+#endif
+ if (value == 0) // +-0
+ {
+ *first++ = '0';
+ // Make it look like a floating-point number (#362, #378)
+ *first++ = '.';
+ *first++ = '0';
+ return first;
+ }
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+
+ JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10);
+
+ // Compute v = buffer * 10^decimal_exponent.
+ // The decimal digits are stored in the buffer, which needs to be interpreted
+ // as an unsigned decimal integer.
+ // len is the length of the buffer, i.e. the number of decimal digits.
+ int len = 0;
+ int decimal_exponent = 0;
+ dtoa_impl::grisu2(first, len, decimal_exponent, value);
+
+ JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10);
+
+ // Format the buffer like printf("%.*g", prec, value)
+ constexpr int kMinExp = -4;
+ // Use digits10 here to increase compatibility with version 2.
+ constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
+
+ JSON_ASSERT(last - first >= kMaxExp + 2);
+ JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
+ JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
+
+ return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
+}
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/output/binary_writer.hpp>
+
+// #include <nlohmann/detail/output/output_adapters.hpp>
+
+// #include <nlohmann/detail/string_concat.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+namespace detail {
+
+///////////////////
+// serialization //
+///////////////////
+
+/// how to treat decoding errors
+enum class error_handler_t {
+ strict, ///< throw a type_error exception in case of invalid UTF-8
+ replace, ///< replace invalid UTF-8 sequences with U+FFFD
+ ignore ///< ignore invalid UTF-8 sequences
+};
+
+template <typename BasicJsonType>
+class serializer {
+ using string_t = typename BasicJsonType::string_t;
+ using number_float_t = typename BasicJsonType::number_float_t;
+ using number_integer_t = typename BasicJsonType::number_integer_t;
+ using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using binary_char_t = typename BasicJsonType::binary_t::value_type;
+ static constexpr std::uint8_t UTF8_ACCEPT = 0;
+ static constexpr std::uint8_t UTF8_REJECT = 1;
+
+ public:
+ /*!
+ @param[in] s output stream to serialize to
+ @param[in] ichar indentation character to use
+ @param[in] error_handler_ how to react on decoding errors
+ */
+ serializer(output_adapter_t<char> s, const char ichar, error_handler_t error_handler_ = error_handler_t::strict)
+ : o(std::move(s)),
+ loc(std::localeconv()),
+ thousands_sep(loc->thousands_sep == nullptr ? '\0'
+ : std::char_traits<char>::to_char_type(*(loc->thousands_sep))),
+ decimal_point(loc->decimal_point == nullptr ? '\0'
+ : std::char_traits<char>::to_char_type(*(loc->decimal_point))),
+ indent_char(ichar),
+ indent_string(512, indent_char),
+ error_handler(error_handler_) {}
+
+ // delete because of pointer members
+ serializer(const serializer&) = delete;
+ serializer&
+ operator=(const serializer&) = delete;
+ serializer(serializer&&) = delete;
+ serializer&
+ operator=(serializer&&) = delete;
+ ~serializer() = default;
+
+ /*!
+ @brief internal implementation of the serialization function
+
+ This function is called by the public member function dump and organizes
+ the serialization internally. The indentation level is propagated as
+ additional parameter. In case of arrays and objects, the function is
+ called recursively.
+
+ - strings and object keys are escaped using `escape_string()`
+ - integer numbers are converted implicitly via `operator<<`
+ - floating-point numbers are converted to a string using `"%g"` format
+ - binary values are serialized as objects containing the subtype and the
+ byte array
+
+ @param[in] val value to serialize
+ @param[in] pretty_print whether the output shall be pretty-printed
+ @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
+ in the output are escaped with `\uXXXX` sequences, and the result consists
+ of ASCII characters only.
+ @param[in] indent_step the indent level
+ @param[in] current_indent the current indent level (only used internally)
+ */
+ void
+ dump(const BasicJsonType& val,
+ const bool pretty_print,
+ const bool ensure_ascii,
+ const unsigned int indent_step,
+ const unsigned int current_indent = 0) {
+ switch (val.m_data.m_type) {
+ case value_t::object: {
+ if (val.m_data.m_value.object->empty()) {
+ o->write_characters("{}", 2);
+ return;
+ }
+
+ if (pretty_print) {
+ o->write_characters("{\n", 2);
+
+ // variable to hold indentation for recursive calls
+ const auto new_indent = current_indent + indent_step;
+ if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) {
+ indent_string.resize(indent_string.size() * 2, ' ');
+ }
+
+ // first n-1 elements
+ auto i = val.m_data.m_value.object->cbegin();
+ for (std::size_t cnt = 0; cnt < val.m_data.m_value.object->size() - 1; ++cnt, ++i) {
+ o->write_characters(indent_string.c_str(), new_indent);
+ o->write_character('\"');
+ dump_escaped(i->first, ensure_ascii);
+ o->write_characters("\": ", 3);
+ dump(i->second, true, ensure_ascii, indent_step, new_indent);
+ o->write_characters(",\n", 2);
+ }
+
+ // last element
+ JSON_ASSERT(i != val.m_data.m_value.object->cend());
+ JSON_ASSERT(std::next(i) == val.m_data.m_value.object->cend());
+ o->write_characters(indent_string.c_str(), new_indent);
+ o->write_character('\"');
+ dump_escaped(i->first, ensure_ascii);
+ o->write_characters("\": ", 3);
+ dump(i->second, true, ensure_ascii, indent_step, new_indent);
+
+ o->write_character('\n');
+ o->write_characters(indent_string.c_str(), current_indent);
+ o->write_character('}');
+ } else {
+ o->write_character('{');
+
+ // first n-1 elements
+ auto i = val.m_data.m_value.object->cbegin();
+ for (std::size_t cnt = 0; cnt < val.m_data.m_value.object->size() - 1; ++cnt, ++i) {
+ o->write_character('\"');
+ dump_escaped(i->first, ensure_ascii);
+ o->write_characters("\":", 2);
+ dump(i->second, false, ensure_ascii, indent_step, current_indent);
+ o->write_character(',');
+ }
+
+ // last element
+ JSON_ASSERT(i != val.m_data.m_value.object->cend());
+ JSON_ASSERT(std::next(i) == val.m_data.m_value.object->cend());
+ o->write_character('\"');
+ dump_escaped(i->first, ensure_ascii);
+ o->write_characters("\":", 2);
+ dump(i->second, false, ensure_ascii, indent_step, current_indent);
+
+ o->write_character('}');
+ }
+
+ return;
+ }
+
+ case value_t::array: {
+ if (val.m_data.m_value.array->empty()) {
+ o->write_characters("[]", 2);
+ return;
+ }
+
+ // Custom from FE: Added to reduce line bloat when dumping dims and strides
+ auto elementType = val.m_data.m_value.array->begin()->type();
+ if (pretty_print && (elementType != value_t::number_integer) &&
+ (elementType != value_t::number_unsigned))
+ // if (pretty_print)
+ {
+ o->write_characters("[\n", 2);
+
+ // variable to hold indentation for recursive calls
+ const auto new_indent = current_indent + indent_step;
+ if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) {
+ indent_string.resize(indent_string.size() * 2, ' ');
+ }
+
+ // first n-1 elements
+ for (auto i = val.m_data.m_value.array->cbegin(); i != val.m_data.m_value.array->cend() - 1; ++i) {
+ o->write_characters(indent_string.c_str(), new_indent);
+ dump(*i, true, ensure_ascii, indent_step, new_indent);
+ o->write_characters(",\n", 2);
+ }
+
+ // last element
+ JSON_ASSERT(!val.m_data.m_value.array->empty());
+ o->write_characters(indent_string.c_str(), new_indent);
+ dump(val.m_data.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
+
+ o->write_character('\n');
+ o->write_characters(indent_string.c_str(), current_indent);
+ o->write_character(']');
+ } else {
+ o->write_character('[');
+
+ // first n-1 elements
+ for (auto i = val.m_data.m_value.array->cbegin(); i != val.m_data.m_value.array->cend() - 1; ++i) {
+ dump(*i, false, ensure_ascii, indent_step, current_indent);
+ o->write_character(',');
+ }
+
+ // last element
+ JSON_ASSERT(!val.m_data.m_value.array->empty());
+ dump(val.m_data.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
+
+ o->write_character(']');
+ }
+
+ return;
+ }
+
+ case value_t::string: {
+ o->write_character('\"');
+ dump_escaped(*val.m_data.m_value.string, ensure_ascii);
+ o->write_character('\"');
+ return;
+ }
+
+ case value_t::binary: {
+ if (pretty_print) {
+ o->write_characters("{\n", 2);
+
+ // variable to hold indentation for recursive calls
+ const auto new_indent = current_indent + indent_step;
+ if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) {
+ indent_string.resize(indent_string.size() * 2, ' ');
+ }
+
+ o->write_characters(indent_string.c_str(), new_indent);
+
+ o->write_characters("\"bytes\": [", 10);
+
+ if (!val.m_data.m_value.binary->empty()) {
+ for (auto i = val.m_data.m_value.binary->cbegin(); i != val.m_data.m_value.binary->cend() - 1;
+ ++i) {
+ dump_integer(*i);
+ o->write_characters(", ", 2);
+ }
+ dump_integer(val.m_data.m_value.binary->back());
+ }
+
+ o->write_characters("],\n", 3);
+ o->write_characters(indent_string.c_str(), new_indent);
+
+ o->write_characters("\"subtype\": ", 11);
+ if (val.m_data.m_value.binary->has_subtype()) {
+ dump_integer(val.m_data.m_value.binary->subtype());
+ } else {
+ o->write_characters("null", 4);
+ }
+ o->write_character('\n');
+ o->write_characters(indent_string.c_str(), current_indent);
+ o->write_character('}');
+ } else {
+ o->write_characters("{\"bytes\":[", 10);
+
+ if (!val.m_data.m_value.binary->empty()) {
+ for (auto i = val.m_data.m_value.binary->cbegin(); i != val.m_data.m_value.binary->cend() - 1;
+ ++i) {
+ dump_integer(*i);
+ o->write_character(',');
+ }
+ dump_integer(val.m_data.m_value.binary->back());
+ }
+
+ o->write_characters("],\"subtype\":", 12);
+ if (val.m_data.m_value.binary->has_subtype()) {
+ dump_integer(val.m_data.m_value.binary->subtype());
+ o->write_character('}');
+ } else {
+ o->write_characters("null}", 5);
+ }
+ }
+ return;
+ }
+
+ case value_t::boolean: {
+ if (val.m_data.m_value.boolean) {
+ o->write_characters("true", 4);
+ } else {
+ o->write_characters("false", 5);
+ }
+ return;
+ }
+
+ case value_t::number_integer: {
+ dump_integer(val.m_data.m_value.number_integer);
+ return;
+ }
+
+ case value_t::number_unsigned: {
+ dump_integer(val.m_data.m_value.number_unsigned);
+ return;
+ }
+
+ case value_t::number_float: {
+ dump_float(val.m_data.m_value.number_float);
+ return;
+ }
+
+ case value_t::discarded: {
+ o->write_characters("<discarded>", 11);
+ return;
+ }
+
+ case value_t::null: {
+ o->write_characters("null", 4);
+ return;
+ }
+
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ }
+ }
+
+ JSON_PRIVATE_UNLESS_TESTED :
+ /*!
+ @brief dump escaped string
+
+ Escape a string by replacing certain special characters by a sequence of an
+ escape character (backslash) and another character and other control
+ characters by a sequence of "\u" followed by a four-digit hex
+ representation. The escaped string is written to output stream @a o.
+
+ @param[in] s the string to escape
+ @param[in] ensure_ascii whether to escape non-ASCII characters with
+ \uXXXX sequences
+
+ @complexity Linear in the length of string @a s.
+ */
+ void
+ dump_escaped(const string_t& s, const bool ensure_ascii) {
+ std::uint32_t codepoint{};
+ std::uint8_t state = UTF8_ACCEPT;
+ std::size_t bytes = 0; // number of bytes written to string_buffer
+
+ // number of bytes written at the point of the last valid byte
+ std::size_t bytes_after_last_accept = 0;
+ std::size_t undumped_chars = 0;
+
+ for (std::size_t i = 0; i < s.size(); ++i) {
+ const auto byte = static_cast<std::uint8_t>(s[i]);
+
+ switch (decode(state, codepoint, byte)) {
+ case UTF8_ACCEPT: // decode found a new code point
+ {
+ switch (codepoint) {
+ case 0x08: // backspace
+ {
+ string_buffer[bytes++] = '\\';
+ string_buffer[bytes++] = 'b';
+ break;
+ }
+
+ case 0x09: // horizontal tab
+ {
+ string_buffer[bytes++] = '\\';
+ string_buffer[bytes++] = 't';
+ break;
+ }
+
+ case 0x0A: // newline
+ {
+ string_buffer[bytes++] = '\\';
+ string_buffer[bytes++] = 'n';
+ break;
+ }
+
+ case 0x0C: // formfeed
+ {
+ string_buffer[bytes++] = '\\';
+ string_buffer[bytes++] = 'f';
+ break;
+ }
+
+ case 0x0D: // carriage return
+ {
+ string_buffer[bytes++] = '\\';
+ string_buffer[bytes++] = 'r';
+ break;
+ }
+
+ case 0x22: // quotation mark
+ {
+ string_buffer[bytes++] = '\\';
+ string_buffer[bytes++] = '\"';
+ break;
+ }
+
+ case 0x5C: // reverse solidus
+ {
+ string_buffer[bytes++] = '\\';
+ string_buffer[bytes++] = '\\';
+ break;
+ }
+
+ default: {
+ // escape control characters (0x00..0x1F) or, if
+ // ensure_ascii parameter is used, non-ASCII characters
+ if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) {
+ if (codepoint <= 0xFFFF) {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+ static_cast<void>((std::snprintf)(string_buffer.data() + bytes,
+ 7,
+ "\\u%04x",
+ static_cast<std::uint16_t>(codepoint)));
+ bytes += 6;
+ } else {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+ static_cast<void>(
+ (std::snprintf)(string_buffer.data() + bytes,
+ 13,
+ "\\u%04x\\u%04x",
+ static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
+ static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu))));
+ bytes += 12;
+ }
+ } else {
+ // copy byte to buffer (all previous bytes
+ // been copied have in default case above)
+ string_buffer[bytes++] = s[i];
+ }
+ break;
+ }
+ }
+
+ // write buffer and reset index; there must be 13 bytes
+ // left, as this is the maximal number of bytes to be
+ // written ("\uxxxx\uxxxx\0") for one code point
+ if (string_buffer.size() - bytes < 13) {
+ o->write_characters(string_buffer.data(), bytes);
+ bytes = 0;
+ }
+
+ // remember the byte position of this accept
+ bytes_after_last_accept = bytes;
+ undumped_chars = 0;
+ break;
+ }
+
+ case UTF8_REJECT: // decode found invalid UTF-8 byte
+ {
+ switch (error_handler) {
+ case error_handler_t::strict: {
+ JSON_THROW(type_error::create(
+ 316,
+ concat("invalid UTF-8 byte at index ", std::to_string(i), ": 0x", hex_bytes(byte | 0)),
+ nullptr));
+ }
+
+ case error_handler_t::ignore:
+ case error_handler_t::replace: {
+ // in case we saw this character the first time, we
+ // would like to read it again, because the byte
+ // may be OK for itself, but just not OK for the
+ // previous sequence
+ if (undumped_chars > 0) {
+ --i;
+ }
+
+ // reset length buffer to the last accepted index;
+ // thus removing/ignoring the invalid characters
+ bytes = bytes_after_last_accept;
+
+ if (error_handler == error_handler_t::replace) {
+ // add a replacement character
+ if (ensure_ascii) {
+ string_buffer[bytes++] = '\\';
+ string_buffer[bytes++] = 'u';
+ string_buffer[bytes++] = 'f';
+ string_buffer[bytes++] = 'f';
+ string_buffer[bytes++] = 'f';
+ string_buffer[bytes++] = 'd';
+ } else {
+ string_buffer[bytes++] =
+ detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
+ string_buffer[bytes++] =
+ detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
+ string_buffer[bytes++] =
+ detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
+ }
+
+ // write buffer and reset index; there must be 13 bytes
+ // left, as this is the maximal number of bytes to be
+ // written ("\uxxxx\uxxxx\0") for one code point
+ if (string_buffer.size() - bytes < 13) {
+ o->write_characters(string_buffer.data(), bytes);
+ bytes = 0;
+ }
+
+ bytes_after_last_accept = bytes;
+ }
+
+ undumped_chars = 0;
+
+ // continue processing the string
+ state = UTF8_ACCEPT;
+ break;
+ }
+
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(
+ false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ }
+ break;
+ }
+
+ default: // decode found yet incomplete multi-byte code point
+ {
+ if (!ensure_ascii) {
+ // code point will not be escaped - copy byte to buffer
+ string_buffer[bytes++] = s[i];
+ }
+ ++undumped_chars;
+ break;
+ }
+ }
+ }
+
+ // we finished processing the string
+ if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) {
+ // write buffer
+ if (bytes > 0) {
+ o->write_characters(string_buffer.data(), bytes);
+ }
+ } else {
+ // we finish reading, but do not accept: string was incomplete
+ switch (error_handler) {
+ case error_handler_t::strict: {
+ JSON_THROW(type_error::create(316,
+ concat("incomplete UTF-8 string; last byte: 0x",
+ hex_bytes(static_cast<std::uint8_t>(s.back() | 0))),
+ nullptr));
+ }
+
+ case error_handler_t::ignore: {
+ // write all accepted bytes
+ o->write_characters(string_buffer.data(), bytes_after_last_accept);
+ break;
+ }
+
+ case error_handler_t::replace: {
+ // write all accepted bytes
+ o->write_characters(string_buffer.data(), bytes_after_last_accept);
+ // add a replacement character
+ if (ensure_ascii) {
+ o->write_characters("\\ufffd", 6);
+ } else {
+ o->write_characters("\xEF\xBF\xBD", 3);
+ }
+ break;
+ }
+
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ }
+ }
+ }
+
+ private:
+ /*!
+ @brief count digits
+
+ Count the number of decimal (base 10) digits for an input unsigned integer.
+
+ @param[in] x unsigned integer number to count its digits
+ @return number of decimal digits
+ */
+ inline unsigned int
+ count_digits(number_unsigned_t x) noexcept {
+ unsigned int n_digits = 1;
+ for (;;) {
+ if (x < 10) {
+ return n_digits;
+ }
+ if (x < 100) {
+ return n_digits + 1;
+ }
+ if (x < 1000) {
+ return n_digits + 2;
+ }
+ if (x < 10000) {
+ return n_digits + 3;
+ }
+ x = x / 10000u;
+ n_digits += 4;
+ }
+ }
+
+ /*!
+ * @brief convert a byte to a uppercase hex representation
+ * @param[in] byte byte to represent
+ * @return representation ("00".."FF")
+ */
+ static std::string
+ hex_bytes(std::uint8_t byte) {
+ std::string result = "FF";
+ constexpr const char* nibble_to_hex = "0123456789ABCDEF";
+ result[0] = nibble_to_hex[byte / 16];
+ result[1] = nibble_to_hex[byte % 16];
+ return result;
+ }
+
+ // templates to avoid warnings about useless casts
+ template <typename NumberType, enable_if_t<std::is_signed<NumberType>::value, int> = 0>
+ bool
+ is_negative_number(NumberType x) {
+ return x < 0;
+ }
+
+ template <typename NumberType, enable_if_t<std::is_unsigned<NumberType>::value, int> = 0>
+ bool
+ is_negative_number(NumberType /*unused*/) {
+ return false;
+ }
+
+ /*!
+ @brief dump an integer
+
+ Dump a given integer to output stream @a o. Works internally with
+ @a number_buffer.
+
+ @param[in] x integer number (signed or unsigned) to dump
+ @tparam NumberType either @a number_integer_t or @a number_unsigned_t
+ */
+ template <
+ typename NumberType,
+ detail::enable_if_t<std::is_integral<NumberType>::value || std::is_same<NumberType, number_unsigned_t>::value ||
+ std::is_same<NumberType, number_integer_t>::value ||
+ std::is_same<NumberType, binary_char_t>::value,
+ int> = 0>
+ void
+ dump_integer(NumberType x) {
+ static constexpr std::array<std::array<char, 2>, 100> digits_to_99{{
+ {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}},
+ {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}},
+ {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, {{'2', '0'}},
+ {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}},
+ {{'2', '8'}}, {{'2', '9'}}, {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}},
+ {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, {{'4', '0'}}, {{'4', '1'}},
+ {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}},
+ {{'4', '9'}}, {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}},
+ {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}},
+ {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
+ {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}},
+ {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}},
+ {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, {{'9', '0'}},
+ {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}},
+ {{'9', '8'}}, {{'9', '9'}},
+ }};
+
+ // special case for "0"
+ if (x == 0) {
+ o->write_character('0');
+ return;
+ }
+
+ // use a pointer to fill the buffer
+ auto buffer_ptr =
+ number_buffer
+ .begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+
+ number_unsigned_t abs_value;
+
+ unsigned int n_chars{};
+
+ if (is_negative_number(x)) {
+ *buffer_ptr = '-';
+ abs_value = remove_sign(static_cast<number_integer_t>(x));
+
+ // account one more byte for the minus sign
+ n_chars = 1 + count_digits(abs_value);
+ } else {
+ abs_value = static_cast<number_unsigned_t>(x);
+ n_chars = count_digits(abs_value);
+ }
+
+ // spare 1 byte for '\0'
+ JSON_ASSERT(n_chars < number_buffer.size() - 1);
+
+ // jump to the end to generate the string from backward,
+ // so we later avoid reversing the result
+ buffer_ptr += n_chars;
+
+ // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
+ // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
+ while (abs_value >= 100) {
+ const auto digits_index = static_cast<unsigned>((abs_value % 100));
+ abs_value /= 100;
+ *(--buffer_ptr) = digits_to_99[digits_index][1];
+ *(--buffer_ptr) = digits_to_99[digits_index][0];
+ }
+
+ if (abs_value >= 10) {
+ const auto digits_index = static_cast<unsigned>(abs_value);
+ *(--buffer_ptr) = digits_to_99[digits_index][1];
+ *(--buffer_ptr) = digits_to_99[digits_index][0];
+ } else {
+ *(--buffer_ptr) = static_cast<char>('0' + abs_value);
+ }
+
+ o->write_characters(number_buffer.data(), n_chars);
+ }
+
+ /*!
+ @brief dump a floating-point number
+
+ Dump a given floating-point number to output stream @a o. Works internally
+ with @a number_buffer.
+
+ @param[in] x floating-point number to dump
+ */
+ void
+ dump_float(number_float_t x) {
+ // NaN / inf
+ if (!std::isfinite(x)) {
+ o->write_characters("null", 4);
+ return;
+ }
+
+ // If number_float_t is an IEEE-754 single or double precision number,
+ // use the Grisu2 algorithm to produce short numbers which are
+ // guaranteed to round-trip, using strtof and strtod, resp.
+ //
+ // NB: The test below works if <long double> == <double>.
+ static constexpr bool is_ieee_single_or_double =
+ (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 &&
+ std::numeric_limits<number_float_t>::max_exponent == 128) ||
+ (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 &&
+ std::numeric_limits<number_float_t>::max_exponent == 1024);
+
+ dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
+ }
+
+ void
+ dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) {
+ auto* begin = number_buffer.data();
+ auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
+
+ o->write_characters(begin, static_cast<size_t>(end - begin));
+ }
+
+ void
+ dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) {
+ // get number of digits for a float -> text -> float round-trip
+ static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
+
+ // the actual conversion
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+ std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
+
+ // negative value indicates an error
+ JSON_ASSERT(len > 0);
+ // check if buffer was large enough
+ JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());
+
+ // erase thousands separator
+ if (thousands_sep != '\0') {
+ // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see
+ // https://github.com/nlohmann/json/issues/3081
+ const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep);
+ std::fill(end, number_buffer.end(), '\0');
+ JSON_ASSERT((end - number_buffer.begin()) <= len);
+ len = (end - number_buffer.begin());
+ }
+
+ // convert decimal point to '.'
+ if (decimal_point != '\0' && decimal_point != '.') {
+ // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see
+ // https://github.com/nlohmann/json/issues/3081
+ const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
+ if (dec_pos != number_buffer.end()) {
+ *dec_pos = '.';
+ }
+ }
+
+ o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
+
+ // determine if we need to append ".0"
+ const bool value_is_int_like = std::none_of(
+ number_buffer.begin(), number_buffer.begin() + len + 1, [](char c) { return c == '.' || c == 'e'; });
+
+ if (value_is_int_like) {
+ o->write_characters(".0", 2);
+ }
+ }
+
+ /*!
+ @brief check whether a string is UTF-8 encoded
+
+ The function checks each byte of a string whether it is UTF-8 encoded. The
+ result of the check is stored in the @a state parameter. The function must
+ be called initially with state 0 (accept). State 1 means the string must
+ be rejected, because the current byte is not allowed. If the string is
+ completely processed, but the state is non-zero, the string ended
+ prematurely; that is, the last byte indicated more bytes should have
+ followed.
+
+ @param[in,out] state the state of the decoding
+ @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
+ @param[in] byte next byte to decode
+ @return new state
+
+ @note The function has been edited: a std::array is used.
+
+ @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
+ @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
+ */
+ static std::uint8_t
+ decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept {
+ static const std::array<std::uint8_t, 400> utf8d = {{
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F
+ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF
+ 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF
+ 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
+ 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
+ 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2
+ 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
+ 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
+ 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1,
+ 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8
+ }};
+
+ JSON_ASSERT(byte < utf8d.size());
+ const std::uint8_t type = utf8d[byte];
+
+ codep = (state != UTF8_ACCEPT) ? (byte & 0x3fu) | (codep << 6u) : (0xFFu >> type) & (byte);
+
+ const std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
+ JSON_ASSERT(index < utf8d.size());
+ state = utf8d[index];
+ return state;
+ }
+
+ /*
+ * Overload to make the compiler happy while it is instantiating
+ * dump_integer for number_unsigned_t.
+ * Must never be called.
+ */
+ number_unsigned_t
+ remove_sign(number_unsigned_t x) {
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ return x; // LCOV_EXCL_LINE
+ }
+
+ /*
+ * Helper function for dump_integer
+ *
+ * This function takes a negative signed integer and returns its absolute
+ * value as unsigned integer. The plus/minus shuffling is necessary as we can
+ * not directly remove the sign of an arbitrary signed integer as the
+ * absolute values of INT_MIN and INT_MAX are usually not the same. See
+ * #1708 for details.
+ */
+ inline number_unsigned_t
+ remove_sign(number_integer_t x) noexcept {
+ JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)()); // NOLINT(misc-redundant-expression)
+ return static_cast<number_unsigned_t>(-(x + 1)) + 1;
+ }
+
+ private:
+ /// the output of the serializer
+ output_adapter_t<char> o = nullptr;
+
+ /// a (hopefully) large enough character buffer
+ std::array<char, 64> number_buffer{{}};
+
+ /// the locale
+ const std::lconv* loc = nullptr;
+ /// the locale's thousand separator character
+ const char thousands_sep = '\0';
+ /// the locale's decimal point character
+ const char decimal_point = '\0';
+
+ /// string buffer
+ std::array<char, 512> string_buffer{{}};
+
+ /// the indentation character
+ const char indent_char;
+ /// the indentation string
+ string_t indent_string;
+
+ /// error_handler how to react on decoding errors
+ const error_handler_t error_handler;
+};
+
+} // namespace detail
+NLOHMANN_JSON_NAMESPACE_END
+
+// #include <nlohmann/detail/value_t.hpp>
+
+// #include <nlohmann/json_fwd.hpp>
+
+// #include <nlohmann/ordered_map.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#include <functional> // equal_to, less
+#include <initializer_list> // initializer_list
+#include <iterator> // input_iterator_tag, iterator_traits
+#include <memory> // allocator
+#include <stdexcept> // for out_of_range
+#include <type_traits> // enable_if, is_convertible
+#include <utility> // pair
+#include <vector> // vector
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+NLOHMANN_JSON_NAMESPACE_BEGIN
+
+/// ordered_map: a minimal map-like container that preserves insertion order
+/// for use within nlohmann::basic_json<ordered_map>
+template <class Key,
+ class T,
+ class IgnoredLess = std::less<Key>,
+ class Allocator = std::allocator<std::pair<const Key, T>>>
+struct ordered_map : std::vector<std::pair<const Key, T>, Allocator> {
+ using key_type = Key;
+ using mapped_type = T;
+ using Container = std::vector<std::pair<const Key, T>, Allocator>;
+ using iterator = typename Container::iterator;
+ using const_iterator = typename Container::const_iterator;
+ using size_type = typename Container::size_type;
+ using value_type = typename Container::value_type;
+#ifdef JSON_HAS_CPP_14
+ using key_compare = std::equal_to<>;
+#else
+ using key_compare = std::equal_to<Key>;
+#endif
+
+ // Explicit constructors instead of `using Container::Container`
+ // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
+ ordered_map() noexcept(noexcept(Container())) : Container{} {}
+ explicit ordered_map(const Allocator& alloc) noexcept(noexcept(Container(alloc))) : Container{alloc} {}
+ template <class It>
+ ordered_map(It first, It last, const Allocator& alloc = Allocator()) : Container{first, last, alloc} {}
+ ordered_map(std::initializer_list<value_type> init, const Allocator& alloc = Allocator())
+ : Container{init, alloc} {}
+
+ std::pair<iterator, bool>
+ emplace(const key_type& key, T&& t) {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return {it, false};
+ }
+ }
+ Container::emplace_back(key, std::forward<T>(t));
+ return {std::prev(this->end()), true};
+ }
+
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0>
+ std::pair<iterator, bool>
+ emplace(KeyType&& key, T&& t) {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return {it, false};
+ }
+ }
+ Container::emplace_back(std::forward<KeyType>(key), std::forward<T>(t));
+ return {std::prev(this->end()), true};
+ }
+
+ T&
+ operator[](const key_type& key) {
+ return emplace(key, T{}).first->second;
+ }
+
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0>
+ T&
+ operator[](KeyType&& key) {
+ return emplace(std::forward<KeyType>(key), T{}).first->second;
+ }
+
+ const T&
+ operator[](const key_type& key) const {
+ return at(key);
+ }
+
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0>
+ const T&
+ operator[](KeyType&& key) const {
+ return at(std::forward<KeyType>(key));
+ }
+
+ T&
+ at(const key_type& key) {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return it->second;
+ }
+ }
+
+ JSON_THROW(std::out_of_range("key not found"));
+ }
+
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0>
+ T&
+ at(KeyType&& key) // NOLINT(cppcoreguidelines-missing-std-forward)
+ {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return it->second;
+ }
+ }
+
+ JSON_THROW(std::out_of_range("key not found"));
+ }
+
+ const T&
+ at(const key_type& key) const {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return it->second;
+ }
+ }
+
+ JSON_THROW(std::out_of_range("key not found"));
+ }
+
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0>
+ const T&
+ at(KeyType&& key) const // NOLINT(cppcoreguidelines-missing-std-forward)
+ {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return it->second;
+ }
+ }
+
+ JSON_THROW(std::out_of_range("key not found"));
+ }
+
+ size_type
+ erase(const key_type& key) {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ // Since we cannot move const Keys, re-construct them in place
+ for (auto next = it; ++next != this->end(); ++it) {
+ it->~value_type(); // Destroy but keep allocation
+ new (&*it) value_type{std::move(*next)};
+ }
+ Container::pop_back();
+ return 1;
+ }
+ }
+ return 0;
+ }
+
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0>
+ size_type
+ erase(KeyType&& key) // NOLINT(cppcoreguidelines-missing-std-forward)
+ {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ // Since we cannot move const Keys, re-construct them in place
+ for (auto next = it; ++next != this->end(); ++it) {
+ it->~value_type(); // Destroy but keep allocation
+ new (&*it) value_type{std::move(*next)};
+ }
+ Container::pop_back();
+ return 1;
+ }
+ }
+ return 0;
+ }
+
+ iterator
+ erase(iterator pos) {
+ return erase(pos, std::next(pos));
+ }
+
+ iterator
+ erase(iterator first, iterator last) {
+ if (first == last) {
+ return first;
+ }
+
+ const auto elements_affected = std::distance(first, last);
+ const auto offset = std::distance(Container::begin(), first);
+
+ // This is the start situation. We need to delete elements_affected
+ // elements (3 in this example: e, f, g), and need to return an
+ // iterator past the last deleted element (h in this example).
+ // Note that offset is the distance from the start of the vector
+ // to first. We will need this later.
+
+ // [ a, b, c, d, e, f, g, h, i, j ]
+ // ^ ^
+ // first last
+
+ // Since we cannot move const Keys, we re-construct them in place.
+ // We start at first and re-construct (viz. copy) the elements from
+ // the back of the vector. Example for first iteration:
+
+ // ,--------.
+ // v | destroy e and re-construct with h
+ // [ a, b, c, d, e, f, g, h, i, j ]
+ // ^ ^
+ // it it + elements_affected
+
+ for (auto it = first; std::next(it, elements_affected) != Container::end(); ++it) {
+ it->~value_type(); // destroy but keep allocation
+ new (&*it) value_type{std::move(*std::next(it, elements_affected))}; // "move" next element to it
+ }
+
+ // [ a, b, c, d, h, i, j, h, i, j ]
+ // ^ ^
+ // first last
+
+ // remove the unneeded elements at the end of the vector
+ Container::resize(this->size() - static_cast<size_type>(elements_affected));
+
+ // [ a, b, c, d, h, i, j ]
+ // ^ ^
+ // first last
+
+ // first is now pointing past the last deleted element, but we cannot
+ // use this iterator, because it may have been invalidated by the
+ // resize call. Instead, we can return begin() + offset.
+ return Container::begin() + offset;
+ }
+
+ size_type
+ count(const key_type& key) const {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return 1;
+ }
+ }
+ return 0;
+ }
+
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0>
+ size_type
+ count(KeyType&& key) const // NOLINT(cppcoreguidelines-missing-std-forward)
+ {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return 1;
+ }
+ }
+ return 0;
+ }
+
+ iterator
+ find(const key_type& key) {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return it;
+ }
+ }
+ return Container::end();
+ }
+
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0>
+ iterator
+ find(KeyType&& key) // NOLINT(cppcoreguidelines-missing-std-forward)
+ {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return it;
+ }
+ }
+ return Container::end();
+ }
+
+ const_iterator
+ find(const key_type& key) const {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, key)) {
+ return it;
+ }
+ }
+ return Container::end();
+ }
+
+ std::pair<iterator, bool>
+ insert(value_type&& value) {
+ return emplace(value.first, std::move(value.second));
+ }
+
+ std::pair<iterator, bool>
+ insert(const value_type& value) {
+ for (auto it = this->begin(); it != this->end(); ++it) {
+ if (m_compare(it->first, value.first)) {
+ return {it, false};
+ }
+ }
+ Container::push_back(value);
+ return {--this->end(), true};
+ }
+
+ template <typename InputIt>
+ using require_input_iter =
+ typename std::enable_if<std::is_convertible<typename std::iterator_traits<InputIt>::iterator_category,
+ std::input_iterator_tag>::value>::type;
+
+ template <typename InputIt, typename = require_input_iter<InputIt>>
+ void
+ insert(InputIt first, InputIt last) {
+ for (auto it = first; it != last; ++it) {
+ insert(*it);
+ }
+ }
+
+ private:
+ JSON_NO_UNIQUE_ADDRESS key_compare m_compare = key_compare();
+};
+
+NLOHMANN_JSON_NAMESPACE_END
+
+#if defined(JSON_HAS_CPP_17)
+#if JSON_HAS_STATIC_RTTI
+#include <any>
+#endif
+#include <string_view>
+#endif
+
+/*!
+@brief namespace for Niels Lohmann
+@see https://github.com/nlohmann
+@since version 1.0.0
+*/
+NLOHMANN_JSON_NAMESPACE_BEGIN
+
+/*!
+@brief a class to store JSON values
+
+@internal
+@invariant The member variables @a m_value and @a m_type have the following
+relationship:
+- If `m_type == value_t::object`, then `m_value.object != nullptr`.
+- If `m_type == value_t::array`, then `m_value.array != nullptr`.
+- If `m_type == value_t::string`, then `m_value.string != nullptr`.
+The invariants are checked by member function assert_invariant().
+
+@note ObjectType trick from https://stackoverflow.com/a/9860911
+@endinternal
+
+@since version 1.0.0
+
+@nosubgrouping
+*/
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
+ : public ::nlohmann::detail::json_base_class<CustomBaseClass> {
+ private:
+ template <detail::value_t>
+ friend struct detail::external_constructor;
+
+ template <typename>
+ friend class ::nlohmann::json_pointer;
+ // can be restored when json_pointer backwards compatibility is removed
+ // friend ::nlohmann::json_pointer<StringType>;
+
+ template <typename BasicJsonType, typename InputType>
+ friend class ::nlohmann::detail::parser;
+ friend ::nlohmann::detail::serializer<basic_json>;
+ template <typename BasicJsonType>
+ friend class ::nlohmann::detail::iter_impl;
+ template <typename BasicJsonType, typename CharType>
+ friend class ::nlohmann::detail::binary_writer;
+ template <typename BasicJsonType, typename InputType, typename SAX>
+ friend class ::nlohmann::detail::binary_reader;
+ template <typename BasicJsonType>
+ friend class ::nlohmann::detail::json_sax_dom_parser;
+ template <typename BasicJsonType>
+ friend class ::nlohmann::detail::json_sax_dom_callback_parser;
+ friend class ::nlohmann::detail::exception;
+
+ /// workaround type for MSVC
+ using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
+ using json_base_class_t = ::nlohmann::detail::json_base_class<CustomBaseClass>;
+
+ JSON_PRIVATE_UNLESS_TESTED :
+ // convenience aliases for types residing in namespace detail;
+ using lexer = ::nlohmann::detail::lexer_base<basic_json>;
+
+ template <typename InputAdapterType>
+ static ::nlohmann::detail::parser<basic_json, InputAdapterType>
+ parser(InputAdapterType adapter,
+ detail::parser_callback_t<basic_json> cb = nullptr,
+ const bool allow_exceptions = true,
+ const bool ignore_comments = false) {
+ return ::nlohmann::detail::parser<basic_json, InputAdapterType>(
+ std::move(adapter), std::move(cb), allow_exceptions, ignore_comments);
+ }
+
+ private:
+ using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
+ template <typename BasicJsonType>
+ using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
+ template <typename BasicJsonType>
+ using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
+ template <typename Iterator>
+ using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
+ template <typename Base>
+ using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
+
+ template <typename CharType>
+ using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
+
+ template <typename InputType>
+ using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
+ template <typename CharType>
+ using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
+
+ JSON_PRIVATE_UNLESS_TESTED : using serializer = ::nlohmann::detail::serializer<basic_json>;
+
+ public:
+ using value_t = detail::value_t;
+ /// JSON Pointer, see @ref nlohmann::json_pointer
+ using json_pointer = ::nlohmann::json_pointer<StringType>;
+ template <typename T, typename SFINAE>
+ using json_serializer = JSONSerializer<T, SFINAE>;
+ /// how to treat decoding errors
+ using error_handler_t = detail::error_handler_t;
+ /// how to treat CBOR tags
+ using cbor_tag_handler_t = detail::cbor_tag_handler_t;
+ /// helper type for initializer lists of basic_json values
+ using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
+
+ using input_format_t = detail::input_format_t;
+ /// SAX interface type, see @ref nlohmann::json_sax
+ using json_sax_t = json_sax<basic_json>;
+
+ ////////////////
+ // exceptions //
+ ////////////////
+
+ /// @name exceptions
+ /// Classes to implement user-defined exceptions.
+ /// @{
+
+ using exception = detail::exception;
+ using parse_error = detail::parse_error;
+ using invalid_iterator = detail::invalid_iterator;
+ using type_error = detail::type_error;
+ using out_of_range = detail::out_of_range;
+ using other_error = detail::other_error;
+
+ /// @}
+
+ /////////////////////
+ // container types //
+ /////////////////////
+
+ /// @name container types
+ /// The canonic container types to use @ref basic_json like any other STL
+ /// container.
+ /// @{
+
+ /// the type of elements in a basic_json container
+ using value_type = basic_json;
+
+ /// the type of an element reference
+ using reference = value_type&;
+ /// the type of an element const reference
+ using const_reference = const value_type&;
+
+ /// a type to represent differences between iterators
+ using difference_type = std::ptrdiff_t;
+ /// a type to represent container sizes
+ using size_type = std::size_t;
+
+ /// the allocator type
+ using allocator_type = AllocatorType<basic_json>;
+
+ /// the type of an element pointer
+ using pointer = typename std::allocator_traits<allocator_type>::pointer;
+ /// the type of an element const pointer
+ using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
+
+ /// an iterator for a basic_json container
+ using iterator = iter_impl<basic_json>;
+ /// a const iterator for a basic_json container
+ using const_iterator = iter_impl<const basic_json>;
+ /// a reverse iterator for a basic_json container
+ using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
+ /// a const reverse iterator for a basic_json container
+ using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
+
+ /// @}
+
+ /// @brief returns the allocator associated with the container
+ /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/
+ static allocator_type
+ get_allocator() {
+ return allocator_type();
+ }
+
+ /// @brief returns version information on the library
+ /// @sa https://json.nlohmann.me/api/basic_json/meta/
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ static basic_json
+ meta() {
+ basic_json result;
+
+ result["copyright"] = "(C) 2013-2023 Niels Lohmann";
+ result["name"] = "JSON for Modern C++";
+ result["url"] = "https://github.com/nlohmann/json";
+ result["version"]["string"] = detail::concat(std::to_string(NLOHMANN_JSON_VERSION_MAJOR),
+ '.',
+ std::to_string(NLOHMANN_JSON_VERSION_MINOR),
+ '.',
+ std::to_string(NLOHMANN_JSON_VERSION_PATCH));
+ result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
+ result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
+ result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
+
+#ifdef _WIN32
+ result["platform"] = "win32";
+#elif defined __linux__
+ result["platform"] = "linux";
+#elif defined __APPLE__
+ result["platform"] = "apple";
+#elif defined __unix__
+ result["platform"] = "unix";
+#else
+ result["platform"] = "unknown";
+#endif
+
+#if defined(__ICC) || defined(__INTEL_COMPILER)
+ result["compiler"] = {{"family", "icc"}, { "version", __INTEL_COMPILER }};
+#elif defined(__clang__)
+ result["compiler"] = {{"family", "clang"}, { "version", __clang_version__ }};
+#elif defined(__GNUC__) || defined(__GNUG__)
+ result["compiler"] = {{"family", "gcc"},
+ { "version",
+ detail::concat(std::to_string(__GNUC__),
+ '.',
+ std::to_string(__GNUC_MINOR__),
+ '.',
+ std::to_string(__GNUC_PATCHLEVEL__)) }};
+#elif defined(__HP_cc) || defined(__HP_aCC)
+ result["compiler"] = "hp"
+#elif defined(__IBMCPP__)
+ result["compiler"] = {{"family", "ilecpp"}, { "version", __IBMCPP__ }};
+#elif defined(_MSC_VER)
+ result["compiler"] = {{"family", "msvc"}, { "version", _MSC_VER }};
+#elif defined(__PGI)
+ result["compiler"] = {{"family", "pgcpp"}, { "version", __PGI }};
+#elif defined(__SUNPRO_CC)
+ result["compiler"] = {{"family", "sunpro"}, { "version", __SUNPRO_CC }};
+#else
+ result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
+#endif
+
+#if defined(_MSVC_LANG)
+ result["compiler"]["c++"] = std::to_string(_MSVC_LANG);
+#elif defined(__cplusplus)
+ result["compiler"]["c++"] = std::to_string(__cplusplus);
+#else
+ result["compiler"]["c++"] = "unknown";
+#endif
+ return result;
+ }
+
+ ///////////////////////////
+ // JSON value data types //
+ ///////////////////////////
+
+ /// @name JSON value data types
+ /// The data types to store a JSON value. These types are derived from
+ /// the template arguments passed to class @ref basic_json.
+ /// @{
+
+ /// @brief default object key comparator type
+ /// The actual object key comparator type (@ref object_comparator_t) may be
+ /// different.
+ /// @sa https://json.nlohmann.me/api/basic_json/default_object_comparator_t/
+#if defined(JSON_HAS_CPP_14)
+ // use of transparent comparator avoids unnecessary repeated construction of temporaries
+ // in functions involving lookup by key with types other than object_t::key_type (aka. StringType)
+ using default_object_comparator_t = std::less<>;
+#else
+ using default_object_comparator_t = std::less<StringType>;
+#endif
+
+ /// @brief a type for an object
+ /// @sa https://json.nlohmann.me/api/basic_json/object_t/
+ using object_t = ObjectType<StringType,
+ basic_json,
+ default_object_comparator_t,
+ AllocatorType<std::pair<const StringType, basic_json>>>;
+
+ /// @brief a type for an array
+ /// @sa https://json.nlohmann.me/api/basic_json/array_t/
+ using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
+
+ /// @brief a type for a string
+ /// @sa https://json.nlohmann.me/api/basic_json/string_t/
+ using string_t = StringType;
+
+ /// @brief a type for a boolean
+ /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/
+ using boolean_t = BooleanType;
+
+ /// @brief a type for a number (integer)
+ /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/
+ using number_integer_t = NumberIntegerType;
+
+ /// @brief a type for a number (unsigned)
+ /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/
+ using number_unsigned_t = NumberUnsignedType;
+
+ /// @brief a type for a number (floating-point)
+ /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/
+ using number_float_t = NumberFloatType;
+
+ /// @brief a type for a packed binary type
+ /// @sa https://json.nlohmann.me/api/basic_json/binary_t/
+ using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
+
+ /// @brief object key comparator type
+ /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/
+ using object_comparator_t = detail::actual_object_comparator_t<basic_json>;
+
+ /// @}
+
+ private:
+ /// helper for exception-safe object creation
+ template <typename T, typename... Args>
+ JSON_HEDLEY_RETURNS_NON_NULL static T*
+ create(Args&&... args) {
+ AllocatorType<T> alloc;
+ using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
+
+ auto deleter = [&](T* obj) { AllocatorTraits::deallocate(alloc, obj, 1); };
+ std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter);
+ AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...);
+ JSON_ASSERT(obj != nullptr);
+ return obj.release();
+ }
+
+ ////////////////////////
+ // JSON value storage //
+ ////////////////////////
+
+ JSON_PRIVATE_UNLESS_TESTED :
+ /*!
+ @brief a JSON value
+
+ The actual storage for a JSON value of the @ref basic_json class. This
+ union combines the different storage types for the JSON value types
+ defined in @ref value_t.
+
+ JSON type | value_t type | used type
+ --------- | --------------- | ------------------------
+ object | object | pointer to @ref object_t
+ array | array | pointer to @ref array_t
+ string | string | pointer to @ref string_t
+ boolean | boolean | @ref boolean_t
+ number | number_integer | @ref number_integer_t
+ number | number_unsigned | @ref number_unsigned_t
+ number | number_float | @ref number_float_t
+ binary | binary | pointer to @ref binary_t
+ null | null | *no value is stored*
+
+ @note Variable-length types (objects, arrays, and strings) are stored as
+ pointers. The size of the union should not exceed 64 bits if the default
+ value types are used.
+
+ @since version 1.0.0
+ */
+ union json_value {
+ /// object (stored with pointer to save storage)
+ object_t* object;
+ /// array (stored with pointer to save storage)
+ array_t* array;
+ /// string (stored with pointer to save storage)
+ string_t* string;
+ /// binary (stored with pointer to save storage)
+ binary_t* binary;
+ /// boolean
+ boolean_t boolean;
+ /// number (integer)
+ number_integer_t number_integer;
+ /// number (unsigned integer)
+ number_unsigned_t number_unsigned;
+ /// number (floating-point)
+ number_float_t number_float;
+
+ /// default constructor (for null values)
+ json_value() = default;
+ /// constructor for booleans
+ json_value(boolean_t v) noexcept : boolean(v) {}
+ /// constructor for numbers (integer)
+ json_value(number_integer_t v) noexcept : number_integer(v) {}
+ /// constructor for numbers (unsigned)
+ json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
+ /// constructor for numbers (floating-point)
+ json_value(number_float_t v) noexcept : number_float(v) {}
+ /// constructor for empty values of a given type
+ json_value(value_t t) {
+ switch (t) {
+ case value_t::object: {
+ object = create<object_t>();
+ break;
+ }
+
+ case value_t::array: {
+ array = create<array_t>();
+ break;
+ }
+
+ case value_t::string: {
+ string = create<string_t>("");
+ break;
+ }
+
+ case value_t::binary: {
+ binary = create<binary_t>();
+ break;
+ }
+
+ case value_t::boolean: {
+ boolean = static_cast<boolean_t>(false);
+ break;
+ }
+
+ case value_t::number_integer: {
+ number_integer = static_cast<number_integer_t>(0);
+ break;
+ }
+
+ case value_t::number_unsigned: {
+ number_unsigned = static_cast<number_unsigned_t>(0);
+ break;
+ }
+
+ case value_t::number_float: {
+ number_float = static_cast<number_float_t>(0.0);
+ break;
+ }
+
+ case value_t::null: {
+ object = nullptr; // silence warning, see #821
+ break;
+ }
+
+ case value_t::discarded:
+ default: {
+ object = nullptr; // silence warning, see #821
+ if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) {
+ JSON_THROW(other_error::create(
+ 500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.11.3", nullptr)); // LCOV_EXCL_LINE
+ }
+ break;
+ }
+ }
+ }
+
+ /// constructor for strings
+ json_value(const string_t& value) : string(create<string_t>(value)) {}
+
+ /// constructor for rvalue strings
+ json_value(string_t&& value) : string(create<string_t>(std::move(value))) {}
+
+ /// constructor for objects
+ json_value(const object_t& value) : object(create<object_t>(value)) {}
+
+ /// constructor for rvalue objects
+ json_value(object_t&& value) : object(create<object_t>(std::move(value))) {}
+
+ /// constructor for arrays
+ json_value(const array_t& value) : array(create<array_t>(value)) {}
+
+ /// constructor for rvalue arrays
+ json_value(array_t&& value) : array(create<array_t>(std::move(value))) {}
+
+ /// constructor for binary arrays
+ json_value(const typename binary_t::container_type& value) : binary(create<binary_t>(value)) {}
+
+ /// constructor for rvalue binary arrays
+ json_value(typename binary_t::container_type&& value) : binary(create<binary_t>(std::move(value))) {}
+
+ /// constructor for binary arrays (internal type)
+ json_value(const binary_t& value) : binary(create<binary_t>(value)) {}
+
+ /// constructor for rvalue binary arrays (internal type)
+ json_value(binary_t&& value) : binary(create<binary_t>(std::move(value))) {}
+
+ void
+ destroy(value_t t) {
+ if ((t == value_t::object && object == nullptr) || (t == value_t::array && array == nullptr) ||
+ (t == value_t::string && string == nullptr) || (t == value_t::binary && binary == nullptr)) {
+ // not initialized (e.g. due to exception in the ctor)
+ return;
+ }
+ if (t == value_t::array || t == value_t::object) {
+ // flatten the current json_value to a heap-allocated stack
+ std::vector<basic_json> stack;
+
+ // move the top-level items to stack
+ if (t == value_t::array) {
+ stack.reserve(array->size());
+ std::move(array->begin(), array->end(), std::back_inserter(stack));
+ } else {
+ stack.reserve(object->size());
+ for (auto&& it : *object) {
+ stack.push_back(std::move(it.second));
+ }
+ }
+
+ while (!stack.empty()) {
+ // move the last item to local variable to be processed
+ basic_json current_item(std::move(stack.back()));
+ stack.pop_back();
+
+ // if current_item is array/object, move
+ // its children to the stack to be processed later
+ if (current_item.is_array()) {
+ std::move(current_item.m_data.m_value.array->begin(),
+ current_item.m_data.m_value.array->end(),
+ std::back_inserter(stack));
+
+ current_item.m_data.m_value.array->clear();
+ } else if (current_item.is_object()) {
+ for (auto&& it : *current_item.m_data.m_value.object) {
+ stack.push_back(std::move(it.second));
+ }
+
+ current_item.m_data.m_value.object->clear();
+ }
+
+ // it's now safe that current_item get destructed
+ // since it doesn't have any children
+ }
+ }
+
+ switch (t) {
+ case value_t::object: {
+ AllocatorType<object_t> alloc;
+ std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
+ std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
+ break;
+ }
+
+ case value_t::array: {
+ AllocatorType<array_t> alloc;
+ std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
+ std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
+ break;
+ }
+
+ case value_t::string: {
+ AllocatorType<string_t> alloc;
+ std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
+ std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
+ break;
+ }
+
+ case value_t::binary: {
+ AllocatorType<binary_t> alloc;
+ std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
+ std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
+ break;
+ }
+
+ case value_t::null:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::discarded:
+ default: {
+ break;
+ }
+ }
+ }
+ };
+
+ private:
+ /*!
+ @brief checks the class invariants
+
+ This function asserts the class invariants. It needs to be called at the
+ end of every constructor to make sure that created objects respect the
+ invariant. Furthermore, it has to be called each time the type of a JSON
+ value is changed, because the invariant expresses a relationship between
+ @a m_type and @a m_value.
+
+ Furthermore, the parent relation is checked for arrays and objects: If
+ @a check_parents true and the value is an array or object, then the
+ container's elements must have the current value as parent.
+
+ @param[in] check_parents whether the parent relation should be checked.
+ The value is true by default and should only be set to false
+ during destruction of objects when the invariant does not
+ need to hold.
+ */
+ void
+ assert_invariant(bool check_parents = true) const noexcept {
+ JSON_ASSERT(m_data.m_type != value_t::object || m_data.m_value.object != nullptr);
+ JSON_ASSERT(m_data.m_type != value_t::array || m_data.m_value.array != nullptr);
+ JSON_ASSERT(m_data.m_type != value_t::string || m_data.m_value.string != nullptr);
+ JSON_ASSERT(m_data.m_type != value_t::binary || m_data.m_value.binary != nullptr);
+
+#if JSON_DIAGNOSTICS
+ JSON_TRY {
+ // cppcheck-suppress assertWithSideEffect
+ JSON_ASSERT(!check_parents || !is_structured() ||
+ std::all_of(begin(), end(), [this](const basic_json& j) { return j.m_parent == this; }));
+ }
+ JSON_CATCH(...) {} // LCOV_EXCL_LINE
+#endif
+ static_cast<void>(check_parents);
+ }
+
+ void
+ set_parents() {
+#if JSON_DIAGNOSTICS
+ switch (m_data.m_type) {
+ case value_t::array: {
+ for (auto& element : *m_data.m_value.array) {
+ element.m_parent = this;
+ }
+ break;
+ }
+
+ case value_t::object: {
+ for (auto& element : *m_data.m_value.object) {
+ element.second.m_parent = this;
+ }
+ break;
+ }
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default:
+ break;
+ }
+#endif
+ }
+
+ iterator
+ set_parents(iterator it, typename iterator::difference_type count_set_parents) {
+#if JSON_DIAGNOSTICS
+ for (typename iterator::difference_type i = 0; i < count_set_parents; ++i) {
+ (it + i)->m_parent = this;
+ }
+#else
+ static_cast<void>(count_set_parents);
+#endif
+ return it;
+ }
+
+ reference
+ set_parent(reference j, std::size_t old_capacity = static_cast<std::size_t>(-1)) {
+#if JSON_DIAGNOSTICS
+ if (old_capacity != static_cast<std::size_t>(-1)) {
+ // see https://github.com/nlohmann/json/issues/2838
+ JSON_ASSERT(type() == value_t::array);
+ if (JSON_HEDLEY_UNLIKELY(m_data.m_value.array->capacity() != old_capacity)) {
+ // capacity has changed: update all parents
+ set_parents();
+ return j;
+ }
+ }
+
+ // ordered_json uses a vector internally, so pointers could have
+ // been invalidated; see https://github.com/nlohmann/json/issues/2962
+#ifdef JSON_HEDLEY_MSVC_VERSION
+#pragma warning(push)
+#pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
+#endif
+ if (detail::is_ordered_map<object_t>::value) {
+ set_parents();
+ return j;
+ }
+#ifdef JSON_HEDLEY_MSVC_VERSION
+#pragma warning(pop)
+#endif
+
+ j.m_parent = this;
+#else
+ static_cast<void>(j);
+ static_cast<void>(old_capacity);
+#endif
+ return j;
+ }
+
+ public:
+ //////////////////////////
+ // JSON parser callback //
+ //////////////////////////
+
+ /// @brief parser event types
+ /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/
+ using parse_event_t = detail::parse_event_t;
+
+ /// @brief per-element parser callback type
+ /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/
+ using parser_callback_t = detail::parser_callback_t<basic_json>;
+
+ //////////////////
+ // constructors //
+ //////////////////
+
+ /// @name constructors and destructors
+ /// Constructors of class @ref basic_json, copy/move constructor, copy
+ /// assignment, static functions creating objects, and the destructor.
+ /// @{
+
+ /// @brief create an empty value with a given type
+ /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+ basic_json(const value_t v) : m_data(v) { assert_invariant(); }
+
+ /// @brief create a null object
+ /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+ basic_json(std::nullptr_t = nullptr) noexcept // NOLINT(bugprone-exception-escape)
+ : basic_json(value_t::null) {
+ assert_invariant();
+ }
+
+ /// @brief create a JSON value from compatible types
+ /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+ template <
+ typename CompatibleType,
+ typename U = detail::uncvref_t<CompatibleType>,
+ detail::enable_if_t<!detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value,
+ int> = 0>
+ basic_json(CompatibleType&& val) noexcept(
+ noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape)
+ JSONSerializer<U>::to_json(std::declval<basic_json_t&>(), std::forward<CompatibleType>(val)))) {
+ JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
+ set_parents();
+ assert_invariant();
+ }
+
+ /// @brief create a JSON value from an existing one
+ /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+ template <typename BasicJsonType,
+ detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value &&
+ !std::is_same<basic_json, BasicJsonType>::value,
+ int> = 0>
+ basic_json(const BasicJsonType& val) {
+ using other_boolean_t = typename BasicJsonType::boolean_t;
+ using other_number_float_t = typename BasicJsonType::number_float_t;
+ using other_number_integer_t = typename BasicJsonType::number_integer_t;
+ using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+ using other_string_t = typename BasicJsonType::string_t;
+ using other_object_t = typename BasicJsonType::object_t;
+ using other_array_t = typename BasicJsonType::array_t;
+ using other_binary_t = typename BasicJsonType::binary_t;
+
+ switch (val.type()) {
+ case value_t::boolean:
+ JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
+ break;
+ case value_t::number_float:
+ JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
+ break;
+ case value_t::number_integer:
+ JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
+ break;
+ case value_t::number_unsigned:
+ JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
+ break;
+ case value_t::string:
+ JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
+ break;
+ case value_t::object:
+ JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
+ break;
+ case value_t::array:
+ JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
+ break;
+ case value_t::binary:
+ JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
+ break;
+ case value_t::null:
+ *this = nullptr;
+ break;
+ case value_t::discarded:
+ m_data.m_type = value_t::discarded;
+ break;
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ }
+ JSON_ASSERT(m_data.m_type == val.type());
+ set_parents();
+ assert_invariant();
+ }
+
+ /// @brief create a container (array or object) from an initializer list
+ /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+ basic_json(initializer_list_t init, bool type_deduction = true, value_t manual_type = value_t::array) {
+ // check if each element is an array with two elements whose first
+ // element is a string
+ bool is_an_object = std::all_of(init.begin(), init.end(), [](const detail::json_ref<basic_json>& element_ref) {
+ // The cast is to ensure op[size_type] is called, bearing in mind size_type may not be int;
+ // (many string types can be constructed from 0 via its null-pointer guise, so we get a
+ // broken call to op[key_type], the wrong semantics and a 4804 warning on Windows)
+ return element_ref->is_array() && element_ref->size() == 2 &&
+ (*element_ref)[static_cast<size_type>(0)].is_string();
+ });
+
+ // adjust type if type deduction is not wanted
+ if (!type_deduction) {
+ // if array is wanted, do not create an object though possible
+ if (manual_type == value_t::array) {
+ is_an_object = false;
+ }
+
+ // if object is wanted but impossible, throw an exception
+ if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) {
+ JSON_THROW(type_error::create(301, "cannot create object from initializer list", nullptr));
+ }
+ }
+
+ if (is_an_object) {
+ // the initializer list is a list of pairs -> create object
+ m_data.m_type = value_t::object;
+ m_data.m_value = value_t::object;
+
+ for (auto& element_ref : init) {
+ auto element = element_ref.moved_or_copied();
+ m_data.m_value.object->emplace(std::move(*((*element.m_data.m_value.array)[0].m_data.m_value.string)),
+ std::move((*element.m_data.m_value.array)[1]));
+ }
+ } else {
+ // the initializer list describes an array -> create array
+ m_data.m_type = value_t::array;
+ m_data.m_value.array = create<array_t>(init.begin(), init.end());
+ }
+
+ set_parents();
+ assert_invariant();
+ }
+
+ /// @brief explicitly create a binary array (without subtype)
+ /// @sa https://json.nlohmann.me/api/basic_json/binary/
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ static basic_json
+ binary(const typename binary_t::container_type& init) {
+ auto res = basic_json();
+ res.m_data.m_type = value_t::binary;
+ res.m_data.m_value = init;
+ return res;
+ }
+
+ /// @brief explicitly create a binary array (with subtype)
+ /// @sa https://json.nlohmann.me/api/basic_json/binary/
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ static basic_json
+ binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype) {
+ auto res = basic_json();
+ res.m_data.m_type = value_t::binary;
+ res.m_data.m_value = binary_t(init, subtype);
+ return res;
+ }
+
+ /// @brief explicitly create a binary array
+ /// @sa https://json.nlohmann.me/api/basic_json/binary/
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ static basic_json
+ binary(typename binary_t::container_type&& init) {
+ auto res = basic_json();
+ res.m_data.m_type = value_t::binary;
+ res.m_data.m_value = std::move(init);
+ return res;
+ }
+
+ /// @brief explicitly create a binary array (with subtype)
+ /// @sa https://json.nlohmann.me/api/basic_json/binary/
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ static basic_json
+ binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype) {
+ auto res = basic_json();
+ res.m_data.m_type = value_t::binary;
+ res.m_data.m_value = binary_t(std::move(init), subtype);
+ return res;
+ }
+
+ /// @brief explicitly create an array from an initializer list
+ /// @sa https://json.nlohmann.me/api/basic_json/array/
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ static basic_json
+ array(initializer_list_t init = {}) {
+ return basic_json(init, false, value_t::array);
+ }
+
+ /// @brief explicitly create an object from an initializer list
+ /// @sa https://json.nlohmann.me/api/basic_json/object/
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ static basic_json
+ object(initializer_list_t init = {}) {
+ return basic_json(init, false, value_t::object);
+ }
+
+ /// @brief construct an array with count copies of given value
+ /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+ basic_json(size_type cnt, const basic_json& val) : m_data{cnt, val} {
+ set_parents();
+ assert_invariant();
+ }
+
+ /// @brief construct a JSON container given an iterator range
+ /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+ template <class InputIT,
+ typename std::enable_if<std::is_same<InputIT, typename basic_json_t::iterator>::value ||
+ std::is_same<InputIT, typename basic_json_t::const_iterator>::value,
+ int>::type = 0>
+ basic_json(InputIT first, InputIT last) {
+ JSON_ASSERT(first.m_object != nullptr);
+ JSON_ASSERT(last.m_object != nullptr);
+
+ // make sure iterator fits the current value
+ if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) {
+ JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", nullptr));
+ }
+
+ // copy type from first iterator
+ m_data.m_type = first.m_object->m_data.m_type;
+
+ // check if iterator range is complete for primitive values
+ switch (m_data.m_type) {
+ case value_t::boolean:
+ case value_t::number_float:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::string: {
+ if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() ||
+ !last.m_it.primitive_iterator.is_end())) {
+ JSON_THROW(invalid_iterator::create(204, "iterators out of range", first.m_object));
+ }
+ break;
+ }
+
+ case value_t::null:
+ case value_t::object:
+ case value_t::array:
+ case value_t::binary:
+ case value_t::discarded:
+ default:
+ break;
+ }
+
+ switch (m_data.m_type) {
+ case value_t::number_integer: {
+ m_data.m_value.number_integer = first.m_object->m_data.m_value.number_integer;
+ break;
+ }
+
+ case value_t::number_unsigned: {
+ m_data.m_value.number_unsigned = first.m_object->m_data.m_value.number_unsigned;
+ break;
+ }
+
+ case value_t::number_float: {
+ m_data.m_value.number_float = first.m_object->m_data.m_value.number_float;
+ break;
+ }
+
+ case value_t::boolean: {
+ m_data.m_value.boolean = first.m_object->m_data.m_value.boolean;
+ break;
+ }
+
+ case value_t::string: {
+ m_data.m_value = *first.m_object->m_data.m_value.string;
+ break;
+ }
+
+ case value_t::object: {
+ m_data.m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator);
+ break;
+ }
+
+ case value_t::array: {
+ m_data.m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator);
+ break;
+ }
+
+ case value_t::binary: {
+ m_data.m_value = *first.m_object->m_data.m_value.binary;
+ break;
+ }
+
+ case value_t::null:
+ case value_t::discarded:
+ default:
+ JSON_THROW(invalid_iterator::create(
+ 206,
+ detail::concat("cannot construct with iterators from ", first.m_object->type_name()),
+ first.m_object));
+ }
+
+ set_parents();
+ assert_invariant();
+ }
+
+ ///////////////////////////////////////
+ // other constructors and destructor //
+ ///////////////////////////////////////
+
+ template <typename JsonRef,
+ detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
+ std::is_same<typename JsonRef::value_type, basic_json>>::value,
+ int> = 0>
+ basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
+
+ /// @brief copy constructor
+ /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+ basic_json(const basic_json& other) : json_base_class_t(other) {
+ m_data.m_type = other.m_data.m_type;
+ // check of passed value is valid
+ other.assert_invariant();
+
+ switch (m_data.m_type) {
+ case value_t::object: {
+ m_data.m_value = *other.m_data.m_value.object;
+ break;
+ }
+
+ case value_t::array: {
+ m_data.m_value = *other.m_data.m_value.array;
+ break;
+ }
+
+ case value_t::string: {
+ m_data.m_value = *other.m_data.m_value.string;
+ break;
+ }
+
+ case value_t::boolean: {
+ m_data.m_value = other.m_data.m_value.boolean;
+ break;
+ }
+
+ case value_t::number_integer: {
+ m_data.m_value = other.m_data.m_value.number_integer;
+ break;
+ }
+
+ case value_t::number_unsigned: {
+ m_data.m_value = other.m_data.m_value.number_unsigned;
+ break;
+ }
+
+ case value_t::number_float: {
+ m_data.m_value = other.m_data.m_value.number_float;
+ break;
+ }
+
+ case value_t::binary: {
+ m_data.m_value = *other.m_data.m_value.binary;
+ break;
+ }
+
+ case value_t::null:
+ case value_t::discarded:
+ default:
+ break;
+ }
+
+ set_parents();
+ assert_invariant();
+ }
+
+ /// @brief move constructor
+ /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+ basic_json(basic_json&& other) noexcept
+ : json_base_class_t(std::forward<json_base_class_t>(other)), m_data(std::move(other.m_data)) {
+ // check that passed value is valid
+ other.assert_invariant(false);
+
+ // invalidate payload
+ other.m_data.m_type = value_t::null;
+ other.m_data.m_value = {};
+
+ set_parents();
+ assert_invariant();
+ }
+
+ /// @brief copy assignment
+ /// @sa https://json.nlohmann.me/api/basic_json/operator=/
+ basic_json&
+ operator=(basic_json other) noexcept(std::is_nothrow_move_constructible<value_t>::value &&
+ std::is_nothrow_move_assignable<value_t>::value &&
+ std::is_nothrow_move_constructible<json_value>::value &&
+ std::is_nothrow_move_assignable<json_value>::value &&
+ std::is_nothrow_move_assignable<json_base_class_t>::value) {
+ // check that passed value is valid
+ other.assert_invariant();
+
+ using std::swap;
+ swap(m_data.m_type, other.m_data.m_type);
+ swap(m_data.m_value, other.m_data.m_value);
+ json_base_class_t::operator=(std::move(other));
+
+ set_parents();
+ assert_invariant();
+ return *this;
+ }
+
+ /// @brief destructor
+ /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/
+ ~basic_json() noexcept { assert_invariant(false); }
+
+ /// @}
+
+ public:
+ ///////////////////////
+ // object inspection //
+ ///////////////////////
+
+ /// @name object inspection
+ /// Functions to inspect the type of a JSON value.
+ /// @{
+
+ /// @brief serialization
+ /// @sa https://json.nlohmann.me/api/basic_json/dump/
+ string_t
+ dump(const int indent = -1,
+ const char indent_char = ' ',
+ const bool ensure_ascii = false,
+ const error_handler_t error_handler = error_handler_t::strict) const {
+ string_t result;
+ serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
+
+ if (indent >= 0) {
+ s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
+ } else {
+ s.dump(*this, false, ensure_ascii, 0);
+ }
+
+ return result;
+ }
+
+ /// @brief return the type of the JSON value (explicit)
+ /// @sa https://json.nlohmann.me/api/basic_json/type/
+ constexpr value_t
+ type() const noexcept {
+ return m_data.m_type;
+ }
+
+ /// @brief return whether type is primitive
+ /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/
+ constexpr bool
+ is_primitive() const noexcept {
+ return is_null() || is_string() || is_boolean() || is_number() || is_binary();
+ }
+
+ /// @brief return whether type is structured
+ /// @sa https://json.nlohmann.me/api/basic_json/is_structured/
+ constexpr bool
+ is_structured() const noexcept {
+ return is_array() || is_object();
+ }
+
+ /// @brief return whether value is null
+ /// @sa https://json.nlohmann.me/api/basic_json/is_null/
+ constexpr bool
+ is_null() const noexcept {
+ return m_data.m_type == value_t::null;
+ }
+
+ /// @brief return whether value is a boolean
+ /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/
+ constexpr bool
+ is_boolean() const noexcept {
+ return m_data.m_type == value_t::boolean;
+ }
+
+ /// @brief return whether value is a number
+ /// @sa https://json.nlohmann.me/api/basic_json/is_number/
+ constexpr bool
+ is_number() const noexcept {
+ return is_number_integer() || is_number_float();
+ }
+
+ /// @brief return whether value is an integer number
+ /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/
+ constexpr bool
+ is_number_integer() const noexcept {
+ return m_data.m_type == value_t::number_integer || m_data.m_type == value_t::number_unsigned;
+ }
+
+ /// @brief return whether value is an unsigned integer number
+ /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/
+ constexpr bool
+ is_number_unsigned() const noexcept {
+ return m_data.m_type == value_t::number_unsigned;
+ }
+
+ /// @brief return whether value is a floating-point number
+ /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/
+ constexpr bool
+ is_number_float() const noexcept {
+ return m_data.m_type == value_t::number_float;
+ }
+
+ /// @brief return whether value is an object
+ /// @sa https://json.nlohmann.me/api/basic_json/is_object/
+ constexpr bool
+ is_object() const noexcept {
+ return m_data.m_type == value_t::object;
+ }
+
+ /// @brief return whether value is an array
+ /// @sa https://json.nlohmann.me/api/basic_json/is_array/
+ constexpr bool
+ is_array() const noexcept {
+ return m_data.m_type == value_t::array;
+ }
+
+ /// @brief return whether value is a string
+ /// @sa https://json.nlohmann.me/api/basic_json/is_string/
+ constexpr bool
+ is_string() const noexcept {
+ return m_data.m_type == value_t::string;
+ }
+
+ /// @brief return whether value is a binary array
+ /// @sa https://json.nlohmann.me/api/basic_json/is_binary/
+ constexpr bool
+ is_binary() const noexcept {
+ return m_data.m_type == value_t::binary;
+ }
+
+ /// @brief return whether value is discarded
+ /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/
+ constexpr bool
+ is_discarded() const noexcept {
+ return m_data.m_type == value_t::discarded;
+ }
+
+ /// @brief return the type of the JSON value (implicit)
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/
+ constexpr
+ operator value_t() const noexcept {
+ return m_data.m_type;
+ }
+
+ /// @}
+
+ private:
+ //////////////////
+ // value access //
+ //////////////////
+
+ /// get a boolean (explicit)
+ boolean_t
+ get_impl(boolean_t* /*unused*/) const {
+ if (JSON_HEDLEY_LIKELY(is_boolean())) {
+ return m_data.m_value.boolean;
+ }
+
+ JSON_THROW(type_error::create(302, detail::concat("type must be boolean, but is ", type_name()), this));
+ }
+
+ /// get a pointer to the value (object)
+ object_t*
+ get_impl_ptr(object_t* /*unused*/) noexcept {
+ return is_object() ? m_data.m_value.object : nullptr;
+ }
+
+ /// get a pointer to the value (object)
+ constexpr const object_t*
+ get_impl_ptr(const object_t* /*unused*/) const noexcept {
+ return is_object() ? m_data.m_value.object : nullptr;
+ }
+
+ /// get a pointer to the value (array)
+ array_t*
+ get_impl_ptr(array_t* /*unused*/) noexcept {
+ return is_array() ? m_data.m_value.array : nullptr;
+ }
+
+ /// get a pointer to the value (array)
+ constexpr const array_t*
+ get_impl_ptr(const array_t* /*unused*/) const noexcept {
+ return is_array() ? m_data.m_value.array : nullptr;
+ }
+
+ /// get a pointer to the value (string)
+ string_t*
+ get_impl_ptr(string_t* /*unused*/) noexcept {
+ return is_string() ? m_data.m_value.string : nullptr;
+ }
+
+ /// get a pointer to the value (string)
+ constexpr const string_t*
+ get_impl_ptr(const string_t* /*unused*/) const noexcept {
+ return is_string() ? m_data.m_value.string : nullptr;
+ }
+
+ /// get a pointer to the value (boolean)
+ boolean_t*
+ get_impl_ptr(boolean_t* /*unused*/) noexcept {
+ return is_boolean() ? &m_data.m_value.boolean : nullptr;
+ }
+
+ /// get a pointer to the value (boolean)
+ constexpr const boolean_t*
+ get_impl_ptr(const boolean_t* /*unused*/) const noexcept {
+ return is_boolean() ? &m_data.m_value.boolean : nullptr;
+ }
+
+ /// get a pointer to the value (integer number)
+ number_integer_t*
+ get_impl_ptr(number_integer_t* /*unused*/) noexcept {
+ return is_number_integer() ? &m_data.m_value.number_integer : nullptr;
+ }
+
+ /// get a pointer to the value (integer number)
+ constexpr const number_integer_t*
+ get_impl_ptr(const number_integer_t* /*unused*/) const noexcept {
+ return is_number_integer() ? &m_data.m_value.number_integer : nullptr;
+ }
+
+ /// get a pointer to the value (unsigned number)
+ number_unsigned_t*
+ get_impl_ptr(number_unsigned_t* /*unused*/) noexcept {
+ return is_number_unsigned() ? &m_data.m_value.number_unsigned : nullptr;
+ }
+
+ /// get a pointer to the value (unsigned number)
+ constexpr const number_unsigned_t*
+ get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept {
+ return is_number_unsigned() ? &m_data.m_value.number_unsigned : nullptr;
+ }
+
+ /// get a pointer to the value (floating-point number)
+ number_float_t*
+ get_impl_ptr(number_float_t* /*unused*/) noexcept {
+ return is_number_float() ? &m_data.m_value.number_float : nullptr;
+ }
+
+ /// get a pointer to the value (floating-point number)
+ constexpr const number_float_t*
+ get_impl_ptr(const number_float_t* /*unused*/) const noexcept {
+ return is_number_float() ? &m_data.m_value.number_float : nullptr;
+ }
+
+ /// get a pointer to the value (binary)
+ binary_t*
+ get_impl_ptr(binary_t* /*unused*/) noexcept {
+ return is_binary() ? m_data.m_value.binary : nullptr;
+ }
+
+ /// get a pointer to the value (binary)
+ constexpr const binary_t*
+ get_impl_ptr(const binary_t* /*unused*/) const noexcept {
+ return is_binary() ? m_data.m_value.binary : nullptr;
+ }
+
+ /*!
+ @brief helper function to implement get_ref()
+
+ This function helps to implement get_ref() without code duplication for
+ const and non-const overloads
+
+ @tparam ThisType will be deduced as `basic_json` or `const basic_json`
+
+ @throw type_error.303 if ReferenceType does not match underlying value
+ type of the current JSON
+ */
+ template <typename ReferenceType, typename ThisType>
+ static ReferenceType
+ get_ref_impl(ThisType& obj) {
+ // delegate the call to get_ptr<>()
+ auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
+
+ if (JSON_HEDLEY_LIKELY(ptr != nullptr)) {
+ return *ptr;
+ }
+
+ JSON_THROW(type_error::create(
+ 303, detail::concat("incompatible ReferenceType for get_ref, actual type is ", obj.type_name()), &obj));
+ }
+
+ public:
+ /// @name value access
+ /// Direct access to the stored value of a JSON value.
+ /// @{
+
+ /// @brief get a pointer value (implicit)
+ /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
+ template <typename PointerType, typename std::enable_if<std::is_pointer<PointerType>::value, int>::type = 0>
+ auto
+ get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>())) {
+ // delegate the call to get_impl_ptr<>()
+ return get_impl_ptr(static_cast<PointerType>(nullptr));
+ }
+
+ /// @brief get a pointer value (implicit)
+ /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
+ template <typename PointerType,
+ typename std::enable_if<std::is_pointer<PointerType>::value &&
+ std::is_const<typename std::remove_pointer<PointerType>::type>::value,
+ int>::type = 0>
+ constexpr auto
+ get_ptr() const noexcept
+ -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>())) {
+ // delegate the call to get_impl_ptr<>() const
+ return get_impl_ptr(static_cast<PointerType>(nullptr));
+ }
+
+ private:
+ /*!
+ @brief get a value (explicit)
+
+ Explicit type conversion between the JSON value and a compatible value
+ which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
+ and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
+ The value is converted by calling the @ref json_serializer<ValueType>
+ `from_json()` method.
+
+ The function is equivalent to executing
+ @code {.cpp}
+ ValueType ret;
+ JSONSerializer<ValueType>::from_json(*this, ret);
+ return ret;
+ @endcode
+
+ This overloads is chosen if:
+ - @a ValueType is not @ref basic_json,
+ - @ref json_serializer<ValueType> has a `from_json()` method of the form
+ `void from_json(const basic_json&, ValueType&)`, and
+ - @ref json_serializer<ValueType> does not have a `from_json()` method of
+ the form `ValueType from_json(const basic_json&)`
+
+ @tparam ValueType the returned value type
+
+ @return copy of the JSON value, converted to @a ValueType
+
+ @throw what @ref json_serializer<ValueType> `from_json()` method throws
+
+ @liveexample{The example below shows several conversions from JSON values
+ to other types. There a few things to note: (1) Floating-point numbers can
+ be converted to integers\, (2) A JSON array can be converted to a standard
+ `std::vector<short>`\, (3) A JSON object can be converted to C++
+ associative containers such as `std::unordered_map<std::string\,
+ json>`.,get__ValueType_const}
+
+ @since version 2.1.0
+ */
+ template <typename ValueType,
+ detail::enable_if_t<detail::is_default_constructible<ValueType>::value &&
+ detail::has_from_json<basic_json_t, ValueType>::value,
+ int> = 0>
+ ValueType
+ get_impl(detail::priority_tag<0> /*unused*/) const
+ noexcept(noexcept(JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(),
+ std::declval<ValueType&>()))) {
+ auto ret = ValueType();
+ JSONSerializer<ValueType>::from_json(*this, ret);
+ return ret;
+ }
+
+ /*!
+ @brief get a value (explicit); special case
+
+ Explicit type conversion between the JSON value and a compatible value
+ which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
+ and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
+ The value is converted by calling the @ref json_serializer<ValueType>
+ `from_json()` method.
+
+ The function is equivalent to executing
+ @code {.cpp}
+ return JSONSerializer<ValueType>::from_json(*this);
+ @endcode
+
+ This overloads is chosen if:
+ - @a ValueType is not @ref basic_json and
+ - @ref json_serializer<ValueType> has a `from_json()` method of the form
+ `ValueType from_json(const basic_json&)`
+
+ @note If @ref json_serializer<ValueType> has both overloads of
+ `from_json()`, this one is chosen.
+
+ @tparam ValueType the returned value type
+
+ @return copy of the JSON value, converted to @a ValueType
+
+ @throw what @ref json_serializer<ValueType> `from_json()` method throws
+
+ @since version 2.1.0
+ */
+ template <typename ValueType,
+ detail::enable_if_t<detail::has_non_default_from_json<basic_json_t, ValueType>::value, int> = 0>
+ ValueType
+ get_impl(detail::priority_tag<1> /*unused*/) const
+ noexcept(noexcept(JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>()))) {
+ return JSONSerializer<ValueType>::from_json(*this);
+ }
+
+ /*!
+ @brief get special-case overload
+
+ This overloads converts the current @ref basic_json in a different
+ @ref basic_json type
+
+ @tparam BasicJsonType == @ref basic_json
+
+ @return a copy of *this, converted into @a BasicJsonType
+
+ @complexity Depending on the implementation of the called `from_json()`
+ method.
+
+ @since version 3.2.0
+ */
+ template <typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
+ BasicJsonType
+ get_impl(detail::priority_tag<2> /*unused*/) const {
+ return *this;
+ }
+
+ /*!
+ @brief get special-case overload
+
+ This overloads avoids a lot of template boilerplate, it can be seen as the
+ identity method
+
+ @tparam BasicJsonType == @ref basic_json
+
+ @return a copy of *this
+
+ @complexity Constant.
+
+ @since version 2.1.0
+ */
+ template <typename BasicJsonType, detail::enable_if_t<std::is_same<BasicJsonType, basic_json_t>::value, int> = 0>
+ basic_json
+ get_impl(detail::priority_tag<3> /*unused*/) const {
+ return *this;
+ }
+
+ /*!
+ @brief get a pointer value (explicit)
+ @copydoc get()
+ */
+ template <typename PointerType, detail::enable_if_t<std::is_pointer<PointerType>::value, int> = 0>
+ constexpr auto
+ get_impl(detail::priority_tag<4> /*unused*/) const noexcept
+ -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>()) {
+ // delegate the call to get_ptr
+ return get_ptr<PointerType>();
+ }
+
+ public:
+ /*!
+ @brief get a (pointer) value (explicit)
+
+ Performs explicit type conversion between the JSON value and a compatible value if required.
+
+ - If the requested type is a pointer to the internally stored JSON value that pointer is returned.
+ No copies are made.
+
+ - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible
+ from the current @ref basic_json.
+
+ - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()`
+ method.
+
+ @tparam ValueTypeCV the provided value type
+ @tparam ValueType the returned value type
+
+ @return copy of the JSON value, converted to @tparam ValueType if necessary
+
+ @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required
+
+ @since version 2.1.0
+ */
+ template <typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>>
+#if defined(JSON_HAS_CPP_14)
+ constexpr
+#endif
+ auto
+ get() const
+ noexcept(noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4>{})))
+ -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4>{})) {
+ // we cannot static_assert on ValueTypeCV being non-const, because
+ // there is support for get<const basic_json_t>(), which is why we
+ // still need the uncvref
+ static_assert(!std::is_reference<ValueTypeCV>::value,
+ "get() cannot be used with reference types, you might want to use get_ref()");
+ return get_impl<ValueType>(detail::priority_tag<4>{});
+ }
+
+ /*!
+ @brief get a pointer value (explicit)
+
+ Explicit pointer access to the internally stored JSON value. No copies are
+ made.
+
+ @warning The pointer becomes invalid if the underlying JSON object
+ changes.
+
+ @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
+ object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
+ @ref number_unsigned_t, or @ref number_float_t.
+
+ @return pointer to the internally stored JSON value if the requested
+ pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
+
+ @complexity Constant.
+
+ @liveexample{The example below shows how pointers to internal values of a
+ JSON value can be requested. Note that no type conversions are made and a
+ `nullptr` is returned if the value and the requested pointer type does not
+ match.,get__PointerType}
+
+ @sa see @ref get_ptr() for explicit pointer-member access
+
+ @since version 1.0.0
+ */
+ template <typename PointerType, typename std::enable_if<std::is_pointer<PointerType>::value, int>::type = 0>
+ auto
+ get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>()) {
+ // delegate the call to get_ptr
+ return get_ptr<PointerType>();
+ }
+
+ /// @brief get a value (explicit)
+ /// @sa https://json.nlohmann.me/api/basic_json/get_to/
+ template <typename ValueType,
+ detail::enable_if_t<!detail::is_basic_json<ValueType>::value &&
+ detail::has_from_json<basic_json_t, ValueType>::value,
+ int> = 0>
+ ValueType&
+ get_to(ValueType& v) const
+ noexcept(noexcept(JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v))) {
+ JSONSerializer<ValueType>::from_json(*this, v);
+ return v;
+ }
+
+ // specialization to allow calling get_to with a basic_json value
+ // see https://github.com/nlohmann/json/issues/2175
+ template <typename ValueType, detail::enable_if_t<detail::is_basic_json<ValueType>::value, int> = 0>
+ ValueType&
+ get_to(ValueType& v) const {
+ v = *this;
+ return v;
+ }
+
+ template <typename T,
+ std::size_t N,
+ typename Array =
+ T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+ detail::enable_if_t<detail::has_from_json<basic_json_t, Array>::value, int> = 0>
+ Array
+ get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+ noexcept(noexcept(JSONSerializer<Array>::from_json(std::declval<const basic_json_t&>(), v))) {
+ JSONSerializer<Array>::from_json(*this, v);
+ return v;
+ }
+
+ /// @brief get a reference value (implicit)
+ /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
+ template <typename ReferenceType, typename std::enable_if<std::is_reference<ReferenceType>::value, int>::type = 0>
+ ReferenceType
+ get_ref() {
+ // delegate call to get_ref_impl
+ return get_ref_impl<ReferenceType>(*this);
+ }
+
+ /// @brief get a reference value (implicit)
+ /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
+ template <typename ReferenceType,
+ typename std::enable_if<std::is_reference<ReferenceType>::value &&
+ std::is_const<typename std::remove_reference<ReferenceType>::type>::value,
+ int>::type = 0>
+ ReferenceType
+ get_ref() const {
+ // delegate call to get_ref_impl
+ return get_ref_impl<ReferenceType>(*this);
+ }
+
+ /*!
+ @brief get a value (implicit)
+
+ Implicit type conversion between the JSON value and a compatible value.
+ The call is realized by calling @ref get() const.
+
+ @tparam ValueType non-pointer type compatible to the JSON value, for
+ instance `int` for JSON integer numbers, `bool` for JSON booleans, or
+ `std::vector` types for JSON arrays. The character type of @ref string_t
+ as well as an initializer list of this type is excluded to avoid
+ ambiguities as these types implicitly convert to `std::string`.
+
+ @return copy of the JSON value, converted to type @a ValueType
+
+ @throw type_error.302 in case passed type @a ValueType is incompatible
+ to the JSON value type (e.g., the JSON value is of type boolean, but a
+ string is requested); see example below
+
+ @complexity Linear in the size of the JSON value.
+
+ @liveexample{The example below shows several conversions from JSON values
+ to other types. There a few things to note: (1) Floating-point numbers can
+ be converted to integers\, (2) A JSON array can be converted to a standard
+ `std::vector<short>`\, (3) A JSON object can be converted to C++
+ associative containers such as `std::unordered_map<std::string\,
+ json>`.,operator__ValueType}
+
+ @since version 1.0.0
+ */
+ template <typename ValueType,
+ typename std::enable_if<
+ detail::conjunction<
+ detail::negation<std::is_pointer<ValueType>>,
+ detail::negation<std::is_same<ValueType, std::nullptr_t>>,
+ detail::negation<std::is_same<ValueType, detail::json_ref<basic_json>>>,
+ detail::negation<std::is_same<ValueType, typename string_t::value_type>>,
+ detail::negation<detail::is_basic_json<ValueType>>,
+ detail::negation<std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>>,
+#if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
+ detail::negation<std::is_same<ValueType, std::string_view>>,
+#endif
+#if defined(JSON_HAS_CPP_17) && JSON_HAS_STATIC_RTTI
+ detail::negation<std::is_same<ValueType, std::any>>,
+#endif
+ detail::is_detected_lazy<detail::get_template_function, const basic_json_t&, ValueType>>::value,
+ int>::type = 0>
+ JSON_EXPLICIT
+ operator ValueType() const {
+ // delegate the call to get<>() const
+ return get<ValueType>();
+ }
+
+ /// @brief get a binary value
+ /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
+ binary_t&
+ get_binary() {
+ if (!is_binary()) {
+ JSON_THROW(type_error::create(302, detail::concat("type must be binary, but is ", type_name()), this));
+ }
+
+ return *get_ptr<binary_t*>();
+ }
+
+ /// @brief get a binary value
+ /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
+ const binary_t&
+ get_binary() const {
+ if (!is_binary()) {
+ JSON_THROW(type_error::create(302, detail::concat("type must be binary, but is ", type_name()), this));
+ }
+
+ return *get_ptr<const binary_t*>();
+ }
+
+ /// @}
+
+ ////////////////////
+ // element access //
+ ////////////////////
+
+ /// @name element access
+ /// Access to the JSON value.
+ /// @{
+
+ /// @brief access specified array element with bounds checking
+ /// @sa https://json.nlohmann.me/api/basic_json/at/
+ reference
+ at(size_type idx) {
+ // at only works for arrays
+ if (JSON_HEDLEY_LIKELY(is_array())) {
+ JSON_TRY { return set_parent(m_data.m_value.array->at(idx)); }
+ JSON_CATCH(std::out_of_range&) {
+ // create better exception explanation
+ JSON_THROW(out_of_range::create(
+ 401, detail::concat("array index ", std::to_string(idx), " is out of range"), this));
+ }
+ } else {
+ JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
+ }
+ }
+
+ /// @brief access specified array element with bounds checking
+ /// @sa https://json.nlohmann.me/api/basic_json/at/
+ const_reference
+ at(size_type idx) const {
+ // at only works for arrays
+ if (JSON_HEDLEY_LIKELY(is_array())) {
+ JSON_TRY { return m_data.m_value.array->at(idx); }
+ JSON_CATCH(std::out_of_range&) {
+ // create better exception explanation
+ JSON_THROW(out_of_range::create(
+ 401, detail::concat("array index ", std::to_string(idx), " is out of range"), this));
+ }
+ } else {
+ JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
+ }
+ }
+
+ /// @brief access specified object element with bounds checking
+ /// @sa https://json.nlohmann.me/api/basic_json/at/
+ reference
+ at(const typename object_t::key_type& key) {
+ // at only works for objects
+ if (JSON_HEDLEY_UNLIKELY(!is_object())) {
+ JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
+ }
+
+ auto it = m_data.m_value.object->find(key);
+ if (it == m_data.m_value.object->end()) {
+ JSON_THROW(out_of_range::create(403, detail::concat("key '", key, "' not found"), this));
+ }
+ return set_parent(it->second);
+ }
+
+ /// @brief access specified object element with bounds checking
+ /// @sa https://json.nlohmann.me/api/basic_json/at/
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
+ reference
+ at(KeyType&& key) {
+ // at only works for objects
+ if (JSON_HEDLEY_UNLIKELY(!is_object())) {
+ JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
+ }
+
+ auto it = m_data.m_value.object->find(std::forward<KeyType>(key));
+ if (it == m_data.m_value.object->end()) {
+ JSON_THROW(out_of_range::create(
+ 403, detail::concat("key '", string_t(std::forward<KeyType>(key)), "' not found"), this));
+ }
+ return set_parent(it->second);
+ }
+
+ /// @brief access specified object element with bounds checking
+ /// @sa https://json.nlohmann.me/api/basic_json/at/
+ const_reference
+ at(const typename object_t::key_type& key) const {
+ // at only works for objects
+ if (JSON_HEDLEY_UNLIKELY(!is_object())) {
+ JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
+ }
+
+ auto it = m_data.m_value.object->find(key);
+ if (it == m_data.m_value.object->end()) {
+ JSON_THROW(out_of_range::create(403, detail::concat("key '", key, "' not found"), this));
+ }
+ return it->second;
+ }
+
+ /// @brief access specified object element with bounds checking
+ /// @sa https://json.nlohmann.me/api/basic_json/at/
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
+ const_reference
+ at(KeyType&& key) const {
+ // at only works for objects
+ if (JSON_HEDLEY_UNLIKELY(!is_object())) {
+ JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
+ }
+
+ auto it = m_data.m_value.object->find(std::forward<KeyType>(key));
+ if (it == m_data.m_value.object->end()) {
+ JSON_THROW(out_of_range::create(
+ 403, detail::concat("key '", string_t(std::forward<KeyType>(key)), "' not found"), this));
+ }
+ return it->second;
+ }
+
+ /// @brief access specified array element
+ /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+ reference
+ operator[](size_type idx) {
+ // implicitly convert null value to an empty array
+ if (is_null()) {
+ m_data.m_type = value_t::array;
+ m_data.m_value.array = create<array_t>();
+ assert_invariant();
+ }
+
+ // operator[] only works for arrays
+ if (JSON_HEDLEY_LIKELY(is_array())) {
+ // fill up array with null values if given idx is outside range
+ if (idx >= m_data.m_value.array->size()) {
+#if JSON_DIAGNOSTICS
+ // remember array size & capacity before resizing
+ const auto old_size = m_data.m_value.array->size();
+ const auto old_capacity = m_data.m_value.array->capacity();
+#endif
+ m_data.m_value.array->resize(idx + 1);
+
+#if JSON_DIAGNOSTICS
+ if (JSON_HEDLEY_UNLIKELY(m_data.m_value.array->capacity() != old_capacity)) {
+ // capacity has changed: update all parents
+ set_parents();
+ } else {
+ // set parent for values added above
+ set_parents(begin() + static_cast<typename iterator::difference_type>(old_size),
+ static_cast<typename iterator::difference_type>(idx + 1 - old_size));
+ }
+#endif
+ assert_invariant();
+ }
+
+ return m_data.m_value.array->operator[](idx);
+ }
+
+ JSON_THROW(type_error::create(
+ 305, detail::concat("cannot use operator[] with a numeric argument with ", type_name()), this));
+ }
+
+ /// @brief access specified array element
+ /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+ const_reference
+ operator[](size_type idx) const {
+ // const operator[] only works for arrays
+ if (JSON_HEDLEY_LIKELY(is_array())) {
+ return m_data.m_value.array->operator[](idx);
+ }
+
+ JSON_THROW(type_error::create(
+ 305, detail::concat("cannot use operator[] with a numeric argument with ", type_name()), this));
+ }
+
+ /// @brief access specified object element
+ /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+ reference
+ operator[](typename object_t::key_type key) {
+ // implicitly convert null value to an empty object
+ if (is_null()) {
+ m_data.m_type = value_t::object;
+ m_data.m_value.object = create<object_t>();
+ assert_invariant();
+ }
+
+ // operator[] only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ auto result = m_data.m_value.object->emplace(std::move(key), nullptr);
+ return set_parent(result.first->second);
+ }
+
+ JSON_THROW(type_error::create(
+ 305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
+ }
+
+ /// @brief access specified object element
+ /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+ const_reference
+ operator[](const typename object_t::key_type& key) const {
+ // const operator[] only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ auto it = m_data.m_value.object->find(key);
+ JSON_ASSERT(it != m_data.m_value.object->end());
+ return it->second;
+ }
+
+ JSON_THROW(type_error::create(
+ 305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
+ }
+
+ // these two functions resolve a (const) char * ambiguity affecting Clang and MSVC
+ // (they seemingly cannot be constrained to resolve the ambiguity)
+ template <typename T>
+ reference
+ operator[](T* key) {
+ return operator[](typename object_t::key_type(key));
+ }
+
+ template <typename T>
+ const_reference
+ operator[](T* key) const {
+ return operator[](typename object_t::key_type(key));
+ }
+
+ /// @brief access specified object element
+ /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
+ reference
+ operator[](KeyType&& key) {
+ // implicitly convert null value to an empty object
+ if (is_null()) {
+ m_data.m_type = value_t::object;
+ m_data.m_value.object = create<object_t>();
+ assert_invariant();
+ }
+
+ // operator[] only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ auto result = m_data.m_value.object->emplace(std::forward<KeyType>(key), nullptr);
+ return set_parent(result.first->second);
+ }
+
+ JSON_THROW(type_error::create(
+ 305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
+ }
+
+ /// @brief access specified object element
+ /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
+ const_reference
+ operator[](KeyType&& key) const {
+ // const operator[] only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ auto it = m_data.m_value.object->find(std::forward<KeyType>(key));
+ JSON_ASSERT(it != m_data.m_value.object->end());
+ return it->second;
+ }
+
+ JSON_THROW(type_error::create(
+ 305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
+ }
+
+ private:
+ template <typename KeyType>
+ using is_comparable_with_object_key =
+ detail::is_comparable<object_comparator_t, const typename object_t::key_type&, KeyType>;
+
+ template <typename ValueType>
+ using value_return_type =
+ std::conditional<detail::is_c_string_uncvref<ValueType>::value, string_t, typename std::decay<ValueType>::type>;
+
+ public:
+ /// @brief access specified object element with default value
+ /// @sa https://json.nlohmann.me/api/basic_json/value/
+ template <class ValueType,
+ detail::enable_if_t<!detail::is_transparent<object_comparator_t>::value &&
+ detail::is_getable<basic_json_t, ValueType>::value &&
+ !std::is_same<value_t, detail::uncvref_t<ValueType>>::value,
+ int> = 0>
+ ValueType
+ value(const typename object_t::key_type& key, const ValueType& default_value) const {
+ // value only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ // if key is found, return value and given default value otherwise
+ const auto it = find(key);
+ if (it != end()) {
+ return it->template get<ValueType>();
+ }
+
+ return default_value;
+ }
+
+ JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
+ }
+
+ /// @brief access specified object element with default value
+ /// @sa https://json.nlohmann.me/api/basic_json/value/
+ template <class ValueType,
+ class ReturnType = typename value_return_type<ValueType>::type,
+ detail::enable_if_t<!detail::is_transparent<object_comparator_t>::value &&
+ detail::is_getable<basic_json_t, ReturnType>::value &&
+ !std::is_same<value_t, detail::uncvref_t<ValueType>>::value,
+ int> = 0>
+ ReturnType
+ value(const typename object_t::key_type& key, ValueType&& default_value) const {
+ // value only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ // if key is found, return value and given default value otherwise
+ const auto it = find(key);
+ if (it != end()) {
+ return it->template get<ReturnType>();
+ }
+
+ return std::forward<ValueType>(default_value);
+ }
+
+ JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
+ }
+
+ /// @brief access specified object element with default value
+ /// @sa https://json.nlohmann.me/api/basic_json/value/
+ template <
+ class ValueType,
+ class KeyType,
+ detail::enable_if_t<
+ detail::is_transparent<object_comparator_t>::value && !detail::is_json_pointer<KeyType>::value &&
+ is_comparable_with_object_key<KeyType>::value && detail::is_getable<basic_json_t, ValueType>::value &&
+ !std::is_same<value_t, detail::uncvref_t<ValueType>>::value,
+ int> = 0>
+ ValueType
+ value(KeyType&& key, const ValueType& default_value) const {
+ // value only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ // if key is found, return value and given default value otherwise
+ const auto it = find(std::forward<KeyType>(key));
+ if (it != end()) {
+ return it->template get<ValueType>();
+ }
+
+ return default_value;
+ }
+
+ JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
+ }
+
+ /// @brief access specified object element via JSON Pointer with default value
+ /// @sa https://json.nlohmann.me/api/basic_json/value/
+ template <
+ class ValueType,
+ class KeyType,
+ class ReturnType = typename value_return_type<ValueType>::type,
+ detail::enable_if_t<
+ detail::is_transparent<object_comparator_t>::value && !detail::is_json_pointer<KeyType>::value &&
+ is_comparable_with_object_key<KeyType>::value && detail::is_getable<basic_json_t, ReturnType>::value &&
+ !std::is_same<value_t, detail::uncvref_t<ValueType>>::value,
+ int> = 0>
+ ReturnType
+ value(KeyType&& key, ValueType&& default_value) const {
+ // value only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ // if key is found, return value and given default value otherwise
+ const auto it = find(std::forward<KeyType>(key));
+ if (it != end()) {
+ return it->template get<ReturnType>();
+ }
+
+ return std::forward<ValueType>(default_value);
+ }
+
+ JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
+ }
+
+ /// @brief access specified object element via JSON Pointer with default value
+ /// @sa https://json.nlohmann.me/api/basic_json/value/
+ template <class ValueType,
+ detail::enable_if_t<detail::is_getable<basic_json_t, ValueType>::value &&
+ !std::is_same<value_t, detail::uncvref_t<ValueType>>::value,
+ int> = 0>
+ ValueType
+ value(const json_pointer& ptr, const ValueType& default_value) const {
+ // value only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ // if pointer resolves a value, return it or use default value
+ JSON_TRY { return ptr.get_checked(this).template get<ValueType>(); }
+ JSON_INTERNAL_CATCH(out_of_range&) { return default_value; }
+ }
+
+ JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
+ }
+
+ /// @brief access specified object element via JSON Pointer with default value
+ /// @sa https://json.nlohmann.me/api/basic_json/value/
+ template <class ValueType,
+ class ReturnType = typename value_return_type<ValueType>::type,
+ detail::enable_if_t<detail::is_getable<basic_json_t, ReturnType>::value &&
+ !std::is_same<value_t, detail::uncvref_t<ValueType>>::value,
+ int> = 0>
+ ReturnType
+ value(const json_pointer& ptr, ValueType&& default_value) const {
+ // value only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ // if pointer resolves a value, return it or use default value
+ JSON_TRY { return ptr.get_checked(this).template get<ReturnType>(); }
+ JSON_INTERNAL_CATCH(out_of_range&) { return std::forward<ValueType>(default_value); }
+ }
+
+ JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
+ }
+
+ template <class ValueType,
+ class BasicJsonType,
+ detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value &&
+ detail::is_getable<basic_json_t, ValueType>::value &&
+ !std::is_same<value_t, detail::uncvref_t<ValueType>>::value,
+ int> = 0>
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0,
+ basic_json::json_pointer or
+ nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
+ ValueType value(const ::nlohmann::json_pointer<BasicJsonType>& ptr, const ValueType& default_value) const {
+ return value(ptr.convert(), default_value);
+ }
+
+ template <class ValueType,
+ class BasicJsonType,
+ class ReturnType = typename value_return_type<ValueType>::type,
+ detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value &&
+ detail::is_getable<basic_json_t, ReturnType>::value &&
+ !std::is_same<value_t, detail::uncvref_t<ValueType>>::value,
+ int> = 0>
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0,
+ basic_json::json_pointer or
+ nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
+ ReturnType value(const ::nlohmann::json_pointer<BasicJsonType>& ptr, ValueType&& default_value) const {
+ return value(ptr.convert(), std::forward<ValueType>(default_value));
+ }
+
+ /// @brief access the first element
+ /// @sa https://json.nlohmann.me/api/basic_json/front/
+ reference
+ front() {
+ return *begin();
+ }
+
+ /// @brief access the first element
+ /// @sa https://json.nlohmann.me/api/basic_json/front/
+ const_reference
+ front() const {
+ return *cbegin();
+ }
+
+ /// @brief access the last element
+ /// @sa https://json.nlohmann.me/api/basic_json/back/
+ reference
+ back() {
+ auto tmp = end();
+ --tmp;
+ return *tmp;
+ }
+
+ /// @brief access the last element
+ /// @sa https://json.nlohmann.me/api/basic_json/back/
+ const_reference
+ back() const {
+ auto tmp = cend();
+ --tmp;
+ return *tmp;
+ }
+
+ /// @brief remove element given an iterator
+ /// @sa https://json.nlohmann.me/api/basic_json/erase/
+ template <class IteratorType,
+ detail::enable_if_t<std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
+ std::is_same<IteratorType, typename basic_json_t::const_iterator>::value,
+ int> = 0>
+ IteratorType
+ erase(IteratorType pos) {
+ // make sure iterator fits the current value
+ if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) {
+ JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
+ }
+
+ IteratorType result = end();
+
+ switch (m_data.m_type) {
+ case value_t::boolean:
+ case value_t::number_float:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::string:
+ case value_t::binary: {
+ if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) {
+ JSON_THROW(invalid_iterator::create(205, "iterator out of range", this));
+ }
+
+ if (is_string()) {
+ AllocatorType<string_t> alloc;
+ std::allocator_traits<decltype(alloc)>::destroy(alloc, m_data.m_value.string);
+ std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_data.m_value.string, 1);
+ m_data.m_value.string = nullptr;
+ } else if (is_binary()) {
+ AllocatorType<binary_t> alloc;
+ std::allocator_traits<decltype(alloc)>::destroy(alloc, m_data.m_value.binary);
+ std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_data.m_value.binary, 1);
+ m_data.m_value.binary = nullptr;
+ }
+
+ m_data.m_type = value_t::null;
+ assert_invariant();
+ break;
+ }
+
+ case value_t::object: {
+ result.m_it.object_iterator = m_data.m_value.object->erase(pos.m_it.object_iterator);
+ break;
+ }
+
+ case value_t::array: {
+ result.m_it.array_iterator = m_data.m_value.array->erase(pos.m_it.array_iterator);
+ break;
+ }
+
+ case value_t::null:
+ case value_t::discarded:
+ default:
+ JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
+ }
+
+ return result;
+ }
+
+ /// @brief remove elements given an iterator range
+ /// @sa https://json.nlohmann.me/api/basic_json/erase/
+ template <class IteratorType,
+ detail::enable_if_t<std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
+ std::is_same<IteratorType, typename basic_json_t::const_iterator>::value,
+ int> = 0>
+ IteratorType
+ erase(IteratorType first, IteratorType last) {
+ // make sure iterator fits the current value
+ if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) {
+ JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", this));
+ }
+
+ IteratorType result = end();
+
+ switch (m_data.m_type) {
+ case value_t::boolean:
+ case value_t::number_float:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::string:
+ case value_t::binary: {
+ if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() ||
+ !last.m_it.primitive_iterator.is_end())) {
+ JSON_THROW(invalid_iterator::create(204, "iterators out of range", this));
+ }
+
+ if (is_string()) {
+ AllocatorType<string_t> alloc;
+ std::allocator_traits<decltype(alloc)>::destroy(alloc, m_data.m_value.string);
+ std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_data.m_value.string, 1);
+ m_data.m_value.string = nullptr;
+ } else if (is_binary()) {
+ AllocatorType<binary_t> alloc;
+ std::allocator_traits<decltype(alloc)>::destroy(alloc, m_data.m_value.binary);
+ std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_data.m_value.binary, 1);
+ m_data.m_value.binary = nullptr;
+ }
+
+ m_data.m_type = value_t::null;
+ assert_invariant();
+ break;
+ }
+
+ case value_t::object: {
+ result.m_it.object_iterator =
+ m_data.m_value.object->erase(first.m_it.object_iterator, last.m_it.object_iterator);
+ break;
+ }
+
+ case value_t::array: {
+ result.m_it.array_iterator =
+ m_data.m_value.array->erase(first.m_it.array_iterator, last.m_it.array_iterator);
+ break;
+ }
+
+ case value_t::null:
+ case value_t::discarded:
+ default:
+ JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
+ }
+
+ return result;
+ }
+
+ private:
+ template <typename KeyType,
+ detail::enable_if_t<detail::has_erase_with_key_type<basic_json_t, KeyType>::value, int> = 0>
+ size_type
+ erase_internal(KeyType&& key) {
+ // this erase only works for objects
+ if (JSON_HEDLEY_UNLIKELY(!is_object())) {
+ JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
+ }
+
+ return m_data.m_value.object->erase(std::forward<KeyType>(key));
+ }
+
+ template <typename KeyType,
+ detail::enable_if_t<!detail::has_erase_with_key_type<basic_json_t, KeyType>::value, int> = 0>
+ size_type
+ erase_internal(KeyType&& key) {
+ // this erase only works for objects
+ if (JSON_HEDLEY_UNLIKELY(!is_object())) {
+ JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
+ }
+
+ const auto it = m_data.m_value.object->find(std::forward<KeyType>(key));
+ if (it != m_data.m_value.object->end()) {
+ m_data.m_value.object->erase(it);
+ return 1;
+ }
+ return 0;
+ }
+
+ public:
+ /// @brief remove element from a JSON object given a key
+ /// @sa https://json.nlohmann.me/api/basic_json/erase/
+ size_type
+ erase(const typename object_t::key_type& key) {
+ // the indirection via erase_internal() is added to avoid making this
+ // function a template and thus de-rank it during overload resolution
+ return erase_internal(key);
+ }
+
+ /// @brief remove element from a JSON object given a key
+ /// @sa https://json.nlohmann.me/api/basic_json/erase/
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
+ size_type
+ erase(KeyType&& key) {
+ return erase_internal(std::forward<KeyType>(key));
+ }
+
+ /// @brief remove element from a JSON array given an index
+ /// @sa https://json.nlohmann.me/api/basic_json/erase/
+ void
+ erase(const size_type idx) {
+ // this erase only works for arrays
+ if (JSON_HEDLEY_LIKELY(is_array())) {
+ if (JSON_HEDLEY_UNLIKELY(idx >= size())) {
+ JSON_THROW(out_of_range::create(
+ 401, detail::concat("array index ", std::to_string(idx), " is out of range"), this));
+ }
+
+ m_data.m_value.array->erase(m_data.m_value.array->begin() + static_cast<difference_type>(idx));
+ } else {
+ JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
+ }
+ }
+
+ /// @}
+
+ ////////////
+ // lookup //
+ ////////////
+
+ /// @name lookup
+ /// @{
+
+ /// @brief find an element in a JSON object
+ /// @sa https://json.nlohmann.me/api/basic_json/find/
+ iterator
+ find(const typename object_t::key_type& key) {
+ auto result = end();
+
+ if (is_object()) {
+ result.m_it.object_iterator = m_data.m_value.object->find(key);
+ }
+
+ return result;
+ }
+
+ /// @brief find an element in a JSON object
+ /// @sa https://json.nlohmann.me/api/basic_json/find/
+ const_iterator
+ find(const typename object_t::key_type& key) const {
+ auto result = cend();
+
+ if (is_object()) {
+ result.m_it.object_iterator = m_data.m_value.object->find(key);
+ }
+
+ return result;
+ }
+
+ /// @brief find an element in a JSON object
+ /// @sa https://json.nlohmann.me/api/basic_json/find/
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
+ iterator
+ find(KeyType&& key) {
+ auto result = end();
+
+ if (is_object()) {
+ result.m_it.object_iterator = m_data.m_value.object->find(std::forward<KeyType>(key));
+ }
+
+ return result;
+ }
+
+ /// @brief find an element in a JSON object
+ /// @sa https://json.nlohmann.me/api/basic_json/find/
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
+ const_iterator
+ find(KeyType&& key) const {
+ auto result = cend();
+
+ if (is_object()) {
+ result.m_it.object_iterator = m_data.m_value.object->find(std::forward<KeyType>(key));
+ }
+
+ return result;
+ }
+
+ /// @brief returns the number of occurrences of a key in a JSON object
+ /// @sa https://json.nlohmann.me/api/basic_json/count/
+ size_type
+ count(const typename object_t::key_type& key) const {
+ // return 0 for all nonobject types
+ return is_object() ? m_data.m_value.object->count(key) : 0;
+ }
+
+ /// @brief returns the number of occurrences of a key in a JSON object
+ /// @sa https://json.nlohmann.me/api/basic_json/count/
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
+ size_type
+ count(KeyType&& key) const {
+ // return 0 for all nonobject types
+ return is_object() ? m_data.m_value.object->count(std::forward<KeyType>(key)) : 0;
+ }
+
+ /// @brief check the existence of an element in a JSON object
+ /// @sa https://json.nlohmann.me/api/basic_json/contains/
+ bool
+ contains(const typename object_t::key_type& key) const {
+ return is_object() && m_data.m_value.object->find(key) != m_data.m_value.object->end();
+ }
+
+ /// @brief check the existence of an element in a JSON object
+ /// @sa https://json.nlohmann.me/api/basic_json/contains/
+ template <class KeyType,
+ detail::enable_if_t<detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
+ bool
+ contains(KeyType&& key) const {
+ return is_object() && m_data.m_value.object->find(std::forward<KeyType>(key)) != m_data.m_value.object->end();
+ }
+
+ /// @brief check the existence of an element in a JSON object given a JSON pointer
+ /// @sa https://json.nlohmann.me/api/basic_json/contains/
+ bool
+ contains(const json_pointer& ptr) const {
+ return ptr.contains(this);
+ }
+
+ template <typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0,
+ basic_json::json_pointer or
+ nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
+ bool contains(const typename ::nlohmann::json_pointer<BasicJsonType>& ptr) const {
+ return ptr.contains(this);
+ }
+
+ /// @}
+
+ ///////////////
+ // iterators //
+ ///////////////
+
+ /// @name iterators
+ /// @{
+
+ /// @brief returns an iterator to the first element
+ /// @sa https://json.nlohmann.me/api/basic_json/begin/
+ iterator
+ begin() noexcept {
+ iterator result(this);
+ result.set_begin();
+ return result;
+ }
+
+ /// @brief returns an iterator to the first element
+ /// @sa https://json.nlohmann.me/api/basic_json/begin/
+ const_iterator
+ begin() const noexcept {
+ return cbegin();
+ }
+
+ /// @brief returns a const iterator to the first element
+ /// @sa https://json.nlohmann.me/api/basic_json/cbegin/
+ const_iterator
+ cbegin() const noexcept {
+ const_iterator result(this);
+ result.set_begin();
+ return result;
+ }
+
+ /// @brief returns an iterator to one past the last element
+ /// @sa https://json.nlohmann.me/api/basic_json/end/
+ iterator
+ end() noexcept {
+ iterator result(this);
+ result.set_end();
+ return result;
+ }
+
+ /// @brief returns an iterator to one past the last element
+ /// @sa https://json.nlohmann.me/api/basic_json/end/
+ const_iterator
+ end() const noexcept {
+ return cend();
+ }
+
+ /// @brief returns an iterator to one past the last element
+ /// @sa https://json.nlohmann.me/api/basic_json/cend/
+ const_iterator
+ cend() const noexcept {
+ const_iterator result(this);
+ result.set_end();
+ return result;
+ }
+
+ /// @brief returns an iterator to the reverse-beginning
+ /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
+ reverse_iterator
+ rbegin() noexcept {
+ return reverse_iterator(end());
+ }
+
+ /// @brief returns an iterator to the reverse-beginning
+ /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
+ const_reverse_iterator
+ rbegin() const noexcept {
+ return crbegin();
+ }
+
+ /// @brief returns an iterator to the reverse-end
+ /// @sa https://json.nlohmann.me/api/basic_json/rend/
+ reverse_iterator
+ rend() noexcept {
+ return reverse_iterator(begin());
+ }
+
+ /// @brief returns an iterator to the reverse-end
+ /// @sa https://json.nlohmann.me/api/basic_json/rend/
+ const_reverse_iterator
+ rend() const noexcept {
+ return crend();
+ }
+
+ /// @brief returns a const reverse iterator to the last element
+ /// @sa https://json.nlohmann.me/api/basic_json/crbegin/
+ const_reverse_iterator
+ crbegin() const noexcept {
+ return const_reverse_iterator(cend());
+ }
+
+ /// @brief returns a const reverse iterator to one before the first
+ /// @sa https://json.nlohmann.me/api/basic_json/crend/
+ const_reverse_iterator
+ crend() const noexcept {
+ return const_reverse_iterator(cbegin());
+ }
+
+ public:
+ /// @brief wrapper to access iterator member functions in range-based for
+ /// @sa https://json.nlohmann.me/api/basic_json/items/
+ /// @deprecated This function is deprecated since 3.1.0 and will be removed in
+ /// version 4.0.0 of the library. Please use @ref items() instead;
+ /// that is, replace `json::iterator_wrapper(j)` with `j.items()`.
+ JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
+ static iteration_proxy<iterator>
+ iterator_wrapper(reference ref) noexcept {
+ return ref.items();
+ }
+
+ /// @brief wrapper to access iterator member functions in range-based for
+ /// @sa https://json.nlohmann.me/api/basic_json/items/
+ /// @deprecated This function is deprecated since 3.1.0 and will be removed in
+ /// version 4.0.0 of the library. Please use @ref items() instead;
+ /// that is, replace `json::iterator_wrapper(j)` with `j.items()`.
+ JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
+ static iteration_proxy<const_iterator>
+ iterator_wrapper(const_reference ref) noexcept {
+ return ref.items();
+ }
+
+ /// @brief helper to access iterator member functions in range-based for
+ /// @sa https://json.nlohmann.me/api/basic_json/items/
+ iteration_proxy<iterator>
+ items() noexcept {
+ return iteration_proxy<iterator>(*this);
+ }
+
+ /// @brief helper to access iterator member functions in range-based for
+ /// @sa https://json.nlohmann.me/api/basic_json/items/
+ iteration_proxy<const_iterator>
+ items() const noexcept {
+ return iteration_proxy<const_iterator>(*this);
+ }
+
+ /// @}
+
+ //////////////
+ // capacity //
+ //////////////
+
+ /// @name capacity
+ /// @{
+
+ /// @brief checks whether the container is empty.
+ /// @sa https://json.nlohmann.me/api/basic_json/empty/
+ bool
+ empty() const noexcept {
+ switch (m_data.m_type) {
+ case value_t::null: {
+ // null values are empty
+ return true;
+ }
+
+ case value_t::array: {
+ // delegate call to array_t::empty()
+ return m_data.m_value.array->empty();
+ }
+
+ case value_t::object: {
+ // delegate call to object_t::empty()
+ return m_data.m_value.object->empty();
+ }
+
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ // all other types are nonempty
+ return false;
+ }
+ }
+ }
+
+ /// @brief returns the number of elements
+ /// @sa https://json.nlohmann.me/api/basic_json/size/
+ size_type
+ size() const noexcept {
+ switch (m_data.m_type) {
+ case value_t::null: {
+ // null values are empty
+ return 0;
+ }
+
+ case value_t::array: {
+ // delegate call to array_t::size()
+ return m_data.m_value.array->size();
+ }
+
+ case value_t::object: {
+ // delegate call to object_t::size()
+ return m_data.m_value.object->size();
+ }
+
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ // all other types have size 1
+ return 1;
+ }
+ }
+ }
+
+ /// @brief returns the maximum possible number of elements
+ /// @sa https://json.nlohmann.me/api/basic_json/max_size/
+ size_type
+ max_size() const noexcept {
+ switch (m_data.m_type) {
+ case value_t::array: {
+ // delegate call to array_t::max_size()
+ return m_data.m_value.array->max_size();
+ }
+
+ case value_t::object: {
+ // delegate call to object_t::max_size()
+ return m_data.m_value.object->max_size();
+ }
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ // all other types have max_size() == size()
+ return size();
+ }
+ }
+ }
+
+ /// @}
+
+ ///////////////
+ // modifiers //
+ ///////////////
+
+ /// @name modifiers
+ /// @{
+
+ /// @brief clears the contents
+ /// @sa https://json.nlohmann.me/api/basic_json/clear/
+ void
+ clear() noexcept {
+ switch (m_data.m_type) {
+ case value_t::number_integer: {
+ m_data.m_value.number_integer = 0;
+ break;
+ }
+
+ case value_t::number_unsigned: {
+ m_data.m_value.number_unsigned = 0;
+ break;
+ }
+
+ case value_t::number_float: {
+ m_data.m_value.number_float = 0.0;
+ break;
+ }
+
+ case value_t::boolean: {
+ m_data.m_value.boolean = false;
+ break;
+ }
+
+ case value_t::string: {
+ m_data.m_value.string->clear();
+ break;
+ }
+
+ case value_t::binary: {
+ m_data.m_value.binary->clear();
+ break;
+ }
+
+ case value_t::array: {
+ m_data.m_value.array->clear();
+ break;
+ }
+
+ case value_t::object: {
+ m_data.m_value.object->clear();
+ break;
+ }
+
+ case value_t::null:
+ case value_t::discarded:
+ default:
+ break;
+ }
+ }
+
+ /// @brief add an object to an array
+ /// @sa https://json.nlohmann.me/api/basic_json/push_back/
+ void
+ push_back(basic_json&& val) {
+ // push_back only works for null objects or arrays
+ if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) {
+ JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this));
+ }
+
+ // transform null object into an array
+ if (is_null()) {
+ m_data.m_type = value_t::array;
+ m_data.m_value = value_t::array;
+ assert_invariant();
+ }
+
+ // add element to array (move semantics)
+ const auto old_capacity = m_data.m_value.array->capacity();
+ m_data.m_value.array->push_back(std::move(val));
+ set_parent(m_data.m_value.array->back(), old_capacity);
+ // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor
+ }
+
+ /// @brief add an object to an array
+ /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
+ reference
+ operator+=(basic_json&& val) {
+ push_back(std::move(val));
+ return *this;
+ }
+
+ /// @brief add an object to an array
+ /// @sa https://json.nlohmann.me/api/basic_json/push_back/
+ void
+ push_back(const basic_json& val) {
+ // push_back only works for null objects or arrays
+ if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) {
+ JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this));
+ }
+
+ // transform null object into an array
+ if (is_null()) {
+ m_data.m_type = value_t::array;
+ m_data.m_value = value_t::array;
+ assert_invariant();
+ }
+
+ // add element to array
+ const auto old_capacity = m_data.m_value.array->capacity();
+ m_data.m_value.array->push_back(val);
+ set_parent(m_data.m_value.array->back(), old_capacity);
+ }
+
+ /// @brief add an object to an array
+ /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
+ reference
+ operator+=(const basic_json& val) {
+ push_back(val);
+ return *this;
+ }
+
+ /// @brief add an object to an object
+ /// @sa https://json.nlohmann.me/api/basic_json/push_back/
+ void
+ push_back(const typename object_t::value_type& val) {
+ // push_back only works for null objects or objects
+ if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) {
+ JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this));
+ }
+
+ // transform null object into an object
+ if (is_null()) {
+ m_data.m_type = value_t::object;
+ m_data.m_value = value_t::object;
+ assert_invariant();
+ }
+
+ // add element to object
+ auto res = m_data.m_value.object->insert(val);
+ set_parent(res.first->second);
+ }
+
+ /// @brief add an object to an object
+ /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
+ reference
+ operator+=(const typename object_t::value_type& val) {
+ push_back(val);
+ return *this;
+ }
+
+ /// @brief add an object to an object
+ /// @sa https://json.nlohmann.me/api/basic_json/push_back/
+ void
+ push_back(initializer_list_t init) {
+ if (is_object() && init.size() == 2 && (*init.begin())->is_string()) {
+ basic_json&& key = init.begin()->moved_or_copied();
+ push_back(typename object_t::value_type(std::move(key.get_ref<string_t&>()),
+ (init.begin() + 1)->moved_or_copied()));
+ } else {
+ push_back(basic_json(init));
+ }
+ }
+
+ /// @brief add an object to an object
+ /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
+ reference
+ operator+=(initializer_list_t init) {
+ push_back(init);
+ return *this;
+ }
+
+ /// @brief add an object to an array
+ /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/
+ template <class... Args>
+ reference
+ emplace_back(Args&&... args) {
+ // emplace_back only works for null objects or arrays
+ if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) {
+ JSON_THROW(type_error::create(311, detail::concat("cannot use emplace_back() with ", type_name()), this));
+ }
+
+ // transform null object into an array
+ if (is_null()) {
+ m_data.m_type = value_t::array;
+ m_data.m_value = value_t::array;
+ assert_invariant();
+ }
+
+ // add element to array (perfect forwarding)
+ const auto old_capacity = m_data.m_value.array->capacity();
+ m_data.m_value.array->emplace_back(std::forward<Args>(args)...);
+ return set_parent(m_data.m_value.array->back(), old_capacity);
+ }
+
+ /// @brief add an object to an object if key does not exist
+ /// @sa https://json.nlohmann.me/api/basic_json/emplace/
+ template <class... Args>
+ std::pair<iterator, bool>
+ emplace(Args&&... args) {
+ // emplace only works for null objects or arrays
+ if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) {
+ JSON_THROW(type_error::create(311, detail::concat("cannot use emplace() with ", type_name()), this));
+ }
+
+ // transform null object into an object
+ if (is_null()) {
+ m_data.m_type = value_t::object;
+ m_data.m_value = value_t::object;
+ assert_invariant();
+ }
+
+ // add element to array (perfect forwarding)
+ auto res = m_data.m_value.object->emplace(std::forward<Args>(args)...);
+ set_parent(res.first->second);
+
+ // create result iterator and set iterator to the result of emplace
+ auto it = begin();
+ it.m_it.object_iterator = res.first;
+
+ // return pair of iterator and boolean
+ return {it, res.second};
+ }
+
+ /// Helper for insertion of an iterator
+ /// @note: This uses std::distance to support GCC 4.8,
+ /// see https://github.com/nlohmann/json/pull/1257
+ template <typename... Args>
+ iterator
+ insert_iterator(const_iterator pos, Args&&... args) {
+ iterator result(this);
+ JSON_ASSERT(m_data.m_value.array != nullptr);
+
+ auto insert_pos = std::distance(m_data.m_value.array->begin(), pos.m_it.array_iterator);
+ m_data.m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
+ result.m_it.array_iterator = m_data.m_value.array->begin() + insert_pos;
+
+ // This could have been written as:
+ // result.m_it.array_iterator = m_data.m_value.array->insert(pos.m_it.array_iterator, cnt, val);
+ // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
+
+ set_parents();
+ return result;
+ }
+
+ /// @brief inserts element into array
+ /// @sa https://json.nlohmann.me/api/basic_json/insert/
+ iterator
+ insert(const_iterator pos, const basic_json& val) {
+ // insert only works for arrays
+ if (JSON_HEDLEY_LIKELY(is_array())) {
+ // check if iterator pos fits to this JSON value
+ if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) {
+ JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
+ }
+
+ // insert to array and return iterator
+ return insert_iterator(pos, val);
+ }
+
+ JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
+ }
+
+ /// @brief inserts element into array
+ /// @sa https://json.nlohmann.me/api/basic_json/insert/
+ iterator
+ insert(const_iterator pos, basic_json&& val) {
+ return insert(pos, val);
+ }
+
+ /// @brief inserts copies of element into array
+ /// @sa https://json.nlohmann.me/api/basic_json/insert/
+ iterator
+ insert(const_iterator pos, size_type cnt, const basic_json& val) {
+ // insert only works for arrays
+ if (JSON_HEDLEY_LIKELY(is_array())) {
+ // check if iterator pos fits to this JSON value
+ if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) {
+ JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
+ }
+
+ // insert to array and return iterator
+ return insert_iterator(pos, cnt, val);
+ }
+
+ JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
+ }
+
+ /// @brief inserts range of elements into array
+ /// @sa https://json.nlohmann.me/api/basic_json/insert/
+ iterator
+ insert(const_iterator pos, const_iterator first, const_iterator last) {
+ // insert only works for arrays
+ if (JSON_HEDLEY_UNLIKELY(!is_array())) {
+ JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
+ }
+
+ // check if iterator pos fits to this JSON value
+ if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) {
+ JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
+ }
+
+ // check if range iterators belong to the same JSON object
+ if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) {
+ JSON_THROW(invalid_iterator::create(210, "iterators do not fit", this));
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) {
+ JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", this));
+ }
+
+ // insert to array and return iterator
+ return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
+ }
+
+ /// @brief inserts elements from initializer list into array
+ /// @sa https://json.nlohmann.me/api/basic_json/insert/
+ iterator
+ insert(const_iterator pos, initializer_list_t ilist) {
+ // insert only works for arrays
+ if (JSON_HEDLEY_UNLIKELY(!is_array())) {
+ JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
+ }
+
+ // check if iterator pos fits to this JSON value
+ if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) {
+ JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
+ }
+
+ // insert to array and return iterator
+ return insert_iterator(pos, ilist.begin(), ilist.end());
+ }
+
+ /// @brief inserts range of elements into object
+ /// @sa https://json.nlohmann.me/api/basic_json/insert/
+ void
+ insert(const_iterator first, const_iterator last) {
+ // insert only works for objects
+ if (JSON_HEDLEY_UNLIKELY(!is_object())) {
+ JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
+ }
+
+ // check if range iterators belong to the same JSON object
+ if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) {
+ JSON_THROW(invalid_iterator::create(210, "iterators do not fit", this));
+ }
+
+ // passed iterators must belong to objects
+ if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) {
+ JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", this));
+ }
+
+ m_data.m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
+ }
+
+ /// @brief updates a JSON object from another object, overwriting existing keys
+ /// @sa https://json.nlohmann.me/api/basic_json/update/
+ void
+ update(const_reference j, bool merge_objects = false) {
+ update(j.begin(), j.end(), merge_objects);
+ }
+
+ /// @brief updates a JSON object from another object, overwriting existing keys
+ /// @sa https://json.nlohmann.me/api/basic_json/update/
+ void
+ update(const_iterator first, const_iterator last, bool merge_objects = false) {
+ // implicitly convert null value to an empty object
+ if (is_null()) {
+ m_data.m_type = value_t::object;
+ m_data.m_value.object = create<object_t>();
+ assert_invariant();
+ }
+
+ if (JSON_HEDLEY_UNLIKELY(!is_object())) {
+ JSON_THROW(type_error::create(312, detail::concat("cannot use update() with ", type_name()), this));
+ }
+
+ // check if range iterators belong to the same JSON object
+ if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) {
+ JSON_THROW(invalid_iterator::create(210, "iterators do not fit", this));
+ }
+
+ // passed iterators must belong to objects
+ if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) {
+ JSON_THROW(type_error::create(
+ 312, detail::concat("cannot use update() with ", first.m_object->type_name()), first.m_object));
+ }
+
+ for (auto it = first; it != last; ++it) {
+ if (merge_objects && it.value().is_object()) {
+ auto it2 = m_data.m_value.object->find(it.key());
+ if (it2 != m_data.m_value.object->end()) {
+ it2->second.update(it.value(), true);
+ continue;
+ }
+ }
+ m_data.m_value.object->operator[](it.key()) = it.value();
+#if JSON_DIAGNOSTICS
+ m_data.m_value.object->operator[](it.key()).m_parent = this;
+#endif
+ }
+ }
+
+ /// @brief exchanges the values
+ /// @sa https://json.nlohmann.me/api/basic_json/swap/
+ void
+ swap(reference other) noexcept(
+ std::is_nothrow_move_constructible<value_t>::value && std::is_nothrow_move_assignable<value_t>::value &&
+ std::is_nothrow_move_constructible<
+ json_value>::value && // NOLINT(cppcoreguidelines-noexcept-swap,performance-noexcept-swap)
+ std::is_nothrow_move_assignable<json_value>::value) {
+ std::swap(m_data.m_type, other.m_data.m_type);
+ std::swap(m_data.m_value, other.m_data.m_value);
+
+ set_parents();
+ other.set_parents();
+ assert_invariant();
+ }
+
+ /// @brief exchanges the values
+ /// @sa https://json.nlohmann.me/api/basic_json/swap/
+ friend void
+ swap(reference left, reference right) noexcept(
+ std::is_nothrow_move_constructible<value_t>::value && std::is_nothrow_move_assignable<value_t>::value &&
+ std::is_nothrow_move_constructible<
+ json_value>::value && // NOLINT(cppcoreguidelines-noexcept-swap,performance-noexcept-swap)
+ std::is_nothrow_move_assignable<json_value>::value) {
+ left.swap(right);
+ }
+
+ /// @brief exchanges the values
+ /// @sa https://json.nlohmann.me/api/basic_json/swap/
+ void
+ swap(array_t& other) // NOLINT(bugprone-exception-escape,cppcoreguidelines-noexcept-swap,performance-noexcept-swap)
+ {
+ // swap only works for arrays
+ if (JSON_HEDLEY_LIKELY(is_array())) {
+ using std::swap;
+ swap(*(m_data.m_value.array), other);
+ } else {
+ JSON_THROW(type_error::create(310, detail::concat("cannot use swap(array_t&) with ", type_name()), this));
+ }
+ }
+
+ /// @brief exchanges the values
+ /// @sa https://json.nlohmann.me/api/basic_json/swap/
+ void
+ swap(
+ object_t& other) // NOLINT(bugprone-exception-escape,cppcoreguidelines-noexcept-swap,performance-noexcept-swap)
+ {
+ // swap only works for objects
+ if (JSON_HEDLEY_LIKELY(is_object())) {
+ using std::swap;
+ swap(*(m_data.m_value.object), other);
+ } else {
+ JSON_THROW(type_error::create(310, detail::concat("cannot use swap(object_t&) with ", type_name()), this));
+ }
+ }
+
+ /// @brief exchanges the values
+ /// @sa https://json.nlohmann.me/api/basic_json/swap/
+ void
+ swap(
+ string_t& other) // NOLINT(bugprone-exception-escape,cppcoreguidelines-noexcept-swap,performance-noexcept-swap)
+ {
+ // swap only works for strings
+ if (JSON_HEDLEY_LIKELY(is_string())) {
+ using std::swap;
+ swap(*(m_data.m_value.string), other);
+ } else {
+ JSON_THROW(type_error::create(310, detail::concat("cannot use swap(string_t&) with ", type_name()), this));
+ }
+ }
+
+ /// @brief exchanges the values
+ /// @sa https://json.nlohmann.me/api/basic_json/swap/
+ void
+ swap(
+ binary_t& other) // NOLINT(bugprone-exception-escape,cppcoreguidelines-noexcept-swap,performance-noexcept-swap)
+ {
+ // swap only works for strings
+ if (JSON_HEDLEY_LIKELY(is_binary())) {
+ using std::swap;
+ swap(*(m_data.m_value.binary), other);
+ } else {
+ JSON_THROW(type_error::create(310, detail::concat("cannot use swap(binary_t&) with ", type_name()), this));
+ }
+ }
+
+ /// @brief exchanges the values
+ /// @sa https://json.nlohmann.me/api/basic_json/swap/
+ void
+ swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape)
+ {
+ // swap only works for strings
+ if (JSON_HEDLEY_LIKELY(is_binary())) {
+ using std::swap;
+ swap(*(m_data.m_value.binary), other);
+ } else {
+ JSON_THROW(type_error::create(
+ 310, detail::concat("cannot use swap(binary_t::container_type&) with ", type_name()), this));
+ }
+ }
+
+ /// @}
+
+ //////////////////////////////////////////
+ // lexicographical comparison operators //
+ //////////////////////////////////////////
+
+ /// @name lexicographical comparison operators
+ /// @{
+
+ // note parentheses around operands are necessary; see
+ // https://github.com/nlohmann/json/issues/1530
+#define JSON_IMPLEMENT_OPERATOR(op, null_result, unordered_result, default_result) \
+ const auto lhs_type = lhs.type(); \
+ const auto rhs_type = rhs.type(); \
+ \
+ if (lhs_type == rhs_type) /* NOLINT(readability/braces) */ \
+ { \
+ switch (lhs_type) { \
+ case value_t::array: \
+ return (*lhs.m_data.m_value.array)op(*rhs.m_data.m_value.array); \
+ \
+ case value_t::object: \
+ return (*lhs.m_data.m_value.object)op(*rhs.m_data.m_value.object); \
+ \
+ case value_t::null: \
+ return (null_result); \
+ \
+ case value_t::string: \
+ return (*lhs.m_data.m_value.string)op(*rhs.m_data.m_value.string); \
+ \
+ case value_t::boolean: \
+ return (lhs.m_data.m_value.boolean)op(rhs.m_data.m_value.boolean); \
+ \
+ case value_t::number_integer: \
+ return (lhs.m_data.m_value.number_integer)op(rhs.m_data.m_value.number_integer); \
+ \
+ case value_t::number_unsigned: \
+ return (lhs.m_data.m_value.number_unsigned)op(rhs.m_data.m_value.number_unsigned); \
+ \
+ case value_t::number_float: \
+ return (lhs.m_data.m_value.number_float)op(rhs.m_data.m_value.number_float); \
+ \
+ case value_t::binary: \
+ return (*lhs.m_data.m_value.binary)op(*rhs.m_data.m_value.binary); \
+ \
+ case value_t::discarded: \
+ default: \
+ return (unordered_result); \
+ } \
+ } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) { \
+ return static_cast<number_float_t>(lhs.m_data.m_value.number_integer) op rhs.m_data.m_value.number_float; \
+ } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) { \
+ return lhs.m_data.m_value.number_float op static_cast<number_float_t>(rhs.m_data.m_value.number_integer); \
+ } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) { \
+ return static_cast<number_float_t>(lhs.m_data.m_value.number_unsigned) op rhs.m_data.m_value.number_float; \
+ } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) { \
+ return lhs.m_data.m_value.number_float op static_cast<number_float_t>(rhs.m_data.m_value.number_unsigned); \
+ } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) { \
+ return static_cast<number_integer_t>(lhs.m_data.m_value.number_unsigned) op rhs.m_data.m_value.number_integer; \
+ } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) { \
+ return lhs.m_data.m_value.number_integer op static_cast<number_integer_t>(rhs.m_data.m_value.number_unsigned); \
+ } else if (compares_unordered(lhs, rhs)) { \
+ return (unordered_result); \
+ } \
+ \
+ return (default_result);
+
+ JSON_PRIVATE_UNLESS_TESTED :
+ // returns true if:
+ // - any operand is NaN and the other operand is of number type
+ // - any operand is discarded
+ // in legacy mode, discarded values are considered ordered if
+ // an operation is computed as an odd number of inverses of others
+ static bool
+ compares_unordered(const_reference lhs, const_reference rhs, bool inverse = false) noexcept {
+ if ((lhs.is_number_float() && std::isnan(lhs.m_data.m_value.number_float) && rhs.is_number()) ||
+ (rhs.is_number_float() && std::isnan(rhs.m_data.m_value.number_float) && lhs.is_number())) {
+ return true;
+ }
+#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
+ return (lhs.is_discarded() || rhs.is_discarded()) && !inverse;
+#else
+ static_cast<void>(inverse);
+ return lhs.is_discarded() || rhs.is_discarded();
+#endif
+ }
+
+ private:
+ bool
+ compares_unordered(const_reference rhs, bool inverse = false) const noexcept {
+ return compares_unordered(*this, rhs, inverse);
+ }
+
+ public:
+#if JSON_HAS_THREE_WAY_COMPARISON
+ /// @brief comparison: equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
+ bool
+ operator==(const_reference rhs) const noexcept {
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wfloat-equal"
+#endif
+ const_reference lhs = *this;
+ JSON_IMPLEMENT_OPERATOR(==, true, false, false)
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+ }
+
+ /// @brief comparison: equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
+ template <typename ScalarType>
+ requires std::is_scalar_v<ScalarType>
+ bool
+ operator==(ScalarType rhs) const noexcept {
+ return *this == basic_json(rhs);
+ }
+
+ /// @brief comparison: not equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
+ bool
+ operator!=(const_reference rhs) const noexcept {
+ if (compares_unordered(rhs, true)) {
+ return false;
+ }
+ return !operator==(rhs);
+ }
+
+ /// @brief comparison: 3-way
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/
+ std::partial_ordering
+ operator<=>(const_reference rhs) const noexcept // *NOPAD*
+ {
+ const_reference lhs = *this;
+ // default_result is used if we cannot compare values. In that case,
+ // we compare types.
+ JSON_IMPLEMENT_OPERATOR(<=>, // *NOPAD*
+ std::partial_ordering::equivalent,
+ std::partial_ordering::unordered,
+ lhs_type <=> rhs_type) // *NOPAD*
+ }
+
+ /// @brief comparison: 3-way
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/
+ template <typename ScalarType>
+ requires std::is_scalar_v<ScalarType>
+ std::partial_ordering
+ operator<=>(ScalarType rhs) const noexcept // *NOPAD*
+ {
+ return *this <=> basic_json(rhs); // *NOPAD*
+ }
+
+#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
+ // all operators that are computed as an odd number of inverses of others
+ // need to be overloaded to emulate the legacy comparison behavior
+
+ /// @brief comparison: less than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0, undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON)
+ bool
+ operator<=(const_reference rhs) const noexcept {
+ if (compares_unordered(rhs, true)) {
+ return false;
+ }
+ return !(rhs < *this);
+ }
+
+ /// @brief comparison: less than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
+ template <typename ScalarType>
+ requires std::is_scalar_v<ScalarType>
+ bool
+ operator<=(ScalarType rhs) const noexcept {
+ return *this <= basic_json(rhs);
+ }
+
+ /// @brief comparison: greater than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0, undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON)
+ bool
+ operator>=(const_reference rhs) const noexcept {
+ if (compares_unordered(rhs, true)) {
+ return false;
+ }
+ return !(*this < rhs);
+ }
+
+ /// @brief comparison: greater than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
+ template <typename ScalarType>
+ requires std::is_scalar_v<ScalarType>
+ bool
+ operator>=(ScalarType rhs) const noexcept {
+ return *this >= basic_json(rhs);
+ }
+#endif
+#else
+ /// @brief comparison: equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
+ friend bool
+ operator==(const_reference lhs, const_reference rhs) noexcept {
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wfloat-equal"
+#endif
+ JSON_IMPLEMENT_OPERATOR(==, true, false, false)
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+ }
+
+ /// @brief comparison: equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator==(const_reference lhs, ScalarType rhs) noexcept {
+ return lhs == basic_json(rhs);
+ }
+
+ /// @brief comparison: equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator==(ScalarType lhs, const_reference rhs) noexcept {
+ return basic_json(lhs) == rhs;
+ }
+
+ /// @brief comparison: not equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
+ friend bool
+ operator!=(const_reference lhs, const_reference rhs) noexcept {
+ if (compares_unordered(lhs, rhs, true)) {
+ return false;
+ }
+ return !(lhs == rhs);
+ }
+
+ /// @brief comparison: not equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator!=(const_reference lhs, ScalarType rhs) noexcept {
+ return lhs != basic_json(rhs);
+ }
+
+ /// @brief comparison: not equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator!=(ScalarType lhs, const_reference rhs) noexcept {
+ return basic_json(lhs) != rhs;
+ }
+
+ /// @brief comparison: less than
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
+ friend bool
+ operator<(const_reference lhs, const_reference rhs) noexcept {
+ // default_result is used if we cannot compare values. In that case,
+ // we compare types. Note we have to call the operator explicitly,
+ // because MSVC has problems otherwise.
+ JSON_IMPLEMENT_OPERATOR(<, false, false, operator<(lhs_type, rhs_type))
+ }
+
+ /// @brief comparison: less than
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator<(const_reference lhs, ScalarType rhs) noexcept {
+ return lhs < basic_json(rhs);
+ }
+
+ /// @brief comparison: less than
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator<(ScalarType lhs, const_reference rhs) noexcept {
+ return basic_json(lhs) < rhs;
+ }
+
+ /// @brief comparison: less than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
+ friend bool
+ operator<=(const_reference lhs, const_reference rhs) noexcept {
+ if (compares_unordered(lhs, rhs, true)) {
+ return false;
+ }
+ return !(rhs < lhs);
+ }
+
+ /// @brief comparison: less than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator<=(const_reference lhs, ScalarType rhs) noexcept {
+ return lhs <= basic_json(rhs);
+ }
+
+ /// @brief comparison: less than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator<=(ScalarType lhs, const_reference rhs) noexcept {
+ return basic_json(lhs) <= rhs;
+ }
+
+ /// @brief comparison: greater than
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
+ friend bool
+ operator>(const_reference lhs, const_reference rhs) noexcept {
+ // double inverse
+ if (compares_unordered(lhs, rhs)) {
+ return false;
+ }
+ return !(lhs <= rhs);
+ }
+
+ /// @brief comparison: greater than
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator>(const_reference lhs, ScalarType rhs) noexcept {
+ return lhs > basic_json(rhs);
+ }
+
+ /// @brief comparison: greater than
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator>(ScalarType lhs, const_reference rhs) noexcept {
+ return basic_json(lhs) > rhs;
+ }
+
+ /// @brief comparison: greater than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
+ friend bool
+ operator>=(const_reference lhs, const_reference rhs) noexcept {
+ if (compares_unordered(lhs, rhs, true)) {
+ return false;
+ }
+ return !(lhs < rhs);
+ }
+
+ /// @brief comparison: greater than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator>=(const_reference lhs, ScalarType rhs) noexcept {
+ return lhs >= basic_json(rhs);
+ }
+
+ /// @brief comparison: greater than or equal
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
+ template <typename ScalarType, typename std::enable_if<std::is_scalar<ScalarType>::value, int>::type = 0>
+ friend bool
+ operator>=(ScalarType lhs, const_reference rhs) noexcept {
+ return basic_json(lhs) >= rhs;
+ }
+#endif
+
+#undef JSON_IMPLEMENT_OPERATOR
+
+ /// @}
+
+ ///////////////////
+ // serialization //
+ ///////////////////
+
+ /// @name serialization
+ /// @{
+#ifndef JSON_NO_IO
+ /// @brief serialize to stream
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
+ friend std::ostream&
+ operator<<(std::ostream& o, const basic_json& j) {
+ // read width member and use it as indentation parameter if nonzero
+ const bool pretty_print = o.width() > 0;
+ const auto indentation = pretty_print ? o.width() : 0;
+
+ // reset width to 0 for subsequent calls to this stream
+ o.width(0);
+
+ // do the actual serialization
+ serializer s(detail::output_adapter<char>(o), o.fill());
+ s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
+ return o;
+ }
+
+ /// @brief serialize to stream
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
+ /// @deprecated This function is deprecated since 3.0.0 and will be removed in
+ /// version 4.0.0 of the library. Please use
+ /// operator<<(std::ostream&, const basic_json&) instead; that is,
+ /// replace calls like `j >> o;` with `o << j;`.
+ JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
+ friend std::ostream&
+ operator>>(const basic_json& j, std::ostream& o) {
+ return o << j;
+ }
+#endif // JSON_NO_IO
+ /// @}
+
+ /////////////////////
+ // deserialization //
+ /////////////////////
+
+ /// @name deserialization
+ /// @{
+
+ /// @brief deserialize from a compatible input
+ /// @sa https://json.nlohmann.me/api/basic_json/parse/
+ template <typename InputType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ parse(InputType&& i,
+ const parser_callback_t cb = nullptr,
+ const bool allow_exceptions = true,
+ const bool ignore_comments = false) {
+ basic_json result;
+ parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments)
+ .parse(true, result);
+ return result;
+ }
+
+ /// @brief deserialize from a pair of character iterators
+ /// @sa https://json.nlohmann.me/api/basic_json/parse/
+ template <typename IteratorType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ parse(IteratorType first,
+ IteratorType last,
+ const parser_callback_t cb = nullptr,
+ const bool allow_exceptions = true,
+ const bool ignore_comments = false) {
+ basic_json result;
+ parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments)
+ .parse(true, result);
+ return result;
+ }
+
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
+ static basic_json
+ parse(detail::span_input_adapter&& i,
+ const parser_callback_t cb = nullptr,
+ const bool allow_exceptions = true,
+ const bool ignore_comments = false) {
+ basic_json result;
+ parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
+ return result;
+ }
+
+ /// @brief check if the input is valid JSON
+ /// @sa https://json.nlohmann.me/api/basic_json/accept/
+ template <typename InputType>
+ static bool
+ accept(InputType&& i, const bool ignore_comments = false) {
+ return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
+ }
+
+ /// @brief check if the input is valid JSON
+ /// @sa https://json.nlohmann.me/api/basic_json/accept/
+ template <typename IteratorType>
+ static bool
+ accept(IteratorType first, IteratorType last, const bool ignore_comments = false) {
+ return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments)
+ .accept(true);
+ }
+
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
+ static bool
+ accept(detail::span_input_adapter&& i, const bool ignore_comments = false) {
+ return parser(i.get(), nullptr, false, ignore_comments).accept(true);
+ }
+
+ /// @brief generate SAX events
+ /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
+ template <typename InputType, typename SAX>
+ JSON_HEDLEY_NON_NULL(2)
+ static bool sax_parse(InputType&& i,
+ SAX* sax,
+ input_format_t format = input_format_t::json,
+ const bool strict = true,
+ const bool ignore_comments = false) {
+ auto ia = detail::input_adapter(std::forward<InputType>(i));
+ return format == input_format_t::json
+ ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
+ : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia), format)
+ .sax_parse(format, sax, strict);
+ }
+
+ /// @brief generate SAX events
+ /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
+ template <class IteratorType, class SAX>
+ JSON_HEDLEY_NON_NULL(3)
+ static bool sax_parse(IteratorType first,
+ IteratorType last,
+ SAX* sax,
+ input_format_t format = input_format_t::json,
+ const bool strict = true,
+ const bool ignore_comments = false) {
+ auto ia = detail::input_adapter(std::move(first), std::move(last));
+ return format == input_format_t::json
+ ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
+ : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia), format)
+ .sax_parse(format, sax, strict);
+ }
+
+ /// @brief generate SAX events
+ /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
+ /// @deprecated This function is deprecated since 3.8.0 and will be removed in
+ /// version 4.0.0 of the library. Please use
+ /// sax_parse(ptr, ptr + len) instead.
+ template <typename SAX>
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
+ JSON_HEDLEY_NON_NULL(2) static bool sax_parse(detail::span_input_adapter&& i,
+ SAX* sax,
+ input_format_t format = input_format_t::json,
+ const bool strict = true,
+ const bool ignore_comments = false) {
+ auto ia = i.get();
+ return format == input_format_t::json
+ // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+ ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
+ // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+ : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia), format)
+ .sax_parse(format, sax, strict);
+ }
+#ifndef JSON_NO_IO
+ /// @brief deserialize from stream
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
+ /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in
+ /// version 4.0.0 of the library. Please use
+ /// operator>>(std::istream&, basic_json&) instead; that is,
+ /// replace calls like `j << i;` with `i >> j;`.
+ JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
+ friend std::istream&
+ operator<<(basic_json& j, std::istream& i) {
+ return operator>>(i, j);
+ }
+
+ /// @brief deserialize from stream
+ /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
+ friend std::istream&
+ operator>>(std::istream& i, basic_json& j) {
+ parser(detail::input_adapter(i)).parse(false, j);
+ return i;
+ }
+#endif // JSON_NO_IO
+ /// @}
+
+ ///////////////////////////
+ // convenience functions //
+ ///////////////////////////
+
+ /// @brief return the type as string
+ /// @sa https://json.nlohmann.me/api/basic_json/type_name/
+ JSON_HEDLEY_RETURNS_NON_NULL
+ const char*
+ type_name() const noexcept {
+ switch (m_data.m_type) {
+ case value_t::null:
+ return "null";
+ case value_t::object:
+ return "object";
+ case value_t::array:
+ return "array";
+ case value_t::string:
+ return "string";
+ case value_t::boolean:
+ return "boolean";
+ case value_t::binary:
+ return "binary";
+ case value_t::discarded:
+ return "discarded";
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ default:
+ return "number";
+ }
+ }
+
+ JSON_PRIVATE_UNLESS_TESTED :
+ //////////////////////
+ // member variables //
+ //////////////////////
+
+ struct data {
+ /// the type of the current element
+ value_t m_type = value_t::null;
+
+ /// the value of the current element
+ json_value m_value = {};
+
+ data(const value_t v) : m_type(v), m_value(v) {}
+
+ data(size_type cnt, const basic_json& val) : m_type(value_t::array) {
+ m_value.array = create<array_t>(cnt, val);
+ }
+
+ data() noexcept = default;
+ data(data&&) noexcept = default;
+ data(const data&) noexcept = delete;
+ data&
+ operator=(data&&) noexcept = delete;
+ data&
+ operator=(const data&) noexcept = delete;
+
+ ~data() noexcept { m_value.destroy(m_type); }
+ };
+
+ data m_data = {};
+
+#if JSON_DIAGNOSTICS
+ /// a pointer to a parent value (for debugging purposes)
+ basic_json* m_parent = nullptr;
+#endif
+
+ //////////////////////////////////////////
+ // binary serialization/deserialization //
+ //////////////////////////////////////////
+
+ /// @name binary serialization/deserialization support
+ /// @{
+
+ public:
+ /// @brief create a CBOR serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
+ static std::vector<std::uint8_t>
+ to_cbor(const basic_json& j) {
+ std::vector<std::uint8_t> result;
+ to_cbor(j, result);
+ return result;
+ }
+
+ /// @brief create a CBOR serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
+ static void
+ to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o) {
+ binary_writer<std::uint8_t>(o).write_cbor(j);
+ }
+
+ /// @brief create a CBOR serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
+ static void
+ to_cbor(const basic_json& j, detail::output_adapter<char> o) {
+ binary_writer<char>(o).write_cbor(j);
+ }
+
+ /// @brief create a MessagePack serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
+ static std::vector<std::uint8_t>
+ to_msgpack(const basic_json& j) {
+ std::vector<std::uint8_t> result;
+ to_msgpack(j, result);
+ return result;
+ }
+
+ /// @brief create a MessagePack serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
+ static void
+ to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o) {
+ binary_writer<std::uint8_t>(o).write_msgpack(j);
+ }
+
+ /// @brief create a MessagePack serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
+ static void
+ to_msgpack(const basic_json& j, detail::output_adapter<char> o) {
+ binary_writer<char>(o).write_msgpack(j);
+ }
+
+ /// @brief create a UBJSON serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
+ static std::vector<std::uint8_t>
+ to_ubjson(const basic_json& j, const bool use_size = false, const bool use_type = false) {
+ std::vector<std::uint8_t> result;
+ to_ubjson(j, result, use_size, use_type);
+ return result;
+ }
+
+ /// @brief create a UBJSON serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
+ static void
+ to_ubjson(const basic_json& j,
+ detail::output_adapter<std::uint8_t> o,
+ const bool use_size = false,
+ const bool use_type = false) {
+ binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type);
+ }
+
+ /// @brief create a UBJSON serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
+ static void
+ to_ubjson(const basic_json& j,
+ detail::output_adapter<char> o,
+ const bool use_size = false,
+ const bool use_type = false) {
+ binary_writer<char>(o).write_ubjson(j, use_size, use_type);
+ }
+
+ /// @brief create a BJData serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/
+ static std::vector<std::uint8_t>
+ to_bjdata(const basic_json& j, const bool use_size = false, const bool use_type = false) {
+ std::vector<std::uint8_t> result;
+ to_bjdata(j, result, use_size, use_type);
+ return result;
+ }
+
+ /// @brief create a BJData serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/
+ static void
+ to_bjdata(const basic_json& j,
+ detail::output_adapter<std::uint8_t> o,
+ const bool use_size = false,
+ const bool use_type = false) {
+ binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type, true, true);
+ }
+
+ /// @brief create a BJData serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/
+ static void
+ to_bjdata(const basic_json& j,
+ detail::output_adapter<char> o,
+ const bool use_size = false,
+ const bool use_type = false) {
+ binary_writer<char>(o).write_ubjson(j, use_size, use_type, true, true);
+ }
+
+ /// @brief create a BSON serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
+ static std::vector<std::uint8_t>
+ to_bson(const basic_json& j) {
+ std::vector<std::uint8_t> result;
+ to_bson(j, result);
+ return result;
+ }
+
+ /// @brief create a BSON serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
+ static void
+ to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o) {
+ binary_writer<std::uint8_t>(o).write_bson(j);
+ }
+
+ /// @brief create a BSON serialization of a given JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
+ static void
+ to_bson(const basic_json& j, detail::output_adapter<char> o) {
+ binary_writer<char>(o).write_bson(j);
+ }
+
+ /// @brief create a JSON value from an input in CBOR format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
+ template <typename InputType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_cbor(InputType&& i,
+ const bool strict = true,
+ const bool allow_exceptions = true,
+ const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::forward<InputType>(i));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor)
+ .sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ /// @brief create a JSON value from an input in CBOR format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
+ template <typename IteratorType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_cbor(IteratorType first,
+ IteratorType last,
+ const bool strict = true,
+ const bool allow_exceptions = true,
+ const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::move(first), std::move(last));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor)
+ .sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ template <typename T>
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) static basic_json
+ from_cbor(const T* ptr,
+ std::size_t len,
+ const bool strict = true,
+ const bool allow_exceptions = true,
+ const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) {
+ return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler);
+ }
+
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
+ static basic_json
+ from_cbor(detail::span_input_adapter&& i,
+ const bool strict = true,
+ const bool allow_exceptions = true,
+ const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = i.get();
+ // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor)
+ .sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ /// @brief create a JSON value from an input in MessagePack format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
+ template <typename InputType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_msgpack(InputType&& i, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::forward<InputType>(i));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack)
+ .sax_parse(input_format_t::msgpack, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ /// @brief create a JSON value from an input in MessagePack format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
+ template <typename IteratorType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_msgpack(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::move(first), std::move(last));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack)
+ .sax_parse(input_format_t::msgpack, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ template <typename T>
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) static basic_json
+ from_msgpack(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) {
+ return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
+ }
+
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
+ static basic_json
+ from_msgpack(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = i.get();
+ // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack)
+ .sax_parse(input_format_t::msgpack, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ /// @brief create a JSON value from an input in UBJSON format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
+ template <typename InputType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_ubjson(InputType&& i, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::forward<InputType>(i));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson)
+ .sax_parse(input_format_t::ubjson, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ /// @brief create a JSON value from an input in UBJSON format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
+ template <typename IteratorType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_ubjson(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::move(first), std::move(last));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson)
+ .sax_parse(input_format_t::ubjson, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ template <typename T>
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) static basic_json
+ from_ubjson(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) {
+ return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
+ }
+
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
+ static basic_json
+ from_ubjson(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = i.get();
+ // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson)
+ .sax_parse(input_format_t::ubjson, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ /// @brief create a JSON value from an input in BJData format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_bjdata/
+ template <typename InputType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_bjdata(InputType&& i, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::forward<InputType>(i));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata)
+ .sax_parse(input_format_t::bjdata, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ /// @brief create a JSON value from an input in BJData format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_bjdata/
+ template <typename IteratorType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_bjdata(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::move(first), std::move(last));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata)
+ .sax_parse(input_format_t::bjdata, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ /// @brief create a JSON value from an input in BSON format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
+ template <typename InputType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_bson(InputType&& i, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::forward<InputType>(i));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson)
+ .sax_parse(input_format_t::bson, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ /// @brief create a JSON value from an input in BSON format
+ /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
+ template <typename IteratorType>
+ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json
+ from_bson(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = detail::input_adapter(std::move(first), std::move(last));
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson)
+ .sax_parse(input_format_t::bson, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+
+ template <typename T>
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) static basic_json
+ from_bson(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) {
+ return from_bson(ptr, ptr + len, strict, allow_exceptions);
+ }
+
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
+ static basic_json
+ from_bson(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) {
+ basic_json result;
+ detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+ auto ia = i.get();
+ // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+ const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson)
+ .sax_parse(input_format_t::bson, &sdp, strict);
+ return res ? result : basic_json(value_t::discarded);
+ }
+ /// @}
+
+ //////////////////////////
+ // JSON Pointer support //
+ //////////////////////////
+
+ /// @name JSON Pointer functions
+ /// @{
+
+ /// @brief access specified element via JSON Pointer
+ /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+ reference
+ operator[](const json_pointer& ptr) {
+ return ptr.get_unchecked(this);
+ }
+
+ template <typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0,
+ basic_json::json_pointer or
+ nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
+ reference
+ operator[](const ::nlohmann::json_pointer<BasicJsonType>& ptr) {
+ return ptr.get_unchecked(this);
+ }
+
+ /// @brief access specified element via JSON Pointer
+ /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+ const_reference
+ operator[](const json_pointer& ptr) const {
+ return ptr.get_unchecked(this);
+ }
+
+ template <typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0,
+ basic_json::json_pointer or
+ nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
+ const_reference
+ operator[](const ::nlohmann::json_pointer<BasicJsonType>& ptr) const {
+ return ptr.get_unchecked(this);
+ }
+
+ /// @brief access specified element via JSON Pointer
+ /// @sa https://json.nlohmann.me/api/basic_json/at/
+ reference
+ at(const json_pointer& ptr) {
+ return ptr.get_checked(this);
+ }
+
+ template <typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0,
+ basic_json::json_pointer or
+ nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
+ reference at(const ::nlohmann::json_pointer<BasicJsonType>& ptr) {
+ return ptr.get_checked(this);
+ }
+
+ /// @brief access specified element via JSON Pointer
+ /// @sa https://json.nlohmann.me/api/basic_json/at/
+ const_reference
+ at(const json_pointer& ptr) const {
+ return ptr.get_checked(this);
+ }
+
+ template <typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
+ JSON_HEDLEY_DEPRECATED_FOR(3.11.0,
+ basic_json::json_pointer or
+ nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
+ const_reference at(const ::nlohmann::json_pointer<BasicJsonType>& ptr) const {
+ return ptr.get_checked(this);
+ }
+
+ /// @brief return flattened JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/flatten/
+ basic_json
+ flatten() const {
+ basic_json result(value_t::object);
+ json_pointer::flatten("", *this, result);
+ return result;
+ }
+
+ /// @brief unflatten a previously flattened JSON value
+ /// @sa https://json.nlohmann.me/api/basic_json/unflatten/
+ basic_json
+ unflatten() const {
+ return json_pointer::unflatten(*this);
+ }
+
+ /// @}
+
+ //////////////////////////
+ // JSON Patch functions //
+ //////////////////////////
+
+ /// @name JSON Patch functions
+ /// @{
+
+ /// @brief applies a JSON patch in-place without copying the object
+ /// @sa https://json.nlohmann.me/api/basic_json/patch/
+ void
+ patch_inplace(const basic_json& json_patch) {
+ basic_json& result = *this;
+ // the valid JSON Patch operations
+ enum class patch_operations { add, remove, replace, move, copy, test, invalid };
+
+ const auto get_op = [](const std::string& op) {
+ if (op == "add") {
+ return patch_operations::add;
+ }
+ if (op == "remove") {
+ return patch_operations::remove;
+ }
+ if (op == "replace") {
+ return patch_operations::replace;
+ }
+ if (op == "move") {
+ return patch_operations::move;
+ }
+ if (op == "copy") {
+ return patch_operations::copy;
+ }
+ if (op == "test") {
+ return patch_operations::test;
+ }
+
+ return patch_operations::invalid;
+ };
+
+ // wrapper for "add" operation; add value at ptr
+ const auto operation_add = [&result](json_pointer& ptr, basic_json val) {
+ // adding to the root of the target document means replacing it
+ if (ptr.empty()) {
+ result = val;
+ return;
+ }
+
+ // make sure the top element of the pointer exists
+ json_pointer const top_pointer = ptr.top();
+ if (top_pointer != ptr) {
+ result.at(top_pointer);
+ }
+
+ // get reference to parent of JSON pointer ptr
+ const auto last_path = ptr.back();
+ ptr.pop_back();
+ // parent must exist when performing patch add per RFC6902 specs
+ basic_json& parent = result.at(ptr);
+
+ switch (parent.m_data.m_type) {
+ case value_t::null:
+ case value_t::object: {
+ // use operator[] to add value
+ parent[last_path] = val;
+ break;
+ }
+
+ case value_t::array: {
+ if (last_path == "-") {
+ // special case: append to back
+ parent.push_back(val);
+ } else {
+ const auto idx = json_pointer::template array_index<basic_json_t>(last_path);
+ if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) {
+ // avoid undefined behavior
+ JSON_THROW(out_of_range::create(
+ 401, detail::concat("array index ", std::to_string(idx), " is out of range"), &parent));
+ }
+
+ // default case: insert add offset
+ parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
+ }
+ break;
+ }
+
+ // if there exists a parent it cannot be primitive
+ case value_t::string: // LCOV_EXCL_LINE
+ case value_t::boolean: // LCOV_EXCL_LINE
+ case value_t::number_integer: // LCOV_EXCL_LINE
+ case value_t::number_unsigned: // LCOV_EXCL_LINE
+ case value_t::number_float: // LCOV_EXCL_LINE
+ case value_t::binary: // LCOV_EXCL_LINE
+ case value_t::discarded: // LCOV_EXCL_LINE
+ default: // LCOV_EXCL_LINE
+ JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+ }
+ };
+
+ // wrapper for "remove" operation; remove value at ptr
+ const auto operation_remove = [this, &result](json_pointer& ptr) {
+ // get reference to parent of JSON pointer ptr
+ const auto last_path = ptr.back();
+ ptr.pop_back();
+ basic_json& parent = result.at(ptr);
+
+ // remove child
+ if (parent.is_object()) {
+ // perform range check
+ auto it = parent.find(last_path);
+ if (JSON_HEDLEY_LIKELY(it != parent.end())) {
+ parent.erase(it);
+ } else {
+ JSON_THROW(out_of_range::create(403, detail::concat("key '", last_path, "' not found"), this));
+ }
+ } else if (parent.is_array()) {
+ // note erase performs range check
+ parent.erase(json_pointer::template array_index<basic_json_t>(last_path));
+ }
+ };
+
+ // type check: top level value must be an array
+ if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) {
+ JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", &json_patch));
+ }
+
+ // iterate and apply the operations
+ for (const auto& val : json_patch) {
+ // wrapper to get a value for an operation
+ const auto get_value =
+ [&val](const std::string& op, const std::string& member, bool string_type) -> basic_json& {
+ // find value
+ auto it = val.m_data.m_value.object->find(member);
+
+ // context-sensitive error message
+ const auto error_msg = (op == "op") ? "operation" : detail::concat("operation '", op, '\'');
+
+ // check if desired value is present
+ if (JSON_HEDLEY_UNLIKELY(it == val.m_data.m_value.object->end())) {
+ // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
+ JSON_THROW(parse_error::create(
+ 105, 0, detail::concat(error_msg, " must have member '", member, "'"), &val));
+ }
+
+ // check if result is of type string
+ if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) {
+ // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
+ JSON_THROW(parse_error::create(
+ 105, 0, detail::concat(error_msg, " must have string member '", member, "'"), &val));
+ }
+
+ // no error: return value
+ return it->second;
+ };
+
+ // type check: every element of the array must be an object
+ if (JSON_HEDLEY_UNLIKELY(!val.is_object())) {
+ JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", &val));
+ }
+
+ // collect mandatory members
+ const auto op = get_value("op", "op", true).template get<std::string>();
+ const auto path = get_value(op, "path", true).template get<std::string>();
+ json_pointer ptr(path);
+
+ switch (get_op(op)) {
+ case patch_operations::add: {
+ operation_add(ptr, get_value("add", "value", false));
+ break;
+ }
+
+ case patch_operations::remove: {
+ operation_remove(ptr);
+ break;
+ }
+
+ case patch_operations::replace: {
+ // the "path" location must exist - use at()
+ result.at(ptr) = get_value("replace", "value", false);
+ break;
+ }
+
+ case patch_operations::move: {
+ const auto from_path = get_value("move", "from", true).template get<std::string>();
+ json_pointer from_ptr(from_path);
+
+ // the "from" location must exist - use at()
+ basic_json const v = result.at(from_ptr);
+
+ // The move operation is functionally identical to a
+ // "remove" operation on the "from" location, followed
+ // immediately by an "add" operation at the target
+ // location with the value that was just removed.
+ operation_remove(from_ptr);
+ operation_add(ptr, v);
+ break;
+ }
+
+ case patch_operations::copy: {
+ const auto from_path = get_value("copy", "from", true).template get<std::string>();
+ const json_pointer from_ptr(from_path);
+
+ // the "from" location must exist - use at()
+ basic_json const v = result.at(from_ptr);
+
+ // The copy is functionally identical to an "add"
+ // operation at the target location using the value
+ // specified in the "from" member.
+ operation_add(ptr, v);
+ break;
+ }
+
+ case patch_operations::test: {
+ bool success = false;
+ JSON_TRY {
+ // check if "value" matches the one at "path"
+ // the "path" location must exist - use at()
+ success = (result.at(ptr) == get_value("test", "value", false));
+ }
+ JSON_INTERNAL_CATCH(out_of_range&) {
+ // ignore out of range errors: success remains false
+ }
+
+ // throw an exception if test fails
+ if (JSON_HEDLEY_UNLIKELY(!success)) {
+ JSON_THROW(other_error::create(501, detail::concat("unsuccessful: ", val.dump()), &val));
+ }
+
+ break;
+ }
+
+ case patch_operations::invalid:
+ default: {
+ // op must be "add", "remove", "replace", "move", "copy", or
+ // "test"
+ JSON_THROW(
+ parse_error::create(105, 0, detail::concat("operation value '", op, "' is invalid"), &val));
+ }
+ }
+ }
+ }
+
+ /// @brief applies a JSON patch to a copy of the current object
+ /// @sa https://json.nlohmann.me/api/basic_json/patch/
+ basic_json
+ patch(const basic_json& json_patch) const {
+ basic_json result = *this;
+ result.patch_inplace(json_patch);
+ return result;
+ }
+
+ /// @brief creates a diff as a JSON patch
+ /// @sa https://json.nlohmann.me/api/basic_json/diff/
+ JSON_HEDLEY_WARN_UNUSED_RESULT
+ static basic_json
+ diff(const basic_json& source, const basic_json& target, const std::string& path = "") {
+ // the patch
+ basic_json result(value_t::array);
+
+ // if the values are the same, return empty patch
+ if (source == target) {
+ return result;
+ }
+
+ if (source.type() != target.type()) {
+ // different types: replace value
+ result.push_back({{"op", "replace"}, {"path", path}, {"value", target}});
+ return result;
+ }
+
+ switch (source.type()) {
+ case value_t::array: {
+ // first pass: traverse common elements
+ std::size_t i = 0;
+ while (i < source.size() && i < target.size()) {
+ // recursive call to compare array values at index i
+ auto temp_diff = diff(source[i], target[i], detail::concat(path, '/', std::to_string(i)));
+ result.insert(result.end(), temp_diff.begin(), temp_diff.end());
+ ++i;
+ }
+
+ // We now reached the end of at least one array
+ // in a second pass, traverse the remaining elements
+
+ // remove my remaining elements
+ const auto end_index = static_cast<difference_type>(result.size());
+ while (i < source.size()) {
+ // add operations in reverse order to avoid invalid
+ // indices
+ result.insert(result.begin() + end_index,
+ object({{"op", "remove"}, {"path", detail::concat(path, '/', std::to_string(i))}}));
+ ++i;
+ }
+
+ // add other remaining elements
+ while (i < target.size()) {
+ result.push_back({{"op", "add"}, {"path", detail::concat(path, "/-")}, {"value", target[i]}});
+ ++i;
+ }
+
+ break;
+ }
+
+ case value_t::object: {
+ // first pass: traverse this object's elements
+ for (auto it = source.cbegin(); it != source.cend(); ++it) {
+ // escape the key name to be used in a JSON patch
+ const auto path_key = detail::concat(path, '/', detail::escape(it.key()));
+
+ if (target.find(it.key()) != target.end()) {
+ // recursive call to compare object values at key it
+ auto temp_diff = diff(it.value(), target[it.key()], path_key);
+ result.insert(result.end(), temp_diff.begin(), temp_diff.end());
+ } else {
+ // found a key that is not in o -> remove it
+ result.push_back(object({{"op", "remove"}, {"path", path_key}}));
+ }
+ }
+
+ // second pass: traverse other object's elements
+ for (auto it = target.cbegin(); it != target.cend(); ++it) {
+ if (source.find(it.key()) == source.end()) {
+ // found a key that is not in this -> add it
+ const auto path_key = detail::concat(path, '/', detail::escape(it.key()));
+ result.push_back({{"op", "add"}, {"path", path_key}, {"value", it.value()}});
+ }
+ }
+
+ break;
+ }
+
+ case value_t::null:
+ case value_t::string:
+ case value_t::boolean:
+ case value_t::number_integer:
+ case value_t::number_unsigned:
+ case value_t::number_float:
+ case value_t::binary:
+ case value_t::discarded:
+ default: {
+ // both primitive type: replace value
+ result.push_back({{"op", "replace"}, {"path", path}, {"value", target}});
+ break;
+ }
+ }
+
+ return result;
+ }
+ /// @}
+
+ ////////////////////////////////
+ // JSON Merge Patch functions //
+ ////////////////////////////////
+
+ /// @name JSON Merge Patch functions
+ /// @{
+
+ /// @brief applies a JSON Merge Patch
+ /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/
+ void
+ merge_patch(const basic_json& apply_patch) {
+ if (apply_patch.is_object()) {
+ if (!is_object()) {
+ *this = object();
+ }
+ for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) {
+ if (it.value().is_null()) {
+ erase(it.key());
+ } else {
+ operator[](it.key()).merge_patch(it.value());
+ }
+ }
+ } else {
+ *this = apply_patch;
+ }
+ }
+
+ /// @}
+};
+
+/// @brief user-defined to_string function for JSON values
+/// @sa https://json.nlohmann.me/api/basic_json/to_string/
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+std::string
+to_string(const NLOHMANN_BASIC_JSON_TPL& j) {
+ return j.dump();
+}
+
+inline namespace literals {
+inline namespace json_literals {
+
+/// @brief user-defined string literal for JSON values
+/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/
+JSON_HEDLEY_NON_NULL(1)
+#if !defined(JSON_HEDLEY_GCC_VERSION) || JSON_HEDLEY_GCC_VERSION_CHECK(4, 9, 0)
+inline nlohmann::json
+operator""_json(const char* s, std::size_t n)
+#else
+inline nlohmann::json
+operator"" _json(const char* s, std::size_t n)
+#endif
+{
+ return nlohmann::json::parse(s, s + n);
+}
+
+/// @brief user-defined string literal for JSON pointer
+/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/
+JSON_HEDLEY_NON_NULL(1)
+#if !defined(JSON_HEDLEY_GCC_VERSION) || JSON_HEDLEY_GCC_VERSION_CHECK(4, 9, 0)
+inline nlohmann::json::json_pointer
+operator""_json_pointer(const char* s, std::size_t n)
+#else
+inline nlohmann::json::json_pointer
+operator"" _json_pointer(const char* s, std::size_t n)
+#endif
+{
+ return nlohmann::json::json_pointer(std::string(s, n));
+}
+
+} // namespace json_literals
+} // namespace literals
+NLOHMANN_JSON_NAMESPACE_END
+
+///////////////////////
+// nonmember support //
+///////////////////////
+
+namespace std // NOLINT(cert-dcl58-cpp)
+{
+
+/// @brief hash value for JSON objects
+/// @sa https://json.nlohmann.me/api/basic_json/std_hash/
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+struct hash<nlohmann::NLOHMANN_BASIC_JSON_TPL> // NOLINT(cert-dcl58-cpp)
+{
+ std::size_t
+ operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const {
+ return nlohmann::detail::hash(j);
+ }
+};
+
+// specialization for std::less<value_t>
+template <>
+struct less<::nlohmann::detail::value_t> // do not remove the space after '<', see
+ // https://github.com/nlohmann/json/pull/679
+{
+ /*!
+ @brief compare two value_t enum values
+ @since version 3.0.0
+ */
+ bool
+ operator()(::nlohmann::detail::value_t lhs, ::nlohmann::detail::value_t rhs) const noexcept {
+#if JSON_HAS_THREE_WAY_COMPARISON
+ return std::is_lt(lhs <=> rhs); // *NOPAD*
+#else
+ return ::nlohmann::detail::operator<(lhs, rhs);
+#endif
+ }
+};
+
+// C++20 prohibit function specialization in the std namespace.
+#ifndef JSON_HAS_CPP_20
+
+/// @brief exchanges the values of two JSON objects
+/// @sa https://json.nlohmann.me/api/basic_json/std_swap/
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+inline void
+swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1,
+ nlohmann::NLOHMANN_BASIC_JSON_TPL&
+ j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name, cert-dcl58-cpp)
+ is_nothrow_move_constructible<nlohmann::NLOHMANN_BASIC_JSON_TPL>::
+ value && // NOLINT(misc-redundant-expression,cppcoreguidelines-noexcept-swap,performance-noexcept-swap)
+ is_nothrow_move_assignable<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value) {
+ j1.swap(j2);
+}
+
+#endif
+
+} // namespace std
+
+#if JSON_USE_GLOBAL_UDLS
+#if !defined(JSON_HEDLEY_GCC_VERSION) || JSON_HEDLEY_GCC_VERSION_CHECK(4, 9, 0)
+using nlohmann::literals::json_literals::
+operator""_json; // NOLINT(misc-unused-using-decls,google-global-names-in-headers)
+using nlohmann::literals::json_literals::
+operator""_json_pointer; // NOLINT(misc-unused-using-decls,google-global-names-in-headers)
+#else
+using nlohmann::literals::json_literals::
+operator"" _json; // NOLINT(misc-unused-using-decls,google-global-names-in-headers)
+using nlohmann::literals::json_literals::
+operator"" _json_pointer; // NOLINT(misc-unused-using-decls,google-global-names-in-headers)
+#endif
+#endif
+
+// #include <nlohmann/detail/macro_unscope.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+// restore clang diagnostic settings
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+// clean up
+#undef JSON_ASSERT
+#undef JSON_INTERNAL_CATCH
+#undef JSON_THROW
+#undef JSON_PRIVATE_UNLESS_TESTED
+#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
+#undef NLOHMANN_BASIC_JSON_TPL
+#undef JSON_EXPLICIT
+#undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL
+#undef JSON_INLINE_VARIABLE
+#undef JSON_NO_UNIQUE_ADDRESS
+#undef JSON_DISABLE_ENUM_SERIALIZATION
+#undef JSON_USE_GLOBAL_UDLS
+
+#ifndef JSON_TEST_KEEP_MACROS
+#undef JSON_CATCH
+#undef JSON_TRY
+#undef JSON_HAS_CPP_11
+#undef JSON_HAS_CPP_14
+#undef JSON_HAS_CPP_17
+#undef JSON_HAS_CPP_20
+#undef JSON_HAS_FILESYSTEM
+#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#undef JSON_HAS_THREE_WAY_COMPARISON
+#undef JSON_HAS_RANGES
+#undef JSON_HAS_STATIC_RTTI
+#undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
+#endif
+
+// #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
+// __ _____ _____ _____
+// __| | __| | | | JSON for Modern C++
+// | | |__ | | | | | | version 3.11.3
+// |_____|_____|_____|_|___| https://github.com/nlohmann/json
+//
+// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann <https://nlohmann.me>
+// SPDX-License-Identifier: MIT
+
+#undef JSON_HEDLEY_ALWAYS_INLINE
+#undef JSON_HEDLEY_ARM_VERSION
+#undef JSON_HEDLEY_ARM_VERSION_CHECK
+#undef JSON_HEDLEY_ARRAY_PARAM
+#undef JSON_HEDLEY_ASSUME
+#undef JSON_HEDLEY_BEGIN_C_DECLS
+#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_CLANG_HAS_BUILTIN
+#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_CLANG_HAS_EXTENSION
+#undef JSON_HEDLEY_CLANG_HAS_FEATURE
+#undef JSON_HEDLEY_CLANG_HAS_WARNING
+#undef JSON_HEDLEY_COMPCERT_VERSION
+#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
+#undef JSON_HEDLEY_CONCAT
+#undef JSON_HEDLEY_CONCAT3
+#undef JSON_HEDLEY_CONCAT3_EX
+#undef JSON_HEDLEY_CONCAT_EX
+#undef JSON_HEDLEY_CONST
+#undef JSON_HEDLEY_CONSTEXPR
+#undef JSON_HEDLEY_CONST_CAST
+#undef JSON_HEDLEY_CPP_CAST
+#undef JSON_HEDLEY_CRAY_VERSION
+#undef JSON_HEDLEY_CRAY_VERSION_CHECK
+#undef JSON_HEDLEY_C_DECL
+#undef JSON_HEDLEY_DEPRECATED
+#undef JSON_HEDLEY_DEPRECATED_FOR
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
+#undef JSON_HEDLEY_DIAGNOSTIC_POP
+#undef JSON_HEDLEY_DIAGNOSTIC_PUSH
+#undef JSON_HEDLEY_DMC_VERSION
+#undef JSON_HEDLEY_DMC_VERSION_CHECK
+#undef JSON_HEDLEY_EMPTY_BASES
+#undef JSON_HEDLEY_EMSCRIPTEN_VERSION
+#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
+#undef JSON_HEDLEY_END_C_DECLS
+#undef JSON_HEDLEY_FLAGS
+#undef JSON_HEDLEY_FLAGS_CAST
+#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_GCC_HAS_BUILTIN
+#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_GCC_HAS_EXTENSION
+#undef JSON_HEDLEY_GCC_HAS_FEATURE
+#undef JSON_HEDLEY_GCC_HAS_WARNING
+#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
+#undef JSON_HEDLEY_GCC_VERSION
+#undef JSON_HEDLEY_GCC_VERSION_CHECK
+#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_GNUC_HAS_BUILTIN
+#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_GNUC_HAS_EXTENSION
+#undef JSON_HEDLEY_GNUC_HAS_FEATURE
+#undef JSON_HEDLEY_GNUC_HAS_WARNING
+#undef JSON_HEDLEY_GNUC_VERSION
+#undef JSON_HEDLEY_GNUC_VERSION_CHECK
+#undef JSON_HEDLEY_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_HAS_BUILTIN
+#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
+#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_HAS_EXTENSION
+#undef JSON_HEDLEY_HAS_FEATURE
+#undef JSON_HEDLEY_HAS_WARNING
+#undef JSON_HEDLEY_IAR_VERSION
+#undef JSON_HEDLEY_IAR_VERSION_CHECK
+#undef JSON_HEDLEY_IBM_VERSION
+#undef JSON_HEDLEY_IBM_VERSION_CHECK
+#undef JSON_HEDLEY_IMPORT
+#undef JSON_HEDLEY_INLINE
+#undef JSON_HEDLEY_INTEL_CL_VERSION
+#undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
+#undef JSON_HEDLEY_INTEL_VERSION
+#undef JSON_HEDLEY_INTEL_VERSION_CHECK
+#undef JSON_HEDLEY_IS_CONSTANT
+#undef JSON_HEDLEY_IS_CONSTEXPR_
+#undef JSON_HEDLEY_LIKELY
+#undef JSON_HEDLEY_MALLOC
+#undef JSON_HEDLEY_MCST_LCC_VERSION
+#undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
+#undef JSON_HEDLEY_MESSAGE
+#undef JSON_HEDLEY_MSVC_VERSION
+#undef JSON_HEDLEY_MSVC_VERSION_CHECK
+#undef JSON_HEDLEY_NEVER_INLINE
+#undef JSON_HEDLEY_NON_NULL
+#undef JSON_HEDLEY_NO_ESCAPE
+#undef JSON_HEDLEY_NO_RETURN
+#undef JSON_HEDLEY_NO_THROW
+#undef JSON_HEDLEY_NULL
+#undef JSON_HEDLEY_PELLES_VERSION
+#undef JSON_HEDLEY_PELLES_VERSION_CHECK
+#undef JSON_HEDLEY_PGI_VERSION
+#undef JSON_HEDLEY_PGI_VERSION_CHECK
+#undef JSON_HEDLEY_PREDICT
+#undef JSON_HEDLEY_PRINTF_FORMAT
+#undef JSON_HEDLEY_PRIVATE
+#undef JSON_HEDLEY_PUBLIC
+#undef JSON_HEDLEY_PURE
+#undef JSON_HEDLEY_REINTERPRET_CAST
+#undef JSON_HEDLEY_REQUIRE
+#undef JSON_HEDLEY_REQUIRE_CONSTEXPR
+#undef JSON_HEDLEY_REQUIRE_MSG
+#undef JSON_HEDLEY_RESTRICT
+#undef JSON_HEDLEY_RETURNS_NON_NULL
+#undef JSON_HEDLEY_SENTINEL
+#undef JSON_HEDLEY_STATIC_ASSERT
+#undef JSON_HEDLEY_STATIC_CAST
+#undef JSON_HEDLEY_STRINGIFY
+#undef JSON_HEDLEY_STRINGIFY_EX
+#undef JSON_HEDLEY_SUNPRO_VERSION
+#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
+#undef JSON_HEDLEY_TINYC_VERSION
+#undef JSON_HEDLEY_TINYC_VERSION_CHECK
+#undef JSON_HEDLEY_TI_ARMCL_VERSION
+#undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CL2000_VERSION
+#undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CL430_VERSION
+#undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CL6X_VERSION
+#undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CL7X_VERSION
+#undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CLPRU_VERSION
+#undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
+#undef JSON_HEDLEY_TI_VERSION
+#undef JSON_HEDLEY_TI_VERSION_CHECK
+#undef JSON_HEDLEY_UNAVAILABLE
+#undef JSON_HEDLEY_UNLIKELY
+#undef JSON_HEDLEY_UNPREDICTABLE
+#undef JSON_HEDLEY_UNREACHABLE
+#undef JSON_HEDLEY_UNREACHABLE_RETURN
+#undef JSON_HEDLEY_VERSION
+#undef JSON_HEDLEY_VERSION_DECODE_MAJOR
+#undef JSON_HEDLEY_VERSION_DECODE_MINOR
+#undef JSON_HEDLEY_VERSION_DECODE_REVISION
+#undef JSON_HEDLEY_VERSION_ENCODE
+#undef JSON_HEDLEY_WARNING
+#undef JSON_HEDLEY_WARN_UNUSED_RESULT
+#undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
+#undef JSON_HEDLEY_FALL_THROUGH
+
+#endif // INCLUDE_NLOHMANN_JSON_HPP_
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/utils/attn_score_modifiers.h b/deps/cudnn-frontend/include/cudnn_frontend/utils/attn_score_modifiers.h
new file mode 100644
index 0000000..a09e538
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/utils/attn_score_modifiers.h
@@ -0,0 +1,330 @@
+#pragma once
+
+#include "../graph_interface.h"
+#include "../../cudnn_frontend_shim.h"
+
+namespace cudnn_frontend::graph::attn::score_modifiers {
+
+[[maybe_unused]] inline float
+get_negative_inf_value() {
+ // older cuDNN version prefers lowest for softmax mask
+ if (detail::get_backend_version() < 91000) {
+ return std::numeric_limits<float>::lowest();
+ }
+ return -std::numeric_limits<float>::infinity();
+}
+
+[[maybe_unused]] inline std::shared_ptr<Tensor_attributes>
+causal_mask(std::shared_ptr<Graph> graph, std::shared_ptr<Tensor_attributes> attention_score) {
+ return sliding_window_mask(graph,
+ attention_score,
+ DiagonalAlignment_t::TOP_LEFT,
+ {}, // no left bound specified
+ 0, // right bound = 0
+ 0, // s_q does not matter for causal mask
+ 0, // s_kv does not matter for causal mask
+ nullptr, // s_q does not matter for causal mask
+ nullptr // s_kv does not matter for causal mask
+ );
+}
+
+[[maybe_unused]] inline std::shared_ptr<Tensor_attributes>
+causal_mask_bottom_right(std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ int64_t s_q,
+ int64_t s_kv,
+ std::shared_ptr<Tensor_attributes> seq_len_q,
+ std::shared_ptr<Tensor_attributes> seq_len_kv) {
+ return sliding_window_mask(graph,
+ attention_score,
+ DiagonalAlignment_t::BOTTOM_RIGHT,
+ {}, // no left bound specified
+ 0, // right bound = 0
+ s_q, // s_q dimension (max Q sequence length)
+ s_kv, // s_kv dimension (max KV sequence length)
+ std::move(seq_len_q), // Actual Q sequence lengths
+ std::move(seq_len_kv) // Actual KV sequence lengths
+ );
+}
+
+// Padding mask for the legacy CompositeSDPANode, not used in UnifiedSDPANode.
+// cu_seq_len_kv and cu_seq_len_q are explicitly not supported.
+[[maybe_unused]] inline std::shared_ptr<Tensor_attributes>
+padding_mask(std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ std::shared_ptr<Tensor_attributes> seq_len_kv,
+ std::shared_ptr<Tensor_attributes> seq_len_q) {
+ auto row_idx_output = graph->pointwise(attention_score,
+ Pointwise_attributes()
+ .set_name("gen_row_idx_padding")
+ .set_mode(PointwiseMode_t::GEN_INDEX)
+ .set_axis(2)
+ .set_compute_data_type(DataType_t::INT32));
+ row_idx_output->set_data_type(DataType_t::INT32);
+
+ auto col_idx_output = graph->pointwise(attention_score,
+ Pointwise_attributes()
+ .set_name("gen_col_idx_padding")
+ .set_mode(PointwiseMode_t::GEN_INDEX)
+ .set_axis(3)
+ .set_compute_data_type(DataType_t::INT32));
+ col_idx_output->set_data_type(DataType_t::INT32);
+
+ auto row_mask_output = graph->pointwise(row_idx_output,
+ seq_len_q,
+ Pointwise_attributes()
+ .set_name("lt_row_sq_padding")
+ .set_mode(PointwiseMode_t::CMP_LT)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ row_mask_output->set_data_type(DataType_t::BOOLEAN);
+
+ auto col_mask_output = graph->pointwise(col_idx_output,
+ seq_len_kv,
+ Pointwise_attributes()
+ .set_name("lt_col_skv_padding")
+ .set_mode(PointwiseMode_t::CMP_LT)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ col_mask_output->set_data_type(DataType_t::BOOLEAN);
+
+ auto padding_mask_output = graph->pointwise(row_mask_output,
+ col_mask_output,
+ Pointwise_attributes()
+ .set_name("and_row_col_padding")
+ .set_mode(PointwiseMode_t::LOGICAL_AND)
+ .set_compute_data_type(DataType_t::BOOLEAN));
+ padding_mask_output->set_data_type(DataType_t::BOOLEAN);
+ auto negative_inf_padding = std::make_shared<Tensor_attributes>(get_negative_inf_value());
+
+ auto after_padding_mask =
+ graph->pointwise(attention_score,
+ negative_inf_padding,
+ padding_mask_output,
+ Pointwise_attributes().set_name("select_padding").set_mode(PointwiseMode_t::BINARY_SELECT));
+
+ return after_padding_mask;
+}
+
+[[maybe_unused]] inline std::shared_ptr<Tensor_attributes>
+alibi_mask(std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ std::shared_ptr<Tensor_attributes>& alibi_slopes,
+ int64_t query_heads,
+ int64_t& alibi_slopes_size) {
+ auto row_idx_output = graph->pointwise(attention_score,
+ Pointwise_attributes()
+ .set_name("gen_row_idx_alibi")
+ .set_mode(PointwiseMode_t::GEN_INDEX)
+ .set_axis(2)
+ .set_compute_data_type(DataType_t::INT32));
+ row_idx_output->set_data_type(DataType_t::INT32);
+
+ auto col_idx_output = graph->pointwise(attention_score,
+ Pointwise_attributes()
+ .set_name("gen_col_idx_alibi")
+ .set_mode(PointwiseMode_t::GEN_INDEX)
+ .set_axis(3)
+ .set_compute_data_type(DataType_t::INT32));
+ col_idx_output->set_data_type(DataType_t::INT32);
+
+ auto sub_idx_output = graph->pointwise(col_idx_output,
+ row_idx_output,
+ Pointwise_attributes()
+ .set_name("sub_col_row_alibi")
+ .set_mode(PointwiseMode_t::SUB)
+ .set_compute_data_type(DataType_t::INT32));
+ sub_idx_output->set_data_type(DataType_t::INT32);
+
+ // Multiply by alibi slope
+ alibi_slopes = std::make_shared<Tensor_attributes>();
+ alibi_slopes->set_dim({1, query_heads, 1, 1}).set_stride({query_heads, 1, 1, 1}).set_data_type(DataType_t::FLOAT);
+ alibi_slopes_size = query_heads * sizeof(float);
+
+ auto alibi_mask_output =
+ graph->pointwise(sub_idx_output,
+ alibi_slopes,
+ Pointwise_attributes().set_name("mul_slope_alibi").set_mode(PointwiseMode_t::MUL));
+
+ auto after_alibi_mask =
+ graph->pointwise(attention_score,
+ alibi_mask_output,
+ Pointwise_attributes().set_name("add_alibi").set_mode(PointwiseMode_t::ADD));
+ return after_alibi_mask;
+}
+
+[[maybe_unused]] inline std::shared_ptr<Tensor_attributes>
+bias(std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ std::shared_ptr<Tensor_attributes> bias) {
+ auto bias_out = graph->pointwise(
+ attention_score, bias, Pointwise_attributes().set_name("bias_add").set_mode(PointwiseMode_t::ADD));
+
+ return bias_out;
+}
+
+[[maybe_unused]] inline std::shared_ptr<Tensor_attributes>
+sliding_window_mask(std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ DiagonalAlignment_t diagonal_alignment,
+ std::optional<int64_t> left_bound,
+ std::optional<int64_t> right_bound,
+ int64_t s_q,
+ int64_t s_kv,
+ std::shared_ptr<Tensor_attributes> s_q_ptr,
+ std::shared_ptr<Tensor_attributes> s_kv_ptr,
+ std::shared_ptr<Tensor_attributes> cu_s_q_ptr,
+ std::shared_ptr<Tensor_attributes> cu_s_kv_ptr) {
+ std::shared_ptr<Tensor_attributes> return_mask = attention_score;
+
+ // Note: the right and left bound subtrees can be constructed in different ways as well that yield functionally
+ // correct results. However, for performance reasons in the cuDNN backend they are organized as they are. Be
+ // cautious of performance when editing.
+
+ // Set the right bound
+ if (right_bound.has_value()) {
+ std::shared_ptr<Tensor_attributes> effective_s_q;
+ std::shared_ptr<Tensor_attributes> effective_s_kv;
+ std::shared_ptr<Tensor_attributes> effective_cu_s_q;
+ std::shared_ptr<Tensor_attributes> effective_cu_s_kv;
+ if (diagonal_alignment == DiagonalAlignment_t::BOTTOM_RIGHT) {
+ effective_s_q = s_q_ptr;
+ effective_s_kv = s_kv_ptr;
+ effective_cu_s_q = cu_s_q_ptr;
+ effective_cu_s_kv = cu_s_kv_ptr;
+ if (effective_s_q == nullptr && effective_cu_s_q == nullptr) {
+ effective_s_q = std::make_shared<Tensor_attributes>(static_cast<int32_t>(s_q));
+ }
+ if (effective_s_kv == nullptr && effective_cu_s_kv == nullptr) {
+ effective_s_kv = std::make_shared<Tensor_attributes>(static_cast<int32_t>(s_kv));
+ }
+ }
+
+ std::shared_ptr<Tensor_attributes> effective_shift_right_bound;
+ if (right_bound.value() != 0) {
+ effective_shift_right_bound =
+ std::make_shared<Tensor_attributes>(static_cast<int32_t>(right_bound.value()));
+ }
+
+ return_mask = graph->diagonal_band_mask(/*x=*/attention_score,
+ /*b=*/std::make_shared<Tensor_attributes>(get_negative_inf_value()),
+ /*seq_len_q=*/effective_s_q,
+ /*seq_len_kv=*/effective_s_kv,
+ /*cu_seq_len_q=*/effective_cu_s_q,
+ /*cu_seq_len_kv=*/effective_cu_s_kv,
+ /*left_bound=*/nullptr,
+ /*shift_right_bound=*/effective_shift_right_bound,
+ DiagonalBandMask_attributes()
+ .set_name("right_bound_diagonal_mask")
+ .set_comparison_mode(PointwiseMode_t::CMP_GE));
+ }
+
+ // Set the left bound
+ if (left_bound.has_value()) {
+ std::shared_ptr<Tensor_attributes> effective_left_bound;
+ std::shared_ptr<Tensor_attributes> effective_s_q;
+ std::shared_ptr<Tensor_attributes> effective_s_kv;
+ std::shared_ptr<Tensor_attributes> effective_cu_s_q;
+ std::shared_ptr<Tensor_attributes> effective_cu_s_kv;
+
+ // When the diagonal is top left aligned: setup a graph so we can compare column + window_size > row
+ // All elements for which column + window_size > row, will be retained, all others will be masked out
+ // Note that here and following sections, row refers to the s_q index and column refers to the s_kv index in
+ // the s_q x s_kv masking matrix
+ if (diagonal_alignment == DiagonalAlignment_t::TOP_LEFT) {
+ // sliding window length parameter should be of float type
+ effective_left_bound = std::make_shared<Tensor_attributes>((float)left_bound.value());
+ }
+ // With bottom right diagonal alignment, we need to shift the diagonal.
+ // Setup a graph so we can compare column + window_size - (s_kv - s_q) > row
+ // Optimization with fixed sequence lengths: single pointwise addition for the left-hand of the comparison
+ // Again, all elements satisfying the comparison will be retained.
+ else if (s_kv_ptr == nullptr && s_q_ptr == nullptr && cu_s_kv_ptr == nullptr && cu_s_q_ptr == nullptr) {
+ effective_left_bound = std::make_shared<Tensor_attributes>((float)(left_bound.value() - s_kv + s_q));
+ }
+ // With bottom right diagonal alignment: general case when at least one of Q and KV have variable sequence
+ // lengths.
+ // Setup a graph so we can compare column + window_size - (s_k[i] - s_q[i]) > row for each batch i
+ // Also here, all elements satisfying the comparison will be retained.
+ else {
+ effective_left_bound = std::make_shared<Tensor_attributes>((int32_t)left_bound.value());
+ effective_s_q = s_q_ptr;
+ effective_s_kv = s_kv_ptr;
+ effective_cu_s_q = cu_s_q_ptr;
+ effective_cu_s_kv = cu_s_kv_ptr;
+ if (effective_s_q == nullptr && effective_cu_s_q == nullptr) {
+ effective_s_q = std::make_shared<Tensor_attributes>(static_cast<int32_t>(s_q));
+ }
+ if (effective_s_kv == nullptr && effective_cu_s_kv == nullptr) {
+ effective_s_kv = std::make_shared<Tensor_attributes>(static_cast<int32_t>(s_kv));
+ }
+ }
+
+ return_mask = graph->diagonal_band_mask(/*x=*/return_mask,
+ /*b=*/std::make_shared<Tensor_attributes>(get_negative_inf_value()),
+ /*seq_len_q=*/effective_s_q,
+ /*seq_len_kv=*/effective_s_kv,
+ /*cu_seq_len_q=*/effective_cu_s_q,
+ /*cu_seq_len_kv=*/effective_cu_s_kv,
+ /*left_bound=*/effective_left_bound,
+ /*shift_right_bound=*/nullptr,
+ DiagonalBandMask_attributes()
+ .set_name("left_bound_diagonal_mask")
+ .set_comparison_mode(PointwiseMode_t::CMP_GT));
+ }
+
+ return return_mask;
+}
+
+[[maybe_unused]] inline error_t
+build_operation_subgraph(std::shared_ptr<Graph> graph) {
+ return graph->build_operation_graph(/*handle=*/nullptr);
+}
+
+class Softcap {
+ private:
+ // saved tensors in fprop to be used in bprop
+
+ std::shared_ptr<Tensor_attributes> before_tanh_activation;
+
+ public:
+ std::shared_ptr<Tensor_attributes>
+ forward(std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ std::shared_ptr<Tensor_attributes> soft_cap_scalar) {
+ before_tanh_activation =
+ graph->pointwise(attention_score,
+ soft_cap_scalar,
+ Pointwise_attributes().set_name("div_by_soft_cap").set_mode(PointwiseMode_t::DIV));
+
+ auto tanh_out = graph->pointwise(
+ before_tanh_activation, Pointwise_attributes().set_name("activation").set_mode(PointwiseMode_t::TANH_FWD));
+
+ auto out = graph->pointwise(tanh_out,
+ soft_cap_scalar,
+ Pointwise_attributes().set_name("mul_by_soft_cap").set_mode(PointwiseMode_t::MUL));
+
+ return out;
+ }
+
+ std::shared_ptr<Tensor_attributes>
+ backward(std::shared_ptr<Graph> graph,
+ std::shared_ptr<Tensor_attributes> attention_score,
+ std::shared_ptr<Tensor_attributes> soft_cap_scalar) {
+ auto mul_out =
+ graph->pointwise(attention_score,
+ soft_cap_scalar,
+ Pointwise_attributes().set_name("mul_by_soft_cap_bprop").set_mode(PointwiseMode_t::MUL));
+
+ auto tanh_out = graph->pointwise(mul_out,
+ before_tanh_activation,
+ Pointwise_attributes().set_name("dtanh").set_mode(PointwiseMode_t::TANH_BWD));
+
+ auto out =
+ graph->pointwise(tanh_out,
+ soft_cap_scalar,
+ Pointwise_attributes().set_name("div_by_soft_cap_bprop").set_mode(PointwiseMode_t::DIV));
+
+ return out;
+ }
+};
+
+} // namespace cudnn_frontend::graph::attn::score_modifiers \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/utils/serialize.h b/deps/cudnn-frontend/include/cudnn_frontend/utils/serialize.h
new file mode 100644
index 0000000..a9061ff
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/utils/serialize.h
@@ -0,0 +1,677 @@
+#pragma once
+
+#include "../graph_properties.h"
+#include "../graph_helpers.h"
+
+namespace cudnn_frontend::graph {
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+NLOHMANN_JSON_SERIALIZE_ENUM(BN_finalize_attributes::input_names,
+ {
+ {BN_finalize_attributes::input_names::SUM, "SUM"},
+ {BN_finalize_attributes::input_names::SQ_SUM, "SQ_SUM"},
+ {BN_finalize_attributes::input_names::SCALE, "SCALE"},
+ {BN_finalize_attributes::input_names::BIAS, "BIAS"},
+ {BN_finalize_attributes::input_names::EPSILON, "EPSILON"},
+ {BN_finalize_attributes::input_names::ACCUM_COUNT, "ACCUM_COUNT"},
+ {BN_finalize_attributes::input_names::PREV_RUNNING_MEAN, "PREV_RUNNING_MEAN"},
+ {BN_finalize_attributes::input_names::PREV_RUNNING_VAR, "PREV_RUNNING_VAR"},
+ {BN_finalize_attributes::input_names::MOMENTUM, "MOMENTUM"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(BN_finalize_attributes::output_names,
+ {
+ {BN_finalize_attributes::output_names::EQ_SCALE, "EQ_SCALE"},
+ {BN_finalize_attributes::output_names::EQ_BIAS, "EQ_BIAS"},
+ {BN_finalize_attributes::output_names::MEAN, "MEAN"},
+ {BN_finalize_attributes::output_names::INV_VARIANCE, "INV_VARIANCE"},
+ {BN_finalize_attributes::output_names::NEXT_RUNNING_MEAN, "NEXT_RUNNING_MEAN"},
+ {BN_finalize_attributes::output_names::NEXT_RUNNING_VAR, "NEXT_RUNNING_VAR"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Batchnorm_attributes::input_names,
+ {
+ {Batchnorm_attributes::input_names::X, "X"},
+ {Batchnorm_attributes::input_names::SCALE, "SCALE"},
+ {Batchnorm_attributes::input_names::BIAS, "BIAS"},
+ {Batchnorm_attributes::input_names::EPSILON, "EPSILON"},
+ {Batchnorm_attributes::input_names::PREV_RUNNING_MEAN, "PREV_RUNNING_MEAN"},
+ {Batchnorm_attributes::input_names::PREV_RUNNING_VAR, "PREV_RUNNING_VAR"},
+ {Batchnorm_attributes::input_names::MOMENTUM, "MOMENTUM"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Batchnorm_attributes::output_names,
+ {
+ {Batchnorm_attributes::output_names::Y, "Y"},
+ {Batchnorm_attributes::output_names::MEAN, "MEAN"},
+ {Batchnorm_attributes::output_names::INV_VARIANCE, "INV_VARIANCE"},
+ {Batchnorm_attributes::output_names::NEXT_RUNNING_MEAN, "NEXT_RUNNING_MEAN"},
+ {Batchnorm_attributes::output_names::NEXT_RUNNING_VAR, "NEXT_RUNNING_VAR"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Batchnorm_backward_attributes::input_names,
+ {
+ {Batchnorm_backward_attributes::input_names::DY, "DY"},
+ {Batchnorm_backward_attributes::input_names::X, "X"},
+ {Batchnorm_backward_attributes::input_names::SCALE, "SCALE"},
+ {Batchnorm_backward_attributes::input_names::MEAN, "MEAN"},
+ {Batchnorm_backward_attributes::input_names::INV_VARIANCE, "INV_VARIANCE"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Batchnorm_backward_attributes::output_names,
+ {
+ {Batchnorm_backward_attributes::output_names::DX, "DX"},
+ {Batchnorm_backward_attributes::output_names::DSCALE, "DSCALE"},
+ {Batchnorm_backward_attributes::output_names::DBIAS, "DBIAS"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Batchnorm_inference_attributes::input_names,
+ {
+ {Batchnorm_inference_attributes::input_names::X, "X"},
+ {Batchnorm_inference_attributes::input_names::SCALE, "SCALE"},
+ {Batchnorm_inference_attributes::input_names::BIAS, "BIAS"},
+ {Batchnorm_inference_attributes::input_names::MEAN, "MEAN"},
+ {Batchnorm_inference_attributes::input_names::INV_VARIANCE, "INV_VARIANCE"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Batchnorm_inference_attributes::output_names,
+ {{Batchnorm_inference_attributes::output_names::Y, "Y"}})
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Conv_dgrad_attributes::input_names,
+ {
+ {Conv_dgrad_attributes::input_names::W, "W"},
+ {Conv_dgrad_attributes::input_names::DY, "DY"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Conv_dgrad_attributes::output_names,
+ {
+ {Conv_dgrad_attributes::output_names::DX, "DX"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Conv_fprop_attributes::input_names,
+ {
+ {Conv_fprop_attributes::input_names::X, "X"},
+ {Conv_fprop_attributes::input_names::W, "W"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Conv_fprop_attributes::output_names,
+ {
+ {Conv_fprop_attributes::output_names::Y, "Y"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Conv_wgrad_attributes::input_names,
+ {
+ {Conv_wgrad_attributes::input_names::DY, "DY"},
+ {Conv_wgrad_attributes::input_names::X, "X"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Conv_wgrad_attributes::output_names,
+ {
+ {Conv_wgrad_attributes::output_names::DW, "DW"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(DBN_weight_attributes::input_names,
+ {
+ {DBN_weight_attributes::input_names::DY, "DY"},
+ {DBN_weight_attributes::input_names::X, "X"},
+ {DBN_weight_attributes::input_names::SCALE, "SCALE"},
+ {DBN_weight_attributes::input_names::MEAN, "MEAN"},
+ {DBN_weight_attributes::input_names::INV_VARIANCE, "INV_VARIANCE"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(DBN_weight_attributes::output_names,
+ {
+ {DBN_weight_attributes::output_names::DSCALE, "DSCALE"},
+ {DBN_weight_attributes::output_names::DBIAS, "DBIAS"},
+ {DBN_weight_attributes::output_names::EQ_BIAS, "EQ_BIAS"},
+ {DBN_weight_attributes::output_names::EQ_SCALE_DY, "EQ_SCALE_DY"},
+ {DBN_weight_attributes::output_names::EQ_SCALE_X, "EQ_SCALE_X"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Genstats_attributes::input_names,
+ {
+ {Genstats_attributes::input_names::X, "X"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Genstats_attributes::output_names,
+ {
+ {Genstats_attributes::output_names::SUM, "SUM"},
+ {Genstats_attributes::output_names::SQ_SUM, "SQ_SUM"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Instancenorm_attributes::input_names,
+ {
+ {Instancenorm_attributes::input_names::X, "X"},
+ {Instancenorm_attributes::input_names::SCALE, "SCALE"},
+ {Instancenorm_attributes::input_names::BIAS, "BIAS"},
+ {Instancenorm_attributes::input_names::EPSILON, "EPSILON"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Instancenorm_attributes::output_names,
+ {
+ {Instancenorm_attributes::output_names::Y, "Y"},
+ {Instancenorm_attributes::output_names::MEAN, "MEAN"},
+ {Instancenorm_attributes::output_names::INV_VARIANCE, "INV_VARIANCE"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Instancenorm_backward_attributes::input_names,
+ {
+ {Instancenorm_backward_attributes::input_names::DY, "DY"},
+ {Instancenorm_backward_attributes::input_names::X, "X"},
+ {Instancenorm_backward_attributes::input_names::SCALE, "SCALE"},
+ {Instancenorm_backward_attributes::input_names::MEAN, "MEAN"},
+ {Instancenorm_backward_attributes::input_names::INV_VARIANCE, "INV_VARIANCE"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Instancenorm_backward_attributes::output_names,
+ {
+ {Instancenorm_backward_attributes::output_names::DX, "DX"},
+ {Instancenorm_backward_attributes::output_names::DSCALE, "DSCALE"},
+ {Instancenorm_backward_attributes::output_names::DBIAS, "DBIAS"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Layernorm_attributes::input_names,
+ {
+ {Layernorm_attributes::input_names::X, "X"},
+ {Layernorm_attributes::input_names::SCALE, "SCALE"},
+ {Layernorm_attributes::input_names::BIAS, "BIAS"},
+ {Layernorm_attributes::input_names::EPSILON, "EPSILON"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Layernorm_attributes::output_names,
+ {
+ {Layernorm_attributes::output_names::Y, "Y"},
+ {Layernorm_attributes::output_names::MEAN, "MEAN"},
+ {Layernorm_attributes::output_names::INV_VARIANCE, "INV_VARIANCE"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Layernorm_backward_attributes::input_names,
+ {
+ {Layernorm_backward_attributes::input_names::DY, "DY"},
+ {Layernorm_backward_attributes::input_names::X, "X"},
+ {Layernorm_backward_attributes::input_names::SCALE, "SCALE"},
+ {Layernorm_backward_attributes::input_names::MEAN, "MEAN"},
+ {Layernorm_backward_attributes::input_names::INV_VARIANCE, "INV_VARIANCE"},
+ {Layernorm_backward_attributes::input_names::EPSILON, "EPSILON"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Layernorm_backward_attributes::output_names,
+ {
+ {Layernorm_backward_attributes::output_names::DX, "DX"},
+ {Layernorm_backward_attributes::output_names::DSCALE, "DSCALE"},
+ {Layernorm_backward_attributes::output_names::DBIAS, "DBIAS"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(AdaLayernorm_attributes::input_names,
+ {
+ {AdaLayernorm_attributes::input_names::X, "X"},
+ {AdaLayernorm_attributes::input_names::SCALE, "SCALE"},
+ {AdaLayernorm_attributes::input_names::BIAS, "BIAS"},
+ {AdaLayernorm_attributes::input_names::EPSILON, "EPSILON"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(AdaLayernorm_attributes::output_names,
+ {
+ {AdaLayernorm_attributes::output_names::Y, "Y"},
+ {AdaLayernorm_attributes::output_names::MEAN, "MEAN"},
+ {AdaLayernorm_attributes::output_names::INV_VARIANCE, "INV_VARIANCE"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(AdaLayernorm_backward_attributes::input_names,
+ {
+ {AdaLayernorm_backward_attributes::input_names::DY, "DY"},
+ {AdaLayernorm_backward_attributes::input_names::X, "X"},
+ {AdaLayernorm_backward_attributes::input_names::SCALE, "SCALE"},
+ {AdaLayernorm_backward_attributes::input_names::MEAN, "MEAN"},
+ {AdaLayernorm_backward_attributes::input_names::INV_VARIANCE, "INV_VARIANCE"},
+ {AdaLayernorm_backward_attributes::input_names::EPSILON, "EPSILON"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(AdaLayernorm_backward_attributes::output_names,
+ {
+ {AdaLayernorm_backward_attributes::output_names::DX, "DX"},
+ {AdaLayernorm_backward_attributes::output_names::DSCALE, "DSCALE"},
+ {AdaLayernorm_backward_attributes::output_names::DBIAS, "DBIAS"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Matmul_attributes::input_names,
+ {
+ {Matmul_attributes::input_names::A, "A"},
+ {Matmul_attributes::input_names::B, "B"},
+ {Matmul_attributes::input_names::M_override, "M_override"},
+ {Matmul_attributes::input_names::N_override, "N_override"},
+ {Matmul_attributes::input_names::K_override, "K_override"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Matmul_attributes::output_names,
+ {
+ {Matmul_attributes::output_names::C, "C"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Matmul_fp8_attributes::input_names,
+ {
+ {Matmul_fp8_attributes::input_names::A, "A"},
+ {Matmul_fp8_attributes::input_names::B, "B"},
+ {Matmul_fp8_attributes::input_names::Descale_A, "Descale_A"},
+ {Matmul_fp8_attributes::input_names::Descale_B, "Descale_B"},
+ {Matmul_fp8_attributes::input_names::M_override, "M_override"},
+ {Matmul_fp8_attributes::input_names::N_override, "N_override"},
+ {Matmul_fp8_attributes::input_names::K_override, "K_override"},
+ {Matmul_fp8_attributes::input_names::Scale_C, "Scale_C"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Matmul_fp8_attributes::output_names,
+ {
+ {Matmul_fp8_attributes::output_names::C, "C"},
+ {Matmul_fp8_attributes::output_names::Amax_C, "Amax_C"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Pointwise_attributes::input_names,
+ {
+ {Pointwise_attributes::input_names::IN_0, "IN_0"},
+ {Pointwise_attributes::input_names::IN_1, "IN_1"},
+ {Pointwise_attributes::input_names::IN_2, "IN_2"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Pointwise_attributes::output_names,
+ {
+ {Pointwise_attributes::output_names::OUT_0, "OUT_0"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Reduction_attributes::input_names,
+ {
+ {Reduction_attributes::input_names::X, "X"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Reduction_attributes::output_names, {{Reduction_attributes::output_names::Y, "Y"}})
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Resample_attributes::input_names,
+ {
+ {Resample_attributes::input_names::X, "X"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Resample_attributes::output_names,
+ {{Resample_attributes::output_names::Y, "Y"},
+ {Resample_attributes::output_names::Index, "Index"}})
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Reshape_attributes::input_names,
+ {
+ {Reshape_attributes::input_names::X, "X"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Reshape_attributes::output_names, {{Reshape_attributes::output_names::Y, "Y"}})
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Transpose_attributes::input_names,
+ {
+ {Transpose_attributes::input_names::X, "X"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Transpose_attributes::output_names, {{Transpose_attributes::output_names::Y, "Y"}})
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Rmsnorm_attributes::input_names,
+ {
+ {Rmsnorm_attributes::input_names::X, "X"},
+ {Rmsnorm_attributes::input_names::SCALE, "SCALE"},
+ {Rmsnorm_attributes::input_names::BIAS, "BIAS"},
+ {Rmsnorm_attributes::input_names::EPSILON, "EPSILON"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Rmsnorm_attributes::output_names,
+ {
+ {Rmsnorm_attributes::output_names::Y, "Y"},
+ {Rmsnorm_attributes::output_names::INV_VARIANCE, "INV_VARIANCE"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Rmsnorm_backward_attributes::input_names,
+ {
+ {Rmsnorm_backward_attributes::input_names::DY, "DY"},
+ {Rmsnorm_backward_attributes::input_names::X, "X"},
+ {Rmsnorm_backward_attributes::input_names::SCALE, "SCALE"},
+ {Rmsnorm_backward_attributes::input_names::INV_VARIANCE, "INV_VARIANCE"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Rmsnorm_backward_attributes::output_names,
+ {
+ {Rmsnorm_backward_attributes::output_names::DX, "DX"},
+ {Rmsnorm_backward_attributes::output_names::DSCALE, "DSCALE"},
+ {Rmsnorm_backward_attributes::output_names::DBIAS, "DBIAS"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Rng_attributes::input_names,
+ {
+ {Rng_attributes::input_names::Seed, "Seed"},
+ {Rng_attributes::input_names::Offset, "Offset"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Rng_attributes::output_names, {{Rng_attributes::output_names::Y, "Y"}})
+
+NLOHMANN_JSON_SERIALIZE_ENUM(PagedCacheLoad_attributes::input_names,
+ {
+ {PagedCacheLoad_attributes::input_names::container, "container"},
+ {PagedCacheLoad_attributes::input_names::seqLen, "seqLen"},
+ {PagedCacheLoad_attributes::input_names::pageTable, "pageTable"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(PagedCacheLoad_attributes::output_names,
+ {
+ {PagedCacheLoad_attributes::output_names::yOut, "yOut"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(SDPA_attributes::input_names,
+ {
+ {SDPA_attributes::input_names::Q, "Q"},
+ {SDPA_attributes::input_names::K, "K"},
+ {SDPA_attributes::input_names::V, "V"},
+ {SDPA_attributes::input_names::Attn_scale, "Attn_scale"},
+ {SDPA_attributes::input_names::Bias, "Bias"},
+ {SDPA_attributes::input_names::SEQ_LEN_Q, "SEQ_LEN_Q"},
+ {SDPA_attributes::input_names::SEQ_LEN_KV, "SEQ_LEN_KV"},
+ {SDPA_attributes::input_names::CU_SEQ_LEN_Q, "CU_SEQ_LEN_Q"},
+ {SDPA_attributes::input_names::CU_SEQ_LEN_KV, "CU_SEQ_LEN_KV"},
+ {SDPA_attributes::input_names::Seed, "Seed"},
+ {SDPA_attributes::input_names::Offset, "Offset"},
+ {SDPA_attributes::input_names::Dropout_mask, "Dropout_mask"},
+ {SDPA_attributes::input_names::Dropout_scale, "Dropout_scale"},
+ {SDPA_attributes::input_names::Page_table_K, "Page_table_K"},
+ {SDPA_attributes::input_names::Page_table_V, "Page_table_V"},
+ {SDPA_attributes::input_names::Block_mask, "Block_mask"},
+ // FP8-specific inputs
+ {SDPA_attributes::input_names::Descale_Q, "Descale_Q"},
+ {SDPA_attributes::input_names::Descale_K, "Descale_K"},
+ {SDPA_attributes::input_names::Descale_V, "Descale_V"},
+ {SDPA_attributes::input_names::Descale_S, "Descale_S"},
+ {SDPA_attributes::input_names::Scale_S, "Scale_S"},
+ {SDPA_attributes::input_names::Scale_O, "Scale_O"},
+ {SDPA_attributes::input_names::SINK_TOKEN, "SINK_TOKEN"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(SDPA_attributes::output_names,
+ {{SDPA_attributes::output_names::O, "O"},
+ {SDPA_attributes::output_names::Stats, "Stats"},
+ {SDPA_attributes::output_names::Max, "Max"},
+ {SDPA_attributes::output_names::Sum_exp, "Sum_exp"},
+ {SDPA_attributes::output_names::RNG_DUMP, "RNG_DUMP"},
+ {SDPA_attributes::output_names::Amax_S, "Amax_S"},
+ {SDPA_attributes::output_names::Amax_O, "Amax_O"}})
+
+NLOHMANN_JSON_SERIALIZE_ENUM(SDPA_backward_attributes::input_names,
+ {
+ {SDPA_backward_attributes::input_names::Q, "Q"},
+ {SDPA_backward_attributes::input_names::K, "K"},
+ {SDPA_backward_attributes::input_names::V, "V"},
+ {SDPA_backward_attributes::input_names::O, "O"},
+ {SDPA_backward_attributes::input_names::dO, "dO"},
+ {SDPA_backward_attributes::input_names::Stats, "Stats"},
+ {SDPA_backward_attributes::input_names::Attn_scale, "Attn_scale"},
+ {SDPA_backward_attributes::input_names::Bias, "Bias"},
+ {SDPA_backward_attributes::input_names::SEQ_LEN_Q, "SEQ_LEN_Q"},
+ {SDPA_backward_attributes::input_names::SEQ_LEN_KV, "SEQ_LEN_KV"},
+ {SDPA_backward_attributes::input_names::Seed, "Seed"},
+ {SDPA_backward_attributes::input_names::Offset, "Offset"},
+ {SDPA_backward_attributes::input_names::Dropout_mask, "Dropout_mask"},
+ {SDPA_backward_attributes::input_names::Dropout_scale, "Dropout_scale"},
+ {SDPA_backward_attributes::input_names::Dropout_scale_inv, "Dropout_scale_inv"},
+ {SDPA_backward_attributes::input_names::SINK_TOKEN, "SINK_TOKEN"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(SDPA_backward_attributes::output_names,
+ {
+ {SDPA_backward_attributes::output_names::dQ, "dQ"},
+ {SDPA_backward_attributes::output_names::dK, "dK"},
+ {SDPA_backward_attributes::output_names::dV, "dV"},
+ {SDPA_backward_attributes::output_names::dBias, "dBias"},
+ {SDPA_backward_attributes::output_names::RNG_DUMP, "RNG_DUMP"},
+ {SDPA_backward_attributes::output_names::DSINK_TOKEN, "DSINK_TOKEN"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Slice_attributes::output_names,
+ {
+ {Slice_attributes::output_names::Y, "Y"},
+ })
+NLOHMANN_JSON_SERIALIZE_ENUM(Slice_attributes::input_names,
+ {
+ {Slice_attributes::input_names::X, "X"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(SDPA_fp8_backward_attributes::input_names,
+ {
+ {SDPA_fp8_backward_attributes::input_names::Q, "Q"},
+ {SDPA_fp8_backward_attributes::input_names::Q_T, "Q_T"},
+ {SDPA_fp8_backward_attributes::input_names::K, "K"},
+ {SDPA_fp8_backward_attributes::input_names::K_T, "K_T"},
+ {SDPA_fp8_backward_attributes::input_names::V, "V"},
+ {SDPA_fp8_backward_attributes::input_names::O, "O"},
+ {SDPA_fp8_backward_attributes::input_names::dO, "dO"},
+ {SDPA_fp8_backward_attributes::input_names::dO_T, "dO_T"},
+ {SDPA_fp8_backward_attributes::input_names::dO_f16, "dO_f16"},
+ {SDPA_fp8_backward_attributes::input_names::Stats, "Stats"},
+ {SDPA_fp8_backward_attributes::input_names::Attn_scale, "Attn_scale"},
+ {SDPA_fp8_backward_attributes::input_names::Bias, "Bias"},
+ {SDPA_fp8_backward_attributes::input_names::SEQ_LEN_Q, "SEQ_LEN_Q"},
+ {SDPA_fp8_backward_attributes::input_names::SEQ_LEN_KV, "SEQ_LEN_KV"},
+ {SDPA_fp8_backward_attributes::input_names::Seed, "Seed"},
+ {SDPA_fp8_backward_attributes::input_names::Offset, "Offset"},
+ {SDPA_fp8_backward_attributes::input_names::Dropout_mask, "Dropout_mask"},
+ {SDPA_fp8_backward_attributes::input_names::Dropout_scale, "Dropout_scale"},
+ {SDPA_fp8_backward_attributes::input_names::Dropout_scale_inv, "Dropout_scale_inv"},
+
+ {SDPA_fp8_backward_attributes::input_names::Descale_Q, "Descale_Q"},
+ {SDPA_fp8_backward_attributes::input_names::Descale_K, "Descale_K"},
+ {SDPA_fp8_backward_attributes::input_names::Descale_V, "Descale_V"},
+ {SDPA_fp8_backward_attributes::input_names::Descale_O, "Descale_O"},
+ {SDPA_fp8_backward_attributes::input_names::Descale_dO, "Descale_dO"},
+ {SDPA_fp8_backward_attributes::input_names::Descale_dO_T, "Descale_dO_T"},
+ {SDPA_fp8_backward_attributes::input_names::Descale_K_T, "Descale_K_T"},
+ {SDPA_fp8_backward_attributes::input_names::Descale_Q_T, "Descale_Q_T"},
+ {SDPA_fp8_backward_attributes::input_names::Descale_S, "Descale_S"},
+ {SDPA_fp8_backward_attributes::input_names::Descale_dP, "Descale_dP"},
+ {SDPA_fp8_backward_attributes::input_names::Scale_dQ, "Scale_dQ"},
+ {SDPA_fp8_backward_attributes::input_names::Scale_dK, "Scale_dK"},
+ {SDPA_fp8_backward_attributes::input_names::Scale_dV, "Scale_dV"},
+ {SDPA_fp8_backward_attributes::input_names::Scale_S, "Scale_S"},
+ {SDPA_fp8_backward_attributes::input_names::Scale_dP, "Scale_dP"},
+ {SDPA_fp8_backward_attributes::input_names::SINK_TOKEN, "SINK_TOKEN"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(SDPA_fp8_backward_attributes::output_names,
+ {
+ {SDPA_fp8_backward_attributes::output_names::dQ, "dQ"},
+ {SDPA_fp8_backward_attributes::output_names::dK, "dK"},
+ {SDPA_fp8_backward_attributes::output_names::dV, "dV"},
+ {SDPA_fp8_backward_attributes::output_names::Amax_dQ, "Amax_dQ"},
+ {SDPA_fp8_backward_attributes::output_names::Amax_dK, "Amax_dK"},
+ {SDPA_fp8_backward_attributes::output_names::Amax_dV, "Amax_dV"},
+ {SDPA_fp8_backward_attributes::output_names::Amax_dP, "Amax_dP"},
+ {SDPA_fp8_backward_attributes::output_names::DSINK_TOKEN, "DSINK_TOKEN"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(RoPE_attributes::input_names,
+ {
+ {RoPE_attributes::input_names::INPUT, "INPUT"},
+ {RoPE_attributes::input_names::FREQS, "FREQS"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(RoPE_attributes::output_names,
+ {
+ {RoPE_attributes::output_names::OUTPUT, "OUTPUT"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(RoPE_backward_attributes::input_names,
+ {
+ {RoPE_backward_attributes::input_names::DY, "DY"},
+ {RoPE_backward_attributes::input_names::FREQS, "FREQS"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(RoPE_backward_attributes::output_names,
+ {
+ {RoPE_backward_attributes::output_names::DX, "DX"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Softmax_attributes::input_names,
+ {
+ {Softmax_attributes::input_names::P, "P"},
+ {Softmax_attributes::input_names::SINK, "SINK"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Softmax_attributes::output_names,
+ {
+ {Softmax_attributes::output_names::S, "S"},
+ {Softmax_attributes::output_names::Stats, "Stats"},
+ {Softmax_attributes::output_names::Max, "Max"},
+ {Softmax_attributes::output_names::Sum_exp, "Sum_exp"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(DiagonalBandMask_attributes::input_names,
+ {
+ {DiagonalBandMask_attributes::input_names::X, "X"},
+ {DiagonalBandMask_attributes::input_names::SEQ_LEN_Q, "SEQ_LEN_Q"},
+ {DiagonalBandMask_attributes::input_names::SEQ_LEN_KV, "SEQ_LEN_KV"},
+ {DiagonalBandMask_attributes::input_names::CU_SEQ_LEN_Q, "CU_SEQ_LEN_Q"},
+ {DiagonalBandMask_attributes::input_names::CU_SEQ_LEN_KV, "CU_SEQ_LEN_KV"},
+ {DiagonalBandMask_attributes::input_names::LeftBound, "LeftBound"},
+ {DiagonalBandMask_attributes::input_names::ShiftRightBound, "ShiftRightBound"},
+ {DiagonalBandMask_attributes::input_names::B, "B"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(DiagonalBandMask_attributes::output_names,
+ {
+ {DiagonalBandMask_attributes::output_names::Y, "Y"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Block_scale_quantize_attributes::input_names,
+ {
+ {Block_scale_quantize_attributes::input_names::X, "X"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Block_scale_quantize_attributes::output_names,
+ {
+ {Block_scale_quantize_attributes::output_names::Y, "Y"},
+ {Block_scale_quantize_attributes::output_names::scale, "scale"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Block_scale_dequantize_attributes::input_names,
+ {
+ {Block_scale_dequantize_attributes::input_names::X, "X"},
+ {Block_scale_dequantize_attributes::input_names::scale, "scale"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Block_scale_dequantize_attributes::output_names,
+ {
+ {Block_scale_dequantize_attributes::output_names::Y, "Y"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Concatenate_attributes::output_names,
+ {
+ {Concatenate_attributes::output_names::Y, "Y"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Moe_grouped_matmul_attributes::input_names,
+ {
+ {Moe_grouped_matmul_attributes::input_names::Token, "Token"},
+ {Moe_grouped_matmul_attributes::input_names::Weight, "Weight"},
+ {Moe_grouped_matmul_attributes::input_names::FirstTokenOffset, "FirstTokenOffset"},
+ {Moe_grouped_matmul_attributes::input_names::TokenIndex, "TokenIndex"},
+ {Moe_grouped_matmul_attributes::input_names::TokenKs, "TokenKs"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Moe_grouped_matmul_attributes::output_names,
+ {
+ {Moe_grouped_matmul_attributes::output_names::Output, "Output"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Moe_grouped_matmul_bwd_attributes::input_names,
+ {
+ {Moe_grouped_matmul_bwd_attributes::input_names::DOutput, "DOutput"},
+ {Moe_grouped_matmul_bwd_attributes::input_names::Token, "Token"},
+ {Moe_grouped_matmul_bwd_attributes::input_names::FirstTokenOffset, "FirstTokenOffset"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(Moe_grouped_matmul_bwd_attributes::output_names,
+ {
+ {Moe_grouped_matmul_bwd_attributes::output_names::DWeight, "DWeight"},
+ })
+
+inline void
+to_json(nlohmann::json& j, const Tensor_attributes& ta) {
+ j = nlohmann::json{{"name", ta.name},
+ {"data_type", ta.data_type},
+ {"dim", ta.dim},
+ {"stride", ta.stride},
+ {"is_virtual", ta.is_virtual},
+ {"pass_by_value", ta.pass_by_value},
+ {"is_pass_by_value", ta.is_pass_by_value},
+ {"reordering_type", ta.reordering_type},
+ {"uid", ta.uid},
+ {"uid_assigned", ta.uid_assigned}};
+ if (ta.ragged_offset) {
+ j["ragged_offset_uid"] = ta.ragged_offset->get_uid();
+ j["ragged_offset_name"] = ta.ragged_offset->get_name();
+ }
+ if (ta.has_ragged_offset_multiplier()) {
+ j["ragged_offset_multiplier"] = ta.ragged_offset_multiplier;
+ }
+}
+
+inline void
+from_json(const nlohmann::json& j, Tensor_attributes& ta) {
+ ta.name = j.at("name").get<std::string>();
+ ta.data_type = j.at("data_type").get<DataType_t>();
+ ta.dim = j.at("dim").get<std::vector<int64_t>>();
+ ta.stride = j.at("stride").get<std::vector<int64_t>>();
+ ta.is_virtual = j.at("is_virtual").get<bool>();
+ ta.is_pass_by_value = j.at("is_pass_by_value").get<bool>();
+ ta.reordering_type = j.at("reordering_type").get<TensorReordering_t>();
+ ta.uid = j.at("uid").get<Tensor_attributes::uid_t>();
+ ta.uid_assigned = j.at("uid_assigned").get<bool>();
+
+ if (ta.is_pass_by_value && !j["pass_by_value"].is_null()) {
+ ta.pass_by_value = j.at("pass_by_value");
+ }
+ if (j.contains("ragged_offset_uid")) {
+ auto ragged_offset = std::make_shared<Tensor_attributes>();
+ ragged_offset->uid = j.at("ragged_offset_uid").get<Tensor_attributes::uid_t>();
+ ragged_offset->uid_assigned = true;
+ if (j.contains("ragged_offset_name")) {
+ ragged_offset->name = j.at("ragged_offset_name").get<std::string>();
+ }
+ ta.ragged_offset = ragged_offset;
+ }
+ if (j.contains("ragged_offset_multiplier")) {
+ ta.ragged_offset_multiplier = j.at("ragged_offset_multiplier").get<int64_t>();
+ }
+}
+
+NLOHMANN_JSON_SERIALIZE_ENUM(KnobType_t,
+ {
+ {KnobType_t::NOT_SET, nullptr},
+ {KnobType_t::SWIZZLE, "SWIZZLE"},
+ {KnobType_t::TILE_SIZE, "TILE_SIZE"},
+ {KnobType_t::EDGE, "EDGE"},
+ {KnobType_t::MULTIPLY, "MULTIPLY"},
+ {KnobType_t::SPLIT_K_BUF, "SPLIT_K_BUF"},
+ {KnobType_t::TILEK, "TILEK"},
+ {KnobType_t::STAGES, "STAGES"},
+ {KnobType_t::REDUCTION_MODE, "REDUCTION_MODE"},
+ {KnobType_t::SPLIT_K_SLC, "SPLIT_K_SLC"},
+ {KnobType_t::IDX_MODE, "IDX_MODE"},
+ {KnobType_t::SPECFILT, "SPECFILT"},
+ {KnobType_t::KERNEL_CFG, "KERNEL_CFG"},
+ {KnobType_t::WORKSPACE, "WORKSPACE"},
+ {KnobType_t::TILE_CGA_M, "TILE_CGA_M"},
+ {KnobType_t::TILE_CGA_N, "TILE_CGA_N"},
+ {KnobType_t::BLOCK_SIZE, "BLOCK_SIZE"},
+ {KnobType_t::OCCUPANCY, "OCCUPANCY"},
+ {KnobType_t::ARRAY_SIZE_PER_THREAD, "ARRAY_SIZE_PER_THREAD"},
+ {KnobType_t::SPLIT_COLS, "SPLIT_COLS"},
+ {KnobType_t::TILE_ROWS, "TILE_ROWS"},
+ {KnobType_t::TILE_COLS, "TILE_COLS"},
+ {KnobType_t::LOAD_SIZE, "LOAD_SIZE"},
+ {KnobType_t::CTA_COUNT, "CTA_COUNT"},
+ {KnobType_t::STREAM_K, "STREAM_K"},
+ {KnobType_t::SPLIT_P_SLC, "SPLIT_P_SLC"},
+ {KnobType_t::TILE_M, "TILE_M"},
+ {KnobType_t::TILE_N, "TILE_N"},
+ {KnobType_t::WARP_SPEC_CFG, "WARP_SPEC_CFG"},
+ })
+
+#endif
+} // namespace cudnn_frontend::graph
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_ConvDesc.h b/deps/cudnn-frontend/include/cudnn_frontend_ConvDesc.h
new file mode 100644
index 0000000..0cbd248
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_ConvDesc.h
@@ -0,0 +1,425 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+
+namespace cudnn_frontend {
+namespace graph {
+class ConvolutionNode;
+}
+} // namespace cudnn_frontend
+namespace cudnn_frontend {
+namespace graph {
+class DgradNode;
+}
+} // namespace cudnn_frontend
+namespace cudnn_frontend {
+namespace graph {
+class WgradNode;
+}
+} // namespace cudnn_frontend
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+
+///
+/// Convolution Descriptor Class
+/// This class tells the properties of the Convolution operation
+/// Properties:
+/// - padLower
+/// - padUpper
+/// - Dilation
+/// - Stride
+/// - Math Operation Data Type
+/// - Convolution Mode
+/// - Convolution spatial dimensions
+///
+/// Use ConvDescBuilder_v8 to build this class.
+/// Describe returns a string describing the convolution operation
+///
+class ConvDesc_v8 : public BackendDescriptor {
+ public:
+ friend class ConvDescBuilder_v8;
+ friend class cudnn_frontend::graph::ConvolutionNode;
+ friend class cudnn_frontend::graph::DgradNode;
+ friend class cudnn_frontend::graph::WgradNode;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ char sep = ' ';
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ ss << "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR :" << " Datatype: " << json{compute_type} << " Mode: " << json{mode}
+#else
+ ss << "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR :" << " Datatype: " << int(compute_type) << " Mode: " << int(mode)
+#endif
+ << " Num Dimensions: " << nDims;
+ ss << " PadLower [";
+ for (auto i = 0; i < nDims; i++) {
+ ss << sep << padLower[i];
+ sep = ',';
+ }
+ ss << " ] PadUpper [";
+ for (auto i = 0; i < nDims; i++) {
+ ss << sep << padUpper[i];
+ sep = ',';
+ }
+ ss << " ] Dilation [";
+ for (auto i = 0; i < nDims; i++) {
+ ss << sep << dilation[i];
+ sep = ',';
+ }
+ ss << " ] Stride [";
+ for (auto i = 0; i < nDims; i++) {
+ ss << sep << stride[i];
+ sep = ',';
+ }
+ ss << "]";
+ return ss.str();
+ }
+
+ ConvDesc_v8(ConvDesc_v8 &&from) = default;
+ ConvDesc_v8 &
+ operator=(ConvDesc_v8 &&) = default;
+
+ ~ConvDesc_v8() = default;
+
+ // TODO: Deprecate in v1.0
+ DataType_t
+ getComputePrecision() const {
+ return compute_type;
+ }
+
+ DataType_t
+ getComputeType() const {
+ return compute_type;
+ }
+
+ int64_t
+ getSpatialDimCount() const {
+ return nDims;
+ }
+
+ int64_t const *
+ getPadding() const {
+ return padLower;
+ }
+
+ int64_t const *
+ getSpatialStride() const {
+ return stride;
+ }
+
+ int64_t const *
+ getDilation() const {
+ return dilation;
+ }
+
+ cudnnConvolutionMode_t
+ getMathMode() const {
+ return detail::convert_to_cudnn_type(mode);
+ }
+
+ // TODO: Deprecate in v1.0
+ int64_t
+ getDimensionCount() const {
+ return getSpatialDimCount();
+ }
+
+ // TODO: Deprecate in v1.0
+ int64_t const *
+ getStride() const {
+ return getSpatialStride();
+ }
+
+ private:
+ ConvDesc_v8() = default;
+ ConvDesc_v8(ConvDesc_v8 const &) = delete;
+ ConvDesc_v8 &
+ operator=(ConvDesc_v8 const &) = delete;
+
+ DataType_t compute_type = DataType_t::FLOAT; //! Convolution operation data type
+ ConvolutionMode_t mode = ConvolutionMode_t::CONVOLUTION; //! Convolution vs cross correlation
+ int64_t nDims = -1; //! number of dimensions
+ int64_t padLower[CUDNN_DIM_MAX + 1] = {0}; //! d, h, w
+ int64_t padUpper[CUDNN_DIM_MAX + 1] = {0}; //! d, h, w
+ int64_t dilation[CUDNN_DIM_MAX + 1] = {0}; //! d, h, w
+ int64_t stride[CUDNN_DIM_MAX + 1] = {-1}; //! d, h, w
+};
+
+///
+/// ConvDescBuilder_v8 Class
+/// Helper class used to build ConvDesc_v8 class
+class ConvDescBuilder_v8 {
+ public:
+ /** @defgroup ConvDescBuilder_v8
+ * Set individual property of ConvDesc_v8 class
+ * @{
+ */
+ //! Set Datatype for the Convolution Operation
+ auto
+ setComputeType(DataType_t data_type) -> ConvDescBuilder_v8 & {
+ m_convDesc.compute_type = data_type;
+ return *this;
+ }
+ // To be deprecated in v1.0.
+ auto
+ setComputeType(cudnnDataType_t data_type_) -> ConvDescBuilder_v8 & {
+ m_convDesc.compute_type = detail::convert_from_cudnn_type(data_type_);
+ return *this;
+ }
+ //! Set Padding Lower of the convDesc
+ auto
+ setPrePadding(int64_t ndims, int64_t const *padding) -> ConvDescBuilder_v8 & {
+ std::copy(padding, padding + ndims, m_convDesc.padLower);
+ return *this;
+ }
+ //! Set Padding Upper of the convDesc
+ auto
+ setPostPadding(int64_t ndims, int64_t const *padding) -> ConvDescBuilder_v8 & {
+ std::copy(padding, padding + ndims, m_convDesc.padUpper);
+ return *this;
+ }
+ //! Set Dilation of the convDesc
+ auto
+ setDilation(int64_t ndims, int64_t const *dilation) -> ConvDescBuilder_v8 & {
+ std::copy(dilation, dilation + ndims, m_convDesc.dilation);
+ return *this;
+ }
+ //! Set Strides of the convDesc
+ auto
+ setSpatialStride(int64_t ndims, int64_t const *strides) -> ConvDescBuilder_v8 & {
+ std::copy(strides, strides + ndims, m_convDesc.stride);
+ return *this;
+ }
+ //! Set Num Spatial Dimensions of the convolution Operation
+ auto
+ setSpatialDimCount(int64_t nDims_) -> ConvDescBuilder_v8 & {
+ m_convDesc.nDims = nDims_;
+ return *this;
+ }
+ //! Set Convolution Mode of the convolution Operation
+ auto
+ setMathMode(ConvolutionMode_t mode_) -> ConvDescBuilder_v8 & {
+ m_convDesc.mode = mode_;
+ return *this;
+ }
+
+ auto
+ setMathMode(cudnnConvolutionMode_t mode_) -> ConvDescBuilder_v8 & {
+ m_convDesc.mode = detail::convert_from_cudnn_type(mode_);
+ return *this;
+ }
+ /** @} */
+
+ // TODO: Deprecate in v1.0
+ auto
+ setNDims(int64_t nDims_) -> ConvDescBuilder_v8 & {
+ return setSpatialDimCount(nDims_);
+ }
+ // TODO: Deprecate in v1.0
+ auto
+ setDataType(cudnnDataType_t data_type_) -> ConvDescBuilder_v8 & {
+ return setComputeType(data_type_);
+ }
+ // TODO: Deprecate in v1.0
+ auto
+ setComputePrecision(cudnnDataType_t data_type_) -> ConvDescBuilder_v8 & {
+ return setComputeType(data_type_);
+ }
+ // TODO: Deprecate in v1.0
+ auto
+ setStrides(int64_t ndims, int64_t const *strides) -> ConvDescBuilder_v8 & {
+ return setSpatialStride(ndims, strides);
+ }
+
+ //! constructs the ConvDesc_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ ConvDesc_v8 &&
+ build() {
+ // Sanity check if non-default fields have been set correctly.
+ if (m_convDesc.nDims <= 0) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: Check and Set the CUDNN_ATTR_CONVOLUTION_SPATIAL_DIMS field");
+ return std::move(m_convDesc);
+ };
+ if (m_convDesc.stride[0] <= 0) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: Check and Set the CUDNN_ATTR_CONVOLUTION_FILTER_STRIDES field");
+ return std::move(m_convDesc);
+ }
+
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_convDesc.initialize_managed_backend_pointer(CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc, status, "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: Bad descriptor created");
+ return std::move(m_convDesc);
+ }
+
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc, status, "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_convDesc);
+ }
+
+ // Once Created lets set the descriptor parameters.
+ cudnnDataType_t cudnn_data_type;
+ status = detail::convert_to_cudnn_type(m_convDesc.compute_type, cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ status,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_CONVOLUTION_COMP_TYPE Failed");
+ return std::move(m_convDesc);
+ }
+ status = detail::set_attribute(m_convDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_CONVOLUTION_COMP_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ status,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_CONVOLUTION_COMP_TYPE Failed");
+ return std::move(m_convDesc);
+ }
+
+ cudnnConvolutionMode_t mode_ = detail::convert_to_cudnn_type(m_convDesc.mode);
+
+ status = detail::set_attribute(m_convDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_CONVOLUTION_CONV_MODE,
+ CUDNN_TYPE_CONVOLUTION_MODE,
+ 1,
+ &mode_);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ status,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_CONVOLUTION_CONV_MODE Failed");
+ return std::move(m_convDesc);
+ }
+
+ status = detail::set_attribute(m_convDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_CONVOLUTION_SPATIAL_DIMS,
+ CUDNN_TYPE_INT64,
+ 1,
+ &m_convDesc.nDims);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ status,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_CONVOLUTION_SPATIAL_DIMS Failed");
+ return std::move(m_convDesc);
+ }
+
+ status = detail::set_attribute(m_convDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_CONVOLUTION_PRE_PADDINGS,
+ CUDNN_TYPE_INT64,
+ m_convDesc.nDims,
+ m_convDesc.padLower);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ status,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_CONVOLUTION_PRE_PADDINGS Failed");
+ return std::move(m_convDesc);
+ }
+
+ status = detail::set_attribute(m_convDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_CONVOLUTION_POST_PADDINGS,
+ CUDNN_TYPE_INT64,
+ m_convDesc.nDims,
+ m_convDesc.padUpper);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ status,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_CONVOLUTION_POST_PADDINGS Failed");
+ return std::move(m_convDesc);
+ }
+
+ status = detail::set_attribute(m_convDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_CONVOLUTION_DILATIONS,
+ CUDNN_TYPE_INT64,
+ m_convDesc.nDims,
+ m_convDesc.dilation);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ status,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_CONVOLUTION_DILATIONS Failed");
+ return std::move(m_convDesc);
+ }
+
+ status = detail::set_attribute(m_convDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_CONVOLUTION_FILTER_STRIDES,
+ CUDNN_TYPE_INT64,
+ m_convDesc.nDims,
+ m_convDesc.stride);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc,
+ status,
+ "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_CONVOLUTION_FILTER_STRIDES Failed");
+ return std::move(m_convDesc);
+ }
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_convDesc.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_convDesc, status, "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_convDesc);
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL(m_convDesc)
+ return std::move(m_convDesc);
+ }
+
+ explicit ConvDescBuilder_v8() = default;
+ ~ConvDescBuilder_v8() = default;
+ ConvDescBuilder_v8(ConvDescBuilder_v8 &&) = delete;
+ ConvDescBuilder_v8(ConvDescBuilder_v8 const &) = delete;
+ ConvDescBuilder_v8 &
+ operator=(ConvDescBuilder_v8 const &) = delete;
+
+ private:
+ ConvDesc_v8 m_convDesc;
+};
+
+using ConvDesc = ConvDesc_v8;
+using ConvDescBuilder = ConvDescBuilder_v8;
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Engine.h b/deps/cudnn-frontend/include/cudnn_frontend_Engine.h
new file mode 100644
index 0000000..cb093cc
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Engine.h
@@ -0,0 +1,341 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+#include <vector>
+
+#include "cudnn_frontend_OperationGraph.h"
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+
+///
+/// Engine_v8 Class
+/// This class tells the properties of the Engine_v8 on which performs the
+/// operation requested
+/// Properties:
+/// - Index
+/// - OperationGraph_v8
+///
+/// Use EngineBuilder_v8 to build this class.
+/// Describe returns a string describing the tensor class
+///
+class Engine_v8 : public BackendDescriptor {
+ private:
+ Engine_v8() = default;
+ Engine_v8(Engine_v8 const &) = delete;
+ Engine_v8 &
+ operator=(Engine_v8 const &) = delete;
+
+ /// Internal class which controls the different knobs for a given engine
+ /// Has min-max and stride as the options.
+ /// User has the option to set the required value as a choice.
+ class Knob {
+ public:
+ Knob(cudnnBackendKnobType_t type_, int64_t max, int64_t min, int64_t stride_)
+ : knobType(type_), maxValue(max), minValue(min), stride(stride_) {}
+
+ std::string
+ describe() const {
+ std::stringstream ss;
+ ss << "Knob:" << knobType;
+ ss << " Min: " << minValue;
+ ss << " Max: " << maxValue;
+ ss << " Stride: " << stride;
+ return ss.str();
+ }
+
+ void
+ setChoice(uint64_t val_) {
+ choice = val_;
+ }
+
+ int64_t
+ getChoice() const {
+ return choice;
+ }
+
+ cudnnBackendKnobType_t
+ getKnobType() const {
+ return knobType;
+ }
+
+ int64_t
+ getMinValue() const {
+ return minValue;
+ }
+
+ int64_t
+ getMaxValue() const {
+ return minValue;
+ }
+
+ int64_t
+ getStride() const {
+ return stride;
+ }
+
+ private:
+ cudnnBackendKnobType_t knobType = CUDNN_KNOB_TYPE_COUNTS;
+ int64_t maxValue = 0, minValue = 0, stride = 0; //!< min, max and stride of the knob value
+ int64_t choice = -1; //!< Choice set by the user
+ };
+
+ ManagedOpaqueDescriptor opGraph = nullptr;
+ int64_t idx = -1; //!< Global Index of the engine for the given operationGraph.
+ int64_t numKnobs = 0; //!< Count of the backend knobs in the engine
+ std::array<ManagedOpaqueDescriptor, CUDNN_KNOB_TYPE_COUNTS> bKnobs = {}; //!< Opaque pointer to the backend knobs
+ std::vector<Knob> knobs;
+ std::string opGraphTag;
+
+ //! Called from the constructor builds the internal knobs vector
+ void
+ buildKnobs() {
+ cudnnStatus_t status;
+ for (auto i = 0; i < numKnobs; i++) {
+ auto bKnob = bKnobs[i]->get_backend_descriptor();
+ cudnnBackendKnobType_t type;
+ int64_t maxValue, minValue, stride, elemCount;
+ status =
+ detail::get_attribute(bKnob, CUDNN_ATTR_KNOB_INFO_TYPE, CUDNN_TYPE_KNOB_TYPE, 1, &elemCount, &type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR "
+ "GetAttribute CUDNN_ATTR_KNOB_INFO_TYPE failed");
+ }
+ status = detail::get_attribute(
+ bKnob, CUDNN_ATTR_KNOB_INFO_MAXIMUM_VALUE, CUDNN_TYPE_INT64, 1, &elemCount, &maxValue);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR "
+ "GetAttribute CUDNN_ATTR_KNOB_INFO_MAXIMUM_VALUE Failed");
+ }
+ status = detail::get_attribute(
+ bKnob, CUDNN_ATTR_KNOB_INFO_MINIMUM_VALUE, CUDNN_TYPE_INT64, 1, &elemCount, &minValue);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR "
+ "GetAttribute CUDNN_ATTR_KNOB_INFO_MINIMUM_VALUE Failed");
+ }
+ status =
+ detail::get_attribute(bKnob, CUDNN_ATTR_KNOB_INFO_STRIDE, CUDNN_TYPE_INT64, 1, &elemCount, &stride);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR "
+ "GetAttribute CUDNN_ATTR_KNOB_INFO_STRIDE Failed");
+ }
+ knobs.emplace_back(Knob(type, maxValue, minValue, stride));
+ }
+ }
+
+ public:
+ friend class EngineBuilder_v8;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_ENGINE_DESCRIPTOR :";
+ ss << " ID: " << idx;
+ ss << " Has " << numKnobs << " knobs";
+ return ss.str();
+ }
+ Engine_v8(Engine_v8 &&from) = default;
+
+ Engine_v8 &
+ operator=(Engine_v8 &&) = default;
+ ~Engine_v8() = default;
+
+ std::string const &
+ getTag() const {
+ return opGraphTag;
+ }
+
+ //! Returns a vector of knobs to the user for modification
+ std::vector<Knob> &
+ getSupportedKnobs() {
+ return knobs;
+ }
+
+ //! Returns a final vector of knobs. Used in EngineConfigBuilder
+ std::vector<Knob> const &
+ getFinalizedKnobs() const {
+ return knobs;
+ }
+
+ bool
+ knobs_set() const {
+ bool is_knob_set = false;
+ for (auto i = 0; i < numKnobs; i++) {
+ if (knobs[i].getChoice() != -1) {
+ is_knob_set = true;
+ break;
+ }
+ }
+ return is_knob_set;
+ }
+};
+
+///
+/// EngineBuilder_v8 Class
+/// Helper class used to build Engine_v8 class
+class EngineBuilder_v8 {
+ public:
+ /** @defgroup EngineBuilder_v8
+ * Set individual property of Engine_v8 class
+ * @{
+ */
+ //! Set operationGraph for the engine
+ auto
+ setOperationGraph(OperationGraph_v8 const &opGraph_) -> EngineBuilder_v8 & {
+ m_engine.opGraph = opGraph_.get_desc();
+ m_engine.opGraphTag = opGraph_.getTag();
+ return *this;
+ }
+
+ //! Set operationGraph for the engine
+ auto
+ setOperationGraph(ManagedOpaqueDescriptor desc_) -> EngineBuilder_v8 & {
+ m_engine.opGraph = desc_;
+ return *this;
+ }
+ //! Set engine index for the engine
+ auto
+ setGlobalEngineIdx(int64_t idx_) -> EngineBuilder_v8 & {
+ m_engine.idx = idx_;
+ return *this;
+ }
+ /** @} */
+
+ //! constructs the Engine_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ Engine_v8 &&
+ build() {
+ if (m_engine.idx < 0) {
+ set_error_and_throw_exception(
+ &m_engine,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: Check and Set the CUDNN_ATTR_ENGINE_GLOBAL_INDEX to valid value");
+ return std::move(m_engine);
+ }
+ if (m_engine.opGraph == nullptr) {
+ set_error_and_throw_exception(
+ &m_engine,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: Check and Set CUDNN_ATTR_ENGINE_OPERATION_GRAPH to valid value");
+ return std::move(m_engine);
+ }
+
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_engine.initialize_managed_backend_pointer(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_engine, status, "CUDNN_BACKEND_ENGINE_DESCRIPTOR: cudnnCreate Descriptor Failed");
+ return std::move(m_engine);
+ }
+
+ status = detail::set_attribute(m_engine.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINE_OPERATION_GRAPH,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_engine.opGraph->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_engine,
+ status,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: SetAttribute CUDNN_ATTR_ENGINE_OPERATION_GRAPH Failed");
+ return std::move(m_engine);
+ }
+
+ status = detail::set_attribute(m_engine.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINE_GLOBAL_INDEX,
+ CUDNN_TYPE_INT64,
+ 1,
+ &m_engine.idx);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_engine,
+ status,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: SetAttribute CUDNN_ATTR_ENGINE_GLOBAL_INDEX Failed");
+ return std::move(m_engine);
+ }
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_engine.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_engine, status, "CUDNN_BACKEND_ENGINE_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_engine);
+ }
+
+ for (size_t i = 0; i < m_engine.bKnobs.size(); i++) {
+ m_engine.bKnobs[i] = make_shared_backend_pointer(CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR);
+ if (m_engine.bKnobs[i]->is_good() == false) {
+ status = m_engine.bKnobs[i]->get_status();
+ set_error_and_throw_exception(
+ &m_engine,
+ status,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR cudnnCreate Failed");
+ }
+ }
+
+ std::array<cudnnBackendDescriptor_t, CUDNN_KNOB_TYPE_COUNTS> bKnobs_ =
+ {}; //!< Opaque pointer to the backend knobs
+ for (std::uint32_t i = 0; i < m_engine.bKnobs.size(); i++) {
+ bKnobs_[i] = m_engine.bKnobs[i]->get_backend_descriptor();
+ }
+ status = detail::get_attribute(m_engine.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINE_KNOB_INFO,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ CUDNN_KNOB_TYPE_COUNTS,
+ &m_engine.numKnobs,
+ bKnobs_.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_engine,
+ status,
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR: GetAttribute CUDNN_ATTR_ENGINE_KNOB_INFO Query Failed");
+ }
+ m_engine.buildKnobs();
+ CUDNN_FE_LOG_LABEL_ENDL(m_engine);
+ return std::move(m_engine);
+ }
+
+ explicit EngineBuilder_v8() = default;
+ ~EngineBuilder_v8() = default;
+ EngineBuilder_v8(EngineBuilder_v8 &&) = delete;
+ EngineBuilder_v8(EngineBuilder_v8 const &) = delete;
+ EngineBuilder_v8 &
+ operator=(EngineBuilder_v8 const &) = delete;
+
+ private:
+ Engine_v8 m_engine;
+};
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_EngineConfig.h b/deps/cudnn-frontend/include/cudnn_frontend_EngineConfig.h
new file mode 100644
index 0000000..15995eb
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_EngineConfig.h
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "cudnn_frontend_Engine.h"
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+///
+/// EngineConfig_v8 Class
+/// This class tells the Configuration of the Engine_v8 in terms of the knob
+/// choices
+/// Properties:
+/// - num knobs
+/// - Choice
+/// - Engine_v8
+///
+/// Use EngineConfigBuilder_v8 to build this class.
+/// Describe returns a string describing the tensor class
+///
+class EngineConfig_v8 : public BackendDescriptor {
+ public:
+ friend class EngineConfigBuilder_v8;
+
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR :";
+ ss << " Number of knobs: " << numKnobs;
+ return ss.str();
+ }
+
+ EngineConfig_v8 &
+ operator=(EngineConfig_v8 &&from) = default;
+
+ EngineConfig_v8(EngineConfig_v8 &&from) = default;
+
+ ~EngineConfig_v8() = default;
+
+ std::string const &
+ getTag() const {
+ return opGraphTag;
+ }
+
+ private:
+ EngineConfig_v8() : BackendDescriptor() {
+ cudnnStatus_t status;
+ for (size_t i = 0; i < bChoices.size(); i++) {
+ bChoices[i] = make_shared_backend_pointer(CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR);
+ if (bChoices[i]->is_good() == false) {
+ status = bChoices[i]->get_status();
+ set_error_and_throw_exception(
+ this,
+ status,
+ "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR cudnnCreate Failed");
+ break;
+ }
+ }
+ }
+ EngineConfig_v8(EngineConfig_v8 const &) = delete;
+ EngineConfig_v8 &
+ operator=(EngineConfig_v8 const &) = delete;
+
+ ManagedOpaqueDescriptor engine = nullptr;
+ int64_t numKnobs = 0;
+ std::string opGraphTag;
+ bool set_knobs_attr = false;
+ std::array<ManagedOpaqueDescriptor, CUDNN_KNOB_TYPE_COUNTS> bChoices = {}; //!< Opaque pointer to the backend knobs
+};
+
+///
+/// EngineConfigBuilder_v8 Class
+/// Helper class used to build EngineConfig_v8 class
+class EngineConfigBuilder_v8 {
+ public:
+ /** @defgroup EngineConfigBuilder_v8
+ * Set individual property of EngineConfig_v8 class
+ * @{
+ */
+ //! Set engine for the EngineConfig_v8
+ auto
+ setEngine(Engine_v8 const &engine_) -> EngineConfigBuilder_v8 & {
+ m_engine_config.engine = engine_.get_desc();
+ m_engine_config.opGraphTag = engine_.getTag();
+ auto &knobs = engine_.getFinalizedKnobs();
+ m_engine_config.numKnobs = knobs.size();
+
+ m_engine_config.set_knobs_attr = engine_.knobs_set();
+
+ for (std::uint32_t i = 0; i < knobs.size(); i++) {
+ cudnnStatus_t status;
+ cudnnBackendKnobType_t type = knobs[i].getKnobType();
+ int64_t value = knobs[i].getChoice();
+ status = detail::set_attribute(m_engine_config.bChoices[i]->get_backend_descriptor(),
+ CUDNN_ATTR_KNOB_CHOICE_KNOB_TYPE,
+ CUDNN_TYPE_KNOB_TYPE,
+ 1,
+ &type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_engine_config,
+ status,
+ "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: "
+ "CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR SetAttribute "
+ "CUDNN_ATTR_KNOB_CHOICE_KNOB_TYPE Failed");
+ }
+ status = detail::set_attribute(m_engine_config.bChoices[i]->get_backend_descriptor(),
+ CUDNN_ATTR_KNOB_CHOICE_KNOB_VALUE,
+ CUDNN_TYPE_INT64,
+ 1,
+ &value);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_engine_config,
+ status,
+ "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: "
+ "CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR SetAttribute "
+ "CUDNN_ATTR_KNOB_CHOICE_KNOB_VALUE Failed");
+ }
+ status = detail::finalize(m_engine_config.bChoices[i]->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_engine_config,
+ status,
+ "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR cudnnFinalize Failed");
+ }
+ }
+
+ return *this;
+ }
+ /** @} */
+
+ //! constructs the Engine_v8 Config by calling the cudnn API
+ //! Throws the appropriate error message
+ EngineConfig_v8 &&
+ build() {
+ if (m_engine_config.status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_engine_config,
+ m_engine_config.status,
+ "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: is not created properly");
+ return std::move(m_engine_config);
+ }
+ if (m_engine_config.engine == nullptr) {
+ set_error_and_throw_exception(
+ &m_engine_config,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: Check and Set the CUDNN_ATTR_ENGINECFG_ENGINE.");
+ return std::move(m_engine_config);
+ }
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_engine_config.initialize_managed_backend_pointer(CUDNN_BACKEND_ENGINECFG_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_engine_config, status, "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_engine_config);
+ }
+
+ status = detail::set_attribute(m_engine_config.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_ENGINE,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_engine_config.engine->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_engine_config,
+ status,
+ "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: SetAttribute CUDNN_ATTR_ENGINECFG_ENGINE Failed");
+ return std::move(m_engine_config);
+ }
+
+ if (m_engine_config.set_knobs_attr && m_engine_config.numKnobs > 0) {
+ std::array<cudnnBackendDescriptor_t, CUDNN_KNOB_TYPE_COUNTS> bChoices_;
+ for (auto i = 0; i < m_engine_config.numKnobs; i++) {
+ bChoices_[i] = m_engine_config.bChoices[i]->get_backend_descriptor();
+ }
+ status = detail::set_attribute(m_engine_config.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_KNOB_CHOICES,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ m_engine_config.numKnobs,
+ bChoices_.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_engine_config,
+ status,
+ "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: SetAttribute CUDNN_ATTR_ENGINECFG_KNOB_CHOICES Failed");
+ return std::move(m_engine_config);
+ }
+ }
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_engine_config.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_engine_config, status, "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_engine_config);
+ }
+ CUDNN_FE_LOG_LABEL_ENDL(m_engine_config);
+ return std::move(m_engine_config);
+ }
+
+ explicit EngineConfigBuilder_v8() = default;
+ ~EngineConfigBuilder_v8() = default;
+ EngineConfigBuilder_v8(EngineConfigBuilder_v8 &&) = delete;
+ EngineConfigBuilder_v8(EngineConfigBuilder_v8 const &) = delete;
+ EngineConfigBuilder_v8 &
+ operator=(EngineConfigBuilder_v8 const &) = delete;
+
+ private:
+ EngineConfig_v8 m_engine_config;
+};
+
+///
+/// EngineConfigList class
+/// This is a RAII type class that holds naked
+/// EngineConfig backendDescriptor.
+/// The purpose of this class is to provide an
+/// easy interface to store the EngineConfigs generated
+/// from various source and apply a filter.
+
+using EngineConfigList = std::vector<ManagedOpaqueDescriptor>;
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_EngineConfigGenerator.h b/deps/cudnn-frontend/include/cudnn_frontend_EngineConfigGenerator.h
new file mode 100644
index 0000000..432f678
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_EngineConfigGenerator.h
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <cudnn_frontend.h>
+
+namespace cudnn_frontend {
+
+/// Variety of renames.
+using executionPlans_t = std::vector<cudnn_frontend::ExecutionPlan>;
+using Predicate = std::function<bool(cudnn_frontend::ExecutionPlan const &plan)>;
+using GeneratorSource = std::function<cudnn_frontend::EngineConfigList(cudnn_frontend::OperationGraph &)>;
+
+enum class CudnnFindSamplingTechnique {
+ CUDNN_FIND_SAMPLE_ONCE, //!< Sample once quick but may have unstable values
+ CUDNN_FIND_SAMPLE_MEDIAN_OF_THREE, //!< Sample 3 times and take median.
+ CUDNN_FIND_SAMPLE_TILL_STABLE //!< Sample multiple times till stable.
+};
+
+/// EngineConfigGenerator class
+/// Contains a vector of methods that generate a vector of backend descriptor
+/// that can be used to create a plan for the method.
+class EngineConfigGenerator {
+ private:
+ std::vector<GeneratorSource> engine_config_generators;
+
+ public:
+ /// Constructor that takes int a array of function pointers that will be called later.
+ /// in the generate_engine_config function.
+ EngineConfigGenerator(int const sourceSize, GeneratorSource const *sources) {
+ for (int i = 0; i < sourceSize; i++) {
+ engine_config_generators.push_back(sources[i]);
+ }
+ };
+
+ /// Calls the vector of engine_config_generators one by one and concatenates the generated
+ /// engine together into a single list.
+ auto
+ generate_engine_config(cudnn_frontend::OperationGraph &opGraph) -> cudnn_frontend::EngineConfigList {
+ cudnn_frontend::EngineConfigList engine_configs;
+ for (auto fn : engine_config_generators) {
+ cudnn_frontend::EngineConfigList new_engine_config = fn(opGraph);
+ CUDNN_FE_LOG_LABEL_ENDL("Called engine config generator and produced " << new_engine_config.size()
+ << " configs.");
+ std::copy(new_engine_config.begin(), new_engine_config.end(), std::back_inserter(engine_configs));
+ new_engine_config.clear();
+ }
+ return engine_configs;
+ }
+
+ /// Returns the concatenated plan in the order of heuristic results.
+ auto
+ cudnnGetPlan(cudnnHandle_t handle, cudnn_frontend::OperationGraph &opGraph, Predicate pred, size_t max_plans = 1000)
+ -> executionPlans_t;
+ auto
+ cudnnGetPlan(cudnnHandle_t handle, cudnn_frontend::OperationGraph &opGraph, size_t max_plans = 1000)
+ -> executionPlans_t;
+
+ /// Reruns the concatenated plans and measures the execution time following which
+ /// a sorted order of executionPlans are return to the user.
+ template <CudnnFindSamplingTechnique samplingTechnique>
+ auto
+ cudnnFindPlan(cudnnHandle_t handle,
+ cudnn_frontend::OperationGraph &opGraph,
+ cudnn_frontend::VariantPack const &variantPack,
+ Predicate pred) -> executionPlans_t;
+
+ template <CudnnFindSamplingTechnique samplingTechnique>
+ auto
+ cudnnFindPlan(cudnnHandle_t handle,
+ cudnn_frontend::OperationGraph &opGraph,
+ cudnn_frontend::VariantPack const &variantPack) -> executionPlans_t;
+
+ template <CudnnFindSamplingTechnique samplingTechnique>
+ auto
+ cudnnFindPlanAndCache(
+ cudnnHandle_t handle,
+ cudnn_frontend::OperationGraph &opGraph,
+ cudnn_frontend::VariantPack const &variantPack,
+ cudnn_frontend::ExecutionPlanCache &cache,
+ Predicate pred = [](const cudnn_frontend::ExecutionPlan &) { return false; }) -> cudnn_frontend::ExecutionPlan;
+};
+
+/// Filter out the execution plan based on the prerequisite conditions.
+/// Goes through vector of execution plans and if the predicate returns
+/// not to block (false), it is inserted into the filtered plans.
+static auto
+filter(Predicate pred, executionPlans_t &plans) -> executionPlans_t {
+ executionPlans_t filtered_plans;
+ for (auto &plan : plans) {
+ CUDNN_FE_LOG_LABEL("Filtered ");
+ if (!pred(plan)) {
+ CUDNN_FE_LOG("and Added ");
+ filtered_plans.emplace_back(std::move(plan));
+ }
+ if (filtered_plans.size()) {
+ CUDNN_FE_LOG(filtered_plans.back().getTag() << std::endl);
+ }
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("Filtered plans count " << filtered_plans.size());
+ return filtered_plans;
+}
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_EngineFallbackList.h b/deps/cudnn-frontend/include/cudnn_frontend_EngineFallbackList.h
new file mode 100644
index 0000000..88f4fd1
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_EngineFallbackList.h
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <numeric>
+#include "cudnn_frontend_Heuristics.h"
+
+namespace cudnn_frontend {
+
+[[maybe_unused]] auto static get_fallback_engine_list(DescriptorType_t mode, const std::string &opGraphTag)
+ -> std::vector<int> {
+ auto major_version = detail::get_backend_version() / 1000;
+
+ auto minor_version = (detail::get_backend_version() / 100) % 10;
+ if (major_version >= 8) {
+ if (minor_version <= 2) {
+ /// Here we are using the term "bias" in the operationGraph as a proxy for
+ /// the conv*bias* operation graph. We are not strictly checking the order of
+ /// the operations in the graph. We propose this as a temporary workaround until
+ /// the backend API supports querying the fallback list directly from cudnn
+ if (mode == DescriptorType_t::OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR) {
+ if (opGraphTag.find("bias") == std::string::npos) {
+ std::vector<int> engine_list(50);
+ std::iota(engine_list.begin(), engine_list.end(), 0);
+ return engine_list;
+ } else {
+ return {11, 0};
+ }
+ } else if (mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) {
+ std::vector<int> engine_list(61);
+ std::iota(engine_list.begin(), engine_list.end(), 0);
+ return engine_list;
+ } else if (mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR) {
+ return {0, 1, 20};
+ } else {
+ return {};
+ }
+ } else {
+ if (mode == DescriptorType_t::OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR) {
+ if (opGraphTag.find("bias") == std::string::npos) {
+ return {0, 1, 28};
+ } else {
+ return {};
+ }
+ } else if (mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) {
+ return {0, 1, 25};
+ } else if (mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR) {
+ return {0, 1, 20};
+ } else {
+ return {};
+ }
+ }
+ } else {
+ return {};
+ }
+}
+
+class EngineFallbackList_v8 : public BackendDescriptor {
+ public:
+ friend class EngineFallbackListBuilder_v8;
+
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_FALLBACK ENGINES :";
+ return ss.str();
+ }
+
+ auto
+ getFallbackList() -> std::vector<ManagedOpaqueDescriptor> & {
+ return m_engine_configs;
+ }
+
+ ~EngineFallbackList_v8() = default;
+
+ EngineFallbackList_v8(EngineFallbackList_v8 &&from)
+ : BackendDescriptor(from.get_desc(), from.get_status(), from.get_error()),
+ opGraph(from.opGraph),
+ mode(from.mode),
+ num_ops(from.num_ops),
+ opGraphTag(from.opGraphTag) {
+ m_engine_configs.swap(from.m_engine_configs);
+ }
+
+ private:
+ EngineFallbackList_v8() = default;
+ EngineFallbackList_v8(EngineFallbackList_v8 const &) = delete;
+ EngineFallbackList_v8 &
+ operator=(EngineFallbackList_v8 const &) = delete;
+
+ ManagedOpaqueDescriptor opGraph = nullptr;
+ DescriptorType_t mode;
+ uint64_t num_ops;
+ std::vector<ManagedOpaqueDescriptor> m_engine_configs;
+ std::string opGraphTag;
+};
+
+///
+/// EngineFallBackListBuilder Class
+/// Helper class used to build EngineFallBackList class
+class EngineFallbackListBuilder_v8 {
+ public:
+ /** @defgroup EngineFallbackListBuilder_v8
+ * Set individual property of EngineFallbackList_v8 class
+ * @{
+ */
+ //! Set operationGraph for the engine (opGraph is not destroyed)
+ auto
+ setOperationGraph(OperationGraph_v8 &opGraph_) -> EngineFallbackListBuilder_v8 & {
+ m_fallback_list.opGraph = opGraph_.get_desc();
+ m_fallback_list.opGraphTag = opGraph_.getTag();
+ m_fallback_list.num_ops = opGraph_.getOpCount();
+ return *this;
+ }
+
+ auto
+ setOperation(DescriptorType_t mode) -> EngineFallbackListBuilder_v8 & {
+ m_fallback_list.mode = mode;
+ return *this;
+ }
+
+ auto
+ setOperation(cudnnBackendDescriptorType_t mode) -> EngineFallbackListBuilder_v8 & {
+ m_fallback_list.mode = detail::convert_from_cudnn_type(mode);
+ return *this;
+ }
+ /** @} */
+
+ //! constructs the EngineFallbackList_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ EngineFallbackList_v8 &&
+ build() {
+ if (m_fallback_list.opGraph == nullptr) {
+ set_error_and_throw_exception(&m_fallback_list,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: Check and Set the "
+ "CUDNN_ATTR_ENGINEHEUR_OPERATION_GRAPH field for heuristic");
+ return std::move(m_fallback_list);
+ };
+ auto fallback_heuristics = EngineHeuristicsBuilder_v8()
+ .setHeurMode(CUDNN_HEUR_MODE_FALLBACK)
+ .setOperationGraph(m_fallback_list.opGraph, m_fallback_list.opGraphTag)
+ .build();
+ auto count = fallback_heuristics.getEngineConfigCount();
+ m_fallback_list.m_engine_configs = fallback_heuristics.getEngineConfig(count);
+ CUDNN_FE_LOG_LABEL_ENDL(m_fallback_list);
+ return std::move(m_fallback_list);
+ }
+
+ explicit EngineFallbackListBuilder_v8() = default;
+ ~EngineFallbackListBuilder_v8() = default;
+ EngineFallbackListBuilder_v8(EngineFallbackListBuilder_v8 &&) = delete;
+ EngineFallbackListBuilder_v8(EngineFallbackListBuilder_v8 const &) = delete;
+ EngineFallbackListBuilder_v8 &
+ operator=(EngineFallbackListBuilder_v8 const &) = delete;
+
+ private:
+ EngineFallbackList_v8 m_fallback_list;
+};
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Errata.h b/deps/cudnn-frontend/include/cudnn_frontend_Errata.h
new file mode 100644
index 0000000..9f2ddf6
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Errata.h
@@ -0,0 +1,293 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#include "../include/cudnn_frontend_Logging.h"
+
+#include <cstdlib>
+#include <fstream>
+#pragma once
+
+namespace cudnn_frontend {
+
+// Loads the json handle from the json file
+// json file is defined by environment variable
+// CUDNN_ERRATA_JSON_FILE. If the environment variable
+// is not set the value set in the API is considered.
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+[[maybe_unused]] static bool
+load_from_config(json &json_handle, const std::string &errata_json) {
+ const char *err_json = get_environment("CUDNN_ERRATA_JSON_FILE");
+ if (err_json == NULL && errata_json == "") {
+ return false;
+ }
+ if (err_json == NULL) {
+ err_json = errata_json.c_str();
+ }
+ std::ifstream ifs(err_json, std::ifstream::in);
+ if (!ifs.is_open() || !ifs.good()) {
+ return false;
+ }
+ ifs >> json_handle;
+ return true;
+}
+#endif
+
+/**
+ * @brief Checks the shape of an operation to compare against errata filter height and width for kernel blocking
+ *
+ * @param op The operation's tensors to check
+ * @param shape_format The shape format of the tensor (NCHW vs NHWC)
+ * @param tensor_attr The cudnnBackendAttributeName_t of the tensor's shape we want to check
+ * @param blocked_height The height we want to filter out
+ * @param blocked_width The width we want to filter out
+ * @param blocked_channels The channels we want to filter out. Defaults to -1 (not filter out channels)
+ * @return true The passed in operation shape matches the blocked shape
+ * @return false The passed in operation shape does not match the blocked shape
+ */
+static bool
+check_shape(cudnnBackendDescriptor_t &op,
+ const std::string &shape_format,
+ cudnnBackendAttributeName_t tensor_attr,
+ const std::vector<int64_t> &blocked_shape) {
+ // Get backend descriptor to individual tensor to be able to get shape
+ ManagedOpaqueDescriptor tensor = make_shared_backend_pointer(CUDNN_BACKEND_TENSOR_DESCRIPTOR);
+ cudnnBackendDescriptor_t tensor_ = tensor->get_backend_descriptor();
+ int64_t count = 0;
+ cudnnStatus_t status = detail::get_attribute(op, tensor_attr, CUDNN_TYPE_BACKEND_DESCRIPTOR, 1, &count, &tensor_);
+ if (status != CUDNN_STATUS_SUCCESS) {
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+ throw cudnnException(std::string("Error getting attribute. cudnn_status: " + to_string(status)).c_str(),
+ status);
+#endif
+ }
+
+ // Get tensor dims
+ std::array<int64_t, 5> tensor_dims;
+ status =
+ detail::get_attribute(tensor_, CUDNN_ATTR_TENSOR_DIMENSIONS, CUDNN_TYPE_INT64, 5, &count, tensor_dims.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+ throw cudnnException(std::string("Error getting attribute. cudnn_status: " + to_string(status)).c_str(),
+ status);
+#endif
+ }
+ // tensor_dims is 1 indexed
+ int64_t first_dim = tensor_dims[1]; // batch size for input/output tensor, output channels for filter tensor
+ int64_t blocked_first_dim = blocked_shape[0];
+
+ // Defaults to true becuase -1 means we don't filter that out (Wildcard). If something later blocks, then the
+ // comparison will be correct
+ bool blocked = (blocked_first_dim != -1) ? (first_dim == blocked_first_dim) : true;
+
+ // Check for shape format to extract the right dimension. Filter shape will always be "NCHW" for convenience.
+ int64_t channels = (shape_format == "NCHW") ? tensor_dims[2] : tensor_dims[4]; // channels
+ int64_t blocked_channels = (shape_format == "NCHW") ? blocked_shape[1] : blocked_shape[3];
+ blocked = (blocked_channels != -1) ? (blocked && channels == blocked_channels) : true;
+
+ int64_t height = (shape_format == "NCHW") ? tensor_dims[3] : tensor_dims[2];
+ int64_t blocked_height = (shape_format == "NCHW") ? blocked_shape[2] : blocked_shape[1];
+ blocked = (blocked_height != -1) ? (blocked && height == blocked_height) : true;
+
+ int64_t width = (shape_format == "NCHW") ? tensor_dims[4] : tensor_dims[3];
+ int64_t blocked_width = (shape_format == "NCHW") ? blocked_shape[3] : blocked_shape[2];
+ blocked = (blocked_width != -1) ? (blocked && width == blocked_width) : true;
+
+ return blocked;
+}
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+template <typename T>
+static bool
+check_rule(const json &json_handle, const std::string &executionPlanTag, cudnnHandle_t handle, T fn) {
+ std::string operation = json_handle["operation"];
+ int64_t engine = json_handle["engine"];
+ uint64_t cudnn_start = 0;
+ uint64_t cudnn_end = std::numeric_limits<uint64_t>::max();
+ if (json_handle.contains("cudnn_version_start")) {
+ cudnn_start = json_handle["cudnn_version_start"];
+ }
+ if (json_handle.contains("cudnn_version_end")) {
+ cudnn_end = json_handle["cudnn_version_end"];
+ }
+ std::string tag_prefix = operation + "_eng" + std::to_string(engine) + "_";
+ std::string mod_tag = executionPlanTag + "_";
+ bool blocked = tag_prefix.size() <= mod_tag.size() &&
+ std::equal(tag_prefix.begin(), tag_prefix.end(), mod_tag.begin()) && CUDNN_VERSION >= cudnn_start &&
+ CUDNN_VERSION < cudnn_end;
+
+ if (blocked && json_handle.contains("knob")) { // Short circuit if operation and engine do not match
+ for (auto &kv : json_handle["knob"]) {
+ blocked = blocked && (executionPlanTag.find(kv) != std::string::npos);
+ }
+ }
+ blocked = blocked && fn();
+ return blocked;
+
+ CUDNN_FRONTEND_UNUSED(handle);
+}
+
+// Overload for check_rule to take in an operation graph for shape filtering
+template <typename T>
+static bool
+check_rule(const json &json_handle,
+ const std::string &executionPlanTag,
+ cudnnHandle_t handle,
+ T fn,
+ const OperationGraph &opGraph) {
+ std::string operation = json_handle["operation"];
+ int64_t engine = json_handle["engine"];
+ uint64_t cudnn_start = 0;
+ uint64_t cudnn_end = std::numeric_limits<uint64_t>::max();
+ if (json_handle.contains("cudnn_version_start")) {
+ cudnn_start = json_handle["cudnn_version_start"];
+ }
+ if (json_handle.contains("cudnn_version_end")) {
+ cudnn_end = json_handle["cudnn_version_end"];
+ }
+ std::string tag_prefix = operation + "_eng" + std::to_string(engine) + "_";
+ std::string mod_tag = executionPlanTag + "_";
+ bool blocked = tag_prefix.size() <= mod_tag.size() &&
+ std::equal(tag_prefix.begin(), tag_prefix.end(), mod_tag.begin()) && CUDNN_VERSION >= cudnn_start &&
+ CUDNN_VERSION < cudnn_end;
+
+ if (blocked && json_handle.contains("knob")) { // Short circuit if operation and engine do not match
+ for (auto &kv : json_handle["knob"]) {
+ blocked = blocked && (executionPlanTag.find(kv) != std::string::npos);
+ }
+ }
+
+ if (blocked &&
+ json_handle.contains("input_shape")) { // Check if user wants to block kernel for specific input shape
+ if (!json_handle.contains("shape_format")) {
+ std::string message =
+ "ERROR: Please set a shape format (e.g. shape_format: \"NCWH\") for errata filters using input/kernel "
+ "shape";
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+ throw cudnnException(message.c_str(), CUDNN_STATUS_BAD_PARAM);
+#else
+ CUDNN_FE_LOG(message << std::endl);
+ return blocked;
+#endif
+ }
+
+ std::array<ManagedOpaqueDescriptor, MAX_OPGRAPH_OPS> ops = opGraph.getOps();
+ std::array<cudnnBackendDescriptor_t, MAX_OPGRAPH_OPS> ops_;
+ for (unsigned int i = 0; i < opGraph.getOpCount(); i++) {
+ ops_[i] = ops[i]->get_backend_descriptor();
+ }
+
+ std::string shape_format = json_handle["shape_format"];
+ std::vector<int64_t> blocked_shape = json_handle["input_shape"];
+
+ // Forward conv operation
+ if (operation == "ConvFwd") {
+ blocked = blocked &&
+ check_shape(ops_[0], shape_format, CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_X, blocked_shape);
+
+ // Operation is conv wgrad
+ } else if (operation == "ConvBwdFilter") {
+ blocked = blocked &&
+ check_shape(ops_[0], shape_format, CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_X, blocked_shape);
+
+ // Operation is conv dgrad
+ } else if (operation == "ConvBwdData") {
+ blocked = blocked &&
+ check_shape(ops_[0], shape_format, CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_DX, blocked_shape);
+ }
+ }
+
+ if (blocked &&
+ json_handle.contains("filter_shape")) { // Check if user wants to block kernel for specific filter shape
+ std::array<ManagedOpaqueDescriptor, MAX_OPGRAPH_OPS> ops = opGraph.getOps();
+ std::array<cudnnBackendDescriptor_t, MAX_OPGRAPH_OPS> ops_;
+ for (unsigned int i = 0; i < opGraph.getOpCount(); i++) {
+ ops_[i] = ops[i]->get_backend_descriptor();
+ }
+
+ std::vector<int64_t> blocked_shape = json_handle["filter_shape"];
+
+ // Forward conv operation
+ if (operation == "ConvFwd") {
+ // Filter format is always [output channels, input channels, height, width] so we hardcode "NCHW" to match
+ // and not repeat code
+ blocked =
+ blocked && check_shape(ops_[0], "NCHW", CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_W, blocked_shape);
+
+ // Operation is conv wgrad
+ } else if (operation == "ConvBwdFilter") {
+ blocked =
+ blocked && check_shape(ops_[0], "NCHW", CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_DW, blocked_shape);
+
+ // Operation is conv dgrad
+ } else if (operation == "ConvBwdData") {
+ blocked =
+ blocked && check_shape(ops_[0], "NCHW", CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_W, blocked_shape);
+ }
+ }
+ blocked = blocked && fn();
+ return blocked;
+
+ CUDNN_FRONTEND_UNUSED(handle);
+}
+
+// Takes in an initialzed json handle and checks if it satisfies the
+// condition for running it. Returns true if the given executionPlanTag
+// is faulty.
+
+template <typename T>
+static bool
+check_errata(const json &json_handle, const std::string &executionPlanTag, cudnnHandle_t handle, T fn) {
+ CUDNN_FE_LOG_LABEL("Verifying " << executionPlanTag);
+ for (auto const &rule : json_handle["rules"]) {
+ if (check_rule<T>(rule, executionPlanTag, handle, fn)) {
+ CUDNN_FE_LOG(". Blocking." << std::endl);
+ return true;
+ }
+ }
+
+ CUDNN_FE_LOG(". Passed." << std::endl);
+ return false;
+}
+
+// Overload. Takes in an initialzed json handle, an execution plan tag, and a operation graph and checks if it satisfies
+// the condition for running it. Returns true if the given executionPlanTag + operation graph is faulty
+template <typename T>
+static bool
+check_errata(const json &json_handle,
+ const std::string &executionPlanTag,
+ cudnnHandle_t handle,
+ const OperationGraph &opGraph,
+ T fn) {
+ CUDNN_FE_LOG_LABEL("Verifying " << executionPlanTag);
+ for (auto const &rule : json_handle["rules"]) {
+ if (check_rule<T>(rule, executionPlanTag, handle, fn, opGraph)) {
+ CUDNN_FE_LOG(". Blocking." << std::endl);
+ return true;
+ }
+ }
+
+ CUDNN_FE_LOG(". Passed." << std::endl);
+ return false;
+}
+#endif
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_ExecutionPlan.h b/deps/cudnn-frontend/include/cudnn_frontend_ExecutionPlan.h
new file mode 100644
index 0000000..9d0a897
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_ExecutionPlan.h
@@ -0,0 +1,599 @@
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <iterator>
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "cudnn_frontend_EngineConfig.h"
+#include "cudnn_frontend_Engine.h"
+#include "cudnn_frontend_utils.h"
+#include "cudnn_frontend/backend/kernel_cache.h"
+#include "cudnn_frontend/backend/device_properties.h"
+
+namespace cudnn_frontend {
+///
+/// ExecutionPlan_v8 Class
+/// This class tells the Configuration of the Engine in terms of the knob
+/// choices
+/// Properties:
+/// - num knobs
+/// - Choice
+/// - Engine
+///
+/// Use ExecutionPlanBuilder_v8 to build this class.
+/// Describe returns a string describing the tensor class
+///
+class ExecutionPlan_v8 : public BackendDescriptor {
+ public:
+ friend class ExecutionPlanBuilder_v8;
+
+ ExecutionPlan_v8(ExecutionPlan_v8 &&from) = default;
+ ExecutionPlan_v8 &
+ operator=(ExecutionPlan_v8 &&) = default;
+
+ ~ExecutionPlan_v8() = default;
+ /** @defgroup ExecutionPlanQuery
+ * Query individual property of ExecutionPlan_v8 class
+ * @{
+ */
+ //! Query the workspace requirement for the given plan
+ auto
+ getWorkspaceSize(void) const -> int64_t {
+ return workSpaceSize;
+ }
+
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR : ";
+ ss << getTag() << ", ";
+ ss << "numeric_notes:" << "[";
+ for (auto note : numeric_notes_vec) {
+ ss << cudnn_frontend::to_string(note) << ",";
+ }
+ ss << "] behavior_notes:" << "[";
+ for (auto note : behavior_notes_vec) {
+ ss << cudnn_frontend::to_string(note) << ",";
+ }
+ ss << "] workSpaceSize: " << workSpaceSize;
+ return ss.str();
+ }
+
+ std::string const &
+ getTag() const {
+ return planTag;
+ }
+
+ void
+ setExecutionTime(float time_) {
+ execution_time_ms = time_;
+ }
+
+ float
+ getExecutionTime() const {
+ return execution_time_ms;
+ }
+
+ std::vector<cudnnBackendNumericalNote_t> const &
+ getAllNumericNotes() const {
+ return numeric_notes_vec;
+ }
+
+ std::array<cudnnBackendNumericalNote_t, CUDNN_NUMERICAL_NOTE_TYPE_COUNT> const &
+ getNumericNotes() const {
+ return numeric_notes;
+ }
+
+ std::array<cudnnBackendBehaviorNote_t, CUDNN_BEHAVIOR_NOTE_TYPE_COUNT> const &
+ getBehaviorNotes() const {
+ return behavior_notes;
+ }
+ std::vector<cudnnBackendBehaviorNote_t> const &
+ getAllBehaviorNotes() const {
+ return behavior_notes_vec;
+ }
+
+ std::string
+ getJsonRepresentation() const {
+ auto status = CUDNN_STATUS_SUCCESS;
+ int64_t serializationSize;
+ std::vector<char> serialization_buf;
+ status = detail::get_attribute(pointer->get_backend_descriptor(),
+ CUDNN_ATTR_EXECUTION_PLAN_JSON_REPRESENTATION,
+ CUDNN_TYPE_CHAR,
+ 0,
+ &serializationSize,
+ nullptr);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_EXECUTION_PLAN_JSON_REPRESENTATION Failed");
+ }
+ serialization_buf.resize(static_cast<size_t>(serializationSize));
+ status = detail::get_attribute(pointer->get_backend_descriptor(),
+ CUDNN_ATTR_EXECUTION_PLAN_JSON_REPRESENTATION,
+ CUDNN_TYPE_CHAR,
+ serializationSize,
+ &serializationSize,
+ serialization_buf.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_EXECUTION_PLAN_JSON_REPRESENTATION Failed");
+ }
+ std::string json_string(serialization_buf.begin(), serialization_buf.end());
+ return json_string;
+ }
+
+ ExecutionPlan_v8(ExecutionPlan_v8 const &) = default;
+ ExecutionPlan_v8 &
+ operator=(ExecutionPlan_v8 const &) = default;
+
+ private:
+ void
+ fetchNotes(ManagedOpaqueDescriptor &extractedEngine) {
+ auto status = CUDNN_STATUS_SUCCESS;
+ int64_t elem_count = 0;
+ cudnnBackendDescriptor_t extractedEngine_ = extractedEngine->get_backend_descriptor();
+ status = detail::get_attribute(extractedEngine_,
+ CUDNN_ATTR_ENGINE_NUMERICAL_NOTE,
+ CUDNN_TYPE_NUMERICAL_NOTE,
+ CUDNN_NUMERICAL_NOTE_TYPE_COUNT,
+ &elem_count,
+ nullptr);
+ numeric_notes_vec.resize(static_cast<size_t>(elem_count));
+ status = detail::get_attribute(extractedEngine_,
+ CUDNN_ATTR_ENGINE_NUMERICAL_NOTE,
+ CUDNN_TYPE_NUMERICAL_NOTE,
+ CUDNN_NUMERICAL_NOTE_TYPE_COUNT,
+ &elem_count,
+ numeric_notes_vec.data());
+ ptrdiff_t end =
+ static_cast<ptrdiff_t>(std::min(elem_count, static_cast<int64_t>(CUDNN_NUMERICAL_NOTE_TYPE_COUNT)));
+ std::copy(numeric_notes_vec.begin(), numeric_notes_vec.begin() + end, numeric_notes.begin());
+ if (static_cast<size_t>(elem_count) < numeric_notes.size())
+ std::fill_n(numeric_notes.begin() + static_cast<size_t>(elem_count),
+ numeric_notes.size() - static_cast<size_t>(elem_count),
+ CUDNN_NUMERICAL_NOTE_TYPE_COUNT);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_ENGINE_NUMERICAL_NOTE Failed");
+ }
+ status = detail::get_attribute(extractedEngine_,
+ CUDNN_ATTR_ENGINE_BEHAVIOR_NOTE,
+ CUDNN_TYPE_BEHAVIOR_NOTE,
+ CUDNN_BEHAVIOR_NOTE_TYPE_COUNT,
+ &elem_count,
+ nullptr);
+ behavior_notes_vec.resize(static_cast<size_t>(elem_count));
+ status = detail::get_attribute(extractedEngine_,
+ CUDNN_ATTR_ENGINE_BEHAVIOR_NOTE,
+ CUDNN_TYPE_BEHAVIOR_NOTE,
+ CUDNN_BEHAVIOR_NOTE_TYPE_COUNT,
+ &elem_count,
+ behavior_notes_vec.data());
+ end = static_cast<ptrdiff_t>(std::min(elem_count, static_cast<int64_t>(CUDNN_BEHAVIOR_NOTE_TYPE_COUNT)));
+ std::copy(behavior_notes_vec.begin(), behavior_notes_vec.begin() + end, behavior_notes.begin());
+ if (static_cast<size_t>(elem_count) < behavior_notes.size())
+ std::fill_n(behavior_notes.begin() + static_cast<size_t>(elem_count),
+ behavior_notes.size() - static_cast<size_t>(elem_count),
+ CUDNN_BEHAVIOR_NOTE_TYPE_COUNT);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_ENGINE_BEHAVIOR_NOTE Failed");
+ }
+ }
+
+ void
+ buildTag(ManagedOpaqueDescriptor &extractedEngine) {
+ // Compute a unique tag for execution plan:
+ auto status = CUDNN_STATUS_SUCCESS;
+ std::stringstream tag{""};
+ int64_t elemCount = 0, engineId = 0, numKnobs = 0;
+
+ std::array<ManagedOpaqueDescriptor, CUDNN_KNOB_TYPE_COUNTS> extractedKnobs{{nullptr}};
+ for (auto &knob : extractedKnobs) {
+ knob = make_shared_backend_pointer(CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR);
+ status = knob->get_status();
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ this, status, "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: cudnnCreate Failed when compute tag");
+ }
+ }
+
+ cudnnBackendDescriptor_t extractedEngine_ = extractedEngine->get_backend_descriptor();
+ std::array<cudnnBackendDescriptor_t, CUDNN_KNOB_TYPE_COUNTS> extractedKnobs_{{nullptr}};
+ for (std::uint32_t i = 0; i < extractedKnobs.size(); i++) {
+ extractedKnobs_[i] = extractedKnobs[i]->get_backend_descriptor();
+ }
+
+ status = detail::get_attribute(
+ extractedEngine_, CUDNN_ATTR_ENGINE_GLOBAL_INDEX, CUDNN_TYPE_INT64, 1, &elemCount, &engineId);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_ENGINE_GLOBAL_INDEX Failed");
+ }
+ tag << "eng" << engineId;
+
+ status = detail::get_attribute(engine_config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_KNOB_CHOICES,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ CUDNN_KNOB_TYPE_COUNTS,
+ &numKnobs,
+ &(extractedKnobs_[0]));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_ENGINECFG_KNOB_CHOICES Failed");
+ }
+ if (numKnobs > CUDNN_KNOB_TYPE_COUNTS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "numKnobs exceed the CUDNN_KNOB_TYPE_COUNTS");
+ }
+ for (size_t idx = 0; idx < static_cast<size_t>(numKnobs); ++idx) {
+ const cudnnBackendDescriptor_t &knob = extractedKnobs_[idx];
+ cudnnBackendKnobType_t type = CUDNN_KNOB_TYPE_COUNTS;
+ int64_t choice = -2;
+ status =
+ detail::get_attribute(knob, CUDNN_ATTR_KNOB_CHOICE_KNOB_TYPE, CUDNN_TYPE_KNOB_TYPE, 1, nullptr, &type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "computeTag CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_KNOB_CHOICE_KNOB_TYPE Failed");
+ }
+ status =
+ detail::get_attribute(knob, CUDNN_ATTR_KNOB_CHOICE_KNOB_VALUE, CUDNN_TYPE_INT64, 1, nullptr, &choice);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_KNOB_CHOICE_KNOB_VALUE Failed");
+ }
+ tag << "_k" << type << "=" << choice;
+ }
+ planTag += tag.str();
+ }
+
+ void
+ computeWorkSpaceSize() {
+ auto status = detail::get_attribute(pointer->get_backend_descriptor(),
+ CUDNN_ATTR_EXECUTION_PLAN_WORKSPACE_SIZE,
+ CUDNN_TYPE_INT64,
+ 1,
+ nullptr,
+ &workSpaceSize);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_EXECUTION_PLAN_WORKSPACE_SIZE Failed");
+ }
+ if (workSpaceSize < 0) {
+ set_error_and_throw_exception(
+ this, status, "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute Workspace Size Invalid");
+ }
+ }
+
+ ExecutionPlan_v8() = default;
+ ManagedOpaqueDescriptor engine_config = nullptr;
+ cudnnHandle_t handle = nullptr;
+ std::string planTag;
+
+ std::int64_t workSpaceSize = 0;
+ std::array<cudnnBackendNumericalNote_t, CUDNN_NUMERICAL_NOTE_TYPE_COUNT> numeric_notes;
+ std::vector<cudnnBackendNumericalNote_t> numeric_notes_vec;
+ std::array<cudnnBackendBehaviorNote_t, CUDNN_BEHAVIOR_NOTE_TYPE_COUNT> behavior_notes;
+ std::vector<cudnnBackendBehaviorNote_t> behavior_notes_vec;
+
+ float execution_time_ms = 0.0f;
+ std::shared_ptr<KernelCache> kernel_cache = nullptr;
+};
+
+///
+/// ExecutionPlanBuilder_v8 Class
+/// Helper class used to build ExecutionPlan_v8 class
+class ExecutionPlanBuilder_v8 {
+ public:
+ /** @defgroup ExecutionPlanBuilder_v8
+ * Set individual property of ExecutionPlan_v8 class
+ * @{
+ */
+ //! Set engine for the ExecutionPlan_v8
+ auto
+ setHandle(cudnnHandle_t handle_) -> ExecutionPlanBuilder_v8 & {
+ m_execution_plan.handle = handle_;
+ return *this;
+ }
+ //! Set engine Config for the Plan
+ auto
+ setEngineConfig(EngineConfig_v8 const &engine_config_) -> ExecutionPlanBuilder_v8 & {
+ m_execution_plan.engine_config = engine_config_.get_desc();
+ m_execution_plan.planTag = engine_config_.getTag();
+ return *this;
+ }
+
+ auto
+ setKernelCache(std::shared_ptr<KernelCache> kernel_cache) -> ExecutionPlanBuilder_v8 & {
+ m_execution_plan.kernel_cache = kernel_cache;
+ return *this;
+ }
+
+ //! Set engine Config for the Plan
+ auto
+ setEngineConfig(ManagedOpaqueDescriptor &desc, std::string const &opGraphTag_ = "") -> ExecutionPlanBuilder_v8 & {
+ m_execution_plan.engine_config = desc;
+ m_execution_plan.planTag = opGraphTag_;
+ return *this;
+ }
+
+ auto
+ setEngineConfig(ManagedOpaqueDescriptor const &desc, std::string const &opGraphTag_ = "")
+ -> ExecutionPlanBuilder_v8 & {
+ m_execution_plan.engine_config = desc;
+ m_execution_plan.planTag = opGraphTag_;
+ return *this;
+ }
+ /** @} */
+
+ //! constructs the Engine Config by calling the cudnn API
+ //! Throws the appropriate error message
+ ExecutionPlan_v8 &&
+ build() {
+ // NOTE: skipping the handle and device properties here which are required for plan deserialization only
+
+ if (m_execution_plan.engine_config == nullptr) {
+ set_error_and_throw_exception(
+ &m_execution_plan,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: Check and Set the CUDNN_ATTR_EXECUTION_PLAN_ENGINE_CONFIG");
+ return std::move(m_execution_plan);
+ };
+
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_execution_plan.initialize_managed_backend_pointer(CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_execution_plan, status, "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_execution_plan);
+ }
+
+ status = detail::set_attribute(m_execution_plan.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_EXECUTION_PLAN_ENGINE_CONFIG,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_execution_plan.engine_config->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: SetAttribute CUDNN_ATTR_EXECUTION_PLAN_ENGINE_CONFIG Failed");
+ return std::move(m_execution_plan);
+ }
+
+#if (CUDNN_VERSION >= 90400)
+ if (m_execution_plan.kernel_cache) {
+ status = detail::set_attribute(m_execution_plan.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_EXECUTION_PLAN_KERNEL_CACHE,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &m_execution_plan.kernel_cache->get_ptr());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_EXECUTION_PLAN_KERNEL_CACHE Failed");
+ return std::move(m_execution_plan);
+ }
+ }
+#endif
+ // Finalizing the descriptor
+ status = detail::finalize(m_execution_plan.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_execution_plan, status, "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: cudnnFinalize Descriptor Failed");
+ return std::move(m_execution_plan);
+ }
+
+ ManagedOpaqueDescriptor extractedEngine = make_shared_backend_pointer(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ status = extractedEngine->get_status();
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: cudnnCreate of "
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR failed when compute tag");
+ return std::move(m_execution_plan);
+ }
+ cudnnBackendDescriptor_t extractedEngine_ = extractedEngine->get_backend_descriptor();
+ int64_t elemCount = 0;
+ status = detail::get_attribute(m_execution_plan.engine_config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_ENGINE,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &elemCount,
+ &extractedEngine_);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_ENGINECFG_ENGINE Failed");
+ return std::move(m_execution_plan);
+ }
+
+ m_execution_plan.buildTag(extractedEngine);
+ m_execution_plan.fetchNotes(extractedEngine);
+ m_execution_plan.computeWorkSpaceSize();
+
+ CUDNN_FE_LOG_LABEL_ENDL(m_execution_plan);
+ return std::move(m_execution_plan);
+ }
+
+ ExecutionPlan_v8 &&
+ loadFromJson(const std::string &json_plan) {
+ CUDNN_FRONTEND_UNUSED(json_plan);
+ auto status = CUDNN_STATUS_SUCCESS;
+
+ if (m_execution_plan.handle == nullptr) {
+ set_error_and_throw_exception(
+ &m_execution_plan,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: Check and Set the CUDNN_ATTR_EXECUTION_PLAN_HANDLE");
+ return std::move(m_execution_plan);
+ };
+
+ // Create a descriptor. Memory allocation happens here.
+ status = m_execution_plan.initialize_managed_backend_pointer(CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_execution_plan, status, "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_execution_plan);
+ }
+
+ std::vector<char> serialization_buf;
+ serialization_buf.assign(json_plan.begin(), json_plan.end());
+ status = detail::set_attribute(m_execution_plan.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_EXECUTION_PLAN_JSON_REPRESENTATION,
+ CUDNN_TYPE_CHAR,
+ serialization_buf.size(),
+ serialization_buf.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_EXECUTION_PLAN_JSON_REPRESENTATION Failed");
+ return std::move(m_execution_plan);
+ }
+
+ status = detail::set_attribute(m_execution_plan.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_EXECUTION_PLAN_HANDLE,
+ CUDNN_TYPE_HANDLE,
+ 1,
+ &m_execution_plan.handle);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: SetAttribute CUDNN_ATTR_EXECUTION_PLAN_HANDLE Failed");
+ return std::move(m_execution_plan);
+ }
+
+ status = detail::finalize(m_execution_plan.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_execution_plan, status, "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: cudnnFinalize Descriptor Failed");
+ return std::move(m_execution_plan);
+ }
+
+ m_execution_plan.engine_config = make_shared_backend_pointer(CUDNN_BACKEND_ENGINECFG_DESCRIPTOR);
+ status = m_execution_plan.engine_config->get_status();
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: cudnnCreate of "
+ "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR failed when computing tag");
+ return std::move(m_execution_plan);
+ }
+
+ cudnnBackendDescriptor_t engCfgDesc = m_execution_plan.engine_config->get_backend_descriptor();
+ int64_t elemCount = 0;
+ status = detail::get_attribute(m_execution_plan.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_EXECUTION_PLAN_ENGINE_CONFIG,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &elemCount,
+ &engCfgDesc);
+
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_EXECUTION_PLAN_ENGINE_CONFIG Failed");
+ return std::move(m_execution_plan);
+ }
+ ManagedOpaqueDescriptor extractedEngine = make_shared_backend_pointer(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ status = extractedEngine->get_status();
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: cudnnCreate of "
+ "CUDNN_BACKEND_ENGINE_DESCRIPTOR failed when computing tag");
+ return std::move(m_execution_plan);
+ }
+
+ cudnnBackendDescriptor_t extractedEngine_ = extractedEngine->get_backend_descriptor();
+
+ status = detail::get_attribute(m_execution_plan.engine_config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_ENGINE,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &elemCount,
+ &extractedEngine_);
+
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_execution_plan,
+ status,
+ "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_ENGINECFG_ENGINE Failed");
+ return std::move(m_execution_plan);
+ }
+
+ m_execution_plan.buildTag(extractedEngine);
+ m_execution_plan.fetchNotes(extractedEngine);
+ m_execution_plan.computeWorkSpaceSize();
+
+ CUDNN_FE_LOG_LABEL_ENDL(m_execution_plan);
+ return std::move(m_execution_plan);
+ }
+
+ explicit ExecutionPlanBuilder_v8() = default;
+ ~ExecutionPlanBuilder_v8() = default;
+ ExecutionPlanBuilder_v8(ExecutionPlanBuilder_v8 &&) = delete;
+ ExecutionPlanBuilder_v8(ExecutionPlanBuilder_v8 const &) = delete;
+ ExecutionPlanBuilder_v8 &
+ operator=(ExecutionPlanBuilder_v8 const &) = delete;
+
+ private:
+ ExecutionPlan_v8 m_execution_plan;
+};
+
+using ExecutionPlan = ExecutionPlan_v8;
+using ExecutionPlanBuilder = ExecutionPlanBuilder_v8;
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_ExecutionPlanCache.h b/deps/cudnn-frontend/include/cudnn_frontend_ExecutionPlanCache.h
new file mode 100644
index 0000000..e41a445
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_ExecutionPlanCache.h
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#include <tuple>
+#include <unordered_map>
+#include <map>
+#include <memory>
+#include <mutex>
+
+#include "cudnn_frontend_OperationGraph.h"
+#include "cudnn_frontend_ExecutionPlan.h"
+
+/// Execution Plan Caching:
+/// Goal is to auto-tune once and then save the best auto-tuned result for a problem for later use.
+/// For every unique Operation Graph (denoted by a string) we have a set of plans identified by a feature vector.
+/// The feature vector could be Tensor dimension/data_type and so on.
+/// Multiple operation Graph can share a feature vector type but may have different Execution Plan(s).
+
+/// The v1 cache has the following format.
+/// It is the reponsibility of the user to query the correct cache for the given device/operation graph combination.
+/***
+ * device_id_0 Operation_Graph0 (conv_fprop)
+ * -------------------------------------------------------------------------------
+ * | Feature_vector_type0_val0 | Plan A0 |
+ * | Feature_vector_type0_val1 | Plan B0 |
+ * ===============================================================================
+ *
+ * device_id_0 Operation_Graph1 (dgrad)
+ * -------------------------------------------------------------------------------
+ * | Feature_vector_type1_val0 | Plan A1 |
+ * | Feature_vector_type1_val1 | Plan B1 |
+ * ===============================================================================
+ *
+ * device_id_0 Operation_Graph2 (wgrad)
+ * -------------------------------------------------------------------------------
+ * | Feature_vector_type2_val0 | Plan B2 |
+ * ===============================================================================
+ *
+ * device_id_1 Operation_Graph0 (conv_fprop)
+ * -------------------------------------------------------------------------------
+ * | Feature_vector_type0_val0 | Plan A0 |
+ * | Feature_vector_type0_val1 | Plan B0 |
+ * ===============================================================================
+ *
+ * device_id_1 Operation_Graph1 (dgrad)
+ * -------------------------------------------------------------------------------
+ * | Feature_vector_type1_val0 | Plan A1 |
+ * | Feature_vector_type1_val1 | Plan B1 |
+ * ===============================================================================
+ *
+ * device_id_1 Operation_Graph2 (wgrad)
+ * -------------------------------------------------------------------------------
+ * | Feature_vector_type2_val0 | Plan B2 |
+ * ===============================================================================
+ */
+
+namespace cudnn_frontend {
+
+/// Plan Cache structure for the above table
+class ExecutionPlanCache_v1 {
+ protected:
+ struct compare {
+ bool
+ operator()(const feature_vector_t &fv1, const feature_vector_t &fv2) const {
+ return fv1 < fv2;
+ }
+ };
+
+ std::string name = "plan_cache_[unnamed]";
+
+ /// String to map of feature_vector to execution plan
+ /// For a given FeatureVector of type T according to the Operation Graph, we get the plan.
+ using FeatureVectorToPlanMap = std::map<cudnn_frontend::feature_vector_t,
+ cudnn_frontend::ExecutionPlan,
+ cudnn_frontend::ExecutionPlanCache_v1::compare>;
+ FeatureVectorToPlanMap cache;
+
+ mutable std::mutex cache_mutex;
+
+ public:
+ virtual bool
+ is_fastest_plan_stable(const cudnn_frontend::OperationGraph &op_graph, const std::string &tag) {
+ CUDNN_FRONTEND_UNUSED(op_graph);
+ CUDNN_FRONTEND_UNUSED(tag);
+ return true;
+ }
+
+ void
+ add_plan_to_cache(const cudnn_frontend::OperationGraph &op_graph, const cudnn_frontend::ExecutionPlan &plan) {
+ std::lock_guard<std::mutex> guard(cache_mutex);
+ cache.insert(std::make_pair(op_graph.getFeatureVector(), plan));
+ CUDNN_FE_LOG_LABEL_ENDL("Added to " << name << " " << op_graph.getTag());
+ }
+
+ ExecutionPlanCache_v1(const char *name_) { name = name_; }
+
+ const std::string &
+ get_name() const {
+ return name;
+ }
+
+ // Plan is the output here.
+ bool
+ get_plan_from_cache(const cudnn_frontend::OperationGraph &op_graph,
+ const cudnn_frontend::ExecutionPlan *&plan) const {
+ {
+ std::lock_guard<std::mutex> guard(cache_mutex);
+ auto it = cache.find(op_graph.getFeatureVector());
+
+ if (it == cache.end()) {
+ CUDNN_FE_LOG_LABEL_ENDL("Cached Plan Not Found in " << name);
+ return false;
+ }
+ plan = &(it->second);
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("Cached Plan Found in " << name);
+ return true;
+ }
+
+ virtual ~ExecutionPlanCache_v1() = default;
+};
+
+class ExecutionPlanCache_v2 : public ExecutionPlanCache_v1 {
+ using SaturationTracker = std::map<std::pair<cudnn_frontend::feature_vector_t, std::string>, int32_t>;
+ SaturationTracker tracker;
+
+ int32_t saturationCount = 1;
+
+ public:
+ virtual bool
+ is_fastest_plan_stable(const cudnn_frontend::OperationGraph &op_graph, const std::string &tag) {
+ if (saturationCount == 1) {
+ return true;
+ } // Special case. Always add to the cache.
+
+ // If plan cache is already created for the op_graph no need to update.
+ // Ideally, one will auto-tune only if the plan cache has no plan for the op_graph.
+ cudnn_frontend::ExecutionPlan const *plan = nullptr;
+ if (get_plan_from_cache(op_graph, plan)) {
+ CUDNN_FE_LOG_LABEL_ENDL("SaturationTracker " << name << " " << op_graph.getTag() << " " << tag
+ << " plan already in cache.");
+ return false;
+ }
+
+ // Lock the cache and increase the count till we saturate
+ std::lock_guard<std::mutex> guard(cache_mutex);
+ auto cnt = tracker[std::make_pair(op_graph.getFeatureVector(), tag)] += 1;
+ CUDNN_FE_LOG_LABEL_ENDL("SaturationTracker " << name << " " << op_graph.getTag() << " " << tag << " " << cnt);
+ return cnt >= saturationCount;
+ }
+
+ void
+ set_saturation_count(int32_t count) {
+ saturationCount = count;
+ }
+
+ ExecutionPlanCache_v2(const char *name_) : ExecutionPlanCache_v1(name_) {}
+
+ virtual ~ExecutionPlanCache_v2() = default;
+};
+
+using ExecutionPlanCache = ExecutionPlanCache_v2;
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Filters.h b/deps/cudnn-frontend/include/cudnn_frontend_Filters.h
new file mode 100644
index 0000000..d16170b
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Filters.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+namespace cudnn_frontend {
+
+// If filter_fn returns true
+// The engine config will be filtered out and will
+// not be part of the to list.
+static void
+filter(EngineConfigList &from, EngineConfigList &to, std::function<bool(cudnnBackendDescriptor_t)> filter_fn) {
+ auto p = std::stable_partition(from.begin(), from.end(), [filter_fn](ManagedOpaqueDescriptor &p) {
+ return filter_fn(const_cast<cudnnBackendDescriptor_t>(p->get_backend_descriptor()));
+ });
+ // range insert with move
+ to.insert(to.end(), std::make_move_iterator(p), std::make_move_iterator(from.end()));
+ // erase the moved-from elements.
+ from.erase(p, from.end());
+}
+
+template <cudnnBackendNumericalNote_t NUMERIC_NOTE>
+bool
+hasNumericalNote(cudnnBackendDescriptor_t engine_config) {
+ bool hasNumerics = false;
+ auto status = CUDNN_STATUS_SUCCESS;
+ ManagedOpaqueDescriptor engine = make_shared_backend_pointer(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ cudnnBackendDescriptor_t engine_ = engine->get_backend_descriptor();
+ int64_t engine_count = -1;
+ status = detail::get_attribute(
+ engine_config, CUDNN_ATTR_ENGINECFG_ENGINE, CUDNN_TYPE_BACKEND_DESCRIPTOR, 1, &engine_count, &engine_);
+ if (status == CUDNN_STATUS_SUCCESS) {
+ cudnnBackendNumericalNote_t notes[CUDNN_NUMERICAL_NOTE_TYPE_COUNT];
+ std::fill_n(notes, CUDNN_NUMERICAL_NOTE_TYPE_COUNT, CUDNN_NUMERICAL_NOTE_TYPE_COUNT);
+ int64_t elem_count = 0;
+ detail::get_attribute(engine->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINE_NUMERICAL_NOTE,
+ CUDNN_TYPE_NUMERICAL_NOTE,
+ CUDNN_NUMERICAL_NOTE_TYPE_COUNT,
+ &elem_count,
+ notes);
+ if (std::any_of(
+ notes, notes + elem_count, [](cudnnBackendNumericalNote_t note) { return note == NUMERIC_NOTE; })) {
+ hasNumerics = true;
+ }
+ }
+ return hasNumerics;
+}
+
+template <cudnnBackendBehaviorNote_t BEHAVIOR_NOTE>
+bool
+hasBehaviorNote(cudnnBackendDescriptor_t engine_config) {
+ bool hasBehavior = false;
+ auto status = CUDNN_STATUS_SUCCESS;
+ ManagedOpaqueDescriptor engine = make_shared_backend_pointer(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ cudnnBackendDescriptor_t engine_ = engine->get_backend_descriptor();
+ int64_t engine_count = -1;
+ status = detail::get_attribute(
+ engine_config, CUDNN_ATTR_ENGINECFG_ENGINE, CUDNN_TYPE_BACKEND_DESCRIPTOR, 1, &engine_count, &engine_);
+ if (status == CUDNN_STATUS_SUCCESS) {
+ cudnnBackendBehaviorNote_t notes[CUDNN_BEHAVIOR_NOTE_TYPE_COUNT];
+ std::fill_n(notes, CUDNN_BEHAVIOR_NOTE_TYPE_COUNT, CUDNN_BEHAVIOR_NOTE_TYPE_COUNT);
+ int64_t elem_count = 0;
+ detail::get_attribute(engine->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINE_BEHAVIOR_NOTE,
+ CUDNN_TYPE_BEHAVIOR_NOTE,
+ CUDNN_BEHAVIOR_NOTE_TYPE_COUNT,
+ &elem_count,
+ notes);
+ if (std::any_of(
+ notes, notes + elem_count, [](cudnnBackendBehaviorNote_t note) { return note == BEHAVIOR_NOTE; })) {
+ hasBehavior = true;
+ }
+ }
+ return hasBehavior;
+}
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Heuristics.h b/deps/cudnn-frontend/include/cudnn_frontend_Heuristics.h
new file mode 100644
index 0000000..06b4ecc
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Heuristics.h
@@ -0,0 +1,491 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <vector>
+#include <mutex>
+
+#include "cudnn_frontend_OperationGraph.h"
+#include "cudnn_frontend_EngineConfig.h"
+#include "cudnn_frontend_utils.h"
+#include "cudnn_frontend_Filters.h"
+#include "cudnn_frontend/backend/device_properties.h"
+
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4127)
+#endif
+namespace cudnn_frontend {
+///
+/// Engine Heuristic Class
+/// This class helps determine the engine from the operation graph
+/// based on the heuristics
+/// Properties:
+/// - heuristic mode
+/// - operation graph
+///
+/// Use EngineHeuristicsBuilder_v8 to build this class.
+/// Describe returns a string describing the EngineHeuristics_v8 class
+///
+class EngineHeuristics_v8 : public BackendDescriptor {
+ public:
+ friend class EngineHeuristicsBuilder_v8;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR :";
+ return ss.str();
+ }
+
+ EngineHeuristics_v8(EngineHeuristics_v8 &&from) = default;
+ EngineHeuristics_v8 &
+ operator=(EngineHeuristics_v8 &&from) = default;
+
+ ~EngineHeuristics_v8() = default;
+
+ /** @defgroup EngineHeuristicsQuery
+ * Query individual property of EngineHeuristics_v8 class
+ * @{
+ */
+ //! Query the total count of the engines for the Operation Set
+ auto
+ getEngineConfig(int64_t count = 1) -> std::vector<ManagedOpaqueDescriptor> & {
+ cudnnStatus_t status;
+ for (auto i = 0u; i < count; ++i) {
+ ManagedOpaqueDescriptor engConfig = nullptr;
+ engConfig = make_shared_backend_pointer(CUDNN_BACKEND_ENGINECFG_DESCRIPTOR);
+ if (engConfig->is_good() == false) {
+ set_error_and_throw_exception(
+ this,
+ engConfig->get_status(),
+ "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: CUDNN_BACKEND_ENGINECFG_DESCRIPTOR cudnnCreate Failed");
+ return m_heuristic_results;
+ };
+ m_heuristic_results.emplace_back(engConfig);
+ }
+ std::vector<cudnnBackendDescriptor_t> heuristic_results_;
+ for (std::uint32_t i = 0; i < m_heuristic_results.size(); i++) {
+ heuristic_results_.emplace_back(m_heuristic_results[i]->get_backend_descriptor());
+ }
+ int64_t result = -1;
+ status = detail::get_attribute(pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINEHEUR_RESULTS,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ count,
+ &result,
+ heuristic_results_.data());
+
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ this, status, "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: GetAttribute CUDNN_ATTR_ENGINEHEUR_RESULTS Failed");
+ };
+ m_heuristic_results.resize(result);
+ return m_heuristic_results;
+ }
+
+ //! Query the total count of the engine config for the Operation Set
+ auto
+ getEngineConfigCount(void) const -> int64_t {
+ cudnnStatus_t status;
+ int64_t count = -1;
+ status = detail::get_attribute(pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINEHEUR_RESULTS,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 0,
+ &count,
+ nullptr);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ this,
+ status,
+ "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: GetAttribute CUDNN_ATTR_ENGINEHEUR_RESULTS Count Failed");
+ };
+ return count;
+ }
+ /** @} */
+
+ private:
+ EngineHeuristics_v8() = default;
+ EngineHeuristics_v8(EngineHeuristics_v8 const &) = delete;
+ EngineHeuristics_v8 &
+ operator=(EngineHeuristics_v8 const &) = delete;
+
+ cudnnBackendHeurMode_t mode = CUDNN_HEUR_MODE_INSTANT;
+ ManagedOpaqueDescriptor opGraph = nullptr;
+ std::shared_ptr<const DeviceProperties> device_properties = nullptr;
+ std::vector<ManagedOpaqueDescriptor> m_heuristic_results; //! storage of heuristic results
+ std::string opGraphTag;
+ int32_t target_sm_count = -1;
+
+ static std::mutex &
+ get_heur_b_mutex() {
+ static std::mutex heur_b_mutex;
+ return heur_b_mutex;
+ }
+};
+
+///
+/// EngineHeuristicsBuilder_v8 Class
+/// Helper class used to build EngineHeuristics_v8 class
+class EngineHeuristicsBuilder_v8 {
+ public:
+ /** @defgroup EngineHeuristicsBuilder_v8
+ * Set individual property of EngineHeuristics_v8 class
+ * @{
+ */
+ //! Set operationGraph for the engine (opGraph is not destroyed)
+ auto
+ setOperationGraph(OperationGraph_v8 &opGraph_) -> EngineHeuristicsBuilder_v8 & {
+ m_heuristics.opGraph = opGraph_.get_desc();
+ m_heuristics.opGraphTag = opGraph_.getTag();
+ return *this;
+ }
+ auto
+ setOperationGraph(ManagedOpaqueDescriptor opGraph, std::string tag) -> EngineHeuristicsBuilder_v8 & {
+ m_heuristics.opGraph = opGraph;
+ m_heuristics.opGraphTag = tag;
+ return *this;
+ }
+
+ auto
+ setDeviceProperties(std::shared_ptr<const DeviceProperties> device_properties) -> EngineHeuristicsBuilder_v8 & {
+ m_heuristics.device_properties = device_properties;
+ return *this;
+ }
+
+ auto
+ setHeurMode(cudnnBackendHeurMode_t mode_) -> EngineHeuristicsBuilder_v8 & {
+ m_heuristics.mode = mode_;
+ return *this;
+ }
+
+ auto
+ setSMCount(int32_t sm_count_) -> EngineHeuristicsBuilder_v8 & {
+ m_heuristics.target_sm_count = sm_count_;
+ return *this;
+ }
+ /** @} */
+
+ //! constructs the EngineHeuristics_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ EngineHeuristics_v8 &&
+ build() {
+ if (m_heuristics.opGraph == nullptr) {
+ set_error_and_throw_exception(&m_heuristics,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: Check and Set the "
+ "CUDNN_ATTR_ENGINEHEUR_OPERATION_GRAPH field for heuristic");
+ return std::move(m_heuristics);
+ };
+
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_heuristics.initialize_managed_backend_pointer(CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_heuristics, status, "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_heuristics);
+ };
+
+ status = detail::set_attribute(m_heuristics.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINEHEUR_OPERATION_GRAPH,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_heuristics.opGraph->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_heuristics,
+ status,
+ "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: SetAttribute CUDNN_ATTR_ENGINEHEUR_OPERATION_GRAPH Failed");
+ return std::move(m_heuristics);
+ };
+
+ status = detail::set_attribute(m_heuristics.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINEHEUR_MODE,
+ CUDNN_TYPE_HEUR_MODE,
+ 1,
+ &m_heuristics.mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_heuristics,
+ status,
+ "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: SetAttribute CUDNN_ATTR_ENGINEHEUR_MODE Failed");
+ return std::move(m_heuristics);
+ };
+
+ if (m_heuristics.device_properties != nullptr) {
+#if (CUDNN_VERSION >= 90800)
+ status = detail::set_attribute(m_heuristics.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINEHEUR_DEVICEPROP,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &m_heuristics.device_properties->get_ptr());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_heuristics,
+ status,
+ "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_ENGINEHEUR_DEVICEPROP Failed");
+ return std::move(m_heuristics);
+ }
+#endif
+ }
+
+#if (CUDNN_VERSION >= 8905)
+ if (m_heuristics.target_sm_count >= 0) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(8905,
+ m_heuristics,
+ "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_ENGINEHEUR_SM_COUNT_TARGET requires cudnn "
+ "version 8.9.5");
+ status = detail::set_attribute(m_heuristics.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINEHEUR_SM_COUNT_TARGET,
+ CUDNN_TYPE_INT32,
+ 1,
+ &m_heuristics.target_sm_count);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_heuristics,
+ status,
+ "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: SetAttribute CUDNN_ATTR_ENGINEHEUR_SM_COUNT_TARGET Failed");
+ return std::move(m_heuristics);
+ };
+ }
+#endif
+
+ if (m_heuristics.mode == CUDNN_HEUR_MODE_B) {
+ EngineHeuristics_v8::get_heur_b_mutex().lock();
+ }
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_heuristics.pointer->get_backend_descriptor());
+
+ if (m_heuristics.mode == CUDNN_HEUR_MODE_B) {
+ EngineHeuristics_v8::get_heur_b_mutex().unlock();
+ }
+
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_heuristics, status, "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: cudnn Finalize failed");
+ return std::move(m_heuristics);
+ };
+
+ CUDNN_FE_LOG_LABEL_ENDL(m_heuristics);
+ return std::move(m_heuristics);
+ }
+
+ explicit EngineHeuristicsBuilder_v8() = default;
+ ~EngineHeuristicsBuilder_v8() = default;
+ EngineHeuristicsBuilder_v8(EngineHeuristicsBuilder_v8 &&) = delete;
+ EngineHeuristicsBuilder_v8(EngineHeuristicsBuilder_v8 const &) = delete;
+ EngineHeuristicsBuilder_v8 &
+ operator=(EngineHeuristicsBuilder_v8 const &) = delete;
+
+ private:
+ EngineHeuristics_v8 m_heuristics;
+};
+
+template <std::size_t SIZE>
+EngineConfigList
+get_heuristics_list(std::array<cudnnBackendHeurMode_t, SIZE> modes,
+ OperationGraph_v8 &opGraph,
+ std::function<bool(cudnnBackendDescriptor_t)> filter_fn) {
+ CUDNN_FRONTEND_UNUSED(modes);
+ EngineConfigList filtered_configs;
+
+ for (auto mode : modes) {
+ if (mode == CUDNN_HEUR_MODES_COUNT) {
+ continue;
+ }
+ auto heuristics = EngineHeuristicsBuilder_v8().setOperationGraph(opGraph).setHeurMode(mode).build();
+ CUDNN_FE_LOG_LABEL_ENDL("Heuristic Mode " << mode << " has " << heuristics.getEngineConfigCount()
+ << " configurations.");
+ auto &engine_config = heuristics.getEngineConfig(heuristics.getEngineConfigCount());
+ cudnn_frontend::filter(engine_config, filtered_configs, filter_fn);
+ }
+ return filtered_configs;
+}
+
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+#define NV_CUDNN_FE_TRY() try {
+#else
+#define NV_CUDNN_FE_TRY()
+#endif
+
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+#define NV_CUDNN_FE_CATCH(...) \
+ } \
+ catch (cudnn_frontend::cudnnException & e) { \
+ __VA_ARGS__; \
+ }
+#else
+#define NV_CUDNN_FE_CATCH(...)
+#endif
+
+#define NV_CUDNN_RETURN_IF_ERROR(heuristics) \
+ do { \
+ if (heuristics.get_status() != CUDNN_STATUS_SUCCESS) { \
+ return heuristics.get_status(); \
+ } \
+ } while (0);
+
+#define NV_CUDNN_SET_STATUS_BREAK_OR_CONTINUE(status, is_last_status) \
+ if (is_last_status || status != CUDNN_STATUS_SUCCESS) { \
+ statuses.push_back(status); \
+ if (status == CUDNN_STATUS_SUCCESS || evaluate_all) { \
+ continue; \
+ } \
+ break; \
+ }
+
+static inline cudnnStatus_t
+get_heuristics_list_impl(cudnnBackendHeurMode_t heur_mode,
+ OperationGraph_v8 &opGraph,
+ std::function<bool(cudnnBackendDescriptor_t)> filter_fn,
+ int32_t sm_count,
+ EngineConfigList &filtered_configs,
+ std::shared_ptr<const DeviceProperties> device_properties = nullptr) {
+ auto heuristics = EngineHeuristicsBuilder_v8()
+ .setDeviceProperties(device_properties)
+ .setOperationGraph(opGraph)
+ .setHeurMode(heur_mode)
+ .setSMCount(sm_count)
+ .build();
+ NV_CUDNN_RETURN_IF_ERROR(heuristics);
+ auto num_config = heuristics.getEngineConfigCount();
+ NV_CUDNN_RETURN_IF_ERROR(heuristics);
+ CUDNN_FE_LOG_LABEL_ENDL("Heuristic query for mode " << heur_mode << " has " << num_config << " configurations.");
+ auto &engine_config = heuristics.getEngineConfig(num_config);
+ NV_CUDNN_RETURN_IF_ERROR(heuristics);
+ CUDNN_FE_LOG_LABEL_ENDL("Backend heuristics recommendation count: " << engine_config.size());
+ cudnn_frontend::filter(engine_config, filtered_configs, filter_fn);
+ return CUDNN_STATUS_SUCCESS;
+}
+
+static inline std::vector<cudnnStatus_t>
+get_heuristics_list(std::vector<std::string> const &modes,
+ OperationGraph_v8 &opGraph,
+ std::function<bool(cudnnBackendDescriptor_t)> filter_fn,
+ EngineConfigList &filtered_configs,
+ bool evaluate_all = false,
+ int32_t sm_count = -1,
+ std::shared_ptr<const DeviceProperties> device_properties = nullptr) {
+ std::vector<cudnnStatus_t> statuses;
+
+ // Try building the heuristics for each mode
+ // if fails push the status in the list of statuses
+ for (auto &mode : modes) {
+ if (mode.find("heuristics_instant") != std::string::npos ||
+ mode.find("heuristics_mode_a") != std::string::npos) {
+ auto heur_mode = CUDNN_HEUR_MODE_A;
+ NV_CUDNN_FE_TRY();
+ auto status_l =
+ get_heuristics_list_impl(heur_mode, opGraph, filter_fn, sm_count, filtered_configs, device_properties);
+ NV_CUDNN_SET_STATUS_BREAK_OR_CONTINUE(status_l, true);
+ NV_CUDNN_FE_CATCH(NV_CUDNN_SET_STATUS_BREAK_OR_CONTINUE(e.getCudnnStatus(), true));
+
+ } else if (mode.find("heuristics_fallback") != std::string::npos) {
+ NV_CUDNN_FE_TRY();
+ auto status_l = get_heuristics_list_impl(
+ CUDNN_HEUR_MODE_FALLBACK, opGraph, filter_fn, sm_count, filtered_configs, device_properties);
+ NV_CUDNN_SET_STATUS_BREAK_OR_CONTINUE(status_l, true);
+ NV_CUDNN_FE_CATCH(NV_CUDNN_SET_STATUS_BREAK_OR_CONTINUE(e.getCudnnStatus(), true));
+ } else if (mode.find("heuristics_mode_b") != std::string::npos) {
+ auto heur_mode = CUDNN_HEUR_MODE_B;
+ NV_CUDNN_FE_TRY();
+ auto status_l =
+ get_heuristics_list_impl(heur_mode, opGraph, filter_fn, sm_count, filtered_configs, device_properties);
+
+ // Between cudnn version 8.3 and 8.6, when heur_mode_b heuristics did not succeed,
+ // there was no fallback to the instant mode. We are here manually adding instant mode
+ // to the heur_mode_b to alleviate this issue.
+#if (CUDNN_VERSION >= 8300) && (CUDNN_VERSION < 8600)
+ if (status_l != CUDNN_STATUS_SUCCESS) {
+ status_l = get_heuristics_list_impl(
+ CUDNN_HEUR_MODE_INSTANT, opGraph, filter_fn, sm_count, filtered_configs, device_properties);
+ }
+#endif
+ NV_CUDNN_SET_STATUS_BREAK_OR_CONTINUE(status_l, true);
+#if (CUDNN_VERSION >= 8300) && (CUDNN_VERSION < 8600)
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+ }
+ catch (cudnn_frontend::cudnnException &) {
+ NV_CUDNN_FE_TRY();
+ auto status_ =
+ get_heuristics_list_impl(heur_mode, opGraph, filter_fn, sm_count, filtered_configs, device_properties);
+ statuses.push_back(status_);
+ NV_CUDNN_FE_CATCH(NV_CUDNN_SET_STATUS_BREAK_OR_CONTINUE(e.getCudnnStatus(), true));
+ }
+#endif
+#else
+ NV_CUDNN_FE_CATCH(NV_CUDNN_SET_STATUS_BREAK_OR_CONTINUE(e.getCudnnStatus(), true));
+#endif
+ }
+}
+return statuses;
+}
+
+static inline std::vector<cudnnStatus_t>
+get_heuristics_list(std::vector<cudnn_frontend::HeurMode_t> const &modes,
+ OperationGraph_v8 &opGraph,
+ std::function<bool(cudnnBackendDescriptor_t)> filter_fn,
+ EngineConfigList &filtered_configs,
+ bool evaluate_all = false,
+ int32_t sm_count = -1,
+ std::shared_ptr<const DeviceProperties> device_properties = nullptr) {
+ std::unordered_map<HeurMode_t, std::string> mode_to_string = {
+ {HeurMode_t::A, "heuristics_mode_a"},
+ {HeurMode_t::B, "heuristics_mode_b"},
+ {HeurMode_t::FALLBACK, "heuristics_fallback"},
+ };
+
+ std::vector<std::string> string_modes(modes.size());
+ std::transform(modes.begin(), modes.end(), string_modes.begin(), [&mode_to_string](const auto &mode) {
+ return mode_to_string.at(mode);
+ });
+
+ return get_heuristics_list(
+ string_modes, opGraph, filter_fn, filtered_configs, evaluate_all, sm_count, device_properties);
+}
+
+template <std::size_t SIZE>
+std::vector<cudnnStatus_t>
+get_heuristics_list(std::array<std::string, SIZE> modes,
+ OperationGraph_v8 &opGraph,
+ std::function<bool(cudnnBackendDescriptor_t)> filter_fn,
+ EngineConfigList &filtered_configs,
+ bool evaluate_all = false) {
+ std::vector<std::string> modes_vector(modes.begin(), modes.end());
+ return get_heuristics_list(modes_vector, opGraph, filter_fn, filtered_configs, evaluate_all);
+}
+
+#undef NV_CUDNN_FE_TRY
+#undef NV_CUDNN_FE_CATCH
+#undef NV_CUDNN_RETURN_IF_ERROR
+#undef NV_CUDNN_SET_STATUS_BREAK_OR_CONTINUE
+
+using EngineHeuristicsBuilde = EngineHeuristicsBuilder_v8;
+using EngineHeuristics = EngineHeuristics_v8;
+} // namespace cudnn_frontend
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Logging.h b/deps/cudnn-frontend/include/cudnn_frontend_Logging.h
new file mode 100644
index 0000000..c232ee2
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Logging.h
@@ -0,0 +1,166 @@
+
+
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <iostream>
+#include <fstream>
+#include <cstring>
+#include <cstdlib>
+
+#include "cudnn_frontend_shim.h" // cudnn_frontend::get_environment
+
+namespace cudnn_frontend {
+
+inline int
+getLogLevel() {
+#ifdef NV_CUDNN_FRONTEND_DISABLE_LOGGING
+ static int log_level = 0;
+#else
+ static int log_level = []() {
+ const char *env_val = get_environment("CUDNN_FRONTEND_LOG_INFO");
+ return env_val ? std::atoi(env_val) : 0;
+ }();
+#endif
+ return log_level;
+}
+
+inline bool &
+isLoggingEnabled() {
+#ifdef NV_CUDNN_FRONTEND_DISABLE_LOGGING
+ static bool log_enabled = false;
+#else
+ static bool log_enabled = (getLogLevel() > 0);
+#endif
+ return log_enabled;
+}
+
+inline bool &
+isLoggingTensorDumpEnabled() {
+#ifdef NV_CUDNN_FRONTEND_DISABLE_LOGGING
+ static bool tensor_dump_enabled = false;
+#else
+ static bool tensor_dump_enabled = []() {
+ int level = getLogLevel();
+ return level >= 1 && level < 10;
+ }();
+#endif
+ return tensor_dump_enabled;
+}
+
+inline std::ostream &
+getStream() {
+ static std::ofstream outFile;
+ static std::ostream &stream =
+ get_environment("CUDNN_FRONTEND_LOG_FILE")
+ ? (std::strncmp(get_environment("CUDNN_FRONTEND_LOG_FILE"), "stdout", 6) == 0
+ ? std::cout
+ : (std::strncmp(get_environment("CUDNN_FRONTEND_LOG_FILE"), "stderr", 6) == 0
+ ? std::cerr
+ : (outFile.open(get_environment("CUDNN_FRONTEND_LOG_FILE"), std::ios::out), outFile)))
+ : (isLoggingEnabled() = false, std::cout);
+ return stream;
+}
+
+class ConditionalStreamer {
+ private:
+ std::ostream &stream;
+
+ public:
+ ConditionalStreamer(std::ostream &stream_) : stream(stream_) {}
+
+ template <typename T>
+ const ConditionalStreamer &
+ operator<<(const T &t) const {
+ if (isLoggingEnabled()) {
+ stream << t;
+ }
+ return *this;
+ }
+
+ const ConditionalStreamer &
+ operator<<(std::ostream &(*spl)(std::ostream &)) const {
+ if (isLoggingEnabled()) {
+ stream << spl;
+ }
+ return *this;
+ }
+};
+
+inline ConditionalStreamer &
+getLogger() {
+ static ConditionalStreamer opt(getStream());
+ return opt;
+}
+
+#define CUDNN_FE_LOG(X) \
+ do { \
+ if (isLoggingEnabled()) { \
+ getLogger() << X; \
+ } \
+ } while (0);
+
+#define CUDNN_FE_LOG_LABEL(X) \
+ do { \
+ if (isLoggingEnabled()) { \
+ getLogger() << "[cudnn_frontend] " << X; \
+ } \
+ } while (0);
+
+#define CUDNN_FE_LOG_LABEL_ENDL(X) \
+ do { \
+ if (isLoggingEnabled()) { \
+ getLogger() << "[cudnn_frontend] " << X << std::endl; \
+ } \
+ } while (0);
+
+#define CUDNN_FE_LOG_BANNER(X) \
+ do { \
+ if (isLoggingEnabled()) { \
+ { \
+ constexpr int total_width = 128; \
+ std::ostringstream oss; \
+ oss << "[cudnn_frontend] ||| === " << X << " === |||"; \
+ std::string banner_line = oss.str(); \
+ int banner_len = static_cast<int>(banner_line.size()); \
+ int pad = total_width - banner_len; \
+ if (pad > 0) { \
+ banner_line.insert(banner_line.size() - 5, std::string(pad, ' ')); \
+ } \
+ getLogger() << std::string(total_width, '=') << std::endl; \
+ getLogger() << banner_line << std::endl; \
+ getLogger() << std::string(total_width, '=') << std::endl; \
+ } \
+ } \
+ } while (0);
+
+static std::ostream &
+operator<<(std::ostream &os, const BackendDescriptor &desc) {
+ if (isLoggingEnabled()) {
+ os << desc.describe();
+ }
+ return os;
+}
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_MatMulDesc.h b/deps/cudnn-frontend/include/cudnn_frontend_MatMulDesc.h
new file mode 100644
index 0000000..ee57403
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_MatMulDesc.h
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+
+namespace cudnn_frontend {
+namespace graph {
+class MatmulNode;
+}
+} // namespace cudnn_frontend
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+///
+/// MatMulDesc Descriptor Class
+/// This class tells the properties of the MatMul operation
+/// Properties:
+/// - compute_type
+///
+/// Use MatMulDesc_v8 to build this class.
+/// Describe returns a string describing the MatMul operation
+///
+class MatMulDesc_v8 : public BackendDescriptor {
+ public:
+ friend class MatMulDescBuilder_v8;
+ friend class cudnn_frontend::graph::MatmulNode;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ ss << "CUDNN_BACKEND_MATMUL_DESCRIPTOR :" << " Math precision " << json{compute_type};
+#else
+ ss << "CUDNN_BACKEND_MATMUL_DESCRIPTOR :" << " Math precision " << int(compute_type);
+#endif
+ return ss.str();
+ }
+
+ MatMulDesc_v8(MatMulDesc_v8 &&from) = default;
+ MatMulDesc_v8 &
+ operator=(MatMulDesc_v8 &&from) = default;
+
+ ~MatMulDesc_v8() = default;
+
+ private:
+ MatMulDesc_v8() = default;
+ MatMulDesc_v8(MatMulDesc_v8 const &) = delete;
+ MatMulDesc_v8 &
+ operator=(MatMulDesc_v8 const &) = delete;
+
+ DataType_t compute_type = DataType_t::NOT_SET;
+ bool isPadded = false;
+ double paddingValue = 0.0;
+};
+
+////
+/// MatMulDescBuilder_v8 Class
+/// Helper class used to build MatMulDesc_v8 class
+class MatMulDescBuilder_v8 {
+ public:
+ /** @defgroup MatMulDescBuilder_v8
+ * Set individual property of MatMulDesc_v8 class
+ * @{
+ */
+ //! Set Math Precision Data Type for the Matmul Operation
+ auto
+ setComputeType(DataType_t data_type_) -> MatMulDescBuilder_v8 & {
+ m_matMulDesc.compute_type = data_type_;
+ return *this;
+ }
+ auto
+ setComputeType(cudnnDataType_t data_type_) -> MatMulDescBuilder_v8 & {
+ m_matMulDesc.compute_type = detail::convert_from_cudnn_type(data_type_);
+ return *this;
+ }
+ /** @} */
+
+ // TODO Deprecate in v1.0
+ auto
+ setMathPrecision(cudnnDataType_t data_type_) -> MatMulDescBuilder_v8 & {
+ return setComputeType(data_type_);
+ }
+
+ //! Set padding value for matmul descriptor
+ auto
+ setPaddingValue(double paddingValue) -> MatMulDescBuilder_v8 & {
+ m_matMulDesc.isPadded = true;
+ m_matMulDesc.paddingValue = paddingValue;
+ return *this;
+ }
+
+ //! constructs the MatMulDesc_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ MatMulDesc_v8 &&
+ build() {
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_matMulDesc.initialize_managed_backend_pointer(CUDNN_BACKEND_MATMUL_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_matMulDesc, status, "CUDNN_BACKEND_MATMUL_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_matMulDesc);
+ }
+
+ // Once Created lets set the descriptor parameters.
+ cudnnDataType_t cudnn_data_type;
+ status = detail::convert_to_cudnn_type(m_matMulDesc.compute_type, cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_matMulDesc,
+ status,
+ "CUDNN_BACKEND_MATMUL_DESCRIPTOR: SetAttribute CUDNN_ATTR_MATMUL_COMP_TYPE Failed");
+ return std::move(m_matMulDesc);
+ }
+ status = detail::set_attribute(m_matMulDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_MATMUL_COMP_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_matMulDesc,
+ status,
+ "CUDNN_BACKEND_MATMUL_DESCRIPTOR: SetAttribute CUDNN_ATTR_MATMUL_COMP_TYPE Failed");
+ return std::move(m_matMulDesc);
+ }
+
+#if (CUDNN_VERSION >= 8900)
+ // Setting padding value if matmul desc is padded
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8900,
+ m_matMulDesc,
+ "CUDNN_BACKEND_MATMUL_DESCRIPTOR: SetAttribute CUDNN_ATTR_MATMUL_PADDING_VALUE requires cudnn 8.9.0");
+ if (m_matMulDesc.isPadded) {
+ status = detail::set_attribute(m_matMulDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_MATMUL_PADDING_VALUE,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &m_matMulDesc.paddingValue);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_matMulDesc,
+ status,
+ "CUDNN_BACKEND_MATMUL_DESCRIPTOR: SetAttribute CUDNN_ATTR_MATMUL_PADDING_VALUE Failed");
+ return std::move(m_matMulDesc);
+ }
+ }
+#endif
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_matMulDesc.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_matMulDesc, status, "CUDNN_BACKEND_MATMUL_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_matMulDesc);
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL(m_matMulDesc);
+ return std::move(m_matMulDesc);
+ }
+
+ explicit MatMulDescBuilder_v8() = default;
+ ~MatMulDescBuilder_v8() = default;
+ MatMulDescBuilder_v8(MatMulDescBuilder_v8 &&) = delete;
+ MatMulDescBuilder_v8(MatMulDescBuilder_v8 const &) = delete;
+ MatMulDescBuilder_v8 &
+ operator=(MatMulDescBuilder_v8 const &) = delete;
+
+ private:
+ MatMulDesc_v8 m_matMulDesc;
+};
+using MatMulDesc = MatMulDesc_v8;
+using MatMulDescBuilder = MatMulDescBuilder_v8;
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Operation.h b/deps/cudnn-frontend/include/cudnn_frontend_Operation.h
new file mode 100644
index 0000000..fa9dbba
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Operation.h
@@ -0,0 +1,3167 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+
+namespace cudnn_frontend {
+namespace graph {
+class ReductionNode;
+class PointwiseNode;
+class MatmulNode;
+class ConvolutionNode;
+class DgradNode;
+class WgradNode;
+class LayerNormNode;
+class BatchNormNode;
+class BatchnormInferenceNode;
+class RMSNormNode;
+class DRMSNormNode;
+class InstanceNormNode;
+class DINNode;
+class DLNNode;
+class DBNNode;
+class DBNWeightNode;
+class BatchNormFinalizeNode;
+class GenstatsNode;
+class ReshapeNode;
+class ResampleNode;
+class RngNode;
+class PagedCacheLoadNode;
+} // namespace graph
+} // namespace cudnn_frontend
+
+#include <array>
+#include <cstddef>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "cudnn_frontend_ConvDesc.h"
+#include "cudnn_frontend_PointWiseDesc.h"
+#include "cudnn_frontend_MatMulDesc.h"
+#include "cudnn_frontend_ReductionDesc.h"
+#include "cudnn_frontend_Resample.h"
+#include "cudnn_frontend_Rng.h"
+#include "cudnn_frontend_Tensor.h"
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+///
+/// Operation_v8 Class
+/// This class has the properties of the operation
+/// Properties:
+/// - xDesc
+/// - yDesc
+/// - wdesc
+/// - bdesc
+/// - tDesc
+/// - dydesc
+/// - dxdesc
+/// - cdesc
+/// - amatdesc
+/// - bmatdesc
+/// - cmatdesc
+/// - moverridedesc
+/// - noverridedesc
+/// - koverridedesc
+/// - pwdesc
+/// - matmuldesc
+/// - reductiondesc
+/// - flagdesc
+/// - inputDescs
+/// - alpha
+/// - beta
+/// - alpha2
+/// - axis
+/// - inplaceIndex
+/// - mode
+/// - value
+///
+/// Use OperationBuilder_v8 to build this class.
+/// Describe returns a string describing the convolution operation
+///
+class Operation_v8 : public BackendDescriptor {
+ public:
+ friend class OperationBuilder_v8;
+ friend class cudnn_frontend::graph::ReductionNode;
+ friend class cudnn_frontend::graph::PointwiseNode;
+ friend class cudnn_frontend::graph::MatmulNode;
+ friend class cudnn_frontend::graph::ConvolutionNode;
+ friend class cudnn_frontend::graph::DgradNode;
+ friend class cudnn_frontend::graph::WgradNode;
+ friend class cudnn_frontend::graph::LayerNormNode;
+ friend class cudnn_frontend::graph::BatchNormNode;
+ friend class cudnn_frontend::graph::BatchnormInferenceNode;
+ friend class cudnn_frontend::graph::RMSNormNode;
+ friend class cudnn_frontend::graph::DRMSNormNode;
+ friend class cudnn_frontend::graph::InstanceNormNode;
+ friend class cudnn_frontend::graph::DINNode;
+ friend class cudnn_frontend::graph::DLNNode;
+ friend class cudnn_frontend::graph::DBNNode;
+ friend class cudnn_frontend::graph::DBNWeightNode;
+ friend class cudnn_frontend::graph::BatchNormFinalizeNode;
+ friend class cudnn_frontend::graph::GenstatsNode;
+ friend class cudnn_frontend::graph::ReshapeNode;
+ friend class cudnn_frontend::graph::ResampleNode;
+ friend class cudnn_frontend::graph::RngNode;
+ friend class cudnn_frontend::graph::PagedCacheLoadNode;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_OPERATION :" << " OpMode: " << op_mode;
+ ss << std::hex << " X " << xdesc;
+ ss << std::hex << " Y " << ydesc;
+ ss << std::hex << " W " << wdesc;
+ ss << std::hex << " B " << bdesc;
+ ss << std::hex << " T " << tdesc;
+ ss << std::hex << " DW " << dwdesc;
+ ss << std::hex << " DY " << dydesc;
+ ss << std::hex << " DX " << dxdesc;
+ ss << std::hex << " C " << cdesc;
+ ss << std::hex << " A Mtrix " << amatdesc;
+ ss << std::hex << " B Mtrix " << bmatdesc;
+ ss << std::hex << " C Mtrix " << cmatdesc;
+ ss << std::hex << " P " << pwdesc;
+ ss << std::hex << " MatMul " << matmuldesc;
+ ss << std::hex << " Reduction " << reductiondesc;
+ ss << std::dec << " alphabetaType " << alphabetaType;
+ ss << " Alpha: " << alpha_s << " " << alpha_d;
+ ss << " Alpha2: " << alpha2_s << " " << alpha2_d;
+ ss << " Beta: " << beta_s << " " << beta_d;
+ return ss.str();
+ }
+
+ Operation_v8(Operation_v8 &&from) = default;
+ Operation_v8 &
+ operator=(Operation_v8 &&from) = default;
+
+ // Will be deprecated. Do Not use
+ ManagedOpaqueDescriptor
+ getOutputTensor() {
+ return (op_mode == DescriptorType_t::OPERATION_MATMUL_DESCRIPTOR) ? cmatdesc : ydesc;
+ }
+
+ std::string const &
+ getTag() const {
+ return operationTag;
+ }
+
+ feature_vector_t
+ getFeatureVector() const {
+ return feature_vector;
+ }
+
+ ~Operation_v8() = default;
+
+ private:
+ Operation_v8() = default;
+ Operation_v8(Operation_v8 const &) = delete;
+ Operation_v8 &
+ operator=(Operation_v8 const &) = delete;
+
+ DescriptorType_t op_mode = DescriptorType_t::NOT_SET;
+
+ ManagedOpaqueDescriptor xdesc = nullptr;
+ ManagedOpaqueDescriptor ydesc = nullptr;
+ ManagedOpaqueDescriptor wdesc = nullptr;
+ ManagedOpaqueDescriptor bdesc = nullptr;
+ ManagedOpaqueDescriptor tdesc = nullptr;
+ ManagedOpaqueDescriptor dydesc = nullptr;
+ ManagedOpaqueDescriptor dxdesc = nullptr;
+ ManagedOpaqueDescriptor dwdesc = nullptr;
+ ManagedOpaqueDescriptor cdesc = nullptr;
+ ManagedOpaqueDescriptor resampledesc = nullptr;
+ ManagedOpaqueDescriptor rngdesc = nullptr;
+ ManagedOpaqueDescriptor amatdesc = nullptr;
+ ManagedOpaqueDescriptor bmatdesc = nullptr;
+ ManagedOpaqueDescriptor cmatdesc = nullptr;
+ ManagedOpaqueDescriptor moverridedesc = nullptr;
+ ManagedOpaqueDescriptor noverridedesc = nullptr;
+ ManagedOpaqueDescriptor koverridedesc = nullptr;
+ ManagedOpaqueDescriptor pwdesc = nullptr;
+ ManagedOpaqueDescriptor matmuldesc = nullptr;
+ ManagedOpaqueDescriptor reductiondesc = nullptr;
+ ManagedOpaqueDescriptor groupoffsetdesc = nullptr;
+ ManagedOpaqueDescriptor sumdesc = nullptr;
+ ManagedOpaqueDescriptor sqsumdesc = nullptr;
+ ManagedOpaqueDescriptor scaledesc = nullptr;
+ ManagedOpaqueDescriptor biasdesc = nullptr;
+ ManagedOpaqueDescriptor dscaledesc = nullptr;
+ ManagedOpaqueDescriptor dbiasdesc = nullptr;
+ ManagedOpaqueDescriptor eqscaledesc = nullptr;
+ ManagedOpaqueDescriptor eqscaledesc1 = nullptr;
+ ManagedOpaqueDescriptor eqbiasdesc = nullptr;
+ ManagedOpaqueDescriptor prevMeandesc = nullptr;
+ ManagedOpaqueDescriptor prevVardesc = nullptr;
+ ManagedOpaqueDescriptor nextMeandesc = nullptr;
+ ManagedOpaqueDescriptor nextVardesc = nullptr;
+ ManagedOpaqueDescriptor savedMeandesc = nullptr;
+ ManagedOpaqueDescriptor savedInVardesc = nullptr;
+ ManagedOpaqueDescriptor accumCountdesc = nullptr;
+ ManagedOpaqueDescriptor epsilondesc = nullptr;
+ ManagedOpaqueDescriptor expDecayFactordesc = nullptr;
+ ManagedOpaqueDescriptor idxdesc = nullptr;
+ ManagedOpaqueDescriptor offsetdesc = nullptr;
+ ManagedOpaqueDescriptor seeddesc = nullptr;
+ ManagedOpaqueDescriptor containerdesc = nullptr;
+ ManagedOpaqueDescriptor pageTabledesc = nullptr;
+ ManagedOpaqueDescriptor sequencedesc = nullptr;
+ std::vector<ManagedOpaqueDescriptor> peerStatdescs;
+
+ cudnnBackendAttributeType_t alphabetaType = CUDNN_TYPE_FLOAT;
+ cudnnDataType_t compute_type = CUDNN_DATA_FLOAT;
+ cudnnGenStatsMode_t genstats_mode = CUDNN_GENSTATS_SUM_SQSUM;
+ cudnnBnFinalizeStatsMode_t bn_stats_mode = CUDNN_BN_FINALIZE_STATISTICS_TRAINING;
+
+ NormFwdPhase_t norm_fwd_phase;
+ NormMode_t norm_mode;
+ ReshapeMode_t reshape_mode = ReshapeMode_t::VIEW_ONLY;
+
+ float alpha_s = 1.0f, beta_s = .0f, alpha2_s = 1.0f;
+ double alpha_d = 1.0, beta_d = 0.0, alpha2_d = 1.0;
+ int64_t pointwise_port_count = -1;
+ PointwiseMode_t pointwise_mode = PointwiseMode_t::NOT_SET;
+ bool is_pointwise_activation_fwd_op = false;
+ bool is_pointwise_identity_op = false;
+ bool is_pointwise_activation_bwd_op = false;
+ bool is_pointwise_math_op = false;
+ std::string operationTag;
+ feature_vector_t feature_vector;
+ int64_t seed = 0;
+};
+
+///
+/// OperationBuilder_v8 Class
+/// Helper class used to build Operation_v8 class
+
+class OperationBuilder_v8 {
+ private:
+ Operation_v8 m_operation;
+ bool is_convolution_op = false;
+ bool is_pointwise_op = false;
+ bool is_matmul_op = false;
+ bool is_reduction_op = false;
+ bool is_genstats_op = false;
+ bool is_bn_finalize_op = false;
+ bool is_resample_fwd_op = false;
+ bool is_resample_bwd_op = false;
+ bool is_norm_forward_op = false;
+ bool is_norm_backward_op = false;
+ bool is_bn_bwd_weight = false;
+ bool is_rng_op = false;
+ bool is_reshape_op = false;
+ bool is_paged_cache_load_op = false;
+
+ using Message_t = const char *;
+
+ int64_t xTensor_dimA[CUDNN_DIM_MAX + 1];
+ int64_t xTensor_strA[CUDNN_DIM_MAX + 1];
+ int64_t wTensor_dimA[CUDNN_DIM_MAX + 1];
+ int64_t wTensor_strA[CUDNN_DIM_MAX + 1];
+ int64_t yTensor_dimA[CUDNN_DIM_MAX + 1];
+ int64_t yTensor_strA[CUDNN_DIM_MAX + 1];
+ int64_t idxTensor_dimA[CUDNN_DIM_MAX + 1];
+ int64_t idxTensor_strA[CUDNN_DIM_MAX + 1];
+
+ bool is2D = true;
+
+ int64_t conv_padding[CUDNN_DIM_MAX];
+ int64_t conv_dilation[CUDNN_DIM_MAX];
+ int64_t conv_stride[CUDNN_DIM_MAX];
+ int64_t mode;
+ int64_t xType, yType, wType, cType, idxType /* compute_precision */;
+
+ int64_t tensor_dims = 0;
+
+ Operation_v8 &&
+ build_reduction_op() {
+ m_operation.operationTag = "Reduction";
+ auto status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_REDUCTION_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.reductiondesc->get_backend_descriptor()));
+
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_REDUCTION_DESC Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_REDUCTION_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.xdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_REDUCTION_XDESC Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_REDUCTION_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.ydesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_REDUCTION_YDESC Failed");
+ return std::move(m_operation);
+ }
+ if (m_operation.groupoffsetdesc != nullptr) {
+#if (CUDNN_VERSION >= 92400)
+ if (detail::get_backend_version() < 92400) {
+ set_error_and_throw_exception(&m_operation,
+ CUDNN_STATUS_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION: Reduction group offset is not supported in "
+ "cudnn version < 9.24.0");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_REDUCTION_GROUP_OFFSET_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.groupoffsetdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_REDUCTION_GROUP_OFFSET_DESC Failed");
+ return std::move(m_operation);
+ }
+#else
+ set_error_and_throw_exception(&m_operation,
+ CUDNN_STATUS_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION: Reduction group offset is not supported in cudnn "
+ "version < 9.24.0");
+ return std::move(m_operation);
+#endif
+ }
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_matmul_op() {
+ m_operation.operationTag = "Matmul";
+ auto status = CUDNN_STATUS_SUCCESS;
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MATMUL_ADESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.amatdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation, status, "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_MATMUL_ADESC Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MATMUL_BDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.bmatdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation, status, "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_MATMUL_BDESC Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MATMUL_CDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.cmatdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation, status, "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_MATMUL_CDESC Failed");
+ return std::move(m_operation);
+ }
+#if (CUDNN_VERSION >= 8700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8700, m_operation, "CUDNN_BACKEND_OPERATION: M,N,K override Requires cudnn 8.7.0 and above");
+ if (m_operation.moverridedesc != nullptr) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MATMUL_GEMM_M_OVERRIDE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.moverridedesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_MATMUL_GEMM_M_OVERRIDE_DESC Failed");
+ return std::move(m_operation);
+ }
+ }
+ if (m_operation.noverridedesc != nullptr) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MATMUL_GEMM_N_OVERRIDE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.noverridedesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_MATMUL_GEMM_N_OVERRIDE_DESC Failed");
+ return std::move(m_operation);
+ }
+ }
+ if (m_operation.koverridedesc != nullptr) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MATMUL_GEMM_K_OVERRIDE_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.koverridedesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_MATMUL_GEMM_K_OVERRIDE_DESC Failed");
+ return std::move(m_operation);
+ }
+ }
+#endif
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_MATMUL_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.matmuldesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation, status, "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_MATMUL_DESC Failed");
+ return std::move(m_operation);
+ }
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_pointwise_op() {
+ auto status = CUDNN_STATUS_SUCCESS;
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ json j = m_operation.pointwise_mode;
+ m_operation.operationTag = j;
+#else
+ m_operation.operationTag = std::to_string((int)m_operation.pointwise_mode);
+#endif
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_POINTWISE_PW_DESCRIPTOR,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.pwdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_POINTWISE_PW_DESCRIPTOR Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_POINTWISE_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.xdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_POINTWISE_XDESC Failed");
+ return std::move(m_operation);
+ }
+
+ if (!m_operation.is_pointwise_activation_bwd_op) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_POINTWISE_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.ydesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_POINTWISE_YDESC Failed");
+ return std::move(m_operation);
+ }
+ } else {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_POINTWISE_DYDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.dydesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_POINTWISE_DYDESC Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_POINTWISE_DXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.dxdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_POINTWISE_DXDESC Failed");
+ return std::move(m_operation);
+ }
+ }
+
+ void *alpha = (m_operation.alphabetaType == CUDNN_TYPE_FLOAT ? static_cast<void *>(&m_operation.alpha_s)
+ : static_cast<void *>(&m_operation.alpha_d));
+ void *alpha2 = (m_operation.alphabetaType == CUDNN_TYPE_FLOAT ? static_cast<void *>(&m_operation.alpha2_s)
+ : static_cast<void *>(&m_operation.alpha2_d));
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_POINTWISE_ALPHA1,
+ m_operation.alphabetaType,
+ 1,
+ alpha);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_POINTWISE_ALPHA1 Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_POINTWISE_ALPHA2,
+ m_operation.alphabetaType,
+ 1,
+ alpha2);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_POINTWISE_ALPHA2 Failed");
+ return std::move(m_operation);
+ }
+
+ if (m_operation.pointwise_port_count >= 3 && !m_operation.is_pointwise_activation_bwd_op) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_POINTWISE_BDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.bdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_POINTWISE_BDESC Failed");
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.pointwise_port_count == 4) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_POINTWISE_TDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.tdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_POINTWISE_TDESC Failed");
+ return std::move(m_operation);
+ }
+ }
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_conv_backward_data() {
+ m_operation.operationTag = "ConvBwdData";
+
+ auto status = CUDNN_STATUS_SUCCESS;
+
+ auto dxdesc_ = m_operation.dxdesc != nullptr ? m_operation.dxdesc : m_operation.xdesc;
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_DX,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(dxdesc_->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_DX Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_W,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.wdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_W Failed");
+ return std::move(m_operation);
+ }
+
+ auto dydesc_ = m_operation.dydesc != nullptr ? m_operation.dydesc : m_operation.ydesc;
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_DY,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(dydesc_->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_DY Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_CONV_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.cdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_CONV_DESC Failed");
+ return std::move(m_operation);
+ }
+
+ void *alpha = (m_operation.alphabetaType == CUDNN_TYPE_FLOAT ? static_cast<void *>(&m_operation.alpha_s)
+ : static_cast<void *>(&m_operation.alpha_d));
+ void *beta = (m_operation.alphabetaType == CUDNN_TYPE_FLOAT ? static_cast<void *>(&m_operation.beta_s)
+ : static_cast<void *>(&m_operation.beta_d));
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_ALPHA,
+ m_operation.alphabetaType,
+ 1,
+ alpha);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_ALPHA Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_BETA,
+ m_operation.alphabetaType,
+ 1,
+ beta);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_BETA Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("Extracting the feature vector");
+ extract_feature_vector(DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR);
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_bn_finalize_op() {
+ m_operation.operationTag = "BNFinalize";
+ auto status = CUDNN_STATUS_SUCCESS;
+
+ auto set_attribute = [&status](Operation_v8 &operation,
+ cudnnBackendAttributeName_t attr,
+ const char *fail_msg,
+ void const *ptr,
+ cudnnBackendAttributeType_t type = CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ int64_t cnt = 1) {
+ status = detail::set_attribute(operation.pointer->get_backend_descriptor(), attr, type, cnt, ptr);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&operation, status, fail_msg);
+ }
+ };
+
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_STATS_MODE,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_STATS_MODE Failed",
+ &(m_operation.bn_stats_mode),
+ CUDNN_TYPE_BN_FINALIZE_STATS_MODE,
+ 1);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_MATH_PREC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_MATH_PREC Failed",
+ &(m_operation.compute_type),
+ CUDNN_TYPE_DATA_TYPE,
+ 1);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.sumdesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_Y_SUM_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_Y_SUM_DESC Failed",
+ &(m_operation.sumdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.sqsumdesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_Y_SQ_SUM_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_Y_SQ_SUM_DESC Failed",
+ &(m_operation.sqsumdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.biasdesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_BIAS_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_BIAS_DESC Failed",
+ &(m_operation.biasdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.scaledesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_SCALE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_SCALE_DESC Failed",
+ &(m_operation.scaledesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.eqscaledesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EQ_SCALE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_EQ_SCALE_DESC Failed",
+ &(m_operation.eqscaledesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.eqbiasdesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EQ_BIAS_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_EQ_BIAS_DESC Failed",
+ &(m_operation.eqbiasdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.prevMeandesc) {
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_PREV_RUNNING_MEAN_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_PREV_RUNNING_MEAN_DESC Failed",
+ &(m_operation.prevMeandesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.prevVardesc) {
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_PREV_RUNNING_VAR_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_PREV_RUNNING_VAR_DESC Failed",
+ &(m_operation.prevVardesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.nextMeandesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_UPDATED_RUNNING_MEAN_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute "
+ "CUDNN_ATTR_OPERATION_BN_FINALIZE_UPDATED_RUNNING_MEAN_DESC Failed",
+ &(m_operation.nextMeandesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.nextVardesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_UPDATED_RUNNING_VAR_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute "
+ "CUDNN_ATTR_OPERATION_BN_FINALIZE_UPDATED_RUNNING_VAR_DESC Failed",
+ &(m_operation.nextVardesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.savedMeandesc) {
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_SAVED_MEAN_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_SAVED_MEAN_DESC Failed",
+ &(m_operation.savedMeandesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.savedInVardesc) {
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_SAVED_INV_STD_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_SAVED_INV_STD_DESC Failed",
+ &(m_operation.savedInVardesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.epsilondesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EPSILON_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_EPSILON_DESC Failed",
+ &(m_operation.epsilondesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.expDecayFactordesc) {
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EXP_AVERATE_FACTOR_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_EXP_AVERATE_FACTOR_DESC Failed",
+ &(m_operation.expDecayFactordesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ if (m_operation.accumCountdesc) {
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_ACCUM_COUNT_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_FINALIZE_ACCUM_COUNT_DESC Failed",
+ &(m_operation.accumCountdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ }
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_genstats_op() {
+ m_operation.operationTag = "GenStats";
+ auto status = CUDNN_STATUS_SUCCESS;
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_GENSTATS_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.xdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_GENSTATS_XDESC Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_GENSTATS_SUMDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.sumdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_GENSTATS_SUMDESC Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_GENSTATS_SQSUMDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.sqsumdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_GENSTATS_SQSUMDESC Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_GENSTATS_MODE,
+ CUDNN_TYPE_GENSTATS_MODE,
+ 1,
+ &(m_operation.genstats_mode));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_GENSTATS_MODE Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_GENSTATS_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &(m_operation.compute_type));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_GENSTATS_MATH_PREC Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_conv_backward_filter() {
+ m_operation.operationTag = "ConvBwdFilter";
+
+ auto status = CUDNN_STATUS_SUCCESS;
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_X,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.xdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_X Failed");
+ return std::move(m_operation);
+ }
+
+ auto dwdesc_ = m_operation.dwdesc != nullptr ? m_operation.dwdesc : m_operation.wdesc;
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_DW,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(dwdesc_->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_DW Failed");
+ return std::move(m_operation);
+ }
+
+ auto dydesc_ = m_operation.dydesc != nullptr ? m_operation.dydesc : m_operation.ydesc;
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_DY,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(dydesc_->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_DY Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_CONV_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.cdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute "
+ "CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_CONV_DESC Failed");
+ return std::move(m_operation);
+ }
+ void *alpha = (m_operation.alphabetaType == CUDNN_TYPE_FLOAT ? static_cast<void *>(&m_operation.alpha_s)
+ : static_cast<void *>(&m_operation.alpha_d));
+ void *beta = (m_operation.alphabetaType == CUDNN_TYPE_FLOAT ? static_cast<void *>(&m_operation.beta_s)
+ : static_cast<void *>(&m_operation.beta_d));
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_ALPHA,
+ m_operation.alphabetaType,
+ 1,
+ alpha);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_ALPHA Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_BETA,
+ m_operation.alphabetaType,
+ 1,
+ beta);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_BETA Failed");
+ return std::move(m_operation);
+ }
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("Extracting the feature vector");
+ extract_feature_vector(DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR);
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_norm_forward() {
+ m_operation.operationTag = "Norm_Fwd";
+ auto status = CUDNN_STATUS_SUCCESS;
+
+ auto set_attribute = [&status](Operation_v8 &operation,
+ cudnnBackendAttributeName_t attr,
+ const char *fail_msg,
+ void const *ptr,
+ cudnnBackendAttributeType_t type = CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ int64_t cnt = 1) {
+ status = detail::set_attribute(operation.pointer->get_backend_descriptor(), attr, type, cnt, ptr);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&operation, status, fail_msg);
+ }
+ };
+
+ cudnnBackendNormMode_t cudnn_norm_mode;
+ status = detail::convert_to_cudnn_type(m_operation.norm_mode, cudnn_norm_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_MODE Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_MODE,
+ CUDNN_TYPE_NORM_MODE,
+ 1,
+ &cudnn_norm_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_MODE Failed");
+ return std::move(m_operation);
+ }
+
+ cudnnBackendNormFwdPhase_t cudnn_norm_fwd_phase;
+ status = detail::convert_to_cudnn_type(m_operation.norm_fwd_phase, cudnn_norm_fwd_phase);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_PHASE Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_NORM_FWD_PHASE,
+ CUDNN_TYPE_NORM_FWD_PHASE,
+ 1,
+ &cudnn_norm_fwd_phase);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_PHASE Failed");
+ return std::move(m_operation);
+ }
+
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_XDESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_XDESC Failed",
+ &m_operation.xdesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.savedMeandesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_MEAN_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_MEAN_DESC Failed",
+ &m_operation.savedMeandesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.savedInVardesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_INV_VARIANCE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_INV_VARIANCE_DESC Failed",
+ &m_operation.savedInVardesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.scaledesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_SCALE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_SCALE_DESC Failed",
+ &m_operation.scaledesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.biasdesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_BIAS_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_BIAS_DESC Failed",
+ &m_operation.biasdesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.epsilondesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_EPSILON_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_EPSILON Failed",
+ &m_operation.epsilondesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.expDecayFactordesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_EXP_AVG_FACTOR_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_EXP_AVG_FACTOR Failed",
+ &m_operation.expDecayFactordesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.prevMeandesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_INPUT_RUNNING_MEAN_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_INPUT_RUNNING_MEAN_DESC Failed",
+ &m_operation.prevMeandesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.prevVardesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_INPUT_RUNNING_VAR_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_INPUT_RUNNING_VAR_DESC Failed",
+ &m_operation.prevVardesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.nextMeandesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_OUTPUT_RUNNING_MEAN_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_OUTPUT_RUNNING_MEAN_DESC Failed",
+ &m_operation.nextMeandesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.nextVardesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_OUTPUT_RUNNING_VAR_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_FWD_OUTPUT_RUNNING_VAR_DESC Failed",
+ &m_operation.nextVardesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.ydesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_YDESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNCUDNN_ATTR_OPERATION_NORM_FWD_YDESC Failed",
+ &m_operation.ydesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.peerStatdescs.size()) {
+ std::vector<cudnnBackendDescriptor_t> backend_peer_stat_descs;
+ for (auto &desc : m_operation.peerStatdescs) {
+ backend_peer_stat_descs.push_back(desc->get_backend_descriptor());
+ }
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_NORM_FWD_PEER_STAT_DESCS,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNCUDNN_ATTR_OPERATION_NORM_FWD_PEER_STAT_DESCS Failed",
+ backend_peer_stat_descs.data(),
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ backend_peer_stat_descs.size());
+ }
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_norm_backward() {
+ m_operation.operationTag = "Norm_Bwd";
+ auto status = CUDNN_STATUS_SUCCESS;
+
+ auto set_attribute = [&status](Operation_v8 &operation,
+ cudnnBackendAttributeName_t attr,
+ const char *fail_msg,
+ void const *ptr,
+ cudnnBackendAttributeType_t type = CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ int64_t cnt = 1) {
+ status = detail::set_attribute(operation.pointer->get_backend_descriptor(), attr, type, cnt, ptr);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&operation, status, fail_msg);
+ }
+ };
+ cudnnBackendNormMode_t cudnn_norm_mode;
+ status = detail::convert_to_cudnn_type(m_operation.norm_mode, cudnn_norm_mode);
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_MODE,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_MODE Failed",
+ &cudnn_norm_mode,
+ CUDNN_TYPE_NORM_MODE);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.xdesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_XDESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_XDESC Failed",
+ &m_operation.xdesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.savedMeandesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_MEAN_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_MEAN_DESC Failed",
+ &m_operation.savedMeandesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.savedInVardesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_INV_VARIANCE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_INV_VARIANCE_DESC Failed",
+ &m_operation.savedInVardesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.dydesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_DYDESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_DYDESC Failed",
+ &m_operation.dydesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.scaledesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_SCALE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_SCALE_DESC Failed",
+ &m_operation.scaledesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.dxdesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_DXDESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_DXDESC Failed",
+ &m_operation.dxdesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.dscaledesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_DSCALE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_DSCALE_DESC Failed",
+ &m_operation.dscaledesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.dbiasdesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_DBIAS_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_DBIAS_DESC Failed",
+ &m_operation.dbiasdesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.peerStatdescs.size()) {
+ std::vector<cudnnBackendDescriptor_t> backend_peer_stat_descs;
+ for (auto &desc : m_operation.peerStatdescs) {
+ backend_peer_stat_descs.push_back(desc->get_backend_descriptor());
+ }
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_PEER_STAT_DESCS,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNCUDNN_ATTR_OPERATION_NORM_BWD_PEER_STAT_DESCS Failed",
+ backend_peer_stat_descs.data(),
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ backend_peer_stat_descs.size());
+ }
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ if (m_operation.epsilondesc) {
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_NORM_BWD_EPSILON_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_NORM_BWD_EPSILON Failed",
+ &m_operation.epsilondesc->get_backend_descriptor());
+ }
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_resample_fwd_operation() {
+ m_operation.operationTag = "Resample_fwd";
+ auto status = CUDNN_STATUS_SUCCESS;
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.xdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_FWD_XDESC Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.ydesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_FWD_YDESC Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_ALPHA,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &(m_operation.alpha_d));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_FWD_ALPHA Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_BETA,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &(m_operation.beta_d));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_FWD_BETA Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.resampledesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_FWD_DESC Failed");
+ return std::move(m_operation);
+ }
+
+ // Maxpooling forward
+ if (m_operation.idxdesc != nullptr) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_IDXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.idxdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_FWD_IDXDESC Failed");
+ return std::move(m_operation);
+ }
+ }
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_resample_bwd_operation() {
+#if (CUDNN_VERSION >= 8600)
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8600, m_operation, "CUDNN_BACKEND_OPERATION: Resample_bwd requires cudnn 8.6.0");
+ m_operation.operationTag = "Resample_bwd";
+ auto status = CUDNN_STATUS_SUCCESS;
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_DXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.dxdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_DXDESC Failed");
+ return std::move(m_operation);
+ }
+#if (CUDNN_VERSION >= 8700)
+ if (m_operation.xdesc != nullptr) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8700,
+ m_operation,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_XDESC requires cudnn 8.7.0");
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.xdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_XDESC Failed");
+ return std::move(m_operation);
+ }
+ }
+ if (m_operation.ydesc != nullptr) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8700,
+ m_operation,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_YDESC requires cudnn 8.7.0");
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.ydesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_YDESC Failed");
+ return std::move(m_operation);
+ }
+ }
+#endif
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_DYDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.dydesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_DYDESC Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_ALPHA,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &(m_operation.alpha_d));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_ALPHA Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_BETA,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &(m_operation.beta_d));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_BETA Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.resampledesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_DESC Failed");
+ return std::move(m_operation);
+ }
+
+ // Maxpooling backward
+ if (m_operation.idxdesc != nullptr) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_IDXDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.idxdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESAMPLE_BWD_IDXDESC Failed");
+ return std::move(m_operation);
+ }
+ }
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+#else
+ set_error_and_throw_exception(&m_operation,
+ CUDNN_STATUS_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION: Resample operation Not supported in this version");
+#endif
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_rng_operation() {
+#if (CUDNN_VERSION >= 8700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8700, m_operation, "CUDNN_BACKEND_OPERATION: build_rng_operation requires cudnn 8.7.0");
+ m_operation.operationTag = "Rng";
+ auto status = CUDNN_STATUS_SUCCESS;
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RNG_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.ydesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation, status, "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RNG_YDESC Failed");
+ return std::move(m_operation);
+ }
+
+#if (CUDNN_VERSION >= 8800)
+ // seed can be a tensor or an int64
+ // if tensor is defined we give it precedence
+ if (m_operation.seeddesc) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8800,
+ m_operation,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RNG_SEED requires cudnn 8.8.0");
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RNG_SEED,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.seeddesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation, status, "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RNG_SEED Failed");
+ return std::move(m_operation);
+ }
+ } else
+#endif
+ {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RNG_SEED,
+ CUDNN_TYPE_INT64,
+ 1,
+ &(m_operation.seed));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation, status, "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RNG_SEED Failed");
+ return std::move(m_operation);
+ }
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RNG_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.rngdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation, status, "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RNG_DESC Failed");
+ return std::move(m_operation);
+ }
+
+#if (CUDNN_VERSION >= 8800)
+ if (m_operation.offsetdesc) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8800,
+ m_operation,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RNG_OFFSET_DESC requires cudnn 8.8.0");
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RNG_OFFSET_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.offsetdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RNG_OFFSET_DESC Failed");
+ return std::move(m_operation);
+ }
+ }
+#endif
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+#else
+ set_error_and_throw_exception(&m_operation,
+ CUDNN_STATUS_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION: Rng operation Not supported in this version");
+#endif
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_paged_cache_load_op() {
+#if (CUDNN_VERSION < 90500)
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION: paged_cache_load_op operation Not supported in this version");
+#else
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 90500, m_operation, "CUDNN_BACKEND_OPERATION: build_paged_cache_load_op requires cudnn 9.5.0");
+
+ // Quick helper lambda to ensure code being DRY
+ auto set_tensor_descriptor = [&](auto attr, const std::string &descriptor_name, auto &descriptor) {
+ std::string error_msg = "CUDNN_BACKEND_OPERATION: Check and Set " + descriptor_name;
+ auto status = CUDNN_STATUS_SUCCESS;
+ if (descriptor != nullptr) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ attr,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(descriptor->get_backend_descriptor()));
+ } else {
+ status = CUDNN_STATUS_BAD_PARAM;
+ }
+
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, error_msg.c_str());
+ }
+ return status;
+ };
+
+ if (CUDNN_STATUS_SUCCESS != set_tensor_descriptor(CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_CONTAINER_DESC,
+ "CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_CONTAINER_DESC",
+ m_operation.containerdesc)) {
+ return std::move(m_operation);
+ }
+
+ if (CUDNN_STATUS_SUCCESS != set_tensor_descriptor(CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_PAGE_TABLE_DESC,
+ "CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_PAGE_TABLE_DESC",
+ m_operation.pageTabledesc)) {
+ return std::move(m_operation);
+ }
+
+ if (CUDNN_STATUS_SUCCESS != set_tensor_descriptor(CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_SEQUENCE_DESC,
+ "CUDNN_ATTR_OPERATION_PAGED_CACHE_SEQUENCE_DESC",
+ m_operation.sequencedesc)) {
+ return std::move(m_operation);
+ }
+
+ if (CUDNN_STATUS_SUCCESS != set_tensor_descriptor(CUDNN_ATTR_OPERATION_PAGED_CACHE_LOAD_YDESC,
+ "CUDNN_ATTR_OPERATION_PAGED_CACHE_YDESC",
+ m_operation.ydesc)) {
+ return std::move(m_operation);
+ }
+
+ auto status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+#endif
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_reshape_operation() {
+#if (CUDNN_VERSION >= 8700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8700, m_operation, "CUDNN_BACKEND_OPERATION: build_reshape_operation requires cudnn 8.7.0");
+ m_operation.operationTag = "Reshape";
+ auto status = CUDNN_STATUS_SUCCESS;
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESHAPE_XDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.xdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESHAPE_XDESC Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESHAPE_YDESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.ydesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESHAPE_YDESC Failed");
+ return std::move(m_operation);
+ }
+
+#if (CUDNN_VERSION >= 92200)
+ // Set reshape mode if it's not NOT_SET
+ if (m_operation.reshape_mode != ReshapeMode_t::NOT_SET) {
+ cudnnBackendReshapeMode_t cudnn_reshape_mode;
+ status = detail::convert_to_cudnn_type(m_operation.reshape_mode, cudnn_reshape_mode);
+ if (status == CUDNN_STATUS_SUCCESS) {
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_RESHAPE_MODE,
+ CUDNN_TYPE_RESHAPE_MODE,
+ 1,
+ &cudnn_reshape_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_RESHAPE_MODE Failed");
+ return std::move(m_operation);
+ }
+ }
+ }
+#endif
+
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+#else
+ set_error_and_throw_exception(&m_operation,
+ CUDNN_STATUS_NOT_SUPPORTED,
+ "CUDNN_BACKEND_OPERATION: Reshape operation Not supported in this version");
+#endif
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_bn_bwd_weight_op() {
+ m_operation.operationTag = "Dgrad_Drelu_BN_Bwd";
+ auto status = CUDNN_STATUS_SUCCESS;
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &(m_operation.compute_type));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_MATH_PREC Failed");
+ return std::move(m_operation);
+ }
+
+ auto set_attribute = [&status](Operation_v8 &operation,
+ cudnnBackendAttributeName_t attr,
+ const char *fail_msg,
+ void const *ptr,
+ cudnnBackendAttributeType_t type = CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ int64_t cnt = 1) {
+ status = detail::set_attribute(operation.pointer->get_backend_descriptor(), attr, type, cnt, ptr);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&operation, status, fail_msg);
+ }
+ };
+
+ if (m_operation.xdesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_X_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_X_DESC Failed",
+ &m_operation.xdesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.savedMeandesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_MEAN_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_MEAN_DESC Failed",
+ &m_operation.savedMeandesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.savedInVardesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_INVSTD_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_INVSTD_DESC Failed",
+ &m_operation.savedInVardesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.scaledesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_BN_SCALE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_BN_SCALE_DESC Failed",
+ &m_operation.scaledesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.dydesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DY_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DY_DESC Failed",
+ &m_operation.dydesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.dscaledesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DBN_SCALE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DBN_SCALE_DESC Failed",
+ &m_operation.dscaledesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.dbiasdesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DBN_BIAS_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DBN_BIAS_DESC Failed",
+ &m_operation.dbiasdesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.eqscaledesc)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_DY_SCALE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_DY_SCALE_DESC Failed",
+ &m_operation.eqscaledesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.eqscaledesc1)
+ set_attribute(
+ m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_X_SCALE_DESC,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_X_SCALE_DESC Failed",
+ &m_operation.eqscaledesc1->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+
+ if (m_operation.eqbiasdesc)
+ set_attribute(m_operation,
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_BIAS,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_BIAS Failed",
+ &m_operation.eqbiasdesc->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return std::move(m_operation);
+ }
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+ return std::move(m_operation);
+ }
+
+ Operation_v8 &&
+ build_conv_forward() {
+ m_operation.operationTag = "ConvFwd";
+
+ auto status = CUDNN_STATUS_SUCCESS;
+
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_X,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.xdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_X Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_W,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.wdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_W Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_Y,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.ydesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_Y Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_CONV_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &(m_operation.cdesc->get_backend_descriptor()));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_CONV_DESC Failed");
+ return std::move(m_operation);
+ }
+ void *alpha = (m_operation.alphabetaType == CUDNN_TYPE_FLOAT ? static_cast<void *>(&m_operation.alpha_s)
+ : static_cast<void *>(&m_operation.alpha_d));
+ void *beta = (m_operation.alphabetaType == CUDNN_TYPE_FLOAT ? static_cast<void *>(&m_operation.beta_s)
+ : static_cast<void *>(&m_operation.beta_d));
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_ALPHA,
+ m_operation.alphabetaType,
+ 1,
+ alpha);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_ALPHA Failed");
+ return std::move(m_operation);
+ }
+ status = detail::set_attribute(m_operation.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_BETA,
+ m_operation.alphabetaType,
+ 1,
+ beta);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation,
+ status,
+ "CUDNN_BACKEND_OPERATION: SetAttribute CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_BETA Failed");
+ return std::move(m_operation);
+ }
+ status = detail::finalize(m_operation.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnFinalize Failed");
+ return std::move(m_operation);
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL("Extracting the feature vector");
+ extract_feature_vector(DescriptorType_t::OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR);
+ return std::move(m_operation);
+ }
+
+ void
+ extract_feature_vector(DescriptorType_t op_type) {
+ /// Build the feature vector of this operation now.
+ m_operation.feature_vector.reserve(50);
+
+ m_operation.feature_vector.push_back(static_cast<int>(op_type));
+ for (auto i = 0; i < tensor_dims; i++) {
+ m_operation.feature_vector.push_back(xTensor_dimA[i]); // n, c, (g), d, h , w
+ }
+ for (auto i = 0; i < tensor_dims; i++) {
+ m_operation.feature_vector.push_back(wTensor_dimA[i]); // n, c, (g), d, h , w
+ }
+ for (auto i = 0; i < tensor_dims; i++) {
+ m_operation.feature_vector.push_back(yTensor_dimA[i]); // n, c, (g), d, h , w
+ }
+ const int max_spatial_dim = 3;
+
+ /// Padding
+ for (auto i = 0; i < max_spatial_dim; i++) {
+ if (i == max_spatial_dim - 1 && is2D) {
+ m_operation.feature_vector.push_back(0);
+ } else {
+ m_operation.feature_vector.push_back(conv_padding[i]);
+ }
+ }
+ /// Dilation
+ for (auto i = 0; i < max_spatial_dim; i++) {
+ if (i == max_spatial_dim - 1 && is2D) {
+ m_operation.feature_vector.push_back(0);
+ } else {
+ m_operation.feature_vector.push_back(conv_dilation[i]);
+ }
+ }
+ /// Strides
+ for (auto i = 0; i < max_spatial_dim; i++) {
+ if (i == max_spatial_dim - 1 && is2D) {
+ m_operation.feature_vector.push_back(0);
+ } else {
+ m_operation.feature_vector.push_back(conv_stride[i]);
+ }
+ }
+
+ m_operation.feature_vector.push_back(xType);
+ m_operation.feature_vector.push_back(wType);
+ m_operation.feature_vector.push_back(yType);
+ m_operation.feature_vector.push_back(cType);
+ m_operation.feature_vector.push_back(mode);
+
+ for (auto i = 0; i < tensor_dims; i++) {
+ m_operation.feature_vector.push_back(xTensor_strA[i]); // n, c, (g), d, h , w
+ }
+ for (auto i = 0; i < tensor_dims; i++) {
+ m_operation.feature_vector.push_back(wTensor_strA[i]); // n, c, (g), d, h , w
+ }
+ for (auto i = 0; i < tensor_dims; i++) {
+ m_operation.feature_vector.push_back(yTensor_strA[i]); // n, c, (g), d, h , w
+ }
+
+ int64_t alpha_as_int;
+ int64_t beta_as_int;
+ std::memcpy((void *)&alpha_as_int, (void *)(&m_operation.alpha_s), sizeof(int64_t));
+ std::memcpy((void *)&beta_as_int, (void *)(&m_operation.beta_s), sizeof(int64_t));
+
+ m_operation.feature_vector.push_back(alpha_as_int);
+ m_operation.feature_vector.push_back(beta_as_int);
+ }
+
+ cudnnStatus_t
+ validate_matmul_op(Message_t &msg) {
+ if (m_operation.matmuldesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_MATMUL_DESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.amatdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_MATMUL_ADESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.bmatdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_MATMUL_BDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.cmatdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_MATMUL_CDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ return CUDNN_STATUS_SUCCESS;
+ }
+
+ cudnnStatus_t
+ validate_norm_op(Message_t &msg) {
+ cudnnStatus_t status = CUDNN_STATUS_SUCCESS;
+ if (m_operation.xdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_NORM.*XDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ if (detail::get_backend_version() == 8500) {
+ std::array<int64_t, 10> x_dimensions;
+ int64_t dim_count;
+ status = detail::get_attribute(m_operation.xdesc->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_DIMENSIONS,
+ CUDNN_TYPE_INT64,
+ x_dimensions.size(),
+ &dim_count,
+ x_dimensions.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ msg = "CUDNN_BACKEND_OPERATION: CUDNN_BACKEND_TENSOR has invalid CUDNN_ATTR_TENSOR_DIMENSIONS";
+ return status;
+ }
+
+ int64_t N = x_dimensions[0];
+ int64_t C = x_dimensions[1];
+
+ if ((N != 1) || ((C % 8) != 0)) {
+ msg = "CUDNN_BACKEND_OPERATION: CUDNN_BACKEND_TENSOR has bad CUDNN_ATTR_TENSOR_DIMENSIONS";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ }
+
+ return status;
+ }
+
+ cudnnStatus_t
+ validate_resample_op(Message_t &msg) {
+ if (m_operation.op_mode == DescriptorType_t::OPERATION_RESAMPLE_FWD_DESCRIPTOR) {
+ if (m_operation.xdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_RESAMPLE.*XDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.ydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_RESAMPLE.*YDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_RESAMPLE_BWD_DESCRIPTOR) {
+ if (m_operation.dxdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_RESAMPLE.*DXDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.dydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_RESAMPLE.*DYDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ }
+
+ if (m_operation.resampledesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_RESAMPLE.*RESAMPLEDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ return CUDNN_STATUS_SUCCESS;
+ }
+
+ cudnnStatus_t
+ validate_rng_op(Message_t &msg) {
+ if (m_operation.ydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_REDUCTION_YDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ if (m_operation.rngdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_RNG_DESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ return CUDNN_STATUS_SUCCESS;
+ }
+
+ cudnnStatus_t
+ validate_reshape_op(Message_t &msg) {
+ if (m_operation.xdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_RESHAPE_XDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ if (m_operation.ydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_RESHAPE_YDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ return CUDNN_STATUS_SUCCESS;
+ }
+
+ cudnnStatus_t
+ validate_bn_bwd_weight_op(Message_t &msg) {
+ if (m_operation.xdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_X_DESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ if (m_operation.dydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DY_DESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ if (m_operation.savedMeandesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_MEAN_DESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ if (m_operation.savedInVardesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_INVSTD_DESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ return CUDNN_STATUS_SUCCESS;
+ }
+
+ cudnnStatus_t
+ validate_reduction_op(Message_t &msg) {
+ if (m_operation.reductiondesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_REDUCTION_DESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.xdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_REDUCTION_XDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.ydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_REDUCTION_YDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ return CUDNN_STATUS_SUCCESS;
+ }
+
+ cudnnStatus_t
+ validate_pointwise_op(Message_t &msg) {
+ if (m_operation.xdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_POINTWISE_XDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.is_pointwise_math_op) {
+ if (m_operation.pointwise_port_count == 3 && m_operation.bdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_POINTWISE_BDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.ydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_POINTWISE_YDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ } else if (m_operation.is_pointwise_activation_fwd_op || m_operation.is_pointwise_identity_op) {
+ if (m_operation.ydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_POINTWISE_YDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ } else if (m_operation.is_pointwise_activation_bwd_op) {
+ if (m_operation.dydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_POINTWISE_DYDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.dxdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_POINTWISE_DXDESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ } else {
+ msg = "CUDNN_BACKEND_OPERATION: Unsupported cudnn pointwise mode. Check PointwiseMode_t::*";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ return CUDNN_STATUS_SUCCESS;
+ }
+
+ cudnnStatus_t
+ validate_convolution_op(Message_t &msg) {
+ if (m_operation.cdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_CONVOLUTION_*_CONV_DESC";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.op_mode == DescriptorType_t::OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR) {
+ if (m_operation.xdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_CONVOLUTION_*_X";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.wdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_CONVOLUTION_*_W";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.ydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_CONVOLUTION_*_Y";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR) {
+ if (m_operation.ydesc != nullptr && m_operation.dydesc != nullptr) {
+ msg =
+ "CUDNN_BACKEND_OPERATION: Ambiguous specification. Choose and Set only one of setyDesc() or "
+ "setdyDesc()";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.ydesc == nullptr && m_operation.dydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Choose and Set one of setyDesc() or setdyDesc()";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.xdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_CONVOLUTION_*_X";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.wdesc != nullptr && m_operation.dwdesc != nullptr) {
+ msg =
+ "CUDNN_BACKEND_OPERATION: Ambiguous specification. Choose and Set only one of setwDesc() or "
+ "setdwDesc()";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.wdesc == nullptr && m_operation.dwdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Choose and Set one of setwDesc() or setdwDesc()";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) {
+ if (m_operation.ydesc != nullptr && m_operation.dydesc != nullptr) {
+ msg =
+ "CUDNN_BACKEND_OPERATION: Ambiguous specification. Choose and Set only one of setyDesc() or "
+ "setdyDesc()";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.ydesc == nullptr && m_operation.dydesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Choose and Set one of setyDesc() or setdyDesc()";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.wdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Check and Set the CUDNN_ATTR_OPERATION_CONVOLUTION_*_W";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.xdesc != nullptr && m_operation.dxdesc != nullptr) {
+ msg =
+ "CUDNN_BACKEND_OPERATION: Ambiguous specification. Choose and Set only one of setxDesc() or "
+ "setdxDesc()";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (m_operation.xdesc == nullptr && m_operation.dxdesc == nullptr) {
+ msg = "CUDNN_BACKEND_OPERATION: Choose and Set one of setxDesc() or setdxDesc()";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ } else {
+ msg =
+ "CUDNN_BACKEND_OPERATION: Unsupported convolution operation. Check and set "
+ "CUDNN_BACKEND_OPERATION_CONVOLUTION_*_DESCRIPTOR";
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ return CUDNN_STATUS_SUCCESS;
+ }
+
+ void
+ copy_dims_and_strides(const int64_t *from, int64_t *to) const {
+ for (auto i = 0; i < CUDNN_DIM_MAX + 1; i++) {
+ to[i] = from[i];
+ }
+ }
+
+ public:
+ /** @defgroup OperationBuilder_v8
+ * Set individual property of Operation_v8 class
+ * @{
+ */
+ /// Will be Deprecated Do not use
+ auto
+ setxDesc(ManagedOpaqueDescriptor const &raw_tensor) -> OperationBuilder_v8 & {
+ m_operation.xdesc = raw_tensor;
+ return *this;
+ }
+
+ auto
+ setxDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.xdesc = tensor.get_desc();
+ copy_dims_and_strides(tensor.getDimArray(), xTensor_dimA);
+ copy_dims_and_strides(tensor.getStrideArray(), xTensor_strA);
+ tensor_dims = tensor.getDimensionCount();
+ xType = tensor.getDataType();
+ return *this;
+ }
+ auto
+ setbDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_pointwise_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Pointwise operation does not need bTensor");
+ }
+ m_operation.bdesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ settDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_pointwise_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Pointwise operation does not need tTensor");
+ }
+ m_operation.tdesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setyDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.ydesc = tensor.get_desc();
+ copy_dims_and_strides(tensor.getDimArray(), yTensor_dimA);
+ copy_dims_and_strides(tensor.getStrideArray(), yTensor_strA);
+ yType = tensor.getDataType();
+ return *this;
+ }
+ auto
+ setwDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_convolution_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Convolution operation does not need wTensor");
+ }
+ m_operation.wdesc = tensor.get_desc();
+ copy_dims_and_strides(tensor.getDimArray(), wTensor_dimA);
+ copy_dims_and_strides(tensor.getStrideArray(), wTensor_strA);
+ wType = tensor.getDataType();
+ return *this;
+ }
+
+ /// Will be Deprecated Do not use
+ auto
+ setdyDesc(ManagedOpaqueDescriptor const &raw_tensor) -> OperationBuilder_v8 & {
+ m_operation.dydesc = raw_tensor;
+ return *this;
+ }
+ auto
+ setdyDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.dydesc = tensor.get_desc();
+ copy_dims_and_strides(tensor.getDimArray(), yTensor_dimA);
+ copy_dims_and_strides(tensor.getStrideArray(), yTensor_strA);
+ yType = tensor.getDataType();
+ return *this;
+ }
+ auto
+ setdxDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.dxdesc = tensor.get_desc();
+ copy_dims_and_strides(tensor.getDimArray(), xTensor_dimA);
+ copy_dims_and_strides(tensor.getStrideArray(), xTensor_strA);
+ tensor_dims = tensor.getDimensionCount();
+ xType = tensor.getDataType();
+ return *this;
+ }
+ auto
+ setdwDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.dwdesc = tensor.get_desc();
+ copy_dims_and_strides(tensor.getDimArray(), wTensor_dimA);
+ copy_dims_and_strides(tensor.getStrideArray(), wTensor_strA);
+ wType = tensor.getDataType();
+ return *this;
+ }
+ auto
+ setResampleDesc(ResampleDesc_v8 const &resampleDesc) -> OperationBuilder_v8 & {
+ if (is_resample_fwd_op == false && is_resample_bwd_op == false) {
+ set_error_and_throw_exception(&m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "RESAMPLE_DESC: Non Resample operation does not need Resample DESCRIPTOR");
+ }
+ m_operation.resampledesc = resampleDesc.get_desc();
+ return *this;
+ }
+
+ auto
+ setRngDesc(RngDesc_v8 const &rngDesc) -> OperationBuilder_v8 & {
+ if (is_rng_op == false) {
+ set_error_and_throw_exception(
+ &m_operation, CUDNN_STATUS_BAD_PARAM, "RNG_DESC: Non Rng operation does not need Rng DESCRIPTOR");
+ }
+ m_operation.rngdesc = rngDesc.get_desc();
+ return *this;
+ }
+
+ auto
+ setidxDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.idxdesc = tensor.get_desc();
+ copy_dims_and_strides(tensor.getDimArray(), idxTensor_dimA);
+ copy_dims_and_strides(tensor.getStrideArray(), idxTensor_strA);
+ idxType = tensor.getDataType();
+ return *this;
+ }
+
+ auto
+ setSeedDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.seeddesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setOffsetDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.offsetdesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setcDesc(ConvDesc_v8 const &conv) -> OperationBuilder_v8 & {
+ if (is_convolution_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Convolution operation does not need Convolution DESCRIPTOR");
+ }
+ m_operation.cdesc = conv.get_desc();
+ if (conv.getComputePrecision() == DataType_t::DOUBLE) {
+ m_operation.alphabetaType = CUDNN_TYPE_DOUBLE;
+ }
+ is2D = conv.getDimensionCount() == 2;
+ copy_dims_and_strides(conv.getPadding(), conv_padding);
+ copy_dims_and_strides(conv.getDilation(), conv_dilation);
+ copy_dims_and_strides(conv.getStride(), conv_stride);
+ cType = static_cast<int>(conv.getComputePrecision());
+ mode = conv.getMathMode();
+ return *this;
+ }
+
+ auto
+ setcontainerDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.containerdesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setpageTableDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.pageTabledesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setsequenceDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.sequencedesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setNormFwdPhase(NormFwdPhase_t mode) -> OperationBuilder_v8 & {
+ m_operation.norm_fwd_phase = mode;
+ return *this;
+ }
+
+ auto
+ setReshapeMode(ReshapeMode_t mode) -> OperationBuilder_v8 & {
+ m_operation.reshape_mode = mode;
+ return *this;
+ }
+
+#if (CUDNN_VERSION >= 92200)
+ // To be deprecated. Please use setReshapeMode(cudnn_frontend::ReshapeMode_t mode) instead.
+ auto
+ setReshapeMode(cudnnBackendReshapeMode_t mode) -> OperationBuilder_v8 & {
+ detail::convert_from_cudnn_type(mode, m_operation.reshape_mode);
+ return *this;
+ }
+#endif
+
+ auto
+ setNormalizationMode(NormMode_t mode) -> OperationBuilder_v8 & {
+ m_operation.norm_mode = mode;
+ return *this;
+ }
+
+ // To be deprecated. Please use setNormalizationMode(cudnn_frontend::NormMode_t mode) instead.
+ auto
+ setNormalizationMode(cudnnBackendNormMode_t mode) -> OperationBuilder_v8 & {
+ detail::convert_from_cudnn_type(mode, m_operation.norm_mode);
+ return *this;
+ }
+
+ // To be deprecated. Please use setNormFwdPhase(cudnn_frontend::NormFwdPhase_t mode) instead.
+ auto
+ setNormFwdPhase(cudnnBackendNormFwdPhase_t mode) -> OperationBuilder_v8 & {
+ detail::convert_from_cudnn_type(mode, m_operation.norm_fwd_phase);
+ return *this;
+ }
+
+ auto
+ setBNFinalizeMode(cudnnBnFinalizeStatsMode_t mode) -> OperationBuilder_v8 & {
+ m_operation.bn_stats_mode = mode;
+ return *this;
+ }
+
+ auto
+ setAccumCountTensor(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.accumCountdesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setEpsilonTensor(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.epsilondesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setExpDecayFactorTensor(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.expDecayFactordesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ addPeerStatTensor(Tensor_v8 const &peer_stat_tensor) -> OperationBuilder_v8 & {
+ m_operation.peerStatdescs.push_back(peer_stat_tensor.get_desc());
+ return *this;
+ }
+
+ auto
+ setPeerStatTensor(std::vector<Tensor_v8> const &peer_stat_tensors) -> OperationBuilder_v8 & {
+ for (auto &tensor : peer_stat_tensors) {
+ m_operation.peerStatdescs.push_back(tensor.get_desc());
+ }
+ return *this;
+ }
+
+ auto
+ setPrevRunningMeanAndVar(Tensor_v8 const &mean, Tensor_v8 const &var) -> OperationBuilder_v8 & {
+ m_operation.prevMeandesc = mean.get_desc();
+ m_operation.prevVardesc = var.get_desc();
+ return *this;
+ }
+
+ auto
+ setNextRunningMeanAndVar(Tensor_v8 const &mean, Tensor_v8 const &var) -> OperationBuilder_v8 & {
+ m_operation.nextMeandesc = mean.get_desc();
+ m_operation.nextVardesc = var.get_desc();
+ return *this;
+ }
+
+ auto
+ setSavedMeanAndInvVar(Tensor_v8 const &mean, Tensor_v8 const &var) -> OperationBuilder_v8 & {
+ m_operation.savedMeandesc = mean.get_desc();
+ m_operation.savedInVardesc = var.get_desc();
+ return *this;
+ }
+
+ auto
+ setSavedInvVar(Tensor_v8 const &var) -> OperationBuilder_v8 & {
+ m_operation.savedInVardesc = var.get_desc();
+ return *this;
+ }
+
+ auto
+ setScale(Tensor_v8 const &scale_tensor) -> OperationBuilder_v8 & {
+ m_operation.scaledesc = scale_tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setBias(Tensor_v8 const &bias_tensor) -> OperationBuilder_v8 & {
+ m_operation.biasdesc = bias_tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setScaleAndBias(Tensor_v8 const &scale_tensor, Tensor_v8 const &bias_tensor) -> OperationBuilder_v8 & {
+ m_operation.scaledesc = scale_tensor.get_desc();
+ m_operation.biasdesc = bias_tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setDScale(Tensor_v8 const &scale_tensor) -> OperationBuilder_v8 & {
+ m_operation.dscaledesc = scale_tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setDBias(Tensor_v8 const &bias_tensor) -> OperationBuilder_v8 & {
+ m_operation.dbiasdesc = bias_tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setDScaleAndDBias(Tensor_v8 const &scale_tensor, Tensor_v8 const &bias_tensor) -> OperationBuilder_v8 & {
+ m_operation.dscaledesc = scale_tensor.get_desc();
+ m_operation.dbiasdesc = bias_tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setEqScalesAndBias(Tensor_v8 const &eq_scale_tensor1,
+ Tensor_v8 const &eq_scale_tensor2,
+ Tensor_v8 const &eq_bias_tensor) -> OperationBuilder_v8 & {
+ m_operation.eqscaledesc = eq_scale_tensor1.get_desc();
+ m_operation.eqscaledesc1 = eq_scale_tensor2.get_desc();
+ m_operation.eqbiasdesc = eq_bias_tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setEqScaleAndBias(Tensor_v8 const &eq_scale_tensor, Tensor_v8 const &eq_bias_tensor) -> OperationBuilder_v8 & {
+ m_operation.eqscaledesc = eq_scale_tensor.get_desc();
+ m_operation.eqbiasdesc = eq_bias_tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setSumDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.sumdesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setSqSumDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ m_operation.sqsumdesc = tensor.get_desc();
+ return *this;
+ }
+
+ auto
+ setaMatDesc(ManagedOpaqueDescriptor const &raw_tensor) -> OperationBuilder_v8 & {
+ m_operation.amatdesc = raw_tensor;
+ return *this;
+ }
+ auto
+ setaMatDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_matmul_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Matmul operation does not need a Matrix Tensor");
+ }
+ m_operation.amatdesc = tensor.get_desc();
+ return *this;
+ }
+ auto
+ setbMatDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_matmul_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Matmul operation does not need b Matrix Tensor");
+ }
+ m_operation.bmatdesc = tensor.get_desc();
+ return *this;
+ }
+ auto
+ setcMatDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_matmul_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Matmul operation does not need c Matrix Tensor");
+ }
+ m_operation.cmatdesc = tensor.get_desc();
+ return *this;
+ }
+ auto
+ setmOverrideDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_matmul_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Matmul operation does not need mOverride Tensor");
+ }
+ m_operation.moverridedesc = tensor.get_desc();
+ return *this;
+ }
+ auto
+ setnOverrideDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_matmul_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Matmul operation does not need nOverride Tensor");
+ }
+ m_operation.noverridedesc = tensor.get_desc();
+ return *this;
+ }
+ auto
+ setkOverrideDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_matmul_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Matmul operation does not need kOverride Tensor");
+ }
+ m_operation.koverridedesc = tensor.get_desc();
+ return *this;
+ }
+ auto
+ setmatmulDesc(MatMulDesc_v8 const &matmulDesc) -> OperationBuilder_v8 & {
+ if (is_matmul_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Matmul operation does not need MATMUL DESCRIPTOR");
+ }
+ m_operation.matmuldesc = matmulDesc.get_desc();
+ return *this;
+ }
+ auto
+ setreductionDesc(ReductionDesc_v8 const &reductionDesc) -> OperationBuilder_v8 & {
+ if (is_reduction_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Reduction operation does not need REDUCTION DESCRIPTOR");
+ }
+ m_operation.reductiondesc = reductionDesc.get_desc();
+ return *this;
+ }
+ auto
+ setGroupOffsetDesc(Tensor_v8 const &tensor) -> OperationBuilder_v8 & {
+ if (is_reduction_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Reduction operation does not need GROUP OFFSET DESCRIPTOR");
+ }
+ m_operation.groupoffsetdesc = tensor.get_desc();
+ return *this;
+ }
+ auto
+ setGroupOffsetDesc(ManagedOpaqueDescriptor const &raw_tensor) -> OperationBuilder_v8 & {
+ if (is_reduction_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Reduction operation does not need GROUP OFFSET DESCRIPTOR");
+ }
+ m_operation.groupoffsetdesc = raw_tensor;
+ return *this;
+ }
+ auto
+ setpwDesc(PointWiseDesc_v8 const &pointWiseDesc) -> OperationBuilder_v8 & {
+ if (is_pointwise_op == false) {
+ set_error_and_throw_exception(
+ &m_operation,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR: Non Pointwise operation does not need POINTWISE DESCRIPTOR");
+ }
+ m_operation.pwdesc = pointWiseDesc.get_desc();
+ m_operation.pointwise_port_count = pointWiseDesc.getPortCount();
+ m_operation.pointwise_mode = pointWiseDesc.getPointWiseMode();
+
+ m_operation.is_pointwise_math_op = ((m_operation.pointwise_mode == PointwiseMode_t::ADD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::MUL) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::DIV) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::SUB) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::ADD_SQUARE) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::RSQRT) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::SIN) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::COS) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::TAN) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::LOGICAL_OR) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::LOGICAL_AND) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::LOGICAL_NOT) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::CMP_EQ) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::CMP_NEQ) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::CMP_GT) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::CMP_GE) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::CMP_LT) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::CMP_LE) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::LOG) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::NEG) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::MOD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::POW) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::ABS) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::CEIL) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::FLOOR) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::GEN_INDEX) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::BINARY_SELECT) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::ERF) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::RECIPROCAL) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::MIN) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::MAX) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::SQRT));
+
+ m_operation.is_pointwise_identity_op = (m_operation.pointwise_mode == PointwiseMode_t::IDENTITY);
+
+ m_operation.is_pointwise_activation_fwd_op =
+ ((m_operation.pointwise_mode == PointwiseMode_t::RELU_FWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::TANH_FWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::SIGMOID_FWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::ELU_FWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::GELU_FWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::GELU_APPROX_TANH_FWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::SOFTPLUS_FWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::EXP) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::SWISH_FWD));
+
+ m_operation.is_pointwise_activation_bwd_op =
+ ((m_operation.pointwise_mode == PointwiseMode_t::RELU_BWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::TANH_BWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::SIGMOID_BWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::ELU_BWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::GELU_BWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::GELU_APPROX_TANH_BWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::SOFTPLUS_BWD) ||
+ (m_operation.pointwise_mode == PointwiseMode_t::SWISH_BWD));
+
+ return *this;
+ }
+
+ auto
+ setAlpha(float alpha) -> OperationBuilder_v8 & {
+ m_operation.alpha_d = static_cast<double>(alpha);
+ m_operation.alpha_s = alpha;
+ return *this;
+ }
+ auto
+ setAlpha(double alpha) -> OperationBuilder_v8 & {
+ m_operation.alpha_s = static_cast<float>(alpha);
+ m_operation.alpha_d = alpha;
+ return *this;
+ }
+ auto
+ setAlpha2(float alpha) -> OperationBuilder_v8 & {
+ m_operation.alpha2_d = static_cast<double>(alpha);
+ m_operation.alpha2_s = alpha;
+ return *this;
+ }
+ auto
+ setAlpha2(double alpha) -> OperationBuilder_v8 & {
+ m_operation.alpha2_s = static_cast<float>(alpha);
+ m_operation.alpha2_d = alpha;
+ return *this;
+ }
+ auto
+ setBeta(float beta) -> OperationBuilder_v8 & {
+ m_operation.beta_d = static_cast<double>(beta);
+ m_operation.beta_s = beta;
+ return *this;
+ }
+ auto
+ setBeta(double beta) -> OperationBuilder_v8 & {
+ m_operation.beta_s = static_cast<float>(beta);
+ m_operation.beta_d = beta;
+ return *this;
+ }
+
+ auto
+ setSeed(int64_t seed) -> OperationBuilder_v8 & {
+ m_operation.seed = seed;
+ return *this;
+ }
+
+ auto
+ setComputeType(cudnnDataType_t dtype) -> OperationBuilder_v8 & {
+ m_operation.compute_type = dtype;
+ return *this;
+ }
+
+ auto
+ setMathPrecision(cudnnDataType_t dtype) -> OperationBuilder_v8 & {
+ return setComputeType(dtype);
+ }
+
+ auto
+ setGenStatsMode(cudnnGenStatsMode_t type) -> OperationBuilder_v8 & {
+ m_operation.genstats_mode = type;
+ return *this;
+ }
+
+ OperationBuilder_v8(DescriptorType_t mode) {
+ m_operation.op_mode = mode;
+ is_convolution_op =
+ ((m_operation.op_mode == DescriptorType_t::OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR) ||
+ (m_operation.op_mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR) ||
+ (m_operation.op_mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR));
+
+ is_pointwise_op = (m_operation.op_mode == DescriptorType_t::OPERATION_POINTWISE_DESCRIPTOR);
+ is_matmul_op = (m_operation.op_mode == DescriptorType_t::OPERATION_MATMUL_DESCRIPTOR);
+ is_reduction_op = (m_operation.op_mode == DescriptorType_t::OPERATION_REDUCTION_DESCRIPTOR);
+ is_genstats_op = (m_operation.op_mode == DescriptorType_t::OPERATION_GEN_STATS_DESCRIPTOR);
+ is_bn_finalize_op = (m_operation.op_mode == DescriptorType_t::OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR);
+ is_bn_bwd_weight = (m_operation.op_mode == DescriptorType_t::OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR);
+ is_resample_fwd_op = (m_operation.op_mode == DescriptorType_t::OPERATION_RESAMPLE_FWD_DESCRIPTOR);
+ is_norm_forward_op = (m_operation.op_mode == DescriptorType_t::OPERATION_NORM_FORWARD_DESCRIPTOR);
+ is_norm_backward_op = (m_operation.op_mode == DescriptorType_t::OPERATION_NORM_BACKWARD_DESCRIPTOR);
+ is_resample_bwd_op = (m_operation.op_mode == DescriptorType_t::OPERATION_RESAMPLE_BWD_DESCRIPTOR);
+ is_rng_op = (m_operation.op_mode == DescriptorType_t::OPERATION_RNG_DESCRIPTOR);
+ is_reshape_op = (m_operation.op_mode == DescriptorType_t::OPERATION_RESHAPE_DESCRIPTOR);
+ is_paged_cache_load_op = (m_operation.op_mode == DescriptorType_t::OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR);
+ }
+
+ // This constructor which takes in cudnn C backend enum for cudnnBackendDescriptorType_t will be deprecated,
+ // in favour of OperationBuilder_v8(cudnn_frontend::DescriptorType_t)
+ OperationBuilder_v8(cudnnBackendDescriptorType_t mode)
+ : OperationBuilder_v8(detail::convert_from_cudnn_type(mode)) {}
+
+ /** @} */
+
+ //! constructs the backend Operation_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ Operation_v8 &&
+ build() {
+ if (m_operation.status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operation, m_operation.status, "CUDNN_BACKEND_OPERATION: Operation not initialized properly");
+ return std::move(m_operation);
+ }
+
+ Message_t msg = nullptr;
+ cudnnStatus_t status_ = CUDNN_STATUS_SUCCESS;
+ if (is_convolution_op) {
+ status_ = validate_convolution_op(msg);
+ } else if (is_pointwise_op) {
+ status_ = validate_pointwise_op(msg);
+ } else if (is_matmul_op) {
+ status_ = validate_matmul_op(msg);
+ } else if (is_reduction_op) {
+ status_ = validate_reduction_op(msg);
+ } else if (is_genstats_op) {
+ status_ = CUDNN_STATUS_SUCCESS;
+ } else if (is_bn_finalize_op) {
+ status_ = CUDNN_STATUS_SUCCESS;
+ } else if (is_bn_bwd_weight) {
+ status_ = validate_bn_bwd_weight_op(msg);
+ } else if (is_resample_fwd_op) {
+ status_ = validate_resample_op(msg);
+ } else if (is_resample_bwd_op) {
+ status_ = validate_resample_op(msg);
+ } else if (is_rng_op) {
+ status_ = validate_rng_op(msg);
+ } else if (is_norm_forward_op || is_norm_backward_op) {
+ status_ = validate_norm_op(msg);
+ } else if (is_reshape_op) {
+ status_ = validate_reshape_op(msg);
+ } else if (is_paged_cache_load_op) {
+ status_ = CUDNN_STATUS_SUCCESS;
+ } else {
+ status_ = CUDNN_STATUS_BAD_PARAM;
+ msg =
+ "CUDNN_BACKEND_OPERATION_DESCRIPTOR: Unsupported cudnn backend descriptor type. Check and set "
+ "CUDNN_BACKEND_OPERATION_*_DESCRIPTOR";
+ }
+ if (status_ != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status_, msg);
+ return std::move(m_operation);
+ }
+
+ // Create the descriptor.
+ cudnnBackendDescriptorType_t cudnn_backend_descriptor_type;
+ auto status = detail::convert_to_cudnn_type(m_operation.op_mode, cudnn_backend_descriptor_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_OPERATION: unable to identify backend operation for " << m_operation.op_mode;
+ set_error_and_throw_exception(&m_operation, status, (ss.str()).c_str());
+ return std::move(m_operation);
+ }
+ status = m_operation.initialize_managed_backend_pointer(cudnn_backend_descriptor_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operation, status, "CUDNN_BACKEND_OPERATION: cudnnCreate Failed");
+ return std::move(m_operation);
+ }
+
+ if (m_operation.op_mode == DescriptorType_t::OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR) {
+ return build_conv_forward();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR) {
+ return build_conv_backward_filter();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) {
+ return build_conv_backward_data();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_POINTWISE_DESCRIPTOR) {
+ return build_pointwise_op();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_MATMUL_DESCRIPTOR) {
+ return build_matmul_op();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_REDUCTION_DESCRIPTOR) {
+ return build_reduction_op();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_GEN_STATS_DESCRIPTOR) {
+ return build_genstats_op();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR) {
+ return build_bn_finalize_op();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR) {
+ return build_bn_bwd_weight_op();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_RESAMPLE_FWD_DESCRIPTOR) {
+ return build_resample_fwd_operation();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_NORM_FORWARD_DESCRIPTOR) {
+ return build_norm_forward();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_NORM_BACKWARD_DESCRIPTOR) {
+ return build_norm_backward();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_RESAMPLE_BWD_DESCRIPTOR) {
+ return build_resample_bwd_operation();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_RNG_DESCRIPTOR) {
+ return build_rng_operation();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR) {
+ return build_paged_cache_load_op();
+ } else if (m_operation.op_mode == DescriptorType_t::OPERATION_RESHAPE_DESCRIPTOR) {
+ return build_reshape_operation();
+ } else {
+ set_error_and_throw_exception(
+ &m_operation, status, "CUDNN_BACKEND_OPERATION: unimplemented operation in frontend");
+ }
+ CUDNN_FE_LOG_LABEL_ENDL(m_operation);
+ return std::move(m_operation);
+ }
+};
+
+using Operation = Operation_v8;
+using OperationBuilder = OperationBuilder_v8;
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_OperationGraph.h b/deps/cudnn-frontend/include/cudnn_frontend_OperationGraph.h
new file mode 100644
index 0000000..903d932
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_OperationGraph.h
@@ -0,0 +1,360 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+#include <vector>
+
+#include "cudnn_frontend_Operation.h"
+#include "cudnn_frontend_utils.h"
+// Compile time constant for max ops in a op graph
+constexpr int64_t MAX_OPGRAPH_OPS = 250;
+
+namespace cudnn_frontend {
+
+///
+/// OperationGraph_v8 Class
+/// This class tells the properties of the Tensor_v8 on which the operation will be
+/// performed
+/// Properties:
+/// - handle
+/// - operation
+///
+/// Use OperationGraphBuilder_v8 to build this class.
+/// Describe returns a string describing the tensor class
+///
+class OperationGraph_v8 : public BackendDescriptor {
+ public:
+ friend class OperationGraphBuilder_v8;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR has " << numOps << " operations." << std::endl;
+ ss << "Tag: " << opGraphTag << std::endl;
+ return ss.str();
+ }
+
+ OperationGraph_v8(OperationGraph_v8 &&from) = default;
+ OperationGraph_v8 &
+ operator=(OperationGraph_v8 &&from) = default;
+
+ ~OperationGraph_v8() = default;
+
+ /** @defgroup OperationGraphQuery
+ * Query individual property of OperationGraph_v8 class
+ * @{
+ */
+ //! Query the total count of the engines for the Operation Set
+ auto
+ getEngineCount(void) const -> int64_t {
+ int64_t global_count = -1;
+ auto status = detail::get_attribute(pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATIONGRAPH_ENGINE_GLOBAL_COUNT,
+ CUDNN_TYPE_INT64,
+ 1,
+ nullptr,
+ &global_count);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(this,
+ status,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: GetAttribute "
+ "CUDNN_ATTR_OPERATIONGRAPH_ENGINE_GLOBAL_COUNT Failed");
+ }
+ return global_count;
+ }
+ /** @} */
+
+ uint64_t
+ getOpCount() const {
+ return numOps;
+ }
+
+ std::string const &
+ getTag() const {
+ return opGraphTag;
+ }
+
+ bool
+ setFeatureVector(feature_vector_t fv) {
+ feature_vectors.push_back(fv);
+ return true;
+ }
+
+ feature_vector_t
+ getFeatureVector() const {
+ if (feature_vectors.size() != 0) {
+ return feature_vectors[0];
+ } else {
+ return {};
+ }
+ }
+
+ const std::array<ManagedOpaqueDescriptor, MAX_OPGRAPH_OPS> &
+ getOps() const {
+ return ops;
+ }
+
+ private:
+ OperationGraph_v8() = default;
+ OperationGraph_v8(OperationGraph_v8 const &) = delete;
+ OperationGraph_v8 &
+ operator=(OperationGraph_v8 const &) = delete;
+
+ cudnnHandle_t handle = nullptr;
+ std::array<ManagedOpaqueDescriptor, MAX_OPGRAPH_OPS> ops{};
+ int64_t numOps = -1;
+ std::string opGraphTag = "";
+ std::vector<feature_vector_t> feature_vectors;
+ bool is_dynamic_shape_enabled = false;
+ bool is_override_shape_enabled = false;
+};
+
+///
+/// OperationGraphBuilder_v8 Class
+/// Helper class used to build OperationGraph_v8 class
+class OperationGraphBuilder_v8 {
+ public:
+ /** @defgroup OperationGraphBuilder_v8
+ * Set individual property of OperationGraph_v8 class
+ * @{
+ */
+ //! Set cudnnHandle for the operations
+ auto
+ setHandle(cudnnHandle_t handle_) -> OperationGraphBuilder_v8 & {
+ m_operationGraph.handle = handle_;
+ return *this;
+ }
+ //! Set numoperations and the operations
+ auto
+ setOperationGraph(int64_t numOps_, Operation_v8 const **ops_) -> OperationGraphBuilder_v8 & {
+ if (numOps_ > MAX_OPGRAPH_OPS) {
+ set_error_and_throw_exception(&m_operationGraph,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: numOps exceeds MAX_OPGRAPH_OPS");
+ return *this;
+ }
+ m_operationGraph.numOps = numOps_;
+ m_operationGraph.feature_vectors.resize(static_cast<size_t>(numOps_));
+ for (auto i = 0u; i < numOps_; i++) {
+ m_operationGraph.ops[i] = ops_[i]->get_desc();
+ m_operationGraph.opGraphTag += ops_[i]->getTag() + '_';
+ m_operationGraph.feature_vectors[i] = ops_[i]->getFeatureVector();
+ }
+ return *this;
+ }
+
+ //! Set numoperations and the operations
+ auto
+ setOperationGraph(std::vector<Operation> const &ops_) -> OperationGraphBuilder_v8 & {
+ if (ops_.size() > static_cast<size_t>(MAX_OPGRAPH_OPS)) {
+ set_error_and_throw_exception(&m_operationGraph,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: numOps exceeds MAX_OPGRAPH_OPS");
+ return *this;
+ }
+ m_operationGraph.numOps = ops_.size();
+ m_operationGraph.feature_vectors.resize(ops_.size());
+ for (auto i = 0u; i < ops_.size(); i++) {
+ m_operationGraph.ops[i] = ops_[i].get_desc();
+ m_operationGraph.opGraphTag += ops_[i].getTag() + '_';
+ m_operationGraph.feature_vectors[i] = ops_[i].getFeatureVector();
+ }
+ return *this;
+ }
+
+ auto
+ addOperation(ManagedOpaqueDescriptor desc) -> OperationGraphBuilder_v8 & {
+ if (m_operationGraph.numOps >= MAX_OPGRAPH_OPS) {
+ set_error_and_throw_exception(&m_operationGraph,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: numOps exceeds MAX_OPGRAPH_OPS");
+ return *this;
+ }
+ m_operationGraph.ops[m_operationGraph.numOps] = desc;
+ ++m_operationGraph.numOps;
+ return *this;
+ }
+ /** @} */
+
+ auto
+ setIsDynamicShapeEnabled(bool is_enabled) -> OperationGraphBuilder_v8 & {
+ m_operationGraph.is_dynamic_shape_enabled = is_enabled;
+ return *this;
+ }
+
+ auto
+ setIsOverrideShapeEnabled(bool is_enabled) -> OperationGraphBuilder_v8 & {
+ m_operationGraph.is_override_shape_enabled = is_enabled;
+ return *this;
+ }
+
+ //! constructs the OperationGraph_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ OperationGraph_v8 &&
+ build() {
+ if (m_operationGraph.numOps <= 0) {
+ set_error_and_throw_exception(
+ &m_operationGraph,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: Check and Set the CUDNN_ATTR_OPERATIONGRAPH_OPS Count field");
+ return std::move(m_operationGraph);
+ }
+ if (m_operationGraph.numOps > MAX_OPGRAPH_OPS) {
+ set_error_and_throw_exception(&m_operationGraph,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: numOps exceeds MAX_OPGRAPH_OPS");
+ return std::move(m_operationGraph);
+ }
+ if (m_operationGraph.ops[0] == nullptr) {
+ set_error_and_throw_exception(
+ &m_operationGraph,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: Check and set CUDNN_ATTR_OPERATIONGRAPH_OPS field");
+ return std::move(m_operationGraph);
+ }
+// handle is not a must-have after cudnn 9.8.0
+#if (CUDNN_VERSION < 90800)
+ if (m_operationGraph.handle == nullptr) {
+ set_error_and_throw_exception(
+ &m_operationGraph,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: Check and Set CUDNN_ATTR_OPERATIONGRAPH_HANDLE");
+ return std::move(m_operationGraph);
+ }
+#endif
+
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_operationGraph.initialize_managed_backend_pointer(CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operationGraph, status, "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_operationGraph);
+ }
+
+ std::array<cudnnBackendDescriptor_t, MAX_OPGRAPH_OPS> ops_raw{nullptr};
+ for (auto i = 0u; i < m_operationGraph.numOps; i++) {
+ ops_raw[i] = m_operationGraph.ops[i]->get_backend_descriptor();
+ }
+
+ status = detail::set_attribute(m_operationGraph.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATIONGRAPH_OPS,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ m_operationGraph.numOps,
+ ops_raw.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operationGraph,
+ status,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: SetAttribute CUDNN_ATTR_OPERATIONGRAPH_OPS Failed");
+ return std::move(m_operationGraph);
+ }
+
+ if (m_operationGraph.handle != nullptr) {
+ status = detail::set_attribute(m_operationGraph.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATIONGRAPH_HANDLE,
+ CUDNN_TYPE_HANDLE,
+ 1,
+ &m_operationGraph.handle);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operationGraph,
+ status,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: SetAttribute CUDNN_ATTR_OPERATIONGRAPH_HANDLE Failed");
+ return std::move(m_operationGraph);
+ }
+ }
+
+#if (CUDNN_VERSION >= 90400)
+ if (m_operationGraph.is_dynamic_shape_enabled) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 90400,
+ m_operationGraph,
+ "CUDNN_BACKEND_OPERATION_GRAPH: Dynamic shape support requires cudnn 9.4.0 and above");
+ status = detail::set_attribute(m_operationGraph.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATIONGRAPH_IS_DYNAMIC_SHAPE_ENABLED,
+ CUDNN_TYPE_BOOLEAN,
+ 1,
+ &m_operationGraph.is_dynamic_shape_enabled);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operationGraph,
+ status,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_OPERATIONGRAPH_IS_DYNAMIC_SHAPE_ENABLED Failed");
+ return std::move(m_operationGraph);
+ }
+ }
+#endif
+
+#if (CUDNN_VERSION >= 92100)
+ if (m_operationGraph.is_override_shape_enabled) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 92100,
+ m_operationGraph,
+ "CUDNN_BACKEND_OPERATION_GRAPH: Override shape support requires cudnn 9.21.0 and above");
+ status = detail::set_attribute(m_operationGraph.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_OPERATIONGRAPH_IS_OVERRIDE_SHAPE_ENABLED,
+ CUDNN_TYPE_BOOLEAN,
+ 1,
+ &m_operationGraph.is_override_shape_enabled);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_operationGraph,
+ status,
+ "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_OPERATIONGRAPH_IS_OVERRIDE_SHAPE_ENABLED Failed");
+ return std::move(m_operationGraph);
+ }
+ }
+#endif
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_operationGraph.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_operationGraph, status, "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_operationGraph);
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL(m_operationGraph);
+ return std::move(m_operationGraph);
+ }
+
+ explicit OperationGraphBuilder_v8() = default;
+ ~OperationGraphBuilder_v8() = default;
+ OperationGraphBuilder_v8(OperationGraphBuilder_v8 &&) = delete;
+ OperationGraphBuilder_v8(OperationGraphBuilder_v8 const &) = delete;
+ OperationGraphBuilder_v8 &
+ operator=(OperationGraphBuilder_v8 const &) = delete;
+
+ private:
+ OperationGraph_v8 m_operationGraph;
+};
+
+using OperationGraph = OperationGraph_v8;
+using OperationGraphBuilder = OperationGraphBuilder_v8;
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_PointWiseDesc.h b/deps/cudnn-frontend/include/cudnn_frontend_PointWiseDesc.h
new file mode 100644
index 0000000..87bfbd2
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_PointWiseDesc.h
@@ -0,0 +1,411 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+
+namespace cudnn_frontend {
+namespace graph {
+class PointwiseNode;
+}
+} // namespace cudnn_frontend
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+#include <limits>
+
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+///
+/// PointWiseDesc Descriptor Class
+/// This class tells the properties of the PointWise operation
+/// Properties:
+/// - compute_type
+/// - mode
+/// - nan_propagation
+/// - upper_clip
+/// - lower_clip
+/// - lower_clip_slope
+/// - elu_alpha
+/// - softplus_beta
+/// - swish_beta
+///
+/// Use PointWiseDesc_v8 to build this class.
+/// Describe returns a string describing the PointWise operation
+///
+class PointWiseDesc_v8 : public BackendDescriptor {
+ public:
+ friend class PointWiseDescBuilder_v8;
+ friend class cudnn_frontend::graph::PointwiseNode;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ ss << "CUDNN_BACKEND_POINTWISE_DESCRIPTOR :" << " Mode: " << json{mode} << " Math precision "
+ << json{compute_type};
+#else
+ ss << "CUDNN_BACKEND_POINTWISE_DESCRIPTOR :" << " Mode: " << int(mode) << " Math precision "
+ << int(compute_type);
+#endif
+ return ss.str();
+ }
+
+ int64_t
+ getPortCount() const {
+ return get_pointwise_mode_port_count(mode);
+ }
+
+ PointwiseMode_t
+ getPointWiseMode() const {
+ return mode;
+ }
+
+ PointWiseDesc_v8(PointWiseDesc_v8 &&from) = default;
+ PointWiseDesc_v8 &
+ operator=(PointWiseDesc_v8 &&from) = default;
+
+ ~PointWiseDesc_v8() = default;
+
+ private:
+ PointWiseDesc_v8() = default;
+ PointWiseDesc_v8(PointWiseDesc_v8 const &) = delete;
+ PointWiseDesc_v8 &
+ operator=(PointWiseDesc_v8 const &) = delete;
+
+ DataType_t compute_type = DataType_t::FLOAT;
+ PointwiseMode_t mode = PointwiseMode_t::NOT_SET;
+ cudnnNanPropagation_t nan_propagation = CUDNN_PROPAGATE_NAN;
+ double upper_clip = std::numeric_limits<double>::max();
+ double lower_clip = 0.0;
+ double lower_clip_slope = 0.0;
+ double elu_alpha = 1.0;
+ double softplus_beta = 1.0;
+ double swish_beta = 1.0;
+ int64_t axis = -1;
+};
+
+////
+/// PointWiseDescBuilder_v8 Class
+/// Helper class used to build PointWiseDesc_v8 class
+class PointWiseDescBuilder_v8 {
+ public:
+ /** @defgroup PointWiseDescBuilder_v8
+ * Set individual property of PointWiseDesc_v8 class
+ * @{
+ */
+ //! Set Math Precision Data Type for the Convolution Operation
+ auto
+ setComputeType(DataType_t data_type_) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.compute_type = data_type_;
+ return *this;
+ }
+ auto
+ setComputeType(cudnnDataType_t data_type_) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.compute_type = detail::convert_from_cudnn_type(data_type_);
+ return *this;
+ }
+ //! Set upper and lower limits for the RELU activation
+ auto
+ setClipping(double l, double u) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.upper_clip = u;
+ m_pointWiseDesc.lower_clip = l;
+ return *this;
+ }
+ //! Set pointwise mode for the activation
+ auto
+ setMode(PointwiseMode_t mode) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.mode = mode;
+ return *this;
+ }
+
+ //! To be deprecated. Please use setMode(PointwiseMode_t).
+ auto
+ setMode(cudnnPointwiseMode_t mode) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.mode = detail::convert_from_cudnn_type(mode);
+ return *this;
+ }
+
+ //! Set NaN propagation mode
+ auto
+ setMode(cudnnNanPropagation_t nan_mode_) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.nan_propagation = nan_mode_;
+ return *this;
+ }
+ /** @} */
+
+ // TODO Deprecate in v1.0
+ auto
+ setMathPrecision(cudnnDataType_t data_type_) -> PointWiseDescBuilder_v8 & {
+ return setComputeType(data_type_);
+ }
+
+ auto
+ setReluLowerClip(double lower_clip_) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.lower_clip = lower_clip_;
+ return *this;
+ }
+
+ auto
+ setReluUpperClip(double upper_clip_) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.upper_clip = upper_clip_;
+ return *this;
+ }
+
+ auto
+ setReluLowerClipSlope(double lower_clip_slope_) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.lower_clip_slope = lower_clip_slope_;
+ return *this;
+ }
+
+ auto
+ setEluAlpha(double elu_alpha_) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.elu_alpha = elu_alpha_;
+ return *this;
+ }
+
+ auto
+ setSoftplusBeta(double softplus_beta_) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.softplus_beta = softplus_beta_;
+ return *this;
+ }
+
+ auto
+ setSwishBeta(double swish_beta_) -> PointWiseDescBuilder_v8 & {
+ m_pointWiseDesc.swish_beta = swish_beta_;
+ return *this;
+ }
+
+ auto
+ setAxis(int64_t axis_) -> PointWiseDescBuilder_v8 & {
+ CUDNN_FRONTEND_UNUSED(axis_);
+ m_pointWiseDesc.axis = axis_;
+ return *this;
+ }
+
+ //! constructs the PointWiseDesc_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ PointWiseDesc_v8
+ build() {
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_pointWiseDesc.initialize_managed_backend_pointer(CUDNN_BACKEND_POINTWISE_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc, status, "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_pointWiseDesc);
+ }
+
+ // Once Created lets set the descriptor parameters.
+ cudnnPointwiseMode_t cudnn_pointwise_mode;
+ status = detail::convert_to_cudnn_type(m_pointWiseDesc.mode, cudnn_pointwise_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_TYPE_POINTWISE_MODE Failed");
+ return std::move(m_pointWiseDesc);
+ }
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_MODE,
+ CUDNN_TYPE_POINTWISE_MODE,
+ 1,
+ &cudnn_pointwise_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_TYPE_POINTWISE_MODE Failed");
+ return std::move(m_pointWiseDesc);
+ }
+
+ cudnnDataType_t cudnn_data_type;
+ status = detail::convert_to_cudnn_type(m_pointWiseDesc.compute_type, cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_ATTR_POINTWISE_MATH_PREC Failed");
+ return std::move(m_pointWiseDesc);
+ }
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_MATH_PREC,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_ATTR_POINTWISE_MATH_PREC Failed");
+ return std::move(m_pointWiseDesc);
+ }
+
+ if (m_pointWiseDesc.mode == PointwiseMode_t::RELU_FWD || m_pointWiseDesc.mode == PointwiseMode_t::RELU_BWD) {
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_NAN_PROPAGATION,
+ CUDNN_TYPE_NAN_PROPOGATION,
+ 1,
+ &m_pointWiseDesc.nan_propagation);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_ATTR_POINTWISE_NAN_PROPAGATION Failed");
+ return std::move(m_pointWiseDesc);
+ }
+
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_RELU_LOWER_CLIP,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &m_pointWiseDesc.lower_clip);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_ATTR_POINTWISE_RELU_LOWER_CLIP, Failed");
+ return std::move(m_pointWiseDesc);
+ }
+
+ if (m_pointWiseDesc.compute_type == DataType_t::FLOAT) {
+ double clamped_upper_clip =
+ std::min<double>(m_pointWiseDesc.upper_clip, std::numeric_limits<float>::max());
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_RELU_UPPER_CLIP,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &clamped_upper_clip);
+
+ } else {
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_RELU_UPPER_CLIP,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &m_pointWiseDesc.upper_clip);
+ }
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_ATTR_POINTWISE_RELU_UPPER_CLIP, Failed");
+ return std::move(m_pointWiseDesc);
+ }
+
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_RELU_LOWER_CLIP_SLOPE,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &m_pointWiseDesc.lower_clip_slope);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_POINTWISE_RELU_LOWER_CLIP_SLOPE, Failed");
+ return std::move(m_pointWiseDesc);
+ }
+ } else if (m_pointWiseDesc.mode == PointwiseMode_t::ELU_FWD ||
+ m_pointWiseDesc.mode == PointwiseMode_t::ELU_BWD) {
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_ELU_ALPHA,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &m_pointWiseDesc.elu_alpha);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_ATTR_POINTWISE_ELU_ALPHA, Failed");
+ return std::move(m_pointWiseDesc);
+ }
+ } else if (m_pointWiseDesc.mode == PointwiseMode_t::SOFTPLUS_FWD ||
+ m_pointWiseDesc.mode == PointwiseMode_t::SOFTPLUS_BWD) {
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_SOFTPLUS_BETA,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &m_pointWiseDesc.softplus_beta);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_ATTR_POINTWISE_SOFTPLUS_BETA, Failed");
+ return std::move(m_pointWiseDesc);
+ }
+ } else if (m_pointWiseDesc.mode == PointwiseMode_t::SWISH_FWD ||
+ m_pointWiseDesc.mode == PointwiseMode_t::SWISH_BWD) {
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_SWISH_BETA,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &m_pointWiseDesc.swish_beta);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_ATTR_POINTWISE_SWISH_BETA, Failed");
+ return std::move(m_pointWiseDesc);
+ }
+ } else if (m_pointWiseDesc.mode == PointwiseMode_t::GEN_INDEX) {
+ status = detail::set_attribute(m_pointWiseDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_POINTWISE_AXIS,
+ CUDNN_TYPE_INT64,
+ 1,
+ &m_pointWiseDesc.axis);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc,
+ status,
+ "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: SetAttribute CUDNN_ATTR_POINTWISE_AXIS, Failed");
+ return std::move(m_pointWiseDesc);
+ }
+ }
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_pointWiseDesc.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_pointWiseDesc, status, "CUDNN_BACKEND_POINTWISE_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_pointWiseDesc);
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL(m_pointWiseDesc);
+ return std::move(m_pointWiseDesc);
+ }
+
+ explicit PointWiseDescBuilder_v8() = default;
+ ~PointWiseDescBuilder_v8() = default;
+ PointWiseDescBuilder_v8(PointWiseDescBuilder_v8 &&) = delete;
+ PointWiseDescBuilder_v8(PointWiseDescBuilder_v8 const &) = delete;
+ PointWiseDescBuilder_v8 &
+ operator=(PointWiseDescBuilder_v8 const &) = delete;
+
+ private:
+ PointWiseDesc_v8 m_pointWiseDesc;
+};
+using PointWiseDescBuilder = PointWiseDescBuilder_v8;
+using PointWiseDesc = PointWiseDesc_v8;
+using PointwiseDescBuilder = PointWiseDescBuilder_v8;
+using PointwiseDesc = PointWiseDesc_v8;
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_ReductionDesc.h b/deps/cudnn-frontend/include/cudnn_frontend_ReductionDesc.h
new file mode 100644
index 0000000..627b5d0
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_ReductionDesc.h
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+
+namespace cudnn_frontend {
+namespace graph {
+class ReductionNode;
+}
+} // namespace cudnn_frontend
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+///
+/// ReductionDesc Descriptor Class
+/// This class tells the properties of the Reduction operation
+/// Properties:
+/// - compute_type
+/// - reduction_mode
+/// - is_deterministic
+///
+/// Use ReductionDesc_v8 to build this class.
+/// Describe returns a string describing the Reduction operation
+///
+class ReductionDesc_v8 : public BackendDescriptor {
+ public:
+ friend class ReductionDescBuilder_v8;
+ friend class cudnn_frontend::graph::ReductionNode;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ ss << "CUDNN_BACKEND_REDUCTION_DESCRIPTOR :"
+ << " Math precision " << json{compute_type} << " Reduction mode " << json{reduction_mode}
+ << " Is deterministic " << json(is_deterministic);
+#else
+ ss << "CUDNN_BACKEND_REDUCTION_DESCRIPTOR :"
+ << " Math precision " << (int)compute_type << " Reduction mode " << int(reduction_mode)
+ << " Is deterministic " << int(is_deterministic);
+#endif
+ return ss.str();
+ }
+
+ ReductionDesc_v8(ReductionDesc_v8 &&from) = default;
+ ReductionDesc_v8 &
+ operator=(ReductionDesc_v8 &&from) = default;
+
+ ~ReductionDesc_v8() = default;
+
+ private:
+ ReductionDesc_v8() = default;
+ ReductionDesc_v8(ReductionDesc_v8 const &) = delete;
+ ReductionDesc_v8 &
+ operator=(ReductionDesc_v8 const &) = delete;
+
+ DataType_t compute_type = DataType_t::NOT_SET;
+ ReductionMode_t reduction_mode = ReductionMode_t::NOT_SET;
+ bool is_deterministic = false;
+};
+
+////
+/// ReductionDescBuilder_v8 Class
+/// Helper class used to build ReductionDesc_v8 class
+class ReductionDescBuilder_v8 {
+ public:
+ /** @defgroup ReductionDescBuilder_v8
+ * Set individual property of ReductionDesc_v8 class
+ * @{
+ */
+ //! Set Math Precision Data Type for the Reduction Operation
+ auto
+ setComputeType(DataType_t data_type_) -> ReductionDescBuilder_v8 & {
+ m_reductionDesc.compute_type = data_type_;
+ return *this;
+ }
+ auto
+ setComputeType(cudnnDataType_t data_type_) -> ReductionDescBuilder_v8 & {
+ m_reductionDesc.compute_type = detail::convert_from_cudnn_type(data_type_);
+ return *this;
+ }
+ //! Set redution operator for the Reduction Operation
+ auto
+ setReductionOp(ReductionMode_t op_) -> ReductionDescBuilder_v8 & {
+ m_reductionDesc.reduction_mode = op_;
+ return *this;
+ }
+ auto
+ setReductionOp(cudnnReduceTensorOp_t op_) -> ReductionDescBuilder_v8 & {
+ m_reductionDesc.reduction_mode = detail::convert_from_cudnn_type(op_);
+ return *this;
+ }
+ /** @} */
+
+ // TODO Deprecate in v1.0
+ auto
+ setMathPrecision(cudnnDataType_t data_type_) -> ReductionDescBuilder_v8 & {
+ return setComputeType(data_type_);
+ }
+ auto
+ setIsDeterministic(bool is_deterministic_) -> ReductionDescBuilder_v8 & {
+ m_reductionDesc.is_deterministic = is_deterministic_;
+ return *this;
+ }
+
+ //! constructs the ReductionDesc_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ ReductionDesc_v8 &&
+ build() {
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_reductionDesc.initialize_managed_backend_pointer(CUDNN_BACKEND_REDUCTION_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_reductionDesc, status, "CUDNN_BACKEND_REDUCTION_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_reductionDesc);
+ }
+
+ // Once Created lets set the descriptor parameters.
+ cudnnDataType_t cudnn_data_type;
+ status = detail::convert_to_cudnn_type(m_reductionDesc.compute_type, cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_reductionDesc,
+ status,
+ "CUDNN_BACKEND_REDUCTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_REDUCTION_COMP_TYPE Failed");
+ return std::move(m_reductionDesc);
+ }
+ status = detail::set_attribute(m_reductionDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_REDUCTION_COMP_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_reductionDesc,
+ status,
+ "CUDNN_BACKEND_REDUCTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_REDUCTION_COMP_TYPE Failed");
+ return std::move(m_reductionDesc);
+ }
+
+ cudnnReduceTensorOp_t cudnn_reduction_mode;
+ status = detail::convert_to_cudnn_type(m_reductionDesc.reduction_mode, cudnn_reduction_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_reductionDesc,
+ status,
+ "CUDNN_BACKEND_REDUCTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_REDUCTION_OPERATOR Failed");
+ return std::move(m_reductionDesc);
+ }
+ status = detail::set_attribute(m_reductionDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_REDUCTION_OPERATOR,
+ CUDNN_TYPE_REDUCTION_OPERATOR_TYPE,
+ 1,
+ &cudnn_reduction_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_reductionDesc,
+ status,
+ "CUDNN_BACKEND_REDUCTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_REDUCTION_OPERATOR Failed");
+ return std::move(m_reductionDesc);
+ }
+
+#if (CUDNN_VERSION >= 91100)
+ // If backend version is less then 9.11.0, then determinisitc mode is not even supported.
+ // But in the default case which exists in current implementations, is_deterministic is false, and should be
+ // ignored.
+ if (detail::get_backend_version() < 91100) {
+ if (m_reductionDesc.is_deterministic) {
+ set_error_and_throw_exception(&m_reductionDesc,
+ CUDNN_STATUS_NOT_SUPPORTED,
+ "CUDNN_BACKEND_REDUCTION_DESCRIPTOR: DETERMINISTIC mode is not supported "
+ "in cudnn version < 9.11.0");
+ return std::move(m_reductionDesc);
+ } else {
+ // Do nothing.
+ }
+ } else {
+ status = detail::set_attribute(m_reductionDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_REDUCTION_IS_DETERMINISTIC,
+ CUDNN_TYPE_BOOLEAN,
+ 1,
+ &m_reductionDesc.is_deterministic);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_reductionDesc,
+ status,
+ "CUDNN_BACKEND_REDUCTION_DESCRIPTOR: SetAttribute CUDNN_ATTR_REDUCTION_IS_DETERMINISTIC Failed");
+ return std::move(m_reductionDesc);
+ }
+ }
+#endif
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_reductionDesc.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_reductionDesc, status, "CUDNN_BACKEND_REDUCTION_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_reductionDesc);
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL(m_reductionDesc);
+ return std::move(m_reductionDesc);
+ }
+
+ explicit ReductionDescBuilder_v8() = default;
+ ~ReductionDescBuilder_v8() = default;
+ ReductionDescBuilder_v8(ReductionDescBuilder_v8 &&) = delete;
+ ReductionDescBuilder_v8(ReductionDescBuilder_v8 const &) = delete;
+ ReductionDescBuilder_v8 &
+ operator=(ReductionDescBuilder_v8 const &) = delete;
+
+ private:
+ ReductionDesc_v8 m_reductionDesc;
+};
+
+using ReductionDesc = ReductionDesc_v8;
+using ReductionDescBuilder = ReductionDescBuilder_v8;
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Reorder_Tensor.h b/deps/cudnn-frontend/include/cudnn_frontend_Reorder_Tensor.h
new file mode 100644
index 0000000..6ac5a8c
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Reorder_Tensor.h
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <iostream>
+#include <utility>
+
+#include "cudnn_frontend_Tensor.h"
+#include "cudnn_frontend_ConvDesc.h"
+
+namespace cudnn_frontend {
+
+[[maybe_unused]] static cudnnStatus_t
+cudnnReorderFilterAndBiasInt8x32(cudnnHandle_t handle,
+ const Tensor_v8 &tensor,
+ const ConvDesc_v8 &conv_desc,
+ void *dev_filter_ptr,
+ void *reordered_filter_ptr,
+ void *dev_bias_ptr,
+ void *reordered_bias_ptr) {
+ auto cudnn_status = CUDNN_STATUS_SUCCESS;
+
+ if (dev_filter_ptr && reordered_filter_ptr == nullptr) {
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+ if (dev_bias_ptr && reordered_bias_ptr == nullptr) {
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ cudnnFilterDescriptor_t filterDesc = nullptr;
+
+ cudnn_status = detail::create_filter_desc_v7(&filterDesc);
+ if (cudnn_status != CUDNN_STATUS_SUCCESS) {
+ return cudnn_status;
+ }
+
+ auto conv_dims = int(conv_desc.getDimensionCount());
+ auto tensor_dims = int(tensor.getDimensionCount());
+ auto non_shape_dims = tensor_dims - conv_dims;
+
+ if (non_shape_dims != 2 && non_shape_dims != 3) {
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ if (conv_dims != 2 && conv_dims != 3) {
+ return CUDNN_STATUS_BAD_PARAM;
+ }
+
+ int filter_dims_[5] = {1, 1, 1, 1, 1};
+ int64_t const *filter_dims = tensor.getDimArray();
+ filter_dims_[0] = static_cast<int>(filter_dims[0]); // n
+ filter_dims_[1] = static_cast<int>((non_shape_dims == 2) ? filter_dims[1] : filter_dims[2]) * 32; // c
+ filter_dims_[2] = static_cast<int>((non_shape_dims == 2) ? filter_dims[2] : filter_dims[3]); // d/h
+ filter_dims_[3] = static_cast<int>((non_shape_dims == 2) ? filter_dims[3] : filter_dims[4]); // h/w
+ if (conv_dims == 3) {
+ filter_dims_[4] = static_cast<int>((non_shape_dims == 2) ? filter_dims[4] : filter_dims[5]); // w
+ }
+
+ cudnn_status = detail::set_ndfilter_desc_v7(
+ filterDesc, CUDNN_DATA_INT8x32, CUDNN_TENSOR_NCHW_VECT_C, conv_dims + 2, filter_dims_);
+
+ if (cudnn_status != CUDNN_STATUS_SUCCESS) {
+ return cudnn_status;
+ }
+
+ int reorderBias = (dev_bias_ptr != nullptr);
+
+ cudnn_status = detail::reorder_filter_bias(handle,
+ filterDesc,
+ CUDNN_DEFAULT_REORDER,
+ dev_filter_ptr,
+ reordered_filter_ptr,
+ reorderBias,
+ dev_bias_ptr,
+ reordered_bias_ptr);
+
+ detail::destroy_filter(filterDesc);
+ return cudnn_status;
+}
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Resample.h b/deps/cudnn-frontend/include/cudnn_frontend_Resample.h
new file mode 100644
index 0000000..a375a45
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Resample.h
@@ -0,0 +1,494 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+namespace graph {
+class ResampleNode;
+}
+} // namespace cudnn_frontend
+
+namespace cudnn_frontend {
+
+///
+/// Resample Descriptor Class
+/// This class tells the properties of the Resample operation
+/// Properties:
+///
+/// Use ResampleDescBuilder_v8 to build this class.
+/// Describe returns a string describing the Resample operation
+///
+class ResampleDesc_v8 : public BackendDescriptor {
+ public:
+ friend class ResampleDescBuilder_v8;
+ friend class graph::ResampleNode;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ char sep = ',';
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ ss << "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: " << "Compute Type: " << json{computeType}
+ << ", Resample Mode: " << json{resample_mode} << ", Spatial Dimensions: " << spatialDim
+ << ", Nan Propagation: " << std::to_string(nanOpt) << ", Padding Mode: " << json{padding_mode};
+#else
+ ss << "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: " << "Compute Type: " << int(computeType)
+ << ", Resample Mode: " << int(resample_mode) << ", Spatial Dimensions: " << spatialDim
+ << ", Nan Propagation: " << std::to_string(nanOpt) << ", Padding Mode: " << int(padding_mode);
+#endif
+
+ ss << ", WindowDim: [";
+ for (auto i = 0; i < spatialDim; i++) {
+ ss << '(' << windowDim[i].numerator << sep << windowDim[i].denominator << ')' << sep;
+ }
+ ss << "]";
+ ss << ", prePadding: [";
+ for (auto i = 0; i < spatialDim; i++) {
+ ss << '(' << prePadding[i].numerator << sep << prePadding[i].denominator << ')' << sep;
+ }
+ ss << "]";
+ ss << ", postPadding: [";
+ for (auto i = 0; i < spatialDim; i++) {
+ ss << '(' << postPadding[i].numerator << sep << postPadding[i].denominator << ')' << sep;
+ }
+ ss << "]";
+ ss << ", stride: [ ";
+ for (auto i = 0; i < spatialDim; i++) {
+ ss << '(' << stride[i].numerator << sep << stride[i].denominator << ')' << sep;
+ }
+ ss << "]";
+ return ss.str();
+ }
+
+ ResampleDesc_v8(ResampleDesc_v8 &&from) = default;
+ ResampleDesc_v8 &
+ operator=(ResampleDesc_v8 &&) = default;
+
+ ~ResampleDesc_v8() = default;
+
+ /** @defgroup ResampleDescBuilder_v8
+ * Get individual property of ResampleDesc_v8 class
+ * @{
+ */
+
+ DataType_t
+ getComputeType() const {
+ return computeType;
+ }
+
+ int64_t
+ getSpatialDimCount() const {
+ return spatialDim;
+ }
+
+ cudnnNanPropagation_t
+ getNanOpt() const {
+ return nanOpt;
+ }
+
+ ResampleMode_t
+ getMode() const {
+ return resample_mode;
+ }
+
+ PaddingMode_t
+ getPaddingMode() const {
+ return padding_mode;
+ }
+
+ cudnnFraction_t const *
+ getSpatialStride() const {
+ return stride;
+ }
+
+ cudnnFraction_t const *
+ getPrePadding() const {
+ return prePadding;
+ }
+
+ cudnnFraction_t const *
+ getPostPadding() const {
+ return postPadding;
+ }
+
+ cudnnFraction_t const *
+ getWindowDim() const {
+ return windowDim;
+ }
+ /** @} */
+
+ private:
+ ResampleDesc_v8() = default;
+ ResampleDesc_v8(ResampleDesc_v8 const &) = delete;
+ ResampleDesc_v8 &
+ operator=(ResampleDesc_v8 const &) = delete;
+
+ // default values for attributes
+ DataType_t computeType = DataType_t::FLOAT;
+ cudnnNanPropagation_t nanOpt = CUDNN_PROPAGATE_NAN;
+ ResampleMode_t resample_mode = ResampleMode_t::NOT_SET;
+ PaddingMode_t padding_mode = PaddingMode_t::NOT_SET;
+
+ int64_t spatialDim = 0;
+
+ // Shape attributes
+ cudnnFraction_t windowDim[CUDNN_DIM_MAX] = {{0, 1}, {0, 1}};
+ cudnnFraction_t prePadding[CUDNN_DIM_MAX] = {{0, 1}, {0, 1}};
+ cudnnFraction_t postPadding[CUDNN_DIM_MAX] = {{0, 1}, {0, 1}};
+ cudnnFraction_t stride[CUDNN_DIM_MAX] = {{0, 1}, {0, 1}};
+};
+
+///
+/// ResampleDescBuilder_v8 Class
+/// Helper class used to build ResampleDesc_v8 class
+class ResampleDescBuilder_v8 {
+ public:
+ /** @defgroup ResampleDescBuilder_v8
+ * Set individual property of ResampleDesc_v8 class
+ * @{
+ */
+ //! Set compute type for the Resample Descriptor
+ auto
+ setComputeType(DataType_t data_type) -> ResampleDescBuilder_v8 & {
+ m_resampleDesc.computeType = data_type;
+ return *this;
+ }
+ // To be deprecated in v1.0.
+ auto
+ setComputeType(cudnnDataType_t data_type_) -> ResampleDescBuilder_v8 & {
+ m_resampleDesc.computeType = detail::convert_from_cudnn_type(data_type_);
+ return *this;
+ }
+
+ //! Set nan propagation mode for the Resample Operation
+ auto
+ setNanPropagation(cudnnNanPropagation_t nanOpt_) -> ResampleDescBuilder_v8 & {
+ m_resampleDesc.nanOpt = nanOpt_;
+ return *this;
+ }
+
+ //! (Overloaded) Set post padding for the Resample Operation with cudnnFraction_t
+ auto
+ setPostPadding(int64_t count, cudnnFraction_t const *arr) -> ResampleDescBuilder_v8 & {
+ // TODO: check the provided array count against the stored spatial dimension count.
+ std::copy(arr, arr + count, m_resampleDesc.postPadding);
+ return *this;
+ }
+
+ //! (Overloaded) Set pre padding for the Resample Operation with cudnnFraction_t
+ auto
+ setPrePadding(int64_t count, cudnnFraction_t const *arr) -> ResampleDescBuilder_v8 & {
+ // TODO: check the provided array count against the stored spatial dimension count.
+ std::copy(arr, arr + count, m_resampleDesc.prePadding);
+ return *this;
+ }
+
+ //! (Overloaded) Set stride for the Resample Operation with cudnnFraction_t
+ auto
+ setSpatialStride(int64_t count, cudnnFraction_t const *arr) -> ResampleDescBuilder_v8 & {
+ // TODO: check the provided array count against the stored spatial dimension count.
+ std::copy(arr, arr + count, m_resampleDesc.stride);
+ return *this;
+ }
+
+ //! Set resample mode for the Resample Operation
+ // To be deprecated. Please use setResampleMode(cudnn_frontend::ResampleMode_t).
+ auto
+ setResampleMode(cudnnResampleMode_t const mode_) -> ResampleDescBuilder_v8 & {
+ detail::convert_from_cudnn_type(mode_, m_resampleDesc.resample_mode);
+ return *this;
+ }
+
+ //! (Overloaded) Set window dim for the Resample Operation with cudnnFraction_t
+ auto
+ setSpatialDim(int64_t count, cudnnFraction_t const *arr) -> ResampleDescBuilder_v8 & {
+ // TODO: check the provided array count against the stored spatial dimension count.
+ m_resampleDesc.spatialDim = count;
+ std::copy(arr, arr + count, m_resampleDesc.windowDim);
+ return *this;
+ }
+
+ //! Set padding mode for the Resample Operation
+ // To be deprecated. Please use setPaddingMode(cudnn_frontend::PaddingMode_t).
+ auto
+ setPaddingMode(cudnnPaddingMode_t const padding_mode) -> ResampleDescBuilder_v8 & {
+ detail::convert_from_cudnn_type(padding_mode, m_resampleDesc.padding_mode);
+ return *this;
+ }
+
+ //! Set padding mode for the Resample Operation
+ auto
+ setPaddingMode(PaddingMode_t const padding_mode) -> ResampleDescBuilder_v8 & {
+ m_resampleDesc.padding_mode = padding_mode;
+ return *this;
+ }
+
+ //! Set resample mode for the Resample Operation
+ auto
+ setResampleMode(ResampleMode_t const mode) -> ResampleDescBuilder_v8 & {
+ m_resampleDesc.resample_mode = mode;
+ return *this;
+ }
+
+ //! (Overloaded) Set post padding for the Resample Operation with int64_t
+ auto
+ setPostPadding(int64_t count, int64_t const *arr) -> ResampleDescBuilder_v8 & {
+ // TODO: check the provided array count against the stored spatial dimension count.
+ for (int i = 0; i < count; i++) {
+ m_resampleDesc.postPadding[i].numerator = arr[i];
+ m_resampleDesc.postPadding[i].denominator = 1;
+ }
+ return *this;
+ }
+
+ //! (Overloaded) Set pre padding for the Resample Operation with int64_t
+ auto
+ setPrePadding(int64_t count, int64_t const *arr) -> ResampleDescBuilder_v8 & {
+ // TODO: check the provided array count against the stored spatial dimension count.
+ for (int i = 0; i < count; i++) {
+ m_resampleDesc.prePadding[i].numerator = arr[i];
+ m_resampleDesc.prePadding[i].denominator = 1;
+ }
+ return *this;
+ }
+
+ //! (Overloaded) Set stride for the Resample Operation with int64_t
+ auto
+ setSpatialStride(int64_t count, int64_t const *arr) -> ResampleDescBuilder_v8 & {
+ // TODO: check the provided array count against the stored spatial dimension count.
+ for (int i = 0; i < count; i++) {
+ m_resampleDesc.stride[i].numerator = arr[i];
+ m_resampleDesc.stride[i].denominator = 1;
+ }
+ return *this;
+ }
+
+ //! (Overloaded) Set window dim for the Resample Operation with int64_t
+ auto
+ setSpatialDim(int64_t count, int64_t const *arr) -> ResampleDescBuilder_v8 & {
+ // TODO: check the provided array count against the stored spatial dimension count.
+ m_resampleDesc.spatialDim = count;
+ for (int i = 0; i < count; i++) {
+ m_resampleDesc.windowDim[i].numerator = arr[i];
+ m_resampleDesc.windowDim[i].denominator = 1;
+ }
+ return *this;
+ }
+
+ /** @} */
+
+ //! constructs the ResampleDesc_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ ResampleDesc_v8 &&
+ build() {
+ // Sanity check if non-default fields have been set correctly.
+ if (m_resampleDesc.spatialDim < 0) {
+ set_error_and_throw_exception(&m_resampleDesc,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: Check and Set the spatialDim field");
+ return std::move(m_resampleDesc);
+ };
+
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_resampleDesc.initialize_managed_backend_pointer(CUDNN_BACKEND_RESAMPLE_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc, status, "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ // Once Created lets set the descriptor parameters.
+ ::cudnnResampleMode_t cudnn_resample_mode;
+ status = detail::convert_to_cudnn_type(m_resampleDesc.resample_mode, cudnn_resample_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_MODE Failed");
+ return std::move(m_resampleDesc);
+ }
+ status = detail::set_attribute(m_resampleDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RESAMPLE_MODE,
+ CUDNN_TYPE_RESAMPLE_MODE,
+ 1,
+ &cudnn_resample_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_MODE Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ cudnnDataType_t cudnn_data_type;
+ status = detail::convert_to_cudnn_type(m_resampleDesc.computeType, cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_COMP_TYPE Failed");
+ return std::move(m_resampleDesc);
+ }
+ status = detail::set_attribute(m_resampleDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RESAMPLE_COMP_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_COMP_TYPE Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ status = detail::set_attribute(m_resampleDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RESAMPLE_NAN_PROPAGATION,
+ CUDNN_TYPE_NAN_PROPOGATION,
+ 1,
+ &(m_resampleDesc.nanOpt));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_NAN_PROPAGATION Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ cudnnPaddingMode_t cudnn_padding_mode;
+ status = detail::convert_to_cudnn_type(m_resampleDesc.padding_mode, cudnn_padding_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_PADDING_MODE Failed");
+ return std::move(m_resampleDesc);
+ }
+ status = detail::set_attribute(m_resampleDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RESAMPLE_PADDING_MODE,
+ CUDNN_TYPE_PADDING_MODE,
+ 1,
+ &cudnn_padding_mode);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_PADDING_MODE Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ status = detail::set_attribute(m_resampleDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RESAMPLE_SPATIAL_DIMS,
+ CUDNN_TYPE_INT64,
+ 1,
+ &(m_resampleDesc.spatialDim));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_SPATIAL_DIMS Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ status = detail::set_attribute(m_resampleDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RESAMPLE_WINDOW_DIMS,
+ CUDNN_TYPE_FRACTION,
+ m_resampleDesc.spatialDim,
+ m_resampleDesc.windowDim);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_WINDOW_DIMS Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ status = detail::set_attribute(m_resampleDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RESAMPLE_PRE_PADDINGS,
+ CUDNN_TYPE_FRACTION,
+ m_resampleDesc.spatialDim,
+ m_resampleDesc.prePadding);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_PRE_PADDINGS Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ status = detail::set_attribute(m_resampleDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RESAMPLE_POST_PADDINGS,
+ CUDNN_TYPE_FRACTION,
+ m_resampleDesc.spatialDim,
+ m_resampleDesc.postPadding);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_POST_PADDINGS Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ status = detail::set_attribute(m_resampleDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RESAMPLE_STRIDES,
+ CUDNN_TYPE_FRACTION,
+ m_resampleDesc.spatialDim,
+ m_resampleDesc.stride);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc,
+ status,
+ "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: SetAttribute CUDNN_ATTR_RESAMPLE_STRIDES Failed");
+ return std::move(m_resampleDesc);
+ }
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_resampleDesc.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_resampleDesc, status, "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_resampleDesc);
+ }
+ CUDNN_FE_LOG_LABEL_ENDL(m_resampleDesc);
+ return std::move(m_resampleDesc);
+ }
+
+ explicit ResampleDescBuilder_v8() = default;
+ ~ResampleDescBuilder_v8() = default;
+ ResampleDescBuilder_v8(ResampleDescBuilder_v8 &&) = delete;
+ ResampleDescBuilder_v8(ResampleDescBuilder_v8 const &) = delete;
+ ResampleDescBuilder_v8 &
+ operator=(ResampleDescBuilder_v8 const &) = delete;
+
+ private:
+ ResampleDesc_v8 m_resampleDesc;
+};
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Rng.h b/deps/cudnn-frontend/include/cudnn_frontend_Rng.h
new file mode 100644
index 0000000..829f8bd
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Rng.h
@@ -0,0 +1,339 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+namespace graph {
+class RngNode;
+}
+} // namespace cudnn_frontend
+
+namespace cudnn_frontend {
+
+///
+/// Rng Descriptor Class
+/// This class tells the properties of the Rng operation
+/// Properties:
+///
+/// Use RngDescBuilder_v8 to build this class.
+/// Describe returns a string describing the Rng operation
+///
+class RngDesc_v8 : public BackendDescriptor {
+ public:
+ friend class RngDescBuilder_v8;
+ friend class graph::RngNode;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+#if (CUDNN_VERSION >= 8700)
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ ss << "CUDNN_BACKEND_RNG_DESCRIPTOR: " << "Distribution Type: " << json{distribution}
+#else
+ ss << "CUDNN_BACKEND_RNG_DESCRIPTOR: " << "Distribution Type: " << int(distribution)
+#endif
+ << ", Normal Distribution Mean: " << normal_dist_mean
+ << ", Normal Distribution Standard Deviation: " << normal_dist_std_dev
+ << ", Uniform Distribution Maximum: " << uniform_dist_max
+ << ", Uniform Distribution Minimum: " << uniform_dist_min
+ << ", Bernoulli Distribution Probability: " << bernoulli_dist_probability;
+#endif
+ return ss.str();
+ }
+
+ RngDesc_v8(RngDesc_v8 &&from) = default;
+ RngDesc_v8 &
+ operator=(RngDesc_v8 &&) = default;
+
+ ~RngDesc_v8() = default;
+
+ /** @defgroup RngDescBuilder_v8
+ * Get individual property of RngDesc_v8 class
+ * @{
+ */
+
+ double
+ getNormalDistMean() const {
+ return normal_dist_mean;
+ }
+
+ double
+ getNormalDistStdDev() const {
+ return normal_dist_std_dev;
+ }
+
+ double
+ getUniformDistMax() const {
+ return uniform_dist_max;
+ }
+
+ double
+ getUniformDistMin() const {
+ return normal_dist_std_dev;
+ }
+
+ double
+ getBernoulliDistProbability() const {
+ return bernoulli_dist_probability;
+ }
+
+ RngDistribution_t
+ getDistribution() const {
+ return distribution;
+ }
+
+ /** @} */
+
+ private:
+ RngDesc_v8() = default;
+ RngDesc_v8(RngDesc_v8 const &) = delete;
+ RngDesc_v8 &
+ operator=(RngDesc_v8 const &) = delete;
+
+ // default values for attributes
+ double normal_dist_mean = -1;
+ double normal_dist_std_dev = -1;
+ double uniform_dist_max = -1;
+ double uniform_dist_min = -1;
+ double bernoulli_dist_probability = -1;
+
+ RngDistribution_t distribution = RngDistribution_t::NOT_SET;
+};
+
+///
+/// RngDescBuilder_v8 Class
+/// Helper class used to build RngDesc_v8 class
+class RngDescBuilder_v8 {
+ public:
+ /** @defgroup RngDescBuilder_v8
+ * Set individual property of RngDesc_v8 class
+ * @{
+ */
+
+ //! Set Rng distribution for the Rng Operation
+ auto
+ setRngDistribution(RngDistribution_t distribution_) -> RngDescBuilder_v8 & {
+ m_RngDesc.distribution = distribution_;
+ return *this;
+ }
+
+#if (CUDNN_VERSION >= 8700)
+ //! Set Rng distribution for the Rng Operation
+ auto
+ setRngDistribution(cudnnRngDistribution_t distribution_) -> RngDescBuilder_v8 & {
+ m_RngDesc.distribution = detail::convert_from_cudnn_type(distribution_);
+ return *this;
+ }
+
+#endif
+
+ //! Set normal distribution params (mean and std dev) for the Rng Operation
+ auto
+ setNormalDistParams(double normal_dist_mean_, double normal_dist_std_dev_) -> RngDescBuilder_v8 & {
+ m_RngDesc.normal_dist_mean = normal_dist_mean_;
+ m_RngDesc.normal_dist_std_dev = normal_dist_std_dev_;
+ return *this;
+ }
+
+ //! Set normal distribution mean for the Rng Operation
+ auto
+ setNormalDistMean(double normal_dist_mean_) -> RngDescBuilder_v8 & {
+ m_RngDesc.normal_dist_mean = normal_dist_mean_;
+ return *this;
+ }
+
+ //! Set normal distribution std dev for the Rng Operation
+ auto
+ setNormalDistStdDev(double normal_dist_std_dev_) -> RngDescBuilder_v8 & {
+ m_RngDesc.normal_dist_std_dev = normal_dist_std_dev_;
+ return *this;
+ }
+
+ //! Set uniform distribution params (min and max) for the Rng Operation
+ auto
+ setUniformDistParams(double uniform_dist_max_, double uniform_dist_min_) -> RngDescBuilder_v8 & {
+ m_RngDesc.uniform_dist_max = uniform_dist_max_;
+ m_RngDesc.uniform_dist_min = uniform_dist_min_;
+ return *this;
+ }
+
+ //! Set uniform distribution max for the Rng Operation
+ auto
+ setUniformDistMax(double uniform_dist_max_) -> RngDescBuilder_v8 & {
+ m_RngDesc.uniform_dist_max = uniform_dist_max_;
+ return *this;
+ }
+
+ //! Set uniform distribution min for the Rng Operation
+ auto
+ setUniformDistMin(double uniform_dist_min_) -> RngDescBuilder_v8 & {
+ m_RngDesc.uniform_dist_min = uniform_dist_min_;
+ return *this;
+ }
+
+ //! Set bernoulli distribution probability for the Rng Operation
+ auto
+ setBernoulliDistProbability(double bernoulli_dist_probability_) -> RngDescBuilder_v8 & {
+ m_RngDesc.bernoulli_dist_probability = bernoulli_dist_probability_;
+ return *this;
+ }
+
+ /** @} */
+
+ //! constructs the RngDesc_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ RngDesc_v8 &&
+ build() {
+#if (CUDNN_VERSION >= 8700)
+ // Create a descriptor. Memory allocation happens here.
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 8700, m_RngDesc, "CUDNN_BACKEND_RNG_DESCRIPTOR: Requires cudnn 8.7.0");
+
+ auto status = m_RngDesc.initialize_managed_backend_pointer(CUDNN_BACKEND_RNG_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_RngDesc, status, "CUDNN_BACKEND_RNG_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_RngDesc);
+ }
+
+ // Once Created lets set the descriptor parameters.
+ cudnnRngDistribution_t cudnn_rng_distribution;
+ status = detail::convert_to_cudnn_type(m_RngDesc.distribution, cudnn_rng_distribution);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_RngDesc, status, "CUDNN_BACKEND_RNG_DESCRIPTOR: SetAttribute CUDNN_ATTR_RNG_DISTRIBUTION Failed");
+ return std::move(m_RngDesc);
+ }
+
+ status = detail::set_attribute(m_RngDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RNG_DISTRIBUTION,
+ CUDNN_TYPE_RNG_DISTRIBUTION,
+ 1,
+ &cudnn_rng_distribution);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_RngDesc, status, "CUDNN_BACKEND_RNG_DESCRIPTOR: SetAttribute CUDNN_ATTR_RNG_DISTRIBUTION Failed");
+ return std::move(m_RngDesc);
+ }
+
+ status = detail::set_attribute(m_RngDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RNG_NORMAL_DIST_MEAN,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &(m_RngDesc.normal_dist_mean));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_RngDesc,
+ status,
+ "CUDNN_BACKEND_RNG_DESCRIPTOR: SetAttribute CUDNN_ATTR_RNG_NORMAL_DIST_MEAN Failed");
+ return std::move(m_RngDesc);
+ }
+
+ status = detail::set_attribute(m_RngDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RNG_NORMAL_DIST_STANDARD_DEVIATION,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &(m_RngDesc.normal_dist_std_dev));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_RngDesc,
+ status,
+ "CUDNN_BACKEND_RNG_DESCRIPTOR: SetAttribute CUDNN_ATTR_RNG_NORMAL_DIST_STANDARD_DEVIATION Failed");
+ return std::move(m_RngDesc);
+ }
+
+ status = detail::set_attribute(m_RngDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RNG_UNIFORM_DIST_MAXIMUM,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &(m_RngDesc.uniform_dist_max));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_RngDesc,
+ status,
+ "CUDNN_BACKEND_RNG_DESCRIPTOR: SetAttribute CUDNN_ATTR_RNG_UNIFORM_DIST_MAXIMUM Failed");
+ return std::move(m_RngDesc);
+ }
+
+ status = detail::set_attribute(m_RngDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RNG_UNIFORM_DIST_MINIMUM,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &(m_RngDesc.uniform_dist_min));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_RngDesc,
+ status,
+ "CUDNN_BACKEND_RNG_DESCRIPTOR: SetAttribute CUDNN_ATTR_RNG_UNIFORM_DIST_MINIMUM Failed");
+ return std::move(m_RngDesc);
+ }
+
+ status = detail::set_attribute(m_RngDesc.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_RNG_BERNOULLI_DIST_PROBABILITY,
+ CUDNN_TYPE_DOUBLE,
+ 1,
+ &(m_RngDesc.bernoulli_dist_probability));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_RngDesc,
+ status,
+ "CUDNN_BACKEND_RNG_DESCRIPTOR: SetAttribute CUDNN_ATTR_RNG_BERNOULLI_DIST_PROBABILITY Failed");
+ return std::move(m_RngDesc);
+ }
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_RngDesc.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_RngDesc, status, "CUDNN_BACKEND_RNG_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_RngDesc);
+ }
+ CUDNN_FE_LOG_LABEL_ENDL(m_RngDesc);
+ return std::move(m_RngDesc);
+#else
+ set_error_and_throw_exception(
+ &m_RngDesc, CUDNN_STATUS_NOT_SUPPORTED, "CUDNN_RNG_DESCRIPTOR: Rng only supported in cuDNN v8.7 or later");
+ return std::move(m_RngDesc);
+#endif
+ }
+
+ explicit RngDescBuilder_v8() = default;
+ ~RngDescBuilder_v8() = default;
+ RngDescBuilder_v8(RngDescBuilder_v8 &&) = delete;
+ RngDescBuilder_v8(RngDescBuilder_v8 const &) = delete;
+ RngDescBuilder_v8 &
+ operator=(RngDescBuilder_v8 const &) = delete;
+
+ private:
+ RngDesc_v8 m_RngDesc;
+};
+
+using RngDesc = RngDesc_v8;
+using RngDescBuilder = RngDescBuilder_v8;
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_Tensor.h b/deps/cudnn-frontend/include/cudnn_frontend_Tensor.h
new file mode 100644
index 0000000..9f1f7c1
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_Tensor.h
@@ -0,0 +1,644 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <cstring>
+#include <functional>
+#include <memory>
+#include <sstream>
+#include <utility>
+#include <vector>
+
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+
+///
+/// Tensor_v8 Class
+/// This class tells the properties of the Tensor_v8 on which the operation will be
+/// performed
+/// Properties:
+/// - dataType
+/// - alignment
+/// - unique identifier
+/// - tensor dimensions
+/// - tensor strides
+/// - isVirtual
+/// - isByValue
+///
+/// Use TensorBuilder_v8 to build this class.
+/// Describe returns a string describing the tensor class
+///
+class Tensor_v8 : public BackendDescriptor {
+ public:
+ friend class TensorBuilder_v8;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ ss << " CUDNN_BACKEND_TENSOR_DESCRIPTOR :\n"
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ << " Datatype: " << json{data_type}
+#else
+ << " Datatype: " << int(data_type)
+#endif
+ << "\n Id: " << id << "\n Dims " << nDims
+ << "\n VectorCount: " << vectorCount
+ << "\n vectorDimension " << vectorDimension;
+ ss << "\n Dim [ ";
+ for (auto i = 0; i < nDims; i++) {
+ if (i != 0) {
+ ss << ',';
+ }
+ ss << btensor_dimA[i];
+ }
+ ss << " ]\n Str [ ";
+ for (auto i = 0; i < nDims; i++) {
+ if (i != 0) {
+ ss << ',';
+ }
+ ss << btensor_strA[i];
+ }
+ ss << " ]";
+ ss << "\n isVirtual: " << isVirtual
+ << "\n isByValue: " << isByValue
+ << "\n Alignment: " << alignment;
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+ ss << "\n reorder_type: " << json{reorder_type};
+#else
+ ss << "\n reorder_type: " << int(reorder_type);
+#endif
+ if (raggedOffset != nullptr) {
+ ss << "\n raggedOffset: Enabled UID: " << raggedOffset->getId();
+ }
+ if (hasRaggedOffsetMultiplier()) {
+ ss << "\n raggedOffsetMultiplier: " << raggedOffsetMultiplier;
+ }
+ return ss.str();
+ }
+
+ int64_t
+ getPackedElementCount() const {
+ int64_t count = vectorCount;
+ for (auto i = 0; i < nDims; i++) {
+ count = count * btensor_dimA[i];
+ }
+ return count;
+ };
+
+ int64_t
+ getDimCount() const {
+ return nDims;
+ }
+
+ int64_t const *
+ getDim() const {
+ return btensor_dimA;
+ }
+
+ int64_t const *
+ getStride() const {
+ return btensor_strA;
+ }
+
+ // TODO: Deprecate in v1.0
+ int64_t const *
+ getDimArray() const {
+ return getDim();
+ }
+
+ // TODO: Deprecate in v1.0
+ int64_t const *
+ getStrideArray() const {
+ return getStride();
+ }
+
+ int64_t
+ getDataType() const {
+ return static_cast<int64_t>(data_type);
+ }
+
+ int64_t
+ getId() const {
+ return id;
+ }
+
+ int64_t
+ getAlignment() const {
+ return alignment;
+ }
+
+ int64_t
+ getRaggedOffsetMultiplier() const {
+ return raggedOffsetMultiplier;
+ }
+
+ bool
+ hasRaggedOffsetMultiplier() const {
+ return raggedOffsetMultiplier != 1;
+ }
+
+ bool
+ isVirtualTensor() const {
+ return isVirtual;
+ }
+
+ // TODO: Deprecate in v1.0
+ int64_t
+ getDimensionCount() const {
+ return getDimCount();
+ }
+
+ Tensor_v8(Tensor_v8 &&from) = default;
+ Tensor_v8 &
+ operator=(Tensor_v8 &&) = default;
+
+ ~Tensor_v8() = default;
+
+ private:
+ Tensor_v8() = default;
+ Tensor_v8(Tensor_v8 const &) = delete;
+ Tensor_v8 &
+ operator=(Tensor_v8 const &) = delete;
+
+ DataType_t data_type = DataType_t::NOT_SET; //! Datatype of the elements
+ int64_t btensor_dimA[CUDNN_DIM_MAX + 1] = {-1}; //! n, g, c, d, h, w
+ int64_t btensor_strA[CUDNN_DIM_MAX + 1] = {-1}; //! n, g, c, d, h, w
+ int64_t id = -1; //! Unique id of the tensor
+ int64_t alignment = -1; //! Alignment of the tensor.
+ //! Certain engine config expect minimum alignment of 16B
+ int64_t nDims = -1; //! Number of Dimensions of the tensor
+ int64_t vectorDimension = -1; //! Which dimension of the tensor is vectorized (Generally the c dim)
+ int64_t vectorCount = 1; //! What is the vectorization count (4 or 32)
+ bool isVirtual = false; //! Whether it is an intermediate tensor of an op graph
+ bool isByValue = false; //! Whether the tensor is in host memory that needs to be passed to the kernel by value
+
+ bool hasConstValue = false; //! Whether this tensor has a compile-time constant value
+ std::vector<uint8_t> constValueBytes; //! Raw bytes of the compile-time constant value
+
+ cudnn_frontend::TensorReordering_t reorder_type =
+ cudnn_frontend::TensorReordering_t::NONE; //! Type of reordering in the tensor
+ std::shared_ptr<Tensor_v8> raggedOffset; //! Ragged offsets for ragged tensors
+ int64_t raggedOffsetMultiplier = 1; //! Unit size of ragged offsets in tensor elements
+};
+
+///
+/// TensorBuilder_v8 Class
+/// Helper class used to build Tensor_v8 class
+class TensorBuilder_v8 {
+ public:
+ /** @defgroup TensorBuilder_v8
+ * Set individual property of Tensor_v8 class
+ * @{
+ */
+ //! Set Datatype for the Tensor_v8
+ auto
+ setDataType(DataType_t data_type) -> TensorBuilder_v8 & {
+ m_tensor.data_type = data_type;
+ return *this;
+ }
+ // To be deprecated in v1.0. Please use setDataType(DataType_t) instead.
+ auto
+ setDataType(cudnnDataType_t data_type) -> TensorBuilder_v8 & {
+ m_tensor.data_type = detail::convert_from_cudnn_type(data_type);
+ return *this;
+ }
+ //! Set Dimensions of the tensor
+ auto
+ setDim(int64_t ndim, int64_t const *dim) -> TensorBuilder_v8 & {
+ std::copy((dim), dim + ndim, m_tensor.btensor_dimA);
+ m_tensor.nDims = ndim;
+ return *this;
+ }
+ //! Set Strides of the tensor
+ auto
+ setStride(int64_t ndim, int64_t const *strides) -> TensorBuilder_v8 & {
+ std::copy(strides, strides + ndim, m_tensor.btensor_strA);
+ return *this;
+ }
+ //! Set Unique Id of the tensor
+ auto
+ setId(int64_t id_) -> TensorBuilder_v8 & {
+ m_tensor.id = id_;
+ return *this;
+ }
+ //! Set Alignment of the tensor
+ auto
+ setAlignment(int64_t alignment_) -> TensorBuilder_v8 & {
+ m_tensor.alignment = alignment_;
+ return *this;
+ }
+ //! Set isVirtual of the tensor
+ auto
+ setVirtual(bool virtual_ = true) -> TensorBuilder_v8 & {
+ m_tensor.isVirtual = virtual_;
+ return *this;
+ }
+ //! Set isByValue of the tensor
+ auto
+ setByValue(bool isByValue_ = true) -> TensorBuilder_v8 & {
+ m_tensor.isByValue = isByValue_;
+ return *this;
+ }
+
+ //! Set compile-time constant value for this tensor
+ template <typename T>
+ auto
+ setConstValue(T const &value) -> TensorBuilder_v8 & {
+ m_tensor.hasConstValue = true;
+ m_tensor.constValueBytes.resize(sizeof(T));
+ std::memcpy(m_tensor.constValueBytes.data(), &value, sizeof(T));
+ m_tensor.isByValue = true;
+ return *this;
+ }
+
+ auto
+ setVectorCountAndDimension(int64_t vectorCount_, int64_t vectorDimension_) -> TensorBuilder_v8 & {
+ m_tensor.vectorCount = vectorCount_;
+ m_tensor.vectorDimension = vectorDimension_;
+ return *this;
+ }
+
+ auto
+ setReorderType(cudnn_frontend::TensorReordering_t reordering_type) -> TensorBuilder_v8 & {
+ m_tensor.reorder_type = reordering_type;
+ return *this;
+ }
+
+ // To be deprecated. Please use setReorderType(cudnn_frontend::cudnnBackendTensorReordering_t).
+ auto
+ setReorderType(cudnnBackendTensorReordering_t reordering_type) -> TensorBuilder_v8 & {
+ detail::convert_from_cudnn_type(reordering_type, m_tensor.reorder_type);
+ return *this;
+ }
+
+ /** @} */
+
+ // TODO: Deprecate in v1.0
+ auto
+ setStrides(int64_t ndim, int64_t const *strides) -> TensorBuilder_v8 & {
+ return setStride(ndim, strides);
+ }
+
+ auto
+ setRaggedOffset(std::shared_ptr<Tensor_v8> &raggedOffset) -> TensorBuilder_v8 & {
+ m_tensor.raggedOffset = raggedOffset;
+ return *this;
+ }
+
+ auto
+ setRaggedOffsetMultiplier(int64_t const multiplier) -> TensorBuilder_v8 & {
+ m_tensor.raggedOffsetMultiplier = multiplier;
+ return *this;
+ }
+
+ // Clone parameters of another tensor. Make sure to still set the UID since UID of two tensors shouldn't be the
+ // same.
+ auto
+ cloneFrom(Tensor_v8 const &from, int64_t newID) -> TensorBuilder_v8 & {
+ m_tensor.data_type = from.data_type;
+ m_tensor.nDims = from.nDims;
+ m_tensor.id = newID;
+ std::copy(from.getDimArray(), from.getDimArray() + m_tensor.nDims, m_tensor.btensor_dimA);
+ std::copy(from.getStrideArray(), from.getStrideArray() + m_tensor.nDims, m_tensor.btensor_strA);
+ m_tensor.alignment = from.alignment;
+ m_tensor.isVirtual = from.isVirtual;
+ m_tensor.isByValue = from.isByValue;
+ m_tensor.vectorCount = from.vectorCount;
+ m_tensor.vectorDimension = from.vectorDimension;
+ m_tensor.reorder_type = from.reorder_type;
+ return *this;
+ }
+
+ //! constructs the Tensor_v8 by calling the cudnn API
+ //! Throws the appropriate error message
+ Tensor_v8 &&
+ build() {
+ // Sanity check if non-default fields have been set correctly.
+ if (m_tensor.alignment <= 0) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: Check and Set the CUDNN_ATTR_TENSOR_BYTE_ALIGNMENT field");
+ return std::move(m_tensor);
+ }
+ if (m_tensor.id < 0) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: Check and Set the CUDNN_ATTR_TENSOR_UNIQUE_ID as a valid value");
+ return std::move(m_tensor);
+ }
+ if (m_tensor.btensor_strA[0] < 0) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: Check and Set the CUDNN_ATTR_TENSOR_STRIDES Correctly");
+ return std::move(m_tensor);
+ }
+ if (m_tensor.btensor_dimA[0] <= 0) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: Check and Set the CUDNN_ATTR_TENSOR_DIMENSIONS Correctly");
+ return std::move(m_tensor);
+ }
+ if (m_tensor.pointer != nullptr) {
+ set_error_and_throw_exception(&m_tensor,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: Bad tensor created. The tensor already "
+ "seems to be pointing to something");
+ return std::move(m_tensor);
+ }
+
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_tensor.initialize_managed_backend_pointer(CUDNN_BACKEND_TENSOR_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor, status, "CUDNN_BACKEND_TENSOR_DESCRIPTOR: cudnnCreate Descriptor Failed");
+ return std::move(m_tensor);
+ }
+
+ // Once Created lets set the descriptor parameters.
+ cudnnDataType_t cudnn_data_type;
+ status = detail::convert_to_cudnn_type(m_tensor.data_type, cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor, status, "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_DATA_TYPE Failed");
+ return std::move(m_tensor);
+ }
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_DATA_TYPE,
+ CUDNN_TYPE_DATA_TYPE,
+ 1,
+ &cudnn_data_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor, status, "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_DATA_TYPE Failed");
+ return std::move(m_tensor);
+ }
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_DIMENSIONS,
+ CUDNN_TYPE_INT64,
+ m_tensor.nDims,
+ m_tensor.btensor_dimA);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor, status, "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_DIMENSIONS Failed");
+ return std::move(m_tensor);
+ }
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_STRIDES,
+ CUDNN_TYPE_INT64,
+ m_tensor.nDims,
+ m_tensor.btensor_strA);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor, status, "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_STRIDES Failed");
+ return std::move(m_tensor);
+ }
+ status = detail::set_attribute(
+ m_tensor.pointer->get_backend_descriptor(), CUDNN_ATTR_TENSOR_UNIQUE_ID, CUDNN_TYPE_INT64, 1, &m_tensor.id);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor, status, "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_UNIQUE_ID Failed");
+ return std::move(m_tensor);
+ }
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_BYTE_ALIGNMENT,
+ CUDNN_TYPE_INT64,
+ 1,
+ &m_tensor.alignment);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_BYTE_ALIGNMENT Failed");
+ return std::move(m_tensor);
+ }
+ if (m_tensor.isVirtual) {
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_IS_VIRTUAL,
+ CUDNN_TYPE_BOOLEAN,
+ 1,
+ &m_tensor.isVirtual);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_BYTE_ALIGNMENT Failed");
+ return std::move(m_tensor);
+ }
+ }
+ if (m_tensor.isByValue) {
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_IS_BY_VALUE,
+ CUDNN_TYPE_BOOLEAN,
+ 1,
+ &m_tensor.isByValue);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_IS_BY_VALUE Failed");
+ return std::move(m_tensor);
+ }
+ }
+
+ if (m_tensor.vectorCount > 1) {
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_VECTOR_COUNT,
+ CUDNN_TYPE_INT64,
+ 1,
+ &m_tensor.vectorCount);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_VECTOR_COUNT Failed");
+ return std::move(m_tensor);
+ }
+ }
+ if (m_tensor.vectorDimension >= 0) {
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_VECTORIZED_DIMENSION,
+ CUDNN_TYPE_INT64,
+ 1,
+ &m_tensor.vectorDimension);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_VECTORIZED_DIMENSION Failed");
+ return std::move(m_tensor);
+ }
+ }
+
+ // Set ragged offset descriptor
+#if (CUDNN_VERSION >= 8900)
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(8900,
+ m_tensor,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_TENSOR_RAGGED_OFFSET_DESC requires cudnn version 8.9");
+ if (m_tensor.raggedOffset != nullptr) {
+ std::vector<cudnnBackendDescriptor_t> backendRaggedOffset;
+ backendRaggedOffset.push_back(m_tensor.raggedOffset.get()->pointer->get_backend_descriptor());
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_RAGGED_OFFSET_DESC,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ static_cast<int64_t>(backendRaggedOffset.size()),
+ backendRaggedOffset.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_RAGGED_OFFSET_DESC Failed");
+ return std::move(m_tensor);
+ }
+ }
+#endif
+
+ // Set ragged offset multiplier
+ if (m_tensor.hasRaggedOffsetMultiplier()) {
+ [[maybe_unused]] auto ragged_offset_multiplier_cudnn_ver_error =
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_TENSOR_RAGGED_OFFSET_MULTIPLIER requires cudnn version 9.24.0";
+#if (CUDNN_VERSION >= 92400)
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(92400, m_tensor, ragged_offset_multiplier_cudnn_ver_error);
+ if (m_tensor.raggedOffset == nullptr) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: CUDNN_ATTR_TENSOR_RAGGED_OFFSET_MULTIPLIER requires "
+ "CUDNN_ATTR_TENSOR_RAGGED_OFFSET_DESC");
+ return std::move(m_tensor);
+ }
+ if (m_tensor.raggedOffsetMultiplier <= 0) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ CUDNN_STATUS_BAD_PARAM,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: CUDNN_ATTR_TENSOR_RAGGED_OFFSET_MULTIPLIER must be positive");
+ return std::move(m_tensor);
+ }
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_RAGGED_OFFSET_MULTIPLIER,
+ CUDNN_TYPE_INT64,
+ 1,
+ &m_tensor.raggedOffsetMultiplier);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_TENSOR_RAGGED_OFFSET_MULTIPLIER Failed");
+ return std::move(m_tensor);
+ }
+#else
+ set_error_and_throw_exception(
+ &m_tensor, CUDNN_STATUS_INVALID_VALUE, ragged_offset_multiplier_cudnn_ver_error);
+ return std::move(m_tensor);
+#endif // CUDNN_VERSION >= 92400
+ }
+
+ // Set the reorder_type
+ if (m_tensor.reorder_type != cudnn_frontend::TensorReordering_t::NONE) {
+ cudnnBackendTensorReordering_t cudnn_reordering_type;
+ status = detail::convert_to_cudnn_type(m_tensor.reorder_type, cudnn_reordering_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_REORDERING_MODE Failed");
+ return std::move(m_tensor);
+ }
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_REORDERING_MODE,
+ CUDNN_TYPE_TENSOR_REORDERING_MODE,
+ 1,
+ &m_tensor.reorder_type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_REORDERING_MODE Failed");
+ return std::move(m_tensor);
+ }
+ }
+
+ // Set compile-time constant value (if present); CUDNN_ATTR_TENSOR_CONSTANT_VALUE is cuDNN 9.22.0+
+#if (CUDNN_VERSION >= 92200)
+ if (m_tensor.hasConstValue) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(
+ 92200,
+ m_tensor,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute "
+ "CUDNN_ATTR_TENSOR_CONSTANT_VALUE requires cudnn version 9.22.0");
+ void *value_ptr = m_tensor.constValueBytes.data();
+ status = detail::set_attribute(m_tensor.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_TENSOR_CONSTANT_VALUE,
+ CUDNN_TYPE_VOID_PTR,
+ 1,
+ &value_ptr);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ status,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: SetAttribute CUDNN_ATTR_TENSOR_CONSTANT_VALUE Failed");
+ return std::move(m_tensor);
+ }
+ }
+#else
+ if (m_tensor.hasConstValue) {
+ set_error_and_throw_exception(
+ &m_tensor,
+ CUDNN_STATUS_INVALID_VALUE,
+ "CUDNN_BACKEND_TENSOR_DESCRIPTOR: CUDNN_ATTR_TENSOR_CONSTANT_VALUE requires cudnn version 9.22.0");
+ return std::move(m_tensor);
+ }
+#endif // CUDNN_VERSION >= 92200
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_tensor.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(&m_tensor, status, "CUDNN_BACKEND_TENSOR_DESCRIPTOR cudnnFinalize failed");
+ return std::move(m_tensor);
+ }
+ CUDNN_FE_LOG_LABEL_ENDL(m_tensor);
+ return std::move(m_tensor);
+ }
+
+ explicit TensorBuilder_v8() = default;
+ ~TensorBuilder_v8() = default;
+ TensorBuilder_v8(TensorBuilder_v8 &&) = delete;
+ TensorBuilder_v8(TensorBuilder_v8 const &) = delete;
+ TensorBuilder_v8 &
+ operator=(TensorBuilder_v8 const &) = delete;
+
+ private:
+ Tensor_v8 m_tensor; //! Tensor built by the TensorBuilder class.
+};
+
+using Tensor = Tensor_v8;
+using TensorBuilder = TensorBuilder_v8;
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_VariantPack.h b/deps/cudnn-frontend/include/cudnn_frontend_VariantPack.h
new file mode 100644
index 0000000..3b7ae8e
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_VariantPack.h
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <functional>
+#include <memory>
+#include <set>
+#include <sstream>
+#include <utility>
+
+#include "cudnn_frontend_utils.h"
+
+namespace cudnn_frontend {
+
+///
+/// VariantPack_v8 Class
+/// This class tells the Configuration of the Engine in terms of the knob
+/// choices
+/// Properties:
+/// - num knobs
+/// - Choice
+/// - Engine
+///
+/// Use VariantPackBuilder_v8 to build this class.
+/// Describe returns a string describing the tensor class
+///
+class VariantPack_v8 : public BackendDescriptor {
+ public:
+ friend class VariantPackBuilder_v8;
+ std::string
+ describe() const override {
+ std::stringstream ss;
+ ss << "CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR :" << " has " << num_ptrs << " data pointers";
+ return ss.str();
+ }
+
+ VariantPack_v8(VariantPack_v8 &&from) = default;
+ VariantPack_v8 &
+ operator=(VariantPack_v8 &&from) = default;
+
+ ~VariantPack_v8() = default;
+
+ private:
+ VariantPack_v8() = default;
+ VariantPack_v8(VariantPack_v8 const &) = delete;
+ VariantPack_v8 &
+ operator=(VariantPack_v8 const &) = delete;
+
+ void *workspace = nullptr;
+ std::vector<void *> data_pointers;
+ std::vector<int64_t> uid;
+ int64_t num_ptrs = -1;
+};
+
+///
+/// VariantPackBuilder_v8 Class
+/// Helper class used to build VariantPack_v8 class
+class VariantPackBuilder_v8 {
+ public:
+ /** @defgroup VariantPackBuilder_v8
+ * Set individual property of VariantPack_v8 class
+ * @{
+ */
+ //! Set dataPointers for the VariantPack_v8
+ auto
+ setDataPointers(int64_t num_ptr, void **ptrs) -> VariantPackBuilder_v8 & {
+ m_variant_pack.data_pointers.reserve(static_cast<size_t>(num_ptr));
+ std::copy(ptrs, ptrs + num_ptr, std::back_inserter(m_variant_pack.data_pointers));
+ m_variant_pack.num_ptrs = num_ptr;
+ return *this;
+ }
+ //! Set Uids for the VariantPack_v8
+ auto
+ setUids(int64_t num_uids, const int64_t *uid) -> VariantPackBuilder_v8 & {
+ return setUids(num_uids, const_cast<int64_t *>(uid));
+ }
+
+ auto
+ setUids(int64_t num_uids, int64_t *uid) -> VariantPackBuilder_v8 & {
+ m_variant_pack.uid.reserve(static_cast<size_t>(num_uids));
+ std::copy(uid, uid + num_uids, std::back_inserter(m_variant_pack.uid));
+ return *this;
+ }
+ //! Initialize a set of pairs containing uid and data pointer.
+ auto
+ setDataPointers(std::set<std::pair<uint64_t, void *>> const &data_pointers) -> VariantPackBuilder_v8 & {
+ m_variant_pack.num_ptrs = data_pointers.size();
+ m_variant_pack.uid.reserve(static_cast<size_t>(m_variant_pack.num_ptrs));
+ m_variant_pack.data_pointers.reserve(static_cast<size_t>(m_variant_pack.num_ptrs));
+ for (auto &data_pointer : data_pointers) {
+ m_variant_pack.uid.push_back(data_pointer.first);
+ m_variant_pack.data_pointers.push_back(data_pointer.second);
+ }
+ return *this;
+ }
+ //! Set Workspace
+ auto
+ setWorkspacePointer(void *ws) -> VariantPackBuilder_v8 & {
+ m_variant_pack.workspace = ws;
+ return *this;
+ }
+ /** @} */
+
+ //! constructs the Engine Config by calling the cudnn API
+ //! Throws the appropriate error message
+ VariantPack_v8 &&
+ build() {
+ // Create a descriptor. Memory allocation happens here.
+ auto status = m_variant_pack.initialize_managed_backend_pointer(CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_variant_pack, status, "CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR: cudnnCreate Failed");
+ return std::move(m_variant_pack);
+ }
+
+ status = detail::set_attribute(m_variant_pack.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_VARIANT_PACK_DATA_POINTERS,
+ CUDNN_TYPE_VOID_PTR,
+ m_variant_pack.num_ptrs,
+ m_variant_pack.data_pointers.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_variant_pack,
+ status,
+ "CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR: SetAttribute CUDNN_ATTR_VARIANT_PACK_DATA_POINTERS Failed");
+ return std::move(m_variant_pack);
+ }
+
+ status = detail::set_attribute(m_variant_pack.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_VARIANT_PACK_UNIQUE_IDS,
+ CUDNN_TYPE_INT64,
+ m_variant_pack.num_ptrs,
+ m_variant_pack.uid.data());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_variant_pack,
+ status,
+ "CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR: SetAttribute CUDNN_ATTR_VARIANT_PACK_UNIQUE_IDS Failed");
+ return std::move(m_variant_pack);
+ }
+
+ status = detail::set_attribute(m_variant_pack.pointer->get_backend_descriptor(),
+ CUDNN_ATTR_VARIANT_PACK_WORKSPACE,
+ CUDNN_TYPE_VOID_PTR,
+ 1,
+ &m_variant_pack.workspace);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_variant_pack,
+ status,
+ "CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR: SetAttribute CUDNN_ATTR_VARIANT_PACK_WORKSPACE Failed");
+ return std::move(m_variant_pack);
+ }
+
+ // Finalizing the descriptor
+ status = detail::finalize(m_variant_pack.pointer->get_backend_descriptor());
+ if (status != CUDNN_STATUS_SUCCESS) {
+ set_error_and_throw_exception(
+ &m_variant_pack, status, "CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR: cudnnFinalize Failed");
+ return std::move(m_variant_pack);
+ }
+ CUDNN_FE_LOG_LABEL_ENDL(m_variant_pack);
+ return std::move(m_variant_pack);
+ }
+
+ explicit VariantPackBuilder_v8() = default;
+ ~VariantPackBuilder_v8() = default;
+ VariantPackBuilder_v8(VariantPackBuilder_v8 &&) = delete;
+ VariantPackBuilder_v8(VariantPackBuilder_v8 const &) = delete;
+ VariantPackBuilder_v8 &
+ operator=(VariantPackBuilder_v8 const &) = delete;
+
+ private:
+ VariantPack_v8 m_variant_pack;
+};
+
+using VariantPack = VariantPack_v8;
+using VariantPackBuilder = VariantPackBuilder_v8;
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_find_plan.h b/deps/cudnn-frontend/include/cudnn_frontend_find_plan.h
new file mode 100644
index 0000000..b907903
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_find_plan.h
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <iomanip>
+#include <set>
+#include "cudnn_frontend_EngineConfigGenerator.h"
+
+namespace cudnn_frontend {
+
+/// Sorts the execution plans by their run time.
+/// The run time of plan may not trivial and hence we
+/// run it multiple times till we get a stable value.
+/// We have an additional dry-run which helps stabilize the
+/// time further.
+template <CudnnFindSamplingTechnique samplingTechnique>
+auto
+time_sorted_plan(cudnnHandle_t handle,
+ executionPlans_t plans,
+ VariantPack const &variantPack,
+ uint64_t max_plans_to_evaluate = 1000) -> executionPlans_t {
+ executionPlans_t time_sorted_plans;
+
+ auto plan_cmp = [](const ExecutionPlan &a, const ExecutionPlan &b) {
+ return a.getExecutionTime() < b.getExecutionTime();
+ };
+ std::set<std::reference_wrapper<ExecutionPlan>, decltype(plan_cmp)> timed_execution_plans(plan_cmp);
+
+ const int maxIterCount = (samplingTechnique == CudnnFindSamplingTechnique::CUDNN_FIND_SAMPLE_ONCE) ? 1
+ : (samplingTechnique == CudnnFindSamplingTechnique::CUDNN_FIND_SAMPLE_MEDIAN_OF_THREE)
+ ? 3
+ : 100;
+ const float threshhold = 0.95f;
+ uint64_t successful_plan_count = 0;
+ cudaEvent_t start, stop;
+ detail::cuda_event_create(&start);
+ detail::cuda_event_create(&stop);
+ detail::cuda_device_synchronize();
+
+ cudaStream_t stream = nullptr;
+ detail::get_stream(handle, &stream);
+
+ for (auto &plan : plans) {
+ float time_ms = 0.0f;
+ float final_time_ms = 0.0f;
+ float min_time_ms = std::numeric_limits<float>::max();
+
+ // Warm-up run
+ auto warmup_status = detail::execute(handle, plan.get_raw_desc(), variantPack.get_raw_desc());
+ if (warmup_status != CUDNN_STATUS_SUCCESS) {
+ CUDNN_FE_LOG_LABEL_ENDL("Plan " << plan.getTag() << " failed with " << to_string(warmup_status));
+ continue;
+ }
+ successful_plan_count++;
+ detail::cuda_device_synchronize();
+
+ float time_run_ms[3] = {0.0f, 0.0f, 0.0f};
+ for (int i = 0; i < maxIterCount; i++) {
+ detail::cuda_event_record(start, stream);
+
+ detail::execute(handle, plan.get_raw_desc(), variantPack.get_raw_desc());
+
+ detail::cuda_event_record(stop, stream);
+ detail::cuda_event_synchronize(stop);
+ detail::cuda_event_elapsed_time(&time_ms, start, stop);
+
+ if constexpr (samplingTechnique == CudnnFindSamplingTechnique::CUDNN_FIND_SAMPLE_TILL_STABLE) {
+ final_time_ms = std::min(min_time_ms, time_ms);
+ if (time_ms / min_time_ms < threshhold) {
+ min_time_ms = final_time_ms;
+ } else {
+ break;
+ }
+ } else if constexpr (samplingTechnique == CudnnFindSamplingTechnique::CUDNN_FIND_SAMPLE_MEDIAN_OF_THREE) {
+ time_run_ms[i] = time_ms;
+ if (i == maxIterCount - 1) {
+ auto min_of_first_two = std::min(time_run_ms[0], time_run_ms[1]);
+ auto max_of_first_two = std::max(time_run_ms[0], time_run_ms[1]);
+ final_time_ms = std::max(min_of_first_two, std::min(max_of_first_two, time_run_ms[2]));
+ }
+ } else {
+ final_time_ms = time_ms;
+ }
+ }
+ CUDNN_FE_LOG_LABEL_ENDL("Plan " << plan.getTag() << " took " << std::setw(10) << final_time_ms);
+ plan.setExecutionTime(final_time_ms);
+ timed_execution_plans.insert(plan);
+ if (successful_plan_count >= max_plans_to_evaluate) {
+ CUDNN_FE_LOG_LABEL_ENDL("Successfully profiled " << max_plans_to_evaluate << "plans.");
+ break;
+ }
+ }
+
+ for (ExecutionPlan &plan : timed_execution_plans) {
+ time_sorted_plans.emplace_back(std::move(plan));
+ }
+
+ detail::cuda_event_destroy(start);
+ detail::cuda_event_destroy(stop);
+
+ CUDNN_FE_LOG_LABEL_ENDL("Auto-tuning returns " << time_sorted_plans.size() << " plans.");
+
+ return time_sorted_plans;
+}
+
+template <CudnnFindSamplingTechnique samplingTechnique>
+auto
+EngineConfigGenerator::cudnnFindPlan(cudnnHandle_t handle,
+ cudnn_frontend::OperationGraph &opGraph,
+ cudnn_frontend::VariantPack const &variantPack) -> executionPlans_t {
+ /// Creating a set of execution plans that are supported.
+ executionPlans_t plans = cudnnGetPlan(handle, opGraph);
+ return time_sorted_plan<samplingTechnique>(handle, std::move(plans), variantPack);
+}
+
+template <CudnnFindSamplingTechnique samplingTechnique>
+auto
+EngineConfigGenerator::cudnnFindPlan(cudnnHandle_t handle,
+ cudnn_frontend::OperationGraph &opGraph,
+ cudnn_frontend::VariantPack const &variantPack,
+ Predicate pred) -> executionPlans_t {
+ /// Creating a set of execution plans that are supported.
+ executionPlans_t plans = cudnnGetPlan(handle, opGraph, pred);
+ return time_sorted_plan<samplingTechnique>(handle, std::move(plans), variantPack);
+}
+
+template <CudnnFindSamplingTechnique samplingTechnique>
+auto
+EngineConfigGenerator::cudnnFindPlanAndCache(cudnnHandle_t handle,
+ cudnn_frontend::OperationGraph &opGraph,
+ cudnn_frontend::VariantPack const &variantPack,
+ cudnn_frontend::ExecutionPlanCache &cache,
+ Predicate pred) -> cudnn_frontend::ExecutionPlan {
+ /// Creating a set of execution plans that are supported.
+ auto sorted_plans = cudnnFindPlan<samplingTechnique>(handle, opGraph, variantPack, pred);
+ /// Check if the fastest plan is stable enough to be added to the plan cache
+ if (cache.is_fastest_plan_stable(opGraph, sorted_plans.front().getTag())) {
+ cache.add_plan_to_cache(opGraph, sorted_plans.front());
+ }
+ return sorted_plans.front();
+}
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_get_plan.h b/deps/cudnn-frontend/include/cudnn_frontend_get_plan.h
new file mode 100644
index 0000000..1cb4c41
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_get_plan.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "cudnn_frontend_EngineConfigGenerator.h"
+
+namespace cudnn_frontend {
+
+auto inline EngineConfigGenerator::cudnnGetPlan(cudnnHandle_t handle, OperationGraph& opGraph, size_t max_plans)
+ -> executionPlans_t {
+ // Creating a set of execution plans that are supported.
+ executionPlans_t plans;
+ for (auto& engine_config : generate_engine_config(opGraph)) {
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+ try {
+#endif
+ plans.push_back(
+ ExecutionPlanBuilder().setHandle(handle).setEngineConfig(engine_config, opGraph.getTag()).build());
+ CUDNN_FE_LOG_LABEL_ENDL("Added plan " << plans.back().getTag() << " "
+ << to_string(plans.back().get_status()));
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+ } catch (cudnnException& e) {
+ CUDNN_FRONTEND_UNUSED(e);
+ continue;
+ }
+#endif
+ if (plans.size() >= max_plans) {
+ break;
+ }
+ }
+ return plans;
+}
+
+auto inline EngineConfigGenerator::cudnnGetPlan(cudnnHandle_t handle,
+ OperationGraph& opGraph,
+ Predicate pred,
+ size_t max_plans) -> executionPlans_t {
+ // Creating a set of execution plans that are supported.
+ executionPlans_t plans = cudnnGetPlan(handle, opGraph, max_plans);
+ return filter(pred, plans);
+}
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_shim.h b/deps/cudnn-frontend/include/cudnn_frontend_shim.h
new file mode 100644
index 0000000..3bdbb0b
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_shim.h
@@ -0,0 +1,768 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <cstdlib>
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+#ifdef _WIN32
+#define NOMINMAX
+#include <windows.h>
+#define dlerror() static_cast<UINT_PTR>(GetLastError())
+#define dlopen(x, y) LoadLibrary(x)
+#define dlsym(x, y) GetProcAddress(x, y)
+#define dlclose(x) FreeLibrary(x)
+#else
+#include <dlfcn.h>
+#define HMODULE void *
+#endif
+#include <mutex>
+#include <stdexcept>
+#include <string>
+#include <cstdio>
+#endif
+
+namespace cudnn_frontend {
+
+// Portable environment-variable accessor. Wraps std::getenv and locally silences MSVC's C4996
+// ("getenv is unsafe") warning, which is treated as an error under /WX. Safe here because the
+// returned value is only read. Defined in this low-level header so every layer (including
+// Logging) can share a single definition without inverting include dependencies.
+inline const char *
+get_environment(const char *name) {
+#ifdef _WIN32
+#pragma warning(push)
+#pragma warning(disable : 4996)
+#endif
+ return std::getenv(name);
+#ifdef _WIN32
+#pragma warning(pop)
+#endif
+}
+
+// cudnn package initialization set this global handle
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+#ifdef _WIN32
+extern HMODULE cudnn_dlhandle;
+#else
+extern void *cudnn_dlhandle;
+#endif
+#endif
+
+namespace detail {
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+
+inline auto
+get_symbol(const char *function_name) {
+ auto ret = dlsym(cudnn_dlhandle, function_name);
+ return ret;
+}
+
+enum class CudaLibrary { CUDART, CUDA };
+
+inline HMODULE
+load_cuda_so() {
+ // Clear any existing error
+ dlerror();
+
+ // Attempt to open the cuda library
+ HMODULE handle = dlopen("libcuda.so.1", RTLD_NOW);
+ const char *error = reinterpret_cast<const char *>(dlerror());
+ if (!handle || error) {
+ // If opening the library fails, throw an exception with the error message
+ throw std::runtime_error("Unable to dlopen libcuda.so.1 : " + std::string(error ? error : "Unknown error"));
+ }
+
+ return handle;
+}
+
+inline HMODULE
+load_cudart_so() {
+ // Clear any existing error
+ dlerror();
+
+ // Allow the user to override the libcudart selection via an environment variable.
+ // This is useful in environments (e.g. containers such as GKE with the TCPXO NCCL
+ // plugin) where multiple major versions of libcudart are present in the library
+ // search path. In such cases the automatic detection below warns about the ambiguity
+ // (see below) and falls back to the first match. Setting CUDNN_FRONTEND_CUDART_LIB_NAME
+ // to the desired library name (or path), e.g. "libcudart.so.13", bypasses the detection
+ // and loads exactly that library.
+ const char *user_lib = get_environment("CUDNN_FRONTEND_CUDART_LIB_NAME");
+ if (user_lib) {
+ if (user_lib[0] != '\0') {
+ HMODULE handle = dlopen(user_lib, RTLD_NOW);
+ const char *error = reinterpret_cast<const char *>(dlerror());
+ if (!handle || error) {
+ throw std::runtime_error(
+ "Unable to load libcudart library specified by CUDNN_FRONTEND_CUDART_LIB_NAME (" +
+ std::string(user_lib) + "): " + std::string(error ? error : "Unknown error"));
+ }
+ return handle;
+ }
+ }
+
+ // List of potential libcudart libraries (Adding major version to support python package)
+ constexpr const char *libs[] = {"libcudart.so.12", "libcudart.so.13"};
+ constexpr size_t num_libs = sizeof(libs) / sizeof(libs[0]);
+
+ HMODULE lib_handle = nullptr;
+ int loaded_index = -1;
+
+ for (size_t i = 0; i < num_libs; ++i) {
+ HMODULE handle = dlopen(libs[i], RTLD_NOW);
+ const char *error = reinterpret_cast<const char *>(dlerror());
+
+ if (handle && !error) {
+ if (lib_handle) {
+ // Already loaded one -> multiple found. This is not fatal: warn on stderr and keep
+ // the first one found. Set CUDNN_FRONTEND_CUDART_LIB_NAME to select one explicitly.
+ dlclose(handle);
+ std::fprintf(stderr,
+ "cuDNN Frontend warning: Multiple libcudart libraries found: %s and %s. "
+ "Using %s. Set CUDNN_FRONTEND_CUDART_LIB_NAME to select one explicitly.\n",
+ libs[loaded_index],
+ libs[i],
+ libs[loaded_index]);
+ } else {
+ lib_handle = handle;
+ loaded_index = static_cast<int>(i);
+ }
+ }
+ }
+
+ // If opening the library fails, throw an exception with the error message
+ if (!lib_handle) {
+ throw std::runtime_error("Unable to load any libcudart.so.* library.");
+ }
+
+ return lib_handle;
+}
+
+inline void *
+get_cuda_symbol(CudaLibrary library, const char *function_name) {
+ // Static mutex to ensure thread-safety
+ (void)function_name;
+ static std::mutex cuda_lib_mutex;
+ // Static map to store handles for different libraries
+ static std::unordered_map<CudaLibrary, HMODULE> dl_handles;
+
+ // Lock the mutex to ensure thread-safe access
+ std::lock_guard<std::mutex> lock(cuda_lib_mutex);
+
+ // If the library hasn't been opened yet, open it and store the handle to future use
+ if (dl_handles.find(library) == dl_handles.end()) {
+ dl_handles[library] = (library == CudaLibrary::CUDART) ? load_cudart_so() : load_cuda_so();
+ }
+
+ // Clear any existing error before calling dlsym
+ dlerror();
+
+ // Try to find the symbol (function) in the library
+ void *symbol = dlsym(dl_handles[library], function_name);
+ const char *error = reinterpret_cast<const char *>(dlerror());
+ if (!symbol || error) {
+ // If the symbol is not found, throw an exception with details
+ throw std::runtime_error("Unable to find symbol " + std::string(function_name) + ": " +
+ std::string(error ? error : "Unknown error"));
+ }
+
+ // Return the pointer to the function
+ return symbol;
+}
+
+#endif
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+#define NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(MINIMUM_VERSION, DESCRIPTOR, MESSAGE) \
+ if (MINIMUM_VERSION > detail::get_backend_version()) { \
+ set_error_and_throw_exception(&DESCRIPTOR, CUDNN_STATUS_INVALID_VALUE, MESSAGE); \
+ return std::move(DESCRIPTOR); \
+ }
+#else
+#define NV_CUDNN_FE_DYNAMIC_CHECK_BACKEND_DESCRIPTOR(MINIMUM_VERSION, DESCRIPTOR, MESSAGE)
+#endif
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+#define NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(MINIMUM_VERSION, STATUS) \
+ if (MINIMUM_VERSION > detail::get_backend_version()) { \
+ return STATUS; \
+ }
+#else
+#define NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(MINIMUM_VERSION, STATUS)
+#endif
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+#define NV_FE_CALL_TO_BACKEND(function_name, backend_symbol, ...) \
+ static void *fptr = get_symbol(#backend_symbol); \
+ if (fptr == nullptr) { \
+ throw std::runtime_error("Unable to find symbol " #backend_symbol); \
+ } \
+ return reinterpret_cast<decltype(function_name) *>(fptr)(__VA_ARGS__);
+#else
+#define NV_FE_CALL_TO_BACKEND(function_name, backend_symbol, ...) return backend_symbol(__VA_ARGS__);
+#endif
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+
+#define NV_FE_CALL_TO_CUDA(function_name, cuda_symbol, ...) \
+ return reinterpret_cast<decltype(function_name) *>(get_cuda_symbol(CudaLibrary::CUDART, #cuda_symbol))(__VA_ARGS__);
+#define NV_FE_CALL_TO_CU(function_name, cuda_symbol, ...) \
+ return reinterpret_cast<decltype(function_name) *>(get_cuda_symbol(CudaLibrary::CUDA, #cuda_symbol))(__VA_ARGS__);
+
+#else
+
+#define NV_FE_CALL_TO_CUDA(function_name, cuda_symbol, ...) return cuda_symbol(__VA_ARGS__);
+#define NV_FE_CALL_TO_CU(function_name, cuda_symbol, ...) return cuda_symbol(__VA_ARGS__);
+
+#endif
+
+inline cudaError_t
+cuda_graph_create(cudaGraph_t *pGraph, unsigned int flags) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_create, cudaGraphCreate, pGraph, flags);
+}
+
+inline cudaError_t
+cuda_graph_get_nodes(cudaGraph_t hGraph, cudaGraphNode_t *nodes, size_t *numNodes) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_get_nodes, cudaGraphGetNodes, hGraph, nodes, numNodes);
+}
+
+inline cudaError_t
+cuda_graph_add_child_graph_node(cudaGraphNode_t *pGraphNode,
+ cudaGraph_t graph,
+ const cudaGraphNode_t *pDependencies,
+ size_t numDependencies,
+ cudaGraph_t childGraph) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_add_child_graph_node,
+ cudaGraphAddChildGraphNode,
+ pGraphNode,
+ graph,
+ pDependencies,
+ numDependencies,
+ childGraph);
+}
+
+inline cudaError_t
+cuda_graph_add_memcpy_node_1D(cudaGraphNode_t *pGraphNode,
+ cudaGraph_t graph,
+ const cudaGraphNode_t *pDependencies,
+ size_t numDependencies,
+ void *dst,
+ const void *src,
+ size_t count,
+ cudaMemcpyKind kind) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_add_memcpy_node_1D,
+ cudaGraphAddMemcpyNode1D,
+ pGraphNode,
+ graph,
+ pDependencies,
+ numDependencies,
+ dst,
+ src,
+ count,
+ kind);
+}
+
+inline cudaError_t
+cuda_graph_add_memset_node(cudaGraphNode_t *pGraphNode,
+ cudaGraph_t graph,
+ const cudaGraphNode_t *pDependencies,
+ size_t numDependencies,
+ const cudaMemsetParams *pMemsetParams) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_add_memset_node,
+ cudaGraphAddMemsetNode,
+ pGraphNode,
+ graph,
+ pDependencies,
+ numDependencies,
+ pMemsetParams);
+}
+
+inline cudaError_t
+cuda_graph_get_root_nodes(cudaGraph_t hGraph, cudaGraphNode_t *phNodes, size_t *pNumNodes) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_get_root_nodes, cudaGraphGetRootNodes, hGraph, phNodes, pNumNodes);
+}
+
+inline cudaError_t
+cuda_graph_child_graph_node_get_graph(cudaGraphNode_t hNode, cudaGraph_t *phGraph) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_child_graph_node_get_graph, cudaGraphChildGraphNodeGetGraph, hNode, phGraph);
+}
+
+// 4-parameter shim for cudaGraphNodeGetDependentNodes.
+// The underlying CUDA feature was introduced in CUDA 12.3, but
+// for simplicity we support this in 13.0+ only.
+#if (CUDART_VERSION >= 13000)
+inline cudaError_t
+cuda_graph_node_get_dependent_nodes_v2(cudaGraphNode_t node,
+ cudaGraphNode_t *pDependentNodes,
+ cudaGraphEdgeData *edgeData,
+ size_t *pNumDependentNodes) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_node_get_dependent_nodes_v2,
+ cudaGraphNodeGetDependentNodes,
+ node,
+ pDependentNodes,
+ edgeData,
+ pNumDependentNodes);
+}
+#endif
+
+// 3-parameter shim for cudaGraphNodeGetDependentNodes.
+inline cudaError_t
+cuda_graph_node_get_dependent_nodes(cudaGraphNode_t node,
+ cudaGraphNode_t *pDependentNodes,
+ size_t *pNumDependentNodes) {
+#if (CUDART_VERSION >= 13000)
+ // The 3-parameter version of cudaGraphNodeGetDependentNodes was removed in CUDA 13.0,
+ // so call the other shim.
+ return cuda_graph_node_get_dependent_nodes_v2(node, pDependentNodes, /*edgeData=*/nullptr, pNumDependentNodes);
+#else
+ NV_FE_CALL_TO_CUDA(
+ cuda_graph_node_get_dependent_nodes, cudaGraphNodeGetDependentNodes, node, pDependentNodes, pNumDependentNodes);
+#endif
+}
+
+inline cudaError_t
+cuda_graph_add_memcpy_node_set_params_1D(cudaGraphNode_t node,
+ void *dst,
+ const void *src,
+ size_t count,
+ cudaMemcpyKind kind) {
+ NV_FE_CALL_TO_CUDA(
+ cuda_graph_add_memcpy_node_set_params_1D, cudaGraphMemcpyNodeSetParams1D, node, dst, src, count, kind);
+}
+
+inline cudaError_t
+cuda_graph_add_memset_node_set_params(cudaGraphNode_t node, const cudaMemsetParams *pMemsetParams) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_add_memset_node_set_params, cudaGraphMemsetNodeSetParams, node, pMemsetParams);
+}
+
+inline cudaError_t
+cuda_graph_begin_capture(cudaStream_t stream, cudaStreamCaptureMode mode) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_begin_capture, cudaStreamBeginCapture, stream, mode);
+}
+
+inline cudaError_t
+cuda_stream_is_capturing(cudaStream_t stream, cudaStreamCaptureStatus *capture_status) {
+ NV_FE_CALL_TO_CUDA(cuda_stream_is_capturing, cudaStreamIsCapturing, stream, capture_status);
+}
+
+inline cudaError_t
+cuda_stream_create(cudaStream_t *stream) {
+ NV_FE_CALL_TO_CUDA(cuda_stream_create, cudaStreamCreate, stream);
+}
+
+inline cudaError_t
+cuda_stream_destroy(cudaStream_t stream) {
+ NV_FE_CALL_TO_CUDA(cuda_stream_destroy, cudaStreamDestroy, stream);
+}
+
+inline cudaError_t
+cuda_graph_end_capture(cudaStream_t stream, cudaGraph_t *graph) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_end_capture, cudaStreamEndCapture, stream, graph);
+}
+
+inline cudaError_t
+cuda_graph_destroy(cudaGraph_t graph) {
+ NV_FE_CALL_TO_CUDA(cuda_graph_destroy, cudaGraphDestroy, graph);
+}
+
+inline cudaError_t
+cuda_event_create(cudaEvent_t *event) {
+ NV_FE_CALL_TO_CUDA(cuda_event_create, cudaEventCreate, event);
+}
+
+inline cudaError_t
+cuda_event_destroy(cudaEvent_t event) {
+ NV_FE_CALL_TO_CUDA(cuda_event_destroy, cudaEventDestroy, event);
+}
+
+inline cudaError_t
+cuda_event_record(cudaEvent_t event, cudaStream_t stream) {
+ NV_FE_CALL_TO_CUDA(cuda_event_record, cudaEventRecord, event, stream);
+}
+
+inline cudaError_t
+cuda_event_synchronize(cudaEvent_t event) {
+ NV_FE_CALL_TO_CUDA(cuda_event_synchronize, cudaEventSynchronize, event);
+}
+
+inline cudaError_t
+cuda_event_elapsed_time(float *ms, cudaEvent_t start, cudaEvent_t end) {
+ NV_FE_CALL_TO_CUDA(cuda_event_elapsed_time, cudaEventElapsedTime, ms, start, end);
+}
+
+inline cudaError_t
+cuda_mem_cpy_async(void *dst, const void *src, size_t count, cudaMemcpyKind kind, cudaStream_t stream) {
+ NV_FE_CALL_TO_CUDA(cuda_mem_cpy_async, cudaMemcpyAsync, dst, src, count, kind, stream);
+}
+
+inline cudaError_t
+cuda_mem_set_async(void *devPtr, int value, size_t count, cudaStream_t stream) {
+ NV_FE_CALL_TO_CUDA(cuda_mem_set_async, cudaMemsetAsync, devPtr, value, count, stream);
+}
+
+inline cudaError_t
+cuda_get_device_properties(cudaDeviceProp *prop, int device) {
+ NV_FE_CALL_TO_CUDA(cuda_get_device_properties, cudaGetDeviceProperties, prop, device);
+}
+
+inline cudaError_t
+cuda_get_device(int *device) {
+ NV_FE_CALL_TO_CUDA(cuda_get_device, cudaGetDevice, device);
+}
+
+inline cudaError_t
+cuda_pointer_get_attributes(cudaPointerAttributes *attributes, const void *ptr) {
+ NV_FE_CALL_TO_CUDA(cuda_pointer_get_attributes, cudaPointerGetAttributes, attributes, ptr);
+}
+
+inline const char *
+cuda_get_error_string(cudaError_t error) {
+ NV_FE_CALL_TO_CUDA(cuda_get_error_string, cudaGetErrorString, error);
+}
+
+inline cudaError_t
+cuda_device_synchronize() {
+ NV_FE_CALL_TO_CUDA(cuda_device_synchronize, cudaDeviceSynchronize);
+}
+
+inline cudaError_t
+cuda_stream_synchronize(cudaStream_t stream) {
+ NV_FE_CALL_TO_CUDA(cuda_stream_synchronize, cudaStreamSynchronize, stream);
+}
+
+inline cudaError_t
+cuda_malloc(void **ptr, size_t sz) {
+ NV_FE_CALL_TO_CUDA(cuda_malloc, cudaMalloc, ptr, sz);
+}
+
+inline cudaError_t
+cuda_free(void *ptr) {
+ NV_FE_CALL_TO_CUDA(cuda_free, cudaFree, ptr);
+}
+
+inline cudnnStatus_t
+create_handle(cudnnHandle_t *handle) {
+ NV_FE_CALL_TO_BACKEND(create_handle, cudnnCreate, handle);
+}
+
+inline cudnnStatus_t
+destroy_handle(cudnnHandle_t handle) {
+ NV_FE_CALL_TO_BACKEND(destroy_handle, cudnnDestroy, handle);
+}
+
+#if CUDNN_VERSION >= 92200
+inline cudnnStatus_t
+causal_conv1d_forward(cudaStream_t stream,
+ const void *x,
+ const void *weight,
+ const void *bias,
+ void *y,
+ int batch,
+ int dim,
+ int seq_len,
+ int kernel_size,
+ cudnnDataType_t data_type,
+ cudnnCausalConv1dActivation_t activation) {
+ NV_FE_CALL_TO_BACKEND(causal_conv1d_forward,
+ cudnnCausalConv1dForward,
+ stream,
+ x,
+ weight,
+ bias,
+ y,
+ batch,
+ dim,
+ seq_len,
+ kernel_size,
+ data_type,
+ activation);
+}
+
+inline cudnnStatus_t
+causal_conv1d_backward(cudaStream_t stream,
+ const void *x,
+ const void *weight,
+ const void *bias,
+ const void *dy,
+ void *dx,
+ void *dweight,
+ void *dbias,
+ int batch,
+ int dim,
+ int seq_len,
+ int kernel_size,
+ cudnnDataType_t data_type,
+ cudnnDataType_t dw_data_type,
+ cudnnCausalConv1dActivation_t activation) {
+ NV_FE_CALL_TO_BACKEND(causal_conv1d_backward,
+ cudnnCausalConv1dBackward,
+ stream,
+ x,
+ weight,
+ bias,
+ dy,
+ dx,
+ dweight,
+ dbias,
+ batch,
+ dim,
+ seq_len,
+ kernel_size,
+ data_type,
+ dw_data_type,
+ activation);
+}
+#endif
+
+inline size_t
+get_backend_version(void) {
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ static void *fptr = get_symbol("cudnnGetVersion");
+ if (fptr == nullptr) {
+ throw std::runtime_error("Unable to find symbol cudnnGetVersion");
+ }
+ return reinterpret_cast<decltype(get_backend_version) *>(fptr)();
+#else
+ return cudnnGetVersion();
+#endif
+}
+
+inline constexpr size_t
+get_compiled_version(void) {
+ return CUDNN_VERSION;
+}
+
+inline std::string
+convert_version_to_str(size_t const version) {
+ // The multiplier for major version pre-v9 and post-v9 are different.
+ size_t major = version / 10000;
+ size_t minor = (version / 100) % 100;
+ if (major == 0) {
+ major = version / 1000;
+ minor = (version / 100) % 10;
+ }
+ auto patch = version % 100;
+
+ return std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(patch);
+}
+
+inline std::string
+get_backend_version_string() {
+ return convert_version_to_str(get_backend_version());
+}
+
+inline cudnnStatus_t
+create_descriptor(cudnnBackendDescriptorType_t descriptorType, cudnnBackendDescriptor_t *descriptor) {
+ NV_FE_CALL_TO_BACKEND(create_descriptor, cudnnBackendCreateDescriptor, descriptorType, descriptor);
+}
+
+inline cudnnStatus_t
+destroy_descriptor(cudnnBackendDescriptor_t descriptor) {
+ NV_FE_CALL_TO_BACKEND(destroy_descriptor, cudnnBackendDestroyDescriptor, descriptor);
+}
+
+inline cudnnStatus_t
+set_attribute(cudnnBackendDescriptor_t descriptor,
+ cudnnBackendAttributeName_t attributeName,
+ cudnnBackendAttributeType_t attributeType,
+ int64_t elementCount,
+ const void *arrayOfElements) {
+ NV_FE_CALL_TO_BACKEND(set_attribute,
+ cudnnBackendSetAttribute,
+ descriptor,
+ attributeName,
+ attributeType,
+ elementCount,
+ arrayOfElements);
+}
+
+inline cudnnStatus_t
+get_attribute(cudnnBackendDescriptor_t const descriptor,
+ cudnnBackendAttributeName_t attributeName,
+ cudnnBackendAttributeType_t attributeType,
+ int64_t requestedElementCount,
+ int64_t *elementCount,
+ void *arrayOfElements) {
+ NV_FE_CALL_TO_BACKEND(get_attribute,
+ cudnnBackendGetAttribute,
+ descriptor,
+ attributeName,
+ attributeType,
+ requestedElementCount,
+ elementCount,
+ arrayOfElements)
+}
+
+inline cudnnStatus_t
+finalize(cudnnBackendDescriptor_t descriptor) {
+ NV_FE_CALL_TO_BACKEND(finalize, cudnnBackendFinalize, descriptor);
+}
+
+inline cudnnStatus_t
+execute(cudnnHandle_t handle, cudnnBackendDescriptor_t executionPlan, cudnnBackendDescriptor_t variantPack) {
+ NV_FE_CALL_TO_BACKEND(execute, cudnnBackendExecute, handle, executionPlan, variantPack);
+}
+
+inline cudnnStatus_t
+get_execution_plan_workspace_size(cudnnHandle_t handle,
+ cudnnBackendDescriptor_t executionPlan,
+ cudnnBackendDescriptor_t variantPack,
+ size_t *workspaceSizeInBytes) {
+#if CUDNN_VERSION >= 92300
+ NV_FE_CALL_TO_BACKEND(get_execution_plan_workspace_size,
+ cudnnGetExecutionPlanWorkspaceSize,
+ handle,
+ executionPlan,
+ variantPack,
+ workspaceSizeInBytes);
+#else
+ (void)handle;
+ (void)executionPlan;
+ (void)variantPack;
+ (void)workspaceSizeInBytes;
+ return CUDNN_STATUS_VERSION_MISMATCH;
+#endif
+}
+
+inline cudnnStatus_t
+populate_cuda_graph(cudnnHandle_t handle,
+ cudnnBackendDescriptor_t executionPlan,
+ cudnnBackendDescriptor_t variantPack,
+ cudaGraph_t cuda_graph) {
+#if CUDNN_VERSION >= 90500
+ NV_FE_CALL_TO_BACKEND(
+ populate_cuda_graph, cudnnBackendPopulateCudaGraph, handle, executionPlan, variantPack, cuda_graph);
+#else
+ (void)handle;
+ (void)executionPlan;
+ (void)variantPack;
+ (void)cuda_graph;
+ return CUDNN_STATUS_VERSION_MISMATCH;
+#endif
+}
+
+inline cudnnStatus_t
+update_cuda_graph(cudnnHandle_t handle,
+ cudnnBackendDescriptor_t executionPlan,
+ cudnnBackendDescriptor_t variantPack,
+ cudaGraph_t cuda_graph) {
+#if CUDNN_VERSION >= 90500
+ NV_FE_CALL_TO_BACKEND(
+ update_cuda_graph, cudnnBackendUpdateCudaGraph, handle, executionPlan, variantPack, cuda_graph);
+#else
+ (void)handle;
+ (void)executionPlan;
+ (void)variantPack;
+ (void)cuda_graph;
+ return CUDNN_STATUS_VERSION_MISMATCH;
+#endif
+}
+
+inline const char *
+get_error_string(cudnnStatus_t status) {
+ NV_FE_CALL_TO_BACKEND(get_error_string, cudnnGetErrorString, status);
+}
+
+inline void
+get_last_error_string(char *message, size_t size) {
+ if (detail::get_backend_version() >= 90000 && detail::get_compiled_version() >= 90000) {
+#if CUDNN_VERSION >= 90000
+ NV_FE_CALL_TO_BACKEND(get_last_error_string, cudnnGetLastErrorString, message, size);
+#endif
+ } else {
+ std::string default_message = "Can't retrieve backend error messages for CUDNN version < 9.0";
+ // strncpy(message, default_message.c_str(), size - 1);
+ message[size - 1] = '\0'; // Ensure null terminator at the end of the string
+ }
+}
+
+inline std::string
+get_last_error_string_() {
+ const size_t size = 65535;
+
+ std::string message;
+
+ message.resize(size);
+
+ get_last_error_string(message.data(), size);
+
+ message.resize(std::strlen(message.c_str()));
+
+ return message;
+}
+
+inline cudnnStatus_t
+set_stream(cudnnHandle_t handle, cudaStream_t stream) {
+ NV_FE_CALL_TO_BACKEND(set_stream, cudnnSetStream, handle, stream);
+}
+
+inline cudnnStatus_t
+get_stream(cudnnHandle_t handle, cudaStream_t *stream) {
+ NV_FE_CALL_TO_BACKEND(get_stream, cudnnGetStream, handle, stream);
+}
+
+inline cudnnStatus_t
+create_filter_desc_v7(cudnnFilterDescriptor_t *filter) {
+ NV_FE_CALL_TO_BACKEND(create_filter_desc_v7, cudnnCreateFilterDescriptor, filter);
+}
+
+inline cudnnStatus_t
+set_ndfilter_desc_v7(cudnnFilterDescriptor_t filter,
+ cudnnDataType_t type,
+ cudnnTensorFormat_t format,
+ int x,
+ const int filterDimA[]) {
+ NV_FE_CALL_TO_BACKEND(set_ndfilter_desc_v7, cudnnSetFilterNdDescriptor, filter, type, format, x, filterDimA);
+}
+
+inline cudnnStatus_t
+reorder_filter_bias(cudnnHandle_t handle,
+ const cudnnFilterDescriptor_t filterDesc,
+ cudnnReorderType_t reorderType,
+ const void *filterData,
+ void *reorderedFilterData,
+ int reorderBias,
+ const void *biasData,
+ void *reorderedBiasData) {
+ NV_FE_CALL_TO_BACKEND(reorder_filter_bias,
+ cudnnReorderFilterAndBias,
+ handle,
+ filterDesc,
+ reorderType,
+ filterData,
+ reorderedFilterData,
+ reorderBias,
+ biasData,
+ reorderedBiasData);
+}
+
+inline cudnnStatus_t
+destroy_filter(cudnnFilterDescriptor_t filter) {
+ NV_FE_CALL_TO_BACKEND(destroy_filter, cudnnDestroyFilterDescriptor, filter);
+}
+
+} // namespace detail
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_utils.h b/deps/cudnn-frontend/include/cudnn_frontend_utils.h
new file mode 100644
index 0000000..8595907
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_utils.h
@@ -0,0 +1,2722 @@
+/*
+ * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+#include <exception>
+#include <optional>
+#include <string>
+#include <algorithm>
+#include <variant>
+#include <vector>
+#include <utility>
+#include <iomanip>
+#include <sstream>
+#include <cmath>
+#include <cstdint>
+
+#include <cuda_fp16.h>
+#include <cuda_bf16.h>
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+
+#ifndef CUDNN_FRONTEND_SKIP_JSON_LIB
+#include "cudnn_frontend/thirdparty/nlohmann/json.hpp"
+#endif
+
+using json = nlohmann::json;
+
+template <>
+struct nlohmann::adl_serializer<float> {
+ static void
+ to_json(nlohmann::json& j, const float& f) {
+ // Convert float to hexadecimal string
+ unsigned int intValue;
+ std::memcpy(&intValue, &f, sizeof(float));
+
+ std::stringstream stream;
+ stream << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << intValue;
+ j = stream.str();
+ }
+
+ static void
+ from_json(const nlohmann::json& j, float& f) {
+ // Read hexadecimal string and convert back to float
+ std::string hexValueStr = j.get<std::string>();
+ unsigned int hexValue;
+ std::stringstream stream(hexValueStr);
+ stream >> std::hex >> hexValue;
+
+ std::memcpy(&f, &hexValue, sizeof(float));
+ }
+};
+
+template <>
+struct nlohmann::adl_serializer<half> {
+ static void
+ to_json(json& j, const half& opt) {
+ // No precision loss when converting to float
+ j = __half2float(opt);
+ }
+
+ static void
+ from_json(const json& j, half& opt) {
+ opt = __float2half(j.get<float>());
+ }
+};
+
+template <>
+struct nlohmann::adl_serializer<nv_bfloat16> {
+ static void
+ to_json(json& j, const nv_bfloat16& opt) {
+ // No precision loss when converting to float
+ j = __bfloat162float(opt);
+ }
+
+ static void
+ from_json(const json& j, nv_bfloat16& opt) {
+ opt = __float2bfloat16(j.get<float>());
+ }
+};
+
+template <>
+struct nlohmann::adl_serializer<std::variant<int64_t, int32_t, half, float, double, nv_bfloat16>> {
+ static void
+ to_json(nlohmann::json& j, const std::variant<int64_t, int32_t, half, float, double, nv_bfloat16>& data) {
+ std::visit([&](const auto& v) { j = {{"index", data.index()}, {"value", v}}; }, data);
+ }
+
+ static void
+ from_json(const nlohmann::json& j, std::variant<int64_t, int32_t, half, float, double, nv_bfloat16>& data) {
+ if (!j.is_object() || !j.contains("index") || !j.contains("value")) {
+ return;
+ }
+
+ size_t type_index = j.at("index").get<size_t>();
+ if (type_index == 0) {
+ data = j.at("value").get<int64_t>();
+ } else if (type_index == 1) {
+ data = j.at("value").get<int32_t>();
+ } else if (type_index == 2) {
+ data = j.at("value").get<half>();
+ } else if (type_index == 3) {
+ data = j.at("value").get<float>();
+ } else if (type_index == 4) {
+ data = j.at("value").get<double>();
+ } else if (type_index == 5) {
+ data = j.at("value").get<nv_bfloat16>();
+ } else {
+ return;
+ }
+ }
+};
+
+// Specialization of nlohmann::adl_serializer for std::optional<T>
+template <typename T>
+struct nlohmann::adl_serializer<std::optional<T>> {
+ static void
+ to_json(json& j, const std::optional<T>& opt) {
+ if (opt.has_value())
+ j = *opt;
+ else
+ j = nullptr;
+ }
+
+ static void
+ from_json(const json& j, std::optional<T>& opt) {
+ if (!j.is_null())
+ opt = j.get<T>();
+ else
+ opt.reset();
+ }
+};
+
+// Specialization of nlohmann::adl_serializer for std::shared_ptr<T>
+template <typename T>
+struct nlohmann::adl_serializer<std::shared_ptr<T>> {
+ static void
+ to_json(json& j, const std::shared_ptr<T>& ptr) {
+ if (ptr)
+ j = *ptr;
+ else
+ j = nullptr;
+ }
+
+ static void
+ from_json(const json& j, std::shared_ptr<T>& ptr) {
+ if (!j.is_null())
+ ptr = std::make_shared<T>(j.get<T>());
+ else
+ ptr.reset();
+ }
+};
+
+// Specialization of nlohmann::adl_serializer for cudnnFraction_t
+template <>
+struct nlohmann::adl_serializer<cudnnFraction_t> {
+ static void
+ to_json(json& j, const cudnnFraction_t& fraction) {
+ j = fraction.numerator;
+ }
+
+ static void
+ from_json(const json& j, cudnnFraction_t& fraction) {
+ fraction.numerator = j;
+ }
+};
+
+#else
+#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...)
+#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...)
+#endif
+
+#include "cudnn_frontend_shim.h"
+#include "cudnn_backend_base.h"
+#include "cudnn_frontend_Logging.h"
+
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+#ifdef _MSC_VER
+#pragma warning(disable : 4702) // if exceptions are enabled there are unreachable return statements
+#endif
+#endif
+
+#define CUDNN_FRONTEND_UNUSED(X) ((void)X)
+namespace cudnn_frontend {
+
+/// Detailed feature_vector. Generally the Tensor and Operation properties
+using feature_vector_t = std::vector<int64_t>;
+
+class cudnnException : public std::runtime_error {
+ public:
+ cudnnException(const char* message, cudnnStatus_t status) throw() : std::runtime_error(message) {
+ error_status = status;
+ }
+ virtual const char*
+ what() const throw() {
+ return std::runtime_error::what();
+ }
+ cudnnStatus_t
+ getCudnnStatus() {
+ return error_status;
+ }
+
+ cudnnStatus_t error_status;
+};
+
+static inline bool
+AllowAll(cudnnBackendDescriptor_t engine_config) {
+ (void)engine_config;
+ return false;
+}
+
+static inline std::string
+to_string(cudnnStatus_t const status) {
+ return detail::get_error_string(status);
+}
+
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+[[noreturn]]
+#endif
+static inline void
+set_error_and_throw_exception(BackendDescriptor const* desc, cudnnStatus_t status, const char* message) {
+
+ std::string padded_message = std::string(message) + detail::get_last_error_string_();
+ if (desc != nullptr) {
+ desc->set_status(status);
+ desc->set_error(padded_message.c_str());
+ }
+#ifndef NV_CUDNN_DISABLE_EXCEPTION
+ throw cudnnException(
+ std::string(std::string(padded_message) + std::string(" cudnn_status: ") + to_string(status)).c_str(), status);
+#endif
+}
+
+static inline std::string
+to_string(cudnnBackendBehaviorNote_t note) {
+ switch (note) {
+ case CUDNN_BEHAVIOR_NOTE_RUNTIME_COMPILATION:
+ return std::string("CUDNN_BEHAVIOR_NOTE_RUNTIME_COMPILATION");
+ case CUDNN_BEHAVIOR_NOTE_REQUIRES_FILTER_INT8x32_REORDER:
+ return std::string("CUDNN_BEHAVIOR_NOTE_REQUIRES_FILTER_INT8x32_REORDER");
+ case CUDNN_BEHAVIOR_NOTE_REQUIRES_BIAS_INT8x32_REORDER:
+ return std::string("CUDNN_BEHAVIOR_NOTE_REQUIRES_BIAS_INT8x32_REORDER");
+ case CUDNN_BEHAVIOR_NOTE_TYPE_COUNT:
+ return std::string("CUDNN_BEHAVIOR_NOTE_TYPE_COUNT");
+ // If none of the above cases hit, its definitely strict nan prop and should raise an error.
+#if (CUDNN_VERSION >= 90500)
+ case CUDNN_BEHAVIOR_NOTE_SUPPORTS_CUDA_GRAPH_NATIVE_API:
+ return std::string("CUDNN_BEHAVIOR_NOTE_SUPPORTS_CUDA_GRAPH_NATIVE_API");
+#endif
+#if (CUDNN_VERSION >= 91500)
+ case CUDNN_BEHAVIOR_NOTE_CUBLASLT_DEPENDENCY:
+ return std::string("CUDNN_BEHAVIOR_NOTE_CUBLASLT_DEPENDENCY");
+#endif
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return std::string("UNKNOWN_BEHAVIOR_NOTE");
+#endif
+ }
+ return std::string("INVALID_BEHAVIOR_NOTE");
+}
+
+static inline std::string
+to_string(cudnnBackendNumericalNote_t note) {
+ switch (note) {
+ case CUDNN_NUMERICAL_NOTE_TENSOR_CORE:
+ return std::string("CUDNN_NUMERICAL_NOTE_TENSOR_CORE");
+ case CUDNN_NUMERICAL_NOTE_DOWN_CONVERT_INPUTS:
+ return std::string("CUDNN_NUMERICAL_NOTE_DOWN_CONVERT_INPUTS");
+ case CUDNN_NUMERICAL_NOTE_REDUCED_PRECISION_REDUCTION:
+ return std::string("CUDNN_NUMERICAL_NOTE_REDUCED_PRECISION_REDUCTION");
+ case CUDNN_NUMERICAL_NOTE_FFT:
+ return std::string("CUDNN_NUMERICAL_NOTE_FFT");
+ case CUDNN_NUMERICAL_NOTE_NONDETERMINISTIC:
+ return std::string("CUDNN_NUMERICAL_NOTE_NONDETERMINISTIC");
+ case CUDNN_NUMERICAL_NOTE_WINOGRAD:
+ return std::string("CUDNN_NUMERICAL_NOTE_WINOGRAD");
+ case CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_4x4:
+ return std::string("CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_4x4");
+ case CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_6x6:
+ return std::string("CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_6x6");
+ case CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_13x13:
+ return std::string("CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_13x13");
+ case CUDNN_NUMERICAL_NOTE_TYPE_COUNT:
+ return std::string("CUDNN_NUMERICAL_NOTE_TYPE_COUNT");
+
+ // If none of the above cases hit, its definitely strict nan prop and should raise an error.
+#if (CUDNN_VERSION >= 90100)
+ case CUDNN_NUMERICAL_NOTE_STRICT_NAN_PROP:
+ return std::string("CUDNN_NUMERICAL_NOTE_STRICT_NAN_PROP");
+#endif
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return std::string("UNKNOWN_NUMERICAL_NOTE");
+#endif
+ }
+ return std::string("INVALID_NUMERICAL_NOTE");
+}
+
+#if (CUDNN_VERSION >= 8700)
+static inline std::string
+to_string(cudnnRngDistribution_t distribution) {
+ switch (distribution) {
+ case CUDNN_RNG_DISTRIBUTION_BERNOULLI:
+ return std::string("CUDNN_RNG_DISTRIBUTION_BERNOULLI");
+ case CUDNN_RNG_DISTRIBUTION_UNIFORM:
+ return std::string("CUDNN_RNG_DISTRIBUTION_UNIFORM");
+ case CUDNN_RNG_DISTRIBUTION_NORMAL:
+ return std::string("CUDNN_RNG_DISTRIBUTION_NORMAL");
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return std::string("UNKNOWN_CUDNN_DISTRIBUTION");
+#endif
+ }
+ return std::string("");
+}
+#endif
+
+enum class BuildPlanPolicy_t {
+ // Builds and stores the "first successful" plan from the list returned by heuristics.
+ // heuristics list is traversed sequentially and in decreasing order of potential performance.
+ HEURISTICS_CHOICE,
+ // Builds and stores all the "successful" plans from the list returned by heuristics.
+ ALL,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(BuildPlanPolicy_t,
+ {
+ {BuildPlanPolicy_t::HEURISTICS_CHOICE, "HEURISTICS_CHOICE"},
+ {BuildPlanPolicy_t::ALL, "ALL"},
+ })
+
+enum class TensorReordering_t {
+ NONE,
+ INT8x32,
+ F16x16,
+ F8_128x4,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(TensorReordering_t,
+ {
+ {TensorReordering_t::NONE, "NONE"},
+ {TensorReordering_t::INT8x32, "INT8x32"},
+ {TensorReordering_t::F16x16, "F16x16"},
+ {TensorReordering_t::F8_128x4, "F8_128x4"},
+ })
+
+enum class ResampleMode_t {
+ NOT_SET,
+
+ AVGPOOL_EXCLUDE_PADDING,
+ AVGPOOL_INCLUDE_PADDING,
+ BILINEAR,
+ NEAREST,
+ MAXPOOL,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(ResampleMode_t,
+ {
+ {ResampleMode_t::NOT_SET, nullptr},
+ {ResampleMode_t::AVGPOOL_EXCLUDE_PADDING, "AVGPOOL_EXCLUDE_PADDING"},
+ {ResampleMode_t::AVGPOOL_INCLUDE_PADDING, "AVGPOOL_INCLUDE_PADDING"},
+ {ResampleMode_t::BILINEAR, "BILINEAR"},
+ {ResampleMode_t::NEAREST, "NEAREST"},
+ {ResampleMode_t::MAXPOOL, "MAXPOOL"},
+ })
+
+enum class PaddingMode_t {
+ NOT_SET,
+
+ EDGE_VAL_PAD,
+ NEG_INF_PAD,
+ ZERO_PAD
+};
+
+enum class ReshapeMode_t {
+ NOT_SET,
+
+ VIEW_ONLY,
+ LOGICAL
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(ReshapeMode_t,
+ {
+ {ReshapeMode_t::NOT_SET, nullptr},
+ {ReshapeMode_t::VIEW_ONLY, "VIEW_ONLY"},
+ {ReshapeMode_t::LOGICAL, "LOGICAL"},
+ })
+
+enum class ConvolutionMode_t {
+ NOT_SET,
+
+ CONVOLUTION,
+ CROSS_CORRELATION,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(ConvolutionMode_t,
+ {
+ {ConvolutionMode_t::CONVOLUTION, "CONVOLUTION"},
+ {ConvolutionMode_t::CROSS_CORRELATION, "CROSS_CORRELATION"},
+ })
+
+NLOHMANN_JSON_SERIALIZE_ENUM(PaddingMode_t,
+ {
+ {PaddingMode_t::NOT_SET, nullptr},
+ {PaddingMode_t::EDGE_VAL_PAD, "EDGE_VAL_PAD"},
+ {PaddingMode_t::NEG_INF_PAD, "NEG_INF_PAD"},
+ {PaddingMode_t::ZERO_PAD, "ZERO_PAD"},
+ })
+
+enum class NormFwdPhase_t {
+ NOT_SET,
+
+ INFERENCE,
+ TRAINING
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(NormFwdPhase_t,
+ {
+ {NormFwdPhase_t::NOT_SET, nullptr},
+ {NormFwdPhase_t::INFERENCE, "INFERENCE"},
+ {NormFwdPhase_t::TRAINING, "TRAINING"},
+ })
+
+enum class MoeGroupedMatmulMode_t {
+ NOT_SET,
+
+ NONE,
+ GATHER,
+ SCATTER
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(MoeGroupedMatmulMode_t,
+ {
+ {MoeGroupedMatmulMode_t::NOT_SET, nullptr},
+ {MoeGroupedMatmulMode_t::NONE, "NONE"},
+ {MoeGroupedMatmulMode_t::GATHER, "GATHER"},
+ {MoeGroupedMatmulMode_t::SCATTER, "SCATTER"},
+ })
+
+enum class DescriptorType_t {
+ NOT_SET,
+
+ POINTWISE_DESCRIPTOR,
+ CONVOLUTION_DESCRIPTOR,
+ ENGINE_DESCRIPTOR,
+ ENGINECFG_DESCRIPTOR,
+ ENGINEHEUR_DESCRIPTOR,
+ EXECUTION_PLAN_DESCRIPTOR,
+ INTERMEDIATE_INFO_DESCRIPTOR,
+ KNOB_CHOICE_DESCRIPTOR,
+ KNOB_INFO_DESCRIPTOR,
+ LAYOUT_INFO_DESCRIPTOR,
+ OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR,
+ OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR,
+ OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR,
+ OPERATION_POINTWISE_DESCRIPTOR,
+ OPERATION_GEN_STATS_DESCRIPTOR,
+ OPERATIONGRAPH_DESCRIPTOR,
+ VARIANT_PACK_DESCRIPTOR,
+ TENSOR_DESCRIPTOR,
+ MATMUL_DESCRIPTOR,
+ OPERATION_MATMUL_DESCRIPTOR,
+ OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR,
+ REDUCTION_DESCRIPTOR,
+ OPERATION_REDUCTION_DESCRIPTOR,
+ OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR,
+ RESAMPLE_DESCRIPTOR,
+ OPERATION_RESAMPLE_FWD_DESCRIPTOR,
+ OPERATION_RESAMPLE_BWD_DESCRIPTOR,
+ OPERATION_CONCAT_DESCRIPTOR,
+ OPERATION_SIGNAL_DESCRIPTOR,
+ OPERATION_NORM_FORWARD_DESCRIPTOR,
+ OPERATION_NORM_BACKWARD_DESCRIPTOR,
+ OPERATION_RESHAPE_DESCRIPTOR,
+ RNG_DESCRIPTOR,
+ OPERATION_RNG_DESCRIPTOR,
+ OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR,
+ OPERATION_BLOCK_SCALE_QUANTIZE_DESCRIPTOR,
+ OPERATION_BLOCK_SCALE_DEQUANTIZE_DESCRIPTOR,
+ OPERATION_CONCATENATE_DESCRIPTOR,
+ OPERATION_MOE_GROUPED_MATMUL_DESCRIPTOR,
+ OPERATION_MOE_GROUPED_MATMUL_BWD_DESCRIPTOR,
+ OPERATION_TRANSPOSE_DESCRIPTOR,
+ OPERATION_SLICE_DESCRIPTOR
+};
+
+enum class NormMode_t {
+ NOT_SET,
+
+ LAYER_NORM,
+ INSTANCE_NORM,
+ BATCH_NORM,
+ GROUP_NORM,
+ RMS_NORM,
+ ADA_LAYER_NORM,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(NormMode_t,
+ {
+ {NormMode_t::NOT_SET, nullptr},
+ {NormMode_t::LAYER_NORM, "LAYER_NORM"},
+ {NormMode_t::INSTANCE_NORM, "INSTANCE_NORM"},
+ {NormMode_t::BATCH_NORM, "BATCH_NORM"},
+ {NormMode_t::GROUP_NORM, "GROUP_NORM"},
+ {NormMode_t::RMS_NORM, "RMS_NORM"},
+ {NormMode_t::ADA_LAYER_NORM, "ADA_LAYER_NORM"},
+ })
+
+enum class PointwiseMode_t {
+ NOT_SET,
+
+ ADD,
+ MUL,
+ SQRT,
+ MAX,
+ MIN,
+ RELU_FWD,
+ TANH_FWD,
+ SIGMOID_FWD,
+ ELU_FWD,
+ GELU_FWD,
+ SOFTPLUS_FWD,
+ SWISH_FWD,
+ RELU_BWD,
+ TANH_BWD,
+ SIGMOID_BWD,
+ ELU_BWD,
+ GELU_BWD,
+ SOFTPLUS_BWD,
+ SWISH_BWD,
+ ERF,
+ IDENTITY,
+ GELU_APPROX_TANH_BWD,
+ GELU_APPROX_TANH_FWD,
+ GEN_INDEX,
+ BINARY_SELECT,
+ EXP,
+ LOG,
+ NEG,
+ MOD,
+ POW,
+ ABS,
+ CEIL,
+ COS,
+ FLOOR,
+ RSQRT,
+ SIN,
+ LOGICAL_NOT,
+ TAN,
+ SUB,
+ ADD_SQUARE,
+ DIV,
+ CMP_EQ,
+ CMP_NEQ,
+ CMP_GT,
+ CMP_GE,
+ CMP_LT,
+ CMP_LE,
+ LOGICAL_AND,
+ LOGICAL_OR,
+ RECIPROCAL,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(PointwiseMode_t,
+ {
+ {PointwiseMode_t::NOT_SET, nullptr},
+ {PointwiseMode_t::ADD, "ADD"},
+ {PointwiseMode_t::MUL, "MUL"},
+ {PointwiseMode_t::SQRT, "SQRT"},
+ {PointwiseMode_t::MAX, "MAX"},
+ {PointwiseMode_t::MIN, "MIN"},
+ {PointwiseMode_t::RELU_FWD, "RELU_FWD"},
+ {PointwiseMode_t::TANH_FWD, "TANH_FWD"},
+ {PointwiseMode_t::SIGMOID_FWD, "SIGMOID_FWD"},
+ {PointwiseMode_t::ELU_FWD, "ELU_FWD"},
+ {PointwiseMode_t::GELU_FWD, "GELU_FWD"},
+ {PointwiseMode_t::SOFTPLUS_FWD, "SOFTPLUS_FWD"},
+ {PointwiseMode_t::SWISH_FWD, "SWISH_FWD"},
+ {PointwiseMode_t::RELU_BWD, "RELU_BWD"},
+ {PointwiseMode_t::TANH_BWD, "TANH_BWD"},
+ {PointwiseMode_t::SIGMOID_BWD, "SIGMOID_BWD"},
+ {PointwiseMode_t::ELU_BWD, "ELU_BWD"},
+ {PointwiseMode_t::GELU_BWD, "GELU_BWD"},
+ {PointwiseMode_t::SOFTPLUS_BWD, "SOFTPLUS_BWD"},
+ {PointwiseMode_t::SWISH_BWD, "SWISH_BWD"},
+ {PointwiseMode_t::ERF, "ERF"},
+ {PointwiseMode_t::IDENTITY, "IDENTITY"},
+ {PointwiseMode_t::GELU_APPROX_TANH_BWD, "GELU_APPROX_TANH_BWD"},
+ {PointwiseMode_t::GELU_APPROX_TANH_FWD, "GELU_APPROX_TANH_FWD"},
+ {PointwiseMode_t::GEN_INDEX, "GEN_INDEX"},
+ {PointwiseMode_t::BINARY_SELECT, "BINARY_SELECT"},
+ {PointwiseMode_t::EXP, "EXP"},
+ {PointwiseMode_t::LOG, "LOG"},
+ {PointwiseMode_t::NEG, "NEG"},
+ {PointwiseMode_t::MOD, "MOD"},
+ {PointwiseMode_t::POW, "POW"},
+ {PointwiseMode_t::ABS, "ABS"},
+ {PointwiseMode_t::CEIL, "CEIL"},
+ {PointwiseMode_t::COS, "COS"},
+ {PointwiseMode_t::FLOOR, "FLOOR"},
+ {PointwiseMode_t::RSQRT, "RSQRT"},
+ {PointwiseMode_t::SIN, "SIN"},
+ {PointwiseMode_t::LOGICAL_NOT, "LOGICAL_NOT"},
+ {PointwiseMode_t::TAN, "TAN"},
+ {PointwiseMode_t::SUB, "SUB"},
+ {PointwiseMode_t::ADD_SQUARE, "ADD_SQUARE"},
+ {PointwiseMode_t::DIV, "DIV"},
+ {PointwiseMode_t::CMP_EQ, "CMP_EQ"},
+ {PointwiseMode_t::CMP_NEQ, "CMP_NEQ"},
+ {PointwiseMode_t::CMP_GT, "CMP_GT"},
+ {PointwiseMode_t::CMP_GE, "CMP_GE"},
+ {PointwiseMode_t::CMP_LT, "CMP_LT"},
+ {PointwiseMode_t::CMP_LE, "CMP_LE"},
+ {PointwiseMode_t::LOGICAL_AND, "LOGICAL_AND"},
+ {PointwiseMode_t::LOGICAL_OR, "LOGICAL_OR"},
+ {PointwiseMode_t::RECIPROCAL, "RECIPROCAL"},
+ })
+
+enum class HeurMode_t {
+ A,
+ B,
+ FALLBACK,
+ OPENSOURCE,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(HeurMode_t,
+ {
+ {HeurMode_t::A, "A"},
+ {HeurMode_t::B, "B"},
+ {HeurMode_t::FALLBACK, "FALLBACK"},
+ {HeurMode_t::OPENSOURCE, "OPENSOURCE"},
+ })
+
+enum class BehaviorNote_t {
+ NOT_SET,
+
+ RUNTIME_COMPILATION,
+ REQUIRES_FILTER_INT8x32_REORDER,
+ REQUIRES_BIAS_INT8x32_REORDER,
+ SUPPORTS_CUDA_GRAPH_NATIVE_API,
+ CUBLASLT_DEPENDENCY,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(BehaviorNote_t,
+ {
+ {BehaviorNote_t::NOT_SET, "NOT_SET"},
+ {BehaviorNote_t::RUNTIME_COMPILATION, "RUNTIME_COMPILATION"},
+ {BehaviorNote_t::REQUIRES_FILTER_INT8x32_REORDER, "REQUIRES_FILTER_INT8x32_REORDER"},
+ {BehaviorNote_t::REQUIRES_BIAS_INT8x32_REORDER, "REQUIRES_BIAS_INT8x32_REORDER"},
+ {BehaviorNote_t::SUPPORTS_CUDA_GRAPH_NATIVE_API, "SUPPORTS_CUDA_GRAPH_NATIVE_API"},
+ {BehaviorNote_t::CUBLASLT_DEPENDENCY, "CUBLASLT_DEPENDENCY"},
+ })
+
+enum class NumericalNote_t {
+ NOT_SET,
+
+ TENSOR_CORE,
+ DOWN_CONVERT_INPUTS,
+ REDUCED_PRECISION_REDUCTION,
+ FFT,
+ NONDETERMINISTIC,
+ WINOGRAD,
+ WINOGRAD_TILE_4x4,
+ WINOGRAD_TILE_6x6,
+ WINOGRAD_TILE_13x13,
+ STRICT_NAN_PROP,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(NumericalNote_t,
+ {
+ {NumericalNote_t::NOT_SET, "NOT_SET"},
+ {NumericalNote_t::TENSOR_CORE, "TENSOR_CORE"},
+ {NumericalNote_t::DOWN_CONVERT_INPUTS, "DOWN_CONVERT_INPUTS"},
+ {NumericalNote_t::REDUCED_PRECISION_REDUCTION, "REDUCED_PRECISION_REDUCTION"},
+ {NumericalNote_t::FFT, "FFT"},
+ {NumericalNote_t::NONDETERMINISTIC, "NONDETERMINISTIC"},
+ {NumericalNote_t::WINOGRAD, "WINOGRAD"},
+ {NumericalNote_t::WINOGRAD_TILE_4x4, "WINOGRAD_TILE_4x4"},
+ {NumericalNote_t::WINOGRAD_TILE_6x6, "WINOGRAD_TILE_6x6"},
+ {NumericalNote_t::WINOGRAD_TILE_13x13, "WINOGRAD_TILE_13x13"},
+ {NumericalNote_t::STRICT_NAN_PROP, "STRICT_NAN_PROP"},
+ })
+
+enum class DataType_t {
+ NOT_SET,
+
+ FLOAT,
+ DOUBLE,
+ HALF,
+ INT8,
+ INT32,
+ INT8x4,
+ UINT8,
+ UINT8x4,
+ INT8x32,
+ BFLOAT16,
+ INT64,
+ BOOLEAN,
+ BYTE_BOOLEAN,
+ FP8_E4M3,
+ FP8_E5M2,
+ FAST_FLOAT_FOR_FP8,
+ FP8_E8M0,
+ FP4_E2M1,
+ INT4,
+ COMPLEX_FP32,
+ COMPLEX_FP64,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(DataType_t,
+ {
+ {DataType_t::NOT_SET, nullptr},
+ {DataType_t::FLOAT, "FLOAT"},
+ {DataType_t::DOUBLE, "DOUBLE"},
+ {DataType_t::HALF, "HALF"},
+ {DataType_t::INT8, "INT8"},
+ {DataType_t::INT32, "INT32"},
+ {DataType_t::INT8x4, "INT8x4"},
+ {DataType_t::UINT8, "UINT8"},
+ {DataType_t::UINT8x4, "UINT8x4"},
+ {DataType_t::INT8x32, "INT8x32"},
+ {DataType_t::BFLOAT16, "BFLOAT16"},
+ {DataType_t::INT64, "INT64"},
+ {DataType_t::BOOLEAN, "BOOLEAN"},
+ {DataType_t::BYTE_BOOLEAN, "BYTE_BOOLEAN"},
+ {DataType_t::FP8_E4M3, "FP8_E4M3"},
+ {DataType_t::FP8_E5M2, "FP8_E5M2"},
+ {DataType_t::FAST_FLOAT_FOR_FP8, "FAST_FLOAT_FOR_FP8"},
+ {DataType_t::FP8_E8M0, "FP8_E8M0"},
+ {DataType_t::FP4_E2M1, "FP4_E2M1"},
+ {DataType_t::INT4, "INT4"},
+ {DataType_t::COMPLEX_FP32, "COMPLEX_FP32"},
+ {DataType_t::COMPLEX_FP64, "COMPLEX_FP64"},
+
+ })
+
+enum class ReductionMode_t {
+ NOT_SET,
+
+ ADD,
+ MUL,
+ MIN,
+ MAX,
+ AMAX,
+ AVG,
+ NORM1,
+ NORM2,
+ MUL_NO_ZEROS
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(ReductionMode_t,
+ {
+ {ReductionMode_t::NOT_SET, nullptr},
+ {ReductionMode_t::ADD, "ADD"},
+ {ReductionMode_t::MUL, "MUL"},
+ {ReductionMode_t::MIN, "MIN"},
+ {ReductionMode_t::MAX, "MAX"},
+ {ReductionMode_t::AMAX, "AMAX"},
+ {ReductionMode_t::AVG, "AVG"},
+ {ReductionMode_t::NORM1, "NORM1"},
+ {ReductionMode_t::NORM2, "NORM2"},
+ {ReductionMode_t::MUL_NO_ZEROS, "MUL_NO_ZEROS"},
+ })
+
+enum class RngDistribution_t {
+ NOT_SET,
+
+ BERNOULLI,
+ UNIFORM,
+ NORMAL,
+};
+
+NLOHMANN_JSON_SERIALIZE_ENUM(RngDistribution_t,
+ {
+ {RngDistribution_t::NOT_SET, nullptr},
+ {RngDistribution_t::BERNOULLI, "BERNOULLI"},
+ {RngDistribution_t::UNIFORM, "UNIFORM"},
+ {RngDistribution_t::NORMAL, "NORMAL"},
+ })
+
+static int64_t
+get_pointwise_mode_port_count(PointwiseMode_t const& mode) {
+ switch (mode) {
+ case PointwiseMode_t::NOT_SET:
+ return 0;
+
+ case PointwiseMode_t::ADD:
+ case PointwiseMode_t::MUL:
+ case PointwiseMode_t::DIV:
+ case PointwiseMode_t::ADD_SQUARE:
+ case PointwiseMode_t::SUB:
+ case PointwiseMode_t::CMP_EQ:
+ case PointwiseMode_t::CMP_NEQ:
+ case PointwiseMode_t::CMP_GT:
+ case PointwiseMode_t::CMP_GE:
+ case PointwiseMode_t::CMP_LT:
+ case PointwiseMode_t::CMP_LE:
+ case PointwiseMode_t::LOGICAL_AND:
+ case PointwiseMode_t::LOGICAL_OR:
+ case PointwiseMode_t::MIN:
+ case PointwiseMode_t::MAX:
+ case PointwiseMode_t::MOD:
+ case PointwiseMode_t::RELU_BWD:
+ case PointwiseMode_t::TANH_BWD:
+ case PointwiseMode_t::SIGMOID_BWD:
+ case PointwiseMode_t::ELU_BWD:
+ case PointwiseMode_t::GELU_BWD:
+ case PointwiseMode_t::SOFTPLUS_BWD:
+ case PointwiseMode_t::SWISH_BWD:
+ case PointwiseMode_t::GELU_APPROX_TANH_BWD:
+ case PointwiseMode_t::POW:
+ return 3;
+
+ case PointwiseMode_t::SQRT:
+ case PointwiseMode_t::RELU_FWD:
+ case PointwiseMode_t::TANH_FWD:
+ case PointwiseMode_t::SIGMOID_FWD:
+ case PointwiseMode_t::ELU_FWD:
+ case PointwiseMode_t::GELU_FWD:
+ case PointwiseMode_t::SOFTPLUS_FWD:
+ case PointwiseMode_t::SWISH_FWD:
+ case PointwiseMode_t::EXP:
+ case PointwiseMode_t::LOG:
+ case PointwiseMode_t::NEG:
+ case PointwiseMode_t::ABS:
+ case PointwiseMode_t::CEIL:
+ case PointwiseMode_t::FLOOR:
+ case PointwiseMode_t::COS:
+ case PointwiseMode_t::TAN:
+ case PointwiseMode_t::SIN:
+ case PointwiseMode_t::RSQRT:
+ case PointwiseMode_t::LOGICAL_NOT:
+ case PointwiseMode_t::GEN_INDEX:
+ case PointwiseMode_t::ERF:
+ case PointwiseMode_t::GELU_APPROX_TANH_FWD:
+ case PointwiseMode_t::IDENTITY:
+ case PointwiseMode_t::RECIPROCAL:
+ return 2;
+
+ case PointwiseMode_t::BINARY_SELECT:
+ return 4;
+ }
+ return -1;
+}
+
+static inline std::ostream&
+operator<<(std::ostream& os, const DescriptorType_t& mode) {
+ switch (mode) {
+ case DescriptorType_t::POINTWISE_DESCRIPTOR:
+ os << "POINTWISE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::CONVOLUTION_DESCRIPTOR:
+ os << "CONVOLUTION_DESCRIPTOR";
+ break;
+ case DescriptorType_t::ENGINE_DESCRIPTOR:
+ os << "ENGINE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::ENGINECFG_DESCRIPTOR:
+ os << "ENGINECFG_DESCRIPTOR";
+ break;
+ case DescriptorType_t::ENGINEHEUR_DESCRIPTOR:
+ os << "ENGINEHEUR_DESCRIPTOR";
+ break;
+ case DescriptorType_t::EXECUTION_PLAN_DESCRIPTOR:
+ os << "EXECUTION_PLAN_DESCRIPTOR";
+ break;
+ case DescriptorType_t::INTERMEDIATE_INFO_DESCRIPTOR:
+ os << "INTERMEDIATE_INFO_DESCRIPTOR";
+ break;
+ case DescriptorType_t::KNOB_CHOICE_DESCRIPTOR:
+ os << "KNOB_CHOICE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::KNOB_INFO_DESCRIPTOR:
+ os << "KNOB_INFO_DESCRIPTOR";
+ break;
+ case DescriptorType_t::LAYOUT_INFO_DESCRIPTOR:
+ os << "LAYOUT_INFO_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR:
+ os << "OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR:
+ os << "OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR:
+ os << "OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_POINTWISE_DESCRIPTOR:
+ os << "OPERATION_POINTWISE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_GEN_STATS_DESCRIPTOR:
+ os << "OPERATION_GEN_STATS_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATIONGRAPH_DESCRIPTOR:
+ os << "OPERATIONGRAPH_DESCRIPTOR";
+ break;
+ case DescriptorType_t::VARIANT_PACK_DESCRIPTOR:
+ os << "VARIANT_PACK_DESCRIPTOR";
+ break;
+ case DescriptorType_t::TENSOR_DESCRIPTOR:
+ os << "TENSOR_DESCRIPTOR";
+ break;
+ case DescriptorType_t::MATMUL_DESCRIPTOR:
+ os << "MATMUL_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_MATMUL_DESCRIPTOR:
+ os << "OPERATION_MATMUL_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR:
+ os << "OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR";
+ break;
+ case DescriptorType_t::REDUCTION_DESCRIPTOR:
+ os << "REDUCTION_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_REDUCTION_DESCRIPTOR:
+ os << "OPERATION_REDUCTION_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR:
+ os << "OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR";
+ break;
+ case DescriptorType_t::RESAMPLE_DESCRIPTOR:
+ os << "RESAMPLE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_RESAMPLE_FWD_DESCRIPTOR:
+ os << "OPERATION_RESAMPLE_FWD_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_RESAMPLE_BWD_DESCRIPTOR:
+ os << "OPERATION_RESAMPLE_BWD_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_CONCAT_DESCRIPTOR:
+ os << "OPERATION_CONCAT_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_SIGNAL_DESCRIPTOR:
+ os << "OPERATION_SIGNAL_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_NORM_FORWARD_DESCRIPTOR:
+ os << "OPERATION_NORM_FORWARD_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_NORM_BACKWARD_DESCRIPTOR:
+ os << "OPERATION_NORM_BACKWARD_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_RESHAPE_DESCRIPTOR:
+ os << "OPERATION_RESHAPE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::RNG_DESCRIPTOR:
+ os << "RNG_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_RNG_DESCRIPTOR:
+ os << "OPERATION_RNG_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR:
+ os << "OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_BLOCK_SCALE_QUANTIZE_DESCRIPTOR:
+ os << "OPERATION_BLOCK_SCALE_QUANTIZE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_BLOCK_SCALE_DEQUANTIZE_DESCRIPTOR:
+ os << "OPERATION_BLOCK_SCALE_DEQUANTIZE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_CONCATENATE_DESCRIPTOR:
+ os << "OPERATION_CONCATENATE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_MOE_GROUPED_MATMUL_DESCRIPTOR:
+ os << "OPERATION_MOE_GROUPED_MATMUL_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_MOE_GROUPED_MATMUL_BWD_DESCRIPTOR:
+ os << "OPERATION_MOE_GROUPED_MATMUL_BWD_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_TRANSPOSE_DESCRIPTOR:
+ os << "OPERATION_TRANSPOSE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::OPERATION_SLICE_DESCRIPTOR:
+ os << "OPERATION_SLICE_DESCRIPTOR";
+ break;
+ case DescriptorType_t::NOT_SET:
+ os << "NOT_SET";
+ break;
+ }
+ return os;
+}
+
+enum class DiagonalAlignment_t { TOP_LEFT, BOTTOM_RIGHT };
+NLOHMANN_JSON_SERIALIZE_ENUM(DiagonalAlignment_t,
+ {
+ {DiagonalAlignment_t::TOP_LEFT, "TOP_LEFT"},
+ {DiagonalAlignment_t::BOTTOM_RIGHT, "BOTTOM_RIGHT"},
+ })
+
+enum class AttentionImplementation_t { AUTO, COMPOSITE, UNIFIED };
+NLOHMANN_JSON_SERIALIZE_ENUM(AttentionImplementation_t,
+ {
+ {AttentionImplementation_t::AUTO, "AUTO"},
+ {AttentionImplementation_t::COMPOSITE, "COMPOSITE"},
+ {AttentionImplementation_t::UNIFIED, "UNIFIED"},
+ })
+
+namespace detail {
+
+inline size_t
+get_data_type_size(DataType_t const data_type) {
+ switch (data_type) {
+ case DataType_t::FLOAT:
+ return sizeof(float);
+ case DataType_t::DOUBLE:
+ return sizeof(double);
+ case DataType_t::HALF:
+ return 2; // 16-bit float
+ case DataType_t::INT8:
+ case DataType_t::UINT8:
+ return 1;
+ case DataType_t::INT32:
+ return sizeof(int32_t);
+ case DataType_t::INT8x4:
+ case DataType_t::UINT8x4:
+ return 4;
+ case DataType_t::INT8x32:
+ return 32;
+ case DataType_t::BFLOAT16:
+ return 2;
+ case DataType_t::INT64:
+ return sizeof(int64_t);
+ case DataType_t::FP8_E4M3:
+ case DataType_t::FP8_E5M2:
+ return 1; // 8-bit float
+ case DataType_t::BYTE_BOOLEAN:
+ return 1;
+ case DataType_t::NOT_SET:
+ case DataType_t::BOOLEAN:
+ default:
+ return 0;
+ }
+}
+
+inline std::vector<float>
+get_alibi_slope(int64_t const n_heads) {
+ std::vector<float> slope;
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4244) // this could be ommited with c++17 and contexpr
+#endif
+ int n = 1 << static_cast<int>(log2(static_cast<double>(n_heads)));
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+ for (int i = 0; i < n; i++) {
+ slope.push_back((float)(i + 1.0));
+ }
+
+ for (int i = 0; i < 2 * (n_heads - n); i += 2) {
+ slope.push_back(static_cast<float>(i + 1) * 0.5f);
+ }
+
+ for (float& elem : slope) {
+ elem *= -8.0f;
+ elem /= static_cast<float>(n);
+ elem = powf(2.0, elem);
+ }
+
+ return slope;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::DataType_t const mode, cudnnDataType_t& cudnn_mode) {
+ switch (mode) {
+ case DataType_t::FLOAT:
+ cudnn_mode = CUDNN_DATA_FLOAT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::DOUBLE:
+ cudnn_mode = CUDNN_DATA_DOUBLE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::HALF:
+ cudnn_mode = CUDNN_DATA_HALF;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::INT8:
+ cudnn_mode = CUDNN_DATA_INT8;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::INT32:
+ cudnn_mode = CUDNN_DATA_INT32;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::INT8x4:
+ cudnn_mode = CUDNN_DATA_INT8x4;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::UINT8:
+ cudnn_mode = CUDNN_DATA_UINT8;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::UINT8x4:
+ cudnn_mode = CUDNN_DATA_UINT8x4;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::INT8x32:
+ cudnn_mode = CUDNN_DATA_INT8x32;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::BFLOAT16:
+ cudnn_mode = CUDNN_DATA_BFLOAT16;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::INT64:
+ cudnn_mode = CUDNN_DATA_INT64;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::BOOLEAN:
+ cudnn_mode = CUDNN_DATA_BOOLEAN;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DataType_t::BYTE_BOOLEAN:
+#if (CUDNN_VERSION >= 93000)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(93000, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_DATA_BYTE_BOOLEAN;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DataType_t::FP8_E4M3:
+#if (CUDNN_VERSION >= 8600)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8600, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_DATA_FP8_E4M3;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DataType_t::FP8_E5M2:
+#if (CUDNN_VERSION >= 8600)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8600, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_DATA_FP8_E5M2;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DataType_t::FAST_FLOAT_FOR_FP8:
+#if (CUDNN_VERSION >= 8700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_DATA_FAST_FLOAT_FOR_FP8;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DataType_t::FP8_E8M0:
+#if (CUDNN_VERSION >= 90700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_DATA_FP8_E8M0;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DataType_t::FP4_E2M1:
+#if (CUDNN_VERSION >= 90700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_DATA_FP4_E2M1;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DataType_t::INT4:
+#if (CUDNN_VERSION >= 91100)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91000, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_DATA_INT4;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DataType_t::COMPLEX_FP32:
+#if (CUDNN_VERSION >= 91400)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91400, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_DATA_COMPLEX_FP32;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DataType_t::COMPLEX_FP64:
+#if (CUDNN_VERSION >= 91400)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91400, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_DATA_COMPLEX_FP64;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::ReductionMode_t const mode, cudnnReduceTensorOp_t& cudnn_mode) {
+ switch (mode) {
+ case ReductionMode_t::ADD:
+ cudnn_mode = CUDNN_REDUCE_TENSOR_ADD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case ReductionMode_t::MUL:
+ cudnn_mode = CUDNN_REDUCE_TENSOR_MUL;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case ReductionMode_t::MIN:
+ cudnn_mode = CUDNN_REDUCE_TENSOR_MIN;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case ReductionMode_t::MAX:
+ cudnn_mode = CUDNN_REDUCE_TENSOR_MAX;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case ReductionMode_t::AMAX:
+ cudnn_mode = CUDNN_REDUCE_TENSOR_AMAX;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case ReductionMode_t::AVG:
+ cudnn_mode = CUDNN_REDUCE_TENSOR_AVG;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case ReductionMode_t::NORM1:
+ cudnn_mode = CUDNN_REDUCE_TENSOR_NORM1;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case ReductionMode_t::NORM2:
+ cudnn_mode = CUDNN_REDUCE_TENSOR_NORM2;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case ReductionMode_t::MUL_NO_ZEROS:
+ cudnn_mode = CUDNN_REDUCE_TENSOR_MUL_NO_ZEROS;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::PointwiseMode_t const mode, cudnnPointwiseMode_t& cudnn_mode) {
+ switch (mode) {
+ case PointwiseMode_t::ADD:
+ cudnn_mode = CUDNN_POINTWISE_ADD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::MUL:
+ cudnn_mode = CUDNN_POINTWISE_MUL;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::SQRT:
+ cudnn_mode = CUDNN_POINTWISE_SQRT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::MAX:
+ cudnn_mode = CUDNN_POINTWISE_MAX;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::MIN:
+ cudnn_mode = CUDNN_POINTWISE_MIN;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::RELU_FWD:
+ cudnn_mode = CUDNN_POINTWISE_RELU_FWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::TANH_FWD:
+ cudnn_mode = CUDNN_POINTWISE_TANH_FWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::SIGMOID_FWD:
+ cudnn_mode = CUDNN_POINTWISE_SIGMOID_FWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::ELU_FWD:
+ cudnn_mode = CUDNN_POINTWISE_ELU_FWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::GELU_FWD:
+ cudnn_mode = CUDNN_POINTWISE_GELU_FWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::SOFTPLUS_FWD:
+ cudnn_mode = CUDNN_POINTWISE_SOFTPLUS_FWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::SWISH_FWD:
+ cudnn_mode = CUDNN_POINTWISE_SWISH_FWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::RELU_BWD:
+ cudnn_mode = CUDNN_POINTWISE_RELU_BWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::TANH_BWD:
+ cudnn_mode = CUDNN_POINTWISE_TANH_BWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::SIGMOID_BWD:
+ cudnn_mode = CUDNN_POINTWISE_SIGMOID_BWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::ELU_BWD:
+ cudnn_mode = CUDNN_POINTWISE_ELU_BWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::GELU_BWD:
+ cudnn_mode = CUDNN_POINTWISE_GELU_BWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::SOFTPLUS_BWD:
+ cudnn_mode = CUDNN_POINTWISE_SOFTPLUS_BWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::SWISH_BWD:
+ cudnn_mode = CUDNN_POINTWISE_SWISH_BWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::DIV:
+ cudnn_mode = CUDNN_POINTWISE_DIV;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::ADD_SQUARE:
+ cudnn_mode = CUDNN_POINTWISE_ADD_SQUARE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::EXP:
+ cudnn_mode = CUDNN_POINTWISE_EXP;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::SUB:
+ cudnn_mode = CUDNN_POINTWISE_SUB;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::CMP_EQ:
+ cudnn_mode = CUDNN_POINTWISE_CMP_EQ;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::CMP_NEQ:
+ cudnn_mode = CUDNN_POINTWISE_CMP_NEQ;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::CMP_GT:
+ cudnn_mode = CUDNN_POINTWISE_CMP_GT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::CMP_GE:
+ cudnn_mode = CUDNN_POINTWISE_CMP_GE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::CMP_LT:
+ cudnn_mode = CUDNN_POINTWISE_CMP_LT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::CMP_LE:
+ cudnn_mode = CUDNN_POINTWISE_CMP_LE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::LOGICAL_AND:
+ cudnn_mode = CUDNN_POINTWISE_LOGICAL_AND;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::LOGICAL_OR:
+ cudnn_mode = CUDNN_POINTWISE_LOGICAL_OR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::LOGICAL_NOT:
+ cudnn_mode = CUDNN_POINTWISE_LOGICAL_NOT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::LOG:
+ cudnn_mode = CUDNN_POINTWISE_LOG;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::NEG:
+ cudnn_mode = CUDNN_POINTWISE_NEG;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::MOD:
+ cudnn_mode = CUDNN_POINTWISE_MOD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::POW:
+ cudnn_mode = CUDNN_POINTWISE_POW;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::ABS:
+ cudnn_mode = CUDNN_POINTWISE_ABS;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::CEIL:
+ cudnn_mode = CUDNN_POINTWISE_CEIL;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::COS:
+ cudnn_mode = CUDNN_POINTWISE_COS;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::FLOOR:
+ cudnn_mode = CUDNN_POINTWISE_FLOOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::RSQRT:
+ cudnn_mode = CUDNN_POINTWISE_RSQRT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::SIN:
+ cudnn_mode = CUDNN_POINTWISE_SIN;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::TAN:
+ cudnn_mode = CUDNN_POINTWISE_TAN;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::GEN_INDEX:
+ cudnn_mode = CUDNN_POINTWISE_GEN_INDEX;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::BINARY_SELECT:
+ cudnn_mode = CUDNN_POINTWISE_BINARY_SELECT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::ERF:
+ cudnn_mode = CUDNN_POINTWISE_ERF;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::IDENTITY:
+ cudnn_mode = CUDNN_POINTWISE_IDENTITY;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::GELU_APPROX_TANH_BWD:
+ cudnn_mode = CUDNN_POINTWISE_GELU_APPROX_TANH_BWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::GELU_APPROX_TANH_FWD:
+ cudnn_mode = CUDNN_POINTWISE_GELU_APPROX_TANH_FWD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case PointwiseMode_t::RECIPROCAL:
+#if (CUDNN_VERSION >= 8900)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8900, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_POINTWISE_RECIPROCAL;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::NumericalNote_t const mode, cudnnBackendNumericalNote_t& cudnn_mode) {
+ switch (mode) {
+ case NumericalNote_t::TENSOR_CORE:
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_TENSOR_CORE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NumericalNote_t::DOWN_CONVERT_INPUTS:
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_DOWN_CONVERT_INPUTS;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NumericalNote_t::REDUCED_PRECISION_REDUCTION:
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_REDUCED_PRECISION_REDUCTION;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NumericalNote_t::FFT:
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_FFT;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NumericalNote_t::NONDETERMINISTIC:
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_NONDETERMINISTIC;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NumericalNote_t::WINOGRAD:
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_WINOGRAD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NumericalNote_t::WINOGRAD_TILE_4x4:
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_4x4;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NumericalNote_t::WINOGRAD_TILE_6x6:
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_6x6;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NumericalNote_t::WINOGRAD_TILE_13x13:
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_13x13;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NumericalNote_t::STRICT_NAN_PROP:
+#if (CUDNN_VERSION >= 90100)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90100, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_NUMERICAL_NOTE_STRICT_NAN_PROP;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::BehaviorNote_t const mode, cudnnBackendBehaviorNote_t& cudnn_mode) {
+ switch (mode) {
+ case BehaviorNote_t::RUNTIME_COMPILATION:
+ cudnn_mode = CUDNN_BEHAVIOR_NOTE_RUNTIME_COMPILATION;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case BehaviorNote_t::REQUIRES_FILTER_INT8x32_REORDER:
+ cudnn_mode = CUDNN_BEHAVIOR_NOTE_REQUIRES_FILTER_INT8x32_REORDER;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case BehaviorNote_t::REQUIRES_BIAS_INT8x32_REORDER:
+ cudnn_mode = CUDNN_BEHAVIOR_NOTE_REQUIRES_BIAS_INT8x32_REORDER;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case BehaviorNote_t::SUPPORTS_CUDA_GRAPH_NATIVE_API:
+#if (CUDNN_VERSION >= 90500)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90500, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BEHAVIOR_NOTE_SUPPORTS_CUDA_GRAPH_NATIVE_API;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case BehaviorNote_t::CUBLASLT_DEPENDENCY:
+#if (CUDNN_VERSION >= 91500)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91500, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BEHAVIOR_NOTE_CUBLASLT_DEPENDENCY;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnn_frontend::BehaviorNote_t
+convert_from_cudnn_type(cudnnBackendBehaviorNote_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case CUDNN_BEHAVIOR_NOTE_RUNTIME_COMPILATION:
+ return BehaviorNote_t::RUNTIME_COMPILATION;
+ case CUDNN_BEHAVIOR_NOTE_REQUIRES_FILTER_INT8x32_REORDER:
+ return BehaviorNote_t::REQUIRES_FILTER_INT8x32_REORDER;
+ case CUDNN_BEHAVIOR_NOTE_REQUIRES_BIAS_INT8x32_REORDER:
+ return BehaviorNote_t::REQUIRES_BIAS_INT8x32_REORDER;
+#if (CUDNN_VERSION >= 90500)
+ case CUDNN_BEHAVIOR_NOTE_SUPPORTS_CUDA_GRAPH_NATIVE_API:
+ return BehaviorNote_t::SUPPORTS_CUDA_GRAPH_NATIVE_API;
+#endif
+#if (CUDNN_VERSION >= 91500)
+ case CUDNN_BEHAVIOR_NOTE_CUBLASLT_DEPENDENCY:
+ return BehaviorNote_t::CUBLASLT_DEPENDENCY;
+#endif
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return BehaviorNote_t::NOT_SET;
+ break;
+#endif
+ }
+ return BehaviorNote_t::NOT_SET;
+}
+
+static inline cudnn_frontend::NumericalNote_t
+convert_from_cudnn_type(cudnnBackendNumericalNote_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case CUDNN_NUMERICAL_NOTE_TENSOR_CORE:
+ return NumericalNote_t::TENSOR_CORE;
+ case CUDNN_NUMERICAL_NOTE_DOWN_CONVERT_INPUTS:
+ return NumericalNote_t::DOWN_CONVERT_INPUTS;
+ case CUDNN_NUMERICAL_NOTE_REDUCED_PRECISION_REDUCTION:
+ return NumericalNote_t::REDUCED_PRECISION_REDUCTION;
+ case CUDNN_NUMERICAL_NOTE_FFT:
+ return NumericalNote_t::FFT;
+ case CUDNN_NUMERICAL_NOTE_NONDETERMINISTIC:
+ return NumericalNote_t::NONDETERMINISTIC;
+ case CUDNN_NUMERICAL_NOTE_WINOGRAD:
+ return NumericalNote_t::WINOGRAD;
+ case CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_4x4:
+ return NumericalNote_t::WINOGRAD_TILE_4x4;
+ case CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_6x6:
+ return NumericalNote_t::WINOGRAD_TILE_6x6;
+ case CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_13x13:
+ return NumericalNote_t::WINOGRAD_TILE_13x13;
+#if (CUDNN_VERSION >= 90100)
+ case CUDNN_NUMERICAL_NOTE_STRICT_NAN_PROP:
+ return NumericalNote_t::STRICT_NAN_PROP;
+#endif
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return NumericalNote_t::NOT_SET;
+ break;
+#endif
+ }
+ return NumericalNote_t::NOT_SET;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::DescriptorType_t const mode, cudnnBackendDescriptorType_t& cudnn_mode) {
+ switch (mode) {
+ case DescriptorType_t::POINTWISE_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_POINTWISE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::CONVOLUTION_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::ENGINE_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_ENGINE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::ENGINECFG_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_ENGINECFG_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::ENGINEHEUR_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::EXECUTION_PLAN_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::INTERMEDIATE_INFO_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_INTERMEDIATE_INFO_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::KNOB_CHOICE_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::KNOB_INFO_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::LAYOUT_INFO_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_LAYOUT_INFO_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_POINTWISE_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_GEN_STATS_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATIONGRAPH_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::VARIANT_PACK_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::TENSOR_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_TENSOR_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::MATMUL_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_MATMUL_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_MATMUL_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::REDUCTION_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_REDUCTION_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_REDUCTION_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::RESAMPLE_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_RESAMPLE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_RESAMPLE_FWD_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_RESAMPLE_BWD_DESCRIPTOR:
+#if (CUDNN_VERSION >= 8600)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8600, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_RESAMPLE_BWD_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DescriptorType_t::OPERATION_CONCAT_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_SIGNAL_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_SIGNAL_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_NORM_FORWARD_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_NORM_BACKWARD_DESCRIPTOR:
+ cudnn_mode = CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case DescriptorType_t::OPERATION_RESHAPE_DESCRIPTOR:
+#if (CUDNN_VERSION >= 8700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_RESHAPE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+
+ case DescriptorType_t::RNG_DESCRIPTOR:
+#if (CUDNN_VERSION >= 8700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_RNG_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+
+ case DescriptorType_t::OPERATION_RNG_DESCRIPTOR:
+#if (CUDNN_VERSION >= 8700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_RNG_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+
+ case DescriptorType_t::OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR:
+#if (CUDNN_VERSION >= 90500)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90500, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+ case DescriptorType_t::OPERATION_BLOCK_SCALE_QUANTIZE_DESCRIPTOR:
+#if (CUDNN_VERSION >= 90700) // TODO: v9.99 is new feature branch; switch to release branch when ready
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_BLOCK_SCALE_QUANTIZE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DescriptorType_t::OPERATION_BLOCK_SCALE_DEQUANTIZE_DESCRIPTOR:
+#if (CUDNN_VERSION >= 90700) // TODO: v9.99 is new feature branch; switch to release branch when ready
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_BLOCK_SCALE_DEQUANTIZE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DescriptorType_t::OPERATION_CONCATENATE_DESCRIPTOR:
+#if (CUDNN_VERSION >= 90700)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DescriptorType_t::OPERATION_MOE_GROUPED_MATMUL_DESCRIPTOR:
+#if (CUDNN_VERSION >= 91500)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91500, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_MOE_GROUPED_MATMUL_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DescriptorType_t::OPERATION_MOE_GROUPED_MATMUL_BWD_DESCRIPTOR:
+#if (CUDNN_VERSION >= 92200)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92200, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_MOE_GROUPED_MATMUL_BWD_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DescriptorType_t::OPERATION_TRANSPOSE_DESCRIPTOR:
+#if (CUDNN_VERSION >= 92200)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92200, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_TRANSPOSE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case DescriptorType_t::OPERATION_SLICE_DESCRIPTOR:
+#if (CUDNN_VERSION >= 92200)
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(92200, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_BACKEND_OPERATION_SLICE_DESCRIPTOR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::ResampleMode_t const mode, cudnnResampleMode_t& cudnn_mode) {
+ switch (mode) {
+#if (CUDNN_VERSION >= 8600)
+ case cudnn_frontend::ResampleMode_t::AVGPOOL_EXCLUDE_PADDING:
+ cudnn_mode = CUDNN_RESAMPLE_AVGPOOL_EXCLUDE_PADDING;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case cudnn_frontend::ResampleMode_t::AVGPOOL_INCLUDE_PADDING:
+ cudnn_mode = CUDNN_RESAMPLE_AVGPOOL_INCLUDE_PADDING;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ case cudnn_frontend::ResampleMode_t::AVGPOOL_INCLUDE_PADDING:
+ cudnn_mode = CUDNN_RESAMPLE_AVGPOOL;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+ case cudnn_frontend::ResampleMode_t::BILINEAR:
+ cudnn_mode = CUDNN_RESAMPLE_BILINEAR;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case cudnn_frontend::ResampleMode_t::NEAREST:
+ cudnn_mode = CUDNN_RESAMPLE_NEAREST;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case cudnn_frontend::ResampleMode_t::MAXPOOL:
+ cudnn_mode = CUDNN_RESAMPLE_MAXPOOL;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::PaddingMode_t const mode, cudnnPaddingMode_t& cudnn_mode) {
+ switch (mode) {
+ case cudnn_frontend::PaddingMode_t::ZERO_PAD:
+ cudnn_mode = CUDNN_ZERO_PAD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case cudnn_frontend::PaddingMode_t::NEG_INF_PAD:
+ cudnn_mode = CUDNN_NEG_INF_PAD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case cudnn_frontend::PaddingMode_t::EDGE_VAL_PAD:
+ cudnn_mode = CUDNN_EDGE_VAL_PAD;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::NormMode_t const mode, cudnnBackendNormMode_t& cudnn_mode) {
+ switch (mode) {
+ case NormMode_t::LAYER_NORM:
+ cudnn_mode = CUDNN_LAYER_NORM;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NormMode_t::INSTANCE_NORM:
+ cudnn_mode = CUDNN_INSTANCE_NORM;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NormMode_t::BATCH_NORM:
+ cudnn_mode = CUDNN_BATCH_NORM;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NormMode_t::GROUP_NORM:
+ cudnn_mode = CUDNN_GROUP_NORM;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+
+#if (CUDNN_VERSION >= 8906)
+ case NormMode_t::RMS_NORM:
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8906, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_RMS_NORM;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#if (CUDNN_VERSION >= 90900)
+ case NormMode_t::ADA_LAYER_NORM:
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(90900, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ cudnn_mode = CUDNN_ADA_LAYER_NORM;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::NormFwdPhase_t const mode, cudnnBackendNormFwdPhase_t& cudnn_mode) {
+ switch (mode) {
+ case NormFwdPhase_t::INFERENCE:
+ cudnn_mode = CUDNN_NORM_FWD_INFERENCE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case NormFwdPhase_t::TRAINING:
+ cudnn_mode = CUDNN_NORM_FWD_TRAINING;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+#if (CUDNN_VERSION >= 92200)
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::ReshapeMode_t const mode, cudnnBackendReshapeMode_t& cudnn_mode) {
+ switch (mode) {
+ case ReshapeMode_t::VIEW_ONLY:
+ cudnn_mode = CUDNN_RESHAPE_VIEW_ONLY;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case ReshapeMode_t::LOGICAL:
+ cudnn_mode = CUDNN_RESHAPE_LOGICAL;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+#endif
+
+// To be deprecated. Only exists as setResampleMode(cudnnPaddingMode_t) requires it.
+static inline void
+convert_from_cudnn_type(cudnnPaddingMode_t const cudnn_mode, cudnn_frontend::PaddingMode_t& mode) {
+ mode = cudnn_frontend::PaddingMode_t::NOT_SET;
+ switch (cudnn_mode) {
+ case CUDNN_EDGE_VAL_PAD:
+ mode = cudnn_frontend::PaddingMode_t::EDGE_VAL_PAD;
+ break;
+ case CUDNN_NEG_INF_PAD:
+ mode = cudnn_frontend::PaddingMode_t::NEG_INF_PAD;
+ break;
+ case CUDNN_ZERO_PAD:
+ mode = cudnn_frontend::PaddingMode_t::ZERO_PAD;
+ break;
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ break;
+#endif
+ }
+}
+
+static inline cudnn_frontend::ConvolutionMode_t
+convert_from_cudnn_type(cudnnConvolutionMode_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case CUDNN_CONVOLUTION:
+ return cudnn_frontend::ConvolutionMode_t::CONVOLUTION;
+ case CUDNN_CROSS_CORRELATION:
+ return cudnn_frontend::ConvolutionMode_t::CROSS_CORRELATION;
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnn_frontend::ConvolutionMode_t::NOT_SET;
+#endif
+ }
+ return cudnn_frontend::ConvolutionMode_t::NOT_SET;
+}
+
+static inline cudnnConvolutionMode_t
+convert_to_cudnn_type(cudnn_frontend::ConvolutionMode_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case cudnn_frontend::ConvolutionMode_t::CONVOLUTION:
+ return CUDNN_CONVOLUTION;
+ case cudnn_frontend::ConvolutionMode_t::CROSS_CORRELATION:
+ return CUDNN_CROSS_CORRELATION;
+ case cudnn_frontend::ConvolutionMode_t::NOT_SET:
+ return CUDNN_CROSS_CORRELATION;
+ }
+ return CUDNN_CROSS_CORRELATION;
+}
+// To be deprecated. Only exists as setResampleMode(cudnnResampleMode_t) requires it.
+static inline void
+convert_from_cudnn_type(cudnnResampleMode_t const cudnn_mode, cudnn_frontend::ResampleMode_t& mode) {
+ mode = cudnn_frontend::ResampleMode_t::NOT_SET;
+ switch (cudnn_mode) {
+#if (CUDNN_VERSION >= 8600)
+ case CUDNN_RESAMPLE_AVGPOOL_EXCLUDE_PADDING:
+ mode = cudnn_frontend::ResampleMode_t::AVGPOOL_EXCLUDE_PADDING;
+ break;
+ case CUDNN_RESAMPLE_AVGPOOL_INCLUDE_PADDING:
+ mode = cudnn_frontend::ResampleMode_t::AVGPOOL_INCLUDE_PADDING;
+ break;
+#else
+ case CUDNN_RESAMPLE_AVGPOOL:
+ mode = cudnn_frontend::ResampleMode_t::AVGPOOL_INCLUDE_PADDING;
+ break;
+#endif
+ case CUDNN_RESAMPLE_BILINEAR:
+ mode = cudnn_frontend::ResampleMode_t::BILINEAR;
+ break;
+ case CUDNN_RESAMPLE_NEAREST:
+ mode = cudnn_frontend::ResampleMode_t::NEAREST;
+ break;
+ case CUDNN_RESAMPLE_MAXPOOL:
+ mode = cudnn_frontend::ResampleMode_t::MAXPOOL;
+ break;
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ break;
+#endif
+ }
+}
+
+// To be deprecated. Only exists as setNormalizationMode(cudnnBackendNormMode_t) requires it.
+static inline void
+convert_from_cudnn_type(cudnnBackendNormMode_t const cudnn_mode, cudnn_frontend::NormMode_t& mode) {
+ mode = NormMode_t::NOT_SET;
+ switch (cudnn_mode) {
+ case CUDNN_LAYER_NORM:
+ mode = NormMode_t::LAYER_NORM;
+ break;
+ case CUDNN_INSTANCE_NORM:
+ mode = NormMode_t::INSTANCE_NORM;
+ break;
+ case CUDNN_BATCH_NORM:
+ mode = NormMode_t::BATCH_NORM;
+ break;
+ case CUDNN_GROUP_NORM:
+ mode = NormMode_t::GROUP_NORM;
+ break;
+
+#if (CUDNN_VERSION >= 8906)
+ case CUDNN_RMS_NORM:
+ mode = NormMode_t::RMS_NORM;
+ break;
+#endif
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ break;
+#endif
+ }
+}
+
+// To be deprecated. Only exists as setNormFwdPhase(cudnnBackendNormFwdPhase_t) requires it.
+static inline void
+convert_from_cudnn_type(cudnnBackendNormFwdPhase_t const cudnn_mode, cudnn_frontend::NormFwdPhase_t& mode) {
+ mode = NormFwdPhase_t::NOT_SET;
+ switch (cudnn_mode) {
+ case CUDNN_NORM_FWD_INFERENCE:
+ mode = NormFwdPhase_t::INFERENCE;
+ break;
+ case CUDNN_NORM_FWD_TRAINING:
+ mode = NormFwdPhase_t::TRAINING;
+ break;
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ break;
+#endif
+ }
+}
+
+#if (CUDNN_VERSION >= 92200)
+// To be deprecated. Only exists as setReshapeMode(cudnnBackendReshapeMode_t) requires it.
+static inline void
+convert_from_cudnn_type(cudnnBackendReshapeMode_t const cudnn_mode, cudnn_frontend::ReshapeMode_t& mode) {
+ mode = ReshapeMode_t::NOT_SET;
+ switch (cudnn_mode) {
+ case CUDNN_RESHAPE_VIEW_ONLY:
+ mode = ReshapeMode_t::VIEW_ONLY;
+ break;
+ case CUDNN_RESHAPE_LOGICAL:
+ mode = ReshapeMode_t::LOGICAL;
+ break;
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ break;
+#endif
+ }
+}
+#endif
+
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::TensorReordering_t const mode, cudnnBackendTensorReordering_t& cudnn_mode) {
+ switch (mode) {
+ case cudnn_frontend::TensorReordering_t::NONE:
+ cudnn_mode = CUDNN_TENSOR_REORDERING_NONE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case cudnn_frontend::TensorReordering_t::INT8x32:
+ cudnn_mode = CUDNN_TENSOR_REORDERING_INT8x32;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case cudnn_frontend::TensorReordering_t::F16x16:
+#if CUDNN_VERSION >= 8800
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ if (get_backend_version() >= 8800) {
+ cudnn_mode = CUDNN_TENSOR_REORDERING_F16x16;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ } else if (get_backend_version() >= 8700) {
+ cudnn_mode = CUDNN_TENSOR_REORDERING_NONE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ } else {
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+ }
+#endif
+ cudnn_mode = CUDNN_TENSOR_REORDERING_F16x16;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#elif CUDNN_VERSION >= 8700
+ cudnn_mode = CUDNN_TENSOR_REORDERING_NONE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#else
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ case cudnn_frontend::TensorReordering_t::F8_128x4:
+#if CUDNN_VERSION >= 90700
+ cudnn_mode = CUDNN_TENSOR_REORDERING_F8_128x4;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#endif
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+// To be deprecated. Only exists as setReorderType(cudnnBackendTensorReordering_t) requires it.
+static inline void
+convert_from_cudnn_type(cudnnBackendTensorReordering_t const cudnn_mode, cudnn_frontend::TensorReordering_t& mode) {
+ mode = cudnn_frontend::TensorReordering_t::NONE;
+ switch (cudnn_mode) {
+ case CUDNN_TENSOR_REORDERING_INT8x32:
+ mode = cudnn_frontend::TensorReordering_t::INT8x32;
+ break;
+#if CUDNN_VERSION >= 8800
+ case CUDNN_TENSOR_REORDERING_F16x16:
+ mode = cudnn_frontend::TensorReordering_t::F16x16;
+ break;
+#endif
+#if CUDNN_VERSION >= 90700
+ case CUDNN_TENSOR_REORDERING_F8_128x4:
+ mode = cudnn_frontend::TensorReordering_t::F8_128x4;
+ break;
+#endif
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ break;
+#endif
+ }
+}
+
+// To be deprecated. Only exists as OperationBuilder_v8(::cudnnBackendDescriptorType_t mode) requires it.
+static inline cudnn_frontend::DescriptorType_t
+convert_from_cudnn_type(cudnnBackendDescriptorType_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case CUDNN_BACKEND_POINTWISE_DESCRIPTOR:
+ return DescriptorType_t::POINTWISE_DESCRIPTOR;
+ case CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR:
+ return DescriptorType_t::CONVOLUTION_DESCRIPTOR;
+ case CUDNN_BACKEND_ENGINE_DESCRIPTOR:
+ return DescriptorType_t::ENGINE_DESCRIPTOR;
+ case CUDNN_BACKEND_ENGINECFG_DESCRIPTOR:
+ return DescriptorType_t::ENGINECFG_DESCRIPTOR;
+ case CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR:
+ return DescriptorType_t::ENGINEHEUR_DESCRIPTOR;
+ case CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR:
+ return DescriptorType_t::EXECUTION_PLAN_DESCRIPTOR;
+ case CUDNN_BACKEND_INTERMEDIATE_INFO_DESCRIPTOR:
+ return DescriptorType_t::INTERMEDIATE_INFO_DESCRIPTOR;
+ case CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR:
+ return DescriptorType_t::KNOB_CHOICE_DESCRIPTOR;
+ case CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR:
+ return DescriptorType_t::KNOB_INFO_DESCRIPTOR;
+ case CUDNN_BACKEND_LAYOUT_INFO_DESCRIPTOR:
+ return DescriptorType_t::LAYOUT_INFO_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_POINTWISE_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_GEN_STATS_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR:
+ return DescriptorType_t::OPERATIONGRAPH_DESCRIPTOR;
+ case CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR:
+ return DescriptorType_t::VARIANT_PACK_DESCRIPTOR;
+ case CUDNN_BACKEND_TENSOR_DESCRIPTOR:
+ return DescriptorType_t::TENSOR_DESCRIPTOR;
+ case CUDNN_BACKEND_MATMUL_DESCRIPTOR:
+ return DescriptorType_t::MATMUL_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_MATMUL_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR;
+ case CUDNN_BACKEND_REDUCTION_DESCRIPTOR:
+ return DescriptorType_t::REDUCTION_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_REDUCTION_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR;
+ case CUDNN_BACKEND_RESAMPLE_DESCRIPTOR:
+ return DescriptorType_t::RESAMPLE_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_RESAMPLE_FWD_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_CONCAT_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_SIGNAL_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_SIGNAL_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_NORM_FORWARD_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_NORM_BACKWARD_DESCRIPTOR;
+#if (CUDNN_VERSION >= 8600)
+ case CUDNN_BACKEND_OPERATION_RESAMPLE_BWD_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_RESAMPLE_BWD_DESCRIPTOR;
+#endif
+#if (CUDNN_VERSION >= 8700)
+ case CUDNN_BACKEND_OPERATION_RESHAPE_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_RESHAPE_DESCRIPTOR;
+ case CUDNN_BACKEND_RNG_DESCRIPTOR:
+ return DescriptorType_t::RNG_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_RNG_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_RNG_DESCRIPTOR;
+#endif
+
+#if (CUDNN_VERSION >= 90500)
+ case CUDNN_BACKEND_OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_PAGED_CACHE_LOAD_DESCRIPTOR;
+#endif
+#if (CUDNN_VERSION >= 90700) // TODO: v9.99 is new feature branch; switch to release branch when ready
+ case CUDNN_BACKEND_OPERATION_BLOCK_SCALE_QUANTIZE_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_BLOCK_SCALE_QUANTIZE_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_BLOCK_SCALE_DEQUANTIZE_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_BLOCK_SCALE_DEQUANTIZE_DESCRIPTOR;
+#endif
+#if (CUDNN_VERSION >= 91500)
+ case CUDNN_BACKEND_OPERATION_MOE_GROUPED_MATMUL_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_MOE_GROUPED_MATMUL_DESCRIPTOR;
+#endif
+#if (CUDNN_VERSION >= 92200)
+ case CUDNN_BACKEND_OPERATION_MOE_GROUPED_MATMUL_BWD_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_MOE_GROUPED_MATMUL_BWD_DESCRIPTOR;
+#endif
+
+#if (CUDNN_VERSION >= 92200)
+ case CUDNN_BACKEND_OPERATION_TRANSPOSE_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_TRANSPOSE_DESCRIPTOR;
+ case CUDNN_BACKEND_OPERATION_SLICE_DESCRIPTOR:
+ return DescriptorType_t::OPERATION_SLICE_DESCRIPTOR;
+#endif
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return DescriptorType_t::NOT_SET;
+ break;
+#endif
+ }
+ return DescriptorType_t::NOT_SET;
+}
+
+// To be deprecated. Only exists as setPointwiseMode(cudnnPointwiseMode_t mode) requires it.
+static inline cudnn_frontend::PointwiseMode_t
+convert_from_cudnn_type(cudnnPointwiseMode_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case CUDNN_POINTWISE_ADD:
+ return PointwiseMode_t::ADD;
+ case CUDNN_POINTWISE_MUL:
+ return PointwiseMode_t::MUL;
+ case CUDNN_POINTWISE_SQRT:
+ return PointwiseMode_t::SQRT;
+ case CUDNN_POINTWISE_MAX:
+ return PointwiseMode_t::MAX;
+ case CUDNN_POINTWISE_MIN:
+ return PointwiseMode_t::MIN;
+ case CUDNN_POINTWISE_RELU_FWD:
+ return PointwiseMode_t::RELU_FWD;
+ case CUDNN_POINTWISE_TANH_FWD:
+ return PointwiseMode_t::TANH_FWD;
+ case CUDNN_POINTWISE_SIGMOID_FWD:
+ return PointwiseMode_t::SIGMOID_FWD;
+ case CUDNN_POINTWISE_ELU_FWD:
+ return PointwiseMode_t::ELU_FWD;
+ case CUDNN_POINTWISE_GELU_FWD:
+ return PointwiseMode_t::GELU_FWD;
+ case CUDNN_POINTWISE_SOFTPLUS_FWD:
+ return PointwiseMode_t::SOFTPLUS_FWD;
+ case CUDNN_POINTWISE_SWISH_FWD:
+ return PointwiseMode_t::SWISH_FWD;
+ case CUDNN_POINTWISE_RELU_BWD:
+ return PointwiseMode_t::RELU_BWD;
+ case CUDNN_POINTWISE_TANH_BWD:
+ return PointwiseMode_t::TANH_BWD;
+ case CUDNN_POINTWISE_SIGMOID_BWD:
+ return PointwiseMode_t::SIGMOID_BWD;
+ case CUDNN_POINTWISE_ELU_BWD:
+ return PointwiseMode_t::ELU_BWD;
+ case CUDNN_POINTWISE_GELU_BWD:
+ return PointwiseMode_t::GELU_BWD;
+ case CUDNN_POINTWISE_SOFTPLUS_BWD:
+ return PointwiseMode_t::SOFTPLUS_BWD;
+ case CUDNN_POINTWISE_SWISH_BWD:
+ return PointwiseMode_t::SWISH_BWD;
+ case CUDNN_POINTWISE_DIV:
+ return PointwiseMode_t::DIV;
+ case CUDNN_POINTWISE_ADD_SQUARE:
+ return PointwiseMode_t::ADD_SQUARE;
+ case CUDNN_POINTWISE_EXP:
+ return PointwiseMode_t::EXP;
+ case CUDNN_POINTWISE_SUB:
+ return PointwiseMode_t::SUB;
+ case CUDNN_POINTWISE_CMP_EQ:
+ return PointwiseMode_t::CMP_EQ;
+ case CUDNN_POINTWISE_CMP_NEQ:
+ return PointwiseMode_t::CMP_NEQ;
+ case CUDNN_POINTWISE_CMP_GT:
+ return PointwiseMode_t::CMP_GT;
+ case CUDNN_POINTWISE_CMP_GE:
+ return PointwiseMode_t::CMP_GE;
+ case CUDNN_POINTWISE_CMP_LT:
+ return PointwiseMode_t::CMP_LT;
+ case CUDNN_POINTWISE_CMP_LE:
+ return PointwiseMode_t::CMP_LE;
+ case CUDNN_POINTWISE_LOGICAL_AND:
+ return PointwiseMode_t::LOGICAL_AND;
+ case CUDNN_POINTWISE_LOGICAL_OR:
+ return PointwiseMode_t::LOGICAL_OR;
+ case CUDNN_POINTWISE_LOGICAL_NOT:
+ return PointwiseMode_t::LOGICAL_NOT;
+ case CUDNN_POINTWISE_LOG:
+ return PointwiseMode_t::LOG;
+ case CUDNN_POINTWISE_NEG:
+ return PointwiseMode_t::NEG;
+ case CUDNN_POINTWISE_MOD:
+ return PointwiseMode_t::MOD;
+ case CUDNN_POINTWISE_POW:
+ return PointwiseMode_t::POW;
+ case CUDNN_POINTWISE_ABS:
+ return PointwiseMode_t::ABS;
+ case CUDNN_POINTWISE_CEIL:
+ return PointwiseMode_t::CEIL;
+ case CUDNN_POINTWISE_COS:
+ return PointwiseMode_t::COS;
+ case CUDNN_POINTWISE_FLOOR:
+ return PointwiseMode_t::FLOOR;
+ case CUDNN_POINTWISE_RSQRT:
+ return PointwiseMode_t::RSQRT;
+ case CUDNN_POINTWISE_SIN:
+ return PointwiseMode_t::SIN;
+ case CUDNN_POINTWISE_TAN:
+ return PointwiseMode_t::TAN;
+ case CUDNN_POINTWISE_GEN_INDEX:
+ return PointwiseMode_t::GEN_INDEX;
+ case CUDNN_POINTWISE_BINARY_SELECT:
+ return PointwiseMode_t::BINARY_SELECT;
+ case CUDNN_POINTWISE_ERF:
+ return PointwiseMode_t::ERF;
+ case CUDNN_POINTWISE_IDENTITY:
+ return PointwiseMode_t::IDENTITY;
+ case CUDNN_POINTWISE_GELU_APPROX_TANH_BWD:
+ return PointwiseMode_t::GELU_APPROX_TANH_BWD;
+ case CUDNN_POINTWISE_GELU_APPROX_TANH_FWD:
+ return PointwiseMode_t::GELU_APPROX_TANH_FWD;
+#if (CUDNN_VERSION >= 8900)
+ case CUDNN_POINTWISE_RECIPROCAL:
+ return PointwiseMode_t::RECIPROCAL;
+#endif
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return PointwiseMode_t::NOT_SET;
+#endif
+ }
+ return PointwiseMode_t::NOT_SET;
+}
+
+// To be deprecated. Only exists as setDataType(cudnnDataType_t mode) requires it.
+static inline cudnn_frontend::DataType_t
+convert_from_cudnn_type(cudnnDataType_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case CUDNN_DATA_FLOAT:
+ return DataType_t::FLOAT;
+ case CUDNN_DATA_DOUBLE:
+ return DataType_t::DOUBLE;
+ case CUDNN_DATA_HALF:
+ return DataType_t::HALF;
+ case CUDNN_DATA_INT8:
+ return DataType_t::INT8;
+ case CUDNN_DATA_INT32:
+ return DataType_t::INT32;
+ case CUDNN_DATA_INT8x4:
+ return DataType_t::INT8x4;
+ case CUDNN_DATA_UINT8:
+ return DataType_t::UINT8;
+ case CUDNN_DATA_UINT8x4:
+ return DataType_t::UINT8x4;
+ case CUDNN_DATA_INT8x32:
+ return DataType_t::INT8x32;
+ case CUDNN_DATA_BFLOAT16:
+ return DataType_t::BFLOAT16;
+ case CUDNN_DATA_INT64:
+ return DataType_t::INT64;
+ case CUDNN_DATA_BOOLEAN:
+ return DataType_t::BOOLEAN;
+#if (CUDNN_VERSION >= 93000)
+ case CUDNN_DATA_BYTE_BOOLEAN:
+ return DataType_t::BYTE_BOOLEAN;
+#endif
+#if (CUDNN_VERSION >= 8600)
+ case CUDNN_DATA_FP8_E4M3:
+ return DataType_t::FP8_E4M3;
+ case CUDNN_DATA_FP8_E5M2:
+ return DataType_t::FP8_E5M2;
+#endif
+#if (CUDNN_VERSION >= 8700)
+ case CUDNN_DATA_FAST_FLOAT_FOR_FP8:
+ return DataType_t::FAST_FLOAT_FOR_FP8;
+#endif
+#if (CUDNN_VERSION >= 90700)
+ case CUDNN_DATA_FP8_E8M0:
+ return DataType_t::FP8_E8M0;
+#endif
+#if (CUDNN_VERSION >= 90700)
+ case CUDNN_DATA_FP4_E2M1:
+ return DataType_t::FP4_E2M1;
+#endif
+#if (CUDNN_VERSION >= 91100)
+ case CUDNN_DATA_INT4:
+ return DataType_t::INT4;
+#endif
+#if (CUDNN_VERSION >= 91400)
+ case CUDNN_DATA_COMPLEX_FP32:
+ return DataType_t::COMPLEX_FP32;
+ case CUDNN_DATA_COMPLEX_FP64:
+ return DataType_t::COMPLEX_FP64;
+#endif
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return DataType_t::NOT_SET;
+#endif
+ }
+ return DataType_t::NOT_SET;
+}
+
+static size_t
+get_element_size_in_bits(cudnn_frontend::DataType_t datatype) {
+ switch (datatype) {
+ case DataType_t::INT8x32:
+ return 256;
+ break;
+#if (CUDNN_VERSION >= 91400)
+ case DataType_t::COMPLEX_FP64:
+ return 128;
+ break;
+#endif
+ case DataType_t::DOUBLE:
+ case DataType_t::INT64:
+#if (CUDNN_VERSION >= 91400)
+ case DataType_t::COMPLEX_FP32:
+#endif
+ return 64;
+ break;
+ case DataType_t::FLOAT:
+ case DataType_t::INT32:
+ case DataType_t::INT8x4:
+ case DataType_t::UINT8x4:
+ return 32;
+ break;
+ case DataType_t::HALF:
+ case DataType_t::BFLOAT16:
+ return 16;
+ break;
+ case DataType_t::INT8:
+ case DataType_t::UINT8:
+#if (CUDNN_VERSION >= 8600)
+ case DataType_t::FP8_E4M3:
+ case DataType_t::FP8_E5M2:
+#endif
+#if (CUDNN_VERSION >= 8700)
+ case DataType_t::FAST_FLOAT_FOR_FP8:
+#endif
+#if (CUDNN_VERSION >= 90700)
+ case DataType_t::FP8_E8M0:
+#endif
+ return 8;
+ break;
+#if (CUDNN_VERSION >= 90700)
+ case DataType_t::FP4_E2M1:
+#if (CUDNN_VERSION >= 91100)
+ case DataType_t::INT4:
+#endif
+ return 4;
+#endif
+ case DataType_t::BOOLEAN:
+ return 1;
+ break;
+ case DataType_t::BYTE_BOOLEAN:
+ return 8;
+ break;
+ default:
+ return 0;
+ break;
+ }
+}
+
+// To be deprecated. Only exists as setReductionOp(cudnnReduceTensorOp_t mode) requires it.
+static inline cudnn_frontend::ReductionMode_t
+convert_from_cudnn_type(cudnnReduceTensorOp_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case CUDNN_REDUCE_TENSOR_ADD:
+ return ReductionMode_t::ADD;
+ case CUDNN_REDUCE_TENSOR_MUL:
+ return ReductionMode_t::MUL;
+ case CUDNN_REDUCE_TENSOR_MIN:
+ return ReductionMode_t::MIN;
+ case CUDNN_REDUCE_TENSOR_MAX:
+ return ReductionMode_t::MAX;
+ case CUDNN_REDUCE_TENSOR_AMAX:
+ return ReductionMode_t::AMAX;
+ case CUDNN_REDUCE_TENSOR_AVG:
+ return ReductionMode_t::AVG;
+ case CUDNN_REDUCE_TENSOR_NORM1:
+ return ReductionMode_t::NORM1;
+ case CUDNN_REDUCE_TENSOR_NORM2:
+ return ReductionMode_t::NORM2;
+ case CUDNN_REDUCE_TENSOR_MUL_NO_ZEROS:
+ return ReductionMode_t::MUL_NO_ZEROS;
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return ReductionMode_t::NOT_SET;
+#endif
+ }
+ return ReductionMode_t::NOT_SET;
+}
+
+#if (CUDNN_VERSION >= 8700)
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::RngDistribution_t const mode, cudnnRngDistribution_t& cudnn_mode) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(8700, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+
+ switch (mode) {
+ case RngDistribution_t::BERNOULLI:
+ cudnn_mode = CUDNN_RNG_DISTRIBUTION_BERNOULLI;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case RngDistribution_t::UNIFORM:
+ cudnn_mode = CUDNN_RNG_DISTRIBUTION_UNIFORM;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case RngDistribution_t::NORMAL:
+ cudnn_mode = CUDNN_RNG_DISTRIBUTION_NORMAL;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+// To be deprecated. Only exists as setRngDistribution(cudnnRngDistribution_t mode) requires it.
+static inline cudnn_frontend::RngDistribution_t
+convert_from_cudnn_type(cudnnRngDistribution_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case CUDNN_RNG_DISTRIBUTION_BERNOULLI:
+ return RngDistribution_t::BERNOULLI;
+ case CUDNN_RNG_DISTRIBUTION_UNIFORM:
+ return RngDistribution_t::UNIFORM;
+ case CUDNN_RNG_DISTRIBUTION_NORMAL:
+ return RngDistribution_t::NORMAL;
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return RngDistribution_t::NOT_SET;
+#endif
+ }
+ return RngDistribution_t::NOT_SET;
+}
+#endif
+
+#if (CUDNN_VERSION >= 91500)
+static inline cudnnStatus_t
+convert_to_cudnn_type(cudnn_frontend::MoeGroupedMatmulMode_t const mode, cudnnMoeGroupedMatmulMode_t& cudnn_mode) {
+ NV_CUDNN_FE_DYNAMIC_CHECK_CUDNN_BACKEND_VERSION(91500, cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE);
+ switch (mode) {
+ case MoeGroupedMatmulMode_t::NONE:
+ cudnn_mode = CUDNN_MOE_GROUPED_MATMUL_MODE_NONE;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case MoeGroupedMatmulMode_t::GATHER:
+ cudnn_mode = CUDNN_MOE_GROUPED_MATMUL_MODE_GATHER;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+ case MoeGroupedMatmulMode_t::SCATTER:
+ cudnn_mode = CUDNN_MOE_GROUPED_MATMUL_MODE_SCATTER;
+ return cudnnStatus_t::CUDNN_STATUS_SUCCESS;
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+#endif
+ }
+ return cudnnStatus_t::CUDNN_STATUS_INVALID_VALUE;
+}
+
+static inline cudnn_frontend::MoeGroupedMatmulMode_t
+convert_from_cudnn_type(cudnnMoeGroupedMatmulMode_t const cudnn_mode) {
+ switch (cudnn_mode) {
+ case CUDNN_MOE_GROUPED_MATMUL_MODE_NONE:
+ return MoeGroupedMatmulMode_t::NONE;
+ case CUDNN_MOE_GROUPED_MATMUL_MODE_GATHER:
+ return MoeGroupedMatmulMode_t::GATHER;
+ case CUDNN_MOE_GROUPED_MATMUL_MODE_SCATTER:
+ return MoeGroupedMatmulMode_t::SCATTER;
+#ifndef NO_DEFAULT_IN_SWITCH
+ default:
+ return MoeGroupedMatmulMode_t::NOT_SET;
+#endif
+ }
+ return MoeGroupedMatmulMode_t::NOT_SET;
+}
+#endif
+
+std::string static get_engine_tag(ManagedOpaqueDescriptor const config) {
+ std::stringstream tag{""};
+ ManagedOpaqueDescriptor extractedEngine = make_shared_backend_pointer(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ auto status = extractedEngine->get_status();
+
+ cudnnBackendDescriptor_t extractedEngine_ = extractedEngine->get_backend_descriptor();
+ int64_t elemCount = 0;
+ status = detail::get_attribute(config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_ENGINE,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &elemCount,
+ &extractedEngine_);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return "INVALID_ENGINE_NAME_CFG";
+ }
+
+ int64_t engineId = 0, numKnobs = 0;
+
+ std::array<ManagedOpaqueDescriptor, CUDNN_KNOB_TYPE_COUNTS> extractedKnobs{{nullptr}};
+ for (auto& knob : extractedKnobs) {
+ knob = make_shared_backend_pointer(CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR);
+ status = knob->get_status();
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return "INVALID_ENGINE_NAME_KNOB";
+ }
+ }
+
+ std::array<cudnnBackendDescriptor_t, CUDNN_KNOB_TYPE_COUNTS> extractedKnobs_{{nullptr}};
+ for (std::uint32_t i = 0; i < extractedKnobs.size(); i++) {
+ extractedKnobs_[i] = extractedKnobs[i]->get_backend_descriptor();
+ }
+
+ status = detail::get_attribute(
+ extractedEngine_, CUDNN_ATTR_ENGINE_GLOBAL_INDEX, CUDNN_TYPE_INT64, 1, &elemCount, &engineId);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return "INVALID_ENGINE_NAME_IDX";
+ }
+ tag << "eng" << engineId;
+
+ status = detail::get_attribute(config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_KNOB_CHOICES,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ CUDNN_KNOB_TYPE_COUNTS,
+ &numKnobs,
+ &(extractedKnobs_[0]));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return "INVALID_ENGINE_NAME_KNOB_QUERY";
+ }
+ if (numKnobs > CUDNN_KNOB_TYPE_COUNTS) {
+ return "INVALID_ENGINE_NAME_KNOB_COUNT";
+ }
+
+ std::vector<std::pair<cudnnBackendKnobType_t, int64_t>> knob_choices;
+ knob_choices.reserve(static_cast<size_t>(numKnobs));
+ for (size_t idx = 0; idx < static_cast<size_t>(numKnobs); ++idx) {
+ const cudnnBackendDescriptor_t& knob = extractedKnobs_[idx];
+ cudnnBackendKnobType_t type = CUDNN_KNOB_TYPE_COUNTS;
+ int64_t choice = -2;
+ status = detail::get_attribute(knob, CUDNN_ATTR_KNOB_CHOICE_KNOB_TYPE, CUDNN_TYPE_KNOB_TYPE, 1, nullptr, &type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return "INVALID_ENGINE_NAME_KNOB_CHOICE_KNOB_TYPE";
+ }
+ status = detail::get_attribute(knob, CUDNN_ATTR_KNOB_CHOICE_KNOB_VALUE, CUDNN_TYPE_INT64, 1, nullptr, &choice);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return "INVALID_ENGINE_NAME_KNOB_CHOICE_KNOB_VALUE";
+ }
+ knob_choices.emplace_back(type, choice);
+ }
+ // Sort by knob type so the tag is a deterministic function of the engine
+ // config -- the knob-choice array order differs between the heuristics path
+ // and create_execution_plan (which iterates an unordered_map), but the
+ // engine + knob values are identical.
+ std::sort(knob_choices.begin(), knob_choices.end());
+ for (auto const& [type, choice] : knob_choices) {
+ tag << "_k" << type << "=" << choice;
+ }
+ return tag.str();
+}
+
+// Structured counterpart of get_engine_tag(): engine global index + (knob type,
+// value) choices instead of a formatted string. Reads the same backend attributes.
+cudnnStatus_t static get_engine_id_and_knobs(ManagedOpaqueDescriptor const config,
+ int64_t& engineId,
+ std::vector<std::pair<cudnnBackendKnobType_t, int64_t>>& knobs) {
+ engineId = -1;
+ knobs.clear();
+
+ ManagedOpaqueDescriptor extractedEngine = make_shared_backend_pointer(CUDNN_BACKEND_ENGINE_DESCRIPTOR);
+ if (extractedEngine->get_status() != CUDNN_STATUS_SUCCESS) {
+ return extractedEngine->get_status();
+ }
+ cudnnBackendDescriptor_t extractedEngine_ = extractedEngine->get_backend_descriptor();
+
+ int64_t elemCount = 0;
+ auto status = detail::get_attribute(config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_ENGINE,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ 1,
+ &elemCount,
+ &extractedEngine_);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return status;
+ }
+
+ std::array<ManagedOpaqueDescriptor, CUDNN_KNOB_TYPE_COUNTS> extractedKnobs{{nullptr}};
+ for (auto& knob : extractedKnobs) {
+ knob = make_shared_backend_pointer(CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR);
+ if (knob->get_status() != CUDNN_STATUS_SUCCESS) {
+ return knob->get_status();
+ }
+ }
+ std::array<cudnnBackendDescriptor_t, CUDNN_KNOB_TYPE_COUNTS> extractedKnobs_{{nullptr}};
+ for (std::uint32_t i = 0; i < extractedKnobs.size(); i++) {
+ extractedKnobs_[i] = extractedKnobs[i]->get_backend_descriptor();
+ }
+
+ status = detail::get_attribute(
+ extractedEngine_, CUDNN_ATTR_ENGINE_GLOBAL_INDEX, CUDNN_TYPE_INT64, 1, &elemCount, &engineId);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return status;
+ }
+
+ int64_t numKnobs = 0;
+ status = detail::get_attribute(config->get_backend_descriptor(),
+ CUDNN_ATTR_ENGINECFG_KNOB_CHOICES,
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
+ CUDNN_KNOB_TYPE_COUNTS,
+ &numKnobs,
+ &(extractedKnobs_[0]));
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return status;
+ }
+ if (numKnobs > CUDNN_KNOB_TYPE_COUNTS) {
+ return CUDNN_STATUS_NOT_SUPPORTED;
+ }
+
+ knobs.reserve(static_cast<size_t>(numKnobs));
+ for (size_t idx = 0; idx < static_cast<size_t>(numKnobs); ++idx) {
+ const cudnnBackendDescriptor_t& knob = extractedKnobs_[idx];
+ cudnnBackendKnobType_t type = CUDNN_KNOB_TYPE_COUNTS;
+ int64_t choice = -2;
+ status = detail::get_attribute(knob, CUDNN_ATTR_KNOB_CHOICE_KNOB_TYPE, CUDNN_TYPE_KNOB_TYPE, 1, nullptr, &type);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return status;
+ }
+ status = detail::get_attribute(knob, CUDNN_ATTR_KNOB_CHOICE_KNOB_VALUE, CUDNN_TYPE_INT64, 1, nullptr, &choice);
+ if (status != CUDNN_STATUS_SUCCESS) {
+ return status;
+ }
+ knobs.emplace_back(type, choice);
+ }
+ return CUDNN_STATUS_SUCCESS;
+}
+
+} // namespace detail
+
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend_version.h b/deps/cudnn-frontend/include/cudnn_frontend_version.h
new file mode 100644
index 0000000..bda15d0
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend_version.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#define CUDNN_FRONTEND_MAJOR_VERSION 1
+#define CUDNN_FRONTEND_MINOR_VERSION 25
+#define CUDNN_FRONTEND_PATCH_VERSION 0
+#define CUDNN_FRONTEND_VERSION \
+ ((CUDNN_FRONTEND_MAJOR_VERSION * 10000) + (CUDNN_FRONTEND_MINOR_VERSION * 100) + CUDNN_FRONTEND_PATCH_VERSION)