From dc6b87c596516e99e31ef82e4f31b690e6561a15 Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 16:02:54 -0800 Subject: [PATCH 01/18] [Common] Make public C API headers valid C Fix the public headers so they compile as C: - Typedef every NVTE enum and struct and include stdbool.h. - Replace C++-only members of NVTETensorPack with NVTE_TENSOR_PACK_MAX_SIZE. - Take NVTETensor arrays instead of std::vector in nvte_delayed_scaling_recipe_amax_and_scale_update_after_reduction. - Take tensors by value instead of by reference in context-parallel attention functions. - Give C linkage to nvte_cudnn_handle_init, nvte_cublas_handle_init, nvte_built_with_cublasmp, and the permutation functions. - Remove default arguments, use (void) prototypes, guard NVTE_Activation_Type for C++, and drop unneeded CUDA includes. Add a test that calls every C API function from a C translation unit compiled with strict flags, so building checks that the headers are valid C and linking checks that the functions have C linkage. A CTest checks that the test covers every function declared in the headers. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tim Moon --- tests/cpp/CMakeLists.txt | 12 +- tests/cpp/util/CMakeLists.txt | 13 + tests/cpp/util/check_c_api_coverage.py | 37 ++ tests/cpp/util/test_c_api.c | 478 ++++++++++++++++++ tests/cpp/util/test_c_api.cpp | 26 + .../comm_gemm_overlap/comm_gemm_overlap.cpp | 2 +- transformer_engine/common/cudnn_utils.cpp | 4 +- .../common/fused_attn/context_parallel.cu | 30 +- .../common/gemm/cublaslt_gemm.cu | 6 +- .../include/transformer_engine/activation.h | 2 + .../include/transformer_engine/comm_gemm.h | 10 +- .../transformer_engine/comm_gemm_overlap.h | 10 +- .../common/include/transformer_engine/cudnn.h | 12 +- .../include/transformer_engine/fused_attn.h | 70 +-- .../common/include/transformer_engine/gemm.h | 27 +- .../include/transformer_engine/multi_stream.h | 4 +- .../include/transformer_engine/nvfp4/4over6.h | 4 +- .../include/transformer_engine/permutation.h | 12 +- .../include/transformer_engine/recipe.h | 11 +- .../include/transformer_engine/softmax.h | 3 - .../transformer_engine/transformer_engine.h | 52 +- .../common/include/transformer_engine/utils.h | 2 +- .../common/libtransformer_engine.version | 2 - .../common/recipe/delayed_scaling.cu | 7 +- .../common/transformer_engine.cpp | 6 +- .../pytorch/csrc/extensions/recipe.cpp | 9 +- 26 files changed, 713 insertions(+), 138 deletions(-) create mode 100644 tests/cpp/util/check_c_api_coverage.py create mode 100644 tests/cpp/util/test_c_api.c create mode 100644 tests/cpp/util/test_c_api.cpp diff --git a/tests/cpp/CMakeLists.txt b/tests/cpp/CMakeLists.txt index 477ed522d27..f6d5aaa6279 100644 --- a/tests/cpp/CMakeLists.txt +++ b/tests/cpp/CMakeLists.txt @@ -17,7 +17,7 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CUDA_STANDARD 17) set(CMAKE_CUDA_STANDARD_REQUIRED ON) -project(transformer_engine_tests LANGUAGES CUDA CXX) +project(transformer_engine_tests LANGUAGES C CUDA CXX) add_subdirectory(../../3rdparty/googletest ${PROJECT_BINARY_DIR}/googletest) @@ -40,7 +40,17 @@ include_directories(../../transformer_engine/common) include_directories(../../transformer_engine) include_directories(${CMAKE_SOURCE_DIR}) +# Configure dependencies find_package(CUDAToolkit REQUIRED) +find_package(Python COMPONENTS Interpreter REQUIRED) +find_path(NCCL_INCLUDE_DIR + NAMES nccl.h + HINTS "${Python_SITEARCH}/nvidia/nccl" + "/opt/nvidia/nccl" + "/usr/local/nccl" + PATH_SUFFIXES include + REQUIRED) +include_directories(SYSTEM ${NCCL_INCLUDE_DIR}) include(${CMAKE_SOURCE_DIR}/../../transformer_engine/common/cmake/cuDNN.cmake) add_subdirectory(operator) diff --git a/tests/cpp/util/CMakeLists.txt b/tests/cpp/util/CMakeLists.txt index 24acec658c6..6b17b8816e7 100644 --- a/tests/cpp/util/CMakeLists.txt +++ b/tests/cpp/util/CMakeLists.txt @@ -4,6 +4,8 @@ add_executable(test_util test_activation_table.cu + test_c_api.c + test_c_api.cpp test_nvrtc.cpp test_string.cpp ../test_common.cu) @@ -21,6 +23,17 @@ target_link_libraries(test_util PUBLIC Threads::Threads) target_compile_options(test_util PRIVATE -O2 -fopenmp) +# test_c_api.c checks that the public headers are valid C, so compile it strictly. +set_source_files_properties(test_c_api.c PROPERTIES + COMPILE_OPTIONS "-pedantic-errors;-Werror;-Wall;-Wextra;-Wstrict-prototypes") +set_target_properties(test_util PROPERTIES C_STANDARD 99 C_STANDARD_REQUIRED ON C_EXTENSIONS OFF) + +# Check that test_c_api.c calls every function in the C API. +add_test(NAME CApiCoverage + COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/check_c_api_coverage.py + ${CMAKE_SOURCE_DIR}/../../transformer_engine/common/include/transformer_engine + ${CMAKE_CURRENT_SOURCE_DIR}/test_c_api.c) + include(GoogleTest) # MALLOC_PERTURB_ makes glibc overwrite freed memory, so a destructor that reads a destroyed object # at exit crashes the test process, which ctest reports as a failure, instead of passing silently. diff --git a/tests/cpp/util/check_c_api_coverage.py b/tests/cpp/util/check_c_api_coverage.py new file mode 100644 index 00000000000..2696bd1e96c --- /dev/null +++ b/tests/cpp/util/check_c_api_coverage.py @@ -0,0 +1,37 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Check that test_c_api.c calls every function in the public C API headers.""" + +import pathlib +import re +import sys + +FUNCTION_NAME = re.compile(r"\b(nvte_\w+)\s*\(") +COMMENT = re.compile(r"/\*.*?\*/|//[^\n]*", re.DOTALL) + + +def function_names(path: pathlib.Path) -> set[str]: + """Names of nvte_* functions appearing in a file, excluding comments.""" + return set(FUNCTION_NAME.findall(COMMENT.sub("", path.read_text()))) + + +def main() -> int: + include_dir, test_file = map(pathlib.Path, sys.argv[1:]) + declared = set() + for header in include_dir.rglob("*.h"): + declared |= function_names(header) + called = function_names(test_file) + + missing = sorted(declared - called) + unknown = sorted(called - declared) + if missing: + print(f"Functions not called in {test_file}:\n " + "\n ".join(missing)) + if unknown: + print(f"Functions in {test_file} that are not in the C API:\n " + "\n ".join(unknown)) + return 1 if missing or unknown else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/cpp/util/test_c_api.c b/tests/cpp/util/test_c_api.c new file mode 100644 index 00000000000..93e3d3805eb --- /dev/null +++ b/tests/cpp/util/test_c_api.c @@ -0,0 +1,478 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +/* Calls every function in the Transformer Engine C API from a C translation + * unit. Compiling this file checks that the public headers are valid C, and + * linking it checks that each function is exported with C linkage. The calls + * use placeholder arguments and must never be executed. + * + * When adding a function to the C API, add a call to it here. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void call_every_c_api_function(void); + +void call_every_c_api_function(void) { + NVTEShape shape = {{0}, 0}; + NVTECommWindow window = {NULL, 0, NULL, 0}; + + /* activation.h */ + nvte_gelu(NULL, NULL, NULL); + nvte_group_gelu(NULL, NULL, NULL); + nvte_silu(NULL, NULL, NULL); + nvte_group_silu(NULL, NULL, NULL); + nvte_group_scaled_swiglu(NULL, NULL, NULL, NULL); + nvte_group_scaled_clamped_swiglu(NULL, NULL, NULL, 0, 0, 0, NULL); + nvte_relu(NULL, NULL, NULL); + nvte_group_relu(NULL, NULL, NULL); + nvte_qgelu(NULL, NULL, NULL); + nvte_group_qgelu(NULL, NULL, NULL); + nvte_srelu(NULL, NULL, NULL); + nvte_group_srelu(NULL, NULL, NULL); + nvte_dgelu(NULL, NULL, NULL, NULL); + nvte_group_dgelu(NULL, NULL, NULL, NULL); + nvte_dsilu(NULL, NULL, NULL, NULL); + nvte_group_dsilu(NULL, NULL, NULL, NULL); + nvte_drelu(NULL, NULL, NULL, NULL); + nvte_group_drelu(NULL, NULL, NULL, NULL); + nvte_dqgelu(NULL, NULL, NULL, NULL); + nvte_group_dqgelu(NULL, NULL, NULL, NULL); + nvte_dsrelu(NULL, NULL, NULL, NULL); + nvte_group_dsrelu(NULL, NULL, NULL, NULL); + nvte_glu(NULL, NULL, NULL); + nvte_dglu(NULL, NULL, NULL, NULL); + nvte_geglu(NULL, NULL, NULL); + nvte_swiglu(NULL, NULL, NULL); + nvte_situglu(NULL, NULL, 0, 0, NULL); + nvte_clamped_swiglu(NULL, NULL, 0, 0, NULL); + nvte_clamped_swiglu_v2(NULL, NULL, 0, 0, 0, NULL); + nvte_scaled_swiglu(NULL, NULL, NULL, 0, NULL); + nvte_scaled_situglu(NULL, NULL, NULL, 0, 0, 0, NULL); + nvte_scaled_clamped_swiglu(NULL, NULL, NULL, 0, 0, 0, 0, NULL); + nvte_reglu(NULL, NULL, NULL); + nvte_qgeglu(NULL, NULL, NULL); + nvte_sreglu(NULL, NULL, NULL); + nvte_dgeglu(NULL, NULL, NULL, NULL); + nvte_dswiglu(NULL, NULL, NULL, NULL); + nvte_dsituglu(NULL, NULL, NULL, 0, 0, NULL); + nvte_clamped_dswiglu(NULL, NULL, NULL, 0, 0, NULL); + nvte_clamped_dswiglu_v2(NULL, NULL, NULL, 0, 0, 0, NULL); + nvte_scaled_dswiglu(NULL, NULL, NULL, NULL, NULL, 0, NULL); + nvte_scaled_dsituglu(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL); + nvte_scaled_clamped_dswiglu(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, NULL); + nvte_dreglu(NULL, NULL, NULL, NULL); + nvte_dqgeglu(NULL, NULL, NULL, NULL); + nvte_dsreglu(NULL, NULL, NULL, NULL); + nvte_scaled_srelu(NULL, NULL, NULL, NULL); + nvte_scaled_dsrelu(NULL, NULL, NULL, NULL, NULL, NULL); + + /* cast.h */ + nvte_quantize(NULL, NULL, NULL); + nvte_group_quantize(NULL, NULL, NULL, NULL); + nvte_quantize_noop(NULL, NULL, NULL, NULL); + nvte_quantize_v2(NULL, NULL, NULL, NULL); + nvte_quantize_dbias(NULL, NULL, NULL, NULL, NULL); + nvte_group_quantize_dbias(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_quantize_dbias_dgelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_group_quantize_dbias_dgelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_quantize_dbias_dsilu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_group_quantize_dbias_dsilu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_quantize_dbias_drelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_group_quantize_dbias_drelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_quantize_dbias_dqgelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_group_quantize_dbias_dqgelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_quantize_dbias_dsrelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_group_quantize_dbias_dsrelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_dequantize(NULL, NULL, NULL); + nvte_group_dequantize(NULL, NULL, NULL); + nvte_group_requantize(NULL, NULL, NULL, NULL, NULL); + nvte_multi_tensor_quantize(NULL, NULL, NULL, 0, NULL); + nvte_group_nvfp4_quantize_with_amax(NULL, NULL, NULL, 0, NULL, NULL); + nvte_group_nvfp4_compute_amax(NULL, NULL, NULL, 0, NULL); + + /* cast_transpose_noop.h */ + nvte_transpose_with_noop(NULL, NULL, NULL, NULL); + nvte_cast_transpose_with_noop(NULL, NULL, NULL, NULL); + + /* comm_gemm.h */ + nvte_comm_gemm_ctx_create(NULL, 0, 0); + nvte_comm_gemm_ctx_destroy(NULL); + nvte_all_gather_gemm(NULL, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, 0); + nvte_gemm_reduce_scatter(NULL, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, 0); + nvte_gemm_all_reduce(NULL, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, 0); + nvte_comm_gemm_numroc(NULL, 0); + nvte_comm_gemm_workspace(NULL, NULL); + nvte_cublasmp_version(); + nvte_built_with_cublasmp(); + + /* cudnn.h */ + nvte_cudnn_handle_init(); + + /* dropout.h */ + nvte_dropout_fwd(NULL, NULL, NULL, NULL, 0, NULL); + nvte_dropout_bwd(NULL, NULL, NULL, 0, NULL); + + /* ep.h */ + nvte_ep_initialize(NULL, NULL); + nvte_ep_shutdown(); + nvte_ep_handle_mem_size(NULL); + nvte_ep_prepare(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_ep_dispatch(NULL, NULL, NULL, window, NULL, window, NULL, window, NULL, window, NULL); + nvte_ep_dispatch_v2(NULL, NULL, NULL, window, NULL, window, NULL, window, NULL, window, NULL, + NULL); + nvte_ep_prepare_and_dispatch(NULL, NULL, NULL, window, NULL, window, NULL, window, NULL, window, + NULL, NULL, NULL, NULL); + nvte_ep_combine(NULL, NULL, window, NULL, NULL); + nvte_ep_combine_v2(NULL, NULL, window, NULL, NULL, NULL); + nvte_ep_dispatch_bwd(NULL, NULL, window, NULL, window, NULL, NULL, NULL); + nvte_ep_dispatch_bwd_v2(NULL, NULL, window, NULL, window, NULL, NULL, NULL, NULL); + nvte_ep_combine_bwd(NULL, NULL, window, NULL, window, NULL); + nvte_ep_combine_bwd_v2(NULL, NULL, window, NULL, window, NULL, NULL); + + /* fused_attn.h */ + nvte_get_qkv_layout_group(0); + nvte_get_qkv_format(0); + nvte_get_q_format(0); + nvte_get_kv_format(0); + nvte_create_fused_attn_config(); + nvte_destroy_fused_attn_config(NULL); + nvte_get_fused_attn_config_attribute(NULL, 0, NULL, 0, NULL); + nvte_set_fused_attn_config_attribute(NULL, 0, NULL, 0); + nvte_create_fused_attn_fwd_params(); + nvte_destroy_fused_attn_fwd_params(NULL); + nvte_get_fused_attn_fwd_params_attribute(NULL, 0, NULL, 0, NULL); + nvte_set_fused_attn_fwd_params_attribute(NULL, 0, NULL, 0); + nvte_create_fused_attn_bwd_params(); + nvte_destroy_fused_attn_bwd_params(NULL); + nvte_get_fused_attn_bwd_params_attribute(NULL, 0, NULL, 0, NULL); + nvte_set_fused_attn_bwd_params_attribute(NULL, 0, NULL, 0); + nvte_get_fused_attn_backend_v2(NULL, NULL); + nvte_get_fused_attn_backend(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + nvte_fused_attn_fwd_v2(NULL); + nvte_fused_attn_fwd(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL); + nvte_fused_attn_bwd_v2(NULL); + nvte_fused_attn_bwd(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + NULL, NULL); + nvte_populate_rng_state_async(NULL, NULL, 0, 0, 0, NULL); + nvte_get_runtime_num_segments(NULL, NULL, 0, NULL); + nvte_cu_seqlens_to_actual_seqlens(NULL, NULL, NULL, NULL, NULL); + nvte_extract_seed_and_offset(NULL, 0, NULL, 0, NULL, 0, 0, NULL); + nvte_copy_to_kv_cache(NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, NULL); + nvte_cp_thd_read_half_tensor(NULL, NULL, NULL, 0, NULL); + nvte_cp_thd_second_half_lse_correction(NULL, NULL, NULL, 0, NULL); + nvte_cp_thd_read_second_half_lse(NULL, NULL, NULL, 0, 0, NULL); + nvte_cp_thd_out_correction(NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL); + nvte_cp_thd_grad_correction(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_cp_thd_get_partitioned_indices(NULL, NULL, 0, 0, 0, NULL); + nvte_thd_sequence_order_to_cp_rank_order(NULL, NULL, NULL, 0, 0, NULL); + nvte_thd_cp_rank_order_to_sequence_order(NULL, NULL, NULL, 0, 0, NULL); + nvte_thd_copy_valid_tokens_from_per_split_to_rank_local(NULL, NULL, NULL, NULL, 0, NULL); + nvte_convert_thd_to_bshd(NULL, NULL, NULL, 0, 0, NULL); + nvte_convert_bshd_to_thd(NULL, NULL, NULL, 0, NULL); + nvte_prepare_flash_attn_fwd(NULL, NULL, NULL); + nvte_prepare_flash_attn_bwd(NULL, NULL, NULL, NULL, NULL); + nvte_multi_tensor_transpose_to_bhsd(NULL, NULL, 0, 0, NULL); + nvte_multi_tensor_pad_last_dim(NULL, NULL, 0, NULL); + + /* fused_rope.h */ + nvte_fused_rope_forward(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + NULL); + nvte_fused_rope_backward(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + NULL); + nvte_fused_qkv_rope_forward(NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, NULL); + nvte_fused_qkv_rope_backward(NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, NULL); + nvte_fused_mla_kv_rope_mxfp8(NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL); + + /* fused_router.h */ + nvte_fused_topk_with_score_function_forward(NULL, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, + NULL); + nvte_fused_topk_with_score_function_forward_v2(NULL, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0, + NULL, NULL); + nvte_fused_topk_with_score_function_forward_with_indices(NULL, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, + NULL, NULL, NULL); + nvte_fused_topk_with_score_function_forward_qb_v2(NULL, 0, 0, 0, 0, NULL, NULL, NULL, 0, NULL, + NULL, NULL, NULL, 0, NULL); + nvte_fused_topk_with_score_function_forward_qb_v2_unchecked(NULL, 0, 0, 0, 0, NULL, NULL, NULL, 0, + NULL, NULL, NULL, NULL, 0, NULL); + nvte_fused_topk_with_score_function_forward_qb_with_indices(NULL, 0, 0, 0, 0, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, 0, NULL); + nvte_fused_topk_with_score_function_forward_qb_with_indices_unchecked(NULL, 0, 0, 0, 0, NULL, + NULL, NULL, NULL, NULL, + NULL, NULL, 0, NULL); + nvte_qb_histogram_accumulate(NULL, NULL, NULL, NULL, NULL); + nvte_qb_histogram_accumulate_unchecked(NULL, NULL, NULL, NULL, NULL); + nvte_fused_topk_with_score_function_backward(NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL); + nvte_fused_topk_with_score_function_backward_v2(NULL, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, + NULL); + nvte_fused_topk_with_score_function_backward_with_indices(NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, + NULL, NULL); + nvte_fused_topk_with_aux_loss_scores_is_supported(0, 0, 0, 0, 0); + nvte_fused_topk_with_aux_loss_scores_forward(NULL, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, + NULL, NULL, NULL); + nvte_fused_topk_with_aux_loss_scores_backward(NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL); + nvte_fused_score_for_moe_aux_loss_forward(NULL, 0, 0, 0, 0, NULL, NULL, NULL, NULL); + nvte_fused_score_for_moe_aux_loss_forward_v2(NULL, 0, 0, 0, 0, NULL, NULL, 0, NULL, NULL); + nvte_fused_score_for_moe_aux_loss_backward(NULL, NULL, 0, 0, 0, 0, NULL, NULL); + nvte_fused_moe_aux_loss_forward(NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL); + nvte_fused_moe_aux_loss_forward_graph_safe(NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL); + nvte_fused_moe_aux_loss_forward_v2(NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL); + nvte_fused_moe_aux_loss_forward_graph_safe_v2(NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, + NULL); + nvte_fused_moe_aux_loss_backward(NULL, NULL, 0, 0, NULL, NULL, NULL); + + /* gemm.h */ + nvte_get_cublaslt_build_version(); + nvte_create_matmul_config(); + nvte_get_matmul_config_attribute(NULL, 0, NULL, 0, NULL); + nvte_set_matmul_config_attribute(NULL, 0, NULL, 0); + nvte_destroy_matmul_config(NULL); + nvte_create_grouped_matmul_config(); + nvte_get_grouped_matmul_config_attribute(NULL, 0, NULL, 0, NULL); + nvte_set_grouped_matmul_config_attribute(NULL, 0, NULL, 0); + nvte_destroy_grouped_matmul_config(NULL); + nvte_cublas_gemm(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, 0, 0, NULL); + nvte_cublas_gemm_v2(0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); + nvte_cublas_gemm_strided_batched(0, 0, NULL, NULL, 0, NULL, 0, NULL, NULL, NULL, 0, NULL, NULL, + NULL); + nvte_cublas_gemm_strided_batched_mxfp8(0, 0, NULL, NULL, NULL, 0, NULL, NULL, 0, NULL, NULL, NULL, + 0, NULL, NULL, NULL); + nvte_cublas_gemm_scaled(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, NULL); + nvte_cublas_atomic_gemm(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, 0, 0, NULL, + NULL); + nvte_multi_tensor_gemm(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, NULL, 0, 0, 0, NULL); + nvte_get_grouped_gemm_setup_workspace_size(0); + nvte_convert_int32_to_int64(NULL, NULL, 0, NULL); + nvte_convert_int32_to_int64_with_multiplier(NULL, NULL, 0, 0, NULL); + nvte_compute_grouped_tensor_offsets(NULL, NULL, 0, 0, NULL); + nvte_grouped_gemm(NULL, 0, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); + nvte_grouped_gemm_with_discrete_inputA(NULL, 0, 0, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL); + nvte_grouped_gemm_with_discrete_out(NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, NULL, NULL, NULL, + NULL, NULL); + nvte_grouped_bias_add(NULL, NULL, NULL); + nvte_grouped_scaled_bias_add(NULL, NULL, NULL, NULL); + nvte_cublas_handle_init(); + + /* hadamard_transform.h */ + nvte_hadamard_transform(NULL, NULL, 0, 0, NULL); + nvte_hadamard_transform_amax(NULL, NULL, 0, 0, NULL); + nvte_hadamard_transform_cast_fusion_columnwise(NULL, NULL, NULL, NULL, NULL); + nvte_quantize_with_hadamard_transform(NULL, NULL, NULL, NULL, NULL); + nvte_group_hadamard_transform_amax(NULL, NULL, NULL, 0, 0, 0, NULL); + nvte_group_hadamard_transform_amax_graph_safe(NULL, NULL, 0, 0, NULL); + nvte_group_hadamard_transform_cast_fusion_columnwise(NULL, NULL, NULL, NULL, 0, NULL, NULL); + nvte_group_hadamard_transform_cast_fusion(NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL); + nvte_group_hadamard_transform_cast_fusion_graph_safe(NULL, NULL, NULL, NULL, NULL, NULL); + + /* linear_attention.h */ + nvte_linear_attention_affine_prefix(NULL, NULL, NULL, NULL, NULL, NULL); + + /* multi_stream.h */ + nvte_get_num_compute_streams(); + nvte_get_compute_stream(0); + nvte_get_compute_stream_event(0); + + /* multi_tensor.h */ + nvte_multi_tensor_l2norm_cuda(0, NULL, NULL, 0, 0, NULL, NULL, NULL, NULL, 0, 0, NULL); + nvte_multi_tensor_unscale_l2norm_cuda(0, NULL, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, 0, 0, + NULL); + nvte_multi_tensor_adam_cuda(0, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL); + nvte_multi_tensor_adam_param_remainder_cuda(0, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL); + nvte_multi_tensor_adam_fp8_cuda(0, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL); + nvte_multi_tensor_adam_capturable_cuda(0, NULL, NULL, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, + NULL); + nvte_multi_tensor_adam_capturable_master_cuda(0, NULL, NULL, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, + NULL, NULL); + nvte_multi_tensor_sgd_cuda(0, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL); + nvte_multi_tensor_scale_cuda(0, NULL, NULL, 0, 0, 0, NULL); + nvte_multi_tensor_scale_tensor_cuda(0, NULL, NULL, 0, 0, NULL, NULL); + nvte_multi_tensor_compute_scale_and_scale_inv_cuda(0, NULL, NULL, 0, 0, 0, 0, 0, NULL); + nvte_multi_tensor_compute_scale_inv_e8m0_cuda(0, NULL, 0, 0, NULL); + nvte_group_amax(NULL, NULL, NULL, 0, NULL); + nvte_group_amax_graph_safe(NULL, NULL, NULL); + + /* newton_schulz.h */ + nvte_cusolvermp_ctx_create(NULL, 0, 0); + nvte_cusolvermp_ctx_destroy(NULL); + nvte_newton_schulz(NULL, 0, 0, NULL, 0, NULL, 0, NULL); + + /* normalization.h */ + nvte_layernorm_fwd(NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, 0, 0, NULL); + nvte_layernorm_bwd(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL); + nvte_rmsnorm_fwd(NULL, NULL, 0, NULL, NULL, NULL, 0, 0, NULL); + nvte_rmsnorm_bwd(NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL); + nvte_rmsnorm_bwd_add(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL); + nvte_enable_cudnn_norm_fwd(0); + nvte_enable_cudnn_norm_bwd(0); + nvte_enable_zero_centered_gamma_in_weight_dtype(0); + + /* padding.h */ + nvte_multi_padding(0, NULL, NULL, NULL, NULL); + nvte_multi_unpadding(0, NULL, NULL, NULL, NULL); + + /* permutation.h */ + nvte_permute(NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, NULL); + nvte_unpermute(NULL, NULL, NULL, NULL, 0, 0, 0, NULL); + nvte_device_radix_sort_pairs(NULL, NULL, NULL, NULL, NULL, NULL, 0); + + /* recipe.h */ + nvte_delayed_scaling_recipe_amax_and_scale_update(NULL, NULL, NULL, NULL, NULL, 0, 0, NULL); + nvte_delayed_scaling_recipe_amax_and_scale_update_after_reduction(NULL, NULL, NULL, 0, NULL, 0, 0, + NULL); + nvte_compute_amax(NULL, NULL, NULL); + nvte_compute_amax_with_config(NULL, NULL, NULL, NULL); + nvte_group_compute_amax_with_config(NULL, NULL, NULL, NULL); + nvte_compute_scale_from_amax(NULL, NULL, NULL); + nvte_group_compute_scale_from_amax(NULL, NULL, NULL); + nvte_fp8_block_scaling_compute_partial_amax(NULL, NULL, 0, 0, 0, 0, 0, 0, NULL); + nvte_fp8_block_scaling_partial_cast(NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, NULL); + nvte_mxfp8_scaling_compute_partial_amax(NULL, NULL, NULL, 0, 0, 0, NULL); + nvte_mxfp8_scaling_partial_cast(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL); + nvte_nvfp4_compute_per_tensor_scale(NULL, 0, NULL, 0, 0, NULL, NULL); + nvte_nvfp4_2d_compute_partial_amax(NULL, NULL, 0, 0, 0, 0, 0, 0, NULL); + nvte_nvfp4_2d_partial_cast(NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, NULL); + nvte_nvfp4_2d_partial_cast_v2(NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, NULL); + nvte_nvfp4_expand_scale_to_fp8(NULL, NULL, 0, 0, 0, 0, NULL); + nvte_nvfp4_expand_scale_to_fp8_v2(NULL, NULL, 0, 0, 0, 0, 0, NULL); + nvte_nvfp4_compute_per_block_scale(NULL, NULL, NULL, NULL); + nvte_nvfp4_compute_per_block_scale_v2(NULL, NULL, NULL, 0, NULL); + nvte_nvfp4_fused_scale(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, NULL); + nvte_nvfp4_fused_scale_v2(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL); + nvte_nvfp4_compute_global_scale(NULL, NULL, NULL); + nvte_nvfp4_compute_global_scale_v2(NULL, NULL, 0, NULL); + + /* softmax.h */ + nvte_scaled_softmax_forward(NULL, NULL, 0, NULL); + nvte_scaled_softmax_backward(NULL, NULL, NULL, 0, NULL); + nvte_scaled_masked_softmax_forward(NULL, NULL, NULL, 0, NULL); + nvte_scaled_masked_softmax_backward(NULL, NULL, NULL, 0, NULL); + nvte_scaled_upper_triang_masked_softmax_forward(NULL, NULL, 0, NULL); + nvte_scaled_upper_triang_masked_softmax_backward(NULL, NULL, NULL, 0, NULL); + nvte_scaled_aligned_causal_masked_softmax_forward(NULL, NULL, 0, NULL); + nvte_scaled_aligned_causal_masked_softmax_backward(NULL, NULL, NULL, 0, NULL); + + /* swizzle.h */ + nvte_swizzle_scaling_factors(NULL, NULL, NULL); + nvte_pack_mxfp8_scales_for_batched_gemm(NULL, NULL, 0, 0, NULL); + nvte_pack_mxfp8_columnwise_scales_for_batched_gemm(NULL, NULL, 0, NULL); + nvte_multi_tensor_swizzle_scaling_factors(NULL, NULL, 0, NULL); + nvte_multi_tensor_swizzle_scaling_factors_unchecked(NULL, NULL, 0, NULL); + nvte_unswizzle_scaling_factors(NULL, NULL, NULL); + nvte_multi_tensor_unswizzle_scaling_factors(NULL, NULL, 0, NULL); + nvte_swizzle_block_scaling_to_mxfp8_scaling_factors(NULL, NULL, NULL); + nvte_multi_tensor_swizzle_block_scaling_to_mxfp8_scaling_factors(NULL, NULL, 0, NULL); + nvte_swizzle_grouped_block_scaling_to_mxfp8_scaling_factors(NULL, NULL, NULL); + nvte_get_grouped_block_scaling_to_mxfp8_scale_inv_size(NULL); + nvte_swizzle_grouped_scaling_factors(NULL, NULL, NULL); + nvte_unswizzle_grouped_scaling_factors(NULL, NULL, NULL); + + /* topk.h */ + nvte_topk(NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0); + + /* transformer_engine.h */ + nvte_create_tensor(0); + nvte_create_tensors(0, NULL, 0); + nvte_destroy_tensor(NULL); + nvte_destroy_tensors(NULL, 0); + nvte_tensor_data(NULL); + nvte_tensor_columnwise_data(NULL); + nvte_make_shape(NULL, 0); + nvte_tensor_shape(NULL); + nvte_tensor_columnwise_shape(NULL); + nvte_tensor_ndims(NULL); + nvte_tensor_size(NULL, 0); + nvte_tensor_size_bytes(NULL); + nvte_tensor_numel(NULL); + nvte_tensor_element_size(NULL); + nvte_tensor_element_size_bits(NULL); + nvte_tensor_type(NULL); + nvte_tensor_amax(NULL); + nvte_tensor_scale(NULL); + nvte_tensor_scale_inv(NULL); + nvte_tensor_scale_inv_shape(NULL); + nvte_zero_tensor(NULL, NULL); + nvte_set_tensor_param(NULL, 0, NULL); + nvte_get_tensor_param(NULL, 0); + nvte_set_tensor_param_v2(NULL, 0, NULL, 0); + nvte_get_tensor_param_v2(NULL, 0, NULL, 0, NULL); + nvte_tensor_scaling_mode(NULL); + nvte_tensor_pack_create(NULL); + nvte_tensor_pack_destroy(NULL); + nvte_create_quantization_config(); + nvte_get_quantization_config_attribute(NULL, 0, NULL, 0, NULL); + nvte_set_quantization_config_attribute(NULL, 0, NULL, 0); + nvte_destroy_quantization_config(NULL); + nvte_is_non_tn_fp8_gemm_supported(); + nvte_memset(NULL, 0, 0, NULL); + nvte_splits_to_offsets(NULL, NULL, 0, 0, NULL); + nvte_splits_to_offsets_2d(NULL, NULL, NULL, NULL); + nvte_splits_to_offsets_multi(NULL, NULL, NULL, NULL, 0, NULL); + nvte_splits_to_offsets_multi_v2(NULL, 0, NULL, NULL, NULL, 0, NULL); + nvte_create_grouped_tensor(0, 0, shape); + nvte_destroy_grouped_tensor(NULL); + nvte_set_grouped_tensor_param(NULL, 0, NULL, 0); + nvte_get_grouped_tensor_param(NULL, 0, NULL, 0, NULL); + nvte_grouped_tensor_num_tensors(NULL); + nvte_grouped_tensor_type(NULL); + nvte_grouped_tensor_scaling_mode(NULL); + nvte_get_grouped_tensor_logical_shape(NULL); + + /* transpose.h */ + nvte_cast_transpose(NULL, NULL, NULL); + nvte_transpose(NULL, NULL, NULL); + nvte_cast_transpose_dbias(NULL, NULL, NULL, NULL, NULL); + nvte_fp8_transpose_dbias(NULL, NULL, NULL, NULL, NULL); + nvte_multi_cast_transpose(0, NULL, NULL, NULL); + nvte_cast_transpose_dbias_dgelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_cast_transpose_dbias_dsilu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_cast_transpose_dbias_drelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_cast_transpose_dbias_dqgelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_cast_transpose_dbias_dsrelu(NULL, NULL, NULL, NULL, NULL, NULL); + nvte_dgeglu_cast_transpose(NULL, NULL, NULL, NULL); + nvte_dswiglu_cast_transpose(NULL, NULL, NULL, NULL); + nvte_dreglu_cast_transpose(NULL, NULL, NULL, NULL); + nvte_dqgeglu_cast_transpose(NULL, NULL, NULL, NULL); + nvte_dsreglu_cast_transpose(NULL, NULL, NULL, NULL); + nvte_swap_first_dims(NULL, NULL, NULL); + nvte_nvfp4_data_transpose(NULL, NULL, NULL); + nvte_nvfp4_scale_transpose(NULL, NULL, 0, 0, NULL); + + /* utils.h */ + nvte_copy_host_to_device_via_kernel(NULL, NULL, 0, NULL); + nvte_convert_pointers_to_tensor(NULL, NULL, 0, NULL); + +} diff --git a/tests/cpp/util/test_c_api.cpp b/tests/cpp/util/test_c_api.cpp new file mode 100644 index 00000000000..5bf79bf1b0b --- /dev/null +++ b/tests/cpp/util/test_c_api.cpp @@ -0,0 +1,26 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#include + +// Defined in test_c_api.c, which is compiled as C. +extern "C" void call_every_c_api_function(void); + +namespace { + +// Read through a volatile so the compiler cannot prove the call unreachable. +volatile bool run_c_api_calls = false; + +} // namespace + +// The C API calls are compiled as C and linked against the library, so building this test checks +// that the public headers are valid C and that every C API function is exported with C linkage. +// The calls use placeholder arguments, so they are never executed. +TEST(CApiTest, CompilesAndLinksAsC) { + if (run_c_api_calls) { + call_every_c_api_function(); + } +} diff --git a/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp b/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp index b8ba4c500d3..1442e6ea0dd 100644 --- a/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp +++ b/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp @@ -24,7 +24,7 @@ using namespace std::placeholders; -bool nvte_built_with_cublasmp() { +bool nvte_built_with_cublasmp(void) { #ifdef NVTE_WITH_CUBLASMP return true; #else diff --git a/transformer_engine/common/cudnn_utils.cpp b/transformer_engine/common/cudnn_utils.cpp index 718147ff5d8..144a17d5738 100644 --- a/transformer_engine/common/cudnn_utils.cpp +++ b/transformer_engine/common/cudnn_utils.cpp @@ -59,8 +59,6 @@ cudnn_frontend::DataType_t get_cudnn_fe_dtype(const transformer_engine::DType t) } } -void nvte_cudnn_handle_init() { auto _ = nvte_get_cudnn_handle(); } - namespace detail { namespace { @@ -90,6 +88,8 @@ void CreateCuDNNHandle(cudnnHandle_t* handle) { } // namespace transformer_engine +void nvte_cudnn_handle_init(void) { auto _ = nvte_get_cudnn_handle(); } + extern "C" cudnnHandle_t nvte_get_cudnn_handle() { return transformer_engine::cudnnExecutionPlanManager::Instance().GetHandle(); } diff --git a/transformer_engine/common/fused_attn/context_parallel.cu b/transformer_engine/common/fused_attn/context_parallel.cu index 9da561abfa4..726ae55cd82 100644 --- a/transformer_engine/common/fused_attn/context_parallel.cu +++ b/transformer_engine/common/fused_attn/context_parallel.cu @@ -912,7 +912,7 @@ void thd_copy_valid_tokens_from_per_split_to_rank_local(const Tensor &inp, } // namespace context_parallel } // namespace transformer_engine -void nvte_cp_thd_read_half_tensor(const NVTETensor &tensor, const NVTETensor &cu_seqlens, +void nvte_cp_thd_read_half_tensor(const NVTETensor tensor, const NVTETensor cu_seqlens, NVTETensor half, int half_idx, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_read_half_tensor); using namespace transformer_engine; @@ -922,8 +922,8 @@ void nvte_cp_thd_read_half_tensor(const NVTETensor &tensor, const NVTETensor &cu *convertNVTETensorCheck(half), half_idx, stream); } -void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor &lse_per_step, - const NVTETensor &cu_seqlens, int lse_packed, +void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor lse_per_step, + const NVTETensor cu_seqlens, int lse_packed, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_second_half_lse_correction); using namespace transformer_engine; @@ -933,7 +933,7 @@ void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor &ls *convertNVTETensorCheck(cu_seqlens), lse_packed, stream); } -void nvte_cp_thd_read_second_half_lse(const NVTETensor &lse, const NVTETensor &cu_seqlens, +void nvte_cp_thd_read_second_half_lse(const NVTETensor lse, const NVTETensor cu_seqlens, NVTETensor half_lse, int lse_packed, int second_half_lse_seqlen, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_read_second_half_lse); @@ -944,9 +944,9 @@ void nvte_cp_thd_read_second_half_lse(const NVTETensor &lse, const NVTETensor &c *convertNVTETensorCheck(half_lse), lse_packed, second_half_lse_seqlen, stream); } -void nvte_cp_thd_out_correction(NVTETensor out, const NVTETensor &out_per_step, - const NVTETensor &old_lse, const NVTETensor &lse, - const NVTETensor &lse_per_step, const NVTETensor &cu_seqlens, +void nvte_cp_thd_out_correction(NVTETensor out, const NVTETensor out_per_step, + const NVTETensor old_lse, const NVTETensor lse, + const NVTETensor lse_per_step, const NVTETensor cu_seqlens, int only_second_half, int lse_packed, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_out_correction); using namespace transformer_engine; @@ -958,8 +958,8 @@ void nvte_cp_thd_out_correction(NVTETensor out, const NVTETensor &out_per_step, lse_packed, stream); } -void nvte_cp_thd_grad_correction(NVTETensor grad, const NVTETensor &grad_per_step, - const NVTETensor &cu_seqlens, const char *first_half, +void nvte_cp_thd_grad_correction(NVTETensor grad, const NVTETensor grad_per_step, + const NVTETensor cu_seqlens, const char *first_half, const char *second_half, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_grad_correction); using namespace transformer_engine; @@ -972,7 +972,7 @@ void nvte_cp_thd_grad_correction(NVTETensor grad, const NVTETensor &grad_per_ste *convertNVTETensorCheck(cu_seqlens), first_half_str, second_half_str, stream); } -void nvte_cp_thd_get_partitioned_indices(const NVTETensor &cu_seqlens, NVTETensor output, +void nvte_cp_thd_get_partitioned_indices(const NVTETensor cu_seqlens, NVTETensor output, int total_tokens, int world_size, int rank, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_get_partitioned_indices); @@ -983,7 +983,7 @@ void nvte_cp_thd_get_partitioned_indices(const NVTETensor &cu_seqlens, NVTETenso world_size, rank, stream); } -void nvte_thd_sequence_order_to_cp_rank_order(const NVTETensor &inp, const NVTETensor &cu_seqlens, +void nvte_thd_sequence_order_to_cp_rank_order(const NVTETensor inp, const NVTETensor cu_seqlens, NVTETensor out, int world_size, int total_tokens, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_sequence_order_to_cp_rank_order); @@ -994,7 +994,7 @@ void nvte_thd_sequence_order_to_cp_rank_order(const NVTETensor &inp, const NVTET *convertNVTETensorCheck(out), world_size, false, total_tokens, stream); } -void nvte_thd_cp_rank_order_to_sequence_order(const NVTETensor &inp, const NVTETensor &cu_seqlens, +void nvte_thd_cp_rank_order_to_sequence_order(const NVTETensor inp, const NVTETensor cu_seqlens, NVTETensor out, int world_size, int total_tokens, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_cp_rank_order_to_sequence_order); @@ -1005,9 +1005,9 @@ void nvte_thd_cp_rank_order_to_sequence_order(const NVTETensor &inp, const NVTET *convertNVTETensorCheck(out), world_size, true, total_tokens, stream); } -void nvte_thd_copy_valid_tokens_from_per_split_to_rank_local(const NVTETensor &inp, - const NVTETensor &cu_seqlens_padded, - const NVTETensor &cu_seqlens, +void nvte_thd_copy_valid_tokens_from_per_split_to_rank_local(const NVTETensor inp, + const NVTETensor cu_seqlens_padded, + const NVTETensor cu_seqlens, NVTETensor out, int total_tokens, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_copy_valid_tokens_from_per_split_to_rank_local); diff --git a/transformer_engine/common/gemm/cublaslt_gemm.cu b/transformer_engine/common/gemm/cublaslt_gemm.cu index 4cb12229b44..e9cddac98f7 100644 --- a/transformer_engine/common/gemm/cublaslt_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_gemm.cu @@ -1219,10 +1219,12 @@ namespace transformer_engine { using cublasHandleManager = detail::HandleManager; -void nvte_cublas_handle_init() { auto _ = cublasHandleManager::Instance().GetHandle(); } - } // namespace transformer_engine +void nvte_cublas_handle_init(void) { + auto _ = transformer_engine::cublasHandleManager::Instance().GetHandle(); +} + void nvte_multi_tensor_gemm(const NVTETensor *A, const NVTETensor *B, NVTETensor *D, const NVTETensor *bias, NVTETensor *pre_gelu_out, const int num_gemms, bool transa, bool transb, bool grad, NVTETensor *workspace, diff --git a/transformer_engine/common/include/transformer_engine/activation.h b/transformer_engine/common/include/transformer_engine/activation.h index 31429cf89cf..99087f0b82e 100644 --- a/transformer_engine/common/include/transformer_engine/activation.h +++ b/transformer_engine/common/include/transformer_engine/activation.h @@ -28,6 +28,7 @@ extern "C" { * \param[in] stream CUDA stream used for the operation. */ +#ifdef __cplusplus enum class NVTE_Activation_Type { GELU, GEGLU, @@ -42,6 +43,7 @@ enum class NVTE_Activation_Type { SREGLU, CLAMPED_SWIGLU }; +#endif /*! \brief Computes the GeLU activation of the input. * If the scaling mode of the output tensor is set to NVTE_MXFP8_1D_SCALING, diff --git a/transformer_engine/common/include/transformer_engine/comm_gemm.h b/transformer_engine/common/include/transformer_engine/comm_gemm.h index 3d81973f02e..b504d373717 100644 --- a/transformer_engine/common/include/transformer_engine/comm_gemm.h +++ b/transformer_engine/common/include/transformer_engine/comm_gemm.h @@ -40,13 +40,13 @@ extern "C" { typedef struct NVTECommGemmCtx NVTECommGemmCtx; -enum NVTECommGemmAlgoType { +typedef enum NVTECommGemmAlgoType { kNVTECommGemmAlgoDefault = 0, kNVTECommGemmAlgoSplitP2P = 1, kNVTECommGemmAlgoSplitMulticast = 2, kNVTECommGemmAlgoAtomicP2P = 3, kNVTECommGemmAlgoAtomicMulticast = 4 -}; +} NVTECommGemmAlgoType; /*! \brief Create a comm-gemm context. * @@ -176,6 +176,12 @@ void* nvte_comm_gemm_workspace(NVTECommGemmCtx* ctx, size_t* size); */ int nvte_cublasmp_version(void); +/*! \brief Check if Transformer Engine is built with cuBLASMp. + * + * \return True if Transformer Engine is built with cuBLASMp. + */ +bool nvte_built_with_cublasmp(void); + #ifdef __cplusplus } // extern "C" #endif diff --git a/transformer_engine/common/include/transformer_engine/comm_gemm_overlap.h b/transformer_engine/common/include/transformer_engine/comm_gemm_overlap.h index b1a7447f2a6..c2fdb2cd857 100644 --- a/transformer_engine/common/include/transformer_engine/comm_gemm_overlap.h +++ b/transformer_engine/common/include/transformer_engine/comm_gemm_overlap.h @@ -7,6 +7,10 @@ #ifndef TRANSFORMER_ENGINE_COMMON_COMM_GEMM_OVERLAP_H_ #define TRANSFORMER_ENGINE_COMMON_COMM_GEMM_OVERLAP_H_ +#ifndef __cplusplus +#error "comm_gemm_overlap.h is a C++ header" +#endif + #include #include #include @@ -19,12 +23,6 @@ #define NVTE_COMM_OVERLAP_MAX_STREAMS 3 -/* \brief Check if TE is built with cuBLASMp. - * - * \return True if TE is built with cuBLASMp. - */ -bool nvte_built_with_cublasmp(); - namespace transformer_engine { /* \brief Check if Userbufers bootstraps with direct calls to MPI collectives. diff --git a/transformer_engine/common/include/transformer_engine/cudnn.h b/transformer_engine/common/include/transformer_engine/cudnn.h index ce44f87d9e8..fbe97300f88 100644 --- a/transformer_engine/common/include/transformer_engine/cudnn.h +++ b/transformer_engine/common/include/transformer_engine/cudnn.h @@ -13,17 +13,19 @@ #include "transformer_engine.h" -/*! \namespace transformer_engine - */ -namespace transformer_engine { +#ifdef __cplusplus +extern "C" { +#endif /*! \brief TE/JAX cudaGraph requires the cuDNN initialization to happen outside of the capturing * region. This function is a helper to call cudnnCreate() which allocate memory for the handle. * The function will be called in the initialize() phase of the related XLA custom calls. */ -void nvte_cudnn_handle_init(); +void nvte_cudnn_handle_init(void); -} // namespace transformer_engine +#ifdef __cplusplus +} // extern "C" +#endif #endif // TRANSFORMER_ENGINE_CUDNN_H_ diff --git a/transformer_engine/common/include/transformer_engine/fused_attn.h b/transformer_engine/common/include/transformer_engine/fused_attn.h index 57d497e4fb6..19d8010312b 100644 --- a/transformer_engine/common/include/transformer_engine/fused_attn.h +++ b/transformer_engine/common/include/transformer_engine/fused_attn.h @@ -26,7 +26,7 @@ extern "C" { * or padded to the same length, and `THD`-based layouts are used when sequences have * different lengths in a batch. `Paged_KV`-based layouts are used for paged attention. */ -enum NVTE_QKV_Layout { +typedef enum NVTE_QKV_Layout { NVTE_SB3HD = 0, /*!< SB3HD layout */ NVTE_SBH3D = 1, /*!< SBH3D layout */ NVTE_SBHD_SB2HD = 2, /*!< SBHD_SB2HD layout */ @@ -54,12 +54,12 @@ enum NVTE_QKV_Layout { NVTE_Paged_KV_THD_SBHD_SBHD = 24, /*!< Paged_KV_THD_SBHD_SBHD layout */ NVTE_BHSD_BHSD_BHSD = 25, /*!< BHSD_BHSD_BHSD layout */ NVTE_QKV_Layout_NOT_SET, /*!< Not set */ -}; +} NVTE_QKV_Layout; /*! \enum NVTE_QKV_Layout_Group * \brief QKV layout groups */ -enum NVTE_QKV_Layout_Group { +typedef enum NVTE_QKV_Layout_Group { /*! 3HD QKV layouts, i.e. BS3HD, SB3HD, T3HD */ NVTE_3HD = 0, /*! H3D QKV layouts, i.e. BSH3D, SBH3D, TH3D */ @@ -74,12 +74,12 @@ enum NVTE_QKV_Layout_Group { NVTE_Paged_KV_HD_HD_HD = 5, /*! SD_SD_SD QKV layouts, e.g. BHSD_BHSD_BHSD */ NVTE_SD_SD_SD = 6, -}; +} NVTE_QKV_Layout_Group; /*! \enum NVTE_QKV_Format * \brief QKV formats */ -enum NVTE_QKV_Format { +typedef enum NVTE_QKV_Format { /*! SBHD QKV format, i.e. SB3HD, SBH3D, SBHD_SB2HD, SBHD_SBH2D, SBHD_SBHD_SBHD, Paged_KV_SBHD_SBHD_SBHD */ NVTE_SBHD = 0, /*! BSHD QKV format, i.e. BS3HD, BSH3D, BSHD_BS2HD, BSHD_BSH2D, BSHD_BSHD_BSHD, Paged_KV_BSHD_BSHD_BSHD */ @@ -98,12 +98,12 @@ enum NVTE_QKV_Format { NVTE_BHSD = 7, /*! Not set */ NVTE_QKV_Format_NOT_SET, -}; +} NVTE_QKV_Format; /*! \enum NVTE_Bias_Type * \brief Bias types */ -enum NVTE_Bias_Type { +typedef enum NVTE_Bias_Type { /*! No bias */ NVTE_NO_BIAS = 0, /*! Bias before scale */ @@ -112,12 +112,12 @@ enum NVTE_Bias_Type { NVTE_POST_SCALE_BIAS = 2, /*! ALiBi */ NVTE_ALIBI = 3, -}; +} NVTE_Bias_Type; /*! \enum NVTE_Mask_Type * \brief Attention mask types */ -enum NVTE_Mask_Type { +typedef enum NVTE_Mask_Type { /*! No masking */ NVTE_NO_MASK = 0, /*! Padding attention mask */ @@ -130,7 +130,7 @@ enum NVTE_Mask_Type { NVTE_CAUSAL_BOTTOM_RIGHT_MASK = 4, /*! Padding and causal attention mask (aligned to the bottom right corner) */ NVTE_PADDING_CAUSAL_BOTTOM_RIGHT_MASK = 5, -}; +} NVTE_Mask_Type; /*! \enum NVTE_Softmax_Type * \brief Attention softmax types as described in @@ -141,26 +141,26 @@ enum NVTE_Mask_Type { * NVTE_LEARNABLE_SOFTMAX: S[:,j,:,i] = exp(S[:,j,:,i])/(exp(alpha[j]) + sum(exp(S[:,j,:,:]), dim=-1)), * where alpha is a learnable parameter of shape [H]. */ -enum NVTE_Softmax_Type { +typedef enum NVTE_Softmax_Type { /*! Vanilla softmax */ NVTE_VANILLA_SOFTMAX = 0, /*! Off-by-one softmax */ NVTE_OFF_BY_ONE_SOFTMAX = 1, /*! Learnable softmax */ NVTE_LEARNABLE_SOFTMAX = 2, -}; +} NVTE_Softmax_Type; /*! \enum NVTE_Fused_Attn_Backend * \brief Fused attention backends */ -enum NVTE_Fused_Attn_Backend { +typedef enum NVTE_Fused_Attn_Backend { /*! No supported backend */ NVTE_No_Backend = -1, /*! cuDNN-based FP16/BF16 fused attention for any sequence length */ NVTE_F16_arbitrary_seqlen = 1, /*! cuDNN-based FP8 fused attention */ NVTE_FP8 = 2, -}; +} NVTE_Fused_Attn_Backend; /*! \brief Get QKV layout group for a given QKV layout. * @@ -204,7 +204,7 @@ typedef void *NVTEFusedAttnConfig; * that of the declaration fields and the `attr_sizes` array of `FusedAttnConfig`. New fields * may be appended at the end, and existing fields are never reordered, removed, or resized. */ -enum NVTEFusedAttnConfigAttribute { +typedef enum NVTEFusedAttnConfigAttribute { // Basic attention settings kNVTEFusedAttnConfigIsTraining = 0, kNVTEFusedAttnConfigDeterministic, @@ -255,7 +255,7 @@ enum NVTEFusedAttnConfigAttribute { kNVTEFusedAttnConfigBiasSeqlenKV, // Number of attributes kNVTEFusedAttnConfigNumAttributes -}; +} NVTEFusedAttnConfigAttribute; /*! \brief Create a fused-attention configuration. * @@ -299,7 +299,7 @@ typedef void *NVTEFusedAttnFwdParams; * that of the declaration fields and the `attr_sizes` array of `FusedAttnFwdParams`. New fields * may be appended at the end, and existing fields are never reordered, removed, or resized. */ -enum NVTEFusedAttnFwdParamsAttribute { +typedef enum NVTEFusedAttnFwdParamsAttribute { // Tensor handles kNVTEFusedAttnFwdParamsQ = 0, kNVTEFusedAttnFwdParamsK, @@ -338,7 +338,7 @@ enum NVTEFusedAttnFwdParamsAttribute { kNVTEFusedAttnFwdParamsStream, // Number of attributes kNVTEFusedAttnFwdParamsNumAttributes -}; +} NVTEFusedAttnFwdParamsAttribute; /*! \brief Create a fused-attention forward-parameter object. * @@ -382,7 +382,7 @@ typedef void *NVTEFusedAttnBwdParams; * that of the declaration fields and the `attr_sizes` array of `FusedAttnBwdParams`. New fields * may be appended at the end, and existing fields are never reordered, removed, or resized. */ -enum NVTEFusedAttnBwdParamsAttribute { +typedef enum NVTEFusedAttnBwdParamsAttribute { // Tensor handles kNVTEFusedAttnBwdParamsQ = 0, kNVTEFusedAttnBwdParamsK, @@ -425,7 +425,7 @@ enum NVTEFusedAttnBwdParamsAttribute { kNVTEFusedAttnBwdParamsStream, // Number of attributes kNVTEFusedAttnBwdParamsNumAttributes -}; +} NVTEFusedAttnBwdParamsAttribute; /*! \brief Create a fused-attention backward-parameter object. * @@ -804,7 +804,7 @@ void nvte_copy_to_kv_cache(NVTETensor new_k, NVTETensor new_v, NVTETensor k_cach * \param[in] half_idx Whether to read first or second half of input tensor. * \param[in] stream CUDA stream used for this operation. */ -void nvte_cp_thd_read_half_tensor(const NVTETensor &tensor, const NVTETensor &cu_seqlens, +void nvte_cp_thd_read_half_tensor(const NVTETensor tensor, const NVTETensor cu_seqlens, NVTETensor half, int half_idx, cudaStream_t stream); /*! \brief Correct the second half of the softmax LSE (LogSumExp) for context parallelism. @@ -817,8 +817,8 @@ void nvte_cp_thd_read_half_tensor(const NVTETensor &tensor, const NVTETensor &cu * \param[in] lse_packed Whether or not lse_per_step is packed. * \param[in] stream CUDA stream used for this operation. */ -void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor &lse_per_step, - const NVTETensor &cu_seqlens, int lse_packed, +void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor lse_per_step, + const NVTETensor cu_seqlens, int lse_packed, cudaStream_t stream); /*! \brief Read the second half of the softmax LSE (LogSumExp) for context parallelism. @@ -832,7 +832,7 @@ void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor &ls * \param[in] second_half_lse_seqlen Sequence length. * \param[in] stream CUDA stream used for this operation. */ -void nvte_cp_thd_read_second_half_lse(const NVTETensor &lse, const NVTETensor &cu_seqlens, +void nvte_cp_thd_read_second_half_lse(const NVTETensor lse, const NVTETensor cu_seqlens, NVTETensor half_lse, int lse_packed, int second_half_lse_seqlen, cudaStream_t stream); @@ -850,9 +850,9 @@ void nvte_cp_thd_read_second_half_lse(const NVTETensor &lse, const NVTETensor &c * \param[in] lse_packed Whether or the softmax LSE is in packed format. * \param[in] stream CUDA stream used for this operation. */ -void nvte_cp_thd_out_correction(NVTETensor out, const NVTETensor &out_per_step, - const NVTETensor &old_lse, const NVTETensor &lse, - const NVTETensor &lse_per_step, const NVTETensor &cu_seqlens, +void nvte_cp_thd_out_correction(NVTETensor out, const NVTETensor out_per_step, + const NVTETensor old_lse, const NVTETensor lse, + const NVTETensor lse_per_step, const NVTETensor cu_seqlens, int only_second_half, int lse_packed, cudaStream_t stream); /*! \brief Update the two halves of each packed THD sequence during context-parallel backward. @@ -873,8 +873,8 @@ void nvte_cp_thd_out_correction(NVTETensor out, const NVTETensor &out_per_step, * \param[in] second_half Operation for each sequence's second half. * \param[in] stream CUDA stream used for this operation. */ -void nvte_cp_thd_grad_correction(NVTETensor grad, const NVTETensor &grad_per_step, - const NVTETensor &cu_seqlens, const char *first_half, +void nvte_cp_thd_grad_correction(NVTETensor grad, const NVTETensor grad_per_step, + const NVTETensor cu_seqlens, const char *first_half, const char *second_half, cudaStream_t stream); /*! \brief Generate partitioned indices for inputs in THD format. @@ -888,7 +888,7 @@ void nvte_cp_thd_grad_correction(NVTETensor grad, const NVTETensor &grad_per_ste * \param[in] rank Device ID for current device. * \param[in] stream CUDA stream used for this operation. */ -void nvte_cp_thd_get_partitioned_indices(const NVTETensor &cu_seqlens, NVTETensor output, +void nvte_cp_thd_get_partitioned_indices(const NVTETensor cu_seqlens, NVTETensor output, int total_tokens, int world_size, int rank, cudaStream_t stream); @@ -904,7 +904,7 @@ void nvte_cp_thd_get_partitioned_indices(const NVTETensor &cu_seqlens, NVTETenso * \param[in] total_tokens Total padded tokens (= inp.shape[0]). * \param[in] stream CUDA stream used for this operation. */ -void nvte_thd_sequence_order_to_cp_rank_order(const NVTETensor &inp, const NVTETensor &cu_seqlens, +void nvte_thd_sequence_order_to_cp_rank_order(const NVTETensor inp, const NVTETensor cu_seqlens, NVTETensor out, int world_size, int total_tokens, cudaStream_t stream); @@ -920,7 +920,7 @@ void nvte_thd_sequence_order_to_cp_rank_order(const NVTETensor &inp, const NVTET * \param[in] total_tokens Total padded tokens (= inp.shape[0]). * \param[in] stream CUDA stream used for this operation. */ -void nvte_thd_cp_rank_order_to_sequence_order(const NVTETensor &inp, const NVTETensor &cu_seqlens, +void nvte_thd_cp_rank_order_to_sequence_order(const NVTETensor inp, const NVTETensor cu_seqlens, NVTETensor out, int world_size, int total_tokens, cudaStream_t stream); @@ -936,9 +936,9 @@ void nvte_thd_cp_rank_order_to_sequence_order(const NVTETensor &inp, const NVTET * \param[in] total_tokens Total padded tokens (= inp.shape[0]). * \param[in] stream CUDA stream used for this operation. */ -void nvte_thd_copy_valid_tokens_from_per_split_to_rank_local(const NVTETensor &inp, - const NVTETensor &cu_seqlens_padded, - const NVTETensor &cu_seqlens, +void nvte_thd_copy_valid_tokens_from_per_split_to_rank_local(const NVTETensor inp, + const NVTETensor cu_seqlens_padded, + const NVTETensor cu_seqlens, NVTETensor out, int total_tokens, cudaStream_t stream); diff --git a/transformer_engine/common/include/transformer_engine/gemm.h b/transformer_engine/common/include/transformer_engine/gemm.h index 533242d3d7e..24af57449f3 100644 --- a/transformer_engine/common/include/transformer_engine/gemm.h +++ b/transformer_engine/common/include/transformer_engine/gemm.h @@ -28,7 +28,7 @@ typedef void *NVTEGroupedMatmulConfig; /*! \enum NVTEMatmulConfigAttribute * \brief Type of option for matrix multiplication. */ -enum NVTEMatmulConfigAttribute { +typedef enum NVTEMatmulConfigAttribute { /*! Bias tensor * * If provided, the bias tensor is applied in the GEMM epilogue. @@ -63,12 +63,12 @@ enum NVTEMatmulConfigAttribute { */ kNVTEMatmulConfigAlphaBetaOnDevice = 7, kNVTEMatmulConfigNumAttributes -}; +} NVTEMatmulConfigAttribute; /*! \enum NVTEGroupedMatmulConfigAttribute * \brief Type of option for grouped matrix multiplication. */ -enum NVTEGroupedMatmulConfigAttribute { +typedef enum NVTEGroupedMatmulConfigAttribute { /*! Average M dimension hint * * Optional hint for average M dimension across all matrices in the group. @@ -95,13 +95,13 @@ enum NVTEGroupedMatmulConfigAttribute { /*! Split accumulator mode. Only taken into account on Hopper. Default: true. */ kNVTEGroupedMatmulConfigUseSplitAccumulator = 4, kNVTEGroupedMatmulConfigNumAttributes -}; +} NVTEGroupedMatmulConfigAttribute; /*! \brief Get the cuBLASLt version that Transformer Engine was built against. */ -int nvte_get_cublaslt_build_version(); +int nvte_get_cublaslt_build_version(void); /*! \brief Create a matrix multiplication configuration. */ -NVTEMatmulConfig nvte_create_matmul_config(); +NVTEMatmulConfig nvte_create_matmul_config(void); /*! \brief Query an option in matrix multiplication configuration. * @@ -131,7 +131,7 @@ void nvte_set_matmul_config_attribute(NVTEMatmulConfig config, NVTEMatmulConfigA void nvte_destroy_matmul_config(NVTEMatmulConfig config); /*! \brief Create a grouped matrix multiplication configuration. */ -NVTEGroupedMatmulConfig nvte_create_grouped_matmul_config(); +NVTEGroupedMatmulConfig nvte_create_grouped_matmul_config(void); /*! \brief Query an option in grouped matrix multiplication configuration. * @@ -557,6 +557,12 @@ void nvte_grouped_bias_add(const NVTEGroupedTensor output, const NVTEGroupedTens void nvte_grouped_scaled_bias_add(const NVTEGroupedTensor output, const NVTEGroupedTensor bias, const NVTETensor scale, cudaStream_t stream); +/*! \brief TE/JAX cudaGraph requires the cuBLAS initialization to happen outside of the capturing + * region. This function is a helper to call cublasCreate() which allocate memory for the handle. + * The function will be called in the initialize phase of the related XLA custom calls. + */ +void nvte_cublas_handle_init(void); + #ifdef __cplusplus } // extern "C" #endif // __cplusplus @@ -567,13 +573,6 @@ void nvte_grouped_scaled_bias_add(const NVTEGroupedTensor output, const NVTEGrou */ namespace transformer_engine { -/*! \brief TE/JAX cudaGraph requires the cuBLAS initialization to happen outside of the capturing - * region. This function is a helper to call cublasCreate() which allocate memory for the handle. - * The function will be called in the initialize phase of the related XLA custom calls. - */ - -void nvte_cublas_handle_init(); - /*! \struct MatmulConfigWrapper * \brief C++ wrapper for NVTEMatmulConfig. */ diff --git a/transformer_engine/common/include/transformer_engine/multi_stream.h b/transformer_engine/common/include/transformer_engine/multi_stream.h index 013a424941e..5c97b043df0 100644 --- a/transformer_engine/common/include/transformer_engine/multi_stream.h +++ b/transformer_engine/common/include/transformer_engine/multi_stream.h @@ -11,14 +11,14 @@ #ifndef TRANSFORMER_ENGINE_MULTI_STREAM_H #define TRANSFORMER_ENGINE_MULTI_STREAM_H -#include "cuda_runtime.h" +#include #ifdef __cplusplus extern "C" { #endif /*! \brief Number of CUDA streams to use in multi-stream operations */ -int nvte_get_num_compute_streams(); +int nvte_get_num_compute_streams(void); /*! \brief Get a CUDA stream for compute operations. * diff --git a/transformer_engine/common/include/transformer_engine/nvfp4/4over6.h b/transformer_engine/common/include/transformer_engine/nvfp4/4over6.h index b186d9e49c9..75d6ca241e4 100644 --- a/transformer_engine/common/include/transformer_engine/nvfp4/4over6.h +++ b/transformer_engine/common/include/transformer_engine/nvfp4/4over6.h @@ -17,10 +17,10 @@ /*! \enum NVTENVFP44Over6Mode * \brief Method for NVFP4 4over6 quantization. */ -enum NVTENVFP44Over6Mode { +typedef enum NVTENVFP44Over6Mode { kNVTENVFP44Over6Disabled = 0, /*!< 4over6 is not applied */ kNVTENVFP44Over6MinMAE = 1, /*!< Select the candidate with lower mean absolute error */ kNVTENVFP44Over6MinMSE = 2, /*!< Select the candidate with lower mean squared error */ -}; +} NVTENVFP44Over6Mode; #endif // TRANSFORMER_ENGINE_NVFP4_4OVER6_H_ diff --git a/transformer_engine/common/include/transformer_engine/permutation.h b/transformer_engine/common/include/transformer_engine/permutation.h index 1fb1963512a..627cff4d23d 100644 --- a/transformer_engine/common/include/transformer_engine/permutation.h +++ b/transformer_engine/common/include/transformer_engine/permutation.h @@ -9,16 +9,24 @@ #include "transformer_engine.h" +#ifdef __cplusplus +extern "C" { +#endif + void nvte_permute(const NVTETensor input, NVTETensor output, const NVTETensor sorted_row_id, NVTETensor row_id_map, const NVTETensor prob, NVTETensor prob_grad, const NVTETensor input_fwd, const int num_rows, const int topK, - const int num_cols, const int num_out_tokens, cudaStream_t stream = nullptr); + const int num_cols, const int num_out_tokens, cudaStream_t stream); void nvte_unpermute(const NVTETensor input, NVTETensor output, NVTETensor row_id_map, const NVTETensor prob, const int num_rows, const int topK, const int num_cols, - cudaStream_t stream = nullptr); + cudaStream_t stream); void nvte_device_radix_sort_pairs(void *temp_storage, size_t *temp_storage_bytes, int *keys_in, int *keys_out, int *values_in, int *values_out, size_t num_items); +#ifdef __cplusplus +} // extern "C" +#endif + #endif // TRANSFORMER_ENGINE_PERMUTATION_H_ diff --git a/transformer_engine/common/include/transformer_engine/recipe.h b/transformer_engine/common/include/transformer_engine/recipe.h index 1c9af7d4fcf..e06be412aac 100644 --- a/transformer_engine/common/include/transformer_engine/recipe.h +++ b/transformer_engine/common/include/transformer_engine/recipe.h @@ -58,10 +58,11 @@ void nvte_delayed_scaling_recipe_amax_and_scale_update( * * \param[in] amax_reduction_buffer The contiguous buffer used for amax reduction. * Shape: [num_scales * num_tensors] - * \param[in,out] amax_histories List of amax histories of maximum absolute values. + * \param[in,out] amax_histories Array of amax histories of maximum absolute values. * Shape: num_tensors x [history_length, num_scales] - * \param[in,out] scales List of scaling factors for casting to FP8. + * \param[in,out] scales Array of scaling factors for casting to FP8. * Shape: num_tensors x [num_scales] + * \param[in] num_tensors Number of tensors in amax_histories and scales. * \param[in] amax_compute_algo Method to reduce amax history. Options are "max" and * "most_recent". * \param[in] fp8_dtype FP8 datatype. @@ -69,9 +70,9 @@ void nvte_delayed_scaling_recipe_amax_and_scale_update( * \param[in] stream CUDA stream. */ void nvte_delayed_scaling_recipe_amax_and_scale_update_after_reduction( - const NVTETensor amax_reduction_buffer, std::vector amax_histories, - std::vector scales, const char* amax_compute_algo, NVTEDType fp8_dtype, - float margin, cudaStream_t stream); + const NVTETensor amax_reduction_buffer, NVTETensor* amax_histories, NVTETensor* scales, + size_t num_tensors, const char* amax_compute_algo, NVTEDType fp8_dtype, float margin, + cudaStream_t stream); /*! \brief Compute an FP8 tensor's amax. * diff --git a/transformer_engine/common/include/transformer_engine/softmax.h b/transformer_engine/common/include/transformer_engine/softmax.h index e8883017a09..9e1b825acd9 100644 --- a/transformer_engine/common/include/transformer_engine/softmax.h +++ b/transformer_engine/common/include/transformer_engine/softmax.h @@ -7,9 +7,6 @@ #ifndef TRANSFORMER_ENGINE_SOFTMAX_H_ #define TRANSFORMER_ENGINE_SOFTMAX_H_ -#include -#include - #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/transformer_engine.h b/transformer_engine/common/include/transformer_engine/transformer_engine.h index 9a08b15a8a8..eb8c3cbc38a 100644 --- a/transformer_engine/common/include/transformer_engine/transformer_engine.h +++ b/transformer_engine/common/include/transformer_engine/transformer_engine.h @@ -12,19 +12,20 @@ #define TRANSFORMER_ENGINE_TRANSFORMER_ENGINE_H_ #include +#include #include #include +#include + #ifdef __cplusplus extern "C" { #endif -#include - /*! \enum NVTEDType * \brief TE datatype. */ -enum NVTEDType { +typedef enum NVTEDType { kNVTEByte = 0, /*!< Byte */ kNVTEInt16 = 1, /*!< 16-bit integer */ kNVTEInt32 = 2, /*!< 32-bit integer */ @@ -38,35 +39,35 @@ enum NVTEDType { kNVTEFloat4E2M1 = 10, /*!< 4-bit float (E2M1) */ kNVTEFloat8UE5M3 = 11, /*!< 8-bit float (UE5M3) */ kNVTENumTypes /*!< Number of supported types */ -}; +} NVTEDType; /*! \struct NVTEShape * \brief Shape of the tensor. */ -struct NVTEShape { +typedef struct NVTEShape { /*! \brief Shape data, with ndim valid elements. */ size_t data[15]; /*! \brief Number of dimensions. */ size_t ndim; -}; +} NVTEShape; /*! \struct NVTEBasicTensor * \brief A basic tensor type used to populate parameters of NVTETensor. * It does not own the memory it points to. */ -struct NVTEBasicTensor { +typedef struct NVTEBasicTensor { /*! Pointer to data buffer. */ void *data_ptr; /*! Data type. */ NVTEDType dtype; /*! Tensor shape. */ NVTEShape shape; -}; +} NVTEBasicTensor; /*! \enum NVTETensorParam * \brief Indicates the kind of the tensor parameter to set/get. */ -enum NVTETensorParam { +typedef enum NVTETensorParam { kNVTERowwiseData = 0, /*!< Data usable in rowwise manner */ kNVTEColumnwiseData = 1, /*!< Data usable in columnwise manner */ kNVTEScale = 2, /*!< Scale tensor */ @@ -98,12 +99,12 @@ enum NVTETensorParam { */ kNVTENVFP4E4M3Max = 9, kNVTENumTensorParams -}; +} NVTETensorParam; /*! \enum NVTEScalingMode * \brief Tensor data format. */ -enum NVTEScalingMode { +typedef enum NVTEScalingMode { /*! Either an unquantized tensor or an FP8 tensor with per-tensor scaling * * Not necessary used for delayed tensor scaling. The unintuitive @@ -123,7 +124,7 @@ enum NVTEScalingMode { * rowwise or columnwise direction */ NVTE_NVFP4_1D_SCALING = 4, NVTE_INVALID_SCALING = 100 -}; +} NVTEScalingMode; /*! \brief TE Tensor type * @@ -372,14 +373,15 @@ NVTEScalingMode nvte_tensor_scaling_mode(const NVTETensor tensor); /*! \struct NVTETensorPack \brief Pack of tensors, generally used for auxiliary outputs. */ -struct NVTETensorPack { - /*! Max number of tensors in the pack. Assumed <= 10. */ - static const int MAX_SIZE = 10; +/*! Max number of tensors in an NVTETensorPack. */ +#define NVTE_TENSOR_PACK_MAX_SIZE 10 + +typedef struct NVTETensorPack { /*! Wrappers of tensors. They do not hold the associated memory. */ - NVTETensor tensors[MAX_SIZE]; - /*! Actual number of tensors in the pack, 0 <= size <= MAX_SIZE. */ - size_t size = 0; -}; + NVTETensor tensors[NVTE_TENSOR_PACK_MAX_SIZE]; + /*! Actual number of tensors in the pack, 0 <= size <= NVTE_TENSOR_PACK_MAX_SIZE. */ + size_t size; +} NVTETensorPack; /*! \brief Create `tensors` in NVTETensorPack. */ @@ -395,7 +397,7 @@ typedef void *NVTEQuantizationConfig; /*! \enum NVTEQuantizationConfigAttribute * \brief Type of option for tensor quantization. */ -enum NVTEQuantizationConfigAttribute { +typedef enum NVTEQuantizationConfigAttribute { /*! Whether to force power of 2 scales */ kNVTEQuantizationConfigForcePow2Scales = 0, /*! Small value to add to amax for numerical stability */ @@ -437,12 +439,12 @@ enum NVTEQuantizationConfigAttribute { /*! Whether to use 2D block scaling for MXFP8 */ kNVTEQuantizationConfigMXFP82DQuantization = 10, kNVTEQuantizationConfigNumAttributes -}; +} NVTEQuantizationConfigAttribute; /*! \brief Create a new quantization config. * \return A new quantization config. */ -NVTEQuantizationConfig nvte_create_quantization_config(); +NVTEQuantizationConfig nvte_create_quantization_config(void); /*! \brief Query an option in quantization config. * @@ -480,7 +482,7 @@ void nvte_destroy_quantization_config(NVTEQuantizationConfig config); * * \return A flag which indicates whether non-TN FP8 Gemm is supported or not. */ -int nvte_is_non_tn_fp8_gemm_supported(); +int nvte_is_non_tn_fp8_gemm_supported(void); /*! \brief Performs a memset of the data at the given pointer and size in bytes. * @@ -569,7 +571,7 @@ typedef void *NVTEGroupedTensor; /*! \enum NVTEGroupedTensorParam * \brief Indicates the kind of the grouped tensor parameter to set/get. */ -enum NVTEGroupedTensorParam { +typedef enum NVTEGroupedTensorParam { kNVTEGroupedRowwiseData = 0, /*!< Data usable in rowwise manner */ kNVTEGroupedColumnwiseData = 1, /*!< Data usable in columnwise manner */ kNVTEGroupedScale = 2, /*!< Scale tensor */ @@ -586,7 +588,7 @@ enum NVTEGroupedTensorParam { kNVTEGroupedRowScaledNVFP4 = 11, /*!< Whether NVFP4 data uses row scaling instead of tensor scaling */ kNVTENumGroupedTensorParams -}; +} NVTEGroupedTensorParam; /* EXPERIMENTAL FEATURE AND SUBJECT TO CHANGE. */ /*! \brief Create a new TE grouped tensor. diff --git a/transformer_engine/common/include/transformer_engine/utils.h b/transformer_engine/common/include/transformer_engine/utils.h index fda49dd5499..994f9e42ad3 100644 --- a/transformer_engine/common/include/transformer_engine/utils.h +++ b/transformer_engine/common/include/transformer_engine/utils.h @@ -11,7 +11,7 @@ #ifndef TRANSFORMER_ENGINE_UTILS_H_ #define TRANSFORMER_ENGINE_UTILS_H_ -#include +#include #include #include #include diff --git a/transformer_engine/common/libtransformer_engine.version b/transformer_engine/common/libtransformer_engine.version index c608cfee04a..47ef2fd2898 100644 --- a/transformer_engine/common/libtransformer_engine.version +++ b/transformer_engine/common/libtransformer_engine.version @@ -13,8 +13,6 @@ transformer_engine::cuda_driver::ensure_context_exists*; transformer_engine::ubuf_built_with_mpi*; *transformer_engine::rtc*; - transformer_engine::nvte_cudnn_handle_init*; - transformer_engine::nvte_cublas_handle_init*; transformer_engine::typeToSize*; transformer_engine::is_fp8_dtype*; *transformer_engine::CommOverlapBase*; diff --git a/transformer_engine/common/recipe/delayed_scaling.cu b/transformer_engine/common/recipe/delayed_scaling.cu index a0da551d0f7..c1bbeac9b60 100644 --- a/transformer_engine/common/recipe/delayed_scaling.cu +++ b/transformer_engine/common/recipe/delayed_scaling.cu @@ -403,12 +403,11 @@ void nvte_delayed_scaling_recipe_amax_and_scale_update( } void nvte_delayed_scaling_recipe_amax_and_scale_update_after_reduction( - const NVTETensor amax_reduction_buffer, std::vector amax_histories, - std::vector scales, const char* amax_compute_algo, NVTEDType fp8_dtype, - float margin, cudaStream_t stream) { + const NVTETensor amax_reduction_buffer, NVTETensor* amax_histories, NVTETensor* scales, + size_t num_tensors, const char* amax_compute_algo, NVTEDType fp8_dtype, float margin, + cudaStream_t stream) { NVTE_API_CALL(nvte_delayed_scaling_recipe_amax_and_scale_update_after_reduction); using namespace transformer_engine; - size_t num_tensors = amax_histories.size(); std::vector t_amax_histories, t_scales; for (size_t i = 0; i < num_tensors; i++) { t_amax_histories.push_back(convertNVTETensor(amax_histories[i])); diff --git a/transformer_engine/common/transformer_engine.cpp b/transformer_engine/common/transformer_engine.cpp index 66693dca3a1..dcf96696f96 100644 --- a/transformer_engine/common/transformer_engine.cpp +++ b/transformer_engine/common/transformer_engine.cpp @@ -1037,12 +1037,12 @@ NVTEScalingMode nvte_tensor_scaling_mode(const NVTETensor tensor) { } void nvte_tensor_pack_create(NVTETensorPack *pack) { - transformer_engine::TensorAllocator::instance().Allocate(NVTE_DELAYED_TENSOR_SCALING, - pack->tensors, pack->MAX_SIZE); + transformer_engine::TensorAllocator::instance().Allocate( + NVTE_DELAYED_TENSOR_SCALING, pack->tensors, NVTE_TENSOR_PACK_MAX_SIZE); } void nvte_tensor_pack_destroy(NVTETensorPack *pack) { - transformer_engine::TensorAllocator::instance().Free(pack->tensors, pack->MAX_SIZE); + transformer_engine::TensorAllocator::instance().Free(pack->tensors, NVTE_TENSOR_PACK_MAX_SIZE); } void nvte_zero_tensor(const NVTETensor tensor, cudaStream_t stream) { diff --git a/transformer_engine/pytorch/csrc/extensions/recipe.cpp b/transformer_engine/pytorch/csrc/extensions/recipe.cpp index 9be288d2f70..3b0e27683ad 100644 --- a/transformer_engine/pytorch/csrc/extensions/recipe.cpp +++ b/transformer_engine/pytorch/csrc/extensions/recipe.cpp @@ -52,13 +52,10 @@ void fused_amax_and_scale_update_after_reduction(const at::Tensor& amax_reductio scale_shape}; nvte_set_tensor_param_v2(te_scales[i], kNVTERowwiseData, &scale_data, sizeof(scale_data)); } - // The recipe function takes std::vector by value, so - // construct fresh vectors from the batches. nvte_delayed_scaling_recipe_amax_and_scale_update_after_reduction( - makeTransformerEngineTensor(amax_reduction_buffer).data(), - std::vector(te_amax_histories.begin(), te_amax_histories.end()), - std::vector(te_scales.begin(), te_scales.end()), amax_compute_algo.c_str(), - static_cast(fp8_dtype), margin, at::cuda::getCurrentCUDAStream()); + makeTransformerEngineTensor(amax_reduction_buffer).data(), te_amax_histories.data(), + te_scales.data(), num_tensors, amax_compute_algo.c_str(), static_cast(fp8_dtype), + margin, at::cuda::getCurrentCUDAStream()); } } // namespace transformer_engine::pytorch From a55a2787a0556e4c1e5d65afd4360fe63d4bdbc6 Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 16:14:50 -0800 Subject: [PATCH 02/18] [Common] Use bool for flag arguments in the C API Now that the public headers include stdbool.h, change int arguments and return values that are logically flags to bool: GEMM transpose flags, router use_pre_softmax, context-parallel attention flags, multi-tensor optimizer flags, and the nvte_is_non_tn_fp8_gemm_supported and nvte_fused_topk_with_aux_loss_scores_is_supported results. Also fix the is_non_paged documentation, which described the opposite meaning. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tim Moon --- .../common/fused_attn/context_parallel.cu | 6 ++--- .../common/fused_attn/kv_cache.cu | 2 +- transformer_engine/common/fused_attn/utils.cu | 2 +- .../fused_topk_with_aux_loss_scores.cu | 4 ++-- .../fused_topk_with_score_function.cu | 17 ++++++------- .../common/gemm/cublaslt_batched_gemm.cu | 4 ++-- .../common/gemm/cublaslt_gemm.cu | 4 ++-- .../common/gemm/cublaslt_grouped_gemm.cu | 24 +++++++++---------- .../include/transformer_engine/fused_attn.h | 12 +++++----- .../include/transformer_engine/fused_router.h | 23 +++++++++--------- .../common/include/transformer_engine/gemm.h | 18 +++++++------- .../include/transformer_engine/multi_tensor.h | 20 ++++++++-------- .../transformer_engine/transformer_engine.h | 2 +- .../common/multi_tensor/adam.cu | 10 ++++---- .../common/multi_tensor/compute_scale.cu | 2 +- .../common/multi_tensor/l2norm.cu | 4 ++-- transformer_engine/common/multi_tensor/sgd.cu | 4 ++-- .../common/transformer_engine.cpp | 2 +- .../pytorch/csrc/extensions/router.cpp | 2 +- transformer_engine/pytorch/csrc/quantizer.cpp | 8 +++---- 20 files changed, 86 insertions(+), 84 deletions(-) diff --git a/transformer_engine/common/fused_attn/context_parallel.cu b/transformer_engine/common/fused_attn/context_parallel.cu index 726ae55cd82..97d95d1eff8 100644 --- a/transformer_engine/common/fused_attn/context_parallel.cu +++ b/transformer_engine/common/fused_attn/context_parallel.cu @@ -923,7 +923,7 @@ void nvte_cp_thd_read_half_tensor(const NVTETensor tensor, const NVTETensor cu_s } void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor lse_per_step, - const NVTETensor cu_seqlens, int lse_packed, + const NVTETensor cu_seqlens, bool lse_packed, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_second_half_lse_correction); using namespace transformer_engine; @@ -934,7 +934,7 @@ void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor lse } void nvte_cp_thd_read_second_half_lse(const NVTETensor lse, const NVTETensor cu_seqlens, - NVTETensor half_lse, int lse_packed, + NVTETensor half_lse, bool lse_packed, int second_half_lse_seqlen, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_read_second_half_lse); using namespace transformer_engine; @@ -947,7 +947,7 @@ void nvte_cp_thd_read_second_half_lse(const NVTETensor lse, const NVTETensor cu_ void nvte_cp_thd_out_correction(NVTETensor out, const NVTETensor out_per_step, const NVTETensor old_lse, const NVTETensor lse, const NVTETensor lse_per_step, const NVTETensor cu_seqlens, - int only_second_half, int lse_packed, cudaStream_t stream) { + bool only_second_half, bool lse_packed, cudaStream_t stream) { NVTE_API_CALL(nvte_thd_out_correction); using namespace transformer_engine; diff --git a/transformer_engine/common/fused_attn/kv_cache.cu b/transformer_engine/common/fused_attn/kv_cache.cu index 52b46a97746..e6dbc54c7f5 100644 --- a/transformer_engine/common/fused_attn/kv_cache.cu +++ b/transformer_engine/common/fused_attn/kv_cache.cu @@ -296,7 +296,7 @@ void nvte_copy_to_kv_cache(NVTETensor new_k, NVTETensor new_v, NVTETensor k_cach NVTETensor v_cache, NVTETensor page_table, NVTETensor cu_new_lens, NVTETensor cu_cached_lens, NVTE_QKV_Format qkv_format, int b, int max_ctx_len, int max_seq_len, int max_pages_per_seq, - int is_non_paged, cudaStream_t stream) { + bool is_non_paged, cudaStream_t stream) { NVTE_API_CALL(nvte_copy_to_kv_cache); using namespace transformer_engine; diff --git a/transformer_engine/common/fused_attn/utils.cu b/transformer_engine/common/fused_attn/utils.cu index 7dea40f70b7..2deb0416af2 100644 --- a/transformer_engine/common/fused_attn/utils.cu +++ b/transformer_engine/common/fused_attn/utils.cu @@ -555,7 +555,7 @@ void nvte_cu_seqlens_to_actual_seqlens(const NVTETensor cu_seqlens_q, NVTE_CHECK_CUDA(cudaGetLastError()); } -void nvte_extract_seed_and_offset(int64_t *rng_state_ptr, int captured, int64_t *seed_ptr, +void nvte_extract_seed_and_offset(int64_t *rng_state_ptr, bool captured, int64_t *seed_ptr, uint64_t seed_val, int64_t *offset_ptr, uint64_t offset_val, uint32_t offset_intragraph, cudaStream_t stream) { NVTE_API_CALL(nvte_extract_seed_and_offset); diff --git a/transformer_engine/common/fused_router/fused_topk_with_aux_loss_scores.cu b/transformer_engine/common/fused_router/fused_topk_with_aux_loss_scores.cu index 3cc4f652916..5b8b45b758b 100644 --- a/transformer_engine/common/fused_router/fused_topk_with_aux_loss_scores.cu +++ b/transformer_engine/common/fused_router/fused_topk_with_aux_loss_scores.cu @@ -594,8 +594,8 @@ void fused_topk_with_aux_loss_scores_backward(const Tensor &logits, const Tensor } // namespace fused_router } // namespace transformer_engine -int nvte_fused_topk_with_aux_loss_scores_is_supported(int num_experts, int topk, int num_groups, - int group_topk, int score_function) { +bool nvte_fused_topk_with_aux_loss_scores_is_supported(int num_experts, int topk, int num_groups, + int group_topk, int score_function) { using namespace transformer_engine::fused_router; const bool supported = separate_topk_is_naive(topk) && diff --git a/transformer_engine/common/fused_router/fused_topk_with_score_function.cu b/transformer_engine/common/fused_router/fused_topk_with_score_function.cu index e9d6626a2b0..5355a798b40 100644 --- a/transformer_engine/common/fused_router/fused_topk_with_score_function.cu +++ b/transformer_engine/common/fused_router/fused_topk_with_score_function.cu @@ -1707,7 +1707,7 @@ void fused_topk_with_score_function_backward_with_indices( } // namespace transformer_engine void nvte_fused_topk_with_score_function_forward_v2( - const NVTETensor logits, int num_tokens, int num_experts, int topk, int use_pre_softmax, + const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, cudaStream_t stream) { @@ -1722,7 +1722,7 @@ void nvte_fused_topk_with_score_function_forward_v2( } void nvte_fused_topk_with_score_function_forward( - const NVTETensor logits, int num_tokens, int num_experts, int topk, int use_pre_softmax, + const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTETensor intermediate_output, cudaStream_t stream) { @@ -1734,7 +1734,7 @@ void nvte_fused_topk_with_score_function_forward( } void nvte_fused_topk_with_score_function_forward_with_indices( - const NVTETensor logits, int num_tokens, int num_experts, int topk, int use_pre_softmax, + const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor topk_indices, NVTETensor intermediate_output, cudaStream_t stream) { @@ -1824,9 +1824,10 @@ void nvte_fused_topk_with_score_function_backward_v2(const NVTETensor routing_ma NVTERoutingMapFormat routing_map_format, const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, - int num_experts, int topk, int use_pre_softmax, - float scaling_factor, int score_function, - NVTETensor grad_logits, cudaStream_t stream) { + int num_experts, int topk, + bool use_pre_softmax, float scaling_factor, + int score_function, NVTETensor grad_logits, + cudaStream_t stream) { NVTE_API_CALL(nvte_fused_topk_with_score_function_backward_v2); using namespace transformer_engine; fused_router::fused_topk_with_score_function_backward( @@ -1839,7 +1840,7 @@ void nvte_fused_topk_with_score_function_backward_v2(const NVTETensor routing_ma void nvte_fused_topk_with_score_function_backward(const NVTETensor routing_map, const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, - int num_experts, int topk, int use_pre_softmax, + int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, NVTETensor grad_logits, cudaStream_t stream) { NVTE_API_CALL(nvte_fused_topk_with_score_function_backward); @@ -1850,7 +1851,7 @@ void nvte_fused_topk_with_score_function_backward(const NVTETensor routing_map, void nvte_fused_topk_with_score_function_backward_with_indices( const NVTETensor topk_indices, const NVTETensor intermediate_output, - const NVTETensor grad_probs, int num_tokens, int num_experts, int topk, int use_pre_softmax, + const NVTETensor grad_probs, int num_tokens, int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, NVTETensor grad_logits, cudaStream_t stream) { NVTE_API_CALL(nvte_fused_topk_with_score_function_backward_with_indices); using namespace transformer_engine; diff --git a/transformer_engine/common/gemm/cublaslt_batched_gemm.cu b/transformer_engine/common/gemm/cublaslt_batched_gemm.cu index d329bf93f57..85a6fa68d7a 100644 --- a/transformer_engine/common/gemm/cublaslt_batched_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_batched_gemm.cu @@ -357,7 +357,7 @@ void strided_batched_gemm(const BatchedMatrix &A, cublasOperation_t transa, cons } // namespace -void nvte_cublas_gemm_strided_batched(int transa, int transb, const float *alpha, +void nvte_cublas_gemm_strided_batched(bool transa, bool transb, const float *alpha, const NVTETensor A, int batch_dim_a, const NVTETensor B, int batch_dim_b, const float *beta, const NVTETensor C, NVTETensor D, int batch_dim_d, NVTETensor workspace, @@ -378,7 +378,7 @@ void nvte_cublas_gemm_strided_batched(int transa, int transb, const float *alpha MakeBatchedMatrix(D_tensor->data, batch_dim_d, "D"), alpha, beta, workspace, config, stream); } -void nvte_cublas_gemm_strided_batched_mxfp8(int transa, int transb, const float *alpha, +void nvte_cublas_gemm_strided_batched_mxfp8(bool transa, bool transb, const float *alpha, const NVTETensor A_data, const NVTETensor A_scale_inv, int batch_dim_a, const NVTETensor B_data, const NVTETensor B_scale_inv, int batch_dim_b, diff --git a/transformer_engine/common/gemm/cublaslt_gemm.cu b/transformer_engine/common/gemm/cublaslt_gemm.cu index e9cddac98f7..6cd4750bedc 100644 --- a/transformer_engine/common/gemm/cublaslt_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_gemm.cu @@ -130,7 +130,7 @@ GemmParam CanonicalizeGemmInput(const transformer_engine::Tensor &A, const cubla // Set conditions for MXFP8 and NVFP4 gemm execution. const auto nvfp4 = is_nvfp_scaling(A.scaling_mode) && is_nvfp_scaling(B.scaling_mode); const auto mxfp8 = !nvfp4 && is_mxfp_scaling(A.scaling_mode) && is_mxfp_scaling(B.scaling_mode); - int is_nvte_non_tn_fp8_gemm_supported = 0; // needed only for per tensor scaling + bool is_nvte_non_tn_fp8_gemm_supported = false; // needed only for per tensor scaling if (is_tensor_scaling(A.scaling_mode) || is_tensor_scaling(B.scaling_mode)) { is_nvte_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); } @@ -1004,7 +1004,7 @@ void nvte_cublas_gemm(const NVTETensor A, const NVTETensor B, NVTETensor D, cons math_sm_count, 0, 0, false, nullptr, stream); } -void nvte_cublas_gemm_v2(int transa, int transb, const float *alpha, const NVTETensor A, +void nvte_cublas_gemm_v2(bool transa, bool transb, const float *alpha, const NVTETensor A, const NVTETensor B, const float *beta, const NVTETensor C, NVTETensor D, NVTETensor workspace, NVTEMatmulConfig config, cudaStream_t stream) { NVTE_API_CALL(nvte_cublas_gemm_v2); diff --git a/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu b/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu index f34b95f2e14..f801d558142 100644 --- a/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu @@ -1692,9 +1692,9 @@ size_t nvte_get_grouped_gemm_setup_workspace_size(size_t num_tensors) { return grouped_gemm_setup_workspace_size(num_tensors); } -void nvte_grouped_gemm(const NVTEGroupedTensor A, int transa, const NVTEGroupedTensor B, int transb, - const NVTEGroupedTensor C, NVTEGroupedTensor D, const NVTETensor alpha, - const NVTETensor beta, NVTETensor workspace_setup, +void nvte_grouped_gemm(const NVTEGroupedTensor A, bool transa, const NVTEGroupedTensor B, + bool transb, const NVTEGroupedTensor C, NVTEGroupedTensor D, + const NVTETensor alpha, const NVTETensor beta, NVTETensor workspace_setup, NVTETensor workspace_cublas, NVTEGroupedMatmulConfig config, cudaStream_t stream) { NVTE_API_CALL(nvte_grouped_gemm); @@ -1769,7 +1769,7 @@ void nvte_grouped_gemm(const NVTEGroupedTensor A, int transa, const NVTEGroupedT } void nvte_grouped_gemm_with_discrete_inputA(const NVTETensor *A_list, size_t num_a_tensors, - int transa, const NVTEGroupedTensor B, int transb, + bool transa, const NVTEGroupedTensor B, bool transb, const NVTEGroupedTensor C, NVTEGroupedTensor D, const NVTETensor alpha, const NVTETensor beta, NVTETensor workspace_setup, NVTETensor workspace_cublas, @@ -1915,8 +1915,8 @@ void nvte_grouped_gemm_with_discrete_inputA(const NVTETensor *A_list, size_t num gemm_config, workspace.cublas_workspace_ptr, stream); } -void nvte_grouped_gemm_with_discrete_out(const NVTEGroupedTensor A, int transa, - const NVTEGroupedTensor B, int transb, +void nvte_grouped_gemm_with_discrete_out(const NVTEGroupedTensor A, bool transa, + const NVTEGroupedTensor B, bool transb, const NVTETensor *C_list, size_t num_c_tensors, NVTETensor *D_list, size_t num_d_tensors, const NVTETensor alpha, const NVTETensor beta, @@ -2126,9 +2126,9 @@ void nvte_grouped_scaled_bias_add(const NVTEGroupedTensor output, const NVTEGrou #else // CUBLAS_VERSION < CUBLAS_GROUPED_GEMM_VERSION -void nvte_grouped_gemm(const NVTEGroupedTensor A, int transa, const NVTEGroupedTensor B, int transb, - const NVTEGroupedTensor C, NVTEGroupedTensor D, const NVTETensor alpha, - const NVTETensor beta, NVTETensor workspace_setup, +void nvte_grouped_gemm(const NVTEGroupedTensor A, bool transa, const NVTEGroupedTensor B, + bool transb, const NVTEGroupedTensor C, NVTEGroupedTensor D, + const NVTETensor alpha, const NVTETensor beta, NVTETensor workspace_setup, NVTETensor workspace_cublas, NVTEGroupedMatmulConfig config, cudaStream_t stream) { NVTE_ERROR("nvte_grouped_gemm requires cuBLAS 13.3+, but compile-time cuBLAS version is ", @@ -2136,7 +2136,7 @@ void nvte_grouped_gemm(const NVTEGroupedTensor A, int transa, const NVTEGroupedT } void nvte_grouped_gemm_with_discrete_inputA(const NVTETensor *A_list, size_t num_a_tensors, - int transa, const NVTEGroupedTensor B, int transb, + bool transa, const NVTEGroupedTensor B, bool transb, const NVTEGroupedTensor C, NVTEGroupedTensor D, const NVTETensor alpha, const NVTETensor beta, NVTETensor workspace_setup, NVTETensor workspace_cublas, @@ -2147,8 +2147,8 @@ void nvte_grouped_gemm_with_discrete_inputA(const NVTETensor *A_list, size_t num CUBLAS_VERSION, ". Please upgrade to cuBLAS 13.3 (shipped with CUDA 13.2) or newer."); } -void nvte_grouped_gemm_with_discrete_out(const NVTEGroupedTensor A, int transa, - const NVTEGroupedTensor B, int transb, +void nvte_grouped_gemm_with_discrete_out(const NVTEGroupedTensor A, bool transa, + const NVTEGroupedTensor B, bool transb, const NVTETensor *C_list, size_t num_c_tensors, NVTETensor *D_list, size_t num_d_tensors, const NVTETensor alpha, const NVTETensor beta, diff --git a/transformer_engine/common/include/transformer_engine/fused_attn.h b/transformer_engine/common/include/transformer_engine/fused_attn.h index 19d8010312b..f3add1b8a87 100644 --- a/transformer_engine/common/include/transformer_engine/fused_attn.h +++ b/transformer_engine/common/include/transformer_engine/fused_attn.h @@ -765,7 +765,7 @@ void nvte_cu_seqlens_to_actual_seqlens(const NVTETensor cu_seqlens_q, * \param[in] offset_intragraph Intragraph offset in RNG states. For use with CUDA Graphs. * \param[in] stream CUDA stream used for this operation. */ -void nvte_extract_seed_and_offset(int64_t *rng_state_ptr, int captured, int64_t *seed_ptr, +void nvte_extract_seed_and_offset(int64_t *rng_state_ptr, bool captured, int64_t *seed_ptr, uint64_t seed_val, int64_t *offset_ptr, uint64_t offset_val, uint32_t offset_intragraph, cudaStream_t stream); @@ -785,14 +785,14 @@ void nvte_extract_seed_and_offset(int64_t *rng_state_ptr, int captured, int64_t * \param[in] max_ctx_len Maximum context length. * \param[in] max_seq_len Maximum sequence length. * \param[in] max_pages_per_seq Maximum number of pages per sequence. - * \param[in] is_non_paged Whether the cache is paged or not. + * \param[in] is_non_paged Whether the cache is non-paged. * \param[in] stream CUDA stream used for this operation. */ void nvte_copy_to_kv_cache(NVTETensor new_k, NVTETensor new_v, NVTETensor k_cache, NVTETensor v_cache, NVTETensor page_table, NVTETensor cu_new_lens, NVTETensor cu_cached_lens, NVTE_QKV_Format qkv_format, int b, int max_ctx_len, int max_seq_len, int max_pages_per_seq, - int is_non_paged, cudaStream_t stream); + bool is_non_paged, cudaStream_t stream); /*! \brief Extract the first half (half_idx=0) or second half (half_idx=1) of a THD tensor. * @@ -818,7 +818,7 @@ void nvte_cp_thd_read_half_tensor(const NVTETensor tensor, const NVTETensor cu_s * \param[in] stream CUDA stream used for this operation. */ void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor lse_per_step, - const NVTETensor cu_seqlens, int lse_packed, + const NVTETensor cu_seqlens, bool lse_packed, cudaStream_t stream); /*! \brief Read the second half of the softmax LSE (LogSumExp) for context parallelism. @@ -833,7 +833,7 @@ void nvte_cp_thd_second_half_lse_correction(NVTETensor lse, const NVTETensor lse * \param[in] stream CUDA stream used for this operation. */ void nvte_cp_thd_read_second_half_lse(const NVTETensor lse, const NVTETensor cu_seqlens, - NVTETensor half_lse, int lse_packed, + NVTETensor half_lse, bool lse_packed, int second_half_lse_seqlen, cudaStream_t stream); /*! \brief Correct the THD format output of context parallelism in forward pass. @@ -853,7 +853,7 @@ void nvte_cp_thd_read_second_half_lse(const NVTETensor lse, const NVTETensor cu_ void nvte_cp_thd_out_correction(NVTETensor out, const NVTETensor out_per_step, const NVTETensor old_lse, const NVTETensor lse, const NVTETensor lse_per_step, const NVTETensor cu_seqlens, - int only_second_half, int lse_packed, cudaStream_t stream); + bool only_second_half, bool lse_packed, cudaStream_t stream); /*! \brief Update the two halves of each packed THD sequence during context-parallel backward. * diff --git a/transformer_engine/common/include/transformer_engine/fused_router.h b/transformer_engine/common/include/transformer_engine/fused_router.h index 90704e0bca0..b40977cd6cb 100644 --- a/transformer_engine/common/include/transformer_engine/fused_router.h +++ b/transformer_engine/common/include/transformer_engine/fused_router.h @@ -62,7 +62,7 @@ typedef enum { * \param[in] stream CUDA stream used for the operation. */ void nvte_fused_topk_with_score_function_forward( - const NVTETensor logits, int num_tokens, int num_experts, int topk, int use_pre_softmax, + const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTETensor intermediate_output, cudaStream_t stream); @@ -89,7 +89,7 @@ void nvte_fused_topk_with_score_function_forward( * \param[in] stream CUDA stream used for the operation. */ void nvte_fused_topk_with_score_function_forward_v2( - const NVTETensor logits, int num_tokens, int num_experts, int topk, int use_pre_softmax, + const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, cudaStream_t stream); @@ -100,7 +100,7 @@ void nvte_fused_topk_with_score_function_forward_v2( * selected expert ids to topk_indices with shape [num_tokens, topk]. */ void nvte_fused_topk_with_score_function_forward_with_indices( - const NVTETensor logits, int num_tokens, int num_experts, int topk, int use_pre_softmax, + const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor topk_indices, NVTETensor intermediate_output, cudaStream_t stream); @@ -195,7 +195,7 @@ void nvte_qb_histogram_accumulate_unchecked(const NVTETensor raw_scores, const N void nvte_fused_topk_with_score_function_backward(const NVTETensor routing_map, const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, - int num_experts, int topk, int use_pre_softmax, + int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, NVTETensor grad_logits, cudaStream_t stream); @@ -218,9 +218,10 @@ void nvte_fused_topk_with_score_function_backward_v2(const NVTETensor routing_ma NVTERoutingMapFormat routing_map_format, const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, - int num_experts, int topk, int use_pre_softmax, - float scaling_factor, int score_function, - NVTETensor grad_logits, cudaStream_t stream); + int num_experts, int topk, + bool use_pre_softmax, float scaling_factor, + int score_function, NVTETensor grad_logits, + cudaStream_t stream); /*! \brief Backward pass for fused topk + score function with dense top-k indices. * @@ -228,7 +229,7 @@ void nvte_fused_topk_with_score_function_backward_v2(const NVTETensor routing_ma */ void nvte_fused_topk_with_score_function_backward_with_indices( const NVTETensor topk_indices, const NVTETensor intermediate_output, - const NVTETensor grad_probs, int num_tokens, int num_experts, int topk, int use_pre_softmax, + const NVTETensor grad_probs, int num_tokens, int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, NVTETensor grad_logits, cudaStream_t stream); /*! \brief Whether nvte_fused_topk_with_aux_loss_scores_forward/_backward support a router @@ -239,10 +240,10 @@ void nvte_fused_topk_with_score_function_backward_with_indices( * (default 16), i.e. the separate top-k kernels use their naive selection, whose tie-breaking * this kernel reproduces. * - * \return 1 if supported, 0 otherwise. + * \return Whether the configuration is supported. */ -int nvte_fused_topk_with_aux_loss_scores_is_supported(int num_experts, int topk, int num_groups, - int group_topk, int score_function); +bool nvte_fused_topk_with_aux_loss_scores_is_supported(int num_experts, int topk, int num_groups, + int group_topk, int score_function); /*! \brief Single-pass router forward: top-k routing plus the auxiliary-loss scores and counts. * diff --git a/transformer_engine/common/include/transformer_engine/gemm.h b/transformer_engine/common/include/transformer_engine/gemm.h index 24af57449f3..340e1b823be 100644 --- a/transformer_engine/common/include/transformer_engine/gemm.h +++ b/transformer_engine/common/include/transformer_engine/gemm.h @@ -214,7 +214,7 @@ void nvte_cublas_gemm(const NVTETensor A, const NVTETensor B, NVTETensor D, cons * \param[in] config Additional configuration. * \param[in] stream CUDA stream used for the operation. */ -void nvte_cublas_gemm_v2(int transa, int transb, const float *alpha, const NVTETensor A, +void nvte_cublas_gemm_v2(bool transa, bool transb, const float *alpha, const NVTETensor A, const NVTETensor B, const float *beta, const NVTETensor C, NVTETensor D, NVTETensor workspace, NVTEMatmulConfig config, cudaStream_t stream); @@ -248,7 +248,7 @@ void nvte_cublas_gemm_v2(int transa, int transb, const float *alpha, const NVTET * \param[in] config Additional configuration. * \param[in] stream CUDA stream used for the operation. */ -void nvte_cublas_gemm_strided_batched(int transa, int transb, const float *alpha, +void nvte_cublas_gemm_strided_batched(bool transa, bool transb, const float *alpha, const NVTETensor A, int batch_dim_a, const NVTETensor B, int batch_dim_b, const float *beta, const NVTETensor C, NVTETensor D, int batch_dim_d, NVTETensor workspace, @@ -283,7 +283,7 @@ void nvte_cublas_gemm_strided_batched(int transa, int transb, const float *alpha * \param[in] config Additional configuration. * \param[in] stream CUDA stream used for the operation. */ -void nvte_cublas_gemm_strided_batched_mxfp8(int transa, int transb, const float *alpha, +void nvte_cublas_gemm_strided_batched_mxfp8(bool transa, bool transb, const float *alpha, const NVTETensor A_data, const NVTETensor A_scale_inv, int batch_dim_a, const NVTETensor B_data, const NVTETensor B_scale_inv, int batch_dim_b, @@ -475,9 +475,9 @@ void nvte_compute_grouped_tensor_offsets(const int64_t *first_dims, int64_t *off * - Shape compatibility: if transa=false, transb=false: * - A[i]: (M[i], K[i]), B[i]: (K[i], N[i]), D[i]: (M[i], N[i]) */ -void nvte_grouped_gemm(const NVTEGroupedTensor A, int transa, const NVTEGroupedTensor B, int transb, - const NVTEGroupedTensor C, NVTEGroupedTensor D, const NVTETensor alpha, - const NVTETensor beta, NVTETensor workspace_setup, +void nvte_grouped_gemm(const NVTEGroupedTensor A, bool transa, const NVTEGroupedTensor B, + bool transb, const NVTEGroupedTensor C, NVTEGroupedTensor D, + const NVTETensor alpha, const NVTETensor beta, NVTETensor workspace_setup, NVTETensor workspace_cublas, NVTEGroupedMatmulConfig config, cudaStream_t stream); @@ -503,7 +503,7 @@ void nvte_grouped_gemm(const NVTEGroupedTensor A, int transa, const NVTEGroupedT * \param[in] stream CUDA stream for the operation. */ void nvte_grouped_gemm_with_discrete_inputA(const NVTETensor *A_list, size_t num_a_tensors, - int transa, const NVTEGroupedTensor B, int transb, + bool transa, const NVTEGroupedTensor B, bool transb, const NVTEGroupedTensor C, NVTEGroupedTensor D, const NVTETensor alpha, const NVTETensor beta, NVTETensor workspace_setup, NVTETensor workspace_cublas, @@ -532,8 +532,8 @@ void nvte_grouped_gemm_with_discrete_inputA(const NVTETensor *A_list, size_t num * \param[in] stream CUDA stream for the operation. * \note All tensors in C_list and D_list must share the same dtype. */ -void nvte_grouped_gemm_with_discrete_out(const NVTEGroupedTensor A, int transa, - const NVTEGroupedTensor B, int transb, +void nvte_grouped_gemm_with_discrete_out(const NVTEGroupedTensor A, bool transa, + const NVTEGroupedTensor B, bool transb, const NVTETensor *C_list, size_t num_c_tensors, NVTETensor *D_list, size_t num_d_tensors, const NVTETensor alpha, const NVTETensor beta, diff --git a/transformer_engine/common/include/transformer_engine/multi_tensor.h b/transformer_engine/common/include/transformer_engine/multi_tensor.h index 30f7669392e..ae923663ac0 100644 --- a/transformer_engine/common/include/transformer_engine/multi_tensor.h +++ b/transformer_engine/common/include/transformer_engine/multi_tensor.h @@ -37,7 +37,7 @@ extern "C" { void nvte_multi_tensor_l2norm_cuda(int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, NVTETensor output, NVTETensor output_per_tensor, NVTETensor ret, - NVTETensor ret_per_tensor, int per_tensor, + NVTETensor ret_per_tensor, bool per_tensor, int max_chunks_per_tensor, cudaStream_t stream); /*! \brief Computes L2 norm for a list of tensors after unscaling. @@ -65,7 +65,7 @@ void nvte_multi_tensor_unscale_l2norm_cuda(int chunk_size, NVTETensor noop_flag, const size_t num_tensors_per_list, NVTETensor output, NVTETensor output_per_tensor, NVTETensor ret, NVTETensor ret_per_tensor, NVTETensor inv_scale, - int per_tensor, int max_chunks_per_tensor, + bool per_tensor, int max_chunks_per_tensor, cudaStream_t stream); /*! \brief Compute and apply gradient update to parameters for Adam optimizer. @@ -91,7 +91,7 @@ void nvte_multi_tensor_adam_cuda(int chunk_size, NVTETensor noop_flag, NVTETenso const size_t num_tensor_lists, const size_t num_tensors_per_list, const float lr, const float beta1, const float beta2, const float epsilon, const int step, const int mode, - const int bias_correction, const float weight_decay, + const bool bias_correction, const float weight_decay, cudaStream_t stream); /*! \brief Compute and apply gradient update to parameters for Adam optimizer @@ -117,7 +117,7 @@ void nvte_multi_tensor_adam_cuda(int chunk_size, NVTETensor noop_flag, NVTETenso void nvte_multi_tensor_adam_param_remainder_cuda( int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, const float lr, const float beta1, const float beta2, - const float epsilon, const int step, const int mode, const int bias_correction, + const float epsilon, const int step, const int mode, const bool bias_correction, const float weight_decay, cudaStream_t stream); /*! \brief Compute and apply gradient update to parameters for Adam optimizer @@ -145,7 +145,7 @@ void nvte_multi_tensor_adam_fp8_cuda(int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, const float lr, const float beta1, const float beta2, const float epsilon, - const int step, const int mode, const int bias_correction, + const int step, const int mode, const bool bias_correction, const float weight_decay, const NVTEDType fp8_dtype, cudaStream_t stream); @@ -173,7 +173,7 @@ void nvte_multi_tensor_adam_fp8_cuda(int chunk_size, NVTETensor noop_flag, void nvte_multi_tensor_adam_capturable_cuda( int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, NVTETensor lr, const float beta1, const float beta2, - const float epsilon, NVTETensor step, const int mode, const int bias_correction, + const float epsilon, NVTETensor step, const int mode, const bool bias_correction, const float weight_decay, NVTETensor inv_scale, cudaStream_t stream); /*! \brief Compute and apply gradient update to parameters for Adam optimizer @@ -200,7 +200,7 @@ void nvte_multi_tensor_adam_capturable_cuda( void nvte_multi_tensor_adam_capturable_master_cuda( int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, NVTETensor lr, const float beta1, const float beta2, - const float epsilon, NVTETensor step, const int mode, const int bias_correction, + const float epsilon, NVTETensor step, const int mode, const bool bias_correction, const float weight_decay, NVTETensor inv_scale, cudaStream_t stream); /*! \brief Compute and apply gradient update to parameters for SGD optimizer. @@ -224,8 +224,8 @@ void nvte_multi_tensor_adam_capturable_master_cuda( */ void nvte_multi_tensor_sgd_cuda(int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, - float wd, float momentum, float dampening, float lr, int nesterov, - int first_run, int wd_after_momentum, float scale, + float wd, float momentum, float dampening, float lr, bool nesterov, + bool first_run, bool wd_after_momentum, float scale, cudaStream_t stream); /*! \brief Check overflow and scale a list of tensors. @@ -279,7 +279,7 @@ void nvte_multi_tensor_compute_scale_and_scale_inv_cuda(int chunk_size, NVTETens NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, - float max_fp8, int force_pow_2_scales, + float max_fp8, bool force_pow_2_scales, float epsilon, cudaStream_t stream); /*! \brief Compute E8M0 scale_inv for a list of tensors. diff --git a/transformer_engine/common/include/transformer_engine/transformer_engine.h b/transformer_engine/common/include/transformer_engine/transformer_engine.h index eb8c3cbc38a..bf0f2fdb9ba 100644 --- a/transformer_engine/common/include/transformer_engine/transformer_engine.h +++ b/transformer_engine/common/include/transformer_engine/transformer_engine.h @@ -482,7 +482,7 @@ void nvte_destroy_quantization_config(NVTEQuantizationConfig config); * * \return A flag which indicates whether non-TN FP8 Gemm is supported or not. */ -int nvte_is_non_tn_fp8_gemm_supported(void); +bool nvte_is_non_tn_fp8_gemm_supported(void); /*! \brief Performs a memset of the data at the given pointer and size in bytes. * diff --git a/transformer_engine/common/multi_tensor/adam.cu b/transformer_engine/common/multi_tensor/adam.cu index d1f5b44c238..41cbe721f1d 100644 --- a/transformer_engine/common/multi_tensor/adam.cu +++ b/transformer_engine/common/multi_tensor/adam.cu @@ -1044,7 +1044,7 @@ void nvte_multi_tensor_adam_cuda(int chunk_size, NVTETensor noop_flag, NVTETenso const size_t num_tensor_lists, const size_t num_tensors_per_list, const float lr, const float beta1, const float beta2, const float epsilon, const int step, const int mode, - const int bias_correction, const float weight_decay, + const bool bias_correction, const float weight_decay, cudaStream_t stream) { NVTE_API_CALL(nvte_multi_tensor_adam_cuda); using namespace transformer_engine; @@ -1058,7 +1058,7 @@ void nvte_multi_tensor_adam_cuda(int chunk_size, NVTETensor noop_flag, NVTETenso void nvte_multi_tensor_adam_param_remainder_cuda( int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, const float lr, const float beta1, const float beta2, - const float epsilon, const int step, const int mode, const int bias_correction, + const float epsilon, const int step, const int mode, const bool bias_correction, const float weight_decay, cudaStream_t stream) { NVTE_API_CALL(nvte_multi_tensor_adam_param_remainder_cuda); using namespace transformer_engine; @@ -1073,7 +1073,7 @@ void nvte_multi_tensor_adam_fp8_cuda(int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, const float lr, const float beta1, const float beta2, const float epsilon, - const int step, const int mode, const int bias_correction, + const int step, const int mode, const bool bias_correction, const float weight_decay, const NVTEDType fp8_dtype, cudaStream_t stream) { NVTE_API_CALL(nvte_multi_tensor_adam_fp8_cuda); @@ -1088,7 +1088,7 @@ void nvte_multi_tensor_adam_fp8_cuda(int chunk_size, NVTETensor noop_flag, void nvte_multi_tensor_adam_capturable_cuda( int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, NVTETensor lr, const float beta1, const float beta2, - const float epsilon, NVTETensor step, const int mode, const int bias_correction, + const float epsilon, NVTETensor step, const int mode, const bool bias_correction, const float weight_decay, NVTETensor inv_scale, cudaStream_t stream) { NVTE_API_CALL(nvte_multi_tensor_adam_capturable_cuda); using namespace transformer_engine; @@ -1103,7 +1103,7 @@ void nvte_multi_tensor_adam_capturable_cuda( void nvte_multi_tensor_adam_capturable_master_cuda( int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, NVTETensor lr, const float beta1, const float beta2, - const float epsilon, NVTETensor step, const int mode, const int bias_correction, + const float epsilon, NVTETensor step, const int mode, const bool bias_correction, const float weight_decay, NVTETensor inv_scale, cudaStream_t stream) { NVTE_API_CALL(nvte_multi_tensor_adam_capturable_master_cuda); using namespace transformer_engine; diff --git a/transformer_engine/common/multi_tensor/compute_scale.cu b/transformer_engine/common/multi_tensor/compute_scale.cu index d4039352afe..c74f1780c5c 100644 --- a/transformer_engine/common/multi_tensor/compute_scale.cu +++ b/transformer_engine/common/multi_tensor/compute_scale.cu @@ -108,7 +108,7 @@ void nvte_multi_tensor_compute_scale_and_scale_inv_cuda(int chunk_size, NVTETens NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, - float max_fp8, int force_pow_2_scales, + float max_fp8, bool force_pow_2_scales, float epsilon, cudaStream_t stream) { NVTE_API_CALL(nvte_multi_tensor_compute_scale_and_scale_inv_cuda); using namespace transformer_engine; diff --git a/transformer_engine/common/multi_tensor/l2norm.cu b/transformer_engine/common/multi_tensor/l2norm.cu index 5c2fdb2ca86..5ccad6bcba1 100644 --- a/transformer_engine/common/multi_tensor/l2norm.cu +++ b/transformer_engine/common/multi_tensor/l2norm.cu @@ -450,7 +450,7 @@ void multi_tensor_unscale_l2norm_cuda(int chunk_size, Tensor noop_flag, void nvte_multi_tensor_l2norm_cuda(int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, NVTETensor output, NVTETensor output_per_tensor, NVTETensor ret, - NVTETensor ret_per_tensor, int per_tensor, + NVTETensor ret_per_tensor, bool per_tensor, int max_chunks_per_tensor, cudaStream_t stream) { NVTE_API_CALL(nvte_multi_tensor_l2norm_cuda); using namespace transformer_engine; @@ -468,7 +468,7 @@ void nvte_multi_tensor_unscale_l2norm_cuda(int chunk_size, NVTETensor noop_flag, const size_t num_tensors_per_list, NVTETensor output, NVTETensor output_per_tensor, NVTETensor ret, NVTETensor ret_per_tensor, NVTETensor inv_scale, - int per_tensor, int max_chunks_per_tensor, + bool per_tensor, int max_chunks_per_tensor, cudaStream_t stream) { NVTE_API_CALL(nvte_multi_tensor_unscale_l2norm_cuda); using namespace transformer_engine; diff --git a/transformer_engine/common/multi_tensor/sgd.cu b/transformer_engine/common/multi_tensor/sgd.cu index 369e70ed26f..b7b291d1312 100644 --- a/transformer_engine/common/multi_tensor/sgd.cu +++ b/transformer_engine/common/multi_tensor/sgd.cu @@ -188,8 +188,8 @@ void multi_tensor_sgd_cuda(int chunk_size, Tensor noop_flag, void nvte_multi_tensor_sgd_cuda(int chunk_size, NVTETensor noop_flag, NVTETensor** tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, - float wd, float momentum, float dampening, float lr, int nesterov, - int first_run, int wd_after_momentum, float scale, + float wd, float momentum, float dampening, float lr, bool nesterov, + bool first_run, bool wd_after_momentum, float scale, cudaStream_t stream) { NVTE_API_CALL(nvte_multi_tensor_sgd_cuda); using namespace transformer_engine; diff --git a/transformer_engine/common/transformer_engine.cpp b/transformer_engine/common/transformer_engine.cpp index dcf96696f96..a7de84b87c8 100644 --- a/transformer_engine/common/transformer_engine.cpp +++ b/transformer_engine/common/transformer_engine.cpp @@ -1224,7 +1224,7 @@ void nvte_destroy_quantization_config(NVTEQuantizationConfig config) { } } -int nvte_is_non_tn_fp8_gemm_supported() { +bool nvte_is_non_tn_fp8_gemm_supported(void) { int num_devices = transformer_engine::cuda::num_devices(); static std::vector cache(num_devices, -1); static std::vector flags(num_devices); diff --git a/transformer_engine/pytorch/csrc/extensions/router.cpp b/transformer_engine/pytorch/csrc/extensions/router.cpp index d739a7c6062..2522436d7b7 100644 --- a/transformer_engine/pytorch/csrc/extensions/router.cpp +++ b/transformer_engine/pytorch/csrc/extensions/router.cpp @@ -330,7 +330,7 @@ bool fused_topk_with_aux_loss_scores_is_supported(int num_experts, int topk, auto it = score_function_map.find(score_function); if (it == score_function_map.end()) return false; return nvte_fused_topk_with_aux_loss_scores_is_supported( - num_experts, topk, num_groups.value_or(-1), group_topk.value_or(-1), it->second) != 0; + num_experts, topk, num_groups.value_or(-1), group_topk.value_or(-1), it->second); } std::tuple fused_topk_with_aux_loss_scores_fwd( diff --git a/transformer_engine/pytorch/csrc/quantizer.cpp b/transformer_engine/pytorch/csrc/quantizer.cpp index d6264dc1359..6e795dbd6fe 100644 --- a/transformer_engine/pytorch/csrc/quantizer.cpp +++ b/transformer_engine/pytorch/csrc/quantizer.cpp @@ -356,7 +356,7 @@ std::pair Float8Quantizer::create_tensor( std::optional device_opt, bool pin_memory) const { const auto device = resolve_device(device_opt, data); using namespace pybind11::literals; - int is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); + const bool is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); // Initialize data tensor const bool with_data = rowwise_usage || is_non_tn_fp8_gemm_supported; if (with_data && !data) { @@ -539,7 +539,7 @@ std::pair Float8Quantizer::create_grouped_tens std::pair Float8Quantizer::convert_and_update_tensor( py::object tensor) const { NVTE_CHECK(detail::IsFloat8Tensor(tensor.ptr()), "Float8Quantizer must output to Float8Tensor."); - int is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); + const bool is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); // Expected buffers const bool need_data = rowwise_usage || is_non_tn_fp8_gemm_supported; const bool need_transpose = columnwise_usage && !is_non_tn_fp8_gemm_supported; @@ -673,7 +673,7 @@ std::pair Float8CurrentScalingQuantizer::create_tenso // Initialize data tensor at::Tensor data_tensor; - int is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); + const bool is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); const bool with_data = rowwise_usage || is_non_tn_fp8_gemm_supported; if (with_data) { const std::vector shape_int64(shape.begin(), shape.end()); @@ -887,7 +887,7 @@ std::pair Float8CurrentScalingQuantizer::convert_and_ py::object tensor) const { NVTE_CHECK(detail::IsFloat8Tensor(tensor.ptr()), "Float8CurrentScalingQuantizer must output to Float8Tensor."); - int is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); + const bool is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); // Expected buffers const bool need_data = rowwise_usage || is_non_tn_fp8_gemm_supported; const bool need_transpose = columnwise_usage && !is_non_tn_fp8_gemm_supported; From dc48e2e09660888b173f3389e39bb6b244b060ca Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 18:09:15 -0800 Subject: [PATCH 03/18] [Common] Replace deprecated C API functions with their versioned signatures Give each unversioned C API function the signature and behavior of its latest _v2 variant, and keep the _v2 names as deprecated aliases that forward to it. Internal callers in common, PyTorch, JAX, and the tests now use the unversioned names. The EP functions are left unchanged while that code is being refactored separately. Notable consequences: - nvte_cublas_gemm takes alpha/beta/C and an NVTEMatmulConfig. The comm-GEMM overlap code and the distributed test map the old bias/GELU/accumulate arguments onto the config. - The MoE aux-loss kernels only implement the deterministic two-stage reduction and require a workspace. The atomic path is removed, the PyTorch deterministic keyword is a deprecated no-op that warns, and the JAX primitive allocates the workspace. - nvte_clamped_swiglu/dswiglu take glu_linear_offset and nvte_splits_to_offsets_multi takes split_alignment. Also remove nvte_quantize_noop (use the quantization config's noop tensor), nvte_cublas_gemm_scaled, and the deprecated _unchecked fused-router functions. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tim Moon --- tests/cpp/operator/test_cast.cu | 2 +- .../cpp/operator/test_cast_current_scaling.cu | 2 +- .../cpp/operator/test_cast_float8blockwise.cu | 4 +- .../test_cast_float8blockwise_grouped.cu | 4 +- tests/cpp/operator/test_cast_mxfp8.cu | 16 +- .../cpp/operator/test_cast_mxfp8_act_exact.cu | 6 +- .../cpp/operator/test_cast_nvfp4_transpose.cu | 28 ++- tests/cpp/operator/test_cast_transpose.cu | 2 +- .../test_cast_transpose_current_scaling.cu | 2 +- tests/cpp/operator/test_dequantize_mxfp8.cu | 2 +- tests/cpp/operator/test_dequantize_nvfp4.cu | 4 +- .../cpp/operator/test_fused_moe_aux_loss.cpp | 8 +- tests/cpp/operator/test_gemm.cu | 24 +- tests/cpp/operator/test_grouped_gemm.cu | 12 +- tests/cpp/operator/test_qdq.cu | 2 +- .../test_row_scaled_nvfp4_grouped_cast.cu | 2 +- tests/cpp/test_common.cu | 4 +- tests/cpp/test_common.h | 7 + tests/cpp/util/test_c_api.c | 58 +++-- tests/cpp_distributed/test_comm_gemm.cu | 36 ++- tests/pytorch/test_fused_router.py | 108 +++------ .../CuTeDSL/cast/mxfp8/quantize_mxfp8_2d.py | 2 +- .../common/activation/swiglu.cu | 21 +- transformer_engine/common/cast/cast.cu | 23 +- .../comm_gemm_overlap/comm_gemm_overlap.cpp | 72 +++--- .../common/fused_attn/config_and_params.cpp | 2 +- .../common/fused_attn/fused_attn.cpp | 188 ++-------------- .../common/fused_router/fused_moe_aux_loss.cu | 132 ++++------- .../fused_score_for_moe_aux_loss.cu | 28 +-- .../fused_topk_with_score_function.cu | 85 +++---- .../common/gemm/cublaslt_gemm.cu | 74 +------ .../include/transformer_engine/activation.h | 66 ++---- .../common/include/transformer_engine/cast.h | 42 ++-- .../include/transformer_engine/fused_attn.h | 207 +++--------------- .../include/transformer_engine/fused_router.h | 196 ++++++----------- .../common/include/transformer_engine/gemm.h | 69 +----- .../include/transformer_engine/recipe.h | 94 +++----- .../transformer_engine/transformer_engine.h | 79 ++++--- transformer_engine/common/recipe/nvfp4.cu | 95 ++++---- .../common/transformer_engine.cpp | 77 ++----- .../common/util/splits_to_offsets.cu | 25 ++- .../jax/cpp_extensions/router.py | 30 ++- transformer_engine/jax/csrc/extensions.h | 1 + .../jax/csrc/extensions/activation.cpp | 8 +- .../jax/csrc/extensions/gemm.cpp | 8 +- .../jax/csrc/extensions/pybind.cpp | 1 + .../jax/csrc/extensions/quantization.cpp | 4 +- .../jax/csrc/extensions/router.cpp | 26 ++- transformer_engine/pytorch/csrc/extensions.h | 12 +- .../pytorch/csrc/extensions/activation.cpp | 4 +- .../pytorch/csrc/extensions/cast.cpp | 2 +- .../pytorch/csrc/extensions/gemm.cpp | 6 +- .../extensions/grouped_mlp_experimental.cpp | 6 +- .../pytorch/csrc/extensions/misc.cpp | 8 +- .../csrc/extensions/nvfp4_2d_partial_cast.cpp | 16 +- .../pytorch/csrc/extensions/pybind.cpp | 4 +- .../pytorch/csrc/extensions/recipe.cpp | 6 +- .../pytorch/csrc/extensions/router.cpp | 60 ++--- .../pytorch/csrc/extensions/swizzle.cpp | 6 +- .../pytorch/csrc/extensions/transpose.cpp | 26 +-- transformer_engine/pytorch/csrc/quantizer.cpp | 16 +- transformer_engine/pytorch/router.py | 50 +++-- 62 files changed, 766 insertions(+), 1444 deletions(-) diff --git a/tests/cpp/operator/test_cast.cu b/tests/cpp/operator/test_cast.cu index e8f48feef87..ac90604ed15 100644 --- a/tests/cpp/operator/test_cast.cu +++ b/tests/cpp/operator/test_cast.cu @@ -55,7 +55,7 @@ void performTest(const std::vector& shape) { setRandomScale(&output_c); const float ref_scale = isFp8Type(otype) ? output_c.scale() : 1.0f; - nvte_quantize(input.data(), output_c.data(), 0); + nvte_quantize(input.data(), output_c.data(), nullptr, 0); float ref_amax; diff --git a/tests/cpp/operator/test_cast_current_scaling.cu b/tests/cpp/operator/test_cast_current_scaling.cu index 7cca0d72e0f..ece1ab91433 100644 --- a/tests/cpp/operator/test_cast_current_scaling.cu +++ b/tests/cpp/operator/test_cast_current_scaling.cu @@ -128,7 +128,7 @@ void performTest(const std::vector& shape) { amax_to_check = output_c.amax(); output_c.set_tensor_amax_nullptr(); } - nvte_quantize(input.data(), output_c.data(), 0); + nvte_quantize(input.data(), output_c.data(), nullptr, 0); float ref_amax; float ref_scale = 1.0; diff --git a/tests/cpp/operator/test_cast_float8blockwise.cu b/tests/cpp/operator/test_cast_float8blockwise.cu index d50589ca437..7d2d1ccef98 100644 --- a/tests/cpp/operator/test_cast_float8blockwise.cu +++ b/tests/cpp/operator/test_cast_float8blockwise.cu @@ -305,7 +305,7 @@ void runTestCase(const ProcessingMethod processing_method, const std::vector& shape, QuantizationConfigWrapper quant_config; quant_config.set_mxfp8_2d_quantization(true); - nvte_quantize_v2(input.data(), output.data(), quant_config, 0); + nvte_quantize(input.data(), output.data(), quant_config, 0); cudaDeviceSynchronize(); auto err = cudaGetLastError(); @@ -1087,7 +1087,7 @@ TEST_P(SwizzledScalesFusedCastMXFP8TestSuite, TestSwizzledCastMXFP8) { // CastTraitsSwizzle<..., kCacheColwise=true, kSwizzled=true> on kernel #3. Tensor output_swizzled("output_swizzled", shape, otype, true, true, NVTE_MXFP8_1D_SCALING); output_swizzled.set_with_gemm_swizzled_scales(true); - nvte_quantize(input.data(), output_swizzled.data(), 0); + nvte_quantize(input.data(), output_swizzled.data(), nullptr, 0); // Rowwise-only activations take the pointer-based cast-only kernel. This // directly exercises its WITH_GEMM_SWIZZLED_SCALES trait specialization @@ -1096,7 +1096,7 @@ TEST_P(SwizzledScalesFusedCastMXFP8TestSuite, TestSwizzledCastMXFP8) { /*rowwise=*/true, /*colwise=*/false, NVTE_MXFP8_1D_SCALING); output_rowwise_swizzled.set_with_gemm_swizzled_scales(true); - nvte_quantize(input.data(), output_rowwise_swizzled.data(), 0); + nvte_quantize(input.data(), output_rowwise_swizzled.data(), nullptr, 0); cudaDeviceSynchronize(); ASSERT_EQ(cudaGetLastError(), cudaSuccess) << "swizzled-scale nvte_quantize failed"; @@ -1111,7 +1111,7 @@ TEST_P(SwizzledScalesFusedCastMXFP8TestSuite, TestSwizzledCastMXFP8) { // Rowwise reference. Tensor linear_row("linear_row", shape, otype, /*rowwise=*/true, /*colwise=*/false, NVTE_MXFP8_1D_SCALING); - nvte_quantize(input.data(), linear_row.data(), 0); + nvte_quantize(input.data(), linear_row.data(), nullptr, 0); Tensor ref_row_swz("ref_row_swz", shape, otype, /*rowwise=*/true, /*colwise=*/false, NVTE_MXFP8_1D_SCALING); ref_row_swz.set_with_gemm_swizzled_scales(true); @@ -1124,7 +1124,7 @@ TEST_P(SwizzledScalesFusedCastMXFP8TestSuite, TestSwizzledCastMXFP8) { // Colwise reference. Tensor linear_col("linear_col", shape, otype, /*rowwise=*/false, /*colwise=*/true, NVTE_MXFP8_1D_SCALING); - nvte_quantize(input.data(), linear_col.data(), 0); + nvte_quantize(input.data(), linear_col.data(), nullptr, 0); Tensor ref_col_swz("ref_col_swz", shape, otype, /*rowwise=*/false, /*colwise=*/true, NVTE_MXFP8_1D_SCALING); ref_col_swz.set_with_gemm_swizzled_scales(true); @@ -1386,7 +1386,7 @@ TEST_P(CompactScalesCastMXFP8TestSuite, TestCompactScales) { // CAST_DBIAS covers the larger tiles of the generic kernel's dbias variant. auto quantize = [&](NVTETensor output) { if (processing_method == ProcessingMethod::CAST_ONLY) { - nvte_quantize(input.data(), output, 0); + nvte_quantize(input.data(), output, nullptr, 0); return; } Tensor dbias("dbias", std::vector{ cols }, itype); diff --git a/tests/cpp/operator/test_cast_mxfp8_act_exact.cu b/tests/cpp/operator/test_cast_mxfp8_act_exact.cu index 1b523cc4bab..cfc7dd77c40 100644 --- a/tests/cpp/operator/test_cast_mxfp8_act_exact.cu +++ b/tests/cpp/operator/test_cast_mxfp8_act_exact.cu @@ -306,7 +306,9 @@ void run_case(const Mode mode, const Fill fill, const size_t rows, const size_t Tensor ref("ref", shape, otype, rowwise, colwise, NVTE_MXFP8_1D_SCALING); ref.set_with_gemm_swizzled_scales(swizzled); Tensor noop("noop", std::vector{1}, DType::kFloat32); - nvte_quantize_noop(y.data(), ref.data(), noop.data(), 0); + QuantizationConfigWrapper quant_config; + quant_config.set_noop_tensor(noop.data()); + nvte_quantize(y.data(), ref.data(), quant_config, 0); // Fused. Tensor out("out", shape, otype, rowwise, colwise, NVTE_MXFP8_1D_SCALING); @@ -317,7 +319,7 @@ void run_case(const Mode mode, const Fill fill, const size_t rows, const size_t ASSERT_EQ(cudaMemset(amax_dev, 0, sizeof(float)), cudaSuccess); const size_t one = 1; const NVTEBasicTensor amax = {amax_dev, kNVTEFloat32, nvte_make_shape(&one, 1)}; - nvte_set_tensor_param_v2(out.data(), kNVTEAmax, &amax, sizeof(amax)); + nvte_set_tensor_param(out.data(), kNVTEAmax, &amax, sizeof(amax)); } Tensor dbias("dbias", std::vector{cols}, itype); Tensor workspace; diff --git a/tests/cpp/operator/test_cast_nvfp4_transpose.cu b/tests/cpp/operator/test_cast_nvfp4_transpose.cu index b3257bf344d..80905fa9976 100644 --- a/tests/cpp/operator/test_cast_nvfp4_transpose.cu +++ b/tests/cpp/operator/test_cast_nvfp4_transpose.cu @@ -1045,7 +1045,7 @@ void performTest(float (*OP)(const float), // Call appropriate function based on operation type // Activation functions take 3 parameters (input, output, stream) - // nvte_quantize_v2 takes 4 parameters (input, output, quant_config, stream) + // nvte_quantize takes 4 parameters (input, output, quant_config, stream) if (OP == &gelu) { nvte_gelu(input.data(), output.data(), 0); } else if (OP == &silu) { @@ -1057,7 +1057,7 @@ void performTest(float (*OP)(const float), } else if (OP == &srelu) { nvte_srelu(input.data(), output.data(), 0); } else { - nvte_quantize_v2(input.data(), output.data(), quant_config, 0); + nvte_quantize(input.data(), output.data(), quant_config, 0); } cudaDeviceSynchronize(); @@ -1170,8 +1170,8 @@ void performTestColumnwiseOnly2D(const std::vector& shape) { quant_config.set_stochastic_rounding(false); quant_config.set_nvfp4_2d_quantization(true); - nvte_quantize_v2(input.data(), output_both.data(), quant_config, 0); - nvte_quantize_v2(input.data(), output_col.data(), quant_config, 0); + nvte_quantize(input.data(), output_both.data(), quant_config, 0); + nvte_quantize(input.data(), output_col.data(), quant_config, 0); cudaDeviceSynchronize(); auto err = cudaGetLastError(); @@ -1260,7 +1260,7 @@ void performTestRowScaledTranspose(const std::vector& shape) { fillCase(&input, InputsFillCase::uniform); // System under test: row-scaled NVFP4 with both directions requested in one - // call. The transpose kernel is selected by the generic nvte_quantize_v2 + // call. The transpose kernel is selected by the generic nvte_quantize // dispatch when a row-scaled tensor (set_row_scaled_nvfp4) also allocates a // columnwise output -- no dedicated config flag. Tensor output("output", shape, otype, /*rowwise=*/true, /*columnwise=*/true, @@ -1271,7 +1271,7 @@ void performTestRowScaledTranspose(const std::vector& shape) { output.set_row_scaled_nvfp4(true); QuantizationConfigWrapper quant_config; quant_config.set_stochastic_rounding(false); - nvte_quantize_v2(input.data(), output.data(), quant_config, 0); + nvte_quantize(input.data(), output.data(), quant_config, 0); // Reference (rowwise direction): trusted row-scaled 1D kernel on the input. Tensor ref_row("ref_row", shape, otype, /*rowwise=*/true, /*columnwise=*/false, @@ -1279,7 +1279,7 @@ void performTestRowScaledTranspose(const std::vector& shape) { ref_row.set_row_scaled_nvfp4(true); QuantizationConfigWrapper ref_config; ref_config.set_stochastic_rounding(false); - nvte_quantize_v2(input.data(), ref_row.data(), ref_config, 0); + nvte_quantize(input.data(), ref_row.data(), ref_config, 0); // Reference (columnwise direction): trusted row-scaled 1D kernel on input^T. input.to_cpu(); @@ -1292,7 +1292,7 @@ void performTestRowScaledTranspose(const std::vector& shape) { Tensor ref_col("ref_col", shape_t, otype, /*rowwise=*/true, /*columnwise=*/false, NVTE_NVFP4_1D_SCALING); ref_col.set_row_scaled_nvfp4(true); - nvte_quantize_v2(input_t.data(), ref_col.data(), ref_config, 0); + nvte_quantize(input_t.data(), ref_col.data(), ref_config, 0); cudaDeviceSynchronize(); ASSERT_EQ(cudaGetLastError(), cudaSuccess) << cudaGetErrorString(cudaGetLastError()); @@ -1368,8 +1368,8 @@ void performTestRowScaledColumnwiseOnly(const std::vector& shape) { QuantizationConfigWrapper quant_config; quant_config.set_stochastic_rounding(false); - nvte_quantize_v2(input.data(), output.data(), quant_config, 0); - nvte_quantize_v2(input.data(), ref.data(), quant_config, 0); + nvte_quantize(input.data(), output.data(), quant_config, 0); + nvte_quantize(input.data(), ref.data(), quant_config, 0); cudaDeviceSynchronize(); ASSERT_EQ(cudaGetLastError(), cudaSuccess) << cudaGetErrorString(cudaGetLastError()); @@ -1668,10 +1668,9 @@ TEST(NVFP4UE5M3ReferenceTest, Grouped) { Tensor output_storage("ue5m3_group_output_storage", input_shape, DType::kFloat4E2M1, true, false, NVTE_NVFP4_1D_SCALING, DType::kFloat8UE5M3); - const NVTEBasicTensor storage_data = - nvte_get_tensor_param(output_storage.data(), kNVTERowwiseData); + const NVTEBasicTensor storage_data = get_tensor_param(output_storage.data(), kNVTERowwiseData); const NVTEBasicTensor storage_scales = - nvte_get_tensor_param(output_storage.data(), kNVTERowwiseScaleInv); + get_tensor_param(output_storage.data(), kNVTERowwiseScaleInv); std::vector output_metadata; std::vector output_views; @@ -1684,8 +1683,7 @@ TEST(NVFP4UE5M3ReferenceTest, Grouped) { DType::kFloat4E2M1, true, false, NVTE_NVFP4_1D_SCALING, DType::kFloat8UE5M3); output_metadata.back().set_amax(golden_amax); - const NVTEBasicTensor amax = - nvte_get_tensor_param(output_metadata.back().data(), kNVTEAmax); + const NVTEBasicTensor amax = get_tensor_param(output_metadata.back().data(), kNVTEAmax); auto *data_ptr = reinterpret_cast(storage_data.data_ptr) + i * rows * cols / 2; auto *scale_ptr = diff --git a/tests/cpp/operator/test_cast_transpose.cu b/tests/cpp/operator/test_cast_transpose.cu index 9a5dc959daf..39cc9398a26 100644 --- a/tests/cpp/operator/test_cast_transpose.cu +++ b/tests/cpp/operator/test_cast_transpose.cu @@ -57,7 +57,7 @@ void performTest(const size_t N, const size_t H) { setRandomScale(&output); const float ref_scale = isFp8Type(otype) ? output.scale() : 1.0f; - nvte_quantize(input.data(), output.data(), 0); + nvte_quantize(input.data(), output.data(), nullptr, 0); float ref_amax; compute_ref(input.rowwise_cpu_dptr(), ref_output_c.get(), diff --git a/tests/cpp/operator/test_cast_transpose_current_scaling.cu b/tests/cpp/operator/test_cast_transpose_current_scaling.cu index 225d24317a3..35f498e9def 100644 --- a/tests/cpp/operator/test_cast_transpose_current_scaling.cu +++ b/tests/cpp/operator/test_cast_transpose_current_scaling.cu @@ -130,7 +130,7 @@ void performTest(const size_t N, const size_t H) { amax_to_check = output.amax(); output.set_tensor_amax_nullptr(); } - nvte_quantize(input.data(), output.data(), 0); + nvte_quantize(input.data(), output.data(), nullptr, 0); float ref_amax; float ref_scale; diff --git a/tests/cpp/operator/test_dequantize_mxfp8.cu b/tests/cpp/operator/test_dequantize_mxfp8.cu index 5950fba9803..50cb2fa565e 100644 --- a/tests/cpp/operator/test_dequantize_mxfp8.cu +++ b/tests/cpp/operator/test_dequantize_mxfp8.cu @@ -280,7 +280,7 @@ void performTest_quantize_then_dequantize(const size_t rows, const size_t copy_size = sizeof(InputType) * rows * cols; cudaMemcpy(input_cpu.get(), input.rowwise_dptr(), copy_size, cudaMemcpyDeviceToHost); - nvte_quantize(input.data(), quantized.data(), 0); + nvte_quantize(input.data(), quantized.data(), nullptr, 0); cudaDeviceSynchronize(); const size_t copy_size_quantized = sizeof(IntermediateType) * rows * cols; diff --git a/tests/cpp/operator/test_dequantize_nvfp4.cu b/tests/cpp/operator/test_dequantize_nvfp4.cu index 3cf9c128129..ec8213d7d6f 100644 --- a/tests/cpp/operator/test_dequantize_nvfp4.cu +++ b/tests/cpp/operator/test_dequantize_nvfp4.cu @@ -156,7 +156,7 @@ void performTest_dequantize_nvfp4(const size_t rows, const size_t cols, if (rows > 0 && cols > 0) { QuantizationConfigWrapper quant_config; quant_config.set_nvfp4_4over6_mode(mode); - nvte_quantize_v2(input.data(), quantized.data(), quant_config, 0); + nvte_quantize(input.data(), quantized.data(), quant_config, 0); cudaDeviceSynchronize(); auto err = cudaGetLastError(); ASSERT_EQ(err, cudaSuccess) << cudaGetErrorString(err); @@ -223,7 +223,7 @@ void performTest_dequantize_nvfp4_swizzled(const size_t rows, const size_t cols, if (rows > 0 && cols > 0) { QuantizationConfigWrapper quant_config; quant_config.set_nvfp4_4over6_mode(mode); - nvte_quantize_v2(input.data(), quantized_compact.data(), quant_config, 0); + nvte_quantize(input.data(), quantized_compact.data(), quant_config, 0); cudaDeviceSynchronize(); } diff --git a/tests/cpp/operator/test_fused_moe_aux_loss.cpp b/tests/cpp/operator/test_fused_moe_aux_loss.cpp index 7b79c63a667..d3c09f2c4e0 100644 --- a/tests/cpp/operator/test_fused_moe_aux_loss.cpp +++ b/tests/cpp/operator/test_fused_moe_aux_loss.cpp @@ -20,11 +20,11 @@ using transformer_engine::TensorWrapper; // calls also verify invalid workspaces fail before accessing other tensors. void call_aux_loss(bool graph_safe, NVTETensor workspace, int num_rows) { if (graph_safe) { - nvte_fused_moe_aux_loss_forward_graph_safe_v2(nullptr, nullptr, nullptr, 0, num_rows, 0, 0, - 0.0f, nullptr, nullptr, workspace, nullptr); + nvte_fused_moe_aux_loss_forward_graph_safe(nullptr, nullptr, nullptr, 0, num_rows, 0, 0, + 0.0f, nullptr, nullptr, workspace, nullptr); } else { - nvte_fused_moe_aux_loss_forward_v2(nullptr, nullptr, 0, 0, num_rows, 0, 0, 0.0f, nullptr, - nullptr, workspace, nullptr); + nvte_fused_moe_aux_loss_forward(nullptr, nullptr, 0, 0, num_rows, 0, 0, 0.0f, nullptr, + nullptr, workspace, nullptr); } } diff --git a/tests/cpp/operator/test_gemm.cu b/tests/cpp/operator/test_gemm.cu index 987ac3c55e3..c890a67196f 100644 --- a/tests/cpp/operator/test_gemm.cu +++ b/tests/cpp/operator/test_gemm.cu @@ -164,8 +164,8 @@ void run_gemm_test(const GemmTestParams ¶ms, bool with_C) { // Launch GEMM MatmulConfigWrapper config; config.set_use_split_accumulator(true); - nvte_cublas_gemm_v2(transa, transb, &alpha, A.data(), B.data(), &beta, - with_C ? C.data() : nullptr, D.data(), workspace.data(), config, 0); + nvte_cublas_gemm(transa, transb, &alpha, A.data(), B.data(), &beta, + with_C ? C.data() : nullptr, D.data(), workspace.data(), config, 0); NVTE_CHECK_CUDA(cudaDeviceSynchronize()); // Check output @@ -230,11 +230,11 @@ TEST(GemmTest, InvalidAccumulationInput) { Tensor workspace("workspace", std::vector{kWorkspaceBytes}, DType::kByte); const float alpha = 1.f; const float beta = 1.f; - EXPECT_THROW(nvte_cublas_gemm_v2(true, false, &alpha, A.data(), B.data(), &beta, - C_wrong_dtype.data(), D.data(), workspace.data(), nullptr, 0), + EXPECT_THROW(nvte_cublas_gemm(true, false, &alpha, A.data(), B.data(), &beta, + C_wrong_dtype.data(), D.data(), workspace.data(), nullptr, 0), std::runtime_error); - EXPECT_THROW(nvte_cublas_gemm_v2(true, false, &alpha, A.data(), B.data(), &beta, - C_wrong_shape.data(), D.data(), workspace.data(), nullptr, 0), + EXPECT_THROW(nvte_cublas_gemm(true, false, &alpha, A.data(), B.data(), &beta, + C_wrong_shape.data(), D.data(), workspace.data(), nullptr, 0), std::runtime_error); } @@ -254,15 +254,15 @@ TEST(GemmTest, InvalidAccumulationInputWithFP8Output) { const float beta = 1.f; // FP8 output cannot be accumulated in-place, even if beta is zero - EXPECT_THROW(nvte_cublas_gemm_v2(true, false, &alpha, A.data(), B.data(), &zero, D.data(), - D.data(), workspace.data(), nullptr, 0), + EXPECT_THROW(nvte_cublas_gemm(true, false, &alpha, A.data(), B.data(), &zero, D.data(), + D.data(), workspace.data(), nullptr, 0), std::runtime_error); - EXPECT_THROW(nvte_cublas_gemm_v2(true, false, &alpha, A.data(), B.data(), &beta, D.data(), - D.data(), workspace.data(), nullptr, 0), + EXPECT_THROW(nvte_cublas_gemm(true, false, &alpha, A.data(), B.data(), &beta, D.data(), + D.data(), workspace.data(), nullptr, 0), std::runtime_error); // FP8 output requires FP16 or BF16 C - EXPECT_THROW(nvte_cublas_gemm_v2(true, false, &alpha, A.data(), B.data(), &beta, - C_fp32.data(), D.data(), workspace.data(), nullptr, 0), + EXPECT_THROW(nvte_cublas_gemm(true, false, &alpha, A.data(), B.data(), &beta, + C_fp32.data(), D.data(), workspace.data(), nullptr, 0), std::runtime_error); } diff --git a/tests/cpp/operator/test_grouped_gemm.cu b/tests/cpp/operator/test_grouped_gemm.cu index b5b4090a2a0..a36b88ff38b 100644 --- a/tests/cpp/operator/test_grouped_gemm.cu +++ b/tests/cpp/operator/test_grouped_gemm.cu @@ -115,7 +115,7 @@ Tensor make_fp8_operand(const std::string& name, const std::vector& shap nvte_compute_amax(input_fp32.data(), fp8.data(), 0); QuantizationConfigWrapper config; nvte_compute_scale_from_amax(fp8.data(), config, 0); - nvte_quantize(input_fp32.data(), fp8.data(), 0); + nvte_quantize(input_fp32.data(), fp8.data(), nullptr, 0); return fp8; } @@ -136,7 +136,7 @@ Tensor make_mxfp8_operand(const std::string& name, const std::vector& sh Tensor mxfp8(name, shape, TypeInfo::dtype, use_rowwise, !use_rowwise, NVTE_MXFP8_1D_SCALING); - nvte_quantize(input_bf16.data(), mxfp8.data(), 0); + nvte_quantize(input_bf16.data(), mxfp8.data(), nullptr, 0); Tensor mxfp8_swizzled(name + "_swizzled", shape, TypeInfo::dtype, use_rowwise, !use_rowwise, NVTE_MXFP8_1D_SCALING); @@ -162,7 +162,7 @@ Tensor make_nvfp4_operand(const std::string& name, const std::vector& sh Tensor nvfp4(name, shape, DType::kFloat4E2M1, use_rowwise, !use_rowwise, NVTE_NVFP4_1D_SCALING); QuantizationConfigWrapper quant_config; - nvte_quantize_v2(input_bf16.data(), nvfp4.data(), quant_config, 0); + nvte_quantize(input_bf16.data(), nvfp4.data(), quant_config, 0); Tensor nvfp4_sw(name + "_sw", shape, DType::kFloat4E2M1, use_rowwise, !use_rowwise, NVTE_NVFP4_1D_SCALING); @@ -170,8 +170,8 @@ Tensor make_nvfp4_operand(const std::string& name, const std::vector& sh // Copy quantized data + amax to swizzled tensor (swizzle only rewrites scale_inv). const auto amax_kind = use_rowwise ? kNVTEAmax : kNVTEColumnwiseAmax; - const NVTEBasicTensor src_amax = nvte_get_tensor_param(nvfp4.data(), amax_kind); - const NVTEBasicTensor dst_amax = nvte_get_tensor_param(nvfp4_sw.data(), amax_kind); + const NVTEBasicTensor src_amax = get_tensor_param(nvfp4.data(), amax_kind); + const NVTEBasicTensor dst_amax = get_tensor_param(nvfp4_sw.data(), amax_kind); NVTE_CHECK_CUDA(cudaMemcpy(dst_amax.data_ptr, src_amax.data_ptr, sizeof(float), cudaMemcpyDeviceToDevice)); const size_t data_bytes = test::bytes( @@ -196,7 +196,7 @@ Tensor make_fp8_block_scaling_operand(const std::string& name, const std::vector scaling_mode); QuantizationConfigWrapper quant_config; quant_config.set_force_pow_2_scales(true); - nvte_quantize_v2(input_bf16.data(), fp8_bs.data(), quant_config, 0); + nvte_quantize(input_bf16.data(), fp8_bs.data(), quant_config, 0); NVTE_CHECK_CUDA(cudaDeviceSynchronize()); return fp8_bs; } diff --git a/tests/cpp/operator/test_qdq.cu b/tests/cpp/operator/test_qdq.cu index 034280aa9a2..141568bbbda 100644 --- a/tests/cpp/operator/test_qdq.cu +++ b/tests/cpp/operator/test_qdq.cu @@ -67,7 +67,7 @@ void performTestQ(const size_t N) { setRandomScale(&output); const float ref_scale = output.scale(); - nvte_quantize(input.data(), output.data(), 0); + nvte_quantize(input.data(), output.data(), nullptr, 0); float ref_amax; compute_ref_q(input.rowwise_cpu_dptr(), ref_output.get(), diff --git a/tests/cpp/operator/test_row_scaled_nvfp4_grouped_cast.cu b/tests/cpp/operator/test_row_scaled_nvfp4_grouped_cast.cu index 673eca5698d..48edfe1c8d2 100644 --- a/tests/cpp/operator/test_row_scaled_nvfp4_grouped_cast.cu +++ b/tests/cpp/operator/test_row_scaled_nvfp4_grouped_cast.cu @@ -97,7 +97,7 @@ GroupedReference build_reference(const std::vector>& ins QuantizationConfigWrapper quant_config; quant_config.set_stochastic_rounding(false); for (size_t i = 0; i < num_tensors; ++i) { - nvte_quantize_v2(ins[i]->data(), ref[i]->data(), quant_config, 0); + nvte_quantize(ins[i]->data(), ref[i]->data(), quant_config, 0); } cudaDeviceSynchronize(); diff --git a/tests/cpp/test_common.cu b/tests/cpp/test_common.cu index 5cb4a93c7e4..3cdffa2f0c6 100644 --- a/tests/cpp/test_common.cu +++ b/tests/cpp/test_common.cu @@ -1381,12 +1381,12 @@ GroupedBuffers build_grouped_tensor(const std::vector& tensors, // Gather per-tensor amax values for NVFP4 global scale computation auto gather_amax = [&](NVTETensorParam param) -> CudaPtr<> { // Check if first tensor has this amax - NVTEBasicTensor first_amax = nvte_get_tensor_param(tensors[0]->data(), param); + NVTEBasicTensor first_amax = get_tensor_param(tensors[0]->data(), param); if (first_amax.data_ptr == nullptr) return CudaPtr<>(); std::vector amax_cpu(num_tensors); for (size_t i = 0; i < num_tensors; ++i) { - NVTEBasicTensor amax_bt = nvte_get_tensor_param(tensors[i]->data(), param); + NVTEBasicTensor amax_bt = get_tensor_param(tensors[i]->data(), param); NVTE_CHECK(amax_bt.data_ptr != nullptr, "Tensor ", i, " is missing amax"); float val; NVTE_CHECK_CUDA(cudaMemcpy(&val, amax_bt.data_ptr, sizeof(float), cudaMemcpyDeviceToHost)); diff --git a/tests/cpp/test_common.h b/tests/cpp/test_common.h index cd96d65beb4..83834f5a3af 100644 --- a/tests/cpp/test_common.h +++ b/tests/cpp/test_common.h @@ -35,6 +35,13 @@ size_t product(const NVTEShape &shape); size_t product(const std::vector &shape); size_t bytes(const NVTEShape& shape, const DType type); +// Query a tensor parameter that is stored as an NVTEBasicTensor. +inline NVTEBasicTensor get_tensor_param(NVTETensor tensor, NVTETensorParam param) { + NVTEBasicTensor ret; + nvte_get_tensor_param(tensor, param, &ret, sizeof(ret), nullptr); + return ret; +} + template struct BytesToType {}; diff --git a/tests/cpp/util/test_c_api.c b/tests/cpp/util/test_c_api.c index 93e3d3805eb..00bbe104172 100644 --- a/tests/cpp/util/test_c_api.c +++ b/tests/cpp/util/test_c_api.c @@ -74,7 +74,7 @@ void call_every_c_api_function(void) { nvte_geglu(NULL, NULL, NULL); nvte_swiglu(NULL, NULL, NULL); nvte_situglu(NULL, NULL, 0, 0, NULL); - nvte_clamped_swiglu(NULL, NULL, 0, 0, NULL); + nvte_clamped_swiglu(NULL, NULL, 0, 0, 0, NULL); nvte_clamped_swiglu_v2(NULL, NULL, 0, 0, 0, NULL); nvte_scaled_swiglu(NULL, NULL, NULL, 0, NULL); nvte_scaled_situglu(NULL, NULL, NULL, 0, 0, 0, NULL); @@ -85,7 +85,7 @@ void call_every_c_api_function(void) { nvte_dgeglu(NULL, NULL, NULL, NULL); nvte_dswiglu(NULL, NULL, NULL, NULL); nvte_dsituglu(NULL, NULL, NULL, 0, 0, NULL); - nvte_clamped_dswiglu(NULL, NULL, NULL, 0, 0, NULL); + nvte_clamped_dswiglu(NULL, NULL, NULL, 0, 0, 0, NULL); nvte_clamped_dswiglu_v2(NULL, NULL, NULL, 0, 0, 0, NULL); nvte_scaled_dswiglu(NULL, NULL, NULL, NULL, NULL, 0, NULL); nvte_scaled_dsituglu(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL); @@ -97,10 +97,9 @@ void call_every_c_api_function(void) { nvte_scaled_dsrelu(NULL, NULL, NULL, NULL, NULL, NULL); /* cast.h */ - nvte_quantize(NULL, NULL, NULL); - nvte_group_quantize(NULL, NULL, NULL, NULL); - nvte_quantize_noop(NULL, NULL, NULL, NULL); + nvte_quantize(NULL, NULL, NULL, NULL); nvte_quantize_v2(NULL, NULL, NULL, NULL); + nvte_group_quantize(NULL, NULL, NULL, NULL); nvte_quantize_dbias(NULL, NULL, NULL, NULL, NULL); nvte_group_quantize_dbias(NULL, NULL, NULL, NULL, NULL, NULL); nvte_quantize_dbias_dgelu(NULL, NULL, NULL, NULL, NULL, NULL); @@ -176,15 +175,12 @@ void call_every_c_api_function(void) { nvte_destroy_fused_attn_bwd_params(NULL); nvte_get_fused_attn_bwd_params_attribute(NULL, 0, NULL, 0, NULL); nvte_set_fused_attn_bwd_params_attribute(NULL, 0, NULL, 0); + nvte_get_fused_attn_backend(NULL, NULL); nvte_get_fused_attn_backend_v2(NULL, NULL); - nvte_get_fused_attn_backend(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + nvte_fused_attn_fwd(NULL); nvte_fused_attn_fwd_v2(NULL); - nvte_fused_attn_fwd(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL); + nvte_fused_attn_bwd(NULL); nvte_fused_attn_bwd_v2(NULL); - nvte_fused_attn_bwd(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - NULL, NULL); nvte_populate_rng_state_async(NULL, NULL, 0, 0, 0, NULL); nvte_get_runtime_num_segments(NULL, NULL, 0, NULL); nvte_cu_seqlens_to_actual_seqlens(NULL, NULL, NULL, NULL, NULL); @@ -218,24 +214,20 @@ void call_every_c_api_function(void) { nvte_fused_mla_kv_rope_mxfp8(NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL); /* fused_router.h */ - nvte_fused_topk_with_score_function_forward(NULL, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, - NULL); + nvte_fused_topk_with_score_function_forward(NULL, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0, + NULL, NULL); nvte_fused_topk_with_score_function_forward_v2(NULL, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0, NULL, NULL); nvte_fused_topk_with_score_function_forward_with_indices(NULL, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL); + nvte_fused_topk_with_score_function_forward_qb(NULL, 0, 0, 0, 0, NULL, NULL, NULL, 0, NULL, NULL, + NULL, NULL, 0, NULL); nvte_fused_topk_with_score_function_forward_qb_v2(NULL, 0, 0, 0, 0, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, 0, NULL); - nvte_fused_topk_with_score_function_forward_qb_v2_unchecked(NULL, 0, 0, 0, 0, NULL, NULL, NULL, 0, - NULL, NULL, NULL, NULL, 0, NULL); nvte_fused_topk_with_score_function_forward_qb_with_indices(NULL, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL); - nvte_fused_topk_with_score_function_forward_qb_with_indices_unchecked(NULL, 0, 0, 0, 0, NULL, - NULL, NULL, NULL, NULL, - NULL, NULL, 0, NULL); nvte_qb_histogram_accumulate(NULL, NULL, NULL, NULL, NULL); - nvte_qb_histogram_accumulate_unchecked(NULL, NULL, NULL, NULL, NULL); - nvte_fused_topk_with_score_function_backward(NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL); + nvte_fused_topk_with_score_function_backward(NULL, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL); nvte_fused_topk_with_score_function_backward_v2(NULL, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL); nvte_fused_topk_with_score_function_backward_with_indices(NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, @@ -244,12 +236,13 @@ void call_every_c_api_function(void) { nvte_fused_topk_with_aux_loss_scores_forward(NULL, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL); nvte_fused_topk_with_aux_loss_scores_backward(NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL); - nvte_fused_score_for_moe_aux_loss_forward(NULL, 0, 0, 0, 0, NULL, NULL, NULL, NULL); + nvte_fused_score_for_moe_aux_loss_forward(NULL, 0, 0, 0, 0, NULL, NULL, 0, NULL, NULL); nvte_fused_score_for_moe_aux_loss_forward_v2(NULL, 0, 0, 0, 0, NULL, NULL, 0, NULL, NULL); nvte_fused_score_for_moe_aux_loss_backward(NULL, NULL, 0, 0, 0, 0, NULL, NULL); - nvte_fused_moe_aux_loss_forward(NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL); - nvte_fused_moe_aux_loss_forward_graph_safe(NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL); + nvte_fused_moe_aux_loss_forward(NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL); nvte_fused_moe_aux_loss_forward_v2(NULL, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL); + nvte_fused_moe_aux_loss_forward_graph_safe(NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, + NULL); nvte_fused_moe_aux_loss_forward_graph_safe_v2(NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL); nvte_fused_moe_aux_loss_backward(NULL, NULL, 0, 0, NULL, NULL, NULL); @@ -264,13 +257,12 @@ void call_every_c_api_function(void) { nvte_get_grouped_matmul_config_attribute(NULL, 0, NULL, 0, NULL); nvte_set_grouped_matmul_config_attribute(NULL, 0, NULL, 0); nvte_destroy_grouped_matmul_config(NULL); - nvte_cublas_gemm(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, 0, 0, NULL); + nvte_cublas_gemm(0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); nvte_cublas_gemm_v2(0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); nvte_cublas_gemm_strided_batched(0, 0, NULL, NULL, 0, NULL, 0, NULL, NULL, NULL, 0, NULL, NULL, NULL); nvte_cublas_gemm_strided_batched_mxfp8(0, 0, NULL, NULL, NULL, 0, NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, NULL, NULL); - nvte_cublas_gemm_scaled(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, NULL); nvte_cublas_atomic_gemm(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, 0, 0, NULL, NULL); nvte_multi_tensor_gemm(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, NULL, 0, 0, 0, NULL); @@ -364,15 +356,15 @@ void call_every_c_api_function(void) { nvte_mxfp8_scaling_partial_cast(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, NULL); nvte_nvfp4_compute_per_tensor_scale(NULL, 0, NULL, 0, 0, NULL, NULL); nvte_nvfp4_2d_compute_partial_amax(NULL, NULL, 0, 0, 0, 0, 0, 0, NULL); - nvte_nvfp4_2d_partial_cast(NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, NULL); + nvte_nvfp4_2d_partial_cast(NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, NULL); nvte_nvfp4_2d_partial_cast_v2(NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, NULL); - nvte_nvfp4_expand_scale_to_fp8(NULL, NULL, 0, 0, 0, 0, NULL); + nvte_nvfp4_expand_scale_to_fp8(NULL, NULL, 0, 0, 0, 0, 0, NULL); nvte_nvfp4_expand_scale_to_fp8_v2(NULL, NULL, 0, 0, 0, 0, 0, NULL); - nvte_nvfp4_compute_per_block_scale(NULL, NULL, NULL, NULL); + nvte_nvfp4_compute_per_block_scale(NULL, NULL, NULL, 0, NULL); nvte_nvfp4_compute_per_block_scale_v2(NULL, NULL, NULL, 0, NULL); - nvte_nvfp4_fused_scale(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, NULL); + nvte_nvfp4_fused_scale(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL); nvte_nvfp4_fused_scale_v2(NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL); - nvte_nvfp4_compute_global_scale(NULL, NULL, NULL); + nvte_nvfp4_compute_global_scale(NULL, NULL, 0, NULL); nvte_nvfp4_compute_global_scale_v2(NULL, NULL, 0, NULL); /* softmax.h */ @@ -425,9 +417,9 @@ void call_every_c_api_function(void) { nvte_tensor_scale_inv(NULL); nvte_tensor_scale_inv_shape(NULL); nvte_zero_tensor(NULL, NULL); - nvte_set_tensor_param(NULL, 0, NULL); - nvte_get_tensor_param(NULL, 0); + nvte_set_tensor_param(NULL, 0, NULL, 0); nvte_set_tensor_param_v2(NULL, 0, NULL, 0); + nvte_get_tensor_param(NULL, 0, NULL, 0, NULL); nvte_get_tensor_param_v2(NULL, 0, NULL, 0, NULL); nvte_tensor_scaling_mode(NULL); nvte_tensor_pack_create(NULL); @@ -440,7 +432,7 @@ void call_every_c_api_function(void) { nvte_memset(NULL, 0, 0, NULL); nvte_splits_to_offsets(NULL, NULL, 0, 0, NULL); nvte_splits_to_offsets_2d(NULL, NULL, NULL, NULL); - nvte_splits_to_offsets_multi(NULL, NULL, NULL, NULL, 0, NULL); + nvte_splits_to_offsets_multi(NULL, 0, NULL, NULL, NULL, 0, NULL); nvte_splits_to_offsets_multi_v2(NULL, 0, NULL, NULL, NULL, 0, NULL); nvte_create_grouped_tensor(0, 0, shape); nvte_destroy_grouped_tensor(NULL); diff --git a/tests/cpp_distributed/test_comm_gemm.cu b/tests/cpp_distributed/test_comm_gemm.cu index 1b20fc17cfb..c0f533a672c 100644 --- a/tests/cpp_distributed/test_comm_gemm.cu +++ b/tests/cpp_distributed/test_comm_gemm.cu @@ -27,6 +27,32 @@ using transformer_engine::DType; using transformer_engine::TypeInfo; +namespace { + +// Single-GPU reference GEMM with an optional bias and GELU epilogue. In the backward pass +// (grad=true), bias receives the bias gradient and pre_gelu_out provides the GELU input. +void ReferenceGemm(NVTETensor a, NVTETensor b, NVTETensor d, NVTETensor bias, + NVTETensor pre_gelu_out, bool transa, bool transb, bool grad, + NVTETensor workspace, bool accumulate, cudaStream_t stream) { + const bool with_gelu = nvte_tensor_data(pre_gelu_out) != nullptr; + transformer_engine::MatmulConfigWrapper config; + if (grad) { + config.set_dbias_tensor(bias); + config.set_with_dgelu_epilogue(with_gelu); + } else { + config.set_bias_tensor(bias); + config.set_with_gelu_epilogue(with_gelu); + } + config.set_epilogue_aux_tensor(pre_gelu_out); + config.set_use_split_accumulator(true); + const float alpha = 1.0f; + const float beta = accumulate ? 1.0f : 0.0f; + nvte_cublas_gemm(transa, transb, &alpha, a, b, &beta, accumulate ? d : nullptr, d, workspace, + config, stream); +} + +} // namespace + #define CHECK_MPI(expr) \ do { \ int err = (expr); \ @@ -363,9 +389,8 @@ class CommGemmFixure : public ::testing::TestWithParam { : MakeFromData(b_global_data, 0, 0, k, n, k, b_scale); auto d_ref = Make(dims.d_rows_num, dims.d_cols_num, d_scale); auto aux_ref = Make(dims.d_rows_num, dims.d_cols_num, d_scale); - nvte_cublas_gemm(a.data(), b_ref.data(), d_ref.data(), bias.data(), aux_ref.data(), transa, - transb, grad, workspace.data(), accumulate, - true /* use_split_accumulator */, 0 /* math_sm_count */, stream); + ReferenceGemm(a.data(), b_ref.data(), d_ref.data(), bias.data(), aux_ref.data(), transa, + transb, grad, workspace.data(), accumulate, stream); std::vector out_ref(dims.d_rows_num * dims.d_cols_num); NVTE_CHECK_CUDA(cudaMemcpy(out_ref.data(), d_ref.rowwise_dptr(), @@ -376,9 +401,8 @@ class CommGemmFixure : public ::testing::TestWithParam { TypeInfo::dtype); auto d_partial = Make(m, n, d_scale); auto aux_partial = Make(m, n, d_scale); - nvte_cublas_gemm(a.data(), b.data(), d_partial.data(), empty_bias.data(), - aux_partial.data(), transa, transb, grad, workspace.data(), accumulate, - true /* use_split_accumulator */, 0 /* math_sm_count */, stream); + ReferenceGemm(a.data(), b.data(), d_partial.data(), empty_bias.data(), aux_partial.data(), + transa, transb, grad, workspace.data(), accumulate, stream); std::vector partial_host(m * n); NVTE_CHECK_CUDA(cudaMemcpy(partial_host.data(), d_partial.rowwise_dptr(), diff --git a/tests/pytorch/test_fused_router.py b/tests/pytorch/test_fused_router.py index e86350f8f1f..7a9fde3f02f 100644 --- a/tests/pytorch/test_fused_router.py +++ b/tests/pytorch/test_fused_router.py @@ -145,8 +145,7 @@ def _check_reference(actual, expected, dtype): "histogram_mode,index_dtype", [(None, torch.int32), ("two_kernel", None), ("fused_atomic", torch.int16)], ) -@pytest.mark.parametrize("deterministic", [False, True]) -def test_router_compile_replay(histogram_mode, index_dtype, deterministic): +def test_router_compile_replay(histogram_mode, index_dtype): torch._dynamo.reset() counters.clear() histogram = torch.full((32, 31), 7, device="cuda", dtype=torch.int32) @@ -177,9 +176,7 @@ def router(logits, bounds, total, indices, histogram): qb_histogram_mode=histogram_mode, ) _, scores = fused_compute_score_for_moe_aux_loss(logits, 4, "sigmoid") - loss = fused_moe_aux_loss( - scores.reshape(-1, 32), counts, total, 32, 4, 0.01, deterministic=deterministic - ) + loss = fused_moe_aux_loss(scores.reshape(-1, 32), counts, total, 32, 4, 0.01) return (outputs[0].float().square().sum() + loss, *outputs[1:]) reference_histogram = histogram.clone() @@ -232,8 +229,7 @@ def router(logits, bounds, total, indices, histogram): "dtype,index_dtype", [(torch.float32, None), (torch.float16, torch.int16), (torch.bfloat16, torch.int64)], ) -@pytest.mark.parametrize("deterministic", [False, True]) -def test_router_compile_dynamic(dtype, index_dtype, deterministic): +def test_router_compile_dynamic(dtype, index_dtype): torch._dynamo.reset() counters.clear() counts = torch.arange(1, 131, device="cuda", dtype=torch.int32) @@ -257,9 +253,7 @@ def router_loss(logits): topk_indices=indices, ) _, scores = fused_compute_score_for_moe_aux_loss(logits, 4, "sigmoid", 1) - aux_loss = fused_moe_aux_loss( - scores, counts, logits.shape[0], 130, 4, 0.01, deterministic=deterministic - ) + aux_loss = fused_moe_aux_loss(scores, counts, logits.shape[0], 130, 4, 0.01) return probs.float().square().sum() + aux_loss, routing_map compiled = torch.compile(router_loss, fullgraph=True, dynamic=True) @@ -360,13 +354,12 @@ def test_router_compile_opcheck(dtype, routing_map_format, index_dtype, histogra ) counts = torch.ones(130, device="cuda", dtype=torch.int32) count = torch.tensor(16, device="cuda", dtype=torch.int64) - for token_count, deterministic in product((None, count), (False, True)): + for token_count in (None, count): torch.library.opcheck( - router._aux_loss_forward, - (logits, counts, 16, token_count, 130, 4, 0.01, deterministic), + router._aux_loss_forward, (logits, counts, 16, token_count, 130, 4, 0.01) ) loss, const_buf = router._aux_loss_forward( - forward_logits, counts, 16, token_count, 130, 4, 0.01, deterministic + forward_logits, counts, 16, token_count, 130, 4, 0.01 ) torch.library.opcheck( router._aux_loss_backward, (const_buf, counts, 16, 130, torch.randn_like(loss)) @@ -1467,16 +1460,7 @@ def test_fused_moe_aux_loss( torch.testing.assert_close(probs.grad, probs_clone.grad.float(), atol=atol, rtol=rtol) -@pytest.mark.parametrize( - "path", - [ - "forward", - "graph_safe_forward", - "deterministic_forward", - "deterministic_graph_safe_forward", - "backward", - ], -) +@pytest.mark.parametrize("path", ["forward", "graph_safe_forward", "backward"]) def test_fused_moe_aux_loss_rejects_int_offset_overflow(path): num_rows, num_cols = 8_388_609, 256 # Above INT_MAX elements. bytes_needed = num_rows * num_cols * 2 @@ -1505,13 +1489,9 @@ def test_fused_moe_aux_loss_rejects_int_offset_overflow(path): num_cols=num_cols, topk=1, coeff=0.01, + workspace=te_router._get_moe_aux_loss_workspace(probs.device), ) - if path.startswith("deterministic_"): - arguments.update( - deterministic=True, - workspace=te_router._get_moe_aux_loss_workspace(probs.device), - ) - if path in ("forward", "deterministic_forward"): + if path == "forward": tex.fused_moe_aux_loss_fwd(total_num_tokens=num_rows, **arguments) else: total = torch.tensor(num_rows, device="cuda", dtype=torch.int64) @@ -1524,16 +1504,7 @@ def test_fused_moe_aux_loss_rejects_int_offset_overflow(path): pytest.fail("Expected the int-offset guard to reject the shape") -@pytest.mark.parametrize( - "path", - [ - "forward", - "graph_safe_forward", - "deterministic_forward", - "deterministic_graph_safe_forward", - "backward", - ], -) +@pytest.mark.parametrize("path", ["forward", "graph_safe_forward", "backward"]) def test_fused_moe_aux_loss_largest_accepted_shape(path): # Exactly INT_MAX elements with one column: loop counters and grid math must not overflow. num_rows, num_cols = 2**31 - 1, 1 @@ -1566,13 +1537,9 @@ def test_fused_moe_aux_loss_largest_accepted_shape(path): num_cols=num_cols, topk=1, coeff=1.0, + workspace=te_router._get_moe_aux_loss_workspace(probs.device), ) - if path.startswith("deterministic_"): - arguments.update( - deterministic=True, - workspace=te_router._get_moe_aux_loss_workspace(probs.device), - ) - if path in ("forward", "deterministic_forward"): + if path == "forward": aux_loss, _ = tex.fused_moe_aux_loss_fwd(total_num_tokens=1, **arguments) else: total = torch.tensor(1, device="cuda", dtype=torch.int64) @@ -1612,8 +1579,7 @@ def _assert_bitwise_equal(actual, expected): @pytest.mark.parametrize("tensor_total", [False, True], ids=["host_total", "tensor_total"]) -@pytest.mark.parametrize("deterministic", [None, False, True], ids=["default", "atomic", "fixed"]) -def test_fused_moe_aux_loss_deterministic_dispatch(monkeypatch, tensor_total, deterministic): +def test_fused_moe_aux_loss_dispatch(monkeypatch, tensor_total): """Check Python dispatch and autograd argument count without launching CUDA.""" probs = torch.ones(3, 2, requires_grad=True) tokens_per_expert = torch.tensor([1, 2], dtype=torch.int32) @@ -1628,10 +1594,10 @@ def fake_workspace(device): return workspace def fake_forward(path, **kwargs): - calls.append((path, kwargs["deterministic"])) + calls.append(path) assert kwargs["probs"] is probs assert kwargs["num_rows"] == 3 and kwargs["num_cols"] == 2 - assert kwargs["workspace"] is (workspace if deterministic is True else None) + assert kwargs["workspace"] is workspace return torch.tensor(2.0), constants def fake_scalar_forward(**kwargs): @@ -1649,12 +1615,11 @@ def fake_backward(**kwargs): monkeypatch.setattr(tex, "fused_moe_aux_loss_fwd_graph_safe", fake_tensor_forward) monkeypatch.setattr(tex, "fused_moe_aux_loss_bwd", fake_backward) monkeypatch.setattr(te_router, "_get_moe_aux_loss_workspace", fake_workspace) - kwargs = {} if deterministic is None else {"deterministic": deterministic} - out = fused_moe_aux_loss(probs, tokens_per_expert, total_num_tokens, 2, 1, 0.01, **kwargs) + out = fused_moe_aux_loss(probs, tokens_per_expert, total_num_tokens, 2, 1, 0.01) out.backward(torch.tensor(0.5)) - assert calls == [("tensor" if tensor_total else "host", deterministic is True)] - assert workspace_requests == ([probs.device] if deterministic is True else []) + assert calls == ["tensor" if tensor_total else "host"] + assert workspace_requests == [probs.device] torch.testing.assert_close(probs.grad, torch.full_like(probs, 3.5)) @@ -1679,7 +1644,6 @@ def test_fused_moe_aux_loss_workspace_reuse(): @pytest.mark.parametrize( "workspace_kind,match", [ - ("missing", "requires a workspace"), ("empty", "must not be empty"), ("undersized", "needs at least"), ("wrong_dtype", "contiguous FP32"), @@ -1694,9 +1658,7 @@ def test_fused_moe_aux_loss_invalid_workspace(device_total, workspace_kind, matc counts = torch.ones(num_experts, dtype=torch.int32, device="cuda") shape, dtype = te_router._get_moe_aux_loss_workspace_config() workspace = torch.empty(shape, dtype=dtype, device="cuda") - if workspace_kind == "missing": - workspace = None - elif workspace_kind == "empty": + if workspace_kind == "empty": workspace = workspace[:0] elif workspace_kind == "undersized": workspace = workspace[:1] @@ -1711,9 +1673,7 @@ def test_fused_moe_aux_loss_invalid_workspace(device_total, workspace_kind, matc ) forward = tex.fused_moe_aux_loss_fwd_graph_safe if device_total else tex.fused_moe_aux_loss_fwd with pytest.raises(RuntimeError, match=match): - forward( - probs, counts, total, num_experts, num_tokens, num_experts, 1, 0.01, True, workspace - ) + forward(probs, counts, total, num_experts, num_tokens, num_experts, 1, 0.01, workspace) @pytest.mark.parametrize("execution", ["eager", "compile"]) @@ -1735,7 +1695,7 @@ def test_fused_moe_aux_loss_cuda_graph_workspace_isolation(monkeypatch, executio loss_fn = _router_function(fused_moe_aux_loss, execution) def run(probs, counts, total): - out = loss_fn(probs, counts, total, num_experts, topk, coeff, deterministic=True) + out = loss_fn(probs, counts, total, num_experts, topk, coeff) (grad,) = torch.autograd.grad(out, probs) return out, grad @@ -1835,9 +1795,7 @@ def test_fused_moe_aux_loss_deterministic( loss_fn = _router_function(fused_moe_aux_loss, execution) expected_out = expected_grad = None for _ in range(32): - out = loss_fn( - probs, tokens_per_expert, total_num_tokens, num_experts, topk, coeff, deterministic=True - ) + out = loss_fn(probs, tokens_per_expert, total_num_tokens, num_experts, topk, coeff) (grad,) = torch.autograd.grad(out, probs, grad_outputs=grad_output) if expected_out is None: torch.testing.assert_close(out, ref.to(dtype), atol=atol, rtol=rtol) @@ -1848,7 +1806,6 @@ def test_fused_moe_aux_loss_deterministic( _assert_bitwise_equal(grad, expected_grad) -@pytest.mark.parametrize("deterministic", [False, True], ids=["atomic", "fixed"]) @pytest.mark.parametrize( "num_tokens,num_experts,expert_multiplier,token_count_dtype", [ @@ -1857,7 +1814,7 @@ def test_fused_moe_aux_loss_deterministic( ], ) def test_fused_moe_aux_loss_cuda_graph_capture( - num_tokens, num_experts, expert_multiplier, token_count_dtype, deterministic + num_tokens, num_experts, expert_multiplier, token_count_dtype ): """CUDA-graph-safe path: total_num_tokens is a device tensor whose value changes between replays. Forward and backward must both observe the new @@ -1887,7 +1844,6 @@ def test_fused_moe_aux_loss_cuda_graph_capture( num_experts=num_experts, topk=topk, coeff=coeff, - deterministic=deterministic, ) torch.autograd.grad(warmup_out, probs) del warmup_out @@ -1902,7 +1858,6 @@ def test_fused_moe_aux_loss_cuda_graph_capture( num_experts=num_experts, topk=topk, coeff=coeff, - deterministic=deterministic, ) (grad_probs,) = torch.autograd.grad(out, probs) @@ -1934,14 +1889,14 @@ def test_fused_moe_aux_loss_cuda_graph_capture( expected_out = expected_grad = None for _ in range(16): g.replay() - if expected_out is None or not deterministic: + if expected_out is None: torch.testing.assert_close(out, ref, atol=atol, rtol=rtol) torch.testing.assert_close(grad_probs, ref_grad_probs, atol=atol, rtol=rtol) expected_out, expected_grad = out.detach().clone(), grad_probs.clone() else: _assert_bitwise_equal(out, expected_out) _assert_bitwise_equal(grad_probs, expected_grad) - if deterministic and not changed_inputs: + if not changed_inputs: if original_out is None: original_out, original_grad = expected_out, expected_grad else: @@ -2249,10 +2204,8 @@ def run(fused): ) loss = (probs * grad_probs).sum() if aux_grad == "aux_loss": - # deterministic, so both runs get the same aux-loss gradient - loss = loss + fused_moe_aux_loss( - scores, counts, num_tokens, num_experts, topk, 1e-3, deterministic=True - ) + # The aux loss is deterministic, so both runs get the same aux-loss gradient + loss = loss + fused_moe_aux_loss(scores, counts, num_tokens, num_experts, topk, 1e-3) loss.backward() return probs, indices, x.grad @@ -2288,7 +2241,7 @@ def step(): probs_dtype=torch.float32, ) loss = (probs * grad_probs).sum() + fused_moe_aux_loss( - scores, counts, num_tokens, num_experts, topk, 1e-3, deterministic=True + scores, counts, num_tokens, num_experts, topk, 1e-3 ) grad = torch.autograd.grad(loss, static_logits)[0] return probs, indices, counts, grad @@ -2314,7 +2267,7 @@ def step(): x, topk, 8, 4, 1.0, expert_bias, torch.float32, torch.int64 ) loss = (probs * grad_probs).sum() + fused_moe_aux_loss( - scores, counts, num_tokens, num_experts, topk, 1e-3, deterministic=True + scores, counts, num_tokens, num_experts, topk, 1e-3 ) loss.backward() expected_counts += ref_routes @@ -2367,7 +2320,6 @@ def router(logits, tokens_per_expert): num_experts, topk, 1e-3, - deterministic=True, ) return probs, indices, aux_loss diff --git a/transformer_engine/common/CuTeDSL/cast/mxfp8/quantize_mxfp8_2d.py b/transformer_engine/common/CuTeDSL/cast/mxfp8/quantize_mxfp8_2d.py index 485fde51043..3a8630f2634 100644 --- a/transformer_engine/common/CuTeDSL/cast/mxfp8/quantize_mxfp8_2d.py +++ b/transformer_engine/common/CuTeDSL/cast/mxfp8/quantize_mxfp8_2d.py @@ -16,7 +16,7 @@ the block's 32 rows itself. Only a plain cast is implemented: the C APIs that fuse dbias or an activation pass no -quantization config, so only plain casts (nvte_quantize_v2, nvte_multi_tensor_quantize) can +quantization config, so only plain casts (nvte_quantize, nvte_multi_tensor_quantize) can request 2D scaling. """ diff --git a/transformer_engine/common/activation/swiglu.cu b/transformer_engine/common/activation/swiglu.cu index 0300ba1bd46..c6f890e4435 100644 --- a/transformer_engine/common/activation/swiglu.cu +++ b/transformer_engine/common/activation/swiglu.cu @@ -59,28 +59,23 @@ void nvte_dsituglu(const NVTETensor grad, const NVTETensor input, NVTETensor out } void nvte_clamped_swiglu(const NVTETensor input, NVTETensor output, float limit, float alpha, - cudaStream_t stream) { + float glu_linear_offset, cudaStream_t stream) { NVTE_API_CALL(nvte_clamped_swiglu); using namespace transformer_engine; - // Preserve original behavior: linear (gate) component offset is hard-coded to 1.0f. - ClampedSwiGLUParam param = {limit, alpha, /*glu_linear_offset=*/1.0f}; + ClampedSwiGLUParam param = {limit, alpha, glu_linear_offset}; gated_act_fn>(input, output, param, stream); } void nvte_clamped_swiglu_v2(const NVTETensor input, NVTETensor output, float limit, float alpha, float glu_linear_offset, cudaStream_t stream) { - NVTE_API_CALL(nvte_clamped_swiglu_v2); - using namespace transformer_engine; - ClampedSwiGLUParam param = {limit, alpha, glu_linear_offset}; - gated_act_fn>(input, output, param, stream); + nvte_clamped_swiglu(input, output, limit, alpha, glu_linear_offset, stream); } void nvte_clamped_dswiglu(const NVTETensor grad, const NVTETensor input, NVTETensor output, - float limit, float alpha, cudaStream_t stream) { + float limit, float alpha, float glu_linear_offset, cudaStream_t stream) { NVTE_API_CALL(nvte_clamped_dswiglu); using namespace transformer_engine; - // Preserve original behavior: linear (gate) component offset is hard-coded to 1.0f. - ClampedSwiGLUParam param = {limit, alpha, /*glu_linear_offset=*/1.0f}; + ClampedSwiGLUParam param = {limit, alpha, glu_linear_offset}; dgated_act_fn, clamped_dsilu>( grad, input, output, param, stream); } @@ -88,9 +83,5 @@ void nvte_clamped_dswiglu(const NVTETensor grad, const NVTETensor input, NVTETen void nvte_clamped_dswiglu_v2(const NVTETensor grad, const NVTETensor input, NVTETensor output, float limit, float alpha, float glu_linear_offset, cudaStream_t stream) { - NVTE_API_CALL(nvte_clamped_dswiglu_v2); - using namespace transformer_engine; - ClampedSwiGLUParam param = {limit, alpha, glu_linear_offset}; - dgated_act_fn, clamped_dsilu>( - grad, input, output, param, stream); + nvte_clamped_dswiglu(grad, input, output, limit, alpha, glu_linear_offset, stream); } diff --git a/transformer_engine/common/cast/cast.cu b/transformer_engine/common/cast/cast.cu index 1e3c04573be..16bb1476230 100644 --- a/transformer_engine/common/cast/cast.cu +++ b/transformer_engine/common/cast/cast.cu @@ -18,33 +18,18 @@ #include "dispatch/quantize.cuh" #include "transformer_engine/transpose.h" -void nvte_quantize(const NVTETensor input, NVTETensor output, cudaStream_t stream) { +void nvte_quantize(const NVTETensor input, NVTETensor output, + const NVTEQuantizationConfig quant_config, cudaStream_t stream) { NVTE_API_CALL(nvte_quantize); using namespace transformer_engine; constexpr bool IS_ACT = false; - dispatch::quantize_fwd_helper(input, output, nullptr, stream); -} - -void nvte_quantize_noop(const NVTETensor input, NVTETensor output, NVTETensor noop, - cudaStream_t stream) { - NVTE_API_CALL(nvte_quantize_noop); - using namespace transformer_engine; - - // Create config with noop tensor - QuantizationConfig quant_config; - quant_config.noop_tensor = noop; - - nvte_quantize_v2(input, output, reinterpret_cast(&quant_config), stream); + dispatch::quantize_fwd_helper(input, output, quant_config, stream); } void nvte_quantize_v2(const NVTETensor input, NVTETensor output, const NVTEQuantizationConfig quant_config, cudaStream_t stream) { - NVTE_API_CALL(nvte_quantize_v2); - using namespace transformer_engine; - - constexpr bool IS_ACT = false; - dispatch::quantize_fwd_helper(input, output, quant_config, stream); + nvte_quantize(input, output, quant_config, stream); } void nvte_dequantize(const NVTETensor input, NVTETensor output, cudaStream_t stream) { diff --git a/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp b/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp index 1442e6ea0dd..9f300b94b6d 100644 --- a/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp +++ b/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp @@ -40,6 +40,30 @@ std::vector shape_to_vector(const NVTEShape &shape) { return std::vector(shape.data, shape.data + shape.ndim); } +// GEMM with an optional bias and GELU epilogue, accumulating into D if requested. In the backward +// pass (grad=true), bias receives the bias gradient and pre_gelu_out provides the GELU input. +void launch_gemm(const TensorWrapper &A, const TensorWrapper &B, const TensorWrapper &D, + const TensorWrapper &bias, const TensorWrapper &pre_gelu_out, bool transa, + bool transb, bool grad, const TensorWrapper &workspace, bool accumulate, + bool use_split_accumulator, int sm_count, cudaStream_t stream) { + const bool with_gelu = pre_gelu_out.dptr() != nullptr; + MatmulConfigWrapper config; + if (grad) { + config.set_dbias_tensor(bias.data()); + config.set_with_dgelu_epilogue(with_gelu); + } else { + config.set_bias_tensor(bias.data()); + config.set_with_gelu_epilogue(with_gelu); + } + config.set_epilogue_aux_tensor(pre_gelu_out.data()); + config.set_use_split_accumulator(use_split_accumulator); + config.set_sm_count(sm_count); + const float alpha = 1.0f; + const float beta = accumulate ? 1.0f : 0.0f; + nvte_cublas_gemm(transa, transb, &alpha, A.data(), B.data(), &beta, + accumulate ? D.data() : nullptr, D.data(), workspace.data(), config, stream); +} + } // namespace bool ubuf_built_with_mpi() { @@ -226,8 +250,8 @@ TensorWrapper CommOverlapCore::get_tensor_chunk(const TensorWrapper &source, siz "Unsupported tensor format (", to_string(scaling_mode), ")."); if (scaling_mode == NVTE_MXFP8_1D_SCALING) { uint8_t has_swizzled_scales = false; - nvte_get_tensor_param_v2(source.data(), NVTETensorParam::kNVTEWithGEMMSwizzledScales, - &has_swizzled_scales, sizeof(has_swizzled_scales), nullptr); + nvte_get_tensor_param(source.data(), NVTETensorParam::kNVTEWithGEMMSwizzledScales, + &has_swizzled_scales, sizeof(has_swizzled_scales), nullptr); NVTE_CHECK(has_swizzled_scales, "Expected MXFP8 tensor to have scales in GEMM swizzled format."); } @@ -491,9 +515,8 @@ void CommOverlapBase::bulk_overlap(const TensorWrapper &A, bool transa, const Te // When the kernel launch order is defined, enforce the GEMM kernel launch to wait for the communication kernel launch if (_comm_launch_event) NVTE_CHECK_CUDA(cudaStreamWaitEvent((cudaStream_t)_stream_compute[0], _comm_launch_event, 0)); - nvte_cublas_gemm(A.data(), B.data(), D.data(), bias.data(), pre_gelu_out.data(), transa, transb, - grad, workspace.data(), accumulate, use_split_accumulator, _math_sms, - _stream_compute[0]); + launch_gemm(A, B, D, bias, pre_gelu_out, transa, transb, grad, workspace, accumulate, + use_split_accumulator, _math_sms, _stream_compute[0]); _ub_comm->sms = ori_sms; NVTE_CHECK_CUDA(cudaEventRecord(_stop_comm, _stream_comm)); @@ -669,9 +692,8 @@ void CommOverlapBase::split_overlap_rs(const TensorWrapper &A, bool transa, cons auto bias_chunk = maybe_get_bias_chunk(0); auto workspace_chunk = get_tensor_chunk(workspace, 0, {workspace_size_chunk}); - nvte_cublas_gemm(input_a_chunk.data(), B.data(), output_chunk.data(), bias_chunk.data(), - pre_gelu_out.data(), transa, transb, grad, workspace_chunk.data(), accumulate, - use_split_accumulator, _math_sms, _stream_compute[0]); + launch_gemm(input_a_chunk, B, output_chunk, bias_chunk, pre_gelu_out, transa, transb, grad, + workspace_chunk, accumulate, use_split_accumulator, _math_sms, _stream_compute[0]); for (int i = 1; i < _num_splits; i++) { input_a_chunk = get_tensor_chunk(A, i * input_a_chunk_size, input_a_chunk_shape); @@ -680,10 +702,9 @@ void CommOverlapBase::split_overlap_rs(const TensorWrapper &A, bool transa, cons workspace_chunk = get_tensor_chunk( workspace, (i % _stream_compute.size()) * workspace_size_chunk, {workspace_size_chunk}); - nvte_cublas_gemm(input_a_chunk.data(), B.data(), output_chunk.data(), bias_chunk.data(), - pre_gelu_out.data(), transa, transb, grad, workspace_chunk.data(), - accumulate, use_split_accumulator, _math_sms, - _stream_compute[i % _stream_compute.size()]); + launch_gemm(input_a_chunk, B, output_chunk, bias_chunk, pre_gelu_out, transa, transb, grad, + workspace_chunk, accumulate, use_split_accumulator, _math_sms, + _stream_compute[i % _stream_compute.size()]); NVTE_CHECK_CUDA( cudaEventRecord(_start_comm, _stream_compute[(i - 1) % _stream_compute.size()])); @@ -729,10 +750,9 @@ void CommOverlapBase::split_overlap_rs(const TensorWrapper &A, bool transa, cons auto workspace_chunk = get_tensor_chunk( workspace, (i % _stream_compute.size()) * workspace_size_chunk, {workspace_size_chunk}); - nvte_cublas_gemm(input_a_chunk.data(), B.data(), output_chunk.data(), bias_chunk.data(), - pre_gelu_out.data(), transa, transb, grad, workspace_chunk.data(), - accumulate, use_split_accumulator, _math_sms, - _stream_compute[i % _stream_compute.size()]); + launch_gemm(input_a_chunk, B, output_chunk, bias_chunk, pre_gelu_out, transa, transb, grad, + workspace_chunk, accumulate, use_split_accumulator, _math_sms, + _stream_compute[i % _stream_compute.size()]); NVTE_CHECK_CUDA(cudaEventRecord(_start_comm, _stream_compute[i % _stream_compute.size()])); NVTE_CHECK_CUDA(cudaStreamWaitEvent(_stream_comm, _start_comm, 0)); @@ -1139,10 +1159,9 @@ void CommOverlapP2PBase::split_overlap_ag(const TensorWrapper &A, bool transa, auto workspace_chunk = get_tensor_chunk( workspace, (i % _stream_compute.size()) * workspace_size_chunk, {workspace_size_chunk}); - nvte_cublas_gemm(A.data(), input_b_chunk.data(), output_chunk.data(), bias.data(), - aux_chunk.data(), transa, transb, grad, workspace_chunk.data(), accumulate, - use_split_accumulator, _math_sms, - _stream_compute[i % _stream_compute.size()]); + launch_gemm(A, input_b_chunk, output_chunk, bias, aux_chunk, transa, transb, grad, + workspace_chunk, accumulate, use_split_accumulator, _math_sms, + _stream_compute[i % _stream_compute.size()]); if (i < num_steps - 1) { // P2P communication @@ -1186,10 +1205,9 @@ void CommOverlapP2PBase::split_overlap_ag(const TensorWrapper &A, bool transa, auto workspace_chunk = get_tensor_chunk( workspace, (i % _stream_compute.size()) * workspace_size_chunk, {workspace_size_chunk}); - nvte_cublas_gemm(A.data(), input_b_chunk.data(), output_chunk.data(), bias.data(), - aux_chunk.data(), transa, transb, grad, workspace_chunk.data(), accumulate, - use_split_accumulator, _math_sms, - _stream_compute[i % _stream_compute.size()]); + launch_gemm(A, input_b_chunk, output_chunk, bias, aux_chunk, transa, transb, grad, + workspace_chunk, accumulate, use_split_accumulator, _math_sms, + _stream_compute[i % _stream_compute.size()]); if (i < _tp_size - 1) { // P2P communication @@ -1363,9 +1381,9 @@ void CommOverlapP2PBase::split_overlap_rs(const TensorWrapper &A, bool transa, cudaEventRecord(_start_compute, _stream_compute[(i - 2) % _stream_compute.size()])); NVTE_CHECK_CUDA(cudaStreamWaitEvent(_stream_compute[stream_id], _start_compute)); } - nvte_cublas_gemm(A.data(), input_b_chunk.data(), output_chunk.data(), bias.data(), - pre_gelu_out.data(), transa, transb, grad, workspace_chunk.data(), accumulate, - use_split_accumulator, _math_sms, _stream_compute[stream_id]); + launch_gemm(A, input_b_chunk, output_chunk, bias, pre_gelu_out, transa, transb, grad, + workspace_chunk, accumulate, use_split_accumulator, _math_sms, + _stream_compute[stream_id]); if (i > 0) { // P2P communication chunk diff --git a/transformer_engine/common/fused_attn/config_and_params.cpp b/transformer_engine/common/fused_attn/config_and_params.cpp index f27859791e8..2272fa96751 100644 --- a/transformer_engine/common/fused_attn/config_and_params.cpp +++ b/transformer_engine/common/fused_attn/config_and_params.cpp @@ -155,7 +155,7 @@ FusedAttnConfig FusedAttnConfig::make_cache_key(Pass pass) const { cache_cfg.attn_scale = 1.0f; // cuda_graph never reaches a graph builder. Its one use is the cuDNN <= 9.15 rejection in - // nvte_get_fused_attn_backend_v2(). + // nvte_get_fused_attn_backend(). cache_cfg.cuda_graph = false; // Normalize the fields its graph actually consumes diff --git a/transformer_engine/common/fused_attn/fused_attn.cpp b/transformer_engine/common/fused_attn/fused_attn.cpp index 0b5a36cffd6..f57290aa414 100644 --- a/transformer_engine/common/fused_attn/fused_attn.cpp +++ b/transformer_engine/common/fused_attn/fused_attn.cpp @@ -247,9 +247,11 @@ thread_local std::string fused_attn_backend_message_buffer; } // namespace // Fused attention backend query: runs TE's specific rules first, then cuDNN's. First rejection wins. -NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend_v2(NVTEFusedAttnConfig config, - const char **message) { - NVTE_API_CALL(nvte_get_fused_attn_backend_v2); + +// Select a backend for fused attention +NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend( + NVTEFusedAttnConfig config, const char **message) { + NVTE_API_CALL(nvte_get_fused_attn_backend); using namespace transformer_engine; using namespace transformer_engine::fused_attn; FusedAttnConfig cfg = *get_fused_attn_config(config); @@ -413,60 +415,17 @@ NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend_v2(NVTEFusedAttnConfig confi return reject(message, "Unsupported QKV dtype qkv_dtype=" + std::to_string(cfg.qkv_dtype) + " ."); } -// Select a backend for fused attention -NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend( - bool is_training, NVTEDType q_dtype, NVTEDType kv_dtype, NVTE_QKV_Layout qkv_layout, - NVTE_Bias_Type bias_type, NVTE_Mask_Type attn_mask_type, NVTE_Softmax_Type softmax_type, - float dropout, size_t num_attn_heads, size_t num_gqa_groups, size_t max_seqlen_q, - size_t max_seqlen_kv, size_t head_dim_qk, size_t head_dim_v, int64_t window_size_left, - int64_t window_size_right, bool return_max_logit, bool cuda_graph, bool deterministic) { - NVTE_API_CALL(nvte_get_fused_attn_backend); - transformer_engine::fused_attn::FusedAttnConfig cfg{}; - cfg.qkv_layout = qkv_layout; - cfg.bias_type = bias_type; - cfg.attn_mask_type = attn_mask_type; - cfg.softmax_type = softmax_type; - cfg.dropout = dropout; - cfg.max_seqlen_q = max_seqlen_q; - cfg.max_seqlen_kv = max_seqlen_kv; - cfg.window_size_left = window_size_left; - cfg.window_size_right = window_size_right; - cfg.cuda_graph = cuda_graph; - NVTE_CHECK(q_dtype == kv_dtype, "Q and KV must have the same data type."); - cfg.qkv_dtype = q_dtype; - cfg.o_dtype = q_dtype; - cfg.do_dtype = q_dtype; - cfg.dqkv_dtype = q_dtype; - cfg.num_attn_heads = num_attn_heads; - cfg.num_gqa_groups = num_gqa_groups; - cfg.head_dim_qk = head_dim_qk; - cfg.head_dim_v = head_dim_v; - cfg.is_training = is_training; - cfg.return_max_logit = return_max_logit; - cfg.deterministic = deterministic; - // fill in the missing fields with the most common use case; - // otherwise it would return NVTE_No_Backend always - cfg.batch_size = 1; - cfg.num_tokens_q = cfg.batch_size * max_seqlen_q; - cfg.num_tokens_kv = cfg.batch_size * max_seqlen_kv; - cfg.o_format = nvte_get_q_format(qkv_layout); - cfg.do_format = cfg.o_format; - cfg.dqkv_layout = qkv_layout; - if (bias_type == NVTE_Bias_Type::NVTE_POST_SCALE_BIAS) { - cfg.bias_batch_size = cfg.batch_size; - cfg.bias_num_heads = num_attn_heads; - cfg.bias_seqlen_q = max_seqlen_q; - cfg.bias_seqlen_kv = max_seqlen_kv; - } - - return nvte_get_fused_attn_backend_v2(reinterpret_cast(&cfg), - /*message=*/nullptr); +NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend_v2( + NVTEFusedAttnConfig config, const char **message) { + return nvte_get_fused_attn_backend(config, message); } // Fused attention forward: create a config based on the params, check which backend supports it, // and run that backend's implementation. -void nvte_fused_attn_fwd_v2(NVTEFusedAttnFwdParams params) { - NVTE_API_CALL(nvte_fused_attn_fwd_v2); + +// NVTE fused attention FWD with separate Q, K and V +void nvte_fused_attn_fwd(NVTEFusedAttnFwdParams params) { + NVTE_API_CALL(nvte_fused_attn_fwd); using namespace transformer_engine; using namespace transformer_engine::fused_attn; const FusedAttnFwdParams &p = *get_fused_attn_fwd_params(params); @@ -490,7 +449,7 @@ void nvte_fused_attn_fwd_v2(NVTEFusedAttnFwdParams params) { FusedAttnConfig cfg = p.make_config(); cfg.derive(); const char *fused_attn_reject_reason = nullptr; - NVTE_Fused_Attn_Backend fused_attention_backend = nvte_get_fused_attn_backend_v2( + NVTE_Fused_Attn_Backend fused_attention_backend = nvte_get_fused_attn_backend( reinterpret_cast(&cfg), &fused_attn_reject_reason); if (fused_attention_backend == NVTE_Fused_Attn_Backend::NVTE_F16_arbitrary_seqlen) { @@ -510,63 +469,16 @@ void nvte_fused_attn_fwd_v2(NVTEFusedAttnFwdParams params) { } } -// NVTE fused attention FWD with separate Q, K and V -void nvte_fused_attn_fwd(const NVTETensor Q, const NVTETensor K, const NVTETensor V, - const NVTETensor Bias, const NVTETensor SoftmaxOffset, NVTETensor S, - NVTETensor O, NVTETensorPack *Aux_CTX_Tensors, - const NVTETensor cu_seqlens_q, const NVTETensor cu_seqlens_kv, - const NVTETensor cu_seqlens_q_padded, - const NVTETensor cu_seqlens_kv_padded, const NVTETensor page_table_k, - const NVTETensor page_table_v, const NVTETensor rng_state, - size_t max_seqlen_q, size_t max_seqlen_kv, bool is_training, - bool return_max_logit, bool cuda_graph, float attn_scale, float dropout, - NVTE_QKV_Layout qkv_layout, NVTE_QKV_Format o_format, - NVTE_QKV_Format qkv_scale_inv_format, NVTE_Bias_Type bias_type, - NVTE_Mask_Type attn_mask_type, NVTE_Softmax_Type softmax_type, - int64_t window_size_left, int64_t window_size_right, - bool bottom_right_diagonal, NVTETensor workspace, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_attn_fwd); - transformer_engine::fused_attn::FusedAttnFwdParams p{}; - p.Q = Q; - p.K = K; - p.V = V; - p.Bias = Bias; - p.SoftmaxOffset = SoftmaxOffset; - p.S = S; - p.O = O; - p.Aux_CTX_Tensors = Aux_CTX_Tensors; - p.cu_seqlens_q = cu_seqlens_q; - p.cu_seqlens_kv = cu_seqlens_kv; - p.cu_seqlens_q_padded = cu_seqlens_q_padded; - p.cu_seqlens_kv_padded = cu_seqlens_kv_padded; - p.page_table_k = page_table_k; - p.page_table_v = page_table_v; - p.rng_state = rng_state; - p.is_training = is_training; - p.cuda_graph = cuda_graph; - p.return_max_logit = return_max_logit; - p.attn_mask_type = attn_mask_type; - p.bias_type = bias_type; - p.window_size_left = window_size_left; - p.window_size_right = window_size_right; - p.bottom_right_diagonal = bottom_right_diagonal; - p.softmax_type = softmax_type; - p.dropout = dropout; - p.attn_scale = attn_scale; - p.qkv_layout = qkv_layout; - p.o_format = o_format; - p.qkv_scale_inv_format = qkv_scale_inv_format; - p.max_seqlen_q = max_seqlen_q; - p.max_seqlen_kv = max_seqlen_kv; - p.workspace = workspace; - p.stream = stream; - nvte_fused_attn_fwd_v2(reinterpret_cast(&p)); +void nvte_fused_attn_fwd_v2(NVTEFusedAttnFwdParams params) { + nvte_fused_attn_fwd(params); } -// Fused attention backward. Same shape as nvte_fused_attn_fwd_v2, whose comment sketches the path; +// Fused attention backward. Same shape as nvte_fused_attn_fwd, whose comment sketches the path; // this one asks the selector for backward support and probes the backward builders. -void nvte_fused_attn_bwd_v2(NVTEFusedAttnBwdParams params) { - NVTE_API_CALL(nvte_fused_attn_bwd_v2); + +// NVTE fused attention BWD with separate Q, K and V +void nvte_fused_attn_bwd(NVTEFusedAttnBwdParams params) { + NVTE_API_CALL(nvte_fused_attn_bwd); using namespace transformer_engine; using namespace transformer_engine::fused_attn; const FusedAttnBwdParams &p = *get_fused_attn_bwd_params(params); @@ -594,7 +506,7 @@ void nvte_fused_attn_bwd_v2(NVTEFusedAttnBwdParams params) { // that goes on to the backend and must arrive with its derived fields filled in. cfg.derive(); const char *fused_attn_reject_reason = nullptr; - NVTE_Fused_Attn_Backend fused_attention_backend = nvte_get_fused_attn_backend_v2( + NVTE_Fused_Attn_Backend fused_attention_backend = nvte_get_fused_attn_backend( reinterpret_cast(&cfg), &fused_attn_reject_reason); if (fused_attention_backend == NVTE_Fused_Attn_Backend::NVTE_F16_arbitrary_seqlen) { @@ -636,62 +548,8 @@ void nvte_fused_attn_bwd_v2(NVTEFusedAttnBwdParams params) { } } -// NVTE fused attention BWD with separate Q, K and V -void nvte_fused_attn_bwd(const NVTETensor Q, const NVTETensor K, const NVTETensor V, - const NVTETensor O, const NVTETensor dO, const NVTETensor S, NVTETensor dP, - const NVTETensorPack *Aux_CTX_Tensors, NVTETensor dQ, NVTETensor dK, - NVTETensor dV, NVTETensor dBias, NVTETensor dSoftmaxOffset, - const NVTETensor cu_seqlens_q, const NVTETensor cu_seqlens_kv, - const NVTETensor cu_seqlens_q_padded, - const NVTETensor cu_seqlens_kv_padded, size_t max_seqlen_q, - size_t max_seqlen_kv, float attn_scale, float dropout, - NVTE_QKV_Layout qkv_layout, NVTE_QKV_Format o_format, - NVTE_QKV_Format do_format, NVTE_QKV_Layout dqkv_layout, - NVTE_QKV_Format qkv_scale_inv_format, NVTE_QKV_Format do_scale_inv_format, - NVTE_Bias_Type bias_type, NVTE_Mask_Type attn_mask_type, - NVTE_Softmax_Type softmax_type, int64_t window_size_left, - int64_t window_size_right, bool bottom_right_diagonal, bool deterministic, - bool cuda_graph, NVTETensor workspace, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_attn_bwd); - transformer_engine::fused_attn::FusedAttnBwdParams p{}; - p.Q = Q; - p.K = K; - p.V = V; - p.O = O; - p.dO = dO; - p.S = S; - p.dP = dP; - p.Aux_CTX_Tensors = Aux_CTX_Tensors; - p.dQ = dQ; - p.dK = dK; - p.dV = dV; - p.dBias = dBias; - p.dSoftmaxOffset = dSoftmaxOffset; - p.cu_seqlens_q = cu_seqlens_q; - p.cu_seqlens_kv = cu_seqlens_kv; - p.cu_seqlens_q_padded = cu_seqlens_q_padded; - p.cu_seqlens_kv_padded = cu_seqlens_kv_padded; - p.deterministic = deterministic; - p.cuda_graph = cuda_graph; - p.attn_mask_type = attn_mask_type; - p.bias_type = bias_type; - p.window_size_left = window_size_left; - p.window_size_right = window_size_right; - p.bottom_right_diagonal = bottom_right_diagonal; - p.softmax_type = softmax_type; - p.dropout = dropout; - p.attn_scale = attn_scale; - p.qkv_layout = qkv_layout; - p.o_format = o_format; - p.do_format = do_format; - p.dqkv_layout = dqkv_layout; - p.qkv_scale_inv_format = qkv_scale_inv_format; - p.do_scale_inv_format = do_scale_inv_format; - p.max_seqlen_q = max_seqlen_q; - p.max_seqlen_kv = max_seqlen_kv; - p.workspace = workspace; - p.stream = stream; - nvte_fused_attn_bwd_v2(reinterpret_cast(&p)); +void nvte_fused_attn_bwd_v2(NVTEFusedAttnBwdParams params) { + nvte_fused_attn_bwd(params); } uint32_t nvte_get_runtime_num_segments(NVTETensor cu_seqlen, NVTETensor workspace, size_t len, diff --git a/transformer_engine/common/fused_router/fused_moe_aux_loss.cu b/transformer_engine/common/fused_router/fused_moe_aux_loss.cu index 9bf79db2144..0c5cc671e82 100644 --- a/transformer_engine/common/fused_router/fused_moe_aux_loss.cu +++ b/transformer_engine/common/fused_router/fused_moe_aux_loss.cu @@ -13,7 +13,6 @@ #include "../common.h" #include "../util/logging.h" #include "../utils.cuh" -#include "common/util/cuda_runtime.h" #include "utils.h" namespace transformer_engine { @@ -45,7 +44,7 @@ void check_aux_loss_const_buffer(const Tensor& const_buf) { "Aux-loss constant buffer must contain at least two FP32 elements."); } -template +template __global__ void fused_moe_aux_loss_forward_kernel(const DataType* probs, const IndexType* tokens_per_expert, int total_num_tokens, int num_rows, int num_cols, @@ -96,26 +95,14 @@ __global__ void fused_moe_aux_loss_forward_kernel(const DataType* probs, CompType block_sum = warp_reduce_on_shmem( shmem_block, static_cast(blockDim.x), lane_id); if (lane_id == 0) { - if constexpr (kDeterministic) { - // Every CTA writes its own slot, including empty row partitions. - partial_sums[blockIdx.x] = static_cast(block_sum * coeff); - } else { - // Retained only for callers of the original C API. - atomicAdd(&Coeff_buf[1], static_cast(block_sum * coeff)); - } + // Every CTA writes its own slot, including empty row partitions. + partial_sums[blockIdx.x] = static_cast(block_sum * coeff); } } } -// Small kernel to convert the float accumulator to the output DataType. -template -__global__ void convert_accum_to_output(const float* Coeff_buf, DataType* aux_loss) { - aux_loss[0] = static_cast(Coeff_buf[1]); -} - // One full warp reads fixed, strided slices and combines them with a fixed tree. -// This replaces the legacy cast kernel, so deterministic forward still uses two -// launches. The final FP32 sum remains in Coeff_buf[1] for compatibility. +// The final FP32 sum is also stored in Coeff_buf[1]. template __global__ void reduce_aux_loss_partials(const float* partial_sums, int num_partials, float* Coeff_buf, DataType* aux_loss) { @@ -136,11 +123,11 @@ __global__ void reduce_aux_loss_partials(const float* partial_sums, int num_part /* ------------------------------------------------------------------------- * Kernel launcher -- simplified (no cluster launch). * ------------------------------------------------------------------------- */ -template +template void fused_moe_aux_loss_forward_kernel_launcher( const DataType* probs, const IndexType* tokens_per_expert, int total_num_tokens, int num_experts, int num_rows, int num_cols, int topk, float coeff, DataType* aux_loss, - float* Coeff_buf, cudaStream_t stream, float* partial_sums = nullptr) { + float* Coeff_buf, cudaStream_t stream, float* partial_sums) { NVTE_CHECK(num_cols > 0, "num_cols must be positive, got ", num_cols); NVTE_CHECK(num_experts > 0, "num_experts must be positive, got ", num_experts); NVTE_CHECK(static_cast(num_rows) * num_cols <= INT_MAX, @@ -154,7 +141,7 @@ void fused_moe_aux_loss_forward_kernel_launcher( const int block_size = ((std::min(1024, num_cols) + static_cast(kThreadsPerWarp) - 1) / static_cast(kThreadsPerWarp)) * static_cast(kThreadsPerWarp); - const int grid_size = kDeterministic ? aux_loss_reduction_blocks(num_rows) : cuda::sm_count() * 2; + const int grid_size = aux_loss_reduction_blocks(num_rows); // One CompType per thread in shared memory. const size_t smem_size = block_size * sizeof(CompType); @@ -162,34 +149,26 @@ void fused_moe_aux_loss_forward_kernel_launcher( // Keep coefficient placement unchanged: scale each partial before summing. const float C_coeff = (num_experts * coeff) / topk / total_num_tokens / total_num_tokens; - if constexpr (!kDeterministic) { - NVTE_CHECK_CUDA(cudaMemsetAsync(Coeff_buf + 1, 0, sizeof(float), stream)); - } - fused_moe_aux_loss_forward_kernel + fused_moe_aux_loss_forward_kernel <<>>(probs, tokens_per_expert, total_num_tokens, num_rows, num_cols, topk, C_coeff, Coeff_buf, partial_sums); NVTE_CHECK_CUDA(cudaGetLastError()); - if constexpr (kDeterministic) { - reduce_aux_loss_partials - <<<1, kThreadsPerWarp, 0, stream>>>(partial_sums, grid_size, Coeff_buf, aux_loss); - } else { - convert_accum_to_output<<<1, 1, 0, stream>>>(Coeff_buf, aux_loss); - } + reduce_aux_loss_partials + <<<1, kThreadsPerWarp, 0, stream>>>(partial_sums, grid_size, Coeff_buf, aux_loss); NVTE_CHECK_CUDA(cudaGetLastError()); } -template void fused_moe_aux_loss_forward(const Tensor& probs, const Tensor& tokens_per_expert, int total_num_tokens, int num_experts, int num_rows, int num_cols, int topk, float coeff, Tensor& aux_loss, Tensor& Coeff_buf, - cudaStream_t stream, float* partial_sums = nullptr) { + cudaStream_t stream, float* partial_sums) { TE_ROUTER_PROBS_TYPE_SWITCH_ALL( probs.data.dtype, DataType, TE_ROUTER_INDEX_TYPE_SWITCH_ALL( tokens_per_expert.data.dtype, IndexType, - fused_moe_aux_loss_forward_kernel_launcher( + fused_moe_aux_loss_forward_kernel_launcher( reinterpret_cast(probs.data.dptr), reinterpret_cast(tokens_per_expert.data.dptr), total_num_tokens, num_experts, num_rows, num_cols, topk, coeff, @@ -203,7 +182,7 @@ void fused_moe_aux_loss_forward(const Tensor& probs, const Tensor& tokens_per_ex * lane computes C_coeff directly from the device value. The first CTA also * writes C_coeff into Coeff_buf[0] for backward. * ------------------------------------------------------------------------- */ -template +template __global__ void fused_moe_aux_loss_forward_kernel_graph_safe( const DataType* probs, const IndexType* tokens_per_expert, const int64_t* total_num_tokens_ptr, int num_experts, int num_rows, int num_cols, int topk, float coeff, float* Coeff_buf, @@ -237,20 +216,16 @@ __global__ void fused_moe_aux_loss_forward_kernel_graph_safe( if (blockIdx.x == 0) { Coeff_buf[0] = C_coeff; } - if constexpr (kDeterministic) { - partial_sums[blockIdx.x] = static_cast(block_sum * C_coeff); - } else { - atomicAdd(&Coeff_buf[1], static_cast(block_sum * C_coeff)); - } + partial_sums[blockIdx.x] = static_cast(block_sum * C_coeff); } } } -template +template void fused_moe_aux_loss_forward_kernel_launcher_graph_safe( const DataType* probs, const IndexType* tokens_per_expert, const int64_t* total_num_tokens_dev, int num_experts, int num_rows, int num_cols, int topk, float coeff, DataType* aux_loss, - float* Coeff_buf, cudaStream_t stream, float* partial_sums = nullptr) { + float* Coeff_buf, cudaStream_t stream, float* partial_sums) { NVTE_CHECK(num_cols > 0, "num_cols must be positive, got ", num_cols); NVTE_CHECK(num_experts > 0, "num_experts must be positive, got ", num_experts); NVTE_CHECK(static_cast(num_rows) * num_cols <= INT_MAX, @@ -262,35 +237,27 @@ void fused_moe_aux_loss_forward_kernel_launcher_graph_safe( const int block_size = ((std::min(1024, num_cols) + static_cast(kThreadsPerWarp) - 1) / static_cast(kThreadsPerWarp)) * static_cast(kThreadsPerWarp); - const int grid_size = kDeterministic ? aux_loss_reduction_blocks(num_rows) : cuda::sm_count() * 2; + const int grid_size = aux_loss_reduction_blocks(num_rows); const size_t smem_size = block_size * sizeof(CompType); check_shared_memory_capacity_num_experts(smem_size, num_cols); // The main kernel refreshes Coeff_buf[0] for backward on every graph replay. - if constexpr (!kDeterministic) { - NVTE_CHECK_CUDA(cudaMemsetAsync(Coeff_buf + 1, 0, sizeof(float), stream)); - } - fused_moe_aux_loss_forward_kernel_graph_safe + fused_moe_aux_loss_forward_kernel_graph_safe <<>>(probs, tokens_per_expert, total_num_tokens_dev, num_experts, num_rows, num_cols, topk, coeff, Coeff_buf, partial_sums); NVTE_CHECK_CUDA(cudaGetLastError()); - if constexpr (kDeterministic) { - reduce_aux_loss_partials - <<<1, kThreadsPerWarp, 0, stream>>>(partial_sums, grid_size, Coeff_buf, aux_loss); - } else { - convert_accum_to_output<<<1, 1, 0, stream>>>(Coeff_buf, aux_loss); - } + reduce_aux_loss_partials + <<<1, kThreadsPerWarp, 0, stream>>>(partial_sums, grid_size, Coeff_buf, aux_loss); NVTE_CHECK_CUDA(cudaGetLastError()); } -template void fused_moe_aux_loss_forward_graph_safe(const Tensor& probs, const Tensor& tokens_per_expert, const Tensor& total_num_tokens, int num_experts, int num_rows, int num_cols, int topk, float coeff, Tensor& aux_loss, Tensor& Coeff_buf, cudaStream_t stream, - float* partial_sums = nullptr) { + float* partial_sums) { NVTE_CHECK(total_num_tokens.data.dtype == DType::kInt64, "total_num_tokens must be a 0-dim int64 tensor; got dtype ", static_cast(total_num_tokens.data.dtype)); @@ -300,8 +267,7 @@ void fused_moe_aux_loss_forward_graph_safe(const Tensor& probs, const Tensor& to probs.data.dtype, DataType, TE_ROUTER_INDEX_TYPE_SWITCH_ALL( tokens_per_expert.data.dtype, IndexType, - fused_moe_aux_loss_forward_kernel_launcher_graph_safe( + fused_moe_aux_loss_forward_kernel_launcher_graph_safe( reinterpret_cast(probs.data.dptr), reinterpret_cast(tokens_per_expert.data.dptr), reinterpret_cast(total_num_tokens.data.dptr), num_experts, num_rows, @@ -368,27 +334,19 @@ void fused_moe_aux_loss_backward(const Tensor& Const_buf, const Tensor& tokens_p void nvte_fused_moe_aux_loss_forward(const NVTETensor probs, const NVTETensor tokens_per_expert, int total_num_tokens, int num_experts, int num_rows, int num_cols, int topk, float coeff, NVTETensor aux_loss, - NVTETensor Coeff_buf, cudaStream_t stream) { + NVTETensor Const_buf, NVTETensor workspace, + cudaStream_t stream) { NVTE_API_CALL(nvte_fused_moe_aux_loss_forward); using namespace transformer_engine; + auto& scratch = *convertNVTETensorCheck(workspace); + fused_router::populate_aux_loss_workspace_config(scratch); + if (scratch.data.dptr == nullptr) return; + auto& constants = *convertNVTETensorCheck(Const_buf); + fused_router::check_aux_loss_const_buffer(constants); fused_router::fused_moe_aux_loss_forward( *convertNVTETensorCheck(probs), *convertNVTETensorCheck(tokens_per_expert), total_num_tokens, - num_experts, num_rows, num_cols, topk, coeff, *convertNVTETensorCheck(aux_loss), - *convertNVTETensorCheck(Coeff_buf), stream); -} - -void nvte_fused_moe_aux_loss_forward_graph_safe(const NVTETensor probs, - const NVTETensor tokens_per_expert, - const NVTETensor total_num_tokens, int num_experts, - int num_rows, int num_cols, int topk, float coeff, - NVTETensor aux_loss, NVTETensor Coeff_buf, - cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_moe_aux_loss_forward_graph_safe); - using namespace transformer_engine; - fused_router::fused_moe_aux_loss_forward_graph_safe( - *convertNVTETensorCheck(probs), *convertNVTETensorCheck(tokens_per_expert), - *convertNVTETensorCheck(total_num_tokens), num_experts, num_rows, num_cols, topk, coeff, - *convertNVTETensorCheck(aux_loss), *convertNVTETensorCheck(Coeff_buf), stream); + num_experts, num_rows, num_cols, topk, coeff, *convertNVTETensorCheck(aux_loss), constants, + stream, reinterpret_cast(scratch.data.dptr)); } void nvte_fused_moe_aux_loss_forward_v2(const NVTETensor probs, const NVTETensor tokens_per_expert, @@ -396,37 +354,37 @@ void nvte_fused_moe_aux_loss_forward_v2(const NVTETensor probs, const NVTETensor int num_cols, int topk, float coeff, NVTETensor aux_loss, NVTETensor Const_buf, NVTETensor workspace, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_moe_aux_loss_forward_v2); - using namespace transformer_engine; - auto& scratch = *convertNVTETensorCheck(workspace); - fused_router::populate_aux_loss_workspace_config(scratch); - if (scratch.data.dptr == nullptr) return; - auto& constants = *convertNVTETensorCheck(Const_buf); - fused_router::check_aux_loss_const_buffer(constants); - fused_router::fused_moe_aux_loss_forward( - *convertNVTETensorCheck(probs), *convertNVTETensorCheck(tokens_per_expert), total_num_tokens, - num_experts, num_rows, num_cols, topk, coeff, *convertNVTETensorCheck(aux_loss), constants, - stream, reinterpret_cast(scratch.data.dptr)); + nvte_fused_moe_aux_loss_forward(probs, tokens_per_expert, total_num_tokens, num_experts, num_rows, + num_cols, topk, coeff, aux_loss, Const_buf, workspace, stream); } -void nvte_fused_moe_aux_loss_forward_graph_safe_v2( +void nvte_fused_moe_aux_loss_forward_graph_safe( const NVTETensor probs, const NVTETensor tokens_per_expert, const NVTETensor total_num_tokens, int num_experts, int num_rows, int num_cols, int topk, float coeff, NVTETensor aux_loss, NVTETensor Const_buf, NVTETensor workspace, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_moe_aux_loss_forward_graph_safe_v2); + NVTE_API_CALL(nvte_fused_moe_aux_loss_forward_graph_safe); using namespace transformer_engine; auto& scratch = *convertNVTETensorCheck(workspace); fused_router::populate_aux_loss_workspace_config(scratch); if (scratch.data.dptr == nullptr) return; auto& constants = *convertNVTETensorCheck(Const_buf); fused_router::check_aux_loss_const_buffer(constants); - fused_router::fused_moe_aux_loss_forward_graph_safe( + fused_router::fused_moe_aux_loss_forward_graph_safe( *convertNVTETensorCheck(probs), *convertNVTETensorCheck(tokens_per_expert), *convertNVTETensorCheck(total_num_tokens), num_experts, num_rows, num_cols, topk, coeff, *convertNVTETensorCheck(aux_loss), constants, stream, reinterpret_cast(scratch.data.dptr)); } +void nvte_fused_moe_aux_loss_forward_graph_safe_v2( + const NVTETensor probs, const NVTETensor tokens_per_expert, const NVTETensor total_num_tokens, + int num_experts, int num_rows, int num_cols, int topk, float coeff, NVTETensor aux_loss, + NVTETensor Const_buf, NVTETensor workspace, cudaStream_t stream) { + nvte_fused_moe_aux_loss_forward_graph_safe(probs, tokens_per_expert, total_num_tokens, + num_experts, num_rows, num_cols, topk, coeff, aux_loss, + Const_buf, workspace, stream); +} + void nvte_fused_moe_aux_loss_backward(const NVTETensor Const_buf, const NVTETensor tokens_per_expert, int num_rows, int num_cols, NVTETensor grad_aux_loss, NVTETensor grad_probs, diff --git a/transformer_engine/common/fused_router/fused_score_for_moe_aux_loss.cu b/transformer_engine/common/fused_router/fused_score_for_moe_aux_loss.cu index 4156a5dfc96..87d696710d9 100644 --- a/transformer_engine/common/fused_router/fused_score_for_moe_aux_loss.cu +++ b/transformer_engine/common/fused_router/fused_score_for_moe_aux_loss.cu @@ -660,13 +660,11 @@ void fused_score_for_moe_aux_loss_backward(const Tensor &intermediate_output, } // namespace fused_router } // namespace transformer_engine -void nvte_fused_score_for_moe_aux_loss_forward_v2(const NVTETensor logits, int num_tokens, - int num_experts, int topk, int score_function, - NVTETensor scores, NVTETensor routing_map, - NVTERoutingMapFormat routing_map_format, - const NVTETensor intermediate_output, - cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_score_for_moe_aux_loss_forward_v2); +void nvte_fused_score_for_moe_aux_loss_forward( + const NVTETensor logits, int num_tokens, int num_experts, int topk, int score_function, + NVTETensor scores, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, + const NVTETensor intermediate_output, cudaStream_t stream) { + NVTE_API_CALL(nvte_fused_score_for_moe_aux_loss_forward); using namespace transformer_engine; fused_router::fused_score_for_moe_aux_loss_forward( *convertNVTETensorCheck(logits), num_tokens, num_experts, topk, score_function, @@ -674,15 +672,13 @@ void nvte_fused_score_for_moe_aux_loss_forward_v2(const NVTETensor logits, int n *convertNVTETensorCheck(intermediate_output), stream); } -void nvte_fused_score_for_moe_aux_loss_forward(const NVTETensor logits, int num_tokens, - int num_experts, int topk, int score_function, - NVTETensor scores, NVTETensor routing_map, - const NVTETensor intermediate_output, - cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_score_for_moe_aux_loss_forward); - nvte_fused_score_for_moe_aux_loss_forward_v2( - logits, num_tokens, num_experts, topk, score_function, scores, routing_map, - NVTE_ROUTING_MAP_FORMAT_BYTEMAP, intermediate_output, stream); +void nvte_fused_score_for_moe_aux_loss_forward_v2( + const NVTETensor logits, int num_tokens, int num_experts, int topk, int score_function, + NVTETensor scores, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, + const NVTETensor intermediate_output, cudaStream_t stream) { + nvte_fused_score_for_moe_aux_loss_forward(logits, num_tokens, num_experts, topk, score_function, + scores, routing_map, routing_map_format, + intermediate_output, stream); } void nvte_fused_score_for_moe_aux_loss_backward(const NVTETensor intermediate_output, diff --git a/transformer_engine/common/fused_router/fused_topk_with_score_function.cu b/transformer_engine/common/fused_router/fused_topk_with_score_function.cu index 5355a798b40..0b54df71929 100644 --- a/transformer_engine/common/fused_router/fused_topk_with_score_function.cu +++ b/transformer_engine/common/fused_router/fused_topk_with_score_function.cu @@ -1706,12 +1706,12 @@ void fused_topk_with_score_function_backward_with_indices( } // namespace fused_router } // namespace transformer_engine -void nvte_fused_topk_with_score_function_forward_v2( +void nvte_fused_topk_with_score_function_forward( const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_topk_with_score_function_forward_v2); + NVTE_API_CALL(nvte_fused_topk_with_score_function_forward); using namespace transformer_engine; fused_router::fused_topk_with_score_function_forward( *convertNVTETensorCheck(logits), num_tokens, num_experts, topk, @@ -1721,16 +1721,16 @@ void nvte_fused_topk_with_score_function_forward_v2( *convertNVTETensorCheck(intermediate_output), stream); } -void nvte_fused_topk_with_score_function_forward( +void nvte_fused_topk_with_score_function_forward_v2( const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, - NVTETensor intermediate_output, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_topk_with_score_function_forward); - nvte_fused_topk_with_score_function_forward_v2( - logits, num_tokens, num_experts, topk, use_pre_softmax, num_groups, group_topk, - scaling_factor, score_function, expert_bias, probs, routing_map, - NVTE_ROUTING_MAP_FORMAT_BYTEMAP, intermediate_output, stream); + NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, cudaStream_t stream) { + nvte_fused_topk_with_score_function_forward(logits, num_tokens, num_experts, topk, + use_pre_softmax, num_groups, group_topk, + scaling_factor, score_function, expert_bias, probs, + routing_map, routing_map_format, intermediate_output, + stream); } void nvte_fused_topk_with_score_function_forward_with_indices( @@ -1747,13 +1747,13 @@ void nvte_fused_topk_with_score_function_forward_with_indices( *convertNVTETensorCheck(topk_indices), *convertNVTETensorCheck(intermediate_output), stream); } -void nvte_fused_topk_with_score_function_forward_qb_v2( +void nvte_fused_topk_with_score_function_forward_qb( const NVTETensor logits, int num_tokens, int num_experts, int topk, float scaling_factor, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, NVTETensor cutoff, NVTETensor histogram, NVTETensor bin_bounds, NVTEQBHistogramMode histogram_mode, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_topk_with_score_function_forward_qb_v2); + NVTE_API_CALL(nvte_fused_topk_with_score_function_forward_qb); using namespace transformer_engine; fused_router::fused_topk_with_score_function_forward_qb( *convertNVTETensorCheck(logits), num_tokens, num_experts, topk, scaling_factor, @@ -1764,17 +1764,16 @@ void nvte_fused_topk_with_score_function_forward_qb_v2( stream); } -void nvte_fused_topk_with_score_function_forward_qb_v2_unchecked( +void nvte_fused_topk_with_score_function_forward_qb_v2( const NVTETensor logits, int num_tokens, int num_experts, int topk, float scaling_factor, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, NVTETensor cutoff, NVTETensor histogram, NVTETensor bin_bounds, NVTEQBHistogramMode histogram_mode, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_topk_with_score_function_forward_qb_v2_unchecked); - nvte_fused_topk_with_score_function_forward_qb_v2(logits, num_tokens, num_experts, topk, - scaling_factor, expert_bias, probs, routing_map, - routing_map_format, intermediate_output, cutoff, - histogram, bin_bounds, histogram_mode, stream); + nvte_fused_topk_with_score_function_forward_qb(logits, num_tokens, num_experts, topk, + scaling_factor, expert_bias, probs, routing_map, + routing_map_format, intermediate_output, cutoff, + histogram, bin_bounds, histogram_mode, stream); } void nvte_fused_topk_with_score_function_forward_qb_with_indices( @@ -1792,17 +1791,6 @@ void nvte_fused_topk_with_score_function_forward_qb_with_indices( *convertNVTETensorCheck(bin_bounds), histogram_mode, stream); } -void nvte_fused_topk_with_score_function_forward_qb_with_indices_unchecked( - const NVTETensor logits, int num_tokens, int num_experts, int topk, float scaling_factor, - const NVTETensor expert_bias, NVTETensor probs, NVTETensor topk_indices, - NVTETensor intermediate_output, NVTETensor cutoff, NVTETensor histogram, NVTETensor bin_bounds, - NVTEQBHistogramMode histogram_mode, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_topk_with_score_function_forward_qb_with_indices_unchecked); - nvte_fused_topk_with_score_function_forward_qb_with_indices( - logits, num_tokens, num_experts, topk, scaling_factor, expert_bias, probs, topk_indices, - intermediate_output, cutoff, histogram, bin_bounds, histogram_mode, stream); -} - void nvte_qb_histogram_accumulate(const NVTETensor raw_scores, const NVTETensor cutoff, const NVTETensor bin_bounds, NVTETensor histogram, cudaStream_t stream) { @@ -1813,22 +1801,12 @@ void nvte_qb_histogram_accumulate(const NVTETensor raw_scores, const NVTETensor *convertNVTETensorCheck(bin_bounds), *convertNVTETensorCheck(histogram), stream); } -void nvte_qb_histogram_accumulate_unchecked(const NVTETensor raw_scores, const NVTETensor cutoff, - const NVTETensor bin_bounds, NVTETensor histogram, - cudaStream_t stream) { - NVTE_API_CALL(nvte_qb_histogram_accumulate_unchecked); - nvte_qb_histogram_accumulate(raw_scores, cutoff, bin_bounds, histogram, stream); -} - -void nvte_fused_topk_with_score_function_backward_v2(const NVTETensor routing_map, - NVTERoutingMapFormat routing_map_format, - const NVTETensor intermediate_output, - const NVTETensor grad_probs, int num_tokens, - int num_experts, int topk, - bool use_pre_softmax, float scaling_factor, - int score_function, NVTETensor grad_logits, - cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_topk_with_score_function_backward_v2); +void nvte_fused_topk_with_score_function_backward( + const NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, + const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, + int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, + NVTETensor grad_logits, cudaStream_t stream) { + NVTE_API_CALL(nvte_fused_topk_with_score_function_backward); using namespace transformer_engine; fused_router::fused_topk_with_score_function_backward( *convertNVTETensorCheck(routing_map), routing_map_format, @@ -1837,16 +1815,15 @@ void nvte_fused_topk_with_score_function_backward_v2(const NVTETensor routing_ma *convertNVTETensorCheck(grad_logits), stream); } -void nvte_fused_topk_with_score_function_backward(const NVTETensor routing_map, - const NVTETensor intermediate_output, - const NVTETensor grad_probs, int num_tokens, - int num_experts, int topk, bool use_pre_softmax, - float scaling_factor, int score_function, - NVTETensor grad_logits, cudaStream_t stream) { - NVTE_API_CALL(nvte_fused_topk_with_score_function_backward); - nvte_fused_topk_with_score_function_backward_v2( - routing_map, NVTE_ROUTING_MAP_FORMAT_BYTEMAP, intermediate_output, grad_probs, num_tokens, - num_experts, topk, use_pre_softmax, scaling_factor, score_function, grad_logits, stream); +void nvte_fused_topk_with_score_function_backward_v2( + const NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, + const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, + int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, + NVTETensor grad_logits, cudaStream_t stream) { + nvte_fused_topk_with_score_function_backward(routing_map, routing_map_format, intermediate_output, + grad_probs, num_tokens, num_experts, topk, + use_pre_softmax, scaling_factor, score_function, + grad_logits, stream); } void nvte_fused_topk_with_score_function_backward_with_indices( diff --git a/transformer_engine/common/gemm/cublaslt_gemm.cu b/transformer_engine/common/gemm/cublaslt_gemm.cu index 6cd4750bedc..8733c10a706 100644 --- a/transformer_engine/common/gemm/cublaslt_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_gemm.cu @@ -972,44 +972,12 @@ void cublas_gemm(const Tensor *inputA, const Tensor *inputB, const Tensor *input int nvte_get_cublaslt_build_version() { return CUBLAS_VERSION; } -void nvte_cublas_gemm(const NVTETensor A, const NVTETensor B, NVTETensor D, const NVTETensor bias, - NVTETensor pre_gelu_out, bool transa, bool transb, bool grad, - NVTETensor workspace, bool accumulate, bool use_split_accumulator, - int math_sm_count, cudaStream_t stream) { +void nvte_cublas_gemm(bool transa, bool transb, const float *alpha, const NVTETensor A, + const NVTETensor B, const float *beta, const NVTETensor C, NVTETensor D, + NVTETensor workspace, NVTEMatmulConfig config, cudaStream_t stream) { NVTE_API_CALL(nvte_cublas_gemm); using namespace transformer_engine; - // Tensors - const Tensor *inputA = convertNVTETensorCheck(A); - const Tensor *inputB = convertNVTETensorCheck(B); - Tensor *outputD = convertNVTETensorCheck(D); - const Tensor *biasTensor = convertNVTETensor(bias); - Tensor *outputGelu = convertNVTETensor(pre_gelu_out); - Tensor *wspace = convertNVTETensor(workspace); - - // Scales - const float alpha = 1; - const float beta = accumulate ? 1 : 0; - - // Check for NVFP4 - // TODO Remove once alpha scale logic is moved into cublas_gemm function - if (is_nvfp_scaling(inputA->scaling_mode) || is_nvfp_scaling(inputB->scaling_mode)) { - NVTE_ERROR("nvte_cublas_gemm does not support NVFP4 data. Use nvte_cublas_gemm_v2 instead."); - } - - // Launch GEMM, accumulating in-place if needed - cublas_gemm(inputA, inputB, accumulate ? outputD : nullptr, outputD, biasTensor, outputGelu, - (transa) ? CUBLAS_OP_T : CUBLAS_OP_N, (transb) ? CUBLAS_OP_T : CUBLAS_OP_N, grad, - wspace->data.dptr, wspace->data.shape[0], &alpha, &beta, false, use_split_accumulator, - math_sm_count, 0, 0, false, nullptr, stream); -} - -void nvte_cublas_gemm_v2(bool transa, bool transb, const float *alpha, const NVTETensor A, - const NVTETensor B, const float *beta, const NVTETensor C, NVTETensor D, - NVTETensor workspace, NVTEMatmulConfig config, cudaStream_t stream) { - NVTE_API_CALL(nvte_cublas_gemm_v2); - using namespace transformer_engine; - // Data tensors const Tensor *A_tensor = convertNVTETensorCheck(A); const Tensor *B_tensor = convertNVTETensorCheck(B); @@ -1064,32 +1032,10 @@ void nvte_cublas_gemm_v2(bool transa, bool transb, const float *alpha, const NVT false, nullptr, stream); } -void nvte_cublas_gemm_scaled(const NVTETensor A, const NVTETensor B, NVTETensor D, - const NVTETensor bias, NVTETensor pre_gelu_out, bool transa, - bool transb, bool grad, NVTETensor workspace, float alpha, float beta, - bool use_split_accumulator, int math_sm_count, cudaStream_t stream) { - NVTE_API_CALL(nvte_cublas_gemm); - using namespace transformer_engine; - - // Tensors - const Tensor *inputA = convertNVTETensorCheck(A); - const Tensor *inputB = convertNVTETensorCheck(B); - Tensor *outputD = convertNVTETensorCheck(D); - const Tensor *biasTensor = convertNVTETensor(bias); - Tensor *outputGelu = convertNVTETensor(pre_gelu_out); - Tensor *wspace = convertNVTETensor(workspace); - - // Check for NVFP4 - // TODO Remove once alpha scale logic is moved into cublas_gemm function - if (is_nvfp_scaling(inputA->scaling_mode) || is_nvfp_scaling(inputB->scaling_mode)) { - NVTE_ERROR("nvte_cublas_gemm does not support NVFP4 data. Use nvte_cublas_gemm_v2 instead."); - } - - // Launch GEMM, accumulating in-place if needed - cublas_gemm(inputA, inputB, beta != 0 ? outputD : nullptr, outputD, biasTensor, outputGelu, - (transa) ? CUBLAS_OP_T : CUBLAS_OP_N, (transb) ? CUBLAS_OP_T : CUBLAS_OP_N, grad, - wspace->data.dptr, wspace->data.shape[0], &alpha, &beta, false, use_split_accumulator, - math_sm_count, 0, 0, false, nullptr, stream); +void nvte_cublas_gemm_v2(bool transa, bool transb, const float *alpha, const NVTETensor A, + const NVTETensor B, const float *beta, const NVTETensor C, NVTETensor D, + NVTETensor workspace, NVTEMatmulConfig config, cudaStream_t stream) { + nvte_cublas_gemm(transa, transb, alpha, A, B, beta, C, D, workspace, config, stream); } void nvte_cublas_atomic_gemm(const NVTETensor A, const NVTETensor B, NVTETensor D, @@ -1180,9 +1126,9 @@ void multi_stream_cublas_gemm(const NVTETensor *A, const NVTETensor *B, NVTETens // Launch GEMM const float alpha = 1.f; const float beta = accumulate ? 1.f : 0.f; - nvte_cublas_gemm_v2(transa, transb, &alpha, A[i], B[i], &beta, accumulate ? D[i] : nullptr, - D[i], workspace[i % num_streams], &config, - detail::get_compute_stream(i % num_streams)); + nvte_cublas_gemm(transa, transb, &alpha, A[i], B[i], &beta, accumulate ? D[i] : nullptr, + D[i], workspace[i % num_streams], &config, + detail::get_compute_stream(i % num_streams)); } // record events on compute streams diff --git a/transformer_engine/common/include/transformer_engine/activation.h b/transformer_engine/common/include/transformer_engine/activation.h index 99087f0b82e..baf8ceeca15 100644 --- a/transformer_engine/common/include/transformer_engine/activation.h +++ b/transformer_engine/common/include/transformer_engine/activation.h @@ -383,31 +383,6 @@ void nvte_swiglu(const NVTETensor input, NVTETensor output, cudaStream_t stream) void nvte_situglu(const NVTETensor input, NVTETensor output, float beta1, float beta2, cudaStream_t stream); -/*! \brief Computes the gated Swish activation of the input used in GPT OSS. - * - * \deprecated This function has been deprecated in favor of nvte_clamped_swiglu_v2, - * which exposes a configurable offset for the linear (gate) component. - * This API is preserved for backward compatibility and is equivalent to - * calling nvte_clamped_swiglu_v2 with glu_linear_offset = 1.0. - * - * See https://github.com/openai/gpt-oss/blob/a0a84273e9e0c14a233cb9befdfd159c2bcfa6cd/gpt_oss/torch/model.py#L250 - * This Gated activation has two differences compared to the original SwiGLU - * 1. Both gate and pre-activations are clipped based on parameter limit. - * 2. Activation uses sigmoid(alpha * x) instead of sigmoid(x) used in Swish activation inspired - * by original GELU paper https://arxiv.org/pdf/1606.08415 - * If the scaling mode of the output tensor is set to NVTE_MXFP8_1D_SCALING, - * the block quantization (MXFP8) of the specified shape of the block will be used. - * - * \param[in] input Input tensor of shape [N, H * 2]. - * \param[in,out] output Output tensor of shape [N, H]. - * It computes Act(input[N, :H]) x input[N, H:] - * \param[in] limit Clipping limits for gate and pre-activation. - * \param[in] alpha Scaling factor for the sigmoid function used in the activation. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_clamped_swiglu(const NVTETensor input, NVTETensor output, float limit, float alpha, - cudaStream_t stream); - /*! \brief Computes the gated Swish activation of the input used in GPT OSS, with a configurable * offset for the linear (gate) component after clamping. * @@ -427,6 +402,13 @@ void nvte_clamped_swiglu(const NVTETensor input, NVTETensor output, float limit, * \param[in] glu_linear_offset Offset added to the linear component after clamping (typically 1.0). * \param[in] stream CUDA stream used for the operation. */ +void nvte_clamped_swiglu(const NVTETensor input, NVTETensor output, float limit, float alpha, + float glu_linear_offset, cudaStream_t stream); + +/*! \brief Deprecated alias for nvte_clamped_swiglu. + * + * \deprecated Use nvte_clamped_swiglu instead. + */ void nvte_clamped_swiglu_v2(const NVTETensor input, NVTETensor output, float limit, float alpha, float glu_linear_offset, cudaStream_t stream); @@ -465,7 +447,7 @@ void nvte_scaled_situglu(const NVTETensor input, const NVTETensor act_scales, NV * * Computes output = ClampedSwiGLU(input) * act_scales[:, None]. * This uses the same clamping, alpha, and linear-offset semantics as - * nvte_clamped_swiglu_v2. + * nvte_clamped_swiglu. * * \param[in] input Input tensor of shape [N, H * 2]. * \param[in] act_scales Row-wise activation scales of shape [N]. @@ -551,31 +533,6 @@ void nvte_dswiglu(const NVTETensor grad, const NVTETensor input, NVTETensor outp void nvte_dsituglu(const NVTETensor grad, const NVTETensor input, NVTETensor output, float beta1, float beta2, cudaStream_t stream); -/*! \brief Computes the gradient of gated Swish activation of the input used in GPT OSS. - * - * \deprecated This function has been deprecated in favor of nvte_clamped_dswiglu_v2, - * which exposes a configurable offset for the linear (gate) component. - * This API is preserved for backward compatibility and is equivalent to - * calling nvte_clamped_dswiglu_v2 with glu_linear_offset = 1.0. - * - * https://github.com/openai/gpt-oss/blob/a0a84273e9e0c14a233cb9befdfd159c2bcfa6cd/gpt_oss/torch/model.py#L250 - * This activation has two differences compared to the original SwiGLU - * 1. Both gate and pre-activations are clipped based on parameter limit. - * 2. Activation uses sigmoid(alpha * x) instead of sigmoid(x) used in Swish activation inspired - * by original GELU paper https://arxiv.org/pdf/1606.08415 - * If the scaling mode of the output tensor is set to NVTE_MXFP8_1D_SCALING, - * the block quantization (MXFP8) of the specified shape of the block will be used. - * - * \param[in] grad Incoming gradient of shape [N, H]. - * \param[in] input Forward input tensor of shape [N, H * 2]. - * \param[in,out] output Outgoing gradient of shape [N, H * 2]. - * \param[in] limit Clipping limits for gate and pre-activation. - * \param[in] alpha Scaling factor for the sigmoid function used in the activation. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_clamped_dswiglu(const NVTETensor grad, const NVTETensor input, NVTETensor output, - float limit, float alpha, cudaStream_t stream); - /*! \brief Computes the gradient of gated Swish activation of the input used in GPT OSS, with a * configurable offset for the linear (gate) component after clamping. * @@ -595,6 +552,13 @@ void nvte_clamped_dswiglu(const NVTETensor grad, const NVTETensor input, NVTETen * \param[in] glu_linear_offset Offset added to the linear component after clamping (typically 1.0). * \param[in] stream CUDA stream used for the operation. */ +void nvte_clamped_dswiglu(const NVTETensor grad, const NVTETensor input, NVTETensor output, + float limit, float alpha, float glu_linear_offset, cudaStream_t stream); + +/*! \brief Deprecated alias for nvte_clamped_dswiglu. + * + * \deprecated Use nvte_clamped_dswiglu instead. + */ void nvte_clamped_dswiglu_v2(const NVTETensor grad, const NVTETensor input, NVTETensor output, float limit, float alpha, float glu_linear_offset, cudaStream_t stream); diff --git a/transformer_engine/common/include/transformer_engine/cast.h b/transformer_engine/common/include/transformer_engine/cast.h index 36e1f584a37..5d6b12099a5 100644 --- a/transformer_engine/common/include/transformer_engine/cast.h +++ b/transformer_engine/common/include/transformer_engine/cast.h @@ -85,15 +85,24 @@ extern "C" { * absolute max is required. The scaling factors are also rounded to powers of 2. */ -/*! \brief Casts input tensor to FP8/MXFP8/BlockwiseFP8. +/*! \brief Casts input tensor to a quantized output tensor. * The type of quantized tensor in the output depends on the scaling mode of the output * tensor. See file level comments. * - * \param[in] input Input tensor to be cast. - * \param[in,out] output Output FP8/MXFP8/BlockwiseFP8 tensor. - * \param[in] stream CUDA stream used for the operation. + * \param[in] input Input tensor to be cast. + * \param[in,out] output Output quantized tensor. + * \param[in] quant_config Quantization configuration, or NULL for defaults. + * \param[in] stream CUDA stream used for the operation. */ -void nvte_quantize(const NVTETensor input, NVTETensor output, cudaStream_t stream); +void nvte_quantize(const NVTETensor input, NVTETensor output, + const NVTEQuantizationConfig quant_config, cudaStream_t stream); + +/*! \brief Deprecated alias for nvte_quantize. + * + * \deprecated Use nvte_quantize instead. + */ +void nvte_quantize_v2(const NVTETensor input, NVTETensor output, + const NVTEQuantizationConfig quant_config, cudaStream_t stream); /*! \brief Casts input grouped tensor. * The type of quantized tensor in the output depends on the scaling mode of the output @@ -109,29 +118,6 @@ void nvte_quantize(const NVTETensor input, NVTETensor output, cudaStream_t strea void nvte_group_quantize(const NVTEGroupedTensor input, NVTEGroupedTensor output, const NVTEQuantizationConfig quant_config, cudaStream_t stream); -/*! \brief Casts input tensor to FP8/MXFP8/BlockwiseFP8, providing the option to immediately exit the kernel - * based on the value of the 'noop' tensor. - * The type of quantized tensor in the output depends on the scaling mode of the output - * tensor. See file level comments. - * - * \param[in] input Input tensor to be cast. - * \param[in,out] output Output quantized tensor. - * \param[out] noop Noop tensor. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_quantize_noop(const NVTETensor input, NVTETensor output, NVTETensor noop, - cudaStream_t stream); - -/*! \brief Casts input tensor to quantized output tensor, with advanced quantization options. - * - * \param[in] input Input tensor to be cast. - * \param[in,out] output Output quantized tensor. - * \param[in] quant_config Quantization configuration. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_quantize_v2(const NVTETensor input, NVTETensor output, - const NVTEQuantizationConfig quant_config, cudaStream_t stream); - /*! \brief Casts input tensor to MXFP8. Additionally, reduces the input along columns. * If the scaling mode of the output tensor is set to NVTE_MXFP8_1D_SCALING, * the block quantization (MXFP8) of the specified shape of the block will be used. diff --git a/transformer_engine/common/include/transformer_engine/fused_attn.h b/transformer_engine/common/include/transformer_engine/fused_attn.h index f3add1b8a87..a7bd7763d43 100644 --- a/transformer_engine/common/include/transformer_engine/fused_attn.h +++ b/transformer_engine/common/include/transformer_engine/fused_attn.h @@ -467,7 +467,7 @@ void nvte_set_fused_attn_bwd_params_attribute(NVTEFusedAttnBwdParams params, * a diagnostic message explaining why the configuration is rejected. Pass * `NULL` to skip the diagnostics. The library maintains a per-thread buffer, * and callers do not need to allocate memory for the message. The buffer - * content stays valid until the next call of `nvte_get_fused_attn_backend_v2`. + * content stays valid until the next call of `nvte_get_fused_attn_backend`. * * \return Fused-attention backend, `NVTE_F16_arbitrary_seqlen` or `NVTE_FP8`, * if the configuration is supported; otherwise, `NVTE_No_Backend`. @@ -475,64 +475,16 @@ void nvte_set_fused_attn_bwd_params_attribute(NVTEFusedAttnBwdParams params, * \deprecated The C fused-attention API will be removed in the next major release. * Use Transformer Engine Python attention APIs instead. */ -NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend_v2(NVTEFusedAttnConfig cfg, - const char **message); +NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend(NVTEFusedAttnConfig cfg, const char **message); -/*! \brief Get fused attention backend based on input parameters. - * - * \param[in] is_training Whether the model is in training mode. - * \param[in] q_dtype The data type of Tensor Q. - * \param[in] kv_dtype The data type of Tensors K, V. - * \param[in] qkv_layout The layout of Tensors Q, K, V. - * \param[in] bias_type The attention bias type. - * \param[in] attn_mask_type The attention mask type. - * \param[in] softmax_type The attention softmax type. - * \param[in] dropout The dropout probability. - * \param[in] num_attn_heads The number of heads in Q. - * \param[in] num_gqa_groups The number of heads in K, V. - * \param[in] max_seqlen_q The sequence length of Q. - * \param[in] max_seqlen_kv The sequence length of K, V. - * \param[in] head_dim_qk The head dimension of Q, K. - * \param[in] head_dim_v The head dimension of V. - * \param[in] window_size_left Sliding window size (the left half). - * \param[in] window_size_right Sliding window size (the right half). - * \param[in] return_max_logit Whether to produce Max along with Stats. - * \param[in] cuda_graph Whether cuda graph capture is enabled or not. - * \param[in] deterministic Whether determinism is required or not. +/*! \brief Deprecated alias for nvte_get_fused_attn_backend. * - * \deprecated The C fused-attention API will be removed in the next major release. - * Use Transformer Engine Python attention APIs instead. - * - * \note `nvte_get_fused_attn_backend` has a narrower input signature compared to - * `nvte_get_fused_attn_backend_v2`. For the fields it cannot express, it fills them with - * the default values of `nvte_get_fused_attn_backend_v2`. This includes setting - * `batch_size` = 1, deriving output/gradient formats from `qkv_layout`, assuming a standard - * bias shape [b, h, sq, skv] for `NVTE_POST_SCALE_BIAS`, using delayed scaling for all FP8, - * and not supporting paged-KV attention checks. Users who need more precise control should - * use `nvte_get_fused_attn_backend_v2` instead. + * \deprecated Use nvte_get_fused_attn_backend instead. */ -NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend( - bool is_training, NVTEDType q_dtype, NVTEDType kv_dtype, NVTE_QKV_Layout qkv_layout, - NVTE_Bias_Type bias_type, NVTE_Mask_Type attn_mask_type, NVTE_Softmax_Type softmax_type, - float dropout, size_t num_attn_heads, size_t num_gqa_groups, size_t max_seqlen_q, - size_t max_seqlen_kv, size_t head_dim_qk, size_t head_dim_v, int64_t window_size_left, - int64_t window_size_right, bool return_max_logit, bool cuda_graph, bool deterministic); +NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend_v2(NVTEFusedAttnConfig cfg, + const char **message); /*! \brief Compute dot product attention with Q, K, and V. - * - * All inputs and outputs are carried by the opaque \p params handle. Create it with - * `nvte_create_fused_attn_fwd_params()`, populate it with - * `nvte_set_fused_attn_fwd_params_attribute()` or `FusedAttnFwdParamsWrapper` setters, and - * destroy it with `nvte_destroy_fused_attn_fwd_params()`. - * - * \param[in,out] params Fused-attention forward-parameter handle. - * - * \deprecated The C fused-attention API will be removed in the next major release. - * Use Transformer Engine Python attention APIs instead. - */ -void nvte_fused_attn_fwd_v2(NVTEFusedAttnFwdParams params); - -/*! \brief Compute dot product attention with separate Q, K and V. * * Computes: * - P = Q * Transpose(K) + Bias @@ -553,78 +505,25 @@ void nvte_fused_attn_fwd_v2(NVTEFusedAttnFwdParams params); * For example, a tensor of 4 sequences `[a, PAD, b, b, c, PAD, PAD, d, d]` should have * `cu_seqlens = [0, 1, 3, 4, 6]` and `cu_seqlens_padded= [0, 2, 4, 7, 9]`. * - * \param[in] Q The Q tensor. - * \param[in] K The K tensor. - * \param[in] V The V tensor. - * \param[in] Bias The Bias tensor. - * \param[in] SoftmaxOffset The SoftmaxOffset tensor. - * \param[in,out] S The S tensor. - * \param[out] O The output O tensor. - * \param[out] Aux_CTX_Tensors Auxiliary output tensors when training, - * e.g. softmax stats, optional Max, rng_state. - * \param[in] cu_seqlens_q Cumulative sequence lengths for Q, [batch_size + 1]. - * \param[in] cu_seqlens_kv Cumulative sequence lengths for K and V, [batch_size + 1]. - * \param[in] cu_seqlens_q_padded Cumulative sequence offsets for Q, [batch_size + 1]. - * \param[in] cu_seqlens_kv_padded Cumulative sequence offsets for KV, [batch_size + 1]. - * \param[in] page_table_k Page table for K cache, [batch_size, max_pages_per_seq_k]. - * \param[in] page_table_v Page table for V cache, [batch_size, max_pages_per_seq_v]. - * \param[in] rng_state Seed and offset of CUDA random number generator. - * \param[in] max_seqlen_q Max sequence length used for computing for Q. - * it may be >= max(seqlen_q_i) for i=0,...batch_size-1. - * \param[in] max_seqlen_kv Max sequence length used for computing for K and V. - * it may be >= max(seqlen_kv_i) for i=0,...batch_size-1. - * \param[in] is_training Whether this is in training mode or inference. - * \param[in] return_max_logit Whether to produce Max along with Stats. - * \param[in] cuda_graph Whether cuda graph capture is enabled or not. - * \param[in] attn_scale Scaling factor for Q * K.T. - * \param[in] dropout Dropout probability. - * \param[in] qkv_layout QKV tensors' layout. - * \param[in] o_format Output format. - * \param[in] qkv_scale_inv_format Format of scale-inverse tensors for QKV; - * if `NVTE_QKV_Format_NOT_SET`, inferred from - * `qkv_layout`. - * \param[in] bias_type Bias type. - * \param[in] attn_mask_type Attention mask type. - * \param[in] softmax_type Attention softmax type. - * \param[in] window_size_left Sliding window size (the left half). - * \param[in] window_size_right Sliding window size (the right half). - * \param[in] bottom_right_diagonal Whether to align sliding window and ALiBi diagonal to the bottom right corner of the softmax matrix. - * \param[in] workspace Workspace tensor. - * \param[in] stream CUDA stream used for this operation. + * All inputs and outputs are carried by the opaque \p params handle. Create it with + * `nvte_create_fused_attn_fwd_params()`, populate it with + * `nvte_set_fused_attn_fwd_params_attribute()` or `FusedAttnFwdParamsWrapper` setters, and + * destroy it with `nvte_destroy_fused_attn_fwd_params()`. + * + * \param[in,out] params Fused-attention forward-parameter handle. * * \deprecated The C fused-attention API will be removed in the next major release. * Use Transformer Engine Python attention APIs instead. */ -void nvte_fused_attn_fwd(const NVTETensor Q, const NVTETensor K, const NVTETensor V, - const NVTETensor Bias, const NVTETensor SoftmaxOffset, NVTETensor S, - NVTETensor O, NVTETensorPack *Aux_CTX_Tensors, - const NVTETensor cu_seqlens_q, const NVTETensor cu_seqlens_kv, - const NVTETensor cu_seqlens_q_padded, - const NVTETensor cu_seqlens_kv_padded, const NVTETensor page_table_k, - const NVTETensor page_table_v, const NVTETensor rng_state, - size_t max_seqlen_q, size_t max_seqlen_kv, bool is_training, - bool return_max_logit, bool cuda_graph, float attn_scale, float dropout, - NVTE_QKV_Layout qkv_layout, NVTE_QKV_Format o_format, - NVTE_QKV_Format qkv_scale_inv_format, NVTE_Bias_Type bias_type, - NVTE_Mask_Type attn_mask_type, NVTE_Softmax_Type softmax_type, - int64_t window_size_left, int64_t window_size_right, - bool bottom_right_diagonal, NVTETensor workspace, cudaStream_t stream); +void nvte_fused_attn_fwd(NVTEFusedAttnFwdParams params); -/*! \brief Compute the backward of the dot product attention with Q, K and V. - * - * All inputs and outputs are carried by the opaque \p params handle. Create it with - * `nvte_create_fused_attn_bwd_params()`, populate it with - * `nvte_set_fused_attn_bwd_params_attribute()` or `FusedAttnBwdParamsWrapper` setters, and - * destroy it with `nvte_destroy_fused_attn_bwd_params()`. +/*! \brief Deprecated alias for nvte_fused_attn_fwd. * - * \param[in,out] params Fused-attention backward-parameter handle. - * - * \deprecated The C fused-attention API will be removed in the next major release. - * Use Transformer Engine Python attention APIs instead. + * \deprecated Use nvte_fused_attn_fwd instead. */ -void nvte_fused_attn_bwd_v2(NVTEFusedAttnBwdParams params); +void nvte_fused_attn_fwd_v2(NVTEFusedAttnFwdParams params); -/*! \brief Compute the backward of the dot product attention with separate Q, K and V. +/*! \brief Compute the backward of the dot product attention with Q, K and V. * * Notes: * @@ -639,69 +538,23 @@ void nvte_fused_attn_bwd_v2(NVTEFusedAttnBwdParams params); * For example, a tensor of 4 sequences `[a, PAD, b, b, c, PAD, PAD, d, d]` should have * `cu_seqlens = [0, 1, 3, 4, 6]` and `cu_seqlens_padded= [0, 2, 4, 7, 9]`. * - * \param[in] Q The Q tensor. - * \param[in] K The K tensor. - * \param[in] V The V tensor. - * \param[in] O The O tensor from forward. - * \param[in] dO The gradient of the O tensor. - * \param[in] S The S tensor. - * \param[in,out] dP The gradient of the P tensor. - * \param[in] Aux_CTX_Tensors Auxiliary tensors from context when in training mode, - * e.g. softmax stats, optional Max, rng_state. - * \param[out] dQ The gradient of the Q tensor. - * \param[out] dK The gradient of the K tensor. - * \param[out] dV The gradient of the V tensor. - * \param[out] dBias The gradient of the Bias tensor. - * \param[out] dSoftmaxOffset The gradient of the SoftmaxOffset tensor. - * \param[in] cu_seqlens_q Cumulative sequence lengths for Q, [batch_size + 1]. - * \param[in] cu_seqlens_kv Cumulative sequence lengths for K and V, [batch_size + 1]. - * \param[in] cu_seqlens_q_padded Cumulative sequence offsets for Q, [batch_size + 1]. - * \param[in] cu_seqlens_kv_padded Cumulative sequence offsets for KV, [batch_size + 1]. - * \param[in] max_seqlen_q Max sequence length used for computing for Q. - * it may be >= max(seqlen_q_i) for i=0,...batch_size-1. - * \param[in] max_seqlen_kv Max sequence length used for computing for K and V. - * it may be >= max(seqlen_kv_i) for i=0,...batch_size-1. - * \param[in] attn_scale Scaling factor for Q * K.T. - * \param[in] dropout Dropout probability. - * \param[in] qkv_layout QKV tensors' layout. - * \param[in] o_format Output format. - * \param[in] do_format Output gradient's format. - * \param[in] dqkv_layout QKV gradient tensors' layout. - * \param[in] qkv_scale_inv_format Format of scale-inverse tensors for QKV; - * if `NVTE_QKV_Format_NOT_SET`, inferred from - * `qkv_layout`. - * \param[in] do_scale_inv_format Format of scale-inverse tensors for dO; - * if `NVTE_QKV_Format_NOT_SET`, inferred from the - * output layout. - * \param[in] bias_type Bias type. - * \param[in] attn_mask_type Attention mask type. - * \param[in] softmax_type Attention softmax type. - * \param[in] window_size_left Sliding window size (the left half). - * \param[in] window_size_right Sliding window size (the right half). - * \param[in] bottom_right_diagonal Whether to align sliding window and ALiBi diagonal to the bottom right corner of the softmax matrix. - * \param[in] deterministic Whether to execute with deterministic behaviours. - * \param[in] cuda_graph Whether cuda graph capture is enabled or not. - * \param[in] workspace Workspace tensor. - * \param[in] stream CUDA stream used for this operation. + * All inputs and outputs are carried by the opaque \p params handle. Create it with + * `nvte_create_fused_attn_bwd_params()`, populate it with + * `nvte_set_fused_attn_bwd_params_attribute()` or `FusedAttnBwdParamsWrapper` setters, and + * destroy it with `nvte_destroy_fused_attn_bwd_params()`. + * + * \param[in,out] params Fused-attention backward-parameter handle. * * \deprecated The C fused-attention API will be removed in the next major release. * Use Transformer Engine Python attention APIs instead. */ -void nvte_fused_attn_bwd(const NVTETensor Q, const NVTETensor K, const NVTETensor V, - const NVTETensor O, const NVTETensor dO, const NVTETensor S, NVTETensor dP, - const NVTETensorPack *Aux_CTX_Tensors, NVTETensor dQ, NVTETensor dK, - NVTETensor dV, NVTETensor dBias, NVTETensor dSoftmaxOffset, - const NVTETensor cu_seqlens_q, const NVTETensor cu_seqlens_kv, - const NVTETensor cu_seqlens_q_padded, - const NVTETensor cu_seqlens_kv_padded, size_t max_seqlen_q, - size_t max_seqlen_kv, float attn_scale, float dropout, - NVTE_QKV_Layout qkv_layout, NVTE_QKV_Format o_format, - NVTE_QKV_Format do_format, NVTE_QKV_Layout dqkv_layout, - NVTE_QKV_Format qkv_scale_inv_format, NVTE_QKV_Format do_scale_inv_format, - NVTE_Bias_Type bias_type, NVTE_Mask_Type attn_mask_type, - NVTE_Softmax_Type softmax_type, int64_t window_size_left, - int64_t window_size_right, bool bottom_right_diagonal, bool deterministic, - bool cuda_graph, NVTETensor workspace, cudaStream_t stream); +void nvte_fused_attn_bwd(NVTEFusedAttnBwdParams params); + +/*! \brief Deprecated alias for nvte_fused_attn_bwd. + * + * \deprecated Use nvte_fused_attn_bwd instead. + */ +void nvte_fused_attn_bwd_v2(NVTEFusedAttnBwdParams params); /*! \brief Update the RNG state with the seed and calculated offset. * diff --git a/transformer_engine/common/include/transformer_engine/fused_router.h b/transformer_engine/common/include/transformer_engine/fused_router.h index b40977cd6cb..64ae877b54b 100644 --- a/transformer_engine/common/include/transformer_engine/fused_router.h +++ b/transformer_engine/common/include/transformer_engine/fused_router.h @@ -39,12 +39,7 @@ typedef enum { NVTE_QB_HISTOGRAM_FUSED_ATOMIC = 1, } NVTEQBHistogramMode; -/*! \brief Apply topk + softmax/sigmoid to the input tensor. Grouped topk is supported (deprecated). - * - * \deprecated This function has been deprecated in favor of - * nvte_fused_topk_with_score_function_forward_v2, which adds support - * for the NVTE_ROUTING_MAP_FORMAT_BITMAP_U8 routing_map layout. This - * entry point assumes NVTE_ROUTING_MAP_FORMAT_BYTEMAP. +/*! \brief Apply topk + softmax/sigmoid to the input tensor. Grouped topk is supported. * * \param[in] logits Logits from the gating GEMM. * \param[in] num_tokens Number of tokens. @@ -57,7 +52,11 @@ typedef enum { * \param[in] score_function Score function, 0: sigmoid, 1: softmax, 2: sqrtsoftplus. * \param[in] expert_bias Expert bias. (Used at the sigmoid/sqrtsoftplus cases) * \param[out] probs Output tensor for probabilities. - * \param[out] routing_map Output tensor for routing map (BYTEMAP layout). + * \param[out] routing_map Output tensor for routing map. Shape depends on + * routing_map_format (see NVTERoutingMapFormat). + * \param[in] routing_map_format NVTERoutingMapFormat value selecting the routing_map + * output layout. The caller is responsible for + * allocating routing_map with the matching shape. * \param[out] intermediate_output Output tensor for intermediate output. (Softmax/sigmoid output) * \param[in] stream CUDA stream used for the operation. */ @@ -65,28 +64,11 @@ void nvte_fused_topk_with_score_function_forward( const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, - NVTETensor intermediate_output, cudaStream_t stream); + NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, cudaStream_t stream); -/*! \brief Apply topk + softmax/sigmoid to the input tensor. Grouped topk is supported. +/*! \brief Deprecated alias for nvte_fused_topk_with_score_function_forward. * - * \param[in] logits Logits from the gating GEMM. - * \param[in] num_tokens Number of tokens. - * \param[in] num_experts Number of experts. - * \param[in] topk Topk value. - * \param[in] use_pre_softmax Whether to use softmax before topk. - * \param[in] num_groups Number of groups in grouped topk. - * \param[in] group_topk Grouped topk value. - * \param[in] scaling_factor Scaling factor. - * \param[in] score_function Score function, 0: sigmoid, 1: softmax, 2: sqrtsoftplus. - * \param[in] expert_bias Expert bias. (Used at the sigmoid/sqrtsoftplus cases) - * \param[out] probs Output tensor for probabilities. - * \param[out] routing_map Output tensor for routing map. Shape depends on - * routing_map_format (see NVTERoutingMapFormat). - * \param[in] routing_map_format NVTERoutingMapFormat value selecting the routing_map - * output layout. The caller is responsible for - * allocating routing_map with the matching shape. - * \param[out] intermediate_output Output tensor for intermediate output. (Softmax/sigmoid output) - * \param[in] stream CUDA stream used for the operation. + * \deprecated Use nvte_fused_topk_with_score_function_forward instead. */ void nvte_fused_topk_with_score_function_forward_v2( const NVTETensor logits, int num_tokens, int num_experts, int topk, bool use_pre_softmax, @@ -115,20 +97,18 @@ void nvte_fused_topk_with_score_function_forward_with_indices( * incorrect histogram; bin indices are clamped to [0, num_bins), so they never cause an * out-of-bounds access. */ -void nvte_fused_topk_with_score_function_forward_qb_v2( +void nvte_fused_topk_with_score_function_forward_qb( const NVTETensor logits, int num_tokens, int num_experts, int topk, float scaling_factor, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, NVTETensor cutoff, NVTETensor histogram, NVTETensor bin_bounds, NVTEQBHistogramMode histogram_mode, cudaStream_t stream); -/*! \brief Same as nvte_fused_topk_with_score_function_forward_qb_v2 (deprecated). +/*! \brief Deprecated alias for nvte_fused_topk_with_score_function_forward_qb. * - * \deprecated nvte_fused_topk_with_score_function_forward_qb_v2 no longer validates bin_bounds - * values, so this variant is identical to it and will be removed in a future - * release. + * \deprecated Use nvte_fused_topk_with_score_function_forward_qb instead. */ -void nvte_fused_topk_with_score_function_forward_qb_v2_unchecked( +void nvte_fused_topk_with_score_function_forward_qb_v2( const NVTETensor logits, int num_tokens, int num_experts, int topk, float scaling_factor, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, NVTETensor cutoff, @@ -137,7 +117,7 @@ void nvte_fused_topk_with_score_function_forward_qb_v2_unchecked( /*! \brief Kimi K3 Quantile Balancing fused-router forward with dense Top-k indices. * - * bin_bounds follows the same contract as in nvte_fused_topk_with_score_function_forward_qb_v2. + * bin_bounds follows the same contract as in nvte_fused_topk_with_score_function_forward_qb. */ void nvte_fused_topk_with_score_function_forward_qb_with_indices( const NVTETensor logits, int num_tokens, int num_experts, int topk, float scaling_factor, @@ -145,42 +125,18 @@ void nvte_fused_topk_with_score_function_forward_qb_with_indices( NVTETensor intermediate_output, NVTETensor cutoff, NVTETensor histogram, NVTETensor bin_bounds, NVTEQBHistogramMode histogram_mode, cudaStream_t stream); -/*! \brief Same as nvte_fused_topk_with_score_function_forward_qb_with_indices (deprecated). - * - * \deprecated nvte_fused_topk_with_score_function_forward_qb_with_indices no longer validates - * bin_bounds values, so this variant is identical to it and will be removed in a - * future release. - */ -void nvte_fused_topk_with_score_function_forward_qb_with_indices_unchecked( - const NVTETensor logits, int num_tokens, int num_experts, int topk, float scaling_factor, - const NVTETensor expert_bias, NVTETensor probs, NVTETensor topk_indices, - NVTETensor intermediate_output, NVTETensor cutoff, NVTETensor histogram, NVTETensor bin_bounds, - NVTEQBHistogramMode histogram_mode, cudaStream_t stream); - /*! \brief Accumulate a QB histogram from raw sigmoid scores and Top-(k+1) cutoffs. * - * bin_bounds follows the same contract as in nvte_fused_topk_with_score_function_forward_qb_v2. + * bin_bounds follows the same contract as in nvte_fused_topk_with_score_function_forward_qb. */ void nvte_qb_histogram_accumulate(const NVTETensor raw_scores, const NVTETensor cutoff, const NVTETensor bin_bounds, NVTETensor histogram, cudaStream_t stream); -/*! \brief Same as nvte_qb_histogram_accumulate (deprecated). - * - * \deprecated nvte_qb_histogram_accumulate no longer validates bin_bounds values, so this variant - * is identical to it and will be removed in a future release. - */ -void nvte_qb_histogram_accumulate_unchecked(const NVTETensor raw_scores, const NVTETensor cutoff, - const NVTETensor bin_bounds, NVTETensor histogram, - cudaStream_t stream); - -/*! \brief Backward pass for fused topk + softmax/sigmoid (deprecated). - * - * \deprecated This function has been deprecated in favor of - * nvte_fused_topk_with_score_function_backward_v2. This entry point - * assumes NVTE_ROUTING_MAP_FORMAT_BYTEMAP. +/*! \brief Backward pass for fused topk + softmax/sigmoid. * - * \param[in] routing_map Routing map (BYTEMAP layout). + * \param[in] routing_map Routing map (same layout as produced by forward). + * \param[in] routing_map_format NVTERoutingMapFormat value matching the layout of routing_map. * \param[in] intermediate_output Intermediate output from the forward pass. (Softmax/sigmoid output) * \param[in] grad_probs Gradient of probs. * \param[in] num_tokens Number of tokens. @@ -193,26 +149,16 @@ void nvte_qb_histogram_accumulate_unchecked(const NVTETensor raw_scores, const N * \param[in] stream CUDA stream used for the operation. */ void nvte_fused_topk_with_score_function_backward(const NVTETensor routing_map, + NVTERoutingMapFormat routing_map_format, const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, NVTETensor grad_logits, cudaStream_t stream); -/*! \brief Backward pass for fused topk + softmax/sigmoid. +/*! \brief Deprecated alias for nvte_fused_topk_with_score_function_backward. * - * \param[in] routing_map Routing map (same layout as produced by forward). - * \param[in] routing_map_format NVTERoutingMapFormat value matching the layout of routing_map. - * \param[in] intermediate_output Intermediate output from the forward pass. (Softmax/sigmoid output) - * \param[in] grad_probs Gradient of probs. - * \param[in] num_tokens Number of tokens. - * \param[in] num_experts Number of experts. - * \param[in] topk Topk value. - * \param[in] use_pre_softmax Whether to use softmax before topk. - * \param[in] scaling_factor Scaling factor. - * \param[in] score_function Score function, 0: sigmoid, 1: softmax, 2: sqrtsoftplus. - * \param[out] grad_logits Gradient of logits. - * \param[in] stream CUDA stream used for the operation. + * \deprecated Use nvte_fused_topk_with_score_function_backward instead. */ void nvte_fused_topk_with_score_function_backward_v2(const NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, @@ -308,11 +254,7 @@ void nvte_fused_topk_with_aux_loss_scores_backward( const NVTETensor grad_aux_scores, int num_tokens, int num_experts, int topk, float scaling_factor, int score_function, NVTETensor grad_logits, cudaStream_t stream); -/*! \brief Forward pass for computing scores/routing map for auxiliary loss (deprecated). - * - * \deprecated This function has been deprecated in favor of - * nvte_fused_score_for_moe_aux_loss_forward_v2. This entry point - * assumes NVTE_ROUTING_MAP_FORMAT_BYTEMAP. +/*! \brief Forward pass for computing scores/routing map for auxiliary loss. * * \param[in] logits Logits from the gating GEMM. * \param[in] num_tokens Number of tokens. @@ -320,30 +262,23 @@ void nvte_fused_topk_with_aux_loss_scores_backward( * \param[in] topk Topk value. * \param[in] score_function Score function, 0: sigmoid, 1: softmax, 2: sqrtsoftplus. * \param[out] scores Output tensor for scores. - * \param[out] routing_map Output tensor for routing map (BYTEMAP layout). + * \param[out] routing_map Output tensor for routing map. Shape depends on + * routing_map_format (see NVTERoutingMapFormat). + * \param[in] routing_map_format NVTERoutingMapFormat value selecting the routing_map + * output layout. * \param[in] intermediate_output Intermediate output from the forward pass. (Softmax/sigmoid output) * \param[in] stream CUDA stream used for the operation. */ void nvte_fused_score_for_moe_aux_loss_forward(const NVTETensor logits, int num_tokens, int num_experts, int topk, int score_function, NVTETensor scores, NVTETensor routing_map, + NVTERoutingMapFormat routing_map_format, const NVTETensor intermediate_output, cudaStream_t stream); -/*! \brief Forward pass for computing scores/routing map for auxiliary loss. +/*! \brief Deprecated alias for nvte_fused_score_for_moe_aux_loss_forward. * - * \param[in] logits Logits from the gating GEMM. - * \param[in] num_tokens Number of tokens. - * \param[in] num_experts Number of experts. - * \param[in] topk Topk value. - * \param[in] score_function Score function, 0: sigmoid, 1: softmax, 2: sqrtsoftplus. - * \param[out] scores Output tensor for scores. - * \param[out] routing_map Output tensor for routing map. Shape depends on - * routing_map_format (see NVTERoutingMapFormat). - * \param[in] routing_map_format NVTERoutingMapFormat value selecting the routing_map - * output layout. - * \param[in] intermediate_output Intermediate output from the forward pass. (Softmax/sigmoid output) - * \param[in] stream CUDA stream used for the operation. + * \deprecated Use nvte_fused_score_for_moe_aux_loss_forward instead. */ void nvte_fused_score_for_moe_aux_loss_forward_v2(const NVTETensor logits, int num_tokens, int num_experts, int topk, int score_function, @@ -368,10 +303,20 @@ void nvte_fused_score_for_moe_aux_loss_backward(const NVTETensor intermediate_ou int num_experts, int topk, int score_function, NVTETensor grad_logits, cudaStream_t stream); -/*! \brief Forward pass for auxiliary loss. Host-int total_num_tokens path: - * the coefficient is folded on the host and passed as a kernel argument. - * This legacy entrypoint uses an atomic reduction and is not deterministic. - * Prefer :c:func:`nvte_fused_moe_aux_loss_forward_v2` for new callers. +/*! \brief Forward pass for auxiliary loss, with a host token count. + * + * Each CTA writes an FP32 partial sum into workspace, then a second kernel + * reduces these values in a fixed order. Repeated execution with identical + * inputs on the same hardware and software is bitwise reproducible; equality + * to other reduction implementations is not guaranteed. + * + * To query workspace requirements, pass a valid workspace tensor whose data + * pointer is nullptr. The call populates its shape and dtype and returns without + * launching kernels or accessing other tensors, which may be nullptr during + * this query. The reported capacity covers all input shapes. Allocate storage + * with the reported metadata, then call again to execute the operation. + * Workspace contents are overwritten and need no initialization. Storage must + * remain valid through the queued forward kernels, but is not saved for backward. * * \param[in] probs Probabilities from the forward pass. * \param[in] tokens_per_expert Number of tokens per expert. @@ -383,45 +328,18 @@ void nvte_fused_score_for_moe_aux_loss_backward(const NVTETensor intermediate_ou * \param[in] coeff Coefficient. * \param[out] aux_loss Output GPU scalar for auxiliary loss. * \param[out] Const_buf Two FP32 elements: backward coefficient and forward sum. + * \param[in,out] workspace Temporary buffer, or an empty tensor to query its metadata. * \param[in] stream CUDA stream used for the operation. */ void nvte_fused_moe_aux_loss_forward(const NVTETensor probs, const NVTETensor tokens_per_expert, int total_num_tokens, int num_experts, int num_rows, int num_cols, int topk, float coeff, NVTETensor aux_loss, - NVTETensor Const_buf, cudaStream_t stream); + NVTETensor Const_buf, NVTETensor workspace, + cudaStream_t stream); -/*! \brief Forward pass for auxiliary loss. Device-tensor total_num_tokens path: - * the coefficient is computed on device from a 0-dim int64 GPU tensor so its - * value stays dynamic across CUDA Graph replays. This legacy entrypoint uses - * an atomic reduction. Prefer :c:func:`nvte_fused_moe_aux_loss_forward_graph_safe_v2`. +/*! \brief Deprecated alias for nvte_fused_moe_aux_loss_forward. * - * \param[in] total_num_tokens 0-dim int64 GPU tensor with the total token count. - * Other parameters as in :c:func:`nvte_fused_moe_aux_loss_forward`. - */ -void nvte_fused_moe_aux_loss_forward_graph_safe(const NVTETensor probs, - const NVTETensor tokens_per_expert, - const NVTETensor total_num_tokens, int num_experts, - int num_rows, int num_cols, int topk, float coeff, - NVTETensor aux_loss, NVTETensor Const_buf, - cudaStream_t stream); - -/*! \brief Deterministic forward pass for auxiliary loss, with a host token count. - * - * Each CTA writes an FP32 partial sum into workspace, then a second kernel - * reduces these values in a fixed order. Repeated execution with identical - * inputs on the same hardware and software is bitwise reproducible; equality - * to other reduction implementations is not guaranteed. - * - * To query workspace requirements, pass a valid workspace tensor whose data - * pointer is nullptr. The call populates its shape and dtype and returns without - * launching kernels or accessing other tensors, which may be nullptr during - * this query. The reported capacity covers all input shapes. Allocate storage - * with the reported metadata, then call again to execute the operation. - * Workspace contents are overwritten and need no initialization. Storage must - * remain valid through the queued forward kernels, but is not saved for backward. - * - * \param[in,out] workspace Temporary buffer, or an empty tensor to query its metadata. - * Other parameters as in :c:func:`nvte_fused_moe_aux_loss_forward`. + * \deprecated Use nvte_fused_moe_aux_loss_forward instead. */ void nvte_fused_moe_aux_loss_forward_v2(const NVTETensor probs, const NVTETensor tokens_per_expert, int total_num_tokens, int num_experts, int num_rows, @@ -429,13 +347,25 @@ void nvte_fused_moe_aux_loss_forward_v2(const NVTETensor probs, const NVTETensor NVTETensor Const_buf, NVTETensor workspace, cudaStream_t stream); -/*! \brief Deterministic forward with a device-tensor token count. +/*! \brief Forward pass for auxiliary loss, with a device-tensor token count. * * total_num_tokens is a 0-dim int64 GPU tensor and may change between CUDA * Graph replays. Its value is never read on the host or used to size workspace. * Both the loss and saved backward coefficient are refreshed on each replay. - * Workspace requirements and lifetime follow :c:func:`nvte_fused_moe_aux_loss_forward_v2`. - * Other parameters as in :c:func:`nvte_fused_moe_aux_loss_forward_graph_safe`. + * The reduction and workspace requirements follow + * :c:func:`nvte_fused_moe_aux_loss_forward`. + * + * \param[in] total_num_tokens 0-dim int64 GPU tensor with the total token count. + * Other parameters as in :c:func:`nvte_fused_moe_aux_loss_forward`. + */ +void nvte_fused_moe_aux_loss_forward_graph_safe( + const NVTETensor probs, const NVTETensor tokens_per_expert, const NVTETensor total_num_tokens, + int num_experts, int num_rows, int num_cols, int topk, float coeff, NVTETensor aux_loss, + NVTETensor Const_buf, NVTETensor workspace, cudaStream_t stream); + +/*! \brief Deprecated alias for nvte_fused_moe_aux_loss_forward_graph_safe. + * + * \deprecated Use nvte_fused_moe_aux_loss_forward_graph_safe instead. */ void nvte_fused_moe_aux_loss_forward_graph_safe_v2( const NVTETensor probs, const NVTETensor tokens_per_expert, const NVTETensor total_num_tokens, diff --git a/transformer_engine/common/include/transformer_engine/gemm.h b/transformer_engine/common/include/transformer_engine/gemm.h index 340e1b823be..36a5003cd74 100644 --- a/transformer_engine/common/include/transformer_engine/gemm.h +++ b/transformer_engine/common/include/transformer_engine/gemm.h @@ -162,35 +162,6 @@ void nvte_set_grouped_matmul_config_attribute(NVTEGroupedMatmulConfig config, /*! \brief Destroy a grouped matrix multiplication configuration. */ void nvte_destroy_grouped_matmul_config(NVTEGroupedMatmulConfig config); -/*! \brief Compute matrix multiplication of 2 matrices, potentially fused with other operations (deprecated). - * - * This has been deprecated in favor of nvte_cublas_gemm_v2. - * - * Computes: - * - `D = AB` if both `bias` and `pre_gelu_out` are empty tensors - * - `D = AB + bias` if `pre_gelu_out` is empty and `bias` is not empty - * - `D = GELU(AB + bias)` if both `bias` and `pre_gelu_out` are not empty tensors - * - * \param[in] A The A matrix. - * \param[in] B The B matrix. - * \param[in,out] D Output matrix. - * \param[in] bias Bias tensor. - * \param[in,out] pre_gelu_out Output matrix before GELU activation. - * \param[in] transa Whether A matrix is transposed. - * \param[in] transb Whether B matrix is transposed. - * \param[in] grad Whether this operation is part of the - * gradient computation. - * \param[out] workspace Workspace tensor. - * \param[in] accumulate Whether to accumulate the result into the D matrix. - * \param[in] use_split_accumulator Whether to use split accumulator in the FP8 GEMM. - * \param[in] math_sm_count Number of GPU SMs to use (default=0: use cuBLAS heuristics) - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_cublas_gemm(const NVTETensor A, const NVTETensor B, NVTETensor D, const NVTETensor bias, - NVTETensor pre_gelu_out, bool transa, bool transb, bool grad, - NVTETensor workspace, bool accumulate, bool use_split_accumulator, - int math_sm_count, cudaStream_t stream); - /*! \brief Compute matrix multiplication of 2 matrices, potentially fused with other operations. * * Computes: @@ -214,6 +185,14 @@ void nvte_cublas_gemm(const NVTETensor A, const NVTETensor B, NVTETensor D, cons * \param[in] config Additional configuration. * \param[in] stream CUDA stream used for the operation. */ +void nvte_cublas_gemm(bool transa, bool transb, const float *alpha, const NVTETensor A, + const NVTETensor B, const float *beta, const NVTETensor C, NVTETensor D, + NVTETensor workspace, NVTEMatmulConfig config, cudaStream_t stream); + +/*! \brief Deprecated alias for nvte_cublas_gemm. + * + * \deprecated Use nvte_cublas_gemm instead. + */ void nvte_cublas_gemm_v2(bool transa, bool transb, const float *alpha, const NVTETensor A, const NVTETensor B, const float *beta, const NVTETensor C, NVTETensor D, NVTETensor workspace, NVTEMatmulConfig config, cudaStream_t stream); @@ -291,38 +270,6 @@ void nvte_cublas_gemm_strided_batched_mxfp8(bool transa, bool transb, const floa int batch_dim_d, NVTETensor workspace, NVTEMatmulConfig config, cudaStream_t stream); -/*! \brief Compute matrix multiplication of 2 matrices, potentially fused with other operations, - * allowing for using a scaling factor for the GEMM result and the accumulation input (deprecated) - * - * This has been deprecated in favor of nvte_cublas_gemm_v2. - * - * Computes: - * - `D = alpha*AB` if both `bias` and `pre_gelu_out` are empty tensors - * - `D = alpha*AB + bias` if `pre_gelu_out` is empty and `bias` is not empty - * - `D = GELU(alpha*AB + bias)` if both `bias` and `pre_gelu_out` are not empty tensors - * - * \param[in] A The A matrix. - * \param[in] B The B matrix. - * \param[in,out] D Output matrix. - * \param[in] bias Bias tensor. - * \param[in,out] pre_gelu_out Output matrix before GELU activation. - * \param[in] transa Whether A matrix is transposed. - * \param[in] transb Whether B matrix is transposed. - * \param[in] grad Whether this operation is part of the - * gradient computation. - * \param[out] workspace Workspace tensor. - * \param[in] alpha Scaling factor applied to the result of the GEMM - * \param[in] beta Scaling factor applied to original value of D when - * accumulating into it. beta=0 means no accumulation. - * \param[in] use_split_accumulator Whether to use split accumulator in the FP8 GEMM. - * \param[in] math_sm_count Number of GPU SMs to use (default=0: use cuBLAS heuristics) - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_cublas_gemm_scaled(const NVTETensor A, const NVTETensor B, NVTETensor D, - const NVTETensor bias, NVTETensor pre_gelu_out, bool transa, - bool transb, bool grad, NVTETensor workspace, float alpha, float beta, - bool use_split_accumulator, int math_sm_count, cudaStream_t stream); - /*! \brief Compute matrix multiplication of 2 matrices with chunking and atomic counters. * * \warning Cublas atomic gemm uses a beta API and is not tested for all use cases. diff --git a/transformer_engine/common/include/transformer_engine/recipe.h b/transformer_engine/common/include/transformer_engine/recipe.h index e06be412aac..3fb6dcde333 100644 --- a/transformer_engine/common/include/transformer_engine/recipe.h +++ b/transformer_engine/common/include/transformer_engine/recipe.h @@ -369,7 +369,6 @@ void nvte_nvfp4_2d_compute_partial_amax(const NVTETensor inp, NVTETensor amax, s * Quantizes elements in [start_offset, start_offset + len) of the flattened tensor * using precomputed per-tile scales. Each 16x16 tile uses its own scale factor. * Used in distributed settings where each rank casts its owned shard. - * Uses E4M3 scale dtype. Use nvte_nvfp4_2d_partial_cast_v2 to specify another scale type. * * \param[in] inp Input tensor (partial shard, high-precision). * \param[out] out Output NVFP4 packed tensor (2 values per byte). @@ -381,29 +380,17 @@ void nvte_nvfp4_2d_compute_partial_amax(const NVTETensor inp, NVTETensor amax, s * \param[in] scale_stride_w Stride for scale in tile-col dimension. * \param[in] start_offset Starting element offset in the flattened tensor. * \param[in] block_len Tile dimension (must be 16 for NVFP4 2D). + * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). * \param[in] stream CUDA stream used for the operation. */ void nvte_nvfp4_2d_partial_cast(const NVTETensor inp, NVTETensor out, const NVTETensor scale, const NVTETensor global_scale, size_t h, size_t w, size_t scale_stride_h, size_t scale_stride_w, size_t start_offset, - size_t block_len, cudaStream_t stream); + size_t block_len, NVTEDType scale_dtype, cudaStream_t stream); -/*! \brief Cast a partial shard of a tensor to NVFP4 using 2D tile-based quantization. +/*! \brief Deprecated alias for nvte_nvfp4_2d_partial_cast. * - * This variant allows the NVFP4 scale storage type to be specified explicitly. - * - * \param[in] inp Input tensor (partial shard, high-precision). - * \param[out] out Output NVFP4 packed tensor (2 values per byte). - * \param[in] scale Per-tile scale factors [tile_rows, tile_cols], float32. - * \param[in] global_scale Global scale factor [1], float32. - * \param[in] h Number of rows in the full 2D tensor. - * \param[in] w Number of columns in the full 2D tensor. - * \param[in] scale_stride_h Stride for scale in tile-row dimension. - * \param[in] scale_stride_w Stride for scale in tile-col dimension. - * \param[in] start_offset Starting element offset in the flattened tensor. - * \param[in] block_len Tile dimension (must be 16 for NVFP4 2D). - * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). - * \param[in] stream CUDA stream used for the operation. + * \deprecated Use nvte_nvfp4_2d_partial_cast instead. */ void nvte_nvfp4_2d_partial_cast_v2(const NVTETensor inp, NVTETensor out, const NVTETensor scale, const NVTETensor global_scale, size_t h, size_t w, @@ -411,7 +398,7 @@ void nvte_nvfp4_2d_partial_cast_v2(const NVTETensor inp, NVTETensor out, const N size_t start_offset, size_t block_len, NVTEDType scale_dtype, cudaStream_t stream); -/*! \brief Expand tile-level scales to row-level scales and convert to E4M3 scale type. +/*! \brief Expand tile-level scales to row-level scales and convert to an FP8 scale type. * * Each tile row's scale is repeated block_len times in the output. * @@ -421,63 +408,54 @@ void nvte_nvfp4_2d_partial_cast_v2(const NVTETensor inp, NVTETensor out, const N * \param[in] tile_cols Number of tile columns. * \param[in] rows_padded Padded row count in output. * \param[in] block_len Block length (typically 16 for NVFP4). + * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). * \param[in] stream CUDA stream. */ void nvte_nvfp4_expand_scale_to_fp8(const NVTETensor input, NVTETensor output, size_t tile_rows, size_t tile_cols, size_t rows_padded, size_t block_len, - cudaStream_t stream); + NVTEDType scale_dtype, cudaStream_t stream); -/*! \brief Expand tile-level scales to row-level scales and convert to the selected FP8 scale type. +/*! \brief Deprecated alias for nvte_nvfp4_expand_scale_to_fp8. * - * \param[in] input Input tensor with tile scales [tile_rows, tile_cols], float32. - * \param[out] output Output tensor with expanded scales [rows_padded, tile_cols], uint8. - * \param[in] tile_rows Number of tile rows. - * \param[in] tile_cols Number of tile columns. - * \param[in] rows_padded Padded row count in output. - * \param[in] block_len Block length (typically 16 for NVFP4). - * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). - * \param[in] stream CUDA stream. + * \deprecated Use nvte_nvfp4_expand_scale_to_fp8 instead. */ void nvte_nvfp4_expand_scale_to_fp8_v2(const NVTETensor input, NVTETensor output, size_t tile_rows, size_t tile_cols, size_t rows_padded, size_t block_len, NVTEDType scale_dtype, cudaStream_t stream); -/*! \brief Compute per-block E4M3 decode scale from block amax and global amax. +/*! \brief Compute per-block decode scale from block amax and global amax. * * Computes: * global_scale = (scale_max * fp4_max) / global_amax * per_block_decode_scale = block_amax / fp4_max * global_scale + * where scale_max is the maximum value of scale_dtype. * * This matches the CUDA device function compute_decoding_scaling_factor() in core_nvfp4.cuh. * * \param[in] block_amax Input block amax tensor [tile_rows, tile_cols], float32. * \param[out] scale Output scale tensor [tile_rows, tile_cols], float32. * \param[in] global_amax Global amax tensor (single element), float32. Avoids D2H transfer. + * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). * \param[in] stream CUDA stream. */ void nvte_nvfp4_compute_per_block_scale(const NVTETensor block_amax, NVTETensor scale, - const NVTETensor global_amax, cudaStream_t stream); + const NVTETensor global_amax, NVTEDType scale_dtype, + cudaStream_t stream); -/*! \brief Compute per-block decode scale from block amax and global amax. - * - * This variant allows the NVFP4 scale storage type to be specified explicitly. +/*! \brief Deprecated alias for nvte_nvfp4_compute_per_block_scale. * - * \param[in] block_amax Input block amax tensor [tile_rows, tile_cols], float32. - * \param[out] scale Output scale tensor [tile_rows, tile_cols], float32. - * \param[in] global_amax Global amax tensor (single element), float32. Avoids D2H transfer. - * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). - * \param[in] stream CUDA stream. + * \deprecated Use nvte_nvfp4_compute_per_block_scale instead. */ void nvte_nvfp4_compute_per_block_scale_v2(const NVTETensor block_amax, NVTETensor scale, const NVTETensor global_amax, NVTEDType scale_dtype, cudaStream_t stream); -/*! \brief Fused kernel for NVFP4 E4M3 scale computation. +/*! \brief Fused kernel for NVFP4 scale computation. * * Fuses three operations into one kernel: * 1. Compute per-block decode scales from block amax and global amax * 2. Copy global amax to target tensor - * 3. Expand tile-level scales to row-level and convert to E4M3 scale type + * 3. Expand tile-level scales to row-level and convert to scale_dtype * * Saves 2 kernel launches per parameter. * @@ -490,28 +468,18 @@ void nvte_nvfp4_compute_per_block_scale_v2(const NVTETensor block_amax, NVTETens * \param[in] tile_cols Number of tile columns. * \param[in] rows_padded Total padded rows in output. * \param[in] block_len Block length (16 for NVFP4). + * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). * \param[in] stream CUDA stream. */ void nvte_nvfp4_fused_scale(const NVTETensor block_amax, const NVTETensor global_amax, NVTETensor per_block_scale, NVTETensor target_scale, NVTETensor target_amax, size_t tile_rows, size_t tile_cols, - size_t rows_padded, size_t block_len, cudaStream_t stream); + size_t rows_padded, size_t block_len, NVTEDType scale_dtype, + cudaStream_t stream); -/*! \brief Fused kernel for NVFP4 scale computation. - * - * This variant allows the NVFP4 scale storage type to be specified explicitly. +/*! \brief Deprecated alias for nvte_nvfp4_fused_scale. * - * \param[in] block_amax Input block amax tensor [tile_rows, tile_cols], float32. - * \param[in] global_amax Global amax tensor [1], float32. - * \param[out] per_block_scale Output per-block scale [tile_rows, tile_cols], float32 (for partial_cast). - * \param[out] target_scale Output scale tensor [rows_padded, tile_cols], uint8. - * \param[out] target_amax Output amax tensor [1], float32 (copy of global_amax). - * \param[in] tile_rows Number of tile rows. - * \param[in] tile_cols Number of tile columns. - * \param[in] rows_padded Total padded rows in output. - * \param[in] block_len Block length (16 for NVFP4). - * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). - * \param[in] stream CUDA stream. + * \deprecated Use nvte_nvfp4_fused_scale instead. */ void nvte_nvfp4_fused_scale_v2(const NVTETensor block_amax, const NVTETensor global_amax, NVTETensor per_block_scale, NVTETensor target_scale, @@ -521,24 +489,20 @@ void nvte_nvfp4_fused_scale_v2(const NVTETensor block_amax, const NVTETensor glo /*! \brief Compute global encode scale from global amax. * - * Computes: global_scale = (scale_max * fp4_max) / global_amax, using E4M3 scale_max. - * If global_amax <= 0, returns 1.0. + * Computes: global_scale = (scale_max * fp4_max) / global_amax, where scale_max is the + * maximum value of scale_dtype. If global_amax <= 0, returns 1.0. * * \param[in] global_amax Input global amax tensor [num_params], float32. * \param[out] global_scale Output global scale tensor [num_params], float32. + * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). * \param[in] stream CUDA stream. */ void nvte_nvfp4_compute_global_scale(const NVTETensor global_amax, NVTETensor global_scale, - cudaStream_t stream); + NVTEDType scale_dtype, cudaStream_t stream); -/*! \brief Compute global encode scale from global amax. - * - * This variant allows the NVFP4 scale storage type to be specified explicitly. +/*! \brief Deprecated alias for nvte_nvfp4_compute_global_scale. * - * \param[in] global_amax Input global amax tensor [num_params], float32. - * \param[out] global_scale Output global scale tensor [num_params], float32. - * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). - * \param[in] stream CUDA stream. + * \deprecated Use nvte_nvfp4_compute_global_scale instead. */ void nvte_nvfp4_compute_global_scale_v2(const NVTETensor global_amax, NVTETensor global_scale, NVTEDType scale_dtype, cudaStream_t stream); diff --git a/transformer_engine/common/include/transformer_engine/transformer_engine.h b/transformer_engine/common/include/transformer_engine/transformer_engine.h index bf0f2fdb9ba..46aa5f6edf4 100644 --- a/transformer_engine/common/include/transformer_engine/transformer_engine.h +++ b/transformer_engine/common/include/transformer_engine/transformer_engine.h @@ -318,26 +318,6 @@ NVTEShape nvte_tensor_scale_inv_shape(const NVTETensor tensor); */ void nvte_zero_tensor(const NVTETensor tensor, cudaStream_t stream); -/*! \brief Set a parameter of the tensor. - * - * \warning Deprecated in favor of nvte_set_tensor_param_v2. - * - * \param[in,out] tensor Tensor. - * \param[in] param_name The parameter to be set. - * \param[in] param The value to be set. - */ -void nvte_set_tensor_param(NVTETensor *tensor, NVTETensorParam param_name, - const NVTEBasicTensor *param); - -/*! \brief Get a value of the parameter of the tensor. - * - * \warning Deprecated in favor of nvte_set_tensor_param_v2. - * - * \param[in] tensor Tensor. - * \param[in] param_name The parameter to be set. - */ -NVTEBasicTensor nvte_get_tensor_param(const NVTETensor tensor, NVTETensorParam param_name); - /*! \brief Set a tensor parameter. * * \param[in,out] tensor Tensor. @@ -345,6 +325,13 @@ NVTEBasicTensor nvte_get_tensor_param(const NVTETensor tensor, NVTETensorParam p * \param[in] buf Memory address to read parameter value. * \param[in] size_in_bytes Size of buf. */ +void nvte_set_tensor_param(NVTETensor tensor, NVTETensorParam param, const void *buf, + size_t size_in_bytes); + +/*! \brief Deprecated alias for nvte_set_tensor_param. + * + * \deprecated Use nvte_set_tensor_param instead. + */ void nvte_set_tensor_param_v2(NVTETensor tensor, NVTETensorParam param, const void *buf, size_t size_in_bytes); @@ -359,6 +346,13 @@ void nvte_set_tensor_param_v2(NVTETensor tensor, NVTETensorParam param, const vo * buf. If buf is NULL, then the number of * bytes that would have been written. */ +void nvte_get_tensor_param(const NVTETensor tensor, NVTETensorParam param, void *buf, + size_t size_in_bytes, size_t *size_written); + +/*! \brief Deprecated alias for nvte_get_tensor_param. + * + * \deprecated Use nvte_get_tensor_param instead. + */ void nvte_get_tensor_param_v2(const NVTETensor tensor, NVTETensorParam param, void *buf, size_t size_in_bytes, size_t *size_written); @@ -535,7 +529,13 @@ void nvte_splits_to_offsets_2d(const NVTETensor first_dims, const NVTETensor las * output multiplies the prefix-sum by a stride. Inputs and outputs * can be any combination of int32 and int64 tensors. * + * Every split size must be a multiple of split_alignment. This is + * asserted on the device without synchronizing the host, so the + * validation remains active during CUDA graph replay. + * * \param[in] split_sizes Device int32/int64 split sizes with shape [N]. + * \param[in] split_alignment Positive required divisor of every split size. + * Pass 1 to skip the alignment check. * \param[out] outputs Array of int32/int64 1D output tensors, one per scan. * \param[in] strides Per-output scale factor. Length num_outputs. * \param[in] include_leading_zero Per-output flag: 0 if outputs[i] has length N @@ -544,17 +544,14 @@ void nvte_splits_to_offsets_2d(const NVTETensor first_dims, const NVTETensor las * \param[in] num_outputs Number of output tensors. * \param[in] stream CUDA stream to use for the operation. */ -void nvte_splits_to_offsets_multi(NVTETensor split_sizes, NVTETensor *outputs, - const int64_t *strides, const int *include_leading_zero, - size_t num_outputs, cudaStream_t stream); +void nvte_splits_to_offsets_multi(NVTETensor split_sizes, size_t split_alignment, + NVTETensor *outputs, const int64_t *strides, + const int *include_leading_zero, size_t num_outputs, + cudaStream_t stream); -/*! \brief Compute multiple scaled offsets and assert row split alignment on the device. - * - * This uses the same prefix-sum kernel as nvte_splits_to_offsets_multi and does not synchronize - * the host, so the validation remains active during CUDA graph replay. +/*! \brief Deprecated alias for nvte_splits_to_offsets_multi. * - * \param[in] split_alignment Positive required divisor of every split size. - * \see nvte_splits_to_offsets_multi for the remaining parameters. + * \deprecated Use nvte_splits_to_offsets_multi instead. */ void nvte_splits_to_offsets_multi_v2(NVTETensor split_sizes, size_t split_alignment, NVTETensor *outputs, const int64_t *strides, @@ -762,20 +759,20 @@ class TensorWrapper { const NVTEScalingMode scaling_mode = NVTE_DELAYED_TENSOR_SCALING) { tensor_ = nvte_create_tensor(scaling_mode); NVTEBasicTensor data = {dptr, static_cast(dtype), shape}; - nvte_set_tensor_param_v2(tensor_, kNVTERowwiseData, &data, sizeof(data)); + nvte_set_tensor_param(tensor_, kNVTERowwiseData, &data, sizeof(data)); NVTEBasicTensor amax = {amax_dptr, kNVTEFloat32, amax_dptr != nullptr ? defaultShape : emptyShape}; - nvte_set_tensor_param_v2(tensor_, kNVTEAmax, &amax, sizeof(amax)); + nvte_set_tensor_param(tensor_, kNVTEAmax, &amax, sizeof(amax)); NVTEBasicTensor scale = {scale_dptr, kNVTEFloat32, scale_dptr != nullptr ? defaultShape : emptyShape}; - nvte_set_tensor_param_v2(tensor_, kNVTEScale, &scale, sizeof(scale)); + nvte_set_tensor_param(tensor_, kNVTEScale, &scale, sizeof(scale)); if (scale_inv_dptr == nullptr && scale_inv_shape.ndim == defaultShape.ndim && scale_inv_shape.ndim == 1 && scale_inv_shape.data[0] == defaultShape.data[0]) { // Scale-inv pointer has not been provided and shape matches default scale_inv_shape = emptyShape; } NVTEBasicTensor scale_inv = {scale_inv_dptr, kNVTEFloat32, scale_inv_shape}; - nvte_set_tensor_param_v2(tensor_, kNVTERowwiseScaleInv, &scale_inv, sizeof(scale_inv)); + nvte_set_tensor_param(tensor_, kNVTERowwiseScaleInv, &scale_inv, sizeof(scale_inv)); } /*! \brief Constructs new TensorWrapper. @@ -846,7 +843,7 @@ class TensorWrapper { const ShapeType &shape) noexcept { NVTEShape nvte_shape = this->convertShape(shape); NVTEBasicTensor data = {dptr, static_cast(type), nvte_shape}; - nvte_set_tensor_param_v2(tensor_, param, &data, sizeof(data)); + nvte_set_tensor_param(tensor_, param, &data, sizeof(data)); return *this; } @@ -887,24 +884,24 @@ class TensorWrapper { void set_with_gemm_swizzled_scales(bool with_gemm_swizzled_scales) { const auto val = static_cast(with_gemm_swizzled_scales); - nvte_set_tensor_param_v2(tensor_, kNVTEWithGEMMSwizzledScales, &val, sizeof(val)); + nvte_set_tensor_param(tensor_, kNVTEWithGEMMSwizzledScales, &val, sizeof(val)); } void set_row_scaled_nvfp4(bool row_scaled_nvfp4) { const auto val = static_cast(row_scaled_nvfp4); - nvte_set_tensor_param_v2(tensor_, kNVTERowScaledNVFP4, &val, sizeof(val)); + nvte_set_tensor_param(tensor_, kNVTERowScaledNVFP4, &val, sizeof(val)); } void set_nvfp4_e4m3_max(int nvfp4_e4m3_max) { const auto val = nvfp4_e4m3_max; - nvte_set_tensor_param_v2(tensor_, kNVTENVFP4E4M3Max, &val, sizeof(val)); + nvte_set_tensor_param(tensor_, kNVTENVFP4E4M3Max, &val, sizeof(val)); } // Parameter getters NVTEBasicTensor get_parameter(const NVTETensorParam param) const noexcept { NVTEBasicTensor ret; - nvte_get_tensor_param_v2(tensor_, param, &ret, sizeof(ret), nullptr); + nvte_get_tensor_param(tensor_, param, &ret, sizeof(ret), nullptr); return ret; } @@ -932,19 +929,19 @@ class TensorWrapper { bool get_with_gemm_swizzled_scales() const { uint8_t val = 0; - nvte_get_tensor_param_v2(tensor_, kNVTEWithGEMMSwizzledScales, &val, sizeof(val), nullptr); + nvte_get_tensor_param(tensor_, kNVTEWithGEMMSwizzledScales, &val, sizeof(val), nullptr); return static_cast(val); } bool get_row_scaled_nvfp4() const { uint8_t val = 0; - nvte_get_tensor_param_v2(tensor_, kNVTERowScaledNVFP4, &val, sizeof(val), nullptr); + nvte_get_tensor_param(tensor_, kNVTERowScaledNVFP4, &val, sizeof(val), nullptr); return static_cast(val); } int get_nvfp4_e4m3_max() const { int val = 0; - nvte_get_tensor_param_v2(tensor_, kNVTENVFP4E4M3Max, &val, sizeof(val), nullptr); + nvte_get_tensor_param(tensor_, kNVTENVFP4E4M3Max, &val, sizeof(val), nullptr); return val; } diff --git a/transformer_engine/common/recipe/nvfp4.cu b/transformer_engine/common/recipe/nvfp4.cu index 14a0264074e..c8dcd1a7f7e 100644 --- a/transformer_engine/common/recipe/nvfp4.cu +++ b/transformer_engine/common/recipe/nvfp4.cu @@ -836,17 +836,9 @@ void nvfp4_fused_scale(const Tensor block_amax, const Tensor global_amax, Tensor void nvte_nvfp4_expand_scale_to_fp8(const NVTETensor input, NVTETensor output, size_t tile_rows, size_t tile_cols, size_t rows_padded, size_t block_len, - cudaStream_t stream) { - NVTE_API_CALL(nvte_nvfp4_expand_scale_to_fp8); - nvte_nvfp4_expand_scale_to_fp8_v2(input, output, tile_rows, tile_cols, rows_padded, block_len, - kNVTEFloat8E4M3, stream); -} - -void nvte_nvfp4_expand_scale_to_fp8_v2(const NVTETensor input, NVTETensor output, size_t tile_rows, - size_t tile_cols, size_t rows_padded, size_t block_len, - NVTEDType scale_dtype, cudaStream_t stream) { + NVTEDType scale_dtype, cudaStream_t stream) { #if FP4_TYPE_SUPPORTED - NVTE_API_CALL(nvte_nvfp4_expand_scale_to_fp8_v2); + NVTE_API_CALL(nvte_nvfp4_expand_scale_to_fp8); using namespace transformer_engine; nvfp4_recipe::nvfp4_expand_scale_to_fp8( *convertNVTETensorCheck(input), *convertNVTETensorCheck(output), tile_rows, tile_cols, @@ -856,17 +848,18 @@ void nvte_nvfp4_expand_scale_to_fp8_v2(const NVTETensor input, NVTETensor output #endif // FP4_TYPE_SUPPORTED } -void nvte_nvfp4_compute_per_block_scale(const NVTETensor block_amax, NVTETensor scale, - const NVTETensor global_amax, cudaStream_t stream) { - NVTE_API_CALL(nvte_nvfp4_compute_per_block_scale); - nvte_nvfp4_compute_per_block_scale_v2(block_amax, scale, global_amax, kNVTEFloat8E4M3, stream); +void nvte_nvfp4_expand_scale_to_fp8_v2(const NVTETensor input, NVTETensor output, size_t tile_rows, + size_t tile_cols, size_t rows_padded, size_t block_len, + NVTEDType scale_dtype, cudaStream_t stream) { + nvte_nvfp4_expand_scale_to_fp8(input, output, tile_rows, tile_cols, rows_padded, block_len, + scale_dtype, stream); } -void nvte_nvfp4_compute_per_block_scale_v2(const NVTETensor block_amax, NVTETensor scale, - const NVTETensor global_amax, NVTEDType scale_dtype, - cudaStream_t stream) { +void nvte_nvfp4_compute_per_block_scale(const NVTETensor block_amax, NVTETensor scale, + const NVTETensor global_amax, NVTEDType scale_dtype, + cudaStream_t stream) { #if FP4_TYPE_SUPPORTED - NVTE_API_CALL(nvte_nvfp4_compute_per_block_scale_v2); + NVTE_API_CALL(nvte_nvfp4_compute_per_block_scale); using namespace transformer_engine; nvfp4_recipe::nvfp4_compute_per_block_scale( *convertNVTETensorCheck(block_amax), *convertNVTETensorCheck(scale), @@ -876,16 +869,16 @@ void nvte_nvfp4_compute_per_block_scale_v2(const NVTETensor block_amax, NVTETens #endif // FP4_TYPE_SUPPORTED } -void nvte_nvfp4_compute_global_scale(const NVTETensor global_amax, NVTETensor global_scale, - cudaStream_t stream) { - NVTE_API_CALL(nvte_nvfp4_compute_global_scale); - nvte_nvfp4_compute_global_scale_v2(global_amax, global_scale, kNVTEFloat8E4M3, stream); +void nvte_nvfp4_compute_per_block_scale_v2(const NVTETensor block_amax, NVTETensor scale, + const NVTETensor global_amax, NVTEDType scale_dtype, + cudaStream_t stream) { + nvte_nvfp4_compute_per_block_scale(block_amax, scale, global_amax, scale_dtype, stream); } -void nvte_nvfp4_compute_global_scale_v2(const NVTETensor global_amax, NVTETensor global_scale, - NVTEDType scale_dtype, cudaStream_t stream) { +void nvte_nvfp4_compute_global_scale(const NVTETensor global_amax, NVTETensor global_scale, + NVTEDType scale_dtype, cudaStream_t stream) { #if FP4_TYPE_SUPPORTED - NVTE_API_CALL(nvte_nvfp4_compute_global_scale_v2); + NVTE_API_CALL(nvte_nvfp4_compute_global_scale); using namespace transformer_engine; nvfp4_recipe::nvfp4_compute_global_scale(*convertNVTETensorCheck(global_amax), *convertNVTETensorCheck(global_scale), @@ -895,6 +888,11 @@ void nvte_nvfp4_compute_global_scale_v2(const NVTETensor global_amax, NVTETensor #endif // FP4_TYPE_SUPPORTED } +void nvte_nvfp4_compute_global_scale_v2(const NVTETensor global_amax, NVTETensor global_scale, + NVTEDType scale_dtype, cudaStream_t stream) { + nvte_nvfp4_compute_global_scale(global_amax, global_scale, scale_dtype, stream); +} + void nvte_nvfp4_scale_transpose(const NVTETensor input, NVTETensor output, size_t M_tiles, size_t K_tiles, cudaStream_t stream) { #if FP4_TYPE_SUPPORTED @@ -936,19 +934,9 @@ void nvte_nvfp4_2d_compute_partial_amax(const NVTETensor inp, NVTETensor amax, s void nvte_nvfp4_2d_partial_cast(const NVTETensor inp, NVTETensor out, const NVTETensor scale, const NVTETensor global_scale, size_t h, size_t w, size_t scale_stride_h, size_t scale_stride_w, size_t start_offset, - size_t block_len, cudaStream_t stream) { - NVTE_API_CALL(nvte_nvfp4_2d_partial_cast); - nvte_nvfp4_2d_partial_cast_v2(inp, out, scale, global_scale, h, w, scale_stride_h, scale_stride_w, - start_offset, block_len, kNVTEFloat8E4M3, stream); -} - -void nvte_nvfp4_2d_partial_cast_v2(const NVTETensor inp, NVTETensor out, const NVTETensor scale, - const NVTETensor global_scale, size_t h, size_t w, - size_t scale_stride_h, size_t scale_stride_w, - size_t start_offset, size_t block_len, NVTEDType scale_dtype, - cudaStream_t stream) { + size_t block_len, NVTEDType scale_dtype, cudaStream_t stream) { #if FP4_TYPE_SUPPORTED - NVTE_API_CALL(nvte_nvfp4_2d_partial_cast_v2); + NVTE_API_CALL(nvte_nvfp4_2d_partial_cast); using namespace transformer_engine; nvfp4_recipe::nvfp4_2d_partial_cast( *convertNVTETensorCheck(inp), *convertNVTETensorCheck(out), *convertNVTETensorCheck(scale), @@ -959,6 +947,15 @@ void nvte_nvfp4_2d_partial_cast_v2(const NVTETensor inp, NVTETensor out, const N #endif // FP4_TYPE_SUPPORTED } +void nvte_nvfp4_2d_partial_cast_v2(const NVTETensor inp, NVTETensor out, const NVTETensor scale, + const NVTETensor global_scale, size_t h, size_t w, + size_t scale_stride_h, size_t scale_stride_w, + size_t start_offset, size_t block_len, NVTEDType scale_dtype, + cudaStream_t stream) { + nvte_nvfp4_2d_partial_cast(inp, out, scale, global_scale, h, w, scale_stride_h, scale_stride_w, + start_offset, block_len, scale_dtype, stream); +} + void nvte_nvfp4_compute_per_tensor_scale(const NVTETensor inpA, const bool use_rowwise_amax_A, const NVTETensor inpB, const bool use_rowwise_amax_B, float alpha_in, NVTETensor alpha_out, @@ -992,19 +989,10 @@ void nvte_nvfp4_compute_per_tensor_scale(const NVTETensor inpA, const bool use_r void nvte_nvfp4_fused_scale(const NVTETensor block_amax, const NVTETensor global_amax, NVTETensor per_block_scale, NVTETensor target_scale, NVTETensor target_amax, size_t tile_rows, size_t tile_cols, - size_t rows_padded, size_t block_len, cudaStream_t stream) { - NVTE_API_CALL(nvte_nvfp4_fused_scale); - nvte_nvfp4_fused_scale_v2(block_amax, global_amax, per_block_scale, target_scale, target_amax, - tile_rows, tile_cols, rows_padded, block_len, kNVTEFloat8E4M3, stream); -} - -void nvte_nvfp4_fused_scale_v2(const NVTETensor block_amax, const NVTETensor global_amax, - NVTETensor per_block_scale, NVTETensor target_scale, - NVTETensor target_amax, size_t tile_rows, size_t tile_cols, - size_t rows_padded, size_t block_len, NVTEDType scale_dtype, - cudaStream_t stream) { + size_t rows_padded, size_t block_len, NVTEDType scale_dtype, + cudaStream_t stream) { #if FP4_TYPE_SUPPORTED - NVTE_API_CALL(nvte_nvfp4_fused_scale_v2); + NVTE_API_CALL(nvte_nvfp4_fused_scale); using namespace transformer_engine; nvfp4_recipe::nvfp4_fused_scale( *convertNVTETensorCheck(block_amax), *convertNVTETensorCheck(global_amax), @@ -1015,3 +1003,12 @@ void nvte_nvfp4_fused_scale_v2(const NVTETensor block_amax, const NVTETensor glo NVTE_ERROR("FP4 support requires CUDA 12.8+, but compile-time CUDA version is ", CUDA_VERSION); #endif // FP4_TYPE_SUPPORTED } + +void nvte_nvfp4_fused_scale_v2(const NVTETensor block_amax, const NVTETensor global_amax, + NVTETensor per_block_scale, NVTETensor target_scale, + NVTETensor target_amax, size_t tile_rows, size_t tile_cols, + size_t rows_padded, size_t block_len, NVTEDType scale_dtype, + cudaStream_t stream) { + nvte_nvfp4_fused_scale(block_amax, global_amax, per_block_scale, target_scale, target_amax, + tile_rows, tile_cols, rows_padded, block_len, scale_dtype, stream); +} diff --git a/transformer_engine/common/transformer_engine.cpp b/transformer_engine/common/transformer_engine.cpp index a7de84b87c8..f275d92f4cd 100644 --- a/transformer_engine/common/transformer_engine.cpp +++ b/transformer_engine/common/transformer_engine.cpp @@ -812,67 +812,8 @@ NVTEShape nvte_tensor_scale_inv_shape(const NVTETensor tensor) { return nvte_make_shape(t->scale_inv.shape.data(), t->scale_inv.shape.size()); } -void nvte_set_tensor_param(NVTETensor *tensor, NVTETensorParam param_name, - const NVTEBasicTensor *param) { - NVTE_CHECK(tensor != nullptr, "Tensor pointer can't be NULL."); - auto *t = transformer_engine::convertNVTETensor(*tensor); - NVTE_CHECK(t != nullptr, "Tensor is not allocated."); - switch (param_name) { - case kNVTERowwiseData: - t->data = *param; - break; - case kNVTEColumnwiseData: - t->columnwise_data = *param; - break; - case kNVTEScale: - t->scale = *param; - break; - case kNVTEAmax: - t->amax = *param; - break; - case kNVTERowwiseScaleInv: - t->scale_inv = *param; - break; - case kNVTEColumnwiseScaleInv: - t->columnwise_scale_inv = *param; - break; - case kNVTEColumnwiseAmax: - t->columnwise_amax = *param; - break; - default: - NVTE_ERROR("Unsupported tensor parameter (", static_cast(param_name), - "). Consider using nvte_set_tensor_param_v2 instead."); - } -} - -NVTEBasicTensor nvte_get_tensor_param(const NVTETensor tensor, NVTETensorParam param_name) { - if (tensor == nullptr) { - return {nullptr, kNVTEFloat32, nvte_make_shape(nullptr, 1)}; - } - const auto &t = *transformer_engine::convertNVTETensorCheck(tensor); - switch (param_name) { - case kNVTERowwiseData: - return t.data; - case kNVTEColumnwiseData: - return t.columnwise_data; - case kNVTEScale: - return t.scale; - case kNVTEAmax: - return t.amax; - case kNVTERowwiseScaleInv: - return t.scale_inv; - case kNVTEColumnwiseScaleInv: - return t.columnwise_scale_inv; - case kNVTEColumnwiseAmax: - return t.columnwise_amax; - default: - NVTE_ERROR("Unsupported tensor parameter (", static_cast(param_name), - "). Consider using nvte_set_tensor_param_v2 instead."); - } -} - -void nvte_set_tensor_param_v2(NVTETensor tensor, NVTETensorParam param, const void *buf, - size_t size_in_bytes) { +void nvte_set_tensor_param(NVTETensor tensor, NVTETensorParam param, const void *buf, + size_t size_in_bytes) { // Check attribute and buffer NVTE_CHECK(param < kNVTENumTensorParams, "Invalid NVTETensorParam (got ", static_cast(param), ")"); @@ -941,8 +882,13 @@ void nvte_set_tensor_param_v2(NVTETensor tensor, NVTETensorParam param, const vo } } -void nvte_get_tensor_param_v2(const NVTETensor tensor, NVTETensorParam param, void *buf, - size_t size_in_bytes, size_t *size_written) { +void nvte_set_tensor_param_v2(NVTETensor tensor, NVTETensorParam param, const void *buf, + size_t size_in_bytes) { + nvte_set_tensor_param(tensor, param, buf, size_in_bytes); +} + +void nvte_get_tensor_param(const NVTETensor tensor, NVTETensorParam param, void *buf, + size_t size_in_bytes, size_t *size_written) { using namespace transformer_engine; // Check param @@ -1028,6 +974,11 @@ void nvte_get_tensor_param_v2(const NVTETensor tensor, NVTETensorParam param, vo } } +void nvte_get_tensor_param_v2(const NVTETensor tensor, NVTETensorParam param, void *buf, + size_t size_in_bytes, size_t *size_written) { + nvte_get_tensor_param(tensor, param, buf, size_in_bytes, size_written); +} + NVTEScalingMode nvte_tensor_scaling_mode(const NVTETensor tensor) { if (tensor == nullptr) { return NVTE_DELAYED_TENSOR_SCALING; diff --git a/transformer_engine/common/util/splits_to_offsets.cu b/transformer_engine/common/util/splits_to_offsets.cu index 4d1adf7ec7c..77ed586d9df 100644 --- a/transformer_engine/common/util/splits_to_offsets.cu +++ b/transformer_engine/common/util/splits_to_offsets.cu @@ -251,18 +251,11 @@ void nvte_splits_to_offsets_2d(const NVTETensor first_dims, const NVTETensor las NVTE_CHECK_CUDA(cudaGetLastError()); } -void nvte_splits_to_offsets_multi(NVTETensor split_sizes, NVTETensor *outputs, - const int64_t *strides, const int *include_leading_zero, - size_t num_outputs, cudaStream_t stream) { - nvte_splits_to_offsets_multi_v2(split_sizes, 1, outputs, strides, include_leading_zero, - num_outputs, stream); -} - -void nvte_splits_to_offsets_multi_v2(NVTETensor split_sizes, size_t split_alignment, - NVTETensor *outputs, const int64_t *strides, - const int *include_leading_zero, size_t num_outputs, - cudaStream_t stream) { - NVTE_API_CALL(nvte_splits_to_offsets_multi_v2); +void nvte_splits_to_offsets_multi(NVTETensor split_sizes, size_t split_alignment, + NVTETensor *outputs, const int64_t *strides, + const int *include_leading_zero, size_t num_outputs, + cudaStream_t stream) { + NVTE_API_CALL(nvte_splits_to_offsets_multi); using namespace transformer_engine; namespace s2o = transformer_engine::splits_to_offsets; @@ -328,3 +321,11 @@ void nvte_splits_to_offsets_multi_v2(NVTETensor split_sizes, size_t split_alignm NVTE_CHECK_CUDA(cudaGetLastError()); } } + +void nvte_splits_to_offsets_multi_v2(NVTETensor split_sizes, size_t split_alignment, + NVTETensor *outputs, const int64_t *strides, + const int *include_leading_zero, size_t num_outputs, + cudaStream_t stream) { + nvte_splits_to_offsets_multi(split_sizes, split_alignment, outputs, strides, include_leading_zero, + num_outputs, stream); +} diff --git a/transformer_engine/jax/cpp_extensions/router.py b/transformer_engine/jax/cpp_extensions/router.py index ad49c7a7d1b..cd979486f47 100644 --- a/transformer_engine/jax/cpp_extensions/router.py +++ b/transformer_engine/jax/cpp_extensions/router.py @@ -3,15 +3,17 @@ # See LICENSE for license information. """JAX/TE custom ops for fused MoE router""" +import functools from enum import IntEnum +import jax import jax.numpy as jnp from jax import dtypes, ffi from jax.sharding import NamedSharding, PartitionSpec from transformer_engine_jax import JAXX_Routing_Map_Format, JAXX_Score_Function from .base import BasePrimitive, register_primitive -from .misc import get_padded_spec +from .misc import get_padded_spec, te_dtype_to_jax_dtype __all__ = [ "ScoreFunction", @@ -467,6 +469,18 @@ def shardy_sharding_rule(*args, **kwargs): # ============================================================================= +@functools.cache +def get_fused_moe_aux_loss_workspace_sizes(): + """Query the workspace shape and dtype required for the aux-loss forward. + + The capacity is the same for all input shapes, so it is queried once. + """ + import transformer_engine_jax as _te_jax + + (wkspace_info,) = _te_jax.get_fused_moe_aux_loss_workspace_sizes() + return wkspace_info + + class FusedMoEAuxLossFwdPrimitive(BasePrimitive): """ Fused MoE Aux Loss Forward Primitive. @@ -484,6 +498,17 @@ def abstract(probs_aval, tokens_per_expert_aval, topk, coeff): i_dtype = dtypes.canonicalize_dtype(probs_aval.dtype) aux_loss_aval = probs_aval.update(shape=(), dtype=i_dtype) const_buf_aval = probs_aval.update(shape=(2,), dtype=jnp.float32) + wkspace_info = get_fused_moe_aux_loss_workspace_sizes() + workspace_aval = jax.core.ShapedArray( + shape=wkspace_info[0], dtype=te_dtype_to_jax_dtype(wkspace_info[1]) + ) + return aux_loss_aval, const_buf_aval, workspace_aval + + @staticmethod + def outer_abstract(*args, **kwargs): + aux_loss_aval, const_buf_aval, _workspace_aval = FusedMoEAuxLossFwdPrimitive.abstract( + *args, **kwargs + ) return aux_loss_aval, const_buf_aval @staticmethod @@ -502,12 +527,13 @@ def impl(probs, tokens_per_expert, topk, coeff): raise RuntimeError( "FusedMoEAuxLossFwdPrimitive.inner_primitive has not been registered" ) - return FusedMoEAuxLossFwdPrimitive.inner_primitive.bind( + aux_loss, const_buf, _workspace = FusedMoEAuxLossFwdPrimitive.inner_primitive.bind( probs, tokens_per_expert, topk=topk, coeff=coeff, ) + return aux_loss, const_buf @staticmethod def batcher(batched_args, batch_dims, *, topk, coeff): diff --git a/transformer_engine/jax/csrc/extensions.h b/transformer_engine/jax/csrc/extensions.h index 0e595fb88e0..3c094375b31 100644 --- a/transformer_engine/jax/csrc/extensions.h +++ b/transformer_engine/jax/csrc/extensions.h @@ -183,6 +183,7 @@ XLA_FFI_DECLARE_HANDLER_SYMBOL(CublasHandleInitHandler); XLA_FFI_DECLARE_HANDLER_SYMBOL(FusedTopkWithScoreFunctionForwardHandler); XLA_FFI_DECLARE_HANDLER_SYMBOL(FusedTopkWithScoreFunctionBackwardHandler); XLA_FFI_DECLARE_HANDLER_SYMBOL(FusedMoEAuxLossForwardHandler); +pybind11::tuple GetFusedMoEAuxLossWorkspaceSizes(); XLA_FFI_DECLARE_HANDLER_SYMBOL(FusedMoEAuxLossBackwardHandler); // Bootstrap EP (eager NCCL comm init); anchor released by ReleaseEpResources. diff --git a/transformer_engine/jax/csrc/extensions/activation.cpp b/transformer_engine/jax/csrc/extensions/activation.cpp index 6325a700d15..0b5e0c95668 100644 --- a/transformer_engine/jax/csrc/extensions/activation.cpp +++ b/transformer_engine/jax/csrc/extensions/activation.cpp @@ -138,8 +138,8 @@ Error_Type ActLuFFI(cudaStream_t stream, Buffer_Type input_buf, Buffer_Type scal nvte_sreglu(input_tensor.data(), output_tensor.data(), stream); break; case NVTE_Activation_Type::CLAMPED_SWIGLU: - nvte_clamped_swiglu_v2(input_tensor.data(), output_tensor.data(), swiglu_limit, swiglu_alpha, - swiglu_glu_linear_offset, stream); + nvte_clamped_swiglu(input_tensor.data(), output_tensor.data(), swiglu_limit, swiglu_alpha, + swiglu_glu_linear_offset, stream); break; default: NVTE_ERROR("Unsupported ActivationEnum"); @@ -448,8 +448,8 @@ Error_Type DActLuDBiasQuantizeFFI(cudaStream_t stream, Buffer_Type input_buf, nvte_dsreglu(input_tensor.data(), act_input_tensor.data(), output_tensor.data(), stream); break; case NVTE_Activation_Type::CLAMPED_SWIGLU: - nvte_clamped_dswiglu_v2(input_tensor.data(), act_input_tensor.data(), output_tensor.data(), - swiglu_limit, swiglu_alpha, swiglu_glu_linear_offset, stream); + nvte_clamped_dswiglu(input_tensor.data(), act_input_tensor.data(), output_tensor.data(), + swiglu_limit, swiglu_alpha, swiglu_glu_linear_offset, stream); break; default: NVTE_ERROR("Unsupported ActivationEnum"); diff --git a/transformer_engine/jax/csrc/extensions/gemm.cpp b/transformer_engine/jax/csrc/extensions/gemm.cpp index ef9a91f2858..b6ae1fab4a2 100644 --- a/transformer_engine/jax/csrc/extensions/gemm.cpp +++ b/transformer_engine/jax/csrc/extensions/gemm.cpp @@ -338,10 +338,10 @@ Error_Type GemmV2FFI(cudaStream_t stream, Buffer_Type lhs, Buffer_Type lhs_scale ", out_shape[1]=", out_shape[1]); // Launch TE/common kernel with swapped LHS/RHS for cuBLAS column-major order - nvte_cublas_gemm_v2(config.rhs_transposed /*transa*/, config.lhs_transposed /*transb*/, - alpha_ptr, rhs_.data() /*A*/, lhs_.data() /*B*/, beta_ptr, - out_.data() /*C*/, out_.data() /*D*/, workspace_.data(), matmul_config, - stream); + nvte_cublas_gemm(config.rhs_transposed /*transa*/, config.lhs_transposed /*transb*/, + alpha_ptr, rhs_.data() /*A*/, lhs_.data() /*B*/, beta_ptr, + out_.data() /*C*/, out_.data() /*D*/, workspace_.data(), matmul_config, + stream); } else { std::vector buffer_shape{0, 0}; DType buffer_dtype = out_dtype; diff --git a/transformer_engine/jax/csrc/extensions/pybind.cpp b/transformer_engine/jax/csrc/extensions/pybind.cpp index 4abcf343bb0..4455d0f0658 100644 --- a/transformer_engine/jax/csrc/extensions/pybind.cpp +++ b/transformer_engine/jax/csrc/extensions/pybind.cpp @@ -163,6 +163,7 @@ PYBIND11_MODULE(transformer_engine_jax, m) { m.def("get_norm_fwd_workspace_sizes", &GetNormForwardWorkspaceSizes); m.def("get_norm_bwd_workspace_sizes", &GetNormBackwardWorkspaceSizes); m.def("get_topk_workspace_sizes", &GetTopkWorkspaceSizes); + m.def("get_fused_moe_aux_loss_workspace_sizes", &GetFusedMoEAuxLossWorkspaceSizes); m.def("is_non_nt_fp8_gemm_supported", &nvte_is_non_tn_fp8_gemm_supported); m.def("nvte_built_with_cublasmp", &::nvte_built_with_cublasmp); m.def("initialize_cgemm_communicator", &InitializeCgemmCommunicator); diff --git a/transformer_engine/jax/csrc/extensions/quantization.cpp b/transformer_engine/jax/csrc/extensions/quantization.cpp index a7bdcee15da..1ff35163d57 100644 --- a/transformer_engine/jax/csrc/extensions/quantization.cpp +++ b/transformer_engine/jax/csrc/extensions/quantization.cpp @@ -181,7 +181,7 @@ Error_Type DBiasQuantizeFFI(cudaStream_t stream, Buffer_Type input_buf, Buffer_T if (is_nvfp4 && use_rht) { if (is_quantize_2x2x(quantize_layout)) { // Do regular rowwise quantization without RHT - nvte_quantize_v2(input_tensor.data(), output_tensor.data(), quant_config, stream); + nvte_quantize(input_tensor.data(), output_tensor.data(), quant_config, stream); } TensorWrapper out_transpose(get_nvte_scaling_mode(scaling_mode)); @@ -255,7 +255,7 @@ Error_Type DBiasQuantizeFFI(cudaStream_t stream, Buffer_Type input_buf, Buffer_T nvte_quantize_dbias(input_tensor.data(), output_tensor.data(), dbias_tensor.data(), workspace_tensor.data(), stream); } else { - nvte_quantize_v2(input_tensor.data(), output_tensor.data(), quant_config, stream); + nvte_quantize(input_tensor.data(), output_tensor.data(), quant_config, stream); } return ffi_with_cuda_error_check(); } diff --git a/transformer_engine/jax/csrc/extensions/router.cpp b/transformer_engine/jax/csrc/extensions/router.cpp index a1d0731b6db..c4c4385d6b7 100644 --- a/transformer_engine/jax/csrc/extensions/router.cpp +++ b/transformer_engine/jax/csrc/extensions/router.cpp @@ -60,7 +60,7 @@ Error_Type FusedTopkWithScoreFunctionForwardFFI( auto intermediate_tensor = TensorWrapper(intermediate, flat_shape, DType::kFloat32); if (compute_aux_scores) { - nvte_fused_score_for_moe_aux_loss_forward_v2( + nvte_fused_score_for_moe_aux_loss_forward( logits_tensor.data(), num_tokens, num_experts, static_cast(topk), static_cast(score_function), probs_tensor.data(), routing_map_tensor.data(), routing_map_format_nvte, intermediate_tensor.data(), stream); @@ -72,7 +72,7 @@ Error_Type FusedTopkWithScoreFunctionForwardFFI( convert_ffi_datatype_to_te_dtype(expert_bias_buf.element_type())) : TensorWrapper(); - nvte_fused_topk_with_score_function_forward_v2( + nvte_fused_topk_with_score_function_forward( logits_tensor.data(), num_tokens, num_experts, static_cast(topk), static_cast(use_pre_softmax), static_cast(num_groups), static_cast(group_topk), static_cast(scaling_factor), @@ -150,7 +150,7 @@ Error_Type FusedTopkWithScoreFunctionBackwardFFI( auto routing_map_tensor = TensorWrapper(routing_map_buf.untyped_data(), routing_map_shape, DType::kByte); - nvte_fused_topk_with_score_function_backward_v2( + nvte_fused_topk_with_score_function_backward( routing_map_tensor.data(), routing_map_format_nvte, intermediate_tensor.data(), grad_probs_tensor.data(), num_tokens, num_experts, static_cast(topk), static_cast(use_pre_softmax), static_cast(scaling_factor), @@ -184,7 +184,8 @@ Error_Type FusedMoEAuxLossForwardFFI(cudaStream_t stream, Buffer_Type probs_buf, // [num_tokens, num_experts] Buffer_Type tokens_per_expert_buf, // [num_experts] Result_Type aux_loss_buf, // scalar - Result_Type const_buf, // scalar + Result_Type const_buf, // [2] + Result_Type workspace_buf, // scratch int64_t topk, double coeff) { auto dtype = convert_ffi_datatype_to_te_dtype(probs_buf.element_type()); auto probs_dims = probs_buf.dimensions(); @@ -201,11 +202,16 @@ Error_Type FusedMoEAuxLossForwardFFI(cudaStream_t stream, auto aux_loss_tensor = TensorWrapper(aux_loss_buf->untyped_data(), std::vector{1}, dtype); auto const_buf_tensor = TensorWrapper(const_buf->untyped_data(), std::vector{2}, DType::kFloat32); + auto workspace_dims = workspace_buf->dimensions(); + auto workspace_tensor = + TensorWrapper(workspace_buf->untyped_data(), + std::vector(workspace_dims.begin(), workspace_dims.end()), + convert_ffi_datatype_to_te_dtype(workspace_buf->element_type())); nvte_fused_moe_aux_loss_forward(probs_tensor.data(), tpe_tensor.data(), num_tokens, num_experts, num_tokens, num_experts, static_cast(topk), static_cast(coeff), aux_loss_tensor.data(), - const_buf_tensor.data(), stream); + const_buf_tensor.data(), workspace_tensor.data(), stream); return ffi_with_cuda_error_check(); } @@ -217,10 +223,20 @@ XLA_FFI_DEFINE_HANDLER_SYMBOL(FusedMoEAuxLossForwardHandler, FusedMoEAuxLossForw .Arg() // tokens_per_expert .Ret() // aux_loss .Ret() // const_buf + .Ret() // workspace .Attr("topk") .Attr("coeff"), FFI_CudaGraph_Traits); +pybind11::tuple GetFusedMoEAuxLossWorkspaceSizes() { + // Query with an empty workspace; the operation reports a fixed capacity for all input shapes. + TensorWrapper workspace_tensor; + nvte_fused_moe_aux_loss_forward(nullptr, nullptr, 0, 0, 0, 0, 0, 0.0f, nullptr, nullptr, + workspace_tensor.data(), nullptr); + auto work_shape = MakeShapeVector(workspace_tensor.shape()); + return pybind11::make_tuple(std::make_pair(work_shape, workspace_tensor.dtype())); +} + // ============================================================================ // Fused MoE Aux Loss - Backward // ============================================================================ diff --git a/transformer_engine/pytorch/csrc/extensions.h b/transformer_engine/pytorch/csrc/extensions.h index 4a582ac24c2..6ff443dcff8 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -77,15 +77,15 @@ void fused_score_for_moe_aux_loss_bwd(at::Tensor intermediate_output, at::Tensor std::pair, DType> get_moe_aux_loss_workspace_config(); -std::tuple fused_moe_aux_loss_fwd( - at::Tensor probs, at::Tensor tokens_per_expert, int total_num_tokens, int num_experts, - int num_rows, int num_cols, int topk, float coeff, bool deterministic = false, - std::optional workspace = std::nullopt); +std::tuple fused_moe_aux_loss_fwd(at::Tensor probs, + at::Tensor tokens_per_expert, + int total_num_tokens, int num_experts, + int num_rows, int num_cols, int topk, + float coeff, at::Tensor workspace); std::tuple fused_moe_aux_loss_fwd_graph_safe( at::Tensor probs, at::Tensor tokens_per_expert, at::Tensor total_num_tokens, int num_experts, - int num_rows, int num_cols, int topk, float coeff, bool deterministic = false, - std::optional workspace = std::nullopt); + int num_rows, int num_cols, int topk, float coeff, at::Tensor workspace); at::Tensor fused_moe_aux_loss_bwd(at::Tensor Const_buf, at::Tensor tokens_per_expert, int num_rows, int num_cols, at::Tensor grad_aux_loss); diff --git a/transformer_engine/pytorch/csrc/extensions/activation.cpp b/transformer_engine/pytorch/csrc/extensions/activation.cpp index 6251872a036..d5aefb99076 100644 --- a/transformer_engine/pytorch/csrc/extensions/activation.cpp +++ b/transformer_engine/pytorch/csrc/extensions/activation.cpp @@ -347,13 +347,13 @@ py::object dsituglu(const at::Tensor& grad, const at::Tensor& input, py::handle /* clamped functions */ py::object clamped_swiglu(const at::Tensor& input, py::handle quantizer, float limit, float alpha, float glu_linear_offset) { - return activation_helper(input, quantizer, 2, limit, alpha, + return activation_helper(input, quantizer, 2, limit, alpha, glu_linear_offset); } py::object clamped_dswiglu(const at::Tensor& grad, const at::Tensor& input, py::handle quantizer, float limit, float alpha, float glu_linear_offset) { - return dactivation_helper(grad, input, quantizer, limit, alpha, + return dactivation_helper(grad, input, quantizer, limit, alpha, glu_linear_offset); } diff --git a/transformer_engine/pytorch/csrc/extensions/cast.cpp b/transformer_engine/pytorch/csrc/extensions/cast.cpp index 82dc187dcd7..8a6e271de29 100644 --- a/transformer_engine/pytorch/csrc/extensions/cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/cast.cpp @@ -2155,7 +2155,7 @@ void split_quantize_nvfp4_impl_helper(const TensorWrapper &input, if (input_list[i].numel() == 0) { continue; } - nvte_quantize_v2(input_list[i].data(), output_list[i].data(), quant_config_list[i], stream); + nvte_quantize(input_list[i].data(), output_list[i].data(), quant_config_list[i], stream); } } diff --git a/transformer_engine/pytorch/csrc/extensions/gemm.cpp b/transformer_engine/pytorch/csrc/extensions/gemm.cpp index 13e218f2f8b..63c51c54c1b 100644 --- a/transformer_engine/pytorch/csrc/extensions/gemm.cpp +++ b/transformer_engine/pytorch/csrc/extensions/gemm.cpp @@ -411,9 +411,9 @@ std::vector gemm(py::handle A, bool transa, py::handle B, bool trans } else { // Launch GEMM, accumulating in-place if needed NVTE_SCOPED_GIL_RELEASE({ - nvte_cublas_gemm_v2(transa, transb, &alpha, A_tensor.data(), B_tensor.data(), &beta.value(), - accumulate ? out_tensor.data() : nullptr, out_tensor.data(), - te_workspace.data(), config, main_stream); + nvte_cublas_gemm(transa, transb, &alpha, A_tensor.data(), B_tensor.data(), &beta.value(), + accumulate ? out_tensor.data() : nullptr, out_tensor.data(), + te_workspace.data(), config, main_stream); }); } } else { diff --git a/transformer_engine/pytorch/csrc/extensions/grouped_mlp_experimental.cpp b/transformer_engine/pytorch/csrc/extensions/grouped_mlp_experimental.cpp index 0ab8bc8d61b..d055b8a7267 100644 --- a/transformer_engine/pytorch/csrc/extensions/grouped_mlp_experimental.cpp +++ b/transformer_engine/pytorch/csrc/extensions/grouped_mlp_experimental.cpp @@ -114,14 +114,14 @@ std::tuple swizzle_scales_and_pack_ptrs_for_ auto set_param = [](NVTETensor t, NVTETensorParam param, void *dptr, transformer_engine::DType dtype, const NVTEShape &shape) { NVTEBasicTensor data{dptr, static_cast(dtype), shape}; - nvte_set_tensor_param_v2(t, param, &data, sizeof(data)); + nvte_set_tensor_param(t, param, &data, sizeof(data)); }; // Configure NVTETensors for (size_t i = 0; i < num_tensors; ++i) { const uint8_t swizzled_flag = 1; - nvte_set_tensor_param_v2(outputs_nvte[i], kNVTEWithGEMMSwizzledScales, &swizzled_flag, - sizeof(swizzled_flag)); + nvte_set_tensor_param(outputs_nvte[i], kNVTEWithGEMMSwizzledScales, &swizzled_flag, + sizeof(swizzled_flag)); void *in_scale_ptr = scale_tensors[i].data_ptr(); void *out_scale_ptr = swizzled_scales_dptr + i * swizzled_scales_stride; set_param(inputs_nvte[i], data_param_name, nullptr, data_dtype, data_shape); diff --git a/transformer_engine/pytorch/csrc/extensions/misc.cpp b/transformer_engine/pytorch/csrc/extensions/misc.cpp index e17e362438b..fd834da5a2b 100644 --- a/transformer_engine/pytorch/csrc/extensions/misc.cpp +++ b/transformer_engine/pytorch/csrc/extensions/misc.cpp @@ -89,15 +89,15 @@ std::tuple> splits_to_offsets_multi( NVTEShape shape = nvte_make_shape(&length, 1); NVTEBasicTensor data = {outputs[i].data_ptr(), static_cast(GetTransformerEngineDType(dtypes[i])), shape}; - nvte_set_tensor_param_v2(outputs_nvte[i], kNVTERowwiseData, &data, sizeof(data)); + nvte_set_tensor_param(outputs_nvte[i], kNVTERowwiseData, &data, sizeof(data)); include_leading_zero_int[i] = include_leading_zero[i] ? 1 : 0; } auto split_sizes_nvte = makeTransformerEngineTensor(split_sizes_out); NVTE_SCOPED_GIL_RELEASE({ - nvte_splits_to_offsets_multi_v2(split_sizes_nvte.data(), split_alignment, outputs_nvte.data(), - strides.data(), include_leading_zero_int.data(), num_outputs, - at::cuda::getCurrentCUDAStream()); + nvte_splits_to_offsets_multi(split_sizes_nvte.data(), split_alignment, outputs_nvte.data(), + strides.data(), include_leading_zero_int.data(), num_outputs, + at::cuda::getCurrentCUDAStream()); }); return {split_sizes_out, std::move(outputs)}; diff --git a/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp b/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp index 4ecd50deb87..dcd833d623b 100644 --- a/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp @@ -43,10 +43,10 @@ void nvfp4_2d_partial_cast(const at::Tensor& inp, py::handle out, const at::Tens const TensorWrapper scale_cu = makeTransformerEngineTensor(scale); const TensorWrapper global_scale_cu = makeTransformerEngineTensor(global_scale); - nvte_nvfp4_2d_partial_cast_v2(inp_cu.data(), out_cu.data(), scale_cu.data(), - global_scale_cu.data(), h, w, scale.stride(0), scale.stride(1), - start_offset, block_len, static_cast(scale_dtype), - at::cuda::getCurrentCUDAStream()); + nvte_nvfp4_2d_partial_cast(inp_cu.data(), out_cu.data(), scale_cu.data(), + global_scale_cu.data(), h, w, scale.stride(0), scale.stride(1), + start_offset, block_len, static_cast(scale_dtype), + at::cuda::getCurrentCUDAStream()); } void nvfp4_multi_tensor_2d_partial_cast(std::vector inp_list, @@ -95,10 +95,10 @@ void nvfp4_multi_tensor_2d_partial_cast(std::vector inp_list, const TensorWrapper scale_cu = makeTransformerEngineTensor(scale); const TensorWrapper global_scale_cu = makeTransformerEngineTensor(global_scale); - nvte_nvfp4_2d_partial_cast_v2(inp_cu.data(), out_cu.data(), scale_cu.data(), - global_scale_cu.data(), h, w, scale.stride(0), scale.stride(1), - start_offset, static_cast(block_len), - static_cast(scale_dtype), stream); + nvte_nvfp4_2d_partial_cast(inp_cu.data(), out_cu.data(), scale_cu.data(), + global_scale_cu.data(), h, w, scale.stride(0), scale.stride(1), + start_offset, static_cast(block_len), + static_cast(scale_dtype), stream); } } diff --git a/transformer_engine/pytorch/csrc/extensions/pybind.cpp b/transformer_engine/pytorch/csrc/extensions/pybind.cpp index d0ebcfa5939..7238a935d98 100644 --- a/transformer_engine/pytorch/csrc/extensions/pybind.cpp +++ b/transformer_engine/pytorch/csrc/extensions/pybind.cpp @@ -181,12 +181,12 @@ void init_router_bindings(pybind11::module &m) { m.def("fused_moe_aux_loss_fwd", &fused_moe_aux_loss_fwd, py::arg("probs"), py::arg("tokens_per_expert"), py::arg("total_num_tokens"), py::arg("num_experts"), py::arg("num_rows"), py::arg("num_cols"), py::arg("topk"), py::arg("coeff"), - py::arg("deterministic") = false, py::arg("workspace") = py::none(), + py::arg("workspace"), "Fused aux loss fwd (host-int total_num_tokens, host-folded C_coeff)"); m.def("fused_moe_aux_loss_fwd_graph_safe", &fused_moe_aux_loss_fwd_graph_safe, py::arg("probs"), py::arg("tokens_per_expert"), py::arg("total_num_tokens"), py::arg("num_experts"), py::arg("num_rows"), py::arg("num_cols"), py::arg("topk"), py::arg("coeff"), - py::arg("deterministic") = false, py::arg("workspace") = py::none(), + py::arg("workspace"), "Fused aux loss fwd (device-tensor total_num_tokens, CUDA-graph-safe)"); m.def("fused_moe_aux_loss_bwd", &fused_moe_aux_loss_bwd, py::arg("Const_buf"), py::arg("tokens_per_expert"), py::arg("num_rows"), py::arg("num_cols"), diff --git a/transformer_engine/pytorch/csrc/extensions/recipe.cpp b/transformer_engine/pytorch/csrc/extensions/recipe.cpp index 3b0e27683ad..3505c785fda 100644 --- a/transformer_engine/pytorch/csrc/extensions/recipe.cpp +++ b/transformer_engine/pytorch/csrc/extensions/recipe.cpp @@ -44,13 +44,13 @@ void fused_amax_and_scale_update_after_reduction(const at::Tensor& amax_reductio NVTEShape amax_shape = convertTorchShape(amax_histories[i].sizes()); NVTEBasicTensor amax_history_data = {amax_histories[i].data_ptr(), static_cast(DType::kFloat32), amax_shape}; - nvte_set_tensor_param_v2(te_amax_histories[i], kNVTERowwiseData, &amax_history_data, - sizeof(amax_history_data)); + nvte_set_tensor_param(te_amax_histories[i], kNVTERowwiseData, &amax_history_data, + sizeof(amax_history_data)); NVTEShape scale_shape = convertTorchShape(scales[i].sizes()); NVTEBasicTensor scale_data = {scales[i].data_ptr(), static_cast(DType::kFloat32), scale_shape}; - nvte_set_tensor_param_v2(te_scales[i], kNVTERowwiseData, &scale_data, sizeof(scale_data)); + nvte_set_tensor_param(te_scales[i], kNVTERowwiseData, &scale_data, sizeof(scale_data)); } nvte_delayed_scaling_recipe_amax_and_scale_update_after_reduction( makeTransformerEngineTensor(amax_reduction_buffer).data(), te_amax_histories.data(), diff --git a/transformer_engine/pytorch/csrc/extensions/router.cpp b/transformer_engine/pytorch/csrc/extensions/router.cpp index 2522436d7b7..f0b9ced2381 100644 --- a/transformer_engine/pytorch/csrc/extensions/router.cpp +++ b/transformer_engine/pytorch/csrc/extensions/router.cpp @@ -144,7 +144,7 @@ std::tuple fused_topk_with_score_function_fw get_score_function_value(score_function), expert_bias_cu.data(), probs_cu.data(), routing_map_cu.data(), intermediate_output_cu.data(), at::cuda::getCurrentCUDAStream()); } else { - nvte_fused_topk_with_score_function_forward_v2( + nvte_fused_topk_with_score_function_forward( logits_cu.data(), static_cast(num_tokens), static_cast(num_experts), topk, use_pre_softmax, num_groups_value, group_topk_value, scaling_factor_value, get_score_function_value(score_function), expert_bias_cu.data(), probs_cu.data(), @@ -245,7 +245,7 @@ fused_topk_with_score_function_qb_fwd(at::Tensor logits, int topk, intermediate_output_cu.data(), cutoff_cu.data(), histogram_cu.data(), bin_bounds_cu.data(), mode, stream); } else { - nvte_fused_topk_with_score_function_forward_qb_v2( + nvte_fused_topk_with_score_function_forward_qb( logits_cu.data(), static_cast(num_tokens), static_cast(num_experts), topk, scaling_factor_value, expert_bias_cu.data(), probs_cu.data(), routing_output_cu.data(), static_cast(routing_map_format), intermediate_output_cu.data(), @@ -315,7 +315,7 @@ void fused_topk_with_score_function_bwd(at::Tensor routing_map, at::Tensor inter scaling_factor_value, score_function_value, grad_logits_cu.data(), at::cuda::getCurrentCUDAStream()); } else { - nvte_fused_topk_with_score_function_backward_v2( + nvte_fused_topk_with_score_function_backward( routing_map_cu.data(), static_cast(routing_map_format), intermediate_output_cu.data(), grad_probs_cu.data(), static_cast(num_tokens), static_cast(num_experts), topk, use_pre_softmax, scaling_factor_value, @@ -490,7 +490,7 @@ std::tuple fused_score_for_moe_aux_loss_fwd( auto intermediate_output_cu = makeTransformerEngineTensor(intermediate_output.data_ptr(), shape_2d, DType::kFloat32); - nvte_fused_score_for_moe_aux_loss_forward_v2( + nvte_fused_score_for_moe_aux_loss_forward( logits_cu.data(), static_cast(num_tokens), static_cast(num_experts), topk, score_function_value, scores_cu.data(), routing_map_cu.data(), static_cast(routing_map_format), intermediate_output_cu.data(), @@ -533,29 +533,27 @@ std::pair, DType> get_moe_aux_loss_workspace_config() { TensorWrapper workspace; // Query the operation with an empty workspace, then let Python own the // allocation and its per-stream or CUDA Graph lifetime. - nvte_fused_moe_aux_loss_forward_v2(nullptr, nullptr, 0, 0, 0, 0, 0, 0.0f, nullptr, nullptr, - workspace.data(), nullptr); + nvte_fused_moe_aux_loss_forward(nullptr, nullptr, 0, 0, 0, 0, 0, 0.0f, nullptr, nullptr, + workspace.data(), nullptr); const auto shape = workspace.shape(); return {std::vector(shape.data, shape.data + shape.ndim), workspace.dtype()}; } -static TensorWrapper make_aux_loss_workspace(const std::optional &workspace, +static TensorWrapper make_aux_loss_workspace(const at::Tensor &workspace, const at::Tensor &probs) { - TORCH_CHECK(workspace.has_value(), "deterministic aux loss requires a workspace"); - TORCH_CHECK(workspace->is_cuda() && workspace->device() == probs.device(), + TORCH_CHECK(workspace.is_cuda() && workspace.device() == probs.device(), "aux-loss workspace must be on the same CUDA device as probs"); - TORCH_CHECK(workspace->scalar_type() == at::kFloat && workspace->is_contiguous(), + TORCH_CHECK(workspace.scalar_type() == at::kFloat && workspace.is_contiguous(), "aux-loss workspace must be contiguous FP32 storage"); - TORCH_CHECK(workspace->numel() > 0, "aux-loss workspace must not be empty"); - return makeTransformerEngineTensor(*workspace); + TORCH_CHECK(workspace.numel() > 0, "aux-loss workspace must not be empty"); + return makeTransformerEngineTensor(workspace); } std::tuple fused_moe_aux_loss_fwd(at::Tensor probs, at::Tensor tokens_per_expert, int total_num_tokens, int num_experts, int num_rows, int num_cols, int topk, - float coeff, bool deterministic, - std::optional workspace) { + float coeff, at::Tensor workspace) { at::cuda::CUDAGuard device_guard(probs.device()); TORCH_CHECK(topk > 0, "topk must be greater than 0"); TORCH_CHECK(total_num_tokens > 0, "total_num_tokens must be greater than 0"); @@ -570,26 +568,18 @@ std::tuple fused_moe_aux_loss_fwd(at::Tensor probs, auto aux_loss_cu = makeTransformerEngineTensor(aux_loss); auto Const_buf_cu = makeTransformerEngineTensor(Const_buf); - const auto stream = at::cuda::getCurrentCUDAStream(); - if (!deterministic) { - nvte_fused_moe_aux_loss_forward(probs_cu.data(), tokens_per_expert_cu.data(), total_num_tokens, - num_experts, num_rows, num_cols, topk, coeff, - aux_loss_cu.data(), Const_buf_cu.data(), stream); - return std::make_tuple(aux_loss, Const_buf); - } - auto workspace_cu = make_aux_loss_workspace(workspace, probs); - nvte_fused_moe_aux_loss_forward_v2( - probs_cu.data(), tokens_per_expert_cu.data(), total_num_tokens, num_experts, num_rows, - num_cols, topk, coeff, aux_loss_cu.data(), Const_buf_cu.data(), workspace_cu.data(), stream); + nvte_fused_moe_aux_loss_forward(probs_cu.data(), tokens_per_expert_cu.data(), total_num_tokens, + num_experts, num_rows, num_cols, topk, coeff, aux_loss_cu.data(), + Const_buf_cu.data(), workspace_cu.data(), + at::cuda::getCurrentCUDAStream()); return std::make_tuple(aux_loss, Const_buf); } std::tuple fused_moe_aux_loss_fwd_graph_safe( at::Tensor probs, at::Tensor tokens_per_expert, at::Tensor total_num_tokens, int num_experts, - int num_rows, int num_cols, int topk, float coeff, bool deterministic, - std::optional workspace) { + int num_rows, int num_cols, int topk, float coeff, at::Tensor workspace) { at::cuda::CUDAGuard device_guard(probs.device()); TORCH_CHECK(topk > 0, "topk must be greater than 0"); TORCH_CHECK(num_experts > 0, "num_experts must be greater than 0"); @@ -611,19 +601,11 @@ std::tuple fused_moe_aux_loss_fwd_graph_safe( auto aux_loss_cu = makeTransformerEngineTensor(aux_loss); auto Const_buf_cu = makeTransformerEngineTensor(Const_buf); - const auto stream = at::cuda::getCurrentCUDAStream(); - if (!deterministic) { - nvte_fused_moe_aux_loss_forward_graph_safe( - probs_cu.data(), tokens_per_expert_cu.data(), total_num_tokens_cu.data(), num_experts, - num_rows, num_cols, topk, coeff, aux_loss_cu.data(), Const_buf_cu.data(), stream); - return std::make_tuple(aux_loss, Const_buf); - } - auto workspace_cu = make_aux_loss_workspace(workspace, probs); - nvte_fused_moe_aux_loss_forward_graph_safe_v2(probs_cu.data(), tokens_per_expert_cu.data(), - total_num_tokens_cu.data(), num_experts, num_rows, - num_cols, topk, coeff, aux_loss_cu.data(), - Const_buf_cu.data(), workspace_cu.data(), stream); + nvte_fused_moe_aux_loss_forward_graph_safe( + probs_cu.data(), tokens_per_expert_cu.data(), total_num_tokens_cu.data(), num_experts, + num_rows, num_cols, topk, coeff, aux_loss_cu.data(), Const_buf_cu.data(), + workspace_cu.data(), at::cuda::getCurrentCUDAStream()); return std::make_tuple(aux_loss, Const_buf); } diff --git a/transformer_engine/pytorch/csrc/extensions/swizzle.cpp b/transformer_engine/pytorch/csrc/extensions/swizzle.cpp index 08b38da8a99..9048f54f105 100644 --- a/transformer_engine/pytorch/csrc/extensions/swizzle.cpp +++ b/transformer_engine/pytorch/csrc/extensions/swizzle.cpp @@ -254,7 +254,7 @@ std::optional multi_tensor_swizzle_scales_for_gemm_impl( auto set_param = [](NVTETensor t, NVTETensorParam param, void *dptr, transformer_engine::DType dtype, const NVTEShape &shape) { NVTEBasicTensor data{dptr, static_cast(dtype), shape}; - nvte_set_tensor_param_v2(t, param, &data, sizeof(data)); + nvte_set_tensor_param(t, param, &data, sizeof(data)); }; // Cache output scale dtype/shape per tensor so we can update the @@ -263,8 +263,8 @@ std::optional multi_tensor_swizzle_scales_for_gemm_impl( for (size_t i = 0; i < n_swizzle; ++i) { auto &tensor = *tensors_needing_swizzle[i]; const uint8_t swizzled_flag = 1; - nvte_set_tensor_param_v2(outputs_nvte[i], kNVTEWithGEMMSwizzledScales, &swizzled_flag, - sizeof(swizzled_flag)); + nvte_set_tensor_param(outputs_nvte[i], kNVTEWithGEMMSwizzledScales, &swizzled_flag, + sizeof(swizzled_flag)); if (rowwise_usage) { const auto data_nvte = tensor.get_rowwise_data(); const auto scales_nvte = tensor.get_rowwise_scale_inv(); diff --git a/transformer_engine/pytorch/csrc/extensions/transpose.cpp b/transformer_engine/pytorch/csrc/extensions/transpose.cpp index 938b0f83b70..f65a7ee67d4 100644 --- a/transformer_engine/pytorch/csrc/extensions/transpose.cpp +++ b/transformer_engine/pytorch/csrc/extensions/transpose.cpp @@ -141,7 +141,7 @@ void nvfp4_expand_scale_to_fp8(at::Tensor input, at::Tensor output, int64_t tile auto output_cu = makeTransformerEngineTensor( output.data_ptr(), std::vector{out_shape[0], out_shape[1]}, DType::kByte); - nvte_nvfp4_expand_scale_to_fp8_v2( + nvte_nvfp4_expand_scale_to_fp8( input_cu.data(), output_cu.data(), static_cast(tile_rows), static_cast(tile_cols), static_cast(rows_padded), static_cast(block_len), static_cast(scale_dtype), @@ -163,9 +163,9 @@ void nvfp4_compute_per_block_scale(at::Tensor block_amax, at::Tensor scale, at:: auto scale_cu = makeTransformerEngineTensor(scale); auto global_amax_cu = makeTransformerEngineTensor(global_amax); - nvte_nvfp4_compute_per_block_scale_v2(block_amax_cu.data(), scale_cu.data(), - global_amax_cu.data(), static_cast(scale_dtype), - at::cuda::getCurrentCUDAStream()); + nvte_nvfp4_compute_per_block_scale(block_amax_cu.data(), scale_cu.data(), + global_amax_cu.data(), static_cast(scale_dtype), + at::cuda::getCurrentCUDAStream()); } void nvfp4_fused_scale(at::Tensor block_amax, at::Tensor global_amax, at::Tensor per_block_scale, @@ -193,11 +193,11 @@ void nvfp4_fused_scale(at::Tensor block_amax, at::Tensor global_amax, at::Tensor auto target_scale_cu = makeTransformerEngineTensor(target_scale); auto target_amax_cu = makeTransformerEngineTensor(target_amax); - nvte_nvfp4_fused_scale_v2(block_amax_cu.data(), global_amax_cu.data(), per_block_scale_cu.data(), - target_scale_cu.data(), target_amax_cu.data(), - static_cast(tile_rows), static_cast(tile_cols), - static_cast(rows_padded), static_cast(block_len), - static_cast(scale_dtype), at::cuda::getCurrentCUDAStream()); + nvte_nvfp4_fused_scale(block_amax_cu.data(), global_amax_cu.data(), per_block_scale_cu.data(), + target_scale_cu.data(), target_amax_cu.data(), + static_cast(tile_rows), static_cast(tile_cols), + static_cast(rows_padded), static_cast(block_len), + static_cast(scale_dtype), at::cuda::getCurrentCUDAStream()); } void nvfp4_multi_tensor_fused_scale( @@ -248,7 +248,7 @@ void nvfp4_multi_tensor_fused_scale( auto target_scale_cu = makeTransformerEngineTensor(target_scale); auto target_amax_cu = makeTransformerEngineTensor(target_amax); - nvte_nvfp4_fused_scale_v2( + nvte_nvfp4_fused_scale( block_amax_cu.data(), global_amax_cu.data(), per_block_scale_cu.data(), target_scale_cu.data(), target_amax_cu.data(), tile_rows, tile_cols, rows_padded, static_cast(block_len), static_cast(scale_dtype), stream); @@ -266,9 +266,9 @@ void nvfp4_compute_global_scale(at::Tensor global_amax, at::Tensor global_scale, auto global_amax_cu = makeTransformerEngineTensor(global_amax); auto global_scale_cu = makeTransformerEngineTensor(global_scale); - nvte_nvfp4_compute_global_scale_v2(global_amax_cu.data(), global_scale_cu.data(), - static_cast(scale_dtype), - at::cuda::getCurrentCUDAStream()); + nvte_nvfp4_compute_global_scale(global_amax_cu.data(), global_scale_cu.data(), + static_cast(scale_dtype), + at::cuda::getCurrentCUDAStream()); } at::Tensor swap_first_dims(at::Tensor tensor, std::optional out) { diff --git a/transformer_engine/pytorch/csrc/quantizer.cpp b/transformer_engine/pytorch/csrc/quantizer.cpp index 6e795dbd6fe..03776999e1d 100644 --- a/transformer_engine/pytorch/csrc/quantizer.cpp +++ b/transformer_engine/pytorch/csrc/quantizer.cpp @@ -638,7 +638,7 @@ void Float8Quantizer::quantize(const TensorWrapper& input, TensorWrapper& out, quant_config.set_noop_tensor(noop_flag->data()); } NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize_v2(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); + nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); }); } @@ -1023,7 +1023,7 @@ void Float8CurrentScalingQuantizer::quantize_impl(const TensorWrapper& input, Te // Cast to FP8 out.set_amax(nullptr, DType::kFloat32, out.defaultShape); // Avoid atomic amax updates - NVTE_SCOPED_GIL_RELEASE({ nvte_quantize_v2(input.data(), out.data(), quant_config, stream); }); + NVTE_SCOPED_GIL_RELEASE({ nvte_quantize(input.data(), out.data(), quant_config, stream); }); // Clear scale pointer defensively: amax_buf/scale_buf are caller-owned locals // that may be released right after this call, leaving a dangling raw pointer in `out`. @@ -1432,7 +1432,7 @@ void Float8BlockQuantizer::quantize(const TensorWrapper& input, TensorWrapper& o quant_config.set_force_pow_2_scales(force_pow_2_scales); quant_config.set_amax_epsilon(amax_epsilon); NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize_v2(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); + nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); }); } @@ -1841,7 +1841,7 @@ void MXFP8Quantizer::quantize(const TensorWrapper& input, TensorWrapper& out, quant_config.set_mxfp8_2d_quantization(true); } NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize_v2(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); + nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); }); } @@ -2517,7 +2517,7 @@ void NVFP4Quantizer::quantize_with_rht_unfused_helper( out_identity.set_row_scaled_nvfp4(out.get_row_scaled_nvfp4()); NVTE_SCOPED_GIL_RELEASE( - { nvte_quantize_v2(input.data(), out_identity.data(), quant_config, stream); }); + { nvte_quantize(input.data(), out_identity.data(), quant_config, stream); }); } if (columnwise_usage) { @@ -2558,8 +2558,8 @@ void NVFP4Quantizer::quantize_with_rht_unfused_helper( // Quantize kernel will treat everything as rowwise input/output, which is // intended. NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize_v2(rht_output_t_cpp.data(), out_transpose.data(), quant_config_columnwise, - stream); + nvte_quantize(rht_output_t_cpp.data(), out_transpose.data(), quant_config_columnwise, + stream); }); } } @@ -2813,7 +2813,7 @@ void NVFP4Quantizer::quantize_impl(const TensorWrapper& input, TensorWrapper& ou } } else { NVTE_SCOPED_GIL_RELEASE( - { nvte_quantize_v2(input.data(), kernel_out.data(), quant_config, stream); }); + { nvte_quantize(input.data(), kernel_out.data(), quant_config, stream); }); } for (auto& scale_view : scale_inputs) { NVTE_SCOPED_GIL_RELEASE( diff --git a/transformer_engine/pytorch/router.py b/transformer_engine/pytorch/router.py index 90279878c1f..ad78947f2e2 100644 --- a/transformer_engine/pytorch/router.py +++ b/transformer_engine/pytorch/router.py @@ -915,12 +915,11 @@ def forward( num_experts: int, topk: int, coeff: float, - deterministic: bool, ): # pylint: disable=missing-function-docstring num_rows = probs.size(0) num_cols = probs.size(1) - workspace = _get_moe_aux_loss_workspace(probs.device) if deterministic else None + workspace = _get_moe_aux_loss_workspace(probs.device) if isinstance(total_num_tokens, torch.Tensor): aux_loss, Const_buf = tex.fused_moe_aux_loss_fwd_graph_safe( probs=probs, @@ -931,7 +930,6 @@ def forward( num_cols=num_cols, topk=topk, coeff=coeff, - deterministic=deterministic, workspace=workspace, ) else: @@ -944,7 +942,6 @@ def forward( num_cols=num_cols, topk=topk, coeff=coeff, - deterministic=deterministic, workspace=workspace, ) ctx.save_for_backward(Const_buf, tokens_per_expert) @@ -963,7 +960,7 @@ def backward(ctx, grad_aux_loss): num_cols=ctx.num_cols, grad_aux_loss=grad_aux_loss, ) - return grad_probs, None, None, None, None, None, None + return grad_probs, None, None, None, None, None def fused_moe_aux_loss( @@ -973,12 +970,16 @@ def fused_moe_aux_loss( num_experts: int, topk: int, coeff: float, - deterministic: bool = False, + deterministic: Optional[bool] = None, ) -> torch.Tensor: - """ - Fused MoE aux loss. + """Fused MoE aux loss. Supports ``torch.compile(fullgraph=True)`` with either form of ``total_num_tokens``. + The loss is computed with a fixed-order two-stage FP32 reduction, so + repeated calls with identical inputs on the same hardware and software + are bitwise reproducible. Eager calls reuse scratch per device and stream; + CUDA Graph capture uses private scratch that is reused on replay. + Parameters ---------- probs : torch.Tensor in fp32/bf16/fp16 @@ -994,8 +995,9 @@ def fused_moe_aux_loss( topk : int coeff : float the coefficient of the aux loss. - deterministic : bool, default = False - Use a fixed-order two-stage FP32 reduction instead of atomic accumulation. + deterministic : bool, optional + Deprecated and has no effect. + The loss is computed with a fixed-order two-stage FP32 reduction. Repeated calls with identical inputs on the same hardware and software are bitwise reproducible. Results may differ from other reduction orders. Eager calls reuse scratch per device and stream; CUDA Graph capture uses @@ -1006,16 +1008,22 @@ def fused_moe_aux_loss( aux_loss : torch.Tensor. A scalar tensor in the same dtype as the "probs". """ + if deterministic is not None: + warnings.warn( + "The deterministic argument of fused_moe_aux_loss is deprecated and has no effect " + "because the aux loss is always computed deterministically. It will be removed in a " + "future release.", + category=DeprecationWarning, + stacklevel=2, + ) if torch.compiler.is_compiling(): token_count = total_num_tokens if isinstance(total_num_tokens, torch.Tensor) else None count = 0 if token_count is not None else total_num_tokens aux_loss, _ = _aux_loss_forward( - probs, tokens_per_expert, count, token_count, num_experts, topk, coeff, deterministic + probs, tokens_per_expert, count, token_count, num_experts, topk, coeff ) return aux_loss - return FusedAuxLoss.apply( - probs, tokens_per_expert, total_num_tokens, num_experts, topk, coeff, deterministic - ) + return FusedAuxLoss.apply(probs, tokens_per_expert, total_num_tokens, num_experts, topk, coeff) def _routing_map_fake(logits, routing_map_format): @@ -1417,12 +1425,9 @@ def _aux_loss_forward( num_experts: int, topk: int, coeff: float, - deterministic: bool, ) -> Tuple[torch.Tensor, torch.Tensor]: with torch.cuda.device(probs.device): - workspace = ( - _get_moe_aux_loss_workspace(probs.device, cache=False) if deterministic else None - ) + workspace = _get_moe_aux_loss_workspace(probs.device, cache=False) if token_count is not None: return tex.fused_moe_aux_loss_fwd_graph_safe( probs, @@ -1433,7 +1438,6 @@ def _aux_loss_forward( probs.shape[1], topk, coeff, - deterministic, workspace, ) return tex.fused_moe_aux_loss_fwd( @@ -1445,7 +1449,6 @@ def _aux_loss_forward( probs.shape[1], topk, coeff, - deterministic, workspace, ) @@ -1459,9 +1462,8 @@ def _aux_loss_forward_fake( num_experts, topk, coeff, - deterministic, ): - del tokens_per_expert, total_num_tokens, token_count, num_experts, topk, coeff, deterministic + del tokens_per_expert, total_num_tokens, token_count, num_experts, topk, coeff return probs.new_empty(()), probs.new_empty((2,), dtype=torch.float32) @@ -1486,7 +1488,7 @@ def _aux_loss_backward_fake(const_buf, tokens_per_expert, num_rows, num_cols, gr def _aux_loss_setup_context(ctx, inputs, output): - probs, tokens_per_expert, _, _, _, _, _, _ = inputs + probs, tokens_per_expert, _, _, _, _, _ = inputs _, const_buf = output ctx.num_rows, ctx.num_cols = probs.shape ctx.mark_non_differentiable(const_buf) @@ -1498,7 +1500,7 @@ def _aux_loss_autograd(ctx, grad_aux_loss, _grad_const): grad_probs = _aux_loss_backward( const_buf, tokens_per_expert, ctx.num_rows, ctx.num_cols, grad_aux_loss ) - return grad_probs, None, None, None, None, None, None, None + return grad_probs, None, None, None, None, None, None _aux_loss_forward.register_autograd(_aux_loss_autograd, setup_context=_aux_loss_setup_context) From 6462858c957125abe89ce37cfba65ab4a6e783e6 Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 18:54:14 -0800 Subject: [PATCH 04/18] [Common] Remove deprecated C API functions Remove nvte_convert_pointers_to_tensor, nvte_group_nvfp4_compute_amax, and nvte_multi_stream_cublas_gemm. Remove the deprecated FP8 block scaling tensor format: the quantization config attribute (value 3 is left unused), the Float8BlockScaleTensorFormat enum and its Python binding, the QuantizationConfigWrapper setter, and the unreachable compact-format path in the FP8 1D block-scaling kernel. That kernel now takes return_rowwise/return_columnwise flags instead of option enums. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tim Moon --- tests/cpp/util/test_c_api.c | 3 - .../common/cast/cast_grouped.cu | 6 - .../common/cast/dispatch/quantize.cuh | 28 +-- .../group_quantize_fp8_blockwise.cuh | 3 - transformer_engine/common/common.h | 22 +-- .../common/gemm/cublaslt_gemm.cu | 19 -- .../common/include/transformer_engine/cast.h | 5 - .../transformer_engine/transformer_engine.h | 17 +- .../common/include/transformer_engine/utils.h | 8 - .../common/transformer_engine.cpp | 9 - .../common/transpose/cast_transpose.h | 29 +-- .../quantize_transpose_vector_blockwise.cu | 184 ++---------------- .../common/util/pybind_helper.h | 5 - transformer_engine/common/util/utils.cu | 9 - 14 files changed, 41 insertions(+), 306 deletions(-) diff --git a/tests/cpp/util/test_c_api.c b/tests/cpp/util/test_c_api.c index 00bbe104172..6afab7281c2 100644 --- a/tests/cpp/util/test_c_api.c +++ b/tests/cpp/util/test_c_api.c @@ -117,7 +117,6 @@ void call_every_c_api_function(void) { nvte_group_requantize(NULL, NULL, NULL, NULL, NULL); nvte_multi_tensor_quantize(NULL, NULL, NULL, 0, NULL); nvte_group_nvfp4_quantize_with_amax(NULL, NULL, NULL, 0, NULL, NULL); - nvte_group_nvfp4_compute_amax(NULL, NULL, NULL, 0, NULL); /* cast_transpose_noop.h */ nvte_transpose_with_noop(NULL, NULL, NULL, NULL); @@ -465,6 +464,4 @@ void call_every_c_api_function(void) { /* utils.h */ nvte_copy_host_to_device_via_kernel(NULL, NULL, 0, NULL); - nvte_convert_pointers_to_tensor(NULL, NULL, 0, NULL); - } diff --git a/transformer_engine/common/cast/cast_grouped.cu b/transformer_engine/common/cast/cast_grouped.cu index 0a33f62d5fb..e3dcec91580 100644 --- a/transformer_engine/common/cast/cast_grouped.cu +++ b/transformer_engine/common/cast/cast_grouped.cu @@ -98,9 +98,3 @@ void nvte_group_nvfp4_quantize_with_amax(const NVTETensor input, NVTETensor *out dispatch::group_quantize_fwd_host_aware_helper( input, outputs, split_sections, num_tensors, quant_config, stream); } - -void nvte_group_nvfp4_compute_amax(const NVTETensor input, NVTETensor *outputs, - const size_t *split_sections, const size_t num_tensors, - cudaStream_t stream) { - nvte_group_amax(input, outputs, split_sections, num_tensors, stream); -} diff --git a/transformer_engine/common/cast/dispatch/quantize.cuh b/transformer_engine/common/cast/dispatch/quantize.cuh index 26768ec96c5..d61c6a5bf38 100644 --- a/transformer_engine/common/cast/dispatch/quantize.cuh +++ b/transformer_engine/common/cast/dispatch/quantize.cuh @@ -230,18 +230,12 @@ void quantize_fwd_helper(const NVTETensor input, NVTETensor output, NVTE_CHECK(!IS_ACT, "IS_ACT is not implemented for FWD NVTE_BLOCK_SCALING_1D"); bool force_pow_2_scales = quant_config_cpp.force_pow_2_scales; float epsilon = quant_config_cpp.amax_epsilon; - FP8BlockwiseRowwiseOption rowwise_option = FP8BlockwiseRowwiseOption::NONE; - FP8BlockwiseColumnwiseOption columnwise_option = FP8BlockwiseColumnwiseOption::NONE; - if (output_tensor->has_data()) { - rowwise_option = FP8BlockwiseRowwiseOption::ROWWISE_GEMM_READY; - } - if (output_tensor->has_columnwise_data()) { - columnwise_option = FP8BlockwiseColumnwiseOption::COLUMNWISE_GEMM_READY; - } quantize_transpose_vector_blockwise( input_tensor->data, output_tensor->scale_inv, output_tensor->columnwise_scale_inv, - output_tensor->data, output_tensor->columnwise_data, epsilon, rowwise_option, - columnwise_option, force_pow_2_scales, noop_tensor->data, stream); + output_tensor->data, output_tensor->columnwise_data, epsilon, + /*return_rowwise=*/output_tensor->has_data(), + /*return_columnwise=*/output_tensor->has_columnwise_data(), force_pow_2_scales, + noop_tensor->data, stream); break; } default: @@ -429,18 +423,12 @@ void quantize_bwd_helper(const NVTETensor grad, const NVTETensor input, NVTETens "IS_DBIAS and IS_DACT are not implemented for BWD NVTE_BLOCK_SCALING_1D"); bool force_pow_2_scales = quant_config_cpp.force_pow_2_scales; float epsilon = quant_config_cpp.amax_epsilon; - FP8BlockwiseRowwiseOption rowwise_option = FP8BlockwiseRowwiseOption::NONE; - FP8BlockwiseColumnwiseOption columnwise_option = FP8BlockwiseColumnwiseOption::NONE; - if (output_tensor->has_data()) { - rowwise_option = FP8BlockwiseRowwiseOption::ROWWISE_GEMM_READY; - } - if (output_tensor->has_columnwise_data()) { - columnwise_option = FP8BlockwiseColumnwiseOption::COLUMNWISE_GEMM_READY; - } quantize_transpose_vector_blockwise( grad_tensor->data, output_tensor->scale_inv, output_tensor->columnwise_scale_inv, - output_tensor->data, output_tensor->columnwise_data, epsilon, rowwise_option, - columnwise_option, force_pow_2_scales, noop_tensor->data, stream); + output_tensor->data, output_tensor->columnwise_data, epsilon, + /*return_rowwise=*/output_tensor->has_data(), + /*return_columnwise=*/output_tensor->has_columnwise_data(), force_pow_2_scales, + noop_tensor->data, stream); break; } default: diff --git a/transformer_engine/common/cast/fp8_blockwise/group_quantize_fp8_blockwise.cuh b/transformer_engine/common/cast/fp8_blockwise/group_quantize_fp8_blockwise.cuh index 20689fce6d6..007342433c5 100644 --- a/transformer_engine/common/cast/fp8_blockwise/group_quantize_fp8_blockwise.cuh +++ b/transformer_engine/common/cast/fp8_blockwise/group_quantize_fp8_blockwise.cuh @@ -33,9 +33,6 @@ namespace transformer_engine { namespace dispatch { namespace fp8_blockwise { -using transformer_engine::detail::FP8BlockwiseColumnwiseOption; -using transformer_engine::detail::FP8BlockwiseRowwiseOption; - constexpr int kTileDim = 128; constexpr int kThreadsPerWarp = 32; constexpr int kThreadsPerBlock = 256; diff --git a/transformer_engine/common/common.h b/transformer_engine/common/common.h index 7d201f6c8ba..1dc0ac81be4 100644 --- a/transformer_engine/common/common.h +++ b/transformer_engine/common/common.h @@ -650,17 +650,17 @@ struct QuantizationConfig { bool mxfp8_2d_quantization = false; static constexpr size_t attr_sizes[] = { - sizeof(uint8_t), // force_pow_2_scales - sizeof(float), // amax_epsilon - sizeof(NVTETensor), // noop_tensor - sizeof(Float8BlockScaleTensorFormat), // (deprecated) - sizeof(NVTETensor), // rng_seed and offset - sizeof(uint8_t), // nvfp4_2d_quantization - sizeof(uint8_t), // stochastic_rounding - sizeof(uint8_t), // use_fast_math - sizeof(uint8_t), // nvfp4_4over6_mode - sizeof(uint8_t), // nvfp4_4over6_err_use_fast_math - sizeof(uint8_t) // mxfp8_2d_quantization + sizeof(uint8_t), // force_pow_2_scales + sizeof(float), // amax_epsilon + sizeof(NVTETensor), // noop_tensor + 0, // unused + sizeof(NVTETensor), // rng_seed and offset + sizeof(uint8_t), // nvfp4_2d_quantization + sizeof(uint8_t), // stochastic_rounding + sizeof(uint8_t), // use_fast_math + sizeof(uint8_t), // nvfp4_4over6_mode + sizeof(uint8_t), // nvfp4_4over6_err_use_fast_math + sizeof(uint8_t) // mxfp8_2d_quantization }; }; diff --git a/transformer_engine/common/gemm/cublaslt_gemm.cu b/transformer_engine/common/gemm/cublaslt_gemm.cu index 8733c10a706..65fd90c65b7 100644 --- a/transformer_engine/common/gemm/cublaslt_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_gemm.cu @@ -1142,25 +1142,6 @@ void multi_stream_cublas_gemm(const NVTETensor *A, const NVTETensor *B, NVTETens } } -void nvte_multi_stream_cublas_gemm(const NVTETensor *A, const NVTETensor *B, NVTETensor *D, - const NVTETensor *bias, NVTETensor *pre_gelu_out, - const int num_gemms, bool transa, bool transb, bool grad, - NVTETensor *workspace, bool accumulate, - bool use_split_accumulator, int math_sm_count, - cudaStream_t stream) { - NVTE_API_CALL(nvte_multi_stream_cublas_gemm); - using namespace transformer_engine; - - // Deprecation warning - NVTE_WARN( - "nvte_multi_stream_cublas_gemm is deprecated and will be removed in a future release. " - "Please migrate to nvte_multi_tensor_gemm (with CUTLASS Grouped GEMM support when " - "applicable)."); - - multi_stream_cublas_gemm(A, B, D, bias, pre_gelu_out, num_gemms, transa, transb, grad, workspace, - accumulate, use_split_accumulator, math_sm_count, stream); -} - namespace transformer_engine { using cublasHandleManager = detail::HandleManager; diff --git a/transformer_engine/common/include/transformer_engine/cast.h b/transformer_engine/common/include/transformer_engine/cast.h index 5d6b12099a5..95f5d070978 100644 --- a/transformer_engine/common/include/transformer_engine/cast.h +++ b/transformer_engine/common/include/transformer_engine/cast.h @@ -472,11 +472,6 @@ void nvte_group_nvfp4_quantize_with_amax(const NVTETensor input, NVTETensor *out const NVTEQuantizationConfig quant_config, cudaStream_t stream); -/*! \deprecated Use nvte_group_amax instead. */ -void nvte_group_nvfp4_compute_amax(const NVTETensor input, NVTETensor *outputs, - const size_t *split_sections, size_t num_tensors, - cudaStream_t stream); - #ifdef __cplusplus } // extern "C" #endif diff --git a/transformer_engine/common/include/transformer_engine/transformer_engine.h b/transformer_engine/common/include/transformer_engine/transformer_engine.h index 46aa5f6edf4..2888a452cdb 100644 --- a/transformer_engine/common/include/transformer_engine/transformer_engine.h +++ b/transformer_engine/common/include/transformer_engine/transformer_engine.h @@ -402,8 +402,7 @@ typedef enum NVTEQuantizationConfigAttribute { conditional early even when captured in a static CUDA graph. */ kNVTEQuantizationConfigNoopTensor = 2, - /*! \warning Deprecated */ - kNVTEQuantizationConfigFloat8BlockScaleTensorFormat = 3, + /* Value 3 is unused. */ /*! RNG state (NVTETensor with 2 elements - seed and offset */ kNVTEQuantizationConfigRNGState = 4, /*! Whether to use 2D block scaling for NVFP4 */ @@ -1421,17 +1420,6 @@ class GroupedTensorWrapper { NVTEGroupedTensor tensor_ = nullptr; }; -/*! \enum Float8BlockScaleTensorFormat - * \brief Data format for an FP8 block-scaled tensor - */ -enum class Float8BlockScaleTensorFormat { - /*! FP8 data is transposed if needed and scales are swizzled */ - GEMM_READY = 0, - /*! FP8 data is untransposed and scales are not swizzled or padded */ - COMPACT = 1, - INVALID -}; - /*! \struct QuantizationConfigWrapper * \brief C++ wrapper for NVTEQuantizationConfigWrapper. */ @@ -1488,9 +1476,6 @@ class QuantizationConfigWrapper { sizeof(NVTETensor)); } - /*! \warning Deprecated */ - void set_float8_block_scale_tensor_format(Float8BlockScaleTensorFormat format) {} - /*! \brief Set stochastic rounding state */ void set_rng_state(NVTETensor rng_state) { nvte_set_quantization_config_attribute(config_, kNVTEQuantizationConfigRNGState, &rng_state, diff --git a/transformer_engine/common/include/transformer_engine/utils.h b/transformer_engine/common/include/transformer_engine/utils.h index 994f9e42ad3..e858a32d8cb 100644 --- a/transformer_engine/common/include/transformer_engine/utils.h +++ b/transformer_engine/common/include/transformer_engine/utils.h @@ -13,7 +13,6 @@ #include #include -#include #include #ifdef __cplusplus @@ -33,13 +32,6 @@ extern "C" { void nvte_copy_host_to_device_via_kernel(const void *host_ptr, void *device_ptr, size_t num_bytes, cudaStream_t stream); -/*! \deprecated Use nvte_copy_host_to_device_via_kernel instead. - * - * \brief Copy an array of device pointers (held on host) into a device tensor. - */ -void nvte_convert_pointers_to_tensor(const uint64_t *host_ptrs, NVTETensor output, int64_t count, - cudaStream_t stream); - #ifdef __cplusplus } // extern "C" #endif diff --git a/transformer_engine/common/transformer_engine.cpp b/transformer_engine/common/transformer_engine.cpp index f275d92f4cd..4b17cb3e20b 100644 --- a/transformer_engine/common/transformer_engine.cpp +++ b/transformer_engine/common/transformer_engine.cpp @@ -1065,12 +1065,6 @@ void nvte_get_quantization_config_attribute(NVTEQuantizationConfig config, case kNVTEQuantizationConfigNoopTensor: std::memcpy(buf, &config_.noop_tensor, attr_size); break; - case kNVTEQuantizationConfigFloat8BlockScaleTensorFormat: { - // Deprecated - const auto invalid = Float8BlockScaleTensorFormat::INVALID; - std::memcpy(buf, &invalid, attr_size); - break; - } case kNVTEQuantizationConfigRNGState: std::memcpy(buf, &config_.rng_state, attr_size); break; @@ -1134,9 +1128,6 @@ void nvte_set_quantization_config_attribute(NVTEQuantizationConfig config, case kNVTEQuantizationConfigNoopTensor: std::memcpy(&config_.noop_tensor, buf, attr_size); break; - case kNVTEQuantizationConfigFloat8BlockScaleTensorFormat: - // Deprecated - break; case kNVTEQuantizationConfigRNGState: std::memcpy(&config_.rng_state, buf, attr_size); break; diff --git a/transformer_engine/common/transpose/cast_transpose.h b/transformer_engine/common/transpose/cast_transpose.h index c462b301475..7553a6cd4ec 100644 --- a/transformer_engine/common/transpose/cast_transpose.h +++ b/transformer_engine/common/transpose/cast_transpose.h @@ -30,35 +30,12 @@ void quantize_transpose_square_blockwise(const SimpleTensor &input, SimpleTensor const bool return_transpose, const bool pow_2_scale, const SimpleTensor &noop_tensor, cudaStream_t stream); -// enum class for rowwise usage -enum class FP8BlockwiseRowwiseOption { - // No rowwise data, skip rowwise quantization - NONE, - // Rowwise data, scales in GEMM format - ROWWISE_GEMM_READY, - // Deprecated - ROWWISE_COMPACT -}; - -// enum class for columnwise usage -// For Hopper sm90 with only TN fp8 gemm, there is need to do columnwise transpose when doing 1D block scaling -enum class FP8BlockwiseColumnwiseOption { - // No columnwise data, skip columnwise quantization - NONE, - // Columnwise data transposed from original shape. - // Scales in GEMM format corresponding to GEMM ingesting transposed column data. - // On Hopper sm90, GEMM_READY means that columnwise quantization also fuses transpose op - // On higher sm versions with TN,NT,NN fp8 gemm, GEMM_READY doesn't fuse transpose - COLUMNWISE_GEMM_READY, - // Deprecated - COLUMNWISE_COMPACT -}; - +// Quantize with FP8 1D block scaling. The row-wise output is in the same layout as the input, and +// the column-wise output is transposed. Scales are in the layout expected by GEMM. void quantize_transpose_vector_blockwise(const SimpleTensor &input, SimpleTensor &scale_inv, SimpleTensor &scale_inv_t, SimpleTensor &output, SimpleTensor &output_t, const float epsilon, - FP8BlockwiseRowwiseOption rowwise_option, - FP8BlockwiseColumnwiseOption columnwise_option, + const bool return_rowwise, const bool return_columnwise, const bool pow_2_scale, const SimpleTensor &noop_tensor, cudaStream_t stream); diff --git a/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu b/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu index df869b43317..1a516326b97 100644 --- a/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu +++ b/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu @@ -23,9 +23,6 @@ namespace transformer_engine { namespace { -using transformer_engine::detail::FP8BlockwiseColumnwiseOption; -using transformer_engine::detail::FP8BlockwiseRowwiseOption; - // clang-format off /* @@ -119,29 +116,6 @@ Step 3 (if columnwise transpose is True, GEMM_READY): Transpose, cast and store | T7 | T15 | T23 | T31 | | | | T7 | T15 | T23 | T31 | | | | +-----------------------+-----------------------+-----------------------+-----------------------+-----------------------+-----------------------+-----------------------+-----------------------+ -Step 3 (if columnwise transpose is False, COMPACT format): Skip Transpose, cast and store to output_t -* shard memory: 128x128 elements with type=InputType (below graph doesn't consider padding) -* 8 warps -* Loop 1 times -* What each thread does in each loop: - * 16 elements (in a row) are read from the shared memory, for a total of 4 rows, - * it needs 8 reads in smem to get 16 elements in a row, thread tile shape is 16x4 - * Every 32 consecutive threads in a warp do reduction and calculate the amax of each column, - * so each thread will do warp shuffle 16 times to get the amax of each column - * 16 elements are quantized and write to output_t at a time, for a total of 4 times -+------16 elements-------+------16 elements-------+-----80 elements-----+------16 elements------+ -| T0 | | | | -| T1 | | | | -| T2 | | | | -| T3 | | | | -| T4 | | | | -| T5 | | | | -| T6 | | | | -| T7 | | | | -| ... | | | | -| T31 | | | | -+-----------------------+-----------------------+-----------------------+-----------------------+ - */ // clang-format on @@ -172,19 +146,13 @@ __global__ void __launch_bounds__(kThreadsPerBlock) block_scaled_1d_cast_transpo CType* const tile_scales_inv_c, CType* const tile_scales_inv_t, const size_t row_length, const size_t num_rows, const size_t scale_stride_x, const size_t scale_stride_y, const size_t scale_t_stride_x, const size_t scale_t_stride_y, const float epsilon, - FP8BlockwiseRowwiseOption rowwise_option, FP8BlockwiseColumnwiseOption columnwise_option, - const bool pow_2_scaling, const float* noop_ptr) { + const bool return_rowwise, const bool return_columnwise, const bool pow_2_scaling, + const float* noop_ptr) { // skip execution if noop if (noop_ptr != nullptr && noop_ptr[0] == 1.0f) { return; } - bool return_rowwise = rowwise_option != FP8BlockwiseRowwiseOption::NONE; - bool return_columnwise_gemm_ready = - columnwise_option == FP8BlockwiseColumnwiseOption::COLUMNWISE_GEMM_READY; - bool return_columnwise_compact = - columnwise_option == FP8BlockwiseColumnwiseOption::COLUMNWISE_COMPACT; - using SMemVec = Vec; using OVec = Vec; union IVec { @@ -331,8 +299,8 @@ __global__ void __launch_bounds__(kThreadsPerBlock) block_scaled_1d_cast_transpo } } - // Step 3 (return_columnwise_gemm_ready): Transpose, cast and store to output_t - if (return_columnwise_gemm_ready) { + // Step 3 (return_columnwise): Transpose, cast and store to output_t + if (return_columnwise) { constexpr int c_stride = kThreadsPerBlock / kNumThreadsStore; // Stride in columns of shared memory constexpr int num_iterations = kTileDim / (c_stride * kNVecSMem); @@ -417,103 +385,6 @@ __global__ void __launch_bounds__(kThreadsPerBlock) block_scaled_1d_cast_transpo } } } - - // Step 4 (return_columnwise_compact): cast in 128x1 style and store to output, skip transpose - if (return_columnwise_compact) { - // thread tile should be 4x16, 16 means 8 smem reads - constexpr int kThreadTileRow = kTileDim / kThreadsPerWarp; - constexpr int kThreadTileCol = kNVecOut; - using RegVec = Vec; - using RegScaleVec = Vec; - constexpr int num_smem_reads = kNVecOut / kNVecSMem; - // c_stride will not be used here because we only have one iteration - // constexpr int c_stride = kThreadTileCol * kNumWarps / kNVecSMem; - constexpr int num_iterations = - kTileDim / (kNumWarps * kThreadTileCol); // should be only one iteration - static_assert(num_iterations == 1, - "num_iterations should be 1 for columnwise non-transpose case"); - const int thr_idx_in_warp = threadIdx.x % kThreadsPerWarp; - const int warp_idx = threadIdx.x / kThreadsPerWarp; - const int r_s = thr_idx_in_warp * kThreadTileRow; // Row in shared memory - int c_s = warp_idx * num_smem_reads; // Column in shared memory - size_t r_g = static_cast(blockIdx.y) * kTileDim + r_s; // Row in global memory - const size_t c_g = - static_cast(blockIdx.x) * kTileDim + c_s * kNVecSMem; // Column in global memory - const size_t num_ele = c_g < row_length - ? min(static_cast(kThreadTileCol), row_length - c_g) - : 0; // For not aligned case -#pragma unroll - for (int iter = 0; iter < num_iterations; ++iter) { - RegVec reg_vec[kThreadTileRow]; - RegScaleVec thr_scale; - - // Step 3.1: Load from shared memory to registers -#pragma unroll - for (int i = 0; i < kThreadTileRow; ++i) { - int r = r_s + i; -#pragma unroll - for (int j = 0; j < num_smem_reads; ++j) { - int c = c_s + j; - SMemVec smem_vec = smem[r * kSMemCol + c]; - // copy smem_vec to reg vec with its elements -#pragma unroll - for (int k = 0; k < kNVecSMem; ++k) { - reg_vec[i].data.elt[j * kNVecSMem + k] = smem_vec.data.elt[k]; - } - } - } -#pragma unroll - for (int reg_idx = 0; reg_idx < kThreadTileCol; ++reg_idx) { - // Step 3.2: Compute local amax - CType amax = 0; -#pragma unroll - for (int i = 0; i < kThreadTileRow; ++i) { - amax = fmaxf(amax, fabsf(reg_vec[i].data.elt[reg_idx])); - } - // Step 3.3: Reduce amax - const bool is_src_lane = thr_idx_in_warp == 0; - amax = warp_reduce_max(amax); - constexpr int lane_zero = 0; - amax = __shfl_sync(0xFFFFFFFF, amax, lane_zero); - // Step 3.4: Compute scale - CType scale; - scale = compute_scale_from_types(amax, epsilon, pow_2_scaling); - thr_scale.data.elt[reg_idx] = scale; - // Step 3.5: Write scale_inv_t - bool write_scale_inv = is_src_lane; - if constexpr (!kAligned) { - write_scale_inv &= (c_g + reg_idx < row_length); - } - if (write_scale_inv) { - CType scale_inv = 1.0 / scale; - size_t row_idx = static_cast(blockIdx.y); - size_t col_idx = static_cast(blockIdx.x) * kTileDim + c_s * kNVecSMem + reg_idx; - tile_scales_inv_t[row_idx * scale_t_stride_y + col_idx * scale_t_stride_x] = scale_inv; - } - } - // Step 3.6: Quantize - for (int row_idx = 0; row_idx < kThreadTileRow; ++row_idx) { - OType* output_g = - &output_t[(r_g + row_idx) * row_length + c_g]; // Output address in global memory - OVec output_vec; -#pragma unroll - for (int i = 0; i < kThreadTileCol; ++i) { - output_vec.data.elt[i] = static_cast( - static_cast(reg_vec[row_idx].data.elt[i]) * thr_scale.data.elt[i]); - } - // Step 3.7: Store output_t - if constexpr (kAligned) { - output_vec.store_to(output_g); - } else { - if (r_g + row_idx < num_rows) { - output_vec.store_to_elts(output_g, 0, num_ele); - } - } - } - // Step 3.8: Update output address, column index of shared memory - // this section shouldn't matter since we only have one iteration - } - } } } // namespace @@ -524,8 +395,7 @@ namespace transformer_engine::detail { void quantize_transpose_vector_blockwise(const SimpleTensor& input, SimpleTensor& scale_inv, SimpleTensor& scale_inv_t, SimpleTensor& output, SimpleTensor& output_t, const float epsilon, - FP8BlockwiseRowwiseOption rowwise_option, - FP8BlockwiseColumnwiseOption columnwise_option, + const bool return_rowwise, const bool return_columnwise, const bool pow2_scale, const SimpleTensor& noop_tensor, cudaStream_t stream) { NVTE_API_CALL(quantize_transpose_vector_blockwise); @@ -554,50 +424,32 @@ void quantize_transpose_vector_blockwise(const SimpleTensor& input, SimpleTensor size_t scale_t_stride_x = 0; size_t scale_t_stride_y = 0; - if (rowwise_option != FP8BlockwiseRowwiseOption::NONE) { - NVTE_CHECK(rowwise_option == FP8BlockwiseRowwiseOption::ROWWISE_GEMM_READY || - rowwise_option == FP8BlockwiseRowwiseOption::ROWWISE_COMPACT, - "Unexpected rowwise enum value"); + if (return_rowwise) { NVTE_CHECK(input.shape == output.shape, "Input and output must have the same shape."); NVTE_CHECK(scale_inv.shape.size() == 2, "Scale dimension must be 2."); - size_t scale_k = scale_inv.shape[1]; - bool rowwise_compact = rowwise_option == FP8BlockwiseRowwiseOption::ROWWISE_COMPACT; - scale_stride_x = rowwise_compact ? 1 : scale_k; - scale_stride_y = rowwise_compact ? scale_k : 1; + scale_stride_x = scale_inv.shape[1]; + scale_stride_y = 1; } - if (columnwise_option != FP8BlockwiseColumnwiseOption::NONE) { + if (return_columnwise) { NVTE_CHECK(output_t.shape.size() == input.shape.size(), "output_t must have same number of dimensions as input."); - if (output_t.shape.size() > 0) { - if (columnwise_option == FP8BlockwiseColumnwiseOption::COLUMNWISE_GEMM_READY) { - NVTE_CHECK(output_t.shape[0] == row_length, "Wrong dimension 0 of output_t."); - for (size_t i = 1; i < output_t.shape.size(); ++i) { - NVTE_CHECK(output_t.shape.at(i) == input.shape.at(i - 1), "Wrong dimension in output_t"); - } - } else { - NVTE_CHECK(columnwise_option == FP8BlockwiseColumnwiseOption::COLUMNWISE_COMPACT, - "Unexpected columnwise option enum value"); - NVTE_CHECK(output_t.shape[0] == input.shape[0], "Wrong dimension 0 of output_t."); - NVTE_CHECK( - input.shape == output_t.shape, - "Input and output_t must have the same shape for columnwise non-transpose case."); + NVTE_CHECK(output_t.shape[0] == row_length, "Wrong dimension 0 of output_t."); + for (size_t i = 1; i < output_t.shape.size(); ++i) { + NVTE_CHECK(output_t.shape.at(i) == input.shape.at(i - 1), "Wrong dimension in output_t"); } } - if (rowwise_option != FP8BlockwiseRowwiseOption::NONE) { + if (return_rowwise) { // output may not be defined if rowwise quantization is not needed. NVTE_CHECK(output.dtype == output_t.dtype, "output and output_t need to have the same dtype."); } NVTE_CHECK(scale_inv_t.shape.size() == 2, "Scale_t dimension must be 2."); - bool columnwise_compact = columnwise_option == FP8BlockwiseColumnwiseOption::COLUMNWISE_COMPACT; - size_t scale_t_k = scale_inv_t.shape[1]; - scale_t_stride_x = columnwise_compact ? 1 : scale_t_k; - scale_t_stride_y = columnwise_compact ? scale_t_k : 1; + scale_t_stride_x = scale_inv_t.shape[1]; + scale_t_stride_y = 1; } - auto output_dtype = - rowwise_option != FP8BlockwiseRowwiseOption::NONE ? output.dtype : output_t.dtype; + auto output_dtype = return_rowwise ? output.dtype : output_t.dtype; const size_t num_blocks_x = DIVUP(row_length, (size_t)kTileDim); const size_t num_blocks_y = DIVUP(num_rows, (size_t)kTileDim); @@ -631,8 +483,8 @@ void quantize_transpose_vector_blockwise(const SimpleTensor& input, SimpleTensor reinterpret_cast(output_t.dptr), reinterpret_cast(scale_inv.dptr), reinterpret_cast(scale_inv_t.dptr), row_length, num_rows, scale_stride_x, - scale_stride_y, scale_t_stride_x, scale_t_stride_y, epsilon, rowwise_option, - columnwise_option, pow2_scale, noop_ptr);) // kAligned + scale_stride_y, scale_t_stride_x, scale_t_stride_y, epsilon, return_rowwise, + return_columnwise, pow2_scale, noop_ptr);) // kAligned ) // OutputType ) // InputType NVTE_CHECK_CUDA(cudaGetLastError()); diff --git a/transformer_engine/common/util/pybind_helper.h b/transformer_engine/common/util/pybind_helper.h index 88d7c0f865b..9c08f91f984 100644 --- a/transformer_engine/common/util/pybind_helper.h +++ b/transformer_engine/common/util/pybind_helper.h @@ -101,11 +101,6 @@ .value("NVTE_BLOCK_SCALING_2D", NVTEScalingMode::NVTE_BLOCK_SCALING_2D) \ .value("NVTE_NVFP4_1D_SCALING", NVTEScalingMode::NVTE_NVFP4_1D_SCALING) \ .value("NVTE_INVALID_SCALING", NVTEScalingMode::NVTE_INVALID_SCALING); \ - pybind11::enum_( \ - m, "Float8BlockScaleTensorFormat", pybind11::module_local()) \ - .value("GEMM_READY", transformer_engine::Float8BlockScaleTensorFormat::GEMM_READY) \ - .value("COMPACT", transformer_engine::Float8BlockScaleTensorFormat::COMPACT) \ - .value("INVALID", transformer_engine::Float8BlockScaleTensorFormat::INVALID); \ pybind11::enum_(m, "CommOverlapType", \ pybind11::module_local()) \ .value("RS", transformer_engine::CommOverlapType::RS) \ diff --git a/transformer_engine/common/util/utils.cu b/transformer_engine/common/util/utils.cu index 39d82624632..9f144bb1d97 100644 --- a/transformer_engine/common/util/utils.cu +++ b/transformer_engine/common/util/utils.cu @@ -71,12 +71,3 @@ void nvte_copy_host_to_device_via_kernel(const void *host_ptr, void *device_ptr, NVTE_CHECK_CUDA(cudaGetLastError()); } } - -void nvte_convert_pointers_to_tensor(const uint64_t *host_ptrs, NVTETensor output, int64_t count, - cudaStream_t stream) { - NVTE_API_CALL(nvte_convert_pointers_to_tensor); - using namespace transformer_engine; - Tensor *out_tensor = convertNVTETensorCheck(output); - nvte_copy_host_to_device_via_kernel(host_ptrs, out_tensor->data.dptr, - static_cast(count) * sizeof(uint64_t), stream); -} From d1d6f332878a379c8bd7e824be809f44c92b5fdc Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 19:01:14 -0800 Subject: [PATCH 05/18] [Common] Remove cast-transpose functions redundant with nvte_quantize Remove nvte_cast_transpose, nvte_cast_transpose_with_noop, nvte_cast_transpose_dbias, and nvte_cast_transpose_dbias_d{gelu,silu, relu,qgelu,srelu}. nvte_quantize and nvte_quantize_dbias[_d*] dispatch to the same kernels for delayed scaling, with the noop tensor passed through the quantization config. Explicitly instantiate the fused dbias+dact cast-transpose kernels, which those removed functions previously instantiated implicitly. Move nvte_transpose_with_noop to transpose.h and delete cast_transpose_noop.h. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tim Moon --- docs/api/c/cast_transpose_noop.rst | 9 - docs/api/c/index.rst | 1 - .../test_cast_transpose_dbias_dgelu.cu | 26 +-- tests/cpp/util/test_c_api.c | 13 +- .../transformer_engine/cast_transpose_noop.h | 44 ----- .../include/transformer_engine/transpose.h | 170 +----------------- .../common/transpose/cast_transpose.cu | 17 -- .../common/transpose/cast_transpose_fusion.cu | 105 +---------- .../common/transpose/transpose.cu | 1 - transformer_engine/pytorch/csrc/common.h | 1 - 10 files changed, 25 insertions(+), 362 deletions(-) delete mode 100644 docs/api/c/cast_transpose_noop.rst delete mode 100644 transformer_engine/common/include/transformer_engine/cast_transpose_noop.h diff --git a/docs/api/c/cast_transpose_noop.rst b/docs/api/c/cast_transpose_noop.rst deleted file mode 100644 index 0399a10f670..00000000000 --- a/docs/api/c/cast_transpose_noop.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. - Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. - - See LICENSE for license information. - -cast_transpose_noop.h -===================== - -.. doxygenfile:: cast_transpose_noop.h diff --git a/docs/api/c/index.rst b/docs/api/c/index.rst index 82024e25b02..282dff6ad22 100644 --- a/docs/api/c/index.rst +++ b/docs/api/c/index.rst @@ -14,7 +14,6 @@ directly from C/C++, without Python. transformer_engine.h activation.h - cast_transpose_noop.h cast.h cudnn.h fused_attn.h diff --git a/tests/cpp/operator/test_cast_transpose_dbias_dgelu.cu b/tests/cpp/operator/test_cast_transpose_dbias_dgelu.cu index 31eafff80f1..be901b43ead 100644 --- a/tests/cpp/operator/test_cast_transpose_dbias_dgelu.cu +++ b/tests/cpp/operator/test_cast_transpose_dbias_dgelu.cu @@ -15,7 +15,7 @@ #include #include -#include +#include #include "../test_common.h" using namespace transformer_engine; @@ -104,22 +104,22 @@ void performTest(const size_t N, const size_t H) { Tensor workspace; - nvte_cast_transpose_dbias_dgelu(input.data(), - gelu_input.data(), - output.data(), - dbias.data(), - workspace.data(), - 0); + nvte_quantize_dbias_dgelu(input.data(), + gelu_input.data(), + output.data(), + dbias.data(), + workspace.data(), + 0); workspace = Tensor("workspace", workspace.rowwise_shape(), workspace.dtype()); - nvte_cast_transpose_dbias_dgelu(input.data(), - gelu_input.data(), - output.data(), - dbias.data(), - workspace.data(), - 0); + nvte_quantize_dbias_dgelu(input.data(), + gelu_input.data(), + output.data(), + dbias.data(), + workspace.data(), + 0); cudaDeviceSynchronize(); auto err = cudaGetLastError(); diff --git a/tests/cpp/util/test_c_api.c b/tests/cpp/util/test_c_api.c index 6afab7281c2..2e38a264a37 100644 --- a/tests/cpp/util/test_c_api.c +++ b/tests/cpp/util/test_c_api.c @@ -15,7 +15,6 @@ #include #include #include -#include #include #include #include @@ -118,10 +117,6 @@ void call_every_c_api_function(void) { nvte_multi_tensor_quantize(NULL, NULL, NULL, 0, NULL); nvte_group_nvfp4_quantize_with_amax(NULL, NULL, NULL, 0, NULL, NULL); - /* cast_transpose_noop.h */ - nvte_transpose_with_noop(NULL, NULL, NULL, NULL); - nvte_cast_transpose_with_noop(NULL, NULL, NULL, NULL); - /* comm_gemm.h */ nvte_comm_gemm_ctx_create(NULL, 0, 0); nvte_comm_gemm_ctx_destroy(NULL); @@ -443,16 +438,10 @@ void call_every_c_api_function(void) { nvte_get_grouped_tensor_logical_shape(NULL); /* transpose.h */ - nvte_cast_transpose(NULL, NULL, NULL); nvte_transpose(NULL, NULL, NULL); - nvte_cast_transpose_dbias(NULL, NULL, NULL, NULL, NULL); + nvte_transpose_with_noop(NULL, NULL, NULL, NULL); nvte_fp8_transpose_dbias(NULL, NULL, NULL, NULL, NULL); nvte_multi_cast_transpose(0, NULL, NULL, NULL); - nvte_cast_transpose_dbias_dgelu(NULL, NULL, NULL, NULL, NULL, NULL); - nvte_cast_transpose_dbias_dsilu(NULL, NULL, NULL, NULL, NULL, NULL); - nvte_cast_transpose_dbias_drelu(NULL, NULL, NULL, NULL, NULL, NULL); - nvte_cast_transpose_dbias_dqgelu(NULL, NULL, NULL, NULL, NULL, NULL); - nvte_cast_transpose_dbias_dsrelu(NULL, NULL, NULL, NULL, NULL, NULL); nvte_dgeglu_cast_transpose(NULL, NULL, NULL, NULL); nvte_dswiglu_cast_transpose(NULL, NULL, NULL, NULL); nvte_dreglu_cast_transpose(NULL, NULL, NULL, NULL); diff --git a/transformer_engine/common/include/transformer_engine/cast_transpose_noop.h b/transformer_engine/common/include/transformer_engine/cast_transpose_noop.h deleted file mode 100644 index d21a28e521d..00000000000 --- a/transformer_engine/common/include/transformer_engine/cast_transpose_noop.h +++ /dev/null @@ -1,44 +0,0 @@ -/************************************************************************* - * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. - * - * See LICENSE for license information. - ************************************************************************/ - -/*! \file cast_transpose_noop.h - * \brief Transpose functions with no-op flag. - */ - -#ifndef TRANSFORMER_ENGINE_CAST_TRANSPOSE_WITH_NOOP_H_ -#define TRANSFORMER_ENGINE_CAST_TRANSPOSE_WITH_NOOP_H_ - -#include "transformer_engine.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/*! \brief Transposes the input. - * - * \param[in] input Input tensor to be cast. - * \param[in] noop If this single element tensor has non-zero value, kernel will exit immediately. - * \param[in,out] output Output tensor. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_transpose_with_noop(const NVTETensor input, const NVTETensor noop, NVTETensor output, - cudaStream_t stream); - -/*! \brief Casts and transposes the input. - * - * \param[in] input Input tensor to be cast. - * \param[in] noop If this single element tensor has non-zero value, kernel will exit immediately. - * \param[in,out] output Output quantized tensor. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_cast_transpose_with_noop(const NVTETensor input, const NVTETensor noop, NVTETensor output, - cudaStream_t stream); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // TRANSFORMER_ENGINE_CAST_TRANSPOSE_WITH_NOOP_H_ diff --git a/transformer_engine/common/include/transformer_engine/transpose.h b/transformer_engine/common/include/transformer_engine/transpose.h index b25337cfb8f..53cd8f78025 100644 --- a/transformer_engine/common/include/transformer_engine/transpose.h +++ b/transformer_engine/common/include/transformer_engine/transpose.h @@ -17,20 +17,6 @@ extern "C" { #endif -/*! \brief Cast and transpose the input. - * - * This function casts the input and produces 2 results: - * - rowwise data in `output` is the result of the cast - * - columnwise data in `output` is the transposed result of the cast. - * - * \param[in] input Input tensor of shape [N, H]. - * \param[in,out] output Result of the cast and transpose. - * Shape of the rowwise data: [N, H]. - * Shape of the columnwise data: [H, N] - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_cast_transpose(const NVTETensor input, NVTETensor output, cudaStream_t stream); - /*! \brief Transpose the input. * * Leading input dimensions are flattened for the transpose. The output @@ -42,26 +28,16 @@ void nvte_cast_transpose(const NVTETensor input, NVTETensor output, cudaStream_t */ void nvte_transpose(const NVTETensor input, NVTETensor transposed_output, cudaStream_t stream); -/*! \brief Cast and transpose the input. Additionally, reduce the input along the first dimension. - * - * This function casts the input and produces 2 results: - * - `output` is the result of the cast (rowwise data) and transposed cast (columnwise data) - * - `dbias` is the result of the reduction of the input along the first dimension. +/*! \brief Transpose the input, skipping the operation based on a no-op flag. * - * Calling this function with workspace being an empty tensor will not perform the operation, - * but instead set the shape and type of the workspace tensor to the required values. - * - * \param[in] input Input tensor of shape [N, H]. - * \param[in,out] output Result of the cast and transpose. - * Shape of the rowwise data: [N, H]. - * Shape of the columnwise data: [H, N] - * \param[out] dbias Result of the reduction of the input along the - * first dimension. Shape: [H]. - * \param[out] workspace Workspace tensor. - * \param[in] stream CUDA stream used for the operation. + * \param[in] input Input tensor to be transposed. + * \param[in] noop If this single element tensor has non-zero value, kernel will exit + * immediately. + * \param[in,out] output Output tensor. + * \param[in] stream CUDA stream used for the operation. */ -void nvte_cast_transpose_dbias(const NVTETensor input, NVTETensor output, NVTETensor dbias, - NVTETensor workspace, cudaStream_t stream); +void nvte_transpose_with_noop(const NVTETensor input, const NVTETensor noop, NVTETensor output, + cudaStream_t stream); /*! \brief Transpose the FP8 input. Additionally, reduce the input along the first dimension. * @@ -96,136 +72,6 @@ void nvte_fp8_transpose_dbias(const NVTETensor input, NVTETensor transposed_outp void nvte_multi_cast_transpose(size_t num_tensors, const NVTETensor* input_list, NVTETensor* output_list, cudaStream_t stream); -/*! \brief Compute backward of GeLU operation on the input, then cast and transpose. - * Additionally, reduce the result of the GeLU backward along the first dimension. - * - * This function produces 2 results: - * - rowwise data of `output` is equal to `cast(dact(input))` - * - columnwise data of `output` is equal to `transpose(cast(dact(input)))` - * - `dbias` is equal to `reduce(dact(input), axis=0)` - * - * Calling this function with workspace being an empty tensor will not perform the operation, - * but instead set the shape and type of the workspace tensor to the required values. - * - * \param[in] input Input tensor of shape [N, H]. - * \param[in] act_input Tensor used as input for the operation of forward activation. - * Shape [N, H]. - * \param[in,out] output Result of the cast. - * Shape of rowwise data: [N, H]. - * Shape of columnwise data: [H, N]. - * \param[out] dbias Result of the reduction of the dact(input) along the - * first dimension. Shape: [H]. - * \param[out] workspace Workspace tensor. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_cast_transpose_dbias_dgelu(const NVTETensor input, const NVTETensor act_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream); - -/*! \brief Compute backward of SiLU operation on the input, then cast and transpose. - * Additionally, reduce the result of the SiLU backward along the first dimension. - * - * This function produces 2 results: - * - rowwise data of `output` is equal to `cast(dact(input))` - * - columnwise data of `output` is equal to `transpose(cast(dact(input)))` - * - `dbias` is equal to `reduce(dact(input), axis=0)` - * - * Calling this function with workspace being an empty tensor will not perform the operation, - * but instead set the shape and type of the workspace tensor to the required values. - * - * \param[in] input Input tensor of shape [N, H]. - * \param[in] act_input Tensor used as input for the operation of forward activation. - * Shape [N, H]. - * \param[in,out] output Result of the cast. - * Shape of rowwise data: [N, H]. - * Shape of columnwise data: [H, N]. - * \param[out] dbias Result of the reduction of the dact(input) along the - * first dimension. Shape: [H]. - * \param[out] workspace Workspace tensor. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_cast_transpose_dbias_dsilu(const NVTETensor input, const NVTETensor act_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream); - -/*! \brief Compute backward of ReLU operation on the input, then cast and transpose. - * Additionally, reduce the result of the ReLU backward along the first dimension. - * - * This function produces 2 results: - * - rowwise data of `output` is equal to `cast(dact(input))` - * - columnwise data of `output` is equal to `transpose(cast(dact(input)))` - * - `dbias` is equal to `reduce(dact(input), axis=0)` - * - * Calling this function with workspace being an empty tensor will not perform the operation, - * but instead set the shape and type of the workspace tensor to the required values. - * - * \param[in] input Input tensor of shape [N, H]. - * \param[in] act_input Tensor used as input for the operation of forward activation. - * Shape [N, H]. - * \param[in,out] output Result of the cast. - * Shape of rowwise data: [N, H]. - * Shape of columnwise data: [H, N]. - * \param[out] dbias Result of the reduction of the dact(input) along the - * first dimension. Shape: [H]. - * \param[out] workspace Workspace tensor. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_cast_transpose_dbias_drelu(const NVTETensor input, const NVTETensor act_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream); - -/*! \brief Compute backward of the Quick GeLU operation on the input, then cast and transpose. - * Additionally, reduce the result of the Quick GeLU backward along the first dimension. - * - * This function produces 2 results: - * - rowwise data of `output` is equal to `cast(dact(input))` - * - columnwise data of `output` is equal to `transpose(cast(dact(input)))` - * - `dbias` is equal to `reduce(dact(input), axis=0)` - * - * Calling this function with workspace being an empty tensor will not perform the operation, - * but instead set the shape and type of the workspace tensor to the required values. - * - * \param[in] input Input tensor of shape [N, H]. - * \param[in] act_input Tensor used as input for the operation of forward activation. - * Shape [N, H]. - * \param[in,out] output Result of the cast. - * Shape of rowwise data: [N, H]. - * Shape of columnwise data: [H, N]. - * \param[out] dbias Result of the reduction of the dact(input) along the - * first dimension. Shape: [H]. - * \param[out] workspace Workspace tensor. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_cast_transpose_dbias_dqgelu(const NVTETensor input, const NVTETensor act_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream); - -/*! \brief Compute backward of the Squared ReLU operation on the input, then cast and transpose. - * Additionally, reduce the result of the Squared ReLU backward along the first dimension. - * - * This function produces 2 results: - * - rowwise data of `output` is equal to `cast(dact(input))` - * - columnwise data of `output` is equal to `transpose(cast(dact(input)))` - * - `dbias` is equal to `reduce(dact(input), axis=0)` - * - * Calling this function with workspace being an empty tensor will not perform the operation, - * but instead set the shape and type of the workspace tensor to the required values. - * - * \param[in] input Input tensor of shape [N, H]. - * \param[in] act_input Tensor used as input for the operation of forward activation. - * Shape [N, H]. - * \param[in,out] output Result of the cast. - * Shape of rowwise data: [N, H]. - * Shape of columnwise data: [H, N]. - * \param[out] dbias Result of the reduction of the dact(input) along the - * first dimension. Shape: [H]. - * \param[out] workspace Workspace tensor. - * \param[in] stream CUDA stream used for the operation. - */ -void nvte_cast_transpose_dbias_dsrelu(const NVTETensor input, const NVTETensor act_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream); - /*! \brief Computes the gated GeLU activation of the input, additionally casts and transposes * the output. * diff --git a/transformer_engine/common/transpose/cast_transpose.cu b/transformer_engine/common/transpose/cast_transpose.cu index dd27fa83ee9..eb2e6666499 100644 --- a/transformer_engine/common/transpose/cast_transpose.cu +++ b/transformer_engine/common/transpose/cast_transpose.cu @@ -5,7 +5,6 @@ ************************************************************************/ #include -#include #include #include @@ -345,19 +344,3 @@ void cast_transpose(const Tensor &input, const Tensor &noop, Tensor *output_, cu } // namespace transformer_engine::detail -void nvte_cast_transpose(const NVTETensor input, NVTETensor output, cudaStream_t stream) { - NVTE_API_CALL(nvte_cast_transpose); - using namespace transformer_engine; - auto noop = Tensor(); - transformer_engine::detail::cast_transpose(*convertNVTETensorCheck(input), noop, - convertNVTETensor(output), stream); -} - -void nvte_cast_transpose_with_noop(const NVTETensor input, const NVTETensor noop, NVTETensor output, - cudaStream_t stream) { - NVTE_API_CALL(nvte_cast_transpose_with_noop); - using namespace transformer_engine; - transformer_engine::detail::cast_transpose(*convertNVTETensorCheck(input), - *convertNVTETensorCheck(noop), - convertNVTETensor(output), stream); -} diff --git a/transformer_engine/common/transpose/cast_transpose_fusion.cu b/transformer_engine/common/transpose/cast_transpose_fusion.cu index 619e60220e6..ea7445006b4 100644 --- a/transformer_engine/common/transpose/cast_transpose_fusion.cu +++ b/transformer_engine/common/transpose/cast_transpose_fusion.cu @@ -1243,6 +1243,9 @@ template void cast_transpose_fused>( \ + const Tensor &, const Tensor *, Tensor *, Tensor *, Tensor *, cudaStream_t); \ + template void cast_transpose_fused>( \ const Tensor &, const Tensor *, Tensor *, Tensor *, Tensor *, cudaStream_t); NVTE_INSTANTIATE_ACTIVATION(relu); NVTE_INSTANTIATE_ACTIVATION(srelu); @@ -1257,108 +1260,6 @@ NVTE_INSTANTIATE_ACTIVATION(silu); using ComputeType = typename transformer_engine::fp32; -void nvte_cast_transpose_dbias(const NVTETensor input, NVTETensor output, NVTETensor dbias, - NVTETensor workspace, cudaStream_t stream) { - NVTE_API_CALL(nvte_cast_transpose_dbias); - using namespace transformer_engine; - using namespace transformer_engine::detail; - - constexpr bool IS_DBIAS = true; - constexpr bool IS_DACT = false; - constexpr bool IS_ACT = false; - - constexpr const NVTETensor activation_input = nullptr; - - cast_transpose_fused( - *convertNVTETensorCheck(input), convertNVTETensor(activation_input), - convertNVTETensor(output), convertNVTETensor(dbias), convertNVTETensor(workspace), stream); -} - -void nvte_cast_transpose_dbias_dgelu(const NVTETensor input, const NVTETensor act_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream) { - NVTE_API_CALL(nvte_cast_transpose_dbias_dgelu); - using namespace transformer_engine; - using namespace transformer_engine::detail; - - constexpr bool IS_DBIAS = true; - constexpr bool IS_DACT = true; - constexpr bool IS_ACT = false; - - cast_transpose_fused>( - *convertNVTETensorCheck(input), convertNVTETensorCheck(act_input), - convertNVTETensorCheck(output), convertNVTETensorCheck(dbias), convertNVTETensor(workspace), - stream); -} - -void nvte_cast_transpose_dbias_dsilu(const NVTETensor input, const NVTETensor silu_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream) { - NVTE_API_CALL(nvte_cast_transpose_dbias_dsilu); - using namespace transformer_engine; - using namespace transformer_engine::detail; - - constexpr bool IS_DBIAS = true; - constexpr bool IS_DACT = true; - constexpr bool IS_ACT = false; - - cast_transpose_fused>( - *convertNVTETensorCheck(input), convertNVTETensorCheck(silu_input), - convertNVTETensorCheck(output), convertNVTETensorCheck(dbias), convertNVTETensor(workspace), - stream); -} - -void nvte_cast_transpose_dbias_drelu(const NVTETensor input, const NVTETensor relu_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream) { - NVTE_API_CALL(nvte_cast_transpose_dbias_drelu); - using namespace transformer_engine; - using namespace transformer_engine::detail; - - constexpr bool IS_DBIAS = true; - constexpr bool IS_DACT = true; - constexpr bool IS_ACT = false; - - cast_transpose_fused>( - *convertNVTETensorCheck(input), convertNVTETensorCheck(relu_input), - convertNVTETensorCheck(output), convertNVTETensorCheck(dbias), convertNVTETensor(workspace), - stream); -} - -void nvte_cast_transpose_dbias_dsrelu(const NVTETensor input, const NVTETensor srelu_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream) { - NVTE_API_CALL(nvte_cast_transpose_dbias_dsrelu); - using namespace transformer_engine; - using namespace transformer_engine::detail; - - constexpr bool IS_DBIAS = true; - constexpr bool IS_DACT = true; - constexpr bool IS_ACT = false; - - cast_transpose_fused>( - *convertNVTETensorCheck(input), convertNVTETensorCheck(srelu_input), - convertNVTETensorCheck(output), convertNVTETensorCheck(dbias), convertNVTETensor(workspace), - stream); -} - -void nvte_cast_transpose_dbias_dqgelu(const NVTETensor input, const NVTETensor qgelu_input, - NVTETensor output, NVTETensor dbias, NVTETensor workspace, - cudaStream_t stream) { - NVTE_API_CALL(nvte_cast_transpose_dbias_dqgelu); - using namespace transformer_engine; - using namespace transformer_engine::detail; - - constexpr bool IS_DBIAS = true; - constexpr bool IS_DACT = true; - constexpr bool IS_ACT = false; - - cast_transpose_fused>( - *convertNVTETensorCheck(input), convertNVTETensorCheck(qgelu_input), - convertNVTETensorCheck(output), convertNVTETensorCheck(dbias), convertNVTETensor(workspace), - stream); -} - void nvte_dgeglu_cast_transpose(const NVTETensor input, const NVTETensor gated_act_input, NVTETensor output, cudaStream_t stream) { NVTE_API_CALL(nvte_dgeglu_cast_transpose); diff --git a/transformer_engine/common/transpose/transpose.cu b/transformer_engine/common/transpose/transpose.cu index 4e2b5ffb551..32eb1d792b8 100644 --- a/transformer_engine/common/transpose/transpose.cu +++ b/transformer_engine/common/transpose/transpose.cu @@ -5,7 +5,6 @@ ************************************************************************/ #include -#include #include #include diff --git a/transformer_engine/pytorch/csrc/common.h b/transformer_engine/pytorch/csrc/common.h index e85ebb491b4..0ee178241e2 100644 --- a/transformer_engine/pytorch/csrc/common.h +++ b/transformer_engine/pytorch/csrc/common.h @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include From 52e4c4cbdf3750e5d7d2ccdde6bd9c5f3a2d06bd Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 19:09:41 -0800 Subject: [PATCH 06/18] [Common] Make public C API headers include what they use Each header now directly includes the headers that declare what it uses: cuda_runtime_api.h for CUDA stream and event types, and stddef.h, stdint.h, and stdbool.h for size_t, fixed-width integers, and bool. Unused includes are removed: transformer_engine.h from cudnn.h and utils.h, stdint.h from ep.h, and cuda.h, cuda_fp8.h, and from comm_gemm_overlap.h, which now includes , , and logging.h directly. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tim Moon --- .../common/include/transformer_engine/activation.h | 3 +++ .../common/include/transformer_engine/cast.h | 3 +++ .../common/include/transformer_engine/comm_gemm.h | 5 +++-- .../common/include/transformer_engine/comm_gemm_overlap.h | 7 ++++--- .../common/include/transformer_engine/cudnn.h | 2 -- .../common/include/transformer_engine/dropout.h | 2 ++ transformer_engine/common/include/transformer_engine/ep.h | 1 - .../common/include/transformer_engine/fused_attn.h | 6 +++++- .../common/include/transformer_engine/fused_rope.h | 3 +++ .../common/include/transformer_engine/fused_router.h | 3 +++ .../common/include/transformer_engine/gemm.h | 3 +++ .../common/include/transformer_engine/hadamard_transform.h | 3 +++ .../common/include/transformer_engine/linear_attention.h | 2 ++ .../common/include/transformer_engine/multi_tensor.h | 4 ++++ .../common/include/transformer_engine/newton_schulz.h | 1 + .../common/include/transformer_engine/normalization.h | 3 +++ .../common/include/transformer_engine/padding.h | 3 +++ .../common/include/transformer_engine/permutation.h | 3 +++ .../common/include/transformer_engine/recipe.h | 4 ++++ .../common/include/transformer_engine/softmax.h | 2 ++ .../common/include/transformer_engine/swizzle.h | 4 ++++ .../common/include/transformer_engine/topk.h | 2 ++ .../common/include/transformer_engine/transpose.h | 3 +++ .../common/include/transformer_engine/utils.h | 1 - 24 files changed, 63 insertions(+), 10 deletions(-) diff --git a/transformer_engine/common/include/transformer_engine/activation.h b/transformer_engine/common/include/transformer_engine/activation.h index baf8ceeca15..421b48128ed 100644 --- a/transformer_engine/common/include/transformer_engine/activation.h +++ b/transformer_engine/common/include/transformer_engine/activation.h @@ -11,6 +11,9 @@ #ifndef TRANSFORMER_ENGINE_ACTIVATION_H_ #define TRANSFORMER_ENGINE_ACTIVATION_H_ +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/cast.h b/transformer_engine/common/include/transformer_engine/cast.h index 95f5d070978..7757fec920c 100644 --- a/transformer_engine/common/include/transformer_engine/cast.h +++ b/transformer_engine/common/include/transformer_engine/cast.h @@ -11,6 +11,9 @@ #ifndef TRANSFORMER_ENGINE_CAST_H_ #define TRANSFORMER_ENGINE_CAST_H_ +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/comm_gemm.h b/transformer_engine/common/include/transformer_engine/comm_gemm.h index b504d373717..deba05b2eb2 100644 --- a/transformer_engine/common/include/transformer_engine/comm_gemm.h +++ b/transformer_engine/common/include/transformer_engine/comm_gemm.h @@ -27,15 +27,16 @@ #ifndef TRANSFORMER_ENGINE_COMMON_COMM_GEMM_H_ #define TRANSFORMER_ENGINE_COMMON_COMM_GEMM_H_ +#include #include +#include +#include #include #include "transformer_engine.h" #ifdef __cplusplus extern "C" { -#else -#include #endif typedef struct NVTECommGemmCtx NVTECommGemmCtx; diff --git a/transformer_engine/common/include/transformer_engine/comm_gemm_overlap.h b/transformer_engine/common/include/transformer_engine/comm_gemm_overlap.h index c2fdb2cd857..c655f4ded5a 100644 --- a/transformer_engine/common/include/transformer_engine/comm_gemm_overlap.h +++ b/transformer_engine/common/include/transformer_engine/comm_gemm_overlap.h @@ -11,15 +11,16 @@ #error "comm_gemm_overlap.h is a C++ header" #endif -#include -#include +#include #include #include #include -#include +#include +#include #include "common/comm_gemm_overlap/userbuffers/userbuffers.h" +#include "common/util/logging.h" #define NVTE_COMM_OVERLAP_MAX_STREAMS 3 diff --git a/transformer_engine/common/include/transformer_engine/cudnn.h b/transformer_engine/common/include/transformer_engine/cudnn.h index fbe97300f88..b1aee5705e4 100644 --- a/transformer_engine/common/include/transformer_engine/cudnn.h +++ b/transformer_engine/common/include/transformer_engine/cudnn.h @@ -11,8 +11,6 @@ #ifndef TRANSFORMER_ENGINE_CUDNN_H_ #define TRANSFORMER_ENGINE_CUDNN_H_ -#include "transformer_engine.h" - #ifdef __cplusplus extern "C" { #endif diff --git a/transformer_engine/common/include/transformer_engine/dropout.h b/transformer_engine/common/include/transformer_engine/dropout.h index 57866abcdb8..15a961202fd 100644 --- a/transformer_engine/common/include/transformer_engine/dropout.h +++ b/transformer_engine/common/include/transformer_engine/dropout.h @@ -11,6 +11,8 @@ #ifndef TRANSFORMER_ENGINE_DROPOUT_FP8_H_ #define TRANSFORMER_ENGINE_DROPOUT_FP8_H_ +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/ep.h b/transformer_engine/common/include/transformer_engine/ep.h index 1cd432a3a0c..7d0342b927d 100644 --- a/transformer_engine/common/include/transformer_engine/ep.h +++ b/transformer_engine/common/include/transformer_engine/ep.h @@ -26,7 +26,6 @@ #include #include -#include #include #include diff --git a/transformer_engine/common/include/transformer_engine/fused_attn.h b/transformer_engine/common/include/transformer_engine/fused_attn.h index a7bd7763d43..de3814fa48c 100644 --- a/transformer_engine/common/include/transformer_engine/fused_attn.h +++ b/transformer_engine/common/include/transformer_engine/fused_attn.h @@ -11,7 +11,11 @@ #ifndef TRANSFORMER_ENGINE_FUSED_ATTN_H_ #define TRANSFORMER_ENGINE_FUSED_ATTN_H_ -#include "stdint.h" +#include +#include +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/fused_rope.h b/transformer_engine/common/include/transformer_engine/fused_rope.h index f0e4540b7cc..b2812e476e0 100644 --- a/transformer_engine/common/include/transformer_engine/fused_rope.h +++ b/transformer_engine/common/include/transformer_engine/fused_rope.h @@ -7,6 +7,9 @@ #ifndef TRANSFORMER_ENGINE_FUSED_ROPE_H_ #define TRANSFORMER_ENGINE_FUSED_ROPE_H_ +#include +#include + #include "fused_attn.h" #include "transformer_engine.h" diff --git a/transformer_engine/common/include/transformer_engine/fused_router.h b/transformer_engine/common/include/transformer_engine/fused_router.h index 64ae877b54b..4d4848dfe34 100644 --- a/transformer_engine/common/include/transformer_engine/fused_router.h +++ b/transformer_engine/common/include/transformer_engine/fused_router.h @@ -7,6 +7,9 @@ #ifndef TRANSFORMER_ENGINE_FUSED_ROUTER_H_ #define TRANSFORMER_ENGINE_FUSED_ROUTER_H_ +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/gemm.h b/transformer_engine/common/include/transformer_engine/gemm.h index 36a5003cd74..61173c9b803 100644 --- a/transformer_engine/common/include/transformer_engine/gemm.h +++ b/transformer_engine/common/include/transformer_engine/gemm.h @@ -11,6 +11,9 @@ #ifndef TRANSFORMER_ENGINE_GEMM_H_ #define TRANSFORMER_ENGINE_GEMM_H_ +#include +#include +#include #include #include "transformer_engine.h" diff --git a/transformer_engine/common/include/transformer_engine/hadamard_transform.h b/transformer_engine/common/include/transformer_engine/hadamard_transform.h index 8f1a213cec1..573038ca830 100644 --- a/transformer_engine/common/include/transformer_engine/hadamard_transform.h +++ b/transformer_engine/common/include/transformer_engine/hadamard_transform.h @@ -11,6 +11,9 @@ #ifndef TRANSFORMER_ENGINE_HADAMARD_TRANSFORM_H_ #define TRANSFORMER_ENGINE_HADAMARD_TRANSFORM_H_ +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/linear_attention.h b/transformer_engine/common/include/transformer_engine/linear_attention.h index 55a3c29ce5d..afce018aebf 100644 --- a/transformer_engine/common/include/transformer_engine/linear_attention.h +++ b/transformer_engine/common/include/transformer_engine/linear_attention.h @@ -10,6 +10,8 @@ #ifndef TRANSFORMER_ENGINE_LINEAR_ATTENTION_H_ #define TRANSFORMER_ENGINE_LINEAR_ATTENTION_H_ +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/multi_tensor.h b/transformer_engine/common/include/transformer_engine/multi_tensor.h index ae923663ac0..3ae4b105d49 100644 --- a/transformer_engine/common/include/transformer_engine/multi_tensor.h +++ b/transformer_engine/common/include/transformer_engine/multi_tensor.h @@ -11,6 +11,10 @@ #ifndef TRANSFORMER_ENGINE_MULTI_TENSOR_H_ #define TRANSFORMER_ENGINE_MULTI_TENSOR_H_ +#include +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/newton_schulz.h b/transformer_engine/common/include/transformer_engine/newton_schulz.h index f4d22ba935e..3eb4a769d32 100644 --- a/transformer_engine/common/include/transformer_engine/newton_schulz.h +++ b/transformer_engine/common/include/transformer_engine/newton_schulz.h @@ -14,6 +14,7 @@ #ifndef TRANSFORMER_ENGINE_COMMON_NEWTON_SCHULZ_H_ #define TRANSFORMER_ENGINE_COMMON_NEWTON_SCHULZ_H_ +#include #include #include diff --git a/transformer_engine/common/include/transformer_engine/normalization.h b/transformer_engine/common/include/transformer_engine/normalization.h index b72b8abe32a..4f1dfd1dbe2 100644 --- a/transformer_engine/common/include/transformer_engine/normalization.h +++ b/transformer_engine/common/include/transformer_engine/normalization.h @@ -11,6 +11,9 @@ #ifndef TRANSFORMER_ENGINE_NORMALIZATION_H_ #define TRANSFORMER_ENGINE_NORMALIZATION_H_ +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/padding.h b/transformer_engine/common/include/transformer_engine/padding.h index 13775b65a5e..5bf723b4da7 100644 --- a/transformer_engine/common/include/transformer_engine/padding.h +++ b/transformer_engine/common/include/transformer_engine/padding.h @@ -11,6 +11,9 @@ #ifndef TRANSFORMER_ENGINE_PADDING_H_ #define TRANSFORMER_ENGINE_PADDING_H_ +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/permutation.h b/transformer_engine/common/include/transformer_engine/permutation.h index 627cff4d23d..7a28b02c761 100644 --- a/transformer_engine/common/include/transformer_engine/permutation.h +++ b/transformer_engine/common/include/transformer_engine/permutation.h @@ -7,6 +7,9 @@ #ifndef TRANSFORMER_ENGINE_PERMUTATION_H_ #define TRANSFORMER_ENGINE_PERMUTATION_H_ +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/recipe.h b/transformer_engine/common/include/transformer_engine/recipe.h index 3fb6dcde333..5faa81a2b46 100644 --- a/transformer_engine/common/include/transformer_engine/recipe.h +++ b/transformer_engine/common/include/transformer_engine/recipe.h @@ -11,6 +11,10 @@ #ifndef TRANSFORMER_ENGINE_RECIPE_H_ #define TRANSFORMER_ENGINE_RECIPE_H_ +#include +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/softmax.h b/transformer_engine/common/include/transformer_engine/softmax.h index 9e1b825acd9..bedb4b652f2 100644 --- a/transformer_engine/common/include/transformer_engine/softmax.h +++ b/transformer_engine/common/include/transformer_engine/softmax.h @@ -7,6 +7,8 @@ #ifndef TRANSFORMER_ENGINE_SOFTMAX_H_ #define TRANSFORMER_ENGINE_SOFTMAX_H_ +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/swizzle.h b/transformer_engine/common/include/transformer_engine/swizzle.h index 013b679c394..a7d1673b93e 100644 --- a/transformer_engine/common/include/transformer_engine/swizzle.h +++ b/transformer_engine/common/include/transformer_engine/swizzle.h @@ -11,6 +11,10 @@ #ifndef TRANSFORMER_ENGINE_SWIZZLE_H_ #define TRANSFORMER_ENGINE_SWIZZLE_H_ +#include +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/topk.h b/transformer_engine/common/include/transformer_engine/topk.h index 3fe9c944789..9a27f3ca38c 100644 --- a/transformer_engine/common/include/transformer_engine/topk.h +++ b/transformer_engine/common/include/transformer_engine/topk.h @@ -7,6 +7,8 @@ #ifndef TRANSFORMER_ENGINE_TOPK_H_ #define TRANSFORMER_ENGINE_TOPK_H_ +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/transpose.h b/transformer_engine/common/include/transformer_engine/transpose.h index 53cd8f78025..2aa24c5b594 100644 --- a/transformer_engine/common/include/transformer_engine/transpose.h +++ b/transformer_engine/common/include/transformer_engine/transpose.h @@ -11,6 +11,9 @@ #ifndef TRANSFORMER_ENGINE_TRANSPOSE_H_ #define TRANSFORMER_ENGINE_TRANSPOSE_H_ +#include +#include + #include "transformer_engine.h" #ifdef __cplusplus diff --git a/transformer_engine/common/include/transformer_engine/utils.h b/transformer_engine/common/include/transformer_engine/utils.h index e858a32d8cb..ff475629ef2 100644 --- a/transformer_engine/common/include/transformer_engine/utils.h +++ b/transformer_engine/common/include/transformer_engine/utils.h @@ -13,7 +13,6 @@ #include #include -#include #ifdef __cplusplus extern "C" { From 220e458d78696471f338e6d80040271a9a1e6b71 Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 19:34:55 -0800 Subject: [PATCH 07/18] [Common] Address review feedback on the C API cleanup Zero NVTETensorPack.size in nvte_tensor_pack_create, since the struct no longer has a default member initializer. Reject NVFP4 operands in the comm+GEMM overlap GEMM helper. Remove stale comments and reformat calls and forwarders affected by the _v2 renames. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tim Moon --- .../cpp/operator/test_cast_nvfp4_transpose.cu | 2 -- .../comm_gemm_overlap/comm_gemm_overlap.cpp | 2 ++ .../common/fused_attn/fused_attn.cpp | 22 +++++-------------- .../common/fused_router/fused_moe_aux_loss.cu | 2 +- .../common/gemm/cublaslt_gemm.cu | 4 ++-- .../include/transformer_engine/multi_stream.h | 2 +- .../transformer_engine/transformer_engine.h | 3 +-- .../common/transformer_engine.cpp | 1 + .../quantize_transpose_vector_blockwise.cu | 2 +- .../jax/csrc/extensions/gemm.cpp | 7 +++--- .../csrc/extensions/nvfp4_2d_partial_cast.cpp | 7 +++--- .../pytorch/csrc/extensions/router.cpp | 7 +++--- .../pytorch/csrc/extensions/transpose.cpp | 4 ++-- transformer_engine/pytorch/router.py | 5 ----- 14 files changed, 26 insertions(+), 44 deletions(-) diff --git a/tests/cpp/operator/test_cast_nvfp4_transpose.cu b/tests/cpp/operator/test_cast_nvfp4_transpose.cu index 80905fa9976..57da2c4dcd2 100644 --- a/tests/cpp/operator/test_cast_nvfp4_transpose.cu +++ b/tests/cpp/operator/test_cast_nvfp4_transpose.cu @@ -1044,8 +1044,6 @@ void performTest(float (*OP)(const float), quant_config.set_nvfp4_4over6_err_use_fast_math(use_4over6 && use_4over6_err_use_fast_math); // Call appropriate function based on operation type - // Activation functions take 3 parameters (input, output, stream) - // nvte_quantize takes 4 parameters (input, output, quant_config, stream) if (OP == &gelu) { nvte_gelu(input.data(), output.data(), 0); } else if (OP == &silu) { diff --git a/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp b/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp index 9f300b94b6d..e0d37d89f89 100644 --- a/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp +++ b/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp @@ -46,6 +46,8 @@ void launch_gemm(const TensorWrapper &A, const TensorWrapper &B, const TensorWra const TensorWrapper &bias, const TensorWrapper &pre_gelu_out, bool transa, bool transb, bool grad, const TensorWrapper &workspace, bool accumulate, bool use_split_accumulator, int sm_count, cudaStream_t stream) { + NVTE_CHECK(!is_nvfp_scaling(A.scaling_mode()) && !is_nvfp_scaling(B.scaling_mode()), + "Comm+GEMM overlap does not support NVFP4 data."); const bool with_gelu = pre_gelu_out.dptr() != nullptr; MatmulConfigWrapper config; if (grad) { diff --git a/transformer_engine/common/fused_attn/fused_attn.cpp b/transformer_engine/common/fused_attn/fused_attn.cpp index f57290aa414..eba14365244 100644 --- a/transformer_engine/common/fused_attn/fused_attn.cpp +++ b/transformer_engine/common/fused_attn/fused_attn.cpp @@ -247,10 +247,8 @@ thread_local std::string fused_attn_backend_message_buffer; } // namespace // Fused attention backend query: runs TE's specific rules first, then cuDNN's. First rejection wins. - -// Select a backend for fused attention -NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend( - NVTEFusedAttnConfig config, const char **message) { +NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend(NVTEFusedAttnConfig config, + const char **message) { NVTE_API_CALL(nvte_get_fused_attn_backend); using namespace transformer_engine; using namespace transformer_engine::fused_attn; @@ -415,15 +413,13 @@ NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend( return reject(message, "Unsupported QKV dtype qkv_dtype=" + std::to_string(cfg.qkv_dtype) + " ."); } -NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend_v2( - NVTEFusedAttnConfig config, const char **message) { +NVTE_Fused_Attn_Backend nvte_get_fused_attn_backend_v2(NVTEFusedAttnConfig config, + const char **message) { return nvte_get_fused_attn_backend(config, message); } // Fused attention forward: create a config based on the params, check which backend supports it, // and run that backend's implementation. - -// NVTE fused attention FWD with separate Q, K and V void nvte_fused_attn_fwd(NVTEFusedAttnFwdParams params) { NVTE_API_CALL(nvte_fused_attn_fwd); using namespace transformer_engine; @@ -469,14 +465,10 @@ void nvte_fused_attn_fwd(NVTEFusedAttnFwdParams params) { } } -void nvte_fused_attn_fwd_v2(NVTEFusedAttnFwdParams params) { - nvte_fused_attn_fwd(params); -} +void nvte_fused_attn_fwd_v2(NVTEFusedAttnFwdParams params) { nvte_fused_attn_fwd(params); } // Fused attention backward. Same shape as nvte_fused_attn_fwd, whose comment sketches the path; // this one asks the selector for backward support and probes the backward builders. - -// NVTE fused attention BWD with separate Q, K and V void nvte_fused_attn_bwd(NVTEFusedAttnBwdParams params) { NVTE_API_CALL(nvte_fused_attn_bwd); using namespace transformer_engine; @@ -548,9 +540,7 @@ void nvte_fused_attn_bwd(NVTEFusedAttnBwdParams params) { } } -void nvte_fused_attn_bwd_v2(NVTEFusedAttnBwdParams params) { - nvte_fused_attn_bwd(params); -} +void nvte_fused_attn_bwd_v2(NVTEFusedAttnBwdParams params) { nvte_fused_attn_bwd(params); } uint32_t nvte_get_runtime_num_segments(NVTETensor cu_seqlen, NVTETensor workspace, size_t len, cudaStream_t stream) { diff --git a/transformer_engine/common/fused_router/fused_moe_aux_loss.cu b/transformer_engine/common/fused_router/fused_moe_aux_loss.cu index 0c5cc671e82..7b4fd393258 100644 --- a/transformer_engine/common/fused_router/fused_moe_aux_loss.cu +++ b/transformer_engine/common/fused_router/fused_moe_aux_loss.cu @@ -147,7 +147,7 @@ void fused_moe_aux_loss_forward_kernel_launcher( const size_t smem_size = block_size * sizeof(CompType); check_shared_memory_capacity_num_experts(smem_size, num_cols); - // Keep coefficient placement unchanged: scale each partial before summing. + // The forward kernel scales each partial sum by C_coeff before the final reduction. const float C_coeff = (num_experts * coeff) / topk / total_num_tokens / total_num_tokens; fused_moe_aux_loss_forward_kernel <<>>(probs, tokens_per_expert, total_num_tokens, diff --git a/transformer_engine/common/gemm/cublaslt_gemm.cu b/transformer_engine/common/gemm/cublaslt_gemm.cu index 65fd90c65b7..39acade3eec 100644 --- a/transformer_engine/common/gemm/cublaslt_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_gemm.cu @@ -1126,8 +1126,8 @@ void multi_stream_cublas_gemm(const NVTETensor *A, const NVTETensor *B, NVTETens // Launch GEMM const float alpha = 1.f; const float beta = accumulate ? 1.f : 0.f; - nvte_cublas_gemm(transa, transb, &alpha, A[i], B[i], &beta, accumulate ? D[i] : nullptr, - D[i], workspace[i % num_streams], &config, + nvte_cublas_gemm(transa, transb, &alpha, A[i], B[i], &beta, accumulate ? D[i] : nullptr, D[i], + workspace[i % num_streams], &config, detail::get_compute_stream(i % num_streams)); } diff --git a/transformer_engine/common/include/transformer_engine/multi_stream.h b/transformer_engine/common/include/transformer_engine/multi_stream.h index 5c97b043df0..d806ba32f67 100644 --- a/transformer_engine/common/include/transformer_engine/multi_stream.h +++ b/transformer_engine/common/include/transformer_engine/multi_stream.h @@ -22,7 +22,7 @@ int nvte_get_num_compute_streams(void); /*! \brief Get a CUDA stream for compute operations. * - * \param[in] idx Index of the stream to retrieve.Add commentMore actions + * \param[in] idx Index of the stream to retrieve. * \return A cudaStream_t. * * This function returns a CUDA stream that can be used for compute operations. diff --git a/transformer_engine/common/include/transformer_engine/transformer_engine.h b/transformer_engine/common/include/transformer_engine/transformer_engine.h index 2888a452cdb..3093e16bec5 100644 --- a/transformer_engine/common/include/transformer_engine/transformer_engine.h +++ b/transformer_engine/common/include/transformer_engine/transformer_engine.h @@ -377,7 +377,7 @@ typedef struct NVTETensorPack { size_t size; } NVTETensorPack; -/*! \brief Create `tensors` in NVTETensorPack. +/*! \brief Create `tensors` in NVTETensorPack and set its size to 0. */ void nvte_tensor_pack_create(NVTETensorPack *pack); @@ -402,7 +402,6 @@ typedef enum NVTEQuantizationConfigAttribute { conditional early even when captured in a static CUDA graph. */ kNVTEQuantizationConfigNoopTensor = 2, - /* Value 3 is unused. */ /*! RNG state (NVTETensor with 2 elements - seed and offset */ kNVTEQuantizationConfigRNGState = 4, /*! Whether to use 2D block scaling for NVFP4 */ diff --git a/transformer_engine/common/transformer_engine.cpp b/transformer_engine/common/transformer_engine.cpp index 4b17cb3e20b..7f589b230b2 100644 --- a/transformer_engine/common/transformer_engine.cpp +++ b/transformer_engine/common/transformer_engine.cpp @@ -990,6 +990,7 @@ NVTEScalingMode nvte_tensor_scaling_mode(const NVTETensor tensor) { void nvte_tensor_pack_create(NVTETensorPack *pack) { transformer_engine::TensorAllocator::instance().Allocate( NVTE_DELAYED_TENSOR_SCALING, pack->tensors, NVTE_TENSOR_PACK_MAX_SIZE); + pack->size = 0; } void nvte_tensor_pack_destroy(NVTETensorPack *pack) { diff --git a/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu b/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu index 1a516326b97..28726cdf934 100644 --- a/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu +++ b/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu @@ -97,7 +97,7 @@ Step 2: Cast and store to output_c | ... | +-------------------------------+-------------------------------+-------------------------------+-------------------------------+ -Step 3 (if columnwise transpose is True, GEMM_READY): Transpose, cast and store to output_t +Step 3 (if columnwise output is requested): Transpose, cast and store to output_t * shard memory: 128x128 elements with type=InputType (below graph doesn't consider padding) * 8 warps * Loop 2 times diff --git a/transformer_engine/jax/csrc/extensions/gemm.cpp b/transformer_engine/jax/csrc/extensions/gemm.cpp index b6ae1fab4a2..a3fef3849c0 100644 --- a/transformer_engine/jax/csrc/extensions/gemm.cpp +++ b/transformer_engine/jax/csrc/extensions/gemm.cpp @@ -338,10 +338,9 @@ Error_Type GemmV2FFI(cudaStream_t stream, Buffer_Type lhs, Buffer_Type lhs_scale ", out_shape[1]=", out_shape[1]); // Launch TE/common kernel with swapped LHS/RHS for cuBLAS column-major order - nvte_cublas_gemm(config.rhs_transposed /*transa*/, config.lhs_transposed /*transb*/, - alpha_ptr, rhs_.data() /*A*/, lhs_.data() /*B*/, beta_ptr, - out_.data() /*C*/, out_.data() /*D*/, workspace_.data(), matmul_config, - stream); + nvte_cublas_gemm(config.rhs_transposed /*transa*/, config.lhs_transposed /*transb*/, alpha_ptr, + rhs_.data() /*A*/, lhs_.data() /*B*/, beta_ptr, out_.data() /*C*/, + out_.data() /*D*/, workspace_.data(), matmul_config, stream); } else { std::vector buffer_shape{0, 0}; DType buffer_dtype = out_dtype; diff --git a/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp b/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp index dcd833d623b..f5d3ad9bc7e 100644 --- a/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp @@ -43,10 +43,9 @@ void nvfp4_2d_partial_cast(const at::Tensor& inp, py::handle out, const at::Tens const TensorWrapper scale_cu = makeTransformerEngineTensor(scale); const TensorWrapper global_scale_cu = makeTransformerEngineTensor(global_scale); - nvte_nvfp4_2d_partial_cast(inp_cu.data(), out_cu.data(), scale_cu.data(), - global_scale_cu.data(), h, w, scale.stride(0), scale.stride(1), - start_offset, block_len, static_cast(scale_dtype), - at::cuda::getCurrentCUDAStream()); + nvte_nvfp4_2d_partial_cast(inp_cu.data(), out_cu.data(), scale_cu.data(), global_scale_cu.data(), + h, w, scale.stride(0), scale.stride(1), start_offset, block_len, + static_cast(scale_dtype), at::cuda::getCurrentCUDAStream()); } void nvfp4_multi_tensor_2d_partial_cast(std::vector inp_list, diff --git a/transformer_engine/pytorch/csrc/extensions/router.cpp b/transformer_engine/pytorch/csrc/extensions/router.cpp index f0b9ced2381..4330d65d98d 100644 --- a/transformer_engine/pytorch/csrc/extensions/router.cpp +++ b/transformer_engine/pytorch/csrc/extensions/router.cpp @@ -539,8 +539,7 @@ std::pair, DType> get_moe_aux_loss_workspace_config() { return {std::vector(shape.data, shape.data + shape.ndim), workspace.dtype()}; } -static TensorWrapper make_aux_loss_workspace(const at::Tensor &workspace, - const at::Tensor &probs) { +static TensorWrapper make_aux_loss_workspace(const at::Tensor &workspace, const at::Tensor &probs) { TORCH_CHECK(workspace.is_cuda() && workspace.device() == probs.device(), "aux-loss workspace must be on the same CUDA device as probs"); TORCH_CHECK(workspace.scalar_type() == at::kFloat && workspace.is_contiguous(), @@ -604,8 +603,8 @@ std::tuple fused_moe_aux_loss_fwd_graph_safe( auto workspace_cu = make_aux_loss_workspace(workspace, probs); nvte_fused_moe_aux_loss_forward_graph_safe( probs_cu.data(), tokens_per_expert_cu.data(), total_num_tokens_cu.data(), num_experts, - num_rows, num_cols, topk, coeff, aux_loss_cu.data(), Const_buf_cu.data(), - workspace_cu.data(), at::cuda::getCurrentCUDAStream()); + num_rows, num_cols, topk, coeff, aux_loss_cu.data(), Const_buf_cu.data(), workspace_cu.data(), + at::cuda::getCurrentCUDAStream()); return std::make_tuple(aux_loss, Const_buf); } diff --git a/transformer_engine/pytorch/csrc/extensions/transpose.cpp b/transformer_engine/pytorch/csrc/extensions/transpose.cpp index f65a7ee67d4..946f1165dc0 100644 --- a/transformer_engine/pytorch/csrc/extensions/transpose.cpp +++ b/transformer_engine/pytorch/csrc/extensions/transpose.cpp @@ -163,8 +163,8 @@ void nvfp4_compute_per_block_scale(at::Tensor block_amax, at::Tensor scale, at:: auto scale_cu = makeTransformerEngineTensor(scale); auto global_amax_cu = makeTransformerEngineTensor(global_amax); - nvte_nvfp4_compute_per_block_scale(block_amax_cu.data(), scale_cu.data(), - global_amax_cu.data(), static_cast(scale_dtype), + nvte_nvfp4_compute_per_block_scale(block_amax_cu.data(), scale_cu.data(), global_amax_cu.data(), + static_cast(scale_dtype), at::cuda::getCurrentCUDAStream()); } diff --git a/transformer_engine/pytorch/router.py b/transformer_engine/pytorch/router.py index ad78947f2e2..468b55f9c2f 100644 --- a/transformer_engine/pytorch/router.py +++ b/transformer_engine/pytorch/router.py @@ -975,11 +975,6 @@ def fused_moe_aux_loss( """Fused MoE aux loss. Supports ``torch.compile(fullgraph=True)`` with either form of ``total_num_tokens``. - The loss is computed with a fixed-order two-stage FP32 reduction, so - repeated calls with identical inputs on the same hardware and software - are bitwise reproducible. Eager calls reuse scratch per device and stream; - CUDA Graph capture uses private scratch that is reused on replay. - Parameters ---------- probs : torch.Tensor in fp32/bf16/fp16 From a1285378099f002abbe1a6fbd171a5a579f78648 Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 19:50:34 -0800 Subject: [PATCH 08/18] Fix broken Doxygen comments Signed-off-by: Tim Moon --- .../common/include/transformer_engine/transformer_engine.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/transformer_engine/common/include/transformer_engine/transformer_engine.h b/transformer_engine/common/include/transformer_engine/transformer_engine.h index 3093e16bec5..f99ff866085 100644 --- a/transformer_engine/common/include/transformer_engine/transformer_engine.h +++ b/transformer_engine/common/include/transformer_engine/transformer_engine.h @@ -364,12 +364,12 @@ void nvte_get_tensor_param_v2(const NVTETensor tensor, NVTETensorParam param, vo */ NVTEScalingMode nvte_tensor_scaling_mode(const NVTETensor tensor); -/*! \struct NVTETensorPack - \brief Pack of tensors, generally used for auxiliary outputs. - */ /*! Max number of tensors in an NVTETensorPack. */ #define NVTE_TENSOR_PACK_MAX_SIZE 10 +/*! \struct NVTETensorPack + \brief Pack of tensors, generally used for auxiliary outputs. + */ typedef struct NVTETensorPack { /*! Wrappers of tensors. They do not hold the associated memory. */ NVTETensor tensors[NVTE_TENSOR_PACK_MAX_SIZE]; From 6b7f1a9f1c695f9bf001f7925015c0bde9d3e532 Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 20:20:50 -0800 Subject: [PATCH 09/18] [Docs] Document typedef'd C API types once The public C API headers now typedef their enums and structs, which made Doxygen emit both the tag and the typedef and Sphinx report duplicate C++ declarations. Enable TYPEDEF_HIDES_STRUCT so each type is documented once under its typedef name. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tim Moon --- docs/Doxyfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/Doxyfile b/docs/Doxyfile index 2c593e45948..8edc8e6101c 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -426,7 +426,7 @@ INLINE_SIMPLE_STRUCTS = NO # types are typedef'ed and only the typedef is referenced, never the tag name. # The default value is: NO. -TYPEDEF_HIDES_STRUCT = NO +TYPEDEF_HIDES_STRUCT = YES # The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This # cache is used to resolve symbols given their name and scope. Since this can be From acdf8817090ca50b728390055114aca4efff0641 Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 20:27:11 -0800 Subject: [PATCH 10/18] [Common] Use int template parameters for the NVFP4 4over6 mode Building the 4over6 kernels with nvcc fails with "wrong number of template arguments" for quantize_4over6_kernel::Config now that NVTENVFP44Over6Mode is a typedef'd C enum. Take the mode as an int template parameter in Config and compute_error_rn. Config::mode keeps the enum type, and enum values still convert implicitly, so callers and the NVRTC source are unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tim Moon --- .../common/cast/nvfp4/quantize_4over6_kernel.cuh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh b/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh index cf69b3b4262..a17e75ee3a7 100644 --- a/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh +++ b/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh @@ -61,9 +61,11 @@ constexpr int kPackedWordsPerGroup = 2; static_assert(kTileRows == kPipelineStages * kStageRows); static_assert(kStageRows % kGroupSize == 0); -template +// The mode is an int template parameter because nvcc mishandles the typedef'd C enum +// NVTENVFP44Over6Mode as a template parameter type when generating host code. +template struct Config { - static constexpr NVTENVFP44Over6Mode mode = kMode; + static constexpr NVTENVFP44Over6Mode mode = static_cast(kMode); static constexpr bool err_use_fast_math = kErrUseFastMath; }; @@ -90,7 +92,7 @@ struct FP16ErrorScalePair { uint32_t map6; }; -template +template __device__ __forceinline__ float compute_error_rn(const float diff) { if constexpr (kMode == kNVTENVFP44Over6MinMSE) { return __fmul_rn(diff, diff); From 0328a1b54c10a3faf8aac1c3e3b30138d7f53188 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:28:17 +0000 Subject: [PATCH 11/18] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../common/fused_router/fused_moe_aux_loss.cu | 20 +++++++------ .../fused_score_for_moe_aux_loss.cu | 20 +++++++------ .../fused_topk_with_score_function.cu | 28 +++++++++---------- .../include/transformer_engine/fused_router.h | 23 ++++++++------- .../transformer_engine/transformer_engine.h | 1 - .../common/transpose/cast_transpose.cu | 1 - .../quantize_transpose_vector_blockwise.cu | 17 ++++++----- .../pytorch/csrc/extensions/activation.cpp | 4 +-- .../pytorch/csrc/extensions/transpose.cpp | 18 ++++++------ transformer_engine/pytorch/csrc/quantizer.cpp | 18 +++++------- 10 files changed, 77 insertions(+), 73 deletions(-) diff --git a/transformer_engine/common/fused_router/fused_moe_aux_loss.cu b/transformer_engine/common/fused_router/fused_moe_aux_loss.cu index 7b4fd393258..b905efefd4a 100644 --- a/transformer_engine/common/fused_router/fused_moe_aux_loss.cu +++ b/transformer_engine/common/fused_router/fused_moe_aux_loss.cu @@ -124,10 +124,12 @@ __global__ void reduce_aux_loss_partials(const float* partial_sums, int num_part * Kernel launcher -- simplified (no cluster launch). * ------------------------------------------------------------------------- */ template -void fused_moe_aux_loss_forward_kernel_launcher( - const DataType* probs, const IndexType* tokens_per_expert, int total_num_tokens, - int num_experts, int num_rows, int num_cols, int topk, float coeff, DataType* aux_loss, - float* Coeff_buf, cudaStream_t stream, float* partial_sums) { +void fused_moe_aux_loss_forward_kernel_launcher(const DataType* probs, + const IndexType* tokens_per_expert, + int total_num_tokens, int num_experts, int num_rows, + int num_cols, int topk, float coeff, + DataType* aux_loss, float* Coeff_buf, + cudaStream_t stream, float* partial_sums) { NVTE_CHECK(num_cols > 0, "num_cols must be positive, got ", num_cols); NVTE_CHECK(num_experts > 0, "num_experts must be positive, got ", num_experts); NVTE_CHECK(static_cast(num_rows) * num_cols <= INT_MAX, @@ -358,10 +360,12 @@ void nvte_fused_moe_aux_loss_forward_v2(const NVTETensor probs, const NVTETensor num_cols, topk, coeff, aux_loss, Const_buf, workspace, stream); } -void nvte_fused_moe_aux_loss_forward_graph_safe( - const NVTETensor probs, const NVTETensor tokens_per_expert, const NVTETensor total_num_tokens, - int num_experts, int num_rows, int num_cols, int topk, float coeff, NVTETensor aux_loss, - NVTETensor Const_buf, NVTETensor workspace, cudaStream_t stream) { +void nvte_fused_moe_aux_loss_forward_graph_safe(const NVTETensor probs, + const NVTETensor tokens_per_expert, + const NVTETensor total_num_tokens, int num_experts, + int num_rows, int num_cols, int topk, float coeff, + NVTETensor aux_loss, NVTETensor Const_buf, + NVTETensor workspace, cudaStream_t stream) { NVTE_API_CALL(nvte_fused_moe_aux_loss_forward_graph_safe); using namespace transformer_engine; auto& scratch = *convertNVTETensorCheck(workspace); diff --git a/transformer_engine/common/fused_router/fused_score_for_moe_aux_loss.cu b/transformer_engine/common/fused_router/fused_score_for_moe_aux_loss.cu index 87d696710d9..7a12a9f0a33 100644 --- a/transformer_engine/common/fused_router/fused_score_for_moe_aux_loss.cu +++ b/transformer_engine/common/fused_router/fused_score_for_moe_aux_loss.cu @@ -660,10 +660,12 @@ void fused_score_for_moe_aux_loss_backward(const Tensor &intermediate_output, } // namespace fused_router } // namespace transformer_engine -void nvte_fused_score_for_moe_aux_loss_forward( - const NVTETensor logits, int num_tokens, int num_experts, int topk, int score_function, - NVTETensor scores, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, - const NVTETensor intermediate_output, cudaStream_t stream) { +void nvte_fused_score_for_moe_aux_loss_forward(const NVTETensor logits, int num_tokens, + int num_experts, int topk, int score_function, + NVTETensor scores, NVTETensor routing_map, + NVTERoutingMapFormat routing_map_format, + const NVTETensor intermediate_output, + cudaStream_t stream) { NVTE_API_CALL(nvte_fused_score_for_moe_aux_loss_forward); using namespace transformer_engine; fused_router::fused_score_for_moe_aux_loss_forward( @@ -672,10 +674,12 @@ void nvte_fused_score_for_moe_aux_loss_forward( *convertNVTETensorCheck(intermediate_output), stream); } -void nvte_fused_score_for_moe_aux_loss_forward_v2( - const NVTETensor logits, int num_tokens, int num_experts, int topk, int score_function, - NVTETensor scores, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, - const NVTETensor intermediate_output, cudaStream_t stream) { +void nvte_fused_score_for_moe_aux_loss_forward_v2(const NVTETensor logits, int num_tokens, + int num_experts, int topk, int score_function, + NVTETensor scores, NVTETensor routing_map, + NVTERoutingMapFormat routing_map_format, + const NVTETensor intermediate_output, + cudaStream_t stream) { nvte_fused_score_for_moe_aux_loss_forward(logits, num_tokens, num_experts, topk, score_function, scores, routing_map, routing_map_format, intermediate_output, stream); diff --git a/transformer_engine/common/fused_router/fused_topk_with_score_function.cu b/transformer_engine/common/fused_router/fused_topk_with_score_function.cu index 0b54df71929..b0373b68fde 100644 --- a/transformer_engine/common/fused_router/fused_topk_with_score_function.cu +++ b/transformer_engine/common/fused_router/fused_topk_with_score_function.cu @@ -1726,11 +1726,10 @@ void nvte_fused_topk_with_score_function_forward_v2( int num_groups, int group_topk, float scaling_factor, int score_function, const NVTETensor expert_bias, NVTETensor probs, NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, NVTETensor intermediate_output, cudaStream_t stream) { - nvte_fused_topk_with_score_function_forward(logits, num_tokens, num_experts, topk, - use_pre_softmax, num_groups, group_topk, - scaling_factor, score_function, expert_bias, probs, - routing_map, routing_map_format, intermediate_output, - stream); + nvte_fused_topk_with_score_function_forward( + logits, num_tokens, num_experts, topk, use_pre_softmax, num_groups, group_topk, + scaling_factor, score_function, expert_bias, probs, routing_map, routing_map_format, + intermediate_output, stream); } void nvte_fused_topk_with_score_function_forward_with_indices( @@ -1801,11 +1800,13 @@ void nvte_qb_histogram_accumulate(const NVTETensor raw_scores, const NVTETensor *convertNVTETensorCheck(bin_bounds), *convertNVTETensorCheck(histogram), stream); } -void nvte_fused_topk_with_score_function_backward( - const NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, - const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, - int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, - NVTETensor grad_logits, cudaStream_t stream) { +void nvte_fused_topk_with_score_function_backward(const NVTETensor routing_map, + NVTERoutingMapFormat routing_map_format, + const NVTETensor intermediate_output, + const NVTETensor grad_probs, int num_tokens, + int num_experts, int topk, bool use_pre_softmax, + float scaling_factor, int score_function, + NVTETensor grad_logits, cudaStream_t stream) { NVTE_API_CALL(nvte_fused_topk_with_score_function_backward); using namespace transformer_engine; fused_router::fused_topk_with_score_function_backward( @@ -1820,10 +1821,9 @@ void nvte_fused_topk_with_score_function_backward_v2( const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, NVTETensor grad_logits, cudaStream_t stream) { - nvte_fused_topk_with_score_function_backward(routing_map, routing_map_format, intermediate_output, - grad_probs, num_tokens, num_experts, topk, - use_pre_softmax, scaling_factor, score_function, - grad_logits, stream); + nvte_fused_topk_with_score_function_backward( + routing_map, routing_map_format, intermediate_output, grad_probs, num_tokens, num_experts, + topk, use_pre_softmax, scaling_factor, score_function, grad_logits, stream); } void nvte_fused_topk_with_score_function_backward_with_indices( diff --git a/transformer_engine/common/include/transformer_engine/fused_router.h b/transformer_engine/common/include/transformer_engine/fused_router.h index 4d4848dfe34..7a3c38132fd 100644 --- a/transformer_engine/common/include/transformer_engine/fused_router.h +++ b/transformer_engine/common/include/transformer_engine/fused_router.h @@ -163,14 +163,11 @@ void nvte_fused_topk_with_score_function_backward(const NVTETensor routing_map, * * \deprecated Use nvte_fused_topk_with_score_function_backward instead. */ -void nvte_fused_topk_with_score_function_backward_v2(const NVTETensor routing_map, - NVTERoutingMapFormat routing_map_format, - const NVTETensor intermediate_output, - const NVTETensor grad_probs, int num_tokens, - int num_experts, int topk, - bool use_pre_softmax, float scaling_factor, - int score_function, NVTETensor grad_logits, - cudaStream_t stream); +void nvte_fused_topk_with_score_function_backward_v2( + const NVTETensor routing_map, NVTERoutingMapFormat routing_map_format, + const NVTETensor intermediate_output, const NVTETensor grad_probs, int num_tokens, + int num_experts, int topk, bool use_pre_softmax, float scaling_factor, int score_function, + NVTETensor grad_logits, cudaStream_t stream); /*! \brief Backward pass for fused topk + score function with dense top-k indices. * @@ -361,10 +358,12 @@ void nvte_fused_moe_aux_loss_forward_v2(const NVTETensor probs, const NVTETensor * \param[in] total_num_tokens 0-dim int64 GPU tensor with the total token count. * Other parameters as in :c:func:`nvte_fused_moe_aux_loss_forward`. */ -void nvte_fused_moe_aux_loss_forward_graph_safe( - const NVTETensor probs, const NVTETensor tokens_per_expert, const NVTETensor total_num_tokens, - int num_experts, int num_rows, int num_cols, int topk, float coeff, NVTETensor aux_loss, - NVTETensor Const_buf, NVTETensor workspace, cudaStream_t stream); +void nvte_fused_moe_aux_loss_forward_graph_safe(const NVTETensor probs, + const NVTETensor tokens_per_expert, + const NVTETensor total_num_tokens, int num_experts, + int num_rows, int num_cols, int topk, float coeff, + NVTETensor aux_loss, NVTETensor Const_buf, + NVTETensor workspace, cudaStream_t stream); /*! \brief Deprecated alias for nvte_fused_moe_aux_loss_forward_graph_safe. * diff --git a/transformer_engine/common/include/transformer_engine/transformer_engine.h b/transformer_engine/common/include/transformer_engine/transformer_engine.h index f99ff866085..3aca997dbf7 100644 --- a/transformer_engine/common/include/transformer_engine/transformer_engine.h +++ b/transformer_engine/common/include/transformer_engine/transformer_engine.h @@ -15,7 +15,6 @@ #include #include #include - #include #ifdef __cplusplus diff --git a/transformer_engine/common/transpose/cast_transpose.cu b/transformer_engine/common/transpose/cast_transpose.cu index eb2e6666499..3a9874a7e16 100644 --- a/transformer_engine/common/transpose/cast_transpose.cu +++ b/transformer_engine/common/transpose/cast_transpose.cu @@ -343,4 +343,3 @@ void cast_transpose(const Tensor &input, const Tensor &noop, Tensor *output_, cu } } // namespace transformer_engine::detail - diff --git a/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu b/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu index 28726cdf934..502de6d3a82 100644 --- a/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu +++ b/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu @@ -141,13 +141,16 @@ static_assert(kNumThreadsStore <= kThreadsPerWarp, "kNumThreadsStore must be <= constexpr int kNumWarps = kThreadsPerBlock / kThreadsPerWarp; template -__global__ void __launch_bounds__(kThreadsPerBlock) block_scaled_1d_cast_transpose_kernel( - const IType* const input, OType* const output_c, OType* const output_t, - CType* const tile_scales_inv_c, CType* const tile_scales_inv_t, const size_t row_length, - const size_t num_rows, const size_t scale_stride_x, const size_t scale_stride_y, - const size_t scale_t_stride_x, const size_t scale_t_stride_y, const float epsilon, - const bool return_rowwise, const bool return_columnwise, const bool pow_2_scaling, - const float* noop_ptr) { +__global__ void __launch_bounds__(kThreadsPerBlock) + block_scaled_1d_cast_transpose_kernel(const IType* const input, OType* const output_c, + OType* const output_t, CType* const tile_scales_inv_c, + CType* const tile_scales_inv_t, const size_t row_length, + const size_t num_rows, const size_t scale_stride_x, + const size_t scale_stride_y, + const size_t scale_t_stride_x, + const size_t scale_t_stride_y, const float epsilon, + const bool return_rowwise, const bool return_columnwise, + const bool pow_2_scaling, const float* noop_ptr) { // skip execution if noop if (noop_ptr != nullptr && noop_ptr[0] == 1.0f) { return; diff --git a/transformer_engine/pytorch/csrc/extensions/activation.cpp b/transformer_engine/pytorch/csrc/extensions/activation.cpp index d5aefb99076..44bfed91281 100644 --- a/transformer_engine/pytorch/csrc/extensions/activation.cpp +++ b/transformer_engine/pytorch/csrc/extensions/activation.cpp @@ -348,13 +348,13 @@ py::object dsituglu(const at::Tensor& grad, const at::Tensor& input, py::handle py::object clamped_swiglu(const at::Tensor& input, py::handle quantizer, float limit, float alpha, float glu_linear_offset) { return activation_helper(input, quantizer, 2, limit, alpha, - glu_linear_offset); + glu_linear_offset); } py::object clamped_dswiglu(const at::Tensor& grad, const at::Tensor& input, py::handle quantizer, float limit, float alpha, float glu_linear_offset) { return dactivation_helper(grad, input, quantizer, limit, alpha, - glu_linear_offset); + glu_linear_offset); } /* Scaled activation helpers (activation + per-row scale via nvte_scaled_*). */ diff --git a/transformer_engine/pytorch/csrc/extensions/transpose.cpp b/transformer_engine/pytorch/csrc/extensions/transpose.cpp index 946f1165dc0..45cacecd7a4 100644 --- a/transformer_engine/pytorch/csrc/extensions/transpose.cpp +++ b/transformer_engine/pytorch/csrc/extensions/transpose.cpp @@ -141,11 +141,11 @@ void nvfp4_expand_scale_to_fp8(at::Tensor input, at::Tensor output, int64_t tile auto output_cu = makeTransformerEngineTensor( output.data_ptr(), std::vector{out_shape[0], out_shape[1]}, DType::kByte); - nvte_nvfp4_expand_scale_to_fp8( - input_cu.data(), output_cu.data(), static_cast(tile_rows), - static_cast(tile_cols), static_cast(rows_padded), - static_cast(block_len), static_cast(scale_dtype), - at::cuda::getCurrentCUDAStream()); + nvte_nvfp4_expand_scale_to_fp8(input_cu.data(), output_cu.data(), static_cast(tile_rows), + static_cast(tile_cols), static_cast(rows_padded), + static_cast(block_len), + static_cast(scale_dtype), + at::cuda::getCurrentCUDAStream()); } void nvfp4_compute_per_block_scale(at::Tensor block_amax, at::Tensor scale, at::Tensor global_amax, @@ -248,10 +248,10 @@ void nvfp4_multi_tensor_fused_scale( auto target_scale_cu = makeTransformerEngineTensor(target_scale); auto target_amax_cu = makeTransformerEngineTensor(target_amax); - nvte_nvfp4_fused_scale( - block_amax_cu.data(), global_amax_cu.data(), per_block_scale_cu.data(), - target_scale_cu.data(), target_amax_cu.data(), tile_rows, tile_cols, rows_padded, - static_cast(block_len), static_cast(scale_dtype), stream); + nvte_nvfp4_fused_scale(block_amax_cu.data(), global_amax_cu.data(), per_block_scale_cu.data(), + target_scale_cu.data(), target_amax_cu.data(), tile_rows, tile_cols, + rows_padded, static_cast(block_len), + static_cast(scale_dtype), stream); } } diff --git a/transformer_engine/pytorch/csrc/quantizer.cpp b/transformer_engine/pytorch/csrc/quantizer.cpp index 03776999e1d..d086a2a1b9d 100644 --- a/transformer_engine/pytorch/csrc/quantizer.cpp +++ b/transformer_engine/pytorch/csrc/quantizer.cpp @@ -637,9 +637,8 @@ void Float8Quantizer::quantize(const TensorWrapper& input, TensorWrapper& out, if (noop_flag) { quant_config.set_noop_tensor(noop_flag->data()); } - NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); - }); + NVTE_SCOPED_GIL_RELEASE( + { nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); }); } Float8CurrentScalingQuantizer::Float8CurrentScalingQuantizer(const py::handle& quantizer) @@ -1431,9 +1430,8 @@ void Float8BlockQuantizer::quantize(const TensorWrapper& input, TensorWrapper& o } quant_config.set_force_pow_2_scales(force_pow_2_scales); quant_config.set_amax_epsilon(amax_epsilon); - NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); - }); + NVTE_SCOPED_GIL_RELEASE( + { nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); }); } std::vector Float8BlockQuantizer::get_scale_shape(const std::vector& shape, @@ -1840,9 +1838,8 @@ void MXFP8Quantizer::quantize(const TensorWrapper& input, TensorWrapper& out, if (this->with_2d_quantization) { quant_config.set_mxfp8_2d_quantization(true); } - NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); - }); + NVTE_SCOPED_GIL_RELEASE( + { nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); }); } std::vector MXFP8Quantizer::get_scale_shape(const std::vector& shape, @@ -2558,8 +2555,7 @@ void NVFP4Quantizer::quantize_with_rht_unfused_helper( // Quantize kernel will treat everything as rowwise input/output, which is // intended. NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize(rht_output_t_cpp.data(), out_transpose.data(), quant_config_columnwise, - stream); + nvte_quantize(rht_output_t_cpp.data(), out_transpose.data(), quant_config_columnwise, stream); }); } } From a6ea70bfd78a06767672de57587ab4a85e0f3ecc Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Tue, 1 Dec 2026 21:03:22 -0800 Subject: [PATCH 12/18] Debug compile error with C enum template arg Signed-off-by: Tim Moon --- .../common/cast/nvfp4/quantize_4over6_kernel.cuh | 3 +-- transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh b/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh index a17e75ee3a7..d1b98bd8936 100644 --- a/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh +++ b/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh @@ -61,8 +61,7 @@ constexpr int kPackedWordsPerGroup = 2; static_assert(kTileRows == kPipelineStages * kStageRows); static_assert(kStageRows % kGroupSize == 0); -// The mode is an int template parameter because nvcc mishandles the typedef'd C enum -// NVTENVFP44Over6Mode as a template parameter type when generating host code. +// The mode is an int to hackily work around a compilation error with C enum template args. template struct Config { static constexpr NVTENVFP44Over6Mode mode = static_cast(kMode); diff --git a/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh b/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh index fb5b4df4ecc..432a985c899 100644 --- a/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh +++ b/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh @@ -172,7 +172,7 @@ void quantize_4over6(const Tensor &input, const Tensor *noop, Tensor *output, quant_config->nvfp4_4over6_mode, MODE, TRANSFORMER_ENGINE_SWITCH_CONDITION( quant_config->nvfp4_4over6_err_use_fast_math, ERR_USE_FAST_MATH, { - using Cfg = quantize_4over6_kernel::Config; + using Cfg = quantize_4over6_kernel::Config(MODE), ERR_USE_FAST_MATH>; TRANSFORMER_ENGINE_TYPE_SWITCH_INPUT( input.dtype(), IType, quantize_4over6_kernel::launch_quantize_4over6 Date: Wed, 2 Dec 2026 05:05:38 +0000 Subject: [PATCH 13/18] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh b/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh index 432a985c899..c72cf8d5b93 100644 --- a/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh +++ b/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh @@ -172,7 +172,8 @@ void quantize_4over6(const Tensor &input, const Tensor *noop, Tensor *output, quant_config->nvfp4_4over6_mode, MODE, TRANSFORMER_ENGINE_SWITCH_CONDITION( quant_config->nvfp4_4over6_err_use_fast_math, ERR_USE_FAST_MATH, { - using Cfg = quantize_4over6_kernel::Config(MODE), ERR_USE_FAST_MATH>; + using Cfg = + quantize_4over6_kernel::Config(MODE), ERR_USE_FAST_MATH>; TRANSFORMER_ENGINE_TYPE_SWITCH_INPUT( input.dtype(), IType, quantize_4over6_kernel::launch_quantize_4over6 Date: Tue, 1 Dec 2026 21:21:00 -0800 Subject: [PATCH 14/18] Revert changes to NVFP4 4over6 enum Signed-off-by: Tim Moon --- .../common/cast/nvfp4/quantize_4over6_kernel.cuh | 7 +++---- .../common/cast/nvfp4/quantize_4over6_nvfp4.cuh | 3 +-- .../common/include/transformer_engine/nvfp4/4over6.h | 4 ++-- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh b/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh index d1b98bd8936..cf69b3b4262 100644 --- a/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh +++ b/transformer_engine/common/cast/nvfp4/quantize_4over6_kernel.cuh @@ -61,10 +61,9 @@ constexpr int kPackedWordsPerGroup = 2; static_assert(kTileRows == kPipelineStages * kStageRows); static_assert(kStageRows % kGroupSize == 0); -// The mode is an int to hackily work around a compilation error with C enum template args. -template +template struct Config { - static constexpr NVTENVFP44Over6Mode mode = static_cast(kMode); + static constexpr NVTENVFP44Over6Mode mode = kMode; static constexpr bool err_use_fast_math = kErrUseFastMath; }; @@ -91,7 +90,7 @@ struct FP16ErrorScalePair { uint32_t map6; }; -template +template __device__ __forceinline__ float compute_error_rn(const float diff) { if constexpr (kMode == kNVTENVFP44Over6MinMSE) { return __fmul_rn(diff, diff); diff --git a/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh b/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh index c72cf8d5b93..fb5b4df4ecc 100644 --- a/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh +++ b/transformer_engine/common/cast/nvfp4/quantize_4over6_nvfp4.cuh @@ -172,8 +172,7 @@ void quantize_4over6(const Tensor &input, const Tensor *noop, Tensor *output, quant_config->nvfp4_4over6_mode, MODE, TRANSFORMER_ENGINE_SWITCH_CONDITION( quant_config->nvfp4_4over6_err_use_fast_math, ERR_USE_FAST_MATH, { - using Cfg = - quantize_4over6_kernel::Config(MODE), ERR_USE_FAST_MATH>; + using Cfg = quantize_4over6_kernel::Config; TRANSFORMER_ENGINE_TYPE_SWITCH_INPUT( input.dtype(), IType, quantize_4over6_kernel::launch_quantize_4over6 Date: Wed, 2 Dec 2026 12:08:10 -0800 Subject: [PATCH 15/18] Synchronize and shut down NCCL at end of TE ops Userbuffers test Signed-off-by: Tim Moon --- .../distributed/test_fusible_ops_with_userbuffers.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/pytorch/distributed/test_fusible_ops_with_userbuffers.py b/tests/pytorch/distributed/test_fusible_ops_with_userbuffers.py index 6c2cb6d6bbf..475362df9fb 100644 --- a/tests/pytorch/distributed/test_fusible_ops_with_userbuffers.py +++ b/tests/pytorch/distributed/test_fusible_ops_with_userbuffers.py @@ -499,9 +499,11 @@ def main() -> None: parser.add_argument("--use-cublasmp", action="store_true") args = parser.parse_args() - # Run parallel tests if needed - if args.parallel: + # Nothing to be done if no parallel tests are needed + if not args.parallel: + return + try: # Model config model_config = ModelConfig( sequence_length=args.sequence_length, @@ -545,7 +547,13 @@ def main() -> None: # Clean up te.module.base.destroy_ub() + torch.distributed.barrier(group) + torch.cuda.synchronize() + finally: + # Stop NCCL background work before the CUDA runtime shuts down. + if torch.distributed.is_initialized(): + torch.distributed.destroy_process_group() if __name__ == "__main__": main() From 9006a39dce667c641eab3d245a9e2dfcde0f3e22 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:09:52 +0000 Subject: [PATCH 16/18] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- tests/pytorch/distributed/test_fusible_ops_with_userbuffers.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/pytorch/distributed/test_fusible_ops_with_userbuffers.py b/tests/pytorch/distributed/test_fusible_ops_with_userbuffers.py index 475362df9fb..635acf05d4f 100644 --- a/tests/pytorch/distributed/test_fusible_ops_with_userbuffers.py +++ b/tests/pytorch/distributed/test_fusible_ops_with_userbuffers.py @@ -555,5 +555,6 @@ def main() -> None: if torch.distributed.is_initialized(): torch.distributed.destroy_process_group() + if __name__ == "__main__": main() From 8790ffaaac867209d9db9bcaf86454cf1e405979 Mon Sep 17 00:00:00 2001 From: Tim Moon Date: Sat, 5 Dec 2026 00:33:15 +0000 Subject: [PATCH 17/18] Fix merge conflicts Signed-off-by: Tim Moon --- tests/cpp/operator/test_cast_mxfp4.cu | 6 ++--- tests/cpp/operator/test_gemm.cu | 8 +++--- tests/cpp/util/test_c_api.c | 26 +++---------------- transformer_engine/pytorch/csrc/quantizer.cpp | 2 +- 4 files changed, 12 insertions(+), 30 deletions(-) diff --git a/tests/cpp/operator/test_cast_mxfp4.cu b/tests/cpp/operator/test_cast_mxfp4.cu index ec8b447803e..d3ddc22d416 100644 --- a/tests/cpp/operator/test_cast_mxfp4.cu +++ b/tests/cpp/operator/test_cast_mxfp4.cu @@ -141,7 +141,7 @@ void check_swizzled(Tensor &input, Tensor &swizzled, const std::vector & Tensor compact("compact", shape, DType::kFloat4E2M1, rowwise, !rowwise, NVTE_MXFP4_1D_SCALING); Tensor ref("ref", shape, DType::kFloat4E2M1, rowwise, !rowwise, NVTE_MXFP4_1D_SCALING); ref.set_with_gemm_swizzled_scales(true); - nvte_quantize(input.data(), compact.data(), 0); + nvte_quantize(input.data(), compact.data(), nullptr, 0); cudaMemcpy(rowwise ? ref.rowwise_dptr() : ref.columnwise_dptr(), rowwise ? compact.rowwise_dptr() : compact.columnwise_dptr(), data_bytes, cudaMemcpyDeviceToDevice); @@ -185,7 +185,7 @@ void performTest(const std::vector &shape, bool rowwise, bool columnwise fillUniform(&input); quantized.set_with_gemm_swizzled_scales(swizzled); - nvte_quantize(input.data(), quantized.data(), 0); + nvte_quantize(input.data(), quantized.data(), nullptr, 0); nvte_dequantize(quantized.data(), output.data(), 0); cudaDeviceSynchronize(); auto err = cudaGetLastError(); @@ -249,7 +249,7 @@ TEST(CastMXFP4Test, RejectsMismatchedOutputShape) { Tensor input("input", std::vector{256, 128}, DType::kBFloat16); Tensor output("output", std::vector{128, 128}, DType::kFloat4E2M1, true, true, NVTE_MXFP4_1D_SCALING); - EXPECT_THROW(nvte_quantize(input.data(), output.data(), 0), std::runtime_error); + EXPECT_THROW(nvte_quantize(input.data(), output.data(), nullptr, 0), std::runtime_error); } #endif // FP4_TYPE_SUPPORTED diff --git a/tests/cpp/operator/test_gemm.cu b/tests/cpp/operator/test_gemm.cu index a1c4ade63a5..2503d26249b 100644 --- a/tests/cpp/operator/test_gemm.cu +++ b/tests/cpp/operator/test_gemm.cu @@ -267,8 +267,8 @@ void run_mxfp4_mxfp8_gemm_test(const MXFP4GemmTestParams ¶ms, Accumulation a Tensor B("B", B_shape, DType::kFloat8E4M3, true, false, NVTE_MXFP8_1D_SCALING); A.set_with_gemm_swizzled_scales(true); B.set_with_gemm_swizzled_scales(true); - nvte_quantize(A_fp32.data(), A.data(), 0); - nvte_quantize(B_fp32.data(), B.data(), 0); + nvte_quantize(A_fp32.data(), A.data(), nullptr, 0); + nvte_quantize(B_fp32.data(), B.data(), nullptr, 0); // Output and accumulation input Tensor C("C", std::vector{n, m}, output_dtype); @@ -288,8 +288,8 @@ void run_mxfp4_mxfp8_gemm_test(const MXFP4GemmTestParams ¶ms, Accumulation a const float alpha = 2.f; const float beta = 0.5f; MatmulConfigWrapper config; - nvte_cublas_gemm_v2(transa, false, &alpha, A.data(), B.data(), &beta, C_arg, D.data(), - workspace.data(), config, 0); + nvte_cublas_gemm(transa, false, &alpha, A.data(), B.data(), &beta, C_arg, D.data(), + workspace.data(), config, 0); NVTE_CHECK_CUDA(cudaDeviceSynchronize()); // Check output diff --git a/tests/cpp/util/test_c_api.c b/tests/cpp/util/test_c_api.c index 2e38a264a37..d0cf7c466c6 100644 --- a/tests/cpp/util/test_c_api.c +++ b/tests/cpp/util/test_c_api.c @@ -140,16 +140,16 @@ void call_every_c_api_function(void) { nvte_ep_shutdown(); nvte_ep_handle_mem_size(NULL); nvte_ep_prepare(NULL, NULL, NULL, NULL, NULL, NULL); - nvte_ep_dispatch(NULL, NULL, NULL, window, NULL, window, NULL, window, NULL, window, NULL); + nvte_ep_dispatch(NULL, NULL, NULL, window, NULL, window, NULL, window, NULL, window, NULL, NULL); nvte_ep_dispatch_v2(NULL, NULL, NULL, window, NULL, window, NULL, window, NULL, window, NULL, NULL); nvte_ep_prepare_and_dispatch(NULL, NULL, NULL, window, NULL, window, NULL, window, NULL, window, NULL, NULL, NULL, NULL); - nvte_ep_combine(NULL, NULL, window, NULL, NULL); + nvte_ep_combine(NULL, NULL, window, NULL, NULL, NULL); nvte_ep_combine_v2(NULL, NULL, window, NULL, NULL, NULL); - nvte_ep_dispatch_bwd(NULL, NULL, window, NULL, window, NULL, NULL, NULL); + nvte_ep_dispatch_bwd(NULL, NULL, window, NULL, window, NULL, NULL, NULL, NULL); nvte_ep_dispatch_bwd_v2(NULL, NULL, window, NULL, window, NULL, NULL, NULL, NULL); - nvte_ep_combine_bwd(NULL, NULL, window, NULL, window, NULL); + nvte_ep_combine_bwd(NULL, NULL, window, NULL, window, NULL, NULL); nvte_ep_combine_bwd_v2(NULL, NULL, window, NULL, window, NULL, NULL); /* fused_attn.h */ @@ -157,24 +157,6 @@ void call_every_c_api_function(void) { nvte_get_qkv_format(0); nvte_get_q_format(0); nvte_get_kv_format(0); - nvte_create_fused_attn_config(); - nvte_destroy_fused_attn_config(NULL); - nvte_get_fused_attn_config_attribute(NULL, 0, NULL, 0, NULL); - nvte_set_fused_attn_config_attribute(NULL, 0, NULL, 0); - nvte_create_fused_attn_fwd_params(); - nvte_destroy_fused_attn_fwd_params(NULL); - nvte_get_fused_attn_fwd_params_attribute(NULL, 0, NULL, 0, NULL); - nvte_set_fused_attn_fwd_params_attribute(NULL, 0, NULL, 0); - nvte_create_fused_attn_bwd_params(); - nvte_destroy_fused_attn_bwd_params(NULL); - nvte_get_fused_attn_bwd_params_attribute(NULL, 0, NULL, 0, NULL); - nvte_set_fused_attn_bwd_params_attribute(NULL, 0, NULL, 0); - nvte_get_fused_attn_backend(NULL, NULL); - nvte_get_fused_attn_backend_v2(NULL, NULL); - nvte_fused_attn_fwd(NULL); - nvte_fused_attn_fwd_v2(NULL); - nvte_fused_attn_bwd(NULL); - nvte_fused_attn_bwd_v2(NULL); nvte_populate_rng_state_async(NULL, NULL, 0, 0, 0, NULL); nvte_get_runtime_num_segments(NULL, NULL, 0, NULL); nvte_cu_seqlens_to_actual_seqlens(NULL, NULL, NULL, NULL, NULL); diff --git a/transformer_engine/pytorch/csrc/quantizer.cpp b/transformer_engine/pytorch/csrc/quantizer.cpp index def1ecf7b3d..6e6fa0bb8ed 100644 --- a/transformer_engine/pytorch/csrc/quantizer.cpp +++ b/transformer_engine/pytorch/csrc/quantizer.cpp @@ -3037,7 +3037,7 @@ void MXFP4Quantizer::quantize(const TensorWrapper& input, TensorWrapper& out, quant_config.set_noop_tensor(noop_flag->data()); } NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize_v2(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); + nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); }); } From 249485371f26e2e5a474b7287e552b1ee0b0054a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:35:01 +0000 Subject: [PATCH 18/18] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- transformer_engine/pytorch/csrc/quantizer.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/transformer_engine/pytorch/csrc/quantizer.cpp b/transformer_engine/pytorch/csrc/quantizer.cpp index 6e6fa0bb8ed..591449a7974 100644 --- a/transformer_engine/pytorch/csrc/quantizer.cpp +++ b/transformer_engine/pytorch/csrc/quantizer.cpp @@ -3036,9 +3036,8 @@ void MXFP4Quantizer::quantize(const TensorWrapper& input, TensorWrapper& out, if (noop_flag) { quant_config.set_noop_tensor(noop_flag->data()); } - NVTE_SCOPED_GIL_RELEASE({ - nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); - }); + NVTE_SCOPED_GIL_RELEASE( + { nvte_quantize(input.data(), out.data(), quant_config, at::cuda::getCurrentCUDAStream()); }); } std::vector MXFP4Quantizer::get_scale_shape(const std::vector& shape,