This is an automated email from the ASF dual-hosted git repository.

hello-stephen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 0cb98579f60 [improvement](be) Accelerate batched MD5 with ARM NEON 
(#70754)
0cb98579f60 is described below

commit 0cb98579f606f6ad83ef2a6446b284c8c3ec3d6a
Author: HappenLee <[email protected]>
AuthorDate: Wed Nov 25 12:50:29 2026 +0800

    [improvement](be) Accelerate batched MD5 with ARM NEON (#70754)
    
    ### Background
    
    The single-argument MD5 function hashes a batch of independent strings.
    The existing AVX2 path processes multiple messages together, while ARM64
    calls the single-message MD5 implementation for each row.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: None
    PR Type: Performance
    
    Problem Summary: Add four-lane NEON operations and reuse the existing
    two-group MD5 rounds, padding, and output conversion to process eight
    messages per batch on ARM64. Batches smaller than four messages use the
    existing serial path, and heavily imbalanced groups use serial hashing
    to avoid spending SIMD work on lanes that have already finished. Digest
    values and the AVX2 path are preserved.
    
    ### Details
    
    - **Why it was slow:** ARM64 did not use the existing multi-message
    execution framework.
    - **Optimization:** Native NEON add, rotate, Boolean operations, and a
    4x4 message-word transpose; architecture-specific selection of serial
    hashing for poorly utilized batches.
    - **Results:** Neoverse-N2, Clang 20.1.8, OpenSSL 3.0.13, `-O3
    -march=armv8-a+crc`, one pinned core; median of seven randomly
    interleaved repetitions (0.15 s minimum). At 4096 rows/batch,
    16/64/256/1024-byte inputs achieve 2.51/2.94/3.40/3.70x throughput over
    the previous per-message ARM algorithm; mixed 0–1024-byte inputs achieve
    2.05x. Highly skewed inputs are within 0.6% of serial in the measured
    cases after fallback. Single-row short inputs and four-row mixed inputs
    retain about 3% overhead. GCC 14 confirms 2.79–3.50x on the equal-length
    cases.
    - **Applicability and cost:** Applies to batched single-argument MD5 on
    ARM64. A NEON batch uses a temporary 16-byte digest per row, as the
    existing AVX2 path does. Small batches and skewed message lengths are
    included in the benchmark. These are MD5 API microbenchmarks, not
    end-to-end SQL measurements.
    
    ARM Clang 20 results (4096 rows per batch):
    
    | Batch rows | Input bytes | Serial ns/row | Batch ns/row | Speedup |
    | ---: | --- | ---: | ---: | ---: |
    | 4096 | 0 | 141.72 | 54.66 | 2.593× |
    | 4096 | 16 | 138.45 | 55.11 | 2.512× |
    | 4096 | 64 | 250.58 | 85.21 | 2.941× |
    | 4096 | 256 | 591.60 | 173.99 | 3.400× |
    | 4096 | 1024 | 1954.94 | 528.34 | 3.700× |
    | 4096 | mixed 0–1024 | 1005.06 | 489.25 | 2.054× |
    | 4096 | 8192 + seven 16-byte strings | 1956.91 | 1962.15 | 0.997× |
    
    ### Testing
    
    - Actual `be/src/util/md5.cpp` and `be/test/util/md5_test.cpp` compiled
    in isolation with ASAN/UBSAN; seven tests cover known digests, padding
    boundaries, partial SIMD groups, binary data, unaligned input,
    zero-length null pointers, and guarded output.
    - Native ARM64 validation with GCC 14 and Clang 20; x86 AVX2 validation
    with Clang 20. [Reproducible workflow and
    
artifacts](https://github.com/HappenLee/incubator-doris/actions/runs/44500133646).
    - Added `benchmark_md5.hpp` and registered it in the standard benchmark
    entry point; serial and batch implementations run on the same inputs
    with setup excluded from timing.
    - clang-format 16, build hygiene, changed-line clang-tidy, and `git diff
    --check` passed locally. clang-tidy used an isolated compilation
    database after the full UT build was blocked by missing third-party
    libraries.
    - The standard `run-be-ut.sh -j 48 --run --filter='Md5Test.*'` was
    attempted locally but could not finish because the installed third-party
    package lacks `libgoogle_cloud_cpp_oauth2.a`. A complete BE build and
    SQL regression run are not claimed.
    
    ### Release note
    
    Improve the performance of batched single-argument MD5 on ARM64 with
    NEON, retaining serial hashing for small or highly imbalanced groups.
    
    ### Check List (For Author)
    
    - Behavior changed: No
    - Does this need documentation: No
    - Pre-submission status: Partially verified: isolated native ARM64/x86
    tests and benchmarks completed; full BE build and SQL regression are
    pending CI.
    
    ### AI Disclosure
    
    - Tool: OpenAI Codex
    - Generated: NEON implementation, tests, benchmark, and PR description.
    - Human review: Not yet performed.
---
 be/benchmark/benchmark_main.cpp |   1 +
 be/benchmark/benchmark_md5.hpp  |  95 ++++++++++++++++++++++++++++++++++++
 be/src/util/md5.cpp             | 104 +++++++++++++++++++++++++++++++++++-----
 be/test/util/md5_test.cpp       |  42 ++++++++++++----
 4 files changed, 219 insertions(+), 23 deletions(-)

diff --git a/be/benchmark/benchmark_main.cpp b/be/benchmark/benchmark_main.cpp
index a17a93226ff..475eaed28f7 100644
--- a/be/benchmark/benchmark_main.cpp
+++ b/be/benchmark/benchmark_main.cpp
@@ -41,6 +41,7 @@
 #include "benchmark_hll_merge.hpp"
 #include "benchmark_hybrid_set.hpp"
 #include "benchmark_json_extract.hpp"
+#include "benchmark_md5.hpp"
 #include "benchmark_relative_day.hpp"
 #include "benchmark_rowid_conversion.hpp"
 #include "benchmark_timestamptz_round.hpp"
diff --git a/be/benchmark/benchmark_md5.hpp b/be/benchmark/benchmark_md5.hpp
new file mode 100644
index 00000000000..fbcbca000da
--- /dev/null
+++ b/be/benchmark/benchmark_md5.hpp
@@ -0,0 +1,95 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+#pragma once
+
+#include <benchmark/benchmark.h>
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+#include "util/md5.h"
+
+namespace doris {
+namespace {
+
+void md5_serial_hex_batch(const unsigned char* const inputs[], const size_t 
lengths[],
+                          char* outputs, size_t count) {
+    static constexpr char digits[] = "0123456789abcdef";
+    for (size_t i = 0; i < count; ++i) {
+        unsigned char digest[MD5_DIGEST_LENGTH];
+        MD5(inputs[i], lengths[i], digest);
+        for (size_t j = 0; j < MD5_DIGEST_LENGTH; ++j) {
+            outputs[i * MD5_HEX_LENGTH + 2 * j] = digits[digest[j] >> 4];
+            outputs[i * MD5_HEX_LENGTH + 2 * j + 1] = digits[digest[j] & 15];
+        }
+    }
+}
+
+struct Md5BenchmarkData {
+    Md5BenchmarkData(size_t count, int64_t length)
+            : strings(count), inputs(count), lengths(count), output(count * 
MD5_HEX_LENGTH) {
+        for (size_t i = 0; i < count; ++i) {
+            // -1 mixes block counts; -2 puts a long message beside seven 
short messages.
+            const size_t size = length == -1   ? (i * 131 + 17) % 1025
+                                : length == -2 ? (i % 8 == 0 ? 8192 : 16)
+                                               : static_cast<size_t>(length);
+            strings[i].resize(size);
+            for (size_t j = 0; j < size; ++j) {
+                strings[i][j] = static_cast<char>((i * 37 + j * 13) & 255);
+            }
+            inputs[i] = reinterpret_cast<const unsigned 
char*>(strings[i].data());
+            lengths[i] = size;
+            bytes += size;
+        }
+    }
+
+    std::vector<std::string> strings;
+    std::vector<const unsigned char*> inputs;
+    std::vector<size_t> lengths;
+    std::vector<char> output;
+    int64_t bytes = 0;
+};
+
+template <bool BATCH>
+void BM_Md5(benchmark::State& state) {
+    const size_t count = state.range(0);
+    Md5BenchmarkData data(count, state.range(1));
+    for (auto _ : state) {
+        if constexpr (BATCH) {
+            md5_hex_batch(data.inputs.data(), data.lengths.data(), 
data.output.data(), count);
+        } else {
+            md5_serial_hex_batch(data.inputs.data(), data.lengths.data(), 
data.output.data(),
+                                 count);
+        }
+        benchmark::DoNotOptimize(data.output.data());
+        benchmark::ClobberMemory();
+    }
+    state.SetItemsProcessed(state.iterations() * count);
+    state.SetBytesProcessed(state.iterations() * data.bytes);
+}
+
+BENCHMARK_TEMPLATE(BM_Md5, false)
+        ->Name("MD5/serial")
+        ->ArgsProduct({{1, 4, 8, 64, 4096}, {0, 16, 64, 256, 1024, -1, -2}});
+BENCHMARK_TEMPLATE(BM_Md5, true)
+        ->Name("MD5/batch")
+        ->ArgsProduct({{1, 4, 8, 64, 4096}, {0, 16, 64, 256, 1024, -1, -2}});
+
+} // namespace
+} // namespace doris
diff --git a/be/src/util/md5.cpp b/be/src/util/md5.cpp
index 9c9b5d7f68c..841c96e9c18 100644
--- a/be/src/util/md5.cpp
+++ b/be/src/util/md5.cpp
@@ -23,6 +23,8 @@
 
 #ifdef __AVX2__
 #include <immintrin.h>
+#elif defined(__aarch64__)
+#include <arm_neon.h>
 #endif
 
 #include "exec/common/endian.h"
@@ -41,7 +43,18 @@ void md5_to_hex(const unsigned char* digest, char* out) {
     }
 }
 
-#ifdef __AVX2__
+#ifndef __AVX2__
+void md5_hex_batch_serial(const unsigned char* const inputs[], const size_t 
lengths[],
+                          char* outputs, size_t count) {
+    for (size_t i = 0; i < count; ++i) {
+        unsigned char digest[MD5_DIGEST_LENGTH];
+        MD5(lengths[i] == 0 ? &MD5_DUMMY_INPUT : inputs[i], lengths[i], 
digest);
+        md5_to_hex(digest, outputs + i * MD5_HEX_LENGTH);
+    }
+}
+#endif
+
+#if defined(__AVX2__) || defined(__aarch64__)
 
 constexpr uint32_t MD5_A0 = 0x67452301;
 constexpr uint32_t MD5_B0 = 0xefcdab89;
@@ -66,10 +79,13 @@ size_t md5_pad_final_blocks(const unsigned char* data, 
size_t len, unsigned char
     return final_count;
 }
 
+#ifdef __AVX2__
 struct AVX2MD5Ops {
     using Vec = __m256i;
     static constexpr size_t LANES = 8;
 
+    static bool prefer_serial(size_t, size_t) { return false; }
+
     static Vec add(Vec a, Vec b) { return _mm256_add_epi32(a, b); }
 
     static Vec set1(uint32_t v) { return 
_mm256_set1_epi32(static_cast<int>(v)); }
@@ -142,6 +158,55 @@ struct AVX2MD5Ops {
     }
 };
 
+using NativeMD5Ops = AVX2MD5Ops;
+#elif defined(__aarch64__)
+struct NeonMD5Ops {
+    using Vec = uint32x4_t;
+    static constexpr size_t LANES = 4;
+
+    static bool prefer_serial(size_t total_blocks, size_t max_blocks) {
+        // A long message keeps both SIMD groups running after shorter lanes 
finish.
+        return max_blocks > total_blocks / LANES;
+    }
+
+    static Vec add(Vec a, Vec b) { return vaddq_u32(a, b); }
+    static Vec set1(uint32_t v) { return vdupq_n_u32(v); }
+    static void storeu(void* p, Vec v) {
+        vst1q_u8(static_cast<uint8_t*>(p), vreinterpretq_u8_u32(v));
+    }
+
+    template <int N>
+    static Vec rotl(Vec x) {
+        return vsriq_n_u32(vshlq_n_u32(x, N), x, 32 - N);
+    }
+
+    static Vec F(Vec b, Vec c, Vec d) { return vbslq_u32(b, c, d); }
+    static Vec G(Vec b, Vec c, Vec d) { return vbslq_u32(d, b, c); }
+    static Vec H(Vec b, Vec c, Vec d) { return veorq_u32(b, veorq_u32(c, d)); }
+    static Vec I(Vec b, Vec c, Vec d) { return veorq_u32(c, vornq_u32(b, d)); }
+
+    static void gather_all_message_words(const unsigned char* const 
block_ptrs[], Vec msg[16]) {
+        // Transpose four messages so each lane runs an independent MD5 chain.
+        for (size_t word = 0; word < 16; word += 4) {
+            const size_t offset = word * sizeof(uint32_t);
+            const Vec r0 = vreinterpretq_u32_u8(vld1q_u8(block_ptrs[0] + 
offset));
+            const Vec r1 = vreinterpretq_u32_u8(vld1q_u8(block_ptrs[1] + 
offset));
+            const Vec r2 = vreinterpretq_u32_u8(vld1q_u8(block_ptrs[2] + 
offset));
+            const Vec r3 = vreinterpretq_u32_u8(vld1q_u8(block_ptrs[3] + 
offset));
+            const Vec t0 = vtrn1q_u32(r0, r1);
+            const Vec t1 = vtrn2q_u32(r0, r1);
+            const Vec t2 = vtrn1q_u32(r2, r3);
+            const Vec t3 = vtrn2q_u32(r2, r3);
+            msg[word] = vcombine_u32(vget_low_u32(t0), vget_low_u32(t2));
+            msg[word + 1] = vcombine_u32(vget_low_u32(t1), vget_low_u32(t3));
+            msg[word + 2] = vcombine_u32(vget_high_u32(t0), vget_high_u32(t2));
+            msg[word + 3] = vcombine_u32(vget_high_u32(t1), vget_high_u32(t3));
+        }
+    }
+};
+using NativeMD5Ops = NeonMD5Ops;
+#endif
+
 #define MD5_STEP_X2(func, w1, x1, y1, z1, w2, x2, y2, z2, g, s, ti) \
     {                                                               \
         Vec t1 = Ops::func(x1, y1, z1);                             \
@@ -270,9 +335,17 @@ void md5_multi_buffer_compute(const unsigned char* const 
inputs[], const size_t
 
     size_t num_blocks[2 * N];
     size_t max_blocks = 0;
+    size_t total_blocks = 0;
     for (size_t i = 0; i < count; ++i) {
         num_blocks[i] = md5_num_blocks(lengths[i]);
         max_blocks = std::max(max_blocks, num_blocks[i]);
+        total_blocks += num_blocks[i];
+    }
+    if (Ops::prefer_serial(total_blocks, max_blocks)) {
+        for (size_t i = 0; i < count; ++i) {
+            MD5(inputs[i], lengths[i], outputs + i * MD5_DIGEST_LENGTH);
+        }
+        return;
     }
     for (size_t i = count; i < 2 * N; ++i) {
         num_blocks[i] = 1;
@@ -347,9 +420,10 @@ void md5_multi_buffer_compute(const unsigned char* const 
inputs[], const size_t
     }
 }
 
-void md5_binary_batch_avx2(const unsigned char* const inputs[], const size_t 
lengths[],
-                           unsigned char* outputs, size_t count) {
-    constexpr size_t BATCH = 2 * AVX2MD5Ops::LANES;
+template <typename Ops>
+void md5_binary_batch(const unsigned char* const inputs[], const size_t 
lengths[],
+                      unsigned char* outputs, size_t count) {
+    constexpr size_t BATCH = 2 * Ops::LANES;
     for (size_t base = 0; base < count; base += BATCH) {
         size_t batch = std::min(BATCH, count - base);
         const unsigned char* batch_inputs[BATCH];
@@ -362,8 +436,8 @@ void md5_binary_batch_avx2(const unsigned char* const 
inputs[], const size_t len
             batch_inputs[i] = &MD5_DUMMY_INPUT;
             batch_lengths[i] = 0;
         }
-        md5_multi_buffer_compute<AVX2MD5Ops>(batch_inputs, batch_lengths,
-                                             outputs + base * 
MD5_DIGEST_LENGTH, batch);
+        md5_multi_buffer_compute<Ops>(batch_inputs, batch_lengths,
+                                      outputs + base * MD5_DIGEST_LENGTH, 
batch);
     }
 }
 
@@ -394,18 +468,22 @@ void md5_hex_batch(const unsigned char* const inputs[], 
const size_t lengths[],
         return;
     }
 
-#ifdef __AVX2__
+#if defined(__aarch64__) && !defined(__AVX2__)
+    // A partial NEON vector cannot amortize the two-group setup and digest 
allocation.
+    if (count < NativeMD5Ops::LANES) {
+        md5_hex_batch_serial(inputs, lengths, outputs, count);
+        return;
+    }
+#endif
+
+#if defined(__AVX2__) || defined(__aarch64__)
     std::vector<unsigned char> digests(count * MD5_DIGEST_LENGTH);
-    md5_binary_batch_avx2(inputs, lengths, digests.data(), count);
+    md5_binary_batch<NativeMD5Ops>(inputs, lengths, digests.data(), count);
     for (size_t i = 0; i < count; ++i) {
         md5_to_hex(digests.data() + i * MD5_DIGEST_LENGTH, outputs + i * 
MD5_HEX_LENGTH);
     }
 #else
-    for (size_t i = 0; i < count; ++i) {
-        unsigned char digest[MD5_DIGEST_LENGTH];
-        MD5(lengths[i] == 0 ? &MD5_DUMMY_INPUT : inputs[i], lengths[i], 
digest);
-        md5_to_hex(digest, outputs + i * MD5_HEX_LENGTH);
-    }
+    md5_hex_batch_serial(inputs, lengths, outputs, count);
 #endif
 }
 
diff --git a/be/test/util/md5_test.cpp b/be/test/util/md5_test.cpp
index 15591626c1c..45e85bc596f 100644
--- a/be/test/util/md5_test.cpp
+++ b/be/test/util/md5_test.cpp
@@ -17,8 +17,7 @@
 
 #include "util/md5.h"
 
-#include <gtest/gtest-message.h>
-#include <gtest/gtest-test-part.h>
+#include <gtest/gtest.h>
 
 #include <algorithm>
 #include <array>
@@ -27,8 +26,6 @@
 #include <utility>
 #include <vector>
 
-#include "gtest/gtest_pred_impl.h"
-
 namespace doris {
 namespace {
 
@@ -91,11 +88,7 @@ void expect_batch_matches_scalar(const 
std::vector<std::string>& inputs) {
 
 } // namespace
 
-class Md5Test : public testing::Test {
-public:
-    Md5Test() {}
-    virtual ~Md5Test() {}
-};
+class Md5Test : public testing::Test {};
 
 TEST_F(Md5Test, empty) {
     Md5Digest digest;
@@ -158,7 +151,8 @@ TEST_F(Md5Test, batch_block_padding_boundaries) {
 }
 
 TEST_F(Md5Test, batch_size_boundaries) {
-    const std::vector<size_t> counts = {0, 1, 7, 8, 9, 15, 16, 17, 31, 32, 33, 
47, 48, 49};
+    const std::vector<size_t> counts = {0,  1,  2,  3,  4,  5,  7,  8,  9,
+                                        15, 16, 17, 31, 32, 33, 47, 48, 49};
     const std::vector<size_t> boundary_lengths = {0, 1, 55, 56, 57, 63, 64, 
65, 119, 120, 121};
 
     for (size_t count : counts) {
@@ -191,4 +185,32 @@ TEST_F(Md5Test, batch_binary_payloads) {
     expect_batch_matches_scalar(inputs);
 }
 
+TEST_F(Md5Test, batch_unaligned_inputs_and_null_empty_input) {
+    const std::array<size_t, 14> boundary_lengths = {0,  1,  15,  16,  55,  
56,  63,
+                                                     64, 65, 119, 120, 127, 
128, 4097};
+    constexpr size_t count = 65;
+    std::vector<std::string> inputs(count);
+    std::vector<std::string> storage(count);
+    std::vector<const unsigned char*> data(count);
+    std::vector<size_t> lengths(count);
+    for (size_t i = 0; i < count; ++i) {
+        lengths[i] = boundary_lengths[i % boundary_lengths.size()];
+        inputs[i] = make_binary_input(lengths[i], i);
+        const size_t prefix = i % 16 + 1;
+        storage[i] = std::string(prefix, '!') + inputs[i];
+        data[i] = lengths[i] == 0
+                          ? nullptr
+                          : reinterpret_cast<const unsigned 
char*>(storage[i].data() + prefix);
+    }
+    std::vector<char> output(count * MD5_HEX_LENGTH + 2, '!');
+    md5_hex_batch(data.data(), lengths.data(), output.data() + 1, count);
+    EXPECT_EQ('!', output.front());
+    EXPECT_EQ('!', output.back());
+    for (size_t i = 0; i < count; ++i) {
+        EXPECT_EQ(scalar_md5_hex(inputs[i]),
+                  std::string(output.data() + 1 + i * MD5_HEX_LENGTH, 
MD5_HEX_LENGTH))
+                << i;
+    }
+}
+
 } // namespace doris


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to