/**
 * ----------------------------------------------------------------------------------------------------------
 * Copyright (c) 2026 Huawei Technologies Co., Ltd.
 * This program is free software; you can redistribute it and/or modify it under the terms and conditions of
 * CANN Open Software License Agreement Version 2.0 (the "License").
 * Please refer to the License for details. You may not use this file in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 * ----------------------------------------------------------------------------------------------------------
 */

/*!
 * \file prune_kernel.cpp
 * \brief sparseLt prune device-side kernel + extern "C" launcher.
 *
 * Kernels:
 *   - prune_kernel    (AIV_ONLY, low-level AscendC Vector API): structured prune A -> A_pruned
 *
 * Launchers wrap <<<>>> in the ASC translation unit; host.cpp calls them as plain C functions.
 * Tiling is passed by value through the kernel launch args block
 * (AclsparseltTilingData is a POD struct).
 * The TilingData struct definition lives in shared/aclsparselt_internal.h.
 */


#include <cstdint>

#include "log/log.h"

#include "kernel_operator.h"

#include "shared/aclsparselt_internal.h"
#include "prune_kernel.h"

#ifdef __CCE_AICORE__
static constexpr const char* kSparseLtLogTag = "aclsparseLt";
#endif

using namespace AscendC;

// ============================================================================
// TILE mode lookup tables.
// 4x4 tile, 2-per-row, 2-per-col: 90 valid configurations.
// Each entry: 4 row-masks, bit c set = keep column c in that row.
// Generated by enumerating all C(4,2)^4 = 1296 row selections
// and filtering to those with col_sum=2 (yields 90).
//
// NOTE: Defined as local arrays inside SpltPruneTileDispatch (not namespace-
// scope static const) because the ASC compiler does not correctly initialize
// namespace-scope static const arrays in AICore code — mask values read as
// 0xFF, causing all elements to be "kept" and none zeroed.
//
// The 90-entry 4x4 and 4-entry 2x2 initializer lists are defined
// once here as macros and consumed by both SpltPruneTileDispatch and
// SpltPruneAlongRowUnified. This guarantees the two function-local copies are
// byte-identical (single source of truth) without introducing static storage,
// which the ASC compiler mis-initializes (see NOTE above).
// ============================================================================
#define SPLT_CONFIGS_2X2_INIT 0b01, 0b10, 0b10, 0b01
#define SPLT_CONFIGS_4X4_INIT \
    3,3,12,12, 3,5,10,12, 3,5,12,10, 3,6,9,12, 3,6,12,9, 3,9,6,12, 3,9,12,6, 3,10,5,12, \
    3,10,12,5, 3,12,3,12, 3,12,5,10, 3,12,6,9, 3,12,9,6, 3,12,10,5, 3,12,12,3, 5,3,10,12, \
    5,3,12,10, 5,5,10,10, 5,6,9,10, 5,6,10,9, 5,9,6,10, 5,9,10,6, 5,10,3,12, 5,10,5,10, \
    5,10,6,9, 5,10,9,6, 5,10,10,5, 5,10,12,3, 5,12,3,10, 5,12,10,3, 6,3,9,12, 6,3,12,9, \
    6,5,9,10, 6,5,10,9, 6,6,9,9, 6,9,3,12, 6,9,5,10, 6,9,6,9, 6,9,9,6, 6,9,10,5, \
    6,9,12,3, 6,10,5,9, 6,10,9,5, 6,12,3,9, 6,12,9,3, 9,3,6,12, 9,3,12,6, 9,5,6,10, \
    9,5,10,6, 9,6,3,12, 9,6,5,10, 9,6,6,9, 9,6,9,6, 9,6,10,5, 9,6,12,3, 9,9,6,6, \
    9,10,5,6, 9,10,6,5, 9,12,3,6, 9,12,6,3, 10,3,5,12, 10,3,12,5, 10,5,3,12, 10,5,5,10, \
    10,5,6,9, 10,5,9,6, 10,5,10,5, 10,5,12,3, 10,6,5,9, 10,6,9,5, 10,9,5,6, 10,9,6,5, \
    10,10,5,5, 10,12,3,5, 10,12,5,3, 12,3,3,12, 12,3,5,10, 12,3,6,9, 12,3,9,6, 12,3,10,5, \
    12,3,12,3, 12,5,3,10, 12,5,10,3, 12,6,3,9, 12,6,9,3, 12,9,3,6, 12,9,6,3, 12,10,3,5, \
    12,10,5,3, 12,12,3,3

// ============================================================================
// Prune helpers below use scalar GetValue/SetValue for
// element-wise compare/zero. Vectorization is not applied because:
//  - 1:2 pairwise keep-max and 2:4 top-2 selection along-col (SpltPruneGroupN
//    with stride > 1, used by the ColView STRIP/TILE paths) cannot
//    be vectorized without gather; strided column access is non-contiguous and
//    GatherMask is non-preferred on arch35 (DAV_3510).
//  - Tail element zero-out with stride > 1 (SpltPruneGroupN, count not multiple
//    of groupSize) operates on at most groupSize-1 non-contiguous elements per
//    call; Duplicate is not applicable for stride > 1.
//  - TILE 90-config enumeration (SpltPruneTile) is scalar control flow;
//    per-config L1-norm is a 16-element reduction and per-config masking
//    zero-out of non-kept elements — both with marginal vectorization benefit.
//  - The RowView path (stride=1) uses SpltPruneGroupNVec (vectorized Cast +
//    Abs + Mul keepMask with scalar GetValue per-group comparison). Scalar
//    GetValue/SetValue remains for ColView (stride > 1), TILE 90-config,
//    stride > 1 tail zero-out, and __bf16 / int8_t (Cast API does not support
//    these type pairs). With (b) layout preserving, ColView direct stores
//    perform all moves via DataCopyPad (int8_t no longer limited by TransDataTo5HD).
// ============================================================================

// ============================================================================
// 2:4 prune helpers (scalar, dtype-agnostic via template)
// For each group of 4 contiguous elements: keep the 2 largest |value|, zero the
// other 2. Tie -> keep lower indices (deterministic).
//
// [BF16-FIX] DAV-3510 backend does not support static_cast for __bf16 (triggers
// "not support bf16 type cast" at code generation). These helpers use union-
// based bit reinterpretation (same pattern as SDK GetScalarBitcodeValue) to
// convert between FP32 and BF16 without emitting any backend BF16 cast.
// ============================================================================

// FP32 → BF16 with RNE (round-to-nearest-even) truncation.
__aicore__ inline bfloat16_t SpltFp32ToBf16(float fVal)
{
    union Fp32Bits { float f; uint32_t u; } src;
    src.f = fVal;
    uint32_t u32 = src.u;
    const uint32_t lsb = (u32 >> 16) & 1;
    const uint32_t roundingBias = 0x7FFFu + lsb;
    u32 += roundingBias;
    union Bf16Bits { uint16_t u; bfloat16_t b; } dst;
    dst.u = static_cast<uint16_t>(u32 >> 16);
    return dst.b;
}

// BF16 → FP32 (zero-extend upper 16 bits, lower 16 = 0).
__aicore__ inline float SpltBf16ToFp32(bfloat16_t bVal)
{
    union Bf16Bits { bfloat16_t b; uint16_t u; } src;
    src.b = bVal;
    union Fp32Bits { uint32_t u; float f; } dst;
    dst.u = static_cast<uint32_t>(src.u) << 16;
    return dst.f;
}

// T → float: uses SpltBf16ToFp32 for BF16, static_cast for others.
template <typename T>
__aicore__ inline float SpltCastToFloat(T val)
{
    if constexpr (std::is_same_v<T, __bf16>) {
        return SpltBf16ToFp32(val);
    } else {
        return static_cast<float>(val);
    }
}

// Returns a zero value of type T. For BF16, uses union to avoid static_cast.
template <typename T>
__aicore__ inline T SpltZeroValue()
{
    if constexpr (std::is_same_v<T, __bf16>) {
        union Bf16Bits { uint16_t u; bfloat16_t b; } z;
        z.u = 0;
        return z.b;
    } else {
        return static_cast<T>(0);
    }
}
template <typename T>
__aicore__ inline void SpltPruneGroup4(T* g)
{
    float a[4];
    for (int i = 0; i < 4; ++i) {
        a[i] = SpltCastToFloat<T>(g[i]);
    }
    float absA[4];
    for (int i = 0; i < 4; ++i) {
        absA[i] = a[i] < 0 ? -a[i] : a[i];
    }
    // Find top-2 by abs, tie keeps lower index (uses > not >=).
    int keep0 = 0;
    if (absA[1] > absA[0]) { keep0 = 1; }
    if (absA[2] > (keep0 == 0 ? absA[0] : absA[1])) { keep0 = 2; }
    if (absA[3] > (keep0 == 0 ? absA[0] : keep0 == 1 ? absA[1] : absA[2])) { keep0 = 3; }
    int keep1 = -1;
    float best1 = -1.0f;
    for (int idx = 0; idx < 4; ++idx) {
        if (idx == keep0) { continue; }
        if (keep1 < 0 || absA[idx] > best1) { best1 = absA[idx]; keep1 = idx; }
    }
    // zero out the two non-kept positions
    for (int idx = 0; idx < 4; ++idx) {
        if (idx != keep0 && idx != keep1) {
            g[idx] = SpltZeroValue<T>();
        }
    }
}

template <typename T>
__aicore__ inline void SpltPruneGroupN(
    LocalTensor<T>& ub, int32_t base, int32_t stride,
    int32_t count, int32_t groupSize)
{
    int32_t groups = count / groupSize;
    for (int32_t gi = 0; gi < groups; ++gi) {
        int32_t b = base + gi * groupSize * stride;
        if constexpr (std::is_same_v<T, float>) {
            float g0 = static_cast<float>(ub.GetValue(b));
            float g1 = static_cast<float>(ub.GetValue(b + stride));
            float a0 = g0 < 0 ? -g0 : g0;
            float a1 = g1 < 0 ? -g1 : g1;
            if (a0 >= a1) {
                ub.SetValue(b + stride, static_cast<T>(0));
            } else {
                ub.SetValue(b, static_cast<T>(0));
            }
        } else {
            T g[4];
            for (int t = 0; t < 4; ++t) {
                g[t] = ub.GetValue(b + t * stride);
            }
            SpltPruneGroup4<T>(g);
            for (int t = 0; t < 4; ++t) {
                ub.SetValue(b + t * stride, g[t]);
            }
        }
    }
    for (int32_t t = groups * groupSize; t < count; ++t) {
        ub.SetValue(base + t * stride, SpltZeroValue<T>());
    }
}

template <typename T>
__aicore__ inline void SpltPruneGroupNVecMask(
    LocalTensor<float>& absUB, LocalTensor<float>& keepMaskUB,
    int32_t groups, int32_t groupSize)
{
    for (int32_t gi = 0; gi < groups; ++gi) {
        int32_t b = gi * groupSize;
        if constexpr (std::is_same_v<T, float>) {
            float a0 = absUB.GetValue(b);
            float a1 = absUB.GetValue(b + 1);
            int32_t nonKeep = (a0 >= a1) ? 1 : 0;
            keepMaskUB.SetValue(b + nonKeep, 0.0f);
        } else {
            float absVals[4];
            for (int32_t t = 0; t < 4; ++t) {
                absVals[t] = absUB.GetValue(b + t);
            }
            int32_t keep0 = 0;
            if (absVals[1] > absVals[0]) { keep0 = 1; }
            if (absVals[2] > (keep0 == 0 ? absVals[0] : absVals[1])) { keep0 = 2; }
            if (absVals[3] > (keep0 == 0 ? absVals[0] : keep0 == 1 ? absVals[1] : absVals[2])) { keep0 = 3; }
            int32_t keep1 = -1;
            float best1 = -1.0f;
            for (int32_t idx = 0; idx < 4; ++idx) {
                if (idx == keep0) { continue; }
                if (keep1 < 0 || absVals[idx] > best1) { best1 = absVals[idx]; keep1 = idx; }
            }
            for (int32_t idx = 0; idx < 4; ++idx) {
                if (idx != keep0 && idx != keep1) {
                    keepMaskUB.SetValue(b + idx, 0.0f);
                }
            }
        }
    }
}

template <typename T>
__aicore__ inline void SpltPruneGroupNVecApply(
    LocalTensor<T>& srcUB, LocalTensor<float>& absUB,
    LocalTensor<float>& keepMaskUB,
    int32_t base, int32_t count)
{
    PipeBarrier<PIPE_V>();
    if constexpr (std::is_same_v<T, float>) {
        Mul<float>(srcUB[base], srcUB[base], keepMaskUB, count);
        PipeBarrier<PIPE_V>();
    } else {
        Cast<float, T>(absUB, srcUB[base], RoundMode::CAST_NONE, count);
        PipeBarrier<PIPE_V>();
        Mul<float>(absUB, absUB, keepMaskUB, count);
        PipeBarrier<PIPE_V>();
        Cast<T, float>(srcUB[base], absUB, RoundMode::CAST_ROUND, count);
        PipeBarrier<PIPE_V>();
    }
}

template <typename T>
__aicore__ inline void SpltPruneGroupNVec(
    LocalTensor<T>& srcUB, LocalTensor<float>& absUB,
    LocalTensor<float>& keepMaskUB,
    int32_t base, int32_t count, int32_t groupSize)
{
    // __bf16/int8_t fall back to scalar: Cast<float> not
    // supported/preferred on arch35 for these types.
    if constexpr (std::is_same_v<T, __bf16> || std::is_same_v<T, int8_t>) {
        SpltPruneGroupN<T>(srcUB, base, 1, count, groupSize);
        return;
    }
    // count < groupSize 时标量回退(如 TILE edge tile 回退到 STRIP 时的尾部行)。
    // 下方 tailCount > 0 分支处理 count % groupSize != 0 的尾部元素(置零)。
    if (count < groupSize) {
        SpltPruneGroupN<T>(srcUB, base, 1, count, groupSize);
        return;
    }
    PipeBarrier<PIPE_V>();
    if constexpr (std::is_same_v<T, float>) {
        Abs<float>(absUB, srcUB[base], count);
        PipeBarrier<PIPE_V>();
    } else {
        Cast<float, T>(absUB, srcUB[base], RoundMode::CAST_NONE, count);
        PipeBarrier<PIPE_V>();
        Abs<float>(absUB, absUB, count);
        PipeBarrier<PIPE_V>();
    }
    Duplicate<float>(keepMaskUB, 1.0f, count);
    PipeBarrier<PIPE_V>();
    int32_t groups = count / groupSize;
    SpltPruneGroupNVecMask<T>(absUB, keepMaskUB, groups, groupSize);
    int32_t tailCount = count - groups * groupSize;
    if (tailCount > 0) {
        Duplicate<float>(keepMaskUB[groups * groupSize], 0.0f, tailCount);
    }
    SpltPruneGroupNVecApply<T>(srcUB, absUB, keepMaskUB, base, count);
}

// SpltPruneLoadRowBlockChunk — chunked GM→UB load for trans paths with large m.
// Loads curRowTile rows × curCols columns starting at (rowStart, colStart) from
// the (k, m) row-major GM source (ld ≥ m). The destination UB row stride is
// forced to alignedStride * sizeof(T) via dstStride padding, so all subsequent
// scalar/Transpose access can use alignedStride uniformly across chunks.
//
// dstStride is in 32-byte blocks (UB-side stride unit per DataCopyPad spec).
// Total UB row stride = ceil_32(curCols * sizeof(T)) + dstStride * 32 bytes,
// which equals alignedStride * sizeof(T) when chunkM is aligned to 32B/elemSize.
// For the full chunk (curCols == chunkM), dstStride = 0 (natural alignment
// already equals alignedStride). For the tail chunk (curCols < chunkM),
// dstStride > 0 pads the row to the fixed stride.
template <typename T>
__aicore__ inline void SpltPruneLoadRowBlockChunk(
    LocalTensor<T>& blkUB, GlobalTensor<T>& aGM,
    DataCopyExtParams& copyParams, DataCopyPadExtParams<T>& padParams,
    int32_t rowStart, int32_t curRowTile, int32_t colStart,
    int32_t curCols, int32_t ld, int32_t alignedStride)
{
    copyParams.blockCount = static_cast<uint32_t>(curRowTile);
    copyParams.blockLen = static_cast<uint32_t>(curCols * sizeof(T));
    copyParams.srcStride = static_cast<uint32_t>((ld - curCols) * sizeof(T));
    // Force UB row stride = alignedStride * sizeof(T).
    // dstStride (32B blocks) = (alignedStride * sizeof(T) - ceil_32(blockLen)) / 32.
    const int32_t naturalBytes = (curCols * static_cast<int32_t>(sizeof(T)) +
                                   SPLT_UB_ALIGN_BYTES - 1) /
                                   SPLT_UB_ALIGN_BYTES * SPLT_UB_ALIGN_BYTES;
    const int32_t dstStrideBytes =
        alignedStride * static_cast<int32_t>(sizeof(T)) - naturalBytes;
    copyParams.dstStride = static_cast<uint32_t>(dstStrideBytes / SPLT_UB_ALIGN_BYTES);
    DataCopyPad(blkUB, aGM[static_cast<int64_t>(rowStart) * ld + colStart],
                copyParams, padParams);
    PipeBarrier<PIPE_MTE2>();
}

// RowView ((N,ROW)/(T,COL)) UB->GM store: output keeps the input (order, ld)
// layout — each row writes rowLen elements at rowStart*outLd; the GM-side
// dstStride skips the [rowLen, outLd) padding (padding is never written, user
// values are kept; under in-place the input padding is preserved as-is).
// blockCount/blockLen reuse the load-side values; UB-side srcStride=0 (k*elemSize
// is a 32B multiple — guaranteed by the descriptor 32B/elem alignment — so rows
// are naturally contiguous in 32B slots).
// GM-side padded 2D write precedent: SpltFusedEpilogueOutputFp32 (same dstStride
// formula).
// S->MTE3 sync: the RowView prune writes are NOT all on the V pipe — the
// float/__fp16 STRIP main path lands via Mul/Cast (V), but the TILE path
// (SpltPruneTile 90-config masking + STRIP tail fallback) and the __bf16 /
// int8_t / short-row scalar fallbacks (SpltPruneGroupN) write blkUB with
// scalar SetValue (S pipe). A lone V_MTE3 flag fires immediately when the V
// pipe is idle, letting MTE3 read blkUB before the scalar writes are visible
// (pruned-out elements written back with their original values — a
// timing-dependent silent failure). The double barrier (V_MTE3 + S_MTE3)
// uniformly covers every producer pipe without enumerating per path; setting
// an extra flag for an idle pipe is harmless (devkit precedent: the
// SetFlag/WaitFlag<HardEvent::S_MTE3> idiom in dav_m200/dav_c100
// kernel_operator_sync_impl.h, scalar UB write -> copy_ubuf_to_gm).
template <typename T>
__aicore__ inline void SpltPruneStoreRowBlock(
    LocalTensor<T>& blkUB, GlobalTensor<T>& aOutGM,
    DataCopyExtParams& copyParams,
    int32_t rowStart, int32_t rowLen, int32_t outLd)
{
    SetFlag<HardEvent::V_MTE3>(0);
    WaitFlag<HardEvent::V_MTE3>(0);
    SetFlag<HardEvent::S_MTE3>(0);
    WaitFlag<HardEvent::S_MTE3>(0);
    copyParams.srcStride = 0;
    copyParams.dstStride = static_cast<uint32_t>((outLd - rowLen) * sizeof(T));
    DataCopyPad(aOutGM[static_cast<int64_t>(rowStart) * outLd], blkUB, copyParams);
    SetFlag<HardEvent::MTE3_MTE2>(0);
    WaitFlag<HardEvent::MTE3_MTE2>(0);
}

// ColView ((N,COL)/(T,ROW)) in-place direct store: UB block (row stride
// alignedStride) -> GM same-position block in (k,m) row-major ld (base
// rowStart*ld + colStart). The UB-side srcStride mirrors the load-side
// dstStride formula of SpltPruneLoadRowBlockChunk (in 32B slot units);
// the GM-side dstStride skips the [curCols, ld) padding. The transpose
// write-back mechanism (TransWrite* + transBuf) has been removed — kept/zeroed
// elements land directly back at the same physical positions they were read from.
// S->MTE3 sync: on BOTH ColView paths the prune writes are entirely scalar
// (S pipe) — STRIP's SpltPruneGroupN runs with stride > 1 (grouping along
// physical columns) and TILE's 90-config masking + tail handling
// (SpltPruneTile / SpltPruneTileTransTails) all use GetValue/SetValue. The
// V pipe is idle, so a lone V_MTE3 flag fires immediately and MTE3 could
// start reading blkUB before the scalar writes are visible (pruned-out
// elements written back with their original values — a timing-dependent
// silent failure). The double barrier (V_MTE3 + S_MTE3) uniformly covers
// both producer pipes; the extra flag on an idle pipe is harmless (devkit
// precedent: the SetFlag/WaitFlag<HardEvent::S_MTE3> idiom in dav_m200 /
// dav_c100 kernel_operator_sync_impl.h, scalar UB write -> copy_ubuf_to_gm).
template <typename T>
__aicore__ inline void SpltPruneStoreRowBlockCol(
    LocalTensor<T>& blkUB, GlobalTensor<T>& aOutGM,
    DataCopyExtParams& copyParams,
    int32_t rowStart, int32_t colStart, int32_t curRowTile,
    int32_t curCols, int32_t ld, int32_t alignedStride)
{
    SetFlag<HardEvent::V_MTE3>(0);
    WaitFlag<HardEvent::V_MTE3>(0);
    SetFlag<HardEvent::S_MTE3>(0);
    WaitFlag<HardEvent::S_MTE3>(0);
    copyParams.blockCount = static_cast<uint32_t>(curRowTile);  // <= TRANS_TILE(16) < 32-block cap
    copyParams.blockLen = static_cast<uint32_t>(curCols * sizeof(T));
    const int32_t naturalBytes = (curCols * static_cast<int32_t>(sizeof(T)) +
                                   SPLT_UB_ALIGN_BYTES - 1) /
                                   SPLT_UB_ALIGN_BYTES * SPLT_UB_ALIGN_BYTES;
    copyParams.srcStride = static_cast<uint32_t>(
        (alignedStride * static_cast<int32_t>(sizeof(T)) - naturalBytes) / SPLT_UB_ALIGN_BYTES);
    copyParams.dstStride = static_cast<uint32_t>((ld - curCols) * sizeof(T));
    DataCopyPad(aOutGM[static_cast<int64_t>(rowStart) * ld + colStart], blkUB, copyParams);
    SetFlag<HardEvent::MTE3_MTE2>(0);  // cross-iteration WAR: drain before the next chunk load overwrites blkUB
    WaitFlag<HardEvent::MTE3_MTE2>(0);
}

// ============================================================================
// PRUNE KERNEL (AIV_ONLY)
//   Uses DataCopyPad (GM<->UB) instead of scalar __gm__ access.
//   Tiling is received by value via the kernel launch args block.
//
// SpltPruneImpl is a thin dispatcher that sets up GlobalTensor and calls
// the appropriate path. Cross-iteration PIPE_ALL barriers replaced with
// precise SetFlag/WaitFlag pairs (MTE3_MTE2 / MTE3_V) for WAR sync.
// ============================================================================

// ----------------------------------------------------------------------------
// [TILE] SpltPruneTile — core TILE prune for one TS×TS tile in UB.
// Enumerates all valid configurations, selects the one with maximum L1-norm
// (sum of |kept elements|), then zeros non-kept elements.
// Tie -> lower config index (uses > not >=).
//
// UB layout: element (r,c) at offset (rowBase + r) * stride + colBase + c.
//
// Template params:
//   T            — data type (float / __fp16)
//   TS           — tile size (4 for FP16, 2 for FP32)
//   CONFIG_COUNT — number of valid configs (90 for 4x4, 2 for 2x2)
// ----------------------------------------------------------------------------
template <typename T, int TS, int CONFIG_COUNT>
__aicore__ inline void SpltPruneTile(
    LocalTensor<T>& blkUB, int32_t rowBase, int32_t colBase, int32_t stride,
    const uint8_t* configs)
{
    float bestSum = -1.0f;
    int32_t bestCfg = 0;
    for (int32_t cfg = 0; cfg < CONFIG_COUNT; ++cfg) {
        float sum = 0.0f;
        for (int32_t r = 0; r < TS; ++r) {
            uint8_t mask = configs[cfg * TS + r];
            for (int32_t c = 0; c < TS; ++c) {
                if (mask & (1u << c)) {
                    T val = blkUB.GetValue((rowBase + r) * stride + colBase + c);
                    float fv = SpltCastToFloat<T>(val);
                    sum += (fv < 0.0f) ? -fv : fv;
                }
            }
        }
        if (sum > bestSum) {
            bestSum = sum;
            bestCfg = cfg;
        }
    }
    for (int32_t r = 0; r < TS; ++r) {
        uint8_t mask = configs[bestCfg * TS + r];
        for (int32_t c = 0; c < TS; ++c) {
            if (!(mask & (1u << c))) {
                blkUB.SetValue((rowBase + r) * stride + colBase + c, SpltZeroValue<T>());
            }
        }
    }
}

// SpltPruneTileDispatch — convenience wrapper that selects the correct config
// table and tile size based on dtype T. Reduces call-site verbosity.
// NOTE: Lookup tables are defined as local 1D arrays here (not namespace-scope
// static const) because the ASC compiler does not correctly initialize
// namespace-scope static const arrays in AICore code. 1D format is used
// to avoid potential 2D array memory layout issues in ASC.
template <typename T>
__aicore__ inline void SpltPruneTileDispatch(
    LocalTensor<T>& blkUB, int32_t rowBase, int32_t colBase, int32_t stride)
{
    if constexpr (std::is_same_v<T, float>) {
        const uint8_t configs[SPLT_TILE_CONFIGS_2X2 * SPLT_TILE_SIZE_FP32] = { SPLT_CONFIGS_2X2_INIT };
        SpltPruneTile<T, SPLT_TILE_SIZE_FP32, SPLT_TILE_CONFIGS_2X2>(
            blkUB, rowBase, colBase, stride, configs);
    } else {
        const uint8_t configs[SPLT_TILE_CONFIGS_4X4 * SPLT_TILE_SIZE_FP16] = { SPLT_CONFIGS_4X4_INIT };
        SpltPruneTile<T, SPLT_TILE_SIZE_FP16, SPLT_TILE_CONFIGS_4X4>(
            blkUB, rowBase, colBase, stride, configs);
    }
}

// ----------------------------------------------------------------------------
// SpltAlignedStride — compute the 32B-aligned UB row stride in elements.
// When DataCopyPad places rows in UB with dstStride=0, each row is padded to
// the next 32-byte boundary. This function returns the padded element count
// per row so that scalar GetValue/SetValue uses the correct offset.
// ----------------------------------------------------------------------------
template <typename T>
__aicore__ inline int32_t SpltAlignedStride(int32_t elems)
{
    const int32_t rowBytes = elems * static_cast<int32_t>(sizeof(T));
    const int32_t alignedBytes = (rowBytes + SPLT_UB_ALIGN_BYTES - 1) /
                                  SPLT_UB_ALIGN_BYTES * SPLT_UB_ALIGN_BYTES;
    return alignedBytes / static_cast<int32_t>(sizeof(T));
}

// ----------------------------------------------------------------------------
// SpltPruneTransInitBuffers — ColView path (shared by STRIP/TILE) UB buffer init.
// blkUB holds a TRANS_TILE x alignedStride (= chunkM 32B-aligned) physical
// block; the last row/block keeps a TRANS_TILE*elemSize margin (hardware
// prefetch safety headroom).
// (b) layout preserving: the transpose write-back transBuf/transUB and the
// TransWrite* family have been removed, together with the STRIP-path
// absBuf/keepMaskBuf (vectorized group masks) — ColView grouping runs along
// physical columns (stride>1) and is a scalar path anyway.
template <typename T>
__aicore__ inline void SpltPruneTransInitBuffers(
    TBuf<TPosition::VECCALC>& blockBuf, TPipe& pipe, int32_t bufStride,
    LocalTensor<T>& blkUB,
    DataCopyExtParams& loadParams, DataCopyPadExtParams<T>& padParams)
{
    constexpr int32_t TRANS_TILE = 16;
    pipe.InitBuffer(blockBuf, static_cast<uint32_t>(TRANS_TILE) *
                                static_cast<uint32_t>(bufStride) * sizeof(T) +
                                static_cast<uint32_t>(TRANS_TILE) * sizeof(T));
    blkUB = blockBuf.Get<T>();
    loadParams = DataCopyExtParams{1, 0, 0, 0, 0};
    padParams = DataCopyPadExtParams<T>{false, 0, 0, T(0)};
}

// ============================================================================
// [TILE] TILE mode paths — SpltPruneAlongRowUnified (RowView) /
// SpltPruneTileTransRowOrder (ColView).
// Each path loads data into UB, processes complete TS×TS tiles via
// SpltPruneTile, and falls back to STRIP (SpltPruneGroupN) for
// edge tiles that cannot form a complete TS×TS block. Data load/store and
// pipeline sync (MTE2→V→MTE3, SetFlag/WaitFlag) mirror the STRIP paths.
//
// When DataCopyPad loads multiple rows (blockCount > 1) with
// blockLen not a multiple of 32 bytes, the UB hardware pads each row to the
// next 32-byte boundary. The actual UB row stride (in elements) is therefore
// ceil(elems * sizeof(T), 32) / sizeof(T), NOT elems. All element access
// (GetValue/SetValue) must use this aligned stride, and the UB buffer must be
// allocated with the aligned size. The load/store DataCopyPad params
// (blockLen, srcStride, dstStride) remain unchanged — the hardware handles
// the alignment transparently for the DMA, but scalar access must match the
// physical UB layout.
// ============================================================================

// ----------------------------------------------------------------------------
// SpltPruneTileTransTails — ColView TILE path edge handling (physical view
// (k,m): rows follow the k dim, cols follow the m dim, TS equals groupSize).
// The full tile region — extent fullTileColsK×TS along the k rows dim and
// fullTileRowsM×TS along the m cols dim — is covered by SpltPruneTileDispatch.
// The tails mirror the golden PruneTileColFp32 Col-STRIP edge semantics on
// the (k,m) view:
//   (1) tail physical columns (curCols not a whole multiple of TS, i.e.
//       op-view tail rows of m past its whole TS multiples):
//       full-column STRIP (SpltPruneGroupN full groups + tail zeroing).
//   (2) tail physical rows (curRowTile not a whole multiple of TS, i.e.
//       k tail groups past the whole TS multiples):
//       partial-group elements zeroed (idempotent, covering all columns —
//       trailing groups with a count below groupSize are zeroed per the
//       2:4 convention).
// stride is alignedChunkM (the 32B-aligned UB row stride, in elements).
// ----------------------------------------------------------------------------
template <typename T>
__aicore__ inline void SpltPruneTileTransTails(
    LocalTensor<T>& blkUB,
    int32_t curRowTile, int32_t curCols,
    int32_t fullTileRowsM, int32_t fullTileColsK,
    int32_t TS, int32_t groupSize, int32_t stride)
{
    // (1) tail physical columns: full-column STRIP (grouping along physical
    // rows k + tail zeroing). No-tail inputs degenerate naturally: the loop
    // condition subsumes the entry check (codecheck redundant-code cleanup,
    // behavior unchanged).
    int32_t tailColStart = fullTileRowsM * TS;
    for (int32_t tc = tailColStart; tc < curCols; ++tc) {
        SpltPruneGroupN<T>(blkUB, tc, stride, curRowTile, groupSize);
    }
    // (2) tail physical rows: partial groups (count < groupSize) zeroed whole row.
    int32_t tailRowStart = fullTileColsK * TS;
    for (int32_t r = tailRowStart; r < curRowTile; ++r) {
        for (int32_t c = 0; c < curCols; ++c) {
            blkUB.SetValue(r * stride + c, SpltZeroValue<T>());
        }
    }
}

template <typename T, int TS, int CONFIG_COUNT>
__aicore__ inline void SpltPruneAlongRowTileCols(
    LocalTensor<T>& blkUB,
    int32_t k, int32_t alignedK, int32_t groupSize,
    const uint8_t* configs)
{
    int32_t fullTiles = k / TS;
    for (int32_t ti = 0; ti < fullTiles; ++ti) {
        SpltPruneTile<T, TS, CONFIG_COUNT>(blkUB, 0, ti * TS, alignedK, configs);
    }
    int32_t tailStart = fullTiles * TS;
    if (tailStart < k) {
        for (int32_t r = 0; r < TS; ++r) {
            SpltPruneGroupN<T>(blkUB, r * alignedK + tailStart, 1, k - tailStart, groupSize);
        }
    }
}

template <typename T>
__aicore__ inline void SpltPruneAlongRowUnified(
    GlobalTensor<T>& aGM, GlobalTensor<T>& aOutGM,
    int32_t m, int32_t k, int32_t ld, int32_t pruneAlg,
    int32_t blockId, int32_t blockNum)
{
    constexpr int32_t groupSize = std::is_same_v<T, float> ? 2 : 4;
    constexpr int32_t TS = std::is_same_v<T, float> ? SPLT_TILE_SIZE_FP32 : SPLT_TILE_SIZE_FP16;
    const bool isTile = (pruneAlg == SPLT_PRUNE_ALG_TILE);
    const int32_t rowStep = isTile ? TS : 1;
    const int32_t alignedK = SpltAlignedStride<T>(k);

    TBuf<TPosition::VECCALC> blockBuf;
    TBuf<TPosition::VECCALC> absBuf, keepMaskBuf;
    TPipe pipe;
    pipe.InitBuffer(blockBuf, static_cast<uint32_t>(rowStep) *
                                static_cast<uint32_t>(alignedK) * sizeof(T));
    LocalTensor<T> blkUB = blockBuf.Get<T>();
    pipe.InitBuffer(absBuf, static_cast<uint32_t>(k + 64) * sizeof(float));
    pipe.InitBuffer(keepMaskBuf, static_cast<uint32_t>(k + 64) * sizeof(float));
    LocalTensor<float> absUB = absBuf.Get<float>();
    LocalTensor<float> keepMaskUB = keepMaskBuf.Get<float>();
    DataCopyExtParams copyParams{1, 0, 0, 0, 0};
    DataCopyPadExtParams<T> padParams{false, 0, 0, T(0)};

    for (int32_t rowStart = blockId * rowStep; rowStart < m; rowStart += blockNum * rowStep) {
        int32_t curRows = (rowStart + rowStep <= m) ? rowStep : (m - rowStart);
        // Load
        copyParams.blockCount = static_cast<uint32_t>(curRows);
        copyParams.blockLen = static_cast<uint32_t>(k * sizeof(T));
        copyParams.srcStride = static_cast<uint32_t>((ld - k) * sizeof(T));
        copyParams.dstStride = 0;
        DataCopyPad(blkUB, aGM[static_cast<int64_t>(rowStart) * ld], copyParams, padParams);
        PipeBarrier<PIPE_MTE2>();

        if (isTile && curRows == TS) {
            // TILE: full TS×TS tiles + STRIP fallback for tail cols
            if constexpr (std::is_same_v<T, float>) {
                const uint8_t configs[SPLT_TILE_CONFIGS_2X2 * SPLT_TILE_SIZE_FP32] = { SPLT_CONFIGS_2X2_INIT };
                SpltPruneAlongRowTileCols<T, SPLT_TILE_SIZE_FP32, SPLT_TILE_CONFIGS_2X2>(
                    blkUB,
                    k, alignedK, groupSize, configs);
            } else {
                const uint8_t configs[SPLT_TILE_CONFIGS_4X4 * SPLT_TILE_SIZE_FP16] = { SPLT_CONFIGS_4X4_INIT };
                SpltPruneAlongRowTileCols<T, SPLT_TILE_SIZE_FP16, SPLT_TILE_CONFIGS_4X4>(
                    blkUB,
                    k, alignedK, groupSize, configs);
            }
        } else {
            // STRIP (or TILE edge with curRows < TS)
            for (int32_t r = 0; r < curRows; ++r) {
                SpltPruneGroupNVec<T>(blkUB, absUB, keepMaskUB,
                                        r * alignedK, k, groupSize);
            }
        }

        // Store (output keeps the (order, ld) layout: dstStride skips row-tail padding)
        SpltPruneStoreRowBlock<T>(blkUB, aOutGM, copyParams, rowStart, k, ld);
    }
}

// ----------------------------------------------------------------------------
// [codecheck dedup] ColView STRIP/TILE shared load/store scaffold. The
// 21-line bit-identical scaffolding of the former SpltPruneTransRowOrder
// (STRIP) and SpltPruneTileTransRowOrder (TILE) bodies (chunkM derivation /
// UB init / rowTile×chunk loops / SpltPruneLoadRowBlockChunk load /
// SpltPruneStoreRowBlockCol in-place writeback) was hoisted here; per-chunk
// grouping dispatches on isTile — statements and evaluation order stay
// bit-identical.
// ----------------------------------------------------------------------------
// SpltPruneTransGroupChunk — STRIP per-chunk grouping.
// Grouping along physical columns (= op-view rows, the K dim):
// fixed physical column c, group elements spanning physical rows
// (stride=alignedChunkM) — same shape as the golden Col variant on
// the (k,m) view; trailing partial groups are zeroed inside
// SpltPruneGroupN.
template <typename T>
__aicore__ inline void SpltPruneTransGroupChunk(
    LocalTensor<T>& blkUB, int32_t curRowTile, int32_t curCols,
    int32_t alignedChunkM, int32_t groupSize)
{
    for (int32_t c = 0; c < curCols; ++c) {
        SpltPruneGroupN<T>(blkUB, c, alignedChunkM, curRowTile, groupSize);
    }
}

// SpltPruneTileTransGroupChunk — TILE per-chunk grouping: complete TS×TS
// tile core (SpltPruneTileDispatch enumerating the 90/2 configs) + edge
// fallback (tail physical columns via full-column STRIP, tail physical rows'
// partial groups zeroed, SpltPruneTileTransTails).
template <typename T>
__aicore__ inline void SpltPruneTileTransGroupChunk(
    LocalTensor<T>& blkUB, int32_t curRowTile, int32_t curCols,
    int32_t alignedChunkM, int32_t groupSize)
{
    constexpr int32_t TS = std::is_same_v<T, float> ? SPLT_TILE_SIZE_FP32 : SPLT_TILE_SIZE_FP16;
    int32_t fullTileRowsM = curCols / TS;
    int32_t fullTileColsK = curRowTile / TS;
    for (int32_t tr = 0; tr < fullTileRowsM; ++tr) {
        int32_t iBase = tr * TS;
        for (int32_t tc = 0; tc < fullTileColsK; ++tc) {
            SpltPruneTileDispatch<T>(blkUB, tc * TS, iBase, alignedChunkM);
        }
    }
    SpltPruneTileTransTails<T>(blkUB,
                                 curRowTile, curCols, fullTileRowsM,
                                 fullTileColsK, TS, groupSize, alignedChunkM);
}

// SpltPruneTransChunkLoop — the shared scaffold body (both entry points pass
// isTile as a literal constant, so the dispatch branch is compile-time
// removable).
template <typename T>
__aicore__ inline void SpltPruneTransChunkLoop(
    GlobalTensor<T>& aGM, GlobalTensor<T>& aOutGM,
    int32_t m, int32_t k, int32_t ld, int32_t blockId, int32_t blockNum,
    int32_t chunkM, bool isTile)
{
    constexpr int32_t groupSize = std::is_same_v<T, float> ? 2 : 4;
    constexpr int32_t TRANS_TILE = 16;
    // When m > chunkM, split the m-dimension into chunks of chunkM
    // columns. Each chunk loads TRANS_TILE rows × chunkM cols, prunes along
    // physical columns (op-view rows), and writes back in-place layout via
    // SpltPruneStoreRowBlockCol. chunkM is aligned to 32B/elemSize so
    // alignedChunkM == chunkM (exact UB row stride).
    // When m <= chunkM, single chunk (= m), behavior unchanged from original.
    const int32_t effectiveChunkM = (chunkM > 0 && chunkM < m) ? chunkM : m;
    const int32_t alignedChunkM = SpltAlignedStride<T>(effectiveChunkM);
    TBuf<TPosition::VECCALC> blockBuf;
    TPipe pipe;
    LocalTensor<T> blkUB;
    DataCopyExtParams loadParams{1, 0, 0, 0, 0};
    DataCopyPadExtParams<T> padParams{false, 0, 0, T(0)};
    DataCopyExtParams storeParams{1, 0, 0, 0, 0};
    SpltPruneTransInitBuffers<T>(blockBuf, pipe, alignedChunkM, blkUB,
                                   loadParams, padParams);

    for (int32_t rowStart = blockId * TRANS_TILE;
         rowStart < k; rowStart += blockNum * TRANS_TILE) {
        int32_t curRowTile = (rowStart + TRANS_TILE <= k) ? TRANS_TILE : (k - rowStart);
        // Iterate over m in chunks of effectiveChunkM columns.
        for (int32_t colStart = 0; colStart < m; colStart += effectiveChunkM) {
            int32_t curCols = (colStart + effectiveChunkM <= m)
                              ? effectiveChunkM : (m - colStart);
            SpltPruneLoadRowBlockChunk<T>(blkUB, aGM, loadParams, padParams,
                                            rowStart, curRowTile, colStart,
                                            curCols, ld, alignedChunkM);
            if (isTile) {
                SpltPruneTileTransGroupChunk<T>(blkUB, curRowTile, curCols,
                                                 alignedChunkM, groupSize);
            } else {
                SpltPruneTransGroupChunk<T>(blkUB, curRowTile, curCols,
                                              alignedChunkM, groupSize);
            }
            SpltPruneStoreRowBlockCol<T>(blkUB, aOutGM, storeParams, rowStart, colStart,
                                           curRowTile, curCols, ld, alignedChunkM);
        }
    }
}

// ----------------------------------------------------------------------------
// SpltPruneTransRowOrder — ColView ((N,COL)/(T,ROW)) STRIP path.
// The sparse-side physical buffer is (k, m) row-major (row stride ld >= m):
// Logical[i][j] = data[j * ld + i]. 2:4 grouping always runs along op-view
// rows (the K dim) = along physical columns (fixed physical column c, group
// elements spanning physical rows with stride alignedChunkM).
// Output keeps the input layout: SpltPruneStoreRowBlockCol writes the
// same-position block back at the original physical positions.
// ----------------------------------------------------------------------------
template <typename T>
__aicore__ inline void SpltPruneTransRowOrder(
    GlobalTensor<T>& aGM, GlobalTensor<T>& aOutGM,
    int32_t m, int32_t k, int32_t ld, int32_t blockId, int32_t blockNum,
    int32_t chunkM)
{
    SpltPruneTransChunkLoop<T>(aGM, aOutGM, m, k, ld, blockId, blockNum,
                               chunkM, false);
}

// ----------------------------------------------------------------------------
// SpltPruneTileTransRowOrder — ColView TILE path: each block handles 16
// physical rows (k dim); the m dim is chunked by chunkM. The tile core
// enumerates the 90/2 configs on the UB physical view (k,m) (the config set is
// transpose-closed and L1-invariant — plan section 2.1.3);
// SpltPruneStoreRowBlockCol writes back at the original physical positions.
// Tails are delegated to SpltPruneTileTransTails.
// ----------------------------------------------------------------------------
template <typename T>
__aicore__ inline void SpltPruneTileTransRowOrder(
    GlobalTensor<T>& aGM, GlobalTensor<T>& aOutGM,
    int32_t m, int32_t k, int32_t ld, int32_t blockId, int32_t blockNum,
    int32_t chunkM)
{
    SpltPruneTransChunkLoop<T>(aGM, aOutGM, m, k, ld, blockId, blockNum,
                               chunkM, true);
}

// ----------------------------------------------------------------------------
// SpltPruneImpl — main prune implementation.
// Sets up GlobalTensor for A and A_pruned, then dispatches to the appropriate
// pruning path based on pruneAlg and pruneAlongRow tiling parameters.
//
// View semantics (aligned with cuSPARSELt; order is the physical memory layout):
//   RowView = (N,ROW)/(T,COL) (pruneAlongRow=1): the physical buffer is
//     row-major under the op view (row stride ld >= k) -> SpltPruneAlongRowUnified;
//   ColView = (N,COL)/(T,ROW) (pruneAlongRow=0): the physical buffer is (k,m)
//     row-major (row stride ld >= m) -> STRIP goes to SpltPruneTransRowOrder,
//     TILE goes to SpltPruneTileTransRowOrder.
// 2:4 grouping always runs along op-view rows (the K dim). Output keeps the
// input (order, ld) layout (padding is never written); in-place (d_in == d_out)
// is supported for all combinations: both views read then write block by block,
// the read/write regions overlap, and the per-core block-grid partitioning is
// disjoint across cores.
// GM length of d_in/d_out = single-batch access span (RowView (m-1)*ld+k /
// ColView (k-1)*ld+m; batch base addresses are advanced by the host according
// to batchStride).
// ----------------------------------------------------------------------------
template <typename T>
__aicore__ inline void SpltPruneImpl(GM_ADDR aGm, GM_ADDR aPrunedGm, AclsparseltTilingData td)
{
    const int32_t m = td.m;
    const int32_t k = td.k;
    const int32_t ld = td.ld;
    const int32_t pruneAlongRow = td.pruneAlongRow;
    const int32_t pruneAlg = td.pruneAlg;
    const int32_t chunkM = td.chunkM;
    const int32_t blockId = static_cast<int32_t>(GetBlockIdx());
    const int32_t blockNum = static_cast<int32_t>(GetBlockNum());

    const bool isColView = (pruneAlongRow == 0);
    const int64_t spanElems = isColView
        ? (static_cast<int64_t>(k) - 1) * static_cast<int64_t>(ld) + static_cast<int64_t>(m)
        : (static_cast<int64_t>(m) - 1) * static_cast<int64_t>(ld) + static_cast<int64_t>(k);
    GlobalTensor<T> aGM;
    aGM.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(aGm),
                        static_cast<uint64_t>(spanElems));
    GlobalTensor<T> aOutGM;
    aOutGM.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(aPrunedGm),
                           static_cast<uint64_t>(spanElems));

    if (pruneAlongRow != 0) {
        // RowView:(N,ROW)/(T,COL)
        SpltPruneAlongRowUnified<T>(aGM, aOutGM, m, k, ld, pruneAlg, blockId, blockNum);
    } else {
        // ColView:(N,COL)/(T,ROW)
        if (pruneAlg == SPLT_PRUNE_ALG_TILE) {
            SpltPruneTileTransRowOrder<T>(aGM, aOutGM, m, k, ld, blockId, blockNum, chunkM);
        } else {
            SpltPruneTransRowOrder<T>(aGM, aOutGM, m, k, ld, blockId, blockNum, chunkM);
        }
    }
}

// ============================================================================
// Kernel entry points (one per dtype), dispatched by host launchers.
// Tiling is passed by value through the kernel launch args block
// (AclsparseltTilingData is a POD struct). This avoids allocating a device
// buffer for tiling on the host side.
// ============================================================================

// --- prune ---
extern "C" __global__ __aicore__ void splt_prune_kernel_fp16(
    GM_ADDR aGm, GM_ADDR aPrunedGm, AclsparseltTilingData tiling)
{
    KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY);
    SpltPruneImpl<__fp16>(aGm, aPrunedGm, tiling);
}
extern "C" __global__ __aicore__ void splt_prune_kernel_fp32(
    GM_ADDR aGm, GM_ADDR aPrunedGm, AclsparseltTilingData tiling)
{
    KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY);
    SpltPruneImpl<float>(aGm, aPrunedGm, tiling);
}
// v2: BF16 prune — re-enabled.
// SpltPruneGroup4/SpltPruneGroupN use static_cast<float> for abs comparison,
// which works for __bf16 via the compiler's implicit conversion. No Vector Cast
// is used in the prune kernel — all element access is scalar GetValue/SetValue.
extern "C" __global__ __aicore__ void splt_prune_kernel_bf16(
    GM_ADDR aGm, GM_ADDR aPrunedGm, AclsparseltTilingData tiling)
{
    KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY);
    SpltPruneImpl<__bf16>(aGm, aPrunedGm, tiling);
}
// v2: INT8 prune — SpltPruneGroup4 casts to float for abs comparison, which
// correctly handles INT8_MIN (-128) since static_cast<float>(-128) is exact.
extern "C" __global__ __aicore__ void splt_prune_kernel_int8(
    GM_ADDR aGm, GM_ADDR aPrunedGm, AclsparseltTilingData tiling)
{
    KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY);
    SpltPruneImpl<int8_t>(aGm, aPrunedGm, tiling);
}

// ============================================================================
// Host-side launchers (ASC TU): wrap <<<>>>. host.cpp calls these as C funcs.
// dataType selects the typed kernel entry point.
// v2: switch four-branch dispatch (FP32/FP16/BF16/INT8).
// tiling points to a host-side POD struct; the launcher forwards
// it by value into the kernel launch args block. The ACL runtime copies the
// args block to device memory managed for the lifetime of the launched task,
// so no extra aclrtMalloc'd buffer is needed and no aclrtSynchronizeStream
// is required before returning.
// ============================================================================
extern "C" void splt_prune_kernel_launch(
    GM_ADDR aGm, GM_ADDR aPrunedGm, const AclsparseltTilingData *tiling,
    int32_t dataType, uint32_t blockDim, void *stream)
{
    switch (dataType) {
        case SPLT_DTYPE_FP32:
            splt_prune_kernel_fp32<<<blockDim, nullptr, stream>>>(
                aGm, aPrunedGm, *tiling);
            break;
        case SPLT_DTYPE_FP16:
            splt_prune_kernel_fp16<<<blockDim, nullptr, stream>>>(
                aGm, aPrunedGm, *tiling);
            break;
        case SPLT_DTYPE_BF16:
            splt_prune_kernel_bf16<<<blockDim, nullptr, stream>>>(
                aGm, aPrunedGm, *tiling);
            break;
        case SPLT_DTYPE_INT8:
            splt_prune_kernel_int8<<<blockDim, nullptr, stream>>>(
                aGm, aPrunedGm, *tiling);
            break;
        default:
            OP_LOGE(kSparseLtLogTag, "unreachable: unknown dtype in prune launcher"); return;
            break;
    }
}