// Copyright 2023 Google LLC // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // OrderedDemote2To is not supported by HWY_SCALAR. #ifndef HWY_DISABLED_TARGETS #define HWY_DISABLED_TARGETS HWY_SCALAR #endif #include #include #include #include #include #include #include #include "hwy/aligned_allocator.h" #include "hwy/base.h" // clang-format off #undef HWY_TARGET_INCLUDE #define HWY_TARGET_INCLUDE "ops/ops_test.cc" // NOLINT // clang-format on #include "hwy/foreach_target.h" // IWYU pragma: keep #include "hwy/highway.h" #include "hwy/tests/test_util-inl.h" // After highway.h #include "gemma/activations.h" #include "gemma/common.h" #include "gemma/configs.h" #include "ops/ops-inl.h" #include "util/allocator.h" #include "hwy/tests/hwy_gtest.h" HWY_BEFORE_NAMESPACE(); namespace gcpp { namespace HWY_NAMESPACE { namespace hn = hwy::HWY_NAMESPACE; template struct ForeachCountAndMisalign { template HWY_NOINLINE void operator()(T /*unused*/, D d) const { hwy::RandomState rng; const size_t N = Lanes(d); const size_t misalignments[3] = {0, N / 4, 3 * N / 5}; for (size_t count = 0; count < 2 * N; ++count) { for (size_t ma : misalignments) { for (size_t mb : misalignments) { Test()(d, count, ma, mb, rng); } } } } }; template T Random(hwy::RandomState& rng) { const int32_t bits = static_cast(Random32(&rng)) & 1023; const double val = (bits - 512) / 64.0; // Clamp negative to zero for unsigned types. return hwy::ConvertScalarTo( HWY_MAX(hwy::ConvertScalarTo(hwy::LowestValue()), val)); } HWY_NOINLINE void SourceAddFrom(const float* HWY_RESTRICT other, float* HWY_RESTRICT x, size_t size) { for (size_t i = 0; i < size; ++i) { x[i] += other[i]; } } HWY_NOINLINE void SourceMulBy(const float* HWY_RESTRICT other, float* HWY_RESTRICT x, size_t size, size_t max_pos) { HWY_DASSERT(max_pos <= size); for (size_t i = 0; i < max_pos; ++i) { x[i] *= other[i]; } } HWY_NOINLINE void SourceMulByConst(float c, float* HWY_RESTRICT x, size_t size, size_t max_pos) { for (size_t i = 0; i < max_pos; ++i) { x[i] *= c; } } HWY_NOINLINE void SourceMulByConstAndAdd(float c, const float* HWY_RESTRICT x, float* HWY_RESTRICT out, size_t size, size_t max_pos) { for (size_t i = 0; i < max_pos; ++i) { out[i] += x[i] * c; } } HWY_NOINLINE void SourceSoftmax(float* HWY_RESTRICT x, size_t size, size_t mask_pos) { HWY_DASSERT(size != 0); HWY_DASSERT(mask_pos <= size); float sum = 0.0; const float maxval = *std::max_element(x, x + mask_pos); for (size_t i = 0; i < mask_pos; ++i) { x[i] = std::exp(x[i] - maxval); sum += x[i]; } const float scale = 1.0f / sum; for (size_t i = 0; i < mask_pos; ++i) { x[i] *= scale; } } template HWY_NOINLINE std::discrete_distribution SourceCreateDistribution( std::array& top_k, float temperature) { // re-normalize distribution for (size_t i = 0; i < k; ++i) { top_k[i] = exp(log(top_k[i]) / temperature); } float denominator = 0.0f; for (size_t i = 0; i < k; ++i) { denominator += top_k[i]; } denominator = 1.0f / denominator; MulByConst(denominator, top_k.data(), k); return std::discrete_distribution(std::begin(top_k), std::end(top_k)); } struct TestAddFrom { template void operator()(D d, size_t count, size_t misalign_a, size_t misalign_b, hwy::RandomState& rng) { using T = hn::TFromD; hwy::AlignedFreeUniquePtr px = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); hwy::AlignedFreeUniquePtr pe = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); hwy::AlignedFreeUniquePtr po = hwy::AllocateAligned(HWY_MAX(1, misalign_b + count)); HWY_ASSERT(px && pe && po); T* x = px.get() + misalign_a; T* e = pe.get() + misalign_a; T* o = po.get() + misalign_b; for (size_t i = 0; i < count; ++i) { x[i] = Random(rng); e[i] = x[i]; o[i] = Random(rng); } SourceAddFrom(o, e, count); AddFrom(o, x, count); hwy::AssertArraySimilar(e, x, count, hwy::TargetName(HWY_TARGET), __FILE__, __LINE__); } }; struct TestMulBy { template void operator()(D d, size_t count, size_t misalign_a, size_t misalign_b, hwy::RandomState& rng) { using T = hn::TFromD; hwy::AlignedFreeUniquePtr px = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); hwy::AlignedFreeUniquePtr pe = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); hwy::AlignedFreeUniquePtr po = hwy::AllocateAligned(HWY_MAX(1, misalign_b + count)); HWY_ASSERT(px && pe && po); T* x = px.get() + misalign_a; T* e = pe.get() + misalign_a; T* o = po.get() + misalign_b; for (size_t i = 0; i < count; ++i) { x[i] = Random(rng); e[i] = x[i]; o[i] = Random(rng); } SourceMulBy(o, e, count, count); MulBy(o, x, count, count); hwy::AssertArraySimilar(e, x, count, hwy::TargetName(HWY_TARGET), __FILE__, __LINE__); } }; struct TestMulByConstAndAdd { template void operator()(D d, size_t count, size_t misalign_a, size_t misalign_b, hwy::RandomState& rng) { using T = hn::TFromD; hwy::AlignedFreeUniquePtr px = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); hwy::AlignedFreeUniquePtr pe = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); hwy::AlignedFreeUniquePtr po = hwy::AllocateAligned(HWY_MAX(1, misalign_b + count)); HWY_ASSERT(px && pe && po); T* x = px.get() + misalign_a; T* e = pe.get() + misalign_a; T* o = po.get() + misalign_b; for (size_t i = 0; i < count; ++i) { x[i] = Random(rng); e[i] = x[i]; o[i] = Random(rng); } T constant = Random(rng); SourceMulByConstAndAdd(constant, o, e, count, count); MulByConstAndAdd(constant, o, x, count, count); hwy::AssertArraySimilar(e, x, count, hwy::TargetName(HWY_TARGET), __FILE__, __LINE__); } }; struct TestMulByConst { template void operator()(D d, size_t count, size_t misalign_a, size_t misalign_b, hwy::RandomState& rng) { if (misalign_b == 0) return; using T = hn::TFromD; hwy::AlignedFreeUniquePtr px = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); hwy::AlignedFreeUniquePtr pe = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); HWY_ASSERT(px && pe); T* x = px.get() + misalign_a; T* e = pe.get() + misalign_a; for (size_t i = 0; i < count; ++i) { x[i] = Random(rng); e[i] = x[i]; } T constant = Random(rng); SourceMulByConst(constant, e, count, count); MulByConst(constant, x, count, count); hwy::AssertArraySimilar(e, x, count, hwy::TargetName(HWY_TARGET), __FILE__, __LINE__); } }; struct TestSoftmax { template void operator()(D d, size_t count, size_t misalign_a, size_t misalign_b, hwy::RandomState& rng) { if (count == 0) return; // *Softmax would assert if (misalign_b == 0) return; using T = hn::TFromD; hwy::AlignedFreeUniquePtr px = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); hwy::AlignedFreeUniquePtr pe = hwy::AllocateAligned(HWY_MAX(1, misalign_a + count)); HWY_ASSERT(px && pe); T* x = px.get() + misalign_a; T* e = pe.get() + misalign_a; for (size_t i = 0; i < count; ++i) { x[i] = Random(rng); e[i] = x[i]; } SourceSoftmax(e, count, count); Softmax(x, count, count); T sum = 0.0f; for (size_t i = 0; i < count; ++i) { sum += x[i]; double rel = std::abs(x[i] - e[i]) / e[i]; ASSERT_LT(rel, 1e-6) << "Mismatch on coordinate " << i << " out of " << count; } ASSERT_NEAR(sum, 1.0, 1e-6); } }; template struct TestCreateDistribution { void operator()(hwy::RandomState& rng) { std::array x; std::array e; for (size_t i = 0; i < k; ++i) { x[i] = Random(rng); e[i] = x[i]; } const float constant = Random(rng); auto expected = SourceCreateDistribution(e, constant); auto output = create_distribution(x, constant); AssertEqual(expected, output, hwy::TargetName(HWY_TARGET), __FILE__, __LINE__); } }; void TestAllAddFrom() { hn::ForPartialVectors>()(float()); } void TestAllMulBy() { hn::ForPartialVectors>()(float()); } void TestAllMulByConst() { hn::ForPartialVectors>()(float()); } void TestAllMulByConstAndAdd() { hn::ForPartialVectors>()( float()); } void TestAllSoftmax() { hn::ForPartialVectors>()(float()); } void TestAllCreateDistribution() { TestCreateDistribution<2048>(); TestCreateDistribution<5000>(); } void TestSigmoid() { std::vector values; for (int i = -150; i <= 150; ++i) { values.push_back(.1f * i); } std::vector result = values; Sigmoid(result.data(), result.size()); for (size_t i = 0; i < values.size(); i++) { const float max_error = 0.00007; float value = values[i]; float approx = result[i]; float expected = (1 / (1 + std::exp(-values[i]))); EXPECT_NEAR(approx, expected, max_error) << "Input: " << value; } } void TestRopeAndMulBy() { using Config = ConfigGemma2_9B; int dim_qkv = Config::kQKVDim; RowVectorBatch x(1, dim_qkv); std::mt19937 gen; gen.seed(0x12345678); std::normal_distribution r{0.0, 5.0}; auto random_float = [&r, &gen] { return r(gen); }; for (int i = 0; i < dim_qkv; ++i) { x.All()[i] = random_float(); } const float qmul = ChooseQueryScale(); const float kmul = 1.0; std::vector qexpected(dim_qkv); std::vector qactual(dim_qkv); std::vector kexpected(dim_qkv); std::vector kactual(dim_qkv); RowVectorBatch inv_timescale = gcpp::Activations::CreateInvTimescale(); // Assert VectorizedRope computation is same as regular rope at different pos. for (int pos = 1; pos < 500; pos++) { // Rope'd Q embeddings RopeAndMulBy(qmul, x.Const(), dim_qkv, inv_timescale.Const(), pos, qexpected.data()); VectorizedRopeAndMulBy(qmul, x.Const(), dim_qkv, inv_timescale.Const(), pos, qactual.data()); for (int i = 0; i < dim_qkv; ++i) { EXPECT_NEAR(qactual[i], qexpected[i], 1e-4) << "qIndex:" << i << "qInput:" << qactual[i]; } // Rope'd K embeddings RopeAndMulBy(kmul, x.Const(), dim_qkv, inv_timescale.Const(), pos, kexpected.data()); VectorizedRopeAndMulBy(kmul, x.Const(), dim_qkv, inv_timescale.Const(), pos, kactual.data()); for (int i = 0; i < dim_qkv; ++i) { EXPECT_NEAR(kactual[i], kexpected[i], 1e-4) << "kIndex:" << i << "kInput:" << kactual[i]; } } } // NOLINTNEXTLINE(google-readability-namespace-comments) } // namespace HWY_NAMESPACE } // namespace gcpp HWY_AFTER_NAMESPACE(); #if HWY_ONCE namespace gcpp { HWY_BEFORE_TEST(OpsTest); HWY_EXPORT_AND_TEST_P(OpsTest, TestAllAddFrom); HWY_EXPORT_AND_TEST_P(OpsTest, TestAllMulBy); HWY_EXPORT_AND_TEST_P(OpsTest, TestAllMulByConst); HWY_EXPORT_AND_TEST_P(OpsTest, TestAllMulByConstAndAdd); HWY_EXPORT_AND_TEST_P(OpsTest, TestAllSoftmax); HWY_EXPORT_AND_TEST_P(OpsTest, TestAllCreateDistribution); HWY_EXPORT_AND_TEST_P(OpsTest, TestSigmoid); HWY_EXPORT_AND_TEST_P(OpsTest, TestRopeAndMulBy); HWY_AFTER_TEST(); } // namespace gcpp #endif