I have a repo that supposedly enables the SIMD TT probe. However, I couldn't get the speedup that I desired from the transposition table probe. How do I get the speedup?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's analyze how Stockfish's transposition table (TT) works and identify potential bottlenecks that might prevent you from seeing the expected speedup from SIMD (Single Instruction, Multiple Data) operations.
Based on the provided code, here's a breakdown of the TT implementation and considerations for optimization:
1. TT Structure:
Clusters: The TT is organized into Cluster objects. Each Cluster contains multiple TTEntry objects and a small array of keys. The Cluster size is fixed at 32 bytes and contains 3 TT entries and 4 keys.
TTEntry: Each TTEntry stores data about a specific position:
key16 (16 bits): Lower 16 bits of the full 64-bit zobrist key, used for fast comparison within a cluster.
depth8 (8 bits): Search depth of the entry.
genBound8 (8 bits): Combination of generation (5 bits) and bound type and pv node info (3 bits).
move16 (16 bits): Best move found for the position.
value16 (16 bits): Evaluation score for the position.
eval16 (16 bits): Evaluation score, potentially from a different eval function.
Hashing: The TT uses a simple hash function ( mul_hi64(key, clusterCount)) to determine the Cluster where a given position's data should reside. It is important to note that the key used to locate the cluster is the full 64bit key and the 16bit key16 is only used within the cluster.
TTWriter: The TTWriter provides an abstraction to the actual TT entry. The write operation is non-atomic, meaning that multiple threads could be writing to the same location.
2. TT Probe (TranspositionTable::probe)
Lookup: When probe is called with a key, the code first calculates the index of the Cluster in the table. The keys array within the Cluster is then searched to see if key matches any of the 3 keys in the cluster.
Replacement Strategy: If a matching key is not found, an entry within the cluster is selected for replacement based on depth and age. The entry with the lowest depth - 2 * relative_age is replaced. The relative_age is calculated using the current generation, which is updated on every root search. The returned TTWriter will point to this entry.
Data Access: When a matching key is found, it returns a copy of TTData, with a move, value, eval, depth, bound, and pv information. Note that because of the concurrent access to the TT, this TTData can be racy and inconsistent.
3. Potential Bottlenecks & How to Improve:
False Sharing: The biggest issue with the TT implementation is the lack of consideration of false sharing. Although the code uses an array of uint16_t for keys, it does not consider that multiple threads may be writing to keys, which are often on the same cache line. The same issue can happen for the TTEntry objects, although the likelihood of this is lower as the are fewer entries than keys.
Solution:
Padding: You could pad the keys array and TTEntry array to the size of a cache line. This reduces the probability that two threads will write to the same cache line.
Thread-Local TT: Another approach is to implement thread-local TT's for each thread, which reduces the overhead of synchronization, and can provide good scaling. This approach requires more work to implement, however, and requires some sort of merging strategy.
Sequential Key Search: The code iterates through the keys array sequentially within the cluster, which may not utilize SIMD effectively.
Solution:
SIMD Comparison: Use SIMD instructions (e.g., SSE/AVX intrinsics) to compare the input key against multiple keys in parallel. Modern x86 CPUs are capable of comparing up to 8 uint16_t values at once.
Memory Access Patterns: The mul_hi64 and the use of clusterCount in calculating the hash table index, as well as the sequential search inside the cluster might lead to non-optimal memory access patterns.
Solution:
Optimize Hashing: Experiment with different hash functions and TT sizes to potentially improve the distribution of entries across the table and reduce cache misses.
Prefetching: Add prefetching instructions to load the cluster into the cache before the loop. The code already has a prefetch function, which may be used for this.
Racy Writes The code explicitly allows for racy updates. This can be problematic if the TT is used for critical operations such as deciding mate scores, since it may lead to very weird behavior.
Solution:
Atomic Writes: Make TT writes atomic.
Age based replacement The code replaces based on age, which in theory may not be a good replacement strategy, since it does not take into account the depth of a position. A position that has been searched at a deeper depth should be preferred for replacement.
4. How to Implement SIMD:
Identify Target Architecture: Determine which SIMD instruction set your target architecture supports (e.g., SSE4.1, AVX2, AVX512 for x86, NEON for ARM).
Use Intrinsics or Libraries:
Intrinsics: Directly use compiler intrinsics (e.g., <xmmintrin.h>, <immintrin.h>).
SIMD Libraries: Use a library that abstracts away the details of different SIMD instruction sets.
Parallelize Key Comparisons: Load multiple keys into SIMD registers, and compare them against the input key in parallel.
Conditional Writes: Use SIMD masks to conditionally write to memory if there is a match.
5. Profiling
Use a profiling tool to accurately determine where the slowdown is. The misc.cpp file already has some basic profiling tools that may be used for this.
Code Example (Illustrative, x86 SSE4.1):
cpp
#include <immintrin.h>
#include <cstdint>
#include <iostream>
// Assume keys is an array of uint16_t, and key16 is the key you are looking for
bool probe_simd(const uint16_t* keys, uint16_t key16) {
__m128i target = _mm_set1_epi16(key16);
__m128i loaded = _mm_loadu_si128(reinterpret_cast<const __m128i*>(keys));
__m128i mask = _mm_cmpeq_epi16(target, loaded);
return _mm_movemask_epi8(mask) != 0;
}
// Modify your TranspositionTable::probe method
std::tuple<bool, TTData, TTWriter> TranspositionTable::probe(const Key key) const {
TTEntry* const tte = first_entry(key);
const uint16_t key16 = uint16_t(key);
uint16_t* keys = get_keys(key);
// If SIMD optimization is successful, you should use this instead of the for loop.
if (probe_simd(keys,key16)){
for(int i=0; i< ClusterSize; ++i){
if(keys[i] == key16){
return {tte[i].is_occupied(), tte[i].read(), TTWriter(reinterpret_cast<uintptr_t>(keys)|i)};
}
}
}
//The rest of your replacement code here
int replace_idx = 0;
for (int i = 1; i < ClusterSize; ++i)
if ( tte[replace_idx].depth8 - tte[replace_idx].relative_age(generation8) * 2
> tte[i].depth8 - tte[i].relative_age(generation8) * 2)
replace_idx = i;
uintptr_t replace = reinterpret_cast<uintptr_t>(keys)|replace_idx;
return {false,
TTData{Move::none(), VALUE_NONE, VALUE_NONE, DEPTH_ENTRY_OFFSET, BOUND_NONE, false},
TTWriter(replace)};
}
Important Notes:
Alignment: Make sure the keys array is properly aligned for SIMD operations. You may need to use alignas(16) or similar specifiers.
Compiler Support: Ensure your compiler and build system are configured to enable the necessary SIMD extensions.
In Summary:
To get the desired TT probe speedup, focus on the following:
False sharing: Use padding or thread local TT to reduce the probability that two threads are writing to the same cache line.
SIMD: Use SIMD instructions to compare multiple keys in parallel.
Memory Access: Optimize hash function and TT sizes and add prefetching.
Atomic Writes: Make sure TT writes are atomic, if necessary.
Profiling: Use profiling tools to accurately determine the bottlenecks.
Start with SIMD key comparisons, then address false sharing and other potential issues. Remember to profile your code to measure the effectiveness of each optimization.
Solution
Depth and age based replacement: Change the replacement strategy such that both age and depth is taken into account for replacement.