Skip to content

Investigate the root causes in DeviceScan that lead to invalid values being passed to the custom reduction operator #5019

Closed

Description

@elstehle

Potential root causes (see #5017):

  • Handling and padding of out-of-bounds input items
  • Mathematical correctness of the TailSegmentedReduce implementation
  • Initialization behavior of out-of-bounds tile states
  • Mathematical Correctness of BlockScan implementations

Activity

  1. pauleonix commented on Jul 1, 2025

    @pauleonix
    Contributor

    The handling of out-of-bounds items is clearly a root cause because the underlying BlockScan algorithm does not have any way of specifying a reduced number of elements. Currently only few block-algorithms (BlockLoad and BlockStore + some exceptions like single element-per-thread BlockReduce and *PartialTile versions in BlockAdjacentDifference) have overloads taking a runtime value for the number of elements. This is used to fill the padding with the first item of the tile which becomes an invalid value being passed to the scan operator because it is copied and commuted to the end.

    if constexpr (IS_LAST_TILE)
    {
    // Fill last element with the first element because collectives are
    // not suffix guarded.
    BlockLoadT(temp_storage.load).Load(d_in + tile_offset, items, num_remaining, *(d_in + tile_offset));
    }
    else
    {
    BlockLoadT(temp_storage.load).Load(d_in + tile_offset, items);
    }

    Fixing this means adding a lot of overloads but given that only the last tile needs to call this new overload performance should be fine.

  2. pauleonix commented on Jul 1, 2025

    @pauleonix
    Contributor

    TailSegmentedReduce as used to compute the prefix from the results of previous blacks does not seem to be a root cause as it does not apply its reduction operator when it would combine results from different segments. Combining values among each segment should be fine, even though we are only interested in the first segment (containing the last values due to how we map threads to memory).

    // Get the start flags for each thread in the warp.
    int warp_flags = __ballot_sync(member_mask, flag);
    // Convert to tail-segmented
    if (HEAD_SEGMENTED)
    {
    warp_flags >>= 1;
    }
    // Mask out the bits below the current thread
    warp_flags &= ::cuda::ptx::get_sreg_lanemask_ge();
    // Mask of physical lanes outside the logical warp and convert to logical lanemask
    if (!IS_ARCH_WARP)
    {
    warp_flags = (warp_flags & member_mask) >> (warp_id * LOGICAL_WARP_THREADS);
    }
    // Mask in the last lane of logical warp
    warp_flags |= 1u << (LOGICAL_WARP_THREADS - 1);
    // Find the next set flag
    int last_lane = __clz(__brev(warp_flags));
    T output = input;
    // Template-iterate reduction steps
    ReduceStep(output, reduction_op, last_lane, constant_v<0>);

    // Perform reduction op if valid
    if (offset + lane_id <= last_lane)
    {
    output = reduction_op(input, temp);
    }

    // Get the start flags for each thread in the warp.
    int warp_flags = __ballot_sync(member_mask, flag);
    if (!HEAD_SEGMENTED)
    {
    warp_flags <<= 1;
    }
    // Keep bits above the current thread.
    warp_flags &= ::cuda::ptx::get_sreg_lanemask_gt();
    // Accommodate packing of multiple logical warps in a single physical warp
    if (!IS_ARCH_WARP)
    {
    warp_flags >>= (::cuda::ptx::get_sreg_laneid() / LOGICAL_WARP_THREADS) * LOGICAL_WARP_THREADS;
    }
    // Find next flag
    int next_flag = __clz(__brev(warp_flags));
    // Clip the next segment at the warp boundary if necessary
    if (LOGICAL_WARP_THREADS != 32)
    {
    next_flag = _CUDA_VSTD::min(next_flag, LOGICAL_WARP_THREADS);
    }
    _CCCL_PRAGMA_UNROLL_FULL()
    for (int STEP = 0; STEP < STEPS; STEP++)
    {
    const int OFFSET = 1 << STEP;
    // Share input into buffer
    temp_storage.reduce[lane_id] = input;
    __syncwarp(member_mask);
    // Update input if peer_addend is in range
    if (OFFSET + lane_id < next_flag)
    {
    T peer_addend = temp_storage.reduce[lane_id + OFFSET];
    input = reduction_op(input, peer_addend);
    }

  3. pauleonix commented on Jul 2, 2025

    @pauleonix
    Contributor

    The OOB tile states look like another root-cause:

    The following code waits for the tile states of the next window to have a status of anything other than SCAN_TILE_INVALID, so either SCAN_TILE_OOB or SCAN_TILE_PARTIAL or SCAN_TILE_INCLUSIVE and then fill our value correspondingly:

    template <class DelayT = detail::default_delay_t<T>>
    _CCCL_DEVICE _CCCL_FORCEINLINE void
    ProcessWindow(int predecessor_idx, StatusWord& predecessor_status, T& window_aggregate, DelayT delay = {})
    {
    T value;
    tile_status.WaitForValid(predecessor_idx, predecessor_status, value, delay);

    The value is then passed to the TailSegmentedReduce described in the previous comment.

    The implementation of the ScanTileState and therefore WaitForValid() depends on the element type being fundamental (detail::is_primitive<T>::value) or not.

    Fundamental

    In this case a kind of AoS implementation is used where the status and the value are packed into one TxnWord aliased to TileDescriptor:

    // Device word type
    struct TileDescriptor
    {
    StatusWord status;
    T value;
    };

    So once the status is not SCAN_TILE_INVALID anymore for all lanes of the warp (only first warp of the block executes this), we just take the value from the already loaded TileDescriptor:

    template <class DelayT = detail::default_delay_t<T>, MemoryOrder Order = MemoryOrder::relaxed>
    _CCCL_DEVICE _CCCL_FORCEINLINE void
    WaitForValid(int tile_idx, StatusWord& status, T& value, DelayT delay_or_prevent_hoisting = {})
    {
    TileDescriptor tile_descriptor;
    {
    TxnWord alias = LoadStatus<Order>(d_tile_descriptors + TILE_STATUS_PADDING + tile_idx);
    tile_descriptor = reinterpret_cast<TileDescriptor&>(alias);
    }
    while (__any_sync(0xffffffff, (tile_descriptor.status == SCAN_TILE_INVALID)))
    {
    delay_or_prevent_hoisting();
    TxnWord alias = LoadStatus<Order>(d_tile_descriptors + TILE_STATUS_PADDING + tile_idx);
    tile_descriptor = reinterpret_cast<TileDescriptor&>(alias);
    }
    // For pre-Volta and load acquire we emit relaxed loads in LoadStatus and hoist the threadfence here
    ThreadfenceForLoadAcqPreVolta<Order>();
    status = tile_descriptor.status;
    value = tile_descriptor.value;
    }

    Therefore we look at how these descriptors were initialized for SCAN_TILE_OOB:

    /**
    * Initialize (from device)
    */
    _CCCL_DEVICE _CCCL_FORCEINLINE void InitializeStatus(int num_tiles)
    {
    int tile_idx = (blockIdx.x * blockDim.x) + threadIdx.x;
    TxnWord val = TxnWord();
    TileDescriptor* descriptor = reinterpret_cast<TileDescriptor*>(&val);
    if (tile_idx < num_tiles)
    {
    // Not-yet-set
    descriptor->status = StatusWord(SCAN_TILE_INVALID);
    d_tile_descriptors[TILE_STATUS_PADDING + tile_idx] = val;
    }
    if ((blockIdx.x == 0) && (threadIdx.x < TILE_STATUS_PADDING))
    {
    // Padding
    descriptor->status = StatusWord(SCAN_TILE_OOB);
    d_tile_descriptors[threadIdx.x] = val;
    }
    }

    As we can see, the value part is never initialized but should be zeroed from initializing TxnWord. This zeroed value is an invalid element.

    Non-fundamental

    Here the ScanTileState is implemented in a SoA-fashion so the value is only loaded from gmem once the status of all lanes is not SCAN_TILE_INVALID anymore:

    /**
    * Wait for the corresponding tile to become non-invalid
    */
    template <class DelayT = detail::default_no_delay_t, MemoryOrder Order = MemoryOrder::relaxed>
    _CCCL_DEVICE _CCCL_FORCEINLINE void WaitForValid(int tile_idx, StatusWord& status, T& value, DelayT delay = {})
    {
    do
    {
    delay();
    status = detail::load_relaxed(d_tile_status + TILE_STATUS_PADDING + tile_idx);
    __threadfence();
    } while (__any_sync(0xffffffff, (status == SCAN_TILE_INVALID)));
    if (status == StatusWord(SCAN_TILE_PARTIAL))
    {
    value = ThreadLoad<LOAD_CG>(d_tile_partial + TILE_STATUS_PADDING + tile_idx);
    }
    else if (status == StatusWord(SCAN_TILE_INCLUSIVE))
    {
    value = ThreadLoad<LOAD_CG>(d_tile_inclusive + TILE_STATUS_PADDING + tile_idx);
    }
    }

    In case of SCAN_TILE_OOB, value is not modified at all and remains in the default initialized state from the first code snippet in this comment which is an invalid value.

    Solution

    Luckily there seems to be an easy fix for avoiding these invalid values being passed to the scan operator that might also be relatively harmless in terms of performance:

    int tail_flag = (predecessor_status == StatusWord(SCAN_TILE_INCLUSIVE));
    window_aggregate =
    WarpReduceT(temp_storage.warp_reduce).TailSegmentedReduce(value, tail_flag, SwizzleScanOp<ScanOpT>(scan_op));
    }

    Just change the calculation of tail flags above to

    int tail_flag = (predecessor_status == StatusWord(SCAN_TILE_INCLUSIVE) || predecessor_status == StatusWord(SCAN_TILE_OOB));

    This means that every OOB value gets its own segment which, according to my previous comment about the workings of TailSegmentedReduce(), is not combined with the values of other segments (specifically the other OOB values).

    EDIT: Not quite enough, see #5019 (comment) below.

  4. pauleonix commented on Jul 7, 2025

    @pauleonix
    Contributor

    After finding higher than expected error counts in our test, we found another root cause: The BlockScan can be problematic even when not handling OOB items. In particular BLOCK_SCAN_WARP_SCANS dispatches to detail::WarpScanShfl which runs

    template <typename _T, typename ScanOpT>
    _CCCL_DEVICE _CCCL_FORCEINLINE _T InclusiveScanStep(_T input, ScanOpT scan_op, int first_lane, int offset)
    {
    _T temp = ShuffleUp<LOGICAL_WARP_THREADS>(input, offset, first_lane, member_mask);
    // Perform scan op if from a valid peer
    _T output = scan_op(temp, input);
    if (static_cast<int>(lane_id) < first_lane + offset)
    {
    output = input;
    }
    return output;
    }

    I.e. the scan operator is applied unconditionally which avoids warp divergence but causes invalid elements being passed to it. So changing the code here would most probably cause significant performance regressions. Another question is if just using other block/warp scan implementation isn't preferrable in terms of performance to "fixing" detail::WarpScanShfl.

  5. moved this from Todo to Done in CCCLon Jul 9, 2025
  6. elstehle commented on Jul 9, 2025

    @elstehle
    ContributorAuthor

    Closing the issue since all presumed root causes have been analyzed - and even one more has been identified. Thank you for the investigation and the excellent documentation, @pauleonix.

  7. pauleonix commented on Aug 21, 2025

    @pauleonix
    Contributor

    Another problematic application of the scan op for BLOCK_SCAN_WARP_SCANS:

    T warp_prefix = ComputeWarpPrefix(scan_op, inclusive_output, block_aggregate, initial_value);
    // Apply warp prefix to our lane's partial
    exclusive_output = scan_op(warp_prefix, exclusive_output);
    if (lane_id == 0)
    {
    exclusive_output = warp_prefix;
    }

    The first warp gets a default-initialized warp_prefix from ComputeWarpPrefix which is in general an invalid input to a custom scan op.

    Fix: Put the scan op in an else branch of the given conditional.

  8. pauleonix commented on Aug 22, 2025

    @pauleonix
    Contributor

    The OOB tile states look like another root-cause:

    The following code waits for the tile states of the next window to have a status of anything other than SCAN_TILE_INVALID, so either SCAN_TILE_OOB or SCAN_TILE_PARTIAL or SCAN_TILE_INCLUSIVE and then fill our value correspondingly:

    Solution

    Luckily there seems to be an easy fix for avoiding these invalid values being passed to the scan operator that might also be relatively harmless in terms of performance:

    Just change the calculation of tail flags above to

    int tail_flag = (predecessor_status == StatusWord(SCAN_TILE_INCLUSIVE) || predecessor_status == StatusWord(SCAN_TILE_OOB));

    This means that every OOB value gets its own segment which, according to my previous comment about the workings of TailSegmentedReduce(), is not combined with the values of other segments (specifically the other OOB values).

    This is not quite true. I overlooked that while only the first lane gets a valid result out of the segmented reduction, all lanes apply the scan_op to their respective results containing invalid elements. Therefore another conditional is needed around the call to scan_op in

    while (__all_sync(0xffffffff, (predecessor_status != StatusWord(SCAN_TILE_INCLUSIVE))))
    {
    predecessor_idx -= detail::warp_threads;
    // Update exclusive tile prefix with the window prefix
    ProcessWindow(predecessor_idx, predecessor_status, window_aggregate, construct_delay());
    exclusive_prefix = scan_op(window_aggregate, exclusive_prefix);
    }

    This change could be another heavy performance hit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

  • Status
    Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions