// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include #include #include "gtest/gtest.h" #include "core/common/inlined_containers.h" #include "core/framework/kernel_registry.h" #include "core/framework/kernel_type_str_resolver.h" #include "core/graph/model.h" #include "core/session/onnxruntime_session_options_config_keys.h" #include "test/providers/provider_test_utils.h" #include "test/util/include/default_providers.h" #include "test/util/include/test_environment.h" #if !defined(DISABLE_CONTRIB_OPS) namespace onnxruntime { namespace test { namespace { template void RunLayerNormTest(bool simplified, bool has_bias) { // Cover scalar, vec2, vec4, multiple elements per thread, and split normalization. for (const auto& dims : {TensorShapeVector{2, 3}, {2, 6}, {2, 128}, {2, 260}, {2, 1024}, {1, 1024}}) { SCOPED_TRACE(MakeString("shape=", TensorShape(dims), ", simplified=", simplified, ", bias=", has_bias)); auto webgpu_ep = DefaultWebGpuExecutionProvider(); if (!webgpu_ep) { GTEST_SKIP() << "WebGPU execution provider is not available."; } constexpr float epsilon = 1e-5f; const int64_t norm_count = dims[0]; const int64_t norm_size = dims[1]; InlinedVector input; InlinedVector scale; InlinedVector bias; InlinedVector expected; InlinedVector mean; InlinedVector inv_std_dev; input.reserve(norm_count * norm_size); expected.reserve(norm_count * norm_size); scale.reserve(norm_size); bias.reserve(norm_size); mean.reserve(norm_count); inv_std_dev.reserve(norm_count); for (int64_t j = 0; j < norm_size; ++j) { scale.emplace_back(0.5f * static_cast(1 + j % 3)); bias.emplace_back(0.125f * static_cast(j % 5 - 2)); } for (int64_t n = 0; n < norm_count; ++n) { double sum = 0.0; for (int64_t j = 0; j < norm_size; ++j) { input.emplace_back(0.25f * static_cast(j % 17 - 8) + 0.5f * static_cast(n)); sum += static_cast(input.back()); } const double row_mean = simplified ? 0.0 : sum / norm_size; double squared_deviation = 0.0; for (int64_t j = 0; j < norm_size; ++j) { const double deviation = static_cast(input[n * norm_size + j]) - row_mean; squared_deviation += deviation * deviation; } const double row_inv_std_dev = 1.0 / std::sqrt(squared_deviation / norm_size + epsilon); mean.push_back(static_cast(row_mean)); inv_std_dev.push_back(static_cast(row_inv_std_dev)); for (int64_t j = 0; j < norm_size; ++j) { const V normalized(static_cast((static_cast(input[n * norm_size + j]) - row_mean) * row_inv_std_dev)); expected.emplace_back(static_cast(normalized) * static_cast(scale[j]) + (has_bias ? static_cast(bias[j]) : 0.0f)); } } OpTester test(simplified ? "SimplifiedLayerNormalization" : "LayerNormalization", 15); test.AddAttribute("epsilon", epsilon); test.AddInput("X", dims, input.data(), input.size()); test.AddInput("Scale", {norm_size}, scale.data(), scale.size(), true); if (has_bias) { test.AddInput("B", {norm_size}, bias.data(), bias.size(), true); } test.AddOutput("Y", dims, expected.data(), expected.size()); constexpr float tolerance = std::is_same_v ? 0.002f : 1e-5f; test.SetOutputAbsErr("Y", tolerance); test.SetOutputRelErr("Y", tolerance); if (!simplified) { test.AddOutput("Mean", {norm_count, 1}, mean.data(), mean.size()); test.AddOutput("InvStdDev", {norm_count, 1}, inv_std_dev.data(), inv_std_dev.size()); } SessionOptions session_options; ASSERT_STATUS_OK(session_options.config_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1")); test.Config(session_options).ConfigEp(std::move(webgpu_ep)).RunWithConfig(); ASSERT_EQ(test.GetFetches().size(), simplified ? 1u : 3u); } } template void RunLayerNormTests() { RunLayerNormTest(false, false); RunLayerNormTest(false, true); RunLayerNormTest(true, false); } template void CheckLayerNormKernelTypes(const KernelRegistry& kernel_registry, bool simplified, bool expect_supported) { SCOPED_TRACE(MakeString("simplified=", simplified, ", V=", DataTypeImpl::ToString(DataTypeImpl::GetTensorType()), ", U=", DataTypeImpl::ToString(DataTypeImpl::GetTensorType()))); // Kernel registration checks need a graph without an OpTester inference run. const auto& logger = DefaultLoggingManager().DefaultLogger(); Model model("LayerNormKernelTypes", false, ModelMetaData{}, PathString{}, IOnnxRuntimeOpSchemaRegistryList{}, {{kOnnxDomain, 15}}, {}, logger); auto& graph = model.MainGraph(); auto& x = graph.GetOrCreateNodeArg("X", DataTypeImpl::GetTensorType()->GetTypeProto()); const auto* v_type = DataTypeImpl::GetTensorType()->GetTypeProto(); const auto* u_type = DataTypeImpl::GetTensorType()->GetTypeProto(); auto& scale = graph.GetOrCreateNodeArg("Scale", v_type); InlinedVector outputs{&graph.GetOrCreateNodeArg("Y", v_type)}; if (!simplified) { outputs.push_back(&graph.GetOrCreateNodeArg("Mean", u_type)); } outputs.push_back(&graph.GetOrCreateNodeArg("InvStdDev", u_type)); auto& node = graph.AddNode("LayerNorm", simplified ? "SimplifiedLayerNormalization" : "LayerNormalization", "", {&x, &scale}, outputs); node.AddAttribute("stash_type", static_cast(std::is_same_v ? ONNX_NAMESPACE::TensorProto_DataType_DOUBLE : ONNX_NAMESPACE::TensorProto_DataType_FLOAT)); ASSERT_STATUS_OK(graph.Resolve()); ASSERT_EQ(graph.NumberOfNodes(), 1u); const KernelCreateInfo* kernel_create_info = nullptr; const auto status = kernel_registry.TryFindKernel(node, kWebGpuExecutionProvider, OpSchemaKernelTypeStrResolver{}, logger, &kernel_create_info); EXPECT_EQ(status.IsOK(), expect_supported) << status.ErrorMessage(); EXPECT_EQ(kernel_create_info != nullptr, expect_supported); } } // namespace TEST(LayerNorm_WebGPU, KernelTypeSupport) { auto webgpu_ep = DefaultWebGpuExecutionProvider(); if (!webgpu_ep) { GTEST_SKIP() << "WebGPU execution provider is not available."; } auto kernel_registry = webgpu_ep->GetKernelRegistry(); ASSERT_NE(kernel_registry, nullptr); for (bool simplified : {false, true}) { CheckLayerNormKernelTypes(*kernel_registry, simplified, true); CheckLayerNormKernelTypes(*kernel_registry, simplified, true); CheckLayerNormKernelTypes(*kernel_registry, simplified, false); CheckLayerNormKernelTypes(*kernel_registry, simplified, false); CheckLayerNormKernelTypes(*kernel_registry, simplified, false); } } TEST(LayerNorm_WebGPU, Float16InputFloat32Output) { RunLayerNormTests(); } TEST(LayerNorm_WebGPU, Float32InputFloat16Output) { RunLayerNormTests(); } TEST(LayerNorm_WebGPU, Float16) { RunLayerNormTests(); } TEST(LayerNorm_WebGPU, Float32) { RunLayerNormTests(); } } // namespace test } // namespace onnxruntime #endif // !defined(DISABLE_CONTRIB_OPS)