Repository navigation
Conversation
Use the "lookup" algorithm of Keiser and Lemire, "Validating UTF-8 In Less Than One Instruction Per Byte", Software: Practice and Experience 51 (5), 2021, as implemented in the simdutf library, for mb_check_encoding() and the other functions which validate UTF-8: - AVX2: full lookup algorithm (the previous version only adopted part of it), errors accumulated over blocks, 64-byte ASCII fast path, and no copying for the tail of the string or for short strings. - AVX-512 (new): selected at runtime when available, on x86-64. - ARM64: NEON implementation of the same algorithm, replacing the emulated SSE2 code. Long strings are validated about twice as fast (UTF-8 text) to three times as fast (ASCII); short strings are not slower.
The new test called preg_match('//u') before mb_check_encoding().
That sets IS_STR_VALID_UTF8, and str_repeat($s, 1) returns the same
string, so valid input never reached the new kernels. Copy the
bytes with pack() first, and cover strings longer than 2048 bytes.
The AVX-512 alignment prologue loaded context through a pointer
before the zend_string. Read the three bytes from inside the string.
OR the NEON continuation checks, matching AVX2.
Record the speedup in NEWS.
|
Opened by mistake. Closing. |
_mm512_setr_epi8 does not exist in GCC or clang. Go back to the _mm512_setr_epi64 constant, which has the same bytes.
|
reopening, as it is now ready for review |
|
@lemire It is awesome to get a PR coming in from "the man" himself! If you've fuzzed this code thoroughly, I don't foresee a lot of issues coming up in review. But I do need to do my due diligence, and because of time constraints, that won't happen for at least several days. So, if you can hold tight for a while, I'll be happy to review this before long. Hopefully shouldn't hold things up too much. |
| * (This will also confirm that the previous block didn't end with a bad byte like 0xFF) */ | ||
| __m256i bad_mask = _mm256_set_epi8(0xB, 0xD, 0xE, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127); | ||
| __m256i bad = _mm256_cmpgt_epi8(last_hi_nibbles, bad_mask); | ||
| if (_mm256_movemask_epi8(bad)) { |
There was a problem hiding this comment.
@lemire Thank you for your pull request. I have a question. In my understand, _mm256_moveask_epi8(bad) is check bad mask in every loop, But your pull request, seems check every 1KiB. I think lost performance when bad UTF-8 sequence, right?
If I am wrong, I'm sorry.
There was a problem hiding this comment.
Thanks, you are right. The loop accumulates errors and only tests them every 1 KiB, so with invalid input it may read up to about 1 KiB past the error before returning false. It is the same tradeoff as in simdutf, which offers an optimistic validator (assume the input is valid, test at the end) and one that stops at the first error. Since mb_check_encoding() returns only a boolean and inputs are usually valid, I went with the optimistic approach, but bounded it: the extra work is at most about 1 KiB, whatever the string length.
Measured with one invalid byte near the start (ns per call, mb_check_encoding($s, 'UTF-8')):
| input | master | this PR (AVX2) | this PR (AVX-512) | master (M4) | this PR (M4, NEON) |
|---|---|---|---|---|---|
| CJK, 1 KiB, valid | 141 | 89 | 70 | 145 | 79 |
| CJK, 1 KiB, error at byte 0 | 24 | 79 | 65 | 18 | 73 |
| CJK, 64 KiB, valid | 8,296 | 4,545 | 3,419 | 9,060 | 4,796 |
| CJK, 64 KiB, error at byte 0 | 24 | 85 | 70 | 18 | 77 |
| ASCII, 64 KiB, error at byte 0 | 27 | 35 | 32 | 21 | 26 |
So an early error costs about 50–60 ns more per call in the worst case, while valid input of the same size runs 1.6–2.7× faster.
It is a trade-off.
In practice, most strings are going to be valid, I believe.
|
@alexdowad Thanks! It was fuzzed for many hours two days ago. But it is actually still fuzzing. I'll report back. The CI failure seems unrelated. |
|
Ok. Done. So beyond the new phpt, each kernel (AVX2, AVX-512, NEON) was fuzzed against a scalar reference, about 12 billion checks in all, with GCC, clang, ASan and UBSan. Two parts got targeted fuzzing:
No mismatches. I can share the fuzzer if it is useful. |
* validate_utf8: stop early on invalid input validate_utf8 accumulated errors over the whole input and tested them once at the end, so an invalid string cost as much as a valid one of the same length. We now test the error vector when a non-ASCII block is reached and at least 1 KiB has been processed since the last test, as in php/php-src#25473. The ASCII path is unchanged. An ASCII block can only be in error when it follows a truncated character, and that error is still caught by the next test or at the end. The test is marked unlikely so that the compiler keeps the ASCII path as the fall-through; without it, clang gave the icelake ASCII loop a second taken branch per block. * icelake: rename check_when_left to left_at_next_check
|
@lemire Just did some testing. This looks good! I found that some operations on pure-ASCII strings seem slower with this patch than before. However, when The new tests also look good. It would be better if a bit more test coverage can be added:
|
…ation Mark the all-ASCII branch as expected in the NEON and AVX-512 block loops, and the periodic error checks as unexpected in all three kernels. The AVX2 ASCII branch is left without a hint: with GCC 16 it makes the compiler spill registers in the non-ASCII path, and UTF-8 text gets about 12% slower, for a gain of about 1% on ASCII. Test lengths around 1024 and 1088 bytes, where the kernels check the accumulated errors, as well as 2047-4097 bytes. Corrupt bytes at offsets around 64, 1024, 1088 and 2048, and in the last 6 bytes.
The content of a long zend_string starts 24 bytes past a 64-byte boundary, so half of the 32-byte loads crossed a cache line. As in the AVX-512 kernel, check one unaligned 64-byte block, then continue from the next 64-byte boundary with the 3 preceding bytes as context. On an Ice Lake server, long ASCII strings were about 7% slower than with the old AVX2 code; they are now about 20% faster.
As in the AVX2 and AVX-512 kernels, check one unaligned 64-byte block, then continue from the next 64-byte boundary with the 3 preceding bytes as context. On Graviton 5 (Neoverse V3), long ASCII strings are validated 5% (64 KiB) to 14% (1 MiB) faster; Apple M4 shows no difference.
|
@alexdowad Thanks for testing! Tests: done. The test now covers lengths just below, at and above 1024 (and 2048, 4096), and puts invalid bytes at many offsets, including 63, 64, 1023, 1024, 1025 and the last few bytes of the string. ASCII slowdown: I found the cause. Long strings start 24 bytes past a cache-line boundary, so many loads crossed cache lines. The AVX2 and NEON kernels now align their loads, as the AVX-512 kernel already did. Long ASCII strings are now about 20% faster than master with AVX2 (they were 7% slower before).
I also tested on Graviton 5. On all the machines I tried (Intel Emerald Rapids, Apple M4, Graviton 5), nothing is slower than master, from 16 bytes to 1 MiB. |
|
I think we can go ahead and merge this. @youkidearitai, do you have any other questions or concerns before I go ahead? |
youkidearitai
left a comment
There was a problem hiding this comment.
@alexdowad Nothing, LGTM! Thanks @lemire !
|
Merged into @lemire, this GH thread may not be the best place to start a separate discussion, but I am very interested if you have any thoughts on the possibility of using SIMD to speed up Unicode case conversions. Our ASCII case conversions use SIMD instructions when available, and it's unfortunate that Unicode case conversion can't benefit as well. A while ago, one of our core contributors wanted to merge a patch which made mbstring's case conversion first check if a string was all-ASCII, and then use the SIMD fast path if so. I didn't like the patch myself, because it forces a full scan of every string, which is wasted work if it turns out the string is non-ASCII. Another option is to convert long runs of ASCII characters using SIMD, and fall back to scalar code for runs of non-ASCII characters. But I wonder how much that will help in real-world usage. Yet another idea is to optimistically try converting an ASCII prefix of the string using SIMD, and fall back to the current code for any non-ASCII suffix. That would avoid the possibility of a wasted full scan. If you have any thoughts, I'd love to hear them. |
|
@alexdowad I comfirmed commit in 0fb074d (and more) but perhaps your Git author's name is T. T is you, right? |
|
@alexdowad I will send an email at the email address your show on your GH profile. |
Oh my. It looks like I didn't have git properly configured on the machine where I applied the patches. |
I checked the git history for |
|
Hmm. The |
|
@alexdowad This PR was already merge, So I close. |
This has been merged to master: 8.6.0 has been released last week, so this will take about a year to be end up in a stable release, I'm afraid |
With an appropriate description in UPGRADING ( Lines 247 to 249 in e6707b5 |
|
Something of the sort maybe? If I need to do something, please tell me. |
|
@lemire @alexdowad I have an idea. Could you create follow-up pull request that about write |
|
Thanks @youkidearitai. I opened #25795 with an UPGRADING entry. |
This PR updates the SIMD UTF-8 validation behind
mb_check_encoding(), and behind the functions that validate UTF-8 before taking a fast path (mb_strlen(),mb_substr(), ...). It uses the "lookup" algorithm fromas implemented in simdutf. The simdutf library is used by mainstream browsers and major JavaScript runtimes. It is thus quite solid (used in production for many years).
Changes
zend_stringheader before the content, which the old code already did, and those bytes are cleared.ext/standard/base64.c. For long strings it checks one unaligned block, then continues from the next 64-byte boundary. The three bytes of context for that boundary are read from inside the string.vqtbl1q_u8) replaces the SSE2 code emulated throughzend_simd.h.Performance
mb_check_encoding($s, 'UTF-8'), ns per call; the string is modified before each call so the cached validity flag is cleared.Intel Xeon Gold 6338 (Ice Lake), GCC 16:
Apple M4 Max, Apple clang:
None of the measured sizes (16 B to 1 MiB, ASCII, Latin, CJK, emoji) got slower.
Testing
ext/mbstring/tests/mb_check_encoding_utf8_blocks.phpt. It puts valid, invalid and truncated sequences at every offset of strings up to 140 bytes, and compares against PCRE's UTF-8 validation. The string passed tomb_check_encoding()is apack()copy, so the UTF-8 flag set bypreg_match('//u')is clear and the SIMD path actually runs. It also checks strings of 2048 bytes and longer, which is when the AVX-512 kernel aligns its loads.preg_match('//u', ...).#24362 also changes the AVX2 dispatch code in
mbstring.c, for i386 clang; whichever lands second will need a small rebase.