The accumulator doubles runtime even without NNUE (Efficiently Updatable Neural Networks) enabled because of the additional overhead associated with maintaining and updating the accumulator data structures. Here's a detailed breakdown:
1. What is the Accumulator?
The accumulator in the Ethereal chess engine is a data structure used to store intermediate evaluation results for the NNUE's input features. It is designed to allow efficient incremental updates to the neural network evaluation when board positions change (e.g., after a move is made).
2. Why Does the Accumulator Run Even Without NNUE Enabled?
Even when NNUE is disabled, the code for managing and updating the accumulator is still executed. This likely happens because:
Consistency: The engine might still maintain the accumulator for potential future use or to simplify the overall code structure.
Incremental Updates: The accumulator handles piece movements and position changes incrementally, which requires tracking board states and deltas (changes) regardless of whether NNUE is used.
Thread Synchronization: The accumulator is tied to thread-local storage and search state, which might still be active even without NNUE.
3. What Causes the Overhead?
The runtime overhead comes from maintaining and updating the accumulator, even if NNUE is not active. Specifically:
a) Piece Movement Tracking
The accumulator tracks changes to pieces on the board (e.g., moves, captures, promotions). Functions such as nnue_move_piece, nnue_add_piece, and nnue_remove_piece are called during every move, and they update the deltas in the accumulator.
b) Index Calculations
The accumulator relies on calculating indices for the neural network's input features. These calculations involve:
Mapping squares from 64-based indices to 32-based indices (sq64_to_sq32).
Determining feature indices for pieces on the board (nnue_index).
These calculations are computationally expensive, especially when performed repeatedly during a search.
c) Memory Access
The accumulator involves frequent memory reads and writes to keep track of deltas and values. This can lead to cache inefficiencies, slowing down the overall runtime.
d) Recursive Updates
The accumulator's incremental nature means it often needs to perform recursive updates for parent accumulators in the search tree. For example:
nnue_update_accumulator is called recursively to propagate changes up the search tree.
Even if NNUE is disabled, these updates may still occur to maintain consistency in the accumulator structure.
e) Redundant Work
When NNUE is disabled, the computations related to the accumulator are effectively redundant. The accumulator is being updated and maintained, but its results are not used in the evaluation, leading to wasted computation.
4. Double Runtime Impact
The runtime doubles because:
The accumulator introduces significant computational overhead in terms of feature indexing, memory operations, and recursive updates.
None of this work contributes to the final evaluation when NNUE is disabled, making it purely additive overhead.
5. How to Mitigate This?
To prevent this overhead when NNUE is disabled, the engine could:
Disable Accumulator Updates: Skip any accumulator-related logic when NNUE is not in use.
Conditional Compilation: Use preprocessor directives to exclude NNUE-related code entirely when NNUE is disabled.
Lazy Initialization: Only initialize and update the accumulator when NNUE is explicitly enabled.
Conclusion
The accumulator's runtime impact comes from the overhead of maintaining and updating it on every board state change, even when NNUE is disabled. This includes tracking piece movements, calculating feature indices, and performing recursive updates. This adds substantial unnecessary computation, effectively doubling the runtime without contributing to the evaluation.
User
Explain the stack part and where it is working from.
Assistant
Understanding the Stack in the Context of NNUE Accumulator
In the Ethereal chess engine, the stack plays a critical role in maintaining the state of the NNUE accumulator during the search process. This ensures that intermediate evaluations can be efficiently updated and reused as the search tree is explored. Let’s break this down in detail.
1. Purpose of the Stack in NNUE Accumulator
The NNUE accumulator relies on a stack to:
Keep track of incremental updates to the accumulator values during search.
Allow efficient rollbacks when the search algorithm backtracks (e.g., during alpha-beta pruning).
Preserve the evaluation state for each position in the search tree.
In chess engines, the search process explores moves recursively (depth-first search). At each depth, the engine needs to:
Apply changes resulting from a move.
Evaluate the new position.
Rollback the changes when returning to the parent node in the search tree.
The stack is used to store these intermediate states of the accumulator so that they can be restored when backtracking.
2. How the Stack Works in the Accumulator
The stack is implemented as part of the NNUEAccumulator structure, and it is closely tied to the search tree. Here's how it works:
a) Structure of the Stack
Each thread maintains its own stack of NNUEAccumulator objects. These accumulators store:
The current evaluation values (values).
Flags indicating whether the evaluation for each color is accurate (accurate[WHITE] and accurate[BLACK]).
A list of deltas (deltas) that represent changes to the accumulator caused by moves.
A counter (changes) to track the number of deltas applied.
b) Pushing to the Stack
When a new move is made during the search, the engine pushes a new NNUEAccumulator onto the stack:
This happens via the nnue_push function.
The newly pushed accumulator inherits the state from the current position but starts with a clean slate for tracking changes.
c
User
Explain how big the stack could be across all nodes and how doesn’t run out of mwmory
Assistant
The stack used for the NNUE accumulator in the Ethereal chess engine is designed to scale efficiently with the depth of the search tree, which can involve millions of nodes in a deep search. Managing memory for the stack across all nodes is critical, as exceeding available memory could crash the program or degrade performance severely. Let’s break this down:
1. How Big the Stack Can Get Across All Nodes
a) Stack Size Per Search Node
Each node in the search tree requires an NNUEAccumulator object to store:
The evaluation state (values for both colors).
Flags for accuracy (accurate).
A list of deltas (deltas) for incremental updates.
A counter to track the number of changes (changes).
The size of an NNUEAccumulator is determined by:
Accumulator Values:
For both WHITE and BLACK, the accumulator stores KPSIZE values.
KPSIZE is the number of features in the NNUE input layer. Commonly, this is 256 or 512 depending on the implementation.
Each value is stored as a 16-bit integer (int16_t).
Example: For KPSIZE = 512:
values[WHITE] = 512 × 2 bytes = 1 KB.
values[BLACK] = 512 × 2 bytes = 1 KB.
Total for values: 2 KB.
Delta List:
Deltas store changes to the accumulator caused by moves.
Each delta entry is a struct (NNUEDelta) storing:
Piece type.
Starting square.
Ending square.
Assuming a delta is ~8 bytes and a typical node may involve ~10 deltas:
Is that limit within one tree or for all branches of all trees and how is the latter bounded.
Assistant
The stack limit discussed earlier pertains to one tree — specifically, the search tree being explored by a single thread at a time. This stack limit is primarily determined by the maximum search depth (e.g., MAX_PLY = 128) and is reused as the search backtracks and explores different branches of the same tree. However, in a real chess engine, multiple threads are often exploring different parts of the tree simultaneously, and all branches of all trees need to be accounted for. Let’s break this down:
1. Stack Limit Per Tree
Each thread maintains a stack for the current search tree it is exploring. The stack size is limited by:
Maximum Depth (MAX_PLY): The maximum number of plies (half-moves) the engine can search in a single branch.
Thread-Local Storage: Each thread has its own independent stack, which is used exclusively for the tree that the thread is exploring.
For a single thread:
The stack grows to a maximum of MAX_PLY nodes in depth, regardless of the number of branches in the tree, because:
When backtracking from a branch, the stack pointer is decremented (nnue_pop), freeing that memory for reuse.
Only the nodes currently being explored in the current branch occupy the stack.
Thus, within one tree, the stack size per thread is bounded by:
[ \text{Stack size per thread} = \text{MAX_PLY} \times \text{size of one NNUEAccumulator} ]
2. How the Stack Works Across All Branches
In the context of all branches in the tree:
The stack does not grow for all branches simultaneously.
The stack is reused as the engine prunes and backtracks (e.g., during alpha-beta pruning). Once a branch is fully explored, its stack memory is freed and reused for the next branch.
For example:
If the engine explores a branch to depth 20, it will allocate stack space for 20 nodes.
After backtracking, the stack is reused for the next branch, so the memory usage is not cumulative across branches.
3. Bounding Memory Across All Trees (Multi-Threading)
In a multi-threaded engine, each thread has its own independent stack. While threads may explore different parts of the search tree simultaneously, their stack usage is isolated. The total memory usage across all threads is bounded by:
[ \text{Total memory usage} = \text{Number of threads} \times \text{Stack size per thread} ]
User
So it traces up and down modifying nnue as it goes.
Assistant
Yes, that's correct! The NNUE accumulator in Ethereal traces up and down the search tree, modifying the NNUE state incrementally as it goes. This approach ensures that the evaluation of positions can be efficiently updated during the search process without recalculating the entire NNUE evaluation from scratch at every node.
Here’s how this works in detail:
1. Traversing the Search Tree
The search process is a recursive exploration of the game tree, typically implemented as a depth-first search with alpha-beta pruning. As the engine moves down the tree (exploring a branch) or backtracks up the tree (to explore another branch), the NNUE accumulator is updated accordingly.
Going Down the Tree (Making Moves):
When a move is made (e.g., nnue_push):
The current state of the NNUE accumulator is "saved" on the stack.
The board state is changed to reflect the move.
The NNUE accumulator is incrementally updated to reflect the new position.
Going Up the Tree (Undoing Moves):
When backtracking (e.g., nnue_pop):
The board state is reverted to the previous position.
The NNUE accumulator is restored to its previous state by popping it off the stack.
This process ensures that the NNUE accumulator always reflects the correct state of the board as the engine moves through the search tree.
2. Incremental Updates to NNUE
The NNUE accumulator is designed to be incrementally updatable, meaning that only the parts of the evaluation affected by a move are updated. This is far more efficient than recomputing the entire NNUE evaluation from scratch.
Key Steps in Incremental Updates:
Track Changes (Deltas):
When a piece moves, the affected features (input indices to the NNUE) are recorded as deltas in the current NNUEAccumulator.
For example, nnue_move_piece, nnue_add_piece, and nnue_remove_piece functions record the changes caused by a move.
c
User
Why might this double the runtime or halve the nodes. (Even without running the nn)
Assistant
The use of the NNUE accumulator in Ethereal can double the runtime or halve the number of nodes searched (even without running the actual neural network evaluation) due to the overhead introduced by managing and updating the accumulator. Here's a detailed explanation of why this happens:
1. Understanding the Overhead
The NNUE accumulator introduces several computational tasks that do not exist when NNUE is disabled. These tasks, even without invoking the neural network itself, can slow down the engine and reduce the number of nodes it can search in a given period.
2. Sources of Overhead
a) Incremental Updates to the Accumulator
When a move is made, the NNUE accumulator must be updated to reflect the new board state. This involves:
Delta Tracking: For each move, the deltas (piece movements, additions, removals) are calculated and stored.
Index Mapping: For each delta, the engine must compute the relevant NNUE input feature indices (e.g., using functions like nnue_index and sq64_to_sq32).
Accumulator Value Updates: The deltas are applied to the accumulator values incrementally.
Even without running the NNUE neural network itself, the accumulator updates require significant computation, especially for:
Mapping squares and piece types to NNUE indices.
Performing bitboard manipulations and relative square calculations.
This additional work increases the runtime of the engine.
b) Increased Memory Access
The accumulator requires frequent memory reads and writes:
Updating the accumulator values involves accessing large arrays (e.g., accum->values[colour]).
This can result in cache misses and slowdowns, especially if the accumulator data cannot fit entirely in the CPU cache.
c) Stack Management
The NNUE stack is used to save and restore the accumulator's state as the engine explores the search tree:
Push Operations: Each time the engine makes a move, the current accumulator state is pushed onto the stack.
Pop Operations: When backtracking, the previous state is restored by popping the stack.
While these operations are lightweight, they still add overhead at every node.
d) Recursive Updates
User
How could nnue index be 5% of runtime
Assistant
The nnue_index function could account for 5% of the runtime due to the following reasons:
1. What Does nnue_index Do?
The nnue_index function is responsible for mapping board features (e.g., piece type, position, color, etc.) into indices that correspond to the neural network's input layer. These indices define the NNUE's input features for the current board state.
In Ethereal, the nnue_index function performs several operations for this mapping:
Extract Piece Properties:
Determine the piece type and color.
Compute the relative position of the piece (from the perspective of the current player).
Mirror and Adjust Squares:
Map square indices (e.g., 64-square chessboard representation) into a compact 32-square representation using sq64_to_sq32.
Mirror squares based on the king's position (e.g., left or right flank).
Compute the Final Index:
Combine all these inputs into an index that identifies the feature corresponding to the piece on a specific square.
Here’s the full implementation for reference:
c
static int nnue_index(int piece, int relksq, int colour, int sq) {
const int ptype = pieceType(piece);
const int pcolour = pieceColour(piece);
const int relpsq = relativeSquare(colour, sq);
const int mksq = testBit(LEFT_FLANK, relksq) ? (relksq ^ 0x7) : relksq;
const int mpsq = testBit(LEFT_FLANK, relksq) ? (relpsq ^ 0x7) : relpsq;
return 640 * sq64_to_sq32(mksq) + (64 * (5 * (colour == pcolour) + ptype)) + mpsq;
}
2. Why nnue_index Can Be Expensive
a) Called Frequently
The nnue_index function is called every time a piece moves during the search.
Each move requires updates to the NNUE accumulator, and is invoked for:
User
How many cycles might it be and why.
Assistant
The number of CPU cycles required to execute the nnue_index function depends on the complexity of its operations and the hardware on which it runs (e.g., CPU architecture, clock speed, and cache behavior). Here's a breakdown of the cost and an estimate of how many cycles it might take, followed by the reasoning behind the estimate.
1. Operations in nnue_index
The nnue_index function performs several steps, each contributing to its runtime:
a) Bitwise Operations
testBit checks and mirroring:
The testBit macro checks if a specific bit is set in a bitboard. This involves a bitwise AND operation and a comparison, which is typically a single CPU cycle if the operands are in a CPU register.
Mirroring a square (relksq ^ 0x7 or relpsq ^ 0x7) involves a simple XOR operation, costing 1-2 cycles.
b) Logical Comparisons
The function uses several logical comparisons (e.g., if statements) to determine whether to apply mirroring or adjust indices based on conditions.
Each comparison typically costs 1-3 cycles, depending on whether the branch is predictable (e.g., if the same branch is frequently taken, modern CPUs can optimize).
c) Array Lookup
The sq64_to_sq32 function accesses a precomputed array to map a 64-square board position to a more compact 32-square representation. This involves:
Calculating an index for the array (1 cycle).
Accessing the array element from memory, which can vary:
When the engine reaches a new position where the accumulator state cannot be incrementally updated (e.g., after a null move or when the history is incomplete), it performs a full refresh:
This is handled by nnue_refresh_accumulator.
The stack helps ensure that these updates do not overwrite or conflict with earlier states.
c
void nnue_refresh_accumulator(NNUEEvaluator *nnue, NNUEAccumulator *accum, Board *board, int colour, int relsq) {
// Rebuilds the accumulator from scratch for the current board state.
// Uses the stack to ensure consistency.
}
3. Where the Stack is Working
The stack is primarily used during search in the following contexts:
a) Move Generation and Evaluation
The stack is updated whenever a move is made. This includes:
During the recursive search process, the stack ensures that the evaluation state is preserved for each position:
Push: When descending into a deeper ply (move).
Pop: When backtracking to the previous ply.
c) Quiescence Search
The stack is also used during quiescence search, which evaluates tactical positions to stabilize the evaluation.
d) Thread-Local Storage
Each search thread has its own stack to avoid conflicts in multi-threaded searches:
Threads access their stack via board->thread->nnue->current.
e) Incremental vs. Full Updates
Incremental Updates: Most updates are incremental and rely on the deltas stored in the stack.
Full Refresh: In cases where the stack becomes inconsistent (e.g., after a king move), a full refresh is performed using the stack to rebuild the accumulator.
4. Code Example: Stack in Action
Here’s how the stack is used in a typical search scenario:
Before Making a Move:
Push the current accumulator state onto the stack (nnue_push).
After Making a Move:
Incrementally update the accumulator for the new position (nnue_move_piece, etc.).
Evaluate the Position:
Use the updated accumulator to evaluate the position (nnue_evaluate).
Backtrack:
Pop the accumulator state off the stack to revert to the previous position (nnue_pop).
5. Why the Stack is Necessary
The stack is essential because:
The search tree involves exploring multiple branches, and intermediate states must be preserved.
Recomputing the accumulator from scratch at every node would be too expensive.
Incremental updates rely on maintaining a history of changes, which the stack provides.
Conclusion
The stack in the NNUE accumulator is tightly integrated into the search process. It works by maintaining a history of incremental updates to the evaluation state, allowing efficient rollbacks during backtracking. Functions like nnue_push, nnue_pop, and nnue_move_piece drive this mechanism, ensuring that the accumulator remains consistent across the search tree.
b) Stack Size for a Full Search Tree
The stack grows with the depth of the search tree. For a typical chess engine:
Depth of Search:
At a depth of 10 plies, there are ~1,000 nodes.
At a depth of 20 plies, there are ~1,000,000 nodes.
At a depth of 30 plies, there are ~1,000,000,000 nodes.
However, not all nodes are alive at the same time due to pruning (e.g., alpha-beta).
Memory Usage:
If all nodes in a depth-20 search needed stack space, memory usage would be:
1,000,000 nodes × 2.1 KB = ~2 GB.
For a depth-30 search, this scales to 2 TB, which is infeasible.
c) Realistic Stack Size
In reality, the stack size is limited by:
Alpha-Beta Pruning: Only a subset of nodes is fully explored due to pruning.
Iterative Deepening: The search is performed incrementally, and earlier depths are discarded as deeper searches progress.
Thread-Local Storage: Each thread has its own stack, limiting memory usage per thread.
For a thread exploring ~1,000 nodes at a time (common in alpha-beta):
typedef struct {
int piece;
int from;
int to;
} NNUEDelta;
4. Why Ethereal Doesn’t Run Out of Memory
Fixed Stack Allocation:
The stack size is preallocated for the maximum depth (MAX_PLY), ensuring memory usage is bounded.
Thread Isolation:
Each thread has its own independent stack, preventing excessive memory usage in multi-threaded environments.
Efficient Pruning:
Alpha-beta pruning significantly reduces the number of nodes explored, keeping stack usage manageable.
Stack Reuse:
The stack memory is reused during backtracking, avoiding the need for dynamic allocations.
Compact Structures:
The NNUEAccumulator and NNUEDelta structures are designed to minimize memory usage.
5. Estimated Memory Usage
For a search depth of 128 plies (the maximum supported):
Per Thread: ~128 nodes × 2.1 KB = ~270 KB.
For 32 Threads: 32 × 270 KB = ~8.6 MB.
This is well within the memory limits of modern systems, even with many threads running concurrently.
Conclusion
The stack in the NNUE accumulator is carefully managed to avoid running out of memory. Fixed stack sizes, thread-local storage, pruning, and stack reuse ensure that memory usage remains proportional to the depth of the search tree, not the total number of nodes. This allows Ethereal to explore millions of nodes efficiently without exhausting system memory.
a) Thread-Local Stacks
Each thread allocates its own stack for MAX_PLY nodes. For example:
If the engine has N threads and MAX_PLY = 128:
Each thread's stack size = ( 128 \times \text{size of one NNUEAccumulator} )
Total memory usage across all threads = ( N \times \text{stack size per thread} ).
b) Example Calculation
Assume:
MAX_PLY = 128
size of NNUEAccumulator = 2.1 KB (as calculated earlier).
This memory usage is manageable even for systems with limited resources.
4. Bounding the Stack Across All Trees and Branches
The following mechanisms ensure that the stack usage is bounded across all branches and threads:
a) Depth Limitation (MAX_PLY)
The stack size is limited by the maximum search depth (MAX_PLY). Even if a thread explores millions of nodes, it does so one branch at a time, and the stack is reused for each branch. Thus, memory usage for all branches in a single tree is bounded by:
[ \text{Stack size per thread} = \text{MAX_PLY} \times \text{size of NNUEAccumulator} ]
For example:
A depth-128 search will only require stack space for 128 nodes, regardless of how many branches are explored.
b) Alpha-Beta Pruning
Alpha-beta pruning ensures that many branches in the tree are not fully explored. This reduces the number of nodes visited and thus the maximum depth of active stack usage at any given time.
For instance:
In a typical search, only a small percentage of the nodes in the tree are fully explored to the maximum depth.
c) Thread Isolation
Each thread operates independently and maintains its own stack. This prevents memory usage from growing linearly with the total number of branches across all threads.
d) Bounded by Thread Count
The total memory usage is bounded by the number of threads, not the total number of branches in the tree. At any given time:
[ \text{Total memory usage} = \text{Number of threads} \times \text{stack size per thread} ]
This ensures that the engine does not run out of memory, even if the search tree has billions of nodes.
e) Incremental Updates
The NNUEAccumulator uses incremental updates (via deltas) rather than recomputing the full evaluation state for each node. This keeps memory usage low and avoids the need to store large amounts of redundant data.
5. Possible Edge Cases
a) Extremely Deep Searches
If the engine performs an unusually deep search (e.g., MAX_PLY > 128), the stack size may exceed its preallocated memory. To prevent this:
The engine can enforce a hard limit on the maximum search depth.
If a deeper search is attempted, the engine can terminate the search or reduce the depth dynamically.
b) Large Numbers of Threads
On systems with many CPU cores, a large number of threads could lead to high memory usage. For example:
While this is still manageable, systems with limited memory could encounter issues. The engine can mitigate this by:
Reducing the number of threads (threads->nthreads).
Reducing MAX_PLY.
6. Summary of Bounding Mechanisms
Per-Thread Stack: Each thread’s stack is limited to MAX_PLY nodes, ensuring memory usage is proportional to the depth of the search tree, not the total number of branches.
Reusing Stack Memory: The stack is reused for each branch in the tree, so memory usage remains constant regardless of the number of branches.
Thread Isolation: Each thread manages its own stack, and memory usage across all threads is simply the sum of the per-thread stack sizes.
Alpha-Beta Pruning: Reduces the number of nodes searched, minimizing stack usage.
Fixed MAX_PLY: Caps the maximum stack size per thread, ensuring memory usage is bounded.
Incremental Updates: The accumulator uses deltas to minimize memory usage for evaluation updates.
Conclusion
The stack size is bounded per tree by MAX_PLY and reused for all branches within that tree. Across all trees, the total memory usage is limited by the number of threads, as each thread maintains its own stack. These mechanisms ensure that Ethereal's memory usage remains efficient and manageable, even during deep searches or in multi-threaded environments.
INLINE void nnue_move_piece(Board *board, int piece, int from, int to) {
if (USE_NNUE && board->thread != NULL) {
NNUEAccumulator *accum = board->thread->nnue->current;
accum->deltas[accum->changes++] = (NNUEDelta) { piece, from, to };
}
}
Update Features (Incrementally):
The affected features are updated in the NNUE accumulator using the deltas.
For example, nnue_update_accumulator applies the changes recorded in the deltas to the accumulator's values.
c
void nnue_update_accumulator(NNUEAccumulator *accum, Board *board, int colour, int relksq) {
// Applies deltas stored in the accumulator to update NNUE values incrementally.
}
Propagate Changes:
If the NNUE state is not accurate (e.g., due to a king move or other disruptive changes), the engine can recursively update the accumulator using parent nodes in the stack.
c
int nnue_can_update(NNUEAccumulator *accum, Board *board, int colour) {
// Determines if the accumulator can be updated incrementally from parent nodes.
}
Refresh if Necessary:
In cases where incremental updates are insufficient (e.g., after a null move or when history is incomplete), the NNUE accumulator is fully rebuilt using nnue_refresh_accumulator.
c
void nnue_refresh_accumulator(NNUEEvaluator *nnue, NNUEAccumulator *accum, Board *board, int colour, int relsq) {
// Fully rebuilds the NNUE accumulator for the current position.
}
3. Tracing Modifications as the Engine Searches
a) Moving Down the Tree
As the engine explores a new position:
Push the current state of the NNUE accumulator onto the stack (nnue_push).
Apply the move and record deltas in the current NNUEAccumulator:
Update the position of the moving piece.
Add or remove captured/promoted pieces.
Adjust the NNUE input indices affected by the move.
b) Modifying NNUE for the New Position
The NNUE accumulator is updated incrementally:
The nnue_update_accumulator function applies the deltas to modify the NNUE values for the new position.
This ensures that the evaluation is always consistent with the current board state.
c) Backtracking Up the Tree
When the search backtracks (e.g., after exploring a branch):
Restore the previous NNUE state by popping the top NNUEAccumulator from the stack (nnue_pop).
Revert the board state to undo the move.
This process ensures that the NNUE values are always correct and consistent as the engine explores different branches of the search tree.
4. Why Incremental Updates Are Necessary
Without incremental updates, the engine would need to recompute the entire NNUE evaluation from scratch at every node, which would be computationally expensive. Incremental updates allow:
Efficiency: Only the features affected by a move are updated.
Speed: The evaluation is updated in constant time for most moves, as the number of deltas is small.
Scalability: The engine can handle deep searches with millions of nodes without excessive recomputation.
5. How NNUE Modifications Are Traced
The NNUE modifications are traced using the stack and the delta system:
The Stack:
Tracks the state of the NNUE accumulator at each depth in the search tree.
Ensures that the accumulator can be restored when backtracking.
The Delta System:
Records changes caused by moves (piece additions, removals, and movements).
Allows incremental updates to the NNUE input features.
6. Example Workflow
Here’s an example of how the stack and NNUE updates work during a search:
Step 1: Root Node (Initial Position)
The engine starts with the initial position.
The NNUE accumulator is computed for the root position.
Step 2: Move to a Child Node
Push the current NNUE state onto the stack (nnue_push).
Make the move and record the deltas (e.g., update the piece positions).
Update the NNUE accumulator incrementally using the deltas (nnue_update_accumulator).
Step 3: Backtrack to Parent Node
Undo the move and revert the board state.
Restore the previous NNUE state by popping it from the stack (nnue_pop).
Step 4: Explore Another Branch
Push the NNUE state for the parent node onto the stack.
Make the next move and repeat the process.
7. Handling Special Cases
Certain moves or situations require special handling:
King Moves:
A king move changes the relative position of all pieces.
The NNUE accumulator may need a full refresh in this case.
Null Moves:
When a null move is made (skipping a turn), the accumulator is temporarily invalidated and later restored.
Check Detection:
Incremental updates are critical for detecting checks and other tactical features.
Conclusion
Yes, the NNUE accumulator traces up and down the search tree, modifying the NNUE state as it goes. By using a stack to save and restore states and applying delta-based incremental updates, the engine ensures that the NNUE evaluation remains efficient and accurate throughout the search. This combination of stack-based state management and incremental updates is what makes NNUE a powerful and efficient evaluation method in modern chess engines.
In some cases (e.g., after a king move or when the accumulator is not accurate), the engine performs recursive updates to the accumulator:
The engine may need to trace back through the stack to find a valid state.
This can involve significant computation, especially if the stack depth is large.
e) Full Refreshes
When the accumulator cannot be updated incrementally (e.g., after certain moves or null moves), the engine performs a full refresh of the accumulator:
The entire NNUE input feature set is recalculated.
This is far more expensive than incremental updates and can significantly impact runtime.
3. Impact on Runtime and Node Count
Given the overhead described above, the NNUE accumulator can double the runtime or halve the nodes searched due to the following factors:
a) Increased Time Per Node
The additional work required to update the NNUE accumulator increases the time spent evaluating each node. This means the engine can process fewer nodes in the same amount of time.
For example:
Without NNUE: Each node is evaluated using lightweight classical evaluation (e.g., material, piece-square tables).
With NNUE accumulator: Each node incurs extra computation for managing the accumulator, even if the NNUE neural network is not invoked.
b) Reduced Pruning Efficiency
The slower evaluation per node can reduce the effectiveness of search pruning techniques (e.g., alpha-beta pruning, null-move pruning). For instance:
If the engine takes longer to process each node, it may not prune as aggressively, resulting in more nodes being searched.
c) Incremental Update Overhead
While incremental updates are more efficient than full recalculations, they still introduce overhead that does not exist in classical evaluation:
For every move, the engine must calculate and apply deltas, which is computationally expensive.
d) Accumulator Management Overhead
The stack management and recursive updates further add to the overhead, especially in deep searches with many moves.
4. Why This Happens Even Without Running the NNUE Neural Network
The slowdown occurs because the NNUE accumulator is used to prepare and update the input features for the neural network. Even if the neural network itself is not being run:
The engine still performs all the work to maintain and update the accumulator.
This includes delta tracking, index mapping, and stack management.
In essence, the engine is doing all the "setup work" for NNUE but skipping the final neural network evaluation step. This means it incurs almost all the computational cost of NNUE without gaining the benefit of the neural network's evaluation strength.
5. Comparison of Classical Evaluation vs. NNUE Accumulator
Aspect
Classical Evaluation
NNUE Accumulator (without NN)
Evaluation Time
Very fast (simple calculations)
Slower (deltas, index mapping)
Memory Usage
Minimal
Higher (accumulator values, stack)
Incremental Updates
Not required
Required for every move
Stack Management
Not required
Push/pop for every node
Pruning Efficiency
High
Reduced due to slower evaluation
6. How the Engine Could Mitigate This
To reduce the runtime impact of the NNUE accumulator when the neural network is not being used, the engine could:
Disable the Accumulator When NNUE is Disabled:
If NNUE is not enabled, skip all accumulator-related updates and rely solely on classical evaluation.
This avoids all the overhead of managing the accumulator.
Optimize Delta Calculations:
Simplify or cache the computations for NNUE input feature indices (e.g., nnue_index).
Reduce the number of deltas tracked for each move.
Reduce Full Refresh Frequency:
Optimize the conditions under which a full refresh of the accumulator is triggered.
Avoid unnecessary refreshes after null moves or other special cases.
Use Conditional Compilation:
Compile the engine without NNUE-related code when NNUE is disabled, eliminating any runtime overhead.
7. Conclusion
The NNUE accumulator, even when the neural network is not run, introduces significant computational overhead due to delta tracking, stack management, and incremental updates. This can double the runtime or halve the number of nodes searched, as the engine spends more time maintaining the accumulator than performing classical evaluation. Disabling the accumulator entirely when NNUE is not in use could mitigate this impact.
nnue_index
The piece being moved.
Any pieces being added, removed, or promoted.
In a deep search, this can result in millions of calls to nnue_index, making even a small cost per call significant.
b) Complex Computations
The function involves several computationally expensive operations:
Square Mapping (sq64_to_sq32):
Converts a 64-square representation to a 32-square representation, which involves bitwise operations and array lookups.
This is non-trivial and adds up when called repeatedly.
Mirroring Squares (LEFT_FLANK):
The function mirrors squares based on the king's position, requiring conditional checks and XOR operations.
Index Calculation:
Combines multiple inputs (square mapping, piece type, color) into a single index using multiplications and additions.
This introduces computational overhead.
c) Memory Access Overhead
The function accesses several arrays (e.g., sq64_to_sq32, LEFT_FLANK), which can cause cache misses if these arrays are not in the CPU's cache.
This can slow down the function significantly when called repeatedly.
d) Lack of Optimization for Repeated Calls
In many cases, the same indices are computed multiple times for the same pieces (e.g., during incremental updates to the NNUE accumulator).
If the indices are not cached or reused, the function performs redundant computations, wasting CPU cycles.
3. How nnue_index Could Be 5% of Runtime
a) High Call Frequency
In a typical search, the engine evaluates millions of nodes.
Each node requires NNUE accumulator updates, which involve calling nnue_index for multiple pieces.
If nnue_index is called, say, 10 times per node, and the engine evaluates 1,000,000 nodes, that’s 10,000,000 calls to nnue_index.
b) Non-Trivial Cost Per Call
Even if nnue_index takes only 10-20 CPU cycles per call, the sheer volume of calls makes it a significant contributor to runtime.
For example:
Assume nnue_index takes 15 cycles per call.
For 10,000,000 calls, that’s 150,000,000 cycles.
On a 3 GHz CPU, this amounts to 50 ms, which is a significant proportion of the engine's runtime for a single search.
c) Profiling Results
In profiling, small but frequently executed functions like nnue_index often show up as hotspots because their cumulative cost dominates the runtime.
If nnue_index accounts for 5% of the runtime, this suggests that:
The function is being called very frequently.
Its cost, while small per call, adds up due to the large number of calls.
4. Ways to Optimize nnue_index
To reduce the runtime impact of nnue_index, the engine could implement several optimizations:
a) Cache Precomputed Indices
Instead of computing the NNUE index for the same piece multiple times, the engine could cache the computed indices for each piece and reuse them.
For example:
Store the NNUE index for each piece in an array and update it only when the piece moves.
This avoids redundant calls to nnue_index.
b) Inline or Simplify the Function
Inline the function directly into the code that uses it to reduce function call overhead.
Simplify the calculations, especially the mirroring and square mapping logic, to minimize computational cost.
c) Optimize sq64_to_sq32
The sq64_to_sq32 mapping is used frequently and could be optimized further:
Use a faster bitwise operation instead of array lookups.
Precompute all possible mappings for the board and store them in a compact format.
d) Avoid Unnecessary Calls
Analyze whether all calls to nnue_index are necessary. For example:
If a piece’s NNUE index has not changed (e.g., it hasn’t moved or been captured), skip the computation.
e) Parallelize or Batch Updates
Group multiple updates to the NNUE accumulator and process them in a batch, reducing the overhead of repeated calls to nnue_index.
5. Impact of Optimization
By optimizing nnue_index, the engine could:
Reduce the overall runtime by eliminating redundant computations.
Increase the number of nodes searched per second (NPS), improving search efficiency.
Minimize the function’s contribution to the runtime (e.g., from 5% to 1% or less).
6. Conclusion
The nnue_index function can account for 5% of the runtime because:
It is called frequently during the search process (millions of times).
It involves non-trivial computations (square mapping, mirroring, index calculations).
Its cost, while small per call, adds up due to the sheer number of calls.
Optimizing this function through caching, simplification, or batching could significantly reduce its runtime impact and improve the overall performance of the engine.
64 * (...)
Additions cost 1 cycle each.
The total for this part is ~10 cycles.
e) Function Call Overhead
If the function is not inlined, calling it adds overhead:
Setting up the stack frame and passing arguments can cost ~5 cycles.
Returning from the function takes another ~2 cycles.
2. Total Estimated Cycle Count
Adding up the costs of the individual operations:
Operation
Cost (Cycles)
Bitwise operations (e.g., XOR, AND)
~2-4
Logical comparisons
~3-6
Array lookup
~4-50 (depends on cache hit/miss)
Multiplications and additions
~10-15
Function call overhead
~5-7 (if not inlined)
Total (best case)
~20-25
Total (worst case)
~50-80
3. Why nnue_index Might Be Relatively Expensive
a) Array Lookup Delays
The array lookup for sq64_to_sq32 can be costly:
If the array is in L1 cache, the lookup is fast (4-5 cycles).
If the array resides in slower levels of the memory hierarchy (L2/L3 cache or main RAM), it can take tens or even hundreds of cycles.
Frequent calls to this function can cause cache evictions, especially in multi-threaded search scenarios.
b) Multiplications
Multiplications are more expensive than simple bitwise operations or additions, especially if the CPU is older or lacks efficient integer multiplication pipelines.
The multiplications in nnue_index (e.g., 640 * sq64_to_sq32(mksq)) dominate the arithmetic cost.
c) Branching and Predictability
The conditional checks (e.g., if (testBit(...))) depend on the board state and king position. If these branches are unpredictable, the CPU's branch predictor may fail, causing pipeline stalls and adding extra cycles.
d) Function Call Overhead
If nnue_index is not inlined, the function call itself adds several cycles of overhead. This is significant when the function is called millions of times during a search.
e) Frequency of Calls
Even if nnue_index takes only ~20-50 cycles per call, it can dominate runtime because it is called millions of times during a typical search. For example:
If nnue_index is called 10 times per node, and the engine evaluates 1,000,000 nodes, that's 10,000,000 calls.
At 50 cycles per call, that’s 500,000,000 cycles, or ~0.167 seconds on a 3 GHz CPU.
4. Potential Optimizations to Reduce Cycle Count
a) Inline the Function
Inlining nnue_index can eliminate the function call overhead, saving 5-7 cycles per call.
b) Cache Results
Cache the computed indices for pieces that do not move frequently. For example:
Store the NNUE index for each piece in a precomputed array.
Update the cache only when the piece moves.
c) Optimize Array Lookups
Precompute all possible sq64_to_sq32 mappings for common scenarios and store them in a compact format that fits in L1 cache.
Use faster calculations (e.g., bitwise shifts) instead of array lookups for square mappings.
d) Simplify Arithmetic
Combine or eliminate multiplications where possible. For example:
Replace 640 * sq64_to_sq32(mksq) with simpler bitwise operations if the values are powers of two or can be pre-shifted.
e) Reduce Redundant Calls
Avoid calling nnue_index multiple times for the same piece during a single move. For instance:
If the NNUE index for a piece is already known, reuse it instead of recomputing it.
5. Conclusion
The nnue_index function might take 20-80 CPU cycles per call, depending on factors like cache behavior, branching, and arithmetic complexity. While this seems small, the sheer number of calls (millions during a search) makes it a significant contributor to runtime—easily accounting for 5% or more of the total runtime. Optimizations like inlining, caching results, and simplifying computations can reduce its impact significantly.