diff --git a/.github/script/ci/changes.py b/.github/script/ci/changes.py index 62ddb74fd..04b5f3060 100644 --- a/.github/script/ci/changes.py +++ b/.github/script/ci/changes.py @@ -611,6 +611,7 @@ def devkit_extra_areas(path: str) -> set: ("minicpm_v_4_7_moe", "minicpm_v_moe"): ("minicpm-v-4.7-moe",), ("minicpm_v_4_7_bf16", "minicpm_v_bf16"): ("minicpm-v-4.7-bf16",), ("minicpm_ocr",): ("minicpm-ocr",), + ("minicpm5_moe", "minicpm5"): ("minicpm5",), ("qwen3_6_moe",): ("qwen3.6-moe",), # qwen3.8-dflash2 is the same engine with a draft package (Qwen3_8DFlash2 derives from Qwen3_8MTP). ("qwen3_8mtp", "qwen3_8_mtp"): ("qwen3.8-mtp", "qwen3.8-dflash2"), diff --git a/.github/script/ci/devkit_symbol_clash.py b/.github/script/ci/devkit_symbol_clash.py index 27b932323..671caf3f4 100755 --- a/.github/script/ci/devkit_symbol_clash.py +++ b/.github/script/ci/devkit_symbol_clash.py @@ -51,6 +51,9 @@ # engine. It starts empty. An HRX wait on this thread fills it and the # completion check on that same thread reads it back. "flm::npu::ert_failure_detail", + # The ELF section-name table of aie2p-launchlib's launch/txn/elf.hpp, a constant every + # engine that writes run ELFs (inkling2_npu, minicpm5_moe_npu) compiles from that one header. + "launch::txn::elf_of(launch::txn::ElfText const&)::kNames", } SKIPPED_LIBS = ("xrt", "boost") diff --git a/.github/script/ci/test_changes.py b/.github/script/ci/test_changes.py index 9020216a4..d5bc14fe7 100644 --- a/.github/script/ci/test_changes.py +++ b/.github/script/ci/test_changes.py @@ -1241,6 +1241,7 @@ def test_engine_library_maps_to_its_family(self): "src/lib/xrt/libqwen3vl_flash.so": {"qwen3vl-flash"}, "src/lib/hrx/libhy_mem_npu.so": {"hy-memory"}, "src/lib/xrt/inkling2_npu.dll": {"inkling-2", "inkling-2-dflash2"}, + "src/lib/hrx/libminicpm5_moe_npu.so": {"minicpm5"}, } for path, expected in cases.items(): with self.subTest(path=path): @@ -1763,9 +1764,11 @@ def test_no_source_includes_an_excluded_file(self): def test_only_known_units_reach_host_outside_host_mk(self): # make bitstream parses each unit's Makefile and its makefiles/*.mk. # These name host/ (or -Ihost) outside host.mk, and were checked: the - # Hy_* prefill_overlay regs and run.exe targets (no bitstream - # prerequisite), and vision_overlay, which XCLBIN_NO_BITSTREAM leaves out. - known = {"Hy_MT2_1.8B/prefill_overlay", "Hy_mem_30BA3B/prefill_overlay", "minicpm_ocr/vision_overlay"} + # Hy_* and MiniCPM5 prefill_overlay regs and run.exe targets (no + # bitstream prerequisite), and vision_overlay, which XCLBIN_NO_BITSTREAM + # leaves out. + known = {"Hy_MT2_1.8B/prefill_overlay", "Hy_mem_30BA3B/prefill_overlay", "MiniCPM5/prefill_overlay", + "minicpm_ocr/vision_overlay"} seen = set() for path in tracked(f"{XB}**/Makefile", f"{XB}**/*.mk"): unit = path[len(XB):].rsplit("/", 1)[0].removesuffix("/makefiles") diff --git a/docs/_config.yml b/docs/_config.yml index e2742e9d0..32f623bf4 100644 --- a/docs/_config.yml +++ b/docs/_config.yml @@ -201,6 +201,8 @@ docs_nav: url: "/docs/benchmarks/hy-memory_results/" - label: MiniCPM-V 4.7 url: "/docs/benchmarks/minicpm-v-4.7_results/" + - label: MiniCPM5 + url: "/docs/benchmarks/minicpm5_results/" - label: Nemotron Bolt url: "/docs/benchmarks/nemotron3.5-bolt_results/" - label: Nemotron Bolt DFlash diff --git a/docs/docs/benchmarks/index.md b/docs/docs/benchmarks/index.md index 107da86a0..b00b78198 100644 --- a/docs/docs/benchmarks/index.md +++ b/docs/docs/benchmarks/index.md @@ -28,6 +28,7 @@ Browse detailed NPU benchmark results for each major model family supported by F - [Hy-MT3](hy-mt3_results/) (FLM v1.0.14 or later) - [Hy-Memory](hy-memory_results/) - [MiniCPM-V 4.7](minicpm-v-4.7_results/) +- [MiniCPM5](minicpm5_results/) (FLM v1.0.15 or later) - [Nemotron Bolt](nemotron3.5-bolt_results/) - [Nemotron Bolt DFlash](nemotron3.5-bolt-dflash_results/) - [Flash Models](flash_results/) diff --git a/docs/docs/benchmarks/minicpm5_results.md b/docs/docs/benchmarks/minicpm5_results.md new file mode 100644 index 000000000..aa3c28095 --- /dev/null +++ b/docs/docs/benchmarks/minicpm5_results.md @@ -0,0 +1,57 @@ +--- +layout: docs +title: MiniCPM5 +parent: Benchmarks +nav_order: 24 +--- + +## ⚑ Performance and Efficiency Benchmarks + +This section reports the performance on NPU with FastFlowLM (FLM). + +> **Note:** +> - Results are based on the FastFlowLM release that adds MiniCPM5-15B-A2.5B (v1.0.15). +> - Under FLM's default NPU power mode (Performance) +> - Decoding runs every layer (attention, router, the 16 routed experts and the shared expert) and the LM head on the NPU. +> - Newer versions may deliver improved performance. + +--- + +### **Test System:** + +AMD Ryzenβ„’ AI MAX+ PRO 395 (Strix Halo) with 128 GB DRAM; performance is comparable to other Strix Halo and Strix Point systems. + +--- + +### πŸš€ Decoding Speed (TPS, or Tokens per Second, starting @ different context lengths) + +| **Model** | **HW** | **1k** | **2k** | **4k** | **8k** | **16k** | **32k** | +|------------------|--------------------|--------:|--------:|--------:|--------:|---------:|---------:| +| **MiniCPM5-15B-A2.5B** | XDNA2 | 24.9 | 24.2 | 22.7 | 20.2 | 16.7 | 12.4 | + +--- + +### πŸš€ Prefill Speed (TPS, or Tokens per Second, with different prompt lengths) + +| **Model** | **HW** | **1k** | **2k** | **4k** | **8k** | **16k** | **32k** | +|------------------|--------------------|--------:|--------:|--------:|--------:|---------:|---------:| +| **MiniCPM5-15B-A2.5B** | XDNA2 | 1032 | 1267 | 1331 | 1132 | 867 | 594 | + +--- + +## 🎯 Accuracy + +The FLM package quantizes the BF16 model to Q4_K throughout (Q8_0 LM head), using the importance matrix published by +bartowski. KL divergence of the next-token distribution against the BF16 model (100 windows of 512 tokens): + +| **Weights** | **WikiText-2** | **Code** | +|-----------------------------------------------|---------------:|---------:| +| Official Q4_K_M GGUF (mixed Q4_K / Q6_K) | 0.053 | 0.032 | +| All Q4_K, no importance matrix | 0.189 | 0.095 | +| All Q4_K with the importance matrix (FLM) | 0.097 | 0.052 | + +> **Note:** +> - The importance matrix halves the error of a plain all-Q4_K quantization; all-Q4_K keeps every layer on the +> fast Q4_K NPU kernels. +> - On the NPU (bf16 compute) the logits match a CPU run of the same Q4_K weights closely: KL 0.005 to 0.020 over +> short chat, multi-turn, math, code, tool-call and 2.7k-token document prompts. diff --git a/docs/docs/models/minicpm.md b/docs/docs/models/minicpm.md index a614eb72d..03e9b4445 100644 --- a/docs/docs/models/minicpm.md +++ b/docs/docs/models/minicpm.md @@ -58,3 +58,34 @@ flm run minicpm-v-4.7-moe:35b-a3b - Video and audio input are not supported. Speculative decoding (DSpark) is not used. --- + +## 🧩 Model Card: [MiniCPM5-15B-A2.5B](https://huggingface.co/openbmb/MiniCPM5-15B-A2.5B) + +- **Type:** Text-to-Text (Mixture of Experts: 15B parameters, about 2.5B active per token) +- **Think:** Toggleable (on by default, as in the model's chat template) +- **Tool Calling Support:** Yes +- **Prefix cache (server mode):** Yes (see [Prefix Cache (Prompt Reuse)](https://fastflowlm.com/docs/instructions/server/prefix_cache/)) +- **Base Model:** [openbmb/MiniCPM5-15B-A2.5B](https://huggingface.co/openbmb/MiniCPM5-15B-A2.5B) (Apache-2.0) +- **Quantization:** Q4_K (Q8_0 LM head), with the importance matrix from [bartowski/MiniCPM5-15B-A2.5B-GGUF](https://huggingface.co/bartowski/MiniCPM5-15B-A2.5B-GGUF) +- **Memory:** about 16 GB at the default 128k context, up to about 21.5 GB while it holds a full 128k prompt +- **Max Context Length:** 128k tokens +- **Default Context Length:** 128k tokens ([change default](https://fastflowlm.com/docs/instructions/cli/#-change-default-context-length-max)) +- **[Set Context Length at Launch](https://fastflowlm.com/docs/instructions/cli/#-set-context-length-at-launch)** +- **Minimum FLM version:** v1.0.15 (first release that supports this model) + +▢️ Run with FastFlowLM in PowerShell: + +```powershell +flm run minicpm5:15b-a2.5b +``` + +πŸ“ **Note** + +- **Requires FastFlowLM v1.0.15 or later.** +- Thinking is on unless you turn it off: `think: false` in a request, `"chat_template_kwargs": {"enable_thinking": false}` (OpenAI API), or the interactive toggle. +- Sampling follows the model card's thinking-mode settings: temperature 1.0, top_p 0.95, min_p 0 (top_k 50). +- Tool calls use the model's own XML format (`...`); the server returns them as OpenAI `tool_calls`. +- Text only. Speculative decoding is not used. +- Speeds: see [MiniCPM5 benchmarks](https://fastflowlm.com/docs/benchmarks/minicpm5_results/). + +--- diff --git a/docs/models.md b/docs/models.md index 0daa5a641..3745ff631 100644 --- a/docs/models.md +++ b/docs/models.md @@ -11,7 +11,7 @@ sections: FastFlowLM curates the most requested families and publishes tuned manifests under `flm pull `. We validate every build on Ryzenβ„’ AI laptops and provide matching cardsβ€”see them [here](/docs/models/). The catalog already covers models spanning Qwen3.8 (27B, MTP and DFlash 2 speculative decoding), Qwen3.6 (MoE), Qwen3.5 (Vision), Gemma4 (omni), Nemotron Bolt (DFlash speculative decoding), Qwen3, GPT-OSS-20B (MoE), DeepSeek-R1, Whisper - (Audio), Hy-MT2, Hy-MT3 (Translation), MiniCPM-V 4.7 (Vision, 1B and 35B-A3B MoE), MedGemma (Medical), Inkling-2 (Vision, 26B-A3B MoE, DFlash 2 speculative decoding), Decision 3.0 (d3-edge, d3-lite, d3-nano, d3-mini, d3-flash, d3-turbo, d3-ultra, the System One + (Audio), Hy-MT2, Hy-MT3 (Translation), MiniCPM-V 4.7 (Vision, 1B and 35B-A3B MoE), MiniCPM5 (15B-A2.5B MoE, tool use), MedGemma (Medical), Inkling-2 (Vision, 26B-A3B MoE, DFlash 2 speculative decoding), Decision 3.0 (d3-edge, d3-lite, d3-nano, d3-mini, d3-flash, d3-turbo, d3-ultra, the System One decision model of vLLM Semantic Router), and other leading open families. ctas: - label: "View model docs" @@ -30,6 +30,7 @@ sections: - "Qwen3.5 (Vision)" - "Qwen 3 (Vision)" - "MiniCPM-V 4.7 (Vision, incl. 35B-A3B MoE)" + - "MiniCPM5 (MoE, tool use)" - "Inkling-2 (Vision, MoE, tool use; DFlash 2 speculative decoding)" - "GPT-OSS (MoE)" - "LFM2 / LFM3 (Liquid AI)" diff --git a/flm-dev-kit/FLM_DLL/build_minicpm5_moe.sh b/flm-dev-kit/FLM_DLL/build_minicpm5_moe.sh new file mode 100755 index 000000000..4ac5ba816 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/build_minicpm5_moe.sh @@ -0,0 +1,28 @@ +#!/usr/bin/bash +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +# MiniCPM5-15B-A2.5B. Every stage runs on its own xclbin, so no host compute +# modules (mha / gemm / dequant / lm_head) are linked; q4nx is the weight reader. +cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" || exit 1 +failed_dirs=() +target_dirs=(q4nx minicpm5_moe_npu) + +for name in "${target_dirs[@]}"; do + dir="detail/${name}" + if [ -f "${dir}/Makefile" ]; then + if ! (cd "$dir" && make clean && make -j4); then + failed_dirs+=("$dir") + fi + fi +done + +if [ ${#failed_dirs[@]} -ne 0 ]; then + echo "Build failures in:" + for dir in "${failed_dirs[@]}"; do + echo " - $dir" + done + exit 1 +else + echo "All builds succeeded." +fi diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/CMakeLists.txt b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/CMakeLists.txt new file mode 100644 index 000000000..b5381995d --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/CMakeLists.txt @@ -0,0 +1,177 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +cmake_minimum_required(VERSION 3.22) +project(minicpm5_moe_npu VERSION 1.0.0 LANGUAGES CXX) + +# Set build type to Release +set(CMAKE_BUILD_TYPE Release) + +# Set C++ standard +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Find and enable OpenMP for multi-threading +find_package(OpenMP) +if(OpenMP_CXX_FOUND) + message(STATUS "OpenMP found - enabling multi-threading support") +else() + message(WARNING "OpenMP not found - optimized functions will run single-threaded") +endif() + +# Force x64 architecture on Windows +if(WIN32) + set(CMAKE_GENERATOR_PLATFORM x64) + set(CMAKE_VS_PLATFORM_NAME "x64") +endif() + +# Set output directories +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/../../build/minicpm5_moe_npu/lib) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/../../build/minicpm5_moe_npu/lib) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/../../build/minicpm5_moe_npu/lib) + +# Force output directories to be absolute +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) + +# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” +# User-tweakable XRT settings (override on cmake command-line) +# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” +option(FLM_USE_HRX "Build FLM engine libs against the HRX amdxdna runtime instead of XRT" OFF) +if(FLM_USE_HRX) + include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/flm_hrx.cmake) + # Stale CMake cache can leak XRT headers into an HRX reconfigure. + set(XRT_INCLUDE_DIR "" CACHE PATH "Where XRT headers live" FORCE) + set(XRT_LIB_DIR "" CACHE PATH "Where XRT libs live" FORCE) + set(FLM_NPU_CORE_LIB ${HRX_LIBRARIES}) + set(FLM_NPU_AIEBU_LIB "") +else() + include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/flm_xrt_win.cmake) + set(HRX_INCLUDE_DIRS "") + set(FLM_NPU_CORE_LIB xrt_coreutil) + set(FLM_NPU_AIEBU_LIB aiebu_static) +endif() + +# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” +# Gather your sources +# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” +file(GLOB SOURCES + "*.cpp" +) +file(GLOB HEADERS "../../include/*.hpp" "*.hpp") + + +# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” +# Define the library +# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” +add_library(minicpm5_moe_npu SHARED ${SOURCES} ${HEADERS}) + + + +# HRX uses the dynamic CRT, the same one as flm and hrx. std::codecvt::id +# then stays in msvcp140.dll, so WINDOWS_EXPORT_ALL_SYMBOLS does not publish it. +# The XRT build links aiebu_static (/MT) and keeps the static CRT. +if(MSVC) + if(FLM_USE_HRX) + set_property(TARGET minicpm5_moe_npu PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>DLL") + target_compile_options(minicpm5_moe_npu PRIVATE $<$:/MDd>$<$>:/MD>) + else() + set_property(TARGET minicpm5_moe_npu PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_compile_options(minicpm5_moe_npu PRIVATE /MT$<$:d>) + endif() +endif() + + +set_target_properties(minicpm5_moe_npu PROPERTIES + PREFIX "" + SUFFIX ".dll" + IMPORT_PREFIX "" + IMPORT_SUFFIX ".lib" + RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_SOURCE_DIR}/../../build/minicpm5_moe_npu/lib" + LIBRARY_OUTPUT_DIRECTORY_RELEASE "${CMAKE_SOURCE_DIR}/../../build/minicpm5_moe_npu/lib" + ARCHIVE_OUTPUT_DIRECTORY_RELEASE "${CMAKE_SOURCE_DIR}/../../build/minicpm5_moe_npu/lib" + WINDOWS_EXPORT_ALL_SYMBOLS ON +) + +# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” +# Library specific settings +# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” +target_include_directories(minicpm5_moe_npu PUBLIC + ${CMAKE_SOURCE_DIR}/../../include + ${CMAKE_SOURCE_DIR}/../../../aie2p-launchlib/launchlib/include + ${XRT_INCLUDE_DIR} ${HRX_INCLUDE_DIRS} ${FLM_BOOST_INCLUDE_DIR} +) + +# Prefill backend, same default as the Makefile: OFF = batched prefill (NPU +# prefill_overlay), ON = the decode overlays one token at a time. See minicpm5_moe_prefill.hpp. +option(PREFILL_WITH_MV "minicpm5_moe: token-by-token (decode-overlay) prefill" OFF) +if(PREFILL_WITH_MV) + target_compile_definitions(minicpm5_moe_npu PUBLIC PREFILL_WITH_MV) +endif() + +# Add AVX2 specific definitions and flags +target_compile_definitions(minicpm5_moe_npu PUBLIC + DISABLE_ABI_CHECK=1 + USEAVX2=1 + USEAVX512=1 + _WIN32 + __WINDOWS__ + _ENABLE_EXTENDED_ALIGNED_STORAGE +) + +# Enhanced compiler options for AVX-512 +target_compile_options(minicpm5_moe_npu PUBLIC + $<$:/arch:AVX512 /O2 /fp:fast> + $<$>:-mavx512f -mavx512vl -mavx512bw -mavx512dq -mfma -O3> +) + +# Add OpenMP compiler flags if available +if(OpenMP_CXX_FOUND) + target_compile_options(minicpm5_moe_npu PUBLIC + $<$:/openmp> + $<$>:-fopenmp> + ) +endif() + +# Link OpenMP if available +if(OpenMP_CXX_FOUND) + target_link_libraries(minicpm5_moe_npu PUBLIC OpenMP::OpenMP_CXX) +endif() + +# Add AVX2 specific link flags for MSVC +if(MSVC) + set_target_properties(minicpm5_moe_npu PROPERTIES + LINK_FLAGS "/MACHINE:X64" + ) + # Add C++ standard library for RTTI and other symbols + target_link_libraries(minicpm5_moe_npu PUBLIC + $<$:msvcrt.lib> + ) +endif() + +target_link_directories(minicpm5_moe_npu PUBLIC + ${XRT_LIB_DIR} + ${FLM_AIEBU_LIB_DIR} +) + +# No host compute modules (gemm / mha / dequant). q4_npu_eXpress is still needed: +# SafeTensors::load_weights lives in q4nx/safe_tensors.cpp, and a DLL must resolve +# it at link time (the Linux .so picks it up from libq4_npu_eXpress.so at load time) +set(Q4NPU_EXPRESS_LIB_PATH ${CMAKE_SOURCE_DIR}/../../build/lib/q4_npu_eXpress.lib) +target_link_libraries(minicpm5_moe_npu PUBLIC + ${FLM_NPU_CORE_LIB} + ${FLM_NPU_AIEBU_LIB} + ${Q4NPU_EXPRESS_LIB_PATH} +) + +# Copy the built library to build/lib directory +add_custom_command(TARGET minicpm5_moe_npu POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_SOURCE_DIR}/../../build/lib + COMMAND ${CMAKE_COMMAND} -E copy + $ + ${CMAKE_SOURCE_DIR}/../../build/lib/minicpm5_moe_npu.dll + COMMAND ${CMAKE_COMMAND} -E copy + $ + ${CMAKE_SOURCE_DIR}/../../build/lib/minicpm5_moe_npu.lib +) diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/Makefile b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/Makefile new file mode 100644 index 000000000..b3c25da05 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/Makefile @@ -0,0 +1,150 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +# ============================================================================= +# MiniCPM5-15B-A2.5B NPU Library Makefile +# ============================================================================= +# +# Usage: +# make - Build libminicpm5_moe_npu.so (copied to ../../build/lib) +# make clean - Remove all built files +# +# The engine has no host compute modules to link (no gemm / mha / dequant / +# lm_head objects): every layer and the lm_head run on their own xclbins. +# ============================================================================= + +# Check if it is in Windows Subsystem for Linux (WSL) +ifeq ($(shell uname -a | grep -i WSL),) + WSL := 0 +else + WSL := 1 +endif + +BUILD_DIR := ../../build/minicpm5_moe_npu +LIB_DIR := $(BUILD_DIR)/lib +BIN_DIR := $(BUILD_DIR)/bin +FINAL_LIB_DIR := ../../build/lib +ifeq ($(WSL), 0) +# Linux build environment +# Use g++-13 directly without CMake + +DEBUG_LEVEL ?= 0 +VERBOSE ?= 0 + +TARGET = $(LIB_DIR)/libminicpm5_moe_npu.so + +CXX := g++-13 +include ../../flags.mk +CXX_FLAGS := -std=c++20 -fPIC -Wall -O3 -fopenmp +CXX_FLAGS += $(FLM_MARCH) -ffast-math +CXX_FLAGS += -fmax-errors=1 +CXX_FLAGS += -I../../include +CXX_FLAGS += -I../q4nx +CXX_FLAGS += -I../../../aie2p-launchlib/launchlib/include +ifeq ($(FLM_USE_HRX),1) +include ../../hrx.mk +CXX_FLAGS += $(HRX_INC) +else +CXX_FLAGS += -I$(XRT_ROOT)/include +endif +CXX_FLAGS += -MMD -MP -DDEBUG_LEVEL=$(DEBUG_LEVEL) -DVERBOSE=$(VERBOSE) +# make PREFILL_WITH_MV=1: prefill through the decode overlays one token at a time, +# instead of the batched prefill (minicpm5_moe_prefill.hpp) +PREFILL_WITH_MV ?= 0 +ifneq ($(PREFILL_WITH_MV), 0) +CXX_FLAGS += -DPREFILL_WITH_MV +endif +# where the batched prefill's heavy stages run: 1 = prefill_overlay.xclbin, 0 = host +# (MINICPM5_MOE_ATTN_HOST=1 / MINICPM5_MOE_MM_HOST=1 at run time also put them on the host) +MINICPM5_MOE_ATTN_ON_NPU ?= 1 +CXX_FLAGS += -DMINICPM5_MOE_ATTN_ON_NPU=$(MINICPM5_MOE_ATTN_ON_NPU) +MINICPM5_MOE_MM_ON_NPU ?= 1 +CXX_FLAGS += -DMINICPM5_MOE_MM_ON_NPU=$(MINICPM5_MOE_MM_ON_NPU) + +# Flags for shared library +LIB_FLAGS := -shared +LIB_FLAGS += $(CXX_FLAGS) +# Each engine .so compiles its own copy of the shared runtime (npu_sequence, +# npu_app_manager, weight_desc_t, bytes/buffer, ...) and exports it with default +# visibility. flm links every engine at once, so ELF interposition makes all +# references -- including calls from inside this .so -- bind to whichever engine +# comes first in DT_NEEDED, silently running another model's implementation. +# -Bsymbolic-functions binds our internal function calls to our own definitions +# at link time. Functions only: typeinfo/vtables stay interposable so +# dynamic_cast across the .so boundary keeps working. +LIB_FLAGS += -Wl,-Bsymbolic-functions + +ifeq ($(FLM_USE_HRX),1) +LDFLAGS += $(HRX_RPATH) +else +LDFLAGS += -L$(XRT_ROOT)/lib +endif + +LDFLAGS += -fopenmp +LDFLAGS += -L../../../../src/lib/xrt +LDFLAGS += -L../../build/lib +ifeq ($(FLM_USE_HRX),1) +LDFLAGS += $(HRX_LIBS) +else +# Link the aiebu that matches ../../include/aiebu by path. With -laiebu, an +# XRT installed in $(XRT_ROOT)/lib (searched first) supplies its own +# libaiebu.a, whose assembler prints a "Header version ..." banner to stdout +# on every _setup_kernel(). +LDFLAGS += -lxrt_coreutil ../../../../src/lib/xrt/libaiebu.a +endif + +# Each source compiles to a flattened object in LIB_DIR so dependency (.d) +# files are emitted next to the objects and -include picks up header changes. +LOCAL_SOURCES = $(wildcard *.cpp) +OBJS = $(patsubst %.cpp,$(LIB_DIR)/%.o,$(LOCAL_SOURCES)) +DEPS := $(OBJS:.o=.d) + +all: directories $(TARGET) + cp $(TARGET) $(FINAL_LIB_DIR) + +directories: + mkdir -p $(FINAL_LIB_DIR) + mkdir -p $(BIN_DIR) + mkdir -p $(LIB_DIR) + +$(LIB_DIR)/%.o: %.cpp + $(CXX) $(CXX_FLAGS) -c -o $@ $< + +$(TARGET): $(OBJS) + $(CXX) $(LIB_FLAGS) -o $@ $^ $(LDFLAGS) + +clean: + rm -rf $(BUILD_DIR) + +-include $(DEPS) +.PHONY: all clean directories + +else + +# WSL build environment +# Use CMake to invoke the Visual Studio +PWSH := powershell.exe +HRX_CMAKE_ARGS := +ifeq ($(FLM_USE_HRX),1) +HRX_CMAKE_ARGS := -DFLM_USE_HRX=ON +endif + +TARGET = $(BUILD_DIR)/minicpm5_moe_npu.dll + +all: directories $(TARGET) + +directories: + mkdir -p $(BUILD_DIR) + mkdir -p $(BIN_DIR) + mkdir -p $(LIB_DIR) + +$(TARGET): directories + cd $(BUILD_DIR) && $(PWSH) -Command "cmake ../../detail/minicpm5_moe_npu $(HRX_CMAKE_ARGS)" + cd $(BUILD_DIR) && $(PWSH) -Command "cmake --build . --config Release --target minicpm5_moe_npu --parallel 4" + +clean: + rm -rf $(BUILD_DIR) + +.PHONY: all clean directories + +endif diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_cpu_functions.hpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_cpu_functions.hpp new file mode 100644 index 000000000..ab082d150 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_cpu_functions.hpp @@ -0,0 +1,282 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_cpu_functions.hpp +/// \brief The small per-row prefill steps of MiniCPM5-15B-A2.5B, on the host +/// \note Norms, RoPE, the K/V rows into the decode cache, the attention output +/// gate, SiLU-GLU, residual, and the MoE router. Every step reads and +/// writes bf16, fp32 inside (as the decode overlay does). +#pragma once +#include +#include +#include +#include +#include "minicpm5_moe_prefill_ops.hpp" + +namespace minicpm5_moe_cpu { + +// ============================================================================= +// bf16 rounding, 16 lanes at a time +// ============================================================================= +/// \brief the bf16 bits of 16 floats, rounded as bf16(float) rounds them: to nearest +/// even, zero and subnormals to a signed zero (NaN aside, which never occurs) +inline __m512i bf16_bits(__m512 v) { + const __m512i i = _mm512_castps_si512(v); + const __m512i lsb = _mm512_and_si512(_mm512_srli_epi32(i, 16), _mm512_set1_epi32(1)); + const __m512i r = _mm512_srli_epi32(_mm512_add_epi32(i, _mm512_add_epi32(lsb, _mm512_set1_epi32(0x7FFF))), 16); + const __mmask16 tiny = _mm512_testn_epi32_mask(i, _mm512_set1_epi32(0x7F800000)); + return _mm512_mask_and_epi32(r, tiny, _mm512_srli_epi32(i, 16), _mm512_set1_epi32(0x8000)); +} +/// \brief (float)(bf16)v per lane +inline __m512 round_bf16(__m512 v) { return _mm512_castsi512_ps(_mm512_slli_epi32(bf16_bits(v), 16)); } +/// \brief 16 x (bf16)v +inline void store_bf16(bf16* p, __m512 v) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), _mm512_cvtepi32_epi16(bf16_bits(v))); +} + +/// \brief out[l] = w * bf16(x[l] * rsqrt(mean(x[l]^2) + eps)) +inline void rms_norm(bf16* out, const bf16* x, const bf16* w, int L, int D, float eps) { + assert(D % 16 == 0); + prefill_pool().run(L, [&](int64_t l0, int64_t l1, int) { + for (int64_t l = l0; l < l1; l++) { + const bf16* xr = x + (size_t)l * D; + bf16* o = out + (size_t)l * D; + double ss = 0.0; + for (int d = 0; d < D; d++) ss += (double)(float)xr[d] * (float)xr[d]; + const float r = 1.0f / std::sqrt((float)(ss / D) + eps); + const __m512 rv = _mm512_set1_ps(r); + for (int d = 0; d < D; d += 16) { + const __m512 n = round_bf16(_mm512_mul_ps(load_bfloat16_to_m512(xr + d), rv)); + store_bf16(o + d, _mm512_mul_ps(n, load_bfloat16_to_m512(w + d))); + } + } + }); +} + +/// \brief elements of one k|v|q|gate projection row (the decode proj order) +inline int kvqg_stride(const minicpm5_moe_desc& desc) { return desc.DK + desc.DV + 2 * desc.DQ; } + +/// \brief cos / sin of every position of a chunk, [L][RoPE_DIM / 2] each, bf16 values +/// as in the decode overlay's RoPE table; the angle is fp32 inv_freq * pos. +/// The same for every layer: built once per chunk. +struct rope_table { + int half = 0; + std::vector cos_t, sin_t; + void build(int L, const minicpm5_moe_desc& desc, int pos0) { + half = desc.RoPE_DIM / 2; + cos_t.resize((size_t)L * half); + sin_t.resize((size_t)L * half); + prefill_pool().run(L, [&](int64_t l0, int64_t l1, int) { + for (int64_t l = l0; l < l1; l++) { + for (int i = 0; i < half; i++) { + const float angle = desc.inv_freq[i] * (float)(pos0 + l); + cos_t[(size_t)l * half + i] = (float)(bf16)std::cos(angle); + sin_t[(size_t)l * half + i] = (float)(bf16)std::sin(angle); + } + } + }); + } +}; + +/// \brief RoPE (NEOX rotate_half, the whole head), in place on one head: +/// x * cos + rotate_half(x) * sin, rotate_half(x) = [-x2, x1] +/// \note No q/k norm in this model. half % 16 == 0. +inline void head_rope(bf16* h, int half, const float* cos_t, const float* sin_t) { + for (int i = 0; i < half; i += 16) { + const __m512 x1 = load_bfloat16_to_m512(h + i), x2 = load_bfloat16_to_m512(h + i + half); + const __m512 c = _mm512_loadu_ps(cos_t + i), s = _mm512_loadu_ps(sin_t + i); + store_bf16(h + i, _mm512_fmsub_ps(x1, c, _mm512_mul_ps(x2, s))); + store_bf16(h + i + half, _mm512_fmadd_ps(x2, c, _mm512_mul_ps(x1, s))); + } +} + +/// \brief RoPE on the k and q heads of the k|v|q|gate projection rows, in place, and the +/// new K (roped) and V rows into the decode KV cache, rows pos0 .. pos0 + L - 1 +/// \param kvqg [L][kvqg_stride]: k, v, q, gate back to back +/// \param rope the chunk's table (row l = position pos0 + l) +inline void rope_store_kv(bf16* kvqg, int L, const minicpm5_moe_desc& desc, const rope_table& rope, + const kv_cache_view& kv, int pos0) { + const int DH = desc.DH, half = rope.half; + assert(half * 2 == DH && half % 16 == 0); + const int stride = kvqg_stride(desc); + prefill_pool().run(L, [&](int64_t l0, int64_t l1, int) { + for (int l = (int)l0; l < (int)l1; l++) { + const float* c = rope.cos_t.data() + (size_t)l * half; + const float* s = rope.sin_t.data() + (size_t)l * half; + bf16* row = kvqg + (size_t)l * stride; + for (uint32_t h = 0; h < desc.num_kv_heads; h++) { + head_rope(row + h * DH, half, c, s); + memcpy(kv.row(0, h, pos0 + l), row + h * DH, DH * sizeof(bf16)); + memcpy(kv.row(1, h, pos0 + l), row + desc.DK + h * DH, DH * sizeof(bf16)); + } + for (uint32_t h = 0; h < desc.num_heads; h++) head_rope(row + desc.DK + desc.DV + h * DH, half, c, s); + } + }); +} + +/// \brief (float)(bf16)sigmoid(g) for every bf16 g, indexed by its bits +inline const float* sigmoid_bf16_table() { + static const std::vector table = [] { + std::vector t(65536); + for (uint32_t b = 0; b < 65536; b++) { + const float g = (float)bf16((uint16_t)b, true); + t[b] = (float)(bf16)(1.0f / (1.0f + std::exp(-g))); + } + return t; + }(); + return table.data(); +} + +/// \brief attn[l] *= sigmoid(gate[l]), the gate being the last DQ of each k|v|q|gate row +inline void attn_gate(bf16* attn, const bf16* kvqg, int L, const minicpm5_moe_desc& desc) { + const int stride = kvqg_stride(desc), DQ = desc.DQ; + assert(DQ % 16 == 0); + const float* sig = sigmoid_bf16_table(); + prefill_pool().run(L, [&](int64_t l0, int64_t l1, int) { + for (int64_t l = l0; l < l1; l++) { + const bf16* g = kvqg + (size_t)l * stride + desc.DK + desc.DV + DQ; + bf16* a = attn + (size_t)l * DQ; + for (int i = 0; i < DQ; i += 16) { + const __m512i gi = _mm512_cvtepu16_epi32(_mm256_loadu_si256(reinterpret_cast(g + i))); + store_bf16(a + i, _mm512_mul_ps(load_bfloat16_to_m512(a + i), _mm512_i32gather_ps(gi, sig, 4))); + } + } + }); +} + +/// \brief hid[l] = silu(gate) * up, from rows stored as the decode GLU reads them: +/// [up slab | gate slab] repeated (minicpm5_moe_model_def.cpp interleave_up_gate) +/// \param width the MLP width (512, shared and routed experts); fused rows are 2 * width +inline void silu_glu_row(bf16* o, const bf16* f, int width, int slab) { + for (int s = 0; s < width / slab; s++) { + const bf16* up = f + (size_t)s * 2 * slab; + const bf16* gate = up + slab; + for (int i = 0; i < slab; i++) { + const float g = (float)gate[i]; + const float silu = (float)(bf16)(g / (1.0f + std::exp(-g))); + o[s * slab + i] = (bf16)(silu * (float)up[i]); + } + } +} + +/// \brief silu_glu_row over L rows +inline void silu_glu(bf16* hid, const bf16* fused, int L, int width, int slab) { + prefill_pool().run(L, [&](int64_t l0, int64_t l1, int) { + for (int64_t l = l0; l < l1; l++) silu_glu_row(hid + (size_t)l * width, fused + (size_t)l * 2 * width, width, slab); + }); +} + +/// \brief x += y, rows of D, rounded to bf16 (the residual stream is bf16) +inline void add_rows(bf16* x, const bf16* y, size_t n) { + assert(n % 16 == 0); + prefill_pool().run((int64_t)n / 16, [&](int64_t b, int64_t e, int) { + for (int64_t i = b * 16; i < e * 16; i += 16) + store_bf16(x + i, _mm512_add_ps(load_bfloat16_to_m512(x + i), load_bfloat16_to_m512(y + i))); + }); +} + +/// \brief x += bf16(y), y fp32 (the MoE sum is kept in fp32 until it joins the residual) +inline void add_rows_f32(bf16* x, const float* y, size_t n) { + assert(n % 16 == 0); + prefill_pool().run((int64_t)n / 16, [&](int64_t b, int64_t e, int) { + for (int64_t i = b * 16; i < e * 16; i += 16) + store_bf16(x + i, _mm512_add_ps(load_bfloat16_to_m512(x + i), round_bf16(_mm512_loadu_ps(y + i)))); + }); +} + +// ============================================================================= +// MoE router +// ============================================================================= +/// \brief logits[l][e] = x[l] . W[e] in fp32, W in the router's read order +/// (minicpm5_moe_model_def.cpp: 32-expert x 256-input blocks, expert-block major, +/// each block input-major with its 32 experts adjacent) +/// \note Rows go 8 at a time, so each weight vector is loaded once per 8 rows; every +/// logit is still one chain of fmas over d in order, as with one row at a time. +inline void router_logits(float* logits, const bf16* x, const bf16* w, int L, int D, int E) { + constexpr int ROW = minicpm5_moe_desc::ROUTER_ROW_BLOCK, COL = minicpm5_moe_desc::ROUTER_COL_BLOCK; + static_assert(ROW == 32, "two 16-lane accumulators per expert block"); + constexpr int R = 8; // rows per step: 16 accumulators + const int steps = (L + R - 1) / R; + prefill_pool().run(steps, [&](int64_t st0, int64_t st1, int) { + std::vector xf((size_t)R * D); + for (int st = (int)st0; st < (int)st1; st++) { + const int l0 = st * R, rows = std::min(R, L - l0); + // fp32 rows (a short last step repeats its last row; those logits are dropped) + for (int r = 0; r < R; r++) { + const bf16* xr = x + (size_t)(l0 + std::min(r, rows - 1)) * D; + for (int d = 0; d < D; d += 16) _mm512_storeu_ps(xf.data() + (size_t)r * D + d, load_bfloat16_to_m512(xr + d)); + } + for (int eb = 0; eb < E; eb += ROW) { + // 32 experts = two vectors; each input value scales one row of the block + __m512 a0[R], a1[R]; + for (int r = 0; r < R; r++) a0[r] = a1[r] = _mm512_setzero_ps(); + for (int db = 0; db < D; db += COL) { + const bf16* blk = w + ((size_t)(eb / ROW) * (D / COL) + db / COL) * ROW * COL; + for (int d = 0; d < COL; d++) { + const __m512 w0 = load_bfloat16_to_m512(blk + d * ROW), w1 = load_bfloat16_to_m512(blk + d * ROW + 16); + for (int r = 0; r < R; r++) { + const __m512 xv = _mm512_set1_ps(xf[(size_t)r * D + db + d]); + a0[r] = _mm512_fmadd_ps(xv, w0, a0[r]); + a1[r] = _mm512_fmadd_ps(xv, w1, a1[r]); + } + } + } + for (int r = 0; r < rows; r++) { + _mm512_storeu_ps(logits + (size_t)(l0 + r) * E + eb, a0[r]); + _mm512_storeu_ps(logits + (size_t)(l0 + r) * E + eb + 16, a1[r]); + } + } + } + }); +} + +/// \brief tokens routed to one expert, with their routing weights +struct expert_task { + int expert; + std::vector tokens; + std::vector weights; +}; + +/// \brief sigmoid scores, top k of (score + bias), weight = score / sum * scaling +/// (the bias only picks); grouped into one task per used expert +/// \note Ties in score + bias go to the lower expert index. +inline std::vector route(const float* logits, const std::vector& bias, int L, int E, int top_k, float scaling) { + std::vector ids((size_t)L * top_k); + std::vector wts((size_t)L * top_k); + prefill_pool().run(L, [&](int64_t l0, int64_t l1, int) { + std::vector score(E), choice(E); + std::vector order(E); + for (int64_t l = l0; l < l1; l++) { + for (int e = 0; e < E; e++) { + score[e] = 1.0f / (1.0f + std::exp(-logits[(size_t)l * E + e])); + choice[e] = score[e] + bias[e]; + } + std::iota(order.begin(), order.end(), 0); + std::partial_sort(order.begin(), order.begin() + top_k, order.end(), [&](int a, int b) { + return choice[a] > choice[b] || (choice[a] == choice[b] && a < b); + }); + float sum = 0.0f; + for (int k = 0; k < top_k; k++) sum += score[order[k]]; + for (int k = 0; k < top_k; k++) { + ids[(size_t)l * top_k + k] = order[k]; + wts[(size_t)l * top_k + k] = score[order[k]] / (sum + 1e-20f) * scaling; + } + } + }); + // one task per expert, tokens in order + std::vector by_expert(E); + for (int e = 0; e < E; e++) by_expert[e].expert = e; + for (int l = 0; l < L; l++) { + for (int k = 0; k < top_k; k++) { + expert_task& t = by_expert[ids[(size_t)l * top_k + k]]; + t.tokens.push_back(l); + t.weights.push_back(wts[(size_t)l * top_k + k]); + } + } + std::vector tasks; + for (auto& t : by_expert) + if (!t.tokens.empty()) tasks.push_back(std::move(t)); + return tasks; +} + +} // namespace minicpm5_moe_cpu diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_model_def.cpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_model_def.cpp new file mode 100644 index 000000000..0f98a1240 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_model_def.cpp @@ -0,0 +1,334 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_model_def.cpp +/// \brief weight loaders for MiniCPM5-15B-A2.5B +/// \note Ported from FLM_Xclbin/MiniCPM5/moe_decoding/host/decoding_layer.cpp +/// and lm_head_npu_bin/host/host.cpp. A Q4_K tensor in model.q4nx is row blocks +/// of 32 rows, each row block's 256-column blocks back to back, so "rows a..b" +/// of a tensor is one contiguous byte range. +#include +#include +#include "minicpm5_moe_model_def.hpp" + +namespace { + +constexpr size_t Q4K_BLOCK = minicpm5_moe_desc::Q4K_BLOCK_BYTES; + +/// Lays a quantized weight out in the order the proj engine reads it: rows of +/// blocks are taken vertical_blocks at a time and interleaved block by block, +/// so one shim BD streams the blocks of vertical_blocks proj cores together. +void reorder_cpy(u8* dst, const u8* src, size_t src_bytes, int col, size_t a_block_size, int vertical_blocks = 2) { + const int blocks_per_row = col / QXNX_COL_BLOCK_SIZE; + const size_t row_bytes = a_block_size * blocks_per_row; // one 32-row block row + const int rows = (int)(src_bytes / row_bytes); + const u8* src_end = src + src_bytes; + + u8* dst_ptr = dst; + std::vector src_ptr(vertical_blocks); + for (int i = 0; i < vertical_blocks; i++) + src_ptr[i] = src + i * row_bytes; + + for (int r = 0; r < rows; r += vertical_blocks) { + for (int c = 0; c < blocks_per_row; c++) { + for (int i = 0; i < vertical_blocks; i++) { + memcpy(dst_ptr, src_ptr[i], a_block_size); + dst_ptr += a_block_size; + src_ptr[i] += a_block_size; + } + } + for (int i = 0; i < vertical_blocks; i++) { + src_ptr[i] += (vertical_blocks - 1) * row_bytes; + if (src_ptr[i] + row_bytes > src_end) + src_ptr[i] = src; // useless padding + } + } +} + +/// Q4_K blocks (32 rows x 256 columns, 4736 B) from the q4nx order into the order +/// of moe_decoding's int8-mmul kernel (_Q4K_x_int8 in kernels/q4_core.h), in place: +/// qs [256 columns][16 B] -> [k step 16][half t 2][16 columns][8 B] +/// (byte b of a column holds rows 2b, 2b + 1; half t = rows 16t .. 16t+15) +/// scales [group 8][32 rows] -> [h 2][t 2][a 4][16 rows], group = 4h + a +/// mins, S, M unchanged. +/// One B matrix of the mmul (16 columns x 16 rows) is then 128 contiguous bytes. +void q4k_relayout_for_mmul(u8* data, size_t bytes) { + constexpr size_t SCALES = 0, QS = 512; + assert(bytes % Q4K_BLOCK == 0); + const int64_t n_blocks = (int64_t)(bytes / Q4K_BLOCK); + // every block is independent: split them over the host cores + #pragma omp parallel for schedule(static) + for (int64_t b = 0; b < n_blocks; b++) { + u8* blk = data + b * Q4K_BLOCK; + std::array old; + memcpy(old.data(), blk, Q4K_BLOCK); + for (int k = 0; k < 16; k++) // 16 columns per k step + for (int t = 0; t < 2; t++) // rows 16t .. 16t+15 + for (int c = 0; c < 16; c++) + memcpy(blk + QS + (k * 2 + t) * 128 + c * 8, + old.data() + QS + (k * 16 + c) * 16 + t * 8, 8); + for (int h = 0; h < 2; h++) + for (int t = 0; t < 2; t++) + for (int a = 0; a < 4; a++) + memcpy(blk + SCALES + ((h * 2 + t) * 4 + a) * 16, + old.data() + SCALES + (4 * h + a) * 32 + 16 * t, 16); + } +} + +/// bytes of `rows` rows of a Q4_K matrix with `in_dim` columns +size_t q4k_row_bytes(size_t rows, size_t in_dim) { + return rows / QXNX_ROW_BLOCK_SIZE * (in_dim / QXNX_COL_BLOCK_SIZE) * Q4K_BLOCK; +} + +/// [up rows 0..n | gate rows 0..n | up rows n..2n | gate rows n..2n | ...], n = rows_per_piece, +/// so every proj round holds matching up and gate rows for the GLU +void interleave_up_gate(u8* out, const u8* up, const u8* gate, size_t rows, size_t rows_per_piece, size_t in_dim) { + const size_t piece = q4k_row_bytes(rows_per_piece, in_dim); + for (size_t r = 0; r < rows; r += rows_per_piece) { + memcpy(out, up, piece); out += piece; up += piece; + memcpy(out, gate, piece); out += piece; gate += piece; + } +} + +/// load one tensor and check its size against `bytes` (default: the descriptor's) +buffer load_checked(Q4NX& q4nx, const std::string& name, size_t bytes) { + buffer w; + q4nx.load_weights(w, name); + if (w.size() != bytes) { + throw std::runtime_error("minicpm5_moe_npu: " + name + " is " + std::to_string(w.size()) + + " bytes, expected " + std::to_string(bytes)); + } + return w; +} +buffer load_checked(Q4NX& q4nx, weight_desc_t& desc, int layer_idx) { + return load_checked(q4nx, desc.format_name(layer_idx), desc.get_size()); +} + +void check_ready(minicpm5_moe_layer_def& L, int layer_idx) { + for (weight_desc_t* w : L.all()) { + if (!w->ready()) { + throw std::runtime_error("minicpm5_moe_npu: weight not loaded: " + w->format_name(layer_idx)); + } + } +} + +} // namespace + +void minicpm5_moe_desc::load_layer(int layer_idx, Q4NX& q4nx, buffer& proj, buffer& rms, + std::vector& router_bias) { + const bool is_dense = layer_kind(layer_idx) == minicpm5_moe_layer_kind::dense; + minicpm5_moe_layer_def& W = layer_def(layer_idx); + assert(proj.size() >= W.proj_bytes && rms.size() * sizeof(bf16) >= W.rms_bytes); + u8* p = proj.data(); + const std::string prefix = "model.layer." + std::to_string(layer_idx) + "."; + + // ---- routed experts ---- + // One expert = [channel 0 stream | channel 1 stream], expert e at + // e * (its gate/up + down bytes) from the up region's start (the router uses + // the same offsets). Each channel stream is that channel's gate/up blocks then + // its down blocks, in the order the proj cores read them, so the router starts + // one linear BD per channel per expert. + // gate/up rows: the 4 cores of a column take 4 row blocks per round; with + // 64-row pieces cores 0, 1 make up and cores 2, 3 make gate, so one round + // of a column is [up 64 | gate 64] + // down rows: in order + // channels: reorder_cpy(..., 4) puts the 4 blocks of a group next to each + // other; channel 0 feeds cores 0, 1 (the first 2), channel 1 cores 2, 3 + { + weight_desc_t& d_up = W.ffn_up_exps; + weight_desc_t& d_gate = W.ffn_gate_exps; + weight_desc_t& d_down = W.ffn_down_exps; + assert(d_gate.offset == d_up.offset + d_up.get_size()); + assert(d_down.offset == d_gate.offset + d_gate.get_size()); + const int experts = (int)W.experts; + const size_t up_per_expert = d_up.get_size() / experts; + const size_t down_per_expert = d_down.get_size() / experts; + assert(up_per_expert == q4k_row_bytes(expert_width, D)); + buffer w_up, w_gate, w_down; + if (is_dense) { + // the 8192-wide MLP as 16 experts of 512: up/gate rows e*512.. are + // already expert e's bytes; down [D, 8192] gives expert e its column + // blocks 2e, 2e+1 of every row block + w_up = load_checked(q4nx, prefix + "mlp.up_proj.weight", d_up.get_size()); + w_gate = load_checked(q4nx, prefix + "mlp.gate_proj.weight", d_gate.get_size()); + buffer w_down_dense = load_checked(q4nx, prefix + "mlp.down_proj.weight", d_down.get_size()); + const size_t piece = expert_width / QXNX_COL_BLOCK_SIZE * Q4K_BLOCK; // one expert's part of a row block + w_down = buffer(w_down_dense.size()); + u8* dst = w_down.data(); + for (int e = 0; e < experts; e++) { + for (uint32_t rb = 0; rb < D / QXNX_ROW_BLOCK_SIZE; rb++) { + memcpy(dst, w_down_dense.data() + ((size_t)rb * experts + e) * piece, piece); + dst += piece; + } + } + } + else { + w_up = load_checked(q4nx, d_up, layer_idx); + w_gate = load_checked(q4nx, d_gate, layer_idx); + w_down = load_checked(q4nx, d_down, layer_idx); + } + + const size_t gate_up_bytes = 2 * up_per_expert; + const size_t expert_bytes = gate_up_bytes + down_per_expert; + const size_t channel_bytes = expert_bytes / 2; + const size_t group = 4 * Q4K_BLOCK; // the 4 blocks of one group + + // ch0 takes the first 2 blocks of every group of `src`, ch1 the last 2 + auto split_channels = [&](u8*& ch0, u8*& ch1, const u8* src, size_t bytes) { + assert(bytes % group == 0); + for (size_t g = 0; g < bytes; g += group) { + memcpy(ch0, src + g, group / 2); ch0 += group / 2; + memcpy(ch1, src + g + group / 2, group / 2); ch1 += group / 2; + } + }; + + // every expert writes its own byte range: run them on all host cores + #pragma omp parallel + { + std::vector both(gate_up_bytes), gate_up(gate_up_bytes), down(down_per_expert); + #pragma omp for schedule(static) + for (int e = 0; e < experts; e++) { + interleave_up_gate(both.data(), w_up.data() + e * up_per_expert, w_gate.data() + e * up_per_expert, + expert_width, EXPERT_ROWS_PER_ROUND, D); + reorder_cpy(gate_up.data(), both.data(), gate_up_bytes, D, Q4K_BLOCK, 4); + reorder_cpy(down.data(), w_down.data() + e * down_per_expert, down_per_expert, expert_width, Q4K_BLOCK, 4); + + u8* ch0 = p + d_up.offset + e * expert_bytes; + u8* ch1 = ch0 + channel_bytes; + split_channels(ch0, ch1, gate_up.data(), gate_up_bytes); + split_channels(ch0, ch1, down.data(), down_per_expert); + assert(ch0 == p + d_up.offset + e * expert_bytes + channel_bytes); + } + } + d_up.load(); + d_gate.load(); + d_down.load(); + } + + // ---- attention: k, v, q, gate back to back (one matrix to the proj engine), then o ---- + { + assert(W.attn_v.offset == W.attn_k.offset + W.attn_k.get_size()); + assert(W.attn_q.offset == W.attn_v.offset + W.attn_v.get_size()); + assert(W.attn_gate.offset == W.attn_q.offset + W.attn_q.get_size()); + // model KV head h -> kernel heads h * dup .. h * dup + dup - 1; rows are + // output-major, so a head is one byte range + const uint32_t dup = num_kv_heads / model_kv_heads; + for (weight_desc_t* w : {&W.attn_k, &W.attn_v}) { + buffer src = load_checked(q4nx, w->format_name(layer_idx), w->get_size() / dup); + const size_t head_bytes = src.size() / model_kv_heads; + buffer heads(w->get_size()); + for (uint32_t h = 0; h < num_kv_heads; h++) + memcpy(heads.data() + h * head_bytes, src.data() + (h / dup) * head_bytes, head_bytes); + reorder_cpy(p + w->offset, heads.data(), heads.size(), D, Q4K_BLOCK); + w->load(); + } + for (weight_desc_t* w : {&W.attn_q, &W.attn_gate}) { + buffer src = load_checked(q4nx, *w, layer_idx); + reorder_cpy(p + w->offset, src.data(), src.size(), D, Q4K_BLOCK); + w->load(); + } + buffer w_o = load_checked(q4nx, W.attn_output, layer_idx); + reorder_cpy(p + W.attn_output.offset, w_o.data(), w_o.size(), DQ, Q4K_BLOCK); + W.attn_output.load(); + } + + // ---- shared expert: up/gate one proj round = [up 256 | gate 256], down in row order ---- + { + weight_desc_t& d_up = W.ffn_up_shexp; + weight_desc_t& d_gate = W.ffn_gate_shexp; + weight_desc_t& d_down = W.ffn_down_shexp; + assert(d_gate.offset == d_up.offset + d_up.get_size()); + assert(d_down.offset == d_gate.offset + d_gate.get_size()); + if (is_dense) { + // no shared expert: zero Q4_K blocks (scales 0) add nothing + memset(p + d_up.offset, 0, d_up.get_size() + d_gate.get_size() + d_down.get_size()); + } + else { + buffer w_up = load_checked(q4nx, d_up, layer_idx); + buffer w_gate = load_checked(q4nx, d_gate, layer_idx); + buffer both(w_up.size() + w_gate.size()); + interleave_up_gate(both.data(), w_up.data(), w_gate.data(), expert_width, SHARED_ROWS_PER_ROUND, D); + reorder_cpy(p + d_up.offset, both.data(), both.size(), D, Q4K_BLOCK); + buffer w_down = load_checked(q4nx, d_down, layer_idx); + reorder_cpy(p + d_down.offset, w_down.data(), w_down.size(), expert_width, Q4K_BLOCK); + } + d_up.load(); + d_gate.load(); + d_down.load(); + } + + // every proj weight block into the int8-mmul kernel's order (Q4K_INT8_MMUL 1); + // zero blocks stay zero + q4k_relayout_for_mmul(p, W.proj_bytes); + + // ---- rms buffer: the two norms, then the router weight ---- + for (weight_desc_t* w : {&W.input_layer_norm, &W.post_attntion_norm}) { + buffer src = load_checked(q4nx, *w, layer_idx); + memcpy((u8*)rms.data() + w->offset, src.data(), w->get_size()); + w->load(); + } + // Router weight, stored in the exact order the router reads it, so its DMA is + // two straight reads. model.q4nx holds it as [D][E]; the router takes + // 32-expert x 256-input blocks, expert-block major, each block input-major + // with the 32 experts adjacent. Layer 0 has no router: the router core still + // reads one (zeros) and then picks experts 0..15 itself (FIRST_K_DENSE). + { + bf16* dst = (bf16*)((u8*)rms.data() + W.ffn_gate_inp.offset); + if (is_dense) { + memset(dst, 0, W.ffn_gate_inp.get_size()); + } + else { + buffer bytes = load_checked(q4nx, W.ffn_gate_inp, layer_idx); + const bf16* w_router = (const bf16*)bytes.data(); + for (uint32_t eb = 0; eb < num_experts; eb += ROUTER_ROW_BLOCK) { + for (uint32_t db = 0; db < D; db += ROUTER_COL_BLOCK) { + for (uint32_t d = db; d < db + ROUTER_COL_BLOCK; d++) { + memcpy(dst, w_router + (size_t)d * num_experts + eb, ROUTER_ROW_BLOCK * sizeof(bf16)); + dst += ROUTER_ROW_BLOCK; + } + } + } + } + W.ffn_gate_inp.load(); + } + // router expert bias: fp32, only picks the experts (see route() in minicpm5_moe_cpu_functions.hpp) + router_bias.assign(num_experts, 0.0f); + if (!is_dense) { + buffer bias_bytes = load_checked(q4nx, prefix + "moe_expert_bias", num_experts * sizeof(float)); + memcpy(router_bias.data(), bias_bytes.data(), bias_bytes.size()); + } + check_ready(W, layer_idx); +} + +/// lm_head.weight, Q8_0 blocks [scales bf16 (8 groups x 32 rows) | q int8 (256 cols x 32 rows)]. +/// A column's weights arrive on two shim channels, one per pair of cores, so each +/// column-round has to be two contiguous halves in DDR rather than one run with all +/// four cores' blocks interleaved: rows r+0/r+1 of the group for the stream that +/// feeds cores 0 and 1, rows r+2/r+3 for the stream that feeds cores 2 and 3. Within +/// a half the order is still k-major, one block per core, because that is exactly one +/// memtile slot. See lm_head_memtile in lm_head_npu_bin/iron/q4k_mm.py. +void minicpm5_moe_desc::load_lm_head(Q4NX& q4nx, buffer& dst) { + constexpr int vertical_blocks = 4; + constexpr int rows_per_stream = vertical_blocks / 2; + buffer src; + q4nx.load_weights(src, "lm_head.weight"); + const int blocks_per_row = D / QXNX_COL_BLOCK_SIZE; + const int rows = (int)(src.size() / Q80_BLOCK_BYTES / blocks_per_row); + assert(dst.size() >= (size_t)vocab_size_padded / 32 * blocks_per_row * Q80_BLOCK_BYTES); + + u8* dst_ptr = dst.data(); + for (int r = 0; r < rows; r += vertical_blocks) { + for (int half = 0; half < 2; half++) { + for (int c = 0; c < blocks_per_row; c++) { + for (int i = 0; i < rows_per_stream; i++) { + const int row = r + half * rows_per_stream + i; + const u8* src_ptr = (row < rows) + ? src.data() + (size_t)(row * blocks_per_row + c) * Q80_BLOCK_BYTES + : src.data(); // useless padding + memcpy(dst_ptr, src_ptr, Q80_BLOCK_BYTES); + dst_ptr += Q80_BLOCK_BYTES; + } + } + } + } +} diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_model_def.hpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_model_def.hpp new file mode 100644 index 000000000..5a70065ce --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_model_def.hpp @@ -0,0 +1,281 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_model_def.hpp +/// \brief weight-shape definition for MiniCPM5-15B-A2.5B (minicpm5_moe) +/// \author FastFlowLM Team +/// \date 2026-12-03 +/// \note Every layer runs on one decode overlay, FLM_Xclbin/MiniCPM5/moe_decoding: +/// * layers 1..27: GQA attention with a sigmoid output gate + 160 experts, +/// top 16, plus one shared expert, all 512 wide, with a sigmoid router +/// * layer 0 (first_k_dense_replace = 1): the same attention + an 8192-wide +/// SwiGLU MLP. SwiGLU is elementwise over its width, so the MLP is the sum +/// of 16 slices of 512: the host stores them as experts 0..15, the router +/// picks those with weight 1 for this layer, and the shared expert is zero. +/// The model has 2 KV heads, the kernels 4 (one per attention CU): every k/v +/// head is loaded twice, [h0, h0, h1, h1], and the KV cache holds each twice. +/// Every projection is Q4_K (4736-byte 32x256 blocks), the lm_head is Q8_0. +/// The layouts and loaders below are ported from moe_decoding's +/// host/decoding_layer.cpp, which is checked against the Q4_K reference; +/// keep them in step with the kernels, not with other engines. +#ifndef __MINICPM5_MOE_MODEL_DEF_HPP__ +#define __MINICPM5_MOE_MODEL_DEF_HPP__ +#include +#include +#include +#include "lm_config.hpp" +#include "weight_desc.hpp" +#include "tensor_utils/q4_npu_eXpress.hpp" + +/// @brief layer 0 (dense MLP as experts 0..15) or a routed MoE layer +enum class minicpm5_moe_layer_kind { dense, moe }; + +/// @brief one layer's buffers, both kinds +/// @note proj buffer order = device order: routed up, gate, down (one region, +/// re-cut per expert, see load_layer), k, v, q, gate (one matrix to the +/// proj engine: RoPE takes K/V first, then Q, the output gate tile the +/// gate logits), o, shared up|gate, shared down. +/// rms buffer: [input_layernorm | post_attention_layernorm | router weight]. +/// The two kinds differ only in how many experts the routed region holds +/// (16 for layer 0, 160 otherwise); the router weight is always 160 wide +/// (zero for layer 0: the router reads it all the same). +struct minicpm5_moe_layer_def { + uint32_t experts = 0; // experts stored in the routed region + weight_desc_t ffn_up_exps, ffn_gate_exps, ffn_down_exps; + weight_desc_t attn_k, attn_v, attn_q, attn_gate, attn_output; + weight_desc_t ffn_up_shexp, ffn_gate_shexp, ffn_down_shexp; + weight_desc_t input_layer_norm, post_attntion_norm, ffn_gate_inp; + size_t proj_bytes = 0, rms_bytes = 0; + + std::vector proj_all() { + return {&ffn_up_exps, &ffn_gate_exps, &ffn_down_exps, + &attn_k, &attn_v, &attn_q, &attn_gate, &attn_output, + &ffn_up_shexp, &ffn_gate_shexp, &ffn_down_shexp}; + } + std::vector rms_all() { return {&input_layer_norm, &post_attntion_norm, &ffn_gate_inp}; } + std::vector all() { + std::vector v = proj_all(); + for (weight_desc_t* w : rms_all()) v.push_back(w); + return v; + } +}; + +struct minicpm5_moe_desc { + // ---- values baked into the xclbins (FLM_Xclbin/MiniCPM5/*/models/*.h) ---- + // build() refuses a config.json that disagrees: the kernels would not notice. + static constexpr uint32_t KERNEL_D = 2048; + static constexpr uint32_t KERNEL_DH = 128; + static constexpr uint32_t KERNEL_HEADS = 32; + static constexpr uint32_t KERNEL_KV_HEADS = 4; // model KV heads, each twice + static constexpr uint32_t MODEL_KV_HEADS = 2; + static constexpr uint32_t KERNEL_DENSE_WIDTH = 8192; // layer 0 = TOP_K experts + static constexpr uint32_t KERNEL_EXPERT_WIDTH = 512; + static constexpr uint32_t KERNEL_EXPERTS = 160; + static constexpr uint32_t KERNEL_TOP_K = 16; + static constexpr uint32_t KERNEL_FIRST_K_DENSE = 1; // FIRST_K_DENSE: the router's fixed-expert layers + static constexpr uint32_t KERNEL_MAX_LAYERS = 28; // the router's per-layer address table + static constexpr uint32_t KERNEL_VOCAB = 131072; // lm_head.xclbin + static constexpr float KERNEL_ROUTER_SCALING = 3.66f; // ROUTER_SCALING + + // up/gate rows per proj round (one round = 16 cores x 32 rows = 512 values): + // shared expert [up 256 | gate 256], routed experts [up 64 | gate 64] per column + static constexpr int SHARED_ROWS_PER_ROUND = 256; + static constexpr int EXPERT_ROWS_PER_ROUND = 64; + // router weight blocks: 32 experts x 256 inputs (router_weight_row/col_block) + static constexpr int ROUTER_ROW_BLOCK = 32; + static constexpr int ROUTER_COL_BLOCK = 256; + // the router memtile holds this many experts' weights; the rest go straight + // to the router helper (MT_EXPERTS in iron/router_w_memtile.py) + static constexpr uint32_t ROUTER_MT_EXPERTS = 128; + // attention: 2 array columns, each holding 2 of the 4 KV heads + static constexpr int ATTN_COLS = 2; + // the attention reads K/V in 16-token chunks, so MAX_L must be whole chunks + static constexpr int KV_CHUNK = 16; + // largest KV cache the engine allocates (the 128K default context) + static constexpr uint32_t MAX_CONTEXT = 131072; + + static constexpr size_t Q4K_BLOCK_BYTES = 4736; // one 32 x 256 Q4_K block + static constexpr size_t Q80_BLOCK_BYTES = 8704; // one 32 x 256 Q8_0 block + + uint32_t num_hidden_layers; + uint32_t D, DH, DQ, DK, DV, RoPE_DIM; + uint32_t num_heads; + uint32_t num_kv_heads; // the kernels' (4): model heads duplicated + uint32_t model_kv_heads; // config.json's (2) + uint32_t dense_width; // intermediate_size, layer 0's MLP + uint32_t expert_width; // moe_intermediate_size (routed and shared) + uint32_t num_experts, top_k; + uint32_t first_k_dense; + uint32_t vocab_size, vocab_size_padded; + f32 rms_norm_eps; + f32 rope_theta; + f32 router_scaling; // routed_scaling_factor: weights = score / sum * this + std::vector inv_freq; // RoPE_DIM / 2, fp32 like transformers + + minicpm5_moe_layer_def dense; // layer 0: 16 experts + minicpm5_moe_layer_def moe; // layers 1..: 160 experts + + inline minicpm5_moe_layer_kind layer_kind(int idx) const { + return idx < (int)first_k_dense ? minicpm5_moe_layer_kind::dense : minicpm5_moe_layer_kind::moe; + } + inline minicpm5_moe_layer_def& layer_def(int idx) { + return layer_kind(idx) == minicpm5_moe_layer_kind::dense ? dense : moe; + } + inline const minicpm5_moe_layer_def& layer_def(int idx) const { + return layer_kind(idx) == minicpm5_moe_layer_kind::dense ? dense : moe; + } + + /// @brief one layer's KV cache in elements: [K col 0][K col 1][V col 0][V col 1], + /// each MAX_L x (2 kernel KV heads x DH) + inline size_t get_kv_cache_elems(uint32_t MAX_L) const { return (size_t)MAX_L * (DK + DV); } + /// @brief zero rows after the last block (V col 1): the prefill attention reads + /// whole 128-row blocks up to ~380 rows past MAX_L for a chunk that ends + /// near it (the other blocks' overrun lands in the next block: finite, + /// and masked) + static constexpr uint32_t KV_TAIL_ROWS = 512; + /// @brief elements to allocate per layer: the cache plus its zero tail + inline size_t get_kv_cache_alloc_elems(uint32_t MAX_L) const { + return get_kv_cache_elems(MAX_L) + (size_t)KV_TAIL_ROWS * kv_col_row(); + } + /// @brief elements per token of one column's K (or V) block + inline size_t kv_col_row() const { return (size_t)(num_kv_heads / ATTN_COLS) * DH; } + /// @brief element offset of a column's K (kv = 0) or V (kv = 1) block + /// (kv_cache_view::row in minicpm5_moe_prefill_ops.hpp has the same rule) + inline size_t kv_block_offset(int col, int kv, uint32_t MAX_L) const { + return (size_t)(2 * kv + col) * MAX_L * kv_col_row(); + } + /// @brief rope buffer: [cos RoPE_DIM/2 | sin RoPE_DIM/2] (no q/k norm) + inline size_t get_rope_rms_elems() const { return RoPE_DIM; } + /// @brief lm_head buffer bytes: Q8_0, vocab padded to 1024 rows + inline size_t get_lm_head_w_size() const { + return (size_t)vocab_size_padded / 32 * (D / 256) * Q80_BLOCK_BYTES; + } + + inline void build(LM_Config& config) { + num_hidden_layers = config.get("num_hidden_layers"); + D = config.get("hidden_size"); + num_heads = config.get("num_attention_heads"); + model_kv_heads = config.get("num_key_value_heads", num_heads); + num_kv_heads = KERNEL_KV_HEADS; + DH = config.get("head_dim", D / num_heads); + DQ = DH * num_heads; + DK = DH * num_kv_heads; + DV = DH * num_kv_heads; + RoPE_DIM = DH; // full-head rotation (NEOX) + dense_width = config.get("intermediate_size"); + expert_width = config.get("moe_intermediate_size"); + num_experts = config.get("n_routed_experts"); + top_k = config.get("num_experts_per_tok"); + first_k_dense = config.get("first_k_dense_replace", 1); + vocab_size = config.get("vocab_size"); + vocab_size_padded = (vocab_size + 1024 - 1) / 1024 * 1024; + // (eos_token_id is a list here; the tokens to stop on are the frontend's) + rms_norm_eps = config.get("rms_norm_eps", 1e-6f); + router_scaling = config.get("routed_scaling_factor", 1.0f); + rope_theta = config.get("rope_theta", 10000.0f); + inv_freq.resize(RoPE_DIM / 2); + for (uint32_t i = 0; i < RoPE_DIM / 2; i++) { + // fp32, as transformers builds it: theta^(-2i / dim) + inv_freq[i] = (f32)(1.0 / std::pow((double)rope_theta, (2.0 * i) / RoPE_DIM)); + } + + DEBUG_BLOCK(1, + std::cout << "================ minicpm5_moe_desc ================" << std::endl; + std::cout << std::left << std::setw(28) << "num_hidden_layers" << " = " << num_hidden_layers << std::endl; + std::cout << std::left << std::setw(28) << "first_k_dense" << " = " << first_k_dense << std::endl; + std::cout << std::left << std::setw(28) << "D (hidden_size)" << " = " << D << std::endl; + std::cout << std::left << std::setw(28) << "DH (head_dim)" << " = " << DH << std::endl; + std::cout << std::left << std::setw(28) << "DQ / DK / DV" << " = " << DQ << " / " << DK << " / " << DV << std::endl; + std::cout << std::left << std::setw(28) << "heads / kv (model)" << " = " << num_heads << " / " << num_kv_heads + << " (" << model_kv_heads << ")" << std::endl; + std::cout << std::left << std::setw(28) << "dense_width" << " = " << dense_width << std::endl; + std::cout << std::left << std::setw(28) << "expert_width" << " = " << expert_width << std::endl; + std::cout << std::left << std::setw(28) << "experts / top_k" << " = " << num_experts << " / " << top_k << std::endl; + std::cout << std::left << std::setw(28) << "rms_norm_eps" << " = " << rms_norm_eps << std::endl; + std::cout << std::left << std::setw(28) << "rope_theta" << " = " << rope_theta << std::endl; + std::cout << std::left << std::setw(28) << "router_scaling" << " = " << router_scaling << std::endl; + std::cout << std::left << std::setw(28) << "vocab (padded)" << " = " << vocab_size << " (" << vocab_size_padded << ")" << std::endl; + std::cout << "==============================================" << std::endl; + ) + + _check_against_kernels(); + _build_layer(dense, dense_width / expert_width); + _build_layer(moe, num_experts); + } + + /// @brief one layer's weights; returns nothing, every value is in the buffers + /// @param proj Q4_K projections in proj engine order (layer_def(idx).proj_all()), + /// relaid for the int8-mmul kernel + /// @param rms [input_layernorm | post_attention_layernorm | router weight in read order] + /// @param router_bias out: the fp32 expert bias (moe_expert_bias; zero for layer 0), + /// sent with RTP writes + void load_layer(int layer_idx, Q4NX& q4nx, buffer& proj, buffer& rms, std::vector& router_bias); + + /// @brief lm_head.weight (Q8_0) in lm_head.xclbin's read order + void load_lm_head(Q4NX& q4nx, buffer& dst); + +private: + inline void _check_against_kernels() { + struct { const char* name; uint32_t got, want; } checks[] = { + {"hidden_size", D, KERNEL_D}, + {"head_dim", DH, KERNEL_DH}, + {"num_attention_heads", num_heads, KERNEL_HEADS}, + {"num_key_value_heads", model_kv_heads, MODEL_KV_HEADS}, + {"intermediate_size", dense_width, KERNEL_DENSE_WIDTH}, + {"moe_intermediate_size", expert_width, KERNEL_EXPERT_WIDTH}, + {"n_routed_experts", num_experts, KERNEL_EXPERTS}, + {"num_experts_per_tok", top_k, KERNEL_TOP_K}, + {"first_k_dense_replace", first_k_dense, KERNEL_FIRST_K_DENSE}, + {"vocab_size (padded)", vocab_size_padded, KERNEL_VOCAB}, + }; + for (auto& c : checks) { + if (c.got != c.want) { + throw std::runtime_error(std::string("minicpm5_moe_npu: config ") + c.name + " = " + std::to_string(c.got) + + ", but the xclbins are built for " + std::to_string(c.want)); + } + } + if (num_hidden_layers > KERNEL_MAX_LAYERS) { + throw std::runtime_error("minicpm5_moe_npu: the MoE router keeps addresses for " + + std::to_string(KERNEL_MAX_LAYERS) + " layers only"); + } + if (std::fabs(router_scaling - KERNEL_ROUTER_SCALING) > 1e-6f) { + throw std::runtime_error("minicpm5_moe_npu: routed_scaling_factor " + std::to_string(router_scaling) + + " differs from the router kernel's"); + } + // layer 0's MLP is exactly the TOP_K experts the router fixes for it + if (dense_width != top_k * expert_width) { + throw std::runtime_error("minicpm5_moe_npu: intermediate_size must be num_experts_per_tok x moe_intermediate_size"); + } + } + + /// @param experts how many experts the routed region holds + inline void _build_layer(minicpm5_moe_layer_def& L, uint32_t experts) { + L.experts = experts; + L.ffn_up_exps = weight_desc_t(flm_q4k, {D, expert_width, experts}, "model.layer.%d.mlp.up_exps_proj.weight"); + L.ffn_gate_exps = weight_desc_t(flm_q4k, {D, expert_width, experts}, "model.layer.%d.mlp.gate_exps_proj.weight"); + L.ffn_down_exps = weight_desc_t(flm_q4k, {expert_width, D, experts}, "model.layer.%d.mlp.down_exps_proj.weight"); + L.attn_k = weight_desc_t(flm_q4k, {D, DK}, "model.layer.%d.self_attn.k_proj.weight"); + L.attn_v = weight_desc_t(flm_q4k, {D, DV}, "model.layer.%d.self_attn.v_proj.weight"); + L.attn_q = weight_desc_t(flm_q4k, {D, DQ}, "model.layer.%d.self_attn.q_proj.weight"); + L.attn_gate = weight_desc_t(flm_q4k, {D, DQ}, "model.layer.%d.self_attn.gate_proj.weight"); + L.attn_output = weight_desc_t(flm_q4k, {DQ, D}, "model.layer.%d.self_attn.o_proj.weight"); + L.ffn_up_shexp = weight_desc_t(flm_q4k, {D, expert_width}, "model.layer.%d.mlp.share_up_exps_proj.weight"); + L.ffn_gate_shexp = weight_desc_t(flm_q4k, {D, expert_width}, "model.layer.%d.mlp.share_gate_exps_proj.weight"); + L.ffn_down_shexp = weight_desc_t(flm_q4k, {expert_width, D}, "model.layer.%d.mlp.share_down_exps_proj.weight"); + L.input_layer_norm = weight_desc_t(flm_bf16, {D}, "model.layer.%d.input_layernorm.weight"); + L.post_attntion_norm = weight_desc_t(flm_bf16, {D}, "model.layer.%d.post_attention_layernorm.weight"); + L.ffn_gate_inp = weight_desc_t(flm_bf16, {D, num_experts}, "model.layer.%d.moe_router.weight"); + + weight_container proj_c, rms_c; + for (weight_desc_t* w : L.proj_all()) proj_c.add_weight(*w); + for (weight_desc_t* w : L.rms_all()) rms_c.add_weight(*w); + L.proj_bytes = proj_c.get_size(); + L.rms_bytes = rms_c.get_size(); + // shim DMA offsets are 32-bit, and one buffer per layer keeps them small + if (L.proj_bytes >= 512ull * 1024 * 1024) { + throw std::runtime_error("minicpm5_moe_npu: one layer's weights do not fit 512 MB"); + } + } +}; + +#endif diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu.cpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu.cpp new file mode 100644 index 000000000..9d9f195c8 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu.cpp @@ -0,0 +1,507 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_npu.cpp +/// \brief minicpm5_moe_npu: MiniCPM5-15B-A2.5B on the NPU2 decode overlays +/// \note See minicpm5_moe_npu_detail.hpp for what one token runs. +#include +#include +#include "minicpm5_moe_npu_detail.hpp" +#include "npu_utils/runtime_wait.hpp" + +namespace { +// MC5_TIME_HOST=1: print where each token's host time goes, in microseconds (the +// same switch as the kernel host test in FLM_Xclbin/MiniCPM5/moe_decoding) +const bool time_host = std::getenv("MC5_TIME_HOST") != nullptr; +using host_clock = std::chrono::steady_clock; +long us_between(host_clock::time_point a, host_clock::time_point b) { + return (long)std::chrono::duration_cast(b - a).count(); +} +} // namespace + +minicpm5_moe_npu::Impl::Impl(LM_Config config, npu_xclbin_manager *npu_instance, int MAX_L) + : config(config), npu(npu_instance) { + current_context_length = 0; + checkpoint_context_length = 0; + is_checkpoint_valid = false; + desc.build(config); + pctx = std::make_unique(desc); + this->MAX_L = _normalize_max_length(MAX_L > 0 ? (uint32_t)MAX_L : 0); + + // Two decode bitstreams (+ the prefill overlay). The layer overlay's RTP addresses + // are constants in minicpm5_moe_npu_sequence.hpp, which has the note about + // re-checking them after a kernel rebuild. + const std::string xclbin_dir = utils::path_join(config.exec_path, "xclbins", config.model_name); + layer_app_manager = npu->register_xclbin(utils::path_join(xclbin_dir, "moe_layer.xclbin")); + lm_head_app_manager = npu->register_xclbin(utils::path_join(xclbin_dir, "lm_head.xclbin")); +#if MINICPM5_MOE_ATTN_ON_NPU || MINICPM5_MOE_MM_ON_NPU + // the batched prefill's dequant_mm / attention (one xclbin, see minicpm5_moe_prefill_overlay.hpp) + overlay = std::make_unique(npu, utils::path_join(xclbin_dir, "prefill_overlay.xclbin"), desc); + pctx->set_overlay(overlay.get()); +#endif + sequence = std::make_unique(desc, this->MAX_L); + + dense_layer = layer_app_manager->create_app(); + moe_layer = layer_app_manager->create_app(); + lm_head = lm_head_app_manager->create_app(); + router_rtp.resize(desc.num_hidden_layers); + for (uint32_t l = 0; l < desc.num_hidden_layers; l++) { + router_rtp[l] = layer_app_manager->create_app(); + } + layer_runlist = layer_app_manager->create_runlist(); + + // ---- per-layer buffers; sizes come from desc only ---- + const uint32_t N = desc.num_hidden_layers; + proj_weights.resize(N); + rms_weights.resize(N); + rope_rms_weights.resize(N); + kv_caches.resize(N); + router_bias.resize(N); + const size_t kv_elems = desc.get_kv_cache_alloc_elems(this->MAX_L); + size_t weight_bytes = 0; + for (uint32_t l = 0; l < N; l++) { + npu_app& app = _layer_app(l); + const minicpm5_moe_layer_def& W = desc.layer_def(l); + proj_weights[l] = app.create_bo_buffer(W.proj_bytes); + rms_weights[l] = app.create_bo_buffer(W.rms_bytes / sizeof(bf16)); + weight_bytes += W.proj_bytes + W.rms_bytes; + rope_rms_weights[l] = app.create_bo_buffer(desc.get_rope_rms_elems()); + // Zeroed once here: the attention reads whole 16-token chunks, so rows past + // L are read (and masked) and only have to be finite. Rows a token has + // written stay finite, so nothing has to re-zero them later. + kv_caches[l] = app.create_bo_buffer(kv_elems); + kv_caches[l].memset((bf16)0.0f); + kv_caches[l].sync_to_device(); + } + + x = moe_layer.create_bo_buffer(X_ELEMS); + assert(desc.D + desc.DQ <= X_ELEMS); + x.memset((bf16)0.0f); + lm_x = lm_head.create_bo_buffer(desc.D * 2); + lm_head_weights = lm_head.create_bo_buffer(desc.get_lm_head_w_size()); + logits = lm_head.create_bo_buffer(desc.vocab_size_padded); + logits_valid = buffer(logits.data(), desc.vocab_size); + embedding = std::make_unique(desc.vocab_size, desc.D); + + sequence->gen_lm_head_seq(lm_head.seq()); + lm_head_run = lm_head.create_run(logits, lm_head_weights, lm_x); + + LOG_VERBOSE(1, "minicpm5_moe_npu: MAX_L " << this->MAX_L << ", KV cache " << (kv_elems * sizeof(bf16) * N >> 20) << " MB, weights " + << (weight_bytes >> 20) << " MB"); +} + +uint32_t minicpm5_moe_npu::Impl::_normalize_max_length(uint32_t requested) { + uint32_t L = std::max(requested, 4096); + // a power of two is also a whole number of 16-token KV chunks + uint32_t pow2 = 1; + while (pow2 < L) pow2 <<= 1; + if (pow2 > minicpm5_moe_desc::MAX_CONTEXT) { + header_print("WARNING", "minicpm5_moe_npu: context " << requested << " capped at " << minicpm5_moe_desc::MAX_CONTEXT + << " (the longest KV cache the attention was checked at)"); + pow2 = minicpm5_moe_desc::MAX_CONTEXT; + } + return pow2; +} + +void minicpm5_moe_npu::Impl::load_weights(Q4NX& q4nx) { + embedding->init_weights(&q4nx, "model.embed_tokens"); + const bool check_layout = std::getenv("MC5_CHECK_LAYOUT") != nullptr; + + for (uint32_t l = 0; l < desc.num_hidden_layers; l++) { + desc.load_layer(l, q4nx, proj_weights[l], rms_weights[l], router_bias[l]); + // never changes, so this sequence is built once + sequence->gen_router_rtp_seq(router_rtp[l].seq(), l, router_bias[l]); + // MC5_CHECK_LAYOUT=1: the prefill's weight views against model.q4nx, byte for byte + if (check_layout) { + const size_t bad = pctx->check_layout(l, q4nx, proj_weights[l]); + const std::string tag = bad ? "ERROR" : "info"; // header_print does not parenthesize its tag + header_print(tag, "layout check, layer " << l << ": " << bad << " blocks differ"); + if (bad) throw std::runtime_error("minicpm5_moe_npu: the prefill weight views do not match the decode layout"); + } + proj_weights[l].sync_to_device(); + rms_weights[l].sync_to_device(); + rope_rms_weights[l].sync_to_device(); + } + + // the lm_head kernel reads the final norm weight from the second half of its x buffer + { + buffer final_norm; + q4nx.load_weights(final_norm, "model.norm.weight"); + memcpy(lm_x.data() + desc.D, final_norm.data(), desc.D * sizeof(bf16)); + lm_x.sync_to_device(); + } + desc.load_lm_head(q4nx, lm_head_weights); + lm_head_weights.sync_to_device(); + + // the prefill's buffers and threads now, not in the first prompt's time to first token + const host_clock::time_point t0 = host_clock::now(); + pctx->prewarm(std::min(PREFILL_CHUNK, (int)MAX_L)); + if (time_host) std::cout << "[minicpm5_moe time] prefill prewarm " << us_between(t0, host_clock::now()) << " us" << std::endl; + + clear_context(); +} + +void minicpm5_moe_npu::Impl::_set_rope(int pos) { + const uint32_t half = desc.RoPE_DIM / 2; + std::vector cos_sin(desc.RoPE_DIM); + for (uint32_t i = 0; i < half; i++) { + // fp32 angle, as transformers computes it (inv_freq fp32 * position fp32) + const float angle = desc.inv_freq[i] * (float)pos; + cos_sin[i] = (bf16)std::cos(angle); + cos_sin[i + half] = (bf16)std::sin(angle); + } + // every layer has its own buffer (a run binds its own BOs) + for (uint32_t l = 0; l < desc.num_hidden_layers; l++) { + memcpy(rope_rms_weights[l].data(), cos_sin.data(), desc.RoPE_DIM * sizeof(bf16)); + rope_rms_weights[l].sync_to_device(); + } +} + +/// L = tokens already in the cache; prepares the runs for the token at position L +void minicpm5_moe_npu::Impl::set_context_length(int L) { + current_context_length = L; + // The one rule the rest of this engine leans on: rows at or past the context are + // zero. Both attentions read whole rounds, so they reach past the last real key + // (prefill a 128-row round, decode a 16-row chunk), and the kernels do not keep + // those rows out of the answer -- as every other engine here already documents + // (kv_rows_state.hpp, qwen3_6_moe_npu.cpp). qwen3_6 wipes the whole cache on every + // clear; we only have to clean what has actually been written, which is what + // dirty_rows tracks. Growing the context needs nothing: those rows were zero and + // are being filled. Shrinking it (a clear, a restore, a slot written back) is where + // another conversation's rows would be left exposed. + // Callers set the length after the rows are in place, so afterwards exactly the + // first `want` rows hold K/V either way, whether we just grew or just cleaned. + const size_t want = (size_t)std::max(L, 0); + if (want < dirty_rows) { + kv_rows_zero(kv_caches, kv_layout(), want, dirty_rows); + } + dirty_rows = want; + // a full cache has no next call to prepare: that call would write row L, past + // the cache. forward() / prefill() refuse to run then. + if (L >= (int)MAX_L) return; + + const host_clock::time_point t0 = host_clock::now(); + sequence->gen_layer_seq(dense_layer.seq(), L + 1, desc.dense); + sequence->gen_layer_seq(moe_layer.seq(), L + 1, desc.moe); + const host_clock::time_point t1 = host_clock::now(); + // the runs hold the sequence's kernel object, so they are rebuilt with it + // (the first create_run after a sequence change also assembles its ELF) + layer_runlist.reset(); + for (uint32_t l = 0; l < desc.num_hidden_layers; l++) { + layer_runlist.add(router_rtp[l].create_run()); + layer_runlist.add(_layer_app(l).create_run(x, proj_weights[l], rms_weights[l], rope_rms_weights[l], kv_caches[l])); + } + const host_clock::time_point t2 = host_clock::now(); + _set_rope(L); + if (time_host) { + std::cout << "[minicpm5_moe time] L " << L << ": sequences " << us_between(t0, t1) << " us, runs (+ ELF) " + << us_between(t1, t2) << " us, rope " << us_between(t2, host_clock::now()) << " us" << std::endl; + } +} + +void minicpm5_moe_npu::Impl::_run_layers(int id) { + if (current_context_length >= (int)MAX_L) { + throw std::runtime_error("minicpm5_moe_npu: the KV cache is full (" + std::to_string(MAX_L) + " tokens)"); + } + const host_clock::time_point t0 = host_clock::now(); + embedding->forward(id, x); + x.sync_to_device(); + // the two contexts do not order against each other: wait for the layers before the lm_head + const host_clock::time_point t1 = host_clock::now(); + layer_runlist.execute(); + flm::npu::wait_for_completion(layer_runlist, "minicpm5_moe layer runlist"); + if (time_host) { + std::cout << "[minicpm5_moe time] embed " << us_between(t0, t1) << " us, layer runlist " + << us_between(t1, host_clock::now()) << " us" << std::endl; + } +} + +void minicpm5_moe_npu::Impl::_start_lm_head() { + x.sync_from_device(); + memcpy(lm_x.data(), x.data(), desc.D * sizeof(bf16)); + lm_x.sync_to_device(); + lm_head_run.start(); +} + +void minicpm5_moe_npu::Impl::_finish_lm_head() { + flm::npu::wait_for_completion(lm_head_run, "minicpm5_moe lm_head"); + logits.sync_from_device(); +} + +buffer minicpm5_moe_npu::Impl::forward(int id) { + _run_layers(id); + const host_clock::time_point t0 = host_clock::now(); + _start_lm_head(); + // the next token's sequences are built while the lm_head runs (it touches none of them) + set_context_length(current_context_length + 1); + _finish_lm_head(); + if (time_host) { + std::cout << "[minicpm5_moe time] lm_head + next sequences " << us_between(t0, host_clock::now()) << " us" << std::endl; + } + return logits_valid; +} + +/// Two ways to run the prompt (Makefile PREFILL_WITH_MV picks): +/// default batched, minicpm5_moe_prefill.hpp: chunks of PREFILL_CHUNK tokens +/// through all layers at once (dequant_mm + attention on the host +/// for now), writing the decode KV cache +/// PREFILL_WITH_MV the decode overlays, one token at a time +buffer minicpm5_moe_npu::Impl::prefill(std::vector& ids, void* payload) { + if (ids.empty()) { + throw std::runtime_error("minicpm5_moe_npu: empty prefill"); + } + if (current_context_length + ids.size() > MAX_L) { + throw std::runtime_error("minicpm5_moe_npu: prompt of " + std::to_string(ids.size()) + " tokens does not fit the KV cache (" + + std::to_string(current_context_length) + " of " + std::to_string(MAX_L) + " used)"); + } +#ifdef PREFILL_WITH_MV + return _prefill_with_mv(ids); +#else + return _prefill_batched(ids); +#endif +} + +buffer minicpm5_moe_npu::Impl::_prefill_with_mv(std::vector& ids) { + for (size_t i = 0; i + 1 < ids.size(); i++) { + _run_layers(ids[i]); + set_context_length(current_context_length + 1); + } + return forward(ids.back()); +} + +buffer minicpm5_moe_npu::Impl::_prefill_batched(std::vector& ids) { + // the decode buffers, which the prefill reads (weights) and writes (KV cache) in place + std::vector layers(desc.num_hidden_layers); + for (uint32_t l = 0; l < desc.num_hidden_layers; l++) { + layers[l] = {&proj_weights[l], &rms_weights[l], &rope_rms_weights[l], &kv_caches[l], &router_bias[l]}; + } + + // decode / lm_head ran since the last prefill (or nothing did yet): the overlay's + // configuration is gone, its first run writes all of it again + if (overlay) overlay->invalidate(); + + const int total = (int)ids.size(); + const int D = desc.D; + std::vector x; + int last_rows = 0; + // Chunks bound the scratch (the dense up|gate rows alone are 27 KB a token); a + // later chunk attends to the earlier ones through the KV cache, like a new turn. + for (int c0 = 0; c0 < total; c0 += PREFILL_CHUNK) { + const int n = std::min(PREFILL_CHUNK, total - c0); + x.resize((size_t)n * D); + for (int i = 0; i < n; i++) { + memcpy(x.data() + (size_t)i * D, embedding->w.data() + (size_t)ids[c0 + i] * D, D * sizeof(bf16)); + } + pctx->forward(x.data(), n, current_context_length, layers, MAX_L); + current_context_length += n; + last_rows = n; + } + + // the last token's hidden state -> lm_head; the decode sequences for the next + // position are built while it runs + memcpy(lm_x.data(), x.data() + (size_t)(last_rows - 1) * D, D * sizeof(bf16)); + lm_x.sync_to_device(); + lm_head_run.start(); + set_context_length(current_context_length); + _finish_lm_head(); + return logits_valid; +} + +buffer minicpm5_moe_npu::Impl::_gather_kv_row(int layer_idx, int kv, int idx) { + assert(idx >= 0 && idx < (int)MAX_L); + kv_caches[layer_idx].sync_from_device(); + const size_t col_row = desc.kv_col_row(); + buffer row(minicpm5_moe_desc::ATTN_COLS * col_row); + for (int col = 0; col < minicpm5_moe_desc::ATTN_COLS; col++) { + const bf16* src = kv_caches[layer_idx].data() + desc.kv_block_offset(col, kv, MAX_L) + (size_t)idx * col_row; + memcpy(row.data() + col * col_row, src, col_row * sizeof(bf16)); + } + return row; +} + +buffer minicpm5_moe_npu::Impl::get_k_cache(int layer_idx, int idx) { return _gather_kv_row(layer_idx, 0, idx); } +buffer minicpm5_moe_npu::Impl::get_v_cache(int layer_idx, int idx) { return _gather_kv_row(layer_idx, 1, idx); } + +/// Every layer is attention, so the state is only the KV rows, and a later token +/// only ever writes rows at or past its own position: rows below the checkpoint +/// stay as they are. A checkpoint is therefore just the context length. +int minicpm5_moe_npu::Impl::checkpoint() { + checkpoint_context_length = current_context_length; + is_checkpoint_valid = true; + return current_context_length; +} + +/// Rows past the checkpoint keep stale (finite) values; they are masked until a +/// new token overwrites them. +int minicpm5_moe_npu::Impl::restore() { + if (!is_checkpoint_valid) { + header_print_r("FLM", "No valid checkpoint to restore"); + return -1; + } + set_context_length(checkpoint_context_length); + return current_context_length; +} + +/// Every layer is full attention and nothing else survives a token, so a saved +/// state is just K/V rows: kv_rows_state.hpp does the copying, and all this has +/// to say is where the four planes are. +/// +/// The "striped" layout there means four planes of one row each per position, +/// stride DK/2. That is exactly our [K c0][K c1][V c0][V c1]: ATTN_COLS is 2 and +/// DK == DV, so kv_col_row() == DK/2. K c0 sits at 0, the other three at +/// kv_block_offset(). +kv_row_layout minicpm5_moe_npu::Impl::kv_layout() const { + kv_row_layout l; + l.DK = desc.DK; + l.DV = desc.DV; + l.striped = true; + l.k47 = desc.kv_block_offset(1, 0, MAX_L); // K column 1 + l.v03 = desc.kv_block_offset(0, 1, MAX_L); // V column 0 + l.v47 = desc.kv_block_offset(1, 1, MAX_L); // V column 1 + return l; +} + +std::unique_ptr minicpm5_moe_npu::Impl::new_state() { + return kv_rows_new_state(desc.num_hidden_layers, kv_layout()); +} + +int minicpm5_moe_npu::Impl::read_state(hybrid_engine_state& state, int kv_from) { + header_print_r("FLM", "Reading state at context length " + std::to_string(current_context_length) + + ", K/V rows from " + std::to_string(kv_from)); + return kv_rows_read(state, kv_caches, kv_layout(), current_context_length, kv_from); +} + +int minicpm5_moe_npu::Impl::write_state_kv(const hybrid_engine_state& state) { + return kv_rows_write(state, kv_caches, kv_layout(), MAX_L); +} + +/// Rows past the restored length hold whatever ran since the state was read. They are +/// not ours to keep: set_context_length() puts the zeros of a fresh context back. +int minicpm5_moe_npu::Impl::write_state(const hybrid_engine_state& state) { + const int length = kv_rows_write(state, kv_caches, kv_layout(), MAX_L); + if (length < 0) { + header_print_r("FLM", "No valid state to write"); + return -1; + } + header_print_r("FLM", "Writing state at context length " + std::to_string(length)); + // the legacy checkpoint was taken against a context this state replaces + is_checkpoint_valid = false; + set_context_length(length); + return current_context_length; +} + +/// set_context_length(0) does the wiping: it zeroes every row that has been written +/// since they were last clean, which is qwen3_6_moe_npu::clear_context's full memset +/// without the part that was never touched. +void minicpm5_moe_npu::Impl::clear_context() { + is_checkpoint_valid = false; + set_context_length(0); +} + +/// The KV block offsets scale with MAX_L, so each column's K and V block moves +/// to its new place (only the rows in use are copied). +void minicpm5_moe_npu::Impl::update_max_length(uint32_t new_max) { + new_max = _normalize_max_length(new_max); + if (new_max <= MAX_L) { + header_print("FLM", "New length is not longer than the current length, no need to update!"); + return; + } + const size_t col_row = desc.kv_col_row(); + const size_t rows = (size_t)current_context_length; + for (uint32_t l = 0; l < desc.num_hidden_layers; l++) { + buffer& old_cache = kv_caches[l]; + old_cache.sync_from_device(); + npu_app& app = _layer_app(l); + buffer new_cache = app.create_bo_buffer(desc.get_kv_cache_alloc_elems(new_max)); + new_cache.memset((bf16)0.0f); + for (int col = 0; col < minicpm5_moe_desc::ATTN_COLS; col++) { + for (int kv = 0; kv < 2; kv++) { + memcpy(new_cache.data() + desc.kv_block_offset(col, kv, new_max), + old_cache.data() + desc.kv_block_offset(col, kv, MAX_L), + rows * col_row * sizeof(bf16)); + } + } + new_cache.sync_to_device(); + kv_caches[l] = new_cache; + } + MAX_L = new_max; + sequence->set_max_length(MAX_L); + set_context_length(current_context_length); // new sequences, runs bound to the new caches +} + +minicpm5_moe_npu::Impl::~Impl() = default; + +// =============================================== +// Externals for minicpm5_moe_npu +// =============================================== +minicpm5_moe_npu::minicpm5_moe_npu(LM_Config config, npu_xclbin_manager *npu_instance, int MAX_L) { + this->_impl = new Impl(config, npu_instance, MAX_L); +} + +buffer minicpm5_moe_npu::forward(int ids) { + return this->_impl->forward(ids); +} + +buffer minicpm5_moe_npu::prefill(std::vector& ids, void* payload) { + return this->_impl->prefill(ids, payload); +} + +void minicpm5_moe_npu::set_context_length(int L) { + this->_impl->set_context_length(L); +} + +void minicpm5_moe_npu::load_weights(Q4NX& q4nx) { + this->_impl->load_weights(q4nx); +} + +void minicpm5_moe_npu::update_max_length(uint32_t MAX_L) { + this->_impl->update_max_length(MAX_L); +} + +void minicpm5_moe_npu::clear_context() { + this->_impl->clear_context(); +} + +buffer minicpm5_moe_npu::get_k_cache(int layer_idx, int idx) { + return this->_impl->get_k_cache(layer_idx, idx); +} + +buffer minicpm5_moe_npu::get_v_cache(int layer_idx, int idx) { + return this->_impl->get_v_cache(layer_idx, idx); +} + +int minicpm5_moe_npu::get_current_context_length() { + return this->_impl->get_current_context_length(); +} + +int minicpm5_moe_npu::checkpoint() { + return this->_impl->checkpoint(); +} + +int minicpm5_moe_npu::restore() { + return this->_impl->restore(); +} + +std::unique_ptr minicpm5_moe_npu::new_state() { + return this->_impl->new_state(); +} + +int minicpm5_moe_npu::read_state(hybrid_engine_state& state, int kv_from) { + return this->_impl->read_state(state, kv_from); +} + +int minicpm5_moe_npu::write_state(const hybrid_engine_state& state) { + return this->_impl->write_state(state); +} + +int minicpm5_moe_npu::write_state_kv(const hybrid_engine_state& state) { + return this->_impl->write_state_kv(state); +} + +minicpm5_moe_npu::~minicpm5_moe_npu() { + delete this->_impl; +} + +extern "C" const flm_state_api* minicpm5_moe_npu_state_api(void* engine) { + return hybrid_state_api(engine); +} diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu_detail.hpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu_detail.hpp new file mode 100644 index 000000000..afff0f2a8 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu_detail.hpp @@ -0,0 +1,108 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#pragma once +#include "models/minicpm5_moe/minicpm5_moe_npu.hpp" +#include "minicpm5_moe_model_def.hpp" +#include "minicpm5_moe_npu_sequence.hpp" +#include "minicpm5_moe_prefill.hpp" +#include "utils/kv_rows_state.hpp" + +/// @brief everything the engine owns +/// @note One token = two runs on two hw contexts, in order: +/// layer_runlist 28 x [router RTP, layer] (moe_layer.xclbin) +/// lm_head_run final norm + logits (lm_head.xclbin) +/// The layer runs all read and write the same x buffer on the device, so +/// nothing goes back to the host between them. +struct minicpm5_moe_npu::Impl{ + LM_Config config; + npu_xclbin_manager *npu; + minicpm5_moe_desc desc; + std::unique_ptr sequence; + std::unique_ptr pctx; // the batched prefill + std::unique_ptr overlay; // its NPU stages (prefill_overlay.xclbin) + uint32_t MAX_L; + // tokens per batched prefill chunk: bounds the scratch (~100 KB a token, ~400 MB a chunk) + static constexpr int PREFILL_CHUNK = 4096; + + npu_app_manager* layer_app_manager; + npu_app_manager* lm_head_app_manager; + + // Both on moe_layer.xclbin. The sequences depend on L and are rebuilt per token; + // layer 0 has its own because its buffers are laid out for 16 experts, not 160. + npu_app dense_layer; // layer 0 + npu_app moe_layer; // layers 1.., one sequence for all + std::vector router_rtp; // per layer: layer number + expert bias, built once + npu_app lm_head; + + // per layer + std::vector> proj_weights; + std::vector> rms_weights; + std::vector> rope_rms_weights; // [cos | sin] + std::vector> kv_caches; // [K col 0][K col 1][V col 0][V col 1] + std::vector> router_bias; + + // x: [0, D) layer input, then layer output; [D, D + DQ) is the attention tap + // of a debug (ATTN_TAP) build of the layer overlay + static constexpr size_t X_ELEMS = 8192; + buffer x; + buffer lm_x; // [x | final norm weight] + buffer lm_head_weights; + buffer logits; + buffer logits_valid; // first vocab_size entries of logits + std::unique_ptr embedding; + + flm_rt::runlist layer_runlist; + flm_rt::run lm_head_run; + + int current_context_length; + int checkpoint_context_length; + bool is_checkpoint_valid; + /// @brief highest context length reached since the rows were last known to be zero + /// @note Rows below it hold some conversation's K/V. write_state() zeroes + /// [restored length, dirty_rows) so a restored context looks like a fresh + /// one; measured, not assumed (check_engine.cpp check 6). + size_t dirty_rows = 0; + + Impl(LM_Config config, npu_xclbin_manager *npu_instance, int MAX_L); + ~Impl(); + + buffer forward(int ids); + buffer prefill(std::vector& ids, void* payload = nullptr); + buffer _prefill_batched(std::vector& ids); // default + buffer _prefill_with_mv(std::vector& ids); // PREFILL_WITH_MV: decode overlays, token by token + void set_context_length(int L); + void load_weights(Q4NX& q4nx); + void update_max_length(uint32_t MAX_L); + void clear_context(); + buffer get_k_cache(int layer_idx, int idx); + buffer get_v_cache(int layer_idx, int idx); + int get_current_context_length() { return current_context_length; } + int checkpoint(); + int restore(); + + /// @brief where this layer's four K/V planes sit, for kv_rows_state.hpp + /// @note Rebuilt on every call: the plane offsets scale with MAX_L, which + /// update_max_length() can grow under a state that was read earlier. + kv_row_layout kv_layout() const; + std::unique_ptr new_state(); + int read_state(hybrid_engine_state& state, int kv_from); + int write_state(const hybrid_engine_state& state); + int write_state_kv(const hybrid_engine_state& state); + + /// @brief round a requested KV length up to a power of two in [4096, MAX_CONTEXT] + static uint32_t _normalize_max_length(uint32_t requested); + /// @brief the app layer `l` runs on (layer 0's layout differs, see dense_layer) + npu_app& _layer_app(uint32_t l) { + return desc.layer_kind(l) == minicpm5_moe_layer_kind::dense ? dense_layer : moe_layer; + } + /// @brief embedding of `id` into x, then all layers; x holds the last hidden state + void _run_layers(int id); + /// @brief x -> final norm + logits + void _start_lm_head(); + void _finish_lm_head(); + /// @brief cos / sin of position `pos` into every layer's rope buffer + void _set_rope(int pos); + /// @brief K (kv = 0) or V (kv = 1) row `idx` of a layer, all KV heads in head order + buffer _gather_kv_row(int layer_idx, int kv, int idx); +}; diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu_sequence.cpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu_sequence.cpp new file mode 100644 index 000000000..a2c6185c3 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu_sequence.cpp @@ -0,0 +1,282 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_npu_sequence.cpp +/// \brief instruction sequences for the MiniCPM5-15B-A2.5B decode overlays +/// \note See minicpm5_moe_npu_sequence.hpp. The DMA order inside the layer sequence is +/// the one the kernels were checked with; do not reorder it casually (the +/// comments say what broke when it was). +#include "minicpm5_moe_npu_sequence.hpp" + +minicpm5_moe_npu_sequence::minicpm5_moe_npu_sequence(minicpm5_moe_desc& desc, uint32_t MAX_L) + : desc(desc), MAX_L(MAX_L) {} + +// ============================================================================= +// one decoder layer; layer 0 differs only in its buffers (see the model def) +// ============================================================================= +void minicpm5_moe_npu_sequence::gen_layer_seq(npu_sequence* seq, int L, const minicpm5_moe_layer_def& W) { + assert(L > 0 && L <= (int)MAX_L); + const size_t kv_col_row = desc.kv_col_row(); + seq->clear_cmds(); + + for (int i = 0; i < attn_cus; i++) { + seq->rtp_write(get_tile(attn_qk_rc[i][0], attn_qk_rc[i][1]), l_attn_qk_address, L); + seq->rtp_write(get_tile(attn_kv_rc[i][0], attn_kv_rc[i][1]), l_attn_kv_address, L); + } + for (int i = 0; i < 16; i++) { + npu_tiles tile = get_tile(proj_rc[i][0], proj_rc[i][1]); + seq->rtp_write(tile, proj_rtp_address, 1); + seq->rtp_write(tile, CT_lock_address_base + 16 * proj_rtp_lock_id, 1); // set lock to 1 + } + // (the router's layer number and expert bias: gen_router_rtp_seq, its own run) + + _send_hidden_states(seq); + // input_layernorm | post_attention_layernorm (the router weight behind them goes on IT5) + seq->npu_dma_memcpy_nd(sizeof(bf16), w_rms_arg_idx, MM2S, xyr_tile, bd_1, it_channel_1, + {0, 0, 0, 0}, {1, 1, 1, desc.D * 2}, {0, 0, 0, 1}, + 0, 0, true, aggressive_cache); + seq->npu_dma_wait(xyr_tile, MM2S, it_channel_1); + _send_rope_weights(seq); + + // Router weight first, so IT5 sends it while attention runs and the router + + // helper start on it as soon as x is there. + _send_router_weights(seq, W); + + // receive y + seq->npu_dma_memcpy_nd(sizeof(bf16), xy_arg_idx, S2MM, xyr_tile, bd_10, it_channel_1, + {0, 0, 0, 0}, {1, 1, 1, desc.D}, {0, 0, 0, 1}, + -1, 0, true); + + // RoPE sends the new token's K (all KV heads) then V (all KV heads) through + // IT3. Write each column's heads into that column's K / V block, row L - 1: + // BDs 0..3 = K col 0, K col 1, V col 0, V col 1, in stream order. + const uint32_t row_offset = (uint32_t)((L - 1) * kv_col_row); + for (int kv = 0; kv < 2; kv++) { + for (int col = 0; col < attn_cols; col++) { + const uint32_t block_offset = (uint32_t)desc.kv_block_offset(col, kv, MAX_L); + seq->npu_dma_memcpy_nd(sizeof(bf16), kv_cache_arg_idx, S2MM, attn_shims[0], npu_bd_id(kv * attn_cols + col), it_channel_0, + {0, 0, 0, block_offset + row_offset}, {1, 1, 1, (uint32_t)kv_col_row}, {0, 0, 0, 1}, + -1, 0, true); + } + } + // k, v, q, gate: one matrix (RoPE takes K, V, Q; the output gate tile the gate) + _move_weights_q4k(seq, desc.DK + desc.DV + 2 * desc.DQ, desc.D, W.attn_k.offset); + + // K reads start once both K writes of the new row are done, V reads once both V writes are + { + const int L_padded = (L + minicpm5_moe_desc::KV_CHUNK - 1) / minicpm5_moe_desc::KV_CHUNK * minicpm5_moe_desc::KV_CHUNK; + assert(L_padded <= (int)MAX_L); + const uint32_t data2move = (uint32_t)(L_padded * kv_col_row); + const npu_bd_id read_bd[2][attn_cols] = {{bd_4, bd_0}, {bd_5, bd_1}}; // IT3 uses BDs 0..3 to write + for (int kv = 0; kv < 2; kv++) { + for (int col = 0; col < attn_cols; col++) { + seq->npu_dma_wait(attn_shims[0], S2MM, it_channel_0); + } + for (int col = 0; col < attn_cols; col++) { + seq->npu_dma_memcpy_nd(sizeof(bf16), kv_cache_arg_idx, MM2S, attn_shims[col], read_bd[kv][col], + kv == 0 ? it_channel_0 : it_channel_1, + {0, 0, 0, (uint32_t)desc.kv_block_offset(col, kv, MAX_L)}, {1, 1, 1, data2move}, {0, 0, 0, 1}, + -1, 0, false, aggressive_cache); + } + } + } + _move_weights_q4k(seq, desc.D, desc.DQ, W.attn_output.offset); + + // Routed expert weight BDs on shim 0, 1, 6, 7: one linear BD per channel, + // 4 / 5 for round 0 and 12 / 13 for round 1. Written here but not started; + // the router CT patches in the chosen expert's address and starts them with + // control packets. + for (int i = 0; i < 4; i++) { + _setup_expert_q4k(seq, i, 4, W.ffn_up_exps.offset); + _setup_expert_q4k(seq, i, 12, W.ffn_up_exps.offset); + } + + // shared expert up-gate, then down (down's last round pushed but not yet waited for) + _move_weights_q4k(seq, 2 * desc.expert_width, desc.D, W.ffn_up_shexp.offset); + _move_weights_q4k(seq, desc.D, desc.expert_width, W.ffn_down_shexp.offset, false); + + // Tell the router the expert BDs are ready. Only now: the router pushes the + // routed-expert weight tasks onto the same shim queues (0, 1, 6, 7) as the + // shared-expert ones above, and a router that got here first queued them in + // front of the last shared-down weights (wrong output from the 2nd call on). + npu_tiles router_CT = get_tile(router_rc[0], router_rc[1]); + seq->npu_maskwrite(router_CT, 0x32038, 0x1, 0x1); + seq->rtp_write(router_CT, CT_lock_address_base + 16 * router_bd_ready_lock_id, 1); // set lock to 1 + _wait_proj_weights(seq); + + seq->npu_dma_wait(xyr_tile, S2MM, it_channel_1); // y + seq->cmds2seq(); +} + +void minicpm5_moe_npu_sequence::gen_router_rtp_seq(npu_sequence* seq, int layer_idx, const std::vector& bias) { + assert(bias.size() == desc.num_experts); + npu_tiles router_CT = get_tile(router_rc[0], router_rc[1]); + seq->clear_cmds(); + // which layer this is: the router keeps one weight base address per layer + seq->rtp_write(router_CT, router_layer_address, (uint32_t)layer_idx); + // the expert bias, one write per expert (fp32 bit pattern). The router reads + // it only after its logits, i.e. well inside the layer run that follows. + for (uint32_t e = 0; e < desc.num_experts; e++) { + uint32_t bits; + memcpy(&bits, &bias[e], sizeof(bits)); + seq->rtp_write(router_CT, router_bias_address + 4 * e, bits); + } + seq->cmds2seq(); +} + +// ============================================================================= +// shared helpers of the two layer overlays +// ============================================================================= +void minicpm5_moe_npu_sequence::_send_hidden_states(npu_sequence* seq) { + // packet 0: to the rms tile + seq->npu_dma_memcpy_nd(sizeof(bf16), xy_arg_idx, MM2S, xyr_tile, bd_0, it_channel_0, + {0, 0, 0, 0}, {1, 1, 1, desc.D}, {0, 0, 0, 1}, + 0, 0, false, aggressive_cache); +} + +void minicpm5_moe_npu_sequence::_send_rope_weights(npu_sequence* seq) { + // cos | sin (packet 1: to the RoPE tile) + seq->npu_dma_memcpy_nd(sizeof(bf16), w_rope_rms_arg_idx, MM2S, xyr_tile, bd_2, it_channel_0, + {0, 0, 0, 0}, {1, 1, 1, (uint32_t)desc.get_rope_rms_elems()}, {0, 0, 0, 1}, + 1, 0, true, no_cache); + seq->npu_dma_wait(xyr_tile, MM2S, it_channel_0); +} + +/// The host stored the router weight in read order (32-expert x 256-input blocks, +/// see load_layer), so each part is one straight read. MT5 holds experts 0..127 +/// (channel 0, packets to MT5); experts 128.. do not fit and go straight to the +/// router helper (channel 1, circuit flow). +void minicpm5_moe_npu_sequence::_send_router_weights(npu_sequence* seq, const minicpm5_moe_layer_def& W) { + constexpr uint32_t mt5_experts = minicpm5_moe_desc::ROUTER_MT_EXPERTS; + const uint32_t base = (uint32_t)(W.ffn_gate_inp.offset / sizeof(bf16)); + assert(desc.num_experts > mt5_experts); + seq->npu_dma_memcpy_nd(sizeof(bf16), w_rms_arg_idx, MM2S, IT5, bd_12, it_channel_0, + {0, 0, 0, base}, {1, 1, 1, mt5_experts * desc.D}, {0, 0, 0, 1}, + 10, 0, false, aggressive_cache); + seq->npu_dma_memcpy_nd(sizeof(bf16), w_rms_arg_idx, MM2S, IT5, bd_13, it_channel_1, + {0, 0, 0, base + mt5_experts * desc.D}, {1, 1, 1, (desc.num_experts - mt5_experts) * desc.D}, {0, 0, 0, 1}, + -1, 0, false, aggressive_cache); +} + +/// One matrix through the 16 proj cores, 32 rows each per round: channel 0 of a +/// column's shim feeds its cores 0, 1 and channel 1 cores 2, 3 (reorder_cpy put +/// those blocks next to each other). Two BD sets ping-pong, so round r + 1 is +/// queued before round r is waited for. +/// \param wait_last_round false: the last round's tasks are pushed but not waited for +void minicpm5_moe_npu_sequence::_move_weights_q4k(npu_sequence* seq, size_t Dout, size_t Din, size_t w_offset, bool wait_last_round) { + const uint32_t m = QXNX_ROW_BLOCK_SIZE; + const uint32_t a_block_size = minicpm5_moe_desc::Q4K_BLOCK_BYTES / sizeof(bf16); // in bf16 elements + const uint32_t blocks_per_row = Din / QXNX_COL_BLOCK_SIZE; + const uint32_t cores = 16; + const uint32_t w_base = (uint32_t)(w_offset / sizeof(bf16)); + assert(Dout % (m * cores) == 0); + for (size_t round = 0; round < Dout / m / cores; round++) { + const uint32_t bd_offset = (round % 2) * 8; + for (uint32_t col = 0; col < 4; col++) { + const uint32_t first_row = round * cores + col * 4; // this column's first block row + seq->npu_dma_memcpy_nd(sizeof(bf16), w_proj_arg_idx, MM2S, mvm_tiles[col], npu_bd_id(bd_1 + bd_offset), it_channel_0, + {0, 0, 0, first_row * a_block_size * blocks_per_row + w_base}, {1, 1, 1, 2 * blocks_per_row * a_block_size}, {0, 0, 0, 1}, + -1, 0, true, aggressive_cache); + seq->npu_dma_memcpy_nd(sizeof(bf16), w_proj_arg_idx, MM2S, mvm_tiles[col], npu_bd_id(bd_2 + bd_offset), it_channel_1, + {0, 0, 0, (first_row + 2) * a_block_size * blocks_per_row + w_base}, {1, 1, 1, 2 * blocks_per_row * a_block_size}, {0, 0, 0, 1}, + -1, 0, true, aggressive_cache); + } + if (round > 0) { + _wait_proj_weights(seq); + } + } + if (wait_last_round) { + _wait_proj_weights(seq); + } +} + +/// Wait for one weight task on both channels of each proj shim (0, 1, 6, 7). +void minicpm5_moe_npu_sequence::_wait_proj_weights(npu_sequence* seq) { + for (uint32_t col = 0; col < 4; col++) { + seq->npu_dma_wait(mvm_tiles[col], MM2S, it_channel_0); + seq->npu_dma_wait(mvm_tiles[col], MM2S, it_channel_1); + } +} + +/// One routed expert's weight BDs on proj shim `col` (0-3): channel 0 gets BD +/// bd_id, channel 1 BD bd_id + 1, each one linear read of half an expert (see +/// minicpm5_moe_desc::load_layer). Points at expert 0; the router patches in the +/// chosen expert's address and pushes the BDs onto the queues. +void minicpm5_moe_npu_sequence::_setup_expert_q4k(npu_sequence* seq, int col, int bd_id, size_t const_w_byte_offset) { + const size_t gate_up_bytes = 2 * (size_t)(desc.expert_width / QXNX_ROW_BLOCK_SIZE) * (desc.D / QXNX_COL_BLOCK_SIZE) * minicpm5_moe_desc::Q4K_BLOCK_BYTES; + const size_t down_bytes = (size_t)(desc.D / QXNX_ROW_BLOCK_SIZE) * (desc.expert_width / QXNX_COL_BLOCK_SIZE) * minicpm5_moe_desc::Q4K_BLOCK_BYTES; + const uint32_t channel_bytes = (uint32_t)((gate_up_bytes + down_bytes) / 2); + constexpr uint32_t SHIM_6_CONTROL_RES_PKT = 30; // the router's control response packet id (kernels) + for (int ch = 0; ch < 2; ch++) { + seq->npu_dma_memcpy_nd(sizeof(uint8_t), w_proj_arg_idx, MM2S, mvm_tiles[col], npu_bd_id(bd_id + ch), + ch == 0 ? it_channel_0 : it_channel_1, + {0, 0, 0, (uint32_t)(const_w_byte_offset + (size_t)ch * channel_bytes)}, {1, 1, 1, channel_bytes}, {0, 0, 0, 1}, + -1, 0, false, aggressive_cache, SHIM_6_CONTROL_RES_PKT, false); + } +} + +// ============================================================================= +// LM head (lm_head.xclbin): final RMS norm + Q8_0 logits over 8 columns +// ============================================================================= +void minicpm5_moe_npu_sequence::gen_lm_head_seq(npu_sequence* seq) { + static constexpr npu_tiles ITs[] = {IT0, IT1, IT2, IT3, IT4, IT5, IT6, IT7}; + static constexpr int COLS = 8; + static constexpr int M_PER_COL = 32 * 4; // 4 cores x 32 rows + static constexpr int M_PER_ROUND = M_PER_COL * COLS; + // the two flows sharing IT0's MM2S 0 (X_PKT_ID / W_PKT_ID in iron/q4k_mm.py); + // every other shim MM2S port is circuit-switched + static constexpr int X_PKT_ID = 0; + static constexpr int W_PKT_ID = 1; + static constexpr int NO_PKT = -1; + // rounds of shim BD ping-pong; also how far the y waits lag the y issues + static constexpr int LOOKAHEAD = 3; + const uint32_t vocab = desc.vocab_size_padded; + const uint32_t D = desc.D; + assert(vocab % M_PER_ROUND == 0); + const int rounds = vocab / M_PER_ROUND; + // Q8_0: 8.5 bits per weight; in bf16 elements + const size_t W_PER_COL = size_t(M_PER_COL * D * 8.5 / 8) / sizeof(bf16); + const size_t W_PER_ROUND = W_PER_COL * COLS; + // each column's weights are split over two shim MM2S channels, one per pair + // of cores; load_lm_head laid the two halves out back to back + const size_t W_PER_STREAM = W_PER_COL / 2; + + seq->clear_cmds(); + // x | final norm weight + seq->npu_dma_memcpy_nd(sizeof(bf16), lm_x_arg_idx, MM2S, ITs[0], bd_0, it_channel_0, + {0, 0, 0, 0}, {1, 1, 1, D * 2}, {0, 0, 0, 1}, + X_PKT_ID, 0, false, aggressive_cache); + + for (int r = 0; r < rounds; r++) { + const int bd_offset = (r % (LOOKAHEAD + 1)) * 3; + const npu_bd_id bd_y = npu_bd_id(bd_1 + bd_offset); + const npu_bd_id bd_wa = npu_bd_id(bd_2 + bd_offset); + const npu_bd_id bd_wb = npu_bd_id(bd_3 + bd_offset); + for (int col = 0; col < COLS; col++) { + const size_t w_col_offset = r * W_PER_ROUND + col * W_PER_COL; + const uint32_t y_offset = r * M_PER_ROUND + col * M_PER_COL; + seq->npu_dma_memcpy_nd(sizeof(bf16), lm_y_arg_idx, S2MM, ITs[col], bd_y, it_channel_0, + {0, 0, 0, y_offset}, {1, 1, 1, (uint32_t)M_PER_COL}, {0, 0, 0, 1}, + -1, 0, true, aggressive_cache); + // group a (cores 0/1) on channel 1, group b (cores 2/3) on channel 0; + // only IT0's channel 0 is shared with the x broadcast and needs a packet id + seq->npu_dma_memcpy_nd(sizeof(bf16), lm_w_arg_idx, MM2S, ITs[col], bd_wa, it_channel_1, + {0, 0, 0, (uint32_t)w_col_offset}, {1, 1, 1, (uint32_t)W_PER_STREAM}, {0, 0, 0, 1}, + NO_PKT, 0, false, aggressive_cache); + seq->npu_dma_memcpy_nd(sizeof(bf16), lm_w_arg_idx, MM2S, ITs[col], bd_wb, it_channel_0, + {0, 0, 0, (uint32_t)(w_col_offset + W_PER_STREAM)}, {1, 1, 1, (uint32_t)W_PER_STREAM}, {0, 0, 0, 1}, + col == 0 ? W_PKT_ID : NO_PKT, 0, false, aggressive_cache); + // four BD sets in flight: a round waits for the y of three rounds back, + // which keeps three rounds of weights queued ahead of the sequencer + if (r > LOOKAHEAD - 1) { + seq->npu_dma_wait(ITs[col], S2MM, it_channel_0); + } + } + } + for (int col = 0; col < COLS; col++) { + for (int i = 0; i < LOOKAHEAD; i++) { + seq->npu_dma_wait(ITs[col], S2MM, it_channel_0); + } + } + seq->cmds2seq(); +} diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu_sequence.hpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu_sequence.hpp new file mode 100644 index 000000000..ec93eb800 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_npu_sequence.hpp @@ -0,0 +1,94 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_npu_sequence.hpp +/// \brief instruction sequences for the MiniCPM5-15B-A2.5B decode overlays +/// \author FastFlowLM Team +/// \date 2026-12-03 +/// \note Two bitstreams: +/// moe_layer.xclbin gen_layer_seq (every layer; one sequence per +/// layer kind, since the two kinds' +/// buffers differ in size) +/// gen_router_rtp_seq (one per layer, built once) +/// lm_head.xclbin gen_lm_head_seq +/// The layer sequences depend on the context length and are rebuilt once per +/// token; the router one only carries the layer's number and expert bias, +/// which never change, so it runs as its own small run in front of every +/// layer (the router reads both long after the layer run has started). +/// Ported from FLM_Xclbin/MiniCPM5/moe_decoding/host/decoding_layer.cpp +/// and lm_head_npu_bin/host/host.cpp. +#pragma once +#include +#include +#include "npu_utils/npu_utils.hpp" +#include "minicpm5_moe_model_def.hpp" + +class minicpm5_moe_npu_sequence { +public: + // kernel argument order of the layer overlay: (x, proj, rms, rope_rms, kv_cache) + static constexpr int xy_arg_idx = 0; + static constexpr int w_proj_arg_idx = 1; + static constexpr int w_rms_arg_idx = 2; + static constexpr int w_rope_rms_arg_idx = 3; + static constexpr int kv_cache_arg_idx = 4; + // lm_head overlay: (y, w, x) + static constexpr int lm_y_arg_idx = 0; + static constexpr int lm_w_arg_idx = 1; + static constexpr int lm_x_arg_idx = 2; + + minicpm5_moe_npu_sequence(minicpm5_moe_desc& desc, uint32_t MAX_L); + + /// \brief the KV block offsets depend on MAX_L; call before regenerating + void set_max_length(uint32_t MAX_L) { this->MAX_L = MAX_L; } + + /// \param L tokens in the cache after this call (the new token is row L - 1) + /// \param W the layer kind's buffer layout (desc.dense or desc.moe) + void gen_layer_seq(npu_sequence* seq, int L, const minicpm5_moe_layer_def& W); + /// \brief the router's layer number and fp32 expert bias, for one layer + void gen_router_rtp_seq(npu_sequence* seq, int layer_idx, const std::vector& bias); + void gen_lm_head_seq(npu_sequence* seq); + +private: + minicpm5_moe_desc& desc; + uint32_t MAX_L; + + // ---- floorplan ---- + static constexpr npu_tiles xyr_tile = IT2; // x / y / rms / rope + static constexpr npu_tiles mvm_tiles[4] = {IT0, IT1, IT6, IT7}; // proj weight shims + static constexpr int attn_cus = 4; // CU i holds kernel KV head i + static constexpr int attn_cols = minicpm5_moe_desc::ATTN_COLS; + static constexpr int attn_qk_rc[attn_cus][2] = {{2, 3}, {4, 3}, {2, 4}, {4, 4}}; + static constexpr int attn_kv_rc[attn_cus][2] = {{3, 3}, {5, 3}, {3, 4}, {5, 4}}; + static constexpr npu_tiles attn_shims[attn_cols] = {IT3, IT4}; + // proj cores wait on lock 6 for their RTP every call + static constexpr int proj_rc[16][2] = {{2, 0}, {3, 0}, {4, 0}, {5, 0}, + {2, 1}, {3, 1}, {4, 1}, {5, 1}, + {2, 6}, {3, 6}, {4, 6}, {5, 6}, + {2, 7}, {3, 7}, {4, 7}, {5, 7}}; + static constexpr int router_rc[2] = {4, 5}; // router CT + static constexpr size_t CT_lock_address_base = 0x000001F000; + static constexpr int proj_rtp_lock_id = 6; + static constexpr int router_bd_ready_lock_id = 10; // expert BDs written + static constexpr uint32_t proj_rtp_address = 17408; // proj cores' RTP word + + // ---- RTP addresses of moe_layer.xclbin ---- + // The xclbin build writes these to its xclbins/rtp_addresses.txt; they are + // copied here as constants, the way every other engine keeps them. Every core + // of a kind holds its RTP at the same offset inside its own data memory, so + // one value covers all of them -- the file lists it once per core, all identical. + // + // RE-CHECK THESE AFTER REBUILDING MiniCPM5/moe_decoding. If a rebuild moves an + // RTP, the host writes to a stale address and the result is wrong output or a + // hang, not an error. Diff the new rtp_addresses.txt against the values below. + static constexpr uint32_t l_attn_qk_address = 5120; // RTP_L_attn_qk_core_* + static constexpr uint32_t l_attn_kv_address = 34816; // RTP_L_attn_kv_core_* + static constexpr uint32_t router_bias_address = 53248; // RTP_router_expert_bias + static constexpr uint32_t router_layer_address = 53888; // RTP_router_layer + + void _send_hidden_states(npu_sequence* seq); + void _send_rope_weights(npu_sequence* seq); + void _send_router_weights(npu_sequence* seq, const minicpm5_moe_layer_def& W); + void _move_weights_q4k(npu_sequence* seq, size_t Dout, size_t Din, size_t w_offset, bool wait_last_round = true); + void _wait_proj_weights(npu_sequence* seq); + void _setup_expert_q4k(npu_sequence* seq, int col, int bd_id, size_t const_w_byte_offset); +}; diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_overlay_configs.hpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_overlay_configs.hpp new file mode 100644 index 000000000..1a16eba37 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_overlay_configs.hpp @@ -0,0 +1,3149 @@ +// Generated by tools/extract_txn2.py from aiecc --aie-generate-txn. Do not edit. +#pragma once +#include +#include + +struct reg_write { uint32_t col, row, offset, value; }; +struct mask_write { uint32_t col, row, offset, mask, value; }; +// shared: another op uses this BD register too -> rewrite it at every switch; +// otherwise it can stay loaded (write it once after the xclbin is loaded) +struct reg_block { uint32_t col, row, offset; bool shared; std::vector words; }; +struct chain_start { uint32_t col, row, ctrl_offset, queue_offset, queue_value, ctrl_value; }; +struct op_config { + std::vector sw; + std::vector mux; + std::vector bds; + std::vector locks; + std::vector starts; +}; + + +// all DMA channel control registers used by any op: (col, row, offset) +inline const std::vector all_channels = { + {0, 1, 0xA0600, 0}, + {0, 1, 0xA0608, 0}, + {0, 1, 0xA0610, 0}, + {0, 1, 0xA0618, 0}, + {0, 1, 0xA0620, 0}, + {0, 1, 0xA0628, 0}, + {0, 1, 0xA0630, 0}, + {0, 1, 0xA0638, 0}, + {0, 1, 0xA0640, 0}, + {0, 1, 0xA0648, 0}, + {0, 1, 0xA0658, 0}, + {0, 2, 0x1DE00, 0}, + {0, 2, 0x1DE08, 0}, + {0, 2, 0x1DE10, 0}, + {0, 2, 0x1DE18, 0}, + {0, 3, 0x1DE00, 0}, + {0, 3, 0x1DE08, 0}, + {0, 3, 0x1DE10, 0}, + {0, 3, 0x1DE18, 0}, + {0, 4, 0x1DE00, 0}, + {0, 4, 0x1DE08, 0}, + {0, 4, 0x1DE10, 0}, + {0, 4, 0x1DE18, 0}, + {0, 5, 0x1DE00, 0}, + {0, 5, 0x1DE08, 0}, + {0, 5, 0x1DE10, 0}, + {0, 5, 0x1DE18, 0}, + {1, 1, 0xA0600, 0}, + {1, 1, 0xA0608, 0}, + {1, 1, 0xA0610, 0}, + {1, 1, 0xA0618, 0}, + {1, 1, 0xA0620, 0}, + {1, 1, 0xA0628, 0}, + {1, 1, 0xA0630, 0}, + {1, 1, 0xA0638, 0}, + {1, 1, 0xA0640, 0}, + {1, 1, 0xA0658, 0}, + {1, 2, 0x1DE00, 0}, + {1, 2, 0x1DE08, 0}, + {1, 2, 0x1DE10, 0}, + {1, 2, 0x1DE18, 0}, + {1, 3, 0x1DE00, 0}, + {1, 3, 0x1DE08, 0}, + {1, 3, 0x1DE10, 0}, + {1, 3, 0x1DE18, 0}, + {1, 4, 0x1DE00, 0}, + {1, 4, 0x1DE08, 0}, + {1, 4, 0x1DE10, 0}, + {1, 4, 0x1DE18, 0}, + {1, 5, 0x1DE00, 0}, + {1, 5, 0x1DE08, 0}, + {1, 5, 0x1DE10, 0}, + {1, 5, 0x1DE18, 0}, + {2, 1, 0xA0600, 0}, + {2, 1, 0xA0608, 0}, + {2, 1, 0xA0610, 0}, + {2, 1, 0xA0618, 0}, + {2, 1, 0xA0620, 0}, + {2, 1, 0xA0628, 0}, + {2, 1, 0xA0630, 0}, + {2, 1, 0xA0638, 0}, + {2, 1, 0xA0640, 0}, + {2, 1, 0xA0648, 0}, + {2, 1, 0xA0658, 0}, + {2, 2, 0x1DE00, 0}, + {2, 2, 0x1DE08, 0}, + {2, 2, 0x1DE10, 0}, + {2, 2, 0x1DE18, 0}, + {2, 3, 0x1DE00, 0}, + {2, 3, 0x1DE08, 0}, + {2, 3, 0x1DE10, 0}, + {2, 3, 0x1DE18, 0}, + {2, 4, 0x1DE00, 0}, + {2, 4, 0x1DE08, 0}, + {2, 4, 0x1DE10, 0}, + {2, 4, 0x1DE18, 0}, + {2, 5, 0x1DE00, 0}, + {2, 5, 0x1DE08, 0}, + {2, 5, 0x1DE10, 0}, + {2, 5, 0x1DE18, 0}, + {3, 1, 0xA0600, 0}, + {3, 1, 0xA0608, 0}, + {3, 1, 0xA0610, 0}, + {3, 1, 0xA0618, 0}, + {3, 1, 0xA0620, 0}, + {3, 1, 0xA0628, 0}, + {3, 1, 0xA0630, 0}, + {3, 1, 0xA0638, 0}, + {3, 1, 0xA0640, 0}, + {3, 1, 0xA0658, 0}, + {3, 2, 0x1DE00, 0}, + {3, 2, 0x1DE08, 0}, + {3, 2, 0x1DE10, 0}, + {3, 2, 0x1DE18, 0}, + {3, 3, 0x1DE00, 0}, + {3, 3, 0x1DE08, 0}, + {3, 3, 0x1DE10, 0}, + {3, 3, 0x1DE18, 0}, + {3, 4, 0x1DE00, 0}, + {3, 4, 0x1DE08, 0}, + {3, 4, 0x1DE10, 0}, + {3, 4, 0x1DE18, 0}, + {3, 5, 0x1DE00, 0}, + {3, 5, 0x1DE08, 0}, + {3, 5, 0x1DE10, 0}, + {3, 5, 0x1DE18, 0}, + {4, 1, 0xA0600, 0}, + {4, 1, 0xA0608, 0}, + {4, 1, 0xA0610, 0}, + {4, 1, 0xA0618, 0}, + {4, 1, 0xA0620, 0}, + {4, 1, 0xA0628, 0}, + {4, 1, 0xA0630, 0}, + {4, 1, 0xA0638, 0}, + {4, 1, 0xA0640, 0}, + {4, 1, 0xA0648, 0}, + {4, 1, 0xA0658, 0}, + {4, 2, 0x1DE00, 0}, + {4, 2, 0x1DE08, 0}, + {4, 2, 0x1DE10, 0}, + {4, 2, 0x1DE18, 0}, + {4, 3, 0x1DE00, 0}, + {4, 3, 0x1DE08, 0}, + {4, 3, 0x1DE10, 0}, + {4, 3, 0x1DE18, 0}, + {4, 4, 0x1DE00, 0}, + {4, 4, 0x1DE08, 0}, + {4, 4, 0x1DE10, 0}, + {4, 4, 0x1DE18, 0}, + {4, 5, 0x1DE00, 0}, + {4, 5, 0x1DE08, 0}, + {4, 5, 0x1DE10, 0}, + {4, 5, 0x1DE18, 0}, + {5, 1, 0xA0600, 0}, + {5, 1, 0xA0608, 0}, + {5, 1, 0xA0610, 0}, + {5, 1, 0xA0618, 0}, + {5, 1, 0xA0620, 0}, + {5, 1, 0xA0628, 0}, + {5, 1, 0xA0630, 0}, + {5, 1, 0xA0638, 0}, + {5, 1, 0xA0640, 0}, + {5, 1, 0xA0658, 0}, + {5, 2, 0x1DE00, 0}, + {5, 2, 0x1DE08, 0}, + {5, 2, 0x1DE10, 0}, + {5, 2, 0x1DE18, 0}, + {5, 3, 0x1DE00, 0}, + {5, 3, 0x1DE08, 0}, + {5, 3, 0x1DE10, 0}, + {5, 3, 0x1DE18, 0}, + {5, 4, 0x1DE00, 0}, + {5, 4, 0x1DE08, 0}, + {5, 4, 0x1DE10, 0}, + {5, 4, 0x1DE18, 0}, + {5, 5, 0x1DE00, 0}, + {5, 5, 0x1DE08, 0}, + {5, 5, 0x1DE10, 0}, + {5, 5, 0x1DE18, 0}, + {6, 1, 0xA0600, 0}, + {6, 1, 0xA0608, 0}, + {6, 1, 0xA0610, 0}, + {6, 1, 0xA0618, 0}, + {6, 1, 0xA0620, 0}, + {6, 1, 0xA0628, 0}, + {6, 1, 0xA0630, 0}, + {6, 1, 0xA0638, 0}, + {6, 1, 0xA0640, 0}, + {6, 1, 0xA0648, 0}, + {6, 1, 0xA0658, 0}, + {6, 2, 0x1DE00, 0}, + {6, 2, 0x1DE08, 0}, + {6, 2, 0x1DE10, 0}, + {6, 2, 0x1DE18, 0}, + {6, 3, 0x1DE00, 0}, + {6, 3, 0x1DE08, 0}, + {6, 3, 0x1DE10, 0}, + {6, 3, 0x1DE18, 0}, + {6, 4, 0x1DE00, 0}, + {6, 4, 0x1DE08, 0}, + {6, 4, 0x1DE10, 0}, + {6, 4, 0x1DE18, 0}, + {6, 5, 0x1DE00, 0}, + {6, 5, 0x1DE08, 0}, + {6, 5, 0x1DE10, 0}, + {6, 5, 0x1DE18, 0}, + {7, 1, 0xA0600, 0}, + {7, 1, 0xA0608, 0}, + {7, 1, 0xA0610, 0}, + {7, 1, 0xA0618, 0}, + {7, 1, 0xA0620, 0}, + {7, 1, 0xA0628, 0}, + {7, 1, 0xA0630, 0}, + {7, 1, 0xA0638, 0}, + {7, 1, 0xA0640, 0}, + {7, 1, 0xA0658, 0}, + {7, 2, 0x1DE00, 0}, + {7, 2, 0x1DE08, 0}, + {7, 2, 0x1DE10, 0}, + {7, 2, 0x1DE18, 0}, + {7, 3, 0x1DE00, 0}, + {7, 3, 0x1DE08, 0}, + {7, 3, 0x1DE10, 0}, + {7, 3, 0x1DE18, 0}, + {7, 4, 0x1DE00, 0}, + {7, 4, 0x1DE08, 0}, + {7, 4, 0x1DE10, 0}, + {7, 4, 0x1DE18, 0}, + {7, 5, 0x1DE00, 0}, + {7, 5, 0x1DE08, 0}, + {7, 5, 0x1DE10, 0}, + {7, 5, 0x1DE18, 0}, +}; + +inline const op_config op_dq = { + // stream switch registers: (col, row, offset, value) + { + {0, 0, 0x3F008, 0xC0000045}, + {0, 0, 0x3F010, 0x80000010}, + {0, 0, 0x3F03C, 0x80000009}, + {0, 0, 0x3F044, 0x80000005}, + {0, 0, 0x3F100, 0xC0000000}, + {0, 0, 0x3F114, 0x80000000}, + {0, 0, 0x3F124, 0x80000000}, + {0, 0, 0x3F140, 0x80000000}, + {0, 0, 0x3F200, 0x0F1F0135}, + {0, 1, 0xB0000, 0x8000000C}, + {0, 1, 0xB0004, 0x8000000E}, + {0, 1, 0xB0008, 0x8000000D}, + {0, 1, 0xB000C, 0x8000000F}, + {0, 1, 0xB0010, 0x80000010}, + {0, 1, 0xB0014, 0x8000000A}, + {0, 1, 0xB0024, 0x80000001}, + {0, 1, 0xB0030, 0x80000002}, + {0, 1, 0xB0040, 0x80000000}, + {0, 1, 0xB0100, 0x80000000}, + {0, 1, 0xB0104, 0x80000000}, + {0, 1, 0xB0108, 0x80000000}, + {0, 1, 0xB0128, 0x80000000}, + {0, 1, 0xB0130, 0x80000000}, + {0, 1, 0xB0134, 0x80000000}, + {0, 1, 0xB0138, 0x80000000}, + {0, 1, 0xB013C, 0x80000000}, + {0, 1, 0xB0140, 0x80000000}, + {0, 2, 0x3F004, 0x8000000A}, + {0, 2, 0x3F008, 0x80000006}, + {0, 2, 0x3F014, 0x80000013}, + {0, 2, 0x3F018, 0x80000001}, + {0, 2, 0x3F01C, 0x80000015}, + {0, 2, 0x3F020, 0x80000014}, + {0, 2, 0x3F038, 0x80000006}, + {0, 2, 0x3F044, 0x80000016}, + {0, 2, 0x3F050, 0x80000010}, + {0, 2, 0x3F054, 0x8000000A}, + {0, 2, 0x3F104, 0x80000000}, + {0, 2, 0x3F118, 0x80000000}, + {0, 2, 0x3F128, 0x80000000}, + {0, 2, 0x3F140, 0x80000000}, + {0, 2, 0x3F14C, 0x80000000}, + {0, 2, 0x3F150, 0x80000000}, + {0, 2, 0x3F154, 0x80000000}, + {0, 2, 0x3F158, 0x80000000}, + {0, 3, 0x3F004, 0x80000009}, + {0, 3, 0x3F018, 0x80000010}, + {0, 3, 0x3F034, 0x80000006}, + {0, 3, 0x3F03C, 0x80000013}, + {0, 3, 0x3F04C, 0x80000001}, + {0, 3, 0x3F104, 0x80000000}, + {0, 3, 0x3F118, 0x80000000}, + {0, 3, 0x3F124, 0x80000000}, + {0, 3, 0x3F140, 0x80000000}, + {0, 3, 0x3F14C, 0x80000000}, + {0, 4, 0x3F004, 0x80000007}, + {0, 4, 0x3F008, 0x80000005}, + {0, 4, 0x3F018, 0x80000001}, + {0, 4, 0x3F104, 0x80000000}, + {0, 4, 0x3F114, 0x80000000}, + {0, 4, 0x3F11C, 0x80000000}, + {0, 5, 0x3F004, 0x80000013}, + {0, 5, 0x3F058, 0x80000001}, + {0, 5, 0x3F104, 0x80000000}, + {0, 5, 0x3F14C, 0x80000000}, + {1, 0, 0x3F008, 0xC0000045}, + {1, 0, 0x3F010, 0x80000010}, + {1, 0, 0x3F034, 0x80000009}, + {1, 0, 0x3F100, 0xC0000000}, + {1, 0, 0x3F124, 0x80000000}, + {1, 0, 0x3F140, 0x80000000}, + {1, 0, 0x3F200, 0x0F1F0135}, + {1, 1, 0xB0004, 0x8000000D}, + {1, 1, 0xB0008, 0x80000010}, + {1, 1, 0xB000C, 0x8000000E}, + {1, 1, 0xB0010, 0x8000000F}, + {1, 1, 0xB0014, 0x80000008}, + {1, 1, 0xB0024, 0x80000001}, + {1, 1, 0xB0030, 0x80000002}, + {1, 1, 0xB0104, 0x80000000}, + {1, 1, 0xB0108, 0x80000000}, + {1, 1, 0xB0120, 0x80000000}, + {1, 1, 0xB0134, 0x80000000}, + {1, 1, 0xB0138, 0x80000000}, + {1, 1, 0xB013C, 0x80000000}, + {1, 1, 0xB0140, 0x80000000}, + {1, 2, 0x3F004, 0x8000000D}, + {1, 2, 0x3F008, 0x80000006}, + {1, 2, 0x3F014, 0x80000010}, + {1, 2, 0x3F018, 0x8000000F}, + {1, 2, 0x3F01C, 0x80000011}, + {1, 2, 0x3F020, 0x80000012}, + {1, 2, 0x3F024, 0x80000001}, + {1, 2, 0x3F028, 0x80000013}, + {1, 2, 0x3F02C, 0x80000016}, + {1, 2, 0x3F030, 0x80000015}, + {1, 2, 0x3F034, 0x80000015}, + {1, 2, 0x3F038, 0x80000014}, + {1, 2, 0x3F040, 0x80000006}, + {1, 2, 0x3F04C, 0x8000000C}, + {1, 2, 0x3F054, 0x8000000D}, + {1, 2, 0x3F104, 0x80000000}, + {1, 2, 0x3F118, 0x80000000}, + {1, 2, 0x3F130, 0x80000000}, + {1, 2, 0x3F134, 0x80000000}, + {1, 2, 0x3F13C, 0x80000000}, + {1, 2, 0x3F140, 0x80000000}, + {1, 2, 0x3F144, 0x80000000}, + {1, 2, 0x3F148, 0x80000000}, + {1, 2, 0x3F14C, 0x80000000}, + {1, 2, 0x3F150, 0x80000000}, + {1, 2, 0x3F154, 0x80000000}, + {1, 2, 0x3F158, 0x80000000}, + {1, 3, 0x3F004, 0x80000005}, + {1, 3, 0x3F014, 0x80000013}, + {1, 3, 0x3F018, 0x8000000B}, + {1, 3, 0x3F01C, 0x80000015}, + {1, 3, 0x3F020, 0x80000001}, + {1, 3, 0x3F024, 0x80000016}, + {1, 3, 0x3F03C, 0x80000006}, + {1, 3, 0x3F044, 0x80000008}, + {1, 3, 0x3F058, 0x80000010}, + {1, 3, 0x3F104, 0x80000000}, + {1, 3, 0x3F114, 0x80000000}, + {1, 3, 0x3F118, 0x80000000}, + {1, 3, 0x3F120, 0x80000000}, + {1, 3, 0x3F12C, 0x80000000}, + {1, 3, 0x3F140, 0x80000000}, + {1, 3, 0x3F14C, 0x80000000}, + {1, 3, 0x3F154, 0x80000000}, + {1, 3, 0x3F158, 0x80000000}, + {1, 4, 0x3F004, 0x80000015}, + {1, 4, 0x3F008, 0x80000009}, + {1, 4, 0x3F018, 0x80000001}, + {1, 4, 0x3F048, 0x80000007}, + {1, 4, 0x3F104, 0x80000000}, + {1, 4, 0x3F11C, 0x80000000}, + {1, 4, 0x3F124, 0x80000000}, + {1, 4, 0x3F154, 0x80000000}, + {1, 5, 0x3F004, 0x8000000A}, + {1, 5, 0x3F024, 0x8000000A}, + {1, 5, 0x3F050, 0x8000000E}, + {1, 5, 0x3F058, 0x80000001}, + {1, 5, 0x3F104, 0x80000000}, + {1, 5, 0x3F128, 0x80000000}, + {1, 5, 0x3F138, 0x80000000}, + {2, 0, 0x3F008, 0xC0000045}, + {2, 0, 0x3F010, 0x80000010}, + {2, 0, 0x3F034, 0x80000009}, + {2, 0, 0x3F044, 0x80000005}, + {2, 0, 0x3F100, 0xC0000000}, + {2, 0, 0x3F114, 0x80000000}, + {2, 0, 0x3F124, 0x80000000}, + {2, 0, 0x3F140, 0x80000000}, + {2, 0, 0x3F200, 0x0F1F0135}, + {2, 1, 0xB0000, 0x8000000C}, + {2, 1, 0xB0004, 0x8000000D}, + {2, 1, 0xB0008, 0x80000010}, + {2, 1, 0xB000C, 0x8000000F}, + {2, 1, 0xB0010, 0x8000000E}, + {2, 1, 0xB0014, 0x80000008}, + {2, 1, 0xB0024, 0x80000001}, + {2, 1, 0xB0030, 0x80000002}, + {2, 1, 0xB0040, 0x80000000}, + {2, 1, 0xB0100, 0x80000000}, + {2, 1, 0xB0104, 0x80000000}, + {2, 1, 0xB0108, 0x80000000}, + {2, 1, 0xB0120, 0x80000000}, + {2, 1, 0xB0130, 0x80000000}, + {2, 1, 0xB0134, 0x80000000}, + {2, 1, 0xB0138, 0x80000000}, + {2, 1, 0xB013C, 0x80000000}, + {2, 1, 0xB0140, 0x80000000}, + {2, 2, 0x3F004, 0x8000000D}, + {2, 2, 0x3F008, 0x80000006}, + {2, 2, 0x3F014, 0x8000000B}, + {2, 2, 0x3F018, 0x80000011}, + {2, 2, 0x3F01C, 0x8000000F}, + {2, 2, 0x3F020, 0x80000012}, + {2, 2, 0x3F024, 0x80000013}, + {2, 2, 0x3F028, 0x80000016}, + {2, 2, 0x3F02C, 0x8000000A}, + {2, 2, 0x3F030, 0x80000001}, + {2, 2, 0x3F038, 0x8000000A}, + {2, 2, 0x3F040, 0x80000006}, + {2, 2, 0x3F04C, 0x8000000D}, + {2, 2, 0x3F050, 0x80000010}, + {2, 2, 0x3F054, 0x8000000A}, + {2, 2, 0x3F104, 0x80000000}, + {2, 2, 0x3F118, 0x80000000}, + {2, 2, 0x3F128, 0x80000000}, + {2, 2, 0x3F12C, 0x80000000}, + {2, 2, 0x3F134, 0x80000000}, + {2, 2, 0x3F13C, 0x80000000}, + {2, 2, 0x3F140, 0x80000000}, + {2, 2, 0x3F144, 0x80000000}, + {2, 2, 0x3F148, 0x80000000}, + {2, 2, 0x3F14C, 0x80000000}, + {2, 2, 0x3F158, 0x80000000}, + {2, 3, 0x3F004, 0x80000006}, + {2, 3, 0x3F014, 0x80000010}, + {2, 3, 0x3F018, 0x80000011}, + {2, 3, 0x3F01C, 0x80000014}, + {2, 3, 0x3F020, 0x8000000E}, + {2, 3, 0x3F024, 0x80000001}, + {2, 3, 0x3F02C, 0x80000016}, + {2, 3, 0x3F030, 0x80000013}, + {2, 3, 0x3F034, 0x80000008}, + {2, 3, 0x3F050, 0x80000012}, + {2, 3, 0x3F104, 0x80000000}, + {2, 3, 0x3F118, 0x80000000}, + {2, 3, 0x3F120, 0x80000000}, + {2, 3, 0x3F138, 0x80000000}, + {2, 3, 0x3F140, 0x80000000}, + {2, 3, 0x3F144, 0x80000000}, + {2, 3, 0x3F148, 0x80000000}, + {2, 3, 0x3F14C, 0x80000000}, + {2, 3, 0x3F150, 0x80000000}, + {2, 3, 0x3F158, 0x80000000}, + {2, 4, 0x3F004, 0x80000015}, + {2, 4, 0x3F008, 0x80000005}, + {2, 4, 0x3F018, 0x80000001}, + {2, 4, 0x3F01C, 0x80000012}, + {2, 4, 0x3F020, 0x8000000F}, + {2, 4, 0x3F02C, 0x80000015}, + {2, 4, 0x3F104, 0x80000000}, + {2, 4, 0x3F114, 0x80000000}, + {2, 4, 0x3F13C, 0x80000000}, + {2, 4, 0x3F148, 0x80000000}, + {2, 4, 0x3F154, 0x80000000}, + {2, 5, 0x3F004, 0x80000014}, + {2, 5, 0x3F014, 0x8000000E}, + {2, 5, 0x3F020, 0x80000001}, + {2, 5, 0x3F054, 0x8000000C}, + {2, 5, 0x3F104, 0x80000000}, + {2, 5, 0x3F130, 0x80000000}, + {2, 5, 0x3F138, 0x80000000}, + {2, 5, 0x3F150, 0x80000000}, + {3, 0, 0x3F008, 0xC0000045}, + {3, 0, 0x3F010, 0x80000010}, + {3, 0, 0x3F034, 0x80000009}, + {3, 0, 0x3F100, 0xC0000000}, + {3, 0, 0x3F124, 0x80000000}, + {3, 0, 0x3F140, 0x80000000}, + {3, 0, 0x3F200, 0x0F1F0135}, + {3, 1, 0xB0004, 0x8000000F}, + {3, 1, 0xB0008, 0x8000000D}, + {3, 1, 0xB000C, 0x80000010}, + {3, 1, 0xB0010, 0x8000000E}, + {3, 1, 0xB0014, 0x80000008}, + {3, 1, 0xB0024, 0x80000001}, + {3, 1, 0xB0030, 0x80000002}, + {3, 1, 0xB0104, 0x80000000}, + {3, 1, 0xB0108, 0x80000000}, + {3, 1, 0xB0120, 0x80000000}, + {3, 1, 0xB0134, 0x80000000}, + {3, 1, 0xB0138, 0x80000000}, + {3, 1, 0xB013C, 0x80000000}, + {3, 1, 0xB0140, 0x80000000}, + {3, 2, 0x3F004, 0x8000000B}, + {3, 2, 0x3F008, 0x80000006}, + {3, 2, 0x3F014, 0x80000012}, + {3, 2, 0x3F018, 0x80000010}, + {3, 2, 0x3F01C, 0x8000000F}, + {3, 2, 0x3F020, 0x8000000C}, + {3, 2, 0x3F024, 0x80000001}, + {3, 2, 0x3F030, 0x80000013}, + {3, 2, 0x3F034, 0x80000015}, + {3, 2, 0x3F03C, 0x8000000D}, + {3, 2, 0x3F040, 0x80000006}, + {3, 2, 0x3F04C, 0x8000000B}, + {3, 2, 0x3F104, 0x80000000}, + {3, 2, 0x3F118, 0x80000000}, + {3, 2, 0x3F12C, 0x80000000}, + {3, 2, 0x3F130, 0x80000000}, + {3, 2, 0x3F134, 0x80000000}, + {3, 2, 0x3F13C, 0x80000000}, + {3, 2, 0x3F140, 0x80000000}, + {3, 2, 0x3F148, 0x80000000}, + {3, 2, 0x3F14C, 0x80000000}, + {3, 2, 0x3F154, 0x80000000}, + {3, 3, 0x3F004, 0x80000007}, + {3, 3, 0x3F014, 0x8000000F}, + {3, 3, 0x3F018, 0x80000012}, + {3, 3, 0x3F020, 0x8000000C}, + {3, 3, 0x3F024, 0x80000005}, + {3, 3, 0x3F028, 0x80000010}, + {3, 3, 0x3F030, 0x80000001}, + {3, 3, 0x3F034, 0x80000008}, + {3, 3, 0x3F058, 0x80000007}, + {3, 3, 0x3F104, 0x80000000}, + {3, 3, 0x3F114, 0x80000000}, + {3, 3, 0x3F11C, 0x80000000}, + {3, 3, 0x3F120, 0x80000000}, + {3, 3, 0x3F130, 0x80000000}, + {3, 3, 0x3F13C, 0x80000000}, + {3, 3, 0x3F140, 0x80000000}, + {3, 3, 0x3F148, 0x80000000}, + {3, 4, 0x3F004, 0x80000016}, + {3, 4, 0x3F008, 0x80000005}, + {3, 4, 0x3F014, 0x80000012}, + {3, 4, 0x3F018, 0x80000001}, + {3, 4, 0x3F020, 0x8000000F}, + {3, 4, 0x3F02C, 0x80000016}, + {3, 4, 0x3F038, 0x80000013}, + {3, 4, 0x3F104, 0x80000000}, + {3, 4, 0x3F114, 0x80000000}, + {3, 4, 0x3F13C, 0x80000000}, + {3, 4, 0x3F148, 0x80000000}, + {3, 4, 0x3F14C, 0x80000000}, + {3, 4, 0x3F158, 0x80000000}, + {3, 5, 0x3F004, 0x80000006}, + {3, 5, 0x3F014, 0x80000001}, + {3, 5, 0x3F020, 0x8000000D}, + {3, 5, 0x3F028, 0x80000006}, + {3, 5, 0x3F104, 0x80000000}, + {3, 5, 0x3F118, 0x80000000}, + {3, 5, 0x3F134, 0x80000000}, + {4, 0, 0x3F008, 0xC0000045}, + {4, 0, 0x3F010, 0x80000010}, + {4, 0, 0x3F034, 0x80000009}, + {4, 0, 0x3F044, 0x80000005}, + {4, 0, 0x3F100, 0xC0000000}, + {4, 0, 0x3F114, 0x80000000}, + {4, 0, 0x3F124, 0x80000000}, + {4, 0, 0x3F140, 0x80000000}, + {4, 0, 0x3F200, 0x0F1F0135}, + {4, 1, 0xB0000, 0x8000000C}, + {4, 1, 0xB0004, 0x8000000E}, + {4, 1, 0xB0008, 0x80000010}, + {4, 1, 0xB000C, 0x8000000D}, + {4, 1, 0xB0010, 0x8000000F}, + {4, 1, 0xB0014, 0x80000008}, + {4, 1, 0xB0024, 0x80000001}, + {4, 1, 0xB0030, 0x80000002}, + {4, 1, 0xB0040, 0x80000000}, + {4, 1, 0xB0100, 0x80000000}, + {4, 1, 0xB0104, 0x80000000}, + {4, 1, 0xB0108, 0x80000000}, + {4, 1, 0xB0120, 0x80000000}, + {4, 1, 0xB0130, 0x80000000}, + {4, 1, 0xB0134, 0x80000000}, + {4, 1, 0xB0138, 0x80000000}, + {4, 1, 0xB013C, 0x80000000}, + {4, 1, 0xB0140, 0x80000000}, + {4, 2, 0x3F004, 0x8000000B}, + {4, 2, 0x3F008, 0x80000006}, + {4, 2, 0x3F014, 0x80000014}, + {4, 2, 0x3F018, 0x80000001}, + {4, 2, 0x3F01C, 0x80000015}, + {4, 2, 0x3F020, 0x80000013}, + {4, 2, 0x3F024, 0x80000016}, + {4, 2, 0x3F02C, 0x8000000A}, + {4, 2, 0x3F038, 0x8000000A}, + {4, 2, 0x3F040, 0x80000006}, + {4, 2, 0x3F04C, 0x80000010}, + {4, 2, 0x3F054, 0x8000000A}, + {4, 2, 0x3F058, 0x8000000B}, + {4, 2, 0x3F104, 0x80000000}, + {4, 2, 0x3F118, 0x80000000}, + {4, 2, 0x3F128, 0x80000000}, + {4, 2, 0x3F12C, 0x80000000}, + {4, 2, 0x3F140, 0x80000000}, + {4, 2, 0x3F14C, 0x80000000}, + {4, 2, 0x3F150, 0x80000000}, + {4, 2, 0x3F154, 0x80000000}, + {4, 2, 0x3F158, 0x80000000}, + {4, 3, 0x3F004, 0x8000000E}, + {4, 3, 0x3F018, 0x80000001}, + {4, 3, 0x3F034, 0x80000008}, + {4, 3, 0x3F040, 0x80000006}, + {4, 3, 0x3F04C, 0x80000012}, + {4, 3, 0x3F050, 0x8000000E}, + {4, 3, 0x3F058, 0x80000010}, + {4, 3, 0x3F104, 0x80000000}, + {4, 3, 0x3F118, 0x80000000}, + {4, 3, 0x3F120, 0x80000000}, + {4, 3, 0x3F138, 0x80000000}, + {4, 3, 0x3F140, 0x80000000}, + {4, 3, 0x3F148, 0x80000000}, + {4, 4, 0x3F004, 0x80000008}, + {4, 4, 0x3F008, 0x80000005}, + {4, 4, 0x3F018, 0x80000001}, + {4, 4, 0x3F020, 0x8000000F}, + {4, 4, 0x3F024, 0x80000013}, + {4, 4, 0x3F030, 0x80000008}, + {4, 4, 0x3F050, 0x80000008}, + {4, 4, 0x3F104, 0x80000000}, + {4, 4, 0x3F114, 0x80000000}, + {4, 4, 0x3F120, 0x80000000}, + {4, 4, 0x3F13C, 0x80000000}, + {4, 4, 0x3F14C, 0x80000000}, + {4, 5, 0x3F004, 0x80000016}, + {4, 5, 0x3F014, 0x80000001}, + {4, 5, 0x3F104, 0x80000000}, + {4, 5, 0x3F158, 0x80000000}, + {5, 0, 0x3F008, 0xC0000045}, + {5, 0, 0x3F010, 0x80000010}, + {5, 0, 0x3F034, 0x80000009}, + {5, 0, 0x3F100, 0xC0000000}, + {5, 0, 0x3F124, 0x80000000}, + {5, 0, 0x3F140, 0x80000000}, + {5, 0, 0x3F200, 0x0F1F0135}, + {5, 1, 0xB0004, 0x8000000F}, + {5, 1, 0xB0008, 0x80000010}, + {5, 1, 0xB000C, 0x8000000E}, + {5, 1, 0xB0010, 0x8000000D}, + {5, 1, 0xB0014, 0x80000008}, + {5, 1, 0xB0024, 0x80000001}, + {5, 1, 0xB0030, 0x80000002}, + {5, 1, 0xB0104, 0x80000000}, + {5, 1, 0xB0108, 0x80000000}, + {5, 1, 0xB0120, 0x80000000}, + {5, 1, 0xB0134, 0x80000000}, + {5, 1, 0xB0138, 0x80000000}, + {5, 1, 0xB013C, 0x80000000}, + {5, 1, 0xB0140, 0x80000000}, + {5, 2, 0x3F004, 0x8000000E}, + {5, 2, 0x3F008, 0x80000006}, + {5, 2, 0x3F014, 0x8000000F}, + {5, 2, 0x3F018, 0x80000013}, + {5, 2, 0x3F01C, 0x8000000B}, + {5, 2, 0x3F020, 0x80000010}, + {5, 2, 0x3F024, 0x80000001}, + {5, 2, 0x3F028, 0x80000016}, + {5, 2, 0x3F02C, 0x80000014}, + {5, 2, 0x3F030, 0x80000015}, + {5, 2, 0x3F040, 0x80000006}, + {5, 2, 0x3F04C, 0x8000000D}, + {5, 2, 0x3F050, 0x80000012}, + {5, 2, 0x3F054, 0x80000011}, + {5, 2, 0x3F058, 0x8000000E}, + {5, 2, 0x3F104, 0x80000000}, + {5, 2, 0x3F118, 0x80000000}, + {5, 2, 0x3F12C, 0x80000000}, + {5, 2, 0x3F134, 0x80000000}, + {5, 2, 0x3F138, 0x80000000}, + {5, 2, 0x3F13C, 0x80000000}, + {5, 2, 0x3F140, 0x80000000}, + {5, 2, 0x3F144, 0x80000000}, + {5, 2, 0x3F148, 0x80000000}, + {5, 2, 0x3F14C, 0x80000000}, + {5, 2, 0x3F150, 0x80000000}, + {5, 2, 0x3F154, 0x80000000}, + {5, 2, 0x3F158, 0x80000000}, + {5, 3, 0x3F004, 0x8000000C}, + {5, 3, 0x3F014, 0x80000016}, + {5, 3, 0x3F018, 0x80000001}, + {5, 3, 0x3F01C, 0x80000010}, + {5, 3, 0x3F020, 0x8000000E}, + {5, 3, 0x3F034, 0x80000008}, + {5, 3, 0x3F040, 0x80000015}, + {5, 3, 0x3F050, 0x80000012}, + {5, 3, 0x3F054, 0x8000000C}, + {5, 3, 0x3F058, 0x8000000B}, + {5, 3, 0x3F104, 0x80000000}, + {5, 3, 0x3F120, 0x80000000}, + {5, 3, 0x3F12C, 0x80000000}, + {5, 3, 0x3F130, 0x80000000}, + {5, 3, 0x3F138, 0x80000000}, + {5, 3, 0x3F140, 0x80000000}, + {5, 3, 0x3F148, 0x80000000}, + {5, 3, 0x3F154, 0x80000000}, + {5, 3, 0x3F158, 0x80000000}, + {5, 4, 0x3F004, 0x8000000C}, + {5, 4, 0x3F008, 0x80000005}, + {5, 4, 0x3F018, 0x80000001}, + {5, 4, 0x3F020, 0x8000000F}, + {5, 4, 0x3F024, 0x80000008}, + {5, 4, 0x3F03C, 0x80000008}, + {5, 4, 0x3F104, 0x80000000}, + {5, 4, 0x3F114, 0x80000000}, + {5, 4, 0x3F120, 0x80000000}, + {5, 4, 0x3F130, 0x80000000}, + {5, 4, 0x3F13C, 0x80000000}, + {5, 5, 0x3F004, 0x80000007}, + {5, 5, 0x3F014, 0x80000001}, + {5, 5, 0x3F030, 0x80000007}, + {5, 5, 0x3F104, 0x80000000}, + {5, 5, 0x3F11C, 0x80000000}, + {6, 0, 0x3F008, 0xC0000045}, + {6, 0, 0x3F010, 0x80000010}, + {6, 0, 0x3F034, 0x80000009}, + {6, 0, 0x3F044, 0x80000005}, + {6, 0, 0x3F100, 0xC0000000}, + {6, 0, 0x3F114, 0x80000000}, + {6, 0, 0x3F124, 0x80000000}, + {6, 0, 0x3F140, 0x80000000}, + {6, 0, 0x3F200, 0x0F1F0135}, + {6, 1, 0xB0000, 0x8000000C}, + {6, 1, 0xB0004, 0x80000010}, + {6, 1, 0xB0008, 0x8000000F}, + {6, 1, 0xB000C, 0x8000000E}, + {6, 1, 0xB0010, 0x8000000D}, + {6, 1, 0xB0014, 0x80000008}, + {6, 1, 0xB0024, 0x80000001}, + {6, 1, 0xB0030, 0x80000002}, + {6, 1, 0xB0040, 0x80000000}, + {6, 1, 0xB0100, 0x80000000}, + {6, 1, 0xB0104, 0x80000000}, + {6, 1, 0xB0108, 0x80000000}, + {6, 1, 0xB0120, 0x80000000}, + {6, 1, 0xB0130, 0x80000000}, + {6, 1, 0xB0134, 0x80000000}, + {6, 1, 0xB0138, 0x80000000}, + {6, 1, 0xB013C, 0x80000000}, + {6, 1, 0xB0140, 0x80000000}, + {6, 2, 0x3F004, 0x8000000E}, + {6, 2, 0x3F008, 0x80000006}, + {6, 2, 0x3F014, 0x80000014}, + {6, 2, 0x3F018, 0x8000000F}, + {6, 2, 0x3F01C, 0x8000000D}, + {6, 2, 0x3F020, 0x8000000C}, + {6, 2, 0x3F024, 0x80000010}, + {6, 2, 0x3F028, 0x80000016}, + {6, 2, 0x3F02C, 0x8000000A}, + {6, 2, 0x3F030, 0x80000001}, + {6, 2, 0x3F034, 0x8000000B}, + {6, 2, 0x3F038, 0x8000000A}, + {6, 2, 0x3F040, 0x80000006}, + {6, 2, 0x3F050, 0x80000011}, + {6, 2, 0x3F054, 0x8000000E}, + {6, 2, 0x3F058, 0x8000000A}, + {6, 2, 0x3F104, 0x80000000}, + {6, 2, 0x3F118, 0x80000000}, + {6, 2, 0x3F128, 0x80000000}, + {6, 2, 0x3F12C, 0x80000000}, + {6, 2, 0x3F130, 0x80000000}, + {6, 2, 0x3F134, 0x80000000}, + {6, 2, 0x3F138, 0x80000000}, + {6, 2, 0x3F13C, 0x80000000}, + {6, 2, 0x3F140, 0x80000000}, + {6, 2, 0x3F144, 0x80000000}, + {6, 2, 0x3F150, 0x80000000}, + {6, 2, 0x3F158, 0x80000000}, + {6, 3, 0x3F004, 0x8000000D}, + {6, 3, 0x3F014, 0x80000010}, + {6, 3, 0x3F018, 0x80000001}, + {6, 3, 0x3F01C, 0x8000000C}, + {6, 3, 0x3F02C, 0x80000006}, + {6, 3, 0x3F030, 0x80000016}, + {6, 3, 0x3F03C, 0x80000006}, + {6, 3, 0x3F040, 0x80000005}, + {6, 3, 0x3F048, 0x80000008}, + {6, 3, 0x3F04C, 0x8000000E}, + {6, 3, 0x3F050, 0x8000000D}, + {6, 3, 0x3F104, 0x80000000}, + {6, 3, 0x3F114, 0x80000000}, + {6, 3, 0x3F118, 0x80000000}, + {6, 3, 0x3F120, 0x80000000}, + {6, 3, 0x3F130, 0x80000000}, + {6, 3, 0x3F134, 0x80000000}, + {6, 3, 0x3F138, 0x80000000}, + {6, 3, 0x3F140, 0x80000000}, + {6, 3, 0x3F158, 0x80000000}, + {6, 4, 0x3F004, 0x80000008}, + {6, 4, 0x3F008, 0x8000000A}, + {6, 4, 0x3F018, 0x80000001}, + {6, 4, 0x3F044, 0x80000007}, + {6, 4, 0x3F050, 0x80000008}, + {6, 4, 0x3F054, 0x8000000F}, + {6, 4, 0x3F104, 0x80000000}, + {6, 4, 0x3F11C, 0x80000000}, + {6, 4, 0x3F120, 0x80000000}, + {6, 4, 0x3F128, 0x80000000}, + {6, 4, 0x3F13C, 0x80000000}, + {6, 5, 0x3F004, 0x80000009}, + {6, 5, 0x3F014, 0x80000001}, + {6, 5, 0x3F104, 0x80000000}, + {6, 5, 0x3F124, 0x80000000}, + {7, 0, 0x3F008, 0xC0000045}, + {7, 0, 0x3F010, 0x80000010}, + {7, 0, 0x3F030, 0x80000009}, + {7, 0, 0x3F100, 0xC0000000}, + {7, 0, 0x3F124, 0x80000000}, + {7, 0, 0x3F140, 0x80000000}, + {7, 0, 0x3F200, 0x0F1F0135}, + {7, 1, 0xB0004, 0x8000000F}, + {7, 1, 0xB0008, 0x80000010}, + {7, 1, 0xB000C, 0x8000000D}, + {7, 1, 0xB0010, 0x8000000E}, + {7, 1, 0xB0014, 0x80000007}, + {7, 1, 0xB0024, 0x80000001}, + {7, 1, 0xB0030, 0x80000002}, + {7, 1, 0xB0104, 0x80000000}, + {7, 1, 0xB0108, 0x80000000}, + {7, 1, 0xB011C, 0x80000000}, + {7, 1, 0xB0134, 0x80000000}, + {7, 1, 0xB0138, 0x80000000}, + {7, 1, 0xB013C, 0x80000000}, + {7, 1, 0xB0140, 0x80000000}, + {7, 2, 0x3F004, 0x8000000D}, + {7, 2, 0x3F008, 0x80000006}, + {7, 2, 0x3F014, 0x8000000F}, + {7, 2, 0x3F018, 0x80000012}, + {7, 2, 0x3F01C, 0x80000011}, + {7, 2, 0x3F020, 0x8000000C}, + {7, 2, 0x3F028, 0x80000010}, + {7, 2, 0x3F030, 0x80000001}, + {7, 2, 0x3F034, 0x8000000E}, + {7, 2, 0x3F044, 0x80000006}, + {7, 2, 0x3F104, 0x80000000}, + {7, 2, 0x3F118, 0x80000000}, + {7, 2, 0x3F130, 0x80000000}, + {7, 2, 0x3F134, 0x80000000}, + {7, 2, 0x3F138, 0x80000000}, + {7, 2, 0x3F13C, 0x80000000}, + {7, 2, 0x3F140, 0x80000000}, + {7, 2, 0x3F144, 0x80000000}, + {7, 2, 0x3F148, 0x80000000}, + {7, 3, 0x3F004, 0x8000000C}, + {7, 3, 0x3F014, 0x80000010}, + {7, 3, 0x3F018, 0x80000012}, + {7, 3, 0x3F01C, 0x8000000B}, + {7, 3, 0x3F020, 0x80000011}, + {7, 3, 0x3F030, 0x80000001}, + {7, 3, 0x3F040, 0x80000009}, + {7, 3, 0x3F048, 0x80000005}, + {7, 3, 0x3F104, 0x80000000}, + {7, 3, 0x3F114, 0x80000000}, + {7, 3, 0x3F124, 0x80000000}, + {7, 3, 0x3F12C, 0x80000000}, + {7, 3, 0x3F130, 0x80000000}, + {7, 3, 0x3F140, 0x80000000}, + {7, 3, 0x3F144, 0x80000000}, + {7, 3, 0x3F148, 0x80000000}, + {7, 4, 0x3F004, 0x8000000C}, + {7, 4, 0x3F008, 0x80000008}, + {7, 4, 0x3F018, 0x8000000D}, + {7, 4, 0x3F01C, 0x8000000F}, + {7, 4, 0x3F020, 0x80000001}, + {7, 4, 0x3F03C, 0x8000000A}, + {7, 4, 0x3F104, 0x80000000}, + {7, 4, 0x3F120, 0x80000000}, + {7, 4, 0x3F128, 0x80000000}, + {7, 4, 0x3F130, 0x80000000}, + {7, 4, 0x3F134, 0x80000000}, + {7, 4, 0x3F13C, 0x80000000}, + {7, 5, 0x3F004, 0x80000007}, + {7, 5, 0x3F014, 0x80000001}, + {7, 5, 0x3F104, 0x80000000}, + {7, 5, 0x3F11C, 0x80000000}, + }, + // shim mux / demux mask writes: (col, row, offset, mask, value) + { + {0, 0, 0x1F000, 0x0000C000, 0x00004000}, + {0, 0, 0x1F000, 0x00000C00, 0x00000400}, + {0, 0, 0x1F004, 0x00000030, 0x00000010}, + {1, 0, 0x1F000, 0x0000C000, 0x00004000}, + {1, 0, 0x1F004, 0x00000030, 0x00000010}, + {2, 0, 0x1F000, 0x0000C000, 0x00004000}, + {2, 0, 0x1F000, 0x00000C00, 0x00000400}, + {2, 0, 0x1F004, 0x00000030, 0x00000010}, + {3, 0, 0x1F000, 0x0000C000, 0x00004000}, + {3, 0, 0x1F004, 0x00000030, 0x00000010}, + {4, 0, 0x1F000, 0x0000C000, 0x00004000}, + {4, 0, 0x1F000, 0x00000C00, 0x00000400}, + {4, 0, 0x1F004, 0x00000030, 0x00000010}, + {5, 0, 0x1F000, 0x0000C000, 0x00004000}, + {5, 0, 0x1F004, 0x00000030, 0x00000010}, + {6, 0, 0x1F000, 0x0000C000, 0x00004000}, + {6, 0, 0x1F000, 0x00000C00, 0x00000400}, + {6, 0, 0x1F004, 0x00000030, 0x00000010}, + {7, 0, 0x1F000, 0x0000C000, 0x00004000}, + {7, 0, 0x1F004, 0x00000030, 0x00000010}, + }, + // BD registers: (col, row, offset, shared, words) + { + {0, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {0, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {0, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {0, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {0, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {0, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {0, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {0, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {0, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {0, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {0, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {0, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {0, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {0, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {0, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {0, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {0, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {0, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {0, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {0, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {1, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {1, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {1, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {1, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {1, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {1, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {1, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {1, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {1, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {1, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {1, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {1, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {1, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {1, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {1, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {1, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {1, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {1, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {1, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {1, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {2, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {2, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {2, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {2, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {2, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {2, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {2, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {2, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {2, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {2, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {2, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {2, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {2, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {2, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {2, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {2, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {2, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {2, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {2, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {2, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {3, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {3, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {3, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {3, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {3, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {3, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {3, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {3, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {3, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {3, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {3, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {3, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {3, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {3, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {3, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {3, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {3, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {3, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {3, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {3, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {4, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {4, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {4, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {4, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {4, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {4, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {4, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {4, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {4, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {4, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {4, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {4, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {4, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {4, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {4, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {4, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {4, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {4, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {4, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {4, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {5, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {5, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {5, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {5, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {5, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {5, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {5, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {5, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {5, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {5, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {5, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {5, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {5, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {5, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {5, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {5, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {5, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {5, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {5, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {5, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {6, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {6, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {6, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {6, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {6, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {6, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {6, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {6, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {6, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {6, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {6, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {6, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {6, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {6, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {6, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {6, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {6, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {6, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {6, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {6, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {7, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {7, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {7, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {7, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {7, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {7, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {7, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {7, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {7, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {7, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {7, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {7, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {7, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {7, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {7, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {7, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {7, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {7, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {7, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {7, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {0, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {0, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {0, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {0, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {0, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {0, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {0, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {0, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {0, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {0, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {0, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {0, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {0, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {0, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {0, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {0, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {0, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {0, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {0, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {0, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {1, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {1, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {1, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {1, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {1, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {1, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {1, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {1, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {1, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {1, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {1, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {1, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {1, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {1, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {1, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {1, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {1, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {1, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {2, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {2, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {2, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {2, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {2, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {2, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {2, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {2, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {2, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {2, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {2, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {2, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {2, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {2, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {2, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {2, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {2, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {2, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {2, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {2, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {3, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {3, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {3, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {3, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {3, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {3, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {3, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {3, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {3, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {3, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {3, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {3, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {3, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {3, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {3, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {3, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {3, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {3, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {4, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {4, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {4, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {4, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {4, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {4, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {4, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {4, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {4, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {4, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {4, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {4, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {4, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {4, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {4, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {4, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {4, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {4, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {4, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {4, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {5, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {5, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {5, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {5, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {5, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {5, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {5, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {5, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {5, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {5, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {5, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {5, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {5, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {5, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {5, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {5, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {5, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {5, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {6, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {6, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {6, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {6, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {6, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {6, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {6, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {6, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {6, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {6, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {6, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {6, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {6, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {6, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {6, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {6, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {6, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {6, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {6, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {6, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {7, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {7, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {7, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {7, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {7, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {7, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {7, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {7, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {7, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {7, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {7, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {7, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {7, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {7, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {7, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {7, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {7, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {7, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + }, + // lock values: (col, row, offset, value) + { + {0, 1, 0xC0000, 2}, + {0, 1, 0xC0010, 0}, + {0, 1, 0xC0020, 0}, + {0, 1, 0xC0030, 0}, + {0, 1, 0xC0040, 0}, + {0, 1, 0xC0050, 4}, + {0, 1, 0xC0060, 4}, + {0, 1, 0xC0070, 0}, + {0, 1, 0xC0080, 0}, + {0, 1, 0xC00A0, 2}, + {0, 1, 0xC00B0, 0}, + {0, 2, 0x1F000, 2}, + {0, 2, 0x1F010, 0}, + {0, 2, 0x1F020, 4}, + {0, 2, 0x1F030, 0}, + {0, 2, 0x1F040, 2}, + {0, 2, 0x1F050, 0}, + {0, 2, 0x1F060, 0}, + {0, 2, 0x1F0F0, 0}, + {0, 3, 0x1F000, 2}, + {0, 3, 0x1F010, 0}, + {0, 3, 0x1F040, 2}, + {0, 3, 0x1F050, 0}, + {0, 3, 0x1F060, 0}, + {0, 3, 0x1F0F0, 0}, + {0, 4, 0x1F000, 2}, + {0, 4, 0x1F010, 0}, + {0, 4, 0x1F020, 4}, + {0, 4, 0x1F030, 0}, + {0, 4, 0x1F040, 2}, + {0, 4, 0x1F050, 0}, + {0, 4, 0x1F060, 0}, + {0, 4, 0x1F0F0, 0}, + {0, 5, 0x1F000, 2}, + {0, 5, 0x1F010, 0}, + {0, 5, 0x1F040, 2}, + {0, 5, 0x1F050, 0}, + {0, 5, 0x1F060, 0}, + {0, 5, 0x1F0F0, 0}, + {1, 1, 0xC0000, 2}, + {1, 1, 0xC0010, 0}, + {1, 1, 0xC0020, 0}, + {1, 1, 0xC0030, 0}, + {1, 1, 0xC0040, 0}, + {1, 1, 0xC0050, 4}, + {1, 1, 0xC0060, 4}, + {1, 1, 0xC0070, 0}, + {1, 1, 0xC0080, 0}, + {1, 1, 0xC00A0, 2}, + {1, 1, 0xC00B0, 0}, + {1, 2, 0x1F000, 2}, + {1, 2, 0x1F010, 0}, + {1, 2, 0x1F020, 4}, + {1, 2, 0x1F030, 0}, + {1, 2, 0x1F040, 2}, + {1, 2, 0x1F050, 0}, + {1, 2, 0x1F060, 0}, + {1, 2, 0x1F0F0, 0}, + {1, 3, 0x1F000, 2}, + {1, 3, 0x1F010, 0}, + {1, 3, 0x1F040, 2}, + {1, 3, 0x1F050, 0}, + {1, 3, 0x1F060, 0}, + {1, 3, 0x1F0F0, 0}, + {1, 4, 0x1F000, 2}, + {1, 4, 0x1F010, 0}, + {1, 4, 0x1F020, 4}, + {1, 4, 0x1F030, 0}, + {1, 4, 0x1F040, 2}, + {1, 4, 0x1F050, 0}, + {1, 4, 0x1F060, 0}, + {1, 4, 0x1F0F0, 0}, + {1, 5, 0x1F000, 2}, + {1, 5, 0x1F010, 0}, + {1, 5, 0x1F040, 2}, + {1, 5, 0x1F050, 0}, + {1, 5, 0x1F060, 0}, + {1, 5, 0x1F0F0, 0}, + {2, 1, 0xC0000, 2}, + {2, 1, 0xC0010, 0}, + {2, 1, 0xC0020, 0}, + {2, 1, 0xC0030, 0}, + {2, 1, 0xC0040, 0}, + {2, 1, 0xC0050, 4}, + {2, 1, 0xC0060, 4}, + {2, 1, 0xC0070, 0}, + {2, 1, 0xC0080, 0}, + {2, 1, 0xC00A0, 2}, + {2, 1, 0xC00B0, 0}, + {2, 2, 0x1F000, 2}, + {2, 2, 0x1F010, 0}, + {2, 2, 0x1F020, 4}, + {2, 2, 0x1F030, 0}, + {2, 2, 0x1F040, 2}, + {2, 2, 0x1F050, 0}, + {2, 2, 0x1F060, 0}, + {2, 2, 0x1F0F0, 0}, + {2, 3, 0x1F000, 2}, + {2, 3, 0x1F010, 0}, + {2, 3, 0x1F040, 2}, + {2, 3, 0x1F050, 0}, + {2, 3, 0x1F060, 0}, + {2, 3, 0x1F0F0, 0}, + {2, 4, 0x1F000, 2}, + {2, 4, 0x1F010, 0}, + {2, 4, 0x1F020, 4}, + {2, 4, 0x1F030, 0}, + {2, 4, 0x1F040, 2}, + {2, 4, 0x1F050, 0}, + {2, 4, 0x1F060, 0}, + {2, 4, 0x1F0F0, 0}, + {2, 5, 0x1F000, 2}, + {2, 5, 0x1F010, 0}, + {2, 5, 0x1F040, 2}, + {2, 5, 0x1F050, 0}, + {2, 5, 0x1F060, 0}, + {2, 5, 0x1F0F0, 0}, + {3, 1, 0xC0000, 2}, + {3, 1, 0xC0010, 0}, + {3, 1, 0xC0020, 0}, + {3, 1, 0xC0030, 0}, + {3, 1, 0xC0040, 0}, + {3, 1, 0xC0050, 4}, + {3, 1, 0xC0060, 4}, + {3, 1, 0xC0070, 0}, + {3, 1, 0xC0080, 0}, + {3, 1, 0xC00A0, 2}, + {3, 1, 0xC00B0, 0}, + {3, 2, 0x1F000, 2}, + {3, 2, 0x1F010, 0}, + {3, 2, 0x1F020, 4}, + {3, 2, 0x1F030, 0}, + {3, 2, 0x1F040, 2}, + {3, 2, 0x1F050, 0}, + {3, 2, 0x1F060, 0}, + {3, 2, 0x1F0F0, 0}, + {3, 3, 0x1F000, 2}, + {3, 3, 0x1F010, 0}, + {3, 3, 0x1F040, 2}, + {3, 3, 0x1F050, 0}, + {3, 3, 0x1F060, 0}, + {3, 3, 0x1F0F0, 0}, + {3, 4, 0x1F000, 2}, + {3, 4, 0x1F010, 0}, + {3, 4, 0x1F020, 4}, + {3, 4, 0x1F030, 0}, + {3, 4, 0x1F040, 2}, + {3, 4, 0x1F050, 0}, + {3, 4, 0x1F060, 0}, + {3, 4, 0x1F0F0, 0}, + {3, 5, 0x1F000, 2}, + {3, 5, 0x1F010, 0}, + {3, 5, 0x1F040, 2}, + {3, 5, 0x1F050, 0}, + {3, 5, 0x1F060, 0}, + {3, 5, 0x1F0F0, 0}, + {4, 1, 0xC0000, 2}, + {4, 1, 0xC0010, 0}, + {4, 1, 0xC0020, 0}, + {4, 1, 0xC0030, 0}, + {4, 1, 0xC0040, 0}, + {4, 1, 0xC0050, 4}, + {4, 1, 0xC0060, 4}, + {4, 1, 0xC0070, 0}, + {4, 1, 0xC0080, 0}, + {4, 1, 0xC00A0, 2}, + {4, 1, 0xC00B0, 0}, + {4, 2, 0x1F000, 2}, + {4, 2, 0x1F010, 0}, + {4, 2, 0x1F020, 4}, + {4, 2, 0x1F030, 0}, + {4, 2, 0x1F040, 2}, + {4, 2, 0x1F050, 0}, + {4, 2, 0x1F060, 0}, + {4, 2, 0x1F0F0, 0}, + {4, 3, 0x1F000, 2}, + {4, 3, 0x1F010, 0}, + {4, 3, 0x1F040, 2}, + {4, 3, 0x1F050, 0}, + {4, 3, 0x1F060, 0}, + {4, 3, 0x1F0F0, 0}, + {4, 4, 0x1F000, 2}, + {4, 4, 0x1F010, 0}, + {4, 4, 0x1F020, 4}, + {4, 4, 0x1F030, 0}, + {4, 4, 0x1F040, 2}, + {4, 4, 0x1F050, 0}, + {4, 4, 0x1F060, 0}, + {4, 4, 0x1F0F0, 0}, + {4, 5, 0x1F000, 2}, + {4, 5, 0x1F010, 0}, + {4, 5, 0x1F040, 2}, + {4, 5, 0x1F050, 0}, + {4, 5, 0x1F060, 0}, + {4, 5, 0x1F0F0, 0}, + {5, 1, 0xC0000, 2}, + {5, 1, 0xC0010, 0}, + {5, 1, 0xC0020, 0}, + {5, 1, 0xC0030, 0}, + {5, 1, 0xC0040, 0}, + {5, 1, 0xC0050, 4}, + {5, 1, 0xC0060, 4}, + {5, 1, 0xC0070, 0}, + {5, 1, 0xC0080, 0}, + {5, 1, 0xC00A0, 2}, + {5, 1, 0xC00B0, 0}, + {5, 2, 0x1F000, 2}, + {5, 2, 0x1F010, 0}, + {5, 2, 0x1F020, 4}, + {5, 2, 0x1F030, 0}, + {5, 2, 0x1F040, 2}, + {5, 2, 0x1F050, 0}, + {5, 2, 0x1F060, 0}, + {5, 2, 0x1F0F0, 0}, + {5, 3, 0x1F000, 2}, + {5, 3, 0x1F010, 0}, + {5, 3, 0x1F040, 2}, + {5, 3, 0x1F050, 0}, + {5, 3, 0x1F060, 0}, + {5, 3, 0x1F0F0, 0}, + {5, 4, 0x1F000, 2}, + {5, 4, 0x1F010, 0}, + {5, 4, 0x1F020, 4}, + {5, 4, 0x1F030, 0}, + {5, 4, 0x1F040, 2}, + {5, 4, 0x1F050, 0}, + {5, 4, 0x1F060, 0}, + {5, 4, 0x1F0F0, 0}, + {5, 5, 0x1F000, 2}, + {5, 5, 0x1F010, 0}, + {5, 5, 0x1F040, 2}, + {5, 5, 0x1F050, 0}, + {5, 5, 0x1F060, 0}, + {5, 5, 0x1F0F0, 0}, + {6, 1, 0xC0000, 2}, + {6, 1, 0xC0010, 0}, + {6, 1, 0xC0020, 0}, + {6, 1, 0xC0030, 0}, + {6, 1, 0xC0040, 0}, + {6, 1, 0xC0050, 4}, + {6, 1, 0xC0060, 4}, + {6, 1, 0xC0070, 0}, + {6, 1, 0xC0080, 0}, + {6, 1, 0xC00A0, 2}, + {6, 1, 0xC00B0, 0}, + {6, 2, 0x1F000, 2}, + {6, 2, 0x1F010, 0}, + {6, 2, 0x1F020, 4}, + {6, 2, 0x1F030, 0}, + {6, 2, 0x1F040, 2}, + {6, 2, 0x1F050, 0}, + {6, 2, 0x1F060, 0}, + {6, 2, 0x1F0F0, 0}, + {6, 3, 0x1F000, 2}, + {6, 3, 0x1F010, 0}, + {6, 3, 0x1F040, 2}, + {6, 3, 0x1F050, 0}, + {6, 3, 0x1F060, 0}, + {6, 3, 0x1F0F0, 0}, + {6, 4, 0x1F000, 2}, + {6, 4, 0x1F010, 0}, + {6, 4, 0x1F020, 4}, + {6, 4, 0x1F030, 0}, + {6, 4, 0x1F040, 2}, + {6, 4, 0x1F050, 0}, + {6, 4, 0x1F060, 0}, + {6, 4, 0x1F0F0, 0}, + {6, 5, 0x1F000, 2}, + {6, 5, 0x1F010, 0}, + {6, 5, 0x1F040, 2}, + {6, 5, 0x1F050, 0}, + {6, 5, 0x1F060, 0}, + {6, 5, 0x1F0F0, 0}, + {7, 1, 0xC0000, 2}, + {7, 1, 0xC0010, 0}, + {7, 1, 0xC0020, 0}, + {7, 1, 0xC0030, 0}, + {7, 1, 0xC0040, 0}, + {7, 1, 0xC0050, 4}, + {7, 1, 0xC0060, 4}, + {7, 1, 0xC0070, 0}, + {7, 1, 0xC0080, 0}, + {7, 1, 0xC00A0, 2}, + {7, 1, 0xC00B0, 0}, + {7, 2, 0x1F000, 2}, + {7, 2, 0x1F010, 0}, + {7, 2, 0x1F020, 4}, + {7, 2, 0x1F030, 0}, + {7, 2, 0x1F040, 2}, + {7, 2, 0x1F050, 0}, + {7, 2, 0x1F060, 0}, + {7, 2, 0x1F0F0, 0}, + {7, 3, 0x1F000, 2}, + {7, 3, 0x1F010, 0}, + {7, 3, 0x1F040, 2}, + {7, 3, 0x1F050, 0}, + {7, 3, 0x1F060, 0}, + {7, 3, 0x1F0F0, 0}, + {7, 4, 0x1F000, 2}, + {7, 4, 0x1F010, 0}, + {7, 4, 0x1F020, 4}, + {7, 4, 0x1F030, 0}, + {7, 4, 0x1F040, 2}, + {7, 4, 0x1F050, 0}, + {7, 4, 0x1F060, 0}, + {7, 4, 0x1F0F0, 0}, + {7, 5, 0x1F000, 2}, + {7, 5, 0x1F010, 0}, + {7, 5, 0x1F040, 2}, + {7, 5, 0x1F050, 0}, + {7, 5, 0x1F060, 0}, + {7, 5, 0x1F0F0, 0}, + }, + // channels: (col, row, control offset, start queue offset, queue value, control value) + { + {0, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {0, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {0, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {0, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {0, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {0, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {0, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {0, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {0, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {0, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {1, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {1, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {1, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {1, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {1, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {1, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {1, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {1, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {1, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {1, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {2, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {2, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {2, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {2, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {2, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {2, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {2, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {2, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {2, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {2, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {3, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {3, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {3, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {3, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {3, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {3, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {3, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {3, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {3, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {3, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {4, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {4, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {4, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {4, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {4, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {4, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {4, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {4, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {4, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {4, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {5, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {5, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {5, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {5, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {5, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {5, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {5, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {5, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {5, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {5, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {6, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {6, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {6, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {6, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {6, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {6, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {6, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {6, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {6, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {6, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {7, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {7, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {7, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {7, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {7, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {7, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {7, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {7, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {7, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {7, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {0, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {0, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {0, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {0, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {0, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {0, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {0, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {0, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {0, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {1, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {1, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {1, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {1, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {1, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {1, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {1, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {1, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {1, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {2, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {2, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {2, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {2, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {2, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {2, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {2, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {2, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {2, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {3, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {3, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {3, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {3, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {3, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {3, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {3, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {3, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {3, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {4, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {4, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {4, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {4, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {4, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {4, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {4, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {4, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {4, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {5, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {5, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {5, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {5, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {5, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {5, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {5, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {5, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {5, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {6, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {6, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {6, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {6, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {6, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {6, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {6, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {6, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {6, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {7, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {7, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {7, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {7, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {7, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {7, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {7, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {7, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {7, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + }, +}; + +inline const op_config op_attn = { + // stream switch registers: (col, row, offset, value) + { + {0, 0, 0x3F008, 0xC0000045}, + {0, 0, 0x3F010, 0x80000010}, + {0, 0, 0x3F03C, 0x80000009}, + {0, 0, 0x3F044, 0x80000005}, + {0, 0, 0x3F100, 0xC0000000}, + {0, 0, 0x3F114, 0x80000000}, + {0, 0, 0x3F124, 0x80000000}, + {0, 0, 0x3F140, 0x80000000}, + {0, 0, 0x3F200, 0x0F1F0135}, + {0, 1, 0xB0000, 0x8000000C}, + {0, 1, 0xB0004, 0x8000000A}, + {0, 1, 0xB0008, 0x8000000E}, + {0, 1, 0xB000C, 0x8000000F}, + {0, 1, 0xB0010, 0x80000010}, + {0, 1, 0xB0014, 0x8000000D}, + {0, 1, 0xB0024, 0x80000005}, + {0, 1, 0xB002C, 0x80000000}, + {0, 1, 0xB0030, 0x80000003}, + {0, 1, 0xB0038, 0x80000001}, + {0, 1, 0xB0040, 0x80000002}, + {0, 1, 0xB0100, 0x80000000}, + {0, 1, 0xB0104, 0x80000000}, + {0, 1, 0xB0108, 0x80000000}, + {0, 1, 0xB010C, 0x80000000}, + {0, 1, 0xB0114, 0x80000000}, + {0, 1, 0xB0128, 0x80000000}, + {0, 1, 0xB0130, 0x80000000}, + {0, 1, 0xB0134, 0x80000000}, + {0, 1, 0xB0138, 0x80000000}, + {0, 1, 0xB013C, 0x80000000}, + {0, 1, 0xB0140, 0x80000000}, + {0, 2, 0x3F004, 0x80000005}, + {0, 2, 0x3F008, 0x80000014}, + {0, 2, 0x3F014, 0x80000011}, + {0, 2, 0x3F018, 0x80000001}, + {0, 2, 0x3F01C, 0x80000016}, + {0, 2, 0x3F020, 0x80000010}, + {0, 2, 0x3F040, 0x80000006}, + {0, 2, 0x3F044, 0x80000008}, + {0, 2, 0x3F048, 0x8000000A}, + {0, 2, 0x3F050, 0x80000005}, + {0, 2, 0x3F058, 0x80000008}, + {0, 2, 0x3F104, 0x80000000}, + {0, 2, 0x3F114, 0x80000000}, + {0, 2, 0x3F118, 0x80000000}, + {0, 2, 0x3F120, 0x80000000}, + {0, 2, 0x3F128, 0x80000000}, + {0, 2, 0x3F140, 0x80000000}, + {0, 2, 0x3F144, 0x80000000}, + {0, 2, 0x3F150, 0x80000000}, + {0, 2, 0x3F158, 0x80000000}, + {0, 3, 0x3F004, 0x80000009}, + {0, 3, 0x3F008, 0x80000014}, + {0, 3, 0x3F018, 0x80000001}, + {0, 3, 0x3F01C, 0x80000016}, + {0, 3, 0x3F034, 0x80000008}, + {0, 3, 0x3F038, 0x8000000A}, + {0, 3, 0x3F04C, 0x8000000F}, + {0, 3, 0x3F104, 0x80000000}, + {0, 3, 0x3F120, 0x80000000}, + {0, 3, 0x3F124, 0x80000000}, + {0, 3, 0x3F128, 0x80000000}, + {0, 3, 0x3F13C, 0x80000000}, + {0, 3, 0x3F150, 0x80000000}, + {0, 3, 0x3F158, 0x80000000}, + {0, 4, 0x3F004, 0x80000006}, + {0, 4, 0x3F008, 0x80000014}, + {0, 4, 0x3F014, 0x8000000F}, + {0, 4, 0x3F03C, 0x80000005}, + {0, 4, 0x3F04C, 0x80000006}, + {0, 4, 0x3F050, 0x80000001}, + {0, 4, 0x3F054, 0x80000005}, + {0, 4, 0x3F104, 0x80000000}, + {0, 4, 0x3F114, 0x80000000}, + {0, 4, 0x3F118, 0x80000000}, + {0, 4, 0x3F13C, 0x80000000}, + {0, 4, 0x3F150, 0x80000000}, + {0, 5, 0x3F004, 0x80000007}, + {0, 5, 0x3F008, 0x80000015}, + {0, 5, 0x3F014, 0x80000001}, + {0, 5, 0x3F104, 0x80000000}, + {0, 5, 0x3F11C, 0x80000000}, + {0, 5, 0x3F154, 0x80000000}, + {1, 0, 0x3F008, 0xC0000045}, + {1, 0, 0x3F010, 0x80000010}, + {1, 0, 0x3F100, 0xC0000000}, + {1, 0, 0x3F140, 0x80000000}, + {1, 0, 0x3F200, 0x0F1F0135}, + {1, 1, 0xB0008, 0x8000000D}, + {1, 1, 0xB000C, 0x8000000F}, + {1, 1, 0xB0010, 0x80000010}, + {1, 1, 0xB0014, 0x8000000E}, + {1, 1, 0xB0024, 0x80000005}, + {1, 1, 0xB0114, 0x80000000}, + {1, 1, 0xB0134, 0x80000000}, + {1, 1, 0xB0138, 0x80000000}, + {1, 1, 0xB013C, 0x80000000}, + {1, 1, 0xB0140, 0x80000000}, + {1, 2, 0x3F004, 0x8000000C}, + {1, 2, 0x3F008, 0x80000014}, + {1, 2, 0x3F014, 0x8000000F}, + {1, 2, 0x3F018, 0x80000012}, + {1, 2, 0x3F01C, 0x80000010}, + {1, 2, 0x3F020, 0x80000011}, + {1, 2, 0x3F028, 0x80000014}, + {1, 2, 0x3F030, 0x80000001}, + {1, 2, 0x3F038, 0x8000000E}, + {1, 2, 0x3F104, 0x80000000}, + {1, 2, 0x3F130, 0x80000000}, + {1, 2, 0x3F138, 0x80000000}, + {1, 2, 0x3F13C, 0x80000000}, + {1, 2, 0x3F140, 0x80000000}, + {1, 2, 0x3F144, 0x80000000}, + {1, 2, 0x3F148, 0x80000000}, + {1, 2, 0x3F150, 0x80000000}, + {1, 3, 0x3F004, 0x80000006}, + {1, 3, 0x3F008, 0x80000013}, + {1, 3, 0x3F014, 0x8000000F}, + {1, 3, 0x3F018, 0x80000011}, + {1, 3, 0x3F01C, 0x8000000B}, + {1, 3, 0x3F020, 0x80000012}, + {1, 3, 0x3F028, 0x80000013}, + {1, 3, 0x3F030, 0x80000001}, + {1, 3, 0x3F048, 0x80000013}, + {1, 3, 0x3F104, 0x80000000}, + {1, 3, 0x3F118, 0x80000000}, + {1, 3, 0x3F12C, 0x80000000}, + {1, 3, 0x3F13C, 0x80000000}, + {1, 3, 0x3F144, 0x80000000}, + {1, 3, 0x3F148, 0x80000000}, + {1, 3, 0x3F14C, 0x80000000}, + {1, 4, 0x3F004, 0x8000000B}, + {1, 4, 0x3F008, 0x8000000A}, + {1, 4, 0x3F014, 0x8000000C}, + {1, 4, 0x3F01C, 0x80000001}, + {1, 4, 0x3F020, 0x8000000F}, + {1, 4, 0x3F028, 0x8000000A}, + {1, 4, 0x3F03C, 0x8000000D}, + {1, 4, 0x3F104, 0x80000000}, + {1, 4, 0x3F128, 0x80000000}, + {1, 4, 0x3F12C, 0x80000000}, + {1, 4, 0x3F130, 0x80000000}, + {1, 4, 0x3F134, 0x80000000}, + {1, 4, 0x3F13C, 0x80000000}, + {1, 5, 0x3F004, 0x80000007}, + {1, 5, 0x3F008, 0x80000013}, + {1, 5, 0x3F014, 0x80000001}, + {1, 5, 0x3F02C, 0x80000013}, + {1, 5, 0x3F104, 0x80000000}, + {1, 5, 0x3F11C, 0x80000000}, + {1, 5, 0x3F14C, 0x80000000}, + {2, 0, 0x3F008, 0xC0000045}, + {2, 0, 0x3F010, 0x80000010}, + {2, 0, 0x3F034, 0x80000005}, + {2, 0, 0x3F044, 0x80000009}, + {2, 0, 0x3F100, 0xC0000000}, + {2, 0, 0x3F114, 0x80000000}, + {2, 0, 0x3F124, 0x80000000}, + {2, 0, 0x3F140, 0x80000000}, + {2, 0, 0x3F200, 0x0F1F0135}, + {2, 1, 0xB0000, 0x80000008}, + {2, 1, 0xB0004, 0x8000000C}, + {2, 1, 0xB0008, 0x8000000F}, + {2, 1, 0xB000C, 0x80000010}, + {2, 1, 0xB0010, 0x8000000E}, + {2, 1, 0xB0014, 0x8000000D}, + {2, 1, 0xB0024, 0x80000005}, + {2, 1, 0xB002C, 0x80000002}, + {2, 1, 0xB0030, 0x80000003}, + {2, 1, 0xB0038, 0x80000001}, + {2, 1, 0xB0040, 0x80000000}, + {2, 1, 0xB0100, 0x80000000}, + {2, 1, 0xB0104, 0x80000000}, + {2, 1, 0xB0108, 0x80000000}, + {2, 1, 0xB010C, 0x80000000}, + {2, 1, 0xB0114, 0x80000000}, + {2, 1, 0xB0120, 0x80000000}, + {2, 1, 0xB0130, 0x80000000}, + {2, 1, 0xB0134, 0x80000000}, + {2, 1, 0xB0138, 0x80000000}, + {2, 1, 0xB013C, 0x80000000}, + {2, 1, 0xB0140, 0x80000000}, + {2, 2, 0x3F004, 0x8000000A}, + {2, 2, 0x3F008, 0x80000013}, + {2, 2, 0x3F014, 0x8000000F}, + {2, 2, 0x3F018, 0x80000011}, + {2, 2, 0x3F01C, 0x80000001}, + {2, 2, 0x3F020, 0x80000014}, + {2, 2, 0x3F028, 0x80000013}, + {2, 2, 0x3F034, 0x80000006}, + {2, 2, 0x3F03C, 0x80000005}, + {2, 2, 0x3F048, 0x80000008}, + {2, 2, 0x3F04C, 0x80000008}, + {2, 2, 0x3F050, 0x8000000A}, + {2, 2, 0x3F054, 0x80000010}, + {2, 2, 0x3F104, 0x80000000}, + {2, 2, 0x3F114, 0x80000000}, + {2, 2, 0x3F118, 0x80000000}, + {2, 2, 0x3F120, 0x80000000}, + {2, 2, 0x3F128, 0x80000000}, + {2, 2, 0x3F13C, 0x80000000}, + {2, 2, 0x3F140, 0x80000000}, + {2, 2, 0x3F144, 0x80000000}, + {2, 2, 0x3F14C, 0x80000000}, + {2, 2, 0x3F150, 0x80000000}, + {2, 3, 0x3F004, 0x8000000A}, + {2, 3, 0x3F008, 0x80000014}, + {2, 3, 0x3F014, 0x80000016}, + {2, 3, 0x3F018, 0x80000012}, + {2, 3, 0x3F01C, 0x80000001}, + {2, 3, 0x3F024, 0x80000014}, + {2, 3, 0x3F038, 0x80000007}, + {2, 3, 0x3F040, 0x80000014}, + {2, 3, 0x3F048, 0x80000005}, + {2, 3, 0x3F058, 0x8000000F}, + {2, 3, 0x3F104, 0x80000000}, + {2, 3, 0x3F114, 0x80000000}, + {2, 3, 0x3F11C, 0x80000000}, + {2, 3, 0x3F128, 0x80000000}, + {2, 3, 0x3F13C, 0x80000000}, + {2, 3, 0x3F148, 0x80000000}, + {2, 3, 0x3F150, 0x80000000}, + {2, 3, 0x3F158, 0x80000000}, + {2, 4, 0x3F004, 0x80000006}, + {2, 4, 0x3F008, 0x80000008}, + {2, 4, 0x3F014, 0x8000000F}, + {2, 4, 0x3F020, 0x80000001}, + {2, 4, 0x3F040, 0x8000000A}, + {2, 4, 0x3F044, 0x80000008}, + {2, 4, 0x3F050, 0x80000006}, + {2, 4, 0x3F104, 0x80000000}, + {2, 4, 0x3F118, 0x80000000}, + {2, 4, 0x3F120, 0x80000000}, + {2, 4, 0x3F128, 0x80000000}, + {2, 4, 0x3F13C, 0x80000000}, + {2, 5, 0x3F004, 0x80000008}, + {2, 5, 0x3F008, 0x80000009}, + {2, 5, 0x3F014, 0x80000001}, + {2, 5, 0x3F024, 0x80000009}, + {2, 5, 0x3F050, 0x80000008}, + {2, 5, 0x3F104, 0x80000000}, + {2, 5, 0x3F120, 0x80000000}, + {2, 5, 0x3F124, 0x80000000}, + {3, 0, 0x3F008, 0xC0000045}, + {3, 0, 0x3F010, 0x80000010}, + {3, 0, 0x3F034, 0x80000005}, + {3, 0, 0x3F044, 0x80000009}, + {3, 0, 0x3F100, 0xC0000000}, + {3, 0, 0x3F114, 0x80000000}, + {3, 0, 0x3F124, 0x80000000}, + {3, 0, 0x3F140, 0x80000000}, + {3, 0, 0x3F200, 0x0F1F0135}, + {3, 1, 0xB0000, 0x80000008}, + {3, 1, 0xB0004, 0x8000000C}, + {3, 1, 0xB0008, 0x8000000E}, + {3, 1, 0xB000C, 0x8000000F}, + {3, 1, 0xB0010, 0x80000010}, + {3, 1, 0xB0014, 0x8000000D}, + {3, 1, 0xB0024, 0x80000005}, + {3, 1, 0xB0030, 0x80000000}, + {3, 1, 0xB0100, 0x80000000}, + {3, 1, 0xB0114, 0x80000000}, + {3, 1, 0xB0120, 0x80000000}, + {3, 1, 0xB0130, 0x80000000}, + {3, 1, 0xB0134, 0x80000000}, + {3, 1, 0xB0138, 0x80000000}, + {3, 1, 0xB013C, 0x80000000}, + {3, 1, 0xB0140, 0x80000000}, + {3, 2, 0x3F004, 0x8000000C}, + {3, 2, 0x3F008, 0x80000006}, + {3, 2, 0x3F014, 0x8000000F}, + {3, 2, 0x3F018, 0x8000000D}, + {3, 2, 0x3F01C, 0x80000010}, + {3, 2, 0x3F020, 0x80000012}, + {3, 2, 0x3F024, 0x80000006}, + {3, 2, 0x3F028, 0x80000001}, + {3, 2, 0x3F038, 0x8000000B}, + {3, 2, 0x3F044, 0x80000006}, + {3, 2, 0x3F104, 0x80000000}, + {3, 2, 0x3F118, 0x80000000}, + {3, 2, 0x3F12C, 0x80000000}, + {3, 2, 0x3F130, 0x80000000}, + {3, 2, 0x3F134, 0x80000000}, + {3, 2, 0x3F13C, 0x80000000}, + {3, 2, 0x3F140, 0x80000000}, + {3, 2, 0x3F148, 0x80000000}, + {3, 3, 0x3F004, 0x80000006}, + {3, 3, 0x3F008, 0x80000009}, + {3, 3, 0x3F014, 0x80000012}, + {3, 3, 0x3F018, 0x80000010}, + {3, 3, 0x3F020, 0x8000000E}, + {3, 3, 0x3F028, 0x80000009}, + {3, 3, 0x3F030, 0x80000001}, + {3, 3, 0x3F044, 0x80000009}, + {3, 3, 0x3F104, 0x80000000}, + {3, 3, 0x3F118, 0x80000000}, + {3, 3, 0x3F124, 0x80000000}, + {3, 3, 0x3F138, 0x80000000}, + {3, 3, 0x3F140, 0x80000000}, + {3, 3, 0x3F148, 0x80000000}, + {3, 4, 0x3F004, 0x8000000C}, + {3, 4, 0x3F008, 0x80000009}, + {3, 4, 0x3F018, 0x80000001}, + {3, 4, 0x3F020, 0x8000000F}, + {3, 4, 0x3F038, 0x80000009}, + {3, 4, 0x3F104, 0x80000000}, + {3, 4, 0x3F124, 0x80000000}, + {3, 4, 0x3F130, 0x80000000}, + {3, 4, 0x3F13C, 0x80000000}, + {3, 5, 0x3F004, 0x8000000C}, + {3, 5, 0x3F008, 0x80000006}, + {3, 5, 0x3F014, 0x80000001}, + {3, 5, 0x3F104, 0x80000000}, + {3, 5, 0x3F118, 0x80000000}, + {3, 5, 0x3F130, 0x80000000}, + {4, 0, 0x3F008, 0xC0000045}, + {4, 0, 0x3F010, 0x80000010}, + {4, 0, 0x3F034, 0x80000005}, + {4, 0, 0x3F044, 0x80000009}, + {4, 0, 0x3F100, 0xC0000000}, + {4, 0, 0x3F114, 0x80000000}, + {4, 0, 0x3F124, 0x80000000}, + {4, 0, 0x3F140, 0x80000000}, + {4, 0, 0x3F200, 0x0F1F0135}, + {4, 1, 0xB0000, 0x80000008}, + {4, 1, 0xB0004, 0x8000000C}, + {4, 1, 0xB0008, 0x8000000F}, + {4, 1, 0xB000C, 0x8000000E}, + {4, 1, 0xB0010, 0x8000000D}, + {4, 1, 0xB0014, 0x80000010}, + {4, 1, 0xB0024, 0x80000005}, + {4, 1, 0xB002C, 0x80000000}, + {4, 1, 0xB0030, 0x80000003}, + {4, 1, 0xB0038, 0x80000001}, + {4, 1, 0xB0040, 0x80000002}, + {4, 1, 0xB0100, 0x80000000}, + {4, 1, 0xB0104, 0x80000000}, + {4, 1, 0xB0108, 0x80000000}, + {4, 1, 0xB010C, 0x80000000}, + {4, 1, 0xB0114, 0x80000000}, + {4, 1, 0xB0120, 0x80000000}, + {4, 1, 0xB0130, 0x80000000}, + {4, 1, 0xB0134, 0x80000000}, + {4, 1, 0xB0138, 0x80000000}, + {4, 1, 0xB013C, 0x80000000}, + {4, 1, 0xB0140, 0x80000000}, + {4, 2, 0x3F004, 0x80000005}, + {4, 2, 0x3F008, 0x80000013}, + {4, 2, 0x3F014, 0x80000012}, + {4, 2, 0x3F018, 0x80000015}, + {4, 2, 0x3F01C, 0x80000001}, + {4, 2, 0x3F020, 0x80000010}, + {4, 2, 0x3F034, 0x80000008}, + {4, 2, 0x3F038, 0x80000006}, + {4, 2, 0x3F03C, 0x8000000A}, + {4, 2, 0x3F04C, 0x80000008}, + {4, 2, 0x3F050, 0x80000005}, + {4, 2, 0x3F054, 0x8000000A}, + {4, 2, 0x3F058, 0x80000011}, + {4, 2, 0x3F104, 0x80000000}, + {4, 2, 0x3F114, 0x80000000}, + {4, 2, 0x3F118, 0x80000000}, + {4, 2, 0x3F120, 0x80000000}, + {4, 2, 0x3F128, 0x80000000}, + {4, 2, 0x3F140, 0x80000000}, + {4, 2, 0x3F144, 0x80000000}, + {4, 2, 0x3F148, 0x80000000}, + {4, 2, 0x3F14C, 0x80000000}, + {4, 2, 0x3F154, 0x80000000}, + {4, 3, 0x3F004, 0x80000005}, + {4, 3, 0x3F008, 0x80000014}, + {4, 3, 0x3F018, 0x80000016}, + {4, 3, 0x3F01C, 0x80000012}, + {4, 3, 0x3F020, 0x80000001}, + {4, 3, 0x3F038, 0x80000006}, + {4, 3, 0x3F040, 0x80000007}, + {4, 3, 0x3F104, 0x80000000}, + {4, 3, 0x3F114, 0x80000000}, + {4, 3, 0x3F118, 0x80000000}, + {4, 3, 0x3F11C, 0x80000000}, + {4, 3, 0x3F148, 0x80000000}, + {4, 3, 0x3F150, 0x80000000}, + {4, 3, 0x3F158, 0x80000000}, + {4, 4, 0x3F004, 0x80000008}, + {4, 4, 0x3F008, 0x80000014}, + {4, 4, 0x3F020, 0x80000001}, + {4, 4, 0x3F03C, 0x80000006}, + {4, 4, 0x3F044, 0x80000014}, + {4, 4, 0x3F04C, 0x80000006}, + {4, 4, 0x3F104, 0x80000000}, + {4, 4, 0x3F118, 0x80000000}, + {4, 4, 0x3F120, 0x80000000}, + {4, 4, 0x3F150, 0x80000000}, + {4, 5, 0x3F004, 0x80000007}, + {4, 5, 0x3F008, 0x80000009}, + {4, 5, 0x3F058, 0x80000001}, + {4, 5, 0x3F104, 0x80000000}, + {4, 5, 0x3F11C, 0x80000000}, + {4, 5, 0x3F124, 0x80000000}, + {5, 0, 0x3F008, 0xC0000045}, + {5, 0, 0x3F010, 0x80000010}, + {5, 0, 0x3F100, 0xC0000000}, + {5, 0, 0x3F140, 0x80000000}, + {5, 0, 0x3F200, 0x0F1F0135}, + {5, 1, 0xB0008, 0x80000010}, + {5, 1, 0xB000C, 0x8000000F}, + {5, 1, 0xB0010, 0x8000000E}, + {5, 1, 0xB0014, 0x8000000D}, + {5, 1, 0xB0024, 0x80000005}, + {5, 1, 0xB0114, 0x80000000}, + {5, 1, 0xB0134, 0x80000000}, + {5, 1, 0xB0138, 0x80000000}, + {5, 1, 0xB013C, 0x80000000}, + {5, 1, 0xB0140, 0x80000000}, + {5, 2, 0x3F004, 0x8000000C}, + {5, 2, 0x3F008, 0x80000013}, + {5, 2, 0x3F014, 0x80000011}, + {5, 2, 0x3F018, 0x80000010}, + {5, 2, 0x3F01C, 0x8000000F}, + {5, 2, 0x3F020, 0x8000000E}, + {5, 2, 0x3F024, 0x80000013}, + {5, 2, 0x3F02C, 0x80000001}, + {5, 2, 0x3F034, 0x8000000B}, + {5, 2, 0x3F038, 0x8000000D}, + {5, 2, 0x3F044, 0x80000013}, + {5, 2, 0x3F104, 0x80000000}, + {5, 2, 0x3F12C, 0x80000000}, + {5, 2, 0x3F130, 0x80000000}, + {5, 2, 0x3F134, 0x80000000}, + {5, 2, 0x3F138, 0x80000000}, + {5, 2, 0x3F13C, 0x80000000}, + {5, 2, 0x3F140, 0x80000000}, + {5, 2, 0x3F144, 0x80000000}, + {5, 2, 0x3F14C, 0x80000000}, + {5, 3, 0x3F004, 0x80000005}, + {5, 3, 0x3F008, 0x80000009}, + {5, 3, 0x3F014, 0x80000012}, + {5, 3, 0x3F018, 0x80000010}, + {5, 3, 0x3F01C, 0x80000011}, + {5, 3, 0x3F028, 0x80000009}, + {5, 3, 0x3F030, 0x80000001}, + {5, 3, 0x3F038, 0x80000009}, + {5, 3, 0x3F048, 0x80000006}, + {5, 3, 0x3F104, 0x80000000}, + {5, 3, 0x3F114, 0x80000000}, + {5, 3, 0x3F118, 0x80000000}, + {5, 3, 0x3F124, 0x80000000}, + {5, 3, 0x3F140, 0x80000000}, + {5, 3, 0x3F144, 0x80000000}, + {5, 3, 0x3F148, 0x80000000}, + {5, 4, 0x3F004, 0x8000000A}, + {5, 4, 0x3F008, 0x80000006}, + {5, 4, 0x3F018, 0x80000011}, + {5, 4, 0x3F01C, 0x8000000F}, + {5, 4, 0x3F020, 0x80000001}, + {5, 4, 0x3F028, 0x80000006}, + {5, 4, 0x3F044, 0x8000000B}, + {5, 4, 0x3F048, 0x80000006}, + {5, 4, 0x3F104, 0x80000000}, + {5, 4, 0x3F118, 0x80000000}, + {5, 4, 0x3F128, 0x80000000}, + {5, 4, 0x3F12C, 0x80000000}, + {5, 4, 0x3F13C, 0x80000000}, + {5, 4, 0x3F144, 0x80000000}, + {5, 5, 0x3F004, 0x80000009}, + {5, 5, 0x3F008, 0x8000000A}, + {5, 5, 0x3F014, 0x80000001}, + {5, 5, 0x3F01C, 0x8000000E}, + {5, 5, 0x3F104, 0x80000000}, + {5, 5, 0x3F124, 0x80000000}, + {5, 5, 0x3F128, 0x80000000}, + {5, 5, 0x3F138, 0x80000000}, + {6, 0, 0x3F008, 0xC0000045}, + {6, 0, 0x3F010, 0x80000010}, + {6, 0, 0x3F034, 0x80000005}, + {6, 0, 0x3F044, 0x80000009}, + {6, 0, 0x3F100, 0xC0000000}, + {6, 0, 0x3F114, 0x80000000}, + {6, 0, 0x3F124, 0x80000000}, + {6, 0, 0x3F140, 0x80000000}, + {6, 0, 0x3F200, 0x0F1F0135}, + {6, 1, 0xB0000, 0x80000008}, + {6, 1, 0xB0004, 0x8000000C}, + {6, 1, 0xB0008, 0x8000000F}, + {6, 1, 0xB000C, 0x80000010}, + {6, 1, 0xB0010, 0x8000000E}, + {6, 1, 0xB0014, 0x8000000D}, + {6, 1, 0xB0024, 0x80000005}, + {6, 1, 0xB002C, 0x80000002}, + {6, 1, 0xB0030, 0x80000001}, + {6, 1, 0xB0034, 0x80000003}, + {6, 1, 0xB0038, 0x80000000}, + {6, 1, 0xB0100, 0x80000000}, + {6, 1, 0xB0104, 0x80000000}, + {6, 1, 0xB0108, 0x80000000}, + {6, 1, 0xB010C, 0x80000000}, + {6, 1, 0xB0114, 0x80000000}, + {6, 1, 0xB0120, 0x80000000}, + {6, 1, 0xB0130, 0x80000000}, + {6, 1, 0xB0134, 0x80000000}, + {6, 1, 0xB0138, 0x80000000}, + {6, 1, 0xB013C, 0x80000000}, + {6, 1, 0xB0140, 0x80000000}, + {6, 2, 0x3F004, 0x80000008}, + {6, 2, 0x3F008, 0x80000014}, + {6, 2, 0x3F014, 0x80000010}, + {6, 2, 0x3F018, 0x8000000F}, + {6, 2, 0x3F01C, 0x80000001}, + {6, 2, 0x3F020, 0x80000016}, + {6, 2, 0x3F024, 0x80000014}, + {6, 2, 0x3F034, 0x80000007}, + {6, 2, 0x3F03C, 0x80000005}, + {6, 2, 0x3F048, 0x80000006}, + {6, 2, 0x3F054, 0x80000012}, + {6, 2, 0x3F058, 0x80000008}, + {6, 2, 0x3F104, 0x80000000}, + {6, 2, 0x3F114, 0x80000000}, + {6, 2, 0x3F118, 0x80000000}, + {6, 2, 0x3F11C, 0x80000000}, + {6, 2, 0x3F120, 0x80000000}, + {6, 2, 0x3F13C, 0x80000000}, + {6, 2, 0x3F140, 0x80000000}, + {6, 2, 0x3F148, 0x80000000}, + {6, 2, 0x3F150, 0x80000000}, + {6, 2, 0x3F158, 0x80000000}, + {6, 3, 0x3F004, 0x8000000A}, + {6, 3, 0x3F008, 0x80000014}, + {6, 3, 0x3F014, 0x80000001}, + {6, 3, 0x3F018, 0x80000015}, + {6, 3, 0x3F020, 0x8000000F}, + {6, 3, 0x3F040, 0x80000005}, + {6, 3, 0x3F048, 0x80000007}, + {6, 3, 0x3F050, 0x8000000A}, + {6, 3, 0x3F104, 0x80000000}, + {6, 3, 0x3F114, 0x80000000}, + {6, 3, 0x3F11C, 0x80000000}, + {6, 3, 0x3F128, 0x80000000}, + {6, 3, 0x3F13C, 0x80000000}, + {6, 3, 0x3F150, 0x80000000}, + {6, 3, 0x3F154, 0x80000000}, + {6, 4, 0x3F004, 0x8000000A}, + {6, 4, 0x3F008, 0x80000014}, + {6, 4, 0x3F014, 0x8000000F}, + {6, 4, 0x3F038, 0x80000008}, + {6, 4, 0x3F04C, 0x80000001}, + {6, 4, 0x3F050, 0x8000000A}, + {6, 4, 0x3F104, 0x80000000}, + {6, 4, 0x3F120, 0x80000000}, + {6, 4, 0x3F128, 0x80000000}, + {6, 4, 0x3F13C, 0x80000000}, + {6, 4, 0x3F150, 0x80000000}, + {6, 5, 0x3F004, 0x80000006}, + {6, 5, 0x3F008, 0x80000015}, + {6, 5, 0x3F014, 0x80000001}, + {6, 5, 0x3F054, 0x80000006}, + {6, 5, 0x3F104, 0x80000000}, + {6, 5, 0x3F118, 0x80000000}, + {6, 5, 0x3F154, 0x80000000}, + {7, 0, 0x3F008, 0xC0000045}, + {7, 0, 0x3F010, 0x80000010}, + {7, 0, 0x3F030, 0x80000005}, + {7, 0, 0x3F034, 0x80000009}, + {7, 0, 0x3F100, 0xC0000000}, + {7, 0, 0x3F114, 0x80000000}, + {7, 0, 0x3F124, 0x80000000}, + {7, 0, 0x3F140, 0x80000000}, + {7, 0, 0x3F200, 0x0F1F0135}, + {7, 1, 0xB0000, 0x80000007}, + {7, 1, 0xB0004, 0x80000008}, + {7, 1, 0xB0008, 0x8000000D}, + {7, 1, 0xB000C, 0x8000000F}, + {7, 1, 0xB0010, 0x8000000E}, + {7, 1, 0xB0014, 0x80000010}, + {7, 1, 0xB0024, 0x80000005}, + {7, 1, 0xB0030, 0x80000000}, + {7, 1, 0xB0100, 0x80000000}, + {7, 1, 0xB0114, 0x80000000}, + {7, 1, 0xB011C, 0x80000000}, + {7, 1, 0xB0120, 0x80000000}, + {7, 1, 0xB0134, 0x80000000}, + {7, 1, 0xB0138, 0x80000000}, + {7, 1, 0xB013C, 0x80000000}, + {7, 1, 0xB0140, 0x80000000}, + {7, 2, 0x3F004, 0x8000000E}, + {7, 2, 0x3F008, 0x80000006}, + {7, 2, 0x3F014, 0x8000000F}, + {7, 2, 0x3F018, 0x8000000D}, + {7, 2, 0x3F01C, 0x80000011}, + {7, 2, 0x3F020, 0x80000012}, + {7, 2, 0x3F028, 0x80000006}, + {7, 2, 0x3F030, 0x80000001}, + {7, 2, 0x3F048, 0x80000006}, + {7, 2, 0x3F104, 0x80000000}, + {7, 2, 0x3F118, 0x80000000}, + {7, 2, 0x3F134, 0x80000000}, + {7, 2, 0x3F138, 0x80000000}, + {7, 2, 0x3F13C, 0x80000000}, + {7, 2, 0x3F144, 0x80000000}, + {7, 2, 0x3F148, 0x80000000}, + {7, 3, 0x3F004, 0x8000000C}, + {7, 3, 0x3F008, 0x8000000A}, + {7, 3, 0x3F014, 0x80000010}, + {7, 3, 0x3F01C, 0x80000011}, + {7, 3, 0x3F020, 0x80000012}, + {7, 3, 0x3F028, 0x8000000A}, + {7, 3, 0x3F02C, 0x80000001}, + {7, 3, 0x3F044, 0x8000000A}, + {7, 3, 0x3F104, 0x80000000}, + {7, 3, 0x3F128, 0x80000000}, + {7, 3, 0x3F130, 0x80000000}, + {7, 3, 0x3F140, 0x80000000}, + {7, 3, 0x3F144, 0x80000000}, + {7, 3, 0x3F148, 0x80000000}, + {7, 4, 0x3F004, 0x8000000C}, + {7, 4, 0x3F008, 0x80000009}, + {7, 4, 0x3F018, 0x8000000B}, + {7, 4, 0x3F01C, 0x80000001}, + {7, 4, 0x3F020, 0x8000000F}, + {7, 4, 0x3F028, 0x80000009}, + {7, 4, 0x3F03C, 0x80000009}, + {7, 4, 0x3F104, 0x80000000}, + {7, 4, 0x3F124, 0x80000000}, + {7, 4, 0x3F12C, 0x80000000}, + {7, 4, 0x3F130, 0x80000000}, + {7, 4, 0x3F13C, 0x80000000}, + {7, 5, 0x3F004, 0x8000000D}, + {7, 5, 0x3F008, 0x80000007}, + {7, 5, 0x3F014, 0x80000001}, + {7, 5, 0x3F02C, 0x80000007}, + {7, 5, 0x3F104, 0x80000000}, + {7, 5, 0x3F11C, 0x80000000}, + {7, 5, 0x3F134, 0x80000000}, + }, + // shim mux / demux mask writes: (col, row, offset, mask, value) + { + {0, 0, 0x1F000, 0x00000C00, 0x00000400}, + {0, 0, 0x1F000, 0x0000C000, 0x00004000}, + {0, 0, 0x1F004, 0x00000030, 0x00000010}, + {2, 0, 0x1F000, 0x00000C00, 0x00000400}, + {2, 0, 0x1F000, 0x0000C000, 0x00004000}, + {2, 0, 0x1F004, 0x00000030, 0x00000010}, + {4, 0, 0x1F000, 0x00000C00, 0x00000400}, + {4, 0, 0x1F000, 0x0000C000, 0x00004000}, + {4, 0, 0x1F004, 0x00000030, 0x00000010}, + {6, 0, 0x1F000, 0x00000C00, 0x00000400}, + {6, 0, 0x1F000, 0x0000C000, 0x00004000}, + {6, 0, 0x1F004, 0x00000030, 0x00000010}, + {3, 0, 0x1F000, 0x00000C00, 0x00000400}, + {3, 0, 0x1F000, 0x0000C000, 0x00004000}, + {3, 0, 0x1F004, 0x00000030, 0x00000010}, + {7, 0, 0x1F000, 0x00000C00, 0x00000400}, + {7, 0, 0x1F000, 0x0000C000, 0x00004000}, + {7, 0, 0x1F004, 0x00000030, 0x00000010}, + {1, 0, 0x1F004, 0x00000030, 0x00000010}, + {5, 0, 0x1F004, 0x00000030, 0x00000010}, + }, + // BD registers: (col, row, offset, shared, words) + { + {0, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {0, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {0, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {0, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {0, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {0, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {0, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {0, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {0, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {0, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {0, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {0, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {0, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {0, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {0, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {0, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {0, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {0, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {0, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {0, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {1, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {1, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {1, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {1, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {1, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {1, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {1, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {1, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {1, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {1, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {1, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {1, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {1, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {1, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {1, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {1, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {1, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {1, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {1, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {1, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {2, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {2, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {2, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {2, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {2, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {2, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {2, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {2, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {2, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {2, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {2, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {2, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {2, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {2, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {2, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {2, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {2, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {2, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {2, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {2, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {3, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {3, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {3, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {3, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {3, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {3, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {3, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {3, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {3, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {3, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {3, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {3, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {3, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {3, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {3, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {3, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {3, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {3, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {3, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {3, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {4, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {4, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {4, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {4, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {4, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {4, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {4, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {4, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {4, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {4, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {4, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {4, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {4, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {4, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {4, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {4, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {4, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {4, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {4, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {4, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {5, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {5, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {5, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {5, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {5, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {5, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {5, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {5, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {5, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {5, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {5, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {5, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {5, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {5, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {5, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {5, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {5, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {5, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {5, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {5, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {6, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {6, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {6, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {6, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {6, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {6, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {6, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {6, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {6, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {6, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {6, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {6, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {6, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {6, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {6, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {6, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {6, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {6, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {6, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {6, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {7, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {7, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {7, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {7, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {7, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {7, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {7, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {7, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {7, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {7, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {7, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {7, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {7, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {7, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {7, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {7, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {7, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {7, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {7, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {7, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {0, 1, 0xA01C0, false, {0x00001000, 0x00FA0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {0, 1, 0xA0480, false, {0x00001000, 0x025A1000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {0, 1, 0xA0200, false, {0x00000800, 0x011A0000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {0, 1, 0xA04C0, false, {0x00000800, 0x027A0800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {0, 1, 0xA0240, false, {0x00000800, 0x013A1000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {0, 1, 0xA0500, false, {0x00000800, 0x029A1800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {0, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {0, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {0, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {0, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {0, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {0, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {0, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {0, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {0, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {0, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {0, 1, 0xA0520, false, {0x00000800, 0x028A5800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {0, 1, 0xA0260, false, {0x00000800, 0x012A5000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {0, 1, 0xA04E0, false, {0x00000800, 0x026A4800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {0, 1, 0xA0220, false, {0x00000800, 0x010A4000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {0, 1, 0xA04A0, false, {0x00001000, 0x024A5000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {0, 1, 0xA01E0, false, {0x00001000, 0x00EA4000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0200, false, {0x00002000, 0x011A0000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0500, false, {0x00002000, 0x029A2000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0240, false, {0x00004000, 0x013A0000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {1, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {1, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {1, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {1, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {1, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {1, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {1, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {1, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {1, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {1, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {1, 1, 0xA0260, false, {0x00004000, 0x012A4000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {1, 1, 0xA0520, false, {0x00002000, 0x028A6000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0220, false, {0x00002000, 0x010A4000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {2, 1, 0xA01C0, false, {0x00001000, 0x00FA0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {2, 1, 0xA0480, false, {0x00001000, 0x025A1000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {2, 1, 0xA0200, false, {0x00000800, 0x011A0000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {2, 1, 0xA04C0, false, {0x00000800, 0x027A0800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {2, 1, 0xA0240, false, {0x00000800, 0x013A1000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {2, 1, 0xA0500, false, {0x00000800, 0x029A1800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {2, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {2, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {2, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {2, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {2, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {2, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {2, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {2, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {2, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {2, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {2, 1, 0xA0520, false, {0x00000800, 0x028A5800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {2, 1, 0xA0260, false, {0x00000800, 0x012A5000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {2, 1, 0xA04E0, false, {0x00000800, 0x026A4800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {2, 1, 0xA0220, false, {0x00000800, 0x010A4000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {2, 1, 0xA04A0, false, {0x00001000, 0x024A5000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {2, 1, 0xA01E0, false, {0x00001000, 0x00EA4000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0200, false, {0x00002000, 0x011A0000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0500, false, {0x00002000, 0x029A2000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0240, false, {0x00004000, 0x013A0000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {3, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {3, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {3, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {3, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {3, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {3, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {3, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {3, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {3, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {3, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {3, 1, 0xA0260, false, {0x00004000, 0x012A4000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {3, 1, 0xA0520, false, {0x00002000, 0x028A6000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0220, false, {0x00002000, 0x010A4000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {4, 1, 0xA01C0, false, {0x00001000, 0x00FA0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {4, 1, 0xA0480, false, {0x00001000, 0x025A1000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {4, 1, 0xA0200, false, {0x00000800, 0x011A0000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {4, 1, 0xA04C0, false, {0x00000800, 0x027A0800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {4, 1, 0xA0240, false, {0x00000800, 0x013A1000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {4, 1, 0xA0500, false, {0x00000800, 0x029A1800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {4, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {4, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {4, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {4, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {4, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {4, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {4, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {4, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {4, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {4, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {4, 1, 0xA0520, false, {0x00000800, 0x028A5800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {4, 1, 0xA0260, false, {0x00000800, 0x012A5000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {4, 1, 0xA04E0, false, {0x00000800, 0x026A4800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {4, 1, 0xA0220, false, {0x00000800, 0x010A4000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {4, 1, 0xA04A0, false, {0x00001000, 0x024A5000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {4, 1, 0xA01E0, false, {0x00001000, 0x00EA4000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0200, false, {0x00002000, 0x011A0000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0500, false, {0x00002000, 0x029A2000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0240, false, {0x00004000, 0x013A0000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {5, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {5, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {5, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {5, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {5, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {5, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {5, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {5, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {5, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {5, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {5, 1, 0xA0260, false, {0x00004000, 0x012A4000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {5, 1, 0xA0520, false, {0x00002000, 0x028A6000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0220, false, {0x00002000, 0x010A4000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {6, 1, 0xA01C0, false, {0x00001000, 0x00FA0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {6, 1, 0xA0480, false, {0x00001000, 0x025A1000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {6, 1, 0xA0200, false, {0x00000800, 0x011A0000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {6, 1, 0xA04C0, false, {0x00000800, 0x027A0800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {6, 1, 0xA0240, false, {0x00000800, 0x013A1000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {6, 1, 0xA0500, false, {0x00000800, 0x029A1800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {6, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {6, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {6, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {6, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {6, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {6, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {6, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {6, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {6, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {6, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {6, 1, 0xA0520, false, {0x00000800, 0x028A5800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {6, 1, 0xA0260, false, {0x00000800, 0x012A5000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {6, 1, 0xA04E0, false, {0x00000800, 0x026A4800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {6, 1, 0xA0220, false, {0x00000800, 0x010A4000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {6, 1, 0xA04A0, false, {0x00001000, 0x024A5000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {6, 1, 0xA01E0, false, {0x00001000, 0x00EA4000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0200, false, {0x00002000, 0x011A0000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0500, false, {0x00002000, 0x029A2000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0240, false, {0x00004000, 0x013A0000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {7, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {7, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {7, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {7, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {7, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {7, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {7, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {7, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {7, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {7, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {7, 1, 0xA0260, false, {0x00004000, 0x012A4000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {7, 1, 0xA0520, false, {0x00002000, 0x028A6000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0220, false, {0x00002000, 0x010A4000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + }, + // lock values: (col, row, offset, value) + { + {0, 1, 0xC0000, 2}, + {0, 1, 0xC0010, 0}, + {0, 1, 0xC0030, 0}, + {0, 1, 0xC0040, 2}, + {0, 1, 0xC0050, 0}, + {0, 1, 0xC0060, 0}, + {0, 1, 0xC0070, 2}, + {0, 1, 0xC0080, 0}, + {0, 1, 0xC0090, 0}, + {0, 1, 0xC00A0, 0}, + {0, 1, 0xC00B0, 0}, + {0, 2, 0x1F000, 1}, + {0, 2, 0x1F010, 0}, + {0, 2, 0x1F020, 2}, + {0, 2, 0x1F030, 0}, + {0, 2, 0x1F040, 2}, + {0, 2, 0x1F050, 0}, + {0, 2, 0x1F0F0, 0}, + {0, 3, 0x1F000, 1}, + {0, 3, 0x1F010, 0}, + {0, 3, 0x1F020, 2}, + {0, 3, 0x1F030, 0}, + {0, 3, 0x1F040, 2}, + {0, 3, 0x1F050, 0}, + {0, 3, 0x1F0F0, 0}, + {0, 4, 0x1F000, 1}, + {0, 4, 0x1F010, 0}, + {0, 4, 0x1F020, 2}, + {0, 4, 0x1F030, 0}, + {0, 4, 0x1F040, 2}, + {0, 4, 0x1F050, 0}, + {0, 4, 0x1F0F0, 0}, + {0, 5, 0x1F000, 1}, + {0, 5, 0x1F010, 0}, + {0, 5, 0x1F020, 2}, + {0, 5, 0x1F030, 0}, + {0, 5, 0x1F040, 2}, + {0, 5, 0x1F050, 0}, + {0, 5, 0x1F0F0, 0}, + {1, 1, 0xC0000, 4}, + {1, 1, 0xC0010, 0}, + {1, 1, 0xC0020, 2}, + {1, 1, 0xC0030, 0}, + {1, 1, 0xC0040, 0}, + {1, 1, 0xC0050, 0}, + {1, 1, 0xC0060, 0}, + {1, 2, 0x1F000, 1}, + {1, 2, 0x1F010, 0}, + {1, 2, 0x1F020, 2}, + {1, 2, 0x1F030, 0}, + {1, 2, 0x1F040, 2}, + {1, 2, 0x1F050, 0}, + {1, 2, 0x1F0F0, 0}, + {1, 3, 0x1F000, 1}, + {1, 3, 0x1F010, 0}, + {1, 3, 0x1F020, 2}, + {1, 3, 0x1F030, 0}, + {1, 3, 0x1F040, 2}, + {1, 3, 0x1F050, 0}, + {1, 3, 0x1F0F0, 0}, + {1, 4, 0x1F000, 1}, + {1, 4, 0x1F010, 0}, + {1, 4, 0x1F020, 2}, + {1, 4, 0x1F030, 0}, + {1, 4, 0x1F040, 2}, + {1, 4, 0x1F050, 0}, + {1, 4, 0x1F0F0, 0}, + {1, 5, 0x1F000, 1}, + {1, 5, 0x1F010, 0}, + {1, 5, 0x1F020, 2}, + {1, 5, 0x1F030, 0}, + {1, 5, 0x1F040, 2}, + {1, 5, 0x1F050, 0}, + {1, 5, 0x1F0F0, 0}, + {2, 1, 0xC0000, 2}, + {2, 1, 0xC0010, 0}, + {2, 1, 0xC0030, 0}, + {2, 1, 0xC0040, 2}, + {2, 1, 0xC0050, 0}, + {2, 1, 0xC0060, 0}, + {2, 1, 0xC0070, 2}, + {2, 1, 0xC0080, 0}, + {2, 1, 0xC0090, 0}, + {2, 1, 0xC00A0, 0}, + {2, 1, 0xC00B0, 0}, + {2, 2, 0x1F000, 1}, + {2, 2, 0x1F010, 0}, + {2, 2, 0x1F020, 2}, + {2, 2, 0x1F030, 0}, + {2, 2, 0x1F040, 2}, + {2, 2, 0x1F050, 0}, + {2, 2, 0x1F0F0, 0}, + {2, 3, 0x1F000, 1}, + {2, 3, 0x1F010, 0}, + {2, 3, 0x1F020, 2}, + {2, 3, 0x1F030, 0}, + {2, 3, 0x1F040, 2}, + {2, 3, 0x1F050, 0}, + {2, 3, 0x1F0F0, 0}, + {2, 4, 0x1F000, 1}, + {2, 4, 0x1F010, 0}, + {2, 4, 0x1F020, 2}, + {2, 4, 0x1F030, 0}, + {2, 4, 0x1F040, 2}, + {2, 4, 0x1F050, 0}, + {2, 4, 0x1F0F0, 0}, + {2, 5, 0x1F000, 1}, + {2, 5, 0x1F010, 0}, + {2, 5, 0x1F020, 2}, + {2, 5, 0x1F030, 0}, + {2, 5, 0x1F040, 2}, + {2, 5, 0x1F050, 0}, + {2, 5, 0x1F0F0, 0}, + {3, 1, 0xC0000, 4}, + {3, 1, 0xC0010, 0}, + {3, 1, 0xC0020, 2}, + {3, 1, 0xC0030, 0}, + {3, 1, 0xC0040, 0}, + {3, 1, 0xC0050, 0}, + {3, 1, 0xC0060, 0}, + {3, 2, 0x1F000, 1}, + {3, 2, 0x1F010, 0}, + {3, 2, 0x1F020, 2}, + {3, 2, 0x1F030, 0}, + {3, 2, 0x1F040, 2}, + {3, 2, 0x1F050, 0}, + {3, 2, 0x1F0F0, 0}, + {3, 3, 0x1F000, 1}, + {3, 3, 0x1F010, 0}, + {3, 3, 0x1F020, 2}, + {3, 3, 0x1F030, 0}, + {3, 3, 0x1F040, 2}, + {3, 3, 0x1F050, 0}, + {3, 3, 0x1F0F0, 0}, + {3, 4, 0x1F000, 1}, + {3, 4, 0x1F010, 0}, + {3, 4, 0x1F020, 2}, + {3, 4, 0x1F030, 0}, + {3, 4, 0x1F040, 2}, + {3, 4, 0x1F050, 0}, + {3, 4, 0x1F0F0, 0}, + {3, 5, 0x1F000, 1}, + {3, 5, 0x1F010, 0}, + {3, 5, 0x1F020, 2}, + {3, 5, 0x1F030, 0}, + {3, 5, 0x1F040, 2}, + {3, 5, 0x1F050, 0}, + {3, 5, 0x1F0F0, 0}, + {4, 1, 0xC0000, 2}, + {4, 1, 0xC0010, 0}, + {4, 1, 0xC0030, 0}, + {4, 1, 0xC0040, 2}, + {4, 1, 0xC0050, 0}, + {4, 1, 0xC0060, 0}, + {4, 1, 0xC0070, 2}, + {4, 1, 0xC0080, 0}, + {4, 1, 0xC0090, 0}, + {4, 1, 0xC00A0, 0}, + {4, 1, 0xC00B0, 0}, + {4, 2, 0x1F000, 1}, + {4, 2, 0x1F010, 0}, + {4, 2, 0x1F020, 2}, + {4, 2, 0x1F030, 0}, + {4, 2, 0x1F040, 2}, + {4, 2, 0x1F050, 0}, + {4, 2, 0x1F0F0, 0}, + {4, 3, 0x1F000, 1}, + {4, 3, 0x1F010, 0}, + {4, 3, 0x1F020, 2}, + {4, 3, 0x1F030, 0}, + {4, 3, 0x1F040, 2}, + {4, 3, 0x1F050, 0}, + {4, 3, 0x1F0F0, 0}, + {4, 4, 0x1F000, 1}, + {4, 4, 0x1F010, 0}, + {4, 4, 0x1F020, 2}, + {4, 4, 0x1F030, 0}, + {4, 4, 0x1F040, 2}, + {4, 4, 0x1F050, 0}, + {4, 4, 0x1F0F0, 0}, + {4, 5, 0x1F000, 1}, + {4, 5, 0x1F010, 0}, + {4, 5, 0x1F020, 2}, + {4, 5, 0x1F030, 0}, + {4, 5, 0x1F040, 2}, + {4, 5, 0x1F050, 0}, + {4, 5, 0x1F0F0, 0}, + {5, 1, 0xC0000, 4}, + {5, 1, 0xC0010, 0}, + {5, 1, 0xC0020, 2}, + {5, 1, 0xC0030, 0}, + {5, 1, 0xC0040, 0}, + {5, 1, 0xC0050, 0}, + {5, 1, 0xC0060, 0}, + {5, 2, 0x1F000, 1}, + {5, 2, 0x1F010, 0}, + {5, 2, 0x1F020, 2}, + {5, 2, 0x1F030, 0}, + {5, 2, 0x1F040, 2}, + {5, 2, 0x1F050, 0}, + {5, 2, 0x1F0F0, 0}, + {5, 3, 0x1F000, 1}, + {5, 3, 0x1F010, 0}, + {5, 3, 0x1F020, 2}, + {5, 3, 0x1F030, 0}, + {5, 3, 0x1F040, 2}, + {5, 3, 0x1F050, 0}, + {5, 3, 0x1F0F0, 0}, + {5, 4, 0x1F000, 1}, + {5, 4, 0x1F010, 0}, + {5, 4, 0x1F020, 2}, + {5, 4, 0x1F030, 0}, + {5, 4, 0x1F040, 2}, + {5, 4, 0x1F050, 0}, + {5, 4, 0x1F0F0, 0}, + {5, 5, 0x1F000, 1}, + {5, 5, 0x1F010, 0}, + {5, 5, 0x1F020, 2}, + {5, 5, 0x1F030, 0}, + {5, 5, 0x1F040, 2}, + {5, 5, 0x1F050, 0}, + {5, 5, 0x1F0F0, 0}, + {6, 1, 0xC0000, 2}, + {6, 1, 0xC0010, 0}, + {6, 1, 0xC0030, 0}, + {6, 1, 0xC0040, 2}, + {6, 1, 0xC0050, 0}, + {6, 1, 0xC0060, 0}, + {6, 1, 0xC0070, 2}, + {6, 1, 0xC0080, 0}, + {6, 1, 0xC0090, 0}, + {6, 1, 0xC00A0, 0}, + {6, 1, 0xC00B0, 0}, + {6, 2, 0x1F000, 1}, + {6, 2, 0x1F010, 0}, + {6, 2, 0x1F020, 2}, + {6, 2, 0x1F030, 0}, + {6, 2, 0x1F040, 2}, + {6, 2, 0x1F050, 0}, + {6, 2, 0x1F0F0, 0}, + {6, 3, 0x1F000, 1}, + {6, 3, 0x1F010, 0}, + {6, 3, 0x1F020, 2}, + {6, 3, 0x1F030, 0}, + {6, 3, 0x1F040, 2}, + {6, 3, 0x1F050, 0}, + {6, 3, 0x1F0F0, 0}, + {6, 4, 0x1F000, 1}, + {6, 4, 0x1F010, 0}, + {6, 4, 0x1F020, 2}, + {6, 4, 0x1F030, 0}, + {6, 4, 0x1F040, 2}, + {6, 4, 0x1F050, 0}, + {6, 4, 0x1F0F0, 0}, + {6, 5, 0x1F000, 1}, + {6, 5, 0x1F010, 0}, + {6, 5, 0x1F020, 2}, + {6, 5, 0x1F030, 0}, + {6, 5, 0x1F040, 2}, + {6, 5, 0x1F050, 0}, + {6, 5, 0x1F0F0, 0}, + {7, 1, 0xC0000, 4}, + {7, 1, 0xC0010, 0}, + {7, 1, 0xC0020, 2}, + {7, 1, 0xC0030, 0}, + {7, 1, 0xC0040, 0}, + {7, 1, 0xC0050, 0}, + {7, 1, 0xC0060, 0}, + {7, 2, 0x1F000, 1}, + {7, 2, 0x1F010, 0}, + {7, 2, 0x1F020, 2}, + {7, 2, 0x1F030, 0}, + {7, 2, 0x1F040, 2}, + {7, 2, 0x1F050, 0}, + {7, 2, 0x1F0F0, 0}, + {7, 3, 0x1F000, 1}, + {7, 3, 0x1F010, 0}, + {7, 3, 0x1F020, 2}, + {7, 3, 0x1F030, 0}, + {7, 3, 0x1F040, 2}, + {7, 3, 0x1F050, 0}, + {7, 3, 0x1F0F0, 0}, + {7, 4, 0x1F000, 1}, + {7, 4, 0x1F010, 0}, + {7, 4, 0x1F020, 2}, + {7, 4, 0x1F030, 0}, + {7, 4, 0x1F040, 2}, + {7, 4, 0x1F050, 0}, + {7, 4, 0x1F0F0, 0}, + {7, 5, 0x1F000, 1}, + {7, 5, 0x1F010, 0}, + {7, 5, 0x1F020, 2}, + {7, 5, 0x1F030, 0}, + {7, 5, 0x1F040, 2}, + {7, 5, 0x1F050, 0}, + {7, 5, 0x1F0F0, 0}, + }, + // channels: (col, row, control offset, start queue offset, queue value, control value) + { + {0, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {0, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {0, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {0, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {0, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {0, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {0, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {0, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {0, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {0, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {0, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {0, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {1, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {1, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {1, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {1, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {1, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {1, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {1, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {1, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {1, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {1, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {1, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {1, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {2, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {2, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {2, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {2, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {2, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {2, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {2, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {2, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {2, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {2, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {2, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {2, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {3, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {3, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {3, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {3, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {3, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {3, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {3, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {3, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {3, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {3, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {3, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {3, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {4, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {4, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {4, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {4, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {4, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {4, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {4, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {4, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {4, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {4, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {4, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {4, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {5, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {5, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {5, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {5, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {5, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {5, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {5, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {5, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {5, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {5, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {5, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {5, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {6, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {6, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {6, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {6, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {6, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {6, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {6, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {6, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {6, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {6, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {6, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {6, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {7, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {7, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {7, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {7, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {7, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {7, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {7, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {7, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {7, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {7, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {7, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {7, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {0, 1, 0xA0600, 0xA0604, 0x0000000E, 1}, + {0, 1, 0xA0608, 0xA060C, 0x00000024, 1}, + {0, 1, 0xA0630, 0xA0634, 0x00000010, 1}, + {0, 1, 0xA0638, 0xA063C, 0x00000026, 1}, + {0, 1, 0xA0640, 0xA0644, 0x00000012, 1}, + {0, 1, 0xA0648, 0xA064C, 0x00000028, 1}, + {0, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {0, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {0, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {0, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {0, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {1, 1, 0xA0600, 0xA0604, 0x00000010, 1}, + {1, 1, 0xA0608, 0xA060C, 0x00000028, 1}, + {1, 1, 0xA0630, 0xA0634, 0x00000012, 1}, + {1, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {1, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {1, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {1, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {1, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {2, 1, 0xA0600, 0xA0604, 0x0000000E, 1}, + {2, 1, 0xA0608, 0xA060C, 0x00000024, 1}, + {2, 1, 0xA0630, 0xA0634, 0x00000010, 1}, + {2, 1, 0xA0638, 0xA063C, 0x00000026, 1}, + {2, 1, 0xA0640, 0xA0644, 0x00000012, 1}, + {2, 1, 0xA0648, 0xA064C, 0x00000028, 1}, + {2, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {2, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {2, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {2, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {2, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {3, 1, 0xA0600, 0xA0604, 0x00000010, 1}, + {3, 1, 0xA0608, 0xA060C, 0x00000028, 1}, + {3, 1, 0xA0630, 0xA0634, 0x00000012, 1}, + {3, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {3, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {3, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {3, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {3, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {4, 1, 0xA0600, 0xA0604, 0x0000000E, 1}, + {4, 1, 0xA0608, 0xA060C, 0x00000024, 1}, + {4, 1, 0xA0630, 0xA0634, 0x00000010, 1}, + {4, 1, 0xA0638, 0xA063C, 0x00000026, 1}, + {4, 1, 0xA0640, 0xA0644, 0x00000012, 1}, + {4, 1, 0xA0648, 0xA064C, 0x00000028, 1}, + {4, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {4, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {4, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {4, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {4, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {5, 1, 0xA0600, 0xA0604, 0x00000010, 1}, + {5, 1, 0xA0608, 0xA060C, 0x00000028, 1}, + {5, 1, 0xA0630, 0xA0634, 0x00000012, 1}, + {5, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {5, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {5, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {5, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {5, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {6, 1, 0xA0600, 0xA0604, 0x0000000E, 1}, + {6, 1, 0xA0608, 0xA060C, 0x00000024, 1}, + {6, 1, 0xA0630, 0xA0634, 0x00000010, 1}, + {6, 1, 0xA0638, 0xA063C, 0x00000026, 1}, + {6, 1, 0xA0640, 0xA0644, 0x00000012, 1}, + {6, 1, 0xA0648, 0xA064C, 0x00000028, 1}, + {6, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {6, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {6, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {6, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {6, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {7, 1, 0xA0600, 0xA0604, 0x00000010, 1}, + {7, 1, 0xA0608, 0xA060C, 0x00000028, 1}, + {7, 1, 0xA0630, 0xA0634, 0x00000012, 1}, + {7, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {7, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {7, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {7, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {7, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + }, +}; diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill.cpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill.cpp new file mode 100644 index 000000000..8ed4349ff --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill.cpp @@ -0,0 +1,760 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_prefill.cpp +/// \brief Batched prefill of MiniCPM5-15B-A2.5B, see minicpm5_moe_prefill.hpp +#include +#include +#include +#include "minicpm5_moe_prefill.hpp" + +using namespace minicpm5_moe_cpu; + +namespace { +const bool time_host = std::getenv("MC5_TIME_HOST") != nullptr; +// MINICPM5_MOE_ATTN_HOST / MINICPM5_MOE_MM_HOST = 1: that stage on the host instead (for comparisons) +const bool attn_forced_host = std::getenv("MINICPM5_MOE_ATTN_HOST") != nullptr; +const bool mm_forced_host = std::getenv("MINICPM5_MOE_MM_HOST") != nullptr; +// MC5_MM_CHECK=1: every NPU dequant_mm also on the host, cosine printed +const int mm_check = std::getenv("MC5_MM_CHECK") ? std::atoi(std::getenv("MC5_MM_CHECK")) : 0; +// MINICPM5_MOE_HOST_GLU=1: the batched experts' GLU on the host (up|gate out of the +// NPU) instead of fused into the up_gate run; MC5_BATCH_CHECK=1: every batched run +// checked against the host, cosine printed +const bool host_glu = std::getenv("MINICPM5_MOE_HOST_GLU") != nullptr; +const bool batch_check = std::getenv("MC5_BATCH_CHECK") != nullptr; +// Shortest prompt chunk whose routed experts go to the overlay (MINICPM5_MOE_MM_NPU_MIN). +// 0 = always, which is the default: the prefill is meant to run on the NPU, and a +// size-dependent fallback would also make the path depend on how a prompt was +// chunked. Set it to e.g. 1024 to put short chunks' experts back on the host. +const int mm_npu_min = std::getenv("MINICPM5_MOE_MM_NPU_MIN") ? std::atoi(std::getenv("MINICPM5_MOE_MM_NPU_MIN")) : 0; +using host_clock = std::chrono::steady_clock; + +/// \brief adds the time since `t` to `acc` and moves `t` on +void lap(double& acc, host_clock::time_point& t) { + const host_clock::time_point now = host_clock::now(); + acc += std::chrono::duration(now - t).count(); + t = now; +} + +/// \brief bytes of one routed expert in the proj buffer: its up and gate (512 rows +/// each, D columns) and its down (D rows, 512 columns) +size_t expert_gate_up_bytes(const minicpm5_moe_desc& d) { return 2 * (size_t)(d.expert_width / 32) * (d.D / 256) * Q4K_BLOCK; } +size_t expert_down_bytes(const minicpm5_moe_desc& d) { return (size_t)(d.D / 32) * (d.expert_width / 256) * Q4K_BLOCK; } + +/// the batched experts' buffer sets, as overlay batch_buffer() indices: x (and the +/// down output) 3, the up_gate output (host GLU only) 2, the GLU output 2 +enum { X_SET = 0, F_SET = 3, H_SET = 5, SETS = 7 }; +} // namespace + +// ============================================================================= +// weight views +// ============================================================================= +q4k_matrix minicpm5_moe_prefill_context::kvqg(int layer, const buffer& proj) const { + q4k_matrix m; + m.base = proj.data() + desc.layer_def(layer).attn_k.offset; + m.K = desc.D; + m.N = kvqg_stride(desc); // k, v, q, gate back to back, each reorder_cpy(.., 2) on its own + m.relaid = true; + return m; +} + +q4k_matrix minicpm5_moe_prefill_context::o(int layer, const buffer& proj) const { + q4k_matrix m; + m.base = proj.data() + desc.layer_def(layer).attn_output.offset; + m.K = desc.DQ; + m.N = desc.D; + m.relaid = true; + return m; +} + +q4k_matrix minicpm5_moe_prefill_context::up_gate(int layer, const buffer& proj) const { + q4k_matrix m; + m.base = proj.data() + desc.layer_def(layer).ffn_up_shexp.offset; + m.K = desc.D; + m.N = 2 * desc.expert_width; // [up 256 | gate 256] per round + m.relaid = true; + return m; +} + +q4k_matrix minicpm5_moe_prefill_context::down(int layer, const buffer& proj) const { + q4k_matrix m; + m.base = proj.data() + desc.layer_def(layer).ffn_down_shexp.offset; + m.K = desc.expert_width; + m.N = desc.D; + m.relaid = true; + return m; +} + +q4k_matrix minicpm5_moe_prefill_context::expert_up_gate(int layer, int expert, const buffer& proj) const { + const size_t expert_bytes = expert_gate_up_bytes(desc) + expert_down_bytes(desc); + q4k_matrix m; + m.base = proj.data() + desc.layer_def(layer).ffn_up_exps.offset + expert * expert_bytes; + m.K = desc.D; + m.N = 2 * desc.expert_width; // [up 64 | gate 64] per round + m.kind = q4k_matrix::expert_channels; + m.relaid = true; + m.channel_bytes = expert_bytes / 2; + m.part_offset = 0; // each stream starts with its gate/up blocks + return m; +} + +q4k_matrix minicpm5_moe_prefill_context::expert_down(int layer, int expert, const buffer& proj) const { + q4k_matrix m = expert_up_gate(layer, expert, proj); + m.K = desc.expert_width; + m.N = desc.D; + m.part_offset = expert_gate_up_bytes(desc) / 2; // ... then its down blocks + return m; +} + +// ============================================================================= +// forward +// ============================================================================= +void minicpm5_moe_prefill_context::_reserve(int L) { + if (L <= capacity) return; + capacity = L; + const size_t D = desc.D; + const size_t W = desc.expert_width; + xn.resize((size_t)L * D); + kvq_out.resize((size_t)L * kvqg_stride(desc)); + attn_out.resize((size_t)L * desc.DQ); + proj_out.resize((size_t)L * D); + fused.resize((size_t)L * 2 * W); + hid.resize((size_t)L * W); + logits.resize((size_t)L * desc.num_experts); + moe_sum.resize((size_t)L * D); +} + +void minicpm5_moe_prefill_context::prewarm(int L) { + _reserve(L); + prefill_pool(); // its threads start here + if (!overlay || !MINICPM5_MOE_MM_ON_NPU || mm_forced_host) return; + + // A MoE layer's batch rows (the dense layer has fewer): the shared expert's, then + // every routed expert's at an even share of the L * top_k routed tokens. A group + // closes on the job that reaches its share of them, the shared expert's at most. + using overlay_t = minicpm5_moe_prefill_overlay; + const int per_expert = (int)(((size_t)L * desc.top_k + desc.num_experts - 1) / desc.num_experts); + const size_t total = overlay_t::dq_rows(L) + (size_t)desc.num_experts * overlay_t::dq_rows(per_expert); + const int G = std::max(1, batch_groups); + const size_t rows = (total + G - 1) / G + overlay_t::dq_rows(L); + for (int g = 0; g < std::min(G, 3); g++) overlay->batch_buffer(X_SET + g, rows * desc.D); + for (int g = 0; g < std::min(G, 2); g++) { + if (host_glu) overlay->batch_buffer(F_SET + g, rows * 2 * desc.expert_width); + overlay->batch_buffer(H_SET + g, rows * desc.expert_width); + } + overlay->batch_slots(2 * G); +} + +void minicpm5_moe_prefill_context::forward(bf16* x, int L, int pos0, std::vector& layers, uint32_t MAX_L) { + _reserve(L); + std::fill(std::begin(stage_us), std::end(stage_us), 0.0); + if (overlay) { + overlay->seq_us = overlay->elf_us = overlay->run_us = 0.0; + overlay->sync_us = overlay->copy_us = overlay->mm_us = overlay->attn_us = 0.0; + } + const host_clock::time_point t0 = host_clock::now(); + + // the attention run is the same for every layer of this chunk (each on its own cache) + attn_on_npu = MINICPM5_MOE_ATTN_ON_NPU && overlay && !attn_forced_host; + mm_on_npu = MINICPM5_MOE_MM_ON_NPU && overlay && !mm_forced_host; + // The routed experts run on the overlay like everything else (mm_npu_min 0). + // A run is a whole number of 256-token rounds and an expert only sees about + // L * top_k / num_experts = L / 10 of a chunk's tokens, so short chunks are + // mostly padding; the knob exists to measure that. + // + // If the knob is set, the test is the CHUNK, not the expert's own token count: + // routing is skewed, so a hot expert could clear a per-expert threshold in one + // prefill and miss it when the same prompt arrives in two halves, and the same + // tokens would then take different code paths. + experts_on_npu = mm_on_npu && L >= mm_npu_min; + if (attn_on_npu) overlay->prepare_attention(L, pos0, MAX_L); + rope.build(L, desc, pos0); + + for (uint32_t layer = 0; layer < desc.num_hidden_layers; layer++) { + _attention_block(layer, x, L, pos0, layers[layer], MAX_L); + _moe(layer, x, L, layers[layer]); + } + + if (time_host) { + static const char* names[S_COUNT] = {"rms norm", "dequant_mm k|v|q|gate, o", "rope + kv store + gate", + "attention", "dequant_mm shared expert", "router", + "dequant_mm routed experts", "glu + residual + gather", "kv cache sync", + "batched experts: gather", "batched experts: weighted sum"}; + const double total = std::chrono::duration(host_clock::now() - t0).count(); + std::cout << "[minicpm5_moe prefill] " << L << " tokens at " << pos0 << ": " << total / 1000.0 << " ms (" + << total / L / 1000.0 << " ms/token), attention on " << (attn_on_npu ? "NPU" : "host") + << ", dequant_mm on " << (mm_on_npu ? "NPU" : "host") + << ", routed experts on " << (experts_on_npu ? "NPU" : "host") + << " (chunk " << L << (L >= mm_npu_min ? " >= " : " < ") << mm_npu_min << ")" << std::endl; + for (int s = 0; s < S_COUNT; s++) { + std::cout << " " << names[s] << ": " << stage_us[s] / 1000.0 << " ms" << std::endl; + } + if (overlay) { + std::cout << " (of the routed experts: writing batched runs " << overlay->seq_us / 1000.0 << " ms, their ELF " + << overlay->elf_us / 1000.0 << " ms, the runs " << overlay->run_us / 1000.0 << " ms)" << std::endl; + std::cout << " (overlay: BO syncs " << overlay->sync_us / 1000.0 << " ms, copies " << overlay->copy_us / 1000.0 + << " ms, dequant_mm runs " << overlay->mm_us / 1000.0 << " ms, attention runs " + << overlay->attn_us / 1000.0 << " ms)" << std::endl; + } + } +} + +/// A routed expert's blocks alternate between two channel streams; the run walks +/// them from the same start, so only the stride goes with it (channel_bytes). +/// part_offset picks the expert's up|gate or down part inside each stream. +size_t minicpm5_moe_prefill_context::_w_offset(const q4k_matrix& w, const minicpm5_moe_layer_buffers& buf) const { + const bool experts = w.kind == q4k_matrix::expert_channels; + return (size_t)(w.base - buf.proj->data()) + (experts ? w.part_offset : 0); +} + +void minicpm5_moe_prefill_context::_mm(bf16* y, const q4k_matrix& w, const bf16* x, int L, minicpm5_moe_layer_buffers& buf) { + const bool experts = w.kind == q4k_matrix::expert_channels; + if (!mm_on_npu || (experts && !experts_on_npu) || !minicpm5_moe_prefill_overlay::fits(w.K, w.N)) { + dequant_mm(y, w, x, L); + return; + } + overlay->dequant_mm(y, x, L, *buf.proj, _w_offset(w, buf), w.K, w.N, + experts ? w.channel_bytes : 0); + + // MC5_MM_CHECK=1: the same product on the host, reported per shape + if (mm_check) { + std::vector ref((size_t)L * w.N); + dequant_mm(ref.data(), w, x, L); + double dot = 0, na = 0, nb = 0; + for (size_t i = 0; i < ref.size(); i++) { + const double a = (double)y[i], b = (double)ref[i]; + dot += a * b; na += a * a; nb += b * b; + } + const double cos = (na > 0 && nb > 0) ? dot / std::sqrt(na * nb) : 0.0; + // a biased rounding shows up as a non-zero mean difference; plain noise does not + double sum_d = 0, sum_abs = 0, sum_ref_abs = 0; + for (size_t i = 0; i < ref.size(); i++) { + const double d = (double)y[i] - (double)ref[i]; + sum_d += d; sum_abs += std::fabs(d); sum_ref_abs += std::fabs((double)ref[i]); + } + const double n = (double)ref.size(); + std::cout << "[minicpm5_moe mm] L " << L << ", " << w.K << " -> " << w.N << ", w_offset " << _w_offset(w, buf) + << ": cos " << cos << " mean_diff " << sum_d / n + << " mean_|diff| " << sum_abs / n << " mean_|ref| " << sum_ref_abs / n + << (cos > 0.99 ? " OK" : " BAD") << std::endl; + // MC5_MM_CHECK=2: run the NPU but carry the host's numbers forward, so a + // failure here means the run disturbs something else, not its own answer + if (mm_check > 1) memcpy(y, ref.data(), ref.size() * sizeof(bf16)); + } +} + +void minicpm5_moe_prefill_context::_attention_block(int layer, bf16* x, int L, int pos0, minicpm5_moe_layer_buffers& buf, uint32_t MAX_L) { + const minicpm5_moe_layer_def& W = desc.layer_def(layer); + const int D = desc.D; + host_clock::time_point t = host_clock::now(); + + const bf16* in_norm = reinterpret_cast((const u8*)buf.rms->data() + W.input_layer_norm.offset); + rms_norm(xn.data(), x, in_norm, L, D, desc.rms_norm_eps); + lap(stage_us[S_NORM], t); + + _mm(kvq_out.data(), kvqg(layer, *buf.proj), xn.data(), L, buf); + lap(stage_us[S_MM_ATTN], t); + + kv_cache_view kv; + kv.base = buf.kv_cache->data(); + kv.MAX_L = MAX_L; + kv.DH = desc.DH; + kv.heads_per_col = desc.num_kv_heads / minicpm5_moe_desc::ATTN_COLS; + // rows before pos0 may have come from the NPU: see them before writing ours + if (pos0 > 0) buf.kv_cache->sync_from_device(); + lap(stage_us[S_SYNC], t); + rope_store_kv(kvq_out.data(), L, desc, rope, kv, pos0); + // Nothing to clean up past our rows: the engine keeps everything at or past the + // context length zero (minicpm5_moe_npu::Impl::set_context_length), so the round the + // attention reads beyond this chunk is already zeros. + lap(stage_us[S_ROPE_KV], t); + buf.kv_cache->sync_to_device(); // the decode overlay reads them next + lap(stage_us[S_SYNC], t); + + // q is the third part of each k|v|q|gate row + const int stride = kvqg_stride(desc); + if (attn_on_npu) { + overlay->attention(attn_out.data(), kvq_out.data() + desc.DK + desc.DV, stride, *buf.kv_cache); + } else { + attention(attn_out.data(), kvq_out.data() + desc.DK + desc.DV, stride, kv, L, pos0, desc.num_heads, desc.num_kv_heads); + } + lap(stage_us[S_ATTN], t); + attn_gate(attn_out.data(), kvq_out.data(), L, desc); + lap(stage_us[S_ROPE_KV], t); + + _mm(proj_out.data(), o(layer, *buf.proj), attn_out.data(), L, buf); + lap(stage_us[S_MM_ATTN], t); + add_rows(x, proj_out.data(), (size_t)L * D); + lap(stage_us[S_GLU_ADD], t); +} + +void minicpm5_moe_prefill_context::_moe(int layer, bf16* x, int L, minicpm5_moe_layer_buffers& buf) { + const minicpm5_moe_layer_def& Wd = desc.layer_def(layer); + const bool dense = desc.layer_kind(layer) == minicpm5_moe_layer_kind::dense; + const int D = desc.D, W = desc.expert_width; + host_clock::time_point t = host_clock::now(); + const u8* rms = (const u8*)buf.rms->data(); + rms_norm(xn.data(), x, reinterpret_cast(rms + Wd.post_attntion_norm.offset), L, D, desc.rms_norm_eps); + lap(stage_us[S_NORM], t); + + std::vector tasks; + if (dense) { + // layer 0: its MLP is experts 0..15, every token, weight 1; no router and + // no shared expert (the decode router fixes the same experts) + for (uint32_t e = 0; e < Wd.experts; e++) { + expert_task task; + task.expert = (int)e; + task.tokens.resize(L); + std::iota(task.tokens.begin(), task.tokens.end(), 0); + task.weights.assign(L, 1.0f); + tasks.push_back(std::move(task)); + } + std::fill(moe_sum.begin(), moe_sum.begin() + (size_t)L * D, 0.0f); + lap(stage_us[S_ROUTER], t); + } else { + // router on the host: fp32 logits, sigmoid, top 16 of score + bias + router_logits(logits.data(), xn.data(), reinterpret_cast(rms + Wd.ffn_gate_inp.offset), + L, D, desc.num_experts); + tasks = route(logits.data(), *buf.router_bias, L, desc.num_experts, desc.top_k, desc.router_scaling); + lap(stage_us[S_ROUTER], t); + } + + if (experts_on_npu && !mm_check) { + _moe_batched(layer, L, tasks, dense, buf); // times its own stages + t = host_clock::now(); + add_rows_f32(x, moe_sum.data(), (size_t)L * D); + lap(stage_us[S_GLU_ADD], t); + return; + } + + if (!dense) { + // shared expert: every token, weight 1; starts the fp32 sum + _mm(fused.data(), up_gate(layer, *buf.proj), xn.data(), L, buf); + lap(stage_us[S_MM_MLP], t); + silu_glu(hid.data(), fused.data(), L, W, minicpm5_moe_desc::SHARED_ROWS_PER_ROUND); + lap(stage_us[S_GLU_ADD], t); + _mm(proj_out.data(), down(layer, *buf.proj), hid.data(), L, buf); + lap(stage_us[S_MM_MLP], t); + for (size_t i = 0; i < (size_t)L * D; i++) moe_sum[i] = (float)proj_out[i]; + lap(stage_us[S_GLU_ADD], t); + } + + // routed experts, one at a time (the host path, and MC5_MM_CHECK): each runs on + // its own tokens only, gathered into a dense block, then scattered back with its + // weight. _moe_batched is the same arithmetic with all experts in two NPU runs. + std::vector xe, fe, he, ye; + for (const expert_task& task : tasks) { + const int n = (int)task.tokens.size(); + // layer 0 sends every token: its input block is xn itself + const bool all_tokens = n == L; + const bf16* xin = xn.data(); + if (!all_tokens) { + xe.resize((size_t)n * D); + for (int i = 0; i < n; i++) { + memcpy(xe.data() + (size_t)i * D, xn.data() + (size_t)task.tokens[i] * D, D * sizeof(bf16)); + } + xin = xe.data(); + } + fe.resize((size_t)n * 2 * W); + he.resize((size_t)n * W); + ye.resize((size_t)n * D); + lap(stage_us[S_GLU_ADD], t); + _mm(fe.data(), expert_up_gate(layer, task.expert, *buf.proj), xin, n, buf); + lap(stage_us[S_MM_EXPERT], t); + silu_glu(he.data(), fe.data(), n, W, minicpm5_moe_desc::EXPERT_ROWS_PER_ROUND); + lap(stage_us[S_GLU_ADD], t); + _mm(ye.data(), expert_down(layer, task.expert, *buf.proj), he.data(), n, buf); + lap(stage_us[S_MM_EXPERT], t); + // a token appears once per expert, so rows never collide inside one task + prefill_pool().run(n, [&](int64_t i0, int64_t i1, int) { + for (int64_t i = i0; i < i1; i++) { + float* acc = moe_sum.data() + (size_t)task.tokens[i] * D; + const bf16* y = ye.data() + (size_t)i * D; + for (int d = 0; d < D; d++) acc[d] += task.weights[i] * (float)y[d]; + } + }); + lap(stage_us[S_GLU_ADD], t); + } + add_rows_f32(x, moe_sum.data(), (size_t)L * D); + lap(stage_us[S_GLU_ADD], t); +} + +void minicpm5_moe_prefill_context::_moe_batched(int layer, int L, const std::vector& tasks, bool dense, + minicpm5_moe_layer_buffers& buf) { + using overlay_t = minicpm5_moe_prefill_overlay; + const int D = desc.D, W = desc.expert_width; + host_clock::time_point t = host_clock::now(); + + // One job per matrix: the shared expert first (MoE layers; every token), then the + // routed experts in task order. Each job owns overlay_t::dq_rows(n) rows of the batch + // buffers; its padding rows hold whatever was there (their outputs are never read). + struct job_t { + int task; // index into tasks, -1: the shared expert + int n; // its tokens + int row; // first row in the batch buffers + q4k_matrix ug, dn; + }; + std::vector jobs; + if (!dense) jobs.push_back({-1, L, 0, up_gate(layer, *buf.proj), down(layer, *buf.proj)}); + for (int k = 0; k < (int)tasks.size(); k++) { + jobs.push_back({k, (int)tasks[k].tokens.size(), 0, expert_up_gate(layer, tasks[k].expert, *buf.proj), + expert_down(layer, tasks[k].expert, *buf.proj)}); + } + auto glu_piece = [](const job_t& job) { + return job.task < 0 ? minicpm5_moe_desc::SHARED_ROWS_PER_ROUND : minicpm5_moe_desc::EXPERT_ROWS_PER_ROUND; + }; + + // each token's routed rows, in task order: the order the per-expert path adds them in + std::vector first(L + 1, 0), at(L); + for (const expert_task& task : tasks) + for (int tok : task.tokens) first[tok + 1]++; + for (int l = 0; l < L; l++) first[l + 1] += first[l]; + std::vector> entry(first[L]); // (job, row within the job) + std::copy(first.begin(), first.end() - 1, at.begin()); + for (int j = 0; j < (int)jobs.size(); j++) { + if (jobs[j].task < 0) continue; + const expert_task& task = tasks[jobs[j].task]; + for (int i = 0; i < (int)task.tokens.size(); i++) entry[at[task.tokens[i]]++] = {j, i}; + } + std::copy(first.begin(), first.end() - 1, at.begin()); // now each token's next entry + lap(stage_us[S_GATHER], t); + + // Jobs go in about batch_groups groups of equal rows, consecutive in task order + // (so every token still adds its experts in the same order), pipelined: while + // the NPU runs one group's projection, the host works on another group. + // NPU: U0 U1 D0 U2 D1 .. U(G-1) D(G-2) D(G-1) (U: up_gate + GLU, D: down) + // host: during D(g) scatter(g-1), then gather(g+2) + // U writes the GLU's output itself (y = silu(gate) * up). MINICPM5_MOE_HOST_GLU=1: + // U writes up|gate and the host does the GLU during U(g+1), as the per-expert path. + // x (and the down output) has 3 buffer sets (g % 3), the up_gate and GLU + // outputs 2 (g % 2): no run touches a buffer the host is using. + struct group_t { + int j0, j1, rows; + std::vector> rows_of; // (job, row within the job) per real row + std::vector ug, dn; + }; + std::vector groups; + { + int total = 0; + for (const job_t& job : jobs) total += overlay_t::dq_rows(job.n); + const int target = (total + batch_groups - 1) / std::max(1, batch_groups); + for (int j0 = 0; j0 < (int)jobs.size();) { + group_t g{j0, j0, 0, {}, {}, {}}; + while (g.j1 < (int)jobs.size() && (g.j1 == j0 || g.rows < target)) { + const int j = g.j1++; + job_t& job = jobs[j]; + const bool experts = job.task >= 0; + job.row = g.rows; + g.ug.push_back({g.rows, job.n, _w_offset(job.ug, buf), experts ? job.ug.channel_bytes : 0, + host_glu ? 0 : glu_piece(job)}); + g.dn.push_back({g.rows, job.n, _w_offset(job.dn, buf), experts ? job.dn.channel_bytes : 0}); + for (int i = 0; i < job.n; i++) g.rows_of.push_back({j, i}); + g.rows += overlay_t::dq_rows(job.n); + } + j0 = g.j1; + groups.push_back(std::move(g)); + } + } + const int G = (int)groups.size(); + + // buffers: grown here, before any run uses them + std::vector*> xs(G), fs(G, nullptr), hs(G); + { + size_t need[SETS] = {}; + for (int g = 0; g < G; g++) { + const size_t rows = groups[g].rows; + need[X_SET + g % 3] = std::max(need[X_SET + g % 3], rows * D); + if (host_glu) need[F_SET + g % 2] = std::max(need[F_SET + g % 2], rows * 2 * W); + need[H_SET + g % 2] = std::max(need[H_SET + g % 2], rows * W); + } + for (int i = 0; i < SETS; i++) + if (need[i]) overlay->batch_buffer(i, need[i]); + for (int g = 0; g < G; g++) { + xs[g] = &overlay->batch_buffer(X_SET + g % 3, 0); + if (host_glu) fs[g] = &overlay->batch_buffer(F_SET + g % 2, 0); + hs[g] = &overlay->batch_buffer(H_SET + g % 2, 0); + } + } + + // every run (U(g): slot 2g, D(g): 2g + 1) is written on one thread, in NPU order, + // from the start; each run waits for its own + overlay->batch_slots(2 * G); + std::vector order{0}; + for (int g = 0; g < G; g++) { + if (g + 1 < G) order.push_back(2 * (g + 1)); + order.push_back(2 * g + 1); + } + std::vector> prepared(2 * G); + std::vector> ready; + for (std::promise& p : prepared) ready.push_back(p.get_future().share()); + const int first_op = overlay->current_op(); + std::future writer = std::async(std::launch::async, [&] { + for (size_t k = 0; k < order.size(); k++) { + const int id = order[k]; + try { + const group_t& gr = groups[id / 2]; + if (id % 2 == 0) { + overlay->prepare_batch(id, gr.ug, D, 2 * W, id == 0 ? first_op : overlay_t::after(overlay_t::OP_DQ), + !host_glu); + } else { + overlay->prepare_batch(id, gr.dn, W, D, overlay_t::after(overlay_t::OP_DQ)); + } + prepared[id].set_value(); + } catch (...) { + for (; k < order.size(); k++) prepared[order[k]].set_exception(std::current_exception()); + return; + } + } + }); + + // Syncs: x is flushed by gather and the down output invalidated by scatter, on + // this thread while the NPU runs another projection; the hidden rows are the + // NPU's alone (fused GLU), so they are never synced (host GLU: by the runs). + std::future npu; // the run in flight + auto launch = [&](int id, buffer* y, buffer* x, unsigned sync) { + npu = std::async(std::launch::async, [&, id, y, x, sync] { + ready[id].get(); + overlay->run_batch(id, *y, *x, *buf.proj, sync); + }); + }; + const unsigned up_sync = host_glu ? overlay_t::SYNC_Y : overlay_t::SYNC_NONE; + const unsigned down_sync = host_glu ? overlay_t::SYNC_X : overlay_t::SYNC_NONE; + auto wait_npu = [&] { + npu.get(); + lap(stage_us[S_MM_EXPERT], t); + }; + + // gather: each real row is its token's normed input. Streaming stores: the host + // never reads these rows back, and the flush then finds no dirty line + assert((D * sizeof(bf16)) % 64 == 0); + auto gather = [&](int g) { + const group_t& gr = groups[g]; + bf16* xd = xs[g]->data(); + assert(reinterpret_cast(xd) % 64 == 0); + prefill_pool().run((int64_t)gr.rows_of.size(), [&](int64_t r0, int64_t r1, int) { + for (int64_t r = r0; r < r1; r++) { + const job_t& job = jobs[gr.rows_of[r].first]; + const int i = gr.rows_of[r].second; + const int tok = job.task < 0 ? i : tasks[job.task].tokens[i]; + const __m512i* src = reinterpret_cast(xn.data() + (size_t)tok * D); + __m512i* dst = reinterpret_cast<__m512i*>(xd + (size_t)(job.row + i) * D); + for (size_t k = 0; k < D * sizeof(bf16) / 64; k++) _mm512_stream_si512(dst + k, _mm512_loadu_si512(src + k)); + } + _mm_sfence(); + }); + xs[g]->sync_to_device((size_t)gr.rows * D); + lap(stage_us[S_GATHER], t); + }; + // host GLU per row (MINICPM5_MOE_HOST_GLU); the shared expert's up|gate slabs are + // wider than a routed one's + auto glu = [&](int g) { + if (!host_glu) return; + const group_t& gr = groups[g]; + const bf16* fd = fs[g]->data(); + bf16* hd = hs[g]->data(); + prefill_pool().run((int64_t)gr.rows_of.size(), [&](int64_t r0, int64_t r1, int) { + for (int64_t r = r0; r < r1; r++) { + const job_t& job = jobs[gr.rows_of[r].first]; + const size_t row = (size_t)job.row + gr.rows_of[r].second; + silu_glu_row(hd + row * W, fd + row * 2 * W, W, glu_piece(job)); + } + }); + lap(stage_us[S_GLU_ADD], t); + }; + // scatter: the shared expert (if in this group) starts each token's fp32 sum, + // then the token's routed rows of this group, weighted, in task order + auto scatter = [&](int g) { + const group_t& gr = groups[g]; + xs[g]->sync_from_device((size_t)gr.rows * D); + const bf16* yd = xs[g]->data(); + const bool shared_here = jobs[gr.j0].task < 0; + prefill_pool().run(L, [&](int64_t l0, int64_t l1, int) { + for (int64_t l = l0; l < l1; l++) { + float* acc = moe_sum.data() + (size_t)l * D; + if (shared_here) { + const bf16* y = yd + (size_t)(jobs[gr.j0].row + l) * D; + for (int d = 0; d < D; d += 16) _mm512_storeu_ps(acc + d, load_bfloat16_to_m512(y + d)); + } + for (; at[l] < first[l + 1] && entry[at[l]].first < gr.j1; at[l]++) { + const job_t& job = jobs[entry[at[l]].first]; + const int i = entry[at[l]].second; + const __m512 w = _mm512_set1_ps(tasks[job.task].weights[i]); + const bf16* y = yd + (size_t)(job.row + i) * D; + for (int d = 0; d < D; d += 16) + _mm512_storeu_ps(acc + d, _mm512_fmadd_ps(w, load_bfloat16_to_m512(y + d), _mm512_loadu_ps(acc + d))); + } + } + }); + lap(stage_us[S_SCATTER], t); + }; + // MC5_BATCH_CHECK=1: a finished run against the host (dequant_mm, silu_glu) on + // the same inputs, cosine per group; U(g) while xs[g] is still its input, D(g) + // while hs[g] still is + auto check = [&](int g, bool up) { + if (!batch_check) return; + const group_t& gr = groups[g]; + for (buffer* b : {xs[g], fs[g], hs[g]}) // the runs leave some unsynced + if (b) b->sync_from_device(); + double dot = 0, na = 0, nb = 0; + std::vector ref, f; + for (int j = gr.j0; j < gr.j1; j++) { + const job_t& job = jobs[j]; + const size_t n = job.n; + const bf16* got; + size_t cols; + if (up) { + f.resize(n * 2 * W); + dequant_mm(f.data(), job.ug, xs[g]->data() + (size_t)job.row * D, job.n); + if (host_glu) { + ref = f; + cols = 2 * W; + got = fs[g]->data() + (size_t)job.row * cols; + } else { + ref.resize(n * W); + silu_glu(ref.data(), f.data(), job.n, W, glu_piece(job)); + cols = W; + got = hs[g]->data() + (size_t)job.row * cols; + } + } else { + ref.resize(n * D); + dequant_mm(ref.data(), job.dn, hs[g]->data() + (size_t)job.row * W, job.n); + cols = D; + got = xs[g]->data() + (size_t)job.row * cols; + } + for (size_t i = 0; i < n * cols; i++) { + const double a = (double)got[i], b = (double)ref[i]; + dot += a * b; na += a * a; nb += b * b; + } + } + const double cos = (na > 0 && nb > 0) ? dot / std::sqrt(na * nb) : 0.0; + std::cout << "[minicpm5_moe batch] layer " << layer << " group " << g << (up ? " up_gate" : " down") + << (up && !host_glu ? "+glu" : "") << ", " << gr.j1 - gr.j0 << " matrices, " << gr.rows + << " rows: cos " << cos << (cos > 0.99 ? " OK" : " BAD") << std::endl; + t = host_clock::now(); + }; + + // U(g) writes the hidden rows (fused GLU) or the up|gate rows (host GLU) + auto up_out = [&](int g) { return host_glu ? fs[g] : hs[g]; }; + gather(0); + launch(0, up_out(0), xs[0], up_sync); + if (G > 1) gather(1); + wait_npu(); + check(0, true); + for (int g = 0; g < G; g++) { + if (g + 1 < G) launch(2 * (g + 1), up_out(g + 1), xs[g + 1], up_sync); + glu(g); + if (g + 1 < G) { + wait_npu(); + check(g + 1, true); + } + launch(2 * g + 1, xs[g], hs[g], down_sync); // down into the x buffer, which up_gate is done with + if (g >= 1) scatter(g - 1); + if (g + 2 < G) gather(g + 2); + wait_npu(); + check(g, false); + } + scatter(G - 1); + writer.get(); +} + +// ============================================================================= +// layout self-check (MC5_CHECK_LAYOUT=1) +// ============================================================================= +namespace { +/// \brief compares every block of `view` with the q4nx blocks it came from +/// \param map logical row block -> (source tensor [row block][column block], its row block) +template +size_t compare_view(const q4k_matrix& view, Map map) { + size_t bad = 0; + alignas(64) u8 plain[Q4K_BLOCK]; + for (int rb = 0; rb < view.row_blocks(); rb++) { + const auto [src, src_rb] = map(rb); + for (int cb = 0; cb < view.blocks_per_row(); cb++) { + const u8* got = view.block(rb, cb); + if (view.relaid) { + q4k_unrelayout(plain, got); + got = plain; + } + const u8* want = src->data() + ((size_t)src_rb * view.blocks_per_row() + cb) * Q4K_BLOCK; + bad += memcmp(got, want, Q4K_BLOCK) != 0; + } + } + return bad; +} + +/// \brief row block rb of an [up slab | gate slab]-interleaved matrix -> (up or gate, row block) +std::pair*, int> interleaved(int rb, int slab_rows, const buffer* up, const buffer* gate, int first_rb) { + const int per = slab_rows / Q4K_ROWS; // row blocks per slab + const int piece = rb / (2 * per), within = rb % (2 * per); + return within < per ? std::make_pair(up, first_rb + piece * per + within) + : std::make_pair(gate, first_rb + piece * per + within - per); +} +} // namespace + +size_t minicpm5_moe_prefill_context::check_layout(int layer, Q4NX& q4nx, const buffer& proj) const { + const bool dense = desc.layer_kind(layer) == minicpm5_moe_layer_kind::dense; + const minicpm5_moe_layer_def& W = desc.layer_def(layer); + const std::string prefix = "model.layer." + std::to_string(layer) + "."; + auto load = [&](const std::string& name) { + buffer b; + q4nx.load_weights(b, name); + return b; + }; + auto load_w = [&](const weight_desc_t& w) { return load(const_cast(w).format_name(layer)); }; + size_t bad = 0; + + // k | v | q | gate; k and v hold each model KV head twice + buffer k = load_w(W.attn_k), v = load_w(W.attn_v), q = load_w(W.attn_q), g = load_w(W.attn_gate); + const int head_rbs = desc.DH / Q4K_ROWS; + const int dup = desc.num_kv_heads / desc.model_kv_heads; + const int k_rbs = desc.DK / Q4K_ROWS, v_rbs = desc.DV / Q4K_ROWS, q_rbs = desc.DQ / Q4K_ROWS; + auto kv_rb = [&](int rb) { return (rb / head_rbs) / dup * head_rbs + rb % head_rbs; }; + bad += compare_view(kvqg(layer, proj), [&](int rb) { + if (rb < k_rbs) return std::make_pair(&k, kv_rb(rb)); + if (rb < k_rbs + v_rbs) return std::make_pair(&v, kv_rb(rb - k_rbs)); + if (rb < k_rbs + v_rbs + q_rbs) return std::make_pair(&q, rb - k_rbs - v_rbs); + return std::make_pair(&g, rb - k_rbs - v_rbs - q_rbs); + }); + buffer wo = load_w(W.attn_output); + bad += compare_view(o(layer, proj), [&](int rb) { return std::make_pair(&wo, rb); }); + + // shared expert (layer 0 has none) + if (!dense) { + buffer up = load_w(W.ffn_up_shexp), gate = load_w(W.ffn_gate_shexp), dn = load_w(W.ffn_down_shexp); + bad += compare_view(up_gate(layer, proj), [&](int rb) { + return interleaved(rb, minicpm5_moe_desc::SHARED_ROWS_PER_ROUND, &up, &gate, 0); + }); + bad += compare_view(down(layer, proj), [&](int rb) { return std::make_pair(&dn, rb); }); + } + + // routed experts: stacked in the q4nx tensors, expert e = row blocks e * (rows / 32) .. + // Layer 0's MLP is cut the same way: up / gate rows e * 512 .. are expert e, and its + // down [D][8192] is re-cut here into per-expert [D][512] matrices, stacked. + buffer eu, eg, ed; + if (dense) { + eu = load(prefix + "mlp.up_proj.weight"); + eg = load(prefix + "mlp.gate_proj.weight"); + buffer dd = load(prefix + "mlp.down_proj.weight"); + const size_t piece = (size_t)desc.expert_width / Q4K_COLS * Q4K_BLOCK; + ed = buffer(dd.size()); + u8* dst = ed.data(); + for (uint32_t e = 0; e < W.experts; e++) { + for (uint32_t rb = 0; rb < desc.D / Q4K_ROWS; rb++) { + memcpy(dst, dd.data() + ((size_t)rb * W.experts + e) * piece, piece); + dst += piece; + } + } + } else { + eu = load_w(W.ffn_up_exps); + eg = load_w(W.ffn_gate_exps); + ed = load_w(W.ffn_down_exps); + } + const int ug_rbs = desc.expert_width / Q4K_ROWS, d_rbs = desc.D / Q4K_ROWS; + for (int e = 0; e < (int)W.experts; e++) { + bad += compare_view(expert_up_gate(layer, e, proj), [&](int rb) { + return interleaved(rb, minicpm5_moe_desc::EXPERT_ROWS_PER_ROUND, &eu, &eg, e * ug_rbs); + }); + bad += compare_view(expert_down(layer, e, proj), [&](int rb) { return std::make_pair(&ed, e * d_rbs + rb); }); + } + return bad; +} diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill.hpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill.hpp new file mode 100644 index 000000000..65b44072b --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill.hpp @@ -0,0 +1,133 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_prefill.hpp +/// \brief Batched prefill of MiniCPM5-15B-A2.5B: a chunk of prompt tokens through all +/// 28 layers at once, writing the decode KV cache as it goes +/// \note Per layer: +/// x -> rms_norm -> dequant_mm(k|v|q|gate) -> rope -> store_kv +/// -> attention -> * sigmoid(gate) -> dequant_mm(o) -> +x +/// -> rms_norm -> layer 0: experts 0..15 on every token, weight 1 (its +/// 8192-wide MLP, stored as 16 experts of 512) +/// MoE: router_logits -> route +/// shared expert (512 wide), every token +/// per used expert: its tokens only, same three steps, +/// times the routing weight, summed in fp32 -> +x +/// The heavy steps are dequant_mm and attention (minicpm5_moe_prefill_ops.hpp); the +/// switches below say where each runs. The NPU versions run on the prefill +/// overlay (minicpm5_moe_prefill_overlay.hpp), reading the same decode weight +/// buffers and KV cache. +/// +/// The other prefill, PREFILL_WITH_MV (Makefile PREFILL_WITH_MV=1), feeds the +/// prompt through the decode overlays one token at a time instead. +#pragma once +#include +#include +#include +#include +#include +#include "minicpm5_moe_model_def.hpp" +#include "minicpm5_moe_prefill_ops.hpp" +#include "minicpm5_moe_cpu_functions.hpp" +#include "minicpm5_moe_prefill_overlay.hpp" + +// Where the two heavy prefill stages run (1 = the prefill overlay, 0 = the host). +// A chunk is zero-padded to a whole number of rounds: 128 rows for the attention, +// 256 for dequant_mm. At run time MINICPM5_MOE_ATTN_HOST=1 / MINICPM5_MOE_MM_HOST=1 put either +// back on the host (for comparisons), and MINICPM5_MOE_MM_NPU_MIN (1024) is the shortest +// chunk whose routed experts are worth the overlay rather than the host. +#ifndef MINICPM5_MOE_MM_ON_NPU +#define MINICPM5_MOE_MM_ON_NPU 1 +#endif +#ifndef MINICPM5_MOE_ATTN_ON_NPU +#define MINICPM5_MOE_ATTN_ON_NPU 1 +#endif + +/// \brief the decode buffers of one layer, which the prefill reads (weights) and +/// writes (KV cache) in place +struct minicpm5_moe_layer_buffers { + buffer* proj; + buffer* rms; + buffer* rope_rms; + buffer* kv_cache; + const std::vector* router_bias; // MoE layers only +}; + +class minicpm5_moe_prefill_context { +public: + explicit minicpm5_moe_prefill_context(minicpm5_moe_desc& desc) : desc(desc) {} + + /// \brief the prefill overlay the NPU stages run on (nullptr: all on the host) + void set_overlay(minicpm5_moe_prefill_overlay* ovl) { overlay = ovl; } + + /// \brief L tokens at positions pos0 .. pos0 + L - 1 through every layer + /// \param x in: the embeddings [L][D]; out: the last layer's output [L][D] + /// \param layers the decode buffers, one entry per layer + /// \param MAX_L the KV cache length the caches were allocated with + void forward(bf16* x, int L, int pos0, std::vector& layers, uint32_t MAX_L); + + /// \brief at load: what the first forward() of up to L tokens would otherwise + /// set up itself (scratch, the host pool's threads, the batch runs and + /// buffers), ~0.2 s of a cold 2K prefill. The batch buffers are sized for an + /// even routing; a skewed one grows them on the way, as without this. + void prewarm(int L); + + // ---- where each weight is in a layer's proj buffer (see minicpm5_moe_model_def.cpp) ---- + // (every block is in the int8-mmul order; both layer kinds share the offsets + // up to the routed region's size, so the views take the layer) + minicpm5_moe_cpu::q4k_matrix kvqg(int layer, const buffer& proj) const; // k | v | q | gate + minicpm5_moe_cpu::q4k_matrix o(int layer, const buffer& proj) const; + minicpm5_moe_cpu::q4k_matrix up_gate(int layer, const buffer& proj) const; // shared expert + minicpm5_moe_cpu::q4k_matrix down(int layer, const buffer& proj) const; // shared expert + minicpm5_moe_cpu::q4k_matrix expert_up_gate(int layer, int expert, const buffer& proj) const; + minicpm5_moe_cpu::q4k_matrix expert_down(int layer, int expert, const buffer& proj) const; + + /// \brief MC5_CHECK_LAYOUT=1: every block the views above point at, compared byte + /// for byte (relayout undone) with the tensors in model.q4nx + /// \return the number of blocks that differ (0 = the views are right) + size_t check_layout(int layer, Q4NX& q4nx, const buffer& proj) const; + +private: + minicpm5_moe_desc& desc; + minicpm5_moe_prefill_overlay* overlay = nullptr; + bool attn_on_npu = false; // this forward()'s attention runs on the overlay + bool mm_on_npu = false; // ... and so do its dequant_mm calls + bool experts_on_npu = false;// ... including the routed experts (long chunks only) + + /// \brief y[L][w.N] = x[L][w.K] W^T, on the overlay when it can take it + /// \note The overlay reads the weights straight from `buf.proj` at the view's + /// byte offset: the decode and prefill kernels take the same block order. + void _mm(bf16* y, const minicpm5_moe_cpu::q4k_matrix& w, const bf16* x, int L, minicpm5_moe_layer_buffers& buf); + + /// \brief where a weight view starts in the layer's projection buffer + size_t _w_offset(const minicpm5_moe_cpu::q4k_matrix& w, const minicpm5_moe_layer_buffers& buf) const; + + + // scratch, grown to the largest chunk seen + int capacity = 0; + std::vector xn, kvq_out, attn_out, proj_out, fused, hid; + std::vector logits, moe_sum; + minicpm5_moe_cpu::rope_table rope; // this chunk's positions, every layer + void _reserve(int L); + + void _attention_block(int layer, bf16* x, int L, int pos0, minicpm5_moe_layer_buffers& buf, uint32_t MAX_L); + /// \brief the MLP of either layer kind (layer 0: fixed experts, no router or shared expert) + void _moe(int layer, bf16* x, int L, minicpm5_moe_layer_buffers& buf); + /// \brief moe_sum += the shared expert (MoE layers; it starts the sum) and every + /// routed expert, all of a group of experts in one overlay run per + /// projection (the GLU fused into the up_gate run). With + /// MINICPM5_MOE_HOST_GLU=1 bit for bit the per-expert path's result + /// \note moe_sum must be zero for a dense layer (it has no shared expert) + void _moe_batched(int layer, int L, const std::vector& tasks, bool dense, + minicpm5_moe_layer_buffers& buf); + /// \brief groups a layer's experts are split into, pipelined against each other + /// (MC5_BATCH_GROUPS). 2K warm: 2 groups 1.50 s, 3: 1.50, 4: 1.49 (more + /// groups hide more of the gather / scatter but add dispatches, and short + /// chunks get small groups) + int batch_groups = std::max(1, std::getenv("MC5_BATCH_GROUPS") ? std::atoi(std::getenv("MC5_BATCH_GROUPS")) : 2); + + // MC5_TIME_HOST=1: time per stage, summed over a forward() and printed at its end + enum stage_t { S_NORM, S_MM_ATTN, S_ROPE_KV, S_ATTN, S_MM_MLP, S_ROUTER, S_MM_EXPERT, S_GLU_ADD, S_SYNC, + S_GATHER, S_SCATTER, S_COUNT }; + double stage_us[S_COUNT] = {}; +}; diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill_ops.hpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill_ops.hpp new file mode 100644 index 000000000..4d388c863 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill_ops.hpp @@ -0,0 +1,399 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_prefill_ops.hpp +/// \brief The two heavy prefill operations, on the host: dequant_mm and attention +/// \note These are the stages a prefill overlay will take over later, so their +/// signatures are what such an overlay would take: whole tensors in, whole +/// tensors out, bf16 activations, the weights read in place from the decode +/// buffers (no second copy), the K/V read in place from the decode KV cache. +/// minicpm5_moe_prefill.cpp calls them through MINICPM5_MOE_MM_ON_NPU / MINICPM5_MOE_ATTN_ON_NPU, +/// which are 0 for now. +/// +/// The small per-row steps (norms, RoPE, GLU, router, residual) are in +/// minicpm5_moe_cpu_functions.hpp. +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _OPENMP +#include +#endif +#include "typedef.hpp" +#include "utils/avx512_util.hpp" +#include "minicpm5_moe_model_def.hpp" + +namespace minicpm5_moe_cpu { + +/// \brief threads for the host prefill: the whole machine (these kernels are the +/// whole cost of a CPU prefill). Override with FLM_PREFILL_THREADS. +inline int prefill_threads() { + static const int nt = [] { +#ifdef _OPENMP + int n = omp_get_max_threads(); +#else + int n = 1; +#endif + if (const char* env = std::getenv("FLM_PREFILL_THREADS")) { + const int v = std::atoi(env); + if (v > 0) n = v; + } + return n < 1 ? 1 : n; + }(); + return nt; +} + +/// \brief threads for the host steps between NPU runs, which sleep when idle +/// \note Not OpenMP: libgomp's default team keeps spinning for a while after each +/// region, and here every region is followed by an NPU run: 31 spinning cores +/// then starve the threads that feed the NPU (the batch writer, the run +/// thread, the driver) and spend the power budget, so the host steps around +/// the runs slow down too (pf2048 1747 ms with OMP_WAIT_POLICY=passive, 2137 +/// with the default). The policy is read at process start, before this +/// library loads, so it cannot be set from here; this pool sleeps instead. +class host_pool { +public: + explicit host_pool(int threads) : T(std::max(1, threads)) { + for (int t = 1; t < T; t++) workers.emplace_back([this, t] { _work(t); }); + } + ~host_pool() { + stop.store(true); + gen.fetch_add(1, std::memory_order_release); + gen.notify_all(); + for (std::thread& w : workers) w.join(); + } + host_pool(const host_pool&) = delete; + host_pool& operator=(const host_pool&) = delete; + int threads() const { return T; } + + /// \brief f(begin, end, part) over [0, n) in threads() contiguous parts (part 0 + /// on the caller), like an OpenMP static schedule; returns when all are done + /// \note One job at a time: callers on other threads wait; f must not call run(). + template + void run(int64_t n, F&& f) { + using Fn = std::remove_reference_t; + if (n <= 0) return; + if (T == 1 || n == 1) { + f((int64_t)0, n, 0); + return; + } + std::lock_guard lock(busy); + job_fn = [](void* ctx, int64_t b, int64_t e, int p) { (*static_cast(ctx))(b, e, p); }; + job_ctx = (void*)std::addressof(f); + job_n = n; + pending.store(T - 1, std::memory_order_relaxed); + gen.fetch_add(1, std::memory_order_release); + gen.notify_all(); + _part(0); + for (int left; (left = pending.load(std::memory_order_acquire)) != 0;) pending.wait(left, std::memory_order_acquire); + } + +private: + void _part(int p) const { + const int64_t b = job_n * p / T, e = job_n * (p + 1) / T; + if (b < e) job_fn(job_ctx, b, e, p); + } + void _work(int t) { + uint32_t seen = 0; + for (;;) { + gen.wait(seen, std::memory_order_acquire); + seen = gen.load(std::memory_order_acquire); + if (stop.load()) return; + _part(t); + if (pending.fetch_sub(1, std::memory_order_acq_rel) == 1) pending.notify_one(); + } + } + + const int T; + std::vector workers; + std::atomic gen{0}; + std::atomic pending{0}; + std::atomic stop{false}; + std::mutex busy; + // the job of generation gen; every worker takes part, so none is read while written + void (*job_fn)(void*, int64_t, int64_t, int) = nullptr; + void* job_ctx = nullptr; + int64_t job_n = 0; +}; + +/// \brief the prefill's pool, prefill_threads() wide, made on first use +/// \note One prefill runs at a time (the engine's lock), so one pool serves them all. +inline host_pool& prefill_pool() { + static host_pool pool(prefill_threads()); + return pool; +} + +/// \brief rows of `bytes` from src (row stride src_stride elements) to dst (dst_stride), +/// on the prefill pool (one thread copies well below the memory bandwidth) +template +inline void copy_rows(T* dst, size_t dst_stride, const T* src, size_t src_stride, int64_t rows, size_t bytes) { + prefill_pool().run(rows, [&](int64_t r0, int64_t r1, int) { + for (int64_t r = r0; r < r1; r++) memcpy(dst + (size_t)r * dst_stride, src + (size_t)r * src_stride, bytes); + }); +} + +// ============================================================================= +// Q4_K blocks +// ============================================================================= +// One block = 32 rows x 256 columns, 4736 bytes, as in model.q4nx +// (FLM_Q4NX_Converter/verify_minicpm5_moe_q4nx.py::decode_q4k): +// uint8 s8 [8 groups][32 rows] per-group scale +// uint8 m8 [8 groups][32 rows] per-group min +// uint4 q [256 cols][16 bytes] byte b of a column = rows 2b (low nibble), 2b + 1 (high) +// bf16 S [32 rows] super-block scale +// bf16 M [32 rows] super-block min, stored negated +// w[r][c] = S[r] * s8[g][r] * q[r][c] + M[r] * m8[g][r], g = c / 32 +constexpr int Q4K_ROWS = 32; +constexpr int Q4K_COLS = 256; +constexpr int Q4K_GROUPS = 8; +constexpr size_t Q4K_BLOCK = minicpm5_moe_desc::Q4K_BLOCK_BYTES; +constexpr size_t Q4K_S8 = 0, Q4K_M8 = 256, Q4K_QS = 512, Q4K_S = 4608, Q4K_M = 4672; + +/// \brief undo minicpm5_moe_model_def.cpp's q4k_relayout_for_mmul (the MoE overlay's +/// int8-mmul order) back into the plain q4nx order above +/// \note relaid qs: [k step 16][half t 2][16 columns][8 B], column = 16k + c +/// relaid scales: [h 2][t 2][a 4][16 rows], group = 4h + a, row = 16t + i +/// mins, S, M were not moved +inline void q4k_unrelayout(u8* plain, const u8* relaid) { + memcpy(plain + Q4K_M8, relaid + Q4K_M8, Q4K_QS - Q4K_M8); // mins + memcpy(plain + Q4K_S, relaid + Q4K_S, Q4K_BLOCK - Q4K_S); // S, M + for (int k = 0; k < 16; k++) + for (int t = 0; t < 2; t++) + for (int c = 0; c < 16; c++) + memcpy(plain + Q4K_QS + (k * 16 + c) * 16 + t * 8, + relaid + Q4K_QS + (k * 2 + t) * 128 + c * 8, 8); + for (int h = 0; h < 2; h++) + for (int t = 0; t < 2; t++) + for (int a = 0; a < 4; a++) + memcpy(plain + Q4K_S8 + (4 * h + a) * 32 + 16 * t, + relaid + Q4K_S8 + ((h * 2 + t) * 4 + a) * 16, 16); +} + +/// \brief one plain block into a fp32 tile: tile[r * ld + col0 + c] +inline void q4k_decode_block(float* tile, int ld, int col0, const u8* blk) { + const u8* s8 = blk + Q4K_S8; + const u8* m8 = blk + Q4K_M8; + const u8* qs = blk + Q4K_QS; + const bf16* S = reinterpret_cast(blk + Q4K_S); + const bf16* M = reinterpret_cast(blk + Q4K_M); + for (int r = 0; r < Q4K_ROWS; r++) { + float* row = tile + (size_t)r * ld + col0; + const float S_r = (float)S[r], M_r = (float)M[r]; + const int byte = r / 2, shift = (r & 1) * 4; // this row's nibble in a column + for (int g = 0; g < Q4K_GROUPS; g++) { + const float scale = S_r * (float)s8[g * Q4K_ROWS + r]; + const float min = M_r * (float)m8[g * Q4K_ROWS + r]; + for (int c = g * 32; c < g * 32 + 32; c++) { + const int q = (qs[c * 16 + byte] >> shift) & 0x0F; + row[c] = scale * (float)q + min; + } + } + } +} + +// ============================================================================= +// Where a weight's blocks are in the decode buffers +// ============================================================================= +/// \brief one weight matrix [N rows][K cols] inside a layer's proj buffer, as the +/// decode overlays laid it out (minicpm5_moe_model_def.cpp). block() is the +/// executable spec of those layouts: minicpm5_moe_desc::check_layer_layout tests +/// it byte for byte against model.q4nx. +struct q4k_matrix { + enum kind_t { + pairs, // reorder_cpy(..., 2): row blocks in pairs, interleaved block by block + expert_channels, // one routed expert's [channel 0 | channel 1] streams (reorder_cpy(..., 4) + split) + }; + const u8* base = nullptr; // pairs: the matrix; expert_channels: the expert's start + int K = 0, N = 0; // columns (input), rows (output) + kind_t kind = pairs; + bool relaid = false; // blocks in the int8-mmul order (every MoE-layer block) + size_t channel_bytes = 0; // expert_channels: one channel stream + size_t part_offset = 0; // expert_channels: where this matrix starts in each stream + + int blocks_per_row() const { return K / Q4K_COLS; } + int row_blocks() const { return N / Q4K_ROWS; } + + /// \brief the block of row block rb (rows 32 rb ..), column block cb + const u8* block(int rb, int cb) const { + const size_t bpr = (size_t)blocks_per_row(); + if (kind == pairs) { + // [pair rb / 2][cb][rb % 2] + return base + (((size_t)(rb / 2) * bpr + cb) * 2 + rb % 2) * Q4K_BLOCK; + } + // groups of 4 row blocks, [group rb / 4][cb][rb % 4]; of each 4, the first + // 2 went to channel 0 and the last 2 to channel 1 + const size_t group = (size_t)(rb / 4) * bpr + cb; + const int i = rb % 4; + return base + (size_t)(i / 2) * channel_bytes + part_offset + (group * 2 + i % 2) * Q4K_BLOCK; + } + + /// \brief rows 32 rb .. 32 rb + 31, all K columns, as fp32: tile[r * K + col] + void dequant_row_block(float* tile, int rb) const { + alignas(64) u8 plain[Q4K_BLOCK]; + for (int cb = 0; cb < blocks_per_row(); cb++) { + const u8* blk = block(rb, cb); + if (relaid) { + q4k_unrelayout(plain, blk); + blk = plain; + } + q4k_decode_block(tile, K, cb * Q4K_COLS, blk); + } + } +}; + +// ============================================================================= +// dequant_mm: y[L][N] = x[L][K] W^T +// ============================================================================= +/// \brief y[l][r0 .. r0 + 31] = x[l] . tile[r], for one 32-row tile and all L rows +/// \note Register blocking: 4 rows of x by 4 rows of the tile at a time, so each +/// pair of loads feeds 16 FMAs and the tile (in L2) is read L / 4 times +/// instead of L times. A tail of fewer than 4 x rows points the missing +/// ones at the last real row and does not store them. +inline void mm_tile(bf16* y, int ldy, const float* tile, const float* xf, int L, int K) { + for (int l = 0; l < L; l += 4) { + const float* xr[4]; + for (int i = 0; i < 4; i++) xr[i] = xf + (size_t)std::min(l + i, L - 1) * K; + for (int r = 0; r < Q4K_ROWS; r += 4) { + __m512 acc[4][4]; + for (int i = 0; i < 4; i++) + for (int j = 0; j < 4; j++) acc[i][j] = _mm512_setzero_ps(); + const float* wr = tile + (size_t)r * K; + for (int k = 0; k < K; k += 16) { + const __m512 w0 = _mm512_loadu_ps(wr + k); + const __m512 w1 = _mm512_loadu_ps(wr + K + k); + const __m512 w2 = _mm512_loadu_ps(wr + 2 * (size_t)K + k); + const __m512 w3 = _mm512_loadu_ps(wr + 3 * (size_t)K + k); + for (int i = 0; i < 4; i++) { + const __m512 xv = _mm512_loadu_ps(xr[i] + k); + acc[i][0] = _mm512_fmadd_ps(xv, w0, acc[i][0]); + acc[i][1] = _mm512_fmadd_ps(xv, w1, acc[i][1]); + acc[i][2] = _mm512_fmadd_ps(xv, w2, acc[i][2]); + acc[i][3] = _mm512_fmadd_ps(xv, w3, acc[i][3]); + } + } + for (int i = 0; i < 4 && l + i < L; i++) + for (int j = 0; j < 4; j++) + y[(size_t)(l + i) * ldy + r + j] = (bf16)_mm512_reduce_add_ps(acc[i][j]); + } + } +} + +/// \brief y[L][N] = x[L][K] W^T, W read in place from the decode buffer +/// \param y [L][N] bf16, row major +/// \param x [L][K] bf16, row major +/// \note Each 32-row block of W is dequantized once and used for all L rows, so +/// the weight traffic is the weight size whatever L is. fp32 inside, bf16 +/// out (what a dequant_mm overlay would return). +inline void dequant_mm(bf16* y, const q4k_matrix& w, const bf16* x, int L) { + if (L <= 0) return; + const int K = w.K, N = w.N; + assert(K % Q4K_COLS == 0 && N % Q4K_ROWS == 0); + + // x to fp32 once, not once per tile + std::vector xf((size_t)L * K); + prefill_pool().run(L, [&](int64_t l0, int64_t l1, int) { + for (int64_t l = l0; l < l1; l++) + for (int k = 0; k < K; k += 16) + _mm512_storeu_ps(xf.data() + (size_t)l * K + k, load_bfloat16_to_m512(x + (size_t)l * K + k)); + }); + + std::vector> tiles(prefill_pool().threads()); + std::atomic next{0}; + prefill_pool().run(prefill_pool().threads(), [&](int64_t, int64_t, int part) { + std::vector& tile = tiles[part]; + tile.resize((size_t)Q4K_ROWS * K); + for (int rb; (rb = next.fetch_add(1, std::memory_order_relaxed)) < w.row_blocks();) { + w.dequant_row_block(tile.data(), rb); + mm_tile(y + (size_t)rb * Q4K_ROWS, N, tile.data(), xf.data(), L, K); + } + }); +} + +// ============================================================================= +// attention: causal GQA over the decode KV cache +// ============================================================================= +/// \brief one layer's KV cache as the decode overlays keep it: +/// [K col 0][K col 1][V col 0][V col 1], each MAX_L x (2 heads x DH), +/// i.e. all K then all V (same rule as minicpm5_moe_desc::kv_block_offset) +struct kv_cache_view { + bf16* base = nullptr; + uint32_t MAX_L = 0; + int DH = 0; + int heads_per_col = 0; + + size_t col_row() const { return (size_t)heads_per_col * DH; } + /// \brief K (kv = 0) or V (kv = 1) of KV head `head` at token j + bf16* row(int kv, int head, int j) const { + const int col = head / heads_per_col; + const size_t block = (size_t)(2 * kv + col) * MAX_L * col_row(); + return base + block + (size_t)j * col_row() + (size_t)(head % heads_per_col) * DH; + } +}; + +/// \brief out[l] = softmax(q[l] K^T / sqrt(DH)) V for every q head, causal +/// \param out [L][num_heads * DH] bf16, q-head order +/// \param q [L] rows of num_heads * DH, row stride q_stride (normed and roped) +/// \param kv the cache; rows 0 .. pos0 + L - 1 are filled (this call's rows too) +/// \param pos0 position of q row 0: row l attends to cache rows 0 .. pos0 + l +/// \note q head h reads KV head h / (num_heads / num_kv_heads), as transformers' +/// repeat_kv. fp32 scores and softmax. +inline void attention(bf16* out, const bf16* q, int q_stride, const kv_cache_view& kv, + int L, int pos0, int num_heads, int num_kv_heads) { + const int DH = kv.DH; + const int group = num_heads / num_kv_heads; + const float scale = 1.0f / std::sqrt((float)DH); + const int L_kv = pos0 + L; + + std::atomic next{0}; + const int64_t jobs = (int64_t)L * num_heads, chunk = 16; + prefill_pool().run(prefill_pool().threads(), [&](int64_t, int64_t, int) { + std::vector scores(L_kv); + std::vector qf(DH), acc(DH); + for (int64_t b; (b = next.fetch_add(chunk, std::memory_order_relaxed)) < jobs;) { + for (int64_t i = b; i < std::min(jobs, b + chunk); i++) { + const int l = (int)(i / num_heads), h = (int)(i % num_heads); + const int hk = h / group; + const int last = pos0 + l; // causal: keys 0 .. last + const bf16* qh = q + (size_t)l * q_stride + (size_t)h * DH; + for (int d = 0; d < DH; d++) qf[d] = (float)qh[d] * scale; + + float m = -INFINITY; + for (int j = 0; j <= last; j++) { + const bf16* kj = kv.row(0, hk, j); + __m512 s = _mm512_setzero_ps(); + for (int d = 0; d < DH; d += 16) + s = _mm512_fmadd_ps(_mm512_loadu_ps(qf.data() + d), load_bfloat16_to_m512(kj + d), s); + scores[j] = _mm512_reduce_add_ps(s); + m = std::max(m, scores[j]); + } + float sum = 0.0f; + for (int j = 0; j <= last; j++) { + scores[j] = std::exp(scores[j] - m); + sum += scores[j]; + } + std::fill(acc.begin(), acc.end(), 0.0f); + for (int j = 0; j <= last; j++) { + const bf16* vj = kv.row(1, hk, j); + const __m512 p = _mm512_set1_ps(scores[j]); + for (int d = 0; d < DH; d += 16) + _mm512_storeu_ps(acc.data() + d, _mm512_fmadd_ps(p, load_bfloat16_to_m512(vj + d), + _mm512_loadu_ps(acc.data() + d))); + } + bf16* o = out + (size_t)l * num_heads * DH + (size_t)h * DH; + const float inv = 1.0f / sum; + for (int d = 0; d < DH; d++) o[d] = (bf16)(acc[d] * inv); + } + } + }); +} + +} // namespace minicpm5_moe_cpu diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill_overlay.cpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill_overlay.cpp new file mode 100644 index 000000000..afb4ff9ac --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill_overlay.cpp @@ -0,0 +1,727 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_prefill_overlay.cpp +/// \brief The prefill overlay: switching the array between its ops, and the ops' runs +/// \note gen_switch / gen_dispatch / gen_attn_seq / rtm_rearm / glu_gather_dma are the +/// ones the overlay's own test checks bit for bit against the standalone xclbins +/// (FLM_Xclbin/MiniCPM5/prefill_overlay/host/overlay_host.hpp). +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "minicpm5_moe_prefill_overlay.hpp" +#include "minicpm5_moe_prefill_ops.hpp" +#if !defined(FLM_USE_HRX) +#include "launch/txn/elf.hpp" +#endif + +// Each op's configuration (routes, BDs, lock values, chain starts), generated from +// the overlay build by FLM_Xclbin/MiniCPM5/prefill_overlay/tools/extract_txn2.py +// (its host/op_configs.hpp). Copy it again whenever the overlay is rebuilt. +namespace minicpm5_overlay_cfg { +#include "minicpm5_moe_overlay_configs.hpp" +} + +namespace { +using namespace minicpm5_overlay_cfg; + +// must match the overlay's iron/layout.py +constexpr uint32_t RTP_ADDR = 64768; // every core's RTP block +constexpr int RTP_OP = 0, RTP_CALLS = 1, RTP_SWITCHED = 2; +// K_div_k[0] = Din / 512, K_div_k[1] = rows per core row / 16: two consecutive words +constexpr int RTP_DQ_K_DIV_K = 4, RTP_DQ_M = 5, RTP_DQ_ACT = 6; +constexpr uint32_t DQ_ACT_GLU = 3; // y = silu(gate) * up of the core's two n slices +constexpr int RTP_AT_L_BEGIN = 8, RTP_AT_L_CHUNKS = 9, RTP_AT_WINDOW = 10; +constexpr uint32_t OP_LOCK_REG = 0x1F000 + 16 * 15; // core lock 15 value register +constexpr uint32_t DMA_CTRL_RESET = 0x2; // bit 1 of a DMA channel control register +constexpr int ROWS = 4, ATTN_COLS = 8, DQ_COLS = 8; +constexpr int ATTN_ROWS_PER_ROUND = 128; // q rows of one attention round (lc 16 x 8) + +/// \brief lap(acc): adds the time since the last lap (or reset) to acc +struct stopwatch { + std::chrono::steady_clock::time_point t = std::chrono::steady_clock::now(); + void reset() { t = std::chrono::steady_clock::now(); } + void lap(double& acc) { + const auto now = std::chrono::steady_clock::now(); + acc += std::chrono::duration(now - t).count(); + t = now; + } +}; + +void write_reg(npu_sequence* seq, uint32_t row, uint32_t col, uint32_t offset, uint32_t value) { + seq->rtp_write(get_tile(row, col), offset, value); // a plain register write +} + +const op_config& config_of(int op) { + return op == minicpm5_moe_prefill_overlay::OP_DQ ? op_dq : op_attn; +} + +using reg_key = std::tuple; + +/// \brief (col, row, offset) of every register of one kind that either op writes +template +std::vector union_of(Get get) { + std::set all; + for (const op_config* cfg : {&op_dq, &op_attn}) + for (const reg_write& w : get(*cfg)) all.insert({w.col, w.row, w.offset}); + return {all.begin(), all.end()}; +} + +/// \brief the value `regs` gives (col, row, offset), 0 if it doesn't write it +uint32_t value_in(const std::vector& regs, const reg_key& key) { + for (const reg_write& w : regs) + if (w.col == std::get<0>(key) && w.row == std::get<1>(key) && w.offset == std::get<2>(key)) return w.value; + return 0; +} + +size_t write_bd(npu_sequence* seq, const reg_block& b) { + for (size_t i = 0; i < b.words.size(); i++) write_reg(seq, b.row, b.col, b.offset + 4 * (uint32_t)i, b.words[i]); + return b.words.size(); +} + +/// \brief configure the array for op `to`, coming from op `from` (OP_NONE: unknown, +/// so everything is written): stop the DMA channels, then write the op's +/// stream switches, BDs and lock values, then start its chains +void gen_switch(npu_sequence* seq, int to, int from) { + static const std::vector sw_regs = union_of([](const op_config& c) -> const auto& { return c.sw; }); + static const std::vector lock_regs = union_of([](const op_config& c) -> const auto& { return c.locks; }); + const op_config& cfg = config_of(to); + const bool full = from == minicpm5_moe_prefill_overlay::OP_NONE; + + // 1. reset the channels the old op runs on: its chains loop forever on a lock + auto reset = [&](uint32_t row, uint32_t col, uint32_t offset) { + seq->npu_maskwrite(get_tile(row, col), offset, DMA_CTRL_RESET, DMA_CTRL_RESET); + seq->npu_maskwrite(get_tile(row, col), offset, 0, DMA_CTRL_RESET); + }; + if (full) { + for (const reg_write& ch : all_channels) reset(ch.row, ch.col, ch.offset); + } else { + for (const chain_start& s : config_of(from).starts) reset(s.row, s.col, s.ctrl_offset); + } + // 2. routes: the op's value, 0 (port off) where only the other op routes; + // after a known op only the registers whose value differs + for (const reg_key& key : sw_regs) { + const uint32_t v = value_in(cfg.sw, key); + if (!full && v == value_in(config_of(from).sw, key)) continue; + write_reg(seq, std::get<1>(key), std::get<0>(key), std::get<2>(key), v); + } + for (const mask_write& m : cfg.mux) seq->npu_maskwrite(get_tile(m.row, m.col), m.offset, m.value, m.mask); + // 3. BDs only one op uses stay loaded once written (full switch); the few + // both ops use are this op's again after every switch + if (full) { + for (const op_config* c : {&op_dq, &op_attn}) + for (const reg_block& b : c->bds) + if (!b.shared) write_bd(seq, b); + } + for (const reg_block& b : cfg.bds) + if (b.shared) write_bd(seq, b); + // 4. lock values, after the reset (a reset chain may hold a lock count); + // not the op lock: every core is waiting on it + for (const reg_key& key : lock_regs) { + if (std::get<1>(key) >= 2 && std::get<2>(key) == OP_LOCK_REG) continue; + write_reg(seq, std::get<1>(key), std::get<0>(key), std::get<2>(key), value_in(cfg.locks, key)); + } + // 5. start the op's chains + for (const chain_start& s : cfg.starts) { + write_reg(seq, s.row, s.col, s.queue_offset, s.queue_value); + write_reg(seq, s.row, s.col, s.ctrl_offset, s.ctrl_value); + } +} + +/// \brief each core's RTP block for one run of `op`, then let the cores go +void gen_dispatch(npu_sequence* seq, int op, int calls, bool switched, int cols, + std::initializer_list> extra) { + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < cols; c++) { + for (const auto& [idx, value] : extra) write_reg(seq, r + 2, c, RTP_ADDR + 4 * idx, value); + write_reg(seq, r + 2, c, RTP_ADDR + 4 * RTP_OP, op); + write_reg(seq, r + 2, c, RTP_ADDR + 4 * RTP_CALLS, calls); + write_reg(seq, r + 2, c, RTP_ADDR + 4 * RTP_SWITCHED, switched ? 1 : 0); + } + } + // after all RTPs: a core reads its block as soon as its lock is set + for (int r = 0; r < ROWS; r++) + for (int c = 0; c < cols; c++) write_reg(seq, r + 2, c, OP_LOCK_REG, 1); +} + +// ---- dequant_mm: runtime m (rows per core row) and the fused GLU ------------------- +// The array works on blocks of 4 core rows x m rows, m a multiple of 16 up to the 128 +// the design is built for. m lives in the cores' RTP (RTP_DQ_M, read once a call's +// first weights are in), the shim x / y descriptors and the memtile DMA lengths, which +// the switch loads for m = 128: a run with another m (or the GLU) re-arms the memtiles +// and puts them back at its end, so the switch's picture of the dq op stays true. +// The overlay's tools/check_memtile_bds.py checks the ids and values below. +constexpr uint32_t MT_BD_BASE = 0xA0000, MT_BD_STRIDE = 0x20, MT_LOCK_BASE = 0xC0000, MT_LOCK_STRIDE = 0x10; +struct rtm_channel { uint32_t ctrl; uint32_t start_bd; }; +constexpr rtm_channel MT_X_CH[] = {{0xA0600, 0}, {0xA0630, 2}}; // S2MM0, MM2S0 +constexpr rtm_channel MT_Y_CH[] = {{0xA0608, 24}, {0xA0610, 6}, {0xA0618, 26}, {0xA0620, 8}, {0xA0638, 28}}; // S2MM1-4, MM2S1 +constexpr uint32_t MT_X_S2MM[] = {0, 1}; +constexpr uint32_t MT_X_MM2S[] = {2, 3, 4, 5}; +constexpr uint32_t MT_Y_S2MM[] = {6, 7, 8, 9, 24, 25, 26, 27}; +constexpr uint32_t MT_Y_MM2S[] = {28, 29}; +constexpr uint32_t MT_X_LOCKS[] = {0, 1, 2, 3, 4}, MT_X_LOCK_INIT[] = {2, 0, 0, 0, 0}; +constexpr uint32_t MT_Y_LOCKS[] = {5, 6, 7, 8}, MT_Y_LOCK_INIT[] = {4, 4, 0, 0}; +// GLU: a core sends 32 columns per row instead of 64 (y S2MM D2 wrap 8 -> 4 tiles, +// y MM2S D0 wrap 32 -> 16 words, lengths halve) +enum rtm_y_mode : uint32_t { RTM_Y_PLAIN = 0, RTM_Y_GLU = 1, RTM_Y_RESTORE = 2 }; +constexpr uint32_t MT_Y_S2MM_D2_PLAIN = (8u << 17) | 3u, MT_Y_S2MM_D2_GLU = (4u << 17) | 3u; // word 4 +constexpr uint32_t MT_Y_MM2S_D0_PLAIN = 32u << 17, MT_Y_MM2S_D0_GLU = 16u << 17; // word 2 + +/// \brief put the memtile x / y paths on m rows per core row (m = 128, RTM_Y_RESTORE: +/// back to what the switch loads). Reset the channels, put their locks back +/// (writing the maximum first grants an acquire still pending), rewrite the +/// lengths, start the chains again. +void rtm_rearm(npu_sequence* seq, uint32_t m, uint32_t ymode) { + auto bd_word = [](uint32_t bd, uint32_t word) { return MT_BD_BASE + MT_BD_STRIDE * bd + 4 * word; }; + const bool glu = ymode == RTM_Y_GLU; + for (uint32_t col = 0; col < (uint32_t)DQ_COLS; col++) { + const npu_tiles mt = get_tile(1, col); + const bool has_x = (col % 2) == 0; // the x of core row r enters through memtile 2r + if (has_x) for (auto& c : MT_X_CH) seq->rtp_write(mt, c.ctrl, DMA_CTRL_RESET); + for (auto& c : MT_Y_CH) seq->rtp_write(mt, c.ctrl, DMA_CTRL_RESET); + if (has_x) + for (uint32_t i = 0; i < 5; i++) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_X_LOCKS[i], 63); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_X_LOCKS[i], MT_X_LOCK_INIT[i]); + } + for (uint32_t i = 0; i < 4; i++) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_Y_LOCKS[i], 63); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_Y_LOCKS[i], MT_Y_LOCK_INIT[i]); + } + if (has_x) { + for (uint32_t bd : MT_X_S2MM) seq->rtp_write(mt, bd_word(bd, 0), m * 256); + for (uint32_t bd : MT_X_MM2S) seq->rtp_write(mt, bd_word(bd, 0), m * 128); + } + for (uint32_t bd : MT_Y_S2MM) { + seq->rtp_write(mt, bd_word(bd, 0), glu ? m * 16 : m * 32); + if (ymode != RTM_Y_PLAIN) seq->rtp_write(mt, bd_word(bd, 4), glu ? MT_Y_S2MM_D2_GLU : MT_Y_S2MM_D2_PLAIN); + } + for (uint32_t bd : MT_Y_MM2S) { + seq->rtp_write(mt, bd_word(bd, 0), glu ? m * 64 : m * 128); + if (ymode != RTM_Y_PLAIN) seq->rtp_write(mt, bd_word(bd, 2), glu ? MT_Y_MM2S_D0_GLU : MT_Y_MM2S_D0_PLAIN); + seq->rtp_write(mt, bd_word(bd, 4), (m << 17) | 0x1F); + } + if (has_x) for (auto& c : MT_X_CH) { seq->rtp_write(mt, c.ctrl, 0); seq->rtp_write(mt, c.ctrl + 4, c.start_bd); } + for (auto& c : MT_Y_CH) { seq->rtp_write(mt, c.ctrl, 0); seq->rtp_write(mt, c.ctrl + 4, c.start_bd); } + } +} + +/// \brief every dq core's rows per core row (between two jobs of one run: the cores +/// are parked on the next job's first weights, and read it once they are in) +void set_core_m(npu_sequence* seq, uint32_t m) { + for (int r = 0; r < ROWS; r++) + for (int c = 0; c < DQ_COLS; c++) write_reg(seq, r + 2, c, RTP_ADDR + 4 * RTP_DQ_M, m / 16); +} + +/// \brief shim DMA of one core pair's GLU weights: [up block | gate block] per column +/// block, the up rows' first block at `up` and the gate rows' at `gate` (bytes +/// into the weight buffer), both in the `pairs` order (row block rb's column +/// block cb at (rb / 2) 2 bpr + 2 cb + rb % 2). A Q4_K block (1184 words) is +/// longer than a DMA wrap (1024), so each moves as two halves; the column +/// blocks are the iteration. +void glu_gather_dma(npu_sequence* seq, npu_tiles tile, npu_bd_id bd, size_t up, size_t gate, uint32_t Din) { + const size_t bb = get_quantization_byte_size((size_t)QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE, flm_q4k); + const uint32_t bpr = Din / QXNX_COL_BLOCK_SIZE; + assert(bpr < 64 && bb % 8 == 0 && gate > up); + seq->npu_dma_memcpy_nd(sizeof(char), 2, MM2S, tile, bd, it_channel_1, + {0, 0, 0, (uint32_t)up}, + {bpr, 2, 2, (uint32_t)(bb / 2)}, + {(uint32_t)(2 * bb), (uint32_t)(gate - up), (uint32_t)(bb / 2), 1}, -1, 0, false, aggressive_cache); +} + +/// \brief one attention run: buffers arg 0 = o, 1 = q, 2 = the layer's KV cache +/// ([K col0][K col1][V col0][V col1], MAX_L x 2 heads x DH each). +/// gen_seq_1_4 of FLM_Xclbin/Hy_mem_30BA3B/attention_prefill on all 8 +/// columns (4 CUs), with the overlay's switch + RTP blocks in front. +void gen_attn_seq(npu_sequence* seq, int from, uint32_t L_begin, uint32_t L_wanted, int MAX_L, int DH, int Heads, + int KV_Heads, int heads_per_col) { + // 4 CUs of 2 columns; CUs 2h, 2h + 1 (columns 4h .. 4h + 3) share the K / V stream of shim 4h + 3 + npu_tiles IT[4][2] = {{IT0, IT1}, {IT2, IT3}, {IT4, IT5}, {IT6, IT7}}; + const int lc = 16; + const int num_cu = 4; + const int q_per_kv = Heads / KV_Heads; + const int Q_chunks = L_wanted / (lc * 8); + const int window = MAX_L; // plain causal + const size_t KV_CACHE_SIZE = (size_t)MAX_L * 2 * KV_Heads * DH; + assert(L_wanted % (lc * 8) == 0 && Heads % num_cu == 0 && q_per_kv % 2 == 0); + + seq->clear_cmds(); + const bool switched = from != minicpm5_moe_prefill_overlay::OP_ATTN; + if (switched) gen_switch(seq, minicpm5_moe_prefill_overlay::OP_ATTN, from); + // one attn() call per head round + gen_dispatch(seq, minicpm5_moe_prefill_overlay::OP_ATTN, Heads / num_cu, switched, ATTN_COLS, + {{RTP_AT_L_BEGIN, L_begin}, {RTP_AT_L_CHUNKS, (uint32_t)Q_chunks}, {RTP_AT_WINDOW, (uint32_t)window}}); + + const int data_per_round = lc * 8; + for (int head = 0; head < Heads / num_cu; head++) { + for (int round = 0; round < Q_chunks; round++) { + const int Lq_current = L_begin + round * data_per_round; + const int kv_begin = std::max(Lq_current - window, 0); + const int kv_end = (Lq_current + 2 * data_per_round - 1) / data_per_round * data_per_round; + const int kv_length = kv_end - kv_begin; + const int bd_offset = (round % 2) * 8; + for (int cu = 0; cu < num_cu; cu++) { + const int head_offset = head * num_cu + cu; + for (int col = 0; col < 2; col++) { + const size_t y_offset = (size_t)head_offset * DH + (size_t)(round * data_per_round + col * lc * 4) * DH * Heads; + seq->npu_dma_memcpy_nd(2, 0, S2MM, IT[cu][col], (npu_bd_id)(bd_offset + 0), it_channel_0, + {0, 0, 0, (uint32_t)y_offset}, {1, 1, (uint32_t)4 * lc, (uint32_t)DH}, + {0, 0, (uint32_t)DH * Heads, 1}, -1, 0, true); + } + const size_t q_offset = (size_t)head_offset * DH + (size_t)round * data_per_round * DH * Heads; + seq->npu_dma_memcpy_nd(2, 1, MM2S, IT[cu][0], (npu_bd_id)(bd_offset + 1), it_channel_0, + {0, 0, 0, (uint32_t)q_offset}, {1, 1, (uint32_t)lc * 4, (uint32_t)DH}, + {0, 0, (uint32_t)DH * Heads, 1}, -1, 0, false); + seq->npu_dma_memcpy_nd(2, 1, MM2S, IT[cu][0], (npu_bd_id)(bd_offset + 2), it_channel_1, + {0, 0, 0, (uint32_t)(q_offset + (size_t)lc * 4 * DH * Heads)}, {1, 1, (uint32_t)lc * 4, (uint32_t)DH}, + {0, 0, (uint32_t)DH * Heads, 1}, -1, 0, false); + } + // per half of the array, both CUs' q heads share one KV head (GQA): its column + // block and half of the row, from shim 4h + 3 + const std::vector kv_size = {1, (uint32_t)kv_length / 128, 128, (uint32_t)DH}; + const std::vector kv_stride = {0, (uint32_t)(128 * DH * heads_per_col), (uint32_t)(DH * heads_per_col), 1}; + for (int half = 0; half < num_cu / 2; half++) { + const int kv_head = (head * num_cu + 2 * half) / q_per_kv; + const size_t k_offset = (size_t)(kv_head / heads_per_col) * MAX_L * DH * heads_per_col + + (size_t)(kv_head % heads_per_col) * DH + (size_t)kv_begin * DH * heads_per_col; + const size_t v_offset = k_offset + KV_CACHE_SIZE / 2; + seq->npu_dma_memcpy_nd(2, 2, MM2S, IT[2 * half + 1][1], (npu_bd_id)(bd_offset + 3), it_channel_0, + {0, 0, 0, (uint32_t)k_offset}, kv_size, kv_stride, -1, 0, false); + seq->npu_dma_memcpy_nd(2, 2, MM2S, IT[2 * half + 1][1], (npu_bd_id)(bd_offset + 4), it_channel_1, + {0, 0, 0, (uint32_t)v_offset}, kv_size, kv_stride, -1, 0, false); + } + if (round > 0) { + for (int cu = 0; cu < num_cu; cu++) + for (int col = 0; col < 2; col++) seq->npu_dma_wait(IT[cu][col], S2MM, it_channel_0); + } + } + for (int cu = 0; cu < num_cu; cu++) + for (int col = 0; col < 2; col++) seq->npu_dma_wait(IT[cu][col], S2MM, it_channel_0); + } + seq->cmds2seq(); +} + +/// \brief the rows per core row (m) and 4 x m row blocks a dequant_mm of `rows` rows runs +/// with: the fewest blocks of at most 512 rows, m as small as covers them. A re-arm +/// costs ~50 us, so below ~128 rows saved the plain m = 128 blocks are faster. +minicpm5_moe_prefill_overlay::dq_geometry pick_geometry(uint32_t rows) { + assert(rows > 0); + minicpm5_moe_prefill_overlay::dq_geometry g; + g.blocks = (rows + 511) / 512; + g.m = 16 * ((rows + g.blocks * 64 - 1) / (g.blocks * 64)); + g.covered = g.blocks * 4 * g.m; + if (g.blocks * 512 - g.covered < 128) { g.m = 128; g.covered = g.blocks * 512; } + return g; +} + +/// \brief dequant_mm runs back to back in one sequence: for each job, +/// y[row .. row + covered][Dy] = x[row .. row + covered][Din] W^T, W Q4_K (relaid +/// blocks) at the job's w_offset, covered = dq_rows(rows). Buffers: arg 0 = y, +/// 1 = x, 2 = the weight buffer. One job is the plain single run. +/// \note gen_dq_run of FLM_Xclbin/MiniCPM5/prefill_overlay/host/overlay_host.hpp with +/// many jobs. Core column c of 8 takes 64 output rows (32 GLU channels); the 4 cores +/// of a column split the 4 m rows of a block. The cores only count rounds (RTP +/// calls), so the jobs' rounds follow each other, ping-ponging their BDs as within +/// one job. Jobs go by m, largest first: a change of m waits for the rounds in +/// flight, gives the cores the new m (each reads it once its next weights are in) +/// and re-arms the memtiles. +/// \note A job's channel_bytes 0: the rows run straight through the buffer (`pairs`, +/// what the attention / shared weights use). Otherwise a routed expert's +/// `expert_channels` view: its 64-row chunks alternate between two streams this +/// far apart, so 64 output rows come from one stream (see w_chunk below). +/// \param glu the fused GLU (act 3): y = silu(gate) * up, Dy = Dout / 2; W's up and gate +/// rows interleave in pieces of each job's glu_piece rows +void gen_dq_seq(npu_sequence* seq, int from, const std::vector& jobs, + uint32_t Din, uint32_t Dout, bool glu) { + static constexpr npu_tiles IT[8] = {IT0, IT1, IT2, IT3, IT4, IT5, IT6, IT7}; + static constexpr uint32_t desired_k = 512; // kernel/dq/common.hpp NPU_K_TILE + static constexpr uint32_t desired_n = 64; + const uint32_t columns = DQ_COLS; + const int K_div_k = Din / desired_k; + const int N_div_n = Dout / desired_n / columns; + assert(Din % desired_k == 0 && Dout % (desired_n * columns) == 0 && !jobs.empty()); + const uint32_t Dy = glu ? Dout / 2 : Dout; // row pitch of y + const uint32_t pass_cols = glu ? desired_n * columns / 2 : desired_n * columns; // y columns per pass + const uint32_t half_cols = pass_cols / 2; // per memtile group + + // by m, largest first (stable: equal m keep their order) + std::vector order(jobs.size()); + std::vector geo(jobs.size()); + int calls = 0; + for (size_t k = 0; k < jobs.size(); k++) { + order[k] = (int)k; + geo[k] = pick_geometry((uint32_t)jobs[k].rows); + calls += (int)geo[k].blocks * N_div_n; + } + std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return geo[a].m > geo[b].m; }); + + seq->clear_cmds(); + const bool switched = from != minicpm5_moe_prefill_overlay::OP_DQ; + if (switched) gen_switch(seq, minicpm5_moe_prefill_overlay::OP_DQ, from); + uint32_t cur_m = geo[order[0]].m; + if (glu) rtm_rearm(seq, cur_m, RTM_Y_GLU); else if (cur_m != 128) rtm_rearm(seq, cur_m, RTM_Y_PLAIN); + // every core computes one m x 64 tile per round + gen_dispatch(seq, minicpm5_moe_prefill_overlay::OP_DQ, calls, switched, DQ_COLS, + {{RTP_DQ_K_DIV_K, (uint32_t)K_div_k}, {RTP_DQ_M, cur_m / 16}, {RTP_DQ_ACT, glu ? DQ_ACT_GLU : 0u}}); + + auto w_bytes = [](size_t elems) { return get_quantization_byte_size(elems, flm_q4k); }; + const size_t chunk_bytes = w_bytes((size_t)desired_n * Din); // the 64 rows of one array column + const size_t bb = w_bytes((size_t)QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE); + const uint32_t bpr = Din / QXNX_COL_BLOCK_SIZE; + + // a round's y rows are written when the round after it has been issued: at most + // two rounds in flight, each BD set (round % 2) reused only once its round is out + int round = 0, outstanding = 0; + auto wait_round = [&] { + for (int r = 0; r < 4; r++) { + seq->npu_dma_wait(IT[r], S2MM, it_channel_0); + seq->npu_dma_wait(IT[r + 4], S2MM, it_channel_0); + } + outstanding--; + }; + for (int k : order) { + const minicpm5_moe_prefill_overlay::dq_job& job = jobs[k]; + const uint32_t m = geo[k].m; + if (m != cur_m) { + while (outstanding > 0) wait_round(); + set_core_m(seq, m); + rtm_rearm(seq, m, glu ? RTM_Y_GLU : RTM_Y_PLAIN); + cur_m = m; + } + const size_t w_offset = job.w_offset, channel_bytes = job.channel_bytes; + /// where array column `c` of pass `j` finds its 64 rows (plain). + /// Both layouts keep a column's 64 rows contiguous (2 row blocks x every column + /// block); only their starts differ. For expert_channels the row blocks go + /// [ch0 ch0 ch1 ch1] in fours, so chunk g = j * columns + c lands in channel + /// g % 2 (= c % 2, columns being even) as that channel's g / 2'th chunk. + auto w_chunk = [&](int j, uint32_t c) { + const size_t g = (size_t)j * columns + c; + if (channel_bytes == 0) return w_offset + chunk_bytes * g; + return w_offset + (c % 2) * channel_bytes + chunk_bytes * (g / 2); + }; + /// GLU: the first up and gate row blocks of hidden channels 32 u .. 32 u + 31. + /// pairs: [up piece | gate piece] repeated, row block rb at (rb / 2) 2 bpr + rb % 2. + /// expert_channels (pieces of 64 = one chunk): up piece p is chunk 2 p (channel 0's + /// chunk p), its gate piece chunk 2 p + 1 (channel 1's chunk p), in pairs order. + auto glu_rows = [&](uint32_t u) { + const uint32_t r = QXNX_ROW_BLOCK_SIZE * u; + if (channel_bytes == 0) { + const uint32_t piece = (uint32_t)job.glu_piece; + auto block_of = [&](uint32_t row) { + const uint32_t rb = row / QXNX_ROW_BLOCK_SIZE; + return w_offset + ((size_t)(rb / 2) * 2 * bpr + rb % 2) * bb; + }; + const uint32_t up_row = 2 * piece * (r / piece) + r % piece; + return std::make_pair(block_of(up_row), block_of(up_row + piece)); + } + assert(job.glu_piece == (int)desired_n); + const size_t up = w_offset + chunk_bytes * (r / desired_n) + (size_t)((r % desired_n) / QXNX_ROW_BLOCK_SIZE) * bb; + return std::make_pair(up, up + channel_bytes); + }; + + for (uint32_t i = 0; i < geo[k].blocks; i++) { + for (int j = 0; j < N_div_n; j++, round++) { + const int bd_offset = (round % 2) * 8; + const uint32_t row = job.row + i * m * 4; + const uint32_t y_offset = row * Dy + j * pass_cols; + const uint32_t x_offset = row * Din; + const npu_bd_id y_bd_0 = npu_bd_id(0 + bd_offset), y_bd_1 = npu_bd_id(3 + bd_offset); + const npu_bd_id x_bd = npu_bd_id(1 + bd_offset); + const npu_bd_id w_bd_0 = npu_bd_id(2 + bd_offset), w_bd_1 = npu_bd_id(4 + bd_offset); + for (uint32_t col = 0; col < 4; col++) { + if (glu) { + const auto a = glu_rows(columns * j + col), b = glu_rows(columns * j + col + 4); + glu_gather_dma(seq, IT[col], w_bd_0, a.first, a.second, Din); + glu_gather_dma(seq, IT[col + 4], w_bd_1, b.first, b.second, Din); + } else { + seq->npu_dma_memcpy_nd(sizeof(char), 2, MM2S, IT[col], w_bd_0, it_channel_1, + {0, 0, 0, (uint32_t)w_chunk(j, col)}, {1, 1, 1, (uint32_t)chunk_bytes}, + {0, 0, 0, 1}, -1, 0, false, aggressive_cache); + seq->npu_dma_memcpy_nd(sizeof(char), 2, MM2S, IT[col + 4], w_bd_1, it_channel_1, + {0, 0, 0, (uint32_t)w_chunk(j, col + 4)}, {1, 1, 1, (uint32_t)chunk_bytes}, + {0, 0, 0, 1}, -1, 0, false, aggressive_cache); + } + seq->npu_dma_memcpy_nd(2, 0, S2MM, IT[col], y_bd_0, it_channel_0, + {0, 0, 0, (uint32_t)(y_offset + col * m * Dy)}, + {1, 1, m, half_cols}, {0, 0, Dy, 1}, -1, 0, true); + seq->npu_dma_memcpy_nd(2, 0, S2MM, IT[col + 4], y_bd_1, it_channel_0, + {0, 0, 0, (uint32_t)(y_offset + col * m * Dy + half_cols)}, + {1, 1, m, half_cols}, {0, 0, Dy, 1}, -1, 0, true); + seq->npu_dma_memcpy_nd(2, 1, MM2S, IT[2 * col], x_bd, it_channel_0, + {0, 0, 0, x_offset + col * m * Din}, + {1, (uint32_t)K_div_k, m, desired_k}, {0, desired_k, Din, 1}, -1, 0, false); + } + if (++outstanding == 2) wait_round(); + } + } + } + while (outstanding > 0) wait_round(); + // leave the switch's configuration behind (the cores get m with every run) + if (glu) rtm_rearm(seq, 128, RTM_Y_RESTORE); else if (cur_m != 128) rtm_rearm(seq, 128, RTM_Y_PLAIN); + seq->cmds2seq(); +} + +int round_up(int x, int m) { return (x + m - 1) / m * m; } + +// MC5_FAKE_FAIL_AT=[,...]: the n-th overlay run of the process (0-based) reports a failure +bool fake_fail() { + static const std::set at = [] { + std::set s; + const char* p = std::getenv("MC5_FAKE_FAIL_AT"); + while (p && *p) { + char* end = nullptr; + const long n = std::strtol(p, &end, 10); + if (end == p) break; + s.insert(n); + p = *end ? end + 1 : end; + } + return s; + }(); + static std::atomic runs{0}; + if (at.empty()) return false; + return at.count(runs++) > 0; +} + +/// \brief after an overlay run of `what` ended with `st`: nothing to do if it completed. +/// Otherwise the driver ended it (timeout) and reset the array, so the configuration +/// written into it is gone: forget it (`configured`) and run again from a full switch +/// (`again()`, which builds its run from OP_NONE). A second failure throws. +template +void run_again_on_failure(const char* what, ert_cmd_state st, int& configured, Again again) { + if (fake_fail()) st = ERT_CMD_STATE_TIMEOUT; + if (st == ERT_CMD_STATE_COMPLETED) return; + std::string detail; + std::swap(detail, flm::npu::ert_failure_detail()); + std::cerr << "[minicpm5_moe] prefill overlay run " << what << " ended with state " << (int)st + << (detail.empty() ? "" : " (" + detail + ")") << ", not completed: running it again from a full switch" + << std::endl; + configured = minicpm5_moe_prefill_overlay::OP_NONE; + st = again(); + if (st != ERT_CMD_STATE_COMPLETED) { + std::string message = std::string("minicpm5_moe_prefill_overlay: run ") + what + " failed twice (state " + + std::to_string((int)st) + ")"; + if (!flm::npu::ert_failure_detail().empty()) { + message += ": " + flm::npu::ert_failure_detail(); + flm::npu::ert_failure_detail().clear(); + } + throw std::runtime_error(message); + } +} +} // namespace + +minicpm5_moe_prefill_overlay::minicpm5_moe_prefill_overlay(npu_xclbin_manager* npu, const std::string& xclbin, const minicpm5_moe_desc& desc) + : desc(desc) { + mgr = npu->register_xclbin(xclbin); + buf_owner = mgr->create_app(); + batch_slots(1); + q_buf = buf_owner.create_bo_buffer((size_t)MAX_ROWS * desc.DQ); + o_buf = buf_owner.create_bo_buffer((size_t)MAX_ROWS * desc.DQ); + q_buf.memset((bf16)0.0f); +} + +void minicpm5_moe_prefill_overlay::prepare_attention(int L, int pos0, uint32_t MAX_L) { + // padded q rows are zeros; their output rows are dropped + const int L_pad = round_up(L, ATTN_ROWS_PER_ROUND); + if (L_pad > MAX_ROWS || pos0 + L > (int)MAX_L) { + throw std::runtime_error("minicpm5_moe_prefill_overlay: chunk of " + std::to_string(L) + " rows at " + std::to_string(pos0) + + " does not fit (" + std::to_string(MAX_ROWS) + " rows, KV cache " + std::to_string(MAX_L) + ")"); + } + // The last round reads KV rows up to the 128 boundary past its own 128 q rows, + // at most this far past the cache: the last block's zero tail must cover it. + const int last_q = pos0 + L_pad - ATTN_ROWS_PER_ROUND; + const int kv_end = (last_q + 2 * ATTN_ROWS_PER_ROUND - 1) / ATTN_ROWS_PER_ROUND * ATTN_ROWS_PER_ROUND; + assert(kv_end <= (int)(MAX_L + minicpm5_moe_desc::KV_TAIL_ROWS)); + (void)kv_end; + attn_L = L; + attn_L_pad = L_pad; + attn_pos0 = pos0; + attn_MAX_L = MAX_L; + attn_runs.clear(); + // q rows past L (padding) only have to be finite + std::fill(q_buf.data() + (size_t)L * desc.DQ, q_buf.data() + (size_t)attn_L_pad * desc.DQ, (bf16)0.0f); +} + +void minicpm5_moe_prefill_overlay::attention(bf16* out, const bf16* q, int q_stride, buffer& kv_cache) { + const size_t DQ = desc.DQ; + stopwatch sw; + minicpm5_moe_cpu::copy_rows(q_buf.data(), DQ, q, (size_t)q_stride, attn_L, DQ * sizeof(bf16)); + sw.lap(copy_us); + q_buf.sync_to_device((size_t)attn_L_pad * DQ); // the buffer holds MAX_ROWS, this chunk is smaller + sw.lap(sync_us); + + // the switch (if any) is part of the run, so there is one run per op the array may come from + auto run = [&]() { + auto it = attn_runs.find(configured); + if (it == attn_runs.end()) { + npu_app app = mgr->create_app(); + gen_attn_seq(app.seq(), configured, attn_pos0, attn_L_pad, attn_MAX_L, desc.DH, desc.num_heads, + desc.num_kv_heads, desc.num_kv_heads / minicpm5_moe_desc::ATTN_COLS); + it = attn_runs.emplace(configured, std::move(app)).first; + } + return it->second.run_for_state(o_buf, q_buf, kv_cache); + }; + sw.reset(); + run_again_on_failure("attention", run(), configured, run); + configured = after(OP_ATTN); + sw.lap(attn_us); + + o_buf.sync_from_device((size_t)attn_L_pad * DQ); + sw.lap(sync_us); + minicpm5_moe_cpu::copy_rows(out, DQ, o_buf.data(), DQ, attn_L, DQ * sizeof(bf16)); + sw.lap(copy_us); +} + +void minicpm5_moe_prefill_overlay::_ensure_mm_buffers(size_t x_elems, size_t y_elems) { + // A reallocation only changes which buffer a run is called with, never the + // run itself (the buffers are call arguments), so dq_runs stays valid. + if (mm_x.size() < x_elems) mm_x = buf_owner.create_bo_buffer(x_elems); + if (mm_y.size() < y_elems) mm_y = buf_owner.create_bo_buffer(y_elems); +} + +void minicpm5_moe_prefill_overlay::dequant_mm(bf16* y, const bf16* x, int L, buffer& weights, + size_t w_offset, int Din, int Dout, size_t channel_bytes) { + if (L <= 0) return; + if (!fits(Din, Dout)) { + throw std::runtime_error("minicpm5_moe_prefill_overlay: dequant_mm " + std::to_string(Din) + " -> " + + std::to_string(Dout) + " is not a shape the overlay takes"); + } + const int L_pad = dq_rows(L); + _ensure_mm_buffers((size_t)L_pad * Din, (size_t)L_pad * Dout); + + // the padding rows only have to be finite; their output rows are dropped + stopwatch sw; + minicpm5_moe_cpu::copy_rows(mm_x.data(), (size_t)Din, x, (size_t)Din, L, Din * sizeof(bf16)); + std::fill(mm_x.data() + (size_t)L * Din, mm_x.data() + (size_t)L_pad * Din, (bf16)0.0f); + sw.lap(copy_us); + mm_x.sync_to_device((size_t)L_pad * Din); // not the whole allocation: it is + // sized for the largest call, and the + // routed experts are the smallest + sw.lap(sync_us); + + // the switch (if any) is part of the run, so the op the array comes from is part of the key + auto run = [&]() { + const dq_key key{L_pad, Din, Dout, configured, w_offset, channel_bytes}; + auto it = dq_runs.find(key); + if (it == dq_runs.end()) { + if (dq_runs.size() >= MAX_DQ_RUNS) dq_runs.clear(); + npu_app app = mgr->create_app(); + gen_dq_seq(app.seq(), configured, {{0, L, w_offset, channel_bytes}}, (uint32_t)Din, (uint32_t)Dout, false); + it = dq_runs.emplace(key, std::move(app)).first; + } + return it->second.run_for_state(mm_y, mm_x, weights); + }; + sw.reset(); + run_again_on_failure("dequant_mm", run(), configured, run); + configured = after(OP_DQ); + sw.lap(mm_us); + + mm_y.sync_from_device((size_t)L_pad * Dout); + sw.lap(sync_us); + minicpm5_moe_cpu::copy_rows(y, (size_t)Dout, mm_y.data(), (size_t)Dout, L, Dout * sizeof(bf16)); + sw.lap(copy_us); +} + +buffer& minicpm5_moe_prefill_overlay::batch_buffer(int index, size_t elems) { + if (index >= 2) { + while ((int)batch_extra.size() <= index - 2) batch_extra.push_back(std::make_unique>()); + } + buffer& b = index == 0 ? mm_x : index == 1 ? mm_y : *batch_extra[index - 2]; + if (b.size() < elems) { + b = buf_owner.create_bo_buffer(elems); + b.sync_to_device(); + } + return b; +} + +void minicpm5_moe_prefill_overlay::batch_slots(int n) { + while ((int)slots.size() < n) { + auto s = std::make_unique(); + s->app = mgr->create_app(); +#if !defined(FLM_USE_HRX) + // a batch's sequence changes every call: build its kernel with the direct ELF + // writer, several times faster than aiebu (the other runs are built once) + s->app.set_elf_writer([](const uint32_t* w, size_t n) { + return launch::txn::to_elf(std::vector(w, w + n)); + }); +#endif + slots.push_back(std::move(s)); + } +} + +int minicpm5_moe_prefill_overlay::dq_rows(int rows) { return (int)pick_geometry((uint32_t)rows).covered; } + +void minicpm5_moe_prefill_overlay::prepare_batch(int slot, const std::vector& jobs, int Din, int Dout, int from, + bool glu) { + if (!fits(Din, Dout)) { + throw std::runtime_error("minicpm5_moe_prefill_overlay: dequant_mm_batch " + std::to_string(Din) + " -> " + + std::to_string(Dout) + " is not a shape the overlay takes"); + } + // a run made again (run_batch) writes its slot on the NPU thread, maybe while the + // writer thread writes another + std::lock_guard lock(prepare_mutex); + batch_slot& s = *slots.at(slot); + size_t rows = 0; + for (const dq_job& job : jobs) rows = std::max(rows, (size_t)job.row + dq_rows(job.rows)); + s.x_elems = rows * Din; + s.y_elems = rows * (glu ? Dout / 2 : Dout); + s.from = from; + if (&s.jobs != &jobs) s.jobs = jobs; + s.Din = Din; + s.Dout = Dout; + s.glu = glu; + if (jobs.empty()) return; + + // A batch's jobs (experts, their token counts) change with every prompt, so its + // sequence is written for each call into the slot's reused app: the app rebuilds + // its kernel when the sequence changes. + using clk = std::chrono::steady_clock; + auto t = clk::now(); + auto lap = [&](double& acc) { + const auto now = clk::now(); + acc += std::chrono::duration(now - t).count(); + t = now; + }; + gen_dq_seq(s.app.seq(), from, jobs, (uint32_t)Din, (uint32_t)Dout, glu); + lap(seq_us); + s.app.update_ctrl_seq(); + lap(elf_us); +} + +void minicpm5_moe_prefill_overlay::run_batch(int slot, buffer& y, buffer& x, buffer& weights, + unsigned sync) { + batch_slot& s = *slots.at(slot); + if (s.x_elems == 0) return; + if (s.from != configured) { + throw std::logic_error("minicpm5_moe_prefill_overlay: batch run prepared for another op of the array"); + } + assert(x.size() >= s.x_elems && y.size() >= s.y_elems); + stopwatch sw; + if (sync & SYNC_X) x.sync_to_device(s.x_elems); + sw.lap(sync_us); + run_again_on_failure("dequant_mm batch", s.app.run_for_state(y, x, weights), configured, [&]() { + prepare_batch(slot, s.jobs, s.Din, s.Dout, configured, s.glu); // from a full switch now + return s.app.run_for_state(y, x, weights); + }); + configured = after(OP_DQ); + sw.lap(run_us); + if (sync & SYNC_Y) y.sync_from_device(s.y_elems); + sw.lap(sync_us); +} + +void minicpm5_moe_prefill_overlay::dequant_mm_batch(buffer& y, buffer& x, const std::vector& jobs, + buffer& weights, int Din, int Dout, bool glu) { + prepare_batch(0, jobs, Din, Dout, configured, glu); + run_batch(0, y, x, weights); +} + + diff --git a/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill_overlay.hpp b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill_overlay.hpp new file mode 100644 index 000000000..1c0268f9f --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_prefill_overlay.hpp @@ -0,0 +1,193 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_prefill_overlay.hpp +/// \brief The prefill overlay: dequant_mm and attention in one xclbin +/// (FLM_Xclbin/MiniCPM5/prefill_overlay, its README has the design). +/// dequant_mm is the bfp16 one: Q4_K weights dequantized to bfp16 in the core, +/// bf16 activations, 4 x m rows per block with m picked per call (dq_rows), and +/// an optional fused GLU (y = silu(gate) * up) on the output. +/// \note An xclbin fixes its stream routes, DMA BDs and lock values at load time, +/// and the two ops need different ones. So the overlay xclbin holds only what +/// both share (core programs, memory arenas), and the host writes the +/// active op's configuration into the array when the op changes: ~0.12 ms, +/// instead of a ~2 ms hw context switch between two xclbins. +/// +/// Whenever another xclbin runs (decode layers, lm_head), the NPU reloads the +/// overlay on its next run and everything written into it is gone: +/// invalidate() then, and the next run writes the full configuration again. +/// +/// HRX manages the hw contexts itself: it may destroy the overlay's context and +/// create a new one between two overlay runs (seen when an executable it built +/// before is released), which loads the overlay again, with nothing written +/// into it. So on HRX every run writes the full configuration (after()); a +/// run that relied on the previous one's would wait forever on the cores. +/// +/// A run that does not complete (the driver ends it after its timeout and +/// resets the array) loses that configuration too: the run is made again from +/// a full switch, and only a second failure throws. Every run reads its inputs +/// and writes only its own output, so running it again gives the same result. +/// MC5_FAKE_FAIL_AT=[,...] makes the n-th run (0-based) of the process +/// report a failure, to test that path. +#pragma once +#include +#include +#include +#include +#include +#include +#include "npu_utils/npu_utils.hpp" +#include "minicpm5_moe_model_def.hpp" + +class minicpm5_moe_prefill_overlay { +public: + /// ops of the overlay (iron/layout.py OPS); NONE = configuration unknown + enum op_t { OP_NONE = 0, OP_DQ = 1, OP_ATTN = 2 }; + + minicpm5_moe_prefill_overlay(npu_xclbin_manager* npu, const std::string& xclbin, const minicpm5_moe_desc& desc); + + /// \brief another xclbin ran: the next run writes the full configuration + void invalidate() { configured = OP_NONE; } + + /// \brief the op the array is known to be in after a run of `op`: `op`, or OP_NONE + /// where the runtime may load the overlay again between two runs (HRX), so + /// that every run writes the full configuration +#if defined(FLM_USE_HRX) + static constexpr int after(int) { return OP_NONE; } +#else + static constexpr int after(int op) { return op; } +#endif + + /// \brief builds the attention runs for a chunk of L tokens at pos0. Once per + /// chunk: every layer's attention is the same run on its own KV cache. + /// The q rows are zero-padded to a multiple of 128 (one attention + /// round); the cache needs minicpm5_moe_desc::KV_TAIL_ROWS behind it. + void prepare_attention(int L, int pos0, uint32_t MAX_L); + + /// \brief out[L][DQ] = attention of q over one layer's decode KV cache + /// \param q [L] rows of DQ (normed, roped), row stride q_stride + /// \param kv_cache the layer's cache, rows 0 .. pos0 + L - 1 filled and on the device + void attention(bf16* out, const bf16* q, int q_stride, buffer& kv_cache); + + /// \brief y[L][Dout] = x[L][Din] W^T, W the Q4_K matrix at `w_offset` bytes into + /// `weights`, in the overlay's block order (pairs, relaid blocks) + /// \param y [L][Dout] bf16, row major; rows past L are not written + /// \param x [L][Din] bf16, row major + /// \param weights the layer's prefill projection buffer, on the device + /// \note L is padded up to dq_rows(L) with zero rows, whose outputs are dropped. + /// Din % 512 and Dout % 512 must hold; fits() says so. + /// \param channel_bytes 0 for a `pairs` matrix; a routed expert's channel stride + /// for an `expert_channels` one (minicpm5_moe_cpu::q4k_matrix) + void dequant_mm(bf16* y, const bf16* x, int L, buffer& weights, size_t w_offset, int Din, int Dout, + size_t channel_bytes = 0); + + /// \brief one matrix of a batched run: rows row .. row + rows - 1 of the batch's + /// x / y buffers times the Q4_K matrix at w_offset (channel_bytes as in + /// dequant_mm). The run computes dq_rows(rows) rows from `row`: the job + /// owns them, the ones past `rows` only have to be finite in x. + /// \param glu_piece a fused-GLU run's [up | gate] interleave, in rows (the + /// shared expert's SHARED_ROWS_PER_ROUND, a routed one's EXPERT_ROWS_PER_ROUND) + struct dq_job { + int row, rows; + size_t w_offset, channel_bytes; + int glu_piece = 0; + }; + /// \brief how a dequant_mm runs `rows` rows: blocks of 4 core rows x m rows + struct dq_geometry { + uint32_t blocks, m, covered; // covered = blocks * 4 * m >= rows + }; + /// \brief rows a dequant_mm of `rows` rows computes (and its x / y must span) + static int dq_rows(int rows); + /// \brief staging buffer `index` of the batched runs, grown to at least `elems` + /// and kept (0 and 1 are also dequant_mm's own x / y staging) + /// \note A new buffer is flushed once (its zero fill), so one that only the NPU + /// writes and reads never needs a sync again: no dirty host line is left + /// to be written back over it. + buffer& batch_buffer(int index, size_t elems); + + /// \brief every job's y rows = its x rows W^T, all in ONE overlay run (one + /// dispatch instead of one per matrix). Same Din / Dout for every job. + /// \param y, x batch_buffer()s, rows [Din] / [Dout] (glu: [Dout / 2], y = + /// silu(gate) * up); x is synced to the device here and y back, up to the + /// last job's rows + /// \note Every output row depends on its own input row only, so a row's result + /// is the same as in a dequant_mm of that matrix alone. + void dequant_mm_batch(buffer& y, buffer& x, const std::vector& jobs, buffer& weights, + int Din, int Dout, bool glu = false); + + /// \brief dequant_mm_batch in two steps, so that runs can be written while + /// others are on the NPU + /// \param slot 0 .. batch_slots(n) - 1; prepare_batch of one slot may run on + /// another thread during run_batch of another (runs themselves in turn); a + /// run_batch that has to run again writes its own slot again + /// \param from the op the array will be in when the run starts (current_op(), + /// or after(OP_DQ) after another batch run) + void prepare_batch(int slot, const std::vector& jobs, int Din, int Dout, int from, bool glu = false); + /// \param sync which of x (to the device, before) and y (back, after) the run + /// syncs; the caller syncs the others itself, or the host never touches them + enum : unsigned { SYNC_NONE = 0, SYNC_X = 1, SYNC_Y = 2, SYNC_XY = 3 }; + void run_batch(int slot, buffer& y, buffer& x, buffer& weights, unsigned sync = SYNC_XY); + /// \brief at least n slots (not while any prepare / run is in flight) + void batch_slots(int n); + int current_op() const { return configured; } + + /// \brief batch time, summed: writing the sequences, building their kernels + /// (ELF), whether or not hidden behind a run, and the runs themselves + double seq_us = 0.0, elf_us = 0.0, run_us = 0.0; + /// \brief every op's time, summed: BO syncs, host copies in / out of the BOs, the + /// dequant_mm and attention runs (not the batched ones) + double sync_us = 0.0, copy_us = 0.0, mm_us = 0.0, attn_us = 0.0; + + /// \brief can dequant_mm take this shape? (the host version takes any) + static bool fits(int Din, int Dout) { return Din % 512 == 0 && Dout % 512 == 0; } + + /// \brief largest chunk the q / o buffers hold + static constexpr int MAX_ROWS = 4096; +private: + /// \brief x / y staging big enough for these element counts, kept across calls + void _ensure_mm_buffers(size_t x_elems, size_t y_elems); + + const minicpm5_moe_desc& desc; + npu_app_manager* mgr; + int configured = OP_NONE; + + // attention of the prepared chunk, one app per op the array may come from + // (the switch is part of the run's instruction sequence) + std::map attn_runs; + int attn_L = 0, attn_L_pad = 0, attn_pos0 = 0; + uint32_t attn_MAX_L = 0; + npu_app buf_owner; // the app the buffers below were created with + buffer q_buf; // [MAX_ROWS][DQ]: q rows packed, padded to 128 rows + buffer o_buf; // [MAX_ROWS][DQ] + + // dequant_mm: one run per (rows computed, shape, weight offset, op the array comes + // from). The weight buffer is a call argument, so all 28 layers share one run. + struct dq_key { + int L_pad, Din, Dout, from; + size_t w_offset, channel_bytes; + bool operator<(const dq_key& o) const { + return std::tie(L_pad, Din, Dout, from, w_offset, channel_bytes) + < std::tie(o.L_pad, o.Din, o.Dout, o.from, o.w_offset, o.channel_bytes); + } + }; + std::map dq_runs; + /// The routed experts give every (expert, token count) its own run, so the cache + /// can grow without bound over a long session; past this many it is dropped and + /// rebuilt. Each entry is an npu_app (an XRT run plus its instruction buffer). + static constexpr size_t MAX_DQ_RUNS = 2048; + buffer mm_x; // [dq_rows(L)][Din] staging, grown as needed + buffer mm_y; // [dq_rows(L)][Dout] + std::vector>> batch_extra; // batch_buffer(2 ..) + // the batch runs, their sequences rewritten per call + struct batch_slot { + npu_app app; + int from = OP_NONE; // the op it was written for + size_t x_elems = 0, y_elems = 0; // what it reads / writes + // what it was written from, to write it again from a full switch + std::vector jobs; + int Din = 0, Dout = 0; + bool glu = false; + }; + std::vector> slots; + std::mutex prepare_mutex; // one prepare_batch at a time +}; diff --git a/flm-dev-kit/FLM_DLL/engines.json b/flm-dev-kit/FLM_DLL/engines.json index e593e25bb..311f2163b 100644 --- a/flm-dev-kit/FLM_DLL/engines.json +++ b/flm-dev-kit/FLM_DLL/engines.json @@ -189,6 +189,15 @@ ], "uses": [] }, + "minicpm5_moe_npu": { + "families": [ + "minicpm5" + ], + "models": [ + "minicpm5:15b-a2.5b" + ], + "uses": [] + }, "minicpm_ocr_npu": { "families": [ "minicpm-ocr" diff --git a/flm-dev-kit/FLM_DLL/include/models/minicpm5_moe/minicpm5_moe_npu.hpp b/flm-dev-kit/FLM_DLL/include/models/minicpm5_moe/minicpm5_moe_npu.hpp new file mode 100644 index 000000000..f7819ac38 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/include/models/minicpm5_moe/minicpm5_moe_npu.hpp @@ -0,0 +1,93 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file minicpm5_moe_npu.hpp +/// \brief minicpm5_moe_npu class +/// \author FastFlowLM Team +/// \date 2026-12-03 +/// \note The engine for MiniCPM5-15B-A2.5B (minicpm5_moe): 28 layers, layer 0 dense +/// (8192 wide, run as 16 fixed experts of 512) and layers 1..27 MoE (160 +/// experts, top 16, + a shared expert), gated attention, Q4_K body, Q8_0 +/// lm_head. Text only. Decode runs on two bitstreams (moe_layer / lm_head +/// .xclbin); prefill runs prompt chunks batched on prefill_overlay.xclbin. +#pragma once +#include "lm_config.hpp" +#include "npu_utils/npu_utils.hpp" +#include "tensor_utils/q4_npu_eXpress.hpp" +#include "modules/embedding.hpp" +#include "tensor_2d.hpp" +#include "utils/utils.hpp" +#include "causal_lm.hpp" +#include "utils/hybrid_state.hpp" + + +class minicpm5_moe_npu : public causal_lm{ +public: + /// \brief initialize the minicpm5_moe_npu + /// \param config the configuration + /// \param npu_instance the npu instance + /// \param MAX_L KV cache length in tokens; rounded up to a power of two in + /// [4096, 131072] + minicpm5_moe_npu(LM_Config config, npu_xclbin_manager *npu_instance, int MAX_L = 16384); + ~minicpm5_moe_npu(); + + /// \brief decode one token + /// \param ids the token + /// \return the logits (vocab_size) + buffer forward(int ids) override; + + /// \brief run the prompt into the KV cache + /// \return the logits of the last prompt token + buffer prefill(std::vector& ids, void* payload = nullptr) override; + + /// \brief set the context length + /// \param L the context length + void set_context_length(int L) override; + + /// \brief load the weights + /// \param q4nx the q4nx + void load_weights(Q4NX& q4nx) override; + + /// \brief clear the context + void clear_context() override; + + /// \brief get the k cache + /// \param layer_idx the layer index + /// \param idx the token index + /// \return K of that token, all KV heads in head order + buffer get_k_cache(int layer_idx, int idx) override; + + /// \brief get the v cache + /// \param layer_idx the layer index + /// \param idx the token index + /// \return V of that token, all KV heads in head order + buffer get_v_cache(int layer_idx, int idx) override; + + /// \brief grow the KV caches, keeping the conversation + /// \param MAX_L the max length + void update_max_length(uint32_t MAX_L) override; + + /// \brief get the current context length + /// \return the current context length + int get_current_context_length() override; + int checkpoint() override; + int restore() override; + + // ---- saved states (see flm_state_api.h) -------------------------------- + // The engine holds no copy of its own context: read_state() copies the live K/V + // rows into a caller's state, write_state() puts one back. How many states exist + // and which one is used is the caller's business (PrefixSlotCache). + // checkpoint()/restore() keep the legacy single-checkpoint path, which is only a + // remembered context length. + std::unique_ptr new_state(); + int read_state(hybrid_engine_state& state, int kv_from); + int write_state(const hybrid_engine_state& state); + int write_state_kv(const hybrid_engine_state& state); + +private: + struct Impl; + Impl* _impl; +}; + +/// \brief the saved-state table of this engine (flm_state_api.h); nullptr if `engine` is not a minicpm5_moe_npu +extern "C" const flm_state_api* minicpm5_moe_npu_state_api(void* engine); diff --git a/flm-dev-kit/FLM_Q4NX_Converter/configs/minicpm5_moe.json b/flm-dev-kit/FLM_Q4NX_Converter/configs/minicpm5_moe.json new file mode 100644 index 000000000..249606702 --- /dev/null +++ b/flm-dev-kit/FLM_Q4NX_Converter/configs/minicpm5_moe.json @@ -0,0 +1,107 @@ +{ + "q4nx_config": { + "row_block_size": 32, + "col_block_size": 256, + "parallel_size": 32, + "keep_block_in_2D": true + }, + "default_tensor_type": "Q4_K", + "name_map": { + "embedding": { + "gguf_name": "token_embd.weight", + "q4nx_name": "model.embed_tokens.weight", + "default_tensor_type": "BF16" + }, + "q_proj": { + "gguf_name": "blk.{bid}.attn_q.weight", + "q4nx_name": "model.layer.{bid}.self_attn.q_proj.weight" + }, + "k_proj": { + "gguf_name": "blk.{bid}.attn_k.weight", + "q4nx_name": "model.layer.{bid}.self_attn.k_proj.weight" + }, + "v_proj": { + "gguf_name": "blk.{bid}.attn_v.weight", + "q4nx_name": "model.layer.{bid}.self_attn.v_proj.weight" + }, + "attn_gate_proj": { + "gguf_name": "blk.{bid}.attn_gate.weight", + "q4nx_name": "model.layer.{bid}.self_attn.gate_proj.weight" + }, + "o_proj": { + "gguf_name": "blk.{bid}.attn_output.weight", + "q4nx_name": "model.layer.{bid}.self_attn.o_proj.weight" + }, + + "pre_attn_norm": { + "gguf_name": "blk.{bid}.attn_norm.weight", + "q4nx_name": "model.layer.{bid}.input_layernorm.weight", + "default_tensor_type": "BF16" + }, + "post_attn_norm": { + "gguf_name": "blk.{bid}.ffn_norm.weight", + "q4nx_name": "model.layer.{bid}.post_attention_layernorm.weight", + "default_tensor_type": "BF16" + }, + + "dense_up_proj": { + "gguf_name": "blk.{bid}.ffn_up.weight", + "q4nx_name": "model.layer.{bid}.mlp.up_proj.weight" + }, + "dense_gate_proj": { + "gguf_name": "blk.{bid}.ffn_gate.weight", + "q4nx_name": "model.layer.{bid}.mlp.gate_proj.weight" + }, + "dense_down_proj": { + "gguf_name": "blk.{bid}.ffn_down.weight", + "q4nx_name": "model.layer.{bid}.mlp.down_proj.weight" + }, + + "router": { + "gguf_name": "blk.{bid}.ffn_gate_inp.weight", + "q4nx_name": "model.layer.{bid}.moe_router.weight", + "default_tensor_type": "BF16" + }, + "router_expert_bias": { + "gguf_name": "blk.{bid}.exp_probs_b.bias", + "q4nx_name": "model.layer.{bid}.moe_expert_bias", + "default_tensor_type": "F32" + }, + + "up_exp_proj": { + "gguf_name": "blk.{bid}.ffn_up_exps.weight", + "q4nx_name": "model.layer.{bid}.mlp.up_exps_proj.weight" + }, + "up_share_exp_proj": { + "gguf_name": "blk.{bid}.ffn_up_shexp.weight", + "q4nx_name": "model.layer.{bid}.mlp.share_up_exps_proj.weight" + }, + "gate_exp_proj": { + "gguf_name": "blk.{bid}.ffn_gate_exps.weight", + "q4nx_name": "model.layer.{bid}.mlp.gate_exps_proj.weight" + }, + "gate_share_exp_proj": { + "gguf_name": "blk.{bid}.ffn_gate_shexp.weight", + "q4nx_name": "model.layer.{bid}.mlp.share_gate_exps_proj.weight" + }, + "down_exp_proj": { + "gguf_name": "blk.{bid}.ffn_down_exps.weight", + "q4nx_name": "model.layer.{bid}.mlp.down_exps_proj.weight" + }, + "down_share_exp_proj": { + "gguf_name": "blk.{bid}.ffn_down_shexp.weight", + "q4nx_name": "model.layer.{bid}.mlp.share_down_exps_proj.weight" + }, + + "model_final_norm": { + "gguf_name": "output_norm.weight", + "q4nx_name": "model.norm.weight", + "default_tensor_type": "BF16" + }, + "lm_head": { + "gguf_name": "output.weight", + "q4nx_name": "lm_head.weight", + "default_tensor_type": "Q8_0" + } + } +} diff --git a/flm-dev-kit/FLM_Q4NX_Converter/q4nx/constants.py b/flm-dev-kit/FLM_Q4NX_Converter/q4nx/constants.py index 164c7369c..c36e4f5f8 100644 --- a/flm-dev-kit/FLM_Q4NX_Converter/q4nx/constants.py +++ b/flm-dev-kit/FLM_Q4NX_Converter/q4nx/constants.py @@ -39,6 +39,7 @@ class ModelArch(IntEnum): QWEN3_ASR = auto() INKLING2_LOOP = auto() INKLING2_DFLASH2 = auto() + MINICPM5_MOE = auto() MINICPM_V_1B_BF16 = auto() @@ -92,6 +93,8 @@ class ModelArch(IntEnum): ModelArch.INKLING2_LOOP: ["inkling2_loop", "inkling-2", "inkling2"], # Read from the HF safetensors by convert_inkling2_dflash2.py, never detected from a GGUF. ModelArch.INKLING2_DFLASH2: [], + # MiniCPM5-15B-A2.5B reports general.architecture = "minicpm5_moe". + ModelArch.MINICPM5_MOE: ["minicpm5_moe", "minicpm5"], } ModelArchConfigs: dict[ModelArch, str] = { @@ -127,4 +130,5 @@ class ModelArch(IntEnum): ModelArch.QWEN3_ASR: "qwen3_asr.json", ModelArch.INKLING2_LOOP: "inkling2_loop.json", ModelArch.INKLING2_DFLASH2: "inkling2_dflash2.json", + ModelArch.MINICPM5_MOE: "minicpm5_moe.json", } \ No newline at end of file diff --git a/flm-dev-kit/FLM_Q4NX_Converter/q4nx/models/__init__.py b/flm-dev-kit/FLM_Q4NX_Converter/q4nx/models/__init__.py index 697793c9c..48d54ca77 100644 --- a/flm-dev-kit/FLM_Q4NX_Converter/q4nx/models/__init__.py +++ b/flm-dev-kit/FLM_Q4NX_Converter/q4nx/models/__init__.py @@ -35,4 +35,5 @@ from .inkling2_dflash2 import Inkling2DFlash2 from .qwen3_asr import Qwen3ASR from .inkling2 import Inkling2Loop -__all__ = ['Qwen3VL', 'Llama', 'LFM2', 'LFM3', 'Qwen3', 'Qwen2', 'Qwen2VL', 'Gemma3', 'Gemma4', 'Gemma4_12B', 'Phi4', 'GPTOSS', 'Nanbeige', 'Qwen35', 'Qwen35_2B', 'Qwen35_9B', 'Qwen35_08B', 'Qwen35_27B', 'Qwen35Omni', 'QWEN35_A3B', 'HunyuanDense', 'Qwen38_27B', 'MiniCPM_V_1B', 'MiniCPM_V_1B_BF16', 'MiniCPM_OCR_1B', 'DFlash', 'Qwen38DFlash2','MiniCPM_V_35B_A3B', 'HyMemory30BA3B', 'Qwen3ASR', 'Inkling2Loop', 'Inkling2DFlash2'] +from .minicpm5 import MiniCPM5MoE +__all__ = ['Qwen3VL', 'Llama', 'LFM2', 'LFM3', 'Qwen3', 'Qwen2', 'Qwen2VL', 'Gemma3', 'Gemma4', 'Gemma4_12B', 'Phi4', 'GPTOSS', 'Nanbeige', 'Qwen35', 'Qwen35_2B', 'Qwen35_9B', 'Qwen35_08B', 'Qwen35_27B', 'Qwen35Omni', 'QWEN35_A3B', 'HunyuanDense', 'Qwen38_27B', 'MiniCPM_V_1B', 'MiniCPM_V_1B_BF16', 'MiniCPM_OCR_1B', 'DFlash', 'Qwen38DFlash2','MiniCPM_V_35B_A3B', 'HyMemory30BA3B', 'Qwen3ASR', 'Inkling2Loop', 'Inkling2DFlash2', 'MiniCPM5MoE'] diff --git a/flm-dev-kit/FLM_Q4NX_Converter/q4nx/models/minicpm5.py b/flm-dev-kit/FLM_Q4NX_Converter/q4nx/models/minicpm5.py new file mode 100644 index 000000000..9b35f471a --- /dev/null +++ b/flm-dev-kit/FLM_Q4NX_Converter/q4nx/models/minicpm5.py @@ -0,0 +1,39 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +from ..constants import ModelArch +from .hy_mem import HyMemory30BA3B + +from gguf import GGUFReader + + +class MiniCPM5MoE(HyMemory30BA3B, model_arch=ModelArch.MINICPM5_MOE): + """Converter for the `minicpm5_moe` GGUF architecture (openbmb MiniCPM5-15B-A2.5B). + + The layer is Hy-Memory's (plain GQA attention on every layer, dense layer 0, + sigmoid router with a selection-only expert bias, one shared expert), so the + packing is inherited unchanged. The differences are all in the name map: + + * 32 q / 2 kv heads, head_dim 128, and no per-head q/k norms. + * A sigmoid output gate per head: HF stores it interleaved in q_proj + ([q 128 | gate 128] rows per head); llama.cpp splits it out as + `attn_gate` [4096, 2048], rows in head order, which is what the engine + reads. No RoPE row permute (HF rotate_half order, as for Hy-Memory). + * Layers 1..27: 160 experts of width 512, top-16, plus a 512-wide shared + expert. Router [160, 2048] -> BF16 [2048, 160]; bias [160] -> F32. + + The GGUF must be all-Q4_K in the projections, BF16 token_embd and Q8_0 + output (the release recipe, see the model card); a stock *_K_M mix with + Q6_K tensors is rejected rather than silently re-quantized. + """ + + def __init__(self, gguf_reader: GGUFReader): + print("[INFO] Using MiniCPM5MoE converter") + self.gguf_reader = gguf_reader + self.gguf_tensors = [] + self.initialize() + + def convert(self, q4nx_path: str, weights_type: str = 'language'): + if weights_type != 'language': + raise ValueError(f"Unsupported weights_type: {weights_type} for minicpm5_moe") + super().convert(q4nx_path, weights_type) diff --git a/flm-dev-kit/FLM_Q4NX_Converter/verify_minicpm5_q4nx.py b/flm-dev-kit/FLM_Q4NX_Converter/verify_minicpm5_q4nx.py new file mode 100644 index 000000000..e6dd1e09d --- /dev/null +++ b/flm-dev-kit/FLM_Q4NX_Converter/verify_minicpm5_q4nx.py @@ -0,0 +1,325 @@ +#!./venv/bin/python3 +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""Check a MiniCPM5-15B-A2.5B model.q4nx against the GGUF it came from. + +Decodes the packed q4k / q8nx blocks back to float32 and compares them with the +GGUF dequantization (and, with --hf, with the original BF16 checkpoint): + + * every expected tensor is present with the expected dtype and shape + * BF16 / F32 tensors (embedding, norms, router, expert bias) are exact + * Q4_K: the 4-bit codes are bit-identical to the GGUF's; the values differ + only by the (BF16 S', uint8 s') super-block re-fit of _pack_q4k + * Q8_0 (lm_head): codes identical, scales are bf16_RNE(fp16 scale) + +The HF checkpoint interleaves the output gate into q_proj ([q 128 | gate 128] +rows per head); the comparison splits it back into q and gate. + +Usage: + ./verify_minicpm5_q4nx.py --gguf model.gguf --q4nx out/model.q4nx [--hf ] +""" +import argparse +import json +import os + +import numpy as np +import torch +from gguf import GGUFReader, dequantize +from safetensors import safe_open + +N_LAYERS = 28 +VOCAB = 130560 +D = 2048 +N_HEADS = 32 +HEAD_DIM = 128 +KV_DIM = 2 * HEAD_DIM +DENSE_I = 8192 +N_EXPERTS = 160 +EXPERT_I = 512 + +ROWS = 32 # row_block_size +COLS = 256 # col_block_size +GROUP = 32 # weights per Q4_K / Q8_0 group +GROUPS = COLS // GROUP +Q4K_BLOCK_BYTES = ROWS * GROUPS * 2 + ROWS * COLS // 2 + ROWS * 2 * 2 # 4736 +Q8_BLOCK_BYTES = ROWS * GROUPS * 2 + ROWS * COLS # 4352 + + +# ---------------------------------------------------------------- block decoders +def decode_q4k(blob: np.ndarray): + """[P, U, 4736] int8 -> (weights [P*32, U*256] fp32, codes [P*32, U*256] uint8). + + Block byte layout (_pack_q4k), everything column major over the block: + uint8 s8[8 groups][32 rows] per-group scale + uint8 m8[8 groups][32 rows] per-group min + uint4 q [256 cols][16 bytes] rows paired per byte, even row = low nibble + bf16 S [32 rows] super-block scale + bf16 Mneg[32 rows] super-block min, stored negated + w[r, c] = S[r] * s8[g, r] * q[r, c] + Mneg[r] * m8[g, r], g = c // 32 + """ + P, U, _ = blob.shape + b = blob.reshape(P * U, Q4K_BLOCK_BYTES).view(np.uint8) + + # cut the block into its five planes + o = 0 + s8 = b[:, o:o + GROUPS * ROWS].reshape(-1, GROUPS, ROWS).astype(np.float32); o += GROUPS * ROWS + m8 = b[:, o:o + GROUPS * ROWS].reshape(-1, GROUPS, ROWS).astype(np.float32); o += GROUPS * ROWS + qb = b[:, o:o + COLS * ROWS // 2].reshape(-1, COLS, ROWS // 2); o += COLS * ROWS // 2 + S = bf16_bytes_to_f32(b[:, o:o + ROWS * 2]); o += ROWS * 2 + Mneg = bf16_bytes_to_f32(b[:, o:o + ROWS * 2]); o += ROWS * 2 + assert o == Q4K_BLOCK_BYTES + + # unpack nibbles: byte k of a column holds rows 2k (low) and 2k+1 (high) + q = np.stack([qb & 0x0F, qb >> 4], axis=-1).reshape(-1, COLS, ROWS) # [blk, col, row] + q = q.transpose(0, 2, 1) # [blk, row, col] + + # broadcast group values over their 32 columns: [blk, g, row] -> [blk, row, col] + scale = np.repeat((S[:, None, :] * s8).transpose(0, 2, 1), GROUP, axis=2) + minv = np.repeat((Mneg[:, None, :] * m8).transpose(0, 2, 1), GROUP, axis=2) + w = scale * q.astype(np.float32) + minv + + return blocks_to_matrix(w, P, U), blocks_to_matrix(q, P, U) + + +def decode_q8(blob: np.ndarray): + """[P, U, 4352] int8 -> (weights, codes). bf16 scales[8 groups][32 rows], then + int8 q[256 cols][32 rows] (parallel_size == row_block_size, so plain column major).""" + P, U, _ = blob.shape + b = blob.reshape(P * U, Q8_BLOCK_BYTES) + d = bf16_bytes_to_f32(b[:, :GROUPS * ROWS * 2].view(np.uint8)).reshape(-1, GROUPS, ROWS) + q = b[:, GROUPS * ROWS * 2:].reshape(-1, COLS, ROWS).transpose(0, 2, 1) # [blk, row, col] + scale = np.repeat(d.transpose(0, 2, 1), GROUP, axis=2) + w = scale * q.astype(np.float32) + return blocks_to_matrix(w, P, U), blocks_to_matrix(q, P, U) + + +def bf16_bytes_to_f32(raw: np.ndarray) -> np.ndarray: + # bf16 is the top half of an fp32: shift the 16 bits up and reinterpret + u16 = np.ascontiguousarray(raw).view(np.uint16) + return (u16.astype(np.uint32) << 16).view(np.float32) + + +def blocks_to_matrix(x: np.ndarray, P: int, U: int) -> np.ndarray: + # [P*U, 32, 256] -> [P*32, U*256] + return x.reshape(P, U, ROWS, COLS).transpose(0, 2, 1, 3).reshape(P * ROWS, U * COLS) + + +# ---------------------------------------------------------------- GGUF side +def gguf_q4k_codes(data: np.ndarray, cols: int) -> np.ndarray: + """Raw Q4_K nibbles in natural (row, col) order (same walk as GGUFTensor.unpack_q4_k).""" + blocks = data.view(np.uint8).reshape(-1, 144) + qb = blocks[:, 16:].reshape(-1, 4, 32) + q = np.stack([qb & 0x0F, qb >> 4], axis=2).reshape(-1, 256) + return q.reshape(-1, cols) + + +def gguf_q8_codes(data: np.ndarray, cols: int) -> np.ndarray: + blocks = data.view(np.uint8).reshape(-1, 34) + return blocks[:, 2:].view(np.int8).reshape(-1, cols) + + +# ---------------------------------------------------------------- HF side +class HFCheckpoint: + """Sharded HF safetensors, read through model.safetensors.index.json.""" + def __init__(self, model_dir: str): + with open(os.path.join(model_dir, "model.safetensors.index.json")) as f: + self.weight_map = json.load(f)["weight_map"] + self.dir = model_dir + self.files = {} + + def get(self, name: str) -> np.ndarray: + shard = self.weight_map[name] + if shard not in self.files: + self.files[shard] = safe_open(os.path.join(self.dir, shard), framework="pt") + return self.files[shard].get_tensor(name).float().numpy() + + +def hf_q_or_gate(hf: HFCheckpoint, layer: int, which: int) -> np.ndarray: + # q_proj rows per head: [q 128 | gate 128]; which = 0 -> q, 1 -> gate + w = hf.get(f"model.layers.{layer}.self_attn.q_proj.weight") + w = w.reshape(N_HEADS, 2, HEAD_DIM, D)[:, which] + return w.reshape(N_HEADS * HEAD_DIM, D) + + +# ---------------------------------------------------------------- metrics +def stats(a: np.ndarray, ref: np.ndarray) -> str: + a = a.astype(np.float64).ravel() + ref = ref.astype(np.float64).ravel() + cos = a @ ref / (np.linalg.norm(a) * np.linalg.norm(ref)) + rel = np.linalg.norm(a - ref) / np.linalg.norm(ref) + return f"cos {cos:.7f} relRMSE {rel:.2e} maxabs {np.abs(a - ref).max():.2e}" + + +# ---------------------------------------------------------------- main +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--gguf", required=True) + ap.add_argument("--q4nx", required=True) + ap.add_argument("--hf", default=None, help="optional original BF16 checkpoint directory (sharded)") + ap.add_argument("--layers", default="0,1,14,27", help="layers to decode in full") + ap.add_argument("--experts", default="0,77,159", help="experts to decode per MoE layer") + args = ap.parse_args() + layers = [int(x) for x in args.layers.split(",")] + experts = [int(x) for x in args.experts.split(",")] + + reader = GGUFReader(args.gguf) + g = {t.name: t for t in reader.tensors} + nx = safe_open(args.q4nx, framework="pt") + hf = HFCheckpoint(args.hf) if args.hf else None + failures = [] + + def fail(msg): + print(f" FAIL {msg}") + failures.append(msg) + + # ---- 1. inventory: names, dtypes, shapes for every layer + print("== inventory") + expect = { + "model.embed_tokens.weight": (torch.bfloat16, (VOCAB, D)), + "model.norm.weight": (torch.bfloat16, (D,)), + "lm_head.weight": (torch.int8, (VOCAB // ROWS, D // COLS, Q8_BLOCK_BYTES)), + } + + def q4k_shape(rows, cols): + return (torch.int8, (rows // ROWS, cols // COLS, Q4K_BLOCK_BYTES)) + + QD = N_HEADS * HEAD_DIM + for L in range(N_LAYERS): + p = f"model.layer.{L}." + expect[p + "self_attn.q_proj.weight"] = q4k_shape(QD, D) + expect[p + "self_attn.gate_proj.weight"] = q4k_shape(QD, D) + expect[p + "self_attn.k_proj.weight"] = q4k_shape(KV_DIM, D) + expect[p + "self_attn.v_proj.weight"] = q4k_shape(KV_DIM, D) + expect[p + "self_attn.o_proj.weight"] = q4k_shape(D, QD) + expect[p + "input_layernorm.weight"] = (torch.bfloat16, (D,)) + expect[p + "post_attention_layernorm.weight"] = (torch.bfloat16, (D,)) + if L == 0: + expect[p + "mlp.gate_proj.weight"] = q4k_shape(DENSE_I, D) + expect[p + "mlp.up_proj.weight"] = q4k_shape(DENSE_I, D) + expect[p + "mlp.down_proj.weight"] = q4k_shape(D, DENSE_I) + else: + expect[p + "moe_router.weight"] = (torch.bfloat16, (D, N_EXPERTS)) + expect[p + "moe_expert_bias"] = (torch.float32, (N_EXPERTS,)) + expect[p + "mlp.gate_exps_proj.weight"] = q4k_shape(N_EXPERTS * EXPERT_I, D) + expect[p + "mlp.up_exps_proj.weight"] = q4k_shape(N_EXPERTS * EXPERT_I, D) + expect[p + "mlp.down_exps_proj.weight"] = q4k_shape(N_EXPERTS * D, EXPERT_I) + expect[p + "mlp.share_gate_exps_proj.weight"] = q4k_shape(EXPERT_I, D) + expect[p + "mlp.share_up_exps_proj.weight"] = q4k_shape(EXPERT_I, D) + expect[p + "mlp.share_down_exps_proj.weight"] = q4k_shape(D, EXPERT_I) + + have = set(nx.keys()) + for name in sorted(set(expect) - have): + fail(f"missing {name}") + for name in sorted(have - set(expect)): + fail(f"unexpected {name}") + for name in sorted(set(expect) & have): + sl = nx.get_slice(name) + dtype, shape = expect[name] + got_shape = tuple(sl.get_shape()) + got_dtype = {"BF16": torch.bfloat16, "F32": torch.float32, "I8": torch.int8}.get(sl.get_dtype()) + if got_shape != shape or got_dtype != dtype: + fail(f"{name}: {sl.get_dtype()} {got_shape}, expected {dtype} {shape}") + print(f" {len(have)} tensors in file, {len(expect)} expected") + + # ---- 2. exact tensors + print("== BF16 / F32 tensors (must be exact)") + + def gdeq(name): + t = g[name] + return np.asarray(dequantize(t.data, t.tensor_type), dtype=np.float32) + + def to_bf16(x): + return torch.from_numpy(np.ascontiguousarray(x)).to(torch.bfloat16).float().numpy() + + def check_exact(q4nx_name, ref, hf_ref=None): + got = nx.get_tensor(q4nx_name).float().numpy() + same = np.array_equal(got, ref) + line = f" {'ok ' if same else 'FAIL'} {q4nx_name}" + if hf_ref is not None: + line += f" | vs HF {stats(got, hf_ref)}" + print(line) + if not same: + fail(f"{q4nx_name} not exact, {stats(got, ref)}") + + check_exact("model.embed_tokens.weight", gdeq("token_embd.weight")) + check_exact("model.norm.weight", gdeq("output_norm.weight")) + for L in layers: + p, h = f"model.layer.{L}.", f"model.layers.{L}." + check_exact(p + "input_layernorm.weight", gdeq(f"blk.{L}.attn_norm.weight")) + check_exact(p + "post_attention_layernorm.weight", gdeq(f"blk.{L}.ffn_norm.weight")) + if L > 0: + # the router is stored bf16 (its GGUF copy is F32): exact after bf16 rounding + check_exact(p + "moe_router.weight", to_bf16(gdeq(f"blk.{L}.ffn_gate_inp.weight").T), + hf.get(h + "mlp.gate.weight").T if hf else None) + check_exact(p + "moe_expert_bias", gdeq(f"blk.{L}.exp_probs_b.bias"), + hf.get(h + "mlp.gate.e_score_correction_bias") if hf else None) + + # ---- 3. quantized tensors + print("== quantized tensors (codes must match; values differ only by the scale re-fit)") + + def check_quant(q4nx_name, gguf_name, hf_ref=None, expert_rows=None): + """hf_ref: callable(expert or None) -> HF matrix. + expert_rows: rows per expert; decodes only args.experts of a 3D tensor.""" + t = g[gguf_name] + cols = int(t.shape[0]) + blob_all = nx.get_tensor(q4nx_name).numpy() + is_q8 = blob_all.shape[-1] == Q8_BLOCK_BYTES + + ref_all = np.asarray(dequantize(t.data, t.tensor_type), dtype=np.float32).reshape(-1, cols) + if is_q8: + codes_all = gguf_q8_codes(t.data, cols) + else: + codes_all = gguf_q4k_codes(t.data, cols) + + pieces = experts if expert_rows else [None] + for e in pieces: + if e is None: + r0, r1, label = 0, ref_all.shape[0], q4nx_name + else: + r0, r1, label = e * expert_rows, (e + 1) * expert_rows, f"{q4nx_name}[expert {e}]" + blob = blob_all[r0 // ROWS: r1 // ROWS] + w, codes = decode_q8(blob) if is_q8 else decode_q4k(blob) + ref = ref_all[r0:r1] + same_codes = np.array_equal(codes.astype(np.int16), codes_all[r0:r1].astype(np.int16)) + line = f" {'ok ' if same_codes else 'FAIL'} {label:62s} vs GGUF {stats(w, ref)}" + if hf is not None and hf_ref is not None: + line += f" | vs HF cos {stats(w, hf_ref(e)).split()[1]}" + print(line) + if not same_codes: + fail(f"{label}: codes differ from GGUF") + + def hf_plain(name): + return lambda e: hf.get(name if e is None else name.format(e=e)) + + check_quant("lm_head.weight", "output.weight", hf_plain("lm_head.weight")) + for L in layers: + p, b, h = f"model.layer.{L}.", f"blk.{L}.", f"model.layers.{L}." + check_quant(p + "self_attn.q_proj.weight", b + "attn_q.weight", + lambda e, L=L: hf_q_or_gate(hf, L, 0)) + check_quant(p + "self_attn.gate_proj.weight", b + "attn_gate.weight", + lambda e, L=L: hf_q_or_gate(hf, L, 1)) + check_quant(p + "self_attn.k_proj.weight", b + "attn_k.weight", hf_plain(h + "self_attn.k_proj.weight")) + check_quant(p + "self_attn.v_proj.weight", b + "attn_v.weight", hf_plain(h + "self_attn.v_proj.weight")) + check_quant(p + "self_attn.o_proj.weight", b + "attn_output.weight", hf_plain(h + "self_attn.o_proj.weight")) + if L == 0: + for k in ("gate", "up", "down"): + check_quant(p + f"mlp.{k}_proj.weight", b + f"ffn_{k}.weight", hf_plain(h + f"mlp.{k}_proj.weight")) + else: + for k in ("gate", "up", "down"): + rows = D if k == "down" else EXPERT_I + check_quant(p + f"mlp.{k}_exps_proj.weight", b + f"ffn_{k}_exps.weight", + hf_plain(h + f"mlp.experts.{{e}}.{k}_proj.weight"), expert_rows=rows) + check_quant(p + f"mlp.share_{k}_exps_proj.weight", b + f"ffn_{k}_shexp.weight", + hf_plain(h + f"mlp.shared_experts.{k}_proj.weight")) + + print() + if failures: + print(f"{len(failures)} FAILURES") + raise SystemExit(1) + print("ALL CHECKS PASSED") + + + +if __name__ == "__main__": + main() diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/.gitignore b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/.gitignore new file mode 100755 index 000000000..eef2e8562 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/.gitignore @@ -0,0 +1,6 @@ +build +*.exe +*.txt +iron/__pycache__/* +trace.* +model.q4nx diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/Makefile b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/Makefile new file mode 100755 index 000000000..e74c09a44 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/Makefile @@ -0,0 +1,64 @@ +# +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Modified by Alfred + +include makefiles/common.mk +MODEL_TYPE ?= MINICPM5_15B_A2_5B +HOME_DIR := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST)))) + +KERNEL_ARGS := -DMODEL_TYPE=${MODEL_TYPE} +IRON_ARGS := ${MODEL_TYPE} + +# Kernel makefile +include makefiles/kernel.mk + +# Bitstream makefile +include makefiles/bitstream.mk + +# Host makefile +include makefiles/host.mk + +.PHONY: run all kernel link bitstream host clean clean_all instructions +all: ${XCLBIN_TARGET} ${INSTS_TARGET} ${HOST_C_TARGET} + +clean_all: + -@rm -rf build + -@rm -rf log + -@rm -rf *.exe + -@rm -rf trace* + -@rm -rf routes + + + +kernel: ${KERNEL_OBJS} + + +instructions: ${INSTS_TARGETS} + + +link: ${MLIR_TARGET} + + +bitstream: ${XCLBIN_TARGETS} + + +host: ${HOST_C_TARGET} + + +clean: + -@rm -rf build/run.exe + -@rm -rf ${HOST_C_TARGET} + + + +test: $(HOST_C_TARGET) + export LD_LIBRARY_PATH=/opt/xilinx/xrt/lib && ./$(HOST_C_TARGET) -m ${MODEL_TYPE} + +route: ${IRON_BOTH_MLIR_TARGET} + mkdir -p routes + aie-opt --aie-create-pathfinder-flows --aie-find-flows ${<} | aie-translate --aie-flows-to-json > ./routes/route.json + python visualize.py -j ./routes/route.json diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/README.md b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/README.md new file mode 100755 index 000000000..7f3a31bf0 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/README.md @@ -0,0 +1,28 @@ + + +# NPU_FlashAttention + +## MiniCPM5-15B-A2.5B + +`MODEL_TYPE=MINICPM5_15B_A2_5B` (the default): vocab 130560, padded to 131072 rows on the host +(the logits past 130560 are ignored), RMS eps 1e-6, untied Q8_0 lm_head. +`./run.exe` reads `$FLM_MODEL_PATH/models/MiniCPM5-15B-A2.5B-NPU2` (else +`~/.config/flm/models/...`): `config.json` and `model.q4nx`. + +Result (2026-12-03, Peano llvm-aie `22.0.0.2026090201`): logits vs the CPU Q8_0 reference +mean cos 0.999989, min 0.999985, top-1 8/8. + +## Peano (Hy-Memory LM head, the unit this one was copied from) + +Peano is the default (`ENABLE_CHESSCC ?= 0` in `makefiles/`), as in `../../Qwen3_5/lm_head_npu_bin`; +`ENABLE_CHESSCC=1` builds with chess. The Peano parts are the parent's: the mean for the +RMS scale is computed with `AIE_FADD / AIE_FMUL` (compiler-rt softfloat) so it rounds like +chess, the scale itself is `flm_rsqrt` (one hardware `invsqrt` on both compilers), and the ping/pong flags live in `.data` (Peano's loader does not zero `.bss`). +Build with `make bitstream`: plain `make` builds only `run.exe` (its `all` target names +variables that do not exist, as in the parent). + +Result (2026-11-04, CI Peano llvm-aie `22.0.0.2026090201`): logits vs the CPU Q8_0 reference +mean cos 0.999988 (same as chess), 5.15-5.17 ms per call host + NPU (chess 5.19-5.68). diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/host/embedding_q8_0.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/host/embedding_q8_0.hpp new file mode 100644 index 000000000..14abcae56 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/host/embedding_q8_0.hpp @@ -0,0 +1,74 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __EMBEDDING_Q8_0_HPP__ +#define __EMBEDDING_Q8_0_HPP__ +#include "buffer.hpp" +#include "typedef.hpp" +#include + +/// \brief Recover embedding rows by dequantizing the packed q8_0 lm_head. +/// \note Newer converters tie the word embeddings and emit only the quantized +/// lm_head, so model.embed_tokens.weight is simply absent. Reading the +/// embedding back out of lm_head.weight works either way, which is why +/// the DLL (FLM_DLL/detail/qwen3_5vl_npu/embedding_q8_0.hpp) does the +/// same. This version dequantizes one row at a time instead of building +/// the whole [vocab, dim] table: the test only ever looks up a handful of +/// tokens, and the full table would be over a gigabyte. +class embedding_q8_0 { +private: + // Packing config, must match _pack_q8nx / dequant_q8_0 in the converter. + static constexpr int m = 32; //!< ROW_BLOCK_SIZE + static constexpr int k = 256; //!< COL_BLOCK_SIZE + static constexpr int parallel_size = 32; + static constexpr int q8_group_size = 32; + + static constexpr int c = k / q8_group_size; //!< scale groups per block col + static constexpr size_t scale_bytes = (size_t)c * m * sizeof(bf16); //!< 512 + static constexpr size_t data_bytes = (size_t)m * k; //!< 8192 + static constexpr size_t block_bytes = scale_bytes + data_bytes; //!< 8704 + + const u8* base; + size_t vocab_size; + size_t dim; + size_t b_cols; + +public: + /// \param packed lm_head.weight exactly as it comes out of the q4nx file, + /// i.e. before reorder_cpy_q80 shuffles it for the NPU + embedding_q8_0(buffer& packed, size_t vocab_size, size_t dim) + : base(packed.begin()), vocab_size(vocab_size), dim(dim) + { + // The packed weight is padded to whole (m x k) blocks on both dims, so + // derive the block grid from the buffer rather than from vocab_size. + this->b_cols = (dim + k - 1) / k; + assert(packed.size() % (this->b_cols * block_bytes) == 0); + assert(packed.size() / (this->b_cols * block_bytes) * m >= vocab_size); + } + + /// \brief Dequantize one vocab row into out[0..dim). + void forward(int token, bf16* out) const + { + assert(token >= 0 && (size_t)token < this->vocab_size); + const size_t br = (size_t)token / m; + const int ri = token % m; + // data was reordered '(r_div_parallel parallel) c -> (r_div_parallel c parallel)'; + // r_div_parallel is 1 here, so rp is always 0 and p is just the row. + const int p = ri % parallel_size; + + for (size_t bc = 0; bc < this->b_cols; bc++) { + const u8* blk = this->base + (br * this->b_cols + bc) * block_bytes; + const bf16* scales = reinterpret_cast(blk); + const int8_t* data = reinterpret_cast(blk + scale_bytes); + + const size_t col_base = bc * (size_t)k; + for (int ci = 0; ci < k; ci++) { + if (col_base + ci >= this->dim) break; // skip padded cols + // scales packed as (c m) within the block -> flat = group * m + ri + const float scale = (float)scales[(ci / q8_group_size) * m + ri]; + out[col_base + ci] = (bf16)(scale * (float)data[(size_t)ci * parallel_size + p]); + } + } + } +}; + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/host/host.cpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/host/host.cpp new file mode 100644 index 000000000..825b81f3a --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/host/host.cpp @@ -0,0 +1,444 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "typedef.hpp" +#include "buffer.hpp" +#include "npu_utils/npu_utils.hpp" +#include "tensor_utils/q4_npu_eXpress.hpp" +#include "utils/debug_utils.hpp" +#include "utils/vm_args.hpp" +#include "utils/utils.hpp" +#include "metrices.hpp" +#include "tensor_2d.hpp" +#include "lm_config.hpp" +#include "embedding_q8_0.hpp" +#include +#include +#include +#include + +void generate_seq(npu_sequence* seq, int VOCAB_SIZE, int D); +void reorder_cpy_q80(u8 *dst, buffer &src, const int col, const int vertical_blocks); + +// Where a model lives and how its files look. +struct model_entry { + std::string config_dir; // folder with config.json + std::string q4nx_dir; // folder with model.q4nx + bool hf_config; // config.json is the plain HF one (LM_Config::from_pretrained asserts FLM fields) + bool tied_embedding; // no model.embed_tokens.weight: rebuild it from lm_head +}; + +/// \brief Where flm keeps its models: $FLM_MODEL_PATH/models, else ~/.config/flm/models. +inline std::string flm_models_dir() { + const char* root = std::getenv("FLM_MODEL_PATH"); + if (root && *root) return std::string(root) + "/models"; + const char* home = std::getenv("HOME"); + return std::string(home ? home : ".") + "/.config/flm/models"; +} + +static std::map get_model_table() { + const std::string qwen_base = flm_models_dir() + "/"; + const std::string hy_dir = flm_models_dir() + "/Hy-Memory-30B-A3B"; + const std::string mc5_dir = flm_models_dir() + "/MiniCPM5-15B-A2.5B-NPU2"; + return { + {"QWEN3_5_0_8B", {qwen_base + "Qwen3.5-0.8B-NPU2", qwen_base + "Qwen3.5-0.8B-NPU2", false, true}}, + {"QWEN3_5_2B", {qwen_base + "Qwen3.5-2B-NPU2", qwen_base + "Qwen3.5-2B-NPU2", false, true}}, + {"QWEN3_5_4B", {qwen_base + "Qwen3.5-4B-NPU2", qwen_base + "Qwen3.5-4B-NPU2", false, true}}, + {"QWEN3_5_9B", {qwen_base + "Qwen3.5-9B-NPU2", qwen_base + "Qwen3.5-9B-NPU2", false, true}}, + // Hy: HF config.json at the top, model.q4nx in q4nx/, and a separate bf16 + // embedding (tie_word_embeddings = false) + {"HY_MEMORY_30B_A3B", {hy_dir, hy_dir + "/q4nx", true, false}}, + // MiniCPM5: HF config.json and model.q4nx side by side, bf16 embedding + {"MINICPM5_15B_A2_5B", {mc5_dir, mc5_dir, true, false}}, + }; +} + +// Only the three numbers this test needs, read straight from an HF config.json. +static void read_hf_config(const std::string& dir, size_t& D, size_t& vocab, float& eps) { + std::ifstream file(dir + "/config.json"); + if (!file.is_open()) { + header_print("error", "Cannot open " << dir << "/config.json"); + exit(1); + } + nlohmann::json cfg = nlohmann::json::parse(file); + D = cfg.at("hidden_size").get(); + vocab = cfg.at("vocab_size").get(); + eps = cfg.at("rms_norm_eps").get(); +} + +/// CPU reference of the whole NPU call: final RMS norm, then logits = W_q8 x. +/// \param packed lm_head.weight as it is in the q4nx file (before reorder_cpy_q80): +/// [vocab/32][D/256] blocks of [scales bf16 (8 groups x 32 rows) | q int8 (256 cols x 32 rows)] +static void ref_lm_head(const u8* packed, const bf16* x, const bf16* norm_w, + size_t D, size_t vocab, float eps, std::vector& logits) { + constexpr int ROWS = 32, COLS = 256, GROUP = 32; + constexpr size_t SCALE_BYTES = (COLS / GROUP) * ROWS * sizeof(bf16); // 512 + constexpr size_t BLOCK_BYTES = SCALE_BYTES + ROWS * COLS; // 8704 + + // final norm, done like the kernel: (x * w) * (1 / rms), rounded to bf16 + double sum_sq = 0.0; + for (size_t i = 0; i < D; i++) { + double v = (float)x[i]; + sum_sq += v * v; + } + float inv_rms = 1.0f / std::sqrt((float)(sum_sq / D) + eps); + std::vector xn(D); + for (size_t i = 0; i < D; i++) { + float wx = (float)x[i] * (float)norm_w[i]; + xn[i] = (float)(bf16)(wx * inv_rms); + } + + const size_t col_blocks = D / COLS; + logits.assign(vocab, 0.0f); + for (size_t br = 0; br < vocab / ROWS; br++) { + float row_acc[ROWS] = {0}; + for (size_t bc = 0; bc < col_blocks; bc++) { + const u8* blk = packed + (br * col_blocks + bc) * BLOCK_BYTES; + const bf16* scales = reinterpret_cast(blk); + const int8_t* q = reinterpret_cast(blk + SCALE_BYTES); + for (int g = 0; g < COLS / GROUP; g++) { + // one 32-wide group: sum q * x for all 32 rows, then apply each row's scale + float group_acc[ROWS] = {0}; + for (int t = 0; t < GROUP; t++) { + const int ci = g * GROUP + t; + const float xv = xn[bc * COLS + ci]; + const int8_t* q_col = q + ci * ROWS; // a column's 32 rows are next to each other + for (int r = 0; r < ROWS; r++) + group_acc[r] += (float)q_col[r] * xv; + } + for (int r = 0; r < ROWS; r++) + row_acc[r] += group_acc[r] * (float)scales[g * ROWS + r]; + } + } + for (int r = 0; r < ROWS; r++) + logits[br * ROWS + r] = row_acc[r]; + } +} + +static size_t argmax(const std::vector& v) { + size_t best = 0; + for (size_t i = 1; i < v.size(); i++) + if (v[i] > v[best]) best = i; + return best; +} + +static float cosine(const std::vector& a, const std::vector& b) { + double dot = 0.0, aa = 0.0, bb = 0.0; + for (size_t i = 0; i < a.size(); i++) { + dot += (double)a[i] * b[i]; + aa += (double)a[i] * a[i]; + bb += (double)b[i] * b[i]; + } + return (float)(dot / (std::sqrt(aa) * std::sqrt(bb))); +} + +int main(int argc, char* argv[]) { + arg_utils::po::options_description desc("Allowed options"); + arg_utils::po::variables_map vm; + arg_utils::add_default_options(desc); + desc.add_options()("model,m", arg_utils::po::value()->default_value("MINICPM5_15B_A2_5B"), "Model type, e.g., MINICPM5_15B_A2_5B"); + desc.add_options()("tokens,n", arg_utils::po::value()->default_value(32), "Number of random tokens to test"); + + arg_utils::parse_options(argc, argv, desc, vm); + + std::string model_type = vm["model"].as(); + int test_size = vm["tokens"].as(); + + header_print("info", "Testing model: " + model_type); + + // -m picks both the checkpoint and the matching xclbin; the builds differ in + // MODEL_DIM and VOCAB_SIZE, which are baked into the kernel, so they are not + // interchangeable. + const auto model_table = get_model_table(); + auto entry_it = model_table.find(model_type); + if (entry_it == model_table.end()){ + header_print("error", "Unknown model type: " + model_type); + return 1; + } + const model_entry& entry = entry_it->second; + header_print("info", "Model path: " + entry.q4nx_dir); + + size_t D = 0, VOCAB_SIZE = 0; + float rms_eps = 0.0f; + if (entry.hf_config) { + read_hf_config(entry.config_dir, D, VOCAB_SIZE, rms_eps); + } else { + LM_Config lm_config; + lm_config.from_pretrained(entry.config_dir); + D = lm_config.hidden_size; + VOCAB_SIZE = lm_config.vocab_size; + rms_eps = lm_config.rms_norm_eps > 0.0f ? lm_config.rms_norm_eps : 1e-6f; + } + size_t M_PER_ROUND = 32 * 32; + size_t VOCAB_SIZE_PADDED = (VOCAB_SIZE + M_PER_ROUND - 1) / M_PER_ROUND * M_PER_ROUND; + + std::string xclbin_name = "./build/" + model_type + "/xclbins/lm_head.xclbin"; + header_print("info", "LM head xclbin path: " + xclbin_name); + header_print("info", "Hidden size (D): " + std::to_string(D)); + header_print("info", "Vocab size: " + std::to_string(VOCAB_SIZE) + " (padded " + std::to_string(VOCAB_SIZE_PADDED) + ")"); + header_print("info", "RMS eps: " << rms_eps); + + std::unique_ptr q4nx_model = std::make_unique(entry.q4nx_dir); + + buffer lm_head_packed; + q4nx_model->load_weights(lm_head_packed, "lm_head.weight"); + + // Input rows: random token embeddings. A tied checkpoint has no + // model.embed_tokens.weight, so its rows are dequantized from lm_head (as the + // DLL does, FLM_DLL/detail/qwen3_5vl_npu); Hy has its own bf16 table. + srand(time(NULL)); + std::vector input_ids(test_size); + for (int i = 0; i < test_size; i++){ + input_ids[i] = rand() % VOCAB_SIZE; + } + buffer x(D * test_size); + if (entry.tied_embedding) { + embedding_q8_0 embed(lm_head_packed, VOCAB_SIZE, D); + for (int i = 0; i < test_size; i++){ + embed.forward(input_ids[i], x.data() + i * D); + } + } else { + buffer embed_table; + q4nx_model->load_weights(embed_table, "model.embed_tokens.weight"); + for (int i = 0; i < test_size; i++){ + memcpy(x.data() + i * D, embed_table.data() + (size_t)input_ids[i] * D, D * sizeof(bf16)); + } + } + + header_print("info", "Initializing NPU manager..."); + xrt::device npu_inst = xrt::device(0); + npu_xclbin_manager xclbin_mgr(npu_device::device_npu2, &npu_inst, false); + npu_app_manager* lm_head_app_mgr = xclbin_mgr.register_xclbin(xclbin_name); + npu_app lm_head = lm_head_app_mgr->create_app(); + + size_t lm_head_weight_size = D * VOCAB_SIZE_PADDED + D * VOCAB_SIZE_PADDED / 32 * 2; + + buffer lm_head_weights = lm_head.create_bo_buffer(lm_head_weight_size); + buffer lm_head_output = lm_head.create_bo_buffer(VOCAB_SIZE_PADDED); + buffer lm_head_input = lm_head.create_bo_buffer(D * 2); + buffer lm_head_output_valid = buffer(lm_head_output.data(), VOCAB_SIZE); + + lm_head_weights.memset(0); + lm_head_output.memset((bf16)0.0f); + lm_head_output.sync_to_device(); + + header_print("info", "Vocab got: " + std::to_string(lm_head_packed.size() * 8 / 8.5 / D)); + header_print("info", "Vocab reserved: " + std::to_string(lm_head_weights.size() * 8 / 8.5 / D)); + reorder_cpy_q80(lm_head_weights.data(), lm_head_packed, D, 4); + + // the kernel reads the final norm weight from the second half of its x buffer + buffer final_rms_weight; + q4nx_model->load_weights(final_rms_weight, "model.norm.weight"); + memcpy(lm_head_input.data() + D, final_rms_weight.data(), D * sizeof(bf16)); + lm_head_input.sync_to_device(); + + generate_seq(lm_head.seq(), VOCAB_SIZE_PADDED, D); + + lm_head_weights.sync_to_device(); + lm_head_app_mgr->get_ready(); + lm_head_app_mgr->ready(); + + header_print("info", "Running " + std::to_string(test_size) + " tokens..."); + double total_us = 0.0; + double sum_cos = 0.0; + float min_cos = 1.0f; + int top1_match = 0; + // A near tie can flip top-1 between two correct answers; count a mismatch as + // real only when the NPU's pick is clearly below the reference's best logit. + int top1_bad = 0; + std::vector y_npu(VOCAB_SIZE), y_ref; + for (int i = 0; i < test_size; i++) { + memcpy(lm_head_input.data(), x.data() + i * D, D * sizeof(bf16)); + lm_head_input.sync_to_device(); + + auto start = std::chrono::steady_clock::now(); + lm_head(lm_head_output, lm_head_weights, lm_head_input); + auto end = std::chrono::steady_clock::now(); + total_us += std::chrono::duration(end - start).count(); + + lm_head_output.sync_from_device(); + for (size_t j = 0; j < VOCAB_SIZE; j++){ + y_npu[j] = (float)lm_head_output_valid[j]; + } + + ref_lm_head(lm_head_packed.data(), x.data() + i * D, final_rms_weight.data(), + D, VOCAB_SIZE, rms_eps, y_ref); + + float cos = cosine(y_npu, y_ref); + size_t top_npu = argmax(y_npu); + size_t top_ref = argmax(y_ref); + float gap = y_ref[top_ref] - y_ref[top_npu]; // how much worse the NPU's pick is in the reference + bool same = top_npu == top_ref; + bool bad = !same && gap > 0.01f * std::fabs(y_ref[top_ref]); + top1_match += same; + top1_bad += bad; + sum_cos += cos; + min_cos = std::min(min_cos, cos); + + std::cout << "token " << i << " id " << input_ids[i] + << ": cos " << cos + << ", top-1 npu " << top_npu << " ref " << top_ref + << (same ? "" : (bad ? " MISMATCH" : " (near tie)")) << std::endl; + } + + // simple pass rule: logits nearly identical and no real top-1 mismatch + const float COS_FLOOR = 0.999f; + bool pass = min_cos >= COS_FLOOR && top1_bad == 0; + + std::cout << "\n===== RESULT =====" << std::endl; + std::cout << "logits vs CPU Q8_0 reference: mean cos " << sum_cos / test_size + << ", min cos " << min_cos << std::endl; + std::cout << "top-1 match: " << top1_match << "/" << test_size + << " (real mismatches " << top1_bad << ")" << std::endl; + std::cout << "time per call: " << total_us / test_size << " us (host + NPU)" << std::endl; + std::cout << (pass ? "PASS" : "FAIL") << " (min cos >= " << COS_FLOOR << ", no real top-1 mismatch)" << std::endl; + return pass ? 0 : 1; +} + +void generate_seq(npu_sequence* seq, int VOCAB_SIZE, int D){ + static constexpr int y_arg_id = 0; + static constexpr int w_arg_id = 1; + static constexpr int x_arg_id = 2; + static constexpr int M_PER_ROUND = 32 * 32; + static constexpr int M = 32; + static constexpr int M_PER_COL = M * 4; + static constexpr int COLS = 8; + static npu_tiles ITs[] = {IT0, IT1, IT2, IT3, IT4, IT5, IT6, IT7}; + // Packet ids for the two flows that share IT0's MM2S 0 -- must match X_PKT_ID / + // W_PKT_ID in iron/q4k_mm.py. Every other shim MM2S port is circuit-switched. + static constexpr int X_PKT_ID = 0; + static constexpr int W_PKT_ID = 1; + static constexpr int NO_PKT = -1; + // Rounds of shim BD ping-pong; also how far the y waits lag the y issues. + static constexpr int LOOKAHEAD = 3; + assert(VOCAB_SIZE % M_PER_ROUND == 0); + int rounds = VOCAB_SIZE / M_PER_ROUND; + size_t W_PER_COL = int(M_PER_COL * D * 8.5 / 8) / sizeof(bf16); + size_t W_PER_ROUND = W_PER_COL * COLS; + // Each column's weights are split over two shim MM2S channels, one per pair of + // cores; reorder_cpy_q80 has already laid the two halves out back to back. + size_t W_PER_STREAM = W_PER_COL / 2; + + seq->clear_cmds(); + seq->npu_dma_memcpy_nd( + sizeof(bf16), + x_arg_id, + MM2S, + ITs[0], + npu_bd_id(bd_0), + it_channel_0, + {0, 0, 0, 0}, + {1, 1, 1, (uint32_t)D * 2}, + {0, 0, 0, 1}, + X_PKT_ID, 0, false, aggressive_cache + ); + + for (int r = 0; r < rounds; r++) { + int bd_offset = (r % (LOOKAHEAD + 1)) * 3; + npu_bd_id bd_y = npu_bd_id(bd_1 + bd_offset); + npu_bd_id bd_wa = npu_bd_id(bd_2 + bd_offset); + npu_bd_id bd_wb = npu_bd_id(bd_3 + bd_offset); + for (size_t col = 0; col < std::size(ITs); col++){ + size_t w_col_offset = r * W_PER_ROUND + col * W_PER_COL; + uint32_t y_offset = r * M_PER_ROUND + col * M_PER_COL; + seq->npu_dma_memcpy_nd( + sizeof(bf16), + y_arg_id, + S2MM, + ITs[col], + bd_y, + it_channel_0, + {0, 0, 0, (uint32_t)(y_offset)}, + {1, 1, 1, (uint32_t)M_PER_COL}, + {0, 0, 0, 1}, + -1, 0, true, aggressive_cache + ); + // Group a (cores 0/1) on channel 1, group b (cores 2/3) on channel 0. + // Channel 0 of IT0 is the one shared with the x broadcast, so only that + // transfer needs a packet id. + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_arg_id, + MM2S, + ITs[col], + bd_wa, + it_channel_1, + {0, 0, 0, (uint32_t)(w_col_offset)}, + {1, 1, 1, (uint32_t)W_PER_STREAM}, + {0, 0, 0, 1}, + NO_PKT, 0, false, aggressive_cache + ); + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_arg_id, + MM2S, + ITs[col], + bd_wb, + it_channel_0, + {0, 0, 0, (uint32_t)(w_col_offset + W_PER_STREAM)}, + {1, 1, 1, (uint32_t)W_PER_STREAM}, + {0, 0, 0, 1}, + col == 0 ? W_PKT_ID : NO_PKT, 0, false, aggressive_cache + ); + // Four sets of shim BDs are in flight, so a round only has to wait for + // the y of the round three back rather than the one immediately before. + // That keeps three rounds of weight transfers queued ahead of the + // sequencer instead of one. + if (r > LOOKAHEAD - 1){ + seq->npu_dma_wait( + ITs[col], + S2MM, + it_channel_0 + ); + } + } + } + for (size_t col = 0; col < std::size(ITs); col++){ + for (int i = 0; i < LOOKAHEAD; i++){ + seq->npu_dma_wait( + ITs[col], + S2MM, + it_channel_0 + ); + } + } + + seq->cmds2seq(); +} + +void reorder_cpy_q80(u8 *dst, buffer &src, const int col, const int vertical_blocks) +{ + // return; + const int a_block_size = 32 * 256 + 256 * 2; + const int blocks_per_row = col / 256; + + const int rows = src.size() / a_block_size / blocks_per_row; + + // A column's weights arrive on two shim channels, one per pair of cores, so each + // column-round has to be two contiguous halves in DDR rather than one run with all + // four cores' blocks interleaved: rows r+0/r+1 of the group for the stream that + // feeds cores 0 and 1, rows r+2/r+3 for the stream that feeds cores 2 and 3. Within + // a half the order is still k-major, one block per core, because that is exactly one + // memtile slot. See lm_head_memtile in iron/q4k_mm.py. + const int rows_per_stream = vertical_blocks / 2; + + u8 *dst_ptr = dst; + for (int r = 0; r < rows; r += vertical_blocks) + { + for (int half = 0; half < 2; half++) + { + for (int c = 0; c < blocks_per_row; c++) + { + for (int i = 0; i < rows_per_stream; i++) + { + const int row = r + half * rows_per_stream + i; + const u8 *src_ptr = (row < rows) + ? src.data() + (size_t)(row * blocks_per_row + c) * a_block_size + : src.data(); // useless padding + memcpy(dst_ptr, src_ptr, a_block_size); + dst_ptr += a_block_size; + } + } + } + } +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/iron/lm_head_aie.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/iron/lm_head_aie.py new file mode 100644 index 000000000..5b3e8cd3a --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/iron/lm_head_aie.py @@ -0,0 +1,118 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +import numpy as np +import sys + +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +from aie.extras import types as T +import aie.dialects.aie as aie +import aie.dialects.aiex as aiex +from aie.helpers.dialects.ext.scf import _for as range_ +import aie.utils.trace as trace_utils +from aie.utils.trace import MemTilePortEvent, MemTileEvent, PortEvent +from aie.utils.trace_events_enum import CoreEvent, MemEvent, ShimTileEvent, MemTileEvent +from aie.dialects import memref + +from utils import dma_mm2s_ch, dma_s2mm_ch, flow_mm2s_ch, flow_s2mm_ch, connect_dma, generate_tile_map, mlir_context +from utils import dma_port, connect_port +from q4k_mm import lm_head_column, W_PKT_ID + +from enum import IntEnum, auto + +class ModelArch(IntEnum): + QWEN3_5_0_8B = auto() + QWEN3_5_2B = auto() + QWEN3_5_4B = auto() + QWEN3_5_9B = auto() + HY_MEMORY_30B_A3B = auto() + MINICPM5_15B_A2_5B = auto() + +ModelArchNames: dict[ModelArch, str] = { + ModelArch.QWEN3_5_0_8B: "QWEN3_5_0_8B", + ModelArch.QWEN3_5_2B : "QWEN3_5_2B", + ModelArch.QWEN3_5_4B : "QWEN3_5_4B", + ModelArch.QWEN3_5_9B : "QWEN3_5_9B", + ModelArch.HY_MEMORY_30B_A3B: "HY_MEMORY_30B_A3B", + ModelArch.MINICPM5_15B_A2_5B: "MINICPM5_15B_A2_5B" +} + +# The dataflow only depends on D; the vocab size lives in the kernel and the +# host sequence (kernel/qmm.cc). +DIM_TABLE = { + ModelArch.QWEN3_5_0_8B: 1024, + ModelArch.QWEN3_5_2B: 2048, + ModelArch.QWEN3_5_4B: 2560, + ModelArch.QWEN3_5_9B: 4096, + ModelArch.HY_MEMORY_30B_A3B: 2048, + ModelArch.MINICPM5_15B_A2_5B: 2048 +} + + +def lm_head_top(model_name: str): + + dev = aie.AIEDevice.npu2 + total_cols = 8 + total_rows = 4 + + Q4NX_ROW_BLOCK_SIZE: int = 32 + Q4NX_COL_BLOCK_SIZE: int = 256 + + MODEL_DIM: int = DIM_TABLE[ModelArch[model_name]] + + W_BLOCK_SIZE = int(Q4NX_COL_BLOCK_SIZE * Q4NX_ROW_BLOCK_SIZE * 8.5 // 8 // 2) + + w_dtype = np.dtype[bfloat16] + x_dtype = np.dtype[bfloat16] + y_dtype = np.dtype[bfloat16] + + with mlir_mod_ctx() as ctx: + @aie.device(dev) + def device_body(): + IT, MT, CT = generate_tile_map(total_rows + 2, total_cols) + + mctx = mlir_context() + x_ty = mctx.data_ty('x_ty', (MODEL_DIM, 2), x_dtype) + w_ty = mctx.data_ty('w_ty', (W_BLOCK_SIZE, 1), w_dtype) + y_ty = mctx.data_ty('y_ty', (Q4NX_ROW_BLOCK_SIZE, 1), y_dtype) + # A memtile weight slot holds one k-block for each of the two cores its + # group feeds, not one for every core in the column: the column's weights + # arrive on two shim channels now. See lm_head_memtile. + w_mem_ty = mctx.data_ty('w_mem_ty', (W_BLOCK_SIZE * 2, 1), w_dtype) + y_mem_ty = mctx.data_ty('y_mem_ty', (Q4NX_ROW_BLOCK_SIZE * total_rows, 1), y_dtype) + + mctx.parameter('W_BLOCK_SIZE', W_BLOCK_SIZE) + mctx.parameter('Q4NX_ROW_BLOCK_SIZE', Q4NX_ROW_BLOCK_SIZE) + + mctx.func("qmm", [mctx.y_ty, mctx.y_ty, mctx.w_ty, mctx.w_ty, mctx.x_ty]) + + lm_head_core_0 = [CT[i][0] for i in range(total_rows)] + lm_head_core_1 = [CT[i][1] for i in range(total_rows)] + lm_head_core_2 = [CT[i][2] for i in range(total_rows)] + lm_head_core_3 = [CT[i][3] for i in range(total_rows)] + lm_head_core_4 = [CT[i][4] for i in range(total_rows)] + lm_head_core_5 = [CT[i][5] for i in range(total_rows)] + lm_head_core_6 = [CT[i][6] for i in range(total_rows)] + lm_head_core_7 = [CT[i][7] for i in range(total_rows)] + + # Column 0's shim MM2S 0 is shared with the x broadcast, so its second + # weight stream is packet-switched; the rest get a plain flow. + lm_head_column(lm_head_core_0, MT[0], IT[0], IT[0], mctx, w_pkt_id = W_PKT_ID) + lm_head_column(lm_head_core_1, MT[1], IT[1], IT[0], mctx) + lm_head_column(lm_head_core_2, MT[2], IT[2], IT[0], mctx) + lm_head_column(lm_head_core_3, MT[3], IT[3], IT[0], mctx) + lm_head_column(lm_head_core_4, MT[4], IT[4], IT[0], mctx) + lm_head_column(lm_head_core_5, MT[5], IT[5], IT[0], mctx) + lm_head_column(lm_head_core_6, MT[6], IT[6], IT[0], mctx) + lm_head_column(lm_head_core_7, MT[7], IT[7], IT[0], mctx) + + print(ctx.module) + +if __name__ == '__main__': + model_type = "QWEN3_5_0_8B" + if len(sys.argv) != 2: + print("Usage: python flowArch_aie.py , Options: QWEN3_5_0_8B, QWEN3_5_2B, QWEN3_5_4B, QWEN3_5_9B, HY_MEMORY_30B_A3B, MINICPM5_15B_A2_5B") + print("Use default model type: QWEN3_5_0_8B") + else: + model_type = sys.argv[1] + lm_head_top(model_type) \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/iron/q4k_mm.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/iron/q4k_mm.py new file mode 100644 index 000000000..b72e88b59 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/iron/q4k_mm.py @@ -0,0 +1,239 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +import numpy as np +import sys + +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +from aie.dialects.aie import * +from aie.dialects.aiex import * +from aie.helpers.dialects.ext.scf import _for as range_ +import aie.utils.trace as trace_utils +from aie.utils.trace import MemTilePortEvent, MemTileEvent, PortEvent +from aie.utils.trace_events_enum import CoreEvent, MemEvent, ShimTileEvent, MemTileEvent +from typing import List +from utils import mlir_context, tile_with_location, connect_dma, connect_port, lock_acquire, lock_release + +# IT0's MM2S 0 carries two things, so both of its flows have to be packet-switched: +# the x broadcast that every core needs, and column 0's second weight stream. Every +# other column gets a plain circuit flow on its own shim tile's MM2S 0. See +# lm_head_column for why column 0 is the odd one out. +X_PKT_ID = 0 +W_PKT_ID = 1 + +# Ping-pong depth of each weight group in the memtile. Two would be enough to keep +# both of a group's output channels busy; four just buys slack against jitter and +# costs 2 * 4 * W_BLOCK_SIZE * 2 B = 70 KB of the memtile's 512 KB. +W_SLOTS = 4 + +def lm_head_tile(tile: tile_with_location, mctx: mlir_context): + + ct = tile.tile + ct_row = tile.row + ct_col = tile.col + + qmm = mctx.qmm + x_ty = mctx.x_ty + w_ty = mctx.w_ty + y_ty = mctx.y_ty + + x_buffer = aie.buffer(tile = ct, datatype = x_ty, name = f"x_{ct_row}_{ct_col}") + w_buffer_0 = aie.buffer(tile = ct, datatype = w_ty, name = f"w_0_{ct_row}_{ct_col}") + w_buffer_1 = aie.buffer(tile = ct, datatype = w_ty, name = f"w_1_{ct_row}_{ct_col}") + y_buffer_0 = aie.buffer(tile = ct, datatype = y_ty, name = f"y_0_{ct_row}_{ct_col}") + y_buffer_1 = aie.buffer(tile = ct, datatype = y_ty, name = f"y_1_{ct_row}_{ct_col}") + + x_prod_lock = aie.lock(ct, lock_id = 0, init = 1) + x_cons_lock = aie.lock(ct, lock_id = 1, init = 0) + w_prod_lock = aie.lock(ct, lock_id = 2, init = 2) + w_cons_lock = aie.lock(ct, lock_id = 3, init = 0) + y_prod_lock = aie.lock(ct, lock_id = 4, init = 2) + y_cons_lock = aie.lock(ct, lock_id = 5, init = 0) + + @aie.core(ct, link_with = "qmm.o", stack_size = 1024 * 8) + def core_body(): + for _ in range_(0xFFFFFFFF): + qmm(y_buffer_0, y_buffer_1, w_buffer_0, w_buffer_1, x_buffer) + + @aie.mem(ct) + def mem_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest=block[1], chain=block[3]) + + with block[1]: + lock_acquire(x_prod_lock, 1) + aie.dma_bd(x_buffer) + lock_release(x_cons_lock, 1) + aie.next_bd(block[1]) + + with block[3]: + s1 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest=block[4], chain=block[6]) + + with block[4]: + lock_acquire(w_prod_lock, 1) + aie.dma_bd(w_buffer_0) + lock_release(w_cons_lock, 1) + aie.next_bd(block[5]) + + with block[5]: + lock_acquire(w_prod_lock, 1) + aie.dma_bd(w_buffer_1) + lock_release(w_cons_lock, 1) + aie.next_bd(block[4]) + + with block[6]: + s2 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest=block[7], chain=block[9]) + + with block[7]: + lock_acquire(y_cons_lock, 1) + aie.dma_bd(y_buffer_0) + lock_release(y_prod_lock, 1) + aie.next_bd(block[8]) + + with block[8]: + lock_acquire(y_cons_lock, 1) + aie.dma_bd(y_buffer_1) + lock_release(y_prod_lock, 1) + aie.next_bd(block[7]) + + with block[9]: + aie.EndOp() + +def _build_dma_chains(block, chains): + """Emit a memtile/mem DMA body from a flat description of its channels. + + ``chains`` is a list of ``(direction, channel, bds)`` where each bd is + ``(buffer, offset, length, acquire_lock, release_lock)`` and ``length = None`` + means the whole buffer. The bds of a channel are wired into a ring, and the + channels are chained together the way aie.dma_start's ``chain`` argument wants. + Writing this out by hand is 60-odd near-identical blocks; the two weight groups + below are structurally identical, so it is worth generating. + """ + starts = [0] + bd_ids = [] + next_id = 1 + for _, _, bds in chains: + bd_ids.append(list(range(next_id, next_id + len(bds)))) + next_id += len(bds) + starts.append(next_id) + next_id += 1 + end_id = starts.pop() + + for ci, (direction, channel, bds) in enumerate(chains): + nxt = block[starts[ci + 1]] if ci + 1 < len(chains) else block[end_id] + + def emit_start(): + aie.dma_start( + channel_dir = direction, + channel_index = channel, + dest = block[bd_ids[ci][0]], + chain = nxt, + ) + + if ci == 0: + # block[0] is the body's entry block, which is already open. + emit_start() + else: + with block[starts[ci]]: + emit_start() + + for bi, (buf, offset, length, acq, rel) in enumerate(bds): + with block[bd_ids[ci][bi]]: + lock_acquire(acq, 1) + if length is None: + aie.dma_bd(buf) + else: + aie.dma_bd(buf, offset = offset, len = length) + lock_release(rel, 1) + aie.next_bd(block[bd_ids[ci][(bi + 1) % len(bds)]]) + + with block[end_id]: + aie.EndOp() + + +def lm_head_memtile(tile: tile_with_location, mctx: mlir_context): + + mt = tile.tile + mt_row = tile.row + mt_col = tile.col + + w_mem_ty = mctx.w_mem_ty + y_mem_ty = mctx.y_mem_ty + + W_BLOCK_SIZE = mctx.W_BLOCK_SIZE + Q4NX_ROW_BLOCK_SIZE = mctx.Q4NX_ROW_BLOCK_SIZE + + # The four cores of a column are fed by two independent weight streams rather + # than one: a single shim->memtile channel saturates at roughly a quarter of what + # the four cores can consume, which is what made this kernel purely data-movement + # bound. Group a serves cores 0/1, group b serves cores 2/3, and each group has + # its own shim MM2S channel behind it. A slot is therefore two k-blocks wide, not + # four, and the host lays the weights out in DDR as two contiguous halves per + # column-round to match (see reorder_cpy in host/host.cpp). + w_a = [aie.buffer(tile = mt, datatype = w_mem_ty, name = f"wa_{i}_{mt_row}_{mt_col}") for i in range(W_SLOTS)] + w_b = [aie.buffer(tile = mt, datatype = w_mem_ty, name = f"wb_{i}_{mt_row}_{mt_col}") for i in range(W_SLOTS)] + y_buffers = [ + aie.buffer(tile = mt, datatype = y_mem_ty, name = f"y_0_{mt_row}_{mt_col}"), + aie.buffer(tile = mt, datatype = y_mem_ty, name = f"y_1_{mt_row}_{mt_col}"), + ] + + # Each group hands a slot down its two output channels in turn and only then + # returns it to the producer, so a slot is never refilled while either core is + # still reading it. + wa_prod_lock = aie.lock(mt, lock_id = 0, init = W_SLOTS) + wa_cons_lock_0 = aie.lock(mt, lock_id = 1, init = 0) + wa_cons_lock_1 = aie.lock(mt, lock_id = 2, init = 0) + wb_prod_lock = aie.lock(mt, lock_id = 3, init = W_SLOTS) + wb_cons_lock_0 = aie.lock(mt, lock_id = 4, init = 0) + wb_cons_lock_1 = aie.lock(mt, lock_id = 5, init = 0) + y_prod_lock_0 = aie.lock(mt, lock_id = 6, init = 2) + y_prod_lock_1 = aie.lock(mt, lock_id = 7, init = 0) + y_prod_lock_2 = aie.lock(mt, lock_id = 8, init = 0) + y_prod_lock_3 = aie.lock(mt, lock_id = 9, init = 0) + y_cons_lock = aie.lock(mt, lock_id = 10, init = 0) + + Y = Q4NX_ROW_BLOCK_SIZE + + chains = [ + # Weight group a: in from the shim, out to cores 0 and 1. + (aie.DMAChannelDir.S2MM, 1, [(b, 0, None, wa_prod_lock, wa_cons_lock_0) for b in w_a]), + (aie.DMAChannelDir.MM2S, 1, [(b, 0, W_BLOCK_SIZE, wa_cons_lock_0, wa_cons_lock_1) for b in w_a]), + (aie.DMAChannelDir.MM2S, 2, [(b, W_BLOCK_SIZE, W_BLOCK_SIZE, wa_cons_lock_1, wa_prod_lock) for b in w_a]), + # Weight group b: in from the shim, out to cores 2 and 3. + (aie.DMAChannelDir.S2MM, 0, [(b, 0, None, wb_prod_lock, wb_cons_lock_0) for b in w_b]), + (aie.DMAChannelDir.MM2S, 3, [(b, 0, W_BLOCK_SIZE, wb_cons_lock_0, wb_cons_lock_1) for b in w_b]), + (aie.DMAChannelDir.MM2S, 4, [(b, W_BLOCK_SIZE, W_BLOCK_SIZE, wb_cons_lock_1, wb_prod_lock) for b in w_b]), + # y: each core drops its 16 logits into its own quarter of the shared buffer, + # in core order, and the last one hands the full buffer to the shim. + (aie.DMAChannelDir.S2MM, 2, [(b, 0, Y, y_prod_lock_0, y_prod_lock_1) for b in y_buffers]), + (aie.DMAChannelDir.S2MM, 3, [(b, Y, Y, y_prod_lock_1, y_prod_lock_2) for b in y_buffers]), + (aie.DMAChannelDir.S2MM, 4, [(b, Y * 2, Y, y_prod_lock_2, y_prod_lock_3) for b in y_buffers]), + (aie.DMAChannelDir.S2MM, 5, [(b, Y * 3, Y, y_prod_lock_3, y_cons_lock) for b in y_buffers]), + (aie.DMAChannelDir.MM2S, 5, [(b, 0, None, y_cons_lock, y_prod_lock_0) for b in y_buffers]), + ] + + @aie.memtile_dma(mt) + def memtile_dma_body(block): + _build_dma_chains(block, chains) + + +def lm_head_column(CTs: List[tile_with_location], MT: tile_with_location, IT: tile_with_location, XIT: tile_with_location, mctx: mlir_context, w_pkt_id: int = -1): + + lm_head_memtile(MT, mctx) + + # Both of this column's shim MM2S channels carry weights. Column 0 is the + # exception: its MM2S 0 also has to carry the x broadcast, because x has to come + # from somewhere and every memtile S2MM channel is now spoken for (two weights, + # four y). Sharing it costs column 0 an extra 7680 B per token against 67 MB of + # weights, and requires the two flows off that port to be packet-switched. + connect_dma(IT, MT, 1, 1) + connect_dma(IT, MT, 0, 0, pkt_id = w_pkt_id) + + for i, proj_core in enumerate(CTs): + lm_head_tile(proj_core, mctx) + # x goes shim -> core directly now, not through the memtile. + connect_dma(XIT, proj_core, 0, 0, pkt_id = X_PKT_ID) + connect_dma(MT, proj_core, i + 1, 1) + + connect_dma(proj_core, MT, 0, i + 2) + + connect_dma(MT, IT, 5, 0) diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/iron/utils.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/iron/utils.py new file mode 100644 index 000000000..b762f8e44 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/iron/utils.py @@ -0,0 +1,156 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +from dataclasses import dataclass +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +from aie.dialects.aie import * +from aie.dialects.aiex import * +from aie.helpers.dialects.ext.scf import _for as range_ +import aie.utils.trace as trace_utils +from aie.utils.trace import MemTilePortEvent, MemTileEvent, PortEvent +from aie.utils.trace_events_enum import CoreEvent, MemEvent, ShimTileEvent, MemTileEvent +from aie.dialects import memref +from typing import Dict, Any, List, Optional +from aie.extras import types as T +from aie.dialects._aie_ops_gen import cascade_flow, CascadeFlowOp + +@dataclass +class tile_with_location: + tile: tile + row: int + col: int + +@dataclass +class dma_port: + tile: tile_with_location + channel: int + +class mlir_context: + def __init__(self): + self.data_tys = {} + self.funcs = {} + self.buffers = {} + self.parameters = {} + self.object_fifos = {} + self.packet_ids = {} + + def data_ty(self, name: str, shape: List[int], dtype: Any): + d_ty = np.ndarray[shape, dtype] + self.data_tys[name] = d_ty + if not hasattr(self, name): + setattr(self, name, d_ty) + else: + raise ValueError(f"Data type {name} already exists") + return d_ty + + def buffer(self, name: str, tile: tile_with_location, dtype: Any): + new_buffer = aie.buffer(tile.tile, dtype, name = name) + self.buffers[name] = new_buffer + if not hasattr(self, name): + setattr(self, name, new_buffer) + else: + raise ValueError(f"Buffer {name} already exists") + + return new_buffer + + def func(self, name: str, inputs: List[Any]): + this_func = aie.external_func(name, inputs) + self.funcs[name] = this_func + if not hasattr(self, name): + setattr(self, name, this_func) + else: + raise ValueError(f"Function {name} already exists") + return this_func + + def parameter(self, name: str, value: Any): + self.parameters[name] = value + if not hasattr(self, name): + setattr(self, name, value) + else: + raise ValueError(f"Parameter {name} already exists") + return value + + def object_fifo(self, name: str, src_tile: tile_with_location, dst_tile: tile_with_location | List[tile_with_location], depth: int, data_ty: Any, *args, **kwargs): + if isinstance(dst_tile, tile_with_location): + fifo = object_fifo(name, src_tile.tile, dst_tile.tile, depth, data_ty, *args, **kwargs) + else: + fifo = object_fifo(name, src_tile.tile, [t.tile for t in dst_tile], depth, data_ty, *args, **kwargs) + self.object_fifos[name] = fifo + if not hasattr(self, name): + setattr(self, name, fifo) + else: + raise ValueError(f"Object fifo {name} already exists") + return fifo + + + +def dma_mm2s_ch(ch: int): + return { + "source_port": WireBundle.DMA, + "source_channel": ch + } + +def dma_s2mm_ch(ch: int): + return { + "dest_port": WireBundle.DMA, + "dest_channel": ch + } + +def flow_mm2s_ch(ch: int): + return { + "source_bundle": WireBundle.DMA, + "source_channel": ch + } + +def flow_s2mm_ch(ch: int): + return { + "dest_bundle": WireBundle.DMA, + "dest_channel": ch + } + +def generate_tile_map(total_rows: int, total_cols: int) -> Tuple[List[tile_with_location], List[tile_with_location], List[List[tile_with_location]]]: + # Tile declarations + ShimTiles = [] + MemTiles = [] + cores = [] + for col in range(total_cols): + ShimTiles.append(tile_with_location(tile(col, 0), 0, col)) + MemTiles.append(tile_with_location(tile(col, 1), 0, col)) + + for row in range(total_rows - 2): + ComputeTilesRow = [] + for col in range(total_cols): + ComputeTilesRow.append(tile_with_location(tile(col, row + 2), row + 2, col)) + + cores.append(ComputeTilesRow) + + return ShimTiles, MemTiles, cores + +def connect_dma(src: tile_with_location, dst: tile_with_location, src_ch: int, dst_ch: int, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile, **flow_mm2s_ch(src_ch), dest = dst.tile, **flow_s2mm_ch(dst_ch)) + else: + aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src_ch), dest = dst.tile, **dma_s2mm_ch(dst_ch), keep_pkt_header = keep_pkt_header) + +def connect_port(src: dma_port, dst: dma_port, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile, **flow_mm2s_ch(src.channel), dest = dst.tile, **flow_s2mm_ch(dst.channel)) + else: + aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src.channel), dest = dst.tile, **dma_s2mm_ch(dst.channel), keep_pkt_header = keep_pkt_header) + + +def lock_acquire(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.AcquireGreaterEqual, value = value) + +def lock_release(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.Release, value = value) + +def cascade_flow(source, dest): + assert source is not None + assert dest is not None + + + return CascadeFlowOp( + source_tile = source, dest_tile = dest + ) + \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/aie_kernel_utils.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/aie_kernel_utils.h new file mode 100644 index 000000000..552a81711 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/aie_kernel_utils.h @@ -0,0 +1,90 @@ +/* + Copyright (C) 2014 - 2022 Xilinx, Inc. All rights reserved. + Copyright (C) 2022 - 2025 Advanced Micro Devices, Inc. All rights reserved. + Portions of this file consist of AI-generated content. + SPDX-License-Identifier: MIT +*/ + +#ifndef _AIE_KERNEL_UTILS_ +#define _AIE_KERNEL_UTILS_ + +#if defined(__chess__) +#define AIE_LOOP_UNROLL(x) [[chess::unroll_loop(x)]] +#define AIE_LOOP_UNROLL_FULL [[chess::unroll_loop()]] +#define AIE_LOOP_NO_UNROLL [[chess::no_unroll]] +#define AIE_LOOP_MIN_ITERATION_COUNT(x) [[chess::min_loop_count(x)]] +#define AIE_LOOP_MAX_ITERATION_COUNT(x) [[chess::max_loop_count(x)]] +#define AIE_LOOP_RANGE(a, ...) \ + [[chess::min_loop_count(a)]] __VA_OPT__( \ + [[chess::max_loop_count(__VA_ARGS__)]]) +#define AIE_PREPARE_FOR_PIPELINING [[chess::prepare_for_pipelining]] +#define AIE_NO_PREPARE_FOR_PIPELINING [[chess::no_prepare_for_pipelining]] +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) \ + [[chess::modulo_scheduling_budget_ratio(x)]] +#define AIE_KEEP_SW_LOOP [[chess::keep_sw_loop]] +#define AIE_PEEL_PIPELINED_LOOP(x) [[chess::peel_pipelined_loop(x)]] +#define AIE_KEEP_FREE_FOR_PIPELINING(x) [[chess::keep_free_for_pipelining(x)]] +#define AIE_ALLOCATE(x) [[chess::allocate(x)]] +#define AIE_NO_HW_LOOP [[chess::no_hw_loop]] +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN chess_flatten_loop + +#elif defined(__AIECC__) +#ifndef __STRINGIFY +#define __STRINGIFY(a) #a +#endif +#define AIE_LOOP_UNROLL(x) _Pragma(__STRINGIFY(clang loop unroll_count(x))) +#define AIE_LOOP_UNROLL_FULL _Pragma("clang loop unroll(full)") +#define AIE_LOOP_NO_UNROLL _Pragma("clang loop unroll(disable)") +#define AIE_LOOP_MIN_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop min_iteration_count(x))) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop max_iteration_count(x))) +#define AIE_LOOP_RANGE(a, ...) \ + AIE_LOOP_MIN_ITERATION_COUNT(a) \ + __VA_OPT__(AIE_LOOP_MAX_ITERATION_COUNT(__VA_ARGS__)) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) \ + _Pragma(__STRINGIFY(clang loop pipeline_initiation_interval(x))) +#define AIE_PREPARE_FOR_POSTPIPELINING _Pragma("clang loop pipeline(disable)") +#define AIE_LOOP_FLATTEN + +#else +#define AIE_LOOP_UNROLL(x) +#define AIE_LOOP_UNROLL_FULL +#define AIE_LOOP_NO_UNROLL +#define AIE_LOOP_MIN_ITERATION_COUNT(x) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) +#define AIE_LOOP_RANGE(a, ...) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN +#endif + +#if !defined(__chess__) +// chess lowers scalar float + - * to IEEE softfloat calls; Peano runs them on the +// vector unit and fuses a*b+c, which rounds differently. Kernels whose scalar +// math has to match chess call compiler-rt's softfloat through these. +extern "C" float __addsf3(float, float); +extern "C" float __mulsf3(float, float); +#define AIE_FADD(a, b) __addsf3((a), (b)) +#define AIE_FMUL(a, b) __mulsf3((a), (b)) +#endif + +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/bf16_limb_math.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/bf16_limb_math.hpp new file mode 100644 index 000000000..a74ebc98b --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/bf16_limb_math.hpp @@ -0,0 +1,318 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __BF16_LIMB_MATH_HPP__ +#define __BF16_LIMB_MATH_HPP__ + +// --------------------------------------------------------------------------- +// fp32 x bf16 products on the native bf16 MMUL datapath. +// +// For a one-off fp32 x fp32 product, use aie::mul / aie::mac directly. Those +// lower to the vendor's emulation (mul_elem_N_accuracy_safe in +// $AIETOOLS/data/aie2p/lib/me_vmult_float_emulated.h, via +// detail/aie2p/mul_acc32_fp.hpp), which splits BOTH operands into 3 bf16 limbs +// and issues all 9 cross products for an fp32-exact result. The cheaper +// mul_elem_N_accuracy_fast (6 MACs) and _low (3 MACs) are always defined too, +// and are callable by name per call site -- the AIE2_FP32_EMULATION_ACCURACY_* +// macros only pick which one aie::mul binds to, so you do not need a +// translation-unit-wide flag to reach them. +// +// Two things the vendor cannot express, which is what this header is for: +// +// 1. Asymmetric fp32 x bf16: one operand is fp32, the other is already exactly +// representable in bf16 (it came from a bf16 buffer). Only the fp32 side +// needs splitting, so the product costs one MAC per limb -- 2 or 3, not 9. +// The vendor has no asymmetric entry point at all; the cheapest thing it can +// do here is _low's 3 full products. +// +// 2. Operands you already hold as limbs. split_f32_3() once, then feed the +// mac_limbs3_* forms -- useful when the same limbs serve several products, +// when you also want l0 as the plain bf16 rounding of x, or when the split +// is invariant in a way the compiler cannot prove (behind a pointer it +// cannot alias-analyse, or a call it did not inline). +// +// What is NOT a reason to use this header: saving a redundant split. The +// scheduler already hoists a loop-invariant split out of a loop body, including +// one buried inside the vendor's emulation -- measured, an aie::mul with one +// invariant operand leaves a single split (3 VCONV + 2 VMSC) in the body, not +// two. The win over the vendor default is the product set and its reduction +// shape, not the split. +// +// Accuracy, measured against a float64 reference over 4e5 operand pairs drawn +// across a ~2^12 dynamic range, worst-case relative error: +// +// op MACs max rel err ~mantissa bits +// plain bf16 x bf16 1 3.9e-03 8 +// mac_f32_bf16_low 2 7.6e-06 17 +// mac_f32_bf16_safe 3 6.0e-08 24 (fp32-exact) +// mac_limbs3_tri (f32xf32) 6 6.0e-08 24 (fp32-exact) +// aie::mac on 2x fp32 9 6.0e-08 24 (vendor, f32xf32) +// +// fp32 carries 24 mantissa bits, so the 3-limb form is exact for practical +// purposes and matches the vendor's 9-MAC safe tier at a third of the cost. +// The 2-limb form drops the last limb (~2^-24 of the operand) for one fewer +// MAC; it is the right pick when the product feeds a bf16 output anyway, and +// the wrong pick for anything that compounds over a sequence, like a decay gate. +// +// The 3 products the triangular fp32 x fp32 form drops (l1*l2, l2*l1, l2*l2) +// are all <= 2^-24 of the result, i.e. below where an fp32 mantissa can hold +// them, so 6 MACs is not an approximation of the 9-MAC form -- it is the same +// answer with the provably-zero terms removed. +// +// Note on rounding: to_vector() rounds using the core's current +// rounding mode. The numbers above assume the default round-to-nearest-even. +// --------------------------------------------------------------------------- + +#include +#include + +namespace bf16_limb { + +// A bf16 vector of ones, used to subtract a limb back out inside a single msc +// rather than converting to fp32 and doing a separate aie::sub. +template +inline aie::vector ones() +{ + return aie::broadcast((bfloat16)1.0f); +} + +// --------------------------------------------------------------------------- +// Splitting +// --------------------------------------------------------------------------- + +// Split x into 2 bf16 limbs with x ~= l0 + l1, carrying ~16 of fp32's 24 +// mantissa bits. Each residual is exact in fp32: l0 is within a factor of two +// of x, so x - l0 cancels without rounding. +template +inline std::pair, aie::vector> +split_f32(aie::vector x) +{ + const aie::vector one = ones(); + + aie::accum r0; + r0.from_vector(x); + aie::vector l0 = r0.template to_vector(); + + aie::accum r1 = aie::msc(r0, l0, one); // r1 = x - l0 + aie::vector l1 = r1.template to_vector(); + + return {l0, l1}; +} + +// Split x into 3 bf16 limbs with x ~= l0 + l1 + l2. 3 x 8 = 24 bits covers the +// whole fp32 mantissa, so the triple is exact up to the exponent range. +template +struct limbs3 { + aie::vector l0, l1, l2; +}; + +template +inline limbs3 split_f32_3(aie::vector x) +{ + const aie::vector one = ones(); + limbs3 out; + + aie::accum r0; + r0.from_vector(x); + out.l0 = r0.template to_vector(); + + aie::accum r1 = aie::msc(r0, out.l0, one); // x - l0 + out.l1 = r1.template to_vector(); + + aie::accum r2 = aie::msc(r1, out.l1, one); // x - l0 - l1 + out.l2 = r2.template to_vector(); + + return out; +} + +// --------------------------------------------------------------------------- +// acc += a * b, where a is fp32 and b is already exact in bf16 +// +// Limbs are accumulated smallest-first, matching the vendor's ordering in +// mac_elem_N_accuracy_safe, so the small terms combine before meeting the +// large one instead of being rounded off against it. +// --------------------------------------------------------------------------- + +// 2 MACs, ~17 bits. +template +inline aie::accum mac_f32_bf16_low( + aie::accum acc, + aie::vector a, + aie::vector b) +{ + auto [l0, l1] = split_f32(a); + acc = aie::mac(acc, b, l1); + acc = aie::mac(acc, b, l0); + return acc; +} + +// 3 MACs, ~24 bits -- fp32-exact, same accuracy as the vendor's 9-MAC path. +template +inline aie::accum mac_f32_bf16_safe( + aie::accum acc, + aie::vector a, + aie::vector b) +{ + limbs3 l = split_f32_3(a); + acc = aie::mac(acc, b, l.l2); + acc = aie::mac(acc, b, l.l1); + acc = aie::mac(acc, b, l.l0); + return acc; +} + +// --------------------------------------------------------------------------- +// Pre-split operands +// +// Take the limbs directly when you already have them -- reused across several +// products, wanted as a bf16 value in their own right (l0 IS the RNE bf16 of x), +// or split outside a loop the compiler cannot prove invariance across. +// --------------------------------------------------------------------------- + +template +inline aie::accum mac_limbs_bf16( + aie::accum acc, + aie::vector l0, + aie::vector l1, + aie::vector b) +{ + acc = aie::mac(acc, b, l1); + acc = aie::mac(acc, b, l0); + return acc; +} + +template +inline aie::accum mac_limbs_bf16( + aie::accum acc, + limbs3 l, + aie::vector b) +{ + acc = aie::mac(acc, b, l.l2); + acc = aie::mac(acc, b, l.l1); + acc = aie::mac(acc, b, l.l0); + return acc; +} + +// acc += a * b, both fp32, both pre-split into 3 limbs. +// +// Only the 6 products with i+j <= 2 are issued. Limb i carries magnitude +// ~2^-8i of its operand, so a dropped term l_i*l_j is ~2^-8(i+j) <= 2^-24 of +// the result -- at or below the fp32 mantissa floor. That is why this matches +// the vendor's 9-product safe tier bit-for-bit in practice rather than +// approximating it. +// +// Against the vendor default this is 6 MACs through an accumulator chain in +// place of 9 VMULs into an 8-deep serial VADD tree -- 26 bundles vs 71 at +// N=32. mul_elem_N_accuracy_fast issues the same 6 products and is callable by +// name; reach for this form when you want the limbs themselves, or when the +// other operand is bf16-exact and belongs in mac_limbs_bf16 instead. +template +inline aie::accum mac_limbs3_tri( + aie::accum acc, + const limbs3& a, + const limbs3& b) +{ + acc = aie::mac(acc, a.l2, b.l0); + acc = aie::mac(acc, a.l1, b.l1); + acc = aie::mac(acc, a.l0, b.l2); + acc = aie::mac(acc, a.l1, b.l0); + acc = aie::mac(acc, a.l0, b.l1); + acc = aie::mac(acc, a.l0, b.l0); + return acc; +} + +// Same, with the second operand still packed as fp32. Splits b in-loop. +template +inline aie::accum mac_limbs3_f32_tri( + aie::accum acc, + const limbs3& a, + aie::vector b) +{ + return mac_limbs3_tri(acc, a, split_f32_3(b)); +} + +// acc -= a * b, the subtracting counterparts of the two above. +template +inline aie::accum msc_limbs3_tri( + aie::accum acc, + const limbs3& a, + const limbs3& b) +{ + acc = aie::msc(acc, a.l2, b.l0); + acc = aie::msc(acc, a.l1, b.l1); + acc = aie::msc(acc, a.l0, b.l2); + acc = aie::msc(acc, a.l1, b.l0); + acc = aie::msc(acc, a.l0, b.l1); + acc = aie::msc(acc, a.l0, b.l0); + return acc; +} + +template +inline aie::accum msc_limbs3_f32_tri( + aie::accum acc, + const limbs3& a, + aie::vector b) +{ + return msc_limbs3_tri(acc, a, split_f32_3(b)); +} + +// --------------------------------------------------------------------------- +// Split-accumulator forms, for reduction loops +// +// In a loop that accumulates over many terms, chaining both limb MACs into one +// accumulator makes the loop-carried dependency two MACs deep and sets the +// initiation interval accordingly. Giving each limb its own accumulator keeps +// each chain one MAC deep; the caller folds them together once, after the loop, +// with reduce(). +// --------------------------------------------------------------------------- + +// 2 MACs into 2 independent accumulators. +template +inline void mac_f32_bf16_low( + aie::accum& acc0, + aie::accum& acc1, + aie::vector a, + aie::vector b) +{ + auto [l0, l1] = split_f32(a); + acc0 = aie::mac(acc0, b, l0); + acc1 = aie::mac(acc1, b, l1); +} + +// 3 MACs into 3 independent accumulators. +template +inline void mac_f32_bf16_safe( + aie::accum& acc0, + aie::accum& acc1, + aie::accum& acc2, + aie::vector a, + aie::vector b) +{ + limbs3 l = split_f32_3(a); + acc0 = aie::mac(acc0, b, l.l0); + acc1 = aie::mac(acc1, b, l.l1); + acc2 = aie::mac(acc2, b, l.l2); +} + +// Fold split accumulators back together, smallest-first. +template +inline aie::accum reduce( + aie::accum acc0, + aie::accum acc1) +{ + aie::accum out; + out.from_vector(aie::add(acc1.template to_vector(), + acc0.template to_vector())); + return out; +} + +template +inline aie::accum reduce( + aie::accum acc0, + aie::accum acc1, + aie::accum acc2) +{ + return reduce(acc0, reduce(acc1, acc2)); +} + +} // namespace bf16_limb + +#endif // __BF16_LIMB_MATH_HPP__ diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/common.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/common.h new file mode 100644 index 000000000..49cf67806 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/common.h @@ -0,0 +1,53 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef COMMON_H +#define COMMON_H + +#include +// #include +typedef bfloat16 bf16; + +inline void _lock_acquire(int lock_id){ + acquire_greater_equal(lock_id + 48, 1); +} + +inline void _lock_release(int lock_id){ + release(lock_id + 48, 1); +} + +inline void _left_lock_acquire(int lock_id){ + acquire_greater_equal(lock_id + 16, 1); +} + +inline void _left_lock_release(int lock_id){ + release(lock_id + 16, 1); +} + +inline void _up_lock_acquire(int lock_id){ + acquire_greater_equal(lock_id + 32, 1); +} + +inline void _up_lock_release(int lock_id){ + release(lock_id + 32, 1); +} + +inline void _down_lock_acquire(int lock_id){ + acquire_greater_equal(lock_id, 1); +} + +inline void _down_lock_release(int lock_id){ + release(lock_id, 1); +} + +template +void zero_vectorized(T *__restrict c) { + constexpr int r = 256 / (sizeof(T) * 8); // one 256 bit store unit + static_assert((M) % r == 0); + const aie::vector zeros = aie::zeros(); + const T *__restrict c_end = c + M; + for (; c < c_end; c += r) { + aie::store_v(c, zeros); + } +} + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/flm_rsqrt.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/flm_rsqrt.h new file mode 100644 index 000000000..12ec952d7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/flm_rsqrt.h @@ -0,0 +1,9 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#pragma once + +#include + +// 1 / sqrt(x) for a positive float: one hardware invsqrt instruction. Keep x a float. +static inline float flm_rsqrt(float x) { return aie::invsqrt(x); } diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/q8_core.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/q8_core.h new file mode 100644 index 000000000..556be50bb --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/q8_core.h @@ -0,0 +1,94 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __Q8_CORE_H__ +#define __Q8_CORE_H__ +#include "aie_kernel_utils.h" +#include "bf16_limb_math.hpp" + +#define QXNX_ROW_BLOCK_SIZE 32 +#define QXNX_COL_BLOCK_SIZE 256 +#define GGML_GROUP_SIZE 32 + +// The core holds a whole block's rows at once: one column of a block is exactly +// PARALLEL_ROWS elements, so this is a layout constant, not a tuning knob. +#define PARALLEL_ROWS QXNX_ROW_BLOCK_SIZE + +///@brief Q80 block +///@param scales: scales and mins, bf16 +///@param mins: scales and mins, bf16 +///@param qs: 4-bit quantized values +typedef struct { + bf16 scales[QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE]; // per-group scales and mins + int8_t qs[QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE]; // 8--bit quants +} q80_block_t; + +/// @brief y += W x for one Q8_0 weight block, x bf16 / y float32. +/// +/// "Reduce first, scale after": a whole 32-value group is reduced against x in +/// one float32 accumulator and only then meets the group's bf16 scale. Every +/// multiplier operand is bf16-exact -- q is an int8 (bf16 holds every integer up +/// to 256) and the scale is *stored* bf16 -- so the group accumulator is the one +/// place a rounding could creep in, and the limb split below keeps it out. +void _Q80_x_bf16( + float * c, + bf16 * x, + q80_block_t* w_buffer +) { + // The whole row span of the block is resident at once, so there is no row + // loop: one pass over the column groups, one scale entry per group. + static constexpr int num_groups_per_row = QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE; + + int8_t* it_q = w_buffer->qs; + bf16* it_scale = w_buffer->scales; + bf16* it_x = x; + + aie::accum c_accum; + c_accum.from_vector(aie::load_v(c)); + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE( num_groups_per_row, num_groups_per_row ) + for (int group = 0; group < num_groups_per_row; group++) { + aie::vector a_scales = aie::load_v(it_scale); + + // inlined Q8_core + aie::vector vec_col = aie::load_v(it_x); + aie::accum temp_acc; + temp_acc.from_vector(aie::broadcast(bf16(0.0f))); + + // Unrolled by 4 to amortize the per-iteration load and int8->bf16 + // conversion overhead, which dominates this loop rather than the + // accumulator dependency. + static constexpr int T_UNROLL = 4; + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE( GGML_GROUP_SIZE, GGML_GROUP_SIZE ) + AIE_LOOP_UNROLL( T_UNROLL ) + for(int t = 0; t < GGML_GROUP_SIZE; t++ ) { + aie::vector a_cc_0 = aie::load_v(it_q); + it_q += PARALLEL_ROWS; + + aie::vector a_col_float = aie::to_float(a_cc_0, 0); + // convert to bfloat16 + aie::accum a_col_accum; + a_col_accum.from_vector(a_col_float); + + aie::vector a_col_bf16 = a_col_accum.template to_vector(); + + temp_acc = aie::mac(temp_acc, a_col_bf16, vec_col.get(t)); + } + + // a_scales is bf16-exact, so the only rounding this MAC could introduce + // is on temp_acc. A plain to_vector() would throw away 16 of the + // group sum's 24 mantissa bits, once per group and per block, and those + // errors add up over the whole K loop. Split the accumulator into two + // bf16 limbs instead: ~17 mantissa bits rather than 8, for 1 extra MAC + // per group against the 32 of the inner loop above. + c_accum = bf16_limb::mac_f32_bf16_low( + c_accum, temp_acc.template to_vector(), a_scales); + it_x += GGML_GROUP_SIZE; + it_scale += PARALLEL_ROWS; + } + + aie::vector c_accum_f32 = c_accum.template to_vector(); + aie::store_v(c, c_accum_f32); +} +#endif // __Q8_CORE_H__ \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/qmm.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/qmm.cc new file mode 100644 index 000000000..4f10152e7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/kernel/qmm.cc @@ -0,0 +1,181 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. +#include +#include "common.h" +#include "aie_kernel_utils.h" +#include "q8_core.h" +#include "flm_rsqrt.h" + + +#define QWEN3_5_0_8B 0 +#define QWEN3_5_2B 1 +#define QWEN3_5_4B 2 +#define QWEN3_5_9B 3 +#define HY_MEMORY_30B_A3B 4 +#define MINICPM5_15B_A2_5B 5 + +#ifndef MODEL_TYPE +#define MODEL_TYPE QWEN3_5_4B +#endif + + +constexpr int NUM_CTS = 32; + +// The vocab size sets how many rounds the kernel loops for, so it must match +// the host's sequence exactly: a kernel that expects more rounds than the host +// sends gets stuck mid-token and eats the next token's weights. +#if MODEL_TYPE == QWEN3_5_0_8B +constexpr int MODEL_DIM = 1024; +constexpr int VOCAB_SIZE = 248320; +constexpr float RMS_EPS = 1e-6f; +#elif MODEL_TYPE == QWEN3_5_2B +constexpr int MODEL_DIM = 2048; +constexpr int VOCAB_SIZE = 248320; +constexpr float RMS_EPS = 1e-6f; +#elif MODEL_TYPE == QWEN3_5_4B +constexpr int MODEL_DIM = 2560; +constexpr int VOCAB_SIZE = 248320; +constexpr float RMS_EPS = 1e-6f; +#elif MODEL_TYPE == QWEN3_5_9B +constexpr int MODEL_DIM = 4096; +constexpr int VOCAB_SIZE = 248320; +constexpr float RMS_EPS = 1e-6f; +#elif MODEL_TYPE == HY_MEMORY_30B_A3B +constexpr int MODEL_DIM = 2048; +constexpr int VOCAB_SIZE = 120832; // 118 rounds of 1024, no padding +constexpr float RMS_EPS = 1e-5f; // config.json rms_norm_eps +#elif MODEL_TYPE == MINICPM5_15B_A2_5B +constexpr int MODEL_DIM = 2048; +constexpr int VOCAB_SIZE = 130560; // padded to 131072: 128 rounds of 1024 +constexpr float RMS_EPS = 1e-6f; // config.json rms_norm_eps +#else +#error "Unsupported MODEL_TYPE" +#endif + + +constexpr int M_PER_ROUND = 32 * 32; + +constexpr int VOCAB_SIZE_PADDED = (VOCAB_SIZE + M_PER_ROUND - 1) / M_PER_ROUND * M_PER_ROUND; +constexpr int MODEL_DIM_PADDED = (MODEL_DIM + QXNX_COL_BLOCK_SIZE - 1) / QXNX_COL_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE; + +constexpr int ROUNDS = VOCAB_SIZE_PADDED / M_PER_ROUND; +constexpr int K_BLOCKS = MODEL_DIM_PADDED / QXNX_COL_BLOCK_SIZE; +void rms_norm( + bf16 *restrict y, + bf16 *restrict x, + bf16 *restrict w +){ + bf16 *it_y = const_cast(y); + bf16 *it_x = const_cast(x); + bf16 *it_w = const_cast(w); + const float epsilon = RMS_EPS; + + constexpr int vector_size = 16; + constexpr float one_over_D = 1.0f / (float)MODEL_DIM; + + aie::accum sum_squares = aie::zeros(); + aie::vector mx_vec; + + const int F = MODEL_DIM / vector_size; + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(F, F) + for (int i = 0; i < F; i++){ + auto x_vec = aie::load_v(it_x); + sum_squares = aie::mac_square(sum_squares, x_vec); + it_x += vector_size; + } + + it_x = const_cast(x); + + mx_vec = sum_squares.template to_vector(); + float sum = aie::reduce_add(mx_vec); +#if defined(__chess__) + sum = sum * one_over_D; + sum = sum + epsilon; +#else + // Same math as the chess branch, rounded like chess (see AIE_FADD). + sum = AIE_FMUL(sum, one_over_D); + sum = AIE_FADD(sum, epsilon); +#endif + const float divrms = flm_rsqrt(sum); + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(F, F) + for (int i = 0; i < F; i++){ + aie::vector x_vec = aie::load_v(it_x); + aie::vector w_vec = aie::load_v(it_w); + aie::vector wx_vec = aie::mul(x_vec, w_vec); + aie::vector o_vec = aie::mul(wx_vec, divrms); + aie::store_v(it_y, o_vec); + it_x += vector_size; + it_y += vector_size; + it_w += vector_size; + } + event1(); +} + +constexpr int x_prod_lock = 0; +constexpr int x_cons_lock = 1; +constexpr int w_prod_lock = 2; +constexpr int w_cons_lock = 3; +constexpr int y_prod_lock = 4; +constexpr int y_cons_lock = 5; + +template +void copy_y(bf16 * y, const float * y_acc) { + for (int i = 0; i < m / 16; i++){ + aie::vector y_vec = aie::load_v<16>(y_acc + i * 16); + aie::accum acc; + acc.from_vector(y_vec); + aie::store_v(y + i * 16, acc.template to_vector()); + } +} + + +extern "C" { +void qmm( + bf16* y_ping, bf16* y_pong, + q80_block_t* w_ping, q80_block_t* w_pong, + bf16* x +){ + // Peano's CDO loader does not zero .bss; keep this ping/pong selector in .data. +#if !defined(__chess__) + __attribute__((section(".data"))) +#endif + static bool is_y_ping = false; +#if !defined(__chess__) + __attribute__((section(".data"))) +#endif + static bool is_w_ping = false; + + alignas(aie::vector_decl_align) float y_acc[QXNX_ROW_BLOCK_SIZE]; + + _lock_acquire(x_cons_lock); + + rms_norm(x, x, x + MODEL_DIM); + for (int r = 0; r < ROUNDS; r++) { + + zero_vectorized(y_acc); + + for (int k = 0; k < K_BLOCKS; k++) { + bf16* x_using = x + k * QXNX_COL_BLOCK_SIZE; + + _lock_acquire(w_cons_lock); + is_w_ping = !is_w_ping; + q80_block_t* w_using = is_w_ping ? w_ping : w_pong; + + _Q80_x_bf16(y_acc, x_using, w_using); + + _lock_release(w_prod_lock); + } + + _lock_acquire(y_prod_lock); + + is_y_ping = !is_y_ping; + bf16* y_using = is_y_ping ? y_ping : y_pong; + copy_y(y_using, y_acc); + + _lock_release(y_cons_lock); + } + _lock_release(x_prod_lock); +} +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/bitstream.mk b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/bitstream.mk new file mode 100644 index 000000000..58033f94e --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/bitstream.mk @@ -0,0 +1,47 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +# MLIR stuff + +MLIR_O_DIR := build/$(MODEL_TYPE)/mlir +BITSTREAM_O_DIR := build/$(MODEL_TYPE)/bitstream + + +IRON_BOTH_SRC := $(wildcard ${HOME_DIR}/iron/*_aie.py) +IRON_OTHER_SRC := $(wildcard ${HOME_DIR}/iron/*.py) +IRON_BOTH_MLIR_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${MLIR_O_DIR}/%.mlir, ${IRON_BOTH_SRC}) +IRON_BOTH_XCLBIN_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${BITSTREAM_O_DIR}/from_iron/%.xclbin, ${IRON_BOTH_SRC}) +IRON_BOTH_INSTS_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${BITSTREAM_O_DIR}/from_iron/%.txt, ${IRON_BOTH_SRC}) + +.PRECIOUS: ${IRON_BOTH_MLIR_TARGET} + +AIECC_FLAGS := --aie-generate-cdo --no-compile-host +ENABLE_CHESSCC ?= 0 +ifeq ($(ENABLE_CHESSCC),1) +AIECC_FLAGS += --xchesscc --xbridge +else +AIECC_FLAGS += --no-xchesscc --no-xbridge +endif +# iron generate mlir +${MLIR_O_DIR}/%.mlir: ${HOME_DIR}/iron/%_aie.py ${IRON_OTHER_SRC} + mkdir -p ${@D} + python3 $< ${IRON_ARGS} > $@ + +# Build xclbin +${BITSTREAM_O_DIR}/from_iron/%.xclbin: ${MLIR_O_DIR}/%.mlir ${KERNEL_OBJS} + mkdir -p ${@D} + cp ${KERNEL_OBJS} ${@D} + cd ${@D} && aiecc.py ${AIECC_FLAGS} --aie-generate-xclbin \ + --xclbin-name=${@F} $(<:${MLIR_O_DIR}/%=../../mlir/%) + mkdir -p build/$(MODEL_TYPE)/xclbins + cp ${@} build/$(MODEL_TYPE)/xclbins/lm_head.xclbin + +${BITSTREAM_O_DIR}/from_iron/%.txt: ${MLIR_O_DIR}/%.mlir + mkdir -p ${@D} + cd ${@D} && aiecc.py -n ${AIECC_FLAGS} --aie-generate-npu-insts \ + --npu-insts-name=${@F} $(<:${MLIR_O_DIR}/%=../../mlir/%) + mkdir -p build/$(MODEL_TYPE)/insts + cp ${@} build/$(MODEL_TYPE)/insts/ + +INSTS_TARGETS += ${IRON_BOTH_INSTS_TARGET} +XCLBIN_TARGETS += ${IRON_BOTH_XCLBIN_TARGET} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/common.mk b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/common.mk new file mode 100644 index 000000000..2d66b1266 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/common.mk @@ -0,0 +1,31 @@ +# common.mk +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Created by Alfred + +ifneq ($(filter -j,$(MAKEFLAGS)),) + # Nothing to do; -j is already set +else + MAKEFLAGS += -j8 +endif + +# VITIS related variables (Chess only: ENABLE_CHESSCC=1; Peano builds never expand them) +AIETOOLS_DIR ?= $(or $(AIETOOLS_ROOT),$(patsubst %/bin/,%,$(dir $(shell command -v xchesscc 2>/dev/null)))) +# Expanded only inside the Chess recipes, so it fires only for ENABLE_CHESSCC=1. +AIETOOLS_CHECK = $(if $(strip $(AIETOOLS_DIR)),,$(error ENABLE_CHESSCC=1 needs Vitis AIE Essentials: set AIETOOLS_ROOT (or AIETOOLS_DIR), or put xchesscc on PATH)) +AIE_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/versal_prod/lib +AIE2_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/aie_ml/lib + +AIEOPT_DIR ?= $(shell realpath $(dir $(shell which aie-opt))/..) + +WARNING_FLAGS = -Wno-parentheses -Wno-attributes -Wno-macro-redefined + + +CHESSCCWRAP1_FLAGS = aie $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include +CHESSCCWRAP2_FLAGS = aie2 $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include +CHESSCCWRAP2P_FLAGS = aie2p $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 +PEANOWRAP2_FLAGS = -O2 -v -std=c++20 --target=aie2-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -I ${AIEOPT_DIR}/include +PEANOWRAP2P_FLAGS = -O2 -v -std=c++20 --target=aie2p-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 -I ${AIEOPT_DIR}/include diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/host.mk b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/host.mk new file mode 100644 index 000000000..2bc425bde --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/host.mk @@ -0,0 +1,61 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +# ============================================================================= +# Llama NPU Library Makefile +# ============================================================================= +# +# Created: 2024 +# +# This Makefile is used to build the Llama NPU library components. +# +# Usage: +# make - Build all targets +# make clean - Remove all built files +# make help - Show this help message +# +# ============================================================================= + +# Linux build environment +# Use g++-13 directly without CMake + +HOST_C_TARGET := run.exe +HOST_COMMON_DIR := ../../host_common + +VERBOSE ?= 0 + +CXX := g++-13 +CXX_FLAGS := -std=c++20 -fPIC -Wall +CXX_FLAGS += -DUSE_AVX2=1 +CXX_FLAGS += -mavx2 -march=native -mfma -ffast-math +CXX_FLAGS += -Ihost +CXX_FLAGS += -I/opt/xilinx/xrt/include +CXX_FLAGS += -I$(HOST_COMMON_DIR) +CXX_FLAGS += -MMD -MP +CXX_FLAGS += -DVERBOSE=$(VERBOSE) + +LDFLAGS += -L/opt/xilinx/xrt/lib +LDFLAGS += -L$(HOST_COMMON_DIR) +LDFLAGS += -lxrt_coreutil $(HOST_COMMON_DIR)/../../../src/lib/xrt/libaiebu.a +LDFLAGS += -lboost_program_options -lboost_filesystem + +# Find all source files in host/ directory (including subdirectories) +HOST_SOURCES := $(shell find host -name '*.cpp') +HOST_OBJECTS := $(HOST_SOURCES:%.cpp=build/%.o) +HOST_DEPENDS := $(HOST_OBJECTS:.o=.d) + +# Default target +$(HOST_C_TARGET): build/$(HOST_C_TARGET) + cp build/$(HOST_C_TARGET) ./ + +# Link the executable +build/$(HOST_C_TARGET): $(HOST_OBJECTS) + @mkdir -p $(dir $@) + $(CXX) $(CXX_FLAGS) $^ -o $@ $(LDFLAGS) + +# Compile source files and generate dependencies +build/%.o: %.cpp + @mkdir -p $(dir $@) + $(CXX) $(CXX_FLAGS) -c $< -o $@ + +# Include dependency files +-include $(HOST_DEPENDS) \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/kernel.mk b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/kernel.mk new file mode 100644 index 000000000..580639a39 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/makefiles/kernel.mk @@ -0,0 +1,25 @@ +# common.mk +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Portions of this file consist of AI-generated content. +# Created by Alfred + +# Kernel stuff +KERNEL_O_DIR := build/$(MODEL_TYPE)/kernel +KERNEL_SRCS := $(wildcard ${HOME_DIR}/kernel/*.cc) +KERNEL_OBJS := $(patsubst ${HOME_DIR}/kernel/%.cc, ${KERNEL_O_DIR}/%.o, $(KERNEL_SRCS)) +KERNEL_HEADERS := $(wildcard ${HOME_DIR}/kernel/*.h) $(wildcard ${HOME_DIR}/kernel/*.hpp) + +# Build kernels +ENABLE_CHESSCC ?= 0 + +${KERNEL_O_DIR}/%.o: ${HOME_DIR}/kernel/%.cc ${KERNEL_HEADERS} + mkdir -p ${@D} +ifeq ($(ENABLE_CHESSCC),1) + cd ${@D} && xchesscc_wrapper ${CHESSCCWRAP2P_FLAGS} -DNPU2 ${KERNEL_ARGS} -c $< -o ${@F} +else + cd ${@D} && ${PEANO_INSTALL_DIR}/bin/clang++ ${PEANOWRAP2P_FLAGS} ${KERNEL_PEANO_EXTRA} -DNPU2 ${KERNEL_ARGS} -c $< -o ${@F} +endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/setup.sh b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/setup.sh new file mode 100755 index 000000000..0cba74315 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/setup.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# The kernel build environment lives in FLM_Xclbin/setup.sh. +source "$(dirname "${BASH_SOURCE[0]}")/../../setup.sh" diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/visualize.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/visualize.py new file mode 100755 index 000000000..c4906ddb5 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/lm_head_npu_bin/visualize.py @@ -0,0 +1,464 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# to print unicode characters, run this: +# export PYTHONIOENCODING=utf8 + +import math +import json +import os, sys +import argparse + +from enum import Enum + + +class Direction(Enum): + Horz = 0 + Vert = 1 + + +class canvas: + def __init__(self, width, height): + self.width = width + self.height = height + self.vert_line_list = [] + self.horz_line_list = [] + self.characters = [] + + def direction(self, line): + Horz_Stationary = False + Vert_Stationary = False + + if line[0][0] == line[1][0]: + # Line Stationary in Horz Axis + Horz_Stationary = True + if line[0][1] == line[1][1]: + # Line Stationary in Vert Axis + Vert_Stationary = True + + if Horz_Stationary and Vert_Stationary: + # Crash + raise Exception("Line is Diagonal") + if not Horz_Stationary and not Vert_Stationary: + # Crash + raise Exception("Line is a dot") + if (not Horz_Stationary) and Vert_Stationary: + return Direction.Horz + + if Horz_Stationary and (not Vert_Stationary): + return Direction.Vert + + def draw_character(self, point, character): + self.characters.append([point, character]) + + def replace_character(self, point, character, replacement): + if self.characters.count([point, character]): + self.characters.remove([point, character]) + self.characters.append([point, replacement]) + + def draw_line(self, start, finish): + if self.direction([start, finish]) == Direction.Vert: + self.vert_line_list.append([start, finish]) + else: + self.horz_line_list.append([start, finish]) + + def draw_square(self, center, size): + horz_origin = math.floor((center[0] + 0.5) - (size / 2)) + horz_extent = math.ceil((center[0] + 0.5) + (size / 2) + 3) + + vert_origin = math.floor((center[1] + 0.5) - (size / 2)) + vert_extent = math.ceil((center[1] + 0.5) + (size / 2)) + + top_left = (horz_origin, vert_origin) + top_right = (horz_extent, vert_origin) + bottom_left = (horz_origin, vert_extent) + bottom_right = (horz_extent, vert_extent) + + self.draw_line(top_left, top_right) + self.draw_line(top_right, bottom_right) + self.draw_line(bottom_left, bottom_right) + self.draw_line(top_left, bottom_left) + + def vertical_index(self, point): + return point[1] + + def horizontal_index(self, point): + return point[0] + + def within_line(self, point, line): + Horz_Stationary = False + Vert_Stationary = False + + if line[0][0] == line[1][0]: + # Line Stationary in Horz Axis + Horz_Stationary = True + if line[0][1] == line[1][1]: + # Line Stationary in Vert Axis + Vert_Stationary = True + + # print("HS: {}, VS: {}, {}".format(Horz_Stationary, Vert_Stationary, line)); + + if Horz_Stationary and Vert_Stationary: + # Crash + raise Exception("Line is Diagonal") + if not Horz_Stationary and not Vert_Stationary: + # Crash + raise Exception("Line is a dot") + + if Horz_Stationary and (not Vert_Stationary): + # it's a vertical line + # Sort the tuples by Horz + line.sort(key=self.vertical_index) + start_line = ( + (point[1] == line[0][1]) + and (point[1] <= line[1][1]) + and (point[0] == line[0][0]) + ) + in_line = ( + (point[1] > line[0][1]) + and (point[1] < line[1][1]) + and (point[0] == line[0][0]) + ) + end_line = ( + (point[1] > line[0][1]) + and (point[1] == line[1][1]) + and (point[0] == line[0][0]) + ) + + # print("Vert {}, point {}, {}".format(line, point, in_line)); + + if (not Horz_Stationary) and Vert_Stationary: + # it's a horizonal line + line.sort(key=self.horizontal_index) + start_line = ( + (point[0] == line[0][0]) + and (point[0] <= line[1][0]) + and (point[1] == line[0][1]) + ) + in_line = ( + (point[0] > line[0][0]) + and (point[0] < line[1][0]) + and (point[1] == line[0][1]) + ) + end_line = ( + (point[0] > line[0][0]) + and (point[0] == line[1][0]) + and (point[1] == line[0][1]) + ) + # print("Horz {}, point {}, {}".format(line, point, in_line)); + + return (start_line, in_line, end_line) + + def find_horz_index(self, line_points): + index = 0 + + if line_points[1]: + index += 2 + else: + if line_points[0]: + index += 1 + if line_points[2]: + index += 4 + return index + + def transform(self, index): + + # if horz through, clear bits for horz end + # if vert through, clear bits for vert end + + chars = { + 0: " ", + 2: "\u2500", # horz line + 16: "\u2502", # vert line + 9: "\u250c", # box top left + 33: "\u2514", # box bot left + 12: "\u2510", # box top right + 36: "\u2518", # box bot right + 1: "\u2576", # right half horz line + 8: "\u2577", # lower half vert line + 32: "\u2575", # upper half vert line + 4: "\u2574", # left half horz line + 18: "\u253c", # vert AND horz + 25: "\u251c", # vert and right + 17: "\u251c", + 20: "\u2524", # vert and left + 10: "\u252c", # horz and bot + 34: "\u2534", # horz and top + 21: "\u253c", # vert AND horz + 42: "\u253c", + } + try: + char = chars[index] + except KeyError: + char = "x" + + return char + + def combine(self, a, b): + return [a[0] or b[0], a[1] or b[1], a[2] or b[2]] + + def rasterize(self): + for x in range(self.height): + for y in range(self.width): + char = "({},{})".format(y, x) + index = 0 + horz_line_points = [False, False, False] + vert_line_points = [False, False, False] + + for charloc in self.characters: + if charloc[0][0] == y and charloc[0][1] == x: + print(charloc[1], end="", sep="") + index = -1 + break + if index == 0: # not a character, either vert or horz line + for line in self.horz_line_list: + horz_line_points = self.combine( + horz_line_points, self.within_line((y, x), line) + ) + index += self.find_horz_index(horz_line_points) + + for line in self.vert_line_list: + vert_line_points = self.combine( + vert_line_points, self.within_line((y, x), line) + ) + index += 8 * self.find_horz_index(vert_line_points) + + print("{}".format(self.transform(index)), end="", sep="") + # print(" {} ".format(index), end='', sep='') + + print("") + + +superscripts = { + # 0 : u'\u2070', + 0: " ", + 1: "\u00b9", + 2: "\u00b2", + 3: "\u00b3", + 4: "\u2074", + 5: "\u2075", + 6: "\u2076", + 7: "\u2077", + 8: "\u2078", + 9: "\u2079", +} +subscripts = { + # 0 : u'\u2080', + 0: " ", + 1: "\u2081", + 2: "\u2082", + 3: "\u2083", + 4: "\u2084", + 5: "\u2085", + 6: "\u2086", + 7: "\u2087", + 8: "\u2088", + 9: "\u2089", +} + + +def draw_switchbox( + canvas, + xoffset, + yoffset, + source_count, + destination_count, + northbound, + southbound, + eastbound, + westbound, + draw_demand=True, + name="", +): + c.draw_square((xoffset + 5, yoffset + 4), 2) + + # label it + if len(name) > 0: + c.draw_character((xoffset + 6, yoffset + 4), name[0]) + if len(name) > 1: + c.draw_character((xoffset + 7, yoffset + 4), name[1]) + if len(name) > 2: + c.draw_character((xoffset + 8, yoffset + 4), name[2]) + if len(name) > 3: + c.draw_character((xoffset + 9, yoffset + 4), name[3]) + + # draw source and destination count + if source_count > 0 or destination_count > 0: + c.draw_character((xoffset + 7, yoffset + 5), "*") + + # left of the switchbox (south) + if northbound > 0: + c.draw_line((xoffset + 10, yoffset + 4), (xoffset + 14, yoffset + 4)) + if draw_demand: + c.draw_character((xoffset + 12, yoffset + 3), subscripts[northbound]) + if northbound > 6: # if overcapacity, mark with an 'x' + c.draw_character((xoffset + 10, yoffset + 4), "x") + # c.draw_character((xoffset+11,yoffset+4), 'x') + c.draw_character((xoffset + 12, yoffset + 4), "x") + if southbound > 0: + c.draw_line((xoffset + 0, yoffset + 5), (xoffset + 4, yoffset + 5)) + if draw_demand: + c.draw_character((xoffset + 2, yoffset + 6), superscripts[southbound]) + if southbound > 4: # if overcapacity, mark with an 'x' + c.draw_character((xoffset + 1, yoffset + 5), "x") + # c.draw_character((xoffset+2, yoffset+5), 'x') + c.draw_character((xoffset + 3, yoffset + 5), "x") + + # below the switchbox (east) + if eastbound > 0: + c.draw_line((xoffset + 6, yoffset + 6), (xoffset + 6, yoffset + 8)) + if draw_demand: + c.draw_character((xoffset + 5, yoffset + 7), superscripts[eastbound]) + if eastbound > 4: # if overcapacity, mark with an 'x' + c.draw_character((xoffset + 6, yoffset + 6), "x") + # c.draw_character((xoffset+6, yoffset+7), 'x') + c.draw_character((xoffset + 6, yoffset + 8), "x") + if westbound > 0: + c.draw_line((xoffset + 8, yoffset + 1), (xoffset + 8, yoffset + 3)) + if draw_demand: + c.draw_character((xoffset + 9, yoffset + 2), superscripts[westbound]) + if westbound > 4: # if overcapacity, mark with an 'x' + c.draw_character((xoffset + 8, yoffset + 1), "x") + # c.draw_character((xoffset+7, yoffset+2), 'x') + c.draw_character((xoffset + 8, yoffset + 3), "x") + + +SB_WIDTH = 10 +SB_HEIGHT = 5 # distances between switchboxes + + +def draw_switchboxes(c, switchboxes): + for item in switchboxes: + draw_switchbox( + c, + SB_WIDTH * item["row"], + SB_HEIGHT * item["col"], + item["source_count"], + item["destination_count"], + item["northbound"], + item["southbound"], + item["eastbound"], + item["westbound"], + draw_demand=True, + name="{},{}".format(item["col"], item["row"]), + ) + + +# given a route, draw arrow characters to indicate the route +# route is a list of switchboxes, represented as int tuple coordinates +left_arrow = "\u2190" +up_arrow = "\u2191" +right_arrow = "\u2192" +down_arrow = "\u2193" + + +def draw_route(c, route): + for i in range(len(route) - 1): + col = route[i][0][0] + row = route[i][0][1] + xoffset = SB_WIDTH * row + yoffset = SB_HEIGHT * col + if len(route[i]) == 1: + continue + dirs = route[i][1] + + # draw source and destination + if i == 0: + c.draw_character((xoffset + 5, yoffset + 5), "S") + if i == (len(route) - 2): + c.draw_character((xoffset + 9, yoffset + 5), "D") + + if i == 0: + if row == 0: # for routes starting in the shim, draw arrows coming from PL + c.draw_character((xoffset + 1, yoffset + 4), right_arrow) + c.draw_character((xoffset + 2, yoffset + 4), right_arrow) + c.draw_character((xoffset + 3, yoffset + 4), right_arrow) + + for j in range(len(dirs)): + # draw indications for cores the route passes through + c.replace_character((xoffset + 7, yoffset + 5), "*", "#") + # 0 = North, 1 = East, 2 = South, 3 = West + if dirs[j] == "North": + c.draw_character((xoffset + 11, yoffset + 4), right_arrow) + c.draw_character((xoffset + 12, yoffset + 4), right_arrow) + c.draw_character((xoffset + 13, yoffset + 4), right_arrow) + row = row + 1 + elif dirs[j] == "East": + c.draw_character((xoffset + 6, yoffset + 7), down_arrow) + col = col + 1 + elif dirs[j] == "South": + c.draw_character((xoffset + 1, yoffset + 5), left_arrow) + c.draw_character((xoffset + 2, yoffset + 5), left_arrow) + c.draw_character((xoffset + 3, yoffset + 5), left_arrow) + row = row - 1 + elif dirs[j] == "West": + c.draw_character((xoffset + 8, yoffset + 2), up_arrow) + col = col - 1 + elif dirs[j] == "DMA": + # draw destination + c.draw_character((xoffset + 9, yoffset + 5), "D") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Draw switchboxes, demands and routes") + parser.add_argument("-j", "--json", help="Filepath for JSON file to read") + parser.add_argument("-r", "--route_list", help="List of routes to print") + parser.add_argument( + "-o", + "--output", + help="Path to output directory. Text files of the routes will be stored here.", + ) + args = parser.parse_args() + + if args.json: + json_file_path = args.json + else: + json_file_path = "switchbox.json" # default JSON + + with open(json_file_path) as f: + json_data = json.load(f) + + switchboxes = [] + routes = [] + + for key, item in json_data.items(): + if "switchbox" in key: + switchboxes.append(item) + if "route" in key: + routes.append(item) + + max_col = 0 + max_row = 0 + for switchbox in switchboxes: + if switchbox["col"] > max_col: + max_col = switchbox["col"] + if switchbox["row"] > max_row: + max_row = switchbox["row"] + + routes_to_print = [] + if args.route_list: + for route in args.route_list.split(","): + routes_to_print.append(int(route.strip())) + else: + routes_to_print = range(len(routes)) + + output_directory = "./routes/" + if args.output: + output_directory = args.output + + if not os.path.isdir(output_directory): + os.mkdir(output_directory) + + for i in routes_to_print: + c = canvas(12 * (max_row + 1), 5 + 5 * (max_col + 1)) + draw_switchboxes(c, switchboxes) + filename = os.path.join(output_directory, "route{}.txt".format(i)) + sys.stdout = sys.__stdout__ + print( + "Printing route {} of {}: {}".format(i, len(routes_to_print) - 1, filename) + ) + with open(filename, "w") as f: + sys.stdout = f + print("Route {}: {}".format(i, routes[i])) + draw_route(c, routes[i]) + c.rasterize() diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/.gitignore b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/.gitignore new file mode 100644 index 000000000..e8493e538 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/.gitignore @@ -0,0 +1,7 @@ +build +.vscode +__pycache__/ +routes/ +*.safetensors +q4nx_files/ +*.exe diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/Makefile b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/Makefile new file mode 100755 index 000000000..0c59d9336 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/Makefile @@ -0,0 +1,67 @@ +# +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Portions of this file consist of AI-generated content. +# Modified by Alfred + +include makefiles/common.mk +MODEL_TYPE ?= MINICPM5_15B_A2_5B + +# 1 = chess, 0 = Peano (default). Both give bit-identical outputs; see README.md, "Peano". +ENABLE_CHESSCC ?= 0 +HOME_DIR := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST)))) + +# ATTN_TAP=1 also sends the attention output (before o_proj) to the host, for +# checking it against the reference. It builds into its own folder, so a tap +# build and a normal build never mix; run it with `run.exe --attn_tap`. +ATTN_TAP ?= 0 +# DEBUG_TAP=x (debug only): copies of the x stream to IT4, see layer_aie.py +DEBUG_TAP ?= +BUILD_DIR := build/$(MODEL_TYPE)$(if $(filter 1,$(ATTN_TAP)),_attn_tap)$(if $(DEBUG_TAP),_dbg_$(DEBUG_TAP)) + +KERNEL_ARGS := -DMODEL_TYPE=${MODEL_TYPE} +IRON_ARGS := ${MODEL_TYPE} ${ATTN_TAP} ${DEBUG_TAP} + +VERBOSE ?= 0 + +# Kernel makefile +include makefiles/kernel.mk + +# Bitstream makefile +include makefiles/bitstream.mk + +# Host makefile +include makefiles/host.mk + +.PHONY: all kernel link bitstream host clean clean_all test route +all: ${XCLBIN_TARGETS} ${HOST_C_TARGET} + +clean_all: + -@rm -rf build + -@rm -rf log + -@rm -rf *.exe + -@rm -rf trace* + -@rm -rf routes + +kernel: ${KERNEL_OBJS} + +link: ${IRON_BOTH_MLIR_TARGET} + +bitstream: ${XCLBIN_TARGETS} + +host: ${HOST_C_TARGET} + +clean: + -@rm -rf build/host + -@rm -rf ${HOST_C_TARGET} + +test: $(HOST_C_TARGET) + export LD_LIBRARY_PATH=/opt/xilinx/xrt/lib && ./$(HOST_C_TARGET) -m ${MODEL_TYPE}$(if $(filter 1,$(ATTN_TAP)), --attn_tap) + +route: ${IRON_BOTH_MLIR_TARGET} + mkdir -p routes + aie-opt --aie-create-pathfinder-flows --aie-find-flows ${<} | aie-translate --aie-flows-to-json > ./routes/route.json + python visualize.py -j ./routes/route.json diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/README.md b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/README.md new file mode 100644 index 000000000..2bef74327 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/README.md @@ -0,0 +1,235 @@ + + +# MiniCPM5-15B-A2.5B decoding layer (NPU2) + +One attention + MoE decoder layer for one token, as a single xclbin, used for all +28 layers of openbmb/MiniCPM5-15B-A2.5B. Started as a copy of +`Hy_mem_30BA3B/moe_decoding` (itself from `Qwen3_6/qwen3_6_moe_decoding`). + +Attention: 32 q heads, head dim 128, full RoPE, no q/k norm, and a sigmoid output +gate (`o_in = attn * sigmoid(x @ W_gate)`). The model has 2 KV heads; the host +duplicates them to 4 (`[h0, h0, h1, h1]`, in the k/v weight rows and in +`--kv_fill`), so each attention CU holds one KV head as in the Hy layer. +MoE: 160 experts, top 16, plus one shared expert, all 512 wide, Q4_K. + +## Layer 0 (dense) runs on this xclbin + +Layer 0 is a dense SwiGLU MLP 8192 wide. SwiGLU is elementwise over its width, +so the MLP is the sum of 16 slices of 512, and the host stores them as experts +0..15: up/gate rows map one to one (the q4nx is row-block major, so each slice +is one contiguous byte range), and down `[D, 8192]` gives expert e column blocks +2e and 2e+1 of every row block. For layers below `FIRST_K_DENSE` +(`models/minicpm5-15b-a2.5b.h`) the router skips routing and picks experts 0..15 +with weight 1; the host zeroes that layer's router weight, bias and shared +expert. The config keys are `n_routed_experts` and `first_k_dense_replace`. + +## MoE + +- **Router** (row 4 col 5, with the helper below it): fp32 logits from the bf16 + router weight, then `kernels/router_math.hpp`: fp32 sigmoid of all 160 logits, + top 16 of score + bias (the bias only picks experts), weight = score / sum of the + 16 * 3.66. The fp32 bias (`moe_expert_bias`) is an RTP buffer the host writes + each call (`RTP_router_expert_bias` in `rtp_addresses.txt`). +- **GLU slices**: one GLU slice is one proj round (16 cores x 32 rows = 512 + values). The host orders the up/gate weight rows so every round holds matching + rows: shared expert `[up 256 | gate 256]` (2 rounds), routed expert (one per + column) `[up 64 | gate 64]` per column (8 rounds). See + `models/minicpm5-15b-a2.5b.h`. +- **Router weight** (640 KB) does not fit MT5. The host stores it in the order it + is read and sends it first in the call: 128 experts go through MT5 (IT5 + channel 0, BD 12, packet 10) and feed the router (experts 0-63) and the helper + (64-127); the other 32 go from IT5 channel 1 (BD 13) straight to the helper + (S2MM 1, a circuit). Router and helper share the buffers through locks. +- **Routed experts**: 4 rounds of 4 experts, one expert per proj column. The host + stores each expert as [channel 0 stream | channel 1 stream] (each its gate/up + then down blocks, in read order), so the router points one linear shim BD per + channel (4 / 5 and 12 / 13, taking turns) at the chosen expert with control + packets. The rounds are pushed together, so each round's weights follow the + last with no gap. +- **Weight base address**: the router keeps one weight-buffer device address per + layer (28), read from a shim BD on that layer's first call only + (`kernels/router.cc`). The host writes the layer number each call + (`RTP_router_layer`). `run.exe -L 1 --alt_layer 2` runs two layers, each with + its own weight buffer, taking turns on one NPU context; this checks the table. + The router's control packets reuse the BDs of the shared-expert weight tasks, + so the host sets the router's "BDs ready" lock only after it has pushed the + last shared-expert task (otherwise a fast router can queue expert weights in + front of them: wrong output, no hang). + +## Attention output gate + +The proj engine runs k, v, q and gate as one 9216-row matrix (k 512, v 512, +q 4096, gate 4096 after the KV duplication). The gate core (row 4 col 2) takes +the gate rows (packet 3), and once the full attention output is there sends +`attn * sigmoid(gate)` into the proj x input as packet 24, which the o projection +reads. + +## Tile map + +| | col 0 | col 1 | col 2 | col 3 | col 4 | col 5 | col 6 | col 7 | +|--------|-------|-------|--------------|----------------|----------------|---------------|-------|-------| +| row 5 | proj | proj | - | attn kv (CU1) | attn kv (CU3) | GLU | proj | proj | +| row 4 | proj | proj | output gate | attn qk (CU1) | attn qk (CU3) | router | proj | proj | +| row 3 | proj | proj | RoPE | attn kv (CU0) | attn kv (CU2) | router helper | proj | proj | +| row 2 | proj | proj | rms+residual | attn qk (CU0) | attn qk (CU2) | - | proj | proj | +| MT | gather| proj x/y | aux | KV, O join | KV, O half | router w | gather| proj w| +| IT | w | w | x/norms/rope | KV (heads 0,1), O tap | KV (heads 2,3) | router w | w | w | + +CU i holds KV head i (model KV head i / 2, duplicated) and its 8 query heads. + +## Q4_K math (proj cores) + +`kernels/q4_core.h`, `_Q4K_x_int8` (`Q4K_INT8_MMUL 1`; must match `host/models.h`): +x is rounded to int8 per 32-value group with a power-of-two scale, once per x +slice; the group sums run on the native `mac_4x8_8x16` instruction against the +4-bit weights (unpacked by hardware); scales and mins stay fp32. The host +reorders every weight block at load time (`q4k_relayout_for_mmul`). About 810 +cycles per block against 1780 for the old bf16 kernel (`_Q4K_x_bf16`, still there +with `Q4K_INT8_MMUL 0` on both sides). `../q4k_unit_test` (`./build.sh`) runs one +block on one core and checks every intermediate against the CPU. + +Each proj core keeps a 4-block weight ring (two 2-block buffers, +`W_RING_BLOCKS` in `kernels/proj_main.cc`), so the weight stream can run further +ahead; the int8 x cache is four 4 KB arrays and the proj stack is 4 KB (every +proj function has a 0-byte frame) so that everything fits the 16 KB data banks. + +## x into the proj engine + +rms, the attention output (MT3) and GLU send packets into MT1's x input; MT1 +broadcasts x to all 16 proj cores over one circuit (as in Gemma4 and Qwen3.5 +decoding). In the routed-expert down step the 4 columns run 4 different experts: +GLU sends the 4 experts' h round robin and each core keeps its own column's +slices (`col_idx`, see `kernels/proj_main.cc`). + +## Routing check + +`check_routes.py` runs after every xclbin build (`makefiles/bitstream.mk`). It +fails the build if a packet flow is delivered somewhere it was not asked to go, +or if flows that wait on each other share a switch arbiter (a packet stalled +halfway holds the arbiter; this deadlocked earlier versions on hardware). Packets +into MT1's x input may share an arbiter only with each other, with a short list +of flows that cannot wait on them, or with flows from their own DMA channel. +`CHECK_ROUTES=0` skips it, for experiments only. + +aiecc's router gives a different routing from run to run (its choices depend +on memory addresses, which Linux randomizes; with `setarch -R` and the same +directory and arguments it repeats). So the build reruns aiecc until the check +passes, up to `ROUTE_TRIES` (default 5) tries; a try takes about a minute. +`quick_route.py ` routes like aiecc in about 2 seconds; run it a few +times to see how often a design change passes. + +## Build and run + + make kernel # AIE kernels (.cc -> .o) + make link # IRON python -> MLIR + make bitstream # MLIR -> build//xclbins/layer.xclbin (+ routing check) + make host # run.exe + make test # run the layer test on the NPU + +Options: `ATTN_TAP=1` also sends the attention output to the host +(`run.exe --attn_tap`); `DEBUG_TAP=x` (debug only) copies rms's x to IT4. + +Host test: `run.exe -L -l [--attn_tap] [--ctx N] [--xclbin path] [--bench N] [--per_step] [--alt_layer N] [--kv_fill N --dump ]`. + +KV cache (per layer, in DDR): four blocks of `MAX_L Γ— 256` bf16 (a column's 2 KV +heads Γ— DH 128 per token, after the duplication), `[K col 0][K col 1][V col 0][V col 1]` +(all K, then all V at `kv_cache_size / 2`; `decoding_layer::kv_block(col, kv)`). `MAX_L` +(`--ctx`, default 131072 = 128K) is a multiple of 16; 128K is 256 MB per layer, +one buffer per layer (DMA offsets are 32-bit byte offsets). Zero the cache at +allocation: the 16-token reads go past `L` (masked, but must be finite). At +`L == MAX_L` the cache is full and the host refuses another call. +`--kv_fill N --dump ` is the long-context accuracy check: it fills KV +rows 0..N-1 with the Q4_K reference's K/V rows (repeated), decodes at positions +N.., and writes the outputs and new K/V rows for +an offline check, which recomputes the layer from the same +cache. + +It ends with one RESULT block: calls completed, time per token, and each check's +mean / min cos (with the worst token) against the Q4_K and bf16 references. It +exits 1 if any call did not complete. `--per_step` adds every token's numbers; +`make host VERBOSE=1` (or 2) brings back the load / buffer / call-state logs. +`MC5_TIME_HOST=1 ./run.exe ...` prints each call's host time by step. Per call +the test copies only the layer input and output (the weights once at load, the +KV cache never; ~2 ms per call instead of ~6 ms); the rest is rebuilding and +reloading the instruction sequence for the new context length. +The per-token latency it prints includes the host syncing every buffer each call; +`--bench N` times the NPU alone (N rounds of 480 back-to-back calls, context +length 8). Use it to measure speed changes. +References (`--ref_dir`, or `$FLM_REFERENCE_DIR`; not shipped): `minicpm5_reference.safetensors` +(bf16) and `minicpm5_layer_q4k_layer_.safetensors` (the whole layer recomputed with the Q4_K +weights). Debug env vars: `MC5_STOP_AFTER=` ends the run +sequence early, `MC5_DEBUG_TAP=x` reads the x tap. + +## Peano + +The notes below come from the Hy-Memory layer this unit was copied from; the +fixes are all in these sources. Peano is the default (`ENABLE_CHESSCC ?= 0`); `make ENABLE_CHESSCC=1` still builds +with chess. Run `make clean_all` (or use another `BUILD_DIR=`) when switching, since +both write the same build folder. Use Peano +`llvm-aie 22.0.0.2026090201+a36c62b9`. + +Result (2026-11-04, Strix Halo test machine): the Peano layer is **bit-identical** to chess +(outputs and new K/V rows, 0 values differ, also with 32K of KV filled), and the +chess build from these same sources is bit-identical to the old chess build. +NPU time per call: 0.762 / 0.967 / 2.398 ms at context 8 / 4K / 32K +(chess 0.756 / 0.979 / 2.550). RTP addresses are unchanged. + +What had to change, and why (each is a no-op under chess): + +1. **`.bss` is not zeroed.** chess's loader zeroes `.bss`; Peano's does not. So any + variable that must start at 0 and keep its value between calls goes to `.data` + with `AIE_PERSIST_ZERO`: the ping/pong flags (proj, glu, rms, attention) and the + router's `base_known` table (garbage there = the router trusts garbage expert + addresses). The int8 A-matrix caches in `proj_main.cc` were the costly one: + `q4k_prepare_x` writes only 1 of every 4 A rows and needs the others to be 0. + Under Peano `proj_main` now zeroes the 16 KB once, on its first call. Without + it the layer output was cos 0.03. +2. **`restrict` + locks.** `rms_residual`, `rope`, `router` and `router_helper` + took their DMA buffers as `restrict` and also take/give locks. A lock call takes + no pointer, so Peano decides it cannot touch a `restrict` buffer and drops or + moves writes across it: it deleted 3 of the 5 packet-id writes in + `rms_residual` (packets would go to the wrong core). These parameters now use + `AIE_DMA_RESTRICT`: `restrict` under chess, nothing under Peano. Helpers with + no lock inside keep their `restrict`. +3. **Lock loops.** Peano can move a loop's last lock release out of the loop. All + 12 loops that contain lock calls count with `AIE_LOCK_LOOP_CTR` (a volatile int + under Peano), as `../../Hy_mem_30BA3B/dense_decoding` does. +4. **Scalar float.** Peano runs scalar `+ -` on the vector unit and fuses `a*b+c`, + which rounds differently from chess's IEEE softfloat. The rms norm scale, rope's + Q/K norm and the router's weight normalization use `AIE_FADD / AIE_FMUL` + (compiler-rt softfloat under Peano) for their sums and means, so both compilers + give the same bits; the 1/sqrt is `flm_rsqrt` (one hardware `invsqrt`). Expert choice itself uses only vector ops and compares. +5. **Attention** (`attn_qk.cc`, `attn_kv.cc`) is now a copy of + `../../Hy_mem_30BA3B/dense_decoding`'s, which only adds Peano fixes (runtime-built constants + instead of `static const`, a workaround for Peano miscompiling `extract<8>` at a + runtime index, `AIE_*` loop macros). +6. **proj core memory** (`iron/proj_tile.py`). chess puts static data and large + locals into any free gap between buffers; Peano's linker only uses the space + after the highest buffer. The int8 caches (16 KB + 4 KB) did not fit there. + Under Peano the six proj buffers are pinned by bank: bank 0 = stack, w_0, x_0, + y_0; bank 1 = w_1, an unused pad, y_1, x_1 (x_1 ends at the bank's end). So + banks 2 and 3 (32 KB) are free for the caches, and the caches no longer share + a bank with w (chess had one cache in w_1's bank). Only the bank is pinned, not + the address: this mlir-aie's bank-aware allocator counts a buffer pinned by + `address=` twice (`checkAndAddBufferWithAddress` sets `mem_bank`, then + `checkAndAddBufferWithMemBank` places it again) and then fails. Pinned buffers + must also be declared in address order. +7. **Stacks.** chess gave every proj function a 0-byte frame (it allocates locals + statically); Peano's frames are real: proj's deepest call chain is 4480 B and + attn_kv's 2944 B. Under Peano the proj stack is 6 KB (bank 0 still fits: + 6144 + 9472 + 512 + 160 B) and attn_kv's 4 KB; the RTP addresses did not move. + `makefiles/check_peano_stack.sh` fails the build if a stack can overflow. +8. `rope.cc`: the `chess_*` loop keywords became `AIE_*` macros (under Peano the + raw keywords expand to nothing). A clang loop pragma rejects a count of 0 even + in a dead `if constexpr` branch, so the remainder loop's count is at least 1. + +Program memory is no longer tight under Peano: router 13,024 B (chess 16,282 B of +16 KB), proj 7,696 B (chess 13,072 B). + +Debugging tools that found these: `--dump` (K/V rows are the proj output, V passes +rope unchanged), a `DEBUG_TAP=x` build with `CHECK_ROUTES=0` (rms output was +bit-identical, so the bug was after rms), and `clang++ -S -emit-llvm` on one kernel +(counting the stores between lock calls). diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/check_routes.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/check_routes.py new file mode 100644 index 000000000..bb8dc5be0 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/check_routes.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""Routing check for the routed design (input_physical.mlir), run after every xclbin build. + +The packet-switched network can deadlock in ways the compiler does not see: a +switch arbiter carries one packet at a time from start to end, so a packet that +stalls halfway (its receiver is full) blocks every other flow on that arbiter, +even ones leaving through other ports. If the stalled flow is waiting for one of +those blocked flows, nothing moves again. Seen on hardware with the old x relay +design (rms -> relay packets vs MT1's per-column x packets, and proj outputs vs +those x packets). + +The check traces every packet flow hop by hop through the switch rules and fails if + 1. a flow does not arrive exactly where it was asked to, or + 2. two flows from FORBIDDEN_PAIRS groups share an arbiter in some switch. + +Usage: check_routes.py (exit 1 on a problem) + The routed file has the switch settings; the IRON file lists the flows asked + for (routing turns circuit flows into plain switch connections). +""" +import re +import sys +from collections import defaultdict + +# ---- flow groups, by (source tile (col, row), source DMA channel, packet id) ---- +# Tile positions follow iron/layer_aie.py. +PROJ_COLS = (0, 1, 6, 7) +GROUPS = { + # packets into the proj engine's x input (MT1 S2MM 3); they stall when MT1's + # x buffers are full, i.e. until the proj cores use up the x they have + "x_in": lambda xy, ch, pid: (xy, ch, pid) in {((2, 2), 0, 0), # rms + ((2, 4), 0, 24), # gated attention O (gate tile) + ((5, 5), 0, 9)}, # GLU + # proj results on their way out: core -> gather mem tiles -> MT1 -> consumers; + # the proj cores stop using x when these cannot leave + "proj_out": lambda xy, ch, pid: (xy[0] in PROJ_COLS and xy[1] >= 2 and ch == 0) + or (xy, ch) in {((0, 1), 4), ((6, 1), 4), ((1, 1), 5)}, + # the router's control packets that start the expert weight streams + "router_ctrl": lambda xy, ch, pid: (xy, ch) == ((5, 4), 1), + # flows that may share an arbiter with x_in because they can never be part of a wait + # loop with it: IT2's sends to rms and rope (layer input, rms weights) finish at the + # start of a call before any x_in packet exists; router control packets go to shim + # control registers, which always accept them, so they never stall + "x_safe": lambda xy, ch, pid: (xy, ch) in {((2, 0), 0), ((2, 0), 1), ((5, 4), 1)}, + # RoPE -> attention CUs (Q) + "rope_q": lambda xy, ch, pid: xy == (2, 3) and 16 <= pid < 20, +} +# x_in may share an arbiter only with x_in and x_safe. A wider proj_out-only rule was +# not enough: in one build GLU x packets shared with MT2 -> rms (o_proj / shared-down +# results on their way to rms) and every call hung. Anything that must move before proj +# can use its next x closes the same loop, so other flows are forbidden by default. +X_ONLY_WITH = ("x_in", "x_safe") +# Per-flow exceptions: (x_in flow, group it may share with). The gate tile sends the +# gated attention output only after it has the whole attention output, i.e. after +# every CU got its Q, and RoPE sends the next call's Q only after proj used all of +# that output (o_proj comes first), so gate O and RoPE Q are never in flight +# together. They share the link (2, 3) -> (2, 2) in most routings. +X_ALSO_WITH = {((2, 4), 0, 24): "rope_q"} +FORBIDDEN_PAIRS = [("x_in", "proj_out")] +# Reported but not failing yet: the shipping Qwen3.6 build has this sharing and +# runs; it matters once the routed experts run (to be fixed in the MoE port). +WARN_PAIRS = [("proj_out", "router_ctrl")] + +# ---- parse ------------------------------------------------------------------------ +text = open(sys.argv[1]).read() +tile_xy = {m.group(1): (int(m.group(2)), int(m.group(3))) + for m in re.finditer(r"%(\w+)\s*=\s*aie\.tile\((\d+),\s*(\d+)\)", text)} + +def blocks(kind): + """Bodies of aie.(%tile) { ... }, brace matched.""" + for m in re.finditer(r"aie\.%s\(%%(\w+)\)\s*\{" % kind, text): + depth, i = 1, m.end() + while depth: + depth += {"{": 1, "}": -1}.get(text[i], 0) + i += 1 + yield tile_xy[m.group(1)], text[m.end():i - 1] + +port = lambda s: tuple(x.strip() for x in s.split(":")) # "East : 2" -> ("East", "2") +switch = {} # xy -> (rules, amsel masters, amsel arbiter, connects) +for xy, body in blocks("switchbox"): + masters = defaultdict(list) + for m in re.finditer(r"aie\.masterset\(([^,]+:[^,]+),\s*([^)]*)\)", body): + for a in m.group(2).split(","): + masters[a.strip()].append(port(m.group(1))) + rules = defaultdict(list) + for m in re.finditer(r"aie\.packet_rules\(([^)]*)\)\s*\{(.*?)\}", body, re.S): + for r in re.finditer(r"aie\.rule\((\d+),\s*(\d+),\s*(%\w+)\)", m.group(2)): + rules[port(m.group(1))].append((int(r.group(1)), int(r.group(2)), r.group(3))) + arbiter = {m.group(1): int(m.group(2)) + for m in re.finditer(r"(%\w+)\s*=\s*aie\.amsel<(\d+)>\s*\((\d+)\)", body)} + connects = defaultdict(list) + for a, b in re.findall(r"aie\.connect<([^,]+),\s*([^>]+)>", body): + connects[port(a)].append(port(b)) + switch[xy] = (rules, masters, arbiter, connects) +shim_mux = {xy: [(port(a), port(b)) for a, b in re.findall(r"aie\.connect<([^,]+),\s*([^>]+)>", body)] + for xy, body in blocks("shim_mux")} + +STEP = {"East": (1, 0, "West"), "West": (-1, 0, "East"), "North": (0, 1, "South"), "South": (0, -1, "North")} + +def start_port(xy, ch): + """Where a DMA MM2S channel enters its switchbox (shims go through the mux).""" + if xy[1] == 0: + for a, b in shim_mux.get(xy, []): + if a == ("DMA", str(ch)): + return ("South", b[1]) + return None + return ("DMA", str(ch)) + +def arrive(xy, mport): + """A master port that ends a flow: a DMA, or a shim's South into the mux.""" + if mport[0] == "DMA": + return (xy, "DMA", mport[1]) + if xy[1] == 0 and mport[0] == "South": + for a, b in shim_mux.get(xy, []): + if a == ("North", mport[1]): + return (xy, b[0], b[1]) + return None + +def next_hop(xy, mport): + if mport[0] in STEP: + dx, dy, back = STEP[mport[0]] + return (xy[0] + dx, xy[1] + dy), (back, mport[1]) + return None + +def trace_packet(xy, slave, pid, arbs, dests, depth=0): + if depth > 64 or xy not in switch: + return + rules, masters, arbiter, _ = switch[xy] + for mask, value, amsel in rules.get(slave, []): + if pid & mask == value & mask: # first matching rule wins + arbs.add((xy, arbiter.get(amsel))) + for mport in masters[amsel]: + hop = next_hop(xy, mport) + end = arrive(xy, mport) + if end: + dests.add(end) + elif hop: + trace_packet(hop[0], hop[1], pid, arbs, dests, depth + 1) + return + +def trace_circuit(xy, slave, dests, depth=0): + if depth > 64 or xy not in switch: + return + for mport in switch[xy][3].get(slave, []): + end = arrive(xy, mport) + hop = next_hop(xy, mport) + if end: + dests.add(end) + elif hop: + trace_circuit(hop[0], hop[1], dests, depth + 1) + +# ---- what was asked (from the IRON MLIR) ------------------------------------------ +asked = open(sys.argv[2]).read() +asked_xy = {m.group(1): (int(m.group(2)), int(m.group(3))) + for m in re.finditer(r"%(\w+)\s*=\s*aie\.tile\((\d+),\s*(\d+)\)", asked)} +want_packet = defaultdict(set) +for m in re.finditer(r"aie\.packet_flow\((\d+)\)\s*\{(.*?)\n\s*\}", asked, re.S): + srcs = re.findall(r"packet_source<%(\w+),\s*(\w+)\s*:\s*(\d+)>", m.group(2)) + dsts = re.findall(r"packet_dest<%(\w+),\s*(\w+)\s*:\s*(\d+)>", m.group(2)) + for s in srcs: + for d in dsts: + want_packet[(asked_xy[s[0]], s[1], int(s[2]), int(m.group(1)))].add((asked_xy[d[0]], d[1], d[2])) +want_circuit = defaultdict(set) +for s, sb, sc, d, db, dc in re.findall(r"aie\.flow\(%(\w+),\s*(\w+)\s*:\s*(\d+),\s*%(\w+),\s*(\w+)\s*:\s*(\d+)\)", asked): + want_circuit[(asked_xy[s], sb, int(sc))].add((asked_xy[d], db, dc)) + +# ---- check ------------------------------------------------------------------------ +problems, warnings = [], [] +arb_users = defaultdict(set) +for key, want in sorted(want_packet.items()): + xy, bundle, ch, pid = key + if bundle != "DMA": + continue # control-port sources (shim TileControl) are not DMA channels + arbs, dests = set(), set() + sp = start_port(xy, ch) + if sp: + trace_packet(xy, sp, pid, arbs, dests) + want_dma = {w for w in want if w[1] == "DMA"} + got_dma = {d for d in dests if d[1] == "DMA"} + if got_dma != want_dma: + problems.append(f"packet flow src {xy} ch{ch} id{pid}: asked {sorted(want_dma)}, routed to {sorted(got_dma)}") + for a in arbs: + arb_users[a].add(key[:1] + key[2:]) # (xy, ch, pid) +for key, want in sorted(want_circuit.items()): + xy, bundle, ch = key + if bundle != "DMA": + continue + dests = set() + sp = start_port(xy, ch) + if sp: + trace_circuit(xy, sp, dests) + want_dma = {w for w in want if w[1] == "DMA"} + if {d for d in dests if d[1] == "DMA"} != want_dma: + problems.append(f"circuit flow src {xy} ch{ch}: asked {sorted(want_dma)}, routed to {sorted(dests)}") + +for (xy, arb), users in sorted(arb_users.items(), key=lambda t: (t[0][0], t[0][1] or 0)): + groups = defaultdict(set) + for u in users: + for name, member in GROUPS.items(): + if member(*u): + groups[name].add(u) + for pairs, out in ((FORBIDDEN_PAIRS, problems), (WARN_PAIRS, warnings)): + for a, b in pairs: + if groups[a] and groups[b] and groups[a] != groups[b]: + out.append(f"switch {xy} arbiter {arb} shared by {a} {sorted(groups[a])} and {b} {sorted(groups[b])}") + # strict x_in rule: everything else on an x_in arbiter must be in X_ONLY_WITH + allowed = set().union(*(groups[g] for g in X_ONLY_WITH)) + # flows from the same DMA channel as an x_in flow are fine: a channel sends one + # packet at a time, so while its x packet is stalled it sends nothing else anyway + x_channels = {u[:2] for u in groups["x_in"]} + allowed |= {u for u in users if u[:2] in x_channels} + for x in sorted(groups["x_in"]): + bad = users - allowed - groups[X_ALSO_WITH[x]] if x in X_ALSO_WITH else users - allowed + if bad: + problems.append(f"switch {xy} arbiter {arb} shared by x_in {x} and {sorted(bad)}") + +for w in warnings: + print("check_routes: WARNING " + w) +if problems: + print("check_routes: FAILED") + for p in problems: + print(" " + p) + sys.exit(1) +print(f"check_routes: OK ({len(want_packet)} packet flows, {len(want_circuit)} circuit flows)") diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/decoding_layer.cpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/decoding_layer.cpp new file mode 100644 index 000000000..56464b7c7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/decoding_layer.cpp @@ -0,0 +1,1164 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "decoding_layer.hpp" + +#include +#include +#include +#include +#include + +decoding_layer::decoding_layer(model_list::model_t model_type, LM_Config& lm_config, npu_app_manager* layer_app_mgr, int context_length, bool attn_tap) + : model_type(model_type), lm_config(lm_config), layer_app_mgr(layer_app_mgr), MAX_L(context_length), attn_tap(attn_tap) { + LOG_VERBOSE(1, "Initializing decoding layer"); + + this->layer_app = this->layer_app_mgr->create_app(); + + this->current_context_length = 0; + + num_hidden_layers = lm_config.num_hidden_layers; + DH = lm_config.head_dim; + DQ = lm_config.head_dim * lm_config.num_attention_heads; + // The model has 2 KV heads, the kernels 4 (one per attention CU, 8 query heads + // each): load_weights duplicates every k/v head, so kernel head i is model head + // i / 2, and the KV cache holds each model head twice. + model_kv_heads = model_list::get_model_kv_heads(model_type); + assert(lm_config.num_key_value_heads == model_kv_heads); + num_kv_heads = attn_cus; + assert(num_kv_heads % model_kv_heads == 0); + DK = lm_config.head_dim * num_kv_heads; + DV = lm_config.head_dim * num_kv_heads; + // config.json's intermediate_size is the dense layer's; the MoE width must + // match the kernels (see model_list::get_moe_intermediate_size) + intermediate_size = model_list::get_moe_intermediate_size(model_type); + D = lm_config.hidden_size; + + assert(num_kv_heads == attn_cus); // one KV head per attention CU + // _move_kv_cache reads whole 16-token chunks, so MAX_L must be whole chunks + assert(MAX_L % L_CHUNK == 0); + kv_heads_per_col = num_kv_heads / attn_cols; + kv_col_row = (size_t)kv_heads_per_col * DH; + kv_col_half = (size_t)MAX_L * kv_col_row; + kv_cache_size = (size_t)MAX_L * (DK + DV); + + RoPE_DIM = int(DH * model_list::get_rope_partial_factor(model_type)); + + _read_rtp_addresses(lm_config.layer_xclbin_name); + + // Debug: MC5_STOP_AFTER=<1..5> ends the run sequence early, to find where a + // hang is (see _gen_sequence). Unset or 0 runs the whole layer. + const char* stop_env = std::getenv("MC5_STOP_AFTER"); + debug_stop_after = stop_env ? std::atoi(stop_env) : 0; + const char* tap_env = std::getenv("MC5_DEBUG_TAP"); + debug_tap = tap_env ? tap_env : ""; + if (debug_stop_after != 0) { + header_print("warning", "MC5_STOP_AFTER=" << debug_stop_after << ": the run sequence ends early (debug)"); + } + + JSON_GET(this->num_experts, lm_config._json_config, "n_routed_experts", 0, int); + JSON_GET(this->first_k_dense, lm_config._json_config, "first_k_dense_replace", 0, int); + + JSON_GET(this->num_activate_experts, lm_config._json_config, "num_experts_per_tok", 0, int); + // the config, only with VERBOSE >= 1 (make host VERBOSE=1) + LOG_VERBOSE(1, "Decoding layer config: D " << D << ", DQ " << DQ << ", DK " << DK << ", DV " << DV + << ", RoPE dim " << RoPE_DIM << ", expert width " << intermediate_size + << ", experts " << num_activate_experts << "/" << num_experts); + has_qk_norm = model_list::has_qk_norm(this->model_type); + LOG_VERBOSE(1, " QK norm: " << (has_qk_norm ? "yes" : "no")); + LOG_VERBOSE(1, " attention tap: " << (attn_tap ? "yes" : "no")); + this->rope_scaling = model_list::get_rope_scaling(this->model_type); + + _weight_desc.attn_k = weight_desc_t(flm_q4k, {D, DK}, "model.layer.%d.self_attn.k_proj.weight"); + _weight_desc.attn_k_norm = weight_desc_t(flm_bf16, {DH}, "model.layer.%d.self_attn.k_norm.weight"); + _weight_desc.input_layer_norm = weight_desc_t(flm_bf16, {D}, "model.layer.%d.input_layernorm.weight"); + _weight_desc.attn_q = weight_desc_t(flm_q4k, {D, DQ}, "model.layer.%d.self_attn.q_proj.weight"); + _weight_desc.attn_gate = weight_desc_t(flm_q4k, {D, DQ}, "model.layer.%d.self_attn.gate_proj.weight"); + _weight_desc.attn_q_norm = weight_desc_t(flm_bf16, {DH}, "model.layer.%d.self_attn.q_norm.weight"); + _weight_desc.attn_v = weight_desc_t(flm_q4k, {D, DV}, "model.layer.%d.self_attn.v_proj.weight"); + _weight_desc.ffn_down_exps = weight_desc_t(flm_q4k, {intermediate_size, D, num_experts}, "model.layer.%d.mlp.down_exps_proj.weight"); + _weight_desc.ffn_down_shexp = weight_desc_t(flm_q4k, {intermediate_size, D}, "model.layer.%d.mlp.share_down_exps_proj.weight"); + _weight_desc.ffn_up_exps = weight_desc_t(flm_q4k, {D, intermediate_size, num_experts}, "model.layer.%d.mlp.up_exps_proj.weight"); + _weight_desc.ffn_up_shexp = weight_desc_t(flm_q4k, {D, intermediate_size}, "model.layer.%d.mlp.share_up_exps_proj.weight"); + _weight_desc.ffn_gate_exps = weight_desc_t(flm_q4k, {D, intermediate_size, num_experts}, "model.layer.%d.mlp.gate_exps_proj.weight"); + _weight_desc.ffn_gate_shexp = weight_desc_t(flm_q4k, {D, intermediate_size}, "model.layer.%d.mlp.share_gate_exps_proj.weight"); + _weight_desc.ffn_gate_inp = weight_desc_t(flm_bf16, {D, num_experts}, "model.layer.%d.moe_router.weight"); + _weight_desc.post_attntion_norm = weight_desc_t(flm_bf16, {D}, "model.layer.%d.post_attention_layernorm.weight"); + _weight_desc.attn_output = weight_desc_t(flm_q4k, {DQ, D}, "model.layer.%d.self_attn.o_proj.weight"); + + proj_weights_helper.add_weight(_weight_desc.ffn_up_exps); + proj_weights_helper.add_weight(_weight_desc.ffn_gate_exps); + proj_weights_helper.add_weight(_weight_desc.ffn_down_exps); + // k, v, q, gate back to back: the proj engine runs them as one matrix; RoPE + // takes its K/V block (kv_in) first, then Q (q_in), and the gate tile the + // output gate logits (the last GATE_REPEATS rounds) + proj_weights_helper.add_weight(_weight_desc.attn_k); + proj_weights_helper.add_weight(_weight_desc.attn_v); + proj_weights_helper.add_weight(_weight_desc.attn_q); + proj_weights_helper.add_weight(_weight_desc.attn_gate); + proj_weights_helper.add_weight(_weight_desc.attn_output); + proj_weights_helper.add_weight(_weight_desc.ffn_up_shexp); + proj_weights_helper.add_weight(_weight_desc.ffn_gate_shexp); + proj_weights_helper.add_weight(_weight_desc.ffn_down_shexp); + + + assert(proj_weights_helper.get_size() < 512ull * 1024 * 1024); // check to avoid 512 M problem + + // [input_layernorm | post_attention_layernorm | router weight] + norm_exp_helper.add_weight(_weight_desc.input_layer_norm); + norm_exp_helper.add_weight(_weight_desc.post_attntion_norm); + norm_exp_helper.add_weight(_weight_desc.ffn_gate_inp); + + + // self managed + _weight_desc.attn_q_norm.indp(); + _weight_desc.attn_k_norm.indp(); + + + + // [0, D): layer input, then layer output; [D, D + DQ): attention tap + this->hidden_states_buffer = this->layer_app.create_bo_buffer(8192); + assert(D + DQ <= 8192); + this->all_proj_weight_buffer = this->layer_app.create_bo_buffer(proj_weights_helper.get_size()); + this->rms_weights_buffer = this->layer_app.create_bo_buffer(norm_exp_helper.get_size() / sizeof(bf16)); + if (this->has_qk_norm) { + this->rope_rms_buffer = this->layer_app.create_bo_buffer(RoPE_DIM + DH * 2); + } + else { + this->rope_rms_buffer = this->layer_app.create_bo_buffer(RoPE_DIM); + } + + + this->kv_cache = this->layer_app.create_bo_buffer(kv_cache_size); + this->kv_cache.memset((bf16)0); + this->kv_cache.sync_to_device(); + +} + +// The xclbin build writes the address of every RTP buffer to +// rtp_addresses.txt next to layer.xclbin, one "RTP_
" per line. +// The attention tiles' context length lives in RTP_L_attn_{qk,kv}_core__. +void decoding_layer::_read_rtp_addresses(const std::string& xclbin_path){ + std::filesystem::path rtp_path = std::filesystem::path(xclbin_path).parent_path() / "rtp_addresses.txt"; + std::ifstream file(rtp_path); + if (!file.is_open()) { + header_print("error", "Cannot open " << rtp_path.string()); + exit(1); + } + std::map addr; + std::string name; + uint32_t value; + while (file >> name >> value) { + addr[name] = value; + } + auto lookup = [&](const char* kind, const int rc[2]) { + std::string key = std::string("RTP_L_attn_") + kind + "_core_" + std::to_string(rc[0]) + "_" + std::to_string(rc[1]); + if (addr.count(key) == 0) { + header_print("error", key << " not in " << rtp_path.string()); + exit(1); + } + return addr[key]; + }; + for (int i = 0; i < attn_cus; i++) { + l_qk_address[i] = lookup("qk", attn_qk_rc[i]); + l_kv_address[i] = lookup("kv", attn_kv_rc[i]); + } + if (addr.count("RTP_router_expert_bias") == 0) { + header_print("error", "RTP_router_expert_bias not in " << rtp_path.string()); + exit(1); + } + router_bias_address = addr["RTP_router_expert_bias"]; + if (addr.count("RTP_router_layer") == 0) { + header_print("error", "RTP_router_layer not in " << rtp_path.string()); + exit(1); + } + router_layer_address = addr["RTP_router_layer"]; +} + +/// Lays a quantized weight out in the order the proj engine reads it: rows of +/// blocks are taken vertical_blocks at a time and interleaved block by block, +/// so one shim BD streams the blocks of vertical_blocks proj cores together. +/// Q4_K blocks (32 rows x 256 columns, 4736 B) from the q4nx order into the +/// order of the int8-mmul kernel (_Q4K_x_int8 in kernels/q4_core.h), in place: +/// qs [256 columns][16 B] -> [k step 16][half t 2][16 columns][8 B] +/// (byte b of a column holds rows 2b, 2b + 1; half t = rows 16t .. 16t+15) +/// scales [group 8][32 rows] -> [h 2][t 2][a 4][16 rows], group = 4h + a +/// mins, S, M unchanged. +/// One B matrix of the mmul (16 columns x 16 rows) is then 128 contiguous bytes. +void decoding_layer::q4k_relayout_for_mmul(u8* data, size_t bytes) +{ + constexpr size_t BLOCK = 4736, SCALES = 0, QS = 512; + assert(bytes % BLOCK == 0); + std::vector old(BLOCK); + for (size_t off = 0; off < bytes; off += BLOCK) { + u8* blk = data + off; + memcpy(old.data(), blk, BLOCK); + for (int k = 0; k < 16; k++) // 16 columns per k step + for (int t = 0; t < 2; t++) // rows 16t .. 16t+15 + for (int c = 0; c < 16; c++) + memcpy(blk + QS + (k * 2 + t) * 128 + c * 8, + old.data() + QS + (k * 16 + c) * 16 + t * 8, 8); + for (int h = 0; h < 2; h++) + for (int t = 0; t < 2; t++) + for (int a = 0; a < 4; a++) + memcpy(blk + SCALES + ((h * 2 + t) * 4 + a) * 16, + old.data() + SCALES + (4 * h + a) * 32 + 16 * t, 16); + } +} + +void decoding_layer::reorder_cpy(u8 *dst, buffer &src, const int col, flm_dtype_t dtype, const int vertical_blocks) +{ + assert(is_quantize(dtype)); + + const int a_block_size = get_quantization_byte_size(QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE, dtype); + + const int blocks_per_row = col / QXNX_COL_BLOCK_SIZE; + const int rows = src.size() / a_block_size / blocks_per_row; + + u8 *dst_ptr = dst; + std::vector src_ptr(vertical_blocks); + for (int i = 0; i < vertical_blocks; i++) + src_ptr[i] = src.data() + i * a_block_size * blocks_per_row; + + for (int r = 0; r < rows; r += vertical_blocks) + { + for (int c = 0; c < blocks_per_row; c++) + { + for (int i = 0; i < vertical_blocks; i++) + { + memcpy(dst_ptr, src_ptr[i], a_block_size); + dst_ptr += a_block_size; + src_ptr[i] += a_block_size; + } + } + for (int i = 0; i < vertical_blocks; i++) + { + src_ptr[i] += (vertical_blocks - 1) * a_block_size * blocks_per_row; + if (src_ptr[i] + a_block_size * blocks_per_row > src.end()) + src_ptr[i] = src.data(); // useless padding + } + } +} + + +void decoding_layer::load_weights(Q4NX& q4nx, int layer_idx) { + // the router keeps one weight base address per layer, by this number + // (MAX_LAYERS in the model header = num_hidden_layers = 48) + assert(layer_idx >= 0 && layer_idx < num_hidden_layers); + this->layer_slot = layer_idx; + u8* w_ptr_begin = this->all_proj_weight_buffer.data(); + + _load_moe_weights(q4nx, layer_idx); + + { + LOG_VERBOSE(1, "Loading qkv and gate weights"); + weight_desc_t& desc_q = _weight_desc.attn_q; + weight_desc_t& desc_k = _weight_desc.attn_k; + weight_desc_t& desc_v = _weight_desc.attn_v; + weight_desc_t& desc_g = _weight_desc.attn_gate; + u8* w_ptr = w_ptr_begin + desc_k.offset; + buffer w_q; + buffer w_k; + buffer w_v; + buffer w_g; + q4nx.load_weights(w_q, desc_q.format_name(layer_idx)); + q4nx.load_weights(w_k, desc_k.format_name(layer_idx)); + q4nx.load_weights(w_v, desc_v.format_name(layer_idx)); + q4nx.load_weights(w_g, desc_g.format_name(layer_idx)); + // model KV head h -> kernel heads h * dup .. h * dup + dup - 1 (see the + // constructor); rows are output-major, so a head is one byte range + const int dup = num_kv_heads / model_kv_heads; + auto dup_heads = [&](buffer& w) { + assert(w.size() * dup == desc_k.get_size()); + const size_t head_bytes = w.size() / model_kv_heads; + buffer out(w.size() * dup); + for (int h = 0; h < num_kv_heads; h++) + memcpy(out.data() + h * head_bytes, w.data() + (h / dup) * head_bytes, head_bytes); + return out; + }; + buffer w_k4 = dup_heads(w_k); + buffer w_v4 = dup_heads(w_v); + LOG_VERBOSE(1, "Copying qkv and gate weights to buffer"); + // k, v, q, gate back to back (see the constructor) + assert(desc_v.offset == desc_k.offset + desc_k.get_size()); + assert(desc_q.offset == desc_v.offset + desc_v.get_size()); + assert(desc_g.offset == desc_q.offset + desc_q.get_size()); + reorder_cpy(w_ptr, w_k4, D, desc_k.dtype); + w_ptr += desc_k.get_size(); + reorder_cpy(w_ptr, w_v4, D, desc_v.dtype); + w_ptr += desc_v.get_size(); + reorder_cpy(w_ptr, w_q, D, desc_q.dtype); + w_ptr += desc_q.get_size(); + reorder_cpy(w_ptr, w_g, D, desc_g.dtype); + desc_q.load(); + desc_k.load(); + desc_v.load(); + desc_g.load(); + } + // read o weights + { + LOG_VERBOSE(1, "Loading o weights"); + weight_desc_t& desc = _weight_desc.attn_output; + u8* w_ptr = w_ptr_begin + desc.offset; + buffer w_o; + q4nx.load_weights(w_o, desc.format_name(layer_idx)); + reorder_cpy(w_ptr, w_o, DQ, desc.dtype); + desc.load(); + } + // read rms weights and the router weight (same buffer, see the constructor) + { + LOG_VERBOSE(1, "Loading rms weights"); + buffer w_rms_pre; + buffer w_rms_post; + + bf16* w_rms_ptr = this->rms_weights_buffer.data(); + q4nx.load_weights(w_rms_pre, _weight_desc.input_layer_norm.format_name(layer_idx)); + q4nx.load_weights(w_rms_post, _weight_desc.post_attntion_norm.format_name(layer_idx)); + + memcpy((unsigned char*)w_rms_ptr, w_rms_pre.data(), D * sizeof(bf16)); + w_rms_ptr += D; + memcpy((unsigned char*)w_rms_ptr, w_rms_post.data(), D * sizeof(bf16)); + w_rms_ptr += D; + _weight_desc.input_layer_norm.load(); + _weight_desc.post_attntion_norm.load(); + + // Router weight, stored in the exact order the router reads it, so its + // DMA is one straight 512 KB read (_send_router_weights). model.q4nx holds + // it as [D][E]; the router takes 32-expert x 256-input blocks, expert-block + // major, each block input-major with the 32 experts adjacent. Read in + // place from [D][E] that was 8192 separate 64-byte pieces per call. + // a dense layer has no router; the router core still reads one (zeros) + // and then picks experts 0..15 itself (FIRST_K_DENSE in the model header) + buffer w_gate_inp((size_t)D * num_experts); + if (layer_idx < first_k_dense) { + memset(w_gate_inp.data(), 0, w_gate_inp.size() * sizeof(bf16)); + } + else { + q4nx.load_weights(w_gate_inp, _weight_desc.ffn_gate_inp.format_name(layer_idx)); + } + assert(w_gate_inp.size() == (size_t)D * num_experts); + const int row_block = 32; // router_weight_row_block (experts per block) + const int col_block = 256; // router_weight_col_block (inputs per block) + bf16* dst = w_rms_ptr; + for (int eb = 0; eb < num_experts; eb += row_block) { + for (int db = 0; db < D; db += col_block) { + for (int d = db; d < db + col_block; d++) { + memcpy(dst, w_gate_inp.data() + (size_t)d * num_experts + eb, row_block * sizeof(bf16)); + dst += row_block; + } + } + } + w_rms_ptr += _weight_desc.ffn_gate_inp.get_size() / sizeof(bf16); + assert(dst == w_rms_ptr); + _weight_desc.ffn_gate_inp.load(); + + assert(w_rms_ptr == this->rms_weights_buffer.end()); + } + // router expert bias, fp32; goes to the router CT with RTP writes (see _gen_sequence) + { + this->router_bias = buffer(num_experts); + if (layer_idx < first_k_dense) { + memset(this->router_bias.data(), 0, num_experts * sizeof(float)); + } + else { + buffer bias_bytes; + q4nx.load_weights(bias_bytes, "model.layer." + std::to_string(layer_idx) + ".moe_expert_bias"); + assert(bias_bytes.size() == num_experts * sizeof(float)); + memcpy(this->router_bias.data(), bias_bytes.data(), bias_bytes.size()); + } + } + + if (this->has_qk_norm) + { + LOG_VERBOSE(1, "Loading attention norm weights"); + buffer q_attn_norm; + buffer k_attn_norm; + q4nx.load_weights(q_attn_norm, _weight_desc.attn_q_norm.format_name(layer_idx)); + q4nx.load_weights(k_attn_norm, _weight_desc.attn_k_norm.format_name(layer_idx)); + memcpy(this->rope_rms_buffer.data() + RoPE_DIM, q_attn_norm.data(), DH * sizeof(bf16)); + memcpy(this->rope_rms_buffer.data() + RoPE_DIM + DH, k_attn_norm.data(), DH * sizeof(bf16)); + _weight_desc.attn_q_norm.load(); + _weight_desc.attn_k_norm.load(); + } + + // every proj weight block into the int8-mmul kernel's order (q4_core.h) + if (Q4K_INT8_MMUL) { + q4k_relayout_for_mmul(this->all_proj_weight_buffer.data(), this->all_proj_weight_buffer.size()); + } + + this->_set_rope_weights(0); + this->kv_cache.memset((bf16)0.0f); + + this->all_proj_weight_buffer.sync_to_device(); + this->rms_weights_buffer.sync_to_device(); + this->rope_rms_buffer.sync_to_device(); + this->kv_cache.sync_to_device(); + + bool all_ready = true; + for (weight_desc_t* w : _weight_desc.all()) { + if (!w->ready()) { + header_print("error", "Weight not ready: " << w->name); + all_ready = false; + } + } + if (all_ready) { + LOG_VERBOSE(1, "Weights ready"); + } else { + header_print("error", "Some weights were not ready!"); + } +} + +/// Expert and shared-expert weights, in the order the proj engine and the GLU +/// read them (see models/minicpm5-15b-a2.5b.h). A Q4_K tensor in model.q4nx is +/// row blocks of 32 rows, each row block's 256-column blocks back to back, so +/// "rows a..b" of a tensor is one contiguous byte range. +void decoding_layer::_load_moe_weights(Q4NX& q4nx, int layer_idx) { + constexpr int SHARED_ROWS_PER_ROUND = 256; // UP_GATE_OUTDIM_REORDEER: shared [up 256 | gate 256] per round + constexpr int EXPERT_ROWS_PER_ROUND = 64; // EXP_UP_GATE_OUTDIM_REORDER: expert [up 64 | gate 64] per column per round + const size_t a_block_size = get_quantization_byte_size(QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE, flm_q4k); + u8* w_ptr_begin = this->all_proj_weight_buffer.data(); + + // bytes of `rows` rows of a matrix with `in_dim` columns + auto row_bytes = [&](size_t rows, size_t in_dim) { + return rows / QXNX_ROW_BLOCK_SIZE * (in_dim / QXNX_COL_BLOCK_SIZE) * a_block_size; + }; + // [up rows 0..n | gate rows 0..n | up rows n..2n | gate rows n..2n | ...], n = rows_per_piece + auto interleave_up_gate = [&](buffer& out, const u8* up, const u8* gate, size_t rows, size_t rows_per_piece) { + const size_t piece = row_bytes(rows_per_piece, D); + u8* dst = out.data(); + for (size_t r = 0; r < rows; r += rows_per_piece) { + memcpy(dst, up, piece); dst += piece; up += piece; + memcpy(dst, gate, piece); dst += piece; gate += piece; + } + }; + + // routed experts: one expert = [channel 0 stream | channel 1 stream], expert e + // at e * (its gate/up + down bytes) from the up region's start (the router + // uses the same offsets). Each channel stream is that channel's gate/up blocks + // then its down blocks, in the order the proj cores read them, so the router + // starts one linear BD per channel per expert. + // gate/up rows: the 4 cores of a column take 4 row blocks per round; with + // 64-row pieces cores 0, 1 make up and cores 2, 3 make gate, so one round + // of a column is [up 64 | gate 64] + // down rows: in order + // channels: reorder_cpy(..., 4) puts the 4 blocks of a group next to each + // other; channel 0 feeds cores 0, 1 (the first 2), channel 1 cores 2, 3 + { + LOG_VERBOSE(1, "Loading routed expert weights"); + weight_desc_t& desc_up = _weight_desc.ffn_up_exps; + weight_desc_t& desc_gate = _weight_desc.ffn_gate_exps; + weight_desc_t& desc_down = _weight_desc.ffn_down_exps; + // up, gate, down are one region, re-cut into experts + assert(desc_gate.offset == desc_up.offset + desc_up.get_size()); + assert(desc_down.offset == desc_gate.offset + desc_gate.get_size()); + buffer w_up_exps; + buffer w_gate_exps; + buffer w_down_exps; + const size_t up_per_expert = desc_up.get_size() / num_experts; + const size_t down_per_expert = desc_down.get_size() / num_experts; + int experts = num_experts; + if (layer_idx < first_k_dense) { + // Dense layer: its 8192-wide MLP as 16 experts of 512 (the router picks + // 0..15 with weight 1). Up/gate rows e*512.. are already expert e's bytes; + // down [D, 8192] gives expert e its column blocks 2e, 2e+1 of every row block. + experts = num_activate_experts; + const std::string p = "model.layer." + std::to_string(layer_idx) + ".mlp."; + buffer w_down; + q4nx.load_weights(w_up_exps, p + "up_proj.weight"); + q4nx.load_weights(w_gate_exps, p + "gate_proj.weight"); + q4nx.load_weights(w_down, p + "down_proj.weight"); + assert(w_up_exps.size() == experts * up_per_expert && w_gate_exps.size() == experts * up_per_expert); + assert(w_down.size() == experts * down_per_expert); + const size_t piece = intermediate_size / QXNX_COL_BLOCK_SIZE * a_block_size; // one expert's part of a row block + w_down_exps = buffer(w_down.size()); + u8* dst = w_down_exps.data(); + for (int e = 0; e < experts; e++) { + for (int rb = 0; rb < D / QXNX_ROW_BLOCK_SIZE; rb++) { + memcpy(dst, w_down.data() + ((size_t)rb * experts + e) * piece, piece); + dst += piece; + } + } + } + else { + q4nx.load_weights(w_up_exps, desc_up.format_name(layer_idx)); + q4nx.load_weights(w_gate_exps, desc_gate.format_name(layer_idx)); + q4nx.load_weights(w_down_exps, desc_down.format_name(layer_idx)); + assert(w_up_exps.size() == desc_up.get_size() && w_gate_exps.size() == desc_gate.get_size()); + assert(w_down_exps.size() == desc_down.get_size()); + } + assert(up_per_expert == row_bytes(intermediate_size, D)); + const size_t gate_up_bytes = 2 * up_per_expert; + const size_t expert_bytes = gate_up_bytes + down_per_expert; + const size_t channel_bytes = expert_bytes / 2; + const size_t group = 4 * a_block_size; // the 4 blocks of one group + + // ch0 takes the first 2 blocks of every group of `src`, ch1 the last 2 + auto split_channels = [&](u8*& ch0, u8*& ch1, const u8* src, size_t bytes) { + assert(bytes % group == 0); + for (size_t g = 0; g < bytes; g += group) { + memcpy(ch0, src + g, group / 2); ch0 += group / 2; + memcpy(ch1, src + g + group / 2, group / 2); ch1 += group / 2; + } + }; + + buffer both(gate_up_bytes); + buffer gate_up(gate_up_bytes); + buffer down(down_per_expert); + for (int e = 0; e < experts; e++) { + interleave_up_gate(both, w_up_exps.data() + e * up_per_expert, w_gate_exps.data() + e * up_per_expert, + intermediate_size, EXPERT_ROWS_PER_ROUND); + reorder_cpy(gate_up.data(), both, D, flm_q4k, 4); + buffer w_down_exp(w_down_exps.data() + e * down_per_expert, down_per_expert); + reorder_cpy(down.data(), w_down_exp, intermediate_size, flm_q4k, 4); + + u8* ch0 = w_ptr_begin + desc_up.offset + e * expert_bytes; + u8* ch1 = ch0 + channel_bytes; + split_channels(ch0, ch1, gate_up.data(), gate_up_bytes); + split_channels(ch0, ch1, down.data(), down_per_expert); + assert(ch0 == w_ptr_begin + desc_up.offset + e * expert_bytes + channel_bytes); + } + desc_up.load(); + desc_gate.load(); + desc_down.load(); + } + // shared expert, up/gate: one proj round (16 cores x 32 rows) is [up 256 | gate 256] + { + LOG_VERBOSE(1, "Loading shared up/gate weights"); + weight_desc_t& desc_up = _weight_desc.ffn_up_shexp; + weight_desc_t& desc_gate = _weight_desc.ffn_gate_shexp; + assert(desc_gate.offset == desc_up.offset + desc_up.get_size()); + if (layer_idx < first_k_dense) { + // no shared expert: zero Q4_K blocks (scales 0) add nothing + weight_desc_t& desc_down = _weight_desc.ffn_down_shexp; + assert(desc_down.offset == desc_gate.offset + desc_gate.get_size()); + memset(w_ptr_begin + desc_up.offset, 0, desc_up.get_size() + desc_gate.get_size() + desc_down.get_size()); + desc_up.load(); + desc_gate.load(); + desc_down.load(); + return; + } + buffer w_up_shexp; + buffer w_gate_shexp; + q4nx.load_weights(w_up_shexp, desc_up.format_name(layer_idx)); + q4nx.load_weights(w_gate_shexp, desc_gate.format_name(layer_idx)); + assert(w_up_shexp.size() == desc_up.get_size() && w_gate_shexp.size() == desc_gate.get_size()); + + buffer both(desc_up.get_size() + desc_gate.get_size()); + interleave_up_gate(both, w_up_shexp.data(), w_gate_shexp.data(), intermediate_size, SHARED_ROWS_PER_ROUND); + reorder_cpy(w_ptr_begin + desc_up.offset, both, D, flm_q4k); + desc_up.load(); + desc_gate.load(); + } + // shared expert, down: plain row order + { + LOG_VERBOSE(1, "Loading shared down weights"); + weight_desc_t& desc = _weight_desc.ffn_down_shexp; + buffer w_down_shexp; + q4nx.load_weights(w_down_shexp, desc.format_name(layer_idx)); + assert(w_down_shexp.size() == desc.get_size()); + reorder_cpy(w_ptr_begin + desc.offset, w_down_shexp, intermediate_size, flm_q4k); + desc.load(); + } +} + +buffer decoding_layer::operator()(buffer& input) { + // the KV cache is full: the new token has no row to go to + assert(this->current_context_length < MAX_L); + // MC5_TIME_HOST=1: print where one call's host time goes (microseconds) + static const bool time_host = std::getenv("MC5_TIME_HOST") != nullptr; + using clk = std::chrono::steady_clock; + auto t = [](clk::time_point a, clk::time_point b) { return (long)std::chrono::duration_cast(b - a).count(); }; + clk::time_point t0 = clk::now(); + + // Only what changes per call goes to / comes from the NPU: the layer input and + // the output. The weights and norms were copied once in load_weights(); the + // RoPE table is copied by _set_rope_weights(); the KV cache is written by the + // NPU only (get_k_cache / get_v_cache copy it back when asked). Copying them + // every call cost ~4 ms of host time (weights 2.9 ms, KV 2 x 0.5 ms). + memcpy(this->hidden_states_buffer.data(), input.data(), D * sizeof(bf16)); + if (debug_tap == "x") { + // fill the tap area with a marker (0xFFFF, a bf16 NaN) to count what arrives + const size_t tap_len = 18 * D; // rms x, QKV_REPEATS + GATE_REPEATS sends + memset(this->kv_cache.data() + kv_cache_size - tap_len, 0xFF, tap_len * sizeof(bf16)); + this->kv_cache.sync_to_device(); + } + this->hidden_states_buffer.sync_to_device(); + clk::time_point t1 = clk::now(); + // the call's end state: anything but completed (e.g. a timeout) means the + // output is not this call's result (the host test counts these) + ert_cmd_state state = this->layer_app(hidden_states_buffer, all_proj_weight_buffer, rms_weights_buffer, rope_rms_buffer, kv_cache); + this->last_call_completed = (state == ERT_CMD_STATE_COMPLETED); + clk::time_point t2 = clk::now(); + this->hidden_states_buffer.sync_from_device(); + if (debug_tap == "x") { + this->kv_cache.sync_from_device(); // report_debug_tap reads the tap area + } + clk::time_point t3 = clk::now(); + this->set_context_length(this->current_context_length + 1); + clk::time_point t4 = clk::now(); + if (time_host) { + std::cout << "host us: x in " << t(t0, t1) << ", NPU run (+ setup) " << t(t1, t2) + << ", y out " << t(t2, t3) << ", new sequence " << t(t3, t4) << std::endl; + } + return this->hidden_states_buffer; +} + + +float decoding_layer::bench(buffer& input, int calls, int ctx) { + this->set_context_length(ctx); + memcpy(this->hidden_states_buffer.data(), input.data(), D * sizeof(bf16)); + xrt::runlist rl = this->layer_app_mgr->create_runlist(); + for (int i = 0; i < calls; i++){ + rl.add(this->layer_app.create_run(hidden_states_buffer, all_proj_weight_buffer, rms_weights_buffer, rope_rms_buffer, kv_cache)); + } + time_utils::time_point start = time_utils::now(); + rl.execute(); + rl.wait(); + this->hidden_states_buffer.sync_from_device(); + time_utils::time_point end = time_utils::now(); + time_utils::time_with_unit total_ms = time_utils::duration_ms(start, end); + return total_ms.first / calls; +} + + +void decoding_layer::_set_rope_weights(int idx){ + bf16* w_rope_ptr = this->rope_rms_buffer.data(); + if (rope_weights.size() == 0) { + // normal at load time: the frequencies come later (set_rope_frequency) + LOG_VERBOSE(1, "No RoPE frequencies yet, RoPE table left at 1"); + for (uint32_t i = 0; i < RoPE_DIM / 2; i++){ + w_rope_ptr[i] = bf16(1.0f); + } + return; // no RoPE, no need to set weights + } + for (uint32_t i = 0; i < RoPE_DIM / 2; i++){ + w_rope_ptr[i] = bf16(std::cos(this->rope_weights[i] * idx) * this->rope_scaling); + w_rope_ptr[i + RoPE_DIM / 2] = bf16(std::sin(this->rope_weights[i] * idx) * this->rope_scaling); + } + this->rope_rms_buffer.sync_to_device(); +} + +void decoding_layer::set_rope_frequency(buffer& rope_freqs){ + this->rope_weights = buffer(rope_freqs.size()); + LOG_VERBOSE(1, "RoPE frequencies set, size: " << rope_weights.size()); + memcpy(this->rope_weights.data(), rope_freqs.data(), rope_freqs.size() * sizeof(float)); +} + +void decoding_layer::set_context_length(int L){ + + this->current_context_length = L; + + // A full cache (L == MAX_L tokens) has no next call to prepare: that call + // would write row L, past the cache. operator() refuses to run then. + if (L >= MAX_L) return; + + this->_gen_sequence(this->layer_app.seq(), L + 1); + + this->_set_rope_weights(L); +} + +void decoding_layer::_gen_sequence(npu_sequence* seq, int L) { + constexpr size_t CT_lock_address_base = 0x000001F000; + int proj_rtp_lock_id = 6; + int router_shimtile_configure_ready_lock = 10; // expert BDs written, safe to push expert tasks + assert(L > 0 && L <= MAX_L); + seq->clear_cmds(); + + for (int i = 0; i < attn_cus; i++) { + seq->rtp_write(get_tile(attn_qk_rc[i][0], attn_qk_rc[i][1]), l_qk_address[i], L); + seq->rtp_write(get_tile(attn_kv_rc[i][0], attn_kv_rc[i][1]), l_kv_address[i], L); + } + for (int i = 0; i < 16; i++){ + seq->rtp_write(proj_tiles[i], 17408, 1); + seq->rtp_write(proj_tiles[i], CT_lock_address_base + 16 * proj_rtp_lock_id, 1); // set lock to 1 + } + + // which layer this is: the router picks this layer's saved weight base address + seq->rtp_write(get_tile(router_rc[0], router_rc[1]), router_layer_address, (uint32_t)layer_slot); + + // router expert bias: one RTP write per expert (fp32 bit pattern). The router + // reads it only after its logits, long after these writes; the previous call + // has finished with it (a call ends after the MoE output arrives). + // TODO(MoE step 2): 128 writes per call; a DMA path would be cheaper. + assert(router_bias.size() == (size_t)num_experts); + for (int e = 0; e < num_experts; e++) { + uint32_t bits; + memcpy(&bits, &router_bias[e], sizeof(bits)); + seq->rtp_write(get_tile(router_rc[0], router_rc[1]), router_bias_address + 4 * e, bits); + } + + _send_hidden_states(seq); + _send_rms_weights(seq, 0); + if (debug_stop_after == 11) { seq->cmds2seq(); return; } + _send_rope_rms_weights(seq); + if (debug_stop_after == 12) { seq->cmds2seq(); return; } + + // Router weight first: MT5 holds all of it (512 KB), so IT5 fills it while + // attention runs, and the router + helper start on it as soon as x is there. + _send_router_weights(seq, num_experts, D, _weight_desc.ffn_gate_inp.offset); + + // DEBUG (MC5_DEBUG_TAP=x with a DEBUG_TAP=x build): catch the copy of rms's + // x for the proj engine in the unused tail of the KV buffer. Not waited on. + if (debug_tap == "x") { + const uint32_t rms_len = 18 * D; // rms output, 18 sends (QKV + gate rounds) + const uint32_t base = (uint32_t)(kv_cache_size - rms_len); + seq->npu_dma_memcpy_nd(sizeof(bf16), kv_cache_arg_idx, S2MM, IT4, bd_8, it_channel_0, + {0, 0, 0, base}, {1, 1, 1, rms_len}, {0, 0, 0, 1}, -1, 0, false); + } + + // receive y + seq->npu_dma_memcpy_nd( + sizeof(bf16), + xy_arg_idx, + S2MM, + xyr_tile, + bd_10, + it_channel_1, + {0, 0, 0, 0}, + {1, 1, 1, (uint32_t)D}, + {0, 0, 0, 1}, + -1, 0, true + ); + + // attention + if (attn_tap) { + _receive_attn_tap(seq); + } + // the new K/V row's receive BDs go first, as in the production sequence + _receive_kv_cache(seq, L); + _move_weights_q4k(seq, DK + DV + DQ + DQ, D, _weight_desc.attn_k.offset); // k, v, q, gate + if (debug_stop_after == 1) { seq->cmds2seq(); return; } + if (debug_stop_after == 2) { + for (int i = 0; i < 2 * attn_cols; i++) { + seq->npu_dma_wait(attn_shims[0], S2MM, it_channel_0); + } + seq->cmds2seq(); + return; + } + _move_kv_cache(seq, L); + if (debug_stop_after == 3) { + if (attn_tap) { + seq->npu_dma_wait(attn_shims[0], S2MM, it_channel_1); + } + seq->cmds2seq(); + return; + } + _move_weights_q4k(seq, D, DQ, _weight_desc.attn_output.offset); + if (debug_stop_after == 4) { seq->cmds2seq(); return; } + + // Routed expert weight BDs on shim 0, 1, 6, 7: one linear BD per channel, + // 4 / 5 for round 0 and 12 / 13 for round 1 (SHIM_X_expert_BD_ID in the + // kernels). Written here but not started; the router CT patches in the chosen + // expert's address and starts them with control packets. + for (int i = 0; i < 4; i++) { + setup_expert_q4k(seq, i, 4, _weight_desc.ffn_up_exps.offset); + setup_expert_q4k(seq, i, 12, _weight_desc.ffn_up_exps.offset); + } + + if (debug_stop_after == 45) { seq->cmds2seq(); return; } + + // shared expert up-gate, then down (down's last round pushed but not yet waited for) + _move_weights_q4k(seq, 2 * intermediate_size, D, _weight_desc.ffn_up_shexp.offset); + _move_weights_q4k(seq, D, intermediate_size, _weight_desc.ffn_down_shexp.offset, false); + + // Tell the router the expert BDs are ready. Only now: the router pushes the + // routed-expert weight tasks onto the same shim queues (0, 1, 6, 7) as the + // shared-expert ones above, and a router that got here first queued them + // in front of the last shared-down weights (wrong output from the 2nd call + // on, seen once the router weights were sent early). + // (Setting this earlier and having the router read the BD base address + // while the shared expert streamed hung every call; MoE step 2, T3.) + auto router_CT = get_tile(router_rc[0], router_rc[1]); + seq->npu_maskwrite(router_CT, 0x32038, 0x1, 0x1); + seq->rtp_write(router_CT, CT_lock_address_base + 16 * router_shimtile_configure_ready_lock, 1); // set lock to 1 + _wait_proj_weights(seq); + if (debug_stop_after == 5) { seq->cmds2seq(); return; } + + // wait for receiving y + seq->npu_dma_wait( + xyr_tile, + S2MM, + it_channel_1 + ); + if (attn_tap) { + seq->npu_dma_wait(attn_shims[0], S2MM, it_channel_1); + } + + seq->cmds2seq(); +} + +void decoding_layer::_send_hidden_states(npu_sequence* seq){ + // send x + seq->npu_dma_memcpy_nd( + sizeof(bf16), + xy_arg_idx, + MM2S, + xyr_tile, + bd_0, + it_channel_0, + {0, 0, 0, 0}, + {1, 1, 1, (uint32_t)D}, + {0, 0, 0, 1}, + 0, 0, false, aggressive_cache + ); +} + +void decoding_layer::_send_rms_weights(npu_sequence* seq, size_t byte_offset){ + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_rms_arg_idx, + MM2S, + xyr_tile, + bd_1, + it_channel_1, + {0, 0, 0, byte_offset/sizeof(bf16)}, + {1, 1, 1, (uint32_t)D*2 }, + {0, 0, 0, 1}, + 0, 0, true, aggressive_cache + ); + seq->npu_dma_wait( + xyr_tile, + MM2S, + it_channel_1 + ); +} + +void decoding_layer::_send_rope_rms_weights(npu_sequence* seq){ + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_rope_rms_arg_idx, + MM2S, + xyr_tile, + bd_2, + it_channel_0, + {0, 0, 0, 0}, + {1, 1, 1, (uint32_t)(this->has_qk_norm? (RoPE_DIM + DH * 2): RoPE_DIM)}, + {0, 0, 0, 1}, + 1, 0, true, no_cache + ); + seq->npu_dma_wait( + xyr_tile, + MM2S, + it_channel_0 + ); +} + +void decoding_layer::_receive_kv_cache(npu_sequence* seq, const int L){ + // RoPE sends the new token's K (all KV heads) then V (all KV heads) through + // IT3. Write each column's heads into that column's K / V block, row L - 1: + // BDs 0..3 = K col 0, K col 1, V col 0, V col 1, in stream order. + const uint32_t row_offset = (uint32_t)((L - 1) * kv_col_row); + for (int kv = 0; kv < 2; kv++) { // 0: K, 1: V + for (int col = 0; col < attn_cols; col++) { + uint32_t block_offset = (uint32_t)(kv_block(col, kv) * kv_col_half); + seq->npu_dma_memcpy_nd( + sizeof(bf16), + kv_cache_arg_idx, + S2MM, + attn_shims[0], + npu_bd_id(kv * attn_cols + col), + it_channel_0, + {0, 0, 0, block_offset + row_offset}, + {1, 1, 1, (uint32_t)kv_col_row}, + {0, 0, 0, 1}, + -1, 0, true + ); + } + } +} + +void decoding_layer::_receive_attn_tap(npu_sequence* seq){ + // attention output (before o_proj), from MT3 through IT3 S2MM 1 + seq->npu_dma_memcpy_nd( + sizeof(bf16), + xy_arg_idx, + S2MM, + attn_shims[0], + bd_6, + it_channel_1, + {0, 0, 0, (uint32_t)D}, + {1, 1, 1, (uint32_t)DQ}, + {0, 0, 0, 1}, + -1, 0, true + ); +} + +void decoding_layer::_send_router_weights(npu_sequence* seq, const size_t NUM_expert, const size_t D, const size_t W_offset_in_byte){ + // The host stored the router weight in read order (32-expert x 256-input + // blocks, see load_weights), so each part is one straight read. MT5 holds + // experts 0..127 (channel 0, packets to MT5); experts 128.. do not fit and go + // straight to the router helper (channel 1, circuit flow). + constexpr size_t mt5_experts = 128; // MT_EXPERTS in iron/router_w_memtile.py + assert(NUM_expert > mt5_experts); + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_rms_arg_idx, + MM2S, + IT5, + npu_bd_id(bd_12), + it_channel_0, + {0, 0, 0, (uint32_t)((W_offset_in_byte/2) )}, + {1, 1, 1, (uint32_t)(mt5_experts * D)}, + {0, 0, 0, 1}, + 10, 0, false, aggressive_cache + ); + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_rms_arg_idx, + MM2S, + IT5, + npu_bd_id(bd_13), + it_channel_1, + {0, 0, 0, (uint32_t)(W_offset_in_byte / 2 + mt5_experts * D)}, + {1, 1, 1, (uint32_t)((NUM_expert - mt5_experts) * D)}, + {0, 0, 0, 1}, + -1, 0, false, aggressive_cache + ); +} + + +/// One routed expert's weight BDs on proj shim `col` (0-3): channel 0 gets BD +/// bd_id, channel 1 BD bd_id + 1, each one linear read of half an expert (see +/// _load_moe_weights). Points at expert 0; the router patches in the chosen +/// expert's address and pushes the BDs onto the queues. +void decoding_layer::setup_expert_q4k(npu_sequence* seq, int col, int bd_id, size_t const_w_byte_offset){ + const uint32_t a_block_size = get_quantization_byte_size(QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE, flm_q4k); + const size_t gate_up_bytes = 2 * (size_t)(intermediate_size / QXNX_ROW_BLOCK_SIZE) * (D / QXNX_COL_BLOCK_SIZE) * a_block_size; + const size_t down_bytes = (size_t)(D / QXNX_ROW_BLOCK_SIZE) * (intermediate_size / QXNX_COL_BLOCK_SIZE) * a_block_size; + const uint32_t channel_bytes = (uint32_t)((gate_up_bytes + down_bytes) / 2); + //TODO: sync with the kernel through share hpp + constexpr uint32_t SHIM_6_CONTROL_RES_PKT = 30; + for (int ch = 0; ch < 2; ch++) { + seq->npu_dma_memcpy_nd( + sizeof(uint8_t), + w_proj_arg_idx, + MM2S, + mvm_tiles[col], + npu_bd_id(bd_id + ch), + ch == 0 ? it_channel_0 : it_channel_1, + {0, 0, 0, (uint32_t)(const_w_byte_offset + (size_t)ch * channel_bytes)}, + {1, 1, 1, channel_bytes}, + {0, 0, 0, 1}, + -1, 0, false, + aggressive_cache, + SHIM_6_CONTROL_RES_PKT, false + ); + } +} + +void decoding_layer::_move_weights_q4k(npu_sequence* seq, const size_t Dout, const size_t Din, const size_t w_offset, bool wait_last_round){ + const int m = 32; + const int k = 256; + const uint32_t columns = 4; + const uint32_t elems = m * k; + const uint32_t a_block_size = elems*37 / 64 / sizeof(bf16); + const uint32_t blocks_per_row = Din / k; + const uint32_t cores = columns * 4; + assert(Dout / m / cores > 0); + assert(Dout % (m * cores) == 0); + for (size_t round = 0; round < Dout / m / cores; round++){ + uint32_t bd_offset = (round % 2) * 8; + for (uint32_t col = 0; col < columns; col++){ + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_proj_arg_idx, + MM2S, + mvm_tiles[col], + npu_bd_id(bd_1 + bd_offset), + it_channel_0, + {0, 0, 0, (uint32_t)((round * cores + col * 4) * a_block_size * blocks_per_row + (uint32_t)w_offset / sizeof(bf16))}, + {1, 1, 1, 2 * blocks_per_row * a_block_size}, + {0, 0, 0, 1}, + -1, 0, true, aggressive_cache + ); + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_proj_arg_idx, + MM2S, + mvm_tiles[col], + npu_bd_id(bd_2 + bd_offset), + it_channel_1, + {0, 0, 0, (uint32_t)((round * cores + col * 4 + 2) * a_block_size * blocks_per_row + (uint32_t)w_offset / sizeof(bf16))}, + {1, 1, 1, 2 * blocks_per_row * a_block_size}, + {0, 0, 0, 1}, + -1, 0, true, aggressive_cache + ); + } + if (round > 0){ + _wait_proj_weights(seq); + } + } + if (wait_last_round) { + _wait_proj_weights(seq); + } +} + +/// Wait for one weight task on both channels of each proj shim (0, 1, 6, 7). +void decoding_layer::_wait_proj_weights(npu_sequence* seq){ + for (uint32_t col = 0; col < 4; col++){ + seq->npu_dma_wait(mvm_tiles[col], MM2S, it_channel_0); + seq->npu_dma_wait(mvm_tiles[col], MM2S, it_channel_1); + } +} + + +void decoding_layer::_move_weights_q80(npu_sequence* seq, const size_t Dout, const size_t Din, const size_t w_offset){ + const int m = 32; + const int k = 256; + const uint32_t columns = 4; + const uint32_t a_block_size = 8704 / sizeof(bf16); + const uint32_t blocks_per_row = Din / k; + const uint32_t cores = columns * 4; + assert(Dout / m / cores > 0); + assert(Dout % (m * cores) == 0); + for (size_t round = 0; round < Dout / m / cores; round++){ + uint32_t bd_offset = (round % 2) * 8; + for (uint32_t col = 0; col < columns; col++){ + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_proj_arg_idx, + MM2S, + mvm_tiles[col], + npu_bd_id(bd_1 + bd_offset), + it_channel_0, + {0, 0, 0, (uint32_t)((round * cores + col * 4) * a_block_size * blocks_per_row + (uint32_t)w_offset / sizeof(bf16))}, + {1, 1, 1, 2 * blocks_per_row * a_block_size}, + {0, 0, 0, 1}, + -1, 0, true, aggressive_cache + ); + seq->npu_dma_memcpy_nd( + sizeof(bf16), + w_proj_arg_idx, + MM2S, + mvm_tiles[col], + npu_bd_id(bd_2 + bd_offset), + it_channel_1, + {0, 0, 0, (uint32_t)((round * cores + col * 4 + 2) * a_block_size * blocks_per_row + (uint32_t)w_offset / sizeof(bf16))}, + {1, 1, 1, 2 * blocks_per_row * a_block_size}, + {0, 0, 0, 1}, + -1, 0, true, aggressive_cache + ); + } + if (round > 0){ + for (uint32_t col = 0; col < columns; col++){ + seq->npu_dma_wait( + mvm_tiles[col], + MM2S, + it_channel_0 + ); + seq->npu_dma_wait( + mvm_tiles[col], + MM2S, + it_channel_1 + ); + } + } + } + for (uint32_t col = 0; col < columns; col++){ + seq->npu_dma_wait( + mvm_tiles[col], + MM2S, + it_channel_0 + ); + seq->npu_dma_wait( + mvm_tiles[col], + MM2S, + it_channel_1 + ); + } +} +void decoding_layer::_move_kv_cache(npu_sequence* seq, const size_t L){ + // Each column's shim reads its own K block (channel 0) and V block + // (channel 1). K reads start once both K writes of the new row are done, + // V reads once both V writes are. + const int L_padded = (L + L_CHUNK - 1) / L_CHUNK * L_CHUNK; + assert(L_padded <= MAX_L); + const uint32_t data2move = (uint32_t)(L_padded * kv_col_row); + const npu_bd_id read_bd[2][attn_cols] = {{bd_4, bd_0}, {bd_5, bd_1}}; // IT3 uses BDs 0..3 to write + + for (int kv = 0; kv < 2; kv++) { // 0: K, 1: V + for (int col = 0; col < attn_cols; col++) { + seq->npu_dma_wait(attn_shims[0], S2MM, it_channel_0); + } + for (int col = 0; col < attn_cols; col++) { + seq->npu_dma_memcpy_nd( + sizeof(bf16), + kv_cache_arg_idx, + MM2S, + attn_shims[col], + read_bd[kv][col], + kv == 0 ? it_channel_0 : it_channel_1, + {0, 0, 0, (uint32_t)(kv_block(col, kv) * kv_col_half)}, + {1, 1, 1, data2move}, + {0, 0, 0, 1}, + -1, 0, false, aggressive_cache + ); + } + } +} + +// K (or V) of token idx, all KV heads in head order +static buffer gather_kv_row(buffer& kv_cache, int kv, int idx, int cols, size_t col_row, size_t col_half) { + buffer row(cols * col_row); + for (int col = 0; col < cols; col++) { + const bf16* src = kv_cache.data() + decoding_layer::kv_block(col, kv) * col_half + idx * col_row; + memcpy(row.data() + col * col_row, src, col_row * sizeof(bf16)); + } + return row; +} + +void decoding_layer::fill_kv(const bf16* k_rows, const bf16* v_rows, int src_rows, int n_rows){ + assert(n_rows <= MAX_L); + const size_t row = (size_t)num_kv_heads * DH; // one source row: all KV heads + for (int j = 0; j < n_rows; j++) { + const size_t src = (size_t)(j % src_rows) * row; + // a column holds its own KV heads: values [col * kv_col_row, (col + 1) * kv_col_row) of a row + for (int col = 0; col < attn_cols; col++) { + bf16* k_dst = kv_cache.data() + kv_block(col, 0) * kv_col_half + (size_t)j * kv_col_row; + bf16* v_dst = kv_cache.data() + kv_block(col, 1) * kv_col_half + (size_t)j * kv_col_row; + memcpy(k_dst, k_rows + src + col * kv_col_row, kv_col_row * sizeof(bf16)); + memcpy(v_dst, v_rows + src + col * kv_col_row, kv_col_row * sizeof(bf16)); + } + } + // operator() does not sync the cache (only the NPU touches it), so push it here + kv_cache.sync_to_device(); +} + +buffer decoding_layer::get_k_cache(int idx){ + this->kv_cache.sync_from_device(); + return gather_kv_row(this->kv_cache, 0, idx, attn_cols, kv_col_row, kv_col_half); +} + +buffer decoding_layer::get_v_cache(int idx){ + this->kv_cache.sync_from_device(); + return gather_kv_row(this->kv_cache, 1, idx, attn_cols, kv_col_row, kv_col_half); +} + +buffer decoding_layer::get_attn_tap(){ + assert(attn_tap); + buffer tap(DQ); + memcpy(tap.data(), this->hidden_states_buffer.data() + D, DQ * sizeof(bf16)); + return tap; +} + +void decoding_layer::report_debug_tap(){ + if (debug_stop_after != 0) { + // did RoPE's new K/V row reach the cache? (proves QKV was computed) + buffer k = get_k_cache(current_context_length - 1); + buffer v = get_v_cache(current_context_length - 1); + size_t k_nz = 0, v_nz = 0; + for (size_t i = 0; i < k.size(); i++) k_nz += (float)k[i] != 0.0f; + for (size_t i = 0; i < v.size(); i++) v_nz += (float)v[i] != 0.0f; + header_print("debug", "new K/V row: " << k_nz << " / " << k.size() << " K values and " + << v_nz << " / " << v.size() << " V values non-zero"); + } + if (debug_tap != "x") return; + const size_t rms_len = 18 * D; + const uint16_t* base = reinterpret_cast(this->kv_cache.data() + kv_cache_size - rms_len); + auto arrived = [](const uint16_t* p, size_t n) { + size_t count = 0; + for (size_t i = 0; i < n; i++) count += (p[i] != 0xFFFF); + return count; + }; + header_print("debug", "x tap: rms output " << arrived(base, rms_len) << " / " << rms_len); +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/decoding_layer.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/decoding_layer.hpp new file mode 100644 index 000000000..908054657 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/decoding_layer.hpp @@ -0,0 +1,200 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __DECODING_LAYER_HPP__ +#define __DECODING_LAYER_HPP__ + +#include "models.h" +#include "lm_config.hpp" +#include "npu_utils/npu_utils.hpp" +#include "tensor_utils/q4_npu_eXpress.hpp" +#include "utils/utils.hpp" +#include "tensor_2d.hpp" +#include "weight_desc.hpp" + + +struct moe_attn_layer_weights{ +public: + weight_desc_t attn_k; + weight_desc_t attn_k_norm; + weight_desc_t input_layer_norm; + weight_desc_t attn_q; + weight_desc_t attn_gate; // sigmoid output gate on the attention output + weight_desc_t attn_q_norm; + weight_desc_t attn_v; + weight_desc_t ffn_down_exps; + weight_desc_t ffn_down_shexp; + weight_desc_t ffn_gate_exps; + weight_desc_t ffn_gate_shexp; + weight_desc_t ffn_up_exps; + weight_desc_t ffn_up_shexp; + weight_desc_t ffn_gate_inp; + weight_desc_t post_attntion_norm; + weight_desc_t attn_output; + + std::vector all() { + return { + &attn_k, &attn_k_norm, &input_layer_norm, &attn_q, &attn_gate, &attn_q_norm, + &attn_v, &ffn_down_exps, &ffn_down_shexp, &ffn_gate_exps, + &ffn_gate_shexp, &ffn_up_exps, &ffn_up_shexp, &ffn_gate_inp, + &post_attntion_norm, &attn_output, + }; + } +}; + +class decoding_layer { +public: + model_list::model_t model_type; + LM_Config& lm_config; + npu_app_manager* layer_app_mgr; + + npu_app layer_app; + + buffer rope_weights; + float rope_scaling; + + int xy_arg_idx = 0; + int w_proj_arg_idx = 1; + int w_rms_arg_idx = 2; + int w_rope_rms_arg_idx = 3; + int kv_cache_arg_idx = 4; + + buffer hidden_states_buffer; + buffer all_proj_weight_buffer; + buffer rms_weights_buffer; + buffer rope_rms_buffer; + buffer kv_cache; + + int current_context_length; + int num_hidden_layers; + moe_attn_layer_weights _weight_desc; + weight_container proj_weights_helper; + weight_container norm_exp_helper; + + void _gen_sequence(npu_sequence* seq, int L); + void _set_rope_weights(int); + + void _send_hidden_states(npu_sequence* seq); + void _send_rms_weights(npu_sequence* seq, size_t byte_offset); + void _send_rope_rms_weights(npu_sequence* seq); + void _receive_kv_cache(npu_sequence* seq, const int L); + void _move_kv_cache(npu_sequence* seq, const size_t L); + void _receive_attn_tap(npu_sequence* seq); + void _read_rtp_addresses(const std::string& xclbin_path); + void _move_weights_q80(npu_sequence* seq, const size_t Dout, const size_t Din, const size_t w_offset); + // wait_last_round = false: the last round's tasks are pushed but not waited for (see _gen_sequence) + void _move_weights_q4k(npu_sequence* seq, const size_t Dout, const size_t Din, const size_t w_offset, bool wait_last_round = true); + void _wait_proj_weights(npu_sequence* seq); + void _send_router_weights(npu_sequence* seq, const size_t NUM_expert, const size_t D, const size_t W_offset_in_byte); + + void setup_expert_q4k(npu_sequence* seq, int col, int bd_id, size_t const_w_byte_offset); + // model specific config + int DH; + int D; + int DQ; + int DK; + int DV; + int RoPE_DIM; + int num_kv_heads; // the kernels' KV heads (one per attention CU) + int model_kv_heads; // the model's; load_weights duplicates them up to num_kv_heads + bool has_qk_norm; + int intermediate_size; + int MAX_L; + int num_experts; + int num_activate_experts; + int first_k_dense; // layers 0 .. first_k_dense - 1 are dense, run as experts 0..15 (see _load_moe_weights) + bool attn_tap; + bool last_call_completed = false; // the last operator() call ended in COMPLETED + int debug_stop_after; // MC5_STOP_AFTER, see _gen_sequence + std::string debug_tap; // MC5_DEBUG_TAP, needs a DEBUG_TAP build, see _gen_sequence + + // KV cache layout: 4 blocks of MAX_L x (kv heads of the column * DH), + // [K col 0][K col 1][V col 0][V col 1] + // i.e. all K, then all V at kv_cache_size / 2 (as FLM_DLL's hunyuan_npu and + // qwen3_6_moe_npu); col 0 = heads 0, 1, col 1 = heads 2, 3, so every column + // reads its K and V with one linear DMA. ../dense_decoding uses the same layout. + // MAX_L 131072 (128K) = 256 MB per layer, one buffer per layer: DMA offsets + // are 32-bit byte offsets, so one buffer for all 48 layers would overflow. + size_t kv_cache_size; + /// \brief index of a column's K (kv = 0) or V (kv = 1) block + static constexpr int kv_block(int col, int kv) { return 2 * kv + col; } + int kv_heads_per_col; + size_t kv_col_row; // elements per token per column, K or V + size_t kv_col_half; // elements of one K (or V) block of a column + + // npu configs + + static constexpr npu_tiles xyr_tile = IT2; + static constexpr npu_tiles mvm_tiles[4] = {IT0, IT1, IT6, IT7}; + + // attention: 2 columns x 2 CUs; CU i holds KV head i. + // AIE (row, col) of the qk and kv tile of each CU, and its column's shim. + static constexpr int attn_cus = 4; + static constexpr int attn_cols = 2; + static constexpr int attn_qk_rc[attn_cus][2] = {{2, 3}, {4, 3}, {2, 4}, {4, 4}}; + static constexpr int attn_kv_rc[attn_cus][2] = {{3, 3}, {5, 3}, {3, 4}, {5, 4}}; + static constexpr npu_tiles attn_shims[attn_cols] = {IT3, IT4}; + // RTP address of the context length in each qk / kv tile, from rtp_addresses.txt + uint32_t l_qk_address[attn_cus]; + uint32_t l_kv_address[attn_cus]; + + // router CT (row 4, col 5) and its fp32 expert bias, written with RTP writes each call + static constexpr int router_rc[2] = {4, 5}; + uint32_t router_bias_address; + uint32_t router_layer_address; // RTP_router_layer: which layer a call is + int layer_slot = 0; // this object's layer (set by load_weights) + buffer router_bias; + + static constexpr npu_tiles proj_tiles[] = {CT00, CT10, CT20, CT30, + CT01, CT11, CT21, CT31, + CT06, CT16, CT26, CT36, + CT07, CT17, CT27, CT37 + }; + int L_CHUNK = 16; + +public: + /// \brief constructor + /// \param model_type the model type + /// \param lm_config the lm config + /// \param xclbin_mgr the xclbin manager + /// \param context_length the context length + decoding_layer(model_list::model_t, LM_Config&, npu_app_manager*, int context_length, bool attn_tap); + + /// \brief load weights + /// \param q4nx_model the q4nx model + void load_weights(Q4NX&, int layer_idx); + void _load_moe_weights(Q4NX&, int layer_idx); + + /// \brief operator() + /// \param input the hidden states + /// \return the output buffer + buffer operator()(buffer&); + + + void reorder_cpy(u8 *dst, buffer &src, const int col, flm_dtype_t dtype, const int vertical_blocks = 2); + void q4k_relayout_for_mmul(u8* data, size_t bytes); + float bench(buffer&, int calls, int ctx = 8); + + + /// \brief set context length + /// \param length the context length + void set_context_length(int length); + + buffer get_k_cache(int idx); + buffer get_v_cache(int idx); + + /// \brief long-context test: KV rows 0..n_rows-1 = row (j % src_rows) of + /// k_rows / v_rows ([src_rows, KV heads * DH], K after RoPE) + void fill_kv(const bf16* k_rows, const bf16* v_rows, int src_rows, int n_rows); + + /// \brief attention output (before o_proj) of the last call; needs an ATTN_TAP=1 build + buffer get_attn_tap(); + + /// \brief DEBUG: how many values reached each MC5_DEBUG_TAP=x tap in the last call + void report_debug_tap(); + + void set_rope_frequency(buffer& freqs); +}; + + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/host.cpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/host.cpp new file mode 100644 index 000000000..67d6b9d78 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/host.cpp @@ -0,0 +1,363 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "typedef.hpp" +#include "buffer.hpp" +#include "decoding_layer.hpp" +#include "npu_utils/npu_utils.hpp" +#include "tensor_utils/q4_npu_eXpress.hpp" +#include "utils/debug_utils.hpp" +#include "utils/vm_args.hpp" +#include "utils/utils.hpp" +#include "models.h" +#include "metrices.hpp" +#include "tensor_2d.hpp" +#include "lm_config.hpp" + +#include +#include +#include +#include +#include +#include + +// One decoded token compared with one reference row. +struct check_t { + std::string name; // what is compared, e.g. "residual" + std::string ref_key; // tensor in the reference file + int width; // elements per token + buffer ref_bf16; // reference with the original bf16 weights + buffer ref_q4k; // reference with the q4nx Q4_K weights (may be empty) + std::vector vs_bf16; + std::vector vs_q4k; +}; + +// LM_Config::from_pretrained wants an FLM config.json (it asserts addr_qk / +// addr_kv). Hy's folder has the HF config.json, and the RTP addresses come from +// the build's rtp_addresses.txt, so fill in only the fields this test uses. +static LM_Config load_hf_config(const std::string& dir) { + std::ifstream file(dir + "/config.json"); + if (!file.is_open()) { + header_print("error", "Cannot open " << dir << "/config.json"); + exit(1); + } + LM_Config cfg; + cfg.model_path = dir; + cfg.model_name = dir; + cfg._json_config = nlohmann::json::parse(file); + JSON_GET(cfg.model_type, cfg._json_config, "model_type", "", std::string); + JSON_GET(cfg.head_dim, cfg._json_config, "head_dim", 0, u32); + JSON_GET(cfg.hidden_size, cfg._json_config, "hidden_size", 0, u32); + JSON_GET(cfg.num_attention_heads, cfg._json_config, "num_attention_heads", 0, u32); + JSON_GET(cfg.num_key_value_heads, cfg._json_config, "num_key_value_heads", 0, u32); + JSON_GET(cfg.num_hidden_layers, cfg._json_config, "num_hidden_layers", 0, u32); + assert(cfg.head_dim > 0 && cfg.hidden_size > 0 && cfg.num_attention_heads > 0); + assert(cfg.num_key_value_heads > 0 && cfg.num_hidden_layers > 0); + return cfg; +} + +// One comparison (e.g. output vs the Q4_K reference) over all tokens. +struct summary_t { + float mean_cos = 0.0f, min_cos = 1.0f, max_l2 = 0.0f; + int min_token = 0; // the token with the lowest cos + int below = 0; // tokens with cos < LOW_COS +}; +constexpr float LOW_COS = 0.999f; + +static summary_t summarize(const std::vector& m) { + summary_t r; + for (size_t i = 0; i < m.size(); i++) { + r.mean_cos += m[i].CosineSimilarity / m.size(); + r.max_l2 = std::max(r.max_l2, m[i].RelativeL2); + if (m[i].CosineSimilarity < r.min_cos) { + r.min_cos = m[i].CosineSimilarity; + r.min_token = (int)i; + } + r.below += m[i].CosineSimilarity < LOW_COS; + } + return r; +} + +// " output vs Q4_K ref: mean cos 0.999803 min 0.999147 (token 69) max rel L2 0.0413 [0 tokens < 0.999]" +static void print_summary_line(const std::string& name, const char* against, const std::vector& m) { + if (m.empty()) return; + const summary_t r = summarize(m); + std::cout << " " << std::left << std::setw(16) << name << " vs " << std::setw(4) << against << " ref: " + << std::right << std::fixed << std::setprecision(6) << "mean cos " << r.mean_cos + << " min " << r.min_cos << " (token " << r.min_token << ")" + << " max rel L2 " << std::setprecision(4) << r.max_l2 + << " [" << r.below << " tokens < " << std::setprecision(3) << LOW_COS << "]" << std::endl; +} + +int main(int argc, char** argv) { + arg_utils::po::options_description desc("Allowed options"); + arg_utils::po::variables_map vm; + arg_utils::add_default_options(desc); + desc.add_options()("model,m", arg_utils::po::value()->default_value("MINICPM5_15B_A2_5B"), "Model type"); + desc.add_options()("len,l", arg_utils::po::value()->default_value(100), "Number of tokens to decode"); + desc.add_options()("layer,L", arg_utils::po::value()->default_value(1), "Layer to test (a sparse layer, 1..27)"); + desc.add_options()("ctx", arg_utils::po::value()->default_value(131072), "KV cache length (a multiple of 16; 131072 = 128K)"); + desc.add_options()("attn_tap", arg_utils::po::bool_switch()->default_value(false), "Also check the attention output; needs an ATTN_TAP=1 build"); + desc.add_options()("xclbin", arg_utils::po::value()->default_value(""), "Use this layer.xclbin instead of the default build (e.g. a DEBUG_TAP build)"); + desc.add_options()("bench", arg_utils::po::value()->default_value(0), "After the check, time the NPU only: this many rounds of 480 back-to-back calls"); + desc.add_options()("bench_ctx", arg_utils::po::value()->default_value(8), "Context length for --bench (must be below --ctx)"); + desc.add_options()("per_step", arg_utils::po::bool_switch()->default_value(false), "Also print every token's cos / rel L2"); + desc.add_options()("alt_layer", arg_utils::po::value()->default_value(-1), "Also run this layer, taking turns with -L on the same NPU context (each has its own weight buffer)"); + desc.add_options()("kv_fill", arg_utils::po::value()->default_value(0), "Long-context check: fill KV rows 0..N-1 with the Q4_K reference's K/V rows (repeated) and decode at positions N..; no reference checks, use --dump and recompute the layer offline"); + desc.add_options()("dump", arg_utils::po::value()->default_value(""), "Write the layer outputs and the new K/V rows to .out.bin / .k.bin / .v.bin (raw bf16)"); + + const char* env_ref = std::getenv("FLM_REFERENCE_DIR"); + desc.add_options()("ref_dir", arg_utils::po::value()->default_value(env_ref ? env_ref : ""), "Directory with minicpm5_reference.safetensors and minicpm5_layer_q4k_layer_.safetensors (default: $FLM_REFERENCE_DIR; not shipped)"); + + arg_utils::parse_options(argc, argv, desc, vm); + + const std::string ref_dir = vm["ref_dir"].as(); + if (ref_dir.empty()) { + header_print("error", "No reference directory: pass --ref_dir or set FLM_REFERENCE_DIR (references are not shipped with the dev kit)"); + return 1; + } + + std::string model_type = vm["model"].as(); + int max_len = vm["len"].as(); + int layer_idx = vm["layer"].as(); + int context_length = vm["ctx"].as(); + bool attn_tap = vm["attn_tap"].as(); + + model_list::model_t model = model_list::get_model_type(model_type); + LM_Config lm_config = load_hf_config(model_list::get_config_path(model)); + int D = lm_config.hidden_size; + int DQ = lm_config.num_attention_heads * lm_config.head_dim; + int DH = lm_config.head_dim; + + lm_config.layer_xclbin_name = vm["xclbin"].as().empty() + ? model_list::get_layer_xclbin_path(model, attn_tap) : vm["xclbin"].as(); + + std::unique_ptr q4nx_model = std::make_unique(model_list::get_q4nx_path(model)); + + // ---- references ---- + std::string reference_path = model_list::get_reference_path(model, ref_dir); + std::unique_ptr references = std::make_unique(reference_path); + + // sanity check: embedding lookup from model.q4nx vs the reference embeddings + buffer ids; + references->load_weights(ids, "input.input_ids"); + buffer ref_embed; + references->load_weights(ref_embed, "embeddings"); + float embed_cos = 0.0f; // model.q4nx embeddings vs the reference's: should be 1 + { + buffer embed; + q4nx_model->load_weights(embed, "model.embed_tokens.weight"); + buffer embeddings(ref_embed.size()); + for (size_t i = 0; i < ids.size(); i++) { + memcpy(embeddings.data() + i * D, embed.data() + (size_t)ids[i] * D, D * sizeof(bf16)); + } + embed_cos = get_error_metrics(embeddings, ref_embed).CosineSimilarity; + } + + // ---- NPU ---- + xrt::device npu_inst = xrt::device(0); + npu_xclbin_manager xclbin_mgr(npu_device::device_npu2, &npu_inst, false); + npu_app_manager* layer_app_mgr = xclbin_mgr.register_xclbin(lm_config.layer_xclbin_name); + + // RoPE frequencies in fp32, as transformers does: theta^(-2i / DH). + // (The reference file stores inv_freq as bf16, which is too coarse: + // ~0.4 rad of angle error by token 100.) + const double theta = model_list::get_rope_theta(model); + const int rope_dim = int(DH * model_list::get_rope_partial_factor(model)); + buffer rope_freqs(rope_dim / 2); + for (int i = 0; i < rope_dim / 2; i++) { + rope_freqs[i] = (float)(1.0 / std::pow(theta, (2.0 * i) / rope_dim)); + } + + // One tested layer: its decoding_layer (own weight buffer and KV cache, same + // NPU context as the others), its reference input / outputs, and its results. + struct layer_run { + int idx; + std::unique_ptr layer; + buffer input_ref; + std::vector checks; + int completed = 0; // calls that ended in COMPLETED (a timeout leaves the last output in place) + float total_ms = 0.0f; + }; + const uint32_t steps = std::min(max_len, ids.size()); + const int kv_fill = vm["kv_fill"].as(); + const std::string dump_prefix = vm["dump"].as(); + if ((kv_fill > 0 || !dump_prefix.empty()) && vm["alt_layer"].as() >= 0) { + header_print("error", "--kv_fill / --dump test one layer: drop --alt_layer"); + return 1; + } + if (kv_fill > 0 && kv_fill + (int)steps > context_length) { + header_print("error", "--kv_fill " << kv_fill << " + " << steps << " tokens is more than --ctx " << context_length); + return 1; + } + std::vector layer_ids = {layer_idx}; + if (vm["alt_layer"].as() >= 0) { + layer_ids.push_back(vm["alt_layer"].as()); + } + std::vector runs(layer_ids.size()); + for (size_t r = 0; r < runs.size(); r++) { + layer_run& run = runs[r]; + run.idx = layer_ids[r]; + const std::string layer_prefix = "layer_" + std::to_string(run.idx) + "."; + references->load_weights(run.input_ref, layer_prefix + "input"); + + std::string q4k_reference_path = model_list::get_q4k_reference_path(model, run.idx, ref_dir); + std::unique_ptr q4k_references; + if (std::filesystem::exists(q4k_reference_path)) { + q4k_references = std::make_unique(q4k_reference_path); + } + else { + header_print("warning", "No Q4_K reference at " << q4k_reference_path + << " (generate it with the Q4_K layer reference script); comparing with the bf16 one only"); + } + // layer output = residual + shared expert + routed experts + run.checks.push_back({"output (layer output)", "output", D}); + if (attn_tap) { + run.checks.push_back({"attention_out (before o_proj)", "attention_out", DQ}); + } + for (auto& c : run.checks) { + references->load_weights(c.ref_bf16, layer_prefix + c.ref_key); + if (q4k_references) { + q4k_references->load_weights(c.ref_q4k, c.ref_key); + } + } + + run.layer = std::make_unique(model, lm_config, layer_app_mgr, context_length, attn_tap); + run.layer->load_weights(*q4nx_model, run.idx); + run.layer->set_rope_frequency(rope_freqs); + run.layer->set_context_length(0); + + // Long-context check (--kv_fill N): the first N cache rows hold the Q4_K + // reference's K/V rows, repeated, and the tokens decode at positions N.. . + // The reference rows assume positions 0.., so there is nothing to check here; + // An offline reference recomputes the layer from --dump. + if (kv_fill > 0) { + if (!q4k_references) { + header_print("error", "--kv_fill needs the Q4_K reference " << q4k_reference_path); + return 1; + } + const int DH = lm_config.head_dim; + const int model_heads = lm_config.num_key_value_heads; + const int dup = run.layer->num_kv_heads / model_heads; + buffer k_rows, v_rows; + q4k_references->load_weights(k_rows, "k_rope"); + q4k_references->load_weights(v_rows, "v_proj"); + // the reference has the model's KV heads, the cache each one dup times + const size_t rows = k_rows.size() / ((size_t)model_heads * DH); + auto dup_heads = [&](const buffer& src) { + buffer out(rows * run.layer->num_kv_heads * DH); + for (size_t r = 0; r < rows; r++) + for (int h = 0; h < run.layer->num_kv_heads; h++) + memcpy(out.data() + (r * run.layer->num_kv_heads + h) * DH, + src.data() + (r * model_heads + h / dup) * DH, DH * sizeof(bf16)); + return out; + }; + buffer k4 = dup_heads(k_rows); + buffer v4 = dup_heads(v_rows); + run.layer->fill_kv(k4.data(), v4.data(), (int)rows, kv_fill); + run.layer->set_context_length(kv_fill); + run.checks.clear(); + header_print("info", "KV rows 0.." << kv_fill - 1 << " filled with the Q4_K reference's K/V rows (repeated)"); + } + } + + // ---- decode ---- + // Decode token i of a layer equals row i of the prefill reference (causal + // attention), so feed the reference layer input row by row and compare. + // With --alt_layer the layers take turns, token by token. + // --dump: the outputs and the new K/V rows, for an offline long-context check + std::ofstream dump_out, dump_k, dump_v; + if (!dump_prefix.empty()) { + dump_out.open(dump_prefix + ".out.bin", std::ios::binary | std::ios::trunc); + dump_k.open(dump_prefix + ".k.bin", std::ios::binary | std::ios::trunc); + dump_v.open(dump_prefix + ".v.bin", std::ios::binary | std::ios::trunc); + } + std::string which = std::to_string(layer_ids[0]); + if (layer_ids.size() > 1) which += " and " + std::to_string(layer_ids[1]) + " (taking turns)"; + header_print("info", "Running layer " << which << " for " << steps << " tokens (" + << lm_config.layer_xclbin_name << ", KV cache " << context_length << ")"); + buffer token_in(D); + for (uint32_t i = 0; i < steps; i++) { + for (layer_run& run : runs) { + decoding_layer& layer = *run.layer; + memcpy(token_in.data(), run.input_ref.data() + (size_t)i * D, D * sizeof(bf16)); + time_utils::time_point start = time_utils::now(); + buffer out = layer(token_in); + run.completed += layer.last_call_completed; + layer.report_debug_tap(); + time_utils::time_point end = time_utils::now(); + // in microseconds: duration_ms counts whole milliseconds, too coarse for ~1-2 ms calls + run.total_ms += std::chrono::duration_cast(end - start).count() / 1000.0f; + if (dump_out.is_open()) { + buffer k_row = layer.get_k_cache(kv_fill + i); + buffer v_row = layer.get_v_cache(kv_fill + i); + dump_out.write(reinterpret_cast(out.data()), D * sizeof(bf16)); + dump_k.write(reinterpret_cast(k_row.data()), k_row.size() * sizeof(bf16)); + dump_v.write(reinterpret_cast(v_row.data()), v_row.size() * sizeof(bf16)); + } + + for (auto& c : run.checks) { + buffer got(c.width); + if (c.ref_key == "attention_out") { + got = layer.get_attn_tap(); + } + else { + memcpy(got.data(), out.data(), D * sizeof(bf16)); + } + buffer ref_row(c.ref_bf16.data() + (size_t)i * c.width, c.width); + c.vs_bf16.push_back(get_error_metrics(got, ref_row)); + if (c.ref_q4k.size() > 0) { + buffer q4k_row(c.ref_q4k.data() + (size_t)i * c.width, c.width); + c.vs_q4k.push_back(get_error_metrics(got, q4k_row)); + } + } + } + } + + // ---- result, one block per layer ---- + bool all_completed = true; + for (const layer_run& run : runs) { + // per-token table, only on request (--per_step) + if (vm["per_step"].as() && !run.checks.empty()) { + for (uint32_t i = 0; i < steps; i++) { + std::cout << "\tLayer " << run.idx << " step " << i; + for (const auto& c : run.checks) { + const error_metrics& e = c.vs_q4k.empty() ? c.vs_bf16[i] : c.vs_q4k[i]; + std::cout << " " << c.ref_key << " cos " << std::fixed << std::setprecision(5) << e.CosineSimilarity + << " L2 " << e.RelativeL2; + } + std::cout << (run.checks[0].vs_q4k.empty() ? " (vs bf16 ref)" : " (vs Q4_K ref)") << std::endl; + } + } + const bool ok = run.completed == (int)steps; + all_completed = all_completed && ok; + std::cout << std::endl << "==== RESULT: layer " << run.idx << ", " << steps << " tokens ====" << std::endl; + std::cout << " calls completed : " << run.completed << " / " << steps + << (ok ? "" : " <-- NOT ALL CALLS COMPLETED: outputs below are not valid") << std::endl; + std::cout << " time per token : " << std::fixed << std::setprecision(2) << run.total_ms / steps + << " ms (host + NPU; the NPU alone: --bench)" << std::endl; + std::cout << " embedding check : cos " << std::setprecision(6) << embed_cos << std::endl; + for (const auto& c : run.checks) { + print_summary_line(c.ref_key, "Q4_K", c.vs_q4k); + print_summary_line(c.ref_key, "bf16", c.vs_bf16); + } + } + + // NPU-only timing (first layer). The per-token latency above includes the host + // syncing every buffer (the 245 MB weight buffer too) each call; bench() runs + // `calls` calls in one runlist with no syncs, at context length 8. 480 calls per + // round, as the timer counts whole ms (0.002 ms per call resolution). Best round reported. + const int bench_rounds = vm["bench"].as(); + if (bench_rounds > 0) { + const int calls = 480; + float best_ms = 1e9f; + for (int r = 0; r < bench_rounds; r++) { + const float ms_per_call = runs[0].layer->bench(token_in, calls, vm["bench_ctx"].as()); + best_ms = std::min(best_ms, ms_per_call); + } + std::cout << " NPU time per call: " << std::fixed << std::setprecision(3) << best_ms << " ms (context " + << vm["bench_ctx"].as() << ", best of " << bench_rounds << " x " << calls << " calls)" << std::endl; + } + std::cout << "=================================================" << std::endl; + return all_completed ? 0 : 1; +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/models.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/models.h new file mode 100644 index 000000000..0438dc454 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/host/models.h @@ -0,0 +1,130 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __MODELS_H__ +#define __MODELS_H__ +#include +#include +#include "typedef.hpp" + +namespace model_list { + /// \brief Where flm keeps its models: $FLM_MODEL_PATH/models, else ~/.config/flm/models. + inline std::string flm_models_dir() { + const char* root = std::getenv("FLM_MODEL_PATH"); + if (root && *root) return std::string(root) + "/models"; + const char* home = std::getenv("HOME"); + return std::string(home ? home : ".") + "/.config/flm/models"; + } + + enum model_t { + MINICPM5_15B_A2_5B, + UNKNOWN_MODEL + }; + + inline model_t get_model_type(const std::string& model_name) { + if (model_name == "MINICPM5_15B_A2_5B") return MINICPM5_15B_A2_5B; + else return UNKNOWN_MODEL; + } + + /// \brief folder with the HF config.json + inline std::string get_config_path(model_t model) { + static const std::string base_path = flm_models_dir() + "/"; + switch (model) { + case MINICPM5_15B_A2_5B: + return base_path + "MiniCPM5-15B-A2.5B-NPU2"; + default: + return "UNKNOWN_MODEL"; + } + } + + /// \brief folder with model.q4nx (the flm model folder itself) + inline std::string get_q4nx_path(model_t model) { + switch (model) { + case MINICPM5_15B_A2_5B: + return get_config_path(model); + default: + return "UNKNOWN_MODEL"; + } + } + + /// \brief per-layer activations (bf16 reference, generated outside the dev kit), in ref_dir + inline std::string get_reference_path(model_t model, const std::string& ref_dir) { + switch (model) { + case MINICPM5_15B_A2_5B: + return ref_dir + "/minicpm5_reference.safetensors"; + default: + return "UNKNOWN_MODEL"; + } + } + + /// \brief the same layers recomputed with the Q4_K weights from model.q4nx, attention + /// and MoE (generated outside the dev kit), one file per layer, in ref_dir + inline std::string get_q4k_reference_path(model_t model, int layer_idx, const std::string& ref_dir) { + switch (model) { + case MINICPM5_15B_A2_5B: + return ref_dir + "/minicpm5_layer_q4k_layer_" + std::to_string(layer_idx) + ".safetensors"; + default: + return "UNKNOWN_MODEL"; + } + } + + /// \brief must match BUILD_DIR in the Makefile + inline std::string get_layer_xclbin_path(model_t model, bool attn_tap) { + static const std::string base_path = "build/"; + static const std::string layer_suffix = "/xclbins/layer.xclbin"; + const std::string tap_suffix = attn_tap ? "_attn_tap" : ""; + switch (model) { + case MINICPM5_15B_A2_5B: + return base_path + "MINICPM5_15B_A2_5B" + tap_suffix + layer_suffix; + + default: + return "UNKNOWN_MODEL"; + } + } + + inline bool has_qk_norm(model_t model) { + switch (model) { + case MINICPM5_15B_A2_5B: + return false; + + default: + return false; + } + } + + /// \brief share of head_dim that RoPE rotates + inline f32 get_rope_partial_factor(model_t model) { + return 1.0f; + } + + inline f32 get_rope_scaling(model_t model) { + return 1.0f; + } + + /// \brief config.json may keep it under rope_parameters, which LM_Config does not read + inline double get_rope_theta(model_t model) { + switch (model) { + case MINICPM5_15B_A2_5B: + return 5000000.0; + default: + return 10000.0; + } + } + + /// \brief expert width, must match INTERMEDIATE_SIZE in the model header + inline int get_moe_intermediate_size(model_t model) { + return 512; + } + + /// \brief the model's real KV heads; the host duplicates each to fill the + /// kernel's NUM_KV_HEADS (4) attention CUs + inline int get_model_kv_heads(model_t model) { + return 2; + } + +} // namespace model_list + +// Proj weight blocks in the int8-mmul kernel's order. Must match Q4K_INT8_MMUL in +// kernels/q4_core.h (a mismatch gives wrong outputs, not an error). +#define Q4K_INT8_MMUL 1 +#endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/RoPE.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/RoPE.py new file mode 100644 index 000000000..667712267 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/RoPE.py @@ -0,0 +1,155 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import numpy as np +import sys +import os +from typing import Any +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig +from ml_dtypes import bfloat16 +import aie.dialects.aie as aie +from aie.helpers.dialects.ext.scf import _for as range_ + +from utils import mlir_context, tile_with_location, lock_acquire, lock_release, comment_print +from utils import AIE_CT_IP +from constants import ROPE_Q_PKT_ID_BASE + +class RoPE(AIE_CT_IP): + dtype = np.dtype[bfloat16] + + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig, stack_size: int = 1024, link_with: str = "rope.o"): + super().__init__(tile, stack_size = stack_size, link_with = link_with) + comment_print(f"Initializing RoPE at ({self.ct_row}, {self.ct_col})") + self.model_config = model_config + self.DQ = model_config.DQ + self.DK = model_config.DK + self.DV = model_config.DV + self.num_attn_cus = model_config.num_attn_cus + q_heads_per_group = model_config.num_heads // model_config.num_kv_heads + self.DQ_PADDED = (q_heads_per_group + model_config.q_heads_padding - 1) // model_config.q_heads_padding * model_config.q_heads_padding * model_config.num_kv_heads * model_config.head_dim + self.q_in_ty = np.ndarray[(self.DQ,), self.dtype] + self.kv_in_ty = np.ndarray[(self.DK + self.DV,), self.dtype] + comment_print(f"DQ: {self.DQ}, DK: {self.DK}, DV: {self.DV}, DQ_PADDED: {self.DQ_PADDED}") + self.q_ty = np.ndarray[(self.DQ_PADDED,), self.dtype] + self.k_ty = np.ndarray[(self.DK,), self.dtype] + self.v_ty = np.ndarray[(self.DV,), self.dtype] + rope_size = model_config.ROPE_DIM # 64, half cos, half sin + + if model_config.has_qk_norm: + rope_size += model_config.DH * 2 + if model_config.has_attn_bias: + rope_size += (model_config.DQ + model_config.DK + model_config.DV) + + self.rope_ty = np.ndarray[(rope_size,), self.dtype] + + comment_print(f"\tRoPE DQ: {self.DQ}, DK: {self.DK}, DV: {self.DV}, DQ_PADDED: {self.DQ_PADDED}, rope_size: {rope_size}") + + self.q_in_buffer = ctx.buffer(tile = self.located_tile, dtype = self.q_in_ty, name = f"q_in_buffer_{self.ct_row}_{self.ct_col}") + self.kv_in_buffer = ctx.buffer(tile = self.located_tile, dtype = self.kv_in_ty, name = f"kv_in_buffer_{self.ct_row}_{self.ct_col}") + self.q_buffer = ctx.buffer(tile = self.located_tile, dtype = self.q_ty, name = f"q_buffer_{self.ct_row}_{self.ct_col}") + self.k_buffer = ctx.buffer(tile = self.located_tile, dtype = self.k_ty, name = f"k_buffer_{self.ct_row}_{self.ct_col}") + self.v_buffer = ctx.buffer(tile = self.located_tile, dtype = self.v_ty, name = f"v_buffer_{self.ct_row}_{self.ct_col}") + self.rope_buffer = ctx.buffer(tile = self.located_tile, dtype = self.rope_ty, name = f"rope_buffer_{self.ct_row}_{self.ct_col}") + self.qkv_prod_lock = aie.lock(self.ct, lock_id = 0, init = 2) + self.qkv_cons_lock = aie.lock(self.ct, lock_id = 1, init = 0) + self.q_prod_lock = aie.lock(self.ct, lock_id = 2, init = 1) + self.q_cons_lock = aie.lock(self.ct, lock_id = 3, init = 0) + self.k_prod_lock = aie.lock(self.ct, lock_id = 4, init = 1) + self.k_cons_lock = aie.lock(self.ct, lock_id = 5, init = 0) + self.v_prod_lock = aie.lock(self.ct, lock_id = 6, init = 1) + self.v_cons_lock = aie.lock(self.ct, lock_id = 7, init = 0) + self.rope_prod_lock = aie.lock(self.ct, lock_id = 8, init = 1) + self.rope_cons_lock = aie.lock(self.ct, lock_id = 9, init = 0) + self.q_pass_lock = aie.lock(self.ct, lock_id = 10, init = 0) + + self.rope = ctx.func(link_with[:-2], [self.q_ty, self.k_ty, self.v_ty, self.q_in_ty, self.kv_in_ty, self.rope_ty]) # sometimes rope_phi4.o + + self.__call__() + + def __call__(self): + @aie.core(self.ct, link_with = self.link_with, stack_size = self.stack_size) + def core_body(): + for _ in range_(0xFFFFFFFF): + self.rope(self.q_buffer, self.k_buffer, self.v_buffer, self.q_in_buffer, self.kv_in_buffer, self.rope_buffer) + + @aie.mem(self.ct) + def mem_dma_body(block): + s0 = aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest = block[1], chain = block[2]) + + with block[1]: + lock_acquire(self.qkv_prod_lock, 1) + aie.dma_bd(self.kv_in_buffer) + lock_release(self.qkv_cons_lock, 1) + aie.next_bd(block[100]) + + with block[100]: + lock_acquire(self.qkv_prod_lock, 1) + aie.dma_bd(self.q_in_buffer) + lock_release(self.qkv_cons_lock, 1) + aie.next_bd(block[1]) + + with block[2]: + s1 = aie.dma_start(aie.DMAChannelDir.MM2S, 0, dest = block[20], chain = block[4]) + + # Q goes out in num_attn_cus equal parts, part i with packet id + # ROPE_Q_PKT_ID_BASE + i (see constants.py) + # (one KV-head group per attention CU). The parts run as one BD chain; + # q_pass_lock hands the turn from one part to the next, the first part + # waits for the kernel and the last one gives the buffer back. + n = self.num_attn_cus + q_part = self.DQ_PADDED // n + for i in range(n): + acq_lock = self.q_cons_lock if i == 0 else self.q_pass_lock + rel_lock = self.q_prod_lock if i == n - 1 else self.q_pass_lock + with block[20 + i]: + lock_acquire(acq_lock, 1) + aie.dma_bd_packet(0, ROPE_Q_PKT_ID_BASE + i) + aie.dma_bd(self.q_buffer, offset=i * q_part, len=q_part) + lock_release(rel_lock, 1) + aie.next_bd(block[20 + (i + 1) % n]) + + with block[4]: + s2 = aie.dma_start(aie.DMAChannelDir.MM2S, 1, dest = block[5], chain = block[9]) + + with block[5]: + lock_acquire(self.k_cons_lock, 1) + aie.dma_bd(self.k_buffer) + lock_release(self.k_prod_lock, 1) + aie.next_bd(block[6]) + + with block[6]: + lock_acquire(self.v_cons_lock, 1) + aie.dma_bd(self.v_buffer) + lock_release(self.v_prod_lock, 1) + aie.next_bd(block[5]) + + with block[9]: + s3 = aie.dma_start(aie.DMAChannelDir.S2MM, 1, dest = block[10], chain = block[11]) + + with block[10]: + lock_acquire(self.rope_prod_lock, 1) + aie.dma_bd(self.rope_buffer) + lock_release(self.rope_cons_lock, 1) + aie.next_bd(block[10]) + + with block[11]: + aie.EndOp() + + @property + def QKV_in(self): + return self.S2MM[0] + + @property + def ROPE_in(self): + return self.S2MM[1] + + @property + def Q_out(self): + return self.MM2S[0] + + @property + def KV_out(self): + return self.MM2S[1] \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/__init__.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/__init__.py new file mode 100644 index 000000000..367e431af --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/__init__.py @@ -0,0 +1,10 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +# Iron package + +from .model_config import ModelConfig +from .constants import ModelArch + +__all__ = [ + "ModelConfig", "ModelArch", +] diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/attn.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/attn.py new file mode 100644 index 000000000..fe6334495 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/attn.py @@ -0,0 +1,587 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import numpy as np +import sys +import os +from typing import Any, List +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig + +from ml_dtypes import bfloat16 +import aie.dialects.aie as aie +from aie.helpers.dialects.ext.scf import _for as range_ + +from utils import connect_port, mlir_context, tile_with_location +from utils import AIE_CT_IP, AIE_MT_IP, comment_print, ShimTile + +class qk_tile(AIE_CT_IP): + dtype = np.dtype[bfloat16] + + def __init__(self, tile: tile_with_location, ctx: mlir_context, shared_s_buffers: List[Any], s_ty: Any, model_config: ModelConfig, stack_size: int = 1024, link_with: str = "attn_qk.o"): + super().__init__(tile, stack_size = stack_size, link_with = link_with) + comment_print(f"Initializing attn_qk_tile at ({self.ct_row}, {self.ct_col})") + self.Q_HEAD_PER_ROUND = model_config.Q_HEAD_PER_ROUND_PADDED + self.KV_HEAD_PER_ROUND = model_config.kv_head_per_cu + self.DH = model_config.DH + self.lc = model_config.lq + + self.attn_q_ty = np.ndarray[(self.Q_HEAD_PER_ROUND * self.DH,), self.dtype] + self.attn_k_ty = np.ndarray[(self.lc, self.KV_HEAD_PER_ROUND * self.DH), self.dtype] + comment_print(f"attn_q_ty shape: ({self.Q_HEAD_PER_ROUND * self.DH},), attn_k_ty shape: ({self.lc}, {self.KV_HEAD_PER_ROUND * self.DH})") + self.attn_s_ty = s_ty + self.L_ty = ctx.data_tys["L_ty"] + + self.attn_qk = ctx.func("attn_qk", [self.attn_q_ty, self.attn_q_ty, self.attn_k_ty, self.attn_k_ty, self.attn_s_ty, self.attn_s_ty, self.L_ty]) + + self.k_buffer_0 = ctx.buffer(tile = self.located_tile, dtype = self.attn_k_ty, name = f"k_0_{self.ct_row}_{self.ct_col}") + self.k_buffer_1 = ctx.buffer(tile = self.located_tile, dtype = self.attn_k_ty, name = f"k_1_{self.ct_row}_{self.ct_col}") + + self.q_buffer_0 = ctx.buffer(tile = self.located_tile, dtype = self.attn_q_ty, name = f"q_0_{self.ct_row}_{self.ct_col}") + self.q_buffer_1 = ctx.buffer(tile = self.located_tile, dtype = self.attn_q_ty, name = f"q_1_{self.ct_row}_{self.ct_col}") + self.q_prod_lock = aie.lock(self.ct, lock_id = 0, init = 2) + self.q_cons_lock = aie.lock(self.ct, lock_id = 1, init = 0) + self.k_prod_lock = aie.lock(self.ct, lock_id = 2, init = 2) + self.k_cons_lock = aie.lock(self.ct, lock_id = 3, init = 0) + self.s_prod_lock = aie.lock(self.ct, lock_id = 4, init = 2) + self.s_cons_lock = aie.lock(self.ct, lock_id = 5, init = 0) + self.l_prod_lock = aie.lock(self.ct, lock_id = 6, init = 2) + self.l_cons_lock = aie.lock(self.ct, lock_id = 7, init = 0) + self.s_buffer_0 = shared_s_buffers[0] + self.s_buffer_1 = shared_s_buffers[1] + + self.L_buffer = ctx.buffer(f"RTP_L_attn_qk_core_{self.ct_row}_{self.ct_col}", self.located_tile, self.L_ty, use_write_rtp = True) + self.q_heads_len = self.Q_HEAD_PER_ROUND * self.DH + self.q_in_order = [(self.Q_HEAD_PER_ROUND, 8), (self.DH // 8, self.Q_HEAD_PER_ROUND * 8), (8, 1)] + + self.__call__() + + def __call__(self): + @aie.core(self.ct, link_with = self.link_with, stack_size = self.stack_size) + def core_body(): + for _ in range_(0xFFFFFFFF): + self.attn_qk(self.q_buffer_0, self.q_buffer_1, self.k_buffer_0, self.k_buffer_1, self.s_buffer_0, self.s_buffer_1, self.L_buffer) + + + @aie.mem(self.ct) + def mem_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest=block[1], chain=block[3]) + + with block[1]: + aie.use_lock(self.q_prod_lock, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.q_buffer_0, offset = 0, len = self.q_heads_len, dimensions = self.q_in_order) + aie.use_lock(self.q_cons_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[2]) + + with block[2]: + aie.use_lock(self.q_prod_lock, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.q_buffer_1, offset = 0, len = self.q_heads_len, dimensions = self.q_in_order) + aie.use_lock(self.q_cons_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[1]) + + with block[3]: + s1 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest=block[4], chain=block[6]) + + with block[4]: + aie.use_lock(self.k_prod_lock, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.k_buffer_0) + aie.use_lock(self.k_cons_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[5]) + + with block[5]: + aie.use_lock(self.k_prod_lock, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.k_buffer_1) + aie.use_lock(self.k_cons_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[4]) + + with block[6]: + aie.EndOp() + + @property + def Q_in(self): + return self.S2MM[0] + + @property + def K_in(self): + return self.S2MM[1] + +class kv_tile(AIE_CT_IP): + dtype = np.dtype[bfloat16] + + def __init__(self, tile: tile_with_location, ctx: mlir_context, s_ty: Any, model_config: ModelConfig, stack_size: int = 1024, link_with: str = "attn_kv.o"): + super().__init__(tile, stack_size = stack_size, link_with = link_with) + comment_print(f"Initializing attn_kv_tile at ({self.ct_row}, {self.ct_col})") + self.NQ_PER_CU = model_config.Q_HEAD_PER_ROUND + self.DH = model_config.DH + self.KV_HEAD_PER_ROUND = model_config.kv_head_per_cu + self.lc = model_config.lk + + self.attn_v_ty = np.ndarray[(self.lc, self.KV_HEAD_PER_ROUND * self.DH), self.dtype] + self.attn_o_ty = np.ndarray[(self.DH * self.NQ_PER_CU, ), self.dtype] + comment_print(f"attn_v_ty shape: ({self.lc}, {self.KV_HEAD_PER_ROUND * self.DH}), attn_o_ty shape: {(self.DH * self.NQ_PER_CU, )}") + self.attn_s_ty = s_ty + self.L_ty = ctx.data_tys["L_ty"] + self.s_ty = s_ty + self.attn_kv = ctx.func("attn_kv", [self.attn_s_ty, self.attn_s_ty, self.attn_v_ty, self.attn_v_ty, self.attn_o_ty, self.attn_o_ty, self.L_ty]) + + self.L_buffer = ctx.buffer(f"RTP_L_attn_kv_core_{self.ct_row}_{self.ct_col}", self.located_tile, self.L_ty, use_write_rtp = True) + self.s_buffer_0 = ctx.buffer(f"s_shared_buffer_0_{self.ct_row + 1}_{self.ct_col}", tile = self.located_tile, dtype = self.s_ty) + self.s_buffer_1 = ctx.buffer(f"s_shared_buffer_1_{self.ct_row + 1}_{self.ct_col}", tile = self.located_tile, dtype = self.s_ty) + self.v_buffer_0 = ctx.buffer(tile = self.located_tile, dtype = self.attn_v_ty, name = f"v_0_{self.ct_row}_{self.ct_col}") + self.v_buffer_1 = ctx.buffer(tile = self.located_tile, dtype = self.attn_v_ty, name = f"v_1_{self.ct_row}_{self.ct_col}") + + self.o_buffer_0 = ctx.buffer(tile = self.located_tile, dtype = self.attn_o_ty, name = f"o_0_{self.ct_row}_{self.ct_col}") + self.o_buffer_1 = ctx.buffer(tile = self.located_tile, dtype = self.attn_o_ty, name = f"o_1_{self.ct_row}_{self.ct_col}") + + self.o_prod_lock = aie.lock(self.ct, lock_id = 0, init = 2) + self.o_cons_lock = aie.lock(self.ct, lock_id = 1, init = 0) + self.v_prod_lock = aie.lock(self.ct, lock_id = 2, init = 2) + self.v_cons_lock = aie.lock(self.ct, lock_id = 3, init = 0) + self.s_proj_lock = aie.lock(self.ct, lock_id = 4, init = 2) + self.s_cons_lock = aie.lock(self.ct, lock_id = 5, init = 0) + + self.__call__() + + def __call__(self): + @aie.core(self.ct, link_with = self.link_with, stack_size = self.stack_size) + def core_body(): + for _ in range_(0xFFFFFFFF): + self.attn_kv(self.s_buffer_0, self.s_buffer_1, self.v_buffer_0, self.v_buffer_1, self.o_buffer_0, self.o_buffer_1, self.L_buffer) + + @aie.mem(self.ct) + def mem_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest=block[1], chain=block[3]) + + with block[1]: + aie.use_lock(self.v_prod_lock, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.v_buffer_0) + aie.use_lock(self.v_cons_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[2]) + + with block[2]: + aie.use_lock(self.v_prod_lock, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.v_buffer_1) + aie.use_lock(self.v_cons_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[1]) + + with block[3]: + s1 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest=block[4], chain=block[6]) + + with block[4]: + aie.use_lock(self.o_cons_lock, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.o_buffer_0, offset = 0, len = self.NQ_PER_CU * self.DH, dimensions = [(self.NQ_PER_CU, 8), (self.DH // 8, self.NQ_PER_CU * 8), (8, 1)]) + aie.use_lock(self.o_prod_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[5]) + + with block[5]: + aie.use_lock(self.o_cons_lock, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.o_buffer_1, offset = 0, len = self.NQ_PER_CU * self.DH, dimensions = [(self.NQ_PER_CU, 8), (self.DH // 8, self.NQ_PER_CU * 8), (8, 1)]) + aie.use_lock(self.o_prod_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[4]) + + with block[6]: + aie.EndOp() + + @property + def V_in(self): + return self.S2MM[1] + + @property + def O_out(self): + return self.MM2S[0] + + @property + def get_s_buffers(self): + return [self.s_buffer_0, self.s_buffer_1] + +class attn_cu: + def __init__(self, + attn_qk_tile: tile_with_location, + attn_kv_tile: tile_with_location, + model_config: ModelConfig, + ctx: mlir_context, + qk_stack_size: int, + kv_stack_size: int, + qk_link_with: str, + kv_link_with: str + ): + comment_print(f"Initializing attn_cu at QK({attn_qk_tile.row}, {attn_qk_tile.col}) KV({attn_kv_tile.row}, {attn_kv_tile.col})") + self.NQ_PER_CU = model_config.Q_HEAD_PER_ROUND_PADDED + self.s_ty = np.ndarray[(self.NQ_PER_CU * 16 + 16, 1), np.dtype[bfloat16]] # for attention score and correction + comment_print(f"\tattn_s_ty shape: {(self.NQ_PER_CU * 16 + 16, 1)}") + self.kv_core = kv_tile(attn_kv_tile, ctx, self.s_ty, model_config, stack_size = kv_stack_size, link_with = kv_link_with) + self.qk_core = qk_tile(attn_qk_tile, ctx, self.kv_core.get_s_buffers, self.s_ty, model_config, stack_size = qk_stack_size, link_with = qk_link_with) + + @property + def Q_in(self): + return self.qk_core.Q_in + + @property + def K_in(self): + return self.qk_core.K_in + + @property + def V_in(self): + return self.kv_core.V_in + + @property + def O_out(self): + return self.kv_core.O_out + +class attn_memtile(AIE_MT_IP): + """Mem tile of one attention column. + + K/V: takes the K and V cache of this column's KV heads from the shim, in + chunks of lc rows, and splits each chunk between the column's 2 CUs (one + head each). + + O: joins o_parts inputs, in order, into one buffer and sends the result out + o_sends times (packet id o_pkt_id, or a plain flow if None). With tap=True + it is also sent once more on MM2S 5, after those, for checking on the host. + + Channels: S2MM 0 K, 1 V, 2.. O parts MM2S 0/1 K, 2/3 V, 4 O, 5 tap + """ + + def __init__(self, tile, mctx: mlir_context, model_config: ModelConfig, kv_heads: int, + o_parts: List[int], o_sends: int, o_pkt_id: int = None, tap: bool = False): + super().__init__(tile) + self.num_kv_heads = kv_heads + self.num_kv_heads_per_round = model_config.kv_head_per_cu + self.DH = model_config.DH + self.lc = model_config.lk + assert 2 <= len(o_parts) <= 4, "O parts come in on S2MM 2..5" + self.o_parts = o_parts + self.o_size = sum(o_parts) + self.o_sends = o_sends + self.o_pkt_id = o_pkt_id + self.tap = tap + + self.k_mem_ty = np.ndarray[(self.lc, self.num_kv_heads * self.DH), np.dtype[bfloat16]] + self.v_mem_ty = np.ndarray[(self.lc, self.num_kv_heads * self.DH), np.dtype[bfloat16]] + self.o_ty = np.ndarray[(self.o_size, ), np.dtype[bfloat16]] + comment_print(f"Initializing attn_memtile at ({self.mt_row}, {self.mt_col}) with lc: {self.lc}, d: { self.num_kv_heads * self.DH }, o_parts: {o_parts}") + + self.k_buffer_0 = aie.buffer(self.mt, self.k_mem_ty, name = f"k_mem_buffer_0_{self.mt_row}_{self.mt_col}") + self.k_buffer_1 = aie.buffer(self.mt, self.k_mem_ty, name = f"k_mem_buffer_1_{self.mt_row}_{self.mt_col}") + self.v_buffer_0 = aie.buffer(self.mt, self.v_mem_ty, name = f"v_mem_buffer_0_{self.mt_row}_{self.mt_col}") + self.v_buffer_1 = aie.buffer(self.mt, self.v_mem_ty, name = f"v_mem_buffer_1_{self.mt_row}_{self.mt_col}") + self.o_buffer = aie.buffer(self.mt, self.o_ty, name = f"o_buffer_{self.mt_row}_{self.mt_col}") + + self.k_prod_lock = aie.lock(self.mt, lock_id = 0, init = 2) + self.k_cons_lock_0 = aie.lock(self.mt, lock_id = 1, init = 0) + self.k_cons_lock_1 = aie.lock(self.mt, lock_id = 2, init = 0) + self.v_prod_lock = aie.lock(self.mt, lock_id = 3, init = 2) + self.v_cons_lock_0 = aie.lock(self.mt, lock_id = 4, init = 0) + self.v_cons_lock_1 = aie.lock(self.mt, lock_id = 5, init = 0) + + # O locks, a chain: part i waits on o_part_locks[i] and passes the turn + # to part i + 1; the last part hands the full buffer to the senders. + # Trick: the first lock starts at the number of sends (not 1). Filling + # takes all counts and each send gives one back, so O is only refilled + # after its last send has left. + # With the tap, the o_sends main sends hand their counts to tap_lock + # instead, and the tap (one send, after all of them) gives all of them + # back at once: the tap always gets exactly one copy, the main output + # exactly o_sends, and they never compete for the same count. + self.o_part_locks = [aie.lock(self.mt, lock_id = 6 + i, init = self.o_sends if i == 0 else 0) + for i in range(len(o_parts))] + self.o_cons_lock = aie.lock(self.mt, lock_id = 6 + len(o_parts), init = 0) + if self.tap: + self.tap_lock = aie.lock(self.mt, lock_id = 7 + len(o_parts), init = 0) + + self.k_mem_row_size = self.num_kv_heads * self.DH + self.k_mem_cu_row_size = self.num_kv_heads_per_round * self.DH + self.k_order = [(self.k_mem_cu_row_size // 8, 8), (16, self.k_mem_row_size), (8, 1)] + self.k_offset = self.k_mem_cu_row_size + comment_print(f"\tattn_memtile k_order: {self.k_order}") + self.k_len_per_cu = self.k_mem_cu_row_size * self.lc + + self.v_mem_row_size = self.num_kv_heads * self.DH + self.v_mem_cu_row_size = self.num_kv_heads_per_round * self.DH + self.v_order = [(self.lc // 8, self.lc // 2 * self.v_mem_row_size), (self.v_mem_cu_row_size // 8, 8), (8, self.v_mem_row_size), (8, 1)] + comment_print(f"\tattn_memtile v_order: {self.v_order}") + self.v_len_per_cu = self.v_mem_cu_row_size * self.lc + self.v_offset = self.v_mem_cu_row_size + self.__call__() + + def __call__(self): + @aie.memtile_dma(self.mt) + def memtile_dma_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest=block[1], chain=block[3]) + + with block[1]: + aie.use_lock(self.k_prod_lock, aie.LockAction.AcquireGreaterEqual, value=1) + aie.dma_bd(self.k_buffer_0) + aie.use_lock(self.k_cons_lock_0, aie.LockAction.Release, value=1) + aie.next_bd(block[2]) + + with block[2]: + aie.use_lock(self.k_prod_lock, aie.LockAction.AcquireGreaterEqual, value=1) + aie.dma_bd(self.k_buffer_1) + aie.use_lock(self.k_cons_lock_0, aie.LockAction.Release, value=1) + aie.next_bd(block[1]) + + with block[3]: + s1 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest=block[4], chain=block[6]) + + with block[4]: + aie.use_lock(self.k_cons_lock_0, aie.LockAction.AcquireGreaterEqual, value=1) + aie.dma_bd(self.k_buffer_0, offset = 0, len = self.k_len_per_cu, dimensions = self.k_order) + aie.use_lock(self.k_cons_lock_1, aie.LockAction.Release, value=1) + aie.next_bd(block[5]) + + with block[5]: + aie.use_lock(self.k_cons_lock_0, aie.LockAction.AcquireGreaterEqual, value=1) + aie.dma_bd(self.k_buffer_1, offset = 0, len = self.k_len_per_cu, dimensions = self.k_order) + aie.use_lock(self.k_cons_lock_1, aie.LockAction.Release, value=1) + aie.next_bd(block[4]) + + with block[6]: + s1 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 1, dest=block[7], chain=block[9]) + + with block[7]: + aie.use_lock(self.k_cons_lock_1, aie.LockAction.AcquireGreaterEqual, value=1) + aie.dma_bd(self.k_buffer_0, offset = self.k_offset, len = self.k_len_per_cu, dimensions = self.k_order) + aie.use_lock(self.k_prod_lock, aie.LockAction.Release, value=1) + aie.next_bd(block[8]) + + with block[8]: + aie.use_lock(self.k_cons_lock_1, aie.LockAction.AcquireGreaterEqual, value=1) + aie.dma_bd(self.k_buffer_1, offset = self.k_offset, len = self.k_len_per_cu, dimensions = self.k_order) + aie.use_lock(self.k_prod_lock, aie.LockAction.Release, value=1) + aie.next_bd(block[7]) + + with block[9]: + s3 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest=block[10], chain=block[12]) + + with block[10]: + aie.use_lock(self.v_prod_lock, aie.LockAction.AcquireGreaterEqual, value=1) + aie.dma_bd(self.v_buffer_0) + aie.use_lock(self.v_cons_lock_0, aie.LockAction.Release, value=1) + aie.next_bd(block[11]) + + with block[11]: + aie.use_lock(self.v_prod_lock, aie.LockAction.AcquireGreaterEqual, value=1) + aie.dma_bd(self.v_buffer_1) + aie.use_lock(self.v_cons_lock_0, aie.LockAction.Release, value=1) + aie.next_bd(block[10]) + + with block[12]: + s4 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 2, dest=block[13], chain=block[15]) + + with block[13]: + aie.use_lock(self.v_cons_lock_0, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.v_buffer_0, offset = 0, len = self.v_len_per_cu, dimensions = self.v_order) + aie.use_lock(self.v_cons_lock_1, aie.LockAction.Release, value = 1) + aie.next_bd(block[14]) + + with block[14]: + aie.use_lock(self.v_cons_lock_0, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.v_buffer_1, offset = 0, len = self.v_len_per_cu, dimensions = self.v_order) + aie.use_lock(self.v_cons_lock_1, aie.LockAction.Release, value = 1) + aie.next_bd(block[13]) + + with block[15]: + s4 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 3, dest=block[16], chain=block[18]) + + with block[16]: + aie.use_lock(self.v_cons_lock_1, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.v_buffer_0, offset = self.v_offset, len = self.v_len_per_cu, dimensions = self.v_order) + aie.use_lock(self.v_prod_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[17]) + + with block[17]: + aie.use_lock(self.v_cons_lock_1, aie.LockAction.AcquireGreaterEqual, value = 1) + aie.dma_bd(self.v_buffer_1, offset = self.v_offset, len = self.v_len_per_cu, dimensions = self.v_order) + aie.use_lock(self.v_prod_lock, aie.LockAction.Release, value = 1) + aie.next_bd(block[16]) + + # O in: part i on S2MM 2 + i, written to its place in o_buffer + with block[18]: + aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 2, dest=block[30], chain=block[19]) + n_parts = len(self.o_parts) + offset = 0 + for i, part_len in enumerate(self.o_parts): + is_last = i == n_parts - 1 + acq_value = self.o_sends if i == 0 else 1 + rel_lock = self.o_cons_lock if is_last else self.o_part_locks[i + 1] + rel_value = self.o_sends if is_last else 1 + with block[30 + i]: + aie.use_lock(self.o_part_locks[i], aie.LockAction.AcquireGreaterEqual, value = acq_value) + aie.dma_bd(self.o_buffer, offset = offset, len = part_len) + aie.use_lock(rel_lock, aie.LockAction.Release, value = rel_value) + aie.next_bd(block[30 + i]) + if not is_last: + with block[19 + i]: + aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 3 + i, dest=block[31 + i], chain=block[20 + i]) + offset += part_len + chain_after_parts = 19 + n_parts - 1 + + # O out, o_sends times + with block[chain_after_parts]: + aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 4, dest=block[40], chain=block[41]) + with block[40]: + aie.use_lock(self.o_cons_lock, aie.LockAction.AcquireGreaterEqual, value = 1) + if self.o_pkt_id is not None: + aie.dma_bd_packet(0, self.o_pkt_id) + aie.dma_bd(self.o_buffer) + aie.use_lock(self.tap_lock if self.tap else self.o_part_locks[0], aie.LockAction.Release, value = 1) + aie.next_bd(block[40]) + + # optional tap: one more copy of O, for the host + if self.tap: + with block[41]: + aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 5, dest=block[42], chain=block[43]) + with block[42]: + aie.use_lock(self.tap_lock, aie.LockAction.AcquireGreaterEqual, value = self.o_sends) + aie.dma_bd(self.o_buffer) + aie.use_lock(self.o_part_locks[0], aie.LockAction.Release, value = self.o_sends) + aie.next_bd(block[42]) + end_block = 43 + else: + end_block = 41 + + with block[end_block]: + aie.EndOp() + + @property + def K_in(self): + return self.S2MM[0] + + @property + def V_in(self): + return self.S2MM[1] + + @property + def K_out_0(self): + return self.MM2S[0] + + @property + def K_out_1(self): + return self.MM2S[1] + + @property + def V_out_0(self): + return self.MM2S[2] + + @property + def V_out_1(self): + return self.MM2S[3] + + def O_in(self, part: int): + return self.S2MM[2 + part] + + @property + def O_out(self): + return self.MM2S[4] + + @property + def TAP_out(self): + assert self.tap + return self.MM2S[5] + + +class attn_column: + """One column: 2 attention CUs (one KV head each), its mem tile and shim. + + The shim feeds this column's slice of the KV cache to the mem tile, which + splits it between the 2 CUs. The CUs' outputs come back to the mem tile as + O parts 0 and 1; extra_o_parts lists the sizes of more O inputs (from + another column) that join after them. + """ + def __init__(self, + attn_qk_tiles: List[tile_with_location], + attn_kv_tiles: List[tile_with_location], + memtile: tile_with_location, + shim_tile: ShimTile, + model_config: ModelConfig, + ctx: mlir_context, + qk_stack_size: int, + kv_stack_size: int, + qk_link_with: str, + kv_link_with: str, + extra_o_parts: List[int], + o_sends: int, + o_pkt_id: int = None, + tap: bool = False, + ): + comment_print(f"Initializing attn_column at MT({memtile.row}, {memtile.col})") + assert len(attn_qk_tiles) == 2 and len(attn_kv_tiles) == 2 + self.attn_cus = [] + for i in range(len(attn_qk_tiles)): + self.attn_cus.append(attn_cu( + attn_qk_tile = attn_qk_tiles[i], + attn_kv_tile = attn_kv_tiles[i], + model_config = model_config, + ctx = ctx, + qk_stack_size = qk_stack_size, + kv_stack_size = kv_stack_size, + qk_link_with = qk_link_with, + kv_link_with = kv_link_with + )) + cu_o_size = model_config.Q_HEAD_PER_ROUND * model_config.DH + self.o_size = cu_o_size * len(self.attn_cus) + self.memtile = attn_memtile(memtile, ctx, model_config, + kv_heads = model_config.kv_head_per_cu * len(self.attn_cus), + o_parts = [cu_o_size] * len(self.attn_cus) + extra_o_parts, + o_sends = o_sends, o_pkt_id = o_pkt_id, tap = tap) + self.IT = shim_tile + + def route(self): + connect_port(self.IT.MM2S[0], self.memtile.K_in) + connect_port(self.IT.MM2S[1], self.memtile.V_in) + connect_port(self.memtile.K_out_0, self.attn_cus[0].K_in) + connect_port(self.memtile.V_out_0, self.attn_cus[0].V_in) + connect_port(self.memtile.K_out_1, self.attn_cus[1].K_in) + connect_port(self.memtile.V_out_1, self.attn_cus[1].V_in) + connect_port(self.attn_cus[0].O_out, self.memtile.O_in(0)) + connect_port(self.attn_cus[1].O_out, self.memtile.O_in(1)) + + @property + def Q_in(self): + return [cu.Q_in for cu in self.attn_cus] + + @property + def O_out(self): + return self.memtile.O_out + + +class attn_block: + """Attention over 2 columns x 2 CUs, one KV head per CU (KV heads 0..3). + + The main column (KV heads 0, 1) owns the output. The second column (KV + heads 2, 3) joins its 2 CU outputs in its own mem tile and sends that half + to the main mem tile, which joins it after its own 2 parts, so O is in head + order. The main mem tile then sends O o_sends times (to o_proj), and once + more to the tap if asked. + """ + def __init__(self, main_column: dict, second_column: dict, model_config: ModelConfig, ctx: mlir_context, + qk_stack_size: int, kv_stack_size: int, qk_link_with: str, kv_link_with: str, + o_sends: int, o_pkt_id: int, tap: bool = False): + assert model_config.num_attn_cus == 4 and model_config.kv_head_per_cu == 1 + common = dict(model_config = model_config, ctx = ctx, + qk_stack_size = qk_stack_size, kv_stack_size = kv_stack_size, + qk_link_with = qk_link_with, kv_link_with = kv_link_with) + self.second = attn_column(**second_column, **common, extra_o_parts = [], o_sends = 1) + self.main = attn_column(**main_column, **common, extra_o_parts = [self.second.o_size], + o_sends = o_sends, o_pkt_id = o_pkt_id, tap = tap) + + def route(self): + self.main.route() + self.second.route() + connect_port(self.second.O_out, self.main.memtile.O_in(2)) + + @property + def Q_in(self): + # CU i gets Q packet i: KV head i and its query heads + return self.main.Q_in + self.second.Q_in + + @property + def O_out(self): + return self.main.O_out + + @property + def TAP_out(self): + return self.main.memtile.TAP_out diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/aux_memtile.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/aux_memtile.py new file mode 100644 index 000000000..df189dedc --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/aux_memtile.py @@ -0,0 +1,253 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +import numpy as np +import sys +import os +from typing import Any, List +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +import aie.dialects.aie as aie +import aie.dialects.aiex as aiex +from aie.helpers.dialects.ext.scf import _for as range_ +import aie.utils.trace as trace_utils +from aie.utils.trace import MemTilePortEvent, MemTileEvent, PortEvent +from aie.utils.trace_events_enum import CoreEvent, MemEvent, ShimTileEvent, MemTileEvent +from aie.dialects import memref + +from utils import dma_port, mlir_context, tile_with_location, lock_acquire, lock_release +from utils import connect_port +from utils import AIE_MT_IP + +from constants import * +from iron.utils import comment_print + +class aux_memtile(AIE_MT_IP): + dtype = np.dtype[bfloat16] + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig): + # aux mt sorts the proj engine outputs by their fixed order in a layer + # (X_in, pkt to_aux): out_projection -> to RMS, MM2S 1 + # down_projection -> to RMS, MM2S 1 + # (GLU_IN, pkt to_glu): up_gate_projection -> to GLU, MM2S 2 + + # for pipelines, all DMA are seperated into 4 partials (ping-ponged, 4 * 4 = 16 bds, plenty) + super().__init__(tile) + self.model_config = model_config + self.D = model_config.D + self.intermediate_size = model_config.intermediate_size + self.out_down_proj_ty = np.ndarray[(self.D // 4,), self.dtype] + # A BD hands its piece on only when full, so the piece must divide every + # amount that flows to the GLU in a call: shared up/gate 2 * I, routed + # up/gate 4 * 2 * I and routed down 4 * D per round. Half a GLU slice (256) + # does; the old 2 * I / 4 (384 at I = 768) left routed down's last piece + # unsent and the GLU waited for it forever. + self.glu_slice_ty = np.ndarray[(model_config.glu_slice // 2,), self.dtype] + for total in (2 * self.intermediate_size, 8 * self.intermediate_size, 4 * self.D): + assert total % (model_config.glu_slice // 2) == 0 + + self.out_prod_lock = aie.lock(self.mt, lock_id = 2, init = 2) + self.out_cons_lock = aie.lock(self.mt, lock_id = 3, init = 0) + self.glu_slice_prod_lock = aie.lock(self.mt, lock_id = 4, init = 2) + self.glu_slice_cons_lock = aie.lock(self.mt, lock_id = 5, init = 0) + self.down_prod_lock = aie.lock(self.mt, lock_id = 6, init = 2) + self.down_cons_lock = aie.lock(self.mt, lock_id = 7, init = 0) + + self.out_down_buffer_0 = aie.buffer(tile = self.mt, datatype = self.out_down_proj_ty, name = f"out_down_buffer_0_{self.mt_row}_{self.mt_col}") + self.out_down_buffer_1 = aie.buffer(tile = self.mt, datatype = self.out_down_proj_ty, name = f"out_down_buffer_1_{self.mt_row}_{self.mt_col}") + self.down_buffer_0 = aie.buffer(tile = self.mt, datatype = self.out_down_proj_ty, name = f"down_buffer_0_{self.mt_row}_{self.mt_col}") + self.down_buffer_1 = aie.buffer(tile = self.mt, datatype = self.out_down_proj_ty, name = f"down_buffer_1_{self.mt_row}_{self.mt_col}") + self.glu_slice_buffer_0 = aie.buffer(tile = self.mt, datatype = self.glu_slice_ty, name = f"glu_slice_buffer_0_{self.mt_row}_{self.mt_col}") + self.glu_slice_buffer_1 = aie.buffer(tile = self.mt, datatype = self.glu_slice_ty, name = f"glu_slice_buffer_1_{self.mt_row}_{self.mt_col}") + + self.__call__() + + def __call__(self): + @aie.memtile_dma(self.mt) + def memtile_dma_body(block): + with block[0]: + aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest = block[5], chain = block[50]) + + with block[5]: + lock_acquire(self.out_prod_lock, 1) + aie.dma_bd(self.out_down_buffer_0) + lock_release(self.out_cons_lock, 1) + aie.next_bd(block[6]) + + with block[6]: + lock_acquire(self.out_prod_lock, 1) + aie.dma_bd(self.out_down_buffer_1) + lock_release(self.out_cons_lock, 1) + aie.next_bd(block[7]) + + with block[7]: + lock_acquire(self.out_prod_lock, 1) + aie.dma_bd(self.out_down_buffer_0) + lock_release(self.out_cons_lock, 1) + aie.next_bd(block[8]) + + with block[8]: + lock_acquire(self.out_prod_lock, 1) + aie.dma_bd(self.out_down_buffer_1) + lock_release(self.out_cons_lock, 1) + aie.next_bd(block[13]) + + with block[13]: + lock_acquire(self.down_prod_lock, 1) + aie.dma_bd(self.down_buffer_0) + lock_release(self.down_cons_lock, 1) + aie.next_bd(block[14]) + + with block[14]: + lock_acquire(self.down_prod_lock, 1) + aie.dma_bd(self.down_buffer_1) + lock_release(self.down_cons_lock, 1) + aie.next_bd(block[15]) + + with block[15]: + lock_acquire(self.down_prod_lock, 1) + aie.dma_bd(self.down_buffer_0) + lock_release(self.down_cons_lock, 1) + aie.next_bd(block[16]) + + with block[16]: + lock_acquire(self.down_prod_lock, 1) + aie.dma_bd(self.down_buffer_1) + lock_release(self.down_cons_lock, 1) + aie.next_bd(block[5]) + + + with block[50]: + aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest=block[51], chain=block[100] ) + + with block[51]: + lock_acquire(self.glu_slice_prod_lock, 1) + aie.dma_bd(self.glu_slice_buffer_0) + lock_release(self.glu_slice_cons_lock, 1) + aie.next_bd(block[52]) + + with block[52]: + lock_acquire(self.glu_slice_prod_lock, 1) + aie.dma_bd(self.glu_slice_buffer_1) + lock_release(self.glu_slice_cons_lock, 1) + aie.next_bd(block[53]) + + with block[53]: + lock_acquire(self.glu_slice_prod_lock, 1) + aie.dma_bd(self.glu_slice_buffer_0) + lock_release(self.glu_slice_cons_lock, 1) + aie.next_bd(block[54]) + + with block[54]: + lock_acquire(self.glu_slice_prod_lock, 1) + aie.dma_bd(self.glu_slice_buffer_1) + lock_release(self.glu_slice_cons_lock, 1) + aie.next_bd(block[51]) + + with block[100]: + aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 1, dest = block[201], chain = block[300]) + + with block[201]: + lock_acquire(self.out_cons_lock, 1) + aie.dma_bd_packet(0, it1_pkt_id.to_rms) + aie.dma_bd(self.out_down_buffer_0) + lock_release(self.out_prod_lock, 1) + aie.next_bd(block[202]) + + with block[202]: + lock_acquire(self.out_cons_lock, 1) + aie.dma_bd_packet(0, it1_pkt_id.to_rms) + aie.dma_bd(self.out_down_buffer_1) + lock_release(self.out_prod_lock, 1) + aie.next_bd(block[203]) + + with block[203]: + lock_acquire(self.out_cons_lock, 1) + aie.dma_bd_packet(0, it1_pkt_id.to_rms) + aie.dma_bd(self.out_down_buffer_0) + lock_release(self.out_prod_lock, 1) + aie.next_bd(block[204]) + + with block[204]: + lock_acquire(self.out_cons_lock, 1) + aie.dma_bd_packet(0, it1_pkt_id.to_rms) + aie.dma_bd(self.out_down_buffer_1) + lock_release(self.out_prod_lock, 1) + aie.next_bd(block[205]) + + with block[205]: + lock_acquire(self.down_cons_lock, 1) + aie.dma_bd_packet(0, it1_pkt_id.to_rms) + aie.dma_bd(self.down_buffer_0) + lock_release(self.down_prod_lock, 1) + aie.next_bd(block[206]) + + with block[206]: + lock_acquire(self.down_cons_lock, 1) + aie.dma_bd_packet(0, it1_pkt_id.to_rms) + aie.dma_bd(self.down_buffer_1) + lock_release(self.down_prod_lock, 1) + aie.next_bd(block[207]) + + with block[207]: + lock_acquire(self.down_cons_lock, 1) + aie.dma_bd_packet(0, it1_pkt_id.to_rms) + aie.dma_bd(self.down_buffer_0) + lock_release(self.down_prod_lock, 1) + aie.next_bd(block[208]) + + with block[208]: + lock_acquire(self.down_cons_lock, 1) + aie.dma_bd_packet(0, it1_pkt_id.to_rms) + aie.dma_bd(self.down_buffer_1) + lock_release(self.down_prod_lock, 1) + aie.next_bd(block[201]) + + with block[300]: + aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 2, dest = block[301], chain = block[400]) + + with block[301]: + lock_acquire(self.glu_slice_cons_lock, 1) + aie.dma_bd(self.glu_slice_buffer_0) + lock_release(self.glu_slice_prod_lock, 1) + aie.next_bd(block[302]) + + with block[302]: + lock_acquire(self.glu_slice_cons_lock, 1) + aie.dma_bd(self.glu_slice_buffer_1) + lock_release(self.glu_slice_prod_lock, 1) + aie.next_bd(block[303]) + + with block[303]: + lock_acquire(self.glu_slice_cons_lock, 1) + aie.dma_bd(self.glu_slice_buffer_0) + lock_release(self.glu_slice_prod_lock, 1) + aie.next_bd(block[304]) + + with block[304]: + lock_acquire(self.glu_slice_cons_lock, 1) + aie.dma_bd(self.glu_slice_buffer_1) + lock_release(self.glu_slice_prod_lock, 1) + aie.next_bd(block[301]) + + with block[400]: + aie.EndOp() + + @property + def X_in(self) -> dma_port: + return self.S2MM[0] + + @property + def OUT(self) -> dma_port: + return self.MM2S[1] + + + @property + def GLU_IN(self)->dma_port: + return self.S2MM[1] + + @property + def GLU_out(self) -> dma_port: + return self.MM2S[2] diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/constants.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/constants.py new file mode 100644 index 000000000..c46cf4bac --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/constants.py @@ -0,0 +1,60 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +from enum import IntEnum, auto + +class proj_pkt_id(IntEnum): + to_rope = 1 + to_aux = 8 + to_glu = 15 + to_gate = 3 # attention output gate logits -> gate tile (not 12: mlir-aie merges {1, 12} into a mask that also takes 8) + + x_to_column_0 = 29 + x_to_column_1 = 25 + x_to_column_2 = 22 + x_to_column_3 = 31 + + + +class rms_pkt_id(IntEnum): + to_proj = 0 + to_st = 1 + to_glu = 7 + from_glu = 11 + +class it1_pkt_id(IntEnum): + to_rms = 0 + to_rope = 1 + +# packet ids into the proj engine's x input (MT1), besides rms_pkt_id.to_proj +class proj_x_pkt_id(IntEnum): + # gated attention output, for o_proj. A high id on purpose: aiecc hands out + # switch arbiters in packet id order, so in the crowded switch below the gate + # (col 2, row 2) this flow comes last and its overflow arbiter is the one of + # rms -> proj x (both x_in, safe). With id 2 it took the arbiter of the flows + # into rms (MT2, GLU), and RoPE Q took rms x's: check_routes failed 8 of 8. + from_attn = 24 + from_glu = 9 # GLU: shared expert h, routed up/gate x, routed experts' h + +class router_w_pkt_id(IntEnum): + to_router_w = 10 + +# RoPE -> attention CU i sends Q with packet id ROPE_Q_PKT_ID_BASE + i. 16..19 are +# used by nothing else and form an aligned group of 4, so if the router merges +# them into one masked rule (mask 0x1C, value 16) that rule matches only Q. With +# ids 0..3 the merged rule also caught rms -> proj (id 0) and the normal build +# could not route at all. +ROPE_Q_PKT_ID_BASE = 16 + + +class ModelArch(IntEnum): + MINICPM5_15B_A2_5B = auto() + +class QuantType(IntEnum): + Q4_1 = auto() + Q8_0 = auto() + Q4_K = auto() + +ModelArchNames: dict[ModelArch, str] = { + ModelArch.MINICPM5_15B_A2_5B: "MINICPM5_15B_A2_5B" +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/gate.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/gate.py new file mode 100644 index 000000000..639eaba88 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/gate.py @@ -0,0 +1,103 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import numpy as np +import sys +import os +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig +from ml_dtypes import bfloat16 +import aie.dialects.aie as aie +from aie.helpers.dialects.ext.scf import _for as range_ + +from utils import dma_port, mlir_context, tile_with_location, lock_acquire, lock_release, comment_print +from utils import AIE_CT_IP +from constants import proj_x_pkt_id + + +class gate_tile(AIE_CT_IP): + """Attention output gate (adapted from Qwen3_6/qwen3_6_moe_decoding): + o_in = attn_out * sigmoid(x @ W_gate). + + Gate_In gets the gate logits (DQ) straight from the proj engine (packet + proj_pkt_id.to_gate), Attn_In the attention output (DQ) once, and Attn_Out + sends the gated output to the proj engine's x input once per o_proj + row-block round (packet proj_x_pkt_id.from_attn). + """ + dtype = np.dtype[bfloat16] + + def __init__(self, ct: tile_with_location, ctx: mlir_context, model_config: ModelConfig, stack_size: int = 1024, link_with: str = "gate.o"): + super().__init__(ct, stack_size = stack_size, link_with = link_with) + comment_print(f"Initializing gate at ({self.ct_row}, {self.ct_col})") + + self.DQ = model_config.DQ + self.D = model_config.D + # o_proj takes its x once per row-block round of the 16 proj cores + self.repeats = self.D // (model_config.q4nx_row_block_size * 16) + self.gate_ty = np.ndarray[(self.DQ,), self.dtype] + + self.gate_buffer = ctx.buffer(tile = self.located_tile, dtype = self.gate_ty, name = f"gate_{self.ct_row}_{self.ct_col}") + self.attn_out_buffer = ctx.buffer(tile = self.located_tile, dtype = self.gate_ty, name = f"attn_out_{self.ct_row}_{self.ct_col}") + self.gated_attn_out_buffer = ctx.buffer(tile = self.located_tile, dtype = self.gate_ty, name = f"gated_attn_out_{self.ct_row}_{self.ct_col}") + + self.gate_prod_lock = aie.lock(self.ct, lock_id = 0, init = 1) + self.gate_cons_lock = aie.lock(self.ct, lock_id = 1, init = 0) + self.attn_out_prod_lock = aie.lock(self.ct, lock_id = 2, init = 1) + self.attn_out_cons_lock = aie.lock(self.ct, lock_id = 3, init = 0) + self.gated_attn_out_prod_lock = aie.lock(self.ct, lock_id = 4, init = self.repeats) + self.gated_attn_out_cons_lock = aie.lock(self.ct, lock_id = 5, init = 0) + + self.gate = ctx.func(link_with[:-2], [self.gate_ty, self.gate_ty, self.gate_ty]) + + self.__call__() + + def __call__(self): + @aie.core(self.ct, link_with = self.link_with, stack_size = self.stack_size) + def core_body(): + for _ in range_(0xFFFFFFFF): + self.gate(self.gated_attn_out_buffer, self.gate_buffer, self.attn_out_buffer) + + @aie.mem(self.ct) + def mem_body(block): + aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest = block[1], chain = block[2]) + with block[1]: + lock_acquire(self.gate_prod_lock, 1) + aie.dma_bd(self.gate_buffer) + lock_release(self.gate_cons_lock, 1) + aie.next_bd(block[1]) + + with block[2]: + aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest = block[3], chain = block[4]) + + with block[3]: + lock_acquire(self.attn_out_prod_lock, 1) + aie.dma_bd(self.attn_out_buffer) + lock_release(self.attn_out_cons_lock, 1) + aie.next_bd(block[3]) + + with block[4]: + aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest = block[5], chain = block[6]) + + with block[5]: + lock_acquire(self.gated_attn_out_cons_lock, 1) + aie.dma_bd_packet(0, proj_x_pkt_id.from_attn) + aie.dma_bd(self.gated_attn_out_buffer) + lock_release(self.gated_attn_out_prod_lock, 1) + aie.next_bd(block[5]) + + with block[6]: + aie.EndOp() + + @property + def Gate_In(self) -> dma_port: + return self.S2MM[0] + + @property + def Attn_In(self) -> dma_port: + return self.S2MM[1] + + @property + def Attn_Out(self) -> dma_port: + return self.MM2S[0] diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/glu.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/glu.py new file mode 100644 index 000000000..5d5ac523b --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/glu.py @@ -0,0 +1,178 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +import numpy as np +import sys +import os +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig +from ml_dtypes import bfloat16 +import aie.dialects.aie as aie +from aie.helpers.dialects.ext.scf import _for as range_ +from utils import dma_port, mlir_context, tile_with_location, lock_acquire, lock_release +from utils import AIE_CT_IP, comment_print +from constants import * + + +class glu_tile(AIE_CT_IP): + dtype = np.dtype[bfloat16] + def __init__(self, ct: tile_with_location, ctx: mlir_context, model_config: ModelConfig, stack_size: int = 1024, link_with: str = "glu.o"): + super().__init__(ct, stack_size = stack_size, link_with = link_with) + self.D = model_config.D + + assert(model_config.hidden_size == model_config.D) + self.intermediate_size = model_config.intermediate_size + self.glu_slice = model_config.glu_slice + self.up_gate_ty = np.ndarray[(self.glu_slice,), self.dtype] + self.hid_ty = np.ndarray[(self.intermediate_size,), self.dtype] # plust 16 for packet_id and alignment issue + self.D_out_ty = np.ndarray[(self.D,), self.dtype] # + 4 for packed_id, + 12 for alignment + + self.hidden_state_ty = np.ndarray[(self.D,), self.dtype] + + self.shared_expert_output_ty = np.ndarray[(self.D,), np.dtype[np.float32]] + + + self.top_k_expert_score_ty = np.ndarray[(model_config.num_experts,), np.dtype[np.float32]] + self.top_k_expert_index_ty = np.ndarray[(model_config.num_experts,), np.dtype[np.int32]] + + + # +14 for alignment, +2 for packet_id + self.to_proj_x_slice_with_pkt_buf_size = 2+ model_config.x_slice_size + self.to_proj_x_slice_with_pkt_ty = np.ndarray[(model_config.x_slice_size+ 16,), self.dtype] + + + assert(self.D % model_config.glu_slice == 0) + + comment_print(f"GLU tile at ({self.ct_row}, {self.ct_col}) with intermediate_size: {self.intermediate_size}, glu_slice: {self.glu_slice}") + # q_proj tile and mem + # double buffer + self.glu_slice_in_buffer_0 = aie.buffer(tile = self.ct, datatype = self.up_gate_ty, name = f"glu_x_slice_buffer_0{self.ct_row}_{self.ct_col}") + self.glu_slice_in_buffer_1 = aie.buffer(tile = self.ct, datatype = self.up_gate_ty, name = f"glu_slice_buffer_1{self.ct_row}_{self.ct_col}") + + self.intermediate_buffer = aie.buffer(tile = self.ct, datatype = self.hid_ty, name = f"intermediate_out_buffer_{self.ct_row}_{self.ct_col}") + self.D_mlp_final_to_rms = aie.buffer(tile=self.ct, datatype = self.D_out_ty, name= f"D_out_buffer{self.ct_row}_{self.ct_col}") + + self.D_in_buffer = aie.buffer(self.ct, datatype = self.hidden_state_ty, name= f"D_in_buffer_{self.ct_row}_{self.ct_col}") + # despite the name: fp32 sum of the routed experts (see glu.cc) + self.shared_expert_output_buffer = aie.buffer(self.ct, datatype = self.shared_expert_output_ty, name= f"shared_Expert_buffer_{self.ct_row}_{self.ct_col}") + + self.top_k_expert_score_buffer = aie.buffer( + tile=self.ct, datatype=self.top_k_expert_score_ty, name=f"top_k_expert_score_{self.ct_row}_{self.ct_col}") + self.top_k_expert_index_buffer = aie.buffer( + tile=self.ct, datatype=self.top_k_expert_index_ty, name=f"top_k_epxert_index_{self.ct_row}_{self.ct_col}") + + + + self.to_proj_x_slice_with_pkt_buffer_0 = aie.buffer( + tile=self.ct, datatype=self.to_proj_x_slice_with_pkt_ty, name=f"to_proj_x_slice_with_pkt_buffer__0_{self.ct_row}_{self.ct_col}" + ) + + self.to_proj_x_slice_with_pkt_buffer_1 = aie.buffer( + tile=self.ct, datatype=self.to_proj_x_slice_with_pkt_ty, name=f"to_proj_x_slice_with_pkt_buffer__1_{self.ct_row}_{self.ct_col}" + ) + + + + self.glu_slice_prod_lock = aie.lock(self.ct, lock_id = 0, init = 2) + self.glu_slice_con_lock = aie.lock(self.ct, lock_id = 1, init = 0) + + + self.to_proj_x_slice_prod_lock = aie.lock(self.ct, lock_id = 2, init = 2) + self.to_proj_x_slice_cons_lock = aie.lock(self.ct, lock_id = 3, init = 0) + + self.D_out_prod_lock = aie.lock(self.ct, lock_id=4, init=0) + self.D_out_cons_lock = aie.lock(self.ct, lock_id=5, init=0) + + self.D_in_prod_lock = aie.lock(self.ct, lock_id=6, init=2) #NOTE 2 not for ping-pong, but for 2 CT + self.D_in_con_lock = aie.lock(self.ct, lock_id=7, init =0) + + + + + self.glu_request_router_send_lock = aie.lock(self.ct, lock_id=12, init=0) + + + self.glu = aie.external_func("glu", [ + self.top_k_expert_score_ty, self.top_k_expert_index_ty, + self.hid_ty, self.D_out_ty, self.hidden_state_ty, self.shared_expert_output_ty, + self.up_gate_ty, self.up_gate_ty, self.to_proj_x_slice_with_pkt_ty, self.to_proj_x_slice_with_pkt_ty + ]) + + self.__call__() + + def __call__(self): + @aie.core(self.ct, link_with = self.link_with, stack_size = self.stack_size) + def core_body(): + for _ in range_(0xFFFFFFFF): + self.glu(self.top_k_expert_score_buffer, self.top_k_expert_index_buffer, + self.intermediate_buffer, self.D_mlp_final_to_rms, self.D_in_buffer, self.shared_expert_output_buffer, + self.glu_slice_in_buffer_0, self.glu_slice_in_buffer_1, + self.to_proj_x_slice_with_pkt_buffer_0, self.to_proj_x_slice_with_pkt_buffer_1 + ) + + @aie.mem(self.ct) + def mem_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest=block[1], chain=block[3]) + with block[1]: + lock_acquire(self.glu_slice_prod_lock, 1) + aie.dma_bd(self.glu_slice_in_buffer_0) + lock_release(self.glu_slice_con_lock, 1) + aie.next_bd(block[2]) + + with block[2]: + lock_acquire(self.glu_slice_prod_lock, 1) + aie.dma_bd(self.glu_slice_in_buffer_1) + lock_release(self.glu_slice_con_lock, 1) + aie.next_bd(block[1]) + + with block[3]: + s2 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest = block[4], chain = block[6]) + + with block[4]: # x, to mt + lock_acquire(self.to_proj_x_slice_cons_lock, 1) + aie.dma_bd(self.to_proj_x_slice_with_pkt_buffer_0, offset=14, len=self.to_proj_x_slice_with_pkt_buf_size) + lock_release(self.to_proj_x_slice_prod_lock, 1) + aie.next_bd(block[5]) + + with block[5]: # x, to mt + lock_acquire(self.to_proj_x_slice_cons_lock, 1) + aie.dma_bd(self.to_proj_x_slice_with_pkt_buffer_1,offset=14, len=self.to_proj_x_slice_with_pkt_buf_size) + lock_release(self.to_proj_x_slice_prod_lock, 1) + aie.next_bd(block[4]) + + with block[6]: + s3 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 1, dest=block[7], chain=block[8]) + with block[7]: + lock_acquire(self.D_out_cons_lock, 1) + aie.dma_bd_packet(0, rms_pkt_id.from_glu) + aie.dma_bd(self.D_mlp_final_to_rms) + lock_release(self.D_out_prod_lock, 1) + aie.next_bd(block[7]) + + with block[8]: + s4 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index =1, dest=block[9], chain=block[10]) + with block[9]: + lock_acquire(self.D_in_prod_lock, value=2) + aie.dma_bd(self.D_in_buffer) + lock_release(self.D_in_con_lock, value=2) + aie.next_bd(block[9]) + with block[10]: + aie.EndOp() + + @property + def Up_Gate_in(self) -> dma_port: + return self.S2MM[0] + + @property + def D_in(self): + return self.S2MM[1] + + @property + def Intermediate_out(self) -> dma_port: + return self.MM2S[0] + + + @property + def D_out(self): + return self.MM2S[1] \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/layer_aie.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/layer_aie.py new file mode 100644 index 000000000..f2730cabc --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/layer_aie.py @@ -0,0 +1,219 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import numpy as np +import sys +import os + +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import get_model_config +from iron.models import * + +from constants import * + +import aie.dialects.aie as aie +from aie.dialects.aie import WireBundle, packetflow +from aie.extras.context import mlir_mod_ctx + +from utils import generate_tile_map, mlir_context, connect_port +from proj_tile import q4_proj_engine, ENABLE_CHESSCC +from rms_residual import rms_residual_tile +from aux_memtile import aux_memtile +from router_w_memtile import router_w_memtile +from glu import glu_tile +from RoPE import RoPE +from attn import attn_block +from router_tile import Router_tile +from router_helper import router_helper +from gate import gate_tile + +# One attention + MoE decoder layer for one token. +# +# col 0 col 1 col 2 col 3 col 4 col 5 col 6 col 7 +# row 5 proj proj - attn kv (CU1) attn kv (CU3) GLU proj proj +# row 4 proj proj output gate attn qk (CU1) attn qk (CU3) router proj proj +# row 3 proj proj RoPE attn kv (CU0) attn kv (CU2) router helper proj proj +# row 2 proj proj rms+residual attn qk (CU0) attn qk (CU2) - proj proj +# MT gather proj aux KV, O join KV, O half router w 0-127 gather proj w +# IT w w x/norms/rope KV (heads 0,1) KV (heads 2,3) router w w w +# O tap (opt.) (128-159 direct +# to the helper) + +def flow_arch(model_type: str, attn_tap: bool = False, debug_tap: str = ""): + dev = aie.AIEDevice.npu2 + total_cols = 8 + total_rows = 4 + # control packet ids the router uses to patch the expert weight BDs of + # shim 0, 1, 6, 7 (one per proj column), and to read shim 6 back + IT_CONTROL_packet_list = [29, 25,-1, -1, -1, -1, 22, 31 ] + IT_CONTRO_response_list = [-1,-1, -1, -1, -1, -1, 30, -1] + model_config = get_model_config(model_type) + print(f"// model_config: {model_config}") + with mlir_mod_ctx() as mctx: + @aie.device(dev) + def device_body(): + IT, MT, CT = generate_tile_map(total_rows + 2, total_cols) + + ctx = mlir_context() + ctx.data_ty('L_ty', (16,), np.dtype[np.int32]) # for all RTP requests + ctx.parameter('router_weight_row_block', 32) + ctx.parameter("router_weight_col_block", value=256) + + CT_from_shimtile_control_bd_port = 1 + CT_to_shimtile_control_bd_port = 1 + + ctx.parameter("CT_from_shimtile_control_bd_port", CT_from_shimtile_control_bd_port) + ctx.parameter("CT_to_shimtile_control_bd_port", CT_to_shimtile_control_bd_port) + # Instantiate IPs with single CT/MT + rms_core = rms_residual_tile(CT[0][2], ctx, model_config, stack_size = 1024 * 8, link_with = model_config.rms_residual_link_with) + rope_core = RoPE(CT[1][2], ctx, model_config, stack_size = 1024 * 4, link_with = model_config.rope_link_with) + glu = glu_tile(CT[3][5], ctx, model_config, stack_size = 20 * 1024, link_with = model_config.glu_link_with) + # o_in = attn_out * sigmoid(x @ W_gate): logits from the proj engine, O from attention + gate_core = gate_tile(CT[2][2], ctx, model_config, stack_size = 1024 * 4, link_with = "gate.o") + + router = Router_tile( + CT[2][5], + ctx=ctx, model_config=model_config, stack_size=12*1024, + up_neighbor_top_k_expert_score_buffer_ty=glu.top_k_expert_score_ty, + up_neighbor_top_k_expert_index_buffer_ty=glu.top_k_expert_index_ty, + up_neighbor_top_k_expert_score_buffer=glu.top_k_expert_score_buffer, + up_neighbor_top_k_expert_index_buffer=glu.top_k_expert_index_buffer, + up_neighbor_hidden_state_in_buffer=glu.D_in_buffer, + up_neighbor_hidden_state_in_buffer_ty=glu.hidden_state_ty, + up_neighbor_share_expert_output_buffer = glu.shared_expert_output_buffer, + up_neighbor_share_expert_output_buffer_ty = glu.shared_expert_output_ty, + link_with="router.o" + ) + # works in the router's memory, so it must sit right below the router + router_helper_core = router_helper(CT[1][5], ctx, model_config, router, stack_size = 1024 * 14, link_with = "router_helper.o") + aux_mt = aux_memtile(MT[2], ctx, model_config) + router_w_mt = router_w_memtile(MT[5], ctx, model_config) + + # Instantiate IPs with multiple CTs/MTs + proj_cores = [] + proj_assemble_mts = [] + proj_shim_tiles = [] + for col in [0, 1, 6, 7]: + proj_cores_col = [] + for row in range(0, 4): + proj_cores_col.append(CT[row][col]) + proj_cores.append(proj_cores_col) + proj_assemble_mts.append(MT[col]) + proj_shim_tiles.append(IT[col]) + # proj core stack 4 KB: every proj function has a 0-byte stack frame (core_0_2.elf.map), + # and the 4 KB went to data memory (4-block weight ring + int8 x cache) + # Peano: 6 KB, its frames are real (deepest chain 4480 B); see README.md, "Peano" + proj_stack = 4 * 1024 if ENABLE_CHESSCC else 6 * 1024 + proj_engine = q4_proj_engine(proj_cores, proj_assemble_mts, proj_shim_tiles, proj_stack, ["proj_main.o", "proj.o"], ctx, model_config) + + # attention: 2 columns x 2 CUs, one KV head per CU. Column 3 holds + # KV heads 0, 1 and gathers O; column 4 holds KV heads 2, 3. + # O goes once to the gate tile, which sends the gated O to o_proj + # once per row-block round of a proj core. + _attn = attn_block( + main_column = dict(attn_qk_tiles = [CT[0][3], CT[2][3]], attn_kv_tiles = [CT[1][3], CT[3][3]], + memtile = MT[3], shim_tile = IT[3]), + second_column = dict(attn_qk_tiles = [CT[0][4], CT[2][4]], attn_kv_tiles = [CT[1][4], CT[3][4]], + memtile = MT[4], shim_tile = IT[4]), + model_config = model_config, + ctx = ctx, + qk_stack_size = 1024, + kv_stack_size = 1024 if ENABLE_CHESSCC else 4 * 1024, # Peano: attn_fv's frame is 2 KB + qk_link_with = model_config.attn_qk_link_with, + kv_link_with = model_config.attn_kv_link_with, + o_sends = 1, + o_pkt_id = None, + tap = attn_tap, + ) + + # Connect all DMAs, the order of connection matters. + # Long connection has higher priority in routing. + connect_port(IT[2].MM2S[0], rms_core.X_in, pkt_id = it1_pkt_id.to_rms, keep_pkt_header = False) + connect_port(IT[2].MM2S[1], rms_core.W_in, pkt_id = it1_pkt_id.to_rms, keep_pkt_header = False) + connect_port(IT[2].MM2S[0], rope_core.ROPE_in, pkt_id = it1_pkt_id.to_rope, keep_pkt_header = False) + + # x for the proj engine: senders merge by packet id into MT1's x input, + # and MT1 broadcasts it to all 16 proj cores over one circuit + # (as in Gemma4 and Qwen3.5 decoding) + connect_port(rms_core.Y_out, proj_engine.X_in, pkt_id = rms_pkt_id.to_proj, keep_pkt_header = False) + # GLU -> proj, one id: shared expert h and routed up/gate x (all cores + # use it), and the 4 routed experts' h (each column keeps its own slices) + connect_port(glu.Intermediate_out, proj_engine.X_in, pkt_id = proj_x_pkt_id.from_glu, keep_pkt_header = False) + + # control packets: router -> shim tile control ports, and the read-back + for idx, val in enumerate(IT_CONTROL_packet_list): + if val != -1: + packetflow( + val, + router.ct, WireBundle.DMA, CT_to_shimtile_control_bd_port, + IT[idx].st, WireBundle.TileControl, 0 + ) + for idx, val in enumerate(IT_CONTRO_response_list): + if val != -1: + packetflow( + val, + IT[idx].st, WireBundle.TileControl, 0, + router.ct, WireBundle.DMA, CT_from_shimtile_control_bd_port + ) + proj_engine.route() + + connect_port(proj_engine.Y_out, aux_mt.X_in, pkt_id = proj_pkt_id.to_aux, keep_pkt_header = False) + + # Q packet ROPE_Q_PKT_ID_BASE + i -> attention CU i + for i, q_in in enumerate(_attn.Q_in): + connect_port(rope_core.Q_out, q_in, pkt_id=ROPE_Q_PKT_ID_BASE + i, keep_pkt_header=False) + + connect_port(rope_core.KV_out, IT[3].S2MM[0]) + + connect_port(proj_engine.Y_out, aux_mt.GLU_IN, pkt_id = proj_pkt_id.to_glu, keep_pkt_header = False) + connect_port(aux_mt.GLU_out, glu.Up_Gate_in) + + connect_port(glu.D_out, rms_core.X_in, pkt_id=rms_pkt_id.from_glu, keep_pkt_header=False) + + connect_port(proj_engine.Y_out, rope_core.QKV_in, pkt_id = proj_pkt_id.to_rope, keep_pkt_header = False) + + # output gate: logits from the proj engine, attention output, gated O -> o_proj + connect_port(proj_engine.Y_out, gate_core.Gate_In, pkt_id = proj_pkt_id.to_gate, keep_pkt_header = False) + connect_port(_attn.O_out, gate_core.Attn_In) + connect_port(gate_core.Attn_Out, proj_engine.X_in, pkt_id = proj_x_pkt_id.from_attn, keep_pkt_header = False) + + # layer output back to the host + connect_port(rms_core.Y_out, IT[2].S2MM[1], pkt_id = rms_pkt_id.to_st, keep_pkt_header = False) + + connect_port(IT[5].MM2S[0], router_w_mt.W_in, pkt_id = router_w_pkt_id.to_router_w, keep_pkt_header=False) + + # proj results (o_proj, shared down) -> rms. It can land on the same arbiter + # as x packets into MT1 (a wait loop: every call hung). The router's choice + # changes from run to run, so no order here guarantees anything; the build + # reruns aiecc until check_routes.py passes (makefiles/bitstream.mk). + connect_port(aux_mt.OUT, rms_core.X_in, pkt_id = it1_pkt_id.to_rms, keep_pkt_header = False) + + _attn.route() + + connect_port(rms_core.Y_out, glu.D_in, pkt_id=rms_pkt_id.to_glu, keep_pkt_header=False) + + # DEBUG ONLY (debug_tap == "x"): copy rms's x (to proj) to IT4 S2MM 0, + # to see whether rms sends it + if debug_tap == "x": + connect_port(rms_core.Y_out, IT[4].S2MM[0], pkt_id = rms_pkt_id.to_proj, keep_pkt_header = False) + connect_port(router_w_mt.W_out, router.router_w_in) + # experts 64..127 -> router helper, in parallel with the router's half + connect_port(router_w_mt.W2_out, router_helper_core.w_in) + # experts 128..159 do not fit in MT5: shim 5's second channel streams + # them straight to the router helper + connect_port(IT[5].MM2S[1], router_helper_core.w2_in) + + # attention tap (ATTN_TAP=1 build): O copy -> IT3 S2MM 1 + if attn_tap: + connect_port(_attn.TAP_out, IT[3].S2MM[1]) + + print(mctx.module) + +if __name__ == "__main__": + if len(sys.argv) not in (2, 3, 4): + print("Usage: python layer_aie.py [attn_tap 0|1] [debug_tap], Options: MINICPM5_15B_A2_5B") + sys.exit(1) + flow_arch(sys.argv[1], attn_tap = len(sys.argv) >= 3 and sys.argv[2] == "1", + debug_tap = sys.argv[3] if len(sys.argv) == 4 else "") diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/model_config.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/model_config.py new file mode 100644 index 000000000..67758c293 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/model_config.py @@ -0,0 +1,175 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +from typing import Dict +from .constants import ModelArch, ModelArchNames, QuantType +from abc import ABCMeta + +_MODEL_CONFIG_REGISTRY: Dict[str, type['ModelConfig']] = {} + +class ModelConfig(metaclass=ABCMeta): + """ + Model configuration for the model. + """ + # From external config + name: str + num_heads: int + num_kv_heads: int + intermediate_size: int + hidden_size: int + vocab_size: int + head_dim: int + q_heads_padding: int + glu_slice: int + has_qk_norm: bool + has_attn_bias: bool + kv_head_per_cu: int + + + num_experts: int + num_active_experts: int + num_shared_experts: int + + q4nx_row_block_size: int + q4nx_col_block_size: int + q4nx_group_size: int + + # self computed values + DQ: int + DK: int + DV: int + + # convenience values + D: int + NH: int + DH: int + + PADDED_DQ: int + NUM_Q_HEADS_PADDED: int + # W_BLOCK_SIZE is size of bytes / sizeof(bf16) + W_BLOCK_SIZE: int + + x_slice_size: int = 256 + + lq: int = 16 + lk: int = 16 + + num_proj_column = 4 + + rms_residual_link_with: str = "rms_residual.o" + rope_link_with: str = "rope.o" + glu_link_with: str = "glu.o" + attn_qk_link_with: str = "attn_qk.o" + attn_kv_link_with: str = "attn_kv.o" + @staticmethod + def _q4_1_size(elems: int) -> int: + return int(elems * 5 // 8) + @staticmethod + def _q4_k_size(elems: int) -> int: + # 4 bits of quant per weight, a uint8 scale and a uint8 min per group of + # 32, and a bf16 S / bf16 M per super-block of 256: 4.625 bits per weight. + return int(elems * 4.625 // 8) + @staticmethod + def _q8_0_size(elems: int) -> int: + return int(elems * 8.5 // 8) + + def __init__( + self, + name: str, + num_heads: int, + num_kv_heads: int, + intermediate_size: int, + hidden_size: int, + glu_slice: int, + vocab_size: int, + head_dim: int, + kv_head_per_cu: int, + num_attn_cus: int, + PROJ_QUANT_TYPE: QuantType, + num_experts: int = 256, + num_active_experts: int = 8, + num_shared_experts: int = 1, + rope_partial_factor: float = 1.0, + q_heads_padding: int = 4, + has_qk_norm: bool = False, + has_attn_bias: bool = False, + q4nx_row_block_size: int = 32, + q4nx_col_block_size: int = 256, + q4nx_group_size: int = 32, + rms_residual_link_with: str = "rms_residual.o", + rope_link_with: str = "rope.o", + glu_link_with: str = "glu.o", + attn_qk_link_with: str = "attn_qk.o", + attn_kv_link_with: str = "attn_kv.o" + ): + self.name = name + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.intermediate_size = intermediate_size + self.hidden_size = hidden_size + self.glu_slice = glu_slice + self.vocab_size = vocab_size + self.head_dim = head_dim + self.has_qk_norm = has_qk_norm + self.has_attn_bias = has_attn_bias + self.q_heads_padding = q_heads_padding + self.kv_head_per_cu = kv_head_per_cu + + self.q4nx_row_block_size = q4nx_row_block_size + self.q4nx_col_block_size = q4nx_col_block_size + self.q4nx_group_size = q4nx_group_size + + self.DQ = num_heads * head_dim + self.DK = num_kv_heads * head_dim + self.DV = num_kv_heads * head_dim + + self.ROPE_DIM = int(head_dim * rope_partial_factor) + + kv_groups = num_heads // num_kv_heads + self.PADDED_DQ = ((kv_groups + self.q_heads_padding - 1) // self.q_heads_padding * self.q_heads_padding) * num_kv_heads * head_dim + self.NUM_Q_HEADS_PADDED = self.PADDED_DQ // head_dim + self.ATTN_ROUNDS = self.num_kv_heads // self.kv_head_per_cu + self.Q_HEAD_PER_ROUND = self.num_heads // self.ATTN_ROUNDS + self.Q_HEAD_PER_ROUND_PADDED = self.NUM_Q_HEADS_PADDED // self.ATTN_ROUNDS + if PROJ_QUANT_TYPE == QuantType.Q4_K: + self.W_BLOCK_SIZE = ModelConfig._q4_k_size(self.q4nx_row_block_size * self.q4nx_col_block_size) // 2 + elif PROJ_QUANT_TYPE == QuantType.Q4_1: + self.W_BLOCK_SIZE = ModelConfig._q4_1_size(self.q4nx_row_block_size * self.q4nx_col_block_size) // 2 + elif PROJ_QUANT_TYPE == QuantType.Q8_0: + self.W_BLOCK_SIZE = ModelConfig._q8_0_size(self.q4nx_row_block_size * self.q4nx_col_block_size) // 2 + + self.num_attn_cus = num_attn_cus + + self.D = hidden_size + self.NH = num_heads + self.DH = head_dim + + self.rms_residual_link_with = rms_residual_link_with + self.rope_link_with = rope_link_with + self.glu_link_with = glu_link_with + self.attn_qk_link_with = attn_qk_link_with + self.attn_kv_link_with = attn_kv_link_with + + self.num_experts = num_experts + self.num_active_experts = num_active_experts + self.num_shared_experts = num_shared_experts + + # do check + # all input must be multiple of x_slice_size + if self.D % self.x_slice_size != 0: + raise ValueError(f"D must be multiple of {self.x_slice_size}, got {self.D}") + if self.DQ % self.x_slice_size != 0: + raise ValueError(f"DQ must be multiple of {self.x_slice_size}, got {self.DQ}") + if self.intermediate_size % self.x_slice_size != 0: + raise ValueError(f"intermediate_size must be multiple of {self.x_slice_size}, got {self.intermediate_size}") + + def __init_subclass__(cls, model_arch: ModelArch, **kwargs): + super().__init_subclass__(**kwargs) + _MODEL_CONFIG_REGISTRY[ModelArchNames[model_arch]] = cls + + def __str__(self): + return f"ModelConfig(name={self.name}, num_heads={self.num_heads}, num_kv_heads={self.num_kv_heads}, intermediate_size={self.intermediate_size}, hidden_size={self.hidden_size}, vocab_size={self.vocab_size}, head_dim={self.head_dim}, q4nx_row_block_size={self.q4nx_row_block_size}, q4nx_col_block_size={self.q4nx_col_block_size}, q4nx_group_size={self.q4nx_group_size})" + +def get_model_config(ModelName: str) -> ModelConfig: + if ModelName not in _MODEL_CONFIG_REGISTRY: + raise ValueError(f"Model {ModelName} not found") + return _MODEL_CONFIG_REGISTRY[ModelName]() \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/models/__init__.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/models/__init__.py new file mode 100644 index 000000000..fea3eb8c8 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/models/__init__.py @@ -0,0 +1,7 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +from .minicpm5 import minicpm5_15b_a2_5b_config +__all__ = [ + "minicpm5_15b_a2_5b_config" +] diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/models/minicpm5.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/models/minicpm5.py new file mode 100644 index 000000000..ae083f330 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/models/minicpm5.py @@ -0,0 +1,28 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +from ..model_config import ModelConfig +from ..constants import ModelArch, QuantType + +class minicpm5_15b_a2_5b_config(ModelConfig, model_arch=ModelArch.MINICPM5_15B_A2_5B): + def __init__(self): + super().__init__( + name = "minicpm5_15b_a2_5b", + num_heads = 32, + # 2 KV heads, duplicated to 4 on the host (see models/minicpm5-15b-a2.5b.h) + num_kv_heads = 4, + # experts and shared expert are 512 wide; one GLU slice = one proj round of 512 + intermediate_size = 512, + hidden_size = 2048, + glu_slice = 512, + vocab_size = 130560, + head_dim = 128, + # 4 attention CUs (2 columns x 2), one KV head each + kv_head_per_cu = 1, + num_attn_cus = 4, + rope_partial_factor = 1.0, + has_qk_norm = False, + PROJ_QUANT_TYPE = QuantType.Q4_K, + num_experts = 160, + num_active_experts = 16, + ) diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/proj_tile.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/proj_tile.py new file mode 100644 index 000000000..47c287ca7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/proj_tile.py @@ -0,0 +1,916 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +import numpy as np +import sys +import os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig +from aie.extras.dialects.ext.arith import constant, index_cast +import aie.dialects.aie as aie +from aie.helpers.dialects.ext.scf import _for as range_ +from ml_dtypes import bfloat16 + +import threading +from utils import mlir_context, tile_with_location, connect_dma, dma_port, connect_port, lock_acquire, lock_release, comment_print, ShimTile +from utils import AIE_CT_IP, AIE_MT_IP + +from constants import proj_pkt_id + +from typing import Any, List +from aie.ir import IntegerAttr, IntegerType + +# Mirrors the makefiles' ENABLE_CHESSCC switch (1 = chess, 0 = Peano). +ENABLE_CHESSCC = os.environ.get("ENABLE_CHESSCC", "0") == "1" +BANK = 16 * 1024 + + +def peano_proj_bank_plan(stack_size: int, w_bytes: int, y_bytes: int, x_bytes: int) -> list: + """Peano layout of a proj core: (buffer, bank, bytes), in placement order. + + Peano's linker puts .data / .bss only after the highest buffer, so the int8 + x caches of proj_main.cc (20 KB) need one free block there. w, x and y go + into banks 0 and 1, and a pad pushes bank 1's last buffer to the bank's + end, which leaves banks 2 and 3 to the caches (the inner loop reads them + together with w). Only the bank is pinned: this mlir-aie's bank-aware + allocator counts a buffer pinned by address twice. See README.md, "Peano". + """ + pad = BANK - w_bytes - y_bytes - x_bytes + assert stack_size + w_bytes + x_bytes + y_bytes <= BANK, "proj bank 0 overflow" + assert pad >= 0 and (BANK - x_bytes) % 64 == 0 + return [("w_0", 0, w_bytes), ("x_0", 0, x_bytes), ("y_0", 0, y_bytes), + ("w_1", 1, w_bytes), ("pad", 1, pad), ("y_1", 1, y_bytes), ("x_1", 1, x_bytes)] + +# phase 1: qkv proj, D -> (D + D // 2) to RoPE + +# phase 2: o_proj, D -> D to rms_residual + +# phase 3: up/gate proj, D -> D * 8 to MT_GLU + +# phase 4: down proj, D * 4 -> D, to rms_residual + +# minimal output unit: (m, 1) + +class proj_tile_main(AIE_CT_IP): + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig, stack_size: int = 1024, link_with: str = "proj_main.o", + send_x_out:bool=True, main_y_buffer_0:Any|None= None, main_y_buffer_1:Any|None=None, + col_idx: int = 0 + ): + + """ + send_x_out: boolean determine of this CT sends the output x to mt + + For context: 2CT are group into one mvm unit produce length of 2*m output, but only CT with send_x_out=True responsible sending the output to MT + + IF `send_x_out`==False, this CT writes the output to `main_y_buffer_0` and `main_y_buffer_1`, the output buffer are buffer allocate in its neighbor CT that has `send_x_out`=True + """ + super().__init__(tile, stack_size = stack_size, link_with = link_with) + comment_print(f"Initializing proj_tile at ({tile.row}, {tile.col})") + + self.send_x_out = send_x_out + # which of the 4 proj columns this core is in (0..3): in the routed-expert + # down step every core receives all 4 experts' x and keeps only its own + self.col_idx = col_idx + + self.m = model_config.q4nx_row_block_size + self.x_slice_size = model_config.x_slice_size + + self.x_slice_ty = np.ndarray[(self.x_slice_size,), np.dtype[bfloat16]] + # 2 weight blocks per buffer, 2 buffers: a 4-block ring (kernels/proj_main.cc W_RING_BLOCKS) + self.w_block = model_config.W_BLOCK_SIZE + self.linear_w_ty = np.ndarray[(2 * model_config.W_BLOCK_SIZE,), np.dtype[bfloat16]] + self.m_pkt_ty = np.ndarray[(2 * self.m + 16,), np.dtype[bfloat16]] + + types = {"x_0": self.x_slice_ty, "x_1": self.x_slice_ty, "w_0": self.linear_w_ty, + "w_1": self.linear_w_ty, "y_0": self.m_pkt_ty, "y_1": self.m_pkt_ty} + bufs = {} + if ENABLE_CHESSCC: + # the original declaration order; the allocator's layout depends on it + for kind in ["x_0", "w_0", "x_1", "w_1", "y_0", "y_1"]: + bufs[kind] = ctx.buffer(tile = self.located_tile, dtype = types[kind], + name = f"{kind}_{self.ct_row}_{self.ct_col}") + else: + i32 = IntegerType.get_signless(32) + plan = peano_proj_bank_plan(self.stack_size, 2 * 2 * self.w_block, 2 * (2 * self.m + 16), 2 * self.x_slice_size) + for kind, bank, nbytes in plan: + ty = types.get(kind, np.ndarray[(nbytes,), np.dtype[np.int8]]) + b = ctx.buffer(tile = self.located_tile, dtype = ty, name = f"{kind}_{self.ct_row}_{self.ct_col}") + b.owner.attributes["mem_bank"] = IntegerAttr.get(i32, bank) + bufs[kind] = b + + self.x_buffer_0 = bufs["x_0"] + self.w_buffer_0 = bufs["w_0"] + self.x_buffer_1 = bufs["x_1"] + self.w_buffer_1 = bufs["w_1"] + + if send_x_out: + self.y_buffer_0 = bufs["y_0"] + self.y_buffer_1 = bufs["y_1"] + else: + assert main_y_buffer_0 is not None + self.y_buffer_0 = main_y_buffer_0 + assert main_y_buffer_1 is not None + self.y_buffer_1 = main_y_buffer_1 + + # allocate fake buffer for the sake of same rtp address + # or use a different addressing mode + self._y_0 = bufs["y_0"] + self._y_1 = bufs["y_1"] + self.x_prod_lock = aie.lock(self.ct, lock_id = 0, init = 2) + self.x_cons_lock = aie.lock(self.ct, lock_id = 1, init = 0) + self.w_prod_lock = aie.lock(self.ct, lock_id = 2, init = 4) # 4 one-block slots + self.w_cons_lock = aie.lock(self.ct, lock_id = 3, init = 0) + self.y_prod_ping_lock = aie.lock(self.ct, lock_id = 4, init = 2) + self.y_prod_pong_lock = aie.lock(self.ct, lock_id = 5, init = 2) + self.rtp_available_lock = aie.lock(self.ct, lock_id = 6, init = 0) + self.y_cons_ping_lock = aie.lock(self.ct, lock_id = 7, init = 0) + self.y_cons_pong_lock = aie.lock(self.ct, lock_id = 8, init = 0) + + self.proj = ctx.func("proj_main", [self.m_pkt_ty, self.linear_w_ty, self.x_slice_ty, self.m_pkt_ty, self.linear_w_ty, self.x_slice_ty, np.int32, np.int32]) + + self.__call__() + + def __call__(self): + @aie.core(self.ct, link_with = self.link_with, stack_size = self.stack_size) + def core_body(): + for _ in range_(0xFFFFFFFF): + if self.send_x_out: + self.proj(self.y_buffer_0, self.w_buffer_0, self.x_buffer_0, self.y_buffer_1, self.w_buffer_1, self.x_buffer_1, constant(1), constant(self.col_idx)) + else: + self.proj(self.y_buffer_0, self.w_buffer_0, self.x_buffer_0, self.y_buffer_1, self.w_buffer_1, self.x_buffer_1, constant(0), constant(self.col_idx)) + + @aie.mem(self.ct) + def mem_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest=block[1], chain=block[3]) + with block[1]: + lock_acquire(self.x_prod_lock, 1) + aie.dma_bd(self.x_buffer_0) + lock_release(self.x_cons_lock, 1) + aie.next_bd(block[2]) + + with block[2]: + lock_acquire(self.x_prod_lock, 1) + aie.dma_bd(self.x_buffer_1) + lock_release(self.x_cons_lock, 1) + aie.next_bd(block[1]) + + with block[3]: + s1 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest=block[20], chain=block[6]) + + # weight ring: one block per BD, w_buffer_0 [0], [1], w_buffer_1 [0], [1] + slots = [(self.w_buffer_0, 0), (self.w_buffer_0, 1), (self.w_buffer_1, 0), (self.w_buffer_1, 1)] + for k, (buf, half) in enumerate(slots): + with block[20 + k]: + lock_acquire(self.w_prod_lock, 1) + aie.dma_bd(buf, offset = half * self.w_block, len = self.w_block) + lock_release(self.w_cons_lock, 1) + aie.next_bd(block[20 + (k + 1) % len(slots)]) + if self.send_x_out: + with block[6]: + s2 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest = block[7], chain = block[9]) + + with block[7]: # x, to mt + lock_acquire(self.y_cons_ping_lock, 2) + aie.dma_bd(self.y_buffer_0, offset = 14, len = 2 * self.m + 2) + lock_release(self.y_prod_ping_lock, 2) + aie.next_bd(block[8]) + + + with block[8]: # x, to mt + lock_acquire(self.y_cons_pong_lock, 2) + aie.dma_bd(self.y_buffer_1, offset = 14, len = 2 * self.m + 2) + lock_release(self.y_prod_pong_lock, 2) + aie.next_bd(block[7]) + + with block[9]: + aie.EndOp() + else: + with block[6]: + aie.EndOp() + + @property + def y_buffer_ping(self): + return self.y_buffer_0 + + @property + def y_buffer_pong(self): + return self.y_buffer_1 + + @property + def w_in(self): + return self.S2MM[1] + + @property + def x_in(self): + return self.S2MM[0] + + @property + def y_out(self): + return self.MM2S[0] + +# return self.S2MM[0] + +class proj_combo: + def __init__(self, cts: List[tile_with_location], ctx, model_config: ModelConfig, stack_size: int = 1024, link_with: List[str] = ["proj_main.o"], + col_idx: int = 0): + self.proj_main = proj_tile_main(tile=cts[0],ctx= ctx, model_config=model_config,stack_size= stack_size,link_with= link_with[0], send_x_out=True, + col_idx=col_idx) + + + self.proj = proj_tile_main(tile=cts[1], ctx=ctx, model_config=model_config, stack_size=stack_size, + link_with=link_with[0], send_x_out=False, main_y_buffer_0=self.proj_main.y_buffer_ping, main_y_buffer_1=self.proj_main.y_buffer_pong, + col_idx=col_idx + + ) + + @property + def w_in_0(self): + return self.proj_main.w_in + @property + def x_in_0(self): + return self.proj_main.x_in + @property + def w_in_1(self): + return self.proj.w_in + @property + def x_in_1(self): + return self.proj.x_in + @property + def y_out(self): + return self.proj_main.y_out + +class proj_assemble_col(AIE_MT_IP): + + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig): + super().__init__(tile) + comment_print(f"Initializing proj_assemble_col at ({tile.row}, {tile.col})") + + self.m = model_config.q4nx_row_block_size + self.w_block_size = model_config.W_BLOCK_SIZE + self.m_col_ty = np.ndarray[(8 * self.m + 2,), np.dtype[bfloat16]] + self.linear_4w_ty = np.ndarray[(4 * model_config.W_BLOCK_SIZE,), np.dtype[bfloat16]] + comment_print(f"proj_assemble_col m: {self.m}") + comment_print(f"proj_assemble_col w_block_size: {self.w_block_size}") + + self.y_buffer_0 = aie.buffer(self.mt, self.m_col_ty, name = f"y_buffer_0_{self.mt_row}_{self.mt_col}") + self.y_buffer_1 = aie.buffer(self.mt, self.m_col_ty, name = f"y_buffer_1_{self.mt_row}_{self.mt_col}") + + self.w_buffer_0 = aie.buffer(self.mt, self.linear_4w_ty, name = f"w_buffer_0_{self.mt_row}_{self.mt_col}") + self.w_buffer_1 = aie.buffer(self.mt, self.linear_4w_ty, name = f"w_buffer_1_{self.mt_row}_{self.mt_col}") + self.y_prod_lock_0 = aie.lock(self.mt, lock_id = 0, init = 2) + self.y_prod_lock_1 = aie.lock(self.mt, lock_id = 1, init = 0) + self.y_prod_lock_2 = aie.lock(self.mt, lock_id = 2, init = 0) + self.y_prod_lock_3 = aie.lock(self.mt, lock_id = 3, init = 0) + self.y_cons_lock = aie.lock(self.mt, lock_id = 4, init = 0) + self.w_p0_prod_lock = aie.lock(self.mt, lock_id = 5, init = 2) + self.w_p0_cons_lock_0 = aie.lock(self.mt, lock_id = 6, init = 0) + self.w_p0_cons_lock_1 = aie.lock(self.mt, lock_id = 7, init = 0) + self.w_p1_prod_lock = aie.lock(self.mt, lock_id = 8, init = 2) + self.w_p1_cons_lock_0 = aie.lock(self.mt, lock_id = 9, init = 0) + self.w_p1_cons_lock_1 = aie.lock(self.mt, lock_id = 10, init = 0) + self.__call__() + + @property + def y_in(self): + return [self.S2MM[i] for i in range(4)] + + @property + def y_out(self): + return self.MM2S[4] + + @property + def w_in(self): + return [self.S2MM[i] for i in range(4, 6)] + + @property + def w_out(self): + return [self.MM2S[i] for i in range(4)] + + def __call__(self): + @aie.memtile_dma(self.mt) + def memtile_dma_body(block): + s0 = aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest = block[1], chain = block[3]) + with block[1]: + lock_acquire(self.y_prod_lock_0, 1) + aie.dma_bd(self.y_buffer_0, offset = 0, len = 2 * self.m + 2) + lock_release(self.y_prod_lock_1, 1) + aie.next_bd(block[2]) + + with block[2]: + lock_acquire(self.y_prod_lock_0, 1) + aie.dma_bd(self.y_buffer_1, offset = 0, len = 2 * self.m + 2) + lock_release(self.y_prod_lock_1, 1) + aie.next_bd(block[1]) + + with block[3]: + s1 = aie.dma_start(aie.DMAChannelDir.S2MM, 1, dest = block[4], chain = block[6]) + + with block[4]: + lock_acquire(self.y_prod_lock_1, 1) + aie.dma_bd(self.y_buffer_0, offset = 2 * self.m + 2, len = 2 * self.m) + lock_release(self.y_prod_lock_2, 1) + aie.next_bd(block[5]) + + with block[5]: + lock_acquire(self.y_prod_lock_1, 1) + aie.dma_bd(self.y_buffer_1, offset = 2 * self.m + 2, len = 2 * self.m) + lock_release(self.y_prod_lock_2, 1) + aie.next_bd(block[4]) + + with block[6]: + s2 = aie.dma_start(aie.DMAChannelDir.S2MM, 2, dest = block[7], chain = block[9]) + + with block[7]: + lock_acquire(self.y_prod_lock_2, 1) + aie.dma_bd(self.y_buffer_0, offset = 4 * self.m + 2, len = 2 * self.m) + lock_release(self.y_prod_lock_3, 1) + aie.next_bd(block[8]) + + with block[8]: + lock_acquire(self.y_prod_lock_2, 1) + aie.dma_bd(self.y_buffer_1, offset = 4 * self.m + 2, len = 2 * self.m) + lock_release(self.y_prod_lock_3, 1) + aie.next_bd(block[7]) + + with block[9]: + s3 = aie.dma_start(aie.DMAChannelDir.S2MM, 3, dest = block[10], chain = block[12]) + + with block[10]: + lock_acquire(self.y_prod_lock_3, 1) + aie.dma_bd(self.y_buffer_0, offset = 6 * self.m + 2, len = 2 * self.m) + lock_release(self.y_cons_lock, 1) + aie.next_bd(block[11]) + + with block[11]: + lock_acquire(self.y_prod_lock_3, 1) + aie.dma_bd(self.y_buffer_1, offset = 6 * self.m + 2, len = 2 * self.m) + lock_release(self.y_cons_lock, 1) + aie.next_bd(block[10]) + + with block[12]: + s4 = aie.dma_start(aie.DMAChannelDir.S2MM, 4, dest = block[13], chain = block[15]) + + with block[13]: + lock_acquire(self.w_p0_prod_lock, 1) + aie.dma_bd(self.w_buffer_0, offset = 0, len = 2 * self.w_block_size) + lock_release(self.w_p0_cons_lock_0, 1) + aie.next_bd(block[14]) + + with block[14]: + lock_acquire(self.w_p0_prod_lock, 1) + aie.dma_bd(self.w_buffer_1, offset = 0, len = 2 * self.w_block_size) + lock_release(self.w_p0_cons_lock_0, 1) + aie.next_bd(block[13]) + + with block[15]: + aie.dma_start(aie.DMAChannelDir.MM2S, 0, dest = block[16], chain = block[18]) + + with block[16]: + lock_acquire(self.w_p0_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_0, offset = 0, len = self.w_block_size) + lock_release(self.w_p0_cons_lock_1, 1) + aie.next_bd(block[17]) + + with block[17]: + lock_acquire(self.w_p0_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_1, offset = 0, len = self.w_block_size) + lock_release(self.w_p0_cons_lock_1, 1) + aie.next_bd(block[16]) + + with block[18]: + aie.dma_start(aie.DMAChannelDir.MM2S, 1, dest = block[19], chain = block[21]) + + with block[19]: + lock_acquire(self.w_p0_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_0, offset = self.w_block_size, len = self.w_block_size) + lock_release(self.w_p0_prod_lock, 1) + aie.next_bd(block[20]) + + with block[20]: + lock_acquire(self.w_p0_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_1, offset = self.w_block_size, len = self.w_block_size) + lock_release(self.w_p0_prod_lock, 1) + aie.next_bd(block[19]) + + with block[21]: + aie.dma_start(aie.DMAChannelDir.MM2S, 2, dest = block[22], chain = block[24]) + + with block[22]: + lock_acquire(self.w_p1_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_0, offset = 2 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_cons_lock_1, 1) + aie.next_bd(block[23]) + + with block[23]: + lock_acquire(self.w_p1_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_1, offset = 2 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_cons_lock_1, 1) + aie.next_bd(block[22]) + + with block[24]: + aie.dma_start(aie.DMAChannelDir.MM2S, 3, dest = block[25], chain = block[27]) + + with block[25]: + lock_acquire(self.w_p1_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_0, offset = 3 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_prod_lock, 1) + aie.next_bd(block[26]) + + with block[26]: + lock_acquire(self.w_p1_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_1, offset = 3 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_prod_lock, 1) + aie.next_bd(block[25]) + + with block[27]: + aie.dma_start(aie.DMAChannelDir.MM2S, 4, dest = block[28], chain = block[30]) + + with block[28]: + lock_acquire(self.y_cons_lock, 1) + aie.dma_bd(self.y_buffer_0) + lock_release(self.y_prod_lock_0, 1) + aie.next_bd(block[29]) + + with block[29]: + lock_acquire(self.y_cons_lock, 1) + aie.dma_bd(self.y_buffer_1) + lock_release(self.y_prod_lock_0, 1) + aie.next_bd(block[28]) + + with block[30]: + aie.dma_start(aie.DMAChannelDir.S2MM, 5, dest = block[31], chain = block[33]) + + with block[31]: + lock_acquire(self.w_p1_prod_lock, 1) + aie.dma_bd(self.w_buffer_0, offset = 2 * self.w_block_size, len = 2 * self.w_block_size) + lock_release(self.w_p1_cons_lock_0, 1) + aie.next_bd(block[32]) + + with block[32]: + lock_acquire(self.w_p1_prod_lock, 1) + aie.dma_bd(self.w_buffer_1, offset = 2 * self.w_block_size, len = 2 * self.w_block_size) + lock_release(self.w_p1_cons_lock_0, 1) + aie.next_bd(block[31]) + + with block[33]: + aie.EndOp() + +class proj_assemble_weight_only(AIE_MT_IP): + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig): + super().__init__(tile) + comment_print(f"Initializing proj_assemble_col at ({tile.row}, {tile.col})") + + self.w_block_size = model_config.W_BLOCK_SIZE + self.linear_4w_ty = np.ndarray[(4 * model_config.W_BLOCK_SIZE,), np.dtype[bfloat16]] + comment_print(f"proj_assemble_col w_block_size: {self.w_block_size}") + + + self.w_buffer_0 = aie.buffer(self.mt, self.linear_4w_ty, name = f"w_buffer_0_{self.mt_row}_{self.mt_col}") + self.w_buffer_1 = aie.buffer(self.mt, self.linear_4w_ty, name = f"w_buffer_1_{self.mt_row}_{self.mt_col}") + self.w_p0_prod_lock = aie.lock(self.mt, lock_id = 5, init = 2) + self.w_p0_cons_lock_0 = aie.lock(self.mt, lock_id = 6, init = 0) + self.w_p0_cons_lock_1 = aie.lock(self.mt, lock_id = 7, init = 0) + self.w_p1_prod_lock = aie.lock(self.mt, lock_id = 8, init = 2) + self.w_p1_cons_lock_0 = aie.lock(self.mt, lock_id = 9, init = 0) + self.w_p1_cons_lock_1 = aie.lock(self.mt, lock_id = 10, init = 0) + + self.__call__() + + @property + def w_in(self): + return [self.S2MM[i] for i in range(4, 6)] + + @property + def w_out(self): + return [self.MM2S[i] for i in range(4)] + + + + def __call__(self): + @aie.memtile_dma(self.mt) + def memtile_dma_body(block): + s0 = aie.dma_start(aie.DMAChannelDir.S2MM, 4, dest = block[13], chain = block[15]) + + with block[13]: + lock_acquire(self.w_p0_prod_lock, 1) + aie.dma_bd(self.w_buffer_0, offset = 0, len = 2 * self.w_block_size) + lock_release(self.w_p0_cons_lock_0, 1) + aie.next_bd(block[14]) + + with block[14]: + lock_acquire(self.w_p0_prod_lock, 1) + aie.dma_bd(self.w_buffer_1, offset = 0, len = 2 * self.w_block_size) + lock_release(self.w_p0_cons_lock_0, 1) + aie.next_bd(block[13]) + + with block[15]: + aie.dma_start(aie.DMAChannelDir.MM2S, 0, dest = block[16], chain = block[18]) + + with block[16]: + lock_acquire(self.w_p0_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_0, offset = 0, len = self.w_block_size) + lock_release(self.w_p0_cons_lock_1, 1) + aie.next_bd(block[17]) + + with block[17]: + lock_acquire(self.w_p0_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_1, offset = 0, len = self.w_block_size) + lock_release(self.w_p0_cons_lock_1, 1) + aie.next_bd(block[16]) + + with block[18]: + aie.dma_start(aie.DMAChannelDir.MM2S, 1, dest = block[19], chain = block[21]) + + with block[19]: + lock_acquire(self.w_p0_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_0, offset = self.w_block_size, len = self.w_block_size) + lock_release(self.w_p0_prod_lock, 1) + aie.next_bd(block[20]) + + with block[20]: + lock_acquire(self.w_p0_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_1, offset = self.w_block_size, len = self.w_block_size) + lock_release(self.w_p0_prod_lock, 1) + aie.next_bd(block[19]) + + with block[21]: + aie.dma_start(aie.DMAChannelDir.MM2S, 2, dest = block[22], chain = block[24]) + + with block[22]: + lock_acquire(self.w_p1_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_0, offset = 2 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_cons_lock_1, 1) + aie.next_bd(block[23]) + + with block[23]: + lock_acquire(self.w_p1_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_1, offset = 2 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_cons_lock_1, 1) + aie.next_bd(block[22]) + + with block[24]: + aie.dma_start(aie.DMAChannelDir.MM2S, 3, dest = block[25], chain = block[30]) + + with block[25]: + lock_acquire(self.w_p1_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_0, offset = 3 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_prod_lock, 1) + aie.next_bd(block[26]) + + with block[26]: + lock_acquire(self.w_p1_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_1, offset = 3 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_prod_lock, 1) + aie.next_bd(block[25]) + + with block[30]: + aie.dma_start(aie.DMAChannelDir.S2MM, 5, dest = block[31], chain = block[33]) + + with block[31]: + lock_acquire(self.w_p1_prod_lock, 1) + aie.dma_bd(self.w_buffer_0, offset = 2 * self.w_block_size, len = 2 * self.w_block_size) + lock_release(self.w_p1_cons_lock_0, 1) + aie.next_bd(block[32]) + + with block[32]: + lock_acquire(self.w_p1_prod_lock, 1) + aie.dma_bd(self.w_buffer_1, offset = 2 * self.w_block_size, len = 2 * self.w_block_size) + lock_release(self.w_p1_cons_lock_0, 1) + aie.next_bd(block[31]) + + + with block[33]: + aie.EndOp() + +class proj_assemble_weight_x(AIE_MT_IP): + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig): + super().__init__(tile) + comment_print(f"Initializing proj_assemble_col at ({tile.row}, {tile.col})") + + self.w_block_size = model_config.W_BLOCK_SIZE + self.m = model_config.q4nx_row_block_size + self.linear_4w_ty = np.ndarray[(4 * model_config.W_BLOCK_SIZE,), np.dtype[bfloat16]] + comment_print(f"proj_assemble_col m: {self.m}") + comment_print(f"proj_assemble_col w_block_size: {self.w_block_size}") + + self.x_chunk_ty = np.ndarray[(model_config.x_slice_size * 2,), np.dtype[bfloat16]] + self.m_full_ty = np.ndarray[(16 * self.m + 2,), np.dtype[bfloat16]] + self.y_buffer_0 = ctx.buffer(tile = self.located_tile, dtype = self.m_full_ty, name = f"y_buffer_0_{self.mt_row}_{self.mt_col}") + self.y_buffer_1 = ctx.buffer(tile = self.located_tile, dtype = self.m_full_ty, name = f"y_buffer_1_{self.mt_row}_{self.mt_col}") + self.x_buffer_0 = ctx.buffer(tile = self.located_tile, dtype = self.x_chunk_ty, name = f"x_buffer_0_{self.mt_row}_{self.mt_col}") + self.x_buffer_1 = ctx.buffer(tile = self.located_tile, dtype = self.x_chunk_ty, name = f"x_buffer_1_{self.mt_row}_{self.mt_col}") + + + self.m_prod_lock_0 = aie.lock(self.mt, lock_id = 0, init = 2) + self.m_prod_lock_1 = aie.lock(self.mt, lock_id = 1, init = 0) + self.m_cons_lock = aie.lock(self.mt, lock_id = 2, init = 0) + self.x_prod_lock = aie.lock(self.mt, lock_id = 3, init = 2) + self.x_cons_lock = aie.lock(self.mt, lock_id = 4, init = 0) + + self.w_buffer_0 = aie.buffer(self.mt, self.linear_4w_ty, name = f"w_buffer_0_{self.mt_row}_{self.mt_col}") + self.w_buffer_1 = aie.buffer(self.mt, self.linear_4w_ty, name = f"w_buffer_1_{self.mt_row}_{self.mt_col}") + self.w_p0_prod_lock = aie.lock(self.mt, lock_id = 5, init = 2) + self.w_p0_cons_lock_0 = aie.lock(self.mt, lock_id = 6, init = 0) + self.w_p0_cons_lock_1 = aie.lock(self.mt, lock_id = 7, init = 0) + self.w_p1_prod_lock = aie.lock(self.mt, lock_id = 8, init = 2) + self.w_p1_cons_lock_0 = aie.lock(self.mt, lock_id = 9, init = 0) + self.w_p1_cons_lock_1 = aie.lock(self.mt, lock_id = 10, init = 0) + + self.__call__() + + @property + def w_in(self): + return [self.S2MM[i] for i in range(4, 6)] + + @property + def w_out(self): + return [self.MM2S[i] for i in range(4)] + + @property + def x_out(self): + return self.MM2S[4] + + @property + def x_in(self): + return self.S2MM[3] + + + @property + def y_out(self): + return self.MM2S[5] + + @property + def y_in(self): + return [self.S2MM[i] for i in range(2)] + + def __call__(self): + @aie.memtile_dma(self.mt) + def memtile_dma_body(block): + chain_id = 0 + s0 = aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest = block[chain_id + 1], chain = block[chain_id + 3]) + with block[chain_id + 1]: + lock_acquire(self.m_prod_lock_0, 1) + aie.dma_bd(self.y_buffer_0, offset = 0, len = 8 * self.m + 2) + lock_release(self.m_prod_lock_1, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.m_prod_lock_0, 1) + aie.dma_bd(self.y_buffer_1, offset = 0, len = 8 * self.m + 2) + lock_release(self.m_prod_lock_1, 1) + aie.next_bd(block[chain_id + 1]) + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.S2MM, 1, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.m_prod_lock_1, 1) + aie.dma_bd(self.y_buffer_0, offset = 8 * self.m + 2, len = 8 * self.m) + lock_release(self.m_cons_lock, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.m_prod_lock_1, 1) + aie.dma_bd(self.y_buffer_1, offset = 8 * self.m + 2, len = 8 * self.m) + lock_release(self.m_cons_lock, 1) + aie.next_bd(block[chain_id + 1]) + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.S2MM, 3, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.x_prod_lock, 1) + aie.dma_bd(self.x_buffer_0) + lock_release(self.x_cons_lock, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.x_prod_lock, 1) + aie.dma_bd(self.x_buffer_1) + lock_release(self.x_cons_lock, 1) + aie.next_bd(block[chain_id + 1]) + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.S2MM, 4, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.w_p0_prod_lock, 1) + aie.dma_bd(self.w_buffer_0, offset = 0, len = 2 * self.w_block_size) + lock_release(self.w_p0_cons_lock_0, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.w_p0_prod_lock, 1) + aie.dma_bd(self.w_buffer_1, offset = 0, len = 2 * self.w_block_size) + lock_release(self.w_p0_cons_lock_0, 1) + aie.next_bd(block[chain_id + 1]) + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.S2MM, 5, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.w_p1_prod_lock, 1) + aie.dma_bd(self.w_buffer_0, offset = 2 * self.w_block_size, len = 2 * self.w_block_size) + lock_release(self.w_p1_cons_lock_0, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.w_p1_prod_lock, 1) + aie.dma_bd(self.w_buffer_1, offset = 2 * self.w_block_size, len = 2 * self.w_block_size) + lock_release(self.w_p1_cons_lock_0, 1) + aie.next_bd(block[chain_id + 1]) + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.MM2S, 5, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.m_cons_lock, 1) + aie.dma_bd(self.y_buffer_0) + lock_release(self.m_prod_lock_0, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.m_cons_lock, 1) + aie.dma_bd(self.y_buffer_1) + lock_release(self.m_prod_lock_0, 1) + aie.next_bd(block[chain_id + 1]) + + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.MM2S, 4, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.x_cons_lock, 1) + aie.dma_bd(self.x_buffer_0) + lock_release(self.x_prod_lock, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.x_cons_lock, 1) + aie.dma_bd(self.x_buffer_1) + lock_release(self.x_prod_lock, 1) + aie.next_bd(block[chain_id + 1]) + + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.MM2S, 0, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.w_p0_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_0, offset = 0, len = self.w_block_size) + lock_release(self.w_p0_cons_lock_1, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.w_p0_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_1, offset = 0, len = self.w_block_size) + lock_release(self.w_p0_cons_lock_1, 1) + aie.next_bd(block[chain_id + 1]) + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.MM2S, 1, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.w_p0_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_0, offset = self.w_block_size, len = self.w_block_size) + lock_release(self.w_p0_prod_lock, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.w_p0_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_1, offset = self.w_block_size, len = self.w_block_size) + lock_release(self.w_p0_prod_lock, 1) + aie.next_bd(block[chain_id + 1]) + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.MM2S, 2, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.w_p1_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_0, offset = 2 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_cons_lock_1, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.w_p1_cons_lock_0, 1) + aie.dma_bd(self.w_buffer_1, offset = 2 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_cons_lock_1, 1) + aie.next_bd(block[chain_id + 1]) + + chain_id += 3 + with block[chain_id]: + aie.dma_start(aie.DMAChannelDir.MM2S, 3, dest = block[chain_id + 1], chain = block[chain_id + 3]) + + with block[chain_id + 1]: + lock_acquire(self.w_p1_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_0, offset = 3 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_prod_lock, 1) + aie.next_bd(block[chain_id + 2]) + + with block[chain_id + 2]: + lock_acquire(self.w_p1_cons_lock_1, 1) + aie.dma_bd(self.w_buffer_1, offset = 3 * self.w_block_size, len = self.w_block_size) + lock_release(self.w_p1_prod_lock, 1) + aie.next_bd(block[chain_id + 1]) + + chain_id += 3 + with block[chain_id]: + aie.EndOp() + +class q4_proj_engine: + def __init__(self, + CTs: List[List[tile_with_location]], + MTs: List[tile_with_location], + ITs: List[ShimTile], + proj_core_stack_size: int, + proj_core_link_with: str, + ctx: mlir_context, + model_config: ModelConfig + ): + self.CTs = CTs + self.MTs = MTs + self.ITs = ITs + self.proj_cores = [] + for col in range(len(CTs) // 2): + cores_this_group = [] + for row in range(len(CTs[0]) // 2): + comment_print(f"Initializing proj_core ({row}, {col})") + cores_this_group.append(proj_combo(CTs[2 * col][row * 2 : row * 2 + 2], ctx, model_config, proj_core_stack_size, proj_core_link_with, + col_idx = 2 * col)) + + for row in range(len(CTs[0]) // 2): + comment_print(f"Initializing proj_core ({row}, {col})") + cores_this_group.append(proj_combo(CTs[2 * col + 1][row * 2 : row * 2 + 2], ctx, model_config, proj_core_stack_size, proj_core_link_with, + col_idx = 2 * col + 1)) + self.proj_cores.append(cores_this_group) + + self.pure_assemble_mts = [] + self.pure_assemble_mts.append( + proj_assemble_col(MTs[0], ctx, model_config) + ) + self.pure_assemble_mts.append( + proj_assemble_col(MTs[2], ctx, model_config) + ) + self.pure_weight_mt = proj_assemble_weight_only(MTs[3], ctx, model_config) + + self.main_mt = proj_assemble_weight_x(MTs[1], ctx, model_config) + + + def route(self): + # connect IT to MT + for i in range(len(self.MTs)): + connect_port(self.ITs[i].MM2S[0], self.MTs[i].S2MM[4]) + connect_port(self.ITs[i].MM2S[1], self.MTs[i].S2MM[5]) + + # connect MT weight to all CTs + for i in range(len(self.MTs)): + for j in range(len(self.CTs[i])): + connect_port(self.MTs[i].MM2S[j], self.CTs[i][j].S2MM[1]) + + # connect x broadcast to all CTs: one circuit, every core gets every + # x chunk (as in Gemma4 and Qwen3.5 decoding; no packet ids, no arbiter) + for i in range(len(self.CTs)): + for j in range(len(self.CTs[i])): + connect_port(self.main_mt.x_out, self.CTs[i][j].S2MM[0]) + + # collect y from two columns to each pure assemble mt + for i in range(len(self.proj_cores)): + for j in range(len(self.proj_cores[i])): + if j == 0: + connect_port(self.proj_cores[i][j].y_out, self.pure_assemble_mts[i].y_in[j], pkt_id = proj_pkt_id.to_rope, keep_pkt_header = True) + connect_port(self.proj_cores[i][j].y_out, self.pure_assemble_mts[i].y_in[j], pkt_id = proj_pkt_id.to_aux, keep_pkt_header = True) + connect_port(self.proj_cores[i][j].y_out, self.pure_assemble_mts[i].y_in[j], pkt_id = proj_pkt_id.to_glu, keep_pkt_header = True) + connect_port(self.proj_cores[i][j].y_out, self.pure_assemble_mts[i].y_in[j], pkt_id = proj_pkt_id.to_gate, keep_pkt_header = True) + else: + connect_port(self.proj_cores[i][j].y_out, self.pure_assemble_mts[i].y_in[j], pkt_id = proj_pkt_id.to_rope, keep_pkt_header = False) + connect_port(self.proj_cores[i][j].y_out, self.pure_assemble_mts[i].y_in[j], pkt_id = proj_pkt_id.to_aux, keep_pkt_header = False) + connect_port(self.proj_cores[i][j].y_out, self.pure_assemble_mts[i].y_in[j], pkt_id = proj_pkt_id.to_glu, keep_pkt_header = False) + connect_port(self.proj_cores[i][j].y_out, self.pure_assemble_mts[i].y_in[j], pkt_id = proj_pkt_id.to_gate, keep_pkt_header = False) + + # collect y from pure assemble mts to main mt + connect_port(self.pure_assemble_mts[0].y_out, self.main_mt.y_in[0], pkt_id = proj_pkt_id.to_rope, keep_pkt_header = True) + connect_port(self.pure_assemble_mts[0].y_out, self.main_mt.y_in[0], pkt_id = proj_pkt_id.to_aux, keep_pkt_header = True) + connect_port(self.pure_assemble_mts[0].y_out, self.main_mt.y_in[0], pkt_id = proj_pkt_id.to_glu, keep_pkt_header = True) + connect_port(self.pure_assemble_mts[0].y_out, self.main_mt.y_in[0], pkt_id = proj_pkt_id.to_gate, keep_pkt_header = True) + connect_port(self.pure_assemble_mts[1].y_out, self.main_mt.y_in[1], pkt_id = proj_pkt_id.to_rope, keep_pkt_header = False) + connect_port(self.pure_assemble_mts[1].y_out, self.main_mt.y_in[1], pkt_id = proj_pkt_id.to_aux, keep_pkt_header = False) + connect_port(self.pure_assemble_mts[1].y_out, self.main_mt.y_in[1], pkt_id = proj_pkt_id.to_glu, keep_pkt_header = False) + connect_port(self.pure_assemble_mts[1].y_out, self.main_mt.y_in[1], pkt_id = proj_pkt_id.to_gate, keep_pkt_header = False) + + # connect weight from pure weight mt to main mt + @property + def X_in(self): + return self.main_mt.x_in + + @property + def Y_out(self): + return self.main_mt.y_out diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/rms_residual.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/rms_residual.py new file mode 100644 index 000000000..76cf2d5f7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/rms_residual.py @@ -0,0 +1,105 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +import numpy as np +import sys +import os +from typing import Any +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig + +import aie.dialects.aie as aie +from aie.helpers.dialects.ext.scf import _for as range_ +from ml_dtypes import bfloat16 + +from utils import comment_print, mlir_context, tile_with_location, lock_acquire, lock_release, AIE_CT_IP + + + +class rms_residual_tile(AIE_CT_IP): + dtype = np.dtype[bfloat16] + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig, stack_size: int = 1024, link_with: str = "rms_residual.o"): + super().__init__(tile, stack_size = stack_size, link_with = link_with) + comment_print(f"Initializing rms_residual_tile at ({self.ct_row}, {self.ct_col})") + + self.model_config = model_config + self.x_ty = np.ndarray[(model_config.D,), self.dtype] + # [input_layernorm | post_attention_layernorm] + self.w_ty = np.ndarray[(model_config.D*2,), self.dtype] + self.y_pkt_ty = np.ndarray[(model_config.D + 16,), self.dtype] + + self.D = model_config.D + comment_print(f"rms_residual_tile D: {self.D}") + + self.x_ping = ctx.buffer(tile = self.located_tile, dtype = self.x_ty, name = f"x_ping_{self.ct_row}_{self.ct_col}") + self.x_pong = ctx.buffer(tile = self.located_tile, dtype = self.x_ty, name = f"x_pong_{self.ct_row}_{self.ct_col}") + self.x_buf = ctx.buffer(tile = self.located_tile, dtype = self.x_ty, name = f"x_buf_{self.ct_row}_{self.ct_col}") + self.w_buffer = ctx.buffer(tile = self.located_tile, dtype = self.w_ty, name = f"w_buffer_{self.ct_row}_{self.ct_col}") + self.y = ctx.buffer(tile = self.located_tile, dtype = self.y_pkt_ty, name = f"y_{self.ct_row}_{self.ct_col}") + self.w_prod_lock = aie.lock(self.ct, lock_id = 0, init = 1) + self.w_cons_lock = aie.lock(self.ct, lock_id = 1, init = 0) + self.y_prod_lock = aie.lock(self.ct, lock_id = 2, init = 0) + self.y_cons_lock = aie.lock(self.ct, lock_id = 3, init = 0) + self.x_prod_lock = aie.lock(self.ct, lock_id = 4, init = 2) + self.x_cons_lock = aie.lock(self.ct, lock_id = 5, init = 0) + self.core_func = ctx.func("rms_residual", [self.y_pkt_ty, self.x_ty, self.x_ty, self.w_ty, self.x_ty]) + + # create mlir code + self.__call__() + + def __call__(self): + @aie.core(self.ct, link_with = self.link_with, stack_size = self.stack_size) + def core_body(): + for _ in range_(0xFFFFFFFF): + self.core_func(self.y, self.x_ping, self.x_pong, self.w_buffer, self.x_buf) + + @aie.mem(self.ct) + def mem_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest=block[1], chain=block[2]) + with block[1]: + lock_acquire(self.x_prod_lock, 1) + aie.dma_bd(self.x_ping, offset = 0, len = self.D) + lock_release(self.x_cons_lock, 1) + aie.next_bd(block[11]) + + with block[11]: + lock_acquire(self.x_prod_lock, 1) + aie.dma_bd(self.x_pong, offset = 0, len = self.D) + lock_release(self.x_cons_lock, 1) + aie.next_bd(block[1]) + + with block[2]: + s1 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest=block[3], chain=block[5]) + + with block[3]: + lock_acquire(self.w_prod_lock, 1) + aie.dma_bd(self.w_buffer, offset = 0, len = self.D*2) + lock_release(self.w_cons_lock, 1) + aie.next_bd(block[3]) + + + with block[5]: + s2 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest = block[6], chain = block[10]) + + # y + 14 holds the packet id the kernel picked, so start the send there + with block[6]: + lock_acquire(self.y_cons_lock, 1) + aie.dma_bd(self.y, offset = 14, len = self.D + 2) + lock_release(self.y_prod_lock, 1) + aie.next_bd(block[6]) + + with block[10]: + aie.EndOp() + + @property + def Y_out(self): + return self.MM2S[0] + + @property + def X_in(self): + return self.S2MM[0] + + @property + def W_in(self): + return self.S2MM[1] diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/router_helper.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/router_helper.py new file mode 100644 index 000000000..25f6afeb6 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/router_helper.py @@ -0,0 +1,97 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import sys +import os +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig +import aie.dialects.aie as aie +from aie.helpers.dialects.ext.scf import _for as range_ + +from utils import mlir_context, tile_with_location, comment_print, lock_acquire, lock_release +from utils import AIE_CT_IP + + +class router_helper(AIE_CT_IP): + """Router logits of experts 64 .. num_experts-1. + + The router weight comes in over 2 shim channels: IT5 channel 0 fills MT5 + (experts 0..127; half 0 -> router CT, half 1 -> this tile's S2MM 0), and + IT5 channel 1 streams experts 128..159, which do not fit in MT5, straight + to this tile's S2MM 1. This tile reads x from the router's memory and + writes its logits there (it sits right below the router CT). + + Both streams share the two weight buffers (no room for two more): S2MM 0 + waits on w_prod, S2MM 1 on b_prod, and the kernel hands the buffers from + one to the other (see kernels/router_helper.cc). + """ + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig, router, + stack_size: int = 1024, link_with: str = "router_helper.o"): + super().__init__(tile, stack_size = stack_size, link_with = link_with) + comment_print(f"Initializing router_helper at ({self.ct_row}, {self.ct_col})") + self.router = router + + # same block shape as the router's: 32 experts x 256 inputs, double buffered + self.w_buffer_0 = aie.buffer(tile=self.ct, datatype=router.weight_ty, name=f"router_helper_w_0_{self.ct_row}_{self.ct_col}") + self.w_buffer_1 = aie.buffer(tile=self.ct, datatype=router.weight_ty, name=f"router_helper_w_1_{self.ct_row}_{self.ct_col}") + self.w_prod_lock = aie.lock(self.ct, lock_id=0, init=2) + self.w_cons_lock = aie.lock(self.ct, lock_id=1, init=0) + self.b_prod_lock = aie.lock(self.ct, lock_id=2, init=0) + + self.router_helper = ctx.func("router_helper", [ + router.up_neighbor_hidden_state_in_buffer_ty, + router.weight_ty, router.weight_ty, + router.up_neighbor_top_k_expert_score_buffer_ty, + ]) + + self.__call__() + + def __call__(self): + @aie.core(self.ct, link_with = self.link_with, stack_size = self.stack_size) + def core_body(): + for _ in range_(0xFFFFFFFF): + self.router_helper( + self.router.ct_hidden_state_in_buffer, + self.w_buffer_0, self.w_buffer_1, + self.router.ct_top_k_expert_score_local, + ) + + @aie.mem(self.ct) + def mem_body(block): + # experts 64..127 from MT5 + aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest=block[1], chain=block[3]) + with block[1]: + lock_acquire(self.w_prod_lock, value=1) + aie.dma_bd(self.w_buffer_0) + lock_release(self.w_cons_lock, value=1) + aie.next_bd(block[2]) + with block[2]: + lock_acquire(self.w_prod_lock, value=1) + aie.dma_bd(self.w_buffer_1) + lock_release(self.w_cons_lock, value=1) + aie.next_bd(block[1]) + # experts 128..159, direct from IT5 channel 1 + with block[3]: + aie.dma_start(aie.DMAChannelDir.S2MM, 1, dest=block[4], chain=block[6]) + with block[4]: + lock_acquire(self.b_prod_lock, value=1) + aie.dma_bd(self.w_buffer_0) + lock_release(self.w_cons_lock, value=1) + aie.next_bd(block[5]) + with block[5]: + lock_acquire(self.b_prod_lock, value=1) + aie.dma_bd(self.w_buffer_1) + lock_release(self.w_cons_lock, value=1) + aie.next_bd(block[4]) + with block[6]: + aie.EndOp() + + @property + def w_in(self): + return self.S2MM[0] + + @property + def w2_in(self): + return self.S2MM[1] diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/router_tile.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/router_tile.py new file mode 100644 index 000000000..6e2b55336 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/router_tile.py @@ -0,0 +1,223 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import numpy as np +import sys +import os +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig +from ml_dtypes import bfloat16 +import aie.dialects.aie as aie +from aie.helpers.dialects.ext.scf import _for as range_ + +from utils import mlir_context, tile_with_location, lock_acquire, lock_release, comment_print +from utils import AIE_CT_IP +from aie.extras.dialects.ext.arith import constant, index_cast + + + +class Router_tile(AIE_CT_IP): + + dtype = np.dtype[bfloat16] + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig, + up_neighbor_hidden_state_in_buffer, + up_neighbor_share_expert_output_buffer, + up_neighbor_top_k_expert_score_buffer, + up_neighbor_top_k_expert_index_buffer, + + up_neighbor_hidden_state_in_buffer_ty, + up_neighbor_share_expert_output_buffer_ty, + up_neighbor_top_k_expert_score_buffer_ty, + up_neighbor_top_k_expert_index_buffer_ty, + + stack_size: int = 3*1024, link_with: str = "router.o" + ): + super().__init__(tile, stack_size = stack_size, link_with = link_with) + comment_print(f"Initializing Router_tile at ({self.ct_row}, {self.ct_col})") + self.model_config = model_config + self.D = model_config.hidden_size + + self.num_active_experts = model_config.num_active_experts + self.num_experts = model_config.num_experts + + + + + + self.router_weight_row_block:int = ctx.parameters["router_weight_row_block"] + self.router_weight_col_block:int = ctx.parameters["router_weight_col_block"] + + self.up_neighbor_hidden_state_in_buffer=up_neighbor_hidden_state_in_buffer + self.up_neighbor_share_expert_output_buffer=up_neighbor_share_expert_output_buffer + self.up_neighbor_top_k_expert_score_buffer= up_neighbor_top_k_expert_score_buffer + self.up_neighbor_top_k_expert_index_buffer = up_neighbor_top_k_expert_index_buffer + + + self.router_control_packet_ty = np.ndarray[( + (16,), np.dtype[np.uint32] + )] + + self.ping_pong_ty = np.ndarray[( + (16,),np.dtype[np.int32] + )] + self.up_neighbor_hidden_state_in_buffer_ty=up_neighbor_hidden_state_in_buffer_ty + self.up_neighbor_top_k_expert_score_buffer_ty=up_neighbor_top_k_expert_score_buffer_ty + self.ct_hidden_state_in_buffer = aie.buffer( + self.ct, + datatype = up_neighbor_hidden_state_in_buffer_ty + ) + self.ct_top_k_expert_score_local = aie.buffer( + self.ct, + datatype=up_neighbor_top_k_expert_score_buffer_ty + ) + + self.router_weight_ping_pong_flag = aie.buffer( + self.ct, + datatype = self.ping_pong_ty + ) + + # fp32 expert bias (moe_expert_bias), written by the host with RTP writes + # each call; its address goes to rtp_addresses.txt as RTP_router_expert_bias + self.expert_bias_ty = np.ndarray[(self.num_experts,), np.dtype[np.float32]] + self.expert_bias_buffer = ctx.buffer("RTP_router_expert_bias", self.located_tile, self.expert_bias_ty, use_write_rtp = True) + # [0]: which layer this call is; the router keeps one weight base address per + # layer (rtp_addresses.txt: RTP_router_layer) + self.layer_ty = np.ndarray[(16,), np.dtype[np.int32]] + self.layer_buffer = ctx.buffer("RTP_router_layer", self.located_tile, self.layer_ty, use_write_rtp = True) + + self.weight_ty = np.ndarray[( + self.router_weight_col_block* self.router_weight_row_block,), np.dtype[bfloat16]] + + + self.router_weight_buffer_0 = aie.buffer(tile=self.ct, + datatype=self.weight_ty, + name=f"router_weight_0_{self.ct_row}_{self.ct_col}") + + self.router_weight_buffer_1 = aie.buffer(tile=self.ct, + datatype=self.weight_ty, + name=f"router_weight_1_{self.ct_row}_{self.ct_col}") + + + self.router_weight_prod_lock = aie.lock(self.ct, lock_id=2, init=2) + self.router_weight_con_lock = aie.lock(self.ct, lock_id=3, init=0) + + self.CT_to_tile_control_buffer = aie.buffer(self.ct, datatype=self.router_control_packet_ty) + self.control_packet_out_prod_lock = aie.lock(self.ct, lock_id=6, init=1) + self.control_packet_out_con_lock = aie.lock(self.ct, lock_id=7, init=0) + + self.CT_from_tile_control_buffer = aie.buffer(self.ct, datatype=self.router_control_packet_ty) + self.control_packet_in_prod_lock = aie.lock(self.ct, lock_id=8, init=1) + self.control_packet_in_con_lock = aie.lock(self.ct, lock_id=9, init=0) + + + + # set by the host sequence each call: expert BDs written, safe to push expert tasks + self.shimtile_configure_ready_lock = aie.lock(self.ct, lock_id=10, init=0) + + + # router <-> helper (the tile below): x copied / helper's logits done + self.router_helper_x_ready_lock = aie.lock(self.ct, lock_id=13, init=0) + self.router_helper_finished_lock = aie.lock(self.ct, lock_id=14, init=0) + + self.SHIM_BD_1_VIRTUAL_buffer = aie.buffer( + self.ct, datatype=self.router_control_packet_ty + ) + + self.CT_to_shimtile_control_bd_id = 10 + self.CT_from_shimtile_control_bd_id = 11 + + self.CT_from_shimtile_control_bd_port = ctx.parameters["CT_from_shimtile_control_bd_port"] + self.CT_to_shimtile_control_bd_port = ctx.parameters["CT_to_shimtile_control_bd_port"] + + self.zero_func =ctx.func( + "zero_int32_1",[ + self.ping_pong_ty + ] + ) + self.router_func = ctx.func("router", [ + up_neighbor_hidden_state_in_buffer_ty, + up_neighbor_hidden_state_in_buffer_ty, + self.weight_ty, self.weight_ty, + up_neighbor_top_k_expert_score_buffer_ty, up_neighbor_top_k_expert_score_buffer_ty, + up_neighbor_top_k_expert_index_buffer_ty, + up_neighbor_share_expert_output_buffer_ty, + + self.router_control_packet_ty, # for virtual buffer + self.router_control_packet_ty, self.router_control_packet_ty, # for ct contorl packer + np.int32, np.int32, + np.int32, np.int32, + + np.int32, np.int32, + np.int32, np.int32, + self.ping_pong_ty, + self.expert_bias_ty, + self.layer_ty + ]) + + self.__call__() + + def __call__(self): + @aie.core(self.ct, link_with = self.link_with, stack_size = self.stack_size) + def core_body(): + self.zero_func(self.router_weight_ping_pong_flag) + for _ in range_(0xFFFFFFFF): + self.router_func( + self.up_neighbor_hidden_state_in_buffer, + self.ct_hidden_state_in_buffer, + self.router_weight_buffer_0, self.router_weight_buffer_1, + self.up_neighbor_top_k_expert_score_buffer, self.ct_top_k_expert_score_local, + self.up_neighbor_top_k_expert_index_buffer, + self.up_neighbor_share_expert_output_buffer, + self.SHIM_BD_1_VIRTUAL_buffer, + self.CT_to_tile_control_buffer, self.CT_from_tile_control_buffer, + constant(48+6), constant(48+7), + constant(48+8), constant(48+9), + constant(self.CT_to_shimtile_control_bd_id), constant(self.CT_from_shimtile_control_bd_id), + constant(self.CT_to_shimtile_control_bd_port), constant(self.CT_from_shimtile_control_bd_port), + self.router_weight_ping_pong_flag, + self.expert_bias_buffer, + self.layer_buffer + ) + + + @aie.mem(self.ct) + def mem_dma_body(block): + + + s0 = aie.dma_start(aie.DMAChannelDir.S2MM, channel_index=self.CT_from_shimtile_control_bd_port, dest=block[1], chain=block[2]) + with block[1]: + lock_acquire(self.control_packet_in_prod_lock, value=1) + aie.dma_bd(self.CT_from_tile_control_buffer, offset=0, len=1, # len=1 since we expect a single value per read to shimtile + bd_id=self.CT_from_shimtile_control_bd_id) + lock_release(self.control_packet_in_con_lock, value=1) + aie.next_bd(block[1]) + with block[2]: + s1 = aie.dma_start(aie.DMAChannelDir.MM2S, channel_index=self.CT_to_shimtile_control_bd_port, dest=block[3], chain=block[4]) + with block[3]: + lock_acquire(self.control_packet_out_con_lock, value=1) + #NOTE: the len is something changes dynamicaly + aie.dma_bd(self.CT_to_tile_control_buffer, offset=0, len=1, #NOTE: for now + bd_id=self.CT_to_shimtile_control_bd_id) + lock_release(self.control_packet_out_prod_lock, value=1) + aie.next_bd(block[3]) + + with block[4]: + s1 = aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest=block[7], chain=block[9]) + with block[7]: + lock_acquire(self.router_weight_prod_lock, value=1) + aie.dma_bd(self.router_weight_buffer_0) + lock_release(self.router_weight_con_lock, value=1) + aie.next_bd(block[8]) + with block[8]: + lock_acquire(self.router_weight_prod_lock, value=1) + aie.dma_bd(self.router_weight_buffer_1) + lock_release(self.router_weight_con_lock, value=1) + aie.next_bd(block[7]) + with block[9]: + aie.EndOp() + + @property + def router_w_in(self): + return self.S2MM[0] \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/router_w_memtile.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/router_w_memtile.py new file mode 100644 index 000000000..be1027983 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/router_w_memtile.py @@ -0,0 +1,98 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import numpy as np +import sys +import os +# Add the parent directory to the path so we can import iron as a package +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from iron.model_config import ModelConfig +from ml_dtypes import bfloat16 +import aie.dialects.aie as aie + +from utils import dma_port, mlir_context, tile_with_location, lock_acquire, lock_release +from utils import AIE_MT_IP +from iron.utils import comment_print + + +class router_w_memtile(AIE_MT_IP): + """Holds experts 0..127 of the router weight (128 x D, bf16 = 512 KB, the + whole mem tile) and feeds them to the router CT and the router helper at + the same time. Experts 128..159 do not fit; IT5 channel 1 streams them + straight to the router helper. + + S2MM 0 (IT5 channel 0): experts 0 .. 63 into half 0, then 64 .. 127 into half 1 + MM2S 0: half 0 -> router CT MM2S 1: half 1 -> router helper + + The host sends the weight early in the call, so IT5 fills both halves while + attention and the shared expert run; then the two CTs stream in parallel. + """ + MT_EXPERTS = 128 + dtype = np.dtype[bfloat16] + def __init__(self, tile: tile_with_location, ctx: mlir_context, model_config: ModelConfig): + super().__init__(tile) + comment_print(f"Initializing router_w_memtile at ({self.mt_row}, {self.mt_col})") + self.router_weight_row_block: int = ctx.parameters["router_weight_row_block"] + assert(self.MT_EXPERTS % (2 * self.router_weight_row_block) == 0) + assert(model_config.num_experts >= self.MT_EXPERTS) + + self.half_ty = np.ndarray[(self.MT_EXPERTS // 2 * model_config.hidden_size, ), self.dtype] + # per half: [buffer, producer lock, consumer lock] + self.halves = [] + for h in range(2): + buf = aie.buffer(tile=self.mt, datatype=self.half_ty, name=f"router_w_half_{h}_{self.mt_row}_{self.mt_col}") + prod = aie.lock(self.mt, lock_id=2 * h, init=1) + cons = aie.lock(self.mt, lock_id=2 * h + 1, init=0) + self.halves.append((buf, prod, cons)) + + self.__call__() + + def __call__(self): + (buf0, prod0, cons0), (buf1, prod1, cons1) = self.halves + + @aie.memtile_dma(self.mt) + def memtile_dma_body(block): + # in: half 0 then half 1, each waits until its previous contents went out + with block[0]: + aie.dma_start(channel_dir=aie.DMAChannelDir.S2MM, channel_index=0, dest=block[1], chain=block[3]) + with block[1]: + lock_acquire(prod0, value=1) + aie.dma_bd(buf0) + lock_release(cons0, value=1) + aie.next_bd(block[2]) + with block[2]: + lock_acquire(prod1, value=1) + aie.dma_bd(buf1) + lock_release(cons1, value=1) + aie.next_bd(block[1]) + + # out: half 0 -> router CT, half 1 -> router helper + with block[3]: + aie.dma_start(channel_dir=aie.DMAChannelDir.MM2S, channel_index=0, dest=block[4], chain=block[5]) + with block[4]: + lock_acquire(cons0, value=1) + aie.dma_bd(buf0) + lock_release(prod0, value=1) + aie.next_bd(block[4]) + with block[5]: + aie.dma_start(channel_dir=aie.DMAChannelDir.MM2S, channel_index=1, dest=block[6], chain=block[7]) + with block[6]: + lock_acquire(cons1, value=1) + aie.dma_bd(buf1) + lock_release(prod1, value=1) + aie.next_bd(block[6]) + with block[7]: + aie.EndOp() + + @property + def W_in(self) -> dma_port: + return self.S2MM[0] + + @property + def W_out(self) -> dma_port: + return self.MM2S[0] + + @property + def W2_out(self) -> dma_port: + return self.MM2S[1] diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/utils.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/utils.py new file mode 100644 index 000000000..c2731c78a --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/iron/utils.py @@ -0,0 +1,264 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +from dataclasses import dataclass +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +from aie.dialects.aie import * +from aie.dialects.aiex import * +from aie.helpers.dialects.ext.scf import _for as range_ +import aie.utils.trace as trace_utils +from aie.utils.trace import MemTilePortEvent, MemTileEvent, PortEvent +from aie.utils.trace_events_enum import CoreEvent, MemEvent, ShimTileEvent, MemTileEvent +from aie.dialects import memref +from typing import Dict, Any, List, Optional +from aie.extras import types as T +from abc import ABC, abstractmethod + +def comment_print(msg: str): + print("// " + msg) + +@dataclass +class tile_with_location: + tile: tile + row: int + col: int + + @property + def S2MM(self): + return [dma_port(self, i) for i in range(6)] + + @property + def MM2S(self): + return [dma_port(self, i) for i in range(6)] + + +@dataclass +class dma_port: + tile: tile_with_location + channel: int + +class mlir_context: + def __init__(self): + self.data_tys = {} + self.funcs = {} + self.buffers = {} + self.parameters = {} + self.object_fifos = {} + self.packet_ids = {} + + + def data_ty(self, name: str, shape: List[int], dtype: Any): + """ + Docstring for data_ty, unique name for each data type + + :param self: Description + :param name: Description + :type name: str + :param shape: Description + :type shape: List[int] + :param dtype: Description + :type dtype: Any + """ + comment_print(f"Defining shared data type {name} with shape {shape} and dtype {dtype}") + d_ty = np.ndarray[shape, dtype] + self.data_tys[name] = d_ty + if not hasattr(self, name): + setattr(self, name, d_ty) + else: + raise ValueError(f"Data type {name} already exists") + return d_ty + + def buffer(self, name: str, tile: tile_with_location, dtype: Any, use_write_rtp: bool = False, use_address: int = None): + comment_print(f"Defining shared buffer {name} at tile ({tile.row}, {tile.col}) with dtype {dtype}, use_write_rtp={use_write_rtp}") + # this should be unique + if use_write_rtp == True: + if name[0:4] != "RTP_": + name = "RTP_" + name + + if not hasattr(self, name): + if (use_address is not None): + new_buffer = aie.buffer(tile.tile, dtype, name = name, use_write_rtp = use_write_rtp, address = use_address) + else: + new_buffer = aie.buffer(tile.tile, dtype, name = name, use_write_rtp = use_write_rtp) + self.buffers[name] = new_buffer + setattr(self, name, new_buffer) + return new_buffer + else: + comment_print(f"Buffer {name} already exists, returning existing buffer") + return self.buffers[name] + + + def func(self, name: str, inputs: List[Any]): + # this should be unique + if not hasattr(self, name): + this_func = aie.external_func(name, inputs) + self.funcs[name] = this_func + setattr(self, name, this_func) + return this_func + else: + comment_print(f"Function {name} already exists, returning existing function") + return self.funcs[name] + + def parameter(self, name: str, value: Any): + self.parameters[name] = value + if not hasattr(self, name): + setattr(self, name, value) + else: + raise ValueError(f"Parameter {name} already exists") + return value + + def object_fifo(self, name: str, src_tile: tile_with_location, dst_tile: tile_with_location | List[tile_with_location], depth: int, data_ty: Any, *args, **kwargs): + if isinstance(dst_tile, tile_with_location): + fifo = object_fifo(name, src_tile.tile, dst_tile.tile, depth, data_ty, *args, **kwargs) + else: + fifo = object_fifo(name, src_tile.tile, [t.tile for t in dst_tile], depth, data_ty, *args, **kwargs) + self.object_fifos[name] = fifo + if not hasattr(self, name): + setattr(self, name, fifo) + else: + raise ValueError(f"Object fifo {name} already exists") + return fifo + + + +def dma_mm2s_ch(ch: int): + return { + "source_port": WireBundle.DMA, + "source_channel": ch + } + +def dma_s2mm_ch(ch: int): + return { + "dest_port": WireBundle.DMA, + "dest_channel": ch + } + +def flow_mm2s_ch(ch: int): + return { + "source_bundle": WireBundle.DMA, + "source_channel": ch + } + +def flow_s2mm_ch(ch: int): + return { + "dest_bundle": WireBundle.DMA, + "dest_channel": ch + } + +class ShimTile: + located_tile: tile_with_location + st: tile + st_row: int + st_col: int + + def __init__(self, tile: tile_with_location): + self.located_tile = tile + self.st = tile.tile + self.st_row = tile.row + self.st_col = tile.col + + @property + def S2MM(self): + return [dma_port(self.located_tile, i) for i in range(2)] + + @property + def MM2S(self): + return [dma_port(self.located_tile, i) for i in range(2)] + +def generate_tile_map(total_rows: int, total_cols: int) -> Tuple[List[tile_with_location], List[tile_with_location], List[List[tile_with_location]]]: + # Tile declarations + ShimTiles = [] + MemTiles = [] + cores = [] + for col in range(total_cols): + ShimTiles.append(ShimTile(tile_with_location(tile(col, 0), 0, col))) + MemTiles.append(tile_with_location(tile(col, 1), 1, col)) + + for row in range(total_rows - 2): + ComputeTilesRow = [] + for col in range(total_cols): + ComputeTilesRow.append(tile_with_location(tile(col, row + 2), row + 2, col)) + + cores.append(ComputeTilesRow) + + return ShimTiles, MemTiles, cores + +def connect_dma(src: tile_with_location, dst: tile_with_location, src_ch: int, dst_ch: int, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile, **flow_mm2s_ch(src_ch), dest = dst.tile, **flow_s2mm_ch(dst_ch)) + else: + aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src_ch), dest = dst.tile, **dma_s2mm_ch(dst_ch), keep_pkt_header = keep_pkt_header) + +def connect_port(src: dma_port, dst: dma_port, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile.tile, **flow_mm2s_ch(src.channel), dest = dst.tile.tile, **flow_s2mm_ch(dst.channel)) + else: + comment_print(f"Connecting port with pkt_id {pkt_id} from tile ({src.tile.row}, {src.tile.col}) channel {src.channel} to tile ({dst.tile.row}, {dst.tile.col}) channel {dst.channel}") + aie.packetflow(pkt_id = pkt_id, source = src.tile.tile, **dma_mm2s_ch(src.channel), dest = dst.tile.tile, **dma_s2mm_ch(dst.channel), keep_pkt_header = keep_pkt_header) + + +def lock_acquire(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.AcquireGreaterEqual, value = value) + +def lock_release(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.Release, value = value) + +class AIE_CT_IP(ABC): + stack_size: int + link_with: str + located_tile: tile_with_location + ct: tile + ct_row: int + ct_col: int + + core_func: external_func + def __init__(self, tile: tile_with_location, stack_size: int = 1024, link_with: str = ""): + self.located_tile = tile + self.ct = tile.tile + self.ct_row = tile.row + self.ct_col = tile.col + self.stack_size = stack_size + self.link_with = link_with + self.core_func = None + + @abstractmethod + def __call__(self): + pass + + def set_stack_size(self, stack_size: int): + self.stack_size = stack_size + + def set_link(self, link_with: str): + self.link_with = link_with + + @property + def S2MM(self): + return [dma_port(self.located_tile, i) for i in range(2)] + + @property + def MM2S(self): + return [dma_port(self.located_tile, i) for i in range(2)] + +class AIE_MT_IP(ABC): + located_tile: tile_with_location + mt: tile + mt_row: int + mt_col: int + + def __init__(self, tile: tile_with_location): + self.located_tile = tile + self.mt = tile.tile + self.mt_row = tile.row + self.mt_col = tile.col + + @abstractmethod + def __call__(self): + pass + + @property + def S2MM(self): + return [dma_port(self.located_tile, i) for i in range(6)] + + @property + def MM2S(self): + return [dma_port(self.located_tile, i) for i in range(6)] diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/aie_array_layout.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/aie_array_layout.h new file mode 100644 index 000000000..dee804642 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/aie_array_layout.h @@ -0,0 +1,90 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __AIE_ARRAY_LAYOUT_H__ +#define __AIE_ARRAY_LAYOUT_H__ + +#include "typedef.hpp" +#include "model_spec.h" + +// calculate the number of repeats of x; +// Each round, the MVM engine computes QKV_ROW_BLOCK_SIZE * MVM_CORES of rows for the output; +constexpr int MVM_CORES = 16; +constexpr int MVM_CORES_Per_Column = 4; +constexpr int NUM_MVM_COLUMN =MVM_CORES / MVM_CORES_Per_Column; + +constexpr int QKV_REPEATS = (DQ + DK + DV) / MVM_CORES / QXNX_ROW_BLOCK_SIZE; +// attention output gate logits (D -> DQ), run right after qkv on the same normed x +constexpr int GATE_REPEATS = DQ / MVM_CORES / QXNX_ROW_BLOCK_SIZE; +constexpr int O_DOWN_REPEATS = MODEL_DIM / MVM_CORES / QXNX_ROW_BLOCK_SIZE; +constexpr int UP_GATE_REPEATS = (2 * INTERMEDIATE_SIZE) / MVM_CORES / QXNX_ROW_BLOCK_SIZE; + + + +//NOTE: For q4nx +// q4_k: 4 bits of quant per weight, a uint8 scale and a uint8 min per group of +// 32, and a bf16 S / bf16 M per super-block of 256, i.e. 37/64 byte = 4.625 bpw. +// With the shipping 32x256 block that is 4096 + 512 + 128 = 4736 B. +constexpr uint32_t Q4_K_block_byte = (QXNX_ROW_BLOCK_SIZE* QXNX_COL_BLOCK_SIZE* 37) /64; +constexpr uint32_t Q4_K_GATE_UP_WEIGHT_BYTE_PER_EXPERT = 2* (INTERMEDIATE_SIZE/QXNX_ROW_BLOCK_SIZE) * (MODEL_DIM/QXNX_COL_BLOCK_SIZE)* Q4_K_block_byte; +constexpr uint32_t Q4_K_DOWN_WEIGHT_BYTE_PER_EXPERT = (MODEL_DIM/QXNX_ROW_BLOCK_SIZE) * (INTERMEDIATE_SIZE/QXNX_COL_BLOCK_SIZE)* Q4_K_block_byte; + +// one routed expert in DDR: [channel 0 stream | channel 1 stream], each stream +// its half of the gate/up blocks then its half of the down blocks (see the host) +constexpr uint32_t Q4_K_EXPERT_BYTE = Q4_K_GATE_UP_WEIGHT_BYTE_PER_EXPERT + Q4_K_DOWN_WEIGHT_BYTE_PER_EXPERT; +constexpr uint32_t Q4_K_EXPERT_BYTE_PER_CHANNEL = Q4_K_EXPERT_BYTE / 2; + +constexpr int UP_GATE_EXPERT_REPEATS =(2 * INTERMEDIATE_SIZE )/ MVM_CORES_Per_Column / QXNX_ROW_BLOCK_SIZE; +constexpr int DOWN_EXPERT_REPEATS = MODEL_DIM /MVM_CORES_Per_Column/QXNX_ROW_BLOCK_SIZE; + +constexpr int PER_PROJ_COLUMN_OUTPUT_SLICE = MVM_CORES_Per_Column*QXNX_ROW_BLOCK_SIZE; +constexpr int PER_PROJ_OUTPUT_SLICE = NUM_MVM_COLUMN* PER_PROJ_COLUMN_OUTPUT_SLICE; + +constexpr int NUM_PROJ_OUT_PER_GLU_SLICE = GLU_SLICE / PER_PROJ_OUTPUT_SLICE; + +// one proj round of a column (its 4 cores x 32 rows) is one expert's [up | gate] +static_assert(2 * EXP_UP_GATE_OUTDIM_REORDER == QXNX_ROW_BLOCK_SIZE * MVM_CORES_Per_Column); +// one GLU slice is exactly one proj round +static_assert(GLU_SLICE == PER_PROJ_OUTPUT_SLICE); + + +constexpr int pkt_id_to_rope = 1; +constexpr int pkt_id_to_aux = 8; +constexpr int pkt_id_to_glu = 15; +constexpr int pkt_id_to_gate = 3; + +constexpr int pkt_id_rms_to_proj = 0; +constexpr int pkt_id_rms_to_it = 1; +constexpr int pkt_id_rms_to_glu = 7; +constexpr int pkt_id_rms_from_glu = 11; + +// packet ids into the proj engine's x input (same values as proj_x_pkt_id in iron/constants.py) +// GLU uses one id for everything it sends to the proj engine: shared expert h, +// routed up/gate x, and the 4 routed experts' h (round robin). Two ids on the +// same path made the router merge them into one masked rule that also caught +// GLU's other packets (id 11, to rms). +constexpr int pkt_id_glu_to_proj_x = 9; + + + + +// configuration for control-packet +// routed expert BDs on shims 0, 1, 6, 7: channel 0 uses the id below, channel 1 the +// next one (round 0: 4, 5; round 1: 12, 13). Must match _gen_sequence on the host. +constexpr uint32_t SHIM_X_expert_BD_ID = 4; +constexpr uint32_t Round_2_SHIM_X_expert_BD_ID = 12; + +constexpr uint32_t SHIM_0_CONTROL_PKT = 29; +constexpr uint32_t SHIM_1_CONTROL_PKT = 25; +constexpr uint32_t SHIM_6_CONTROL_PKT = 22; +constexpr uint32_t SHIM_7_CONTROL_PKT = 31; + +constexpr uint32_t SHIM_6_CONTROL_RES_PKT = 30; + +constexpr bfloat16 exp_scale = 1.44269504089; +// The MVM cores hold a whole weight block's rows at once: one column of a block +// is exactly PARALLEL_ROWS elements, so this is a layout constant tied to the +// block shape, not a tuning knob. +constexpr int PARALLEL_ROWS = QXNX_ROW_BLOCK_SIZE; + +#endif // __AIE_ARRAY_LAYOUT_H__ \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/aie_kernel_utils.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/aie_kernel_utils.h new file mode 100644 index 000000000..3351c671c --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/aie_kernel_utils.h @@ -0,0 +1,267 @@ +/* + Copyright (C) 2014 - 2022 Xilinx, Inc. All rights reserved. + Copyright (C) 2022 - 2025 Advanced Micro Devices, Inc. All rights reserved. + Portions of this file consist of AI-generated content. + SPDX-License-Identifier: MIT +*/ +#include "zero.h" +#include "passThroughCommon.hpp" +#ifndef _AIE_KERNEL_UTILS_ +#define _AIE_KERNEL_UTILS_ +#include "typedef.hpp" +#if defined(__chess__) +#define AIE_LOOP_UNROLL(x) [[chess::unroll_loop(x)]] +#define AIE_LOOP_UNROLL_FULL [[chess::unroll_loop()]] +#define AIE_LOOP_NO_UNROLL [[chess::no_unroll]] +#define AIE_LOOP_MIN_ITERATION_COUNT(x) [[chess::min_loop_count(x)]] +#define AIE_LOOP_MAX_ITERATION_COUNT(x) [[chess::max_loop_count(x)]] +#define AIE_LOOP_RANGE(a, ...) \ + [[chess::min_loop_count(a)]] __VA_OPT__( \ + [[chess::max_loop_count(__VA_ARGS__)]]) +#define AIE_PREPARE_FOR_PIPELINING [[chess::prepare_for_pipelining]] +#define AIE_NO_PREPARE_FOR_PIPELINING [[chess::no_prepare_for_pipelining]] +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) \ + [[chess::modulo_scheduling_budget_ratio(x)]] +#define AIE_KEEP_SW_LOOP [[chess::keep_sw_loop]] +#define AIE_PEEL_PIPELINED_LOOP(x) [[chess::peel_pipelined_loop(x)]] +#define AIE_KEEP_FREE_FOR_PIPELINING(x) [[chess::keep_free_for_pipelining(x)]] +#define AIE_ALLOCATE(x) [[chess::allocate(x)]] +#define AIE_NO_HW_LOOP [[chess::no_hw_loop]] +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN chess_flatten_loop + +#elif defined(__AIECC__) +#ifndef __STRINGIFY +#define __STRINGIFY(a) #a +#endif +#define AIE_LOOP_UNROLL(x) _Pragma(__STRINGIFY(clang loop unroll_count(x))) +#define AIE_LOOP_UNROLL_FULL _Pragma("clang loop unroll(full)") +#define AIE_LOOP_NO_UNROLL _Pragma("clang loop unroll(disable)") +#define AIE_LOOP_MIN_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop min_iteration_count(x))) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop max_iteration_count(x))) +#define AIE_LOOP_RANGE(a, ...) \ + AIE_LOOP_MIN_ITERATION_COUNT(a) \ + __VA_OPT__(AIE_LOOP_MAX_ITERATION_COUNT(__VA_ARGS__)) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) \ + _Pragma(__STRINGIFY(clang loop pipeline_initiation_interval(x))) +#define AIE_PREPARE_FOR_POSTPIPELINING _Pragma("clang loop pipeline(disable)") +#define AIE_LOOP_FLATTEN + +#else +#define AIE_LOOP_UNROLL(x) +#define AIE_LOOP_UNROLL_FULL +#define AIE_LOOP_NO_UNROLL +#define AIE_LOOP_MIN_ITERATION_COUNT(x) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) +#define AIE_LOOP_RANGE(a, ...) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN +#endif + +// Loop-counter type for loops whose body ends in a per-iteration lock release. +// Peano/llvm-aie (non-chess) sinks the final lock release past the loop +// back-edge, so it runs once on loop exit instead of every iteration and +// deadlocks any multi-iteration lock loop. A volatile counter makes the trip +// count opaque and keeps the release inside the loop. chess schedules correctly. +#if defined(__chess__) +#define AIE_LOCK_LOOP_CTR int +#else +#define AIE_LOCK_LOOP_CTR volatile int +#endif + +// State that must start at zero and keep its value between calls (ping/pong +// flags, "already known" tables). Peano's CDO loader does not zero .bss, so +// under Peano such variables go to .data, which is loaded with its initial value. +#if defined(__chess__) +#define AIE_PERSIST_ZERO +#else +#define AIE_PERSIST_ZERO __attribute__((section(".data"))) +#endif + +// Scalar float +, -, * rounded like chess. chess computes these with IEEE +// round-to-nearest-even softfloat; Peano fuses a*b+c and runs scalar add/sub on +// the vector unit, which rounds some results differently. Under Peano, call +// compiler-rt's IEEE softfloat directly so both compilers round the same way. +#if defined(__chess__) +#define AIE_FADD(a, b) ((a) + (b)) +#define AIE_FMUL(a, b) ((a) * (b)) +#else +extern "C" float __addsf3(float, float); +extern "C" float __mulsf3(float, float); +#define AIE_FADD(a, b) __addsf3((a), (b)) +#define AIE_FMUL(a, b) __mulsf3((a), (b)) +#endif + +// Buffer parameters of a kernel entry function that also takes and gives back +// locks. The DMA reads and writes these buffers between the lock calls, so they +// are not "restrict" in the C sense. chess keeps every access where it is +// written; Peano sees that a lock call cannot reach a restrict buffer and drops +// or moves accesses across it (it deleted packet-id writes in rms_residual). +#if defined(__chess__) +#define AIE_DMA_RESTRICT restrict +#else +#define AIE_DMA_RESTRICT +#endif + +// Some lock utilities +/// \brief Acquire a lock with given lock ID on this CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 48, num_locks); +} + +/// \brief Release a lock with given lock ID on this CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 48, num_locks); +} + + +/// \brief Acquire a lock with given lock ID on left CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _left_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 16, num_locks); +} + +/// \brief Release a lock with given lock ID on left CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _left_lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 16, num_locks); +} + +/// \brief Acquire a lock with given lock ID on up CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _up_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 32, num_locks); +} + +/// \brief Release a lock with given lock ID on up CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _up_lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 32, num_locks); +} + +/// \brief Acquire a lock with given lock ID on down CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _down_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id, num_locks); +} + +/// \brief Release a lock with given lock ID on down CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _down_lock_release(int lock_id, int num_locks = 1){ + release(lock_id, num_locks); +} + +// template +// void zero_vectorized(T *__restrict c) { +// constexpr int r = 256 / (sizeof(T) * 8); // one 256 bit store unit +// static_assert((M) % r == 0); +// const aie::vector zeros = aie::zeros(); +// const T *__restrict c_end = c + M; +// for (; c < c_end; c += r) { +// aie::store_v(c, zeros); +// } +// } + + + + + +// template +// void copy_float_to_bf16(bfloat16 * y, const float * y_acc) { +// static_assert(m%16 == 0); +// AIE_PREPARE_FOR_PIPELINING +// AIE_LOOP_UNROLL_FULL +// for (int i = 0; i < m / 16; i++){ +// aie::vector y_vec = aie::load_v<16>(y_acc + i * 16); +// aie::accum acc; +// acc.from_vector(y_vec); +// aie::vector y_vec_bf16 = acc.template to_vector(); +// // y_vec_bf16 = aie::mul(y_vec_bf16, (bf16)0.5); // convert from float32 to bfloat16 by dividing 256 and truncating +// aie::store_v(y + i * 16, y_vec_bf16); +// } +// } + +// template +// void copy_bf16_to_float(float * y, const bfloat16 * y_bf16) { +// static_assert(m%16 == 0); +// AIE_PREPARE_FOR_PIPELINING +// for (int i = 0; i < m / 16; i++){ +// aie::vector y_vec = aie::load_v<16>(y_bf16 + i * 16); +// aie::accum acc; +// acc.from_vector(y_vec); +// aie::store_v(y + i * 16, acc.template to_vector()); +// } +// } + + +// template +// void copy_bf16_to_bf16( bfloat16 *y, const bfloat16 * y_bf16) { +// static_assert(m%16 == 0); +// AIE_PREPARE_FOR_PIPELINING +// for (int i = 0; i < m / 16; i++){ +// aie::vector y_vec = aie::load_v<16>(y_bf16 + i * 16); +// aie::store_v(y + i * 16, y_vec); +// } + +// } + + +template +void _memcpy(uint8* dst, uint8* src){ + static_assert(SIZE%vec_size == 0); + if constexpr(SIZE/vec_size <= 3){ + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_UNROLL_FULL + for (int i = 0; i < SIZE; i += vec_size){ + aie::vector data = aie::load_v(src + i); + aie::store_v(dst + i, data); + } + } else { + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(SIZE/vec_size,SIZE/vec_size) + for (int i = 0; i < SIZE; i += vec_size){ + aie::vector data = aie::load_v(src + i); + aie::store_v(dst + i, data); + } + } +} +// template +// inline aie::vector getExpBf16(aie::vector& x) { +// constexpr bfloat16 exp_scale = 1.44269504089; +// aie::vector y_scaled = aie::mul(x, aie::broadcast(exp_scale)); +// aie::vector y_exp = aie::exp2(y_scaled); +// return y_exp; +// } + + +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/attn_kv.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/attn_kv.cc new file mode 100644 index 000000000..3a52c4e3e --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/attn_kv.cc @@ -0,0 +1,767 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#include "lut_based_ops.h" +#include "aie_kernel_utils.h" +#include "aie_array_layout.h" + +typedef float y_acc_dtype; +void calculate_l(bf16 *__restrict pS, float *__restrict c, float *__restrict l); +template +void attn_fv(bf16 *__restrict pS, bf16 *__restrict pV, y_acc_dtype *__restrict pY, float *__restrict c); +template +void scale_div_aie(bf16 *a, bf16* o, float *l); +template +void passThrough_aie(T_in *restrict in0, T_out *restrict out); + + +constexpr int s_prod_lock = 4; +constexpr int s_cons_lock = 5; +constexpr int v_prod_lock = 2; +constexpr int v_cons_lock = 3; +constexpr int o_prod_lock = 0; +constexpr int o_cons_lock = 1; +// constexpr int l_prod_lock = 6; +constexpr int l_cons_lock = 7; + +extern "C"{ + +void attn_kv( + bf16 *__restrict s_ping, + bf16 *__restrict s_pong, + bf16 *__restrict v_ping, + bf16 *__restrict v_pong, + bf16 *__restrict o_ping, + bf16 *__restrict o_pong, + int* L +) +{ + alignas(aie::vector_decl_align) static y_acc_dtype y[8 * DH] = {}; + alignas(aie::vector_decl_align) static bf16 y_bf16[8 * DH] = {}; + alignas(aie::vector_decl_align) static float l[16] = {}; + const aie::vector zero = aie::broadcast(0); + + AIE_PERSIST_ZERO static bool is_svc_ping = false; + AIE_PERSIST_ZERO static bool is_lo_ping = false; + zero_vectorized(y); + aie::store_v(l, zero); + _down_lock_acquire(l_cons_lock); + AIE_LOCK_LOOP_CTR i = L[0]; + do { + _down_lock_acquire(s_cons_lock); + _lock_acquire(v_cons_lock); + is_svc_ping = !is_svc_ping; + bf16 *s = is_svc_ping ? s_ping : s_pong; + bf16 *v = is_svc_ping ? v_ping : v_pong; + float *c = (float *)(s + Q_HEADS_PADDED_PER_CU * 16); + calculate_l(s, c, l); + attn_fv(s, v, y, c); + _down_lock_release(s_prod_lock); + _lock_release(v_prod_lock); + i -= 16; + } while (i > 0); + passThrough_aie(y, y_bf16); + is_lo_ping = !is_lo_ping; + bf16 *o = is_lo_ping ? o_ping : o_pong; + _lock_acquire(o_prod_lock); + scale_div_aie<8 * DH>(y_bf16, o, l); + _lock_release(o_cons_lock); +} +} + + +template +void passThrough_aie(T_in *restrict in0, T_out *restrict out) { + + const int vec_factor = 16; + + aie::vector Out; + + const int F = N / vec_factor; + for (int i = 0; i < F; i++) AIE_LOOP_FLATTEN { + aie::accum c_acc_in; + c_acc_in.from_vector(aie::load_v(in0)); + aie::store_v(out, c_acc_in.template to_vector()); + in0 += vec_factor; + out += vec_factor; + } +} + +#if ATTN_IMPL == ATTN_IMPL_2x4x1 +void calculate_l(bf16 *__restrict pS, float *__restrict c, float *__restrict l) { + using MMUL = aie::mmul<8, 8, 8, bf16, bf16, accfloat>; + + bf16 *__restrict pS1 = pS; + + aie::vector S_up = aie::load_v<64>(pS1); + pS1 += 64; + aie::vector S_down = aie::load_v<64>(pS1); + + aie::vector S10 = aie::filter_even(S_up, 8); + aie::vector S11 = aie::filter_odd(S_up, 8); + aie::vector S20 = aie::filter_even(S_down, 8); + aie::vector S21 = aie::filter_odd(S_down, 8); + + aie::vector S0 = aie::concat(S10, S20); + aie::vector S1 = aie::concat(S11, S21); + aie::vector ones = aie::broadcast(1); + + aie::vector acc_C00 = aie::zeros(); + + MMUL C00(acc_C00); + + C00.mac(S0, ones); + C00.mac(S1, ones); + + aie::vector sumf = C00.template to_vector(); + auto sum03 = aie::filter_even(sumf, 4); + auto sum02 = aie::filter_even(sum03, 2); + auto sum01 = aie::filter_even(sum02, 1); + auto sum00 = aie::concat(sum01, sum01); + aie::accum sum; + sum.from_vector(sum00); + + aie::vector c_float32 = aie::load_v<8>(c); + aie::vector c_in = aie::concat(c_float32, c_float32); + + aie::vector l_float32 = aie::load_v<8>(l); + aie::vector l_in = aie::concat(l_float32, l_float32); + + aie::accum l_out; + l_out = mac_elem_16_accuracy_safe(l_in, c_in, sum, 0, 0, 0); + aie::store_v(l, l_out.template to_vector()); + + // bf16 sums[8] = {}; + // aie::vector s0 = aie::load_v<16>(pS); + // aie::vector s1 = aie::load_v<16>(pS + 16); + // aie::vector s2 = aie::load_v<16>(pS + 32); + // aie::vector s3 = aie::load_v<16>(pS + 48); + // aie::vector s4 = aie::load_v<16>(pS + 64); + // aie::vector s5 = aie::load_v<16>(pS + 80); + // aie::vector s6 = aie::load_v<16>(pS + 96); + // aie::vector s7 = aie::load_v<16>(pS + 112); + + // sums[0] = aie::reduce_add(s0); + // sums[1] = aie::reduce_add(s1); + // sums[2] = aie::reduce_add(s2); + // sums[3] = aie::reduce_add(s3); + // sums[4] = aie::reduce_add(s4); + // sums[5] = aie::reduce_add(s5); + // sums[6] = aie::reduce_add(s6); + // sums[7] = aie::reduce_add(s7); + + // aie::vector sum_bf16 = aie::load_v<8>(sums); + // aie::vector sum_16 = aie::concat(sum_bf16, sum_bf16); + // aie::accum sum_float32_16; + // sum_float32_16.from_vector(sum_16); + + // aie::vector c_float32 = aie::load_v<8>(c); + // aie::vector c_in = aie::concat(c_float32, c_float32); + // aie::vector l_float32 = aie::load_v<8>(l); + // aie::vector l_in = aie::concat(l_float32, l_float32); + + // aie::accum l_out; + // l_out = mac_elem_16_accuracy_safe(l_in, c_in, sum_float32_16, 0, 0, 0); + // aie::store_v(l, l_out.template to_vector()); +} + +template +void attn_fv(bf16 *__restrict pS, bf16 *__restrict pV, y_acc_dtype *__restrict pY, float *__restrict c) { + + using MMUL = aie::mmul; + + + + y_acc_dtype *__restrict pY1 = pY; + bf16 *__restrict pS1 = pS; + + aie::vector S_up = aie::load_v<64>(pS1); + pS1 += 64; + aie::vector S_down = aie::load_v<64>(pS1); + + aie::vector S10 = aie::filter_even(S_up, 8); + aie::vector S11 = aie::filter_odd(S_up, 8); + aie::vector S20 = aie::filter_even(S_down, 8); + aie::vector S21 = aie::filter_odd(S_down, 8); + + aie::vector S0 = aie::concat(S10, S20); + aie::vector S1 = aie::concat(S11, S21); + + aie::vector c0 = aie::broadcast(c[0]); + aie::vector c1 = aie::broadcast(c[1]); + aie::vector c2 = aie::broadcast(c[2]); + aie::vector c3 = aie::broadcast(c[3]); + aie::vector c4 = aie::broadcast(c[4]); + aie::vector c5 = aie::broadcast(c[5]); + aie::vector c6 = aie::broadcast(c[6]); + aie::vector c7 = aie::broadcast(c[7]); + aie::vector CORRECT = aie::concat(c0, c1, c2, c3, c4, c5, c6, c7); + + bf16 *__restrict pV1 = pV; + bf16 *__restrict pV2 = pV + MMUL::size_B * colQ; + + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(2) + for (unsigned j = 0; j < colQ; j += 4) { + //v0 + bf16 *__restrict pV01 = pV1 + (j + 0) * MMUL::size_B; + bf16 *__restrict pV02 = pV1 + (j + 1) * MMUL::size_B; + + aie::vector V00 = aie::load_v(pV01); + pV01 += MMUL::size_B * colQ * 2; + aie::vector V01 = aie::load_v(pV02); + pV02 += MMUL::size_B * colQ * 2; + + aie::vector acc_Y00 = aie::load_v(pY1); + aie::vector acc_Y01 = aie::load_v(pY1 + MMUL::size_C); + + aie::accum ACC_Y00; + aie::accum ACC_Y01; + ACC_Y00 = aie::mul(CORRECT, acc_Y00); + ACC_Y01 = aie::mul(CORRECT, acc_Y01); + + MMUL Y00(ACC_Y00); + MMUL Y01(ACC_Y01); + MMUL Y10(ACC_Y00); + MMUL Y11(ACC_Y01); + + + Y00.mac(S0, V00); + Y01.mac(S0, V01); + + V00 = aie::load_v(pV01); + V01 = aie::load_v(pV02); + + Y00.mac(S1, V00); + Y01.mac(S1, V01); + + //v1 + bf16 *__restrict pV11 = pV2 + (j + 0) * MMUL::size_B; + bf16 *__restrict pV12 = pV2 + (j + 1) * MMUL::size_B; + + aie::vector V10 = aie::load_v(pV11); + pV11 += MMUL::size_B * colQ * 2; + aie::vector V11 = aie::load_v(pV12); + pV12 += MMUL::size_B * colQ * 2; + + Y10.mac(S0, V10); + Y11.mac(S0, V11); + + V10 = aie::load_v(pV11); + V11 = aie::load_v(pV12); + + Y10.mac(S1, V10); + Y11.mac(S1, V11); + + auto Y20 = aie::filter_even(Y00.template to_vector(), 32); + auto Y22 = aie::filter_even(Y01.template to_vector(), 32); + + auto Y31 = aie::filter_odd (Y10.template to_vector(), 32); + auto Y33 = aie::filter_odd (Y11.template to_vector(), 32); + + auto Y = aie::concat(Y20, Y31); //, Y22, Y33, Y24, Y35, Y26, Y37); + aie::store_v(pY1, Y); + pY1 += MMUL::size_C; + + Y = aie::concat(Y22, Y33); + aie::store_v(pY1, Y); + pY1 += MMUL::size_C; + + bf16 *__restrict pV03 = pV1 + (j + 2) * MMUL::size_B; + bf16 *__restrict pV04 = pV1 + (j + 3) * MMUL::size_B; + + aie::vector V02 = aie::load_v(pV03); + pV03 += MMUL::size_B * colQ * 2; + aie::vector V03 = aie::load_v(pV04); + pV04 += MMUL::size_B * colQ * 2; + + aie::vector acc_Y02 = aie::load_v(pY1); + aie::vector acc_Y03 = aie::load_v(pY1 + MMUL::size_C); + + aie::accum ACC_Y02; + aie::accum ACC_Y03; + ACC_Y02 = aie::mul(CORRECT, acc_Y02); + ACC_Y03 = aie::mul(CORRECT, acc_Y03); + + + MMUL Y02(ACC_Y02); + MMUL Y03(ACC_Y03); + MMUL Y12(ACC_Y02); + MMUL Y13(ACC_Y03); + + + Y02.mac(S0, V02); + Y03.mac(S0, V03); + + V02 = aie::load_v(pV03); + V03 = aie::load_v(pV04); + + Y02.mac(S1, V02); + Y03.mac(S1, V03); + + //v1 + bf16 *__restrict pV13 = pV2 + (j + 2) * MMUL::size_B; + bf16 *__restrict pV14 = pV2 + (j + 3) * MMUL::size_B; + + aie::vector V12 = aie::load_v(pV13); + pV13 += MMUL::size_B * colQ * 2; + aie::vector V13 = aie::load_v(pV14); + pV14 += MMUL::size_B * colQ * 2; + + + Y12.mac(S0, V12); + Y13.mac(S0, V13); + + V12 = aie::load_v(pV13); + V13 = aie::load_v(pV14); + + Y12.mac(S1, V12); + Y13.mac(S1, V13); + + auto Y24 = aie::filter_even(Y02.template to_vector(), 32); + auto Y26 = aie::filter_even(Y03.template to_vector(), 32); + + auto Y35 = aie::filter_odd (Y12.template to_vector(), 32); + auto Y37 = aie::filter_odd (Y13.template to_vector(), 32); + + Y = aie::concat(Y24, Y35); //, Y22, Y33, Y24, Y35, Y26, Y37); + aie::store_v(pY1, Y); + pY1 += MMUL::size_C; + + Y = aie::concat(Y26, Y37); + aie::store_v(pY1, Y); + pY1 += MMUL::size_C; + } + +} + +template +void scale_div_aie(bf16 *a, bf16* o, float *l) { + + constexpr int vec_factor = 64; + const int F = N / vec_factor; + + bf16* pA1 = a; + bf16* pO1 = o; + bf16 l00 = (bf16)getInvBf16(l[0]); + aie::vector L0 = aie::broadcast(l00); + bf16 l01 = (bf16)getInvBf16(l[1]); + aie::vector L1 = aie::broadcast(l01); + bf16 l02 = (bf16)getInvBf16(l[2]); + aie::vector L2 = aie::broadcast(l02); + bf16 l03 = (bf16)getInvBf16(l[3]); + aie::vector L3 = aie::broadcast(l03); + bf16 l04 = (bf16)getInvBf16(l[4]); + aie::vector L4 = aie::broadcast(l04); + bf16 l05 = (bf16)getInvBf16(l[5]); + aie::vector L5 = aie::broadcast(l05); + bf16 l06 = (bf16)getInvBf16(l[6]); + aie::vector L6 = aie::broadcast(l06); + bf16 l07 = (bf16)getInvBf16(l[7]); + aie::vector L7 = aie::broadcast(l07); + + auto L = aie::concat(L0, L1, L2, L3, L4, L5, L6, L7); + + for (int d = 0; d < N / vec_factor; d++){ + aie::vector A0 = aie::load_v(pA1); + aie::accum AL = aie::mul(A0, L); + aie::vector AL_bf16 = AL.template to_vector(); +#if defined(__chess__) + for (int g = 0; g < KV_HEADS_PER_CU; g++) AIE_LOOP_FLATTEN { + int v_offset = g * 4; + for (int h = 0; h < Q_HEADS_PER_GROUP; h++) { + aie::vector temp = AL_bf16.extract<8>(v_offset + h); + aie::store_v(pO1, temp); + pO1 += 8; + } + } +#else + // Peano miscompiles extract<8> with a runtime index (it lowers it to a + // jump table and stores the wrong slice, which swaps Q heads within a + // GQA group). Store the vector and reload the slices from memory. + alignas(aie::vector_decl_align) bf16 al_buf[vec_factor]; + aie::store_v(al_buf, AL_bf16); + for (int g = 0; g < KV_HEADS_PER_CU; g++) { + int v_offset = g * 4; + for (int h = 0; h < Q_HEADS_PER_GROUP; h++) { + aie::store_v(pO1, aie::load_v<8>(al_buf + (v_offset + h) * 8)); + pO1 += 8; + } + } +#endif + pA1 += vec_factor; + } + +} + +#elif ATTN_IMPL == ATTN_IMPL_1x4x1 + +void calculate_l(bf16 *__restrict pS, float *__restrict c, float *__restrict l) { + using MMUL = aie::mmul; + bf16 *__restrict pS1 = pS; + + aie::vector S_up = aie::load_v<32>(pS1); + pS1 += 32; + + aie::vector S10 = aie::filter_even(S_up, 8); + aie::vector S11 = aie::filter_odd(S_up, 8); + aie::vector zeros = aie::zeros(); + + aie::vector S0 = aie::concat(S10, zeros); + aie::vector S1 = aie::concat(S11, zeros); + aie::vector ones = aie::broadcast(1); + + aie::vector acc_C00 = aie::zeros(); + + MMUL C00(acc_C00); + + C00.mac(S0, ones); + C00.mac(S1, ones); + + aie::vector sumf = C00.template to_vector(); + auto sum03 = aie::filter_even(sumf, 4); + auto sum02 = aie::filter_even(sum03, 2); + auto sum01 = aie::filter_even(sum02, 1); + + float sum0 = sum01[0]; + float sum1 = sum01[1]; + + l[0] = l[0] * c[0] + sum0; + l[1] = l[1] * c[1] + sum1; +} + +typedef float y_acc_dtype; +template +void attn_fv(bf16 *__restrict pS, bf16 *__restrict pV, y_acc_dtype *__restrict pY, float *__restrict c) { + + using MMUL = aie::mmul; + + + + y_acc_dtype *__restrict pY1 = pY; + bf16 *__restrict pS1 = pS; + + aie::vector S_up = aie::load_v<32>(pS1); + pS1 += 32; + + aie::vector S10 = aie::filter_even(S_up, 8); + aie::vector S11 = aie::filter_odd(S_up, 8); + aie::vector zeros_vec = aie::zeros(); + + aie::vector S0 = aie::concat(S10, zeros_vec); + aie::vector S1 = aie::concat(S11, zeros_vec); + + aie::vector c0 = aie::broadcast(c[0]); + aie::vector c1 = aie::broadcast(c[1]); + aie::vector c2 = aie::broadcast(c[2]); + aie::vector c3 = aie::broadcast(c[3]); + aie::vector CORRECT = aie::concat(c0, c1, c2, c3); + + bf16 *__restrict pV1 = pV; + aie::vector zeros_float = aie::zeros(); + + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(2) + for (unsigned j = 0; j < colQ; j += 4) { + //v0 + bf16 *__restrict pV01 = pV1 + (j + 0) * MMUL::size_B; + bf16 *__restrict pV02 = pV1 + (j + 1) * MMUL::size_B; + + aie::vector V00 = aie::load_v(pV01); + pV01 += MMUL::size_B * colQ; + aie::vector V01 = aie::load_v(pV02); + pV02 += MMUL::size_B * colQ; + + aie::vector acc_y00 = aie::load_v<16>(pY1); + aie::vector acc_y01 = aie::load_v<16>(pY1 + 16); + aie::vector acc_Y00 = aie::concat(acc_y00, zeros_float); + aie::vector acc_Y01 = aie::concat(acc_y01, zeros_float); + + aie::accum ACC_Y00; + aie::accum ACC_Y01; + ACC_Y00 = aie::mul(CORRECT, acc_Y00); + ACC_Y01 = aie::mul(CORRECT, acc_Y01); + + MMUL Y00(ACC_Y00); + MMUL Y01(ACC_Y01); + + + Y00.mac(S0, V00); + Y01.mac(S0, V01); + + V00 = aie::load_v(pV01); + V01 = aie::load_v(pV02); + + Y00.mac(S1, V00); + Y01.mac(S1, V01); + + auto Y0 = aie::filter_even(Y00.template to_vector(), 16); + auto Y1 = aie::filter_even (Y01.template to_vector(), 16); + + aie::store_v(pY1, Y0); + pY1 += 16; + + aie::store_v(pY1, Y1); + pY1 += 16; + + bf16 *__restrict pV03 = pV1 + (j + 2) * MMUL::size_B; + bf16 *__restrict pV04 = pV1 + (j + 3) * MMUL::size_B; + + aie::vector V02 = aie::load_v(pV03); + pV03 += MMUL::size_B * colQ; + aie::vector V03 = aie::load_v(pV04); + pV04 += MMUL::size_B * colQ; + + aie::vector acc_y02 = aie::load_v<16>(pY1); + aie::vector acc_y03 = aie::load_v<16>(pY1 + 16); + aie::vector acc_Y02 = aie::concat(acc_y02, zeros_float); + aie::vector acc_Y03 = aie::concat(acc_y03, zeros_float); + + aie::accum ACC_Y02; + aie::accum ACC_Y03; + ACC_Y02 = aie::mul(CORRECT, acc_Y02); + ACC_Y03 = aie::mul(CORRECT, acc_Y03); + + + MMUL Y02(ACC_Y02); + MMUL Y03(ACC_Y03); + + Y02.mac(S0, V02); + Y03.mac(S0, V03); + + V02 = aie::load_v(pV03); + V03 = aie::load_v(pV04); + + Y02.mac(S1, V02); + Y03.mac(S1, V03); + + auto Y2 = aie::filter_even(Y02.template to_vector(), 16); + auto Y3 = aie::filter_even(Y03.template to_vector(), 16); + + aie::store_v(pY1, Y2); + pY1 += 16; + + aie::store_v(pY1, Y3); + pY1 += 16; + } + +} + +template +void scale_div_aie(bf16 *a, bf16* o, float *l) { + + constexpr int vec_factor = 16; + const int F = N / vec_factor; + + bf16* pA1 = a; + bf16* pO1 = o; + bf16 l00 = (bf16)getInvBf16(l[0]); + aie::vector L0 = aie::broadcast(l00); + bf16 l01 = (bf16)getInvBf16(l[1]); + aie::vector L1 = aie::broadcast(l01); + + auto L = aie::concat(L0, L1); + + for (int d = 0; d < N / vec_factor; d++){ + aie::vector A0 = aie::load_v(pA1); + aie::accum AL = aie::mul(A0, L); + aie::vector AL_bf16 = AL.template to_vector(); + aie::store_v(pO1, AL_bf16); + pO1 += vec_factor; + pA1 += vec_factor; + } + +} + + +#elif ATTN_IMPL == ATTN_IMPL_1x8x1 + +void calculate_l(bf16 *__restrict pS, float *__restrict c, float *__restrict l) { + using MMUL = aie::mmul; + bf16 *__restrict pS1 = pS; + + aie::vector S_up = aie::load_v<64>(pS1); + pS1 += 64; + aie::vector S_down = aie::load_v<64>(pS1); + pS1 += 64; + + aie::vector S10 = aie::filter_even(S_up, 8); + aie::vector S11 = aie::filter_odd(S_up, 8); + aie::vector S20 = aie::filter_even(S_down, 8); + aie::vector S21 = aie::filter_odd(S_down, 8); + + aie::vector S0 = aie::concat(S10, S20); + aie::vector S1 = aie::concat(S11, S21); + aie::vector ones = aie::broadcast(1); + + aie::vector acc_C00 = aie::zeros(); + + MMUL C00(acc_C00); + + C00.mac(S0, ones); + C00.mac(S1, ones); + + aie::vector sumf = C00.template to_vector(); + auto sum03 = aie::filter_even(sumf, 4); + auto sum02 = aie::filter_even(sum03, 2); + auto sum01 = aie::filter_even(sum02, 1); + auto sum00 = aie::concat(sum01, sum01); + aie::accum sum; + sum.from_vector(sum00); + + aie::vector c_float32 = aie::load_v<8>(c); + aie::vector c_in = aie::concat(c_float32, c_float32); + + aie::vector l_float32 = aie::load_v<8>(l); + aie::vector l_in = aie::concat(l_float32, l_float32); + + aie::accum l_out; + l_out = mac_elem_16_accuracy_safe(l_in, c_in, sum, 0, 0, 0); + aie::store_v(l, l_out.template to_vector()); +} + +typedef float y_acc_dtype; +template +void attn_fv(bf16 *__restrict pS, bf16 *__restrict pV, y_acc_dtype *__restrict pY, float *__restrict c) { + + using MMUL = aie::mmul; + + y_acc_dtype *__restrict pY1 = pY; + bf16 *__restrict pS1 = pS; + + aie::vector S_up = aie::load_v<64>(pS1); + pS1 += 64; + aie::vector S_down = aie::load_v<64>(pS1); + pS1 += 64; + + aie::vector S10 = aie::filter_even(S_up, 8); + aie::vector S11 = aie::filter_odd(S_up, 8); + aie::vector S20 = aie::filter_even(S_down, 8); + aie::vector S21 = aie::filter_odd(S_down, 8); + + aie::vector S0 = aie::concat(S10, S20); + aie::vector S1 = aie::concat(S11, S21); + + aie::vector c0 = aie::broadcast(c[0]); + aie::vector c1 = aie::broadcast(c[1]); + aie::vector c2 = aie::broadcast(c[2]); + aie::vector c3 = aie::broadcast(c[3]); + aie::vector c4 = aie::broadcast(c[4]); + aie::vector c5 = aie::broadcast(c[5]); + aie::vector c6 = aie::broadcast(c[6]); + aie::vector c7 = aie::broadcast(c[7]); + aie::vector CORRECT = aie::concat(c0, c1, c2, c3, c4, c5, c6, c7); + + bf16 *__restrict pV1 = pV; + + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(2) + for (unsigned j = 0; j < colQ; j += 4) { + //v0 + bf16 *__restrict pV01 = pV1 + (j + 0) * MMUL::size_B; + bf16 *__restrict pV02 = pV1 + (j + 1) * MMUL::size_B; + bf16 *__restrict pV03 = pV1 + (j + 2) * MMUL::size_B; + bf16 *__restrict pV04 = pV1 + (j + 3) * MMUL::size_B; + + aie::vector V00 = aie::load_v(pV01); + pV01 += MMUL::size_B * colQ; + aie::vector V01 = aie::load_v(pV02); + pV02 += MMUL::size_B * colQ; + aie::vector V02 = aie::load_v(pV03); + pV03 += MMUL::size_B * colQ; + aie::vector V03 = aie::load_v(pV04); + pV04 += MMUL::size_B * colQ; + + aie::vector acc_y00 = aie::load_v(pY1); + aie::vector acc_y01 = aie::load_v(pY1 + MMUL::size_C); + aie::vector acc_y02 = aie::load_v(pY1 + MMUL::size_C * 2); + aie::vector acc_y03 = aie::load_v(pY1 + MMUL::size_C * 3); + + aie::accum ACC_Y00; + aie::accum ACC_Y01; + aie::accum ACC_Y02; + aie::accum ACC_Y03; + ACC_Y00 = aie::mul(CORRECT, acc_y00); + ACC_Y01 = aie::mul(CORRECT, acc_y01); + ACC_Y02 = aie::mul(CORRECT, acc_y02); + ACC_Y03 = aie::mul(CORRECT, acc_y03); + + MMUL Y00(ACC_Y00); + MMUL Y01(ACC_Y01); + MMUL Y02(ACC_Y02); + MMUL Y03(ACC_Y03); + + Y00.mac(S0, V00); + Y01.mac(S0, V01); + Y02.mac(S0, V02); + Y03.mac(S0, V03); + + V00 = aie::load_v(pV01); + V01 = aie::load_v(pV02); + V02 = aie::load_v(pV03); + V03 = aie::load_v(pV04); + + Y00.mac(S1, V00); + Y01.mac(S1, V01); + Y02.mac(S1, V02); + Y03.mac(S1, V03); + + aie::store_v(pY1, Y00.template to_vector()); + pY1 += MMUL::size_C; + aie::store_v(pY1, Y01.template to_vector()); + pY1 += MMUL::size_C; + aie::store_v(pY1, Y02.template to_vector()); + pY1 += MMUL::size_C; + aie::store_v(pY1, Y03.template to_vector()); + pY1 += MMUL::size_C; + } + +} + +template +void scale_div_aie(bf16 *a, bf16* o, float *l) { + + constexpr int vec_factor = 64; + const int F = N / vec_factor; + + bf16* pA1 = a; + bf16* pO1 = o; + bf16 l00 = (bf16)getInvBf16(l[0]); + aie::vector L0 = aie::broadcast(l00); + bf16 l01 = (bf16)getInvBf16(l[1]); + aie::vector L1 = aie::broadcast(l01); + bf16 l02 = (bf16)getInvBf16(l[2]); + aie::vector L2 = aie::broadcast(l02); + bf16 l03 = (bf16)getInvBf16(l[3]); + aie::vector L3 = aie::broadcast(l03); + bf16 l04 = (bf16)getInvBf16(l[4]); + aie::vector L4 = aie::broadcast(l04); + bf16 l05 = (bf16)getInvBf16(l[5]); + aie::vector L5 = aie::broadcast(l05); + bf16 l06 = (bf16)getInvBf16(l[6]); + aie::vector L6 = aie::broadcast(l06); + bf16 l07 = (bf16)getInvBf16(l[7]); + aie::vector L7 = aie::broadcast(l07); + auto L = aie::concat(L0, L1, L2, L3, L4, L5, L6, L7); + + for (int d = 0; d < N / vec_factor; d++){ + aie::vector A0 = aie::load_v(pA1); + aie::accum AL = aie::mul(A0, L); + aie::vector AL_bf16 = AL.template to_vector(); +#if defined(__chess__) + for (int h = 0; h < Q_HEADS_PER_GROUP; h++) { + aie::vector temp = AL_bf16.extract<8>(h); + aie::store_v(pO1, temp); + pO1 += 8; + } +#else + // Peano: no runtime-index extract, see the 2x4x1 scale_div_aie above. + alignas(aie::vector_decl_align) bf16 al_buf[vec_factor]; + aie::store_v(al_buf, AL_bf16); + for (int h = 0; h < Q_HEADS_PER_GROUP; h++) { + aie::store_v(pO1, aie::load_v<8>(al_buf + h * 8)); + pO1 += 8; + } +#endif + pA1 += vec_factor; + } + +} + +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/attn_qk.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/attn_qk.cc new file mode 100644 index 000000000..0679e505a --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/attn_qk.cc @@ -0,0 +1,384 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#include "lut_based_ops.h" +#include "aie_kernel_utils.h" +#include "aie_array_layout.h" + + +inline aie::vector update(bf16* m, float* c, aie::vector& out, aie::mask<16>& mask, bool& is_first); +template +void _attn_qk(bf16 *__restrict pQ, bf16 *__restrict pK, bf16 *__restrict pY, bf16 *__restrict m, float *__restrict c, aie::mask<16>& mask, bool& is_first); + + + +constexpr int q_prod_lock = 0; +constexpr int q_cons_lock = 1; +constexpr int k_prod_lock = 2; +constexpr int k_cons_lock = 3; +constexpr int s_prod_lock = 4; +constexpr int s_cons_lock = 5; +// constexpr int l_prod_lock = 6; +constexpr int l_cons_lock = 7; + +extern "C"{ + +void attn_qk( + bf16 *__restrict q_ping, + bf16 *__restrict q_pong, + bf16 *__restrict k_ping, + bf16 *__restrict k_pong, + bf16 *__restrict s_ping, + bf16 *__restrict s_pong, + int* L +) +{ + AIE_PERSIST_ZERO static bool is_ql_ping = false; + AIE_PERSIST_ZERO static bool is_ksc_ping = false; + alignas(aie::vector_decl_align) static bf16 m[16] = {}; + alignas(aie::vector_decl_align) AIE_PERSIST_ZERO static float c_local[8] = {}; +#if defined(__chess__) + static const aie::vector neg_inf = aie::broadcast(-0x1.FEp127f); + static const aie::vector idx = aie::vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +#else + // Peano: build these at runtime. A function-local `static const` with a + // non-trivial constructor needs a guard variable in .bss, and Peano's CDO + // loader does not zero .bss, so the guard can already be set on entry and + // the constructor never runs, leaving both vectors undefined. + aie::vector neg_inf = aie::broadcast(-0x1.FEp127f); + aie::vector idx; + for (int _i = 0; _i < 16; _i++) idx[_i] = _i + 1; +#endif + + _lock_acquire(q_cons_lock); + is_ql_ping = !is_ql_ping; + // bf16 *l = is_ql_ping ? l_ping : l_pong; + bf16 *q = is_ql_ping ? q_ping : q_pong; + // aie::store_v(l_local, zero); + aie::store_v(m, neg_inf); + int rounds = (L[0] + 15) / 16; + _lock_release(l_cons_lock); + AIE_LOCK_LOOP_CTR i = L[0]; + do { + _lock_acquire(k_cons_lock); + _lock_acquire(s_prod_lock); + is_ksc_ping = !is_ksc_ping; + bf16 *k = is_ksc_ping ? k_ping : k_pong; + bf16 *s = is_ksc_ping ? s_ping : s_pong; + float *c = (float *)(s + Q_HEADS_PADDED_PER_CU * 16); + bool is_first = (i == L[0]); + aie::mask<16> mask = aie::le(idx, (i < 16) ? i : 16); + _attn_qk(q, k, s, m, c_local, mask, is_first); + aie::vector c_vec = aie::load_v<8>(c_local); + aie::store_v(c, c_vec); + _lock_release(k_prod_lock); + _lock_release(s_cons_lock); + i -= 16; + } while (i > 0); + _lock_release(q_prod_lock); +} + +} + + +inline aie::vector update(bf16* m, float* c, aie::vector& out, aie::mask<16>& mask, bool& is_first){ + aie::vector masked_vm = aie::select((bf16)(-0x1.FEp127f), out, mask); + bf16 vm = aie::reduce_max(masked_vm); + bf16 vmax = aie::max(vm, (bf16) *m); + aie::vector Vecsub = aie::sub(out, vmax); + + constexpr int min_clamp = -87.0f; + constexpr int max_clamp = 88.0f; + aie::vector min_value = aie::broadcast(min_clamp); + aie::vector max_value = aie::broadcast(max_clamp); + + aie::vector Vec = aie::clamp(Vecsub, min_value, max_value); + aie::accum Outvec = getExpBf16(Vec); + Vec = Outvec.template to_vector(0); + Vec = aie::select((bf16)0, Vec, mask); + + bf16 correct = aie::sub((bf16) *m, vmax); + aie::vector correct_vec = aie::broadcast(correct); + correct_vec = aie::clamp(correct_vec, min_value, max_value); + aie::accum correct_acc = getExpBf16(correct_vec); + aie::vector correct_float = correct_acc.template to_vector(); + + *m = (float)vmax; + *c = (float)correct_float.get(0); + return Vec; +} + +#if ATTN_IMPL == ATTN_IMPL_2x4x1 + +template +void _attn_qk(bf16 *__restrict pQ, bf16 *__restrict pK, bfloat16 *__restrict pY, bf16 *__restrict m, float *__restrict c, aie::mask<16>& mask, bool& is_first) { + + using MMUL = aie::mmul; + + bfloat16 *__restrict pY1 = pY; + // g times K + bf16 *__restrict pK1 = pK; + bf16 *__restrict pK2 = pK + 1 * MMUL::size_B; + + { + bf16 *__restrict pQ1 = pQ; + aie::vector A0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + aie::vector B00 = aie::load_v(pK1); + aie::vector B0 = aie::transpose(B00, 8, 8); + pK1 += MMUL::size_B * 2; + aie::vector B01 = aie::load_v(pK2); + aie::vector B1 = aie::transpose(B01, 8, 8); + pK2 += MMUL::size_B * 2; + + aie::vector acc_C00 = aie::zeros(); + aie::vector acc_C01 = aie::zeros(); + + MMUL C00(acc_C00); + MMUL C01(acc_C01); + + C00.mac(A0, B0); + C01.mac(A0, B1); + + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(7) + for (unsigned i = 1; i < colQ; ++i) { + A0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + + B00 = aie::load_v(pK1); + B0 = aie::transpose(B00, 8, 8); + pK1 += MMUL::size_B * 2; + B01 = aie::load_v(pK2); + B1 = aie::transpose(B01, 8, 8); + pK2 += MMUL::size_B * 2; + + C00.mac(A0, B0); + C01.mac(A0, B1); + } + auto mout0 = aie::interleave_zip(C00.template to_vector(), C01.template to_vector(), 8); + + aie::vector mout2, mout3; + + mout2 = aie::filter_even(mout0.first, 32); + mout3 = aie::filter_odd (mout0.first, 32); + + mout2 = aie::mul(mout2, (bf16)ATTN_SCALE).template to_vector(0); + mout3 = aie::mul(mout3, (bf16)ATTN_SCALE).template to_vector(0); + + + aie::vector out[4]; + out[0] = aie::filter_even(mout2, 16); + out[1] = aie::filter_odd(mout2, 16); + out[2] = aie::filter_even(mout3, 16); + out[3] = aie::filter_odd(mout3, 16); + + AIE_LOOP_UNROLL_FULL + for (int h = 0; h < Q_HEADS_PER_GROUP; h++) { + aie::vector vec = update(m + h, c + h, out[h], mask, is_first); + aie::store_v(pY1, vec); + pY1 += 16; + } + pY1 += 16 * ATTN_GROUPS_PADDING; + } + { + bf16 *__restrict pQ1 = pQ; + aie::vector A0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + aie::vector B00 = aie::load_v(pK1); + aie::vector B0 = aie::transpose(B00, 8, 8); + pK1 += MMUL::size_B * 2; + aie::vector B01 = aie::load_v(pK2); + aie::vector B1 = aie::transpose(B01, 8, 8); + pK2 += MMUL::size_B * 2; + + aie::vector acc_C00 = aie::zeros(); + aie::vector acc_C01 = aie::zeros(); + + MMUL C00(acc_C00); + MMUL C01(acc_C01); + + C00.mac(A0, B0); + C01.mac(A0, B1); + + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(7) + for (unsigned i = 1; i < colQ; ++i) { + A0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + + B00 = aie::load_v(pK1); + B0 = aie::transpose(B00, 8, 8); + pK1 += MMUL::size_B * 2; + B01 = aie::load_v(pK2); + B1 = aie::transpose(B01, 8, 8); + pK2 += MMUL::size_B * 2; + + C00.mac(A0, B0); + C01.mac(A0, B1); + } + auto mout0 = aie::interleave_zip(C00.template to_vector(), C01.template to_vector(), 8); + + aie::vector mout2, mout3; + mout2 = aie::filter_even(mout0.second, 32); + mout3 = aie::filter_odd(mout0.second, 32); + mout2 = aie::mul(mout2, (bf16)ATTN_SCALE).template to_vector(0); + mout3 = aie::mul(mout3, (bf16)ATTN_SCALE).template to_vector(0); + + aie::vector out[4]; + out[0] = aie::filter_even(mout2, 16); + out[1] = aie::filter_odd(mout2, 16); + out[2] = aie::filter_even(mout3, 16); + out[3] = aie::filter_odd(mout3, 16); + AIE_LOOP_UNROLL_FULL + for (int h = 0; h < Q_HEADS_PER_GROUP; h++) { + aie::vector vec = update(m + 4 + h, c + 4 + h, out[h], mask, is_first); + aie::store_v(pY1, vec); + pY1 += 16; + } + pY1 += 16 * ATTN_GROUPS_PADDING; + } +} + +#elif ATTN_IMPL == ATTN_IMPL_1x4x1 + + +template +void _attn_qk(bf16 *__restrict pQ, bf16 *__restrict pK, bfloat16 *__restrict pY, bf16 *__restrict m, float *__restrict c, aie::mask<16>& mask, bool& is_first) { + + using MMUL = aie::mmul; + + + + bfloat16 *__restrict pY1 = pY; + // g times K + bf16 *__restrict pK1 = pK; + bf16 *__restrict pK2 = pK + 1 * MMUL::size_B; + { + bf16 *__restrict pQ1 = pQ; + aie::vector A0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + aie::vector B00 = aie::load_v(pK1); + aie::vector B0 = aie::transpose(B00, 8, 8); + pK1 += MMUL::size_B * 2; + aie::vector B01 = aie::load_v(pK2); + aie::vector B1 = aie::transpose(B01, 8, 8); + pK2 += MMUL::size_B * 2; + + aie::vector acc_C00 = aie::zeros(); + aie::vector acc_C01 = aie::zeros(); + + MMUL C00(acc_C00); + MMUL C01(acc_C01); + + C00.mac(A0, B0); + C01.mac(A0, B1); + + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(7) + for (unsigned i = 1; i < colQ; ++i) { + A0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + + B00 = aie::load_v(pK1); + B0 = aie::transpose(B00, 8, 8); + pK1 += MMUL::size_B * 2; + B01 = aie::load_v(pK2); + B1 = aie::transpose(B01, 8, 8); + pK2 += MMUL::size_B * 2; + + C00.mac(A0, B0); + C01.mac(A0, B1); + } + auto mout0 = aie::interleave_zip(C00.template to_vector(), C01.template to_vector(), 8); + + aie::vector mout2, mout3; + + mout2 = aie::filter_even(mout0.first, 16); + mout3 = aie::filter_odd (mout0.first, 16); + + mout2 = aie::mul(mout2, (bf16)ATTN_SCALE).template to_vector(0); + mout3 = aie::mul(mout3, (bf16)ATTN_SCALE).template to_vector(0); + + aie::vector vec = update(m, c, mout2, mask, is_first); + aie::store_v(pY1, vec); + pY1 += 16; + vec = update(m + 1, c + 1, mout3, mask, is_first); + aie::store_v(pY1, vec); + pY1 += 16; + } + +} + + +#elif ATTN_IMPL == ATTN_IMPL_1x8x1 + + +template +void _attn_qk(bf16 *__restrict pQ, bf16 *__restrict pK, bfloat16 *__restrict pY, bf16 *__restrict m, float *__restrict c, aie::mask<16>& mask, bool& is_first) { + + using MMUL = aie::mmul; + + bfloat16 *__restrict pY1 = pY; + // g times K + bf16 *__restrict pK1 = pK; + bf16 *__restrict pK2 = pK + 1 * MMUL::size_B; + { + bf16 *__restrict pQ1 = pQ; + aie::vector A0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + aie::vector B00 = aie::load_v(pK1); + aie::vector B0 = aie::transpose(B00, 8, 8); + pK1 += MMUL::size_B * 2; + aie::vector B01 = aie::load_v(pK2); + aie::vector B1 = aie::transpose(B01, 8, 8); + pK2 += MMUL::size_B * 2; + + aie::vector acc_C00 = aie::zeros(); + aie::vector acc_C01 = aie::zeros(); + + MMUL C00(acc_C00); + MMUL C01(acc_C01); + + C00.mac(A0, B0); + C01.mac(A0, B1); + + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(7) + for (unsigned i = 1; i < colQ; ++i) { + A0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + + B00 = aie::load_v(pK1); + B0 = aie::transpose(B00, 8, 8); + pK1 += MMUL::size_B * 2; + B01 = aie::load_v(pK2); + B1 = aie::transpose(B01, 8, 8); + pK2 += MMUL::size_B * 2; + + C00.mac(A0, B0); + C01.mac(A0, B1); + } + auto mout0 = aie::interleave_zip(C00.template to_vector(), C01.template to_vector(), 8); + + aie::vector mout2 = aie::mul(mout0.first, (bf16)ATTN_SCALE).template to_vector(0); + aie::vector mout3 = aie::mul(mout0.second, (bf16)ATTN_SCALE).template to_vector(0); + + aie::vector out[8]; + + out[0] = mout2.extract<16>(0); + out[1] = mout2.extract<16>(1); + out[2] = mout2.extract<16>(2); + out[3] = mout2.extract<16>(3); + out[4] = mout3.extract<16>(0); + out[5] = mout3.extract<16>(1); + out[6] = mout3.extract<16>(2); + out[7] = mout3.extract<16>(3); + + for (int h = 0; h < Q_HEADS_PER_CU; h++) { + aie::vector vec = update(m + h, c + h, out[h], mask, is_first); + aie::store_v(pY1, vec); + pY1 += 16; + } + pY1 += ATTN_GROUPS_PADDING * 16; + } + +} + +#endif + diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/bf16_limb_math.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/bf16_limb_math.hpp new file mode 100644 index 000000000..a74ebc98b --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/bf16_limb_math.hpp @@ -0,0 +1,318 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __BF16_LIMB_MATH_HPP__ +#define __BF16_LIMB_MATH_HPP__ + +// --------------------------------------------------------------------------- +// fp32 x bf16 products on the native bf16 MMUL datapath. +// +// For a one-off fp32 x fp32 product, use aie::mul / aie::mac directly. Those +// lower to the vendor's emulation (mul_elem_N_accuracy_safe in +// $AIETOOLS/data/aie2p/lib/me_vmult_float_emulated.h, via +// detail/aie2p/mul_acc32_fp.hpp), which splits BOTH operands into 3 bf16 limbs +// and issues all 9 cross products for an fp32-exact result. The cheaper +// mul_elem_N_accuracy_fast (6 MACs) and _low (3 MACs) are always defined too, +// and are callable by name per call site -- the AIE2_FP32_EMULATION_ACCURACY_* +// macros only pick which one aie::mul binds to, so you do not need a +// translation-unit-wide flag to reach them. +// +// Two things the vendor cannot express, which is what this header is for: +// +// 1. Asymmetric fp32 x bf16: one operand is fp32, the other is already exactly +// representable in bf16 (it came from a bf16 buffer). Only the fp32 side +// needs splitting, so the product costs one MAC per limb -- 2 or 3, not 9. +// The vendor has no asymmetric entry point at all; the cheapest thing it can +// do here is _low's 3 full products. +// +// 2. Operands you already hold as limbs. split_f32_3() once, then feed the +// mac_limbs3_* forms -- useful when the same limbs serve several products, +// when you also want l0 as the plain bf16 rounding of x, or when the split +// is invariant in a way the compiler cannot prove (behind a pointer it +// cannot alias-analyse, or a call it did not inline). +// +// What is NOT a reason to use this header: saving a redundant split. The +// scheduler already hoists a loop-invariant split out of a loop body, including +// one buried inside the vendor's emulation -- measured, an aie::mul with one +// invariant operand leaves a single split (3 VCONV + 2 VMSC) in the body, not +// two. The win over the vendor default is the product set and its reduction +// shape, not the split. +// +// Accuracy, measured against a float64 reference over 4e5 operand pairs drawn +// across a ~2^12 dynamic range, worst-case relative error: +// +// op MACs max rel err ~mantissa bits +// plain bf16 x bf16 1 3.9e-03 8 +// mac_f32_bf16_low 2 7.6e-06 17 +// mac_f32_bf16_safe 3 6.0e-08 24 (fp32-exact) +// mac_limbs3_tri (f32xf32) 6 6.0e-08 24 (fp32-exact) +// aie::mac on 2x fp32 9 6.0e-08 24 (vendor, f32xf32) +// +// fp32 carries 24 mantissa bits, so the 3-limb form is exact for practical +// purposes and matches the vendor's 9-MAC safe tier at a third of the cost. +// The 2-limb form drops the last limb (~2^-24 of the operand) for one fewer +// MAC; it is the right pick when the product feeds a bf16 output anyway, and +// the wrong pick for anything that compounds over a sequence, like a decay gate. +// +// The 3 products the triangular fp32 x fp32 form drops (l1*l2, l2*l1, l2*l2) +// are all <= 2^-24 of the result, i.e. below where an fp32 mantissa can hold +// them, so 6 MACs is not an approximation of the 9-MAC form -- it is the same +// answer with the provably-zero terms removed. +// +// Note on rounding: to_vector() rounds using the core's current +// rounding mode. The numbers above assume the default round-to-nearest-even. +// --------------------------------------------------------------------------- + +#include +#include + +namespace bf16_limb { + +// A bf16 vector of ones, used to subtract a limb back out inside a single msc +// rather than converting to fp32 and doing a separate aie::sub. +template +inline aie::vector ones() +{ + return aie::broadcast((bfloat16)1.0f); +} + +// --------------------------------------------------------------------------- +// Splitting +// --------------------------------------------------------------------------- + +// Split x into 2 bf16 limbs with x ~= l0 + l1, carrying ~16 of fp32's 24 +// mantissa bits. Each residual is exact in fp32: l0 is within a factor of two +// of x, so x - l0 cancels without rounding. +template +inline std::pair, aie::vector> +split_f32(aie::vector x) +{ + const aie::vector one = ones(); + + aie::accum r0; + r0.from_vector(x); + aie::vector l0 = r0.template to_vector(); + + aie::accum r1 = aie::msc(r0, l0, one); // r1 = x - l0 + aie::vector l1 = r1.template to_vector(); + + return {l0, l1}; +} + +// Split x into 3 bf16 limbs with x ~= l0 + l1 + l2. 3 x 8 = 24 bits covers the +// whole fp32 mantissa, so the triple is exact up to the exponent range. +template +struct limbs3 { + aie::vector l0, l1, l2; +}; + +template +inline limbs3 split_f32_3(aie::vector x) +{ + const aie::vector one = ones(); + limbs3 out; + + aie::accum r0; + r0.from_vector(x); + out.l0 = r0.template to_vector(); + + aie::accum r1 = aie::msc(r0, out.l0, one); // x - l0 + out.l1 = r1.template to_vector(); + + aie::accum r2 = aie::msc(r1, out.l1, one); // x - l0 - l1 + out.l2 = r2.template to_vector(); + + return out; +} + +// --------------------------------------------------------------------------- +// acc += a * b, where a is fp32 and b is already exact in bf16 +// +// Limbs are accumulated smallest-first, matching the vendor's ordering in +// mac_elem_N_accuracy_safe, so the small terms combine before meeting the +// large one instead of being rounded off against it. +// --------------------------------------------------------------------------- + +// 2 MACs, ~17 bits. +template +inline aie::accum mac_f32_bf16_low( + aie::accum acc, + aie::vector a, + aie::vector b) +{ + auto [l0, l1] = split_f32(a); + acc = aie::mac(acc, b, l1); + acc = aie::mac(acc, b, l0); + return acc; +} + +// 3 MACs, ~24 bits -- fp32-exact, same accuracy as the vendor's 9-MAC path. +template +inline aie::accum mac_f32_bf16_safe( + aie::accum acc, + aie::vector a, + aie::vector b) +{ + limbs3 l = split_f32_3(a); + acc = aie::mac(acc, b, l.l2); + acc = aie::mac(acc, b, l.l1); + acc = aie::mac(acc, b, l.l0); + return acc; +} + +// --------------------------------------------------------------------------- +// Pre-split operands +// +// Take the limbs directly when you already have them -- reused across several +// products, wanted as a bf16 value in their own right (l0 IS the RNE bf16 of x), +// or split outside a loop the compiler cannot prove invariance across. +// --------------------------------------------------------------------------- + +template +inline aie::accum mac_limbs_bf16( + aie::accum acc, + aie::vector l0, + aie::vector l1, + aie::vector b) +{ + acc = aie::mac(acc, b, l1); + acc = aie::mac(acc, b, l0); + return acc; +} + +template +inline aie::accum mac_limbs_bf16( + aie::accum acc, + limbs3 l, + aie::vector b) +{ + acc = aie::mac(acc, b, l.l2); + acc = aie::mac(acc, b, l.l1); + acc = aie::mac(acc, b, l.l0); + return acc; +} + +// acc += a * b, both fp32, both pre-split into 3 limbs. +// +// Only the 6 products with i+j <= 2 are issued. Limb i carries magnitude +// ~2^-8i of its operand, so a dropped term l_i*l_j is ~2^-8(i+j) <= 2^-24 of +// the result -- at or below the fp32 mantissa floor. That is why this matches +// the vendor's 9-product safe tier bit-for-bit in practice rather than +// approximating it. +// +// Against the vendor default this is 6 MACs through an accumulator chain in +// place of 9 VMULs into an 8-deep serial VADD tree -- 26 bundles vs 71 at +// N=32. mul_elem_N_accuracy_fast issues the same 6 products and is callable by +// name; reach for this form when you want the limbs themselves, or when the +// other operand is bf16-exact and belongs in mac_limbs_bf16 instead. +template +inline aie::accum mac_limbs3_tri( + aie::accum acc, + const limbs3& a, + const limbs3& b) +{ + acc = aie::mac(acc, a.l2, b.l0); + acc = aie::mac(acc, a.l1, b.l1); + acc = aie::mac(acc, a.l0, b.l2); + acc = aie::mac(acc, a.l1, b.l0); + acc = aie::mac(acc, a.l0, b.l1); + acc = aie::mac(acc, a.l0, b.l0); + return acc; +} + +// Same, with the second operand still packed as fp32. Splits b in-loop. +template +inline aie::accum mac_limbs3_f32_tri( + aie::accum acc, + const limbs3& a, + aie::vector b) +{ + return mac_limbs3_tri(acc, a, split_f32_3(b)); +} + +// acc -= a * b, the subtracting counterparts of the two above. +template +inline aie::accum msc_limbs3_tri( + aie::accum acc, + const limbs3& a, + const limbs3& b) +{ + acc = aie::msc(acc, a.l2, b.l0); + acc = aie::msc(acc, a.l1, b.l1); + acc = aie::msc(acc, a.l0, b.l2); + acc = aie::msc(acc, a.l1, b.l0); + acc = aie::msc(acc, a.l0, b.l1); + acc = aie::msc(acc, a.l0, b.l0); + return acc; +} + +template +inline aie::accum msc_limbs3_f32_tri( + aie::accum acc, + const limbs3& a, + aie::vector b) +{ + return msc_limbs3_tri(acc, a, split_f32_3(b)); +} + +// --------------------------------------------------------------------------- +// Split-accumulator forms, for reduction loops +// +// In a loop that accumulates over many terms, chaining both limb MACs into one +// accumulator makes the loop-carried dependency two MACs deep and sets the +// initiation interval accordingly. Giving each limb its own accumulator keeps +// each chain one MAC deep; the caller folds them together once, after the loop, +// with reduce(). +// --------------------------------------------------------------------------- + +// 2 MACs into 2 independent accumulators. +template +inline void mac_f32_bf16_low( + aie::accum& acc0, + aie::accum& acc1, + aie::vector a, + aie::vector b) +{ + auto [l0, l1] = split_f32(a); + acc0 = aie::mac(acc0, b, l0); + acc1 = aie::mac(acc1, b, l1); +} + +// 3 MACs into 3 independent accumulators. +template +inline void mac_f32_bf16_safe( + aie::accum& acc0, + aie::accum& acc1, + aie::accum& acc2, + aie::vector a, + aie::vector b) +{ + limbs3 l = split_f32_3(a); + acc0 = aie::mac(acc0, b, l.l0); + acc1 = aie::mac(acc1, b, l.l1); + acc2 = aie::mac(acc2, b, l.l2); +} + +// Fold split accumulators back together, smallest-first. +template +inline aie::accum reduce( + aie::accum acc0, + aie::accum acc1) +{ + aie::accum out; + out.from_vector(aie::add(acc1.template to_vector(), + acc0.template to_vector())); + return out; +} + +template +inline aie::accum reduce( + aie::accum acc0, + aie::accum acc1, + aie::accum acc2) +{ + return reduce(acc0, reduce(acc1, acc2)); +} + +} // namespace bf16_limb + +#endif // __BF16_LIMB_MATH_HPP__ diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/common_external.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/common_external.hpp new file mode 100644 index 000000000..092ee72f2 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/common_external.hpp @@ -0,0 +1,40 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __COMMON_EXTERNAL_HPP__ +#define __COMMON_EXTERNAL_HPP__ + + + + + + + + + + + +#include +#include +#include +#include + + + + + +extern "C"{ + + void zero_int32_1(int32 *pt) + { + *pt = 0; + } + + void zero_int32_array(int32 *pt, int size) + { + for(int i = 0; i < size; i++){ + *(pt + i) = 0; + } + } +} + +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/flm_rsqrt.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/flm_rsqrt.h new file mode 100644 index 000000000..12ec952d7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/flm_rsqrt.h @@ -0,0 +1,9 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#pragma once + +#include + +// 1 / sqrt(x) for a positive float: one hardware invsqrt instruction. Keep x a float. +static inline float flm_rsqrt(float x) { return aie::invsqrt(x); } diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/gate.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/gate.cc new file mode 100644 index 000000000..497e97076 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/gate.cc @@ -0,0 +1,80 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +// Attention output gate, adapted from Qwen3_6/qwen3_6_moe_decoding/kernels/gate.cc +// (sigmoid only): y = attn_out * sigmoid(gate), DQ values per token. + +#include "aie_kernel_utils.h" +#include "aie_array_layout.h" + +// sigmoid(x) = (tanh(x / 2) + 1) / 2 +template +aie::vector getSigmoidBf16_nonLUT(aie::vector x){ + const bfloat16 half = 0.5f; + const bfloat16 one = 1.0f; + aie::vector v_half = aie::broadcast(half); + aie::vector v_one = aie::broadcast(one); + aie::accum x_mul_half = aie::mul(x, v_half); + aie::vector tanh_x_half = aie::tanh(x_mul_half.template to_vector()); + aie::vector tanh_x_half_plus_one = aie::add(tanh_x_half, v_one); + return aie::mul(tanh_x_half_plus_one, v_half); +} + +// sigmoid(gate) * attn_out in one pass +template +void activate_and_apply_gate_sigmoid(bf16 * y, const bf16 * gate, const bf16 * attn_out){ + const bf16* gate_ptr_0 = gate; + const bf16* gate_ptr_1 = gate + 16; + const bf16* attn_out_ptr_0 = attn_out; + const bf16* attn_out_ptr_1 = attn_out + 16; + bf16* y_ptr_0 = y; + bf16* y_ptr_1 = y + 16; + for (int i = 0; i < L; i += 32) { + aie::vector gate_vec_0 = aie::load_v<16>(gate_ptr_0); + aie::vector gate_vec_1 = aie::load_v<16>(gate_ptr_1); + aie::vector sig_vec_0 = getSigmoidBf16_nonLUT<16>(gate_vec_0); + aie::vector sig_vec_1 = getSigmoidBf16_nonLUT<16>(gate_vec_1); + aie::vector attn_out_vec_0 = aie::load_v<16>(attn_out_ptr_0); + aie::vector attn_out_vec_1 = aie::load_v<16>(attn_out_ptr_1); + aie::vector y_vec_0 = aie::mul(sig_vec_0, attn_out_vec_0); + aie::vector y_vec_1 = aie::mul(sig_vec_1, attn_out_vec_1); + aie::store_v(y_ptr_0, y_vec_0); + aie::store_v(y_ptr_1, y_vec_1); + gate_ptr_0 += 32; + gate_ptr_1 += 32; + attn_out_ptr_0 += 32; + attn_out_ptr_1 += 32; + y_ptr_0 += 32; + y_ptr_1 += 32; + } +} + +constexpr int gate_prod_lock = 0; +constexpr int gate_cons_lock = 1; +constexpr int attn_out_prod_lock = 2; +constexpr int attn_out_cons_lock = 3; +constexpr int gated_attn_out_prod_lock = 4; +constexpr int gated_attn_out_cons_lock = 5; + +extern "C" { + +// One decoder layer per call. The gated output goes to o_proj once per +// row-block round of the proj engine (O_DOWN_REPEATS sends). +void gate( + bf16 * y, + bf16 * gate, + bf16 * attn_out +) +{ + _lock_acquire(gate_cons_lock); + _lock_acquire(attn_out_cons_lock); + _lock_acquire(gated_attn_out_prod_lock, O_DOWN_REPEATS); + + activate_and_apply_gate_sigmoid(y, gate, attn_out); + + _lock_release(gate_prod_lock); + _lock_release(attn_out_prod_lock); + _lock_release(gated_attn_out_cons_lock, O_DOWN_REPEATS); +} + +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/glu.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/glu.cc new file mode 100644 index 000000000..7e1425584 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/glu.cc @@ -0,0 +1,351 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "aie_kernel_utils.h" +#include "aie_array_layout.h" +#include "lut_based_ops.h" +#include "nonLinearFunction.h" +#include "zero.h" + +// y = silu(gate) * up +template +void pseduo_glu(bf16 * y_ptr, bf16 * gate_ptr, bf16 * hid_ptr) { + + constexpr int vec_Size = 32; + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(L/vec_Size, L/vec_Size) + for (int i = 0; i < L ; i += vec_Size) { + aie::vector gate_vec = aie::load_v(gate_ptr + i); + aie::vector hid_vec = aie::load_v(hid_ptr + i); + gate_vec = getSiluBf16_nonLUT(gate_vec); + aie::vector y_vec = aie::mul(gate_vec, hid_vec); + aie::store_v(y_ptr + i, y_vec); + } +} + +// does the following operation +// output = vec*scalar + output + +template +void mul_scalar_accum(float*output_ptr, bf16* in_ptr, float scalar){ + constexpr int vecSize=32; + static_assert(L%vecSize == 0); + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(L/vecSize, L/vecSize) + for(int i = 0; i < L; i+=vecSize){ + aie::vector in_vec = aie::load_v(in_ptr+i); + + aie::accum in_vec_acc; + in_vec_acc.from_vector(in_vec); + + aie::vector in_vec_mul = aie::mul( + in_vec_acc.template to_vector(), scalar); + + + aie::vector acc_vec = aie::load_v(output_ptr+i); + + aie::vector res = aie::add(in_vec_mul, acc_vec); + + aie::store_v( output_ptr+i, res ); + } +} + + + +template +void send_to_proj_x( + int out_pkt_id, + bf16* out_buffer, + bool *is_to_proj_x_slice_ping_ptr, + bf16* to_proj_x_slice_With_pkt_ping, + bf16* to_proj_x_slice_With_pkt_pong, + int to_proj_x_slice_prod_lock, + int to_proj_x_slice_cons_lock +){ + + + uint32_t* to_proj_x_slice_pkt_ping = reinterpret_cast(to_proj_x_slice_With_pkt_ping+14); + uint32_t* to_proj_x_slice_pkt_pong = reinterpret_cast(to_proj_x_slice_With_pkt_pong+14); + bf16* to_proj_x_slice_data_ping = to_proj_x_slice_With_pkt_ping+16; + bf16* to_proj_x_slice_data_pong = to_proj_x_slice_With_pkt_pong+ 16; + + + + // setup the pkt_id for this + *to_proj_x_slice_pkt_ping = out_pkt_id; + *to_proj_x_slice_pkt_pong = out_pkt_id; + static_assert(OUT_SIZE % PROJ_X_SLICE == 0); + for(AIE_LOCK_LOOP_CTR j = 0; j ( + to_proj_x_slice_data_ping, out_buffer+j + ); + }else{ + copy_bf16_to_bf16( + to_proj_x_slice_data_pong, out_buffer+j + ); + } + + _lock_release(to_proj_x_slice_cons_lock,1); + } +} + + +constexpr int x_prod_lock = 0; +constexpr int x_cons_lock = 1; +constexpr int to_proj_x_slice_prod_lock = 2; +constexpr int to_proj_x_slice_cons_lock = 3; +constexpr int D_out_prod_lock = 4; +constexpr int D_out_con_lock = 5; +constexpr int D_in_prod_lock = 6; +constexpr int D_in_con_lock = 7; + +constexpr int glu_request_router_send_lock = 12; + + +extern "C" { +AIE_PERSIST_ZERO static bool is_glu_slice_in_ping = false; +AIE_PERSIST_ZERO static bool is_to_proj_x_slice_ping = false; + + +void receive_down( + size_t &share_expert_result_offset, + float* share_expert_result, + + float* expert_score, // assume already in the right offset + bool *is_glu_slice_in_ping_ptr, + const bf16 * glu_slice_in_buffer_ping, + const bf16 * glu_slice_in_buffer_pong +){ + + static_assert( (NUM_MVM_COLUMN*MODEL_DIM)% GLU_SLICE == 0 ); + static_assert( NUM_PROJ_OUT_PER_GLU_SLICE *PER_PROJ_OUTPUT_SLICE ==GLU_SLICE); + // One slice is NUM_PROJ_OUT_PER_GLU_SLICE proj rounds (1 with GLU_SLICE = 512), + // each ordered by column, i.e. by expert: + // expert-0-down[0-127], expert-1-down[0-127], expert-2-down[0-127], expert-3-down[0-127] + // then the next round's expert-0-down[128-255], expert-1-down, ... + + *(is_glu_slice_in_ping_ptr) = !*(is_glu_slice_in_ping_ptr); + bf16* x_using = *(is_glu_slice_in_ping_ptr) ? const_cast(glu_slice_in_buffer_ping) : const_cast(glu_slice_in_buffer_pong); + _lock_acquire(x_cons_lock); + + + for(int exp_idx = 0; exp_idx< NUM_MVM_COLUMN; exp_idx ++){ + + for(int l = 0; l < NUM_PROJ_OUT_PER_GLU_SLICE; l++){ + + static_assert(PER_PROJ_COLUMN_OUTPUT_SLICE * NUM_MVM_COLUMN == PER_PROJ_OUTPUT_SLICE); + mul_scalar_accum( + share_expert_result + share_expert_result_offset + l*PER_PROJ_COLUMN_OUTPUT_SLICE, + x_using + (exp_idx*PER_PROJ_COLUMN_OUTPUT_SLICE) + l*(PER_PROJ_OUTPUT_SLICE), + *(expert_score+exp_idx) + ); + } + } + share_expert_result_offset+= NUM_PROJ_OUT_PER_GLU_SLICE* PER_PROJ_COLUMN_OUTPUT_SLICE; + + _lock_release(x_prod_lock); +} + + +void receive_expert_up_gate( + int slice, // which GLU slice of this round, 0 .. 2 * INTERMEDIATE_SIZE / PER_PROJ_COLUMN_OUTPUT_SLICE - 1 + bf16* exp_glu_res, + bool *is_glu_slice_in_ping_ptr, + const bf16 * glu_slice_in_buffer_ping, + const bf16 * glu_slice_in_buffer_pong + +){ + constexpr int E = EXP_UP_GATE_OUTDIM_REORDER; // h values per expert per slice + static_assert( GLU_SLICE == NUM_MVM_COLUMN * E * 2 ); + + // In: one slice is one proj round, column c = expert c, each column's part is + // [up E | gate E] (the host orders the expert weight rows this way) + // + // Out: exp_glu_res is the x of the routed down step, which the proj engine + // reads in PROJ_X_SLICE pieces, round robin over the 4 experts: + // exp0 h[0:256], exp1 h[0:256], exp2, exp3, exp0 h[256:512], ... + // Slice s gives h[s*E, s*E + E) of every expert; find where that lands. + const int h_pos = slice * E; // position inside one expert's h + const int chunk = h_pos / PROJ_X_SLICE; // which x piece of that expert + const int in_chunk = h_pos % PROJ_X_SLICE; // where inside the piece + + *(is_glu_slice_in_ping_ptr) = !*(is_glu_slice_in_ping_ptr); + const bf16* x_using = *(is_glu_slice_in_ping_ptr) ? glu_slice_in_buffer_ping : glu_slice_in_buffer_pong; + _lock_acquire(x_cons_lock); + for(int exp_idx = 0; exp_idx < NUM_MVM_COLUMN; exp_idx++){ + bf16* exp_up = const_cast(x_using + exp_idx * 2 * E); + bf16* exp_gate = exp_up + E; + bf16* exp_h = exp_glu_res + chunk * NUM_MVM_COLUMN * PROJ_X_SLICE + exp_idx * PROJ_X_SLICE + in_chunk; + + pseduo_glu(exp_h, exp_gate, exp_up); + } + _lock_release(x_prod_lock); +} + + +void process_glu( + bf16* y_it, + const bf16* glu_slice_in_buffer_ping, + const bf16* glu_slice_in_buffer_pong + +){ + + + static_assert((2 * INTERMEDIATE_SIZE) % GLU_SLICE == 0, "GLU_SLICE must divide 2 * INTERMEDIATE_SIZE"); + constexpr int chunks = 2 * INTERMEDIATE_SIZE / GLU_SLICE; // number of chunks in one GLU, each chunk is GLU_SLICE in size + + for (AIE_LOCK_LOOP_CTR i = 0; i < chunks; i++) { + is_glu_slice_in_ping = !is_glu_slice_in_ping; + const bf16* x_using = is_glu_slice_in_ping ? glu_slice_in_buffer_ping : glu_slice_in_buffer_pong; + + bf16* gate_ptr = const_cast(x_using+UP_GATE_OUTDIM_REORDEER); + bf16* up_ptr = const_cast(x_using); + + _lock_acquire(x_cons_lock); + pseduo_glu(y_it, gate_ptr,up_ptr ); + static_assert(UP_GATE_OUTDIM_REORDEER == GLU_SLICE/2); + y_it += UP_GATE_OUTDIM_REORDEER; + _lock_release(x_prod_lock); + } + +} + + +void glu( + float* topk_router_score, + int32_t* top_k_expert_index_buffer, + bf16 * intermediate_buffer, + bf16* D_mlp_final_to_rms, + bf16* D_in, + float* shared_expert_output, + const bf16 * glu_slice_in_buffer_ping, + const bf16 * glu_slice_in_buffer_pong, + bf16* to_proj_x_slice_With_pkt_ping, + bf16* to_proj_x_slice_With_pkt_pong +) +{ + // NOTE: despite its name, shared_expert_output is the fp32 sum of the + // *routed* experts. The shared expert's result comes back from rms into + // D_in (the second D_in fill below). + + // buffer to save the intermediate result + alignas(aie::vector_decl_align) bfloat16 exp_glu_res[INTERMEDIATE_SIZE * NUM_MVM_COLUMN]; + + zero_vectorized_512( + shared_expert_output + ); + + // shared expert: silu(gate) * up, then send it to the proj engine for down + process_glu( + intermediate_buffer, + glu_slice_in_buffer_ping, glu_slice_in_buffer_pong + ); + + for(int i = 0; i ( + pkt_id_glu_to_proj_x, + intermediate_buffer, + &is_to_proj_x_slice_ping, + to_proj_x_slice_With_pkt_ping,to_proj_x_slice_With_pkt_pong, + to_proj_x_slice_prod_lock, to_proj_x_slice_cons_lock + ); + static_assert(MODEL_DIM% GLU_SLICE == 0); + static_assert(O_DOWN_REPEATS % NUM_PROJ_OUT_PER_GLU_SLICE ==0); + } + + // First D_in fill: the post_attention_layernorm x, the MoE input. + _lock_acquire(D_in_con_lock,1); + + // Routed experts: each round runs NUM_MVM_COLUMN experts, one per proj column. + for(AIE_LOCK_LOOP_CTR round = 0; round < NUM_ACT_EXPERTS/NUM_MVM_COLUMN; round++){ + + // let the router point the shim weight BDs at this round's experts + _lock_release(glu_request_router_send_lock ); + + // gate/up: send x once per row-block round, collect silu(gate) * up + { + for(int i =0; i ( + pkt_id_glu_to_proj_x, + D_in, + &is_to_proj_x_slice_ping, + to_proj_x_slice_With_pkt_ping,to_proj_x_slice_With_pkt_pong, + to_proj_x_slice_prod_lock, to_proj_x_slice_cons_lock + ); + + static_assert( (NUM_MVM_COLUMN* INTERMEDIATE_SIZE) %GLU_SLICE == 0 ); + static_assert( UP_GATE_EXPERT_REPEATS % NUM_PROJ_OUT_PER_GLU_SLICE == 0); + if((i+1)%NUM_PROJ_OUT_PER_GLU_SLICE == 0){ + receive_expert_up_gate( + i / NUM_PROJ_OUT_PER_GLU_SLICE, + exp_glu_res, + &is_glu_slice_in_ping, + glu_slice_in_buffer_ping, glu_slice_in_buffer_pong + ); + } + } + } + + // down: exp_glu_res is laid out as + // exp0-glu[0:255], exp1-glu[0:255], exp2-glu[0:255], exp3-glu[0:255], exp0-glu[256:511], ... + // add score * down of each expert into shared_expert_output + { + size_t share_expert_result_offset = 0; + for(int i =0; i < DOWN_EXPERT_REPEATS; i++){ + + send_to_proj_x( + pkt_id_glu_to_proj_x, + exp_glu_res, + &is_to_proj_x_slice_ping, + to_proj_x_slice_With_pkt_ping,to_proj_x_slice_With_pkt_pong, + to_proj_x_slice_prod_lock, to_proj_x_slice_cons_lock + ); + + static_assert( (NUM_MVM_COLUMN*MODEL_DIM)%GLU_SLICE == 0); + static_assert( DOWN_EXPERT_REPEATS %NUM_PROJ_OUT_PER_GLU_SLICE == 0 ); + if((i +1)%NUM_PROJ_OUT_PER_GLU_SLICE ==0 ){ + receive_down( + share_expert_result_offset, + shared_expert_output, + topk_router_score+ round*NUM_MVM_COLUMN, + &is_glu_slice_in_ping, + glu_slice_in_buffer_ping, glu_slice_in_buffer_pong + ); + } + } + } + } + + _lock_release(D_in_prod_lock,1); + + // Second D_in fill: the shared expert's down output. MoE out = shared + routed. + _lock_acquire(D_in_con_lock,1); + constexpr int vec_size = 32; + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(MODEL_DIM/vec_size,MODEL_DIM/vec_size) + for(int i = 0; i < MODEL_DIM; i+=vec_size ){ + aie::vector shared_vec = aie::load_v(D_in + i); + aie::vector routed_vec = aie::load_v(shared_expert_output + i); + + aie::accum temp_acc; + temp_acc.from_vector( routed_vec); + + aie::vector result = aie::add( shared_vec, temp_acc.template to_vector() ); + aie::store_v(D_mlp_final_to_rms+i,result ); + } + _lock_release(D_in_prod_lock,1); + + // send the MoE output to rms + _lock_release(D_out_con_lock, 1); + _lock_acquire(D_out_prod_lock, 1); +} + + +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/lut_based_ops.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/lut_based_ops.h new file mode 100644 index 000000000..00c963e67 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/lut_based_ops.h @@ -0,0 +1,527 @@ +//===--- exp_lut.h - get exponential values from loopup tables ---===// +// +// This file is licensed under the Apache License v2.0 with LLVM Exceptions +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// +// +//===----------------------------------------------------------------------===// +// This is the implementation of getting exponential values for a bfloat16 +// vector from exponential lookup tables. +//===----------------------------------------------------------------------===// +#ifndef __LUT_BASED_OPS_H__ +#define __LUT_BASED_OPS_H__ + +#include "aie_api/aie.hpp" +#include "model_spec.h" + + +// The tables _ab and _cd are copies of each other +// Also, each table has a copy of data seperated by 256-bit +// This effectively creates 4 copies of the table (located in 4 (256-bit) banks) +// This allows the user to use the "gather" read feature and read 4 values from +// 4 different banks at once Tables entries are in BF16 +alignas(aie::vector_decl_align) int16 exp_ilut_ab[512] = { + 16256, 16430, 16620, 16801, 16986, 17172, 17354, 17545, 17722, 17917, 18092, 18282, 18463, 18648, 18835, 19016, + 16256, 16430, 16620, 16801, 16986, 17172, 17354, 17545, 17722, 17917, 18092, 18282, 18463, 18648, 18835, 19016, + 19208, 19384, 19578, 19754, 19943, 20125, 20310, 20497, 20677, 20870, 21046, 21240, 21416, 21605, 21788, 21971, + 19208, 19384, 19578, 19754, 19943, 20125, 20310, 20497, 20677, 20870, 21046, 21240, 21416, 21605, 21788, 21971, + 22160, 22339, 22533, 22708, 22901, 23079, 23266, 23450, 23633, 23822, 24001, 24195, 24370, 24562, 24741, 24928, + 22160, 22339, 22533, 22708, 22901, 23079, 23266, 23450, 23633, 23822, 24001, 24195, 24370, 24562, 24741, 24928, + 25112, 25295, 25485, 25663, 25858, 26032, 26224, 26403, 26589, 26774, 26957, 27147, 27325, 27520, 27695, 27885, + 25112, 25295, 25485, 25663, 25858, 26032, 26224, 26403, 26589, 26774, 26957, 27147, 27325, 27520, 27695, 27885, + 28065, 28251, 28437, 28618, 28809, 28987, 29182, 29357, 29547, 29727, 29913, 30099, 30280, 30472, 30649, 30843, + 28065, 28251, 28437, 28618, 28809, 28987, 29182, 29357, 29547, 29727, 29913, 30099, 30280, 30472, 30649, 30843, + 31019, 31208, 31390, 31574, 31762, 31942, 32135, 32311, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 31019, 31208, 31390, 31574, 31762, 31942, 32135, 32311, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , + 0 , 0 , 0 , 0 , 1 , 3 , 9 , 24 , 66 , 179 , 372 , 550 , 737 , 921 , 1104 , 1293 , + 0 , 0 , 0 , 0 , 1 , 3 , 9 , 24 , 66 , 179 , 372 , 550 , 737 , 921 , 1104 , 1293 , + 1472 , 1666 , 1841 , 2033 , 2212 , 2399 , 2583 , 2766 , 2956 , 3134 , 3329 , 3503 , 3694 , 3874 , 4060 , 4246 , + 1472 , 1666 , 1841 , 2033 , 2212 , 2399 , 2583 , 2766 , 2956 , 3134 , 3329 , 3503 , 3694 , 3874 , 4060 , 4246 , + 4427 , 4618 , 4796 , 4991 , 5165 , 5356 , 5536 , 5722 , 5908 , 6089 , 6281 , 6458 , 6652 , 6828 , 7017 , 7198 , + 4427 , 4618 , 4796 , 4991 , 5165 , 5356 , 5536 , 5722 , 5908 , 6089 , 6281 , 6458 , 6652 , 6828 , 7017 , 7198 , + 7383 , 7570 , 7751 , 7943 , 8120 , 8314 , 8490 , 8679 , 8861 , 9045 , 9233 , 9413 , 9606 , 9782 , 9975 , 10152, + 7383 , 7570 , 7751 , 7943 , 8120 , 8314 , 8490 , 8679 , 8861 , 9045 , 9233 , 9413 , 9606 , 9782 , 9975 , 10152, + 10340, 10523, 10707, 10895, 11075, 11268, 11444, 11636, 11814, 12002, 12185, 12368, 12558, 12737, 12931, 13106, + 10340, 10523, 10707, 10895, 11075, 11268, 11444, 11636, 11814, 12002, 12185, 12368, 12558, 12737, 12931, 13106, + 13298, 13476, 13663, 13848, 14030, 14220, 14398, 14593, 14768, 14959, 15138, 15325, 15510, 15692, 15883, 16060, + 13298, 13476, 13663, 13848, 14030, 14220, 14398, 14593, 14768, 14959, 15138, 15325, 15510, 15692, 15883, 16060 +}; + +alignas(aie::vector_decl_align) int16 exp_ilut_cd[512] = { + 16256, 16430, 16620, 16801, 16986, 17172, 17354, 17545, 17722, 17917, 18092, 18282, 18463, 18648, 18835, 19016, + 16256, 16430, 16620, 16801, 16986, 17172, 17354, 17545, 17722, 17917, 18092, 18282, 18463, 18648, 18835, 19016, + 19208, 19384, 19578, 19754, 19943, 20125, 20310, 20497, 20677, 20870, 21046, 21240, 21416, 21605, 21788, 21971, + 19208, 19384, 19578, 19754, 19943, 20125, 20310, 20497, 20677, 20870, 21046, 21240, 21416, 21605, 21788, 21971, + 22160, 22339, 22533, 22708, 22901, 23079, 23266, 23450, 23633, 23822, 24001, 24195, 24370, 24562, 24741, 24928, + 22160, 22339, 22533, 22708, 22901, 23079, 23266, 23450, 23633, 23822, 24001, 24195, 24370, 24562, 24741, 24928, + 25112, 25295, 25485, 25663, 25858, 26032, 26224, 26403, 26589, 26774, 26957, 27147, 27325, 27520, 27695, 27885, + 25112, 25295, 25485, 25663, 25858, 26032, 26224, 26403, 26589, 26774, 26957, 27147, 27325, 27520, 27695, 27885, + 28065, 28251, 28437, 28618, 28809, 28987, 29182, 29357, 29547, 29727, 29913, 30099, 30280, 30472, 30649, 30843, + 28065, 28251, 28437, 28618, 28809, 28987, 29182, 29357, 29547, 29727, 29913, 30099, 30280, 30472, 30649, 30843, + 31019, 31208, 31390, 31574, 31762, 31942, 32135, 32311, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 31019, 31208, 31390, 31574, 31762, 31942, 32135, 32311, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, 32505, + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , + 0 , 0 , 0 , 0 , 1 , 3 , 9 , 24 , 66 , 179 , 372 , 550 , 737 , 921 , 1104 , 1293 , + 0 , 0 , 0 , 0 , 1 , 3 , 9 , 24 , 66 , 179 , 372 , 550 , 737 , 921 , 1104 , 1293 , + 1472 , 1666 , 1841 , 2033 , 2212 , 2399 , 2583 , 2766 , 2956 , 3134 , 3329 , 3503 , 3694 , 3874 , 4060 , 4246 , + 1472 , 1666 , 1841 , 2033 , 2212 , 2399 , 2583 , 2766 , 2956 , 3134 , 3329 , 3503 , 3694 , 3874 , 4060 , 4246 , + 4427 , 4618 , 4796 , 4991 , 5165 , 5356 , 5536 , 5722 , 5908 , 6089 , 6281 , 6458 , 6652 , 6828 , 7017 , 7198 , + 4427 , 4618 , 4796 , 4991 , 5165 , 5356 , 5536 , 5722 , 5908 , 6089 , 6281 , 6458 , 6652 , 6828 , 7017 , 7198 , + 7383 , 7570 , 7751 , 7943 , 8120 , 8314 , 8490 , 8679 , 8861 , 9045 , 9233 , 9413 , 9606 , 9782 , 9975 , 10152, + 7383 , 7570 , 7751 , 7943 , 8120 , 8314 , 8490 , 8679 , 8861 , 9045 , 9233 , 9413 , 9606 , 9782 , 9975 , 10152, + 10340, 10523, 10707, 10895, 11075, 11268, 11444, 11636, 11814, 12002, 12185, 12368, 12558, 12737, 12931, 13106, + 10340, 10523, 10707, 10895, 11075, 11268, 11444, 11636, 11814, 12002, 12185, 12368, 12558, 12737, 12931, 13106, + 13298, 13476, 13663, 13848, 14030, 14220, 14398, 14593, 14768, 14959, 15138, 15325, 15510, 15692, 15883, 16060, + 13298, 13476, 13663, 13848, 14030, 14220, 14398, 14593, 14768, 14959, 15138, 15325, 15510, 15692, 15883, 16060 +}; + +alignas(aie::vector_decl_align) int16 exp_flut_ab[512] = { + 16256, 16257, 16257, 16258, 16258, 16259, 16259, 16260, 16260, 16261, 16261, 16262, 16262, 16263, 16263, 16264, + 16256, 16257, 16257, 16258, 16258, 16259, 16259, 16260, 16260, 16261, 16261, 16262, 16262, 16263, 16263, 16264, + 16264, 16265, 16265, 16266, 16266, 16267, 16267, 16268, 16269, 16269, 16270, 16270, 16271, 16271, 16272, 16272, + 16264, 16265, 16265, 16266, 16266, 16267, 16267, 16268, 16269, 16269, 16270, 16270, 16271, 16271, 16272, 16272, + 16273, 16274, 16274, 16275, 16275, 16276, 16276, 16277, 16278, 16278, 16279, 16279, 16280, 16281, 16281, 16282, + 16273, 16274, 16274, 16275, 16275, 16276, 16276, 16277, 16278, 16278, 16279, 16279, 16280, 16281, 16281, 16282, + 16282, 16283, 16284, 16284, 16285, 16285, 16286, 16287, 16287, 16288, 16289, 16289, 16290, 16290, 16291, 16292, + 16282, 16283, 16284, 16284, 16285, 16285, 16286, 16287, 16287, 16288, 16289, 16289, 16290, 16290, 16291, 16292, + 16292, 16293, 16294, 16294, 16295, 16296, 16296, 16297, 16298, 16298, 16299, 16300, 16300, 16301, 16302, 16302, + 16292, 16293, 16294, 16294, 16295, 16296, 16296, 16297, 16298, 16298, 16299, 16300, 16300, 16301, 16302, 16302, + 16303, 16304, 16304, 16305, 16306, 16306, 16307, 16308, 16309, 16309, 16310, 16311, 16311, 16312, 16313, 16314, + 16303, 16304, 16304, 16305, 16306, 16306, 16307, 16308, 16309, 16309, 16310, 16311, 16311, 16312, 16313, 16314, + 16314, 16315, 16316, 16316, 16317, 16318, 16319, 16319, 16320, 16321, 16322, 16322, 16323, 16324, 16325, 16325, + 16314, 16315, 16316, 16316, 16317, 16318, 16319, 16319, 16320, 16321, 16322, 16322, 16323, 16324, 16325, 16325, + 16326, 16327, 16328, 16329, 16329, 16330, 16331, 16332, 16333, 16333, 16334, 16335, 16336, 16337, 16337, 16338, + 16326, 16327, 16328, 16329, 16329, 16330, 16331, 16332, 16333, 16333, 16334, 16335, 16336, 16337, 16337, 16338, + 16339, 16340, 16341, 16342, 16342, 16343, 16344, 16345, 16346, 16347, 16347, 16348, 16349, 16350, 16351, 16352, + 16339, 16340, 16341, 16342, 16342, 16343, 16344, 16345, 16346, 16347, 16347, 16348, 16349, 16350, 16351, 16352, + 16353, 16354, 16354, 16355, 16356, 16357, 16358, 16359, 16360, 16361, 16362, 16363, 16363, 16364, 16365, 16366, + 16353, 16354, 16354, 16355, 16356, 16357, 16358, 16359, 16360, 16361, 16362, 16363, 16363, 16364, 16365, 16366, + 16367, 16368, 16369, 16370, 16371, 16372, 16373, 16374, 16375, 16376, 16377, 16378, 16379, 16380, 16381, 16382, + 16367, 16368, 16369, 16370, 16371, 16372, 16373, 16374, 16375, 16376, 16377, 16378, 16379, 16380, 16381, 16382, + 16383, 16384, 16384, 16385, 16385, 16386, 16386, 16387, 16387, 16388, 16388, 16389, 16389, 16390, 16390, 16391, + 16383, 16384, 16384, 16385, 16385, 16386, 16386, 16387, 16387, 16388, 16388, 16389, 16389, 16390, 16390, 16391, + 16391, 16392, 16393, 16393, 16394, 16394, 16395, 16395, 16396, 16396, 16397, 16397, 16398, 16399, 16399, 16400, + 16391, 16392, 16393, 16393, 16394, 16394, 16395, 16395, 16396, 16396, 16397, 16397, 16398, 16399, 16399, 16400, + 16400, 16401, 16401, 16402, 16402, 16403, 16404, 16404, 16405, 16405, 16406, 16407, 16407, 16408, 16408, 16409, + 16400, 16401, 16401, 16402, 16402, 16403, 16404, 16404, 16405, 16405, 16406, 16407, 16407, 16408, 16408, 16409, + 16410, 16410, 16411, 16411, 16412, 16413, 16413, 16414, 16414, 16415, 16416, 16416, 16417, 16418, 16418, 16419, + 16410, 16410, 16411, 16411, 16412, 16413, 16413, 16414, 16414, 16415, 16416, 16416, 16417, 16418, 16418, 16419, + 16419, 16420, 16421, 16421, 16422, 16423, 16423, 16424, 16425, 16425, 16426, 16427, 16427, 16428, 16429, 16429, + 16419, 16420, 16421, 16421, 16422, 16423, 16423, 16424, 16425, 16425, 16426, 16427, 16427, 16428, 16429, 16429 +}; + +alignas(aie::vector_decl_align) int16 exp_flut_cd[512] = { + 16256, 16257, 16257, 16258, 16258, 16259, 16259, 16260, 16260, 16261, 16261, 16262, 16262, 16263, 16263, 16264, + 16256, 16257, 16257, 16258, 16258, 16259, 16259, 16260, 16260, 16261, 16261, 16262, 16262, 16263, 16263, 16264, + 16264, 16265, 16265, 16266, 16266, 16267, 16267, 16268, 16269, 16269, 16270, 16270, 16271, 16271, 16272, 16272, + 16264, 16265, 16265, 16266, 16266, 16267, 16267, 16268, 16269, 16269, 16270, 16270, 16271, 16271, 16272, 16272, + 16273, 16274, 16274, 16275, 16275, 16276, 16276, 16277, 16278, 16278, 16279, 16279, 16280, 16281, 16281, 16282, + 16273, 16274, 16274, 16275, 16275, 16276, 16276, 16277, 16278, 16278, 16279, 16279, 16280, 16281, 16281, 16282, + 16282, 16283, 16284, 16284, 16285, 16285, 16286, 16287, 16287, 16288, 16289, 16289, 16290, 16290, 16291, 16292, + 16282, 16283, 16284, 16284, 16285, 16285, 16286, 16287, 16287, 16288, 16289, 16289, 16290, 16290, 16291, 16292, + 16292, 16293, 16294, 16294, 16295, 16296, 16296, 16297, 16298, 16298, 16299, 16300, 16300, 16301, 16302, 16302, + 16292, 16293, 16294, 16294, 16295, 16296, 16296, 16297, 16298, 16298, 16299, 16300, 16300, 16301, 16302, 16302, + 16303, 16304, 16304, 16305, 16306, 16306, 16307, 16308, 16309, 16309, 16310, 16311, 16311, 16312, 16313, 16314, + 16303, 16304, 16304, 16305, 16306, 16306, 16307, 16308, 16309, 16309, 16310, 16311, 16311, 16312, 16313, 16314, + 16314, 16315, 16316, 16316, 16317, 16318, 16319, 16319, 16320, 16321, 16322, 16322, 16323, 16324, 16325, 16325, + 16314, 16315, 16316, 16316, 16317, 16318, 16319, 16319, 16320, 16321, 16322, 16322, 16323, 16324, 16325, 16325, + 16326, 16327, 16328, 16329, 16329, 16330, 16331, 16332, 16333, 16333, 16334, 16335, 16336, 16337, 16337, 16338, + 16326, 16327, 16328, 16329, 16329, 16330, 16331, 16332, 16333, 16333, 16334, 16335, 16336, 16337, 16337, 16338, + 16339, 16340, 16341, 16342, 16342, 16343, 16344, 16345, 16346, 16347, 16347, 16348, 16349, 16350, 16351, 16352, + 16339, 16340, 16341, 16342, 16342, 16343, 16344, 16345, 16346, 16347, 16347, 16348, 16349, 16350, 16351, 16352, + 16353, 16354, 16354, 16355, 16356, 16357, 16358, 16359, 16360, 16361, 16362, 16363, 16363, 16364, 16365, 16366, + 16353, 16354, 16354, 16355, 16356, 16357, 16358, 16359, 16360, 16361, 16362, 16363, 16363, 16364, 16365, 16366, + 16367, 16368, 16369, 16370, 16371, 16372, 16373, 16374, 16375, 16376, 16377, 16378, 16379, 16380, 16381, 16382, + 16367, 16368, 16369, 16370, 16371, 16372, 16373, 16374, 16375, 16376, 16377, 16378, 16379, 16380, 16381, 16382, + 16383, 16384, 16384, 16385, 16385, 16386, 16386, 16387, 16387, 16388, 16388, 16389, 16389, 16390, 16390, 16391, + 16383, 16384, 16384, 16385, 16385, 16386, 16386, 16387, 16387, 16388, 16388, 16389, 16389, 16390, 16390, 16391, + 16391, 16392, 16393, 16393, 16394, 16394, 16395, 16395, 16396, 16396, 16397, 16397, 16398, 16399, 16399, 16400, + 16391, 16392, 16393, 16393, 16394, 16394, 16395, 16395, 16396, 16396, 16397, 16397, 16398, 16399, 16399, 16400, + 16400, 16401, 16401, 16402, 16402, 16403, 16404, 16404, 16405, 16405, 16406, 16407, 16407, 16408, 16408, 16409, + 16400, 16401, 16401, 16402, 16402, 16403, 16404, 16404, 16405, 16405, 16406, 16407, 16407, 16408, 16408, 16409, + 16410, 16410, 16411, 16411, 16412, 16413, 16413, 16414, 16414, 16415, 16416, 16416, 16417, 16418, 16418, 16419, + 16410, 16410, 16411, 16411, 16412, 16413, 16413, 16414, 16414, 16415, 16416, 16416, 16417, 16418, 16418, 16419, + 16419, 16420, 16421, 16421, 16422, 16423, 16423, 16424, 16425, 16425, 16426, 16427, 16427, 16428, 16429, 16429, + 16419, 16420, 16421, 16421, 16422, 16423, 16423, 16424, 16425, 16425, 16426, 16427, 16427, 16428, 16429, 16429 +}; + +alignas(aie::vector_decl_align) unsigned char m_inv_lut[128] = { + 0, 126, 124, 122, 120, 118, 117, 115, 113, 111, 109, 108, 106, 104, 103, + 101, 100, 98, 96, 95, 93, 92, 90, 89, 88, 86, 85, 83, 82, 81, + 79, 78, 77, 76, 74, 73, 72, 71, 69, 68, 67, 66, 65, 64, 63, + 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, + 46, 45, 44, 44, 43, 42, 41, 40, 39, 38, 37, 37, 36, 35, 34, + 33, 33, 32, 31, 30, 30, 29, 28, 27, 27, 26, 25, 24, 24, 23, + 22, 22, 21, 20, 20, 19, 18, 18, 17, 16, 16, 15, 14, 14, 13, + 13, 12, 11, 11, 10, 10, 9, 9, 8, 7, 7, 6, 6, 5, 5, + 4, 4, 3, 3, 2, 2, 1, 1}; + +#if A_FUNC == A_SILU +float chess_storage(% chess_alignof(v32int8)) activation_lut_ab[256] = { + -0.00000000f, -0.00000000f, -0.00323609f, -0.02841651f, + -0.00399708f, -0.03412396f, -0.00492899f, -0.04088030f, + -0.00000000f, -0.00000000f, -0.00323609f, -0.02841651f, + -0.00399708f, -0.03412396f, -0.00492899f, -0.04088030f, + -0.00606734f, -0.04884876f, -0.00745396f, -0.05820843f, + -0.00913763f, -0.06915227f, -0.01117459f, -0.08188327f, + -0.00606734f, -0.04884876f, -0.00745396f, -0.05820843f, + -0.00913763f, -0.06915227f, -0.01117459f, -0.08188327f, + -0.01362875f, -0.09660824f, -0.01657132f, -0.11352804f, + -0.02007961f, -0.13282361f, -0.02423438f, -0.15463615f, + -0.01362875f, -0.09660824f, -0.01657132f, -0.11352804f, + -0.02007961f, -0.13282361f, -0.02423438f, -0.15463615f, + -0.02911520f, -0.17904028f, -0.03479274f, -0.20600859f, + -0.04131669f, -0.23536636f, -0.04869770f, -0.26673564f, + -0.02911520f, -0.17904028f, -0.03479274f, -0.20600859f, + -0.04131669f, -0.23536636f, -0.04869770f, -0.26673564f, + -0.05688119f, -0.29946960f, -0.06571068f, -0.33258019f, + -0.07487830f, -0.36466687f, -0.08386094f, -0.39386045f, + -0.05688119f, -0.29946960f, -0.06571068f, -0.33258019f, + -0.07487830f, -0.36466687f, -0.08386094f, -0.39386045f, + -0.09184267f, -0.41780564f, -0.09762865f, -0.43371707f, + -0.09956338f, -0.43855391f, -0.09547819f, -0.42936223f, + -0.09184267f, -0.41780564f, -0.09762865f, -0.43371707f, + -0.09956338f, -0.43855391f, -0.09547819f, -0.42936223f, + -0.08270701f, -0.40381986f, -0.05822276f, -0.36097242f, + -0.01894755f, -0.30205961f, 0.03773501f, -0.23120641f, + -0.08270701f, -0.40381986f, -0.05822276f, -0.36097242f, + -0.01894755f, -0.30205961f, 0.03773501f, -0.23120641f, + 0.11330178f, -0.15563964f, 0.20738256f, -0.08507905f, + 0.31725784f, -0.03014142f, 0.43782350f, 0.00000000f, + 0.11330178f, -0.15563964f, 0.20738256f, -0.08507905f, + 0.31725784f, -0.03014142f, 0.43782350f, 0.00000000f, + 0.56217650f, 0.00000000f, 0.68274216f, -0.03014142f, + 0.79261744f, -0.08507905f, 0.88669822f, -0.15563964f, + 0.56217650f, 0.00000000f, 0.68274216f, -0.03014142f, + 0.79261744f, -0.08507905f, 0.88669822f, -0.15563964f, + 0.96226499f, -0.23120641f, 1.01894755f, -0.30205961f, + 1.05822276f, -0.36097242f, 1.08270701f, -0.40381986f, + 0.96226499f, -0.23120641f, 1.01894755f, -0.30205961f, + 1.05822276f, -0.36097242f, 1.08270701f, -0.40381986f, + 1.09547819f, -0.42936223f, 1.09956338f, -0.43855391f, + 1.09762865f, -0.43371707f, 1.09184267f, -0.41780564f, + 1.09547819f, -0.42936223f, 1.09956338f, -0.43855391f, + 1.09762865f, -0.43371707f, 1.09184267f, -0.41780564f, + 1.08386094f, -0.39386045f, 1.07487830f, -0.36466687f, + 1.06571068f, -0.33258019f, 1.05688119f, -0.29946960f, + 1.08386094f, -0.39386045f, 1.07487830f, -0.36466687f, + 1.06571068f, -0.33258019f, 1.05688119f, -0.29946960f, + 1.04869770f, -0.26673564f, 1.04131669f, -0.23536636f, + 1.03479274f, -0.20600859f, 1.02911520f, -0.17904028f, + 1.04869770f, -0.26673564f, 1.04131669f, -0.23536636f, + 1.03479274f, -0.20600859f, 1.02911520f, -0.17904028f, + 1.02423438f, -0.15463615f, 1.02007961f, -0.13282361f, + 1.01657132f, -0.11352804f, 1.01362875f, -0.09660824f, + 1.02423438f, -0.15463615f, 1.02007961f, -0.13282361f, + 1.01657132f, -0.11352804f, 1.01362875f, -0.09660824f, + 1.01117459f, -0.08188327f, 1.00913763f, -0.06915227f, + 1.00745396f, -0.05820843f, 1.00606734f, -0.04884876f, + 1.01117459f, -0.08188327f, 1.00913763f, -0.06915227f, + 1.00745396f, -0.05820843f, 1.00606734f, -0.04884876f, + 1.00492899f, -0.04088030f, 1.00399708f, -0.03412396f, + 1.00323609f, -0.02841651f, 1.00000000f, -0.00000000f, + 1.00492899f, -0.04088030f, 1.00399708f, -0.03412396f, + 1.00323609f, -0.02841651f, 1.00000000f, -0.00000000f +}; + +float chess_storage(% chess_alignof(v32int8)) activation_lut_cd[256] = { + -0.00000000f, -0.00000000f, -0.00323609f, -0.02841651f, + -0.00399708f, -0.03412396f, -0.00492899f, -0.04088030f, + -0.00000000f, -0.00000000f, -0.00323609f, -0.02841651f, + -0.00399708f, -0.03412396f, -0.00492899f, -0.04088030f, + -0.00606734f, -0.04884876f, -0.00745396f, -0.05820843f, + -0.00913763f, -0.06915227f, -0.01117459f, -0.08188327f, + -0.00606734f, -0.04884876f, -0.00745396f, -0.05820843f, + -0.00913763f, -0.06915227f, -0.01117459f, -0.08188327f, + -0.01362875f, -0.09660824f, -0.01657132f, -0.11352804f, + -0.02007961f, -0.13282361f, -0.02423438f, -0.15463615f, + -0.01362875f, -0.09660824f, -0.01657132f, -0.11352804f, + -0.02007961f, -0.13282361f, -0.02423438f, -0.15463615f, + -0.02911520f, -0.17904028f, -0.03479274f, -0.20600859f, + -0.04131669f, -0.23536636f, -0.04869770f, -0.26673564f, + -0.02911520f, -0.17904028f, -0.03479274f, -0.20600859f, + -0.04131669f, -0.23536636f, -0.04869770f, -0.26673564f, + -0.05688119f, -0.29946960f, -0.06571068f, -0.33258019f, + -0.07487830f, -0.36466687f, -0.08386094f, -0.39386045f, + -0.05688119f, -0.29946960f, -0.06571068f, -0.33258019f, + -0.07487830f, -0.36466687f, -0.08386094f, -0.39386045f, + -0.09184267f, -0.41780564f, -0.09762865f, -0.43371707f, + -0.09956338f, -0.43855391f, -0.09547819f, -0.42936223f, + -0.09184267f, -0.41780564f, -0.09762865f, -0.43371707f, + -0.09956338f, -0.43855391f, -0.09547819f, -0.42936223f, + -0.08270701f, -0.40381986f, -0.05822276f, -0.36097242f, + -0.01894755f, -0.30205961f, 0.03773501f, -0.23120641f, + -0.08270701f, -0.40381986f, -0.05822276f, -0.36097242f, + -0.01894755f, -0.30205961f, 0.03773501f, -0.23120641f, + 0.11330178f, -0.15563964f, 0.20738256f, -0.08507905f, + 0.31725784f, -0.03014142f, 0.43782350f, 0.00000000f, + 0.11330178f, -0.15563964f, 0.20738256f, -0.08507905f, + 0.31725784f, -0.03014142f, 0.43782350f, 0.00000000f, + 0.56217650f, 0.00000000f, 0.68274216f, -0.03014142f, + 0.79261744f, -0.08507905f, 0.88669822f, -0.15563964f, + 0.56217650f, 0.00000000f, 0.68274216f, -0.03014142f, + 0.79261744f, -0.08507905f, 0.88669822f, -0.15563964f, + 0.96226499f, -0.23120641f, 1.01894755f, -0.30205961f, + 1.05822276f, -0.36097242f, 1.08270701f, -0.40381986f, + 0.96226499f, -0.23120641f, 1.01894755f, -0.30205961f, + 1.05822276f, -0.36097242f, 1.08270701f, -0.40381986f, + 1.09547819f, -0.42936223f, 1.09956338f, -0.43855391f, + 1.09762865f, -0.43371707f, 1.09184267f, -0.41780564f, + 1.09547819f, -0.42936223f, 1.09956338f, -0.43855391f, + 1.09762865f, -0.43371707f, 1.09184267f, -0.41780564f, + 1.08386094f, -0.39386045f, 1.07487830f, -0.36466687f, + 1.06571068f, -0.33258019f, 1.05688119f, -0.29946960f, + 1.08386094f, -0.39386045f, 1.07487830f, -0.36466687f, + 1.06571068f, -0.33258019f, 1.05688119f, -0.29946960f, + 1.04869770f, -0.26673564f, 1.04131669f, -0.23536636f, + 1.03479274f, -0.20600859f, 1.02911520f, -0.17904028f, + 1.04869770f, -0.26673564f, 1.04131669f, -0.23536636f, + 1.03479274f, -0.20600859f, 1.02911520f, -0.17904028f, + 1.02423438f, -0.15463615f, 1.02007961f, -0.13282361f, + 1.01657132f, -0.11352804f, 1.01362875f, -0.09660824f, + 1.02423438f, -0.15463615f, 1.02007961f, -0.13282361f, + 1.01657132f, -0.11352804f, 1.01362875f, -0.09660824f, + 1.01117459f, -0.08188327f, 1.00913763f, -0.06915227f, + 1.00745396f, -0.05820843f, 1.00606734f, -0.04884876f, + 1.01117459f, -0.08188327f, 1.00913763f, -0.06915227f, + 1.00745396f, -0.05820843f, 1.00606734f, -0.04884876f, + 1.00492899f, -0.04088030f, 1.00399708f, -0.03412396f, + 1.00323609f, -0.02841651f, 1.00000000f, -0.00000000f, + 1.00492899f, -0.04088030f, 1.00399708f, -0.03412396f, + 1.00323609f, -0.02841651f, 1.00000000f, -0.00000000f +}; +#elif A_FUNC == A_GELU +float chess_storage(% chess_alignof(v32int8)) activation_lut_ab[256] = { + -0.00000000f, -0.00000000f, -0.00099681f, -0.00406485f, + -0.00153315f, -0.00607442f, -0.00231779f, -0.00891632f, + -0.00000000f, -0.00000000f, -0.00099681f, -0.00406485f, + -0.00153315f, -0.00607442f, -0.00231779f, -0.00891632f, + -0.00344358f, -0.01285333f, -0.00502712f, -0.01819347f, + -0.00720965f, -0.02528113f, -0.01015534f, -0.03447940f, + -0.00344358f, -0.01285333f, -0.00502712f, -0.01819347f, + -0.00720965f, -0.02528113f, -0.01015534f, -0.03447940f, + -0.01404561f, -0.04614168f, -0.01906834f, -0.06057197f, + -0.02540058f, -0.07797424f, -0.03318416f, -0.09839385f, + -0.01404561f, -0.04614168f, -0.01906834f, -0.06057197f, + -0.02540058f, -0.07797424f, -0.03318416f, -0.09839385f, + -0.04249404f, -0.12165605f, -0.05330032f, -0.14730932f, + -0.06542629f, -0.17458333f, -0.07850615f, -0.20237258f, + -0.04249404f, -0.12165605f, -0.05330032f, -0.14730932f, + -0.06542629f, -0.17458333f, -0.07850615f, -0.20237258f, + -0.09194764f, -0.22925607f, -0.10490580f, -0.25356126f, + -0.11627461f, -0.27347556f, -0.12470285f, -0.28720243f, + -0.09194764f, -0.22925607f, -0.10490580f, -0.25356126f, + -0.11627461f, -0.27347556f, -0.12470285f, -0.28720243f, + -0.12863902f, -0.29315110f, -0.12640746f, -0.29014116f, + -0.11631434f, -0.27759683f, -0.09677767f, -0.25570219f, + -0.12863902f, -0.29315110f, -0.12640746f, -0.29014116f, + -0.11631434f, -0.27759683f, -0.09677767f, -0.25570219f, + -0.06647138f, -0.22548929f, -0.02446993f, -0.18883672f, + 0.02962273f, -0.14836636f, 0.09557602f, -0.10723962f, + -0.06647138f, -0.22548929f, -0.02446993f, -0.18883672f, + 0.02962273f, -0.14836636f, 0.09557602f, -0.10723962f, + 0.17248185f, -0.06886999f, 0.25876027f, -0.03658275f, + 0.35222573f, -0.01326287f, 0.45021109f, -0.00103722f, + 0.17248185f, -0.06886999f, 0.25876027f, -0.03658275f, + 0.35222573f, -0.01326287f, 0.45021109f, -0.00103722f, + 0.54973927f, -0.00103412f, 0.64772617f, -0.01325384f, + 0.74119459f, -0.03656863f, 0.82747719f, -0.06885207f, + 0.54973927f, -0.00103412f, 0.64772617f, -0.01325384f, + 0.74119459f, -0.03656863f, 0.82747719f, -0.06885207f, + 0.90438816f, -0.10721946f, 0.97034721f, -0.14834569f, + 1.02444591f, -0.18881720f, 1.06645335f, -0.22547238f, + 0.90438816f, -0.10721946f, 0.97034721f, -0.14834569f, + 1.02444591f, -0.18881720f, 1.06645335f, -0.22547238f, + 1.09676530f, -0.25568904f, 1.11630706f, -0.27758817f, + 1.12640452f, -0.29013729f, 1.12863958f, -0.29315191f, + 1.09676530f, -0.25568904f, 1.11630706f, -0.27758817f, + 1.12640452f, -0.29013729f, 1.12863958f, -0.29315191f, + 1.12470608f, -0.28720746f, 1.11627968f, -0.27348412f, + 1.10491198f, -0.25357247f, 1.09195432f, -0.22926902f, + 1.12470608f, -0.28720746f, 1.11627968f, -0.27348412f, + 1.10491198f, -0.25357247f, 1.09195432f, -0.22926902f, + 1.07851284f, -0.20238637f, 1.06543263f, -0.17459720f, + 1.05330608f, -0.14732263f, 1.04249908f, -0.12166833f, + 1.07851284f, -0.20238637f, 1.06543263f, -0.17459720f, + 1.05330608f, -0.14732263f, 1.04249908f, -0.12166833f, + 1.03318843f, -0.09840480f, 1.02540410f, -0.07798370f, + 1.01907116f, -0.06057991f, 1.01404783f, -0.04614818f, + 1.03318843f, -0.09840480f, 1.02540410f, -0.07798370f, + 1.01907116f, -0.06057991f, 1.01404783f, -0.04614818f, + 1.01015703f, -0.03448459f, 1.00721092f, -0.02528517f, + 1.00502805f, -0.01819655f, 1.00344425f, -0.01285563f, + 1.01015703f, -0.03448459f, 1.00721092f, -0.02528517f, + 1.00502805f, -0.01819655f, 1.00344425f, -0.01285563f, + 1.00231826f, -0.00891799f, 1.00153348f, -0.00607561f, + 1.00099703f, -0.00406568f, 1.00000000f, -0.00000000f, + 1.00231826f, -0.00891799f, 1.00153348f, -0.00607561f, + 1.00099703f, -0.00406568f, 1.00000000f, -0.00000000f +}; + +float chess_storage(% chess_alignof(v32int8)) activation_lut_cd[256] = { + -0.00000000f, -0.00000000f, -0.00099681f, -0.00406485f, + -0.00153315f, -0.00607442f, -0.00231779f, -0.00891632f, + -0.00000000f, -0.00000000f, -0.00099681f, -0.00406485f, + -0.00153315f, -0.00607442f, -0.00231779f, -0.00891632f, + -0.00344358f, -0.01285333f, -0.00502712f, -0.01819347f, + -0.00720965f, -0.02528113f, -0.01015534f, -0.03447940f, + -0.00344358f, -0.01285333f, -0.00502712f, -0.01819347f, + -0.00720965f, -0.02528113f, -0.01015534f, -0.03447940f, + -0.01404561f, -0.04614168f, -0.01906834f, -0.06057197f, + -0.02540058f, -0.07797424f, -0.03318416f, -0.09839385f, + -0.01404561f, -0.04614168f, -0.01906834f, -0.06057197f, + -0.02540058f, -0.07797424f, -0.03318416f, -0.09839385f, + -0.04249404f, -0.12165605f, -0.05330032f, -0.14730932f, + -0.06542629f, -0.17458333f, -0.07850615f, -0.20237258f, + -0.04249404f, -0.12165605f, -0.05330032f, -0.14730932f, + -0.06542629f, -0.17458333f, -0.07850615f, -0.20237258f, + -0.09194764f, -0.22925607f, -0.10490580f, -0.25356126f, + -0.11627461f, -0.27347556f, -0.12470285f, -0.28720243f, + -0.09194764f, -0.22925607f, -0.10490580f, -0.25356126f, + -0.11627461f, -0.27347556f, -0.12470285f, -0.28720243f, + -0.12863902f, -0.29315110f, -0.12640746f, -0.29014116f, + -0.11631434f, -0.27759683f, -0.09677767f, -0.25570219f, + -0.12863902f, -0.29315110f, -0.12640746f, -0.29014116f, + -0.11631434f, -0.27759683f, -0.09677767f, -0.25570219f, + -0.06647138f, -0.22548929f, -0.02446993f, -0.18883672f, + 0.02962273f, -0.14836636f, 0.09557602f, -0.10723962f, + -0.06647138f, -0.22548929f, -0.02446993f, -0.18883672f, + 0.02962273f, -0.14836636f, 0.09557602f, -0.10723962f, + 0.17248185f, -0.06886999f, 0.25876027f, -0.03658275f, + 0.35222573f, -0.01326287f, 0.45021109f, -0.00103722f, + 0.17248185f, -0.06886999f, 0.25876027f, -0.03658275f, + 0.35222573f, -0.01326287f, 0.45021109f, -0.00103722f, + 0.54973927f, -0.00103412f, 0.64772617f, -0.01325384f, + 0.74119459f, -0.03656863f, 0.82747719f, -0.06885207f, + 0.54973927f, -0.00103412f, 0.64772617f, -0.01325384f, + 0.74119459f, -0.03656863f, 0.82747719f, -0.06885207f, + 0.90438816f, -0.10721946f, 0.97034721f, -0.14834569f, + 1.02444591f, -0.18881720f, 1.06645335f, -0.22547238f, + 0.90438816f, -0.10721946f, 0.97034721f, -0.14834569f, + 1.02444591f, -0.18881720f, 1.06645335f, -0.22547238f, + 1.09676530f, -0.25568904f, 1.11630706f, -0.27758817f, + 1.12640452f, -0.29013729f, 1.12863958f, -0.29315191f, + 1.09676530f, -0.25568904f, 1.11630706f, -0.27758817f, + 1.12640452f, -0.29013729f, 1.12863958f, -0.29315191f, + 1.12470608f, -0.28720746f, 1.11627968f, -0.27348412f, + 1.10491198f, -0.25357247f, 1.09195432f, -0.22926902f, + 1.12470608f, -0.28720746f, 1.11627968f, -0.27348412f, + 1.10491198f, -0.25357247f, 1.09195432f, -0.22926902f, + 1.07851284f, -0.20238637f, 1.06543263f, -0.17459720f, + 1.05330608f, -0.14732263f, 1.04249908f, -0.12166833f, + 1.07851284f, -0.20238637f, 1.06543263f, -0.17459720f, + 1.05330608f, -0.14732263f, 1.04249908f, -0.12166833f, + 1.03318843f, -0.09840480f, 1.02540410f, -0.07798370f, + 1.01907116f, -0.06057991f, 1.01404783f, -0.04614818f, + 1.03318843f, -0.09840480f, 1.02540410f, -0.07798370f, + 1.01907116f, -0.06057991f, 1.01404783f, -0.04614818f, + 1.01015703f, -0.03448459f, 1.00721092f, -0.02528517f, + 1.00502805f, -0.01819655f, 1.00344425f, -0.01285563f, + 1.01015703f, -0.03448459f, 1.00721092f, -0.02528517f, + 1.00502805f, -0.01819655f, 1.00344425f, -0.01285563f, + 1.00231826f, -0.00891799f, 1.00153348f, -0.00607561f, + 1.00099703f, -0.00406568f, 1.00000000f, -0.00000000f, + 1.00231826f, -0.00891799f, 1.00153348f, -0.00607561f, + 1.00099703f, -0.00406568f, 1.00000000f, -0.00000000f +}; +#endif + + +extern "C" { +__attribute__((always_inline)) v16accfloat getExpBf16(v16bfloat16 x) { + bfloat16 __aie_dm_resource_a *ilut_ab = (bfloat16 __aie_dm_resource_a *)exp_ilut_ab; + bfloat16 __aie_dm_resource_b *ilut_cd = (bfloat16 __aie_dm_resource_b *)exp_ilut_cd; + bfloat16 __aie_dm_resource_a *flut_ab = (bfloat16 __aie_dm_resource_a *)exp_flut_ab; + bfloat16 __aie_dm_resource_b *flut_cd = (bfloat16 __aie_dm_resource_b *)exp_flut_cd; + + using lut_type = aie::lut<4, bfloat16, bfloat16>; + const int LUT_elems = 256; + const int step_i = 8; + const int step_f = 0; + + lut_type lut_i(LUT_elems, ilut_ab, ilut_cd); + lut_type lut_f(LUT_elems, flut_ab, flut_cd); + aie::parallel_lookup lookup_i(lut_i, step_i); + aie::parallel_lookup lookup_f(lut_f, step_f); + + aie::vector I_val_vec, F_val_vec; + aie::accum exp_val; + aie::vector input_bf16 = x; + + // position of output decimal point = 8, making input become 8 bits, and for + // LUT_elems = 256 lookup. aie::vector + // input=aie::to_fixed(input_bf16,8); + aie::vector input0 = v32int16(bfloat16_to_int(input_bf16, 8)); + aie::vector input = aie::filter_even(input0); + + I_val_vec = lookup_i.fetch(input.cast_to()); + F_val_vec = lookup_f.fetch(input.cast_to()); + exp_val = aie::mul(I_val_vec, F_val_vec); + return v16accfloat(exp_val); +} + + +__attribute__((always_inline)) v16bfloat16 getActivationBf16(v16bfloat16 vInput) { + aie::vector input = vInput; + + #if A_FUNC == A_SILU + int step_bits = -2; + #elif A_FUNC == A_GELU + int step_bits = -3; + #endif + int bias = 32; + int data_size = 16; + int LUT_elems = 64; + int shift_offset = 0; // unused + + using lut_type = aie::lut<4, float, bfloat16>; + + lut_type test_lut(LUT_elems, (bfloat16 *)activation_lut_ab, (bfloat16 *)activation_lut_cd); + + aie::linear_approx lin_aprox(test_lut, step_bits, bias, shift_offset); + + aie::vector output = lin_aprox.compute(input).to_vector(); + + return (v16bfloat16)output; +} + +__attribute__((always_inline)) bfloat16 getInvBf16(float x) { + unsigned int *B_x; + unsigned int exp_mask = 0x7F800000; + unsigned int mantissa_mask = 0x007FFFFF; + unsigned int mantissa_Q = 0x00008000; + unsigned char exponent, mantissa; + unsigned inv_exponent; + unsigned short inv_x_val; + unsigned int B_Q; + bfloat16 *inv_x; + B_x = (unsigned int *)&x; + B_Q = *B_x + mantissa_Q; + exponent = (B_Q & exp_mask) >> 23; + mantissa = (B_Q & mantissa_mask) >> 16; + inv_exponent = (mantissa == 0) + (253 - exponent); + inv_x_val = (inv_exponent << 7) + m_inv_lut[mantissa]; + inv_x = (bfloat16 *)&inv_x_val; + return *inv_x; +} + +} +#endif //__LUT_BASED_OPS_H__ \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/model_spec.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/model_spec.h new file mode 100644 index 000000000..34960ba4c --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/model_spec.h @@ -0,0 +1,86 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __MODEL_SPEC__ +#define __MODEL_SPEC__ + +#include "typedef.hpp" +#include "../models/all_models.h" + +constexpr int Q_HEADS_PER_GROUP = NUM_ATTN_HEADS / NUM_KV_HEADS; + +constexpr int DQ = NUM_ATTN_HEADS * DH; +constexpr int DK = NUM_KV_HEADS * DH; +constexpr int DV = DK; + +// Largest reduction dimension any mvm() phase runs with. o_proj uses DQ, +// which can exceed MODEL_DIM. +constexpr int MAX_MVM_K_FFN = MODEL_DIM > INTERMEDIATE_SIZE ? MODEL_DIM : INTERMEDIATE_SIZE; +constexpr int MAX_MVM_K = MAX_MVM_K_FFN > DQ ? MAX_MVM_K_FFN : DQ; + +// Analize the GQA patterns; + +#if ATTN_IMPL == ATTN_IMPL_2x4x1 + const int GQA_R = 8; + const int GQA_S = 8; + const int GQA_T = 8; + constexpr int GQA_SEGMENT_SIZE = 4; // 8x8x8 or 4x8x8, must be multiple of 4 + constexpr int KV_HEADS_PER_CU = 2; + constexpr int Q_HEADS_PER_CU = Q_HEADS_PER_GROUP * 2; + constexpr int ATTN_GROUPS_PADDING = ((Q_HEADS_PER_GROUP + GQA_SEGMENT_SIZE - 1) / GQA_SEGMENT_SIZE) * GQA_SEGMENT_SIZE - Q_HEADS_PER_GROUP; +#elif ATTN_IMPL == ATTN_IMPL_1x4x1 + const int GQA_R = 4; + const int GQA_S = 8; + const int GQA_T = 8; + constexpr int GQA_SEGMENT_SIZE = 4; // 4x8x8, must be multiple of 4 + constexpr int KV_HEADS_PER_CU = 1; + constexpr int Q_HEADS_PER_CU = Q_HEADS_PER_GROUP * 1; + constexpr int ATTN_GROUPS_PADDING = ((Q_HEADS_PER_CU + GQA_SEGMENT_SIZE - 1) / GQA_SEGMENT_SIZE) * GQA_SEGMENT_SIZE - Q_HEADS_PER_CU; +#elif ATTN_IMPL == ATTN_IMPL_1x8x1 + const int GQA_R = 8; + const int GQA_S = 8; + const int GQA_T = 8; + constexpr int GQA_SEGMENT_SIZE = 8; // 8x8x8, must be multiple of 8 + constexpr int KV_HEADS_PER_CU = 1; + constexpr int Q_HEADS_PER_CU = Q_HEADS_PER_GROUP * 1; + constexpr int ATTN_GROUPS_PADDING = ((Q_HEADS_PER_CU + GQA_SEGMENT_SIZE - 1) / GQA_SEGMENT_SIZE) * GQA_SEGMENT_SIZE - Q_HEADS_PER_CU; +#endif + + +constexpr int Q_HEADS_PER_GROUP_PADDED = Q_HEADS_PER_GROUP + ATTN_GROUPS_PADDING; + +constexpr int Q_HEADS_PADDED_PER_CU = KV_HEADS_PER_CU * Q_HEADS_PER_GROUP_PADDED; + +constexpr int ROPE_BY_PASS = DH - ROPE_DIM; + +///@brief Q4K block +///@param scales: per-group uint8 scale s' +///@param mins: per-group uint8 min m' +///@param qs: 4-bit quantized values +///@param S: per-super-block bf16 scale S' +///@param M: per-super-block bf16 min M' (stored negated; the kernel adds it) +typedef struct { + uint8 scales[QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE]; // per-group scales and mins + uint8 mins[QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE]; // per-group scales and mins + uint4 qs[QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE / 2]; // 4-bit quantized values + bf16 S[QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE / 256]; + bf16 M[QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE / 256]; +} q4k_block_t; + +///@brief Q80 block +///@param scales: scales and mins, bf16 +///@param mins: scales and mins, bf16 +///@param qs: 4-bit quantized values +typedef struct { + bf16 scales[QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE]; // per-group scales and mins + int8_t qs[QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE]; // 8--bit quants +} q80_block_t; + + +#if QUANT_TYPE == __Q4_K__ +#define QUANT_BLOCK q4k_block_t +#elif QUANT_TYPE == __Q8_0__ +#define QUANT_BLOCK q80_block_t +#endif + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/mvm_col_major.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/mvm_col_major.hpp new file mode 100644 index 000000000..e5bc61b78 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/mvm_col_major.hpp @@ -0,0 +1,153 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __MVM_BF16_HPP__ +#define __MVM_BF16_HPP__ + +#include +#include +#include + +#include "zero.h" +#include +#include "passThroughCommon.hpp" + +#include "common_external.hpp" + + +// Column-major matrix-vector multiply, accumulating into result_acc_ptr. +// +// mat_in is column-major: each column is a contiguous block of TILE_ROW_STRIDE +// elements. The outer loop walks TILE_ROW_STRIDE-row bands of the output; the +// inner loop walks all columns, processing VEC_IN_LANES columns per iteration +// alongside the matching VEC_IN_LANES input-vector elements. +// +// mat_in : MatrixRows x MatrixCols, column-major, column stride = TILE_ROW_STRIDE +// vec_in : length MatrixCols +// result : length MatrixRows (float accumulator; caller initialises to 0 or a partial sum) +template +void matvec_vectorized_col_major( + MatrixT *mat_in, VectorInT * vec_in, VectorOutT *result_acc_ptr +){ + static_assert(MatrixRows % TILE_ROW_STRIDE == 0); + + // Columns consumed per inner iteration. Fixed at 16 to match the 16-way + // aie::accumulate call below; enforced by the static_assert inside the loop. + constexpr const int VEC_IN_LANES = 32; + static_assert(MatrixCols % VEC_IN_LANES == 0); + + + MatrixT* a_ptr = mat_in; + VectorOutT* res_ptr = result_acc_ptr; + + // AIE_PREPARE_FOR_PIPELINING + // AIE_LOOP_RANGE(MatrixRows/TILE_ROW_STRIDE, MatrixRows/TILE_ROW_STRIDE ) + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(MatrixRows/TILE_ROW_STRIDE, MatrixRows/TILE_ROW_STRIDE) + for(size_t row_idx = 0; row_idx _res_vec = aie::load_v(res_ptr); + aie::accum res_acc; + res_acc.from_vector(_res_vec); + + VectorInT* b_ptr = vec_in; + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(MatrixCols/VEC_IN_LANES, MatrixCols/VEC_IN_LANES) + for(int col_idx = 0; col_idx < MatrixCols; col_idx += VEC_IN_LANES){ + + // Load VEC_IN_LANES consecutive input-vector elements (one column group). + aie::vector b_vec = aie::load_v(b_ptr); + aie::vector b_vec_in_MatrixT; + if constexpr (std::is_same_v) { + b_vec_in_MatrixT = b_vec; + } else { + aie::accum b_vec_acc; + b_vec_acc.from_vector(b_vec); + b_vec_in_MatrixT = b_vec_acc.template to_vector(); + } + + b_ptr += VEC_IN_LANES; + + // Load and mac in a loop (slower compile, may reduce pipeline efficiency vs unrolled below) + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_UNROLL_FULL + for (int i = 0; i < VEC_IN_LANES; i++) { + aie::vector a_vec = aie::load_v(a_ptr); + a_ptr += PHYSICAL_ROW_STRIDE; + res_acc = aie::mac(res_acc, a_vec, b_vec_in_MatrixT.get(i)); + } + + // // Load the corresponding VEC_IN_LANES column slices of the matrix tile + // // (each slice is TILE_ROW_STRIDE elements, one per output row in the band). + // // Unrolled manually for pipeline efficiency; static_assert guards the count. + // static_assert(VEC_IN_LANES == 16); + // aie::vector a_vec_0 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_1 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_2 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_3 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_4 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_5 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_6 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_7 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_8 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_9 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_10 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_11 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_12 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_13 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_14 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + // aie::vector a_vec_15 = aie::load_v(a_ptr); + // a_ptr+= TILE_ROW_STRIDE; + + // // res_acc = aie::accumulate( + // // res_acc, b_vec, 0, + // // a_vec_0, a_vec_1, a_vec_2, a_vec_3, + // // a_vec_4, a_vec_5, a_vec_6, a_vec_7, + // // a_vec_8, a_vec_9, a_vec_10, a_vec_11, + // // a_vec_12, a_vec_13, a_vec_14, a_vec_15 + // // ); + + // res_acc = aie::mac(res_acc, a_vec_0, b_vec_in_MatrixT.get(0)); + // res_acc = aie::mac(res_acc, a_vec_1, b_vec_in_MatrixT.get(1)); + // res_acc = aie::mac(res_acc, a_vec_2, b_vec_in_MatrixT.get(2)); + // res_acc = aie::mac(res_acc, a_vec_3, b_vec_in_MatrixT.get(3)); + // res_acc = aie::mac(res_acc, a_vec_4, b_vec_in_MatrixT.get(4)); + // res_acc = aie::mac(res_acc, a_vec_5, b_vec_in_MatrixT.get(5)); + // res_acc = aie::mac(res_acc, a_vec_6, b_vec_in_MatrixT.get(6)); + // res_acc = aie::mac(res_acc, a_vec_7, b_vec_in_MatrixT.get(7)); + // res_acc = aie::mac(res_acc, a_vec_8, b_vec_in_MatrixT.get(8)); + // res_acc = aie::mac(res_acc, a_vec_9, b_vec_in_MatrixT.get(9)); + // res_acc = aie::mac(res_acc, a_vec_10, b_vec_in_MatrixT.get(10)); + // res_acc = aie::mac(res_acc, a_vec_11, b_vec_in_MatrixT.get(11)); + // res_acc = aie::mac(res_acc, a_vec_12, b_vec_in_MatrixT.get(12)); + // res_acc = aie::mac(res_acc, a_vec_13, b_vec_in_MatrixT.get(13)); + // res_acc = aie::mac(res_acc, a_vec_14, b_vec_in_MatrixT.get(14)); + // res_acc = aie::mac(res_acc, a_vec_15, b_vec_in_MatrixT.get(15)); + } + aie::store_v(res_ptr, res_acc.template to_vector()); + res_ptr+= TILE_ROW_STRIDE; + + } + +} + + +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/nonLinearFunction.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/nonLinearFunction.h new file mode 100644 index 000000000..cb845d27c --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/nonLinearFunction.h @@ -0,0 +1,162 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __NONLINEAR_HPP__ +#define __NONLINEAR_HPP__ + +#include +#include +#include + +#include "zero.h" +#include +#include "passThroughCommon.hpp" +#include "aie_kernel_utils.h" + +#include "lut_based_ops.h" + +template +__attribute__((always_inline)) aie::vector exp2_bf16_noLUT(aie::vector&x){ + + constexpr bfloat16 min_clamp = -87.0f; + constexpr bfloat16 max_clamp = 88.0f; + aie::vector min_value = aie::broadcast(min_clamp); + aie::vector max_value = aie::broadcast(max_clamp); // max of float + + x = aie::clamp(x, min_value, max_value); + aie::accum Vec_acc = aie::mul(x, exp_scale); + aie::vector result = aie::exp2(Vec_acc.template to_vector()); + return result; + +} + + + + + +template +aie::vector getSigmoidBf16_nonLUT(aie::vector x){ + + + const bfloat16 half = 0.5f; + const bfloat16 one = 1.0f; + aie::vector v_half = aie::broadcast(half); + aie::vector v_one = aie::broadcast(one); + aie::accum x_mul_half =aie::mul(x, v_half); + aie::vector tanh_x_half = aie::tanh(x_mul_half.template to_vector()); + + aie::vector tanh_x_half_plus_one = aie::add(tanh_x_half, v_one); + aie::vector tanh_x_half_plus_one_div_2 = aie::mul(tanh_x_half_plus_one, v_half); + + return tanh_x_half_plus_one_div_2; + + +} + + +template +aie::vector getSiluBf16_nonLUT(aie::vector x){ + + + aie::vector sigmoid_x = getSigmoidBf16_nonLUT(x); + aie::vector res = aie::mul(x, sigmoid_x); + return res; + +} + +template +void softmax( + bfloat16* vec_in +){ + // apply softmax function on this input vector, assume vec_in is size + + + + constexpr int vecLen = 32; + static_assert(size % vecLen == 0); + float exp_sum =0.0f; + + + constexpr bf16 min_clamp = -87.0f; + constexpr bf16 max_clamp = 88.0f; + aie::vector min_value = aie::broadcast(min_clamp); + aie::vector max_value = aie::broadcast(max_clamp); + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(size/vecLen,size/vecLen) + for(int i = 0; i < size; i += vecLen){ + aie::vector v = aie::load_v(vec_in + i); + // aie::vector v_clamped = aie::clamp(v, min_value, max_value); + // aie::accum exp_res_acc = getExpBf16(v_clamped); + // aie::vector exp_res_bf16 = exp_res_acc.template to_vector(); + aie::vector exp_res_bf16= exp2_bf16_noLUT(v); + aie::store_v(vec_in + i, exp_res_bf16); + exp_sum += aie::reduce_add(exp_res_bf16); + } + bf16 inv_exp_sum = 1.0f / exp_sum; + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(size/vecLen,size/vecLen) + for(int i = 0; i < size; i += vecLen){ + aie::vector v = aie::load_v(vec_in + i); + aie::accum mul_res = aie::mul(inv_exp_sum, v); + aie::store_v(vec_in + i, mul_res.template to_vector()); + } + + + +} + +/// @brief Softmax over the K selected router logits, kept in float32. +/// +/// Running the full NUM_EXPERTS-wide softmax before the top-K selection is both +/// wasted work and the router's largest avoidable error term. Its denominator +/// is cancelled by the renormalization that follows the selection, so +/// +/// softmax_all(i) / sum_{j in topK} softmax_all(j) +/// == exp(z_i - zmax) / sum_{j in topK} exp(z_j - zmax) +/// +/// and evaluating the right-hand side over K values instead of 256 lets the +/// whole thing stay in float32. Two roundings disappear with it. The logits +/// no longer round to bfloat16 before the exponential -- a bfloat16 ulp at +/// |z| = 8 is 0.0625, which is a 6% relative error on that expert's weight and, +/// worse, collapses near-ties so the selection itself picks the wrong expert. +/// And subtracting zmax puts every argument in (-inf, 0], which removes the +/// [-87, 88] clamp: it was a hard clip, not a max subtraction, so a logit past +/// the top of that range used to saturate silently. +/// +/// The one rounding left is aie::exp2's bfloat16 result -- the hardware op only +/// returns float32 on AIE_ARCH 22 with FP32 emulation -- and it lands on a +/// routing weight as a smooth 0.4% perturbation, not on the discrete choice. +/// +/// @param out K normalized routing weights, float32 +/// @param z the K selected logits, descending, so z[0] is the max +template +void softmax_topk_f32(float* out, const float* z) +{ + static_assert(K <= VLEN); + constexpr float log2_e = 1.44269504088896341f; + + // 2^-127 flushes to zero, so the VLEN-K padding lanes drop out of the sum + aie::vector t = aie::broadcast(-127.0f); + + const float zmax = z[0]; + AIE_LOOP_UNROLL_FULL + for (int i = 0; i < K; i++) { + t.set((z[i] - zmax) * log2_e, i); + } + aie::vector e = aie::exp2(t); + + float exp_sum = 0.0f; + AIE_LOOP_UNROLL_FULL + for (int i = 0; i < K; i++) { + exp_sum += (float)e.get(i); + } + const float inv_exp_sum = 1.0f / exp_sum; + + AIE_LOOP_UNROLL_FULL + for (int i = 0; i < K; i++) { + out[i] = (float)e.get(i) * inv_exp_sum; + } +} + +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/packet_control_gen.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/packet_control_gen.hpp new file mode 100644 index 000000000..d7ff8d4a7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/packet_control_gen.hpp @@ -0,0 +1,297 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __PACKET_CONTROL_GEN_H__ +#define __PACKET_CONTROL_GEN_H__ +#define NOCPP +#include +#include +#include +#include + +#include + + + + +// Use a constexpr function for compile-time computation +constexpr uint32_t get_CT_bd_x_0_address(int32_t bd_id) { + return 0x000001D000u + static_cast(bd_id) * 0x20u; +} + + +constexpr uint32_t get_SHM_bd_x_0_address(int32_t bd_id){ + + return 0x000001D000 + bd_id*0x20; + +} + +constexpr uint32_t tm_start_addr = 0x80000; +static volatile uint32_t chess_storage(TM : tm_start_addr) addr_space_start; + +void read_processor_bus(uint32_t *data, uint32_t addr, uint32_t size, + uint32_t stride=16) { + for (uint32_t i = 0; i < size; i++) { + + #if defined(__chess__) + uint32_t offset = addr + (i * stride); + data[i] = *(&addr_space_start + (offset / 4)); + #elif defined(__AIECC__) + uint32_t offset =addr + (i*(stride/4)); + data[i] = read_tm(offset ); + #else + static_assert(false, "Unexpected case here"); + #endif + } +} + +void write_process_bus(uint32_t *data, uint32_t addr, uint32_t size, uint32_t stride=16){ + + for (uint32_t i = 0; i < size; i++) { + + #if defined(__chess__) + uint32_t offset = addr + (i * stride); + *(&addr_space_start + (offset / 4)) = data[i]; + #elif defined(__AIECC__) + uint32_t offset =addr + (i*(stride/4)); + write_tm( data[i], offset ); + #else + static_assert(false, "Unexpected case here"); + #endif + } +} + +inline volatile void compiler_sync_barrier(){ + #if defined(__chess__) + chess_separator_scheduler(4); + #elif defined(__AIECC__) + __builtin_aie2p_sched_barrier(); + volatile int32_t k = 0; + k++; + __builtin_aie2p_sched_barrier(); + k++; + __builtin_aie2p_sched_barrier(); + + #else + static_assert(false, "Unexpected case here"); + #endif +} + + + +bool even_parity(uint32_t n) { + // Return true of even number of "1" bits, false otherwise + uint32_t p = 0; + while (n) { + p += n & 1; + n >>= 1; + } + return (p % 2) == 0; +} +uint32_t control_packet_gen(int32_t stream_id, int32_t operation, int32_t beats, int32_t address){ + //operation: 0 read, 1 write + uint32_t control_packet = + stream_id << 24 | operation << 22 | beats << 20 | address; + control_packet |= (0x1 & even_parity(control_packet)) << 31; + + return control_packet; +} + + + +inline uint32_t source_core_id_gen(uint32_t source_col, uint32_t source_row){ + return (source_col <<5)|source_row; +} + +// Generate packet flow header +uint32_t packet_flow_gen(uint32_t packet_type, uint32_t stream_id, uint32_t source_core_id =get_coreid()){ + + //TODO: put a check on the packet_type? core=0, memtile=1, shimtile=2??? + uint32_t packet_header = (source_core_id << 16) | (packet_type<<12) | (stream_id); + + bool odd_parity = (even_parity(packet_header)) ; + packet_header |= (0x1 & odd_parity) << 31; + + return packet_header; +} + + + + + +// Code for changing CT's register/behavior at runtime + + +// change the buffer len this bd receive/send at each transaction +inline void configure_BD_x_MM2S_y_dma_bd_len( + + const uint32_t CT_BD_id, // The CT dma's bd_id for configuration + + const uint32_t MM2S_port_num, uint32_t len, uint32_t bd_repeat_len=0 ){ + uint32_t len_mask = 0; + uint32_t write_buffer[1]; + + + uint32_t BD_x_0_addr = get_CT_bd_x_0_address(CT_BD_id); + + uint32_t MM2S_CTRL = (MM2S_port_num==0)? 0x000001DE10 : 0x000001DE18; + uint32_t MM2S_START_QUEUE = (MM2S_port_num == 0) ? 0x000001DE14 : 0x000001DE1C; + + read_processor_bus( write_buffer, BD_x_0_addr, 1, 16 );// first read + compiler_sync_barrier(); + + len_mask = 0x3FFF; + *write_buffer = ( (*write_buffer) & ~len_mask) | ( (len) & len_mask); + write_process_bus( write_buffer, BD_x_0_addr, 1, 16 ); + compiler_sync_barrier(); + + *(write_buffer) =(1<<1);// disable MM2S-1 + write_process_bus( (uint32_t*)(write_buffer),MM2S_CTRL, 1, 16 ); + compiler_sync_barrier(); + + *(write_buffer) =(0<1); // renable MM2S-1 + write_process_bus( (uint32_t*)(write_buffer),MM2S_CTRL, 1, 16 ); + compiler_sync_barrier(); + + *(write_buffer) =(bd_repeat_len<<16) | (CT_BD_id); + write_process_bus( (uint32_t*)(write_buffer),MM2S_START_QUEUE, 1, 16 ); + compiler_sync_barrier(); + + + + +} + + + + + + +// CODE For control shimtile transfer by changing shimtile BD_x_0 address and the corresponding queue +//THIS version assume the packet_id is already setup in CT's MM2S port + +inline void add_shim_bd_address_offset( + uint32_t virtual_address_base_low, uint32_t virtual_address_base_x2, + uint32_t address_offset, uint32_t& virtual_address_low, + uint32_t& virtual_address_x2) { + virtual_address_low = virtual_address_base_low + address_offset; + const uint32_t carry = virtual_address_low < virtual_address_base_low; + const uint32_t address_high = + ((virtual_address_base_x2 & 0xFFFFu) + carry) & 0xFFFFu; + virtual_address_x2 = + (virtual_address_base_x2 & 0xFFFF0000u) | address_high; +} + +void control_Shimtile_transfer( + uint32_t virtual_address_base_low, uint32_t virtual_address_base_x2, + uint32_t length, uint32_t address_offset, + uint32_t control_packet_out_prod_lock, uint32_t control_packet_out_con_lock, + uint32_t * control_packet_out_buf, + + + uint32_t CT_to_shimtile_control_bd_id, + uint32_t CT_to_shimtile_control_bd_port, + uint32_t SHIM_control_packet_id, + + uint32_t SHM_MM2S_channel_idx, uint32_t Shimtile_bd_id +){ + + uint32_t Shimtile_BD_X_0_addr = get_SHM_bd_x_0_address(Shimtile_bd_id); + uint32_t virtual_address_low; + uint32_t virtual_address_x2; + add_shim_bd_address_offset( + virtual_address_base_low, virtual_address_base_x2, address_offset, + virtual_address_low, virtual_address_x2); + + configure_BD_x_MM2S_y_dma_bd_len(CT_to_shimtile_control_bd_id,CT_to_shimtile_control_bd_port, 4,0);//Configure MM2s-0 to send data + // Write BD X0, X1, and X2 so a carry from X1 updates address bits 47:32. + acquire_greater_equal(control_packet_out_prod_lock,1); + *control_packet_out_buf = control_packet_gen(SHIM_control_packet_id , 0,2, Shimtile_BD_X_0_addr); + *(control_packet_out_buf+1) = length; //bd_x_0 + *(control_packet_out_buf+2) = virtual_address_low; //bd_x_1 + *(control_packet_out_buf+3) = virtual_address_x2; //bd_x_2 + release(control_packet_out_con_lock, 1); + + + uint32_t Shimtile_MM2S_X_TASK_QUEUE_addr = SHM_MM2S_channel_idx==0 ?0x000001D214 : 0x000001D21C; + + configure_BD_x_MM2S_y_dma_bd_len(CT_to_shimtile_control_bd_id,CT_to_shimtile_control_bd_port, 2,0);//Configure MM2s-0 to send data + // Send write message + acquire_greater_equal(control_packet_out_prod_lock,1); + *control_packet_out_buf = control_packet_gen( SHIM_control_packet_id, 0,0, Shimtile_MM2S_X_TASK_QUEUE_addr); + + // assume not enable token issue + // repeat_count = 1-0 + *(control_packet_out_buf+1) = 0<<16 | Shimtile_bd_id; + release(control_packet_out_con_lock, 1); + +} + + + + + +// This is the version where the packet_flow is not being setup in MM2S port of CT +template +void control_Shimtile_transfer_with_packetflow_gen( + uint32_t virtual_address_base_low, uint32_t virtual_address_base_x2, + uint32_t length, uint32_t address_offset, + uint32_t control_packet_out_prod_lock, uint32_t control_packet_out_con_lock, + uint32_t * control_packet_out_buf, + + + uint32_t CT_to_shimtile_control_bd_id, + uint32_t CT_to_shimtile_control_bd_port, + uint32_t SHIM_control_packet_id, + + uint32_t SHM_MM2S_channel_idx, uint32_t Shimtile_bd_id +){ + + uint32_t Shimtile_BD_X_0_addr = get_SHM_bd_x_0_address(Shimtile_bd_id); + uint32_t virtual_address_low; + uint32_t virtual_address_x2; + add_shim_bd_address_offset( + virtual_address_base_low, virtual_address_base_x2, address_offset, + virtual_address_low, virtual_address_x2); + + configure_BD_x_MM2S_y_dma_bd_len(CT_to_shimtile_control_bd_id,CT_to_shimtile_control_bd_port, 5,0);//Configure MM2s-0 to send data + // Write BD X0, X1, and X2 so a carry from X1 updates address bits 47:32. + acquire_greater_equal(control_packet_out_prod_lock,1); + *control_packet_out_buf = packet_flow_gen(0, // 0 since is from CT? + SHIM_control_packet_id + ); + *(control_packet_out_buf+1) = control_packet_gen(SHIM_control_packet_id , 0,2, Shimtile_BD_X_0_addr); + *(control_packet_out_buf+2) = length; //bd_x_0 + *(control_packet_out_buf+3) = virtual_address_low; //bd_x_1 + *(control_packet_out_buf+4) = virtual_address_x2; //bd_x_2 + release(control_packet_out_con_lock, 1); + + + uint32_t Shimtile_MM2S_X_TASK_QUEUE_addr = SHM_MM2S_channel_idx==0 ?0x000001D214 : 0x000001D21C; + + configure_BD_x_MM2S_y_dma_bd_len(CT_to_shimtile_control_bd_id,CT_to_shimtile_control_bd_port, 3,0);//Configure MM2s-0 to send data + // Send write message + acquire_greater_equal(control_packet_out_prod_lock,1); + + *control_packet_out_buf = packet_flow_gen(0, // 0 since is from CT? + SHIM_control_packet_id); + + *(control_packet_out_buf+1) = control_packet_gen( SHIM_control_packet_id, 0,0, Shimtile_MM2S_X_TASK_QUEUE_addr); + + // assume not enable token issue + // repeat_count = 1-0 + if(! issue_token){ + *(control_packet_out_buf+2) = 0<<16 | Shimtile_bd_id; + }else{ + *(control_packet_out_buf+2) = 1<<31 | 0<<16 | Shimtile_bd_id; + } + + release(control_packet_out_con_lock, 1); + +} + + + + + +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/passThroughCommon.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/passThroughCommon.hpp new file mode 100644 index 000000000..8a6322224 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/passThroughCommon.hpp @@ -0,0 +1,48 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef PASS_THROUGH_COMMON_HPP +#define PASS_THROUGH_COMMON_HPP + +#include +#include +#include +#include +#include "aie_kernel_utils.h" //TODO: a better method? +template + +void copy_float_to_bf16(bfloat16 * y, const float * y_acc) { + static_assert(m%16 == 0); + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_UNROLL_FULL + for (int i = 0; i < m / 16; i++){ + aie::vector y_vec = aie::load_v<16>(y_acc + i * 16); + aie::accum acc; + acc.from_vector(y_vec); + aie::store_v(y + i * 16, acc.template to_vector()); + } +} + +template +void copy_bf16_to_float(float * y, const bfloat16 * y_bf16) { + static_assert(m%16 == 0); + AIE_PREPARE_FOR_PIPELINING + for (int i = 0; i < m / 16; i++){ + aie::vector y_vec = aie::load_v<16>(y_bf16 + i * 16); + aie::accum acc; + acc.from_vector(y_vec); + aie::store_v(y + i * 16, acc.template to_vector()); + } +} + +template +void copy_bf16_to_bf16( bfloat16 *y, const bfloat16 * y_bf16) { + static_assert(m%16 == 0); + AIE_PREPARE_FOR_PIPELINING + for (int i = 0; i < m / 16; i++){ + aie::vector y_vec = aie::load_v<16>(y_bf16 + i * 16); + aie::store_v(y + i * 16, y_vec); + } + +} + +#endif // PASS_THROUGH_COMMON_HPP diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/proj_main.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/proj_main.cc new file mode 100644 index 000000000..46493b10d --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/proj_main.cc @@ -0,0 +1,251 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "model_spec.h" +#include "aie_kernel_utils.h" +#include "aie_array_layout.h" +#include "q4_core.h" +#include "q8_core.h" + + + +constexpr int x_prod_lock = 0; +constexpr int x_cons_lock = 1; +constexpr int w_prod_lock = 2; +constexpr int w_cons_lock = 3; +constexpr int y_prod_ping_lock = 4; +constexpr int y_prod_pong_lock = 5; +constexpr int rtp_available_lock = 6; +constexpr int y_cons_ping_lock = 7; +constexpr int y_cons_pong_lock = 8; +AIE_PERSIST_ZERO bool is_y_ping = false; +// weight ring: W_RING_BLOCKS one-block slots, 2 in each of w_ping / w_pong (so +// the stream can run further ahead of the math; MoE step 2, item 3a) +constexpr int W_RING_BLOCKS = 4; +int w_slot = W_RING_BLOCKS - 1; +AIE_PERSIST_ZERO bool is_x_ping = false; + +#if QUANT_TYPE == __Q4_K__ && Q4K_INT8_MMUL +// int8 x of every x slice of one mvm() (see q4k_prepare_x): K <= MAX_MVM_K +// the A matrices of up to 16 x slices (1 KB each), as four 4 KB arrays: data +// memory is four 16 KB banks and an array must sit in one; with the 4-block +// weight ring, 8 KB pieces no longer fit +constexpr int Q4K_SLICES = MAX_MVM_K / QXNX_COL_BLOCK_SIZE; +constexpr int Q4K_SLICES_PER_PART = (Q4K_SLICES + 3) / 4; +alignas(64) static int8 q4k_a_cache_0[Q4K_SLICES_PER_PART * Q4K_A_BYTES]; +alignas(64) static int8 q4k_a_cache_1[Q4K_SLICES_PER_PART * Q4K_A_BYTES]; +alignas(64) static int8 q4k_a_cache_2[Q4K_SLICES_PER_PART * Q4K_A_BYTES]; +alignas(64) static int8 q4k_a_cache_3[Q4K_SLICES_PER_PART * Q4K_A_BYTES]; +alignas(64) static bf16 q4k_e_cache[MAX_MVM_K / QXNX_COL_BLOCK_SIZE * Q4K_E_ELEMS]; +#endif + +// x arrives by circuit broadcast: every core sees every x slice. In the routed +// expert down step the 4 columns run 4 different experts and the slices come +// round robin (expert 0, 1, 2, 3, then the next k columns), so a core keeps +// slice x_pick of every x_stride and hands the rest straight back. +static inline void skip_x_slices(int n) { + for (AIE_LOCK_LOOP_CTR t = 0; t < n; t++) { + _lock_acquire(x_cons_lock); + is_x_ping = !is_x_ping; + _lock_release(x_prod_lock); + } +} + +void mvm( + int M, int K, + bf16 * x_ping, + bf16 * x_pong, + QUANT_BLOCK * w_ping, + QUANT_BLOCK * w_pong, + bf16 * y_ping, + bf16 * y_pong, + float* y_acc, + bf16 * b_col_reduce_add, + const int32_t send_x_output, + const uint32 pkt_id, + const int x_stride = 1, // x slices per K step (NUM_MVM_COLUMN in routed down) + const int x_pick = 0 // the slice this core uses, 0 .. x_stride - 1 +) { + + constexpr int m = QXNX_ROW_BLOCK_SIZE; + constexpr int k = QXNX_COL_BLOCK_SIZE; + + uint32* pkt_id_ping = reinterpret_cast(y_ping + 14); + uint32* pkt_id_pong = reinterpret_cast(y_pong + 14); + + for (AIE_LOCK_LOOP_CTR i = 0; i < M / m; i++) { + #if QUANT_TYPE == __Q4_K__ + // the scale path and the min path stay in registers for the whole + // K loop; nothing touches y_acc until _Q4K_finalize() + q4k_accum_t c_accum_s; + q4k_accum_t c_accum_m; + _Q4K_zero(c_accum_s, c_accum_m); + #else + zero_vectorized(y_acc); + #endif + for (AIE_LOCK_LOOP_CTR j = 0; j < K / k; j++) { + + skip_x_slices(x_pick); + _lock_acquire(x_cons_lock); + _lock_acquire(w_cons_lock); + is_x_ping = !is_x_ping; + bf16* x_using = is_x_ping ? x_ping : x_pong; + w_slot = (w_slot + 1) % W_RING_BLOCKS; + QUANT_BLOCK* w_using = (w_slot < W_RING_BLOCKS / 2 ? w_ping : w_pong) + w_slot % (W_RING_BLOCKS / 2); + + + #if QUANT_TYPE == __Q4_K__ + // two bf16 limbs per group, interleaved (hi, lo) + bf16* b_col_reduce_add_ptr = b_col_reduce_add + 2 * j * (k / GGML_GROUP_SIZE); + // special logic for i == 0, avoid recompute if it is repeat. + if(i == 0){ + // Fill the b_col_reduce_add. aie::reduce_add over a bf16 + // vector already sums in accfloat, but returns bf16 and + // throws 16 of those mantissa bits away; that error rides + // the whole min path and is then amplified by the + // scale/min cancellation in _Q4K_finalize. Reduce in + // float32 instead and hand the kernel two bf16 limbs. + // This runs once per mvm() and is read back by every row + // block, so the split costs nothing in the steady state. + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_UNROLL_FULL + for(int l = 0; l < k / GGML_GROUP_SIZE; l++)AIE_LOOP_FLATTEN{ + aie::accum x_acc; + x_acc.from_vector(aie::load_v(x_using + GGML_GROUP_SIZE * l)); + float sum = aie::reduce_add(x_acc.template to_vector()); + bf16 hi = bf16(sum); + *(b_col_reduce_add_ptr + 2 * l) = hi; + *(b_col_reduce_add_ptr + 2 * l + 1) = bf16(sum - float(hi)); + } + } + #if Q4K_INT8_MMUL + // x slice j as int8 A matrices + group scales, made once (row + // block 0) and reused by every row block, like the sums above + int8* const parts[4] = {q4k_a_cache_0, q4k_a_cache_1, q4k_a_cache_2, q4k_a_cache_3}; + int8* a_tiles = parts[j / Q4K_SLICES_PER_PART] + (j % Q4K_SLICES_PER_PART) * Q4K_A_BYTES; + bf16* e64 = q4k_e_cache + j * Q4K_E_ELEMS; + if (i == 0) { + // also rewrites this slice's min-path sums (of the rounded x) + q4k_prepare_x(x_using, a_tiles, e64, b_col_reduce_add_ptr); + } + #endif + // PROJ_COMPUTE_REPEAT is a timing experiment only (wrong results unless 1): + // 0 = stream the weights but skip the math, 2 = do the math twice + #ifndef PROJ_COMPUTE_REPEAT + #define PROJ_COMPUTE_REPEAT 1 + #endif + for (int rep = 0; rep < PROJ_COMPUTE_REPEAT; rep++) { + #if Q4K_INT8_MMUL + _Q4K_x_int8(c_accum_s, c_accum_m, a_tiles, e64, w_using, b_col_reduce_add_ptr); + #else + _Q4K_x_bf16(c_accum_s, c_accum_m, x_using, w_using, b_col_reduce_add_ptr); + #endif + } + #elif QUANT_TYPE == __Q8_0__ + _Q80_x_bf16(y_acc, x_using, w_using); + #endif + + _lock_release(w_prod_lock); + _lock_release(x_prod_lock); + skip_x_slices(x_stride - 1 - x_pick); + } + #if QUANT_TYPE == __Q4_K__ + // the whole row is done: scale path + min path, once + _Q4K_finalize(y_acc, c_accum_s, c_accum_m); + #endif + is_y_ping = !is_y_ping; + + if(send_x_output != 0){ + uint32* pkt_id_using = is_y_ping ? pkt_id_ping : pkt_id_pong; + bf16* y_using = is_y_ping ? y_ping : y_pong; + *pkt_id_using = pkt_id; + if (is_y_ping) { + _lock_acquire(y_prod_ping_lock); + } + else{ + _lock_acquire(y_prod_pong_lock); + } + copy_float_to_bf16(y_using + 16, y_acc); + if (is_y_ping) { + _lock_release(y_cons_ping_lock); + } + else { + _lock_release(y_cons_pong_lock); + } + }else{ + + bf16* y_using = is_y_ping ? y_ping : y_pong; + if (is_y_ping) { + _down_lock_acquire(y_prod_ping_lock); + } + else { + _down_lock_acquire(y_prod_pong_lock); + } + copy_float_to_bf16(y_using + 16 + m, y_acc); // offset of 16+m, 16 for packed_it + if (is_y_ping) { + _down_lock_release(y_cons_ping_lock); + } + else { + _down_lock_release(y_cons_pong_lock); + } + } + } +} + + +extern "C" { + +void proj_main( + bf16 * y_ping, + QUANT_BLOCK * w_ping, + bf16 * x_ping, + bf16 * y_pong, + QUANT_BLOCK * w_pong, + bf16 * x_pong, + int send_x_output, + int col_idx // this core's proj column, 0 .. NUM_MVM_COLUMN - 1 +) +{ +#if QUANT_TYPE == __Q4_K__ && Q4K_INT8_MMUL && !defined(__chess__) + // q4k_prepare_x never writes 3 of every 4 A rows and needs them 0. chess's + // loader zeroes .bss; Peano's does not, so zero the caches on the first call. + AIE_PERSIST_ZERO static bool a_cache_zeroed = false; + if (!a_cache_zeroed) { + zero_vectorized(q4k_a_cache_0); + zero_vectorized(q4k_a_cache_1); + zero_vectorized(q4k_a_cache_2); + zero_vectorized(q4k_a_cache_3); + a_cache_zeroed = true; + } +#endif + alignas(aie::vector_decl_align) float y_acc[QXNX_ROW_BLOCK_SIZE]; + // 2 bf16 limbs per group, see the fill loop in mvm() + alignas(aie::vector_decl_align) bfloat16 b_col_reduce_add[2 * MAX_MVM_K / GGML_GROUP_SIZE]; + + // phase 1: qkv proj, D -> DQ + DK + DV, to RoPE + mvm((DQ + DK + DV) / MVM_CORES, MODEL_DIM, x_ping, x_pong, w_ping, w_pong, y_ping, y_pong, y_acc, b_col_reduce_add, send_x_output, pkt_id_to_rope); + + // phase 1b: attention output gate logits, D -> DQ, to the gate tile + mvm(DQ / MVM_CORES, MODEL_DIM, x_ping, x_pong, w_ping, w_pong, y_ping, y_pong, y_acc, b_col_reduce_add, send_x_output, pkt_id_to_gate); + + // phase 2: o proj, DQ -> D, to RMS + mvm(MODEL_DIM / MVM_CORES, DQ, x_ping, x_pong, w_ping, w_pong, y_ping, y_pong, y_acc, b_col_reduce_add, send_x_output, pkt_id_to_aux); + + // phase 3: shared expert up/gate, D -> 2 * I, to GLU + mvm(2 * INTERMEDIATE_SIZE / MVM_CORES, MODEL_DIM, x_ping, x_pong, w_ping, w_pong, y_ping, y_pong, y_acc, b_col_reduce_add, send_x_output, pkt_id_to_glu); + + // phase 4: shared expert down, I -> D, to RMS + mvm(MODEL_DIM / MVM_CORES, INTERMEDIATE_SIZE, x_ping, x_pong, w_ping, w_pong, y_ping, y_pong, y_acc, b_col_reduce_add, send_x_output, pkt_id_to_aux); + + // phase 5: routed experts. Each column runs one expert, so the 4 columns + // take NUM_ACT_EXPERTS / NUM_MVM_COLUMN rounds of gate/up + down. + for(int k = 0; k < NUM_ACT_EXPERTS/NUM_MVM_COLUMN; k++){ + mvm((2*INTERMEDIATE_SIZE) / MVM_CORES_Per_Column, MODEL_DIM, x_ping, x_pong, w_ping, w_pong, y_ping, y_pong, y_acc, b_col_reduce_add, send_x_output, pkt_id_to_glu); + // down: x is the 4 experts' h, round robin; keep this column's expert + mvm((MODEL_DIM) /MVM_CORES_Per_Column , INTERMEDIATE_SIZE, x_ping, x_pong, w_ping, w_pong, y_ping, y_pong, y_acc, b_col_reduce_add, send_x_output, pkt_id_to_glu, + NUM_MVM_COLUMN, col_idx); + } +} + + +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/q4_core.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/q4_core.h new file mode 100644 index 000000000..c5f791455 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/q4_core.h @@ -0,0 +1,433 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __Q4_CORE_H__ +#define __Q4_CORE_H__ +#include "aie_kernel_utils.h" +#include "model_spec.h" +#include "aie_array_layout.h" +#include "bf16_limb_math.hpp" + +/// @brief y += W x for one Q4_K weight block, x and y bf16 / float32. +/// +/// Format (see FLM_Q4NX_Converter/quant.md): a super-block is 256 weights of +/// one row, split into 8 groups of GGML_GROUP_SIZE. Per group it stores a uint8 +/// scale s' and a uint8 min m'; per super-block a bf16 S' and a bf16 M'. The +/// dequantized weight is +/// +/// w = S' s'_j q + M' m'_j +/// +/// The datapath keeps "reduce first, scale after": the whole 32-value group is +/// reduced against x in one float32 accumulator and only then meets s'_j; S' is +/// applied once per super-block. Every multiplier operand is bf16-exact -- q is +/// a uint4, s'/m' are uint8 (bf16 holds every integer up to 256), S'/M' are +/// stored bf16 -- so a rounding can only ever land on an accumulator, and none +/// of the three that reach the output are rounded to bf16 on their way in: the +/// group sum and both super-block accumulators go through a two-limb split +/// instead. Emulating the whole datapath against an exact float64 reference +/// (FLM_Q4NX_Converter/npu_q4k_emulate.py) puts the result at ~1e-05 relative, +/// two orders under the ~4e-03 of the Q4_K format itself. +/// +/// Layout, all column major over the QXNX_ROW_BLOCK_SIZE x QXNX_COL_BLOCK_SIZE +/// block, whose whole row span is resident at once (PARALLEL_ROWS): +/// qs : one column = PARALLEL_ROWS nibbles, columns ascending +/// scales : one group = PARALLEL_ROWS uint8, groups ascending +/// mins : same as scales +/// S / M : PARALLEL_ROWS bf16; a block is exactly one super-block, so there +/// is one entry per row and no super-block loop +/// +/// The scale path and the min path live in two separate float32 accumulators +/// that the caller carries across the whole K loop, so the min term never has to +/// be folded in inside the inner loop and nothing round-trips through memory +/// between blocks. Call _Q4K_finalize() once the K loop is done. +/// +/// @param c_accum_s running sum_b S'_b * (scale path), updated in place +/// @param c_accum_m running sum_b M'_b * (min path), updated in place +/// @param x activations, bf16, QXNX_COL_BLOCK_SIZE of them +/// @param w_buffer the weight block +/// @param b_col_reduce_buffer sum_i x_i per group as two interleaved bf16 +/// limbs (hi, lo), shared across all rows +using q4k_accum_t = aie::accum; + +void _Q4K_x_bf16( + q4k_accum_t & c_accum_s, + q4k_accum_t & c_accum_m, + bf16 * x, + q4k_block_t* w_buffer, + bf16* b_col_reduce_buffer +) { + static constexpr int SUPER_BLOCK_SIZE = 256; + static constexpr int GROUPS_PER_SB = SUPER_BLOCK_SIZE / GGML_GROUP_SIZE; + // one 512-bit uint4 load is 128 nibbles, i.e. this many whole columns + static constexpr int NIBBLES_PER_LOAD = 128; + static constexpr int COLS_PER_LOAD = NIBBLES_PER_LOAD / PARALLEL_ROWS; + static constexpr int LOADS_PER_GROUP = GGML_GROUP_SIZE / COLS_PER_LOAD; + + static_assert(PARALLEL_ROWS == QXNX_ROW_BLOCK_SIZE); + // one weight block is exactly one super-block, so there is no super-block loop + static_assert(QXNX_COL_BLOCK_SIZE == SUPER_BLOCK_SIZE); + static_assert(NIBBLES_PER_LOAD % PARALLEL_ROWS == 0); + static_assert(GGML_GROUP_SIZE % COLS_PER_LOAD == 0); + + uint4* it_quant = w_buffer->qs; + uint8* it_scale = w_buffer->scales; + uint8* it_min = w_buffer->mins; + + bf16* it_reduce_b = b_col_reduce_buffer; + bf16* it_x = x; + + // sum_j s'_j * (sum_i q_i x_i) and sum_j m'_j * (sum_i x_i), both carried + // in float32 for the whole super-block and both fed through a two-limb + // split, so neither reduction passes through a bf16 on its way in. + aie::accum acc_s; + aie::accum acc_m; + acc_s.from_vector(aie::zeros()); + acc_m.from_vector(aie::zeros()); + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE( GROUPS_PER_SB, GROUPS_PER_SB ) + for (int g = 0; g < GROUPS_PER_SB; g++) { + aie::vector b_col = aie::load_v(it_x); + + // One float32 accumulator for the whole 32-value group: a + // PARALLEL_ROWS-wide MAC already covers the accumulator dependency, + // so there is nothing to interleave against. + aie::accum temp_acc; + temp_acc.from_vector(aie::zeros()); + + AIE_LOOP_UNROLL_FULL + for (int l = 0; l < LOADS_PER_GROUP; l++) { + aie::vector q_raw = + aie::load_v(it_quant); + it_quant += NIBBLES_PER_LOAD / 2; // uint4* steps two nibbles + + // uint4 -> bf16 is exact + aie::accum q_acc; + q_acc.from_vector(aie::to_float(q_raw, 0)); + aie::vector q_bf16 = + q_acc.template to_vector(); + + AIE_LOOP_UNROLL_FULL + for (int k = 0; k < COLS_PER_LOAD; k++) { + aie::vector a_col = + q_bf16.template extract(k); + bfloat16 scalar = b_col.get(l * COLS_PER_LOAD + k); + temp_acc = aie::mac(temp_acc, a_col, scalar); + } + } + + // uint8 s' / m' -> bf16, exact for every value up to 255 + aie::accum s_acc; + s_acc.from_vector(aie::to_float(aie::load_v(it_scale), 0)); + + // Rounding the group sum to bf16 here is by far the largest error term + // the kernel can introduce: 2e-03 relative, taken once per group, + // correlated across the 8 groups that share an S', and then amplified + // ~2.3x by the scale/min cancellation in _Q4K_finalize. It does not + // average away over the K loop the way an independent error would -- + // |y| ends up far smaller than the group sums that build it, so the + // error is measured against the small number. Split into two bf16 limbs + // instead: 1 extra MAC and a split per group, against the 32 MACs of the + // loop above. + acc_s = bf16_limb::mac_f32_bf16_low( + acc_s, temp_acc.template to_vector(), + s_acc.template to_vector()); + + aie::accum m_acc; + m_acc.from_vector(aie::to_float(aie::load_v(it_min), 0)); + // sum_i x_i arrives pre-split as two bf16 limbs; smallest first, so the + // small term joins acc_m before it meets the large one. + aie::vector a_mins = m_acc.template to_vector(); + acc_m = aie::mac(acc_m, a_mins, *(it_reduce_b + 1)); + acc_m = aie::mac(acc_m, a_mins, *it_reduce_b); + + it_reduce_b += 2; + it_x += GGML_GROUP_SIZE; + it_scale += PARALLEL_ROWS; + it_min += PARALLEL_ROWS; + } + + // S' * acc_s and M' * acc_m go to their own running accumulators; the two + // paths never meet inside the K loop, so neither depends on the other and + // the combining add stays off the critical path. + // + // Both multiplicands are bf16-exact (S'/M' are *stored* bf16), so the only + // rounding here would be on the accumulators -- and it would land before + // the scale/min cancellation in _Q4K_finalize, where a relative error is + // amplified ~2.3x (quant.md, "cancellation ratio"). Same reasoning as the + // group sum above, one level up and twice. Split each accumulator into two + // bf16 limbs: ~17 mantissa bits rather than 8, for 2 extra MACs and 2 msc + // per 32x256 block -- amortized over the ~800 vector ops of the group loop + // above, and in its drain phase. + aie::vector a_S = aie::load_v(w_buffer->S); + aie::vector a_M = aie::load_v(w_buffer->M); + c_accum_s = bf16_limb::mac_f32_bf16_low( + c_accum_s, acc_s.template to_vector(), a_S); + c_accum_m = bf16_limb::mac_f32_bf16_low( + c_accum_m, acc_m.template to_vector(), a_M); +} + +// =========================================================================== +// int8 x / uint4 W path (Q4K_INT8_MMUL = 1, the default) +// +// The group sums sum_i q_i x_i run on the matrix unit, on the native AIE2P +// instruction mac_4x8_8x16: A int8 4 x 8, B int8 8 x 16, C int32 4 x 16. B is the +// 4-bit weights of 8 columns x 16 rows, unpacked to int8 by one native unpack. +// (aie::mmul<4,16,16, int8, uint4> exists but is built from two of these plus a +// shuffle of A on every call: ~34 cycles each, measured.) +// +// x -> int8: per 32-value group g, x8 = round(x / 2^e_g), e_g picked so the +// largest |x| lands in 64..127. The scale is a power of two, so undoing it +// later is exact. Done once per x slice (the same x serves every row block). +// +// A trick: the 4 A rows hold 4 different groups. For the 8 columns of step s +// (group g = s / 4), only row g % 4 of A is filled, so row a of the result +// collects group a's sum. One accumulator holds 4 groups (groups 0..3 and +// 4..7 in two of them), per 16 output rows (t = 0, 1): no reset per group. +// The 32 A matrices of an x slice (1 KB) are made once with the int8 x. +// +// Host layout (decoding_layer: q4k_relayout_for_mmul), per 32 x 256 block: +// qs : [16-column step 16][t 2][16 columns][8 bytes]: 128 B; its two +// 64 B halves are the B matrices of 8 columns +// scales : [h 2][t 2][a 4][16 rows] (group g = 4 h + a, row r = 16 t + n) +// mins, S, M : unchanged +// +// The int32 group sums are exact; times 2^e_g they are exact in fp32. From there +// the scale / min paths are the same as _Q4K_x_bf16's. The one new error is x's +// rounding to 8 bits per group (bf16 itself carries 8). +// =========================================================================== +#ifndef Q4K_INT8_MMUL +#define Q4K_INT8_MMUL 1 +#endif + +constexpr int Q4K_STEPS = QXNX_COL_BLOCK_SIZE / 8; // 32 steps of 8 columns +constexpr int Q4K_A_BYTES = Q4K_STEPS * 32; // A matrices of one x slice (4 x 8 int8 each) +constexpr int Q4K_E_ELEMS = 2 * 64; // 2^e_g per lane, both halves + +/// @brief One x slice (QXNX_COL_BLOCK_SIZE bf16) -> the 32 A matrices (int8 x), +/// the per-lane group scales 2^e_g, and the min path's per-group sums. Once per +/// x slice per mvm(). +/// +/// The sums are of the ROUNDED x (sum x8 * 2^e, exact in two bf16 limbs), not of +/// x: then the block computes exactly W x^ (x^ = the rounded x) and the error is +/// W (x^ - x). With the exact sum of x in the min path instead, the error would be +/// S' s' q (x^ - x), and q is never negative (mean ~7.5), so the rounding errors +/// would add up instead of cancelling against the min term. +inline void q4k_prepare_x(const bf16* x, int8* a_tiles, bf16* e64, bf16* reduce_out) +{ + constexpr int GROUPS = QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE; // 8 + static_assert(GGML_GROUP_SIZE == 32 && GROUPS == 8); + aie::set_rounding(aie::rounding_mode::conv_even); + aie::set_saturation(aie::saturation_mode::saturate); + + // A rows that are never written must be 0. Every x slice writes the same + // positions (row g % 4 of steps 4g .. 4g+3), so zero the cache once. + // No scalar float below: this core has no scalar FPU (softfloat, slow). + alignas(64) int32 sum8[16] = {}; // per group: sum of x8 + alignas(64) uint16_t p2[16] = {}; // per group: 2^e as bf16 bits + for (int g = 0; g < GROUPS; g++) { + aie::vector xv = aie::load_v<32>(x + g * 32); + + // max |x| from the bf16 bits: clear the sign; for non-negative bf16 the + // bit pattern orders like the value. Its exponent field gives e. + aie::vector ax = aie::bit_and(xv.template cast_to(), aie::broadcast(0x7FFF)); + const int max_bits = aie::reduce_max(ax); + // m = f * 2^k, f in [1, 2): e = k - 6 puts m / 2^e in [64, 128) + // (a value that rounds to 128 saturates to 127); clamp keeps 2^+-e normal + int e = max_bits == 0 ? 0 : (max_bits >> 7) - 127 - 6; + e = e < -120 ? -120 : (e > 120 ? 120 : e); + + // x * 2^-e: exact (a power of two only moves the exponent) + union { uint16_t u; bfloat16 b; } inv; + inv.u = (uint16_t)((127 - e) << 7); + aie::accum scaled = aie::mul(xv, inv.b); + // round to the nearest integer with the fp32 "magic number": adding + // 1.5 * 2^23 leaves the integer in the low mantissa bits (fp32 add rounds + // to nearest even); |v| < 128 is far below 2^22. The bf16 -> int + // conversion is not used: it is software, slow, and rounds down. + constexpr float MAGIC = 12582912.0f; // 1.5 * 2^23, bits 0x4B400000 + scaled = aie::add(scaled, aie::broadcast(MAGIC)); + aie::vector xi = aie::sub(scaled.template to_vector().template cast_to(), + aie::broadcast(0x4B400000)); + aie::accum xi_acc; + xi_acc.from_vector(xi); + aie::vector x8 = xi_acc.template to_vector(0); // saturating (128 -> 127) + + // group g = steps 4g .. 4g+3 (8 columns each), in A row g % 4 + // (8 bytes at a time: there is no 8-lane int8 vector, so two 32-bit words) + const int row = g % 4; + alignas(32) int8 x8_mem[32]; + aie::store_v(x8_mem, x8); + AIE_LOOP_UNROLL_FULL + for (int s = 0; s < 4; s++) { + uint32_t* dst = (uint32_t*)(a_tiles + (4 * g + s) * 32 + row * 8); + const uint32_t* src = (const uint32_t*)(x8_mem + s * 8); + dst[0] = src[0]; + dst[1] = src[1]; + } + + // 2^e as bf16 (exponent field only), on group g's 16 lanes of half g / 4 + union { uint16_t u; bfloat16 b; } p2e; + p2e.u = (uint16_t)((e + 127) << 7); + aie::store_v(e64 + (g / 4) * 64 + row * 16, aie::broadcast(p2e.b)); + p2[g] = p2e.u; + + // sum of the (saturated) int8 values, for the min path + aie::accum x8_acc; + x8_acc.from_vector(x8); + sum8[g] = aie::reduce_add(x8_acc.template to_vector(0)); + } + + // min path sums of all 8 groups at once, in vector ops: sum8 * 2^e as two bf16 + // limbs (hi, lo). |sum8| <= 32 * 127 needs 12 bits, so the limbs hold it + // exactly, and times a power of two they stay exact. + aie::vector sf = aie::to_float(aie::load_v<16>(sum8), 0); + auto [l0, l1] = bf16_limb::split_f32<16>(sf); + aie::vector p2v = aie::load_v<16>((bf16*)p2); + aie::vector hi = aie::mul(l0, p2v).template to_vector(); + aie::vector lo = aie::mul(l1, p2v).template to_vector(); + aie::store_v(reduce_out, aie::interleave_zip(hi, lo, 1).first); // hi0 lo0 hi1 lo1 ... +} + +// One step of 8 columns: A from the cache, B = the (step % 2) half of the 128 B +// tile of 16-column step step / 2, half t = 0 / 1 (uint4 pointers step one byte). +#define Q4K_STEP_OPERANDS(step) \ + aie::vector a = aie::concat(aie::load_v<32>(a_tiles + (step) * 32), \ + aie::zeros()); \ + const uint4* tile = q + ((step) / 2) * 256 + ((step) % 2) * 64; \ + v128int8 b0 = (v128int8)::unpack((v128uint4)aie::load_v<128>(tile), 0); \ + v128int8 b1 = (v128int8)::unpack((v128uint4)aie::load_v<128>(tile + 128), 0); + +/// @brief The group sums of groups 4H .. 4H+3 (steps 16H .. 16H+15) for both row +/// halves: acc_t0 rows 0..15, acc_t1 rows 16..31; row a of C = group 4H + a. +/// Not inlined, loop not unrolled: one big basic block made the scheduler give up. +template +__attribute__((noinline)) void q4k_group_sums(aie::accum& acc_t0, aie::accum& acc_t1, + const int8* a_tiles, const uint4* q) +{ + v64acc32 c0, c1; + { // first step: mul (A signed = 1, B unsigned = 0) + Q4K_STEP_OPERANDS(16 * H) + c0 = ::mul_4x8_8x16(a, 1, b0, 0); + c1 = ::mul_4x8_8x16(a, 1, b1, 0); + } + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_NO_UNROLL + for (int s = 1; s < 16; s++) { + Q4K_STEP_OPERANDS(16 * H + s) + c0 = ::mac_4x8_8x16(a, 1, b0, 0, c0); + c1 = ::mac_4x8_8x16(a, 1, b1, 0, c1); + } + acc_t0 = aie::accum(c0); + acc_t1 = aie::accum(c1); +} + +/// @brief Scale path of one row half t: sum over the 8 groups of s'_g 2^e_g G_g +/// for its 16 rows (fp32). acc_h0 / acc_h1: the group sums of groups 0..3 / 4..7. +__attribute__((noinline)) aie::vector q4k_scale_rows( + const aie::accum& acc_h0, const aie::accum& acc_h1, + const uint8* scales_t0h0, const uint8* scales_t0h1, const bf16* e64) +{ + aie::accum s64; + s64.from_vector(aie::zeros()); + const aie::accum* accs[2] = {&acc_h0, &acc_h1}; + const uint8* scales[2] = {scales_t0h0, scales_t0h1}; + AIE_LOOP_NO_UNROLL + for (int h = 0; h < 2; h++) { + // int32 sums are exact; to_float is exact below 2^24 (|G| <= 32*15*128) + aie::vector g = aie::to_float(accs[h]->template to_vector(0), 0); + // s' (uint8) * 2^e (power of two) is exact in bf16 + aie::accum s_acc; + s_acc.from_vector(aie::to_float(aie::load_v<64>(scales[h]), 0)); + aie::accum sd_acc = aie::mul(s_acc.template to_vector(), aie::load_v<64>(e64 + h * 64)); + s64 = bf16_limb::mac_f32_bf16_low(s64, g, sd_acc.template to_vector()); + } + // lanes are (group a, row n): add the 4 groups -> 16 rows + aie::vector v = s64.template to_vector(); + aie::accum v32; + v32.from_vector(v.template extract<32>(0)); + v32 = aie::add(v32, v.template extract<32>(1)); + aie::vector w32 = v32.template to_vector(); + aie::accum v16; + v16.from_vector(w32.template extract<16>(0)); + v16 = aie::add(v16, w32.template extract<16>(1)); + return v16.template to_vector(); +} + +/// @brief Min path of one block: sum over groups of m'_g * (sum of x_g), then +/// times M', into c_accum_m. As _Q4K_x_bf16's. +__attribute__((noinline)) void q4k_min_path(q4k_accum_t& c_accum_m, q4k_block_t* w_buffer, const bf16* reduce) +{ + aie::accum acc_m; + acc_m.from_vector(aie::zeros()); + const uint8* it_min = w_buffer->mins; + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE, QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE) + for (int g = 0; g < QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE; g++) { + aie::accum m_acc; + m_acc.from_vector(aie::to_float(aie::load_v(it_min), 0)); + aie::vector a_mins = m_acc.template to_vector(); + acc_m = aie::mac(acc_m, a_mins, reduce[2 * g + 1]); + acc_m = aie::mac(acc_m, a_mins, reduce[2 * g]); + it_min += PARALLEL_ROWS; + } + aie::vector a_M = aie::load_v(w_buffer->M); + c_accum_m = bf16_limb::mac_f32_bf16_low(c_accum_m, acc_m.template to_vector(), a_M); +} + +/// @brief y += W x for one Q4_K block, as _Q4K_x_bf16, with x given as the +/// A matrices and group scales of q4k_prepare_x. +void _Q4K_x_int8( + q4k_accum_t & c_accum_s, + q4k_accum_t & c_accum_m, + const int8* a_tiles, + const bf16* e64, + q4k_block_t* w_buffer, + bf16* b_col_reduce_buffer +) { + static_assert(PARALLEL_ROWS == 32 && QXNX_COL_BLOCK_SIZE == 256); + const uint4* q = w_buffer->qs; + + // ---- group sums: acc[t][h], row a = group 4 h + a, 16 output rows each ---- + aie::accum acc[2][2]; + q4k_group_sums<0>(acc[0][0], acc[1][0], a_tiles, q); + q4k_group_sums<1>(acc[0][1], acc[1][1], a_tiles, q); + + // ---- scale path: per row sum_g s'_g 2^e_g G_g, then times S' ---- + // scales layout [h][t][a][16 rows]: (h, t) at (h * 2 + t) * 64 + aie::vector row_sums; + row_sums.insert(0, q4k_scale_rows(acc[0][0], acc[0][1], w_buffer->scales + 0 * 64, w_buffer->scales + 2 * 64, e64)); + row_sums.insert(1, q4k_scale_rows(acc[1][0], acc[1][1], w_buffer->scales + 1 * 64, w_buffer->scales + 3 * 64, e64)); + aie::vector a_S = aie::load_v(w_buffer->S); + c_accum_s = bf16_limb::mac_f32_bf16_low(c_accum_s, row_sums, a_S); + + // ---- min path ---- + q4k_min_path(c_accum_m, w_buffer, b_col_reduce_buffer); +} + +/// @brief Zero the accumulator pair, once per output row block. +void _Q4K_zero( + q4k_accum_t & c_accum_s, + q4k_accum_t & c_accum_m +) { + c_accum_s.from_vector(aie::zeros()); + c_accum_m.from_vector(aie::zeros()); +} + +/// @brief Collapse the accumulator pair of _Q4K_x_bf16 into the final result. +/// +/// Call once, after the whole K loop: the scale path and the min path have each +/// been summed over every block of the row, and the single combining add +/// c = scale + min happens here, in the accumulator domain. +/// +/// @param c float32 result, PARALLEL_ROWS wide +void _Q4K_finalize( + float * c, + const q4k_accum_t & c_accum_s, + const q4k_accum_t & c_accum_m +) { + q4k_accum_t c_accum = aie::add(c_accum_s, c_accum_m); + aie::store_v(c, c_accum.template to_vector()); +} + +#endif // __Q4_CORE_H__ \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/q8_core.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/q8_core.h new file mode 100644 index 000000000..e6932a9ce --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/q8_core.h @@ -0,0 +1,81 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __Q8_CORE_H__ +#define __Q8_CORE_H__ +#include "aie_kernel_utils.h" +#include "model_spec.h" +#include "aie_array_layout.h" +#include "bf16_limb_math.hpp" + +/// @brief y += W x for one Q8_0 weight block, x bf16 / y float32. +/// +/// "Reduce first, scale after": a whole 32-value group is reduced against x in +/// one float32 accumulator and only then meets the group's bf16 scale. Every +/// multiplier operand is bf16-exact -- q is an int8 (bf16 holds every integer up +/// to 256) and the scale is *stored* bf16 -- so the group accumulator is the one +/// place a rounding could creep in, and the limb split below keeps it out. +void _Q80_x_bf16( + float * c, + bf16 * x, + q80_block_t* w_buffer +) { + // The whole row span of the block is resident at once, so there is no row + // loop: one pass over the column groups, one scale entry per group. + static constexpr int num_groups_per_row = QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE; + + static_assert(PARALLEL_ROWS == QXNX_ROW_BLOCK_SIZE); + + int8_t* it_q = w_buffer->qs; + bf16* it_scale = w_buffer->scales; + bf16* it_x = x; + + aie::accum c_accum; + c_accum.from_vector(aie::load_v(c)); + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE( num_groups_per_row, num_groups_per_row ) + for (int group = 0; group < num_groups_per_row; group++) { + aie::vector a_scales = aie::load_v(it_scale); + + // inlined Q8_core + aie::vector vec_col = aie::load_v(it_x); + aie::accum temp_acc; + temp_acc.from_vector(aie::broadcast(bf16(0.0f))); + + // Unrolled by 4 to amortize the per-iteration load and int8->bf16 + // conversion overhead, which dominates this loop rather than the + // accumulator dependency. + static constexpr int T_UNROLL = 4; + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE( GGML_GROUP_SIZE, GGML_GROUP_SIZE ) + AIE_LOOP_UNROLL( T_UNROLL ) + for(int t = 0; t < GGML_GROUP_SIZE; t++ ) { + aie::vector a_cc_0 = aie::load_v(it_q); + it_q += PARALLEL_ROWS; + + aie::vector a_col_float = aie::to_float(a_cc_0, 0); + // convert to bfloat16 + aie::accum a_col_accum; + a_col_accum.from_vector(a_col_float); + + aie::vector a_col_bf16 = a_col_accum.template to_vector(); + + temp_acc = aie::mac(temp_acc, a_col_bf16, vec_col.get(t)); + } + + // a_scales is bf16-exact, so the only rounding this MAC could introduce + // is on temp_acc. A plain to_vector() would throw away 16 of the + // group sum's 24 mantissa bits, once per group and per block, and those + // errors add up over the whole K loop. Split the accumulator into two + // bf16 limbs instead: ~17 mantissa bits rather than 8, for 1 extra MAC + // per group against the 32 of the inner loop above. + c_accum = bf16_limb::mac_f32_bf16_low( + c_accum, temp_acc.template to_vector(), a_scales); + it_x += GGML_GROUP_SIZE; + it_scale += PARALLEL_ROWS; + } + + aie::vector c_accum_f32 = c_accum.template to_vector(); + aie::store_v(c, c_accum_f32); +} +#endif // __Q8_CORE_H__ diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/rms_residual.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/rms_residual.cc new file mode 100644 index 000000000..97bbd33d4 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/rms_residual.cc @@ -0,0 +1,195 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "aie_array_layout.h" +#include "aie_kernel_utils.h" +#include "typedef.hpp" + +#include "passThroughCommon.hpp" + + +///@brief rms norm: y = nrom(x) * w; +///@param y: output +///@param x: input +///@param w: weight +void rms_norm( + bf16 *restrict y, + const bf16 *restrict x, + const bf16 *restrict w +){ + const float epsilon = RMS_EPS; + + constexpr int vector_size = 16; + constexpr float one_over_D = 1.0f / (float)MODEL_DIM; + + bf16 *it_y_0 = const_cast(y); + bf16 *it_y_1 = const_cast(y) + vector_size; + bf16 *it_x_0 = const_cast(x); + bf16 *it_x_1 = const_cast(x) + vector_size; + bf16 *it_w_0 = const_cast(w); + bf16 *it_w_1 = const_cast(w) + vector_size; + + aie::accum sum_squares_0 = aie::zeros(); + aie::accum sum_squares_1 = aie::zeros(); + aie::vector mx_vec; + + const int F = MODEL_DIM / (2 * vector_size); + for (int i = 0; i < F; i++){ + auto x_vec_0 = aie::load_v(it_x_0); + auto x_vec_1 = aie::load_v(it_x_1); + sum_squares_0 = aie::mac_square(sum_squares_0, x_vec_0); + sum_squares_1 = aie::mac_square(sum_squares_1, x_vec_1); + it_x_0 += 2 * vector_size; + it_x_1 += 2 * vector_size; + } + + it_x_0 = const_cast(x); + it_x_1 = const_cast(x) + vector_size; + + mx_vec = aie::add(sum_squares_0.template to_vector(), + sum_squares_1.template to_vector()); + float sum = aie::reduce_add(mx_vec); + sum = AIE_FADD(AIE_FMUL(sum, one_over_D), epsilon); + aie::vector sum_vec = aie::broadcast(sum); + float divrms = aie::invsqrt(sum_vec)[0]; + + for (int i = 0; i < F; i++){ + aie::vector x_vec_0 = aie::load_v(it_x_0); + aie::vector x_vec_1 = aie::load_v(it_x_1); + aie::vector w_vec_0 = aie::load_v(it_w_0); + aie::vector w_vec_1 = aie::load_v(it_w_1); + aie::vector wx_vec_0 = aie::mul(x_vec_0, w_vec_0); + aie::vector wx_vec_1 = aie::mul(x_vec_1, w_vec_1); + aie::vector o_vec_0 = aie::mul(wx_vec_0, divrms); + aie::vector o_vec_1 = aie::mul(wx_vec_1, divrms); + aie::store_v(it_y_0, o_vec_0); + aie::store_v(it_y_1, o_vec_1); + it_x_0 += 2 * vector_size; + it_x_1 += 2 * vector_size; + it_y_0 += 2 * vector_size; + it_y_1 += 2 * vector_size; + it_w_0 += 2 * vector_size; + it_w_1 += 2 * vector_size; + } + event1(); +} + + +///@brief residual add: y = x + x_buf, and x_buf = y +///@param y: output +///@param x: input +///@param x_buf: copy of x +void residual_add( + bf16 *restrict y, + const bf16 *restrict x_buf, + const bf16 *restrict x +){ + constexpr int vector_size = 16; + bf16 *it_x_0 = const_cast(x); + bf16 *it_x_1 = const_cast(x) + vector_size; + bf16 *it_y_0 = const_cast(y); + bf16 *it_y_1 = const_cast(y) + vector_size; + bf16 *it_x_buf_0 = const_cast(x_buf); + bf16 *it_x_buf_1 = const_cast(x_buf) + vector_size; + + for (int i = 0; i < MODEL_DIM / (2 * vector_size); i++) { + aie::vector x_vec_0 = aie::load_v(it_x_0); + aie::vector x_vec_1 = aie::load_v(it_x_1); + aie::vector x_buf_vec_0 = aie::load_v(it_x_buf_0); + aie::vector x_buf_vec_1 = aie::load_v(it_x_buf_1); + auto out_vec_0 = aie::add(x_vec_0, x_buf_vec_0); + auto out_vec_1 = aie::add(x_vec_1, x_buf_vec_1); + aie::store_v(it_y_0, out_vec_0); + aie::store_v(it_y_1, out_vec_1); + aie::store_v(it_x_buf_0, out_vec_0); + aie::store_v(it_x_buf_1, out_vec_1); + it_x_0 += 2 * vector_size; + it_x_1 += 2 * vector_size; + it_y_0 += 2 * vector_size; + it_y_1 += 2 * vector_size; + it_x_buf_0 += 2 * vector_size; + it_x_buf_1 += 2 * vector_size; + } +} + + +extern "C" { + +// One decoder layer per call. y is the outgoing packet buffer: y + 14 holds the +// packet id, y + 16 the data, so every send below first picks a destination. +void rms_residual( + bf16 * AIE_DMA_RESTRICT y, + bf16 * AIE_DMA_RESTRICT x_ping, + bf16 * AIE_DMA_RESTRICT x_pong, + bf16 * AIE_DMA_RESTRICT w, + bf16 * AIE_DMA_RESTRICT x_buf +){ + constexpr int w_prod_lock = 0; + constexpr int w_cons_lock = 1; + constexpr int y_prod_lock = 2; + constexpr int y_cons_lock = 3; + constexpr int x_prod_lock = 4; + constexpr int x_cons_lock = 5; + uint32_t* pkt_id_ptr = reinterpret_cast(y + 14); + bf16* x; + + AIE_PERSIST_ZERO static bool is_x_ping = false; + + bf16* w_input_norm = w; + bf16* w_post_attention_norm = w_input_norm + MODEL_DIM; + + // 1. layer input: keep a copy for the residual, send input_layernorm(x) + // to the proj engine once per q/k/v and output-gate row-block round. + _lock_acquire(x_cons_lock); + _lock_acquire(w_cons_lock); + *pkt_id_ptr = pkt_id_rms_to_proj; + is_x_ping = !is_x_ping; + x = is_x_ping ? x_ping : x_pong; + _memcpy((uint8*)x_buf, (uint8*)x); + rms_norm(y + 16, x_buf, w_input_norm); + _lock_release(x_prod_lock); + _lock_release(y_cons_lock, QKV_REPEATS + GATE_REPEATS); + + // 2. o_proj result: residual add, then post_attention_layernorm. + _lock_acquire(x_cons_lock); + _lock_acquire(y_prod_lock, QKV_REPEATS + GATE_REPEATS); + is_x_ping = !is_x_ping; + x = is_x_ping ? x_ping : x_pong; + residual_add(x_buf, x_buf, x); + rms_norm(y + 16, x_buf, w_post_attention_norm); + _lock_release(x_prod_lock); + + // 3. send the normed x to GLU (the router reads it from there) ... + *pkt_id_ptr = pkt_id_rms_to_glu; + _lock_release(y_cons_lock, 1); + _lock_acquire(y_prod_lock, 1); + + // ... and to the proj engine for the shared expert's up/gate. + *pkt_id_ptr = pkt_id_rms_to_proj; + _lock_release(y_cons_lock, UP_GATE_REPEATS); + + // 4. shared expert down result: pass it on to GLU, which adds the routed + // experts to it. + _lock_acquire(x_cons_lock); + _lock_acquire(y_prod_lock, UP_GATE_REPEATS); + *pkt_id_ptr = pkt_id_rms_to_glu; + is_x_ping = !is_x_ping; + x = is_x_ping ? x_ping : x_pong; + copy_bf16_to_bf16(y + 16, x); + _lock_release(w_prod_lock); + _lock_release(x_prod_lock); + _lock_release(y_cons_lock, 1); + + // 5. MoE output from GLU: final residual add, send the layer output out. + _lock_acquire(x_cons_lock); + _lock_acquire(y_prod_lock, 1); + *pkt_id_ptr = pkt_id_rms_to_it; + is_x_ping = !is_x_ping; + x = is_x_ping ? x_ping : x_pong; + residual_add(y + 16, x_buf, x); + _lock_release(x_prod_lock); + _lock_release(y_cons_lock, 1); + _lock_acquire(y_prod_lock, 1); +} + +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/rope.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/rope.cc new file mode 100644 index 000000000..fd161fb9b --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/rope.cc @@ -0,0 +1,246 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +#include "aie_array_layout.h" +#include "aie_kernel_utils.h" +#include "typedef.hpp" +#include "flm_rsqrt.h" + +#ifdef HAS_QK_NORM +///@brief pseduo rms norm: y = x * w +///@param y: output +///@param x_buf: copy of x +///@param x: input +///@param w: weight +///@param overwrite_x_buf: if true, overwrite x_buf with x +void qk_norm( + const bf16 *restrict x, + const bf16 *restrict w +){ + const float epsilon = RMS_EPS; + + constexpr int vector_size = 16; + constexpr float one_over_D = 1.0f / (float)DH; + + bf16 *it_x_0 = const_cast(x); + bf16 *it_x_1 = const_cast(x) + vector_size; + bf16 *it_w_0 = const_cast(w); + bf16 *it_w_1 = const_cast(w) + vector_size; + + aie::accum sum_squares_0 = aie::zeros(); + aie::accum sum_squares_1 = aie::zeros(); + aie::vector mx_vec; + + constexpr int F = DH / (2 * vector_size); + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(F, F) + for (int i = 0; i < F; i++) { + auto x_vec_0 = aie::load_v(it_x_0); + auto x_vec_1 = aie::load_v(it_x_1); + sum_squares_0 = aie::mac_square(sum_squares_0, x_vec_0); + sum_squares_1 = aie::mac_square(sum_squares_1, x_vec_1); + it_x_0 += 2 * vector_size; + it_x_1 += 2 * vector_size; + } + + it_x_0 = const_cast(x); + it_x_1 = const_cast(x) + vector_size; + + mx_vec = aie::add(sum_squares_0.template to_vector(), + sum_squares_1.template to_vector()); + float sum = aie::reduce_add(mx_vec); + sum = AIE_FMUL(sum, one_over_D); + sum = AIE_FADD(sum, epsilon); + const float divrms = flm_rsqrt(sum); + + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(F, F) + for (int i = 0; i < F; i++) { + aie::vector x_vec_0 = aie::load_v(it_x_0); + aie::vector x_vec_1 = aie::load_v(it_x_1); + aie::vector w_vec_0 = aie::load_v(it_w_0); + aie::vector w_vec_1 = aie::load_v(it_w_1); + aie::vector wx_vec_0 = aie::mul(x_vec_0, w_vec_0); + aie::vector wx_vec_1 = aie::mul(x_vec_1, w_vec_1); + aie::vector o_vec_0 = aie::mul(wx_vec_0, divrms); + aie::vector o_vec_1 = aie::mul(wx_vec_1, divrms); + aie::store_v(it_x_0, o_vec_0); + aie::store_v(it_x_1, o_vec_1); + it_x_0 += 2 * vector_size; + it_x_1 += 2 * vector_size; + it_w_0 += 2 * vector_size; + it_w_1 += 2 * vector_size; + } +} +#endif + +void apply_rope( + bf16 *restrict y, + bf16 *restrict x, + bf16 *restrict cos_val, + bf16 *restrict sin_val +) { + constexpr int vector_size = 16; + const int DH_2 = ROPE_DIM / 2; + constexpr int F = DH_2 / vector_size; + constexpr int remaining_F = (ROPE_BY_PASS) / vector_size; + bf16 *it_y_p1 = y; + bf16 *it_y_p2 = y + DH_2; + bf16 *it_x_p1 = x; + bf16 *it_x_p2 = x + DH_2; + bf16 *it_cos = cos_val; + bf16 *it_sin = sin_val; + // |x_p1 |x_p2 |Bypass | + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(F, F) + for (int i = 0; i < F; i++) { + aie::vector x1_vec = aie::load_v(it_x_p1); + aie::vector x2_vec = aie::load_v(it_x_p2); + aie::vector cos_vec = aie::load_v(it_cos); + aie::vector sin_vec = aie::load_v(it_sin); + aie::vector neg_sin_vec = aie::neg(sin_vec); + aie::accum C = aie::mul(x1_vec, cos_vec); + C = aie::mac(C, x2_vec, neg_sin_vec); + aie::accum D = aie::mul(x1_vec, sin_vec); + D = aie::mac(D, x2_vec, cos_vec); + aie::store_v(it_y_p1, C.template to_vector()); + aie::store_v(it_y_p2, D.template to_vector()); + it_y_p1 += vector_size; + it_y_p2 += vector_size; + it_x_p1 += vector_size; + it_x_p2 += vector_size; + it_cos += vector_size; + it_sin += vector_size; + } + // bypass the part of the head RoPE does not touch; with full RoPE + // (ROPE_DIM == DH) there is none, so the loop must not exist at all + if constexpr (remaining_F > 0) { + AIE_PREPARE_FOR_PIPELINING AIE_LOOP_RANGE(remaining_F > 0 ? remaining_F : 1, remaining_F > 0 ? remaining_F : 1) + for (int i = 0; i < remaining_F; i++) { + aie::vector x2_vec = aie::load_v(it_x_p2); + aie::store_v(it_y_p2, x2_vec); + it_y_p2 += vector_size; + it_x_p2 += vector_size; + } + } +} +///@brief pseduo RoPE: q = q, k = k + 1, v = v - 1 +///@param y: output +///@param x: input +///@param w: weight +///@note: C = A cos - B sin, D = A sin + B cos +void pseduo_rope_kv( + bf16 *restrict k, + bf16 *restrict v, + bf16 * restrict qkv, + bf16 * restrict rope_w +) { + bf16 *it_k = k; + bf16 *it_v = v; + bf16 *it_qkv = qkv; + bf16 *it_rope = rope_w; + #ifdef HAS_QK_NORM + bf16 *q_norm_weight = rope_w + ROPE_DIM; + bf16 *k_norm_weight = rope_w + ROPE_DIM + DH; + #endif + const int DH_2 = ROPE_DIM / 2; + + bf16* cos_val = it_rope; + bf16* sin_val = it_rope + ROPE_DIM / 2; + + for (int h = 0; h < NUM_KV_HEADS; h++){ + #ifdef HAS_QK_NORM + qk_norm(it_qkv, k_norm_weight); + #endif + apply_rope(it_k, it_qkv, cos_val, sin_val); + it_k += DH; + it_qkv += DH; + } + + // move v from qkv to v, N + for (int i = 0; i < DV / 32; i++) { + aie::vector v_vec = aie::load_v<32>(it_qkv); + aie::store_v(it_v, v_vec); + it_v += 32; + it_qkv += 32; + } +} + +///@brief pseduo RoPE: q = q, k = k + 1, v = v - 1 +///@param y: output +///@param x: input +///@param w: weight +///@note: C = A cos - B sin, D = A sin + B cos +void pseduo_rope_q( + bf16 *restrict q, + bf16 * restrict qkv, + bf16 * restrict rope_w +) { + bf16 *it_q = q; + bf16 *it_qkv = qkv; + bf16 *it_rope = rope_w; + #ifdef HAS_QK_NORM + bf16 *q_norm_weight = rope_w + ROPE_DIM; + bf16 *k_norm_weight = rope_w + ROPE_DIM + DH; + #endif + const int DH_2 = ROPE_DIM / 2; + + bf16* cos_val = it_rope; + bf16* sin_val = it_rope + ROPE_DIM / 2; + + for (int h = 0; h < NUM_KV_HEADS; h++){ + for (int g = 0; g < Q_HEADS_PER_GROUP; g++){ + #ifdef HAS_QK_NORM + qk_norm(it_qkv, q_norm_weight); + #endif + apply_rope(it_q, it_qkv, cos_val, sin_val); + it_q += DH; + it_qkv += DH; + } + #if ATTN_GROUPS_PADDING > 0 + aie::vector zero = aie::zeros(); + for (int i = 0; i < ATTN_GROUPS_PADDING; i++){ + aie::store_v(it_q, zero); + it_q += DH_2; + aie::store_v(it_q, zero); + it_q += DH_2; + } + #endif + } +} + +extern "C" { + +void rope( + bf16* AIE_DMA_RESTRICT q, + bf16* AIE_DMA_RESTRICT k, + bf16* AIE_DMA_RESTRICT v, + bf16* AIE_DMA_RESTRICT q_in, + bf16* AIE_DMA_RESTRICT kv_in, + bf16* AIE_DMA_RESTRICT rope_w +) +{ + constexpr int qkv_prod_lock = 0; + constexpr int qkv_cons_lock = 1; + constexpr int q_prod_lock = 2; + constexpr int q_cons_lock = 3; + constexpr int k_prod_lock = 4; + constexpr int k_cons_lock = 5; + constexpr int v_prod_lock = 6; + constexpr int v_cons_lock = 7; + constexpr int rope_prod_lock = 8; + constexpr int rope_cons_lock = 9; + _lock_acquire(qkv_cons_lock); + _lock_acquire(rope_cons_lock); + _lock_acquire(k_prod_lock, 1); + _lock_acquire(v_prod_lock, 1); + pseduo_rope_kv(k, v, kv_in, rope_w); + _lock_release(qkv_prod_lock); + _lock_release(v_cons_lock, 1); + _lock_release(k_cons_lock, 1); + + _lock_acquire(qkv_cons_lock); + _lock_acquire(q_prod_lock); + pseduo_rope_q(q, q_in, rope_w); + _lock_release(q_cons_lock); + _lock_release(qkv_prod_lock); + _lock_release(rope_prod_lock); +} + + +} \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router.cc new file mode 100644 index 000000000..33bd2903a --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router.cc @@ -0,0 +1,276 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "aie_array_layout.h" +#include "aie_kernel_utils.h" +#include "typedef.hpp" +#include "mvm_col_major.hpp" +#include "zero.h" +#include "nonLinearFunction.h" +#include "sort.hpp" +#include "common_external.hpp" +#include "packet_control_gen.hpp" +#include "router_math.hpp" +#include "router_block.hpp" + +void get_SHM_bd_virtual_address( + // TODO: improve this, right now assume the lock is being added +48 already + uint32_t * SHIM_BD_VIRTUAL_ptr, + uint32_t * control_packet_out_buf, uint32_t* control_packet_in_buf, + const uint32_t control_packet_out_prod_lock_id, const uint32_t control_packet_out_con_lock_id, + const uint32_t control_packet_in_prod_lock_id, const uint32_t control_packet_in_con_lock_id, + + // configure of this CT, aka bd_id and port of this CT + const uint32_t CT_to_shimtile_control_bd_id, const uint32_t CT_from_shimtile_control_bd_id, + const uint32_t CT_to_shimtile_control_bd_port, const uint32_t CT_from_shimtile_control_bd_port, + + // related to packet_flow routing + const uint32_t SHIM_control_packet_id, const uint32_t SHIM_0_control_response_id, + + const uint32_t SHM_MM2S_channel_idx, // 0 or 1 + const uint32_t SHM_bd_id + +){ + + // first, get the virtual base address in BD_id0 + + //configure dmab_bd_id to send only the + // control_packet_header read + + configure_BD_x_MM2S_y_dma_bd_len( + CT_to_shimtile_control_bd_id, + CT_to_shimtile_control_bd_port, 2, 0); // packet-flow header + control packet + + // Shim control reads return one register value per response packet. Keep + // the established one-word response DMA and read X1 and X2 sequentially. + for (AIE_LOCK_LOOP_CTR word = 0; word < 2; ++word) { + acquire_greater_equal(control_packet_out_prod_lock_id, 1); + *control_packet_out_buf = packet_flow_gen( + 0, // 0 since is from CT? + SHIM_control_packet_id + ); + *(control_packet_out_buf + 1) = control_packet_gen( + SHIM_0_control_response_id, 1, 0, + get_SHM_bd_x_0_address(SHM_bd_id) + 0x4 + word * 0x4 + ); + release(control_packet_out_con_lock_id, 1); + + acquire_greater_equal(control_packet_in_con_lock_id, 1); + SHIM_BD_VIRTUAL_ptr[word] = *control_packet_in_buf; + release(control_packet_in_prod_lock_id, 1); + } +} + +template +void retrieveData( + + // TODO: improve this, right now assume the lock is being added +48 already + uint32_t * control_packet_out_buf, uint32_t* control_packet_in_buf, + const uint32_t control_packet_out_prod_lock_id, const uint32_t control_packet_out_con_lock_id, + const uint32_t control_packet_in_prod_lock_id, const uint32_t control_packet_in_con_lock_id, + + // configure of this CT, aka bd_id and port of this CT + const uint32_t CT_to_shimtile_control_bd_id, const uint32_t CT_from_shimtile_control_bd_id, + const uint32_t CT_to_shimtile_control_bd_port, const uint32_t CT_from_shimtile_control_bd_port, + + // related to packet_flow routing + const uint32_t SHIM_control_packet_id, + + const uint32_t SHM_MM2S_channel_idx, // 0 or 1 + const uint32_t SHM_bd_id, + + const uint32_t shim_bd_id_1_val, + const uint32_t shim_bd_id_2_val, + const uint32_t buffer_fetch_size_in_byte, const uint32_t address_offset_in_byte +){ + control_Shimtile_transfer_with_packetflow_gen( + shim_bd_id_1_val, shim_bd_id_2_val, + buffer_fetch_size_in_byte/4, address_offset_in_byte, // div 4 due to 4 byte granduality + + control_packet_out_prod_lock_id, control_packet_out_con_lock_id, + control_packet_out_buf, + + CT_to_shimtile_control_bd_id, CT_to_shimtile_control_bd_port, + SHIM_control_packet_id, + + SHM_MM2S_channel_idx, SHM_bd_id + ); +} + +extern "C" { + //TODO: have this from function parameter + // this is from glu (CT above it) + constexpr int x_in_prod_lock = 6; + constexpr int x_in_con_lock = 7; + constexpr int glu_request_router_send_lock = 12; + + + constexpr int router_weight_prod_lock = 2; + constexpr int router_weight_con_lock = 3; + constexpr int shimtile_configure_ready_lock = 10; // expert BDs written, safe to push expert tasks + + // handshake with the router helper (the tile below), both locks in this tile: + // x copied, the helper may start / the helper's 96 logits are in local_top_k_score_vector + constexpr int router_helper_x_ready_lock = 13; + constexpr int router_helper_finished_lock = 14; + void router( + bf16* AIE_DMA_RESTRICT top_x_in, + + bf16* AIE_DMA_RESTRICT x_in, // a copy of top_x_in + + bfloat16* AIE_DMA_RESTRICT router_w_block_ping, + bfloat16* AIE_DMA_RESTRICT router_w_block_pong, + + float* _top_k_score_vector, float* local_top_k_score_vector, + + int32_t* top_k_exp_index_vector, + float * share_expert_output, + + + uint32_t *SHIM_BD_1_VIRTUAL_ptr, + // control packet related + uint32_t * control_packet_out_buf, uint32_t* control_packet_in_buf, + const uint32_t control_packet_out_prod_lock_id, const uint32_t control_packet_out_con_lock_id, + const uint32_t control_packet_in_prod_lock_id, const uint32_t control_packet_in_con_lock_id, + + // configure of this CT, aka bd_id and port of this CT + const uint32_t CT_to_shimtile_control_bd_id, const uint32_t CT_from_shimtile_control_bd_id, + const uint32_t CT_to_shimtile_control_bd_port, const uint32_t CT_from_shimtile_control_bd_port, + int *router_weight_ping_pong_flag, + const float* expert_bias, // NUM_EXPERTS fp32, an RTP buffer the host writes each call + const int32_t* layer_rtp // [0]: which layer this call is (0 .. MAX_LAYERS-1), RTP + + ){ + + + static uint32_t SHIM_x_control_packet_id_list[4] = {SHIM_0_CONTROL_PKT, SHIM_1_CONTROL_PKT, SHIM_6_CONTROL_PKT, SHIM_7_CONTROL_PKT}; + static uint32_t SHIM_x_control_respose_id_list[1] = { SHIM_6_CONTROL_RES_PKT}; + + + + zero_vectorized_512( + local_top_k_score_vector + ); + + _up_lock_acquire(x_in_con_lock); + copy_bf16_to_bf16( + x_in, top_x_in + ); + _up_lock_release(x_in_prod_lock); + // the helper may start on experts 64..159 (its own weight streams) + _lock_release(router_helper_x_ready_lock); + + // experts 0..63, MT5 half 0 (IT5 channel 0) + for(AIE_LOCK_LOOP_CTR i = 0; i < 64; i+= router_weight_row_block ){ + float* res_ptr = local_top_k_score_vector + i; + + for(AIE_LOCK_LOOP_CTR j = 0; j < MODEL_DIM; j+= router_weight_col_block ){ + _lock_acquire(router_weight_con_lock); + bfloat16* block = *router_weight_ping_pong_flag == 0 ? router_w_block_ping : router_w_block_pong; + router_block_matvec(block, x_in + j, res_ptr); + _lock_release(router_weight_prod_lock); + *router_weight_ping_pong_flag = 1 - *router_weight_ping_pong_flag; + } + } + + // the helper's experts 64..159 are in too + _lock_acquire(router_helper_finished_lock); + + + + // MiniCPM5 routing, all fp32 (see router_math.hpp): sigmoid scores, top 16 of + // score + bias, weights = score / sum * ROUTER_SCALING. The weights go + // straight into the GLU's buffer (the tile above). A dense layer (see + // FIRST_K_DENSE) takes its 16 MLP slices, experts 0..15, each with weight 1. + const int layer = layer_rtp[0]; + if (layer < FIRST_K_DENSE) { + for (int k = 0; k < NUM_ACT_EXPERTS; k++) { + top_k_exp_index_vector[k] = k; + _top_k_score_vector[k] = 1.0f; + } + } + else { + router_math::route_sigmoid_topk( + _top_k_score_vector, + top_k_exp_index_vector, + local_top_k_score_vector, + expert_bias, + ROUTER_SCALING + ); + } + + + + // The host sets this after writing this call's expert BDs and pushing its + // last shared-expert weight task on shims 0, 1, 6, 7 (expert tasks pushed + // earlier would queue in front of them). Reading the base address before + // this, while the shared expert streamed (MoE step 2, T3), hung every call. + _lock_acquire(shimtile_configure_ready_lock); + + // The weight buffer's device address, read from the BD the host points at + // expert 0. Each layer has its own weight buffer, so one saved address per + // layer: read on the first call of that layer, reused afterwards (this core + // keeps running between calls, so the table survives; XRT buffers do not move). + static uint32_t base_table[MAX_LAYERS][2]; + AIE_PERSIST_ZERO static bool base_known[MAX_LAYERS] = {}; + if (!base_known[layer]) { + get_SHM_bd_virtual_address( + base_table[layer], + control_packet_out_buf, control_packet_in_buf, + control_packet_out_prod_lock_id, control_packet_out_con_lock_id, + control_packet_in_prod_lock_id, control_packet_in_con_lock_id, + CT_to_shimtile_control_bd_id, CT_from_shimtile_control_bd_id, + CT_to_shimtile_control_bd_port, CT_from_shimtile_control_bd_port, + SHIM_6_CONTROL_PKT, SHIM_6_CONTROL_RES_PKT, // BIG assume, all MVM shm share same bo buffer + 0, SHIM_X_expert_BD_ID + ); + base_known[layer] = true; + } + SHIM_BD_1_VIRTUAL_ptr[0] = base_table[layer][0]; + SHIM_BD_1_VIRTUAL_ptr[1] = base_table[layer][1]; + + // Each round: point one BD per channel of shim 0, 1, 6, 7 at one chosen + // expert each (one expert per proj column). The host stores every expert + // as [channel 0 stream | channel 1 stream], each stream its gate/up blocks + // then its down blocks in read order, so one linear BD per channel covers + // the expert (8 BD patches per round). + // + // 4 rounds, 2 BD sets (even rounds SHIM_X_expert_BD_ID, odd rounds + // Round_2_SHIM_X_expert_BD_ID), so each channel queues at most 2 expert + // tasks: rounds 0 and 1 at the GLU's first request, and round r + 1 at + // request r. The GLU asks for round r after all of round r - 1's down + // outputs, so round r - 1's BDs, which round r + 1 reuses, are done. + constexpr int rounds = NUM_ACT_EXPERTS / NUM_MVM_COLUMN; + for(AIE_LOCK_LOOP_CTR req = 0; req < rounds; req++){ + _up_lock_acquire(glu_request_router_send_lock); + const int first = req == 0 ? 0 : req + 1; + const int last = req + 1 < rounds ? req + 1 : rounds - 1; + for(int round = first; round <= last; round++){ + for(int i = 0; i ( + control_packet_out_buf, control_packet_in_buf, + control_packet_out_prod_lock_id, control_packet_out_con_lock_id, + control_packet_in_prod_lock_id, control_packet_in_con_lock_id, + CT_to_shimtile_control_bd_id, CT_from_shimtile_control_bd_id, + CT_to_shimtile_control_bd_port, CT_from_shimtile_control_bd_port, + SHIM_x_control_packet_id_list[i], + ch, ((round & 1) == 0 ? SHIM_X_expert_BD_ID : Round_2_SHIM_X_expert_BD_ID) + ch, + SHIM_BD_1_VIRTUAL_ptr[0], SHIM_BD_1_VIRTUAL_ptr[1], + Q4_K_EXPERT_BYTE_PER_CHANNEL, expert_offset + ch * Q4_K_EXPERT_BYTE_PER_CHANNEL + ); + } + } + } + } + + _up_lock_acquire(x_in_con_lock); + _up_lock_release(x_in_prod_lock); + + + } + + + +} \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router_block.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router_block.hpp new file mode 100644 index 000000000..f25338c1b --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router_block.hpp @@ -0,0 +1,27 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __ROUTER_BLOCK_HPP__ +#define __ROUTER_BLOCK_HPP__ + +#include "aie_array_layout.h" +#include "mvm_col_major.hpp" + +// The router weight arrives in blocks of router_weight_row_block (32) experts x +// router_weight_col_block (256) inputs, column major (the 32 experts of one input +// adjacent). The router CT takes experts 0..63 (MT5 half 0) and the router +// helper takes 64..159 (MT5 half 1, then IT5 channel 1 direct); both run this per block. +// +// logits[0..31] += block * x[0..255], in fp32. +// Done as two 16-row halves with the 16-row matvec that was already in use (a +// 32-row instantiation would be new code in the router CT, which has ~330 B of +// program memory left). +static inline void router_block_matvec(bfloat16* block, bf16* x, float* logits) +{ + constexpr int R = router_weight_row_block; + constexpr int C = router_weight_col_block; + matvec_vectorized_col_major(block, x, logits); + matvec_vectorized_col_major(block + R / 2, x, logits + R / 2); +} + +#endif // __ROUTER_BLOCK_HPP__ diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router_helper.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router_helper.cc new file mode 100644 index 000000000..b89215aff --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router_helper.cc @@ -0,0 +1,61 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "model_spec.h" +#include "aie_kernel_utils.h" +#include "aie_array_layout.h" +#include "router_block.hpp" + +// In the router CT (the tile above), reached with _up_lock_*. +constexpr int router_helper_x_ready_lock = 13; // the router copied x +constexpr int router_helper_finished_lock = 14; // set when this tile's logits are in + +// This tile's weight blocks, two buffers shared by two streams: +// S2MM 0 (IT5 channel 0 -> MT5 half 1): experts 64..127 (A, 16 blocks) +// S2MM 1 (IT5 channel 1, direct): experts 128..159 (B, 8 blocks) +// Both fill the buffers in turn and release w_cons_lock. S2MM 0 waits on +// w_prod_lock, S2MM 1 on b_prod_lock, so the order is fixed: the last two A +// blocks free their buffers to B, and the last two B blocks hand them back to +// the next call's A. +constexpr int w_prod_lock = 0; +constexpr int w_cons_lock = 1; +constexpr int b_prod_lock = 2; + +constexpr int HELPER_FIRST_EXPERT = 64; // MT5 half 0 is the router's +constexpr int MT5_EXPERTS = 128; // MT5 holds 0..127, the rest come direct +constexpr int BLOCKS_PER_ROW = MODEL_DIM / router_weight_col_block; +constexpr int A_BLOCKS = (MT5_EXPERTS - HELPER_FIRST_EXPERT) / router_weight_row_block * BLOCKS_PER_ROW; +constexpr int B_BLOCKS = (NUM_EXPERTS - MT5_EXPERTS) / router_weight_row_block * BLOCKS_PER_ROW; +static_assert(A_BLOCKS % 2 == 0 && B_BLOCKS % 2 == 0 && B_BLOCKS >= 2, "ping/pong alignment"); +static_assert((NUM_EXPERTS - MT5_EXPERTS) % router_weight_row_block == 0); + +extern "C" { +// Router logits of experts 64 .. NUM_EXPERTS-1, written straight into the +// router CT's logit buffer. The router does 0..63 from its own stream at the +// same time. +void router_helper( + bf16* AIE_DMA_RESTRICT x_in, // the router's copy of x (router memory) + bfloat16* AIE_DMA_RESTRICT w_block_ping, // this tile's weight blocks + bfloat16* AIE_DMA_RESTRICT w_block_pong, + float* logits // NUM_EXPERTS fp32 (router memory) +) +{ + static bool is_ping = true; + + _up_lock_acquire(router_helper_x_ready_lock); + int n = 0; + for (AIE_LOCK_LOOP_CTR i = HELPER_FIRST_EXPERT; i < NUM_EXPERTS; i += router_weight_row_block) { + for (AIE_LOCK_LOOP_CTR j = 0; j < MODEL_DIM; j += router_weight_col_block) { + _lock_acquire(w_cons_lock); + router_block_matvec(is_ping ? w_block_ping : w_block_pong, x_in + j, logits + i); + // A blocks 0 .. A-3 and the last 2 B blocks go back to S2MM 0, the + // rest to S2MM 1 + const bool to_b = (n >= A_BLOCKS - 2) && (n < A_BLOCKS + B_BLOCKS - 2); + _lock_release(to_b ? b_prod_lock : w_prod_lock); + is_ping = !is_ping; + n++; + } + } + _up_lock_release(router_helper_finished_lock); +} +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router_math.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router_math.hpp new file mode 100644 index 000000000..f6419deb2 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/router_math.hpp @@ -0,0 +1,125 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __ROUTER_MATH_HPP__ +#define __ROUTER_MATH_HPP__ + +// fp32 sigmoid routing for MiniCPM5-15B-A2.5B: +// scores = sigmoid(logits) all experts +// choose = top K of (scores + bias) the bias only picks experts +// weights = picked scores / their sum * scaling +// +// AIE2P's exp2 returns bf16 (0.4% error), enough to swap two close experts, so +// the exponential here is built from fp32 vector ops (aie::mul on fp32 is exact, +// see bf16_limb_math.hpp). All 160 experts take a few hundred vector ops. +// The loops stay rolled (AIE_LOOP_NO_UNROLL): every fp32 multiply is 9 bf16 +// MACs of code, and unrolled they overflowed the router core's 16 KB program memory. + +#include +#include "sort.hpp" +#include "aie_kernel_utils.h" + +namespace router_math { + +// 2^t for t <= 0, fp32, relative error ~1e-7. +// Trick: split t = n + f with n an integer. 2^f (|f| < 1) is a short polynomial, +// and 2^n * 2^f needs no multiply: add n to the float's exponent field. +template +aie::vector exp2_f32(aie::vector t) +{ + // keep the result a normal float (2^f >= 0.5, so 2^t >= 2^-126); + // sigmoid is 0 or 1 to fp32 there anyway + t = aie::max(t, -125.0f); + + // n = t rounded to an integer (nearest or down; either way |f| < 1) + aie::vector n = aie::to_fixed(t, 0); + aie::vector f = aie::sub(t, aie::to_float(n, 0)); + + // 2^f = e^(f ln2): Taylor series to degree 8, c_k = ln2^k / k!. + // Error <= ln2^9 / 9! = 1e-7 for |f| < 1. Horner form: p = (..(c8 f + c7) f ..) f + c0 + constexpr float c[9] = {1.0f, 0.69314718f, 0.24022651f, + 0.055504109f, 0.0096181291f, 0.0013333558f, + 1.5403530e-4f, 1.5252734e-5f, 1.3215487e-6f}; + aie::vector p = aie::broadcast(c[8]); + AIE_LOOP_NO_UNROLL + for (int k = 7; k >= 0; k--) { + p = aie::add(aie::mul(p, f).template to_vector(), c[k]); + } + + // p * 2^n: add n to the exponent field (bits 23..30) of p, as integers. + // Exact while the result stays normal (the clamp above). This saves an fp32 + // multiply, which is 9 bf16 MACs of program memory. + aie::vector p_bits = p.template cast_to(); + return aie::add(p_bits, aie::upshift(n, 23)).template cast_to(); +} + +// 1 / d for d in [1, 2], fp32. +// Start from the hardware bf16 reciprocal (error ~2^-8), then Newton: +// r <- r + r (1 - d r) squares the error each step: 2^-8 -> 2^-16 -> 2^-32. +template +aie::vector inv_1_to_2(aie::vector d) +{ + aie::accum d_acc(d); + aie::vector r_bf16 = aie::inv(d_acc.template to_vector()); + aie::accum r_acc(r_bf16); + aie::vector r = r_acc.template to_vector(); + AIE_LOOP_NO_UNROLL + for (int step = 0; step < 2; step++) { + aie::vector err = aie::sub(aie::broadcast(1.0f), + aie::mul(d, r).template to_vector()); + r = aie::add(r, aie::mul(r, err).template to_vector()); + } + return r; +} + +// out[i] = sigmoid(in[i]), fp32, E a multiple of VLEN. +// Trick: only ever take exp of -|x|, so e = e^-|x| is in (0, 1] and cannot overflow: +// sigmoid(|x|) = 1 / (1 + e), sigmoid(-|x|) = e / (1 + e) +template +void sigmoid_f32(float* out, const float* in) +{ + static_assert(E % VLEN == 0); + constexpr float log2_e = 1.44269504088896341f; + AIE_LOOP_NO_UNROLL + for (int i = 0; i < E; i += VLEN) { + aie::vector x = aie::load_v(in + i); + aie::vector t = aie::mul(aie::abs(x), -log2_e).template to_vector(); + aie::vector e = exp2_f32(t); // e^-|x| + aie::vector r = inv_1_to_2(aie::add(e, 1.0f)); // 1 / (1 + e) + aie::vector s_neg = aie::mul(e, r).template to_vector(); + // select(a, b, m) takes b where m is set + aie::store_v(out + i, aie::select(r, s_neg, aie::lt(x, 0.0f))); + } +} + +// The whole routing step. +// logits: E router logits; overwritten (used as scratch for scores + bias) +// bias: E fp32 expert biases +// idx: out, the K chosen experts, highest score + bias first +// weights: out, their routing weights +template +void route_sigmoid_topk(float* weights, int32_t* idx, float* logits, const float* bias, float scaling) +{ + alignas(aie::vector_decl_align) float scores[E]; + sigmoid_f32(scores, logits); + + // choice = scores + bias, over the logits (not needed any more) + for (int i = 0; i < E; i += VLEN) { + aie::store_v(logits + i, aie::add(aie::load_v(scores + i), aie::load_v(bias + i))); + } + partial_select_largest(logits, idx); + + // weights come from the plain scores, not score + bias + float sum = 0.0f; + for (int k = 0; k < K; k++) { + sum = AIE_FADD(sum, scores[idx[k]]); + } + const float factor = scaling / sum; + for (int k = 0; k < K; k++) { + weights[k] = AIE_FMUL(scores[idx[k]], factor); + } +} + +} // namespace router_math + +#endif // __ROUTER_MATH_HPP__ diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/sort.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/sort.hpp new file mode 100644 index 000000000..235d84507 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/sort.hpp @@ -0,0 +1,155 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + + +#ifndef __SORT_HPP__ +#define __SORT_HPP__ + +#include +#include +#include + + +#include + + +#include "aie_kernel_utils.h" + +template +void bubble_sort_largest_to_smallest(T * data, int* index) { + // Initialize the index array with original indices (0, 1, 2, ...) + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(size, size) + for (int i = 0; i < size; i++) { + index[i] = i; + } + + bool swapped; + + AIE_PREPARE_FOR_PIPELINING + for (int i = 0; i < size - 1; i++) { + swapped = false; + + AIE_PREPARE_FOR_PIPELINING + for (int j = 0; j < size - i - 1; j++) { + // Compare the adjacent data elements. + if ((float)data[j] <(float) data[j + 1]) { + // Swap the data elements. + T tempData = data[j]; + data[j] = data[j + 1]; + data[j + 1] = tempData; + + // IMPORTANT: Swap the corresponding indices in parallel. + int tempIndex = index[j]; + index[j] = index[j + 1]; + index[j + 1] = tempIndex; + + swapped = true; + } + } + + // If no elements were swapped, the array is sorted. + if (swapped == false) { + break; + } + } +} + +template +void bubble_sort_largest_to_smallest_bf16_with_index(bfloat16* data, int* index) { + bubble_sort_largest_to_smallest(data, index); +} + +// Iterative quicksort, O(n log n) time, O(log n) stack space. +// Always processes the smaller partition first to bound stack depth at O(log n). +template +void quick_sort_largest_to_smallest(T* data, int* index) { + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(size, size) + for (int i = 0; i < size; i++) { + index[i] = i; + } + + // Stack depth is O(log n): worst case ceil(log2(size)) levels. + // 32 is safe for size up to 2^16. + constexpr int STACK_SIZE = 32; + int lo_stk[STACK_SIZE]; + int hi_stk[STACK_SIZE]; + int top = 0; + lo_stk[0] = 0; + hi_stk[0] = size - 1; + + while (top >= 0) { + int lo = lo_stk[top]; + int hi = hi_stk[top--]; + if (lo >= hi) continue; + + // Partition around pivot = data[hi], descending order. + float pivot = (float)data[hi]; + int i = lo - 1; + for (int j = lo; j < hi; j++) { + if ((float)data[j] >= pivot) { + ++i; + T td = data[i]; data[i] = data[j]; data[j] = td; + int ti = index[i]; index[i] = index[j]; index[j] = ti; + } + } + ++i; + T td = data[i]; data[i] = data[hi]; data[hi] = td; + int ti = index[i]; index[i] = index[hi]; index[hi] = ti; + + int p = i; + int left_sz = p - lo; + int right_sz = hi - p; + + // Push larger partition first so the smaller one is processed first, + // keeping max stack depth at O(log n). + if (left_sz >= right_sz) { + if (lo < p - 1) { lo_stk[++top] = lo; hi_stk[top] = p - 1; } + if (p + 1 < hi) { lo_stk[++top] = p + 1; hi_stk[top] = hi; } + } else { + if (p + 1 < hi) { lo_stk[++top] = p + 1; hi_stk[top] = hi; } + if (lo < p - 1) { lo_stk[++top] = lo; hi_stk[top] = p - 1; } + } + } +} + +template +void quick_sort_largest_to_smallest_bf16_with_index(bfloat16* data, int* index) { + quick_sort_largest_to_smallest(data, index); +} + +// Top-K partial selection sort: O(n*K) time, O(1) extra space. +// Produces the K largest values in descending order at data[0..K-1] / index[0..K-1]. +// Elements beyond K are left in an unspecified order. +template +void partial_select_largest(T* data, int* index) { + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(size, size) + for (int i = 0; i < size; i++) { + index[i] = i; + } + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(K, K) + for (int i = 0; i < K; i++) { + int max_j = i; + + AIE_PREPARE_FOR_PIPELINING + for (int j = i + 1; j < size; j++) { + if (data[j] > data[max_j]) { + max_j = j; + } + } + + if (max_j != i) { + T td = data[i]; data[i] = data[max_j]; data[max_j] = td; + int ti = index[i]; index[i] = index[max_j]; index[max_j] = ti; + } + } +} + +template +void partial_select_largest_bf16_with_index(bfloat16* data, int* index) { + partial_select_largest(data, index); +} +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/typedef.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/typedef.hpp new file mode 100644 index 000000000..a069f58fd --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/typedef.hpp @@ -0,0 +1,14 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +///@file typedef.hpp +///@brief Define the typedefs for the kernels +#ifndef __TYPEDEF_HPP__ +#define __TYPEDEF_HPP__ + +#include +#include + +typedef bfloat16 bf16; + + +#endif // __TYPEDEF_HPP__ \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/zero.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/zero.h new file mode 100644 index 000000000..ae86b6d88 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/kernels/zero.h @@ -0,0 +1,39 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef __ZERO_H__ +#define __ZERO_H__ +#define NOCPP +#include +#include +#include +#include + +#include + +template +void zero_vectorized(T *__restrict c) { + constexpr int r = 256 / (sizeof(T) * 8); // one 256 bit store unit + static_assert((M) % r == 0); + const aie::vector zeros = aie::zeros(); + const T *__restrict c_end = c + M; + for (; c < c_end; c += r) { + aie::store_v(c, zeros); + } +} + + + +template +void zero_vectorized_512(T *__restrict c) { + constexpr int r = 512 / (sizeof(T) * 8); // 512 bit store units for AIE2P + static_assert((M * N) % r == 0); + const aie::vector zeros = aie::zeros(); + const T *__restrict c_end = c + M * N; + event0(); + for (; c < c_end; c += r) { + aie::store_v(c, zeros); + } + event1(); +} +#endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/bitstream.mk b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/bitstream.mk new file mode 100644 index 000000000..5c5f55758 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/bitstream.mk @@ -0,0 +1,61 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +# MLIR stuff + +MLIR_O_DIR := $(BUILD_DIR)/mlir +BITSTREAM_O_DIR := $(BUILD_DIR)/bitstream + + +IRON_BOTH_SRC := $(wildcard ${HOME_DIR}/iron/*_aie.py) +IRON_OTHER_SRC := $(wildcard ${HOME_DIR}/iron/*.py) +IRON_OTHER_SRC += $(wildcard ${HOME_DIR}/iron/models/*.py) +IRON_BOTH_MLIR_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${MLIR_O_DIR}/%.mlir, ${IRON_BOTH_SRC}) +IRON_BOTH_XCLBIN_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${BITSTREAM_O_DIR}/from_iron/%.xclbin, ${IRON_BOTH_SRC}) + +.PRECIOUS: ${IRON_BOTH_MLIR_TARGET} + +AIECC_FLAGS := --aie-generate-cdo --no-compile-host +# ENABLE_CHESSCC is set by the top-level Makefile. +ifeq ($(ENABLE_CHESSCC),1) +AIECC_FLAGS += --xchesscc --xbridge +else +AIECC_FLAGS += --no-xchesscc --no-xbridge +endif +# iron generate mlir +${MLIR_O_DIR}/%.mlir: ${HOME_DIR}/iron/%_aie.py ${IRON_OTHER_SRC} + mkdir -p ${@D} + ENABLE_CHESSCC=$(ENABLE_CHESSCC) python3 $< ${IRON_ARGS} > $@ + +# Routing check (deadlock-prone arbiter sharing, misdelivered flows), run in ${@D}. +ifeq ($(CHECK_ROUTES),0) +CHECK_ROUTES_CMD = echo "check_routes: SKIPPED (CHECK_ROUTES=0; experiments only)" +else +CHECK_ROUTES_CMD = python3 ${HOME_DIR}/check_routes.py $(notdir $<).prj/input_physical.mlir ../../mlir/$(notdir $<) +endif +# aiecc's router gives a different routing from run to run (its choices depend on +# memory addresses, which Linux randomizes), so a failed check is retried with a +# fresh routing, up to ROUTE_TRIES times. A failed try's xclbin is deleted so it +# is never used or seen as up to date. +ROUTE_TRIES ?= 5 + +# Build xclbin +${BITSTREAM_O_DIR}/from_iron/%.xclbin: ${MLIR_O_DIR}/%.mlir ${KERNEL_OBJS} + mkdir -p ${@D} + cp ${KERNEL_OBJS} ${@D} + cd ${@D} && for try in $$(seq 1 $(ROUTE_TRIES)); do \ + aiecc.py ${AIECC_FLAGS} --aie-generate-xclbin \ + --xclbin-name=${@F} $(<:${MLIR_O_DIR}/%=../../mlir/%) || exit 1; \ + if $(CHECK_ROUTES_CMD); then break; fi; \ + rm -f ${@F}; \ + if [ $$try -eq $(ROUTE_TRIES) ]; then echo "check_routes: failed all $(ROUTE_TRIES) tries"; exit 1; fi; \ + echo "check_routes: try $$try failed, routing again"; \ + done + mkdir -p $(BUILD_DIR)/xclbins + cp ${@} $(BUILD_DIR)/xclbins/layer.xclbin + cat ${@D}/*/input_with_addresses.mlir | grep "%RTP" | grep "aie.buffer" | awk '{print $$1, $$6}' | sed 's/%//g' | tee $(BUILD_DIR)/xclbins/rtp_addresses.txt +ifneq ($(ENABLE_CHESSCC),1) + @${HOME_DIR}/makefiles/check_peano_stack.sh ${@D}/*/*.elf +endif + +XCLBIN_TARGETS += ${IRON_BOTH_XCLBIN_TARGET} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/check_peano_stack.sh b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/check_peano_stack.sh new file mode 100755 index 000000000..f0e346071 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/check_peano_stack.sh @@ -0,0 +1,122 @@ +#!/bin/bash +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +# Fail the build if any core's stack frames can overrun its stack region. +# +# The AIE stack starts at _sp_start_value_DM_stack and grows upward until it +# reaches the next buffer. The Peano toolchain does not check this (the stack is +# not a section, so ld.lld cannot see it), and an overrun overwrites that buffer +# without any error. +# +# frames is the sum of every positive SP adjustment in the ELF, an upper bound +# on the deepest call chain. It over-counts, so the check can reject a build +# that would have fit, but not the reverse. If it fires, raise the stack size in +# iron/layer_aie.py and re-check xclbins/rtp_addresses.txt, since a bigger stack +# can move the RTP buffers that FLM_DLL hardcodes. +# +# Anything the check cannot work out (a missing tool or ELF, disassembly or +# symbols it cannot parse) is an error, never a skipped core: a check that +# quietly checks nothing looks the same as one that passes. Only bash, grep and +# awk are used (no bc), so it runs in the kernel build image as it is. +set -u + +err() { echo "error: check_peano_stack.sh: $*" >&2; } + +: "${PEANO_INSTALL_DIR:?check_peano_stack.sh needs PEANO_INSTALL_DIR}" +OBJDUMP="${PEANO_INSTALL_DIR}/bin/llvm-objdump" +NM="${PEANO_INSTALL_DIR}/bin/llvm-nm" +for tool in "$OBJDUMP" "$NM"; do + [ -x "$tool" ] || { err "$tool not found or not executable"; exit 1; } +done +for tool in grep awk; do + command -v "$tool" >/dev/null 2>&1 || { err "$tool not found"; exit 1; } +done +[ $# -gt 0 ] || { err "no ELF files given"; exit 1; } + +# Sum of the positive immediates of every "padd* [sp], #imm" in a disassembly +# on stdin. Negative immediates are the epilogues giving the frame back. Prints +# the sum, or prints each SP adjustment it cannot read and fails. +sum_frames() { + local line sign num total=0 bad=0 + while IFS= read -r line; do + if [[ $line =~ padd[a-z]*[[:space:]]*\[sp\],[[:space:]]*#(-?)(0x[0-9a-fA-F]+|[0-9]+)([^0-9a-zA-Z]|$) ]]; then + sign=${BASH_REMATCH[1]} + num=${BASH_REMATCH[2]} + # Decimal goes through 10# so a leading zero is not read as octal. + if [[ $num == 0x* ]]; then num=$((num)); else num=$((10#$num)); fi + [ -n "$sign" ] || total=$((total + num)) + else + echo "cannot parse SP adjustment: $line" >&2 + bad=1 + fi + done < <(grep -E 'padd[a-z]*[[:space:]]*\[sp\]') + [ "$bad" -eq 0 ] || return 1 + echo "$total" +} + +rc=0 +for f in "$@"; do + if [ ! -f "$f" ]; then + err "$f: no such ELF" + rc=1 + continue + fi + base=$(basename "$f") + + if ! dis=$("$OBJDUMP" -d "$f" 2>&1); then + err "$base: llvm-objdump failed:" + printf '%s\n' "$dis" | head -5 >&2 + rc=1 + continue + fi + # A disassembly without a single function is not one this script can read. + if ! grep -qE '^[0-9a-fA-F]+ <[^>]+>:' <<<"$dis"; then + err "$base: no functions in the llvm-objdump -d output" + rc=1 + continue + fi + if ! frames=$(sum_frames <<<"$dis"); then + err "$base: cannot read the SP adjustments above" + rc=1 + continue + fi + # A core with no SP adjustment at all uses no stack; nothing to check. + [ "$frames" -gt 0 ] || continue + + if ! syms=$("$NM" -n "$f" 2>&1); then + err "$base: llvm-nm failed:" + printf '%s\n' "$syms" | head -5 >&2 + rc=1 + continue + fi + start=$(awk '$NF == "_sp_start_value_DM_stack" {print $1; exit}' <<<"$syms") + if ! [[ $start =~ ^[0-9a-fA-F]+$ ]]; then + err "$base: uses ${frames} B of stack but has no _sp_start_value_DM_stack address" + rc=1 + continue + fi + # llvm-nm -n sorts by address, so the first absolute symbol above the stack + # start is the buffer that bounds it. Compare as integers: awk would read + # "00070000" as a number but "0007c000" as a string. + limit="" + while read -r addr type _; do + [ "$type" = "N" ] && [[ $addr =~ ^[0-9a-fA-F]+$ ]] || continue + if [ $((16#$addr)) -gt $((16#$start)) ]; then limit=$addr; break; fi + done <<<"$syms" + if [ -z "$limit" ]; then + err "$base: uses ${frames} B of stack but no buffer above the stack start 0x${start} bounds it" + rc=1 + continue + fi + + region=$(( 16#$limit - 16#$start )) + if [ "$frames" -gt "$region" ]; then + echo "error: $base: stack frames total ${frames} B but only ${region} B of stack" >&2 + echo " (stack 0x${start} grows up into the buffer at 0x${limit})" >&2 + rc=1 + elif [ $((frames * 100 / region)) -ge 95 ]; then + echo "warning: $base: stack ${frames}/${region} B ($((frames * 100 / region))% used)" >&2 + fi +done +exit $rc diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/common.mk b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/common.mk new file mode 100644 index 000000000..045bffdb4 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/common.mk @@ -0,0 +1,31 @@ +# common.mk +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Created by Alfred + +ifneq ($(filter -j,$(MAKEFLAGS)),) + # Nothing to do; -j is already set +else + MAKEFLAGS += -j8 +endif + +# VITIS related variables (Chess only: ENABLE_CHESSCC=1; Peano builds never expand them) +AIETOOLS_DIR ?= $(or $(AIETOOLS_ROOT),$(patsubst %/bin/,%,$(dir $(shell command -v xchesscc 2>/dev/null)))) +# Expanded only inside the Chess recipes, so it fires only for ENABLE_CHESSCC=1. +AIETOOLS_CHECK = $(if $(strip $(AIETOOLS_DIR)),,$(error ENABLE_CHESSCC=1 needs Vitis AIE Essentials: set AIETOOLS_ROOT (or AIETOOLS_DIR), or put xchesscc on PATH)) +AIE_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/versal_prod/lib +AIE2_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/aie_ml/lib + +AIEOPT_DIR ?= $(shell realpath $(dir $(shell which aie-opt))/..) + +WARNING_FLAGS = -Wno-parentheses -Wno-attributes -Wno-macro-redefined + + +CHESSCCWRAP1_FLAGS = aie $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include +CHESSCCWRAP2_FLAGS = aie2 $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include +CHESSCCWRAP2P_FLAGS = aie2p $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 -O3 +PEANOWRAP2_FLAGS = -O2 -v -std=c++20 --target=aie2-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -I ${AIEOPT_DIR}/include +PEANOWRAP2P_FLAGS = -O2 -std=c++20 --target=aie2p-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 -I ${AIEOPT_DIR}/include diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/host.mk b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/host.mk new file mode 100644 index 000000000..e51d66e87 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/host.mk @@ -0,0 +1,60 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +# ============================================================================= +# Llama NPU Library Makefile +# ============================================================================= +# +# Created: 2024 +# +# This Makefile is used to build the Llama NPU library components. +# +# Usage: +# make - Build all targets +# make clean - Remove all built files +# make help - Show this help message +# +# ============================================================================= + +# Linux build environment +# Use g++-13 directly without CMake + +HOST_C_TARGET := run.exe +HOST_COMMON_DIR := ../../host_common + + +CXX := g++-13 +CXX_FLAGS := -std=c++20 -fPIC -Wall +CXX_FLAGS += -DUSE_AVX2=1 +CXX_FLAGS += -mavx2 -march=native -mfma -ffast-math +CXX_FLAGS += -Ihost +CXX_FLAGS += -I/opt/xilinx/xrt/include +CXX_FLAGS += -I$(HOST_COMMON_DIR) +CXX_FLAGS += -MMD -MP +CXX_FLAGS += -DVERBOSE=$(VERBOSE) + +LDFLAGS += -L/opt/xilinx/xrt/lib +LDFLAGS += -L$(HOST_COMMON_DIR) +LDFLAGS += -lxrt_coreutil $(HOST_COMMON_DIR)/../../../src/lib/xrt/libaiebu.a +LDFLAGS += -lboost_program_options -lboost_filesystem + +# Find all source files in host/ directory (including subdirectories) +HOST_SOURCES := $(shell find host -name '*.cpp') +HOST_OBJECTS := $(HOST_SOURCES:%.cpp=build/%.o) +HOST_DEPENDS := $(HOST_OBJECTS:.o=.d) + +# Default target +$(HOST_C_TARGET): build/$(HOST_C_TARGET) + cp build/$(HOST_C_TARGET) ./ + +# Link the executable +build/$(HOST_C_TARGET): $(HOST_OBJECTS) + @mkdir -p $(dir $@) + $(CXX) $(CXX_FLAGS) $^ -o $@ $(LDFLAGS) + +# Compile source files and generate dependencies +build/%.o: %.cpp + @mkdir -p $(dir $@) + $(CXX) $(CXX_FLAGS) -c $< -o $@ + +# Include dependency files +-include $(HOST_DEPENDS) \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/kernel.mk b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/kernel.mk new file mode 100644 index 000000000..e5c18a7ef --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/makefiles/kernel.mk @@ -0,0 +1,23 @@ +# common.mk +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Portions of this file consist of AI-generated content. +# Created by Alfred + +# Kernel stuff +KERNEL_O_DIR := $(BUILD_DIR)/kernels +KERNEL_SRCS := $(wildcard ${HOME_DIR}/kernels/*.cc) +KERNEL_OBJS := $(patsubst ${HOME_DIR}/kernels/%.cc, ${KERNEL_O_DIR}/%.o, $(KERNEL_SRCS)) +KERNEL_HEADERS := $(wildcard ${HOME_DIR}/kernels/*.h) $(wildcard ${HOME_DIR}/kernels/*.hpp) + +# Build kernels +${KERNEL_O_DIR}/%.o: ${HOME_DIR}/kernels/%.cc ${KERNEL_HEADERS} + mkdir -p ${@D} +ifeq ($(ENABLE_CHESSCC),1) + cd ${@D} && xchesscc_wrapper ${CHESSCCWRAP2P_FLAGS} -DNPU2 ${KERNEL_ARGS} -c $< -o ${@F} +else + cd ${@D} && ${PEANO_INSTALL_DIR}/bin/clang++ ${PEANOWRAP2P_FLAGS} ${KERNEL_PEANO_EXTRA} -DNPU2 ${KERNEL_ARGS} -c $< -o ${@F} +endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/models/all_models.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/models/all_models.h new file mode 100644 index 000000000..796ac789a --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/models/all_models.h @@ -0,0 +1,46 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __ALL_MODELS_H__ +#define __ALL_MODELS_H__ + +/// @brief Attention implementation +/// @note 2x4x1: for 8 kv heads +#define ATTN_IMPL_2x4x1 0 +/// @brief Attention implementation +/// @note 2x4x1: for 4 kv heads +#define ATTN_IMPL_1x4x1 1 +/// @brief Attention implementation +/// @note 1x8x1: for 2 kv heads +#define ATTN_IMPL_1x8x1 2 + +/// @brief Activation function +#define A_SILU 0 +/// @brief Activation function +#define A_GELU 1 + +#define MINICPM5_15B_A2_5B 0 + +#define __Q4_1__ 0 +#define __Q8_0__ 1 +#define __Q4_K__ 2 + +// For each Q4NX block of Q4NX_ROW_BLOCK_SIZEx Q4NX_COL_BLOCK_SIZE +// The data block are in column-major order, with each column being Q4NX_ROW_STRIDE in length, +//and the next column start after Q4NX_ROW_STRIDE elements. +/* +The data block is the following layout, where index represent the data element index view in 1D array +[0,Q4NX_ROW_STRIDE , .... (Q4NX_COL_BLOCK_SIZE-1)*Q4NX_ROW_STRIDE], +[1,Q4NX_ROW_STRIDE + 1, .... (Q4NX_COL_BLOCK_SIZE-1)*Q4NX_ROW_STRIDE + 1], +[2,Q4NX_ROW_STRIDE + 2, .... (Q4NX_COL_BLOCK_SIZE-1)*Q4NX_ROW_STRIDE + 2], +... +*/ + + +#ifndef MODEL_TYPE +#define MODEL_TYPE MINICPM5_15B_A2_5B +#endif + +#include "../models/minicpm5-15b-a2.5b.h" + +#endif // __ALL_MODELS_H__ \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/models/minicpm5-15b-a2.5b.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/models/minicpm5-15b-a2.5b.h new file mode 100644 index 000000000..1febde6e1 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/models/minicpm5-15b-a2.5b.h @@ -0,0 +1,60 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +///@file minicpm5-15b-a2.5b.h +///@brief Model parameters for openbmb/MiniCPM5-15B-A2.5B (minicpm5_moe), sparse (MoE) layers 1..27 +#ifndef __MINICPM5_15B_A2_5B_H__ +#define __MINICPM5_15B_A2_5B_H__ + +#if MODEL_TYPE == MINICPM5_15B_A2_5B +constexpr int MODEL_DIM = 2048; +constexpr int NUM_ATTN_HEADS = 32; +// the model has 2 KV heads; the host duplicates the k/v weight rows as +// [h0, h0, h1, h1], so each of the 4 attention CUs holds one KV head +constexpr int NUM_KV_HEADS = 4; +constexpr int DH = 128; +constexpr int ROPE_DIM = 128; // full RoPE (NEOX) +constexpr float ATTN_SCALE = 0.08838834764831845f; // 1 / sqrt(DH) +constexpr float RMS_EPS = 1e-6f; + +// ---- MoE ---- +// Experts and the shared expert are 512 wide. One GLU slice is one proj round: +// 16 cores x 32 rows = 512 values, and the host orders the up/gate weight rows +// so that every round holds matching up and gate rows: +// shared expert: [up 256 | gate 256] -> 256 h per round, 2 rounds +// routed experts: per column (one expert each) [up 64 | gate 64] +// -> 64 h per expert per round, 8 rounds +constexpr int INTERMEDIATE_SIZE = 512; +constexpr int GLU_SLICE = 512; +constexpr int UP_GATE_OUTDIM_REORDEER = 256; // shared: up (or gate) rows per round +constexpr int EXP_UP_GATE_OUTDIM_REORDER = 64; // routed: up (or gate) rows per column per round +constexpr int NUM_EXPERTS = 160; +constexpr int NUM_ACT_EXPERTS = 16; +// router: sigmoid scores, top 16 of (score + fp32 bias), weight = score / sum * this +constexpr float ROUTER_SCALING = 3.66f; +// layers the router keeps a weight base address for (num_hidden_layers) +constexpr int MAX_LAYERS = 28; +// Layers 0 .. FIRST_K_DENSE - 1 are dense (SwiGLU, 8192 wide) and run on this +// design too: SwiGLU is elementwise over its width, so the 8192-wide MLP is the +// sum of 16 slices of 512, which the host stores as experts 0..15. For these +// layers the router skips routing and picks experts 0..15 with weight 1; the +// host gives them a zero shared expert. +constexpr int FIRST_K_DENSE = 1; +static_assert(NUM_ACT_EXPERTS * INTERMEDIATE_SIZE == 8192, "dense width must be top-k x expert width"); + +#define QUANT_TYPE __Q4_K__ +#define ATTN_IMPL ATTN_IMPL_1x8x1 +#define A_FUNC A_SILU +// no q/k norm; attention output is gated: o_in = attn * sigmoid(x @ W_gate) + +constexpr int QXNX_ROW_BLOCK_SIZE = 32; +constexpr int QXNX_COL_BLOCK_SIZE = 256; +constexpr int GGML_GROUP_SIZE = 32; + +constexpr int PROJ_X_SLICE = QXNX_COL_BLOCK_SIZE; +// for decode reorder only +constexpr int router_weight_row_block= 32; +constexpr int router_weight_col_block = 256; +#endif + +#endif // __MINICPM5_15B_A2_5B_H__ diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/quick_route.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/quick_route.py new file mode 100644 index 000000000..97d8c8419 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/quick_route.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""Route an IRON layer.mlir the way aiecc does, in seconds, and run check_routes.py on it. + +aiecc routes after its address pipeline (which also adds its own control-packet +flows), so routing the plain IRON MLIR gives a different answer. This runs the +same pipeline (INPUT_WITH_ADDRESSES_PIPELINE) and then aie-opt's pathfinder. + +The router's result changes from run to run (its choices depend on memory +addresses, randomized by Linux), so one run says only what one routing looks +like; run it several times to see how often a design passes. It does not predict +a given aiecc build, which the build checks itself (makefiles/bitstream.mk). + +Usage: quick_route.py (exit code = check_routes.py's) +""" +import os +import subprocess +import sys +import tempfile + +from aie.compiler.aiecc.main import INPUT_WITH_ADDRESSES_PIPELINE, run_passes + +layer_mlir = sys.argv[1] +here = os.path.dirname(os.path.abspath(__file__)) +with tempfile.TemporaryDirectory() as tmp: + with_addresses = os.path.join(tmp, "input_with_addresses.mlir") + physical = os.path.join(tmp, "input_physical.mlir") + # same arguments aiecc uses by default for this design (see makefiles/bitstream.mk) + pipeline = INPUT_WITH_ADDRESSES_PIPELINE("", False, False, False, "AIE2P").materialize(module=True) + run_passes(pipeline, open(layer_mlir).read(), with_addresses, False) + subprocess.run(["aie-opt", "--aie-create-pathfinder-flows", with_addresses, "-o", physical], check=True) + sys.exit(subprocess.run([sys.executable, os.path.join(here, "check_routes.py"), physical, layer_mlir]).returncode) diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/visualize.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/visualize.py new file mode 100755 index 000000000..c4906ddb5 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/moe_decoding/visualize.py @@ -0,0 +1,464 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# to print unicode characters, run this: +# export PYTHONIOENCODING=utf8 + +import math +import json +import os, sys +import argparse + +from enum import Enum + + +class Direction(Enum): + Horz = 0 + Vert = 1 + + +class canvas: + def __init__(self, width, height): + self.width = width + self.height = height + self.vert_line_list = [] + self.horz_line_list = [] + self.characters = [] + + def direction(self, line): + Horz_Stationary = False + Vert_Stationary = False + + if line[0][0] == line[1][0]: + # Line Stationary in Horz Axis + Horz_Stationary = True + if line[0][1] == line[1][1]: + # Line Stationary in Vert Axis + Vert_Stationary = True + + if Horz_Stationary and Vert_Stationary: + # Crash + raise Exception("Line is Diagonal") + if not Horz_Stationary and not Vert_Stationary: + # Crash + raise Exception("Line is a dot") + if (not Horz_Stationary) and Vert_Stationary: + return Direction.Horz + + if Horz_Stationary and (not Vert_Stationary): + return Direction.Vert + + def draw_character(self, point, character): + self.characters.append([point, character]) + + def replace_character(self, point, character, replacement): + if self.characters.count([point, character]): + self.characters.remove([point, character]) + self.characters.append([point, replacement]) + + def draw_line(self, start, finish): + if self.direction([start, finish]) == Direction.Vert: + self.vert_line_list.append([start, finish]) + else: + self.horz_line_list.append([start, finish]) + + def draw_square(self, center, size): + horz_origin = math.floor((center[0] + 0.5) - (size / 2)) + horz_extent = math.ceil((center[0] + 0.5) + (size / 2) + 3) + + vert_origin = math.floor((center[1] + 0.5) - (size / 2)) + vert_extent = math.ceil((center[1] + 0.5) + (size / 2)) + + top_left = (horz_origin, vert_origin) + top_right = (horz_extent, vert_origin) + bottom_left = (horz_origin, vert_extent) + bottom_right = (horz_extent, vert_extent) + + self.draw_line(top_left, top_right) + self.draw_line(top_right, bottom_right) + self.draw_line(bottom_left, bottom_right) + self.draw_line(top_left, bottom_left) + + def vertical_index(self, point): + return point[1] + + def horizontal_index(self, point): + return point[0] + + def within_line(self, point, line): + Horz_Stationary = False + Vert_Stationary = False + + if line[0][0] == line[1][0]: + # Line Stationary in Horz Axis + Horz_Stationary = True + if line[0][1] == line[1][1]: + # Line Stationary in Vert Axis + Vert_Stationary = True + + # print("HS: {}, VS: {}, {}".format(Horz_Stationary, Vert_Stationary, line)); + + if Horz_Stationary and Vert_Stationary: + # Crash + raise Exception("Line is Diagonal") + if not Horz_Stationary and not Vert_Stationary: + # Crash + raise Exception("Line is a dot") + + if Horz_Stationary and (not Vert_Stationary): + # it's a vertical line + # Sort the tuples by Horz + line.sort(key=self.vertical_index) + start_line = ( + (point[1] == line[0][1]) + and (point[1] <= line[1][1]) + and (point[0] == line[0][0]) + ) + in_line = ( + (point[1] > line[0][1]) + and (point[1] < line[1][1]) + and (point[0] == line[0][0]) + ) + end_line = ( + (point[1] > line[0][1]) + and (point[1] == line[1][1]) + and (point[0] == line[0][0]) + ) + + # print("Vert {}, point {}, {}".format(line, point, in_line)); + + if (not Horz_Stationary) and Vert_Stationary: + # it's a horizonal line + line.sort(key=self.horizontal_index) + start_line = ( + (point[0] == line[0][0]) + and (point[0] <= line[1][0]) + and (point[1] == line[0][1]) + ) + in_line = ( + (point[0] > line[0][0]) + and (point[0] < line[1][0]) + and (point[1] == line[0][1]) + ) + end_line = ( + (point[0] > line[0][0]) + and (point[0] == line[1][0]) + and (point[1] == line[0][1]) + ) + # print("Horz {}, point {}, {}".format(line, point, in_line)); + + return (start_line, in_line, end_line) + + def find_horz_index(self, line_points): + index = 0 + + if line_points[1]: + index += 2 + else: + if line_points[0]: + index += 1 + if line_points[2]: + index += 4 + return index + + def transform(self, index): + + # if horz through, clear bits for horz end + # if vert through, clear bits for vert end + + chars = { + 0: " ", + 2: "\u2500", # horz line + 16: "\u2502", # vert line + 9: "\u250c", # box top left + 33: "\u2514", # box bot left + 12: "\u2510", # box top right + 36: "\u2518", # box bot right + 1: "\u2576", # right half horz line + 8: "\u2577", # lower half vert line + 32: "\u2575", # upper half vert line + 4: "\u2574", # left half horz line + 18: "\u253c", # vert AND horz + 25: "\u251c", # vert and right + 17: "\u251c", + 20: "\u2524", # vert and left + 10: "\u252c", # horz and bot + 34: "\u2534", # horz and top + 21: "\u253c", # vert AND horz + 42: "\u253c", + } + try: + char = chars[index] + except KeyError: + char = "x" + + return char + + def combine(self, a, b): + return [a[0] or b[0], a[1] or b[1], a[2] or b[2]] + + def rasterize(self): + for x in range(self.height): + for y in range(self.width): + char = "({},{})".format(y, x) + index = 0 + horz_line_points = [False, False, False] + vert_line_points = [False, False, False] + + for charloc in self.characters: + if charloc[0][0] == y and charloc[0][1] == x: + print(charloc[1], end="", sep="") + index = -1 + break + if index == 0: # not a character, either vert or horz line + for line in self.horz_line_list: + horz_line_points = self.combine( + horz_line_points, self.within_line((y, x), line) + ) + index += self.find_horz_index(horz_line_points) + + for line in self.vert_line_list: + vert_line_points = self.combine( + vert_line_points, self.within_line((y, x), line) + ) + index += 8 * self.find_horz_index(vert_line_points) + + print("{}".format(self.transform(index)), end="", sep="") + # print(" {} ".format(index), end='', sep='') + + print("") + + +superscripts = { + # 0 : u'\u2070', + 0: " ", + 1: "\u00b9", + 2: "\u00b2", + 3: "\u00b3", + 4: "\u2074", + 5: "\u2075", + 6: "\u2076", + 7: "\u2077", + 8: "\u2078", + 9: "\u2079", +} +subscripts = { + # 0 : u'\u2080', + 0: " ", + 1: "\u2081", + 2: "\u2082", + 3: "\u2083", + 4: "\u2084", + 5: "\u2085", + 6: "\u2086", + 7: "\u2087", + 8: "\u2088", + 9: "\u2089", +} + + +def draw_switchbox( + canvas, + xoffset, + yoffset, + source_count, + destination_count, + northbound, + southbound, + eastbound, + westbound, + draw_demand=True, + name="", +): + c.draw_square((xoffset + 5, yoffset + 4), 2) + + # label it + if len(name) > 0: + c.draw_character((xoffset + 6, yoffset + 4), name[0]) + if len(name) > 1: + c.draw_character((xoffset + 7, yoffset + 4), name[1]) + if len(name) > 2: + c.draw_character((xoffset + 8, yoffset + 4), name[2]) + if len(name) > 3: + c.draw_character((xoffset + 9, yoffset + 4), name[3]) + + # draw source and destination count + if source_count > 0 or destination_count > 0: + c.draw_character((xoffset + 7, yoffset + 5), "*") + + # left of the switchbox (south) + if northbound > 0: + c.draw_line((xoffset + 10, yoffset + 4), (xoffset + 14, yoffset + 4)) + if draw_demand: + c.draw_character((xoffset + 12, yoffset + 3), subscripts[northbound]) + if northbound > 6: # if overcapacity, mark with an 'x' + c.draw_character((xoffset + 10, yoffset + 4), "x") + # c.draw_character((xoffset+11,yoffset+4), 'x') + c.draw_character((xoffset + 12, yoffset + 4), "x") + if southbound > 0: + c.draw_line((xoffset + 0, yoffset + 5), (xoffset + 4, yoffset + 5)) + if draw_demand: + c.draw_character((xoffset + 2, yoffset + 6), superscripts[southbound]) + if southbound > 4: # if overcapacity, mark with an 'x' + c.draw_character((xoffset + 1, yoffset + 5), "x") + # c.draw_character((xoffset+2, yoffset+5), 'x') + c.draw_character((xoffset + 3, yoffset + 5), "x") + + # below the switchbox (east) + if eastbound > 0: + c.draw_line((xoffset + 6, yoffset + 6), (xoffset + 6, yoffset + 8)) + if draw_demand: + c.draw_character((xoffset + 5, yoffset + 7), superscripts[eastbound]) + if eastbound > 4: # if overcapacity, mark with an 'x' + c.draw_character((xoffset + 6, yoffset + 6), "x") + # c.draw_character((xoffset+6, yoffset+7), 'x') + c.draw_character((xoffset + 6, yoffset + 8), "x") + if westbound > 0: + c.draw_line((xoffset + 8, yoffset + 1), (xoffset + 8, yoffset + 3)) + if draw_demand: + c.draw_character((xoffset + 9, yoffset + 2), superscripts[westbound]) + if westbound > 4: # if overcapacity, mark with an 'x' + c.draw_character((xoffset + 8, yoffset + 1), "x") + # c.draw_character((xoffset+7, yoffset+2), 'x') + c.draw_character((xoffset + 8, yoffset + 3), "x") + + +SB_WIDTH = 10 +SB_HEIGHT = 5 # distances between switchboxes + + +def draw_switchboxes(c, switchboxes): + for item in switchboxes: + draw_switchbox( + c, + SB_WIDTH * item["row"], + SB_HEIGHT * item["col"], + item["source_count"], + item["destination_count"], + item["northbound"], + item["southbound"], + item["eastbound"], + item["westbound"], + draw_demand=True, + name="{},{}".format(item["col"], item["row"]), + ) + + +# given a route, draw arrow characters to indicate the route +# route is a list of switchboxes, represented as int tuple coordinates +left_arrow = "\u2190" +up_arrow = "\u2191" +right_arrow = "\u2192" +down_arrow = "\u2193" + + +def draw_route(c, route): + for i in range(len(route) - 1): + col = route[i][0][0] + row = route[i][0][1] + xoffset = SB_WIDTH * row + yoffset = SB_HEIGHT * col + if len(route[i]) == 1: + continue + dirs = route[i][1] + + # draw source and destination + if i == 0: + c.draw_character((xoffset + 5, yoffset + 5), "S") + if i == (len(route) - 2): + c.draw_character((xoffset + 9, yoffset + 5), "D") + + if i == 0: + if row == 0: # for routes starting in the shim, draw arrows coming from PL + c.draw_character((xoffset + 1, yoffset + 4), right_arrow) + c.draw_character((xoffset + 2, yoffset + 4), right_arrow) + c.draw_character((xoffset + 3, yoffset + 4), right_arrow) + + for j in range(len(dirs)): + # draw indications for cores the route passes through + c.replace_character((xoffset + 7, yoffset + 5), "*", "#") + # 0 = North, 1 = East, 2 = South, 3 = West + if dirs[j] == "North": + c.draw_character((xoffset + 11, yoffset + 4), right_arrow) + c.draw_character((xoffset + 12, yoffset + 4), right_arrow) + c.draw_character((xoffset + 13, yoffset + 4), right_arrow) + row = row + 1 + elif dirs[j] == "East": + c.draw_character((xoffset + 6, yoffset + 7), down_arrow) + col = col + 1 + elif dirs[j] == "South": + c.draw_character((xoffset + 1, yoffset + 5), left_arrow) + c.draw_character((xoffset + 2, yoffset + 5), left_arrow) + c.draw_character((xoffset + 3, yoffset + 5), left_arrow) + row = row - 1 + elif dirs[j] == "West": + c.draw_character((xoffset + 8, yoffset + 2), up_arrow) + col = col - 1 + elif dirs[j] == "DMA": + # draw destination + c.draw_character((xoffset + 9, yoffset + 5), "D") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Draw switchboxes, demands and routes") + parser.add_argument("-j", "--json", help="Filepath for JSON file to read") + parser.add_argument("-r", "--route_list", help="List of routes to print") + parser.add_argument( + "-o", + "--output", + help="Path to output directory. Text files of the routes will be stored here.", + ) + args = parser.parse_args() + + if args.json: + json_file_path = args.json + else: + json_file_path = "switchbox.json" # default JSON + + with open(json_file_path) as f: + json_data = json.load(f) + + switchboxes = [] + routes = [] + + for key, item in json_data.items(): + if "switchbox" in key: + switchboxes.append(item) + if "route" in key: + routes.append(item) + + max_col = 0 + max_row = 0 + for switchbox in switchboxes: + if switchbox["col"] > max_col: + max_col = switchbox["col"] + if switchbox["row"] > max_row: + max_row = switchbox["row"] + + routes_to_print = [] + if args.route_list: + for route in args.route_list.split(","): + routes_to_print.append(int(route.strip())) + else: + routes_to_print = range(len(routes)) + + output_directory = "./routes/" + if args.output: + output_directory = args.output + + if not os.path.isdir(output_directory): + os.mkdir(output_directory) + + for i in routes_to_print: + c = canvas(12 * (max_row + 1), 5 + 5 * (max_col + 1)) + draw_switchboxes(c, switchboxes) + filename = os.path.join(output_directory, "route{}.txt".format(i)) + sys.stdout = sys.__stdout__ + print( + "Printing route {} of {}: {}".format(i, len(routes_to_print) - 1, filename) + ) + with open(filename, "w") as f: + sys.stdout = f + print("Route {}: {}".format(i, routes[i])) + draw_route(c, routes[i]) + c.rasterize() diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/Makefile b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/Makefile new file mode 100644 index 000000000..5297f08ed --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/Makefile @@ -0,0 +1,109 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +# MiniCPM5 prefill overlay: bfp16 dequant_mm (runtime m, fused GLU) + attention in one xclbin (see iron/overlay_aie.py). +# +# make kernel objects, base xclbin, txn dumps of both ops, op table, run.exe +# make bitstream build/xclbins/overlay.xclbin +# make regs host/op_configs.hpp (each op's configuration, from aiecc --aie-generate-txn) +# make host run.exe +# +# Needs the kernel env (AIETOOLS_ROOT, mlir-aie, PEANO_INSTALL_DIR). Peano by default; +# ENABLE_CHESSCC=1 builds the same design with chess. Run make clean_all when switching. + +HOME_DIR := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST)))) +ENABLE_CHESSCC ?= 0 +export ENABLE_CHESSCC +AIETOOLS_DIR ?= $(or $(AIETOOLS_ROOT),$(patsubst %/bin/,%,$(dir $(shell command -v xchesscc 2>/dev/null)))) +# Expanded only inside the Chess recipes, so it fires only for ENABLE_CHESSCC=1. +AIETOOLS_CHECK = $(if $(strip $(AIETOOLS_DIR)),,$(error ENABLE_CHESSCC=1 needs Vitis AIE Essentials: set AIETOOLS_ROOT (or AIETOOLS_DIR), or put xchesscc on PATH)) +AIEOPT_DIR ?= $(shell realpath $(dir $(shell which aie-opt))/..) + +WARNING_FLAGS = -Wno-parentheses -Wno-attributes -Wno-macro-redefined +CHESSCCWRAP2P_FLAGS = aie2p $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 +PEANOWRAP2P_FLAGS = -O2 -std=c++20 --target=aie2p-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG \ + -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 -I ${AIEOPT_DIR}/include +KERNEL_INCLUDES = -DNPU2 -I. -I${HOME_DIR}/kernel -I${HOME_DIR}/kernel/dq -I${HOME_DIR}/kernel/attn + +ifeq ($(ENABLE_CHESSCC),1) +AIECC_FLAGS := --no-compile-host --xchesscc --xbridge +else +AIECC_FLAGS := --no-compile-host --no-xchesscc --no-xbridge +endif + +LAYOUT_H := build/kernel/overlay_layout.h +KERNEL_OBJS := build/kernel/fused_e.o build/kernel/fused_o.o +KERNEL_SRCS := $(wildcard kernel/*.h kernel/*.cc kernel/dq/* kernel/attn/*) +IRON_SRC := $(wildcard iron/*.py) +XCLBIN := build/xclbins/overlay.xclbin +REGS := host/op_configs.hpp + +.PHONY: all kernel bitstream regs host clean_all +all: ${XCLBIN} ${REGS} run.exe +kernel: ${KERNEL_OBJS} +bitstream: ${XCLBIN} +regs: ${REGS} +host: run.exe + +${LAYOUT_H}: iron/layout.py + mkdir -p ${@D} + python3 $< > $@ + +build/kernel/%.o: kernel/%.cc ${KERNEL_SRCS} ${LAYOUT_H} +ifeq ($(ENABLE_CHESSCC),1) + cd ${@D} && xchesscc_wrapper ${CHESSCCWRAP2P_FLAGS} ${KERNEL_INCLUDES} -c ${HOME_DIR}/$< -o ${@F} +else + cd ${@D} && ${PEANO_INSTALL_DIR}/bin/clang++ ${PEANOWRAP2P_FLAGS} ${KERNEL_INCLUDES} -c ${HOME_DIR}/$< -o ${@F} +endif + +.PRECIOUS: build/mlir/%.mlir +build/mlir/%.mlir: ${IRON_SRC} + mkdir -p ${@D} + cd iron && python3 overlay_aie.py $* > ${HOME_DIR}/$@ + +# the xclbin that runs: core programs + arenas, no routes or chains +build/base/overlay.xclbin: build/mlir/base.mlir ${KERNEL_OBJS} + mkdir -p ${@D} + cp ${KERNEL_OBJS} ${@D} + cd ${@D} && aiecc.py ${AIECC_FLAGS} --aie-generate-cdo --aie-generate-xclbin \ + --xclbin-name=${@F} ../mlir/base.mlir > aiecc.log 2>&1 +ifneq ($(ENABLE_CHESSCC),1) + @python3 tools/check_stack.py ${PEANO_INSTALL_DIR}/bin/llvm-objdump 4096 build/base/base.mlir.prj/*.elf +endif +build/base/base.mlir.prj/input_with_addresses.mlir: build/base/overlay.xclbin + +${XCLBIN}: build/base/overlay.xclbin + mkdir -p ${@D} + cp $< $@ + +# each op's load-time configuration as register writes +build/%/txn.mlir: build/mlir/%.mlir ${KERNEL_OBJS} + mkdir -p ${@D} + cp ${KERNEL_OBJS} ${@D} + cd ${@D} && aiecc.py ${AIECC_FLAGS} --aie-generate-txn --txn-name=txn.mlir ../mlir/$*.mlir > aiecc.log 2>&1 + +${REGS}: tools/extract_txn2.py tools/check_memtile_bds.py build/dq/txn.mlir build/attn/txn.mlir build/base/base.mlir.prj/input_with_addresses.mlir + python3 tools/extract_txn2.py --base build/base/base.mlir.prj/input_with_addresses.mlir \ + --op dq=build/dq/txn.mlir --op attn=build/attn/txn.mlir -o $@.tmp + python3 tools/check_memtile_bds.py $@.tmp + mv $@.tmp $@ + +# ---- host --------------------------------------------------------------------- +HOST_COMMON_DIR := ../../host_common +CXX := g++-13 +CXX_FLAGS := -std=c++20 -O2 -fPIC -Wall -Wno-sign-compare -Wno-unused-variable -march=native -fopenmp +CXX_FLAGS += -Ihost -I$(HOST_COMMON_DIR) -I../../dequant_mm_bfp16_rtm2_glu_512x512x512/host -I/opt/xilinx/xrt/include -MMD -MP +LDFLAGS := -L/opt/xilinx/xrt/lib -L$(HOST_COMMON_DIR) -lxrt_coreutil $(HOST_COMMON_DIR)/../../../src/lib/xrt/libaiebu.a +LDFLAGS += -lboost_program_options -lboost_filesystem -fopenmp + +run.exe: build/host/host.o + $(CXX) $(CXX_FLAGS) $^ -o $@ $(LDFLAGS) + +build/host/host.o: host/host.cpp ${REGS} $(wildcard host/*.hpp) + @mkdir -p $(dir $@) + $(CXX) $(CXX_FLAGS) -c $< -o $@ + +-include build/host/host.d + +clean_all: + -rm -rf build run.exe ${REGS} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/README.md b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/README.md new file mode 100644 index 000000000..a1cc03b67 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/README.md @@ -0,0 +1,146 @@ + + +# prefill_overlay β€” MiniCPM5 dequant_mm (bfp16) and attention in one xclbin + +MiniCPM5-15B-A2.5B prefill alternates dequant_mm (k|v|q|gate, o, the routed and +shared experts) and attention in every layer. Between two separate xclbins +each change of op is a hardware context switch, ~2 ms. This overlay keeps both +ops in one xclbin; a switch costs **~0.1 ms**. + +| (Strix Halo, NPU2, Peano) | standalone xclbins | overlay | +|---|---|---| +| dequant_mm 2048 rows, 2048 -> 8704 (k\|v\|q\|gate) | 4846 us | 4771 us | +| dequant_mm 2048 rows, 4096 -> 2048 (o) | 2302 us | 2196 us | +| dequant_mm 2048 rows, 512 -> 2048 (expert down) | 487 us | 487 us | +| dequant_mm 2048 rows, 2048 -> 1024 + GLU (expert up\|gate) | 719 us | 674 us | +| attention, L 512, 32 q / 4 kv heads | β€” | 792 us | +| attention, L 2048 | β€” | 6.7 ms | +| switch dq <-> attention | ~2 ms (context switch) | 116 us | + +**dequant_mm** is the kernel of `../../dequant_mm_bfp16_rtm2_glu_512x512x512`: +Q4_K weights dequantized to bfp16 inside the matmul, activations in bfp16, +128 x 512 x 64 tiles, 32 cores. Two of its features: + +* **runtime m**: a dispatch of `rows` tokens runs `rtm_pick_geometry(rows)` + rounds of 4 x m rows (m 16 .. 128), so a routed expert with 40 tokens does not + pay for 512. The host re-arms the mem tiles' x / y descriptors for m before the + run and puts them back to m = 128 after it (`rtm_rearm`); the cores get m in + their RTP block. +* **fused GLU** (act 3): a core pair takes 32 up rows and the matching 32 gate + rows and writes `silu(gate) * up`, Dout / 2 columns. + +The overlay's copy differs in one thing: it reads the weight blocks in the order +the decode kernels keep them (`relaid`, `kernel/dq/q4_core.h`), so the engine +needs no second copy of the weights for prefill. For the GLU the decode keeps +up and gate interleaved in pieces of 64 (routed experts) or 256 (shared expert) +rows; `glu_gather_dma` gathers each core pair's [up | gate] blocks from there +with the shim DMA, no repacking. Both copies round with `conv_even`, so the +overlay's output is bit for bit the standalone's. + +**attention** is the Hy-Memory prefill attention kernel (online softmax, dh 128, +GQA, KV cache in the decode layout) on all 32 cores: 4 CUs of 2 columns, one q +head each per round (8 heads per round). A CU's q comes from its even column's +shim and mem tile; the two CUs of a half of the array (columns 0-3, 4-7) share +one KV head, streamed from shim 3 / 7 through mem tile 3 / 7 to all 16 cores of +the half (GQA needs an even number of q heads per KV head). + +## How it works + +An xclbin fixes the stream routes, DMA BDs and lock values at load time, and the +two ops need different ones (they feed the same core ports from different mem +tiles). So the xclbin only holds what both ops share, and the host writes the +rest into the array when the op changes. + +* **base xclbin** (`iron/overlay_aie.py base`): per core an *arena* (one buffer + both ops lay their buffers into, `iron/layout.py`), an RTP block and an op + lock; per mem tile an arena; the core programs. No routes, no DMA chains. +* **op variants** (`overlay_aie.py dq | attn`): base + that op's original locks, + chains and routes (`iron/dq_tiles.py`, `iron/attn_tiles.py`). Never run: + `aiecc --aie-generate-txn` dumps their load-time configuration as register + writes, `tools/extract_txn2.py` turns it into `host/op_configs.hpp`. + `tools/check_memtile_bds.py` then checks that the dq op's mem tile descriptor + ids, lengths, channel starts and lock values are the ones `rtm_rearm` rewrites. +* **switch** (`host/overlay_host.hpp`, `gen_switch`): reset the old op's DMA + channels (they loop forever on a lock), write the routing registers that + differ, the shared BDs, the lock values, then start the new op's chains. +* **core program** (`kernel/fused_e.cc`, `fused_o.cc`): both kernels in one + object, each `#include`d inside its own namespace. `kernel/dispatch.h` waits on + the op lock, reads the RTP block (op, number of calls, "just switched", dq's + K / 512, m / 16 and act), resets the op's ping/pong flags after a switch (the + chains restart at ping), and runs the op's kernel calls. +* **rounding mode**: `aie::set_rounding` is per-core state that lasts across + calls; both kernels set `conv_even` themselves. A kernel added here must set + its own mode too. + +A run of an op = [switch if needed] + [dq: re-arm for m / GLU] + RTP blocks + +op lock = 1 on the op's cores + the op's usual shim DMAs + [dq: re-arm back to +m = 128] (`gen_dq_run`, `gen_attn_run`). + +## Rules for the caller + +* Keep `configured` (the op the array is set up for) across runs. +* **After any other xclbin ran** (decode layers, lm_head), pass `configured = -1`: + the NPU reloads the overlay and everything the host wrote is gone. A partial + switch then hangs (`qds_device::wait() unexpected command state`). +* **On HRX, every run is a full switch** (`configured = -1` for each run). HRX + manages the hw contexts itself and may destroy the overlay's context and create + a new one between two runs of the overlay alone (seen right after it releases an + executable built before): the same reload, with no other xclbin in between, so + the caller cannot tell when it happens. The full switch costs ~6% of a 2K + prefill (measured on XRT, bit-identical output). +* A dq run computes `rtm_pick_geometry(rows).covered` rows: x and y must span + that many (the extra rows' outputs are whatever their x gives). + +## Build and test + +``` +export MLIR_AIE_DIR=/path/to/mlir-aie +export PEANO_INSTALL_DIR=/path/to/llvm-aie-22.0.0.2026090201/llvm-aie # the pinned Peano +source ../../setup.sh # FLM_Xclbin/setup.sh +make # kernels, base xclbin, both txn dumps, op table (+ check), run.exe +./run.exe # --iters N (timing), --soak N (dispatches per shape), + # --attn-l L (attention rows = keys, default 512; e.g. 8192) +``` + +`run.exe` needs `../../dequant_mm_bfp16_rtm2_glu_512x512x512` built (`make +bitstream` there): it is the bit-exact dequant_mm reference. It checks + +1. MiniCPM5's five dequant_mm shapes (k|v|q|gate, o, expert down, routed and + shared up|gate with the fused GLU) at 64 .. 2048 rows, bit for bit against + the standalone at m = 128, nothing written past the covered rows; and each + against an fp64 reference (rel-rms ~1.6-1.9%, GLU ~3.0-3.2%; plain + host GLU + is printed beside it, ~2.7-2.8%); +2. switches dq <-> attention both ways, next to reduced m and GLU runs; + attention against the CPU (cos >= 0.999) and its own first run; +3. a soak: 400 dispatches per shape, shapes and row counts shuffled; +4. speed, and the switch cost. + +Result 2026-12-03: PASSED, soak 2000 / 2000; attention cos 0.99945 (L 512), +0.99941 (2048), 0.99960 (8192). + +The engine (`FLM_DLL/detail/minicpm5_moe_npu`) keeps a copy of the op table: +copy `host/op_configs.hpp` to its `minicpm5_moe_overlay_configs.hpp` after a +rebuild. Its `RTP_*` constants must match `iron/layout.py`. + +## Peano + +Peano is the default (`ENABLE_CHESSCC ?= 0`). Notes carried over from the +attention kernel's earlier overlays: + +* `kernel/attn/attn.cc`: no function-local `static const` vectors. Peano's + loader does not zero `.bss`, so a static's "already built" guard can read as + true and the vector is never built. +* the ping/pong flags use `AIE_PING_FLAG` (in `.data`, volatile: Peano does not + treat a lock acquire as a barrier for a flag it can prove). +* `tools/check_stack.py` checks the deepest call chain of both kernels against + the 4 KB stack (every build). + +## Not done yet + +* Attention at very long KV: cos 0.989 but NMSE 1.8 at 128K keys (the online + softmax rescale is kept in bf16); fine to ~8K. +* Fewer writes per switch: lock values only where they change, a block-write + instruction in `npu_sequence`. diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/attn_ref.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/attn_ref.hpp new file mode 100644 index 000000000..20f539392 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/attn_ref.hpp @@ -0,0 +1,135 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#pragma once +/// \file attn_ref.hpp +/// \brief CPU golden reference for the Hy-MT2-1.8B prefill attention kernel. +/// +/// The NPU kernel (kernel/attn.cc + kernel/attn_kernel.h) implements a flash +/// attention with GQA. This file re-implements the same math in fp32 so the NPU +/// result can be checked against it. +/// +/// Data layouts (all row major, matching what the host feeds to the NPU): +/// q : [L_q ][n_q_heads * dh] row r is global token (L_begin + r) +/// k : [L_kv][n_kv_heads * dh] row r is global token r +/// v : [L_kv][n_kv_heads * dh] row r is global token r +/// o : [L_q ][n_q_heads * dh] row r is global token (L_begin + r) +/// +/// Mask: kernel/attn_kernel.h::apply_mask_and_get_max keeps score(q, k) when +/// k <= q and k > q - window_size +/// i.e. causal, plus a sliding window lower bound. The kernel is launched with +/// window_size == MAX_L when is_sliding_window is false, which makes the lower +/// bound inactive (plain causal attention). + +#include +#include +#include +#include "typedef.hpp" + +/// \brief shape / masking description of the attention to reproduce +struct attn_ref_config { + /// \brief head dimension (128 for Hy-MT2) + int dh = 128; + /// \brief number of query heads (16 for Hy-MT2) + int n_q_heads = 16; + /// \brief number of key/value heads (4 for Hy-MT2, GQA 1:4) + int n_kv_heads = 4; + /// \brief sliding window size; pass >= sequence length for plain causal + int window_size = 1 << 30; + /// \brief softmax scale applied to q.k, must match `scale` in kernel/common.h + float scale = 0.08838834764831843f; +}; + +/// \brief fp32 causal (optionally windowed) GQA attention reference +/// \param o output buffer, [L_q][n_q_heads * dh], written as bf16 +/// \param q query buffer, [L_q][n_q_heads * dh], rows start at global L_begin +/// \param k key buffer, [L_kv][n_kv_heads * dh], rows start at global 0 +/// \param v value buffer, [L_kv][n_kv_heads * dh], rows start at global 0 +/// \param L_q number of query rows to compute +/// \param L_begin global position of the first query row +/// \param cfg shape / masking description +inline void attn_cpu_ref( + buffer& o, + const buffer& q, + const buffer& k, + const buffer& v, + const int L_q, + const int L_begin, + const attn_ref_config& cfg +){ + const int dh = cfg.dh; + const int DQ = cfg.n_q_heads * dh; + const int DK = cfg.n_kv_heads * dh; + // GQA: q head h reads kv head h / q_per_kv + const int q_per_kv = cfg.n_q_heads / cfg.n_kv_heads; + assert(cfg.n_q_heads % cfg.n_kv_heads == 0); + assert((int)o.size() >= L_q * DQ); + assert((int)q.size() >= L_q * DQ); + + // Widen the inputs to fp32 up front: the whole reference then runs on + // contiguous floats, which is what lets the inner loops vectorize. + const int L_kv = L_begin + L_q; + assert((int)k.size() >= (size_t)L_kv * DK); + assert((int)v.size() >= (size_t)L_kv * DK); + std::vector qf((size_t)L_q * DQ); + std::vector kf((size_t)L_kv * DK); + std::vector vf((size_t)L_kv * DK); + for (size_t i = 0; i < qf.size(); i++) qf[i] = (float)q.data()[i]; + for (size_t i = 0; i < kf.size(); i++) kf[i] = (float)k.data()[i]; + for (size_t i = 0; i < vf.size(); i++) vf[i] = (float)v.data()[i]; + + // rows are independent (8K keys take minutes on one thread) + #pragma omp parallel for schedule(dynamic, 16) + for (int r = 0; r < L_q; r++) { + std::vector scores; + std::vector acc(dh); + const int q_pos = L_begin + r; + // causal upper bound, sliding window lower bound (both inclusive) + const int k_hi = q_pos; + const int k_lo = std::max(0, q_pos - cfg.window_size + 1); + const int n_k = k_hi - k_lo + 1; + scores.resize(n_k); + + for (int h = 0; h < cfg.n_q_heads; h++) { + const float* q_row = qf.data() + (size_t)r * DQ + (size_t)h * dh; + const int kv_h = h / q_per_kv; + const float* k_base = kf.data() + (size_t)k_lo * DK + (size_t)kv_h * dh; + const float* v_base = vf.data() + (size_t)k_lo * DK + (size_t)kv_h * dh; + + // s = scale * q . k, keeping the running max for a stable softmax + float m = -std::numeric_limits::infinity(); + for (int j = 0; j < n_k; j++) { + const float* k_row = k_base + (size_t)j * DK; + float dot = 0.0f; + for (int e = 0; e < dh; e++) { + dot += q_row[e] * k_row[e]; + } + const float s = dot * cfg.scale; + scores[j] = s; + m = s > m ? s : m; + } + + // p = exp(s - m), l = sum(p) + float l = 0.0f; + for (int j = 0; j < n_k; j++) { + const float p = std::exp(scores[j] - m); + scores[j] = p; + l += p; + } + + // y = p . v, o = y / l + std::fill(acc.begin(), acc.end(), 0.0f); + for (int j = 0; j < n_k; j++) { + const float* v_row = v_base + (size_t)j * DK; + const float p = scores[j]; + for (int e = 0; e < dh; e++) { + acc[e] += p * v_row[e]; + } + } + const float inv_l = 1.0f / l; + bf16* o_row = o.data() + (size_t)r * DQ + (size_t)h * dh; + for (int e = 0; e < dh; e++) { + o_row[e] = (bf16)(acc[e] * inv_l); + } + } + } +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/host.cpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/host.cpp new file mode 100644 index 000000000..c2761aaa9 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/host.cpp @@ -0,0 +1,455 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +// Test of the MiniCPM5 prefill overlay: bfp16 dequant_mm (runtime m, fused GLU) and +// attention in ONE xclbin. +// +// 1. dequant_mm, MiniCPM5's shapes, row counts 64 .. 2048: bit for bit against the +// standalone dequant_mm_bfp16_rtm2_glu_512x512x512 at 2048 rows (m = 128). That +// kernel does the same arithmetic on plain-order blocks; the overlay reads the +// relaid blocks the engine keeps for decode. Also against an fp64 reference. +// Fused GLU: the overlay gathers [up | gate] from the engine's piece layout +// (glu_gather_dma); its sigmoid (exp2) is not the standalone's (tanh), so row counts +// are bit for bit against the overlay's own 2048-row run, and both are scored against +// fp64 beside plain dispatch + host GLU (the engine's fallback). +// 2. switches dq <-> attn in both directions (dq at reduced m and GLU next to a switch): +// dq bit for bit as above, attention (--attn-l rows, causal, as many keys) against +// the CPU reference (cos >= 0.999) and its first run +// 3. soak: --soak dispatches per shape, row counts and shapes in random order, each +// bit for bit against its first run +// 4. speed: overlay vs standalone per shape +// +// run.exe [--iters N] [--soak N] [--attn-l L] + +#include +#include +#include "typedef.hpp" +#include "npu_utils/npu_utils.hpp" +#include "metrices.hpp" +#include "cpu_q4_k.hpp" // dequant_mm_bfp16_rtm2_glu_512x512x512/host +#include "util.hpp" // reorder_cpy +#include "seq_gen.hpp" // gen_dequant_mm_rtm, glu_repack (standalone) +#include "attn_ref.hpp" // attn_cpu_ref +#include "overlay_host.hpp" + +namespace po = boost::program_options; +using clk = std::chrono::steady_clock; + +static constexpr uint32_t LMAX = 2048; +static const bf16 SENTINEL = bf16(12345.0f); + +template +static double time_us(F&& f, int iters) { + for (int i = 0; i < 2; i++) f(); + clk::time_point t0 = clk::now(); + for (int i = 0; i < iters; i++) f(); + return std::chrono::duration(clk::now() - t0).count() / iters; +} + +/// @brief every 32 x 256 block into the decode kernel's order, in place +/// @note Mirrors q4k_relayout_for_mmul in +/// FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_model_def.cpp, which lays out +/// MiniCPM5's weights. The overlay's dequant_mm reads this order +/// (kernel/dq/q4_core.h), the standalone the plain one. +static void relayout_for_mmul(u8* data, size_t bytes) { + constexpr size_t BLOCK = 4736, SCALES = 0, QS = 512; + assert(bytes % BLOCK == 0); + for (size_t b = 0; b < bytes / BLOCK; b++) { + u8* blk = data + b * BLOCK; + std::array old; + memcpy(old.data(), blk, BLOCK); + for (int k = 0; k < 16; k++) // 16 columns per k step + for (int t = 0; t < 2; t++) // rows 16t .. 16t+15 + for (int c = 0; c < 16; c++) + memcpy(blk + QS + (k * 2 + t) * 128 + c * 8, + old.data() + QS + (k * 16 + c) * 16 + t * 8, 8); + for (int h = 0; h < 2; h++) + for (int t = 0; t < 2; t++) + for (int a = 0; a < 4; a++) + memcpy(blk + SCALES + ((h * 2 + t) * 4 + a) * 16, + old.data() + SCALES + (4 * h + a) * 32 + 16 * t, 16); + } +} + +/// @brief one MiniCPM5 dequant_mm shape: random q4_k weights, the standalone's and +/// the overlay's copies of them, and the dequantized weights for fp64 references. +/// GLU shapes (act 3) are one expert's up|gate: canonical rows [up 512 | gate 512] +/// (glu_repack's slab); the engine keeps them as [up piece | gate piece] repeated +/// (interleave_up_gate in minicpm5_moe_model_def.cpp), the same 32-row blocks moved. +struct dq_case { + const char* name; + uint32_t Din, Dout; + int act; + uint32_t piece; // GLU: rows per [up | gate] piece of the engine layout + uint32_t Dy; + std::vector w_deq; // [Dout][Din], canonical row order + buffer plain; // packed q4_k, canonical row order, [row block][column block] + + dq_case(const char* name, uint32_t Din, uint32_t Dout, int act, uint32_t piece, uint32_t seed) + : name(name), Din(Din), Dout(Dout), act(act), piece(piece), Dy(act == overlay::DQ_ACT_GLU ? Dout / 2 : Dout) { + buffer w((size_t)Dout * Din), wd((size_t)Dout * Din); + plain = buffer(q4_k_size((size_t)Din * Dout)); + std::mt19937 rng(seed); + std::normal_distribution dist(0.0f, 0.02f); + for (size_t i = 0; i < w.size(); i++) w[i] = bf16(dist(rng)); + q4_k_quantize_pack(plain.data(), wd.data(), w.data(), Dout, Din); + w_deq.assign(wd.data(), wd.data() + wd.size()); + } + bool glu() const { return act == overlay::DQ_ACT_GLU; } + size_t bytes() const { return plain.size(); } + + /// the standalone's weights: pairs layout, glu_repack()ed for the GLU + void fill_standalone(u8* dst) { + if (!glu()) { reorder_cpy(dst, plain, Din, 2); return; } + std::vector pairs(bytes()); + reorder_cpy(pairs.data(), plain, Din, 2); + ::glu_repack(dst, pairs.data(), Din, Dout); + } + /// the overlay's weights: what the engine keeps (engine row order, pairs layout, relaid) + void fill_overlay(u8* dst) { + buffer eng(bytes()); + const size_t rb_bytes = bytes() / (Dout / QXNX_ROW_BLOCK_SIZE); + if (!glu()) { + memcpy(eng.data(), plain.data(), bytes()); + } else { + const uint32_t half = Dout / 2 / QXNX_ROW_BLOCK_SIZE, pb = piece / QXNX_ROW_BLOCK_SIZE; + assert(Dout == 1024 && piece % QXNX_ROW_BLOCK_SIZE == 0); + u8* o = eng.data(); + for (uint32_t q = 0; q < half / pb; q++) + for (uint32_t g = 0; g < 2; g++) // up, then gate + for (uint32_t b = 0; b < pb; b++, o += rb_bytes) + memcpy(o, plain.data() + (size_t)(g * half + q * pb + b) * rb_bytes, rb_bytes); + } + reorder_cpy(dst, eng, Din, 2); + relayout_for_mmul(dst, bytes()); + } + /// fp64 truth of the first `rows` rows: y (plain) or silu(gate) * up (GLU) + std::vector truth(const bf16* x, int rows) const { + std::vector t((size_t)rows * Dy); + #pragma omp parallel for collapse(2) + for (int l = 0; l < rows; l++) + for (uint32_t n = 0; n < Dy; n++) { + auto dot = [&](uint32_t r) { + double a = 0; + for (uint32_t k = 0; k < Din; k++) a += (double)(float)x[(size_t)l * Din + k] * (float)w_deq[(size_t)r * Din + k]; + return a; + }; + if (!glu()) { t[(size_t)l * Dy + n] = dot(n); continue; } + const double up = dot(n), gate = dot(Dout / 2 + n); + t[(size_t)l * Dy + n] = up * gate / (1.0 + std::exp(-gate)); + } + return t; + } +}; + +static double rel_rms(const bf16* got, const std::vector& truth) { + double e = 0, r = 0; + for (size_t i = 0; i < truth.size(); i++) { + const double d = (double)(float)got[i] - truth[i]; + e += d * d; + r += truth[i] * truth[i]; + } + return std::sqrt(e / r); +} + +/// rows of `got` (pitch width) that differ from `ref` in the first `rows` +static size_t rows_differing(const bf16* got, const bf16* ref, uint32_t rows, uint32_t width) { + size_t n = 0; + for (uint32_t l = 0; l < rows; l++) n += memcmp(got + (size_t)l * width, ref + (size_t)l * width, width * sizeof(bf16)) != 0; + return n; +} + +/// rows in [from, to) that are no longer all SENTINEL +static size_t rows_written(const bf16* y, uint32_t from, uint32_t to, uint32_t width) { + size_t n = 0; + for (uint32_t l = from; l < to; l++) + for (uint32_t i = 0; i < width; i++) + if (std::bit_cast(y[(size_t)l * width + i]) != std::bit_cast(SENTINEL)) { n++; break; } + return n; +} + +int main(int argc, char** argv) { + po::options_description desc("Allowed options"); + desc.add_options()("iters,i", po::value()->default_value(20), "timing iterations") + ("soak", po::value()->default_value(400), "soak dispatches per shape") + ("attn-l", po::value()->default_value(512), "attention query rows = keys (multiple of 128)"); + po::variables_map vm; + po::store(po::parse_command_line(argc, argv, desc), vm); + po::notify(vm); + const int ITERS = vm["iters"].as(); + const int SOAK = vm["soak"].as(); + const int AL = vm["attn-l"].as(); + + xrt::device device(0); + npu_xclbin_manager mgr(device_npu2, &device, false); + npu_app_manager* std_mgr = mgr.register_xclbin("../../dequant_mm_bfp16_rtm2_glu_512x512x512/build/xclbins/dequant_mm.xclbin"); + npu_app_manager* ovl_mgr = mgr.register_xclbin("build/xclbins/overlay.xclbin"); + + // ---- MiniCPM5's dequant_mm shapes ------------------------------------------------ + std::vector> cases; + cases.push_back(std::make_unique("k|v|q|gate 2048 -> 8704", 2048, 8704, 0, 0, 1)); + cases.push_back(std::make_unique("o 4096 -> 2048", 4096, 2048, 0, 0, 2)); + cases.push_back(std::make_unique("expert down 512 -> 2048", 512, 2048, 0, 0, 3)); + cases.push_back(std::make_unique("expert up|gate GLU (pieces 64)", 2048, 1024, 3, 64, 4)); + cases.push_back(std::make_unique("shared up|gate GLU (pieces 256)", 2048, 1024, 3, 256, 5)); + const std::vector rowsets = {64, 128, 200, 264, 512, 520, 1032, 1536, 2048}; + const uint32_t DIN_MAX = 4096, DY_MAX = 8704; + + buffer x_host((size_t)LMAX * DIN_MAX); + { + std::mt19937 rng(99); + std::normal_distribution xd(0.0f, 1.0f); + for (size_t i = 0; i < x_host.size(); i++) x_host[i] = bf16(xd(rng)); + } + // x is [LMAX][Din] for every shape: the first LMAX * Din values of x_host + + // ---- attention data (32 q / 4 kv heads, dh 128, decode KV layout) ------------------ + if (AL % 128 != 0 || AL <= 0) { std::cout << "--attn-l must be a positive multiple of 128" << std::endl; return 1; } + const int MAX_L = std::max(1024, AL), HEADS = 32, KV_HEADS = 4, DH = 128, PER_COL = 2; + const int DQ = HEADS * DH, DK = KV_HEADS * DH; + const int KV_CACHE_SIZE = MAX_L * 2 * DK; + buffer q_host((size_t)AL * DQ), k_host((size_t)AL * DK), v_host((size_t)AL * DK); + { + std::mt19937 rng(32); + std::normal_distribution dist(0.0f, 1.0f); + for (size_t i = 0; i < q_host.size(); i++) q_host[i] = (bf16)dist(rng); + for (size_t i = 0; i < k_host.size(); i++) k_host[i] = (bf16)dist(rng); + for (size_t i = 0; i < v_host.size(); i++) v_host[i] = (bf16)dist(rng); + } + buffer kv_host(KV_CACHE_SIZE); + for (int i = 0; i < KV_CACHE_SIZE; i++) kv_host[i] = (bf16)((i & 1) ? 64.0f : -64.0f); // finite junk past L + for (int j = 0; j < AL; j++) { + for (int h = 0; h < KV_HEADS; h++) { + const size_t row = (size_t)j * PER_COL * DH + (size_t)(h % PER_COL) * DH; + const size_t kb = (size_t)(h / PER_COL) * MAX_L * PER_COL * DH; // [K col0][K col1] + const size_t vb = (size_t)(2 + h / PER_COL) * MAX_L * PER_COL * DH; // [V col0][V col1] + memcpy(kv_host.data() + kb + row, k_host.data() + (size_t)j * DK + h * DH, DH * sizeof(bf16)); + memcpy(kv_host.data() + vb + row, v_host.data() + (size_t)j * DK + h * DH, DH * sizeof(bf16)); + } + } + buffer o_cpu((size_t)AL * DQ); + { + attn_ref_config cfg; + cfg.dh = DH; + cfg.n_q_heads = HEADS; + cfg.n_kv_heads = KV_HEADS; + cfg.window_size = MAX_L; + cfg.scale = 1.0f / std::sqrt((float)DH); + attn_cpu_ref(o_cpu, q_host, k_host, v_host, AL, 0, cfg); + } + + bool pass = true; + std::cout << std::fixed; + + // ---- standalone references, all first: the overlay must start from a full + // switch after another xclbin ran ------------------------------------------------ + std::vector> ref(cases.size()); + std::vector t_std(cases.size()); + { + npu_app std0 = std_mgr->create_app(); + buffer s_x = std0.create_bo_buffer((size_t)LMAX * DIN_MAX); + buffer s_y = std0.create_bo_buffer((size_t)LMAX * DY_MAX); + s_x.copy_from(x_host.data(), x_host.size()); + s_x.sync_to_device(); + for (size_t ci = 0; ci < cases.size(); ci++) { + dq_case& c = *cases[ci]; + npu_app app = std_mgr->create_app(); + gen_dequant_mm_rtm(app.seq(), LMAX, c.Din, c.Dout, 0, 0, c.act); + buffer s_w = std0.create_bo_buffer(c.bytes()); + c.fill_standalone(s_w.data()); + s_w.sync_to_device(); + s_y.memset(SENTINEL); + s_y.sync_to_device(); + ert_cmd_state st = app(s_y, s_x, s_w); + s_y.sync_from_device(); + if (st != ERT_CMD_STATE_COMPLETED) { std::cout << "[ref] " << c.name << ": state " << app.cmd_state_map[st] << std::endl; return 1; } + ref[ci].assign(s_y.data(), s_y.data() + (size_t)LMAX * c.Dy); + t_std[ci] = time_us([&] { app(s_y, s_x, s_w); }, ITERS); + } + } + + // ---- overlay buffers and apps -------------------------------------------------------- + int cfg = -1; + npu_app first = ovl_mgr->create_app(); + overlay::gen_dq_run(first.seq(), cfg, LMAX, cases[0]->Din, cases[0]->Dout, 0, 0, 0); // full switch (fresh xclbin) + buffer o_x = first.create_bo_buffer((size_t)LMAX * DIN_MAX); + buffer o_y = first.create_bo_buffer((size_t)LMAX * DY_MAX); + o_x.copy_from(x_host.data(), x_host.size()); + o_x.sync_to_device(); + std::vector> o_w; + for (auto& c : cases) { + o_w.push_back(first.create_bo_buffer(c->bytes())); + c->fill_overlay(o_w.back().data()); + o_w.back().sync_to_device(); + } + buffer o_o = first.create_bo_buffer((size_t)AL * DQ); + buffer o_q = first.create_bo_buffer((size_t)AL * DQ); + buffer o_kv = first.create_bo_buffer(KV_CACHE_SIZE); + o_q.copy_from(q_host.data(), q_host.size()); + o_kv.copy_from(kv_host.data(), kv_host.size()); + o_q.sync_to_device(); + o_kv.sync_to_device(); + + // a dq app that expects the array configured as `from` + auto make_dq = [&](int from, size_t ci, uint32_t rows) { + auto app = std::make_unique(ovl_mgr->create_app()); + const dq_case& c = *cases[ci]; + overlay::gen_dq_run(app->seq(), from, rows, c.Din, c.Dout, 0, 0, c.act, c.glu() ? c.piece : 0); + return app; + }; + auto make_attn = [&](int from) { + auto app = std::make_unique(ovl_mgr->create_app()); + overlay::gen_attn_run(app->seq(), from, 0, AL, MAX_L, MAX_L, 16, DH, HEADS, KV_HEADS, PER_COL, KV_CACHE_SIZE); + return app; + }; + // run a dq app; bit for bit against the standalone on `rows` rows, nothing past `covered` written + auto run_dq = [&](npu_app& app, size_t ci, uint32_t rows, const std::string& label, bool quiet = false) { + const dq_case& c = *cases[ci]; + const uint32_t covered = overlay::rtm_pick_geometry(rows).covered; + std::fill(o_y.data(), o_y.data() + (size_t)LMAX * c.Dy, SENTINEL); + o_y.sync_to_device(); + ert_cmd_state st = app(o_y, o_x, o_w[ci]); + o_y.sync_from_device(); + const size_t bad = rows_differing(o_y.data(), ref[ci].data(), rows, c.Dy); + const size_t over = rows_written(o_y.data(), covered, LMAX, c.Dy); + const bool ok = st == ERT_CMD_STATE_COMPLETED && bad == 0 && over == 0; + if (!ok || !quiet) + std::cout << "[check] " << std::left << std::setw(44) << label << " rows " << std::setw(5) << rows + << (st == ERT_CMD_STATE_COMPLETED ? "" : " state " + std::string(app.cmd_state_map[st])) + << " rows != ref " << bad << ", written past covered " << over << (ok ? " OK" : " FAIL") << std::endl; + return ok; + }; + std::vector attn_first; + auto run_at = [&](npu_app& app, const std::string& label) { + o_o.memset((bf16)-1.0f); + o_o.sync_to_device(); + ert_cmd_state st = app(o_o, o_q, o_kv); + o_o.sync_from_device(); + buffer g((size_t)AL * DQ), c((size_t)AL * DQ); + g.copy_from(o_o.data(), g.size()); + c.copy_from(o_cpu.data(), c.size()); + error_metrics m = get_error_metrics(g, c); + if (attn_first.empty()) attn_first.assign(o_o.data(), o_o.data() + g.size()); + const size_t diff = rows_differing(o_o.data(), attn_first.data(), AL, DQ); + const bool ok = st == ERT_CMD_STATE_COMPLETED && m.CosineSimilarity >= 0.999f && diff == 0; + std::cout << "[check] " << std::left << std::setw(44) << label << " cos vs CPU " << std::setprecision(6) + << m.CosineSimilarity << ", rows != first run " << diff << (ok ? " OK" : " FAIL") << std::endl; + return ok; + }; + + // ---- 1. shapes x row counts, bit for bit; fp64 error ------------------------------ + // apps[ci][ri]: built for an array configured for dq (they run back to back) + std::vector>> apps(cases.size()); + for (size_t ci = 0; ci < cases.size(); ci++) + for (uint32_t rows : rowsets) apps[ci].push_back(make_dq(overlay::OP_DQ, ci, rows)); + pass &= run_dq(first, 0, LMAX, std::string(cases[0]->name) + " (full switch)"); + const int NT = 32; // rows scored against fp64 + for (size_t ci = 0; ci < cases.size(); ci++) { + dq_case& c = *cases[ci]; + const std::vector t = c.truth(x_host.data(), NT); + double e_std = 0; + if (c.glu()) { + // the overlay's GLU takes sigmoid from exp2, the standalone's from tanh: the overlay's + // own m = 128 run (LMAX rows) is the reference every row count matches bit for bit + e_std = rel_rms(ref[ci].data(), t); + std::fill(o_y.data(), o_y.data() + (size_t)LMAX * c.Dy, SENTINEL); + o_y.sync_to_device(); + (*apps[ci].back())(o_y, o_x, o_w[ci]); + o_y.sync_from_device(); + ref[ci].assign(o_y.data(), o_y.data() + (size_t)LMAX * c.Dy); + } + for (size_t ri = 0; ri < rowsets.size(); ri++) pass &= run_dq(*apps[ci][ri], ci, rowsets[ri], c.name); + const double e = rel_rms(ref[ci].data(), t); + std::cout << "[fp64] " << std::left << std::setw(45) << c.name << " rel-rms " << std::setprecision(4) << 100 * e << " %"; + if (c.glu()) std::cout << " (standalone, tanh silu " << 100 * e_std << " %)"; + bool ok = e < (c.glu() ? 0.035 : 0.025); + if (c.glu()) { + // the engine's fallback: plain dispatch on the same weights, host GLU (silu + // rounded to bf16, then * up: minicpm5_moe_cpu_functions.hpp silu_glu_row) + npu_app plain = ovl_mgr->create_app(); + int from = overlay::OP_DQ; + overlay::gen_dq_run(plain.seq(), from, LMAX, c.Din, c.Dout, 0, 0, 0); + o_y.sync_to_device(); + plain(o_y, o_x, o_w[ci]); + o_y.sync_from_device(); + std::vector hid((size_t)NT * c.Dy); + for (int l = 0; l < NT; l++) { + const bf16* f = o_y.data() + (size_t)l * c.Dout; + for (uint32_t s = 0; s < c.Dy / c.piece; s++) + for (uint32_t i = 0; i < c.piece; i++) { + const float up = (float)f[s * 2 * c.piece + i], g = (float)f[s * 2 * c.piece + c.piece + i]; + const float silu = (float)(bf16)(g / (1.0f + std::exp(-g))); + hid[(size_t)l * c.Dy + s * c.piece + i] = (bf16)(silu * up); + } + } + std::cout << " (plain + host GLU " << 100 * rel_rms(hid.data(), t) << " %)"; + } + std::cout << (ok ? " OK" : " FAIL") << std::endl; + pass &= ok; + } + + // ---- 2. switches dq <-> attn --------------------------------------------------------- + { + auto at_sw = make_attn(overlay::OP_DQ); + auto at_ns = make_attn(overlay::OP_ATTN); + auto glu_from_attn = make_dq(overlay::OP_ATTN, 3, 264); // GLU, m 80, right after attention + auto kvqg_from_attn = make_dq(overlay::OP_ATTN, 0, 520); // m 48 + auto down_from_attn = make_dq(overlay::OP_ATTN, 2, LMAX); // m 128 + auto o_full = make_dq(-1, 1, 1032); // full switch, from attention + pass &= run_at(*at_sw, "attn (switch from dq GLU)"); // the array is on dq, last run: GLU + pass &= run_at(*at_ns, "attn (no switch)"); + pass &= run_dq(*glu_from_attn, 3, 264, "dq GLU (switch from attn)"); + pass &= run_at(*at_sw, "attn (switch from dq GLU m 80)"); + pass &= run_dq(*kvqg_from_attn, 0, 520, "dq kvqg (switch from attn)"); + pass &= run_dq(*apps[4][3], 4, rowsets[3], "dq GLU (no switch)"); + pass &= run_dq(*apps[1][0], 1, rowsets[0], "dq o m 16 (no switch)"); + pass &= run_at(*at_sw, "attn (switch from dq m 16)"); + pass &= run_dq(*down_from_attn, 2, LMAX, "dq down (switch from attn)"); + pass &= run_at(*at_sw, "attn (switch from dq m 128)"); + pass &= run_dq(*o_full, 1, 1032, "dq o (full switch from attn)"); + pass &= run_dq(*apps[3][8], 3, rowsets[8], "dq GLU (no switch)"); + } + std::cout << "[check] " << (pass ? "PASSED" : "FAILED") << std::endl; + if (!pass) return 1; + + // ---- 3. soak ------------------------------------------------------------------------- + { + std::mt19937 rng(5); + std::vector> order; + for (size_t ci = 0; ci < cases.size(); ci++) + for (int k = 0; k < SOAK; k++) order.push_back({ci, k % rowsets.size()}); + std::shuffle(order.begin(), order.end(), rng); + size_t fails = 0; + const clk::time_point t0 = clk::now(); + for (auto [ci, ri] : order) fails += !run_dq(*apps[ci][ri], ci, rowsets[ri], cases[ci]->name, true); + std::cout << "[soak] " << order.size() << " dispatches (" << SOAK << " per shape, random shapes and row counts) in " + << std::setprecision(1) << std::chrono::duration(clk::now() - t0).count() << " s: " + << fails << " failed" << (fails ? " FAIL" : " OK") << std::endl; + if (fails) return 1; + } + + // ---- 4. speed -------------------------------------------------------------------------- + std::cout << std::setprecision(0); + for (size_t ci = 0; ci < cases.size(); ci++) { + const dq_case& c = *cases[ci]; + auto& a2048 = *apps[ci].back(); + auto& a264 = *apps[ci][3]; + const double t_full = time_us([&] { a2048(o_y, o_x, o_w[ci]); }, ITERS); + const double t_264 = time_us([&] { a264(o_y, o_x, o_w[ci]); }, ITERS); + std::cout << "[speed] " << std::left << std::setw(40) << c.name << " 2048 rows: standalone " << t_std[ci] + << " us, overlay " << t_full << " us; 264 rows: overlay " << t_264 << " us" << std::endl; + } + { + // the array is on dq after the timings above; dq GLU 264 rows <-> attention + auto at_sw = make_attn(overlay::OP_DQ), at_ns = make_attn(overlay::OP_ATTN); + auto dq_sw = make_dq(overlay::OP_ATTN, 3, 264); + npu_app& dq_ns = *apps[3][3]; + const double t_dq = time_us([&] { dq_ns(o_y, o_x, o_w[3]); }, ITERS); + (*at_sw)(o_o, o_q, o_kv); + const double t_at = time_us([&] { (*at_ns)(o_o, o_q, o_kv); }, ITERS); + const double t_pair = time_us([&] { (*dq_sw)(o_y, o_x, o_w[3]); (*at_sw)(o_o, o_q, o_kv); }, ITERS); + std::cout << "[speed] attention L " << AL << ": " << t_at << " us; switch dq <-> attn: " + << (t_pair - t_at - t_dq) / 2 << " us each way (pair " << t_pair << " us)" << std::endl; + } + return 0; +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/op_configs.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/op_configs.hpp new file mode 100644 index 000000000..1a16eba37 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/op_configs.hpp @@ -0,0 +1,3149 @@ +// Generated by tools/extract_txn2.py from aiecc --aie-generate-txn. Do not edit. +#pragma once +#include +#include + +struct reg_write { uint32_t col, row, offset, value; }; +struct mask_write { uint32_t col, row, offset, mask, value; }; +// shared: another op uses this BD register too -> rewrite it at every switch; +// otherwise it can stay loaded (write it once after the xclbin is loaded) +struct reg_block { uint32_t col, row, offset; bool shared; std::vector words; }; +struct chain_start { uint32_t col, row, ctrl_offset, queue_offset, queue_value, ctrl_value; }; +struct op_config { + std::vector sw; + std::vector mux; + std::vector bds; + std::vector locks; + std::vector starts; +}; + + +// all DMA channel control registers used by any op: (col, row, offset) +inline const std::vector all_channels = { + {0, 1, 0xA0600, 0}, + {0, 1, 0xA0608, 0}, + {0, 1, 0xA0610, 0}, + {0, 1, 0xA0618, 0}, + {0, 1, 0xA0620, 0}, + {0, 1, 0xA0628, 0}, + {0, 1, 0xA0630, 0}, + {0, 1, 0xA0638, 0}, + {0, 1, 0xA0640, 0}, + {0, 1, 0xA0648, 0}, + {0, 1, 0xA0658, 0}, + {0, 2, 0x1DE00, 0}, + {0, 2, 0x1DE08, 0}, + {0, 2, 0x1DE10, 0}, + {0, 2, 0x1DE18, 0}, + {0, 3, 0x1DE00, 0}, + {0, 3, 0x1DE08, 0}, + {0, 3, 0x1DE10, 0}, + {0, 3, 0x1DE18, 0}, + {0, 4, 0x1DE00, 0}, + {0, 4, 0x1DE08, 0}, + {0, 4, 0x1DE10, 0}, + {0, 4, 0x1DE18, 0}, + {0, 5, 0x1DE00, 0}, + {0, 5, 0x1DE08, 0}, + {0, 5, 0x1DE10, 0}, + {0, 5, 0x1DE18, 0}, + {1, 1, 0xA0600, 0}, + {1, 1, 0xA0608, 0}, + {1, 1, 0xA0610, 0}, + {1, 1, 0xA0618, 0}, + {1, 1, 0xA0620, 0}, + {1, 1, 0xA0628, 0}, + {1, 1, 0xA0630, 0}, + {1, 1, 0xA0638, 0}, + {1, 1, 0xA0640, 0}, + {1, 1, 0xA0658, 0}, + {1, 2, 0x1DE00, 0}, + {1, 2, 0x1DE08, 0}, + {1, 2, 0x1DE10, 0}, + {1, 2, 0x1DE18, 0}, + {1, 3, 0x1DE00, 0}, + {1, 3, 0x1DE08, 0}, + {1, 3, 0x1DE10, 0}, + {1, 3, 0x1DE18, 0}, + {1, 4, 0x1DE00, 0}, + {1, 4, 0x1DE08, 0}, + {1, 4, 0x1DE10, 0}, + {1, 4, 0x1DE18, 0}, + {1, 5, 0x1DE00, 0}, + {1, 5, 0x1DE08, 0}, + {1, 5, 0x1DE10, 0}, + {1, 5, 0x1DE18, 0}, + {2, 1, 0xA0600, 0}, + {2, 1, 0xA0608, 0}, + {2, 1, 0xA0610, 0}, + {2, 1, 0xA0618, 0}, + {2, 1, 0xA0620, 0}, + {2, 1, 0xA0628, 0}, + {2, 1, 0xA0630, 0}, + {2, 1, 0xA0638, 0}, + {2, 1, 0xA0640, 0}, + {2, 1, 0xA0648, 0}, + {2, 1, 0xA0658, 0}, + {2, 2, 0x1DE00, 0}, + {2, 2, 0x1DE08, 0}, + {2, 2, 0x1DE10, 0}, + {2, 2, 0x1DE18, 0}, + {2, 3, 0x1DE00, 0}, + {2, 3, 0x1DE08, 0}, + {2, 3, 0x1DE10, 0}, + {2, 3, 0x1DE18, 0}, + {2, 4, 0x1DE00, 0}, + {2, 4, 0x1DE08, 0}, + {2, 4, 0x1DE10, 0}, + {2, 4, 0x1DE18, 0}, + {2, 5, 0x1DE00, 0}, + {2, 5, 0x1DE08, 0}, + {2, 5, 0x1DE10, 0}, + {2, 5, 0x1DE18, 0}, + {3, 1, 0xA0600, 0}, + {3, 1, 0xA0608, 0}, + {3, 1, 0xA0610, 0}, + {3, 1, 0xA0618, 0}, + {3, 1, 0xA0620, 0}, + {3, 1, 0xA0628, 0}, + {3, 1, 0xA0630, 0}, + {3, 1, 0xA0638, 0}, + {3, 1, 0xA0640, 0}, + {3, 1, 0xA0658, 0}, + {3, 2, 0x1DE00, 0}, + {3, 2, 0x1DE08, 0}, + {3, 2, 0x1DE10, 0}, + {3, 2, 0x1DE18, 0}, + {3, 3, 0x1DE00, 0}, + {3, 3, 0x1DE08, 0}, + {3, 3, 0x1DE10, 0}, + {3, 3, 0x1DE18, 0}, + {3, 4, 0x1DE00, 0}, + {3, 4, 0x1DE08, 0}, + {3, 4, 0x1DE10, 0}, + {3, 4, 0x1DE18, 0}, + {3, 5, 0x1DE00, 0}, + {3, 5, 0x1DE08, 0}, + {3, 5, 0x1DE10, 0}, + {3, 5, 0x1DE18, 0}, + {4, 1, 0xA0600, 0}, + {4, 1, 0xA0608, 0}, + {4, 1, 0xA0610, 0}, + {4, 1, 0xA0618, 0}, + {4, 1, 0xA0620, 0}, + {4, 1, 0xA0628, 0}, + {4, 1, 0xA0630, 0}, + {4, 1, 0xA0638, 0}, + {4, 1, 0xA0640, 0}, + {4, 1, 0xA0648, 0}, + {4, 1, 0xA0658, 0}, + {4, 2, 0x1DE00, 0}, + {4, 2, 0x1DE08, 0}, + {4, 2, 0x1DE10, 0}, + {4, 2, 0x1DE18, 0}, + {4, 3, 0x1DE00, 0}, + {4, 3, 0x1DE08, 0}, + {4, 3, 0x1DE10, 0}, + {4, 3, 0x1DE18, 0}, + {4, 4, 0x1DE00, 0}, + {4, 4, 0x1DE08, 0}, + {4, 4, 0x1DE10, 0}, + {4, 4, 0x1DE18, 0}, + {4, 5, 0x1DE00, 0}, + {4, 5, 0x1DE08, 0}, + {4, 5, 0x1DE10, 0}, + {4, 5, 0x1DE18, 0}, + {5, 1, 0xA0600, 0}, + {5, 1, 0xA0608, 0}, + {5, 1, 0xA0610, 0}, + {5, 1, 0xA0618, 0}, + {5, 1, 0xA0620, 0}, + {5, 1, 0xA0628, 0}, + {5, 1, 0xA0630, 0}, + {5, 1, 0xA0638, 0}, + {5, 1, 0xA0640, 0}, + {5, 1, 0xA0658, 0}, + {5, 2, 0x1DE00, 0}, + {5, 2, 0x1DE08, 0}, + {5, 2, 0x1DE10, 0}, + {5, 2, 0x1DE18, 0}, + {5, 3, 0x1DE00, 0}, + {5, 3, 0x1DE08, 0}, + {5, 3, 0x1DE10, 0}, + {5, 3, 0x1DE18, 0}, + {5, 4, 0x1DE00, 0}, + {5, 4, 0x1DE08, 0}, + {5, 4, 0x1DE10, 0}, + {5, 4, 0x1DE18, 0}, + {5, 5, 0x1DE00, 0}, + {5, 5, 0x1DE08, 0}, + {5, 5, 0x1DE10, 0}, + {5, 5, 0x1DE18, 0}, + {6, 1, 0xA0600, 0}, + {6, 1, 0xA0608, 0}, + {6, 1, 0xA0610, 0}, + {6, 1, 0xA0618, 0}, + {6, 1, 0xA0620, 0}, + {6, 1, 0xA0628, 0}, + {6, 1, 0xA0630, 0}, + {6, 1, 0xA0638, 0}, + {6, 1, 0xA0640, 0}, + {6, 1, 0xA0648, 0}, + {6, 1, 0xA0658, 0}, + {6, 2, 0x1DE00, 0}, + {6, 2, 0x1DE08, 0}, + {6, 2, 0x1DE10, 0}, + {6, 2, 0x1DE18, 0}, + {6, 3, 0x1DE00, 0}, + {6, 3, 0x1DE08, 0}, + {6, 3, 0x1DE10, 0}, + {6, 3, 0x1DE18, 0}, + {6, 4, 0x1DE00, 0}, + {6, 4, 0x1DE08, 0}, + {6, 4, 0x1DE10, 0}, + {6, 4, 0x1DE18, 0}, + {6, 5, 0x1DE00, 0}, + {6, 5, 0x1DE08, 0}, + {6, 5, 0x1DE10, 0}, + {6, 5, 0x1DE18, 0}, + {7, 1, 0xA0600, 0}, + {7, 1, 0xA0608, 0}, + {7, 1, 0xA0610, 0}, + {7, 1, 0xA0618, 0}, + {7, 1, 0xA0620, 0}, + {7, 1, 0xA0628, 0}, + {7, 1, 0xA0630, 0}, + {7, 1, 0xA0638, 0}, + {7, 1, 0xA0640, 0}, + {7, 1, 0xA0658, 0}, + {7, 2, 0x1DE00, 0}, + {7, 2, 0x1DE08, 0}, + {7, 2, 0x1DE10, 0}, + {7, 2, 0x1DE18, 0}, + {7, 3, 0x1DE00, 0}, + {7, 3, 0x1DE08, 0}, + {7, 3, 0x1DE10, 0}, + {7, 3, 0x1DE18, 0}, + {7, 4, 0x1DE00, 0}, + {7, 4, 0x1DE08, 0}, + {7, 4, 0x1DE10, 0}, + {7, 4, 0x1DE18, 0}, + {7, 5, 0x1DE00, 0}, + {7, 5, 0x1DE08, 0}, + {7, 5, 0x1DE10, 0}, + {7, 5, 0x1DE18, 0}, +}; + +inline const op_config op_dq = { + // stream switch registers: (col, row, offset, value) + { + {0, 0, 0x3F008, 0xC0000045}, + {0, 0, 0x3F010, 0x80000010}, + {0, 0, 0x3F03C, 0x80000009}, + {0, 0, 0x3F044, 0x80000005}, + {0, 0, 0x3F100, 0xC0000000}, + {0, 0, 0x3F114, 0x80000000}, + {0, 0, 0x3F124, 0x80000000}, + {0, 0, 0x3F140, 0x80000000}, + {0, 0, 0x3F200, 0x0F1F0135}, + {0, 1, 0xB0000, 0x8000000C}, + {0, 1, 0xB0004, 0x8000000E}, + {0, 1, 0xB0008, 0x8000000D}, + {0, 1, 0xB000C, 0x8000000F}, + {0, 1, 0xB0010, 0x80000010}, + {0, 1, 0xB0014, 0x8000000A}, + {0, 1, 0xB0024, 0x80000001}, + {0, 1, 0xB0030, 0x80000002}, + {0, 1, 0xB0040, 0x80000000}, + {0, 1, 0xB0100, 0x80000000}, + {0, 1, 0xB0104, 0x80000000}, + {0, 1, 0xB0108, 0x80000000}, + {0, 1, 0xB0128, 0x80000000}, + {0, 1, 0xB0130, 0x80000000}, + {0, 1, 0xB0134, 0x80000000}, + {0, 1, 0xB0138, 0x80000000}, + {0, 1, 0xB013C, 0x80000000}, + {0, 1, 0xB0140, 0x80000000}, + {0, 2, 0x3F004, 0x8000000A}, + {0, 2, 0x3F008, 0x80000006}, + {0, 2, 0x3F014, 0x80000013}, + {0, 2, 0x3F018, 0x80000001}, + {0, 2, 0x3F01C, 0x80000015}, + {0, 2, 0x3F020, 0x80000014}, + {0, 2, 0x3F038, 0x80000006}, + {0, 2, 0x3F044, 0x80000016}, + {0, 2, 0x3F050, 0x80000010}, + {0, 2, 0x3F054, 0x8000000A}, + {0, 2, 0x3F104, 0x80000000}, + {0, 2, 0x3F118, 0x80000000}, + {0, 2, 0x3F128, 0x80000000}, + {0, 2, 0x3F140, 0x80000000}, + {0, 2, 0x3F14C, 0x80000000}, + {0, 2, 0x3F150, 0x80000000}, + {0, 2, 0x3F154, 0x80000000}, + {0, 2, 0x3F158, 0x80000000}, + {0, 3, 0x3F004, 0x80000009}, + {0, 3, 0x3F018, 0x80000010}, + {0, 3, 0x3F034, 0x80000006}, + {0, 3, 0x3F03C, 0x80000013}, + {0, 3, 0x3F04C, 0x80000001}, + {0, 3, 0x3F104, 0x80000000}, + {0, 3, 0x3F118, 0x80000000}, + {0, 3, 0x3F124, 0x80000000}, + {0, 3, 0x3F140, 0x80000000}, + {0, 3, 0x3F14C, 0x80000000}, + {0, 4, 0x3F004, 0x80000007}, + {0, 4, 0x3F008, 0x80000005}, + {0, 4, 0x3F018, 0x80000001}, + {0, 4, 0x3F104, 0x80000000}, + {0, 4, 0x3F114, 0x80000000}, + {0, 4, 0x3F11C, 0x80000000}, + {0, 5, 0x3F004, 0x80000013}, + {0, 5, 0x3F058, 0x80000001}, + {0, 5, 0x3F104, 0x80000000}, + {0, 5, 0x3F14C, 0x80000000}, + {1, 0, 0x3F008, 0xC0000045}, + {1, 0, 0x3F010, 0x80000010}, + {1, 0, 0x3F034, 0x80000009}, + {1, 0, 0x3F100, 0xC0000000}, + {1, 0, 0x3F124, 0x80000000}, + {1, 0, 0x3F140, 0x80000000}, + {1, 0, 0x3F200, 0x0F1F0135}, + {1, 1, 0xB0004, 0x8000000D}, + {1, 1, 0xB0008, 0x80000010}, + {1, 1, 0xB000C, 0x8000000E}, + {1, 1, 0xB0010, 0x8000000F}, + {1, 1, 0xB0014, 0x80000008}, + {1, 1, 0xB0024, 0x80000001}, + {1, 1, 0xB0030, 0x80000002}, + {1, 1, 0xB0104, 0x80000000}, + {1, 1, 0xB0108, 0x80000000}, + {1, 1, 0xB0120, 0x80000000}, + {1, 1, 0xB0134, 0x80000000}, + {1, 1, 0xB0138, 0x80000000}, + {1, 1, 0xB013C, 0x80000000}, + {1, 1, 0xB0140, 0x80000000}, + {1, 2, 0x3F004, 0x8000000D}, + {1, 2, 0x3F008, 0x80000006}, + {1, 2, 0x3F014, 0x80000010}, + {1, 2, 0x3F018, 0x8000000F}, + {1, 2, 0x3F01C, 0x80000011}, + {1, 2, 0x3F020, 0x80000012}, + {1, 2, 0x3F024, 0x80000001}, + {1, 2, 0x3F028, 0x80000013}, + {1, 2, 0x3F02C, 0x80000016}, + {1, 2, 0x3F030, 0x80000015}, + {1, 2, 0x3F034, 0x80000015}, + {1, 2, 0x3F038, 0x80000014}, + {1, 2, 0x3F040, 0x80000006}, + {1, 2, 0x3F04C, 0x8000000C}, + {1, 2, 0x3F054, 0x8000000D}, + {1, 2, 0x3F104, 0x80000000}, + {1, 2, 0x3F118, 0x80000000}, + {1, 2, 0x3F130, 0x80000000}, + {1, 2, 0x3F134, 0x80000000}, + {1, 2, 0x3F13C, 0x80000000}, + {1, 2, 0x3F140, 0x80000000}, + {1, 2, 0x3F144, 0x80000000}, + {1, 2, 0x3F148, 0x80000000}, + {1, 2, 0x3F14C, 0x80000000}, + {1, 2, 0x3F150, 0x80000000}, + {1, 2, 0x3F154, 0x80000000}, + {1, 2, 0x3F158, 0x80000000}, + {1, 3, 0x3F004, 0x80000005}, + {1, 3, 0x3F014, 0x80000013}, + {1, 3, 0x3F018, 0x8000000B}, + {1, 3, 0x3F01C, 0x80000015}, + {1, 3, 0x3F020, 0x80000001}, + {1, 3, 0x3F024, 0x80000016}, + {1, 3, 0x3F03C, 0x80000006}, + {1, 3, 0x3F044, 0x80000008}, + {1, 3, 0x3F058, 0x80000010}, + {1, 3, 0x3F104, 0x80000000}, + {1, 3, 0x3F114, 0x80000000}, + {1, 3, 0x3F118, 0x80000000}, + {1, 3, 0x3F120, 0x80000000}, + {1, 3, 0x3F12C, 0x80000000}, + {1, 3, 0x3F140, 0x80000000}, + {1, 3, 0x3F14C, 0x80000000}, + {1, 3, 0x3F154, 0x80000000}, + {1, 3, 0x3F158, 0x80000000}, + {1, 4, 0x3F004, 0x80000015}, + {1, 4, 0x3F008, 0x80000009}, + {1, 4, 0x3F018, 0x80000001}, + {1, 4, 0x3F048, 0x80000007}, + {1, 4, 0x3F104, 0x80000000}, + {1, 4, 0x3F11C, 0x80000000}, + {1, 4, 0x3F124, 0x80000000}, + {1, 4, 0x3F154, 0x80000000}, + {1, 5, 0x3F004, 0x8000000A}, + {1, 5, 0x3F024, 0x8000000A}, + {1, 5, 0x3F050, 0x8000000E}, + {1, 5, 0x3F058, 0x80000001}, + {1, 5, 0x3F104, 0x80000000}, + {1, 5, 0x3F128, 0x80000000}, + {1, 5, 0x3F138, 0x80000000}, + {2, 0, 0x3F008, 0xC0000045}, + {2, 0, 0x3F010, 0x80000010}, + {2, 0, 0x3F034, 0x80000009}, + {2, 0, 0x3F044, 0x80000005}, + {2, 0, 0x3F100, 0xC0000000}, + {2, 0, 0x3F114, 0x80000000}, + {2, 0, 0x3F124, 0x80000000}, + {2, 0, 0x3F140, 0x80000000}, + {2, 0, 0x3F200, 0x0F1F0135}, + {2, 1, 0xB0000, 0x8000000C}, + {2, 1, 0xB0004, 0x8000000D}, + {2, 1, 0xB0008, 0x80000010}, + {2, 1, 0xB000C, 0x8000000F}, + {2, 1, 0xB0010, 0x8000000E}, + {2, 1, 0xB0014, 0x80000008}, + {2, 1, 0xB0024, 0x80000001}, + {2, 1, 0xB0030, 0x80000002}, + {2, 1, 0xB0040, 0x80000000}, + {2, 1, 0xB0100, 0x80000000}, + {2, 1, 0xB0104, 0x80000000}, + {2, 1, 0xB0108, 0x80000000}, + {2, 1, 0xB0120, 0x80000000}, + {2, 1, 0xB0130, 0x80000000}, + {2, 1, 0xB0134, 0x80000000}, + {2, 1, 0xB0138, 0x80000000}, + {2, 1, 0xB013C, 0x80000000}, + {2, 1, 0xB0140, 0x80000000}, + {2, 2, 0x3F004, 0x8000000D}, + {2, 2, 0x3F008, 0x80000006}, + {2, 2, 0x3F014, 0x8000000B}, + {2, 2, 0x3F018, 0x80000011}, + {2, 2, 0x3F01C, 0x8000000F}, + {2, 2, 0x3F020, 0x80000012}, + {2, 2, 0x3F024, 0x80000013}, + {2, 2, 0x3F028, 0x80000016}, + {2, 2, 0x3F02C, 0x8000000A}, + {2, 2, 0x3F030, 0x80000001}, + {2, 2, 0x3F038, 0x8000000A}, + {2, 2, 0x3F040, 0x80000006}, + {2, 2, 0x3F04C, 0x8000000D}, + {2, 2, 0x3F050, 0x80000010}, + {2, 2, 0x3F054, 0x8000000A}, + {2, 2, 0x3F104, 0x80000000}, + {2, 2, 0x3F118, 0x80000000}, + {2, 2, 0x3F128, 0x80000000}, + {2, 2, 0x3F12C, 0x80000000}, + {2, 2, 0x3F134, 0x80000000}, + {2, 2, 0x3F13C, 0x80000000}, + {2, 2, 0x3F140, 0x80000000}, + {2, 2, 0x3F144, 0x80000000}, + {2, 2, 0x3F148, 0x80000000}, + {2, 2, 0x3F14C, 0x80000000}, + {2, 2, 0x3F158, 0x80000000}, + {2, 3, 0x3F004, 0x80000006}, + {2, 3, 0x3F014, 0x80000010}, + {2, 3, 0x3F018, 0x80000011}, + {2, 3, 0x3F01C, 0x80000014}, + {2, 3, 0x3F020, 0x8000000E}, + {2, 3, 0x3F024, 0x80000001}, + {2, 3, 0x3F02C, 0x80000016}, + {2, 3, 0x3F030, 0x80000013}, + {2, 3, 0x3F034, 0x80000008}, + {2, 3, 0x3F050, 0x80000012}, + {2, 3, 0x3F104, 0x80000000}, + {2, 3, 0x3F118, 0x80000000}, + {2, 3, 0x3F120, 0x80000000}, + {2, 3, 0x3F138, 0x80000000}, + {2, 3, 0x3F140, 0x80000000}, + {2, 3, 0x3F144, 0x80000000}, + {2, 3, 0x3F148, 0x80000000}, + {2, 3, 0x3F14C, 0x80000000}, + {2, 3, 0x3F150, 0x80000000}, + {2, 3, 0x3F158, 0x80000000}, + {2, 4, 0x3F004, 0x80000015}, + {2, 4, 0x3F008, 0x80000005}, + {2, 4, 0x3F018, 0x80000001}, + {2, 4, 0x3F01C, 0x80000012}, + {2, 4, 0x3F020, 0x8000000F}, + {2, 4, 0x3F02C, 0x80000015}, + {2, 4, 0x3F104, 0x80000000}, + {2, 4, 0x3F114, 0x80000000}, + {2, 4, 0x3F13C, 0x80000000}, + {2, 4, 0x3F148, 0x80000000}, + {2, 4, 0x3F154, 0x80000000}, + {2, 5, 0x3F004, 0x80000014}, + {2, 5, 0x3F014, 0x8000000E}, + {2, 5, 0x3F020, 0x80000001}, + {2, 5, 0x3F054, 0x8000000C}, + {2, 5, 0x3F104, 0x80000000}, + {2, 5, 0x3F130, 0x80000000}, + {2, 5, 0x3F138, 0x80000000}, + {2, 5, 0x3F150, 0x80000000}, + {3, 0, 0x3F008, 0xC0000045}, + {3, 0, 0x3F010, 0x80000010}, + {3, 0, 0x3F034, 0x80000009}, + {3, 0, 0x3F100, 0xC0000000}, + {3, 0, 0x3F124, 0x80000000}, + {3, 0, 0x3F140, 0x80000000}, + {3, 0, 0x3F200, 0x0F1F0135}, + {3, 1, 0xB0004, 0x8000000F}, + {3, 1, 0xB0008, 0x8000000D}, + {3, 1, 0xB000C, 0x80000010}, + {3, 1, 0xB0010, 0x8000000E}, + {3, 1, 0xB0014, 0x80000008}, + {3, 1, 0xB0024, 0x80000001}, + {3, 1, 0xB0030, 0x80000002}, + {3, 1, 0xB0104, 0x80000000}, + {3, 1, 0xB0108, 0x80000000}, + {3, 1, 0xB0120, 0x80000000}, + {3, 1, 0xB0134, 0x80000000}, + {3, 1, 0xB0138, 0x80000000}, + {3, 1, 0xB013C, 0x80000000}, + {3, 1, 0xB0140, 0x80000000}, + {3, 2, 0x3F004, 0x8000000B}, + {3, 2, 0x3F008, 0x80000006}, + {3, 2, 0x3F014, 0x80000012}, + {3, 2, 0x3F018, 0x80000010}, + {3, 2, 0x3F01C, 0x8000000F}, + {3, 2, 0x3F020, 0x8000000C}, + {3, 2, 0x3F024, 0x80000001}, + {3, 2, 0x3F030, 0x80000013}, + {3, 2, 0x3F034, 0x80000015}, + {3, 2, 0x3F03C, 0x8000000D}, + {3, 2, 0x3F040, 0x80000006}, + {3, 2, 0x3F04C, 0x8000000B}, + {3, 2, 0x3F104, 0x80000000}, + {3, 2, 0x3F118, 0x80000000}, + {3, 2, 0x3F12C, 0x80000000}, + {3, 2, 0x3F130, 0x80000000}, + {3, 2, 0x3F134, 0x80000000}, + {3, 2, 0x3F13C, 0x80000000}, + {3, 2, 0x3F140, 0x80000000}, + {3, 2, 0x3F148, 0x80000000}, + {3, 2, 0x3F14C, 0x80000000}, + {3, 2, 0x3F154, 0x80000000}, + {3, 3, 0x3F004, 0x80000007}, + {3, 3, 0x3F014, 0x8000000F}, + {3, 3, 0x3F018, 0x80000012}, + {3, 3, 0x3F020, 0x8000000C}, + {3, 3, 0x3F024, 0x80000005}, + {3, 3, 0x3F028, 0x80000010}, + {3, 3, 0x3F030, 0x80000001}, + {3, 3, 0x3F034, 0x80000008}, + {3, 3, 0x3F058, 0x80000007}, + {3, 3, 0x3F104, 0x80000000}, + {3, 3, 0x3F114, 0x80000000}, + {3, 3, 0x3F11C, 0x80000000}, + {3, 3, 0x3F120, 0x80000000}, + {3, 3, 0x3F130, 0x80000000}, + {3, 3, 0x3F13C, 0x80000000}, + {3, 3, 0x3F140, 0x80000000}, + {3, 3, 0x3F148, 0x80000000}, + {3, 4, 0x3F004, 0x80000016}, + {3, 4, 0x3F008, 0x80000005}, + {3, 4, 0x3F014, 0x80000012}, + {3, 4, 0x3F018, 0x80000001}, + {3, 4, 0x3F020, 0x8000000F}, + {3, 4, 0x3F02C, 0x80000016}, + {3, 4, 0x3F038, 0x80000013}, + {3, 4, 0x3F104, 0x80000000}, + {3, 4, 0x3F114, 0x80000000}, + {3, 4, 0x3F13C, 0x80000000}, + {3, 4, 0x3F148, 0x80000000}, + {3, 4, 0x3F14C, 0x80000000}, + {3, 4, 0x3F158, 0x80000000}, + {3, 5, 0x3F004, 0x80000006}, + {3, 5, 0x3F014, 0x80000001}, + {3, 5, 0x3F020, 0x8000000D}, + {3, 5, 0x3F028, 0x80000006}, + {3, 5, 0x3F104, 0x80000000}, + {3, 5, 0x3F118, 0x80000000}, + {3, 5, 0x3F134, 0x80000000}, + {4, 0, 0x3F008, 0xC0000045}, + {4, 0, 0x3F010, 0x80000010}, + {4, 0, 0x3F034, 0x80000009}, + {4, 0, 0x3F044, 0x80000005}, + {4, 0, 0x3F100, 0xC0000000}, + {4, 0, 0x3F114, 0x80000000}, + {4, 0, 0x3F124, 0x80000000}, + {4, 0, 0x3F140, 0x80000000}, + {4, 0, 0x3F200, 0x0F1F0135}, + {4, 1, 0xB0000, 0x8000000C}, + {4, 1, 0xB0004, 0x8000000E}, + {4, 1, 0xB0008, 0x80000010}, + {4, 1, 0xB000C, 0x8000000D}, + {4, 1, 0xB0010, 0x8000000F}, + {4, 1, 0xB0014, 0x80000008}, + {4, 1, 0xB0024, 0x80000001}, + {4, 1, 0xB0030, 0x80000002}, + {4, 1, 0xB0040, 0x80000000}, + {4, 1, 0xB0100, 0x80000000}, + {4, 1, 0xB0104, 0x80000000}, + {4, 1, 0xB0108, 0x80000000}, + {4, 1, 0xB0120, 0x80000000}, + {4, 1, 0xB0130, 0x80000000}, + {4, 1, 0xB0134, 0x80000000}, + {4, 1, 0xB0138, 0x80000000}, + {4, 1, 0xB013C, 0x80000000}, + {4, 1, 0xB0140, 0x80000000}, + {4, 2, 0x3F004, 0x8000000B}, + {4, 2, 0x3F008, 0x80000006}, + {4, 2, 0x3F014, 0x80000014}, + {4, 2, 0x3F018, 0x80000001}, + {4, 2, 0x3F01C, 0x80000015}, + {4, 2, 0x3F020, 0x80000013}, + {4, 2, 0x3F024, 0x80000016}, + {4, 2, 0x3F02C, 0x8000000A}, + {4, 2, 0x3F038, 0x8000000A}, + {4, 2, 0x3F040, 0x80000006}, + {4, 2, 0x3F04C, 0x80000010}, + {4, 2, 0x3F054, 0x8000000A}, + {4, 2, 0x3F058, 0x8000000B}, + {4, 2, 0x3F104, 0x80000000}, + {4, 2, 0x3F118, 0x80000000}, + {4, 2, 0x3F128, 0x80000000}, + {4, 2, 0x3F12C, 0x80000000}, + {4, 2, 0x3F140, 0x80000000}, + {4, 2, 0x3F14C, 0x80000000}, + {4, 2, 0x3F150, 0x80000000}, + {4, 2, 0x3F154, 0x80000000}, + {4, 2, 0x3F158, 0x80000000}, + {4, 3, 0x3F004, 0x8000000E}, + {4, 3, 0x3F018, 0x80000001}, + {4, 3, 0x3F034, 0x80000008}, + {4, 3, 0x3F040, 0x80000006}, + {4, 3, 0x3F04C, 0x80000012}, + {4, 3, 0x3F050, 0x8000000E}, + {4, 3, 0x3F058, 0x80000010}, + {4, 3, 0x3F104, 0x80000000}, + {4, 3, 0x3F118, 0x80000000}, + {4, 3, 0x3F120, 0x80000000}, + {4, 3, 0x3F138, 0x80000000}, + {4, 3, 0x3F140, 0x80000000}, + {4, 3, 0x3F148, 0x80000000}, + {4, 4, 0x3F004, 0x80000008}, + {4, 4, 0x3F008, 0x80000005}, + {4, 4, 0x3F018, 0x80000001}, + {4, 4, 0x3F020, 0x8000000F}, + {4, 4, 0x3F024, 0x80000013}, + {4, 4, 0x3F030, 0x80000008}, + {4, 4, 0x3F050, 0x80000008}, + {4, 4, 0x3F104, 0x80000000}, + {4, 4, 0x3F114, 0x80000000}, + {4, 4, 0x3F120, 0x80000000}, + {4, 4, 0x3F13C, 0x80000000}, + {4, 4, 0x3F14C, 0x80000000}, + {4, 5, 0x3F004, 0x80000016}, + {4, 5, 0x3F014, 0x80000001}, + {4, 5, 0x3F104, 0x80000000}, + {4, 5, 0x3F158, 0x80000000}, + {5, 0, 0x3F008, 0xC0000045}, + {5, 0, 0x3F010, 0x80000010}, + {5, 0, 0x3F034, 0x80000009}, + {5, 0, 0x3F100, 0xC0000000}, + {5, 0, 0x3F124, 0x80000000}, + {5, 0, 0x3F140, 0x80000000}, + {5, 0, 0x3F200, 0x0F1F0135}, + {5, 1, 0xB0004, 0x8000000F}, + {5, 1, 0xB0008, 0x80000010}, + {5, 1, 0xB000C, 0x8000000E}, + {5, 1, 0xB0010, 0x8000000D}, + {5, 1, 0xB0014, 0x80000008}, + {5, 1, 0xB0024, 0x80000001}, + {5, 1, 0xB0030, 0x80000002}, + {5, 1, 0xB0104, 0x80000000}, + {5, 1, 0xB0108, 0x80000000}, + {5, 1, 0xB0120, 0x80000000}, + {5, 1, 0xB0134, 0x80000000}, + {5, 1, 0xB0138, 0x80000000}, + {5, 1, 0xB013C, 0x80000000}, + {5, 1, 0xB0140, 0x80000000}, + {5, 2, 0x3F004, 0x8000000E}, + {5, 2, 0x3F008, 0x80000006}, + {5, 2, 0x3F014, 0x8000000F}, + {5, 2, 0x3F018, 0x80000013}, + {5, 2, 0x3F01C, 0x8000000B}, + {5, 2, 0x3F020, 0x80000010}, + {5, 2, 0x3F024, 0x80000001}, + {5, 2, 0x3F028, 0x80000016}, + {5, 2, 0x3F02C, 0x80000014}, + {5, 2, 0x3F030, 0x80000015}, + {5, 2, 0x3F040, 0x80000006}, + {5, 2, 0x3F04C, 0x8000000D}, + {5, 2, 0x3F050, 0x80000012}, + {5, 2, 0x3F054, 0x80000011}, + {5, 2, 0x3F058, 0x8000000E}, + {5, 2, 0x3F104, 0x80000000}, + {5, 2, 0x3F118, 0x80000000}, + {5, 2, 0x3F12C, 0x80000000}, + {5, 2, 0x3F134, 0x80000000}, + {5, 2, 0x3F138, 0x80000000}, + {5, 2, 0x3F13C, 0x80000000}, + {5, 2, 0x3F140, 0x80000000}, + {5, 2, 0x3F144, 0x80000000}, + {5, 2, 0x3F148, 0x80000000}, + {5, 2, 0x3F14C, 0x80000000}, + {5, 2, 0x3F150, 0x80000000}, + {5, 2, 0x3F154, 0x80000000}, + {5, 2, 0x3F158, 0x80000000}, + {5, 3, 0x3F004, 0x8000000C}, + {5, 3, 0x3F014, 0x80000016}, + {5, 3, 0x3F018, 0x80000001}, + {5, 3, 0x3F01C, 0x80000010}, + {5, 3, 0x3F020, 0x8000000E}, + {5, 3, 0x3F034, 0x80000008}, + {5, 3, 0x3F040, 0x80000015}, + {5, 3, 0x3F050, 0x80000012}, + {5, 3, 0x3F054, 0x8000000C}, + {5, 3, 0x3F058, 0x8000000B}, + {5, 3, 0x3F104, 0x80000000}, + {5, 3, 0x3F120, 0x80000000}, + {5, 3, 0x3F12C, 0x80000000}, + {5, 3, 0x3F130, 0x80000000}, + {5, 3, 0x3F138, 0x80000000}, + {5, 3, 0x3F140, 0x80000000}, + {5, 3, 0x3F148, 0x80000000}, + {5, 3, 0x3F154, 0x80000000}, + {5, 3, 0x3F158, 0x80000000}, + {5, 4, 0x3F004, 0x8000000C}, + {5, 4, 0x3F008, 0x80000005}, + {5, 4, 0x3F018, 0x80000001}, + {5, 4, 0x3F020, 0x8000000F}, + {5, 4, 0x3F024, 0x80000008}, + {5, 4, 0x3F03C, 0x80000008}, + {5, 4, 0x3F104, 0x80000000}, + {5, 4, 0x3F114, 0x80000000}, + {5, 4, 0x3F120, 0x80000000}, + {5, 4, 0x3F130, 0x80000000}, + {5, 4, 0x3F13C, 0x80000000}, + {5, 5, 0x3F004, 0x80000007}, + {5, 5, 0x3F014, 0x80000001}, + {5, 5, 0x3F030, 0x80000007}, + {5, 5, 0x3F104, 0x80000000}, + {5, 5, 0x3F11C, 0x80000000}, + {6, 0, 0x3F008, 0xC0000045}, + {6, 0, 0x3F010, 0x80000010}, + {6, 0, 0x3F034, 0x80000009}, + {6, 0, 0x3F044, 0x80000005}, + {6, 0, 0x3F100, 0xC0000000}, + {6, 0, 0x3F114, 0x80000000}, + {6, 0, 0x3F124, 0x80000000}, + {6, 0, 0x3F140, 0x80000000}, + {6, 0, 0x3F200, 0x0F1F0135}, + {6, 1, 0xB0000, 0x8000000C}, + {6, 1, 0xB0004, 0x80000010}, + {6, 1, 0xB0008, 0x8000000F}, + {6, 1, 0xB000C, 0x8000000E}, + {6, 1, 0xB0010, 0x8000000D}, + {6, 1, 0xB0014, 0x80000008}, + {6, 1, 0xB0024, 0x80000001}, + {6, 1, 0xB0030, 0x80000002}, + {6, 1, 0xB0040, 0x80000000}, + {6, 1, 0xB0100, 0x80000000}, + {6, 1, 0xB0104, 0x80000000}, + {6, 1, 0xB0108, 0x80000000}, + {6, 1, 0xB0120, 0x80000000}, + {6, 1, 0xB0130, 0x80000000}, + {6, 1, 0xB0134, 0x80000000}, + {6, 1, 0xB0138, 0x80000000}, + {6, 1, 0xB013C, 0x80000000}, + {6, 1, 0xB0140, 0x80000000}, + {6, 2, 0x3F004, 0x8000000E}, + {6, 2, 0x3F008, 0x80000006}, + {6, 2, 0x3F014, 0x80000014}, + {6, 2, 0x3F018, 0x8000000F}, + {6, 2, 0x3F01C, 0x8000000D}, + {6, 2, 0x3F020, 0x8000000C}, + {6, 2, 0x3F024, 0x80000010}, + {6, 2, 0x3F028, 0x80000016}, + {6, 2, 0x3F02C, 0x8000000A}, + {6, 2, 0x3F030, 0x80000001}, + {6, 2, 0x3F034, 0x8000000B}, + {6, 2, 0x3F038, 0x8000000A}, + {6, 2, 0x3F040, 0x80000006}, + {6, 2, 0x3F050, 0x80000011}, + {6, 2, 0x3F054, 0x8000000E}, + {6, 2, 0x3F058, 0x8000000A}, + {6, 2, 0x3F104, 0x80000000}, + {6, 2, 0x3F118, 0x80000000}, + {6, 2, 0x3F128, 0x80000000}, + {6, 2, 0x3F12C, 0x80000000}, + {6, 2, 0x3F130, 0x80000000}, + {6, 2, 0x3F134, 0x80000000}, + {6, 2, 0x3F138, 0x80000000}, + {6, 2, 0x3F13C, 0x80000000}, + {6, 2, 0x3F140, 0x80000000}, + {6, 2, 0x3F144, 0x80000000}, + {6, 2, 0x3F150, 0x80000000}, + {6, 2, 0x3F158, 0x80000000}, + {6, 3, 0x3F004, 0x8000000D}, + {6, 3, 0x3F014, 0x80000010}, + {6, 3, 0x3F018, 0x80000001}, + {6, 3, 0x3F01C, 0x8000000C}, + {6, 3, 0x3F02C, 0x80000006}, + {6, 3, 0x3F030, 0x80000016}, + {6, 3, 0x3F03C, 0x80000006}, + {6, 3, 0x3F040, 0x80000005}, + {6, 3, 0x3F048, 0x80000008}, + {6, 3, 0x3F04C, 0x8000000E}, + {6, 3, 0x3F050, 0x8000000D}, + {6, 3, 0x3F104, 0x80000000}, + {6, 3, 0x3F114, 0x80000000}, + {6, 3, 0x3F118, 0x80000000}, + {6, 3, 0x3F120, 0x80000000}, + {6, 3, 0x3F130, 0x80000000}, + {6, 3, 0x3F134, 0x80000000}, + {6, 3, 0x3F138, 0x80000000}, + {6, 3, 0x3F140, 0x80000000}, + {6, 3, 0x3F158, 0x80000000}, + {6, 4, 0x3F004, 0x80000008}, + {6, 4, 0x3F008, 0x8000000A}, + {6, 4, 0x3F018, 0x80000001}, + {6, 4, 0x3F044, 0x80000007}, + {6, 4, 0x3F050, 0x80000008}, + {6, 4, 0x3F054, 0x8000000F}, + {6, 4, 0x3F104, 0x80000000}, + {6, 4, 0x3F11C, 0x80000000}, + {6, 4, 0x3F120, 0x80000000}, + {6, 4, 0x3F128, 0x80000000}, + {6, 4, 0x3F13C, 0x80000000}, + {6, 5, 0x3F004, 0x80000009}, + {6, 5, 0x3F014, 0x80000001}, + {6, 5, 0x3F104, 0x80000000}, + {6, 5, 0x3F124, 0x80000000}, + {7, 0, 0x3F008, 0xC0000045}, + {7, 0, 0x3F010, 0x80000010}, + {7, 0, 0x3F030, 0x80000009}, + {7, 0, 0x3F100, 0xC0000000}, + {7, 0, 0x3F124, 0x80000000}, + {7, 0, 0x3F140, 0x80000000}, + {7, 0, 0x3F200, 0x0F1F0135}, + {7, 1, 0xB0004, 0x8000000F}, + {7, 1, 0xB0008, 0x80000010}, + {7, 1, 0xB000C, 0x8000000D}, + {7, 1, 0xB0010, 0x8000000E}, + {7, 1, 0xB0014, 0x80000007}, + {7, 1, 0xB0024, 0x80000001}, + {7, 1, 0xB0030, 0x80000002}, + {7, 1, 0xB0104, 0x80000000}, + {7, 1, 0xB0108, 0x80000000}, + {7, 1, 0xB011C, 0x80000000}, + {7, 1, 0xB0134, 0x80000000}, + {7, 1, 0xB0138, 0x80000000}, + {7, 1, 0xB013C, 0x80000000}, + {7, 1, 0xB0140, 0x80000000}, + {7, 2, 0x3F004, 0x8000000D}, + {7, 2, 0x3F008, 0x80000006}, + {7, 2, 0x3F014, 0x8000000F}, + {7, 2, 0x3F018, 0x80000012}, + {7, 2, 0x3F01C, 0x80000011}, + {7, 2, 0x3F020, 0x8000000C}, + {7, 2, 0x3F028, 0x80000010}, + {7, 2, 0x3F030, 0x80000001}, + {7, 2, 0x3F034, 0x8000000E}, + {7, 2, 0x3F044, 0x80000006}, + {7, 2, 0x3F104, 0x80000000}, + {7, 2, 0x3F118, 0x80000000}, + {7, 2, 0x3F130, 0x80000000}, + {7, 2, 0x3F134, 0x80000000}, + {7, 2, 0x3F138, 0x80000000}, + {7, 2, 0x3F13C, 0x80000000}, + {7, 2, 0x3F140, 0x80000000}, + {7, 2, 0x3F144, 0x80000000}, + {7, 2, 0x3F148, 0x80000000}, + {7, 3, 0x3F004, 0x8000000C}, + {7, 3, 0x3F014, 0x80000010}, + {7, 3, 0x3F018, 0x80000012}, + {7, 3, 0x3F01C, 0x8000000B}, + {7, 3, 0x3F020, 0x80000011}, + {7, 3, 0x3F030, 0x80000001}, + {7, 3, 0x3F040, 0x80000009}, + {7, 3, 0x3F048, 0x80000005}, + {7, 3, 0x3F104, 0x80000000}, + {7, 3, 0x3F114, 0x80000000}, + {7, 3, 0x3F124, 0x80000000}, + {7, 3, 0x3F12C, 0x80000000}, + {7, 3, 0x3F130, 0x80000000}, + {7, 3, 0x3F140, 0x80000000}, + {7, 3, 0x3F144, 0x80000000}, + {7, 3, 0x3F148, 0x80000000}, + {7, 4, 0x3F004, 0x8000000C}, + {7, 4, 0x3F008, 0x80000008}, + {7, 4, 0x3F018, 0x8000000D}, + {7, 4, 0x3F01C, 0x8000000F}, + {7, 4, 0x3F020, 0x80000001}, + {7, 4, 0x3F03C, 0x8000000A}, + {7, 4, 0x3F104, 0x80000000}, + {7, 4, 0x3F120, 0x80000000}, + {7, 4, 0x3F128, 0x80000000}, + {7, 4, 0x3F130, 0x80000000}, + {7, 4, 0x3F134, 0x80000000}, + {7, 4, 0x3F13C, 0x80000000}, + {7, 5, 0x3F004, 0x80000007}, + {7, 5, 0x3F014, 0x80000001}, + {7, 5, 0x3F104, 0x80000000}, + {7, 5, 0x3F11C, 0x80000000}, + }, + // shim mux / demux mask writes: (col, row, offset, mask, value) + { + {0, 0, 0x1F000, 0x0000C000, 0x00004000}, + {0, 0, 0x1F000, 0x00000C00, 0x00000400}, + {0, 0, 0x1F004, 0x00000030, 0x00000010}, + {1, 0, 0x1F000, 0x0000C000, 0x00004000}, + {1, 0, 0x1F004, 0x00000030, 0x00000010}, + {2, 0, 0x1F000, 0x0000C000, 0x00004000}, + {2, 0, 0x1F000, 0x00000C00, 0x00000400}, + {2, 0, 0x1F004, 0x00000030, 0x00000010}, + {3, 0, 0x1F000, 0x0000C000, 0x00004000}, + {3, 0, 0x1F004, 0x00000030, 0x00000010}, + {4, 0, 0x1F000, 0x0000C000, 0x00004000}, + {4, 0, 0x1F000, 0x00000C00, 0x00000400}, + {4, 0, 0x1F004, 0x00000030, 0x00000010}, + {5, 0, 0x1F000, 0x0000C000, 0x00004000}, + {5, 0, 0x1F004, 0x00000030, 0x00000010}, + {6, 0, 0x1F000, 0x0000C000, 0x00004000}, + {6, 0, 0x1F000, 0x00000C00, 0x00000400}, + {6, 0, 0x1F004, 0x00000030, 0x00000010}, + {7, 0, 0x1F000, 0x0000C000, 0x00004000}, + {7, 0, 0x1F004, 0x00000030, 0x00000010}, + }, + // BD registers: (col, row, offset, shared, words) + { + {0, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {0, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {0, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {0, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {0, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {0, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {0, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {0, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {0, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {0, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {0, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {0, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {0, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {0, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {0, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {0, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {0, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {0, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {0, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {0, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {1, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {1, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {1, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {1, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {1, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {1, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {1, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {1, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {1, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {1, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {1, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {1, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {1, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {1, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {1, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {1, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {1, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {1, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {1, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {1, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {2, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {2, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {2, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {2, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {2, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {2, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {2, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {2, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {2, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {2, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {2, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {2, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {2, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {2, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {2, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {2, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {2, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {2, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {2, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {2, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {3, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {3, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {3, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {3, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {3, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {3, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {3, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {3, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {3, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {3, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {3, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {3, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {3, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {3, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {3, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {3, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {3, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {3, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {3, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {3, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {4, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {4, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {4, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {4, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {4, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {4, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {4, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {4, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {4, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {4, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {4, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {4, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {4, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {4, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {4, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {4, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {4, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {4, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {4, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {4, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {5, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {5, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {5, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {5, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {5, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {5, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {5, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {5, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {5, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {5, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {5, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {5, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {5, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {5, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {5, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {5, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {5, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {5, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {5, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {5, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {6, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {6, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {6, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {6, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {6, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {6, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {6, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {6, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {6, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {6, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {6, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {6, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {6, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {6, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {6, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {6, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {6, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {6, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {6, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {6, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {7, 2, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {7, 2, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {7, 2, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {7, 2, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {7, 2, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {7, 2, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {7, 3, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {7, 3, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {7, 3, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {7, 3, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {7, 4, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {7, 4, 0x1D040, false, {0x0B0004A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E087FC2}}, + {7, 4, 0x1D080, false, {0x0D500080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2E049FE5}}, + {7, 4, 0x1D0A0, false, {0x0D700080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x26049FE5}}, + {7, 4, 0x1D060, false, {0x0C2804A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16087FC2}}, + {7, 4, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {7, 5, 0x1D000, false, {0x01000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x0E043FE0}}, + {7, 5, 0x1D040, false, {0x0F800080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1E049FE5}}, + {7, 5, 0x1D060, false, {0x0FA00080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x16049FE5}}, + {7, 5, 0x1D020, false, {0x02000400, 0x00000000, 0x0007E000, 0x02008003, 0x00000000, 0x06043FE0}}, + {0, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {0, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {0, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {0, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {0, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {0, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {0, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {0, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {0, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {0, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {0, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {0, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {0, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {0, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {0, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {0, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {0, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {0, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {0, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {0, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {1, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {1, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {1, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {1, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {1, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {1, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {1, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {1, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {1, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {1, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {1, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {1, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {1, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {1, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {1, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {1, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {1, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {1, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {2, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {2, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {2, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {2, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {2, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {2, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {2, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {2, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {2, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {2, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {2, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {2, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {2, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {2, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {2, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {2, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {2, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {2, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {2, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {2, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {3, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {3, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {3, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {3, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {3, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {3, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {3, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {3, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {3, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {3, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {3, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {3, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {3, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {3, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {3, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {3, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {3, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {3, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {4, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {4, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {4, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {4, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {4, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {4, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {4, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {4, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {4, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {4, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {4, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {4, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {4, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {4, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {4, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {4, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {4, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {4, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {4, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {4, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {5, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {5, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {5, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {5, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {5, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {5, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {5, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {5, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {5, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {5, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {5, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {5, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {5, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {5, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {5, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {5, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {5, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {5, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {6, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {6, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {6, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {6, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {6, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {6, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {6, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {6, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {6, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {6, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {6, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {6, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {6, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {6, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {6, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {6, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {6, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {6, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {6, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {6, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0000, false, {0x00008000, 0x001A0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0040, false, {0x00004000, 0x003A0000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {7, 1, 0xA0300, false, {0x00001000, 0x019B0000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {7, 1, 0xA00C0, false, {0x00001000, 0x007B1000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {7, 1, 0xA0340, false, {0x00001000, 0x01BB2000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {7, 1, 0xA0100, false, {0x00001000, 0x009B3000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8147FF45}}, + {7, 1, 0xA0380, false, {0x00004000, 0x01DB0000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8445FC47}}, + {7, 1, 0xA03C0, false, {0x000004A0, 0x01FB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {7, 1, 0xA0140, false, {0x000004A0, 0x00BB8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {7, 1, 0xA0160, false, {0x000004A0, 0x00AB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814AFF4B}}, + {7, 1, 0xA03E0, false, {0x000004A0, 0x01EB84A0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x814BFF4A}}, + {7, 1, 0xA03A0, false, {0x00004000, 0x01CB4000, 0x00400000, 0x00080FFF, 0x0100001F, 0x00000000, 0x00000000, 0x8446FC48}}, + {7, 1, 0xA0120, false, {0x00001000, 0x008B7000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {7, 1, 0xA0360, false, {0x00001000, 0x01AB6000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {7, 1, 0xA00E0, false, {0x00001000, 0x006B5000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {7, 1, 0xA0320, false, {0x00001000, 0x018B4000, 0x00080000, 0x0010001F, 0x00100003, 0x000000FF, 0x00000000, 0x8148FF46}}, + {7, 1, 0xA0060, false, {0x00004000, 0x004A0080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {7, 1, 0xA0080, false, {0x00004000, 0x005A8000, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8142FF41}}, + {7, 1, 0xA00A0, false, {0x00004000, 0x002A8080, 0x00800000, 0x002000FF, 0x0004003F, 0x00000FFF, 0x00000000, 0x8140FF42}}, + {7, 1, 0xA0020, false, {0x00008000, 0x000A8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + }, + // lock values: (col, row, offset, value) + { + {0, 1, 0xC0000, 2}, + {0, 1, 0xC0010, 0}, + {0, 1, 0xC0020, 0}, + {0, 1, 0xC0030, 0}, + {0, 1, 0xC0040, 0}, + {0, 1, 0xC0050, 4}, + {0, 1, 0xC0060, 4}, + {0, 1, 0xC0070, 0}, + {0, 1, 0xC0080, 0}, + {0, 1, 0xC00A0, 2}, + {0, 1, 0xC00B0, 0}, + {0, 2, 0x1F000, 2}, + {0, 2, 0x1F010, 0}, + {0, 2, 0x1F020, 4}, + {0, 2, 0x1F030, 0}, + {0, 2, 0x1F040, 2}, + {0, 2, 0x1F050, 0}, + {0, 2, 0x1F060, 0}, + {0, 2, 0x1F0F0, 0}, + {0, 3, 0x1F000, 2}, + {0, 3, 0x1F010, 0}, + {0, 3, 0x1F040, 2}, + {0, 3, 0x1F050, 0}, + {0, 3, 0x1F060, 0}, + {0, 3, 0x1F0F0, 0}, + {0, 4, 0x1F000, 2}, + {0, 4, 0x1F010, 0}, + {0, 4, 0x1F020, 4}, + {0, 4, 0x1F030, 0}, + {0, 4, 0x1F040, 2}, + {0, 4, 0x1F050, 0}, + {0, 4, 0x1F060, 0}, + {0, 4, 0x1F0F0, 0}, + {0, 5, 0x1F000, 2}, + {0, 5, 0x1F010, 0}, + {0, 5, 0x1F040, 2}, + {0, 5, 0x1F050, 0}, + {0, 5, 0x1F060, 0}, + {0, 5, 0x1F0F0, 0}, + {1, 1, 0xC0000, 2}, + {1, 1, 0xC0010, 0}, + {1, 1, 0xC0020, 0}, + {1, 1, 0xC0030, 0}, + {1, 1, 0xC0040, 0}, + {1, 1, 0xC0050, 4}, + {1, 1, 0xC0060, 4}, + {1, 1, 0xC0070, 0}, + {1, 1, 0xC0080, 0}, + {1, 1, 0xC00A0, 2}, + {1, 1, 0xC00B0, 0}, + {1, 2, 0x1F000, 2}, + {1, 2, 0x1F010, 0}, + {1, 2, 0x1F020, 4}, + {1, 2, 0x1F030, 0}, + {1, 2, 0x1F040, 2}, + {1, 2, 0x1F050, 0}, + {1, 2, 0x1F060, 0}, + {1, 2, 0x1F0F0, 0}, + {1, 3, 0x1F000, 2}, + {1, 3, 0x1F010, 0}, + {1, 3, 0x1F040, 2}, + {1, 3, 0x1F050, 0}, + {1, 3, 0x1F060, 0}, + {1, 3, 0x1F0F0, 0}, + {1, 4, 0x1F000, 2}, + {1, 4, 0x1F010, 0}, + {1, 4, 0x1F020, 4}, + {1, 4, 0x1F030, 0}, + {1, 4, 0x1F040, 2}, + {1, 4, 0x1F050, 0}, + {1, 4, 0x1F060, 0}, + {1, 4, 0x1F0F0, 0}, + {1, 5, 0x1F000, 2}, + {1, 5, 0x1F010, 0}, + {1, 5, 0x1F040, 2}, + {1, 5, 0x1F050, 0}, + {1, 5, 0x1F060, 0}, + {1, 5, 0x1F0F0, 0}, + {2, 1, 0xC0000, 2}, + {2, 1, 0xC0010, 0}, + {2, 1, 0xC0020, 0}, + {2, 1, 0xC0030, 0}, + {2, 1, 0xC0040, 0}, + {2, 1, 0xC0050, 4}, + {2, 1, 0xC0060, 4}, + {2, 1, 0xC0070, 0}, + {2, 1, 0xC0080, 0}, + {2, 1, 0xC00A0, 2}, + {2, 1, 0xC00B0, 0}, + {2, 2, 0x1F000, 2}, + {2, 2, 0x1F010, 0}, + {2, 2, 0x1F020, 4}, + {2, 2, 0x1F030, 0}, + {2, 2, 0x1F040, 2}, + {2, 2, 0x1F050, 0}, + {2, 2, 0x1F060, 0}, + {2, 2, 0x1F0F0, 0}, + {2, 3, 0x1F000, 2}, + {2, 3, 0x1F010, 0}, + {2, 3, 0x1F040, 2}, + {2, 3, 0x1F050, 0}, + {2, 3, 0x1F060, 0}, + {2, 3, 0x1F0F0, 0}, + {2, 4, 0x1F000, 2}, + {2, 4, 0x1F010, 0}, + {2, 4, 0x1F020, 4}, + {2, 4, 0x1F030, 0}, + {2, 4, 0x1F040, 2}, + {2, 4, 0x1F050, 0}, + {2, 4, 0x1F060, 0}, + {2, 4, 0x1F0F0, 0}, + {2, 5, 0x1F000, 2}, + {2, 5, 0x1F010, 0}, + {2, 5, 0x1F040, 2}, + {2, 5, 0x1F050, 0}, + {2, 5, 0x1F060, 0}, + {2, 5, 0x1F0F0, 0}, + {3, 1, 0xC0000, 2}, + {3, 1, 0xC0010, 0}, + {3, 1, 0xC0020, 0}, + {3, 1, 0xC0030, 0}, + {3, 1, 0xC0040, 0}, + {3, 1, 0xC0050, 4}, + {3, 1, 0xC0060, 4}, + {3, 1, 0xC0070, 0}, + {3, 1, 0xC0080, 0}, + {3, 1, 0xC00A0, 2}, + {3, 1, 0xC00B0, 0}, + {3, 2, 0x1F000, 2}, + {3, 2, 0x1F010, 0}, + {3, 2, 0x1F020, 4}, + {3, 2, 0x1F030, 0}, + {3, 2, 0x1F040, 2}, + {3, 2, 0x1F050, 0}, + {3, 2, 0x1F060, 0}, + {3, 2, 0x1F0F0, 0}, + {3, 3, 0x1F000, 2}, + {3, 3, 0x1F010, 0}, + {3, 3, 0x1F040, 2}, + {3, 3, 0x1F050, 0}, + {3, 3, 0x1F060, 0}, + {3, 3, 0x1F0F0, 0}, + {3, 4, 0x1F000, 2}, + {3, 4, 0x1F010, 0}, + {3, 4, 0x1F020, 4}, + {3, 4, 0x1F030, 0}, + {3, 4, 0x1F040, 2}, + {3, 4, 0x1F050, 0}, + {3, 4, 0x1F060, 0}, + {3, 4, 0x1F0F0, 0}, + {3, 5, 0x1F000, 2}, + {3, 5, 0x1F010, 0}, + {3, 5, 0x1F040, 2}, + {3, 5, 0x1F050, 0}, + {3, 5, 0x1F060, 0}, + {3, 5, 0x1F0F0, 0}, + {4, 1, 0xC0000, 2}, + {4, 1, 0xC0010, 0}, + {4, 1, 0xC0020, 0}, + {4, 1, 0xC0030, 0}, + {4, 1, 0xC0040, 0}, + {4, 1, 0xC0050, 4}, + {4, 1, 0xC0060, 4}, + {4, 1, 0xC0070, 0}, + {4, 1, 0xC0080, 0}, + {4, 1, 0xC00A0, 2}, + {4, 1, 0xC00B0, 0}, + {4, 2, 0x1F000, 2}, + {4, 2, 0x1F010, 0}, + {4, 2, 0x1F020, 4}, + {4, 2, 0x1F030, 0}, + {4, 2, 0x1F040, 2}, + {4, 2, 0x1F050, 0}, + {4, 2, 0x1F060, 0}, + {4, 2, 0x1F0F0, 0}, + {4, 3, 0x1F000, 2}, + {4, 3, 0x1F010, 0}, + {4, 3, 0x1F040, 2}, + {4, 3, 0x1F050, 0}, + {4, 3, 0x1F060, 0}, + {4, 3, 0x1F0F0, 0}, + {4, 4, 0x1F000, 2}, + {4, 4, 0x1F010, 0}, + {4, 4, 0x1F020, 4}, + {4, 4, 0x1F030, 0}, + {4, 4, 0x1F040, 2}, + {4, 4, 0x1F050, 0}, + {4, 4, 0x1F060, 0}, + {4, 4, 0x1F0F0, 0}, + {4, 5, 0x1F000, 2}, + {4, 5, 0x1F010, 0}, + {4, 5, 0x1F040, 2}, + {4, 5, 0x1F050, 0}, + {4, 5, 0x1F060, 0}, + {4, 5, 0x1F0F0, 0}, + {5, 1, 0xC0000, 2}, + {5, 1, 0xC0010, 0}, + {5, 1, 0xC0020, 0}, + {5, 1, 0xC0030, 0}, + {5, 1, 0xC0040, 0}, + {5, 1, 0xC0050, 4}, + {5, 1, 0xC0060, 4}, + {5, 1, 0xC0070, 0}, + {5, 1, 0xC0080, 0}, + {5, 1, 0xC00A0, 2}, + {5, 1, 0xC00B0, 0}, + {5, 2, 0x1F000, 2}, + {5, 2, 0x1F010, 0}, + {5, 2, 0x1F020, 4}, + {5, 2, 0x1F030, 0}, + {5, 2, 0x1F040, 2}, + {5, 2, 0x1F050, 0}, + {5, 2, 0x1F060, 0}, + {5, 2, 0x1F0F0, 0}, + {5, 3, 0x1F000, 2}, + {5, 3, 0x1F010, 0}, + {5, 3, 0x1F040, 2}, + {5, 3, 0x1F050, 0}, + {5, 3, 0x1F060, 0}, + {5, 3, 0x1F0F0, 0}, + {5, 4, 0x1F000, 2}, + {5, 4, 0x1F010, 0}, + {5, 4, 0x1F020, 4}, + {5, 4, 0x1F030, 0}, + {5, 4, 0x1F040, 2}, + {5, 4, 0x1F050, 0}, + {5, 4, 0x1F060, 0}, + {5, 4, 0x1F0F0, 0}, + {5, 5, 0x1F000, 2}, + {5, 5, 0x1F010, 0}, + {5, 5, 0x1F040, 2}, + {5, 5, 0x1F050, 0}, + {5, 5, 0x1F060, 0}, + {5, 5, 0x1F0F0, 0}, + {6, 1, 0xC0000, 2}, + {6, 1, 0xC0010, 0}, + {6, 1, 0xC0020, 0}, + {6, 1, 0xC0030, 0}, + {6, 1, 0xC0040, 0}, + {6, 1, 0xC0050, 4}, + {6, 1, 0xC0060, 4}, + {6, 1, 0xC0070, 0}, + {6, 1, 0xC0080, 0}, + {6, 1, 0xC00A0, 2}, + {6, 1, 0xC00B0, 0}, + {6, 2, 0x1F000, 2}, + {6, 2, 0x1F010, 0}, + {6, 2, 0x1F020, 4}, + {6, 2, 0x1F030, 0}, + {6, 2, 0x1F040, 2}, + {6, 2, 0x1F050, 0}, + {6, 2, 0x1F060, 0}, + {6, 2, 0x1F0F0, 0}, + {6, 3, 0x1F000, 2}, + {6, 3, 0x1F010, 0}, + {6, 3, 0x1F040, 2}, + {6, 3, 0x1F050, 0}, + {6, 3, 0x1F060, 0}, + {6, 3, 0x1F0F0, 0}, + {6, 4, 0x1F000, 2}, + {6, 4, 0x1F010, 0}, + {6, 4, 0x1F020, 4}, + {6, 4, 0x1F030, 0}, + {6, 4, 0x1F040, 2}, + {6, 4, 0x1F050, 0}, + {6, 4, 0x1F060, 0}, + {6, 4, 0x1F0F0, 0}, + {6, 5, 0x1F000, 2}, + {6, 5, 0x1F010, 0}, + {6, 5, 0x1F040, 2}, + {6, 5, 0x1F050, 0}, + {6, 5, 0x1F060, 0}, + {6, 5, 0x1F0F0, 0}, + {7, 1, 0xC0000, 2}, + {7, 1, 0xC0010, 0}, + {7, 1, 0xC0020, 0}, + {7, 1, 0xC0030, 0}, + {7, 1, 0xC0040, 0}, + {7, 1, 0xC0050, 4}, + {7, 1, 0xC0060, 4}, + {7, 1, 0xC0070, 0}, + {7, 1, 0xC0080, 0}, + {7, 1, 0xC00A0, 2}, + {7, 1, 0xC00B0, 0}, + {7, 2, 0x1F000, 2}, + {7, 2, 0x1F010, 0}, + {7, 2, 0x1F020, 4}, + {7, 2, 0x1F030, 0}, + {7, 2, 0x1F040, 2}, + {7, 2, 0x1F050, 0}, + {7, 2, 0x1F060, 0}, + {7, 2, 0x1F0F0, 0}, + {7, 3, 0x1F000, 2}, + {7, 3, 0x1F010, 0}, + {7, 3, 0x1F040, 2}, + {7, 3, 0x1F050, 0}, + {7, 3, 0x1F060, 0}, + {7, 3, 0x1F0F0, 0}, + {7, 4, 0x1F000, 2}, + {7, 4, 0x1F010, 0}, + {7, 4, 0x1F020, 4}, + {7, 4, 0x1F030, 0}, + {7, 4, 0x1F040, 2}, + {7, 4, 0x1F050, 0}, + {7, 4, 0x1F060, 0}, + {7, 4, 0x1F0F0, 0}, + {7, 5, 0x1F000, 2}, + {7, 5, 0x1F010, 0}, + {7, 5, 0x1F040, 2}, + {7, 5, 0x1F050, 0}, + {7, 5, 0x1F060, 0}, + {7, 5, 0x1F0F0, 0}, + }, + // channels: (col, row, control offset, start queue offset, queue value, control value) + { + {0, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {0, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {0, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {0, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {0, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {0, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {0, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {0, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {0, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {0, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {1, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {1, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {1, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {1, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {1, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {1, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {1, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {1, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {1, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {1, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {2, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {2, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {2, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {2, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {2, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {2, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {2, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {2, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {2, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {2, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {3, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {3, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {3, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {3, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {3, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {3, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {3, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {3, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {3, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {3, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {4, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {4, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {4, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {4, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {4, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {4, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {4, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {4, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {4, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {4, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {5, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {5, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {5, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {5, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {5, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {5, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {5, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {5, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {5, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {5, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {6, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {6, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {6, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {6, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {6, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {6, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {6, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {6, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {6, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {6, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {7, 2, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {7, 2, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {7, 2, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {7, 3, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {7, 3, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {7, 4, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {7, 4, 0x1DE08, 0x1DE0C, 0x00000002, 1}, + {7, 4, 0x1DE10, 0x1DE14, 0x00000004, 1}, + {7, 5, 0x1DE00, 0x1DE04, 0x00000000, 1}, + {7, 5, 0x1DE10, 0x1DE14, 0x00000002, 1}, + {0, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {0, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {0, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {0, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {0, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {0, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {0, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {0, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {0, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {1, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {1, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {1, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {1, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {1, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {1, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {1, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {1, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {1, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {2, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {2, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {2, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {2, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {2, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {2, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {2, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {2, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {2, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {3, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {3, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {3, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {3, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {3, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {3, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {3, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {3, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {3, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {4, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {4, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {4, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {4, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {4, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {4, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {4, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {4, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {4, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {5, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {5, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {5, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {5, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {5, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {5, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {5, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {5, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {5, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {6, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {6, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {6, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {6, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {6, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {6, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {6, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {6, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {6, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + {7, 1, 0xA0600, 0xA0604, 0x00000000, 1}, + {7, 1, 0xA0630, 0xA0634, 0x00000002, 1}, + {7, 1, 0xA0608, 0xA060C, 0x00000018, 1}, + {7, 1, 0xA0610, 0xA0614, 0x00000006, 1}, + {7, 1, 0xA0618, 0xA061C, 0x0000001A, 1}, + {7, 1, 0xA0620, 0xA0624, 0x00000008, 1}, + {7, 1, 0xA0638, 0xA063C, 0x0000001C, 1}, + {7, 1, 0xA0628, 0xA062C, 0x0000001E, 1}, + {7, 1, 0xA0640, 0xA0644, 0x0000000A, 1}, + }, +}; + +inline const op_config op_attn = { + // stream switch registers: (col, row, offset, value) + { + {0, 0, 0x3F008, 0xC0000045}, + {0, 0, 0x3F010, 0x80000010}, + {0, 0, 0x3F03C, 0x80000009}, + {0, 0, 0x3F044, 0x80000005}, + {0, 0, 0x3F100, 0xC0000000}, + {0, 0, 0x3F114, 0x80000000}, + {0, 0, 0x3F124, 0x80000000}, + {0, 0, 0x3F140, 0x80000000}, + {0, 0, 0x3F200, 0x0F1F0135}, + {0, 1, 0xB0000, 0x8000000C}, + {0, 1, 0xB0004, 0x8000000A}, + {0, 1, 0xB0008, 0x8000000E}, + {0, 1, 0xB000C, 0x8000000F}, + {0, 1, 0xB0010, 0x80000010}, + {0, 1, 0xB0014, 0x8000000D}, + {0, 1, 0xB0024, 0x80000005}, + {0, 1, 0xB002C, 0x80000000}, + {0, 1, 0xB0030, 0x80000003}, + {0, 1, 0xB0038, 0x80000001}, + {0, 1, 0xB0040, 0x80000002}, + {0, 1, 0xB0100, 0x80000000}, + {0, 1, 0xB0104, 0x80000000}, + {0, 1, 0xB0108, 0x80000000}, + {0, 1, 0xB010C, 0x80000000}, + {0, 1, 0xB0114, 0x80000000}, + {0, 1, 0xB0128, 0x80000000}, + {0, 1, 0xB0130, 0x80000000}, + {0, 1, 0xB0134, 0x80000000}, + {0, 1, 0xB0138, 0x80000000}, + {0, 1, 0xB013C, 0x80000000}, + {0, 1, 0xB0140, 0x80000000}, + {0, 2, 0x3F004, 0x80000005}, + {0, 2, 0x3F008, 0x80000014}, + {0, 2, 0x3F014, 0x80000011}, + {0, 2, 0x3F018, 0x80000001}, + {0, 2, 0x3F01C, 0x80000016}, + {0, 2, 0x3F020, 0x80000010}, + {0, 2, 0x3F040, 0x80000006}, + {0, 2, 0x3F044, 0x80000008}, + {0, 2, 0x3F048, 0x8000000A}, + {0, 2, 0x3F050, 0x80000005}, + {0, 2, 0x3F058, 0x80000008}, + {0, 2, 0x3F104, 0x80000000}, + {0, 2, 0x3F114, 0x80000000}, + {0, 2, 0x3F118, 0x80000000}, + {0, 2, 0x3F120, 0x80000000}, + {0, 2, 0x3F128, 0x80000000}, + {0, 2, 0x3F140, 0x80000000}, + {0, 2, 0x3F144, 0x80000000}, + {0, 2, 0x3F150, 0x80000000}, + {0, 2, 0x3F158, 0x80000000}, + {0, 3, 0x3F004, 0x80000009}, + {0, 3, 0x3F008, 0x80000014}, + {0, 3, 0x3F018, 0x80000001}, + {0, 3, 0x3F01C, 0x80000016}, + {0, 3, 0x3F034, 0x80000008}, + {0, 3, 0x3F038, 0x8000000A}, + {0, 3, 0x3F04C, 0x8000000F}, + {0, 3, 0x3F104, 0x80000000}, + {0, 3, 0x3F120, 0x80000000}, + {0, 3, 0x3F124, 0x80000000}, + {0, 3, 0x3F128, 0x80000000}, + {0, 3, 0x3F13C, 0x80000000}, + {0, 3, 0x3F150, 0x80000000}, + {0, 3, 0x3F158, 0x80000000}, + {0, 4, 0x3F004, 0x80000006}, + {0, 4, 0x3F008, 0x80000014}, + {0, 4, 0x3F014, 0x8000000F}, + {0, 4, 0x3F03C, 0x80000005}, + {0, 4, 0x3F04C, 0x80000006}, + {0, 4, 0x3F050, 0x80000001}, + {0, 4, 0x3F054, 0x80000005}, + {0, 4, 0x3F104, 0x80000000}, + {0, 4, 0x3F114, 0x80000000}, + {0, 4, 0x3F118, 0x80000000}, + {0, 4, 0x3F13C, 0x80000000}, + {0, 4, 0x3F150, 0x80000000}, + {0, 5, 0x3F004, 0x80000007}, + {0, 5, 0x3F008, 0x80000015}, + {0, 5, 0x3F014, 0x80000001}, + {0, 5, 0x3F104, 0x80000000}, + {0, 5, 0x3F11C, 0x80000000}, + {0, 5, 0x3F154, 0x80000000}, + {1, 0, 0x3F008, 0xC0000045}, + {1, 0, 0x3F010, 0x80000010}, + {1, 0, 0x3F100, 0xC0000000}, + {1, 0, 0x3F140, 0x80000000}, + {1, 0, 0x3F200, 0x0F1F0135}, + {1, 1, 0xB0008, 0x8000000D}, + {1, 1, 0xB000C, 0x8000000F}, + {1, 1, 0xB0010, 0x80000010}, + {1, 1, 0xB0014, 0x8000000E}, + {1, 1, 0xB0024, 0x80000005}, + {1, 1, 0xB0114, 0x80000000}, + {1, 1, 0xB0134, 0x80000000}, + {1, 1, 0xB0138, 0x80000000}, + {1, 1, 0xB013C, 0x80000000}, + {1, 1, 0xB0140, 0x80000000}, + {1, 2, 0x3F004, 0x8000000C}, + {1, 2, 0x3F008, 0x80000014}, + {1, 2, 0x3F014, 0x8000000F}, + {1, 2, 0x3F018, 0x80000012}, + {1, 2, 0x3F01C, 0x80000010}, + {1, 2, 0x3F020, 0x80000011}, + {1, 2, 0x3F028, 0x80000014}, + {1, 2, 0x3F030, 0x80000001}, + {1, 2, 0x3F038, 0x8000000E}, + {1, 2, 0x3F104, 0x80000000}, + {1, 2, 0x3F130, 0x80000000}, + {1, 2, 0x3F138, 0x80000000}, + {1, 2, 0x3F13C, 0x80000000}, + {1, 2, 0x3F140, 0x80000000}, + {1, 2, 0x3F144, 0x80000000}, + {1, 2, 0x3F148, 0x80000000}, + {1, 2, 0x3F150, 0x80000000}, + {1, 3, 0x3F004, 0x80000006}, + {1, 3, 0x3F008, 0x80000013}, + {1, 3, 0x3F014, 0x8000000F}, + {1, 3, 0x3F018, 0x80000011}, + {1, 3, 0x3F01C, 0x8000000B}, + {1, 3, 0x3F020, 0x80000012}, + {1, 3, 0x3F028, 0x80000013}, + {1, 3, 0x3F030, 0x80000001}, + {1, 3, 0x3F048, 0x80000013}, + {1, 3, 0x3F104, 0x80000000}, + {1, 3, 0x3F118, 0x80000000}, + {1, 3, 0x3F12C, 0x80000000}, + {1, 3, 0x3F13C, 0x80000000}, + {1, 3, 0x3F144, 0x80000000}, + {1, 3, 0x3F148, 0x80000000}, + {1, 3, 0x3F14C, 0x80000000}, + {1, 4, 0x3F004, 0x8000000B}, + {1, 4, 0x3F008, 0x8000000A}, + {1, 4, 0x3F014, 0x8000000C}, + {1, 4, 0x3F01C, 0x80000001}, + {1, 4, 0x3F020, 0x8000000F}, + {1, 4, 0x3F028, 0x8000000A}, + {1, 4, 0x3F03C, 0x8000000D}, + {1, 4, 0x3F104, 0x80000000}, + {1, 4, 0x3F128, 0x80000000}, + {1, 4, 0x3F12C, 0x80000000}, + {1, 4, 0x3F130, 0x80000000}, + {1, 4, 0x3F134, 0x80000000}, + {1, 4, 0x3F13C, 0x80000000}, + {1, 5, 0x3F004, 0x80000007}, + {1, 5, 0x3F008, 0x80000013}, + {1, 5, 0x3F014, 0x80000001}, + {1, 5, 0x3F02C, 0x80000013}, + {1, 5, 0x3F104, 0x80000000}, + {1, 5, 0x3F11C, 0x80000000}, + {1, 5, 0x3F14C, 0x80000000}, + {2, 0, 0x3F008, 0xC0000045}, + {2, 0, 0x3F010, 0x80000010}, + {2, 0, 0x3F034, 0x80000005}, + {2, 0, 0x3F044, 0x80000009}, + {2, 0, 0x3F100, 0xC0000000}, + {2, 0, 0x3F114, 0x80000000}, + {2, 0, 0x3F124, 0x80000000}, + {2, 0, 0x3F140, 0x80000000}, + {2, 0, 0x3F200, 0x0F1F0135}, + {2, 1, 0xB0000, 0x80000008}, + {2, 1, 0xB0004, 0x8000000C}, + {2, 1, 0xB0008, 0x8000000F}, + {2, 1, 0xB000C, 0x80000010}, + {2, 1, 0xB0010, 0x8000000E}, + {2, 1, 0xB0014, 0x8000000D}, + {2, 1, 0xB0024, 0x80000005}, + {2, 1, 0xB002C, 0x80000002}, + {2, 1, 0xB0030, 0x80000003}, + {2, 1, 0xB0038, 0x80000001}, + {2, 1, 0xB0040, 0x80000000}, + {2, 1, 0xB0100, 0x80000000}, + {2, 1, 0xB0104, 0x80000000}, + {2, 1, 0xB0108, 0x80000000}, + {2, 1, 0xB010C, 0x80000000}, + {2, 1, 0xB0114, 0x80000000}, + {2, 1, 0xB0120, 0x80000000}, + {2, 1, 0xB0130, 0x80000000}, + {2, 1, 0xB0134, 0x80000000}, + {2, 1, 0xB0138, 0x80000000}, + {2, 1, 0xB013C, 0x80000000}, + {2, 1, 0xB0140, 0x80000000}, + {2, 2, 0x3F004, 0x8000000A}, + {2, 2, 0x3F008, 0x80000013}, + {2, 2, 0x3F014, 0x8000000F}, + {2, 2, 0x3F018, 0x80000011}, + {2, 2, 0x3F01C, 0x80000001}, + {2, 2, 0x3F020, 0x80000014}, + {2, 2, 0x3F028, 0x80000013}, + {2, 2, 0x3F034, 0x80000006}, + {2, 2, 0x3F03C, 0x80000005}, + {2, 2, 0x3F048, 0x80000008}, + {2, 2, 0x3F04C, 0x80000008}, + {2, 2, 0x3F050, 0x8000000A}, + {2, 2, 0x3F054, 0x80000010}, + {2, 2, 0x3F104, 0x80000000}, + {2, 2, 0x3F114, 0x80000000}, + {2, 2, 0x3F118, 0x80000000}, + {2, 2, 0x3F120, 0x80000000}, + {2, 2, 0x3F128, 0x80000000}, + {2, 2, 0x3F13C, 0x80000000}, + {2, 2, 0x3F140, 0x80000000}, + {2, 2, 0x3F144, 0x80000000}, + {2, 2, 0x3F14C, 0x80000000}, + {2, 2, 0x3F150, 0x80000000}, + {2, 3, 0x3F004, 0x8000000A}, + {2, 3, 0x3F008, 0x80000014}, + {2, 3, 0x3F014, 0x80000016}, + {2, 3, 0x3F018, 0x80000012}, + {2, 3, 0x3F01C, 0x80000001}, + {2, 3, 0x3F024, 0x80000014}, + {2, 3, 0x3F038, 0x80000007}, + {2, 3, 0x3F040, 0x80000014}, + {2, 3, 0x3F048, 0x80000005}, + {2, 3, 0x3F058, 0x8000000F}, + {2, 3, 0x3F104, 0x80000000}, + {2, 3, 0x3F114, 0x80000000}, + {2, 3, 0x3F11C, 0x80000000}, + {2, 3, 0x3F128, 0x80000000}, + {2, 3, 0x3F13C, 0x80000000}, + {2, 3, 0x3F148, 0x80000000}, + {2, 3, 0x3F150, 0x80000000}, + {2, 3, 0x3F158, 0x80000000}, + {2, 4, 0x3F004, 0x80000006}, + {2, 4, 0x3F008, 0x80000008}, + {2, 4, 0x3F014, 0x8000000F}, + {2, 4, 0x3F020, 0x80000001}, + {2, 4, 0x3F040, 0x8000000A}, + {2, 4, 0x3F044, 0x80000008}, + {2, 4, 0x3F050, 0x80000006}, + {2, 4, 0x3F104, 0x80000000}, + {2, 4, 0x3F118, 0x80000000}, + {2, 4, 0x3F120, 0x80000000}, + {2, 4, 0x3F128, 0x80000000}, + {2, 4, 0x3F13C, 0x80000000}, + {2, 5, 0x3F004, 0x80000008}, + {2, 5, 0x3F008, 0x80000009}, + {2, 5, 0x3F014, 0x80000001}, + {2, 5, 0x3F024, 0x80000009}, + {2, 5, 0x3F050, 0x80000008}, + {2, 5, 0x3F104, 0x80000000}, + {2, 5, 0x3F120, 0x80000000}, + {2, 5, 0x3F124, 0x80000000}, + {3, 0, 0x3F008, 0xC0000045}, + {3, 0, 0x3F010, 0x80000010}, + {3, 0, 0x3F034, 0x80000005}, + {3, 0, 0x3F044, 0x80000009}, + {3, 0, 0x3F100, 0xC0000000}, + {3, 0, 0x3F114, 0x80000000}, + {3, 0, 0x3F124, 0x80000000}, + {3, 0, 0x3F140, 0x80000000}, + {3, 0, 0x3F200, 0x0F1F0135}, + {3, 1, 0xB0000, 0x80000008}, + {3, 1, 0xB0004, 0x8000000C}, + {3, 1, 0xB0008, 0x8000000E}, + {3, 1, 0xB000C, 0x8000000F}, + {3, 1, 0xB0010, 0x80000010}, + {3, 1, 0xB0014, 0x8000000D}, + {3, 1, 0xB0024, 0x80000005}, + {3, 1, 0xB0030, 0x80000000}, + {3, 1, 0xB0100, 0x80000000}, + {3, 1, 0xB0114, 0x80000000}, + {3, 1, 0xB0120, 0x80000000}, + {3, 1, 0xB0130, 0x80000000}, + {3, 1, 0xB0134, 0x80000000}, + {3, 1, 0xB0138, 0x80000000}, + {3, 1, 0xB013C, 0x80000000}, + {3, 1, 0xB0140, 0x80000000}, + {3, 2, 0x3F004, 0x8000000C}, + {3, 2, 0x3F008, 0x80000006}, + {3, 2, 0x3F014, 0x8000000F}, + {3, 2, 0x3F018, 0x8000000D}, + {3, 2, 0x3F01C, 0x80000010}, + {3, 2, 0x3F020, 0x80000012}, + {3, 2, 0x3F024, 0x80000006}, + {3, 2, 0x3F028, 0x80000001}, + {3, 2, 0x3F038, 0x8000000B}, + {3, 2, 0x3F044, 0x80000006}, + {3, 2, 0x3F104, 0x80000000}, + {3, 2, 0x3F118, 0x80000000}, + {3, 2, 0x3F12C, 0x80000000}, + {3, 2, 0x3F130, 0x80000000}, + {3, 2, 0x3F134, 0x80000000}, + {3, 2, 0x3F13C, 0x80000000}, + {3, 2, 0x3F140, 0x80000000}, + {3, 2, 0x3F148, 0x80000000}, + {3, 3, 0x3F004, 0x80000006}, + {3, 3, 0x3F008, 0x80000009}, + {3, 3, 0x3F014, 0x80000012}, + {3, 3, 0x3F018, 0x80000010}, + {3, 3, 0x3F020, 0x8000000E}, + {3, 3, 0x3F028, 0x80000009}, + {3, 3, 0x3F030, 0x80000001}, + {3, 3, 0x3F044, 0x80000009}, + {3, 3, 0x3F104, 0x80000000}, + {3, 3, 0x3F118, 0x80000000}, + {3, 3, 0x3F124, 0x80000000}, + {3, 3, 0x3F138, 0x80000000}, + {3, 3, 0x3F140, 0x80000000}, + {3, 3, 0x3F148, 0x80000000}, + {3, 4, 0x3F004, 0x8000000C}, + {3, 4, 0x3F008, 0x80000009}, + {3, 4, 0x3F018, 0x80000001}, + {3, 4, 0x3F020, 0x8000000F}, + {3, 4, 0x3F038, 0x80000009}, + {3, 4, 0x3F104, 0x80000000}, + {3, 4, 0x3F124, 0x80000000}, + {3, 4, 0x3F130, 0x80000000}, + {3, 4, 0x3F13C, 0x80000000}, + {3, 5, 0x3F004, 0x8000000C}, + {3, 5, 0x3F008, 0x80000006}, + {3, 5, 0x3F014, 0x80000001}, + {3, 5, 0x3F104, 0x80000000}, + {3, 5, 0x3F118, 0x80000000}, + {3, 5, 0x3F130, 0x80000000}, + {4, 0, 0x3F008, 0xC0000045}, + {4, 0, 0x3F010, 0x80000010}, + {4, 0, 0x3F034, 0x80000005}, + {4, 0, 0x3F044, 0x80000009}, + {4, 0, 0x3F100, 0xC0000000}, + {4, 0, 0x3F114, 0x80000000}, + {4, 0, 0x3F124, 0x80000000}, + {4, 0, 0x3F140, 0x80000000}, + {4, 0, 0x3F200, 0x0F1F0135}, + {4, 1, 0xB0000, 0x80000008}, + {4, 1, 0xB0004, 0x8000000C}, + {4, 1, 0xB0008, 0x8000000F}, + {4, 1, 0xB000C, 0x8000000E}, + {4, 1, 0xB0010, 0x8000000D}, + {4, 1, 0xB0014, 0x80000010}, + {4, 1, 0xB0024, 0x80000005}, + {4, 1, 0xB002C, 0x80000000}, + {4, 1, 0xB0030, 0x80000003}, + {4, 1, 0xB0038, 0x80000001}, + {4, 1, 0xB0040, 0x80000002}, + {4, 1, 0xB0100, 0x80000000}, + {4, 1, 0xB0104, 0x80000000}, + {4, 1, 0xB0108, 0x80000000}, + {4, 1, 0xB010C, 0x80000000}, + {4, 1, 0xB0114, 0x80000000}, + {4, 1, 0xB0120, 0x80000000}, + {4, 1, 0xB0130, 0x80000000}, + {4, 1, 0xB0134, 0x80000000}, + {4, 1, 0xB0138, 0x80000000}, + {4, 1, 0xB013C, 0x80000000}, + {4, 1, 0xB0140, 0x80000000}, + {4, 2, 0x3F004, 0x80000005}, + {4, 2, 0x3F008, 0x80000013}, + {4, 2, 0x3F014, 0x80000012}, + {4, 2, 0x3F018, 0x80000015}, + {4, 2, 0x3F01C, 0x80000001}, + {4, 2, 0x3F020, 0x80000010}, + {4, 2, 0x3F034, 0x80000008}, + {4, 2, 0x3F038, 0x80000006}, + {4, 2, 0x3F03C, 0x8000000A}, + {4, 2, 0x3F04C, 0x80000008}, + {4, 2, 0x3F050, 0x80000005}, + {4, 2, 0x3F054, 0x8000000A}, + {4, 2, 0x3F058, 0x80000011}, + {4, 2, 0x3F104, 0x80000000}, + {4, 2, 0x3F114, 0x80000000}, + {4, 2, 0x3F118, 0x80000000}, + {4, 2, 0x3F120, 0x80000000}, + {4, 2, 0x3F128, 0x80000000}, + {4, 2, 0x3F140, 0x80000000}, + {4, 2, 0x3F144, 0x80000000}, + {4, 2, 0x3F148, 0x80000000}, + {4, 2, 0x3F14C, 0x80000000}, + {4, 2, 0x3F154, 0x80000000}, + {4, 3, 0x3F004, 0x80000005}, + {4, 3, 0x3F008, 0x80000014}, + {4, 3, 0x3F018, 0x80000016}, + {4, 3, 0x3F01C, 0x80000012}, + {4, 3, 0x3F020, 0x80000001}, + {4, 3, 0x3F038, 0x80000006}, + {4, 3, 0x3F040, 0x80000007}, + {4, 3, 0x3F104, 0x80000000}, + {4, 3, 0x3F114, 0x80000000}, + {4, 3, 0x3F118, 0x80000000}, + {4, 3, 0x3F11C, 0x80000000}, + {4, 3, 0x3F148, 0x80000000}, + {4, 3, 0x3F150, 0x80000000}, + {4, 3, 0x3F158, 0x80000000}, + {4, 4, 0x3F004, 0x80000008}, + {4, 4, 0x3F008, 0x80000014}, + {4, 4, 0x3F020, 0x80000001}, + {4, 4, 0x3F03C, 0x80000006}, + {4, 4, 0x3F044, 0x80000014}, + {4, 4, 0x3F04C, 0x80000006}, + {4, 4, 0x3F104, 0x80000000}, + {4, 4, 0x3F118, 0x80000000}, + {4, 4, 0x3F120, 0x80000000}, + {4, 4, 0x3F150, 0x80000000}, + {4, 5, 0x3F004, 0x80000007}, + {4, 5, 0x3F008, 0x80000009}, + {4, 5, 0x3F058, 0x80000001}, + {4, 5, 0x3F104, 0x80000000}, + {4, 5, 0x3F11C, 0x80000000}, + {4, 5, 0x3F124, 0x80000000}, + {5, 0, 0x3F008, 0xC0000045}, + {5, 0, 0x3F010, 0x80000010}, + {5, 0, 0x3F100, 0xC0000000}, + {5, 0, 0x3F140, 0x80000000}, + {5, 0, 0x3F200, 0x0F1F0135}, + {5, 1, 0xB0008, 0x80000010}, + {5, 1, 0xB000C, 0x8000000F}, + {5, 1, 0xB0010, 0x8000000E}, + {5, 1, 0xB0014, 0x8000000D}, + {5, 1, 0xB0024, 0x80000005}, + {5, 1, 0xB0114, 0x80000000}, + {5, 1, 0xB0134, 0x80000000}, + {5, 1, 0xB0138, 0x80000000}, + {5, 1, 0xB013C, 0x80000000}, + {5, 1, 0xB0140, 0x80000000}, + {5, 2, 0x3F004, 0x8000000C}, + {5, 2, 0x3F008, 0x80000013}, + {5, 2, 0x3F014, 0x80000011}, + {5, 2, 0x3F018, 0x80000010}, + {5, 2, 0x3F01C, 0x8000000F}, + {5, 2, 0x3F020, 0x8000000E}, + {5, 2, 0x3F024, 0x80000013}, + {5, 2, 0x3F02C, 0x80000001}, + {5, 2, 0x3F034, 0x8000000B}, + {5, 2, 0x3F038, 0x8000000D}, + {5, 2, 0x3F044, 0x80000013}, + {5, 2, 0x3F104, 0x80000000}, + {5, 2, 0x3F12C, 0x80000000}, + {5, 2, 0x3F130, 0x80000000}, + {5, 2, 0x3F134, 0x80000000}, + {5, 2, 0x3F138, 0x80000000}, + {5, 2, 0x3F13C, 0x80000000}, + {5, 2, 0x3F140, 0x80000000}, + {5, 2, 0x3F144, 0x80000000}, + {5, 2, 0x3F14C, 0x80000000}, + {5, 3, 0x3F004, 0x80000005}, + {5, 3, 0x3F008, 0x80000009}, + {5, 3, 0x3F014, 0x80000012}, + {5, 3, 0x3F018, 0x80000010}, + {5, 3, 0x3F01C, 0x80000011}, + {5, 3, 0x3F028, 0x80000009}, + {5, 3, 0x3F030, 0x80000001}, + {5, 3, 0x3F038, 0x80000009}, + {5, 3, 0x3F048, 0x80000006}, + {5, 3, 0x3F104, 0x80000000}, + {5, 3, 0x3F114, 0x80000000}, + {5, 3, 0x3F118, 0x80000000}, + {5, 3, 0x3F124, 0x80000000}, + {5, 3, 0x3F140, 0x80000000}, + {5, 3, 0x3F144, 0x80000000}, + {5, 3, 0x3F148, 0x80000000}, + {5, 4, 0x3F004, 0x8000000A}, + {5, 4, 0x3F008, 0x80000006}, + {5, 4, 0x3F018, 0x80000011}, + {5, 4, 0x3F01C, 0x8000000F}, + {5, 4, 0x3F020, 0x80000001}, + {5, 4, 0x3F028, 0x80000006}, + {5, 4, 0x3F044, 0x8000000B}, + {5, 4, 0x3F048, 0x80000006}, + {5, 4, 0x3F104, 0x80000000}, + {5, 4, 0x3F118, 0x80000000}, + {5, 4, 0x3F128, 0x80000000}, + {5, 4, 0x3F12C, 0x80000000}, + {5, 4, 0x3F13C, 0x80000000}, + {5, 4, 0x3F144, 0x80000000}, + {5, 5, 0x3F004, 0x80000009}, + {5, 5, 0x3F008, 0x8000000A}, + {5, 5, 0x3F014, 0x80000001}, + {5, 5, 0x3F01C, 0x8000000E}, + {5, 5, 0x3F104, 0x80000000}, + {5, 5, 0x3F124, 0x80000000}, + {5, 5, 0x3F128, 0x80000000}, + {5, 5, 0x3F138, 0x80000000}, + {6, 0, 0x3F008, 0xC0000045}, + {6, 0, 0x3F010, 0x80000010}, + {6, 0, 0x3F034, 0x80000005}, + {6, 0, 0x3F044, 0x80000009}, + {6, 0, 0x3F100, 0xC0000000}, + {6, 0, 0x3F114, 0x80000000}, + {6, 0, 0x3F124, 0x80000000}, + {6, 0, 0x3F140, 0x80000000}, + {6, 0, 0x3F200, 0x0F1F0135}, + {6, 1, 0xB0000, 0x80000008}, + {6, 1, 0xB0004, 0x8000000C}, + {6, 1, 0xB0008, 0x8000000F}, + {6, 1, 0xB000C, 0x80000010}, + {6, 1, 0xB0010, 0x8000000E}, + {6, 1, 0xB0014, 0x8000000D}, + {6, 1, 0xB0024, 0x80000005}, + {6, 1, 0xB002C, 0x80000002}, + {6, 1, 0xB0030, 0x80000001}, + {6, 1, 0xB0034, 0x80000003}, + {6, 1, 0xB0038, 0x80000000}, + {6, 1, 0xB0100, 0x80000000}, + {6, 1, 0xB0104, 0x80000000}, + {6, 1, 0xB0108, 0x80000000}, + {6, 1, 0xB010C, 0x80000000}, + {6, 1, 0xB0114, 0x80000000}, + {6, 1, 0xB0120, 0x80000000}, + {6, 1, 0xB0130, 0x80000000}, + {6, 1, 0xB0134, 0x80000000}, + {6, 1, 0xB0138, 0x80000000}, + {6, 1, 0xB013C, 0x80000000}, + {6, 1, 0xB0140, 0x80000000}, + {6, 2, 0x3F004, 0x80000008}, + {6, 2, 0x3F008, 0x80000014}, + {6, 2, 0x3F014, 0x80000010}, + {6, 2, 0x3F018, 0x8000000F}, + {6, 2, 0x3F01C, 0x80000001}, + {6, 2, 0x3F020, 0x80000016}, + {6, 2, 0x3F024, 0x80000014}, + {6, 2, 0x3F034, 0x80000007}, + {6, 2, 0x3F03C, 0x80000005}, + {6, 2, 0x3F048, 0x80000006}, + {6, 2, 0x3F054, 0x80000012}, + {6, 2, 0x3F058, 0x80000008}, + {6, 2, 0x3F104, 0x80000000}, + {6, 2, 0x3F114, 0x80000000}, + {6, 2, 0x3F118, 0x80000000}, + {6, 2, 0x3F11C, 0x80000000}, + {6, 2, 0x3F120, 0x80000000}, + {6, 2, 0x3F13C, 0x80000000}, + {6, 2, 0x3F140, 0x80000000}, + {6, 2, 0x3F148, 0x80000000}, + {6, 2, 0x3F150, 0x80000000}, + {6, 2, 0x3F158, 0x80000000}, + {6, 3, 0x3F004, 0x8000000A}, + {6, 3, 0x3F008, 0x80000014}, + {6, 3, 0x3F014, 0x80000001}, + {6, 3, 0x3F018, 0x80000015}, + {6, 3, 0x3F020, 0x8000000F}, + {6, 3, 0x3F040, 0x80000005}, + {6, 3, 0x3F048, 0x80000007}, + {6, 3, 0x3F050, 0x8000000A}, + {6, 3, 0x3F104, 0x80000000}, + {6, 3, 0x3F114, 0x80000000}, + {6, 3, 0x3F11C, 0x80000000}, + {6, 3, 0x3F128, 0x80000000}, + {6, 3, 0x3F13C, 0x80000000}, + {6, 3, 0x3F150, 0x80000000}, + {6, 3, 0x3F154, 0x80000000}, + {6, 4, 0x3F004, 0x8000000A}, + {6, 4, 0x3F008, 0x80000014}, + {6, 4, 0x3F014, 0x8000000F}, + {6, 4, 0x3F038, 0x80000008}, + {6, 4, 0x3F04C, 0x80000001}, + {6, 4, 0x3F050, 0x8000000A}, + {6, 4, 0x3F104, 0x80000000}, + {6, 4, 0x3F120, 0x80000000}, + {6, 4, 0x3F128, 0x80000000}, + {6, 4, 0x3F13C, 0x80000000}, + {6, 4, 0x3F150, 0x80000000}, + {6, 5, 0x3F004, 0x80000006}, + {6, 5, 0x3F008, 0x80000015}, + {6, 5, 0x3F014, 0x80000001}, + {6, 5, 0x3F054, 0x80000006}, + {6, 5, 0x3F104, 0x80000000}, + {6, 5, 0x3F118, 0x80000000}, + {6, 5, 0x3F154, 0x80000000}, + {7, 0, 0x3F008, 0xC0000045}, + {7, 0, 0x3F010, 0x80000010}, + {7, 0, 0x3F030, 0x80000005}, + {7, 0, 0x3F034, 0x80000009}, + {7, 0, 0x3F100, 0xC0000000}, + {7, 0, 0x3F114, 0x80000000}, + {7, 0, 0x3F124, 0x80000000}, + {7, 0, 0x3F140, 0x80000000}, + {7, 0, 0x3F200, 0x0F1F0135}, + {7, 1, 0xB0000, 0x80000007}, + {7, 1, 0xB0004, 0x80000008}, + {7, 1, 0xB0008, 0x8000000D}, + {7, 1, 0xB000C, 0x8000000F}, + {7, 1, 0xB0010, 0x8000000E}, + {7, 1, 0xB0014, 0x80000010}, + {7, 1, 0xB0024, 0x80000005}, + {7, 1, 0xB0030, 0x80000000}, + {7, 1, 0xB0100, 0x80000000}, + {7, 1, 0xB0114, 0x80000000}, + {7, 1, 0xB011C, 0x80000000}, + {7, 1, 0xB0120, 0x80000000}, + {7, 1, 0xB0134, 0x80000000}, + {7, 1, 0xB0138, 0x80000000}, + {7, 1, 0xB013C, 0x80000000}, + {7, 1, 0xB0140, 0x80000000}, + {7, 2, 0x3F004, 0x8000000E}, + {7, 2, 0x3F008, 0x80000006}, + {7, 2, 0x3F014, 0x8000000F}, + {7, 2, 0x3F018, 0x8000000D}, + {7, 2, 0x3F01C, 0x80000011}, + {7, 2, 0x3F020, 0x80000012}, + {7, 2, 0x3F028, 0x80000006}, + {7, 2, 0x3F030, 0x80000001}, + {7, 2, 0x3F048, 0x80000006}, + {7, 2, 0x3F104, 0x80000000}, + {7, 2, 0x3F118, 0x80000000}, + {7, 2, 0x3F134, 0x80000000}, + {7, 2, 0x3F138, 0x80000000}, + {7, 2, 0x3F13C, 0x80000000}, + {7, 2, 0x3F144, 0x80000000}, + {7, 2, 0x3F148, 0x80000000}, + {7, 3, 0x3F004, 0x8000000C}, + {7, 3, 0x3F008, 0x8000000A}, + {7, 3, 0x3F014, 0x80000010}, + {7, 3, 0x3F01C, 0x80000011}, + {7, 3, 0x3F020, 0x80000012}, + {7, 3, 0x3F028, 0x8000000A}, + {7, 3, 0x3F02C, 0x80000001}, + {7, 3, 0x3F044, 0x8000000A}, + {7, 3, 0x3F104, 0x80000000}, + {7, 3, 0x3F128, 0x80000000}, + {7, 3, 0x3F130, 0x80000000}, + {7, 3, 0x3F140, 0x80000000}, + {7, 3, 0x3F144, 0x80000000}, + {7, 3, 0x3F148, 0x80000000}, + {7, 4, 0x3F004, 0x8000000C}, + {7, 4, 0x3F008, 0x80000009}, + {7, 4, 0x3F018, 0x8000000B}, + {7, 4, 0x3F01C, 0x80000001}, + {7, 4, 0x3F020, 0x8000000F}, + {7, 4, 0x3F028, 0x80000009}, + {7, 4, 0x3F03C, 0x80000009}, + {7, 4, 0x3F104, 0x80000000}, + {7, 4, 0x3F124, 0x80000000}, + {7, 4, 0x3F12C, 0x80000000}, + {7, 4, 0x3F130, 0x80000000}, + {7, 4, 0x3F13C, 0x80000000}, + {7, 5, 0x3F004, 0x8000000D}, + {7, 5, 0x3F008, 0x80000007}, + {7, 5, 0x3F014, 0x80000001}, + {7, 5, 0x3F02C, 0x80000007}, + {7, 5, 0x3F104, 0x80000000}, + {7, 5, 0x3F11C, 0x80000000}, + {7, 5, 0x3F134, 0x80000000}, + }, + // shim mux / demux mask writes: (col, row, offset, mask, value) + { + {0, 0, 0x1F000, 0x00000C00, 0x00000400}, + {0, 0, 0x1F000, 0x0000C000, 0x00004000}, + {0, 0, 0x1F004, 0x00000030, 0x00000010}, + {2, 0, 0x1F000, 0x00000C00, 0x00000400}, + {2, 0, 0x1F000, 0x0000C000, 0x00004000}, + {2, 0, 0x1F004, 0x00000030, 0x00000010}, + {4, 0, 0x1F000, 0x00000C00, 0x00000400}, + {4, 0, 0x1F000, 0x0000C000, 0x00004000}, + {4, 0, 0x1F004, 0x00000030, 0x00000010}, + {6, 0, 0x1F000, 0x00000C00, 0x00000400}, + {6, 0, 0x1F000, 0x0000C000, 0x00004000}, + {6, 0, 0x1F004, 0x00000030, 0x00000010}, + {3, 0, 0x1F000, 0x00000C00, 0x00000400}, + {3, 0, 0x1F000, 0x0000C000, 0x00004000}, + {3, 0, 0x1F004, 0x00000030, 0x00000010}, + {7, 0, 0x1F000, 0x00000C00, 0x00000400}, + {7, 0, 0x1F000, 0x0000C000, 0x00004000}, + {7, 0, 0x1F004, 0x00000030, 0x00000010}, + {1, 0, 0x1F004, 0x00000030, 0x00000010}, + {5, 0, 0x1F004, 0x00000030, 0x00000010}, + }, + // BD registers: (col, row, offset, shared, words) + { + {0, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {0, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {0, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {0, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {0, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {0, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {0, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {0, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {0, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {0, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {0, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {0, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {0, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {0, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {0, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {0, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {0, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {0, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {0, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {0, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {1, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {1, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {1, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {1, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {1, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {1, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {1, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {1, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {1, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {1, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {1, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {1, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {1, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {1, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {1, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {1, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {1, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {1, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {1, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {1, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {2, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {2, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {2, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {2, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {2, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {2, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {2, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {2, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {2, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {2, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {2, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {2, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {2, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {2, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {2, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {2, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {2, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {2, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {2, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {2, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {3, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {3, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {3, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {3, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {3, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {3, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {3, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {3, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {3, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {3, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {3, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {3, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {3, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {3, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {3, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {3, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {3, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {3, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {3, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {3, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {4, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {4, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {4, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {4, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {4, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {4, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {4, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {4, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {4, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {4, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {4, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {4, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {4, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {4, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {4, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {4, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {4, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {4, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {4, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {4, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {5, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {5, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {5, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {5, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {5, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {5, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {5, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {5, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {5, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {5, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {5, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {5, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {5, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {5, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {5, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {5, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {5, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {5, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {5, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {5, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {6, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {6, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {6, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {6, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {6, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {6, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {6, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {6, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {6, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {6, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {6, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {6, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {6, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {6, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {6, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {6, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {6, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {6, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {6, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {6, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {7, 2, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {7, 2, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {7, 2, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {7, 2, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {7, 2, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {7, 3, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {7, 3, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {7, 3, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {7, 3, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {7, 3, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {7, 4, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {7, 4, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {7, 4, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {7, 4, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {7, 4, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {7, 5, 0x1D100, false, {0x01000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46043FE0}}, + {7, 5, 0x1D120, false, {0x08000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x56047FE2}}, + {7, 5, 0x1D160, false, {0x09000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x66049FE5}}, + {7, 5, 0x1D180, false, {0x0D000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5E049FE5}}, + {7, 5, 0x1D140, false, {0x0C000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x4E047FE2}}, + {0, 1, 0xA01C0, false, {0x00001000, 0x00FA0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {0, 1, 0xA0480, false, {0x00001000, 0x025A1000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {0, 1, 0xA0200, false, {0x00000800, 0x011A0000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {0, 1, 0xA04C0, false, {0x00000800, 0x027A0800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {0, 1, 0xA0240, false, {0x00000800, 0x013A1000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {0, 1, 0xA0500, false, {0x00000800, 0x029A1800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {0, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {0, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {0, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {0, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {0, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {0, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {0, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {0, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {0, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {0, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {0, 1, 0xA0520, false, {0x00000800, 0x028A5800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {0, 1, 0xA0260, false, {0x00000800, 0x012A5000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {0, 1, 0xA04E0, false, {0x00000800, 0x026A4800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {0, 1, 0xA0220, false, {0x00000800, 0x010A4000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {0, 1, 0xA04A0, false, {0x00001000, 0x024A5000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {0, 1, 0xA01E0, false, {0x00001000, 0x00EA4000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0200, false, {0x00002000, 0x011A0000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0500, false, {0x00002000, 0x029A2000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0240, false, {0x00004000, 0x013A0000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {1, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {1, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {1, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {1, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {1, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {1, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {1, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {1, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {1, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {1, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {1, 1, 0xA0260, false, {0x00004000, 0x012A4000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {1, 1, 0xA0520, false, {0x00002000, 0x028A6000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {1, 1, 0xA0220, false, {0x00002000, 0x010A4000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {2, 1, 0xA01C0, false, {0x00001000, 0x00FA0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {2, 1, 0xA0480, false, {0x00001000, 0x025A1000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {2, 1, 0xA0200, false, {0x00000800, 0x011A0000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {2, 1, 0xA04C0, false, {0x00000800, 0x027A0800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {2, 1, 0xA0240, false, {0x00000800, 0x013A1000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {2, 1, 0xA0500, false, {0x00000800, 0x029A1800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {2, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {2, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {2, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {2, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {2, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {2, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {2, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {2, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {2, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {2, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {2, 1, 0xA0520, false, {0x00000800, 0x028A5800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {2, 1, 0xA0260, false, {0x00000800, 0x012A5000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {2, 1, 0xA04E0, false, {0x00000800, 0x026A4800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {2, 1, 0xA0220, false, {0x00000800, 0x010A4000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {2, 1, 0xA04A0, false, {0x00001000, 0x024A5000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {2, 1, 0xA01E0, false, {0x00001000, 0x00EA4000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0200, false, {0x00002000, 0x011A0000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0500, false, {0x00002000, 0x029A2000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0240, false, {0x00004000, 0x013A0000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {3, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {3, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {3, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {3, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {3, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {3, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {3, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {3, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {3, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {3, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {3, 1, 0xA0260, false, {0x00004000, 0x012A4000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {3, 1, 0xA0520, false, {0x00002000, 0x028A6000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {3, 1, 0xA0220, false, {0x00002000, 0x010A4000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {4, 1, 0xA01C0, false, {0x00001000, 0x00FA0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {4, 1, 0xA0480, false, {0x00001000, 0x025A1000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {4, 1, 0xA0200, false, {0x00000800, 0x011A0000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {4, 1, 0xA04C0, false, {0x00000800, 0x027A0800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {4, 1, 0xA0240, false, {0x00000800, 0x013A1000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {4, 1, 0xA0500, false, {0x00000800, 0x029A1800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {4, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {4, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {4, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {4, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {4, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {4, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {4, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {4, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {4, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {4, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {4, 1, 0xA0520, false, {0x00000800, 0x028A5800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {4, 1, 0xA0260, false, {0x00000800, 0x012A5000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {4, 1, 0xA04E0, false, {0x00000800, 0x026A4800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {4, 1, 0xA0220, false, {0x00000800, 0x010A4000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {4, 1, 0xA04A0, false, {0x00001000, 0x024A5000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {4, 1, 0xA01E0, false, {0x00001000, 0x00EA4000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0200, false, {0x00002000, 0x011A0000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0500, false, {0x00002000, 0x029A2000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0240, false, {0x00004000, 0x013A0000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {5, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {5, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {5, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {5, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {5, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {5, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {5, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {5, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {5, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {5, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {5, 1, 0xA0260, false, {0x00004000, 0x012A4000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {5, 1, 0xA0520, false, {0x00002000, 0x028A6000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {5, 1, 0xA0220, false, {0x00002000, 0x010A4000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {6, 1, 0xA01C0, false, {0x00001000, 0x00FA0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {6, 1, 0xA0480, false, {0x00001000, 0x025A1000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {6, 1, 0xA0200, false, {0x00000800, 0x011A0000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {6, 1, 0xA04C0, false, {0x00000800, 0x027A0800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {6, 1, 0xA0240, false, {0x00000800, 0x013A1000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {6, 1, 0xA0500, false, {0x00000800, 0x029A1800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {6, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {6, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {6, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {6, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {6, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {6, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8147FF4B}}, + {6, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814BFF4A}}, + {6, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x814AFF49}}, + {6, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8149FF48}}, + {6, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8148FF47}}, + {6, 1, 0xA0520, false, {0x00000800, 0x028A5800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF46}}, + {6, 1, 0xA0260, false, {0x00000800, 0x012A5000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {6, 1, 0xA04E0, false, {0x00000800, 0x026A4800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8140FF43}}, + {6, 1, 0xA0220, false, {0x00000800, 0x010A4000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF41}}, + {6, 1, 0xA04A0, false, {0x00001000, 0x024A5000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8145FF44}}, + {6, 1, 0xA01E0, false, {0x00001000, 0x00EA4000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0200, false, {0x00002000, 0x011A0000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0500, false, {0x00002000, 0x029A2000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0240, false, {0x00004000, 0x013A0000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {7, 1, 0xA0280, false, {0x00000400, 0x015A8000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {7, 1, 0xA0540, false, {0x00000400, 0x02BA8400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {7, 1, 0xA02C0, false, {0x00000400, 0x017A8800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {7, 1, 0xA0580, false, {0x00000400, 0x02DA8C00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {7, 1, 0xA05C0, false, {0x00001000, 0x02FA8000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {7, 1, 0xA05E0, false, {0x00001000, 0x02EAC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x8142FF46}}, + {7, 1, 0xA05A0, false, {0x00000400, 0x02CACC00, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8146FF45}}, + {7, 1, 0xA02E0, false, {0x00000400, 0x016AC800, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8145FF44}}, + {7, 1, 0xA0560, false, {0x00000400, 0x02AAC400, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8144FF43}}, + {7, 1, 0xA02A0, false, {0x00000400, 0x014AC000, 0x00080000, 0x0010003F, 0x00200003, 0x000001FF, 0x00000000, 0x8143FF42}}, + {7, 1, 0xA0260, false, {0x00004000, 0x012A4000, 0x00800000, 0x0020003F, 0x002003FF, 0x00000000, 0x00000000, 0x8240FE41}}, + {7, 1, 0xA0520, false, {0x00002000, 0x028A6000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + {7, 1, 0xA0220, false, {0x00002000, 0x010A4000, 0x00080000, 0x0020003F, 0x00200003, 0x000003FF, 0x00000000, 0x8141FF40}}, + }, + // lock values: (col, row, offset, value) + { + {0, 1, 0xC0000, 2}, + {0, 1, 0xC0010, 0}, + {0, 1, 0xC0030, 0}, + {0, 1, 0xC0040, 2}, + {0, 1, 0xC0050, 0}, + {0, 1, 0xC0060, 0}, + {0, 1, 0xC0070, 2}, + {0, 1, 0xC0080, 0}, + {0, 1, 0xC0090, 0}, + {0, 1, 0xC00A0, 0}, + {0, 1, 0xC00B0, 0}, + {0, 2, 0x1F000, 1}, + {0, 2, 0x1F010, 0}, + {0, 2, 0x1F020, 2}, + {0, 2, 0x1F030, 0}, + {0, 2, 0x1F040, 2}, + {0, 2, 0x1F050, 0}, + {0, 2, 0x1F0F0, 0}, + {0, 3, 0x1F000, 1}, + {0, 3, 0x1F010, 0}, + {0, 3, 0x1F020, 2}, + {0, 3, 0x1F030, 0}, + {0, 3, 0x1F040, 2}, + {0, 3, 0x1F050, 0}, + {0, 3, 0x1F0F0, 0}, + {0, 4, 0x1F000, 1}, + {0, 4, 0x1F010, 0}, + {0, 4, 0x1F020, 2}, + {0, 4, 0x1F030, 0}, + {0, 4, 0x1F040, 2}, + {0, 4, 0x1F050, 0}, + {0, 4, 0x1F0F0, 0}, + {0, 5, 0x1F000, 1}, + {0, 5, 0x1F010, 0}, + {0, 5, 0x1F020, 2}, + {0, 5, 0x1F030, 0}, + {0, 5, 0x1F040, 2}, + {0, 5, 0x1F050, 0}, + {0, 5, 0x1F0F0, 0}, + {1, 1, 0xC0000, 4}, + {1, 1, 0xC0010, 0}, + {1, 1, 0xC0020, 2}, + {1, 1, 0xC0030, 0}, + {1, 1, 0xC0040, 0}, + {1, 1, 0xC0050, 0}, + {1, 1, 0xC0060, 0}, + {1, 2, 0x1F000, 1}, + {1, 2, 0x1F010, 0}, + {1, 2, 0x1F020, 2}, + {1, 2, 0x1F030, 0}, + {1, 2, 0x1F040, 2}, + {1, 2, 0x1F050, 0}, + {1, 2, 0x1F0F0, 0}, + {1, 3, 0x1F000, 1}, + {1, 3, 0x1F010, 0}, + {1, 3, 0x1F020, 2}, + {1, 3, 0x1F030, 0}, + {1, 3, 0x1F040, 2}, + {1, 3, 0x1F050, 0}, + {1, 3, 0x1F0F0, 0}, + {1, 4, 0x1F000, 1}, + {1, 4, 0x1F010, 0}, + {1, 4, 0x1F020, 2}, + {1, 4, 0x1F030, 0}, + {1, 4, 0x1F040, 2}, + {1, 4, 0x1F050, 0}, + {1, 4, 0x1F0F0, 0}, + {1, 5, 0x1F000, 1}, + {1, 5, 0x1F010, 0}, + {1, 5, 0x1F020, 2}, + {1, 5, 0x1F030, 0}, + {1, 5, 0x1F040, 2}, + {1, 5, 0x1F050, 0}, + {1, 5, 0x1F0F0, 0}, + {2, 1, 0xC0000, 2}, + {2, 1, 0xC0010, 0}, + {2, 1, 0xC0030, 0}, + {2, 1, 0xC0040, 2}, + {2, 1, 0xC0050, 0}, + {2, 1, 0xC0060, 0}, + {2, 1, 0xC0070, 2}, + {2, 1, 0xC0080, 0}, + {2, 1, 0xC0090, 0}, + {2, 1, 0xC00A0, 0}, + {2, 1, 0xC00B0, 0}, + {2, 2, 0x1F000, 1}, + {2, 2, 0x1F010, 0}, + {2, 2, 0x1F020, 2}, + {2, 2, 0x1F030, 0}, + {2, 2, 0x1F040, 2}, + {2, 2, 0x1F050, 0}, + {2, 2, 0x1F0F0, 0}, + {2, 3, 0x1F000, 1}, + {2, 3, 0x1F010, 0}, + {2, 3, 0x1F020, 2}, + {2, 3, 0x1F030, 0}, + {2, 3, 0x1F040, 2}, + {2, 3, 0x1F050, 0}, + {2, 3, 0x1F0F0, 0}, + {2, 4, 0x1F000, 1}, + {2, 4, 0x1F010, 0}, + {2, 4, 0x1F020, 2}, + {2, 4, 0x1F030, 0}, + {2, 4, 0x1F040, 2}, + {2, 4, 0x1F050, 0}, + {2, 4, 0x1F0F0, 0}, + {2, 5, 0x1F000, 1}, + {2, 5, 0x1F010, 0}, + {2, 5, 0x1F020, 2}, + {2, 5, 0x1F030, 0}, + {2, 5, 0x1F040, 2}, + {2, 5, 0x1F050, 0}, + {2, 5, 0x1F0F0, 0}, + {3, 1, 0xC0000, 4}, + {3, 1, 0xC0010, 0}, + {3, 1, 0xC0020, 2}, + {3, 1, 0xC0030, 0}, + {3, 1, 0xC0040, 0}, + {3, 1, 0xC0050, 0}, + {3, 1, 0xC0060, 0}, + {3, 2, 0x1F000, 1}, + {3, 2, 0x1F010, 0}, + {3, 2, 0x1F020, 2}, + {3, 2, 0x1F030, 0}, + {3, 2, 0x1F040, 2}, + {3, 2, 0x1F050, 0}, + {3, 2, 0x1F0F0, 0}, + {3, 3, 0x1F000, 1}, + {3, 3, 0x1F010, 0}, + {3, 3, 0x1F020, 2}, + {3, 3, 0x1F030, 0}, + {3, 3, 0x1F040, 2}, + {3, 3, 0x1F050, 0}, + {3, 3, 0x1F0F0, 0}, + {3, 4, 0x1F000, 1}, + {3, 4, 0x1F010, 0}, + {3, 4, 0x1F020, 2}, + {3, 4, 0x1F030, 0}, + {3, 4, 0x1F040, 2}, + {3, 4, 0x1F050, 0}, + {3, 4, 0x1F0F0, 0}, + {3, 5, 0x1F000, 1}, + {3, 5, 0x1F010, 0}, + {3, 5, 0x1F020, 2}, + {3, 5, 0x1F030, 0}, + {3, 5, 0x1F040, 2}, + {3, 5, 0x1F050, 0}, + {3, 5, 0x1F0F0, 0}, + {4, 1, 0xC0000, 2}, + {4, 1, 0xC0010, 0}, + {4, 1, 0xC0030, 0}, + {4, 1, 0xC0040, 2}, + {4, 1, 0xC0050, 0}, + {4, 1, 0xC0060, 0}, + {4, 1, 0xC0070, 2}, + {4, 1, 0xC0080, 0}, + {4, 1, 0xC0090, 0}, + {4, 1, 0xC00A0, 0}, + {4, 1, 0xC00B0, 0}, + {4, 2, 0x1F000, 1}, + {4, 2, 0x1F010, 0}, + {4, 2, 0x1F020, 2}, + {4, 2, 0x1F030, 0}, + {4, 2, 0x1F040, 2}, + {4, 2, 0x1F050, 0}, + {4, 2, 0x1F0F0, 0}, + {4, 3, 0x1F000, 1}, + {4, 3, 0x1F010, 0}, + {4, 3, 0x1F020, 2}, + {4, 3, 0x1F030, 0}, + {4, 3, 0x1F040, 2}, + {4, 3, 0x1F050, 0}, + {4, 3, 0x1F0F0, 0}, + {4, 4, 0x1F000, 1}, + {4, 4, 0x1F010, 0}, + {4, 4, 0x1F020, 2}, + {4, 4, 0x1F030, 0}, + {4, 4, 0x1F040, 2}, + {4, 4, 0x1F050, 0}, + {4, 4, 0x1F0F0, 0}, + {4, 5, 0x1F000, 1}, + {4, 5, 0x1F010, 0}, + {4, 5, 0x1F020, 2}, + {4, 5, 0x1F030, 0}, + {4, 5, 0x1F040, 2}, + {4, 5, 0x1F050, 0}, + {4, 5, 0x1F0F0, 0}, + {5, 1, 0xC0000, 4}, + {5, 1, 0xC0010, 0}, + {5, 1, 0xC0020, 2}, + {5, 1, 0xC0030, 0}, + {5, 1, 0xC0040, 0}, + {5, 1, 0xC0050, 0}, + {5, 1, 0xC0060, 0}, + {5, 2, 0x1F000, 1}, + {5, 2, 0x1F010, 0}, + {5, 2, 0x1F020, 2}, + {5, 2, 0x1F030, 0}, + {5, 2, 0x1F040, 2}, + {5, 2, 0x1F050, 0}, + {5, 2, 0x1F0F0, 0}, + {5, 3, 0x1F000, 1}, + {5, 3, 0x1F010, 0}, + {5, 3, 0x1F020, 2}, + {5, 3, 0x1F030, 0}, + {5, 3, 0x1F040, 2}, + {5, 3, 0x1F050, 0}, + {5, 3, 0x1F0F0, 0}, + {5, 4, 0x1F000, 1}, + {5, 4, 0x1F010, 0}, + {5, 4, 0x1F020, 2}, + {5, 4, 0x1F030, 0}, + {5, 4, 0x1F040, 2}, + {5, 4, 0x1F050, 0}, + {5, 4, 0x1F0F0, 0}, + {5, 5, 0x1F000, 1}, + {5, 5, 0x1F010, 0}, + {5, 5, 0x1F020, 2}, + {5, 5, 0x1F030, 0}, + {5, 5, 0x1F040, 2}, + {5, 5, 0x1F050, 0}, + {5, 5, 0x1F0F0, 0}, + {6, 1, 0xC0000, 2}, + {6, 1, 0xC0010, 0}, + {6, 1, 0xC0030, 0}, + {6, 1, 0xC0040, 2}, + {6, 1, 0xC0050, 0}, + {6, 1, 0xC0060, 0}, + {6, 1, 0xC0070, 2}, + {6, 1, 0xC0080, 0}, + {6, 1, 0xC0090, 0}, + {6, 1, 0xC00A0, 0}, + {6, 1, 0xC00B0, 0}, + {6, 2, 0x1F000, 1}, + {6, 2, 0x1F010, 0}, + {6, 2, 0x1F020, 2}, + {6, 2, 0x1F030, 0}, + {6, 2, 0x1F040, 2}, + {6, 2, 0x1F050, 0}, + {6, 2, 0x1F0F0, 0}, + {6, 3, 0x1F000, 1}, + {6, 3, 0x1F010, 0}, + {6, 3, 0x1F020, 2}, + {6, 3, 0x1F030, 0}, + {6, 3, 0x1F040, 2}, + {6, 3, 0x1F050, 0}, + {6, 3, 0x1F0F0, 0}, + {6, 4, 0x1F000, 1}, + {6, 4, 0x1F010, 0}, + {6, 4, 0x1F020, 2}, + {6, 4, 0x1F030, 0}, + {6, 4, 0x1F040, 2}, + {6, 4, 0x1F050, 0}, + {6, 4, 0x1F0F0, 0}, + {6, 5, 0x1F000, 1}, + {6, 5, 0x1F010, 0}, + {6, 5, 0x1F020, 2}, + {6, 5, 0x1F030, 0}, + {6, 5, 0x1F040, 2}, + {6, 5, 0x1F050, 0}, + {6, 5, 0x1F0F0, 0}, + {7, 1, 0xC0000, 4}, + {7, 1, 0xC0010, 0}, + {7, 1, 0xC0020, 2}, + {7, 1, 0xC0030, 0}, + {7, 1, 0xC0040, 0}, + {7, 1, 0xC0050, 0}, + {7, 1, 0xC0060, 0}, + {7, 2, 0x1F000, 1}, + {7, 2, 0x1F010, 0}, + {7, 2, 0x1F020, 2}, + {7, 2, 0x1F030, 0}, + {7, 2, 0x1F040, 2}, + {7, 2, 0x1F050, 0}, + {7, 2, 0x1F0F0, 0}, + {7, 3, 0x1F000, 1}, + {7, 3, 0x1F010, 0}, + {7, 3, 0x1F020, 2}, + {7, 3, 0x1F030, 0}, + {7, 3, 0x1F040, 2}, + {7, 3, 0x1F050, 0}, + {7, 3, 0x1F0F0, 0}, + {7, 4, 0x1F000, 1}, + {7, 4, 0x1F010, 0}, + {7, 4, 0x1F020, 2}, + {7, 4, 0x1F030, 0}, + {7, 4, 0x1F040, 2}, + {7, 4, 0x1F050, 0}, + {7, 4, 0x1F0F0, 0}, + {7, 5, 0x1F000, 1}, + {7, 5, 0x1F010, 0}, + {7, 5, 0x1F020, 2}, + {7, 5, 0x1F030, 0}, + {7, 5, 0x1F040, 2}, + {7, 5, 0x1F050, 0}, + {7, 5, 0x1F0F0, 0}, + }, + // channels: (col, row, control offset, start queue offset, queue value, control value) + { + {0, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {0, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {0, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {0, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {0, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {0, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {0, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {0, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {0, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {0, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {0, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {0, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {1, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {1, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {1, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {1, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {1, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {1, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {1, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {1, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {1, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {1, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {1, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {1, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {2, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {2, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {2, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {2, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {2, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {2, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {2, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {2, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {2, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {2, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {2, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {2, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {3, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {3, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {3, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {3, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {3, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {3, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {3, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {3, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {3, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {3, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {3, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {3, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {4, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {4, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {4, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {4, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {4, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {4, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {4, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {4, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {4, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {4, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {4, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {4, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {5, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {5, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {5, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {5, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {5, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {5, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {5, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {5, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {5, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {5, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {5, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {5, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {6, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {6, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {6, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {6, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {6, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {6, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {6, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {6, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {6, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {6, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {6, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {6, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {7, 2, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {7, 2, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {7, 2, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {7, 3, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {7, 3, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {7, 3, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {7, 4, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {7, 4, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {7, 4, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {7, 5, 0x1DE00, 0x1DE04, 0x00000008, 1}, + {7, 5, 0x1DE08, 0x1DE0C, 0x00000009, 1}, + {7, 5, 0x1DE10, 0x1DE14, 0x0000000B, 1}, + {0, 1, 0xA0600, 0xA0604, 0x0000000E, 1}, + {0, 1, 0xA0608, 0xA060C, 0x00000024, 1}, + {0, 1, 0xA0630, 0xA0634, 0x00000010, 1}, + {0, 1, 0xA0638, 0xA063C, 0x00000026, 1}, + {0, 1, 0xA0640, 0xA0644, 0x00000012, 1}, + {0, 1, 0xA0648, 0xA064C, 0x00000028, 1}, + {0, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {0, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {0, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {0, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {0, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {1, 1, 0xA0600, 0xA0604, 0x00000010, 1}, + {1, 1, 0xA0608, 0xA060C, 0x00000028, 1}, + {1, 1, 0xA0630, 0xA0634, 0x00000012, 1}, + {1, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {1, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {1, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {1, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {1, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {2, 1, 0xA0600, 0xA0604, 0x0000000E, 1}, + {2, 1, 0xA0608, 0xA060C, 0x00000024, 1}, + {2, 1, 0xA0630, 0xA0634, 0x00000010, 1}, + {2, 1, 0xA0638, 0xA063C, 0x00000026, 1}, + {2, 1, 0xA0640, 0xA0644, 0x00000012, 1}, + {2, 1, 0xA0648, 0xA064C, 0x00000028, 1}, + {2, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {2, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {2, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {2, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {2, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {3, 1, 0xA0600, 0xA0604, 0x00000010, 1}, + {3, 1, 0xA0608, 0xA060C, 0x00000028, 1}, + {3, 1, 0xA0630, 0xA0634, 0x00000012, 1}, + {3, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {3, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {3, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {3, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {3, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {4, 1, 0xA0600, 0xA0604, 0x0000000E, 1}, + {4, 1, 0xA0608, 0xA060C, 0x00000024, 1}, + {4, 1, 0xA0630, 0xA0634, 0x00000010, 1}, + {4, 1, 0xA0638, 0xA063C, 0x00000026, 1}, + {4, 1, 0xA0640, 0xA0644, 0x00000012, 1}, + {4, 1, 0xA0648, 0xA064C, 0x00000028, 1}, + {4, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {4, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {4, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {4, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {4, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {5, 1, 0xA0600, 0xA0604, 0x00000010, 1}, + {5, 1, 0xA0608, 0xA060C, 0x00000028, 1}, + {5, 1, 0xA0630, 0xA0634, 0x00000012, 1}, + {5, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {5, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {5, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {5, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {5, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {6, 1, 0xA0600, 0xA0604, 0x0000000E, 1}, + {6, 1, 0xA0608, 0xA060C, 0x00000024, 1}, + {6, 1, 0xA0630, 0xA0634, 0x00000010, 1}, + {6, 1, 0xA0638, 0xA063C, 0x00000026, 1}, + {6, 1, 0xA0640, 0xA0644, 0x00000012, 1}, + {6, 1, 0xA0648, 0xA064C, 0x00000028, 1}, + {6, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {6, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {6, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {6, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {6, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + {7, 1, 0xA0600, 0xA0604, 0x00000010, 1}, + {7, 1, 0xA0608, 0xA060C, 0x00000028, 1}, + {7, 1, 0xA0630, 0xA0634, 0x00000012, 1}, + {7, 1, 0xA0610, 0xA0614, 0x00000014, 1}, + {7, 1, 0xA0618, 0xA061C, 0x0000002A, 1}, + {7, 1, 0xA0620, 0xA0624, 0x00000016, 1}, + {7, 1, 0xA0628, 0xA062C, 0x0000002C, 1}, + {7, 1, 0xA0658, 0xA065C, 0x0000002E, 1}, + }, +}; diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/overlay_host.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/overlay_host.hpp new file mode 100644 index 000000000..59a04660f --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/host/overlay_host.hpp @@ -0,0 +1,438 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +// Host side of the prefill overlay: switch the array between ops, and the +// instruction sequences of the two ops. +// +// A run of an op = [switch, if another op was configured] + per-core RTP block +// + "go" (op lock = 1) + the op's usual shim DMAs. gen_dq_run / gen_attn_run +// copy gen_dequant_mm_rtm (dequant_mm_bfp16_rtm2_glu_512x512x512/host/seq_gen.hpp) +// and gen_seq_1_4 (../attention_prefill/host/seq_gen.hpp); only their RTP part changed. +#pragma once +#include +#include +#include "npu_utils/npu_utils.hpp" +#include "weights_desc.hpp" // dequant_mm_bfp16_rtm2_glu_512x512x512/host: get_quantization_byte_size +#include "op_configs.hpp" // generated by tools/extract_txn2.py + +namespace overlay { + +// must match iron/layout.py +constexpr uint32_t RTP_ADDR = 64768; // every core's RTP block (checked in the build) +constexpr int RTP_OP = 0, RTP_CALLS = 1, RTP_SWITCHED = 2; +// K_div_k[0] = Din / 512, K_div_k[1] = rows per core row / 16: two consecutive words +constexpr int RTP_DQ_K_DIV_K = 4, RTP_DQ_M = 5, RTP_DQ_ACT = 6; +constexpr int DQ_ACT_GLU = 3; // y = silu(gate) * up of the core's two n slices +constexpr int RTP_AT_L_BEGIN = 8, RTP_AT_L_CHUNKS = 9, RTP_AT_WINDOW = 10; +constexpr int OP_DQ = 1, OP_ATTN = 2; +constexpr uint32_t OP_LOCK_REG = 0x1F000 + 16 * 15; // core lock 15 value register +constexpr uint32_t DMA_CTRL_RESET = 0x2; // bit 1 of a DMA channel control register +constexpr int ROWS = 4, COLS = 8, ATTN_COLS = 8; + +inline void write_reg(npu_sequence* seq, uint32_t row, uint32_t col, uint32_t offset, uint32_t value) { + seq->rtp_write(get_tile(row, col), offset, value); +} + +inline const op_config& config_of(int op) { + return op == OP_DQ ? op_dq : op_attn; +} + +using reg_key = std::tuple; + +/// @brief (col, row, offset) of every register of one kind that either op writes +template +inline std::vector union_of(Get get) { + std::set all; + for (const op_config* cfg : {&op_dq, &op_attn}) + for (const reg_write& w : get(*cfg)) all.insert({w.col, w.row, w.offset}); + return {all.begin(), all.end()}; +} + +/// @brief the value `regs` gives (col, row, offset), 0 if it doesn't write it +inline uint32_t value_in(const std::vector& regs, const reg_key& key) { + for (const reg_write& w : regs) + if (w.col == std::get<0>(key) && w.row == std::get<1>(key) && w.offset == std::get<2>(key)) return w.value; + return 0; +} + +inline size_t write_bd(npu_sequence* seq, const reg_block& b) { + for (size_t i = 0; i < b.words.size(); i++) write_reg(seq, b.row, b.col, b.offset + 4 * (uint32_t)i, b.words[i]); + return b.words.size(); +} + +/// @brief configure the array for op `to`: stop the DMA channels, then write +/// the op's stream switches, BDs and lock values, then start its chains. +/// @param from the op configured now; -1 = unknown (fresh load, or another +/// xclbin ran since), which means a full write of everything +/// @return number of register writes +inline size_t gen_switch(npu_sequence* seq, int to, int from) { + static const std::vector sw_regs = union_of([](const op_config& c) -> const auto& { return c.sw; }); + static const std::vector lock_regs = union_of([](const op_config& c) -> const auto& { return c.locks; }); + const op_config& cfg = config_of(to); + const bool full = from != OP_DQ && from != OP_ATTN; + size_t writes = 0; + + // 1. reset the channels the old op runs on: its chains loop forever, + // waiting on a lock (the other op's channels are idle already) + auto reset = [&](uint32_t row, uint32_t col, uint32_t offset) { + seq->npu_maskwrite(get_tile(row, col), offset, DMA_CTRL_RESET, DMA_CTRL_RESET); + seq->npu_maskwrite(get_tile(row, col), offset, 0, DMA_CTRL_RESET); + writes += 2; + }; + if (full) { + for (const reg_write& ch : all_channels) reset(ch.row, ch.col, ch.offset); + } else { + for (const chain_start& s : config_of(from).starts) reset(s.row, s.col, s.ctrl_offset); + } + // 2. routes: this op's value, or 0 (port off) where only the other op + // routes; after a known op only the registers whose value differs + for (const reg_key& key : sw_regs) { + const uint32_t v = value_in(cfg.sw, key); + if (!full && v == value_in(config_of(from).sw, key)) continue; + write_reg(seq, std::get<1>(key), std::get<0>(key), std::get<2>(key), v); + writes++; + } + for (const mask_write& m : cfg.mux) { + seq->npu_maskwrite(get_tile(m.row, m.col), m.offset, m.value, m.mask); + writes++; + } + // 3. BDs: those only one op uses stay loaded once written (full switch); + // those both ops use are this op's again after every switch + if (full) { + for (const op_config* c : {&op_dq, &op_attn}) + for (const reg_block& b : c->bds) + if (!b.shared) writes += write_bd(seq, b); + } + for (const reg_block& b : cfg.bds) + if (b.shared) writes += write_bd(seq, b); + // 4. lock values, after the reset (a reset chain may hold a lock count). + // Not the op lock: every core is waiting on it right now. + for (const reg_key& key : lock_regs) { + if (std::get<1>(key) >= 2 && std::get<2>(key) == OP_LOCK_REG) continue; + write_reg(seq, std::get<1>(key), std::get<0>(key), std::get<2>(key), value_in(cfg.locks, key)); + writes++; + } + // 5. start the op's chains + for (const chain_start& s : cfg.starts) { + write_reg(seq, s.row, s.col, s.queue_offset, s.queue_value); + write_reg(seq, s.row, s.col, s.ctrl_offset, s.ctrl_value); + writes += 2; + } + return writes; +} + +/// @brief per-core RTP block for one run of `op`, then let the cores go +/// @param extra (index, value) pairs of the op's own RTP fields +inline void gen_dispatch(npu_sequence* seq, int op, int calls, bool switched, int cols, + std::initializer_list> extra) { + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < cols; c++) { + const uint32_t row = r + 2; + for (const auto& [idx, value] : extra) write_reg(seq, row, c, RTP_ADDR + 4 * idx, value); + write_reg(seq, row, c, RTP_ADDR + 4 * RTP_OP, op); + write_reg(seq, row, c, RTP_ADDR + 4 * RTP_CALLS, calls); + write_reg(seq, row, c, RTP_ADDR + 4 * RTP_SWITCHED, switched ? 1 : 0); + } + } + // after all RTPs: the cores read them as soon as their lock is set + for (int r = 0; r < ROWS; r++) + for (int c = 0; c < cols; c++) write_reg(seq, r + 2, c, OP_LOCK_REG, 1); +} + +// ---- dequant_mm: runtime m (rows per core row) and the fused GLU -------------- +// The array works on blocks of 4 core rows x m rows, m a multiple of 16 up to the +// 128 the design is built for. m lives in the cores' RTP (RTP_DQ_M), the shim x / y +// descriptors and the memtile DMA lengths, which the overlay's switch loads for +// m = 128: a dispatch with another m (or the GLU) re-arms the memtiles and puts +// them back at its end, so the switch's picture of the dq op stays true. +// See dequant_mm_bfp16_rtm2_glu_512x512x512/host/seq_gen.hpp, which this mirrors; +// tools/check_memtile_bds.py checks the ids and values below in every build. +struct rtm_geometry { + uint32_t blocks; //!< 4 x m row blocks + uint32_t m; //!< rows per core row, multiple of 16 + uint32_t covered; //!< blocks * 4 * m +}; + +inline rtm_geometry rtm_pick_geometry(uint32_t rows) { + assert(rows > 0); + rtm_geometry g; + g.blocks = (rows + 511) / 512; + g.m = 16 * ((rows + g.blocks * 64 - 1) / (g.blocks * 64)); + g.covered = g.blocks * 4 * g.m; + // a re-arm costs ~50 us; below ~128 rows saved the full blocks are faster + if (g.blocks * 512 - g.covered < 128) { g.m = 128; g.covered = g.blocks * 512; } + return g; +} + +constexpr uint32_t MT_BD_BASE = 0xA0000, MT_BD_STRIDE = 0x20, MT_LOCK_BASE = 0xC0000, MT_LOCK_STRIDE = 0x10; +struct rtm_channel { uint32_t ctrl; uint32_t start_bd; }; +constexpr rtm_channel MT_X_CH[] = {{0xA0600, 0}, {0xA0630, 2}}; // S2MM0, MM2S0 +constexpr rtm_channel MT_Y_CH[] = {{0xA0608, 24}, {0xA0610, 6}, {0xA0618, 26}, {0xA0620, 8}, {0xA0638, 28}}; // S2MM1-4, MM2S1 +constexpr uint32_t MT_X_S2MM[] = {0, 1}; +constexpr uint32_t MT_X_MM2S[] = {2, 3, 4, 5}; +constexpr uint32_t MT_Y_S2MM[] = {6, 7, 8, 9, 24, 25, 26, 27}; +constexpr uint32_t MT_Y_MM2S[] = {28, 29}; +constexpr uint32_t MT_X_LOCKS[] = {0, 1, 2, 3, 4}, MT_X_LOCK_INIT[] = {2, 0, 0, 0, 0}; +constexpr uint32_t MT_Y_LOCKS[] = {5, 6, 7, 8}, MT_Y_LOCK_INIT[] = {4, 4, 0, 0}; +// GLU: a core sends 32 columns per row instead of 64 (y S2MM D2 wrap 8 -> 4 tiles, +// y MM2S D0 wrap 32 -> 16 words, lengths halve) +enum rtm_y_mode : uint32_t { RTM_Y_PLAIN = 0, RTM_Y_GLU = 1, RTM_Y_RESTORE = 2 }; +constexpr uint32_t MT_Y_S2MM_D2_PLAIN = (8u << 17) | 3u, MT_Y_S2MM_D2_GLU = (4u << 17) | 3u; // word 4 +constexpr uint32_t MT_Y_MM2S_D0_PLAIN = 32u << 17, MT_Y_MM2S_D0_GLU = 16u << 17; // word 2 + +/// @brief put the memtile x / y paths on m rows per core row (m = 128, RTM_Y_RESTORE: +/// back to what the switch loads). Reset the channels, put their locks back +/// (writing the maximum first grants an acquire still pending), rewrite the +/// lengths, start the chains again. +inline void rtm_rearm(npu_sequence* seq, uint32_t m, uint32_t ymode = RTM_Y_PLAIN) { + auto bd_word = [](uint32_t bd, uint32_t word) { return MT_BD_BASE + MT_BD_STRIDE * bd + 4 * word; }; + const bool glu = ymode == RTM_Y_GLU; + for (uint32_t col = 0; col < (uint32_t)COLS; col++) { + const npu_tiles mt = get_tile(1, col); + const bool has_x = (col % 2) == 0; // the x of core row r enters through memtile 2r + if (has_x) for (auto& c : MT_X_CH) seq->rtp_write(mt, c.ctrl, DMA_CTRL_RESET); + for (auto& c : MT_Y_CH) seq->rtp_write(mt, c.ctrl, DMA_CTRL_RESET); + if (has_x) + for (uint32_t i = 0; i < 5; i++) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_X_LOCKS[i], 63); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_X_LOCKS[i], MT_X_LOCK_INIT[i]); + } + for (uint32_t i = 0; i < 4; i++) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_Y_LOCKS[i], 63); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_Y_LOCKS[i], MT_Y_LOCK_INIT[i]); + } + if (has_x) { + for (uint32_t bd : MT_X_S2MM) seq->rtp_write(mt, bd_word(bd, 0), m * 256); + for (uint32_t bd : MT_X_MM2S) seq->rtp_write(mt, bd_word(bd, 0), m * 128); + } + for (uint32_t bd : MT_Y_S2MM) { + seq->rtp_write(mt, bd_word(bd, 0), glu ? m * 16 : m * 32); + if (ymode != RTM_Y_PLAIN) seq->rtp_write(mt, bd_word(bd, 4), glu ? MT_Y_S2MM_D2_GLU : MT_Y_S2MM_D2_PLAIN); + } + for (uint32_t bd : MT_Y_MM2S) { + seq->rtp_write(mt, bd_word(bd, 0), glu ? m * 64 : m * 128); + if (ymode != RTM_Y_PLAIN) seq->rtp_write(mt, bd_word(bd, 2), glu ? MT_Y_MM2S_D0_GLU : MT_Y_MM2S_D0_PLAIN); + seq->rtp_write(mt, bd_word(bd, 4), (m << 17) | 0x1F); + } + if (has_x) for (auto& c : MT_X_CH) { seq->rtp_write(mt, c.ctrl, 0); seq->rtp_write(mt, c.ctrl + 4, c.start_bd); } + for (auto& c : MT_Y_CH) { seq->rtp_write(mt, c.ctrl, 0); seq->rtp_write(mt, c.ctrl + 4, c.start_bd); } + } +} + +/// @brief gate/up weights for the fused GLU (copy of glu_repack in the rtm2 seq_gen.hpp). +/// The model's projection is slabs of 1024 rows [up 512 | gate 512], 32-row +/// blocks in pairs (reorder_cpy, vertical_blocks = 2). The fused kernel needs up +/// and the matching gate channels in the same core: pair P = 8 (2 slab + half) + c +/// holds [up row block 32 slab + 8 half + c | gate row block 32 slab + 16 + 8 half + c]. +/// Block-local relaying (relaid reader) commutes with this. +inline void glu_repack(uint8_t* dst, const uint8_t* src, uint32_t Din, uint32_t Dout) { + assert(Dout % 1024 == 0 && Din % QXNX_COL_BLOCK_SIZE == 0); + const size_t bb = get_quantization_byte_size((size_t)QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE, flm_q4k); + const uint32_t bpr = Din / QXNX_COL_BLOCK_SIZE; + auto off = [&](uint32_t rb, uint32_t cb) { return ((size_t)(rb / 2) * 2 * bpr + (size_t)cb * 2 + (rb % 2)) * bb; }; + for (uint32_t s = 0; s < Dout / 1024; s++) + for (uint32_t h = 0; h < 2; h++) + for (uint32_t c = 0; c < 8; c++) { + const uint32_t P = (2 * s + h) * 8 + c; + const uint32_t rb_up = 32 * s + 8 * h + c, rb_gate = 32 * s + 16 + 8 * h + c; + for (uint32_t cb = 0; cb < bpr; cb++) { + memcpy(dst + off(2 * P, cb), src + off(rb_up, cb), bb); + memcpy(dst + off(2 * P + 1, cb), src + off(rb_gate, cb), bb); + } + } +} + +/// @brief shim DMA of one core pair's GLU weights straight from the model's layout: +/// up / gate rows interleaved in pieces of `piece` rows ([up piece | gate piece] +/// repeated, pairs layout), core pair `u` = hidden channels 32 u .. 32 u + 31. +/// Reads [up block | gate block] per column block, the stream glu_repack() +/// would have laid out. A Q4_K block (1184 words) is longer than a DMA wrap +/// (1024), so each moves as two halves; the column blocks are the iteration. +inline void glu_gather_dma(npu_sequence* seq, npu_tiles tile, npu_bd_id bd, size_t weight_offset, + uint32_t u, uint32_t piece, uint32_t Din) { + const size_t bb = get_quantization_byte_size((size_t)QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE, flm_q4k); + const uint32_t bpr = Din / QXNX_COL_BLOCK_SIZE; + assert(piece % QXNX_ROW_BLOCK_SIZE == 0 && bpr < 64 && bb % 8 == 0); + auto block_of = [&](uint32_t row) { // pairs layout: row block rb at (rb / 2) 2 bpr + rb % 2 blocks + const uint32_t rb = row / QXNX_ROW_BLOCK_SIZE; + return weight_offset + ((size_t)(rb / 2) * 2 * bpr + rb % 2) * bb; + }; + const uint32_t r = QXNX_ROW_BLOCK_SIZE * u; + const uint32_t up_row = 2 * piece * (r / piece) + r % piece; + const size_t up = block_of(up_row), gate = block_of(up_row + piece); + seq->npu_dma_memcpy_nd(sizeof(char), 2, MM2S, tile, bd, it_channel_1, + {0, 0, 0, (uint32_t)up}, + {bpr, 2, 2, (uint32_t)(bb / 2)}, + {(uint32_t)(2 * bb), (uint32_t)(gate - up), (uint32_t)(bb / 2), 1}, -1, 0, false, aggressive_cache); +} + +/// @brief one dequant_mm run: y[rows][Dy] = x[rows][Din] W^T, W q4_k (pairs layout, relaid +/// blocks). Buffers: arg 0 = y, 1 = x, 2 = w. Din % 512, Dout % 512. +/// rtp_act 3 (GLU): y = silu(gate) * up, Dy = Dout / 2; W glu_repack()ed +/// (glu_piece 0) or the model's [up | gate] pieces of glu_piece rows (glu_gather_dma). +/// Rows [rows, covered) are computed on whatever x holds there and written to y: +/// both must span rtm_pick_geometry(rows).covered rows. +/// @param configured the op the array is set up for; updated to OP_DQ +inline void gen_dq_run(npu_sequence* seq, int& configured, const uint32_t rows, const uint32_t Din, const uint32_t Dout, + const size_t weight_offset, const size_t out_offset, const int rtp_act, const uint32_t glu_piece = 0) { + static constexpr npu_tiles IT[8] = {IT0, IT1, IT2, IT3, IT4, IT5, IT6, IT7}; + static constexpr uint32_t qm = QXNX_ROW_BLOCK_SIZE; + static constexpr uint32_t desired_k = 512; // kernel/dq/common.hpp NPU_K_TILE + static constexpr uint32_t desired_n = 64; + const uint32_t columns = COLS; + assert(Dout % (qm * columns) == 0 && Din % desired_k == 0); + const int K_div_k = Din / desired_k; + const rtm_geometry g = rtm_pick_geometry(rows); + const uint32_t m = g.m; + const int M_div_m = g.blocks; + const int N_div_n = Dout / desired_n / columns; + const bool glu = rtp_act == DQ_ACT_GLU; + const uint32_t Dy = glu ? Dout / 2 : Dout; // row pitch of y + const uint32_t pass_cols = glu ? desired_n * columns / 2 : desired_n * columns; // y columns per pass + const uint32_t half_cols = pass_cols / 2; // per memtile group + + seq->clear_cmds(); + const bool switched = configured != OP_DQ; + if (switched) gen_switch(seq, OP_DQ, configured); + configured = OP_DQ; + if (glu) overlay::rtm_rearm(seq, m, RTM_Y_GLU); else if (m != 128) overlay::rtm_rearm(seq, m); + // every core computes one m x 64 tile per round + gen_dispatch(seq, OP_DQ, M_div_m * N_div_n, switched, COLS, + {{RTP_DQ_K_DIV_K, (uint32_t)K_div_k}, {RTP_DQ_M, m / 16}, {RTP_DQ_ACT, (uint32_t)rtp_act}}); + + for (int i = 0; i < M_div_m; i++) { + for (int j = 0; j < N_div_n; j++) { + const int round = i * N_div_n + j; + const int bd_offset = (round % 2) * 8; + const uint32_t y_offset = i * m * 4 * Dy + j * pass_cols; + const uint32_t x_offset = i * m * 4 * Din; + const size_t w_offset = get_quantization_byte_size((size_t)j * desired_n * Din * columns, flm_q4k) + weight_offset; + const npu_bd_id y_bd_0 = npu_bd_id(0 + bd_offset); + const npu_bd_id y_bd_1 = npu_bd_id(3 + bd_offset); + const npu_bd_id x_bd = npu_bd_id(1 + bd_offset); + const npu_bd_id w_bd_0 = npu_bd_id(2 + bd_offset); + const npu_bd_id w_bd_1 = npu_bd_id(4 + bd_offset); + for (uint32_t col = 0; col < 4; col++) { + if (glu && glu_piece) { + glu_gather_dma(seq, IT[col], w_bd_0, weight_offset, columns * j + col, glu_piece, Din); + glu_gather_dma(seq, IT[col + 4], w_bd_1, weight_offset, columns * j + col + 4, glu_piece, Din); + } else { + seq->npu_dma_memcpy_nd(sizeof(char), 2, MM2S, IT[col], w_bd_0, it_channel_1, + {0, 0, 0, (uint32_t)(w_offset + get_quantization_byte_size((size_t)col * desired_n * Din, flm_q4k))}, + {1, 1, 1, (uint32_t)get_quantization_byte_size(desired_n * Din, flm_q4k)}, + {0, 0, 0, 1}, -1, 0, false, aggressive_cache); + seq->npu_dma_memcpy_nd(sizeof(char), 2, MM2S, IT[col + 4], w_bd_1, it_channel_1, + {0, 0, 0, (uint32_t)(w_offset + get_quantization_byte_size((size_t)col * desired_n * Din, flm_q4k) + + get_quantization_byte_size(4 * desired_n * Din, flm_q4k))}, + {1, 1, 1, (uint32_t)get_quantization_byte_size(desired_n * Din, flm_q4k)}, + {0, 0, 0, 1}, -1, 0, false, aggressive_cache); + } + seq->npu_dma_memcpy_nd(2, 0, S2MM, IT[col], y_bd_0, it_channel_0, + {0, 0, 0, (uint32_t)(y_offset + col * m * Dy + out_offset)}, + {1, 1, m, half_cols}, {0, 0, Dy, 1}, -1, 0, true); + seq->npu_dma_memcpy_nd(2, 0, S2MM, IT[col + 4], y_bd_1, it_channel_0, + {0, 0, 0, (uint32_t)(y_offset + col * m * Dy + half_cols + out_offset)}, + {1, 1, m, half_cols}, {0, 0, Dy, 1}, -1, 0, true); + seq->npu_dma_memcpy_nd(2, 1, MM2S, IT[2 * col], x_bd, it_channel_0, + {0, 0, 0, x_offset + col * m * Din}, + {1, (uint32_t)K_div_k, m, desired_k}, {0, desired_k, Din, 1}, -1, 0, false); + } + if (round > 0) { + for (int r = 0; r < 4; r++) { + seq->npu_dma_wait(IT[r], S2MM, it_channel_0); + seq->npu_dma_wait(IT[r + 4], S2MM, it_channel_0); + } + } + } + } + for (int r = 0; r < 4; r++) { + seq->npu_dma_wait(IT[r], S2MM, it_channel_0); + seq->npu_dma_wait(IT[r + 4], S2MM, it_channel_0); + } + // leave the switch's configuration behind (the cores get m with every run) + if (glu) overlay::rtm_rearm(seq, 128, RTM_Y_RESTORE); else if (m != 128) overlay::rtm_rearm(seq, 128); + seq->cmds2seq(); +} + +/// @brief one attention run (Hy: dh 128, GQA, KV cache in the decode layout +/// [K col0][K col1][V col0][V col1]). Buffers: arg 0 = o, 1 = q, 2 = kv cache. +/// @param configured the op the array is set up for; updated to OP_ATTN +inline void gen_attn_run(npu_sequence* seq, int& configured, const uint32_t L_begin, const uint32_t L_wanted, + const int MAX_L, const int WINDOW_SIZE, const int lc, const int DH, const int Heads, + const int KV_Heads, const int Num_of_d_in_KV_cache, const int KV_CACHE_SIZE, + bool is_sliding_window = false) { + // 4 CUs of 2 columns; CUs 2h, 2h + 1 (columns 4h .. 4h + 3) share one K / V + // stream from shim 4h + 3, so their two heads must share a KV head + npu_tiles IT[4][2] = {{IT0, IT1}, {IT2, IT3}, {IT4, IT5}, {IT6, IT7}}; + assert(L_wanted % (lc * 8) == 0); + const int q_per_kv = Heads / KV_Heads; + const int using_window_size = is_sliding_window ? WINDOW_SIZE : MAX_L; + const int Q_chunks = L_wanted / (lc * 8); + const int num_cu = 4; + assert(Heads % num_cu == 0 && q_per_kv % 2 == 0); + + seq->clear_cmds(); + const bool switched = configured != OP_ATTN; + if (switched) gen_switch(seq, OP_ATTN, configured); + configured = OP_ATTN; + // one attn() call per head round + gen_dispatch(seq, OP_ATTN, Heads / num_cu, switched, ATTN_COLS, + {{RTP_AT_L_BEGIN, L_begin}, {RTP_AT_L_CHUNKS, (uint32_t)Q_chunks}, + {RTP_AT_WINDOW, (uint32_t)using_window_size}}); + + const int data_per_round = lc * 8; + for (int head = 0; head < Heads / num_cu; head++) { + for (int round = 0; round < Q_chunks; round++) { + int Lq_current = L_begin + round * data_per_round; + int kv_begin = ((Lq_current - using_window_size) > 0) ? (Lq_current - using_window_size) : 0; + int kv_end = (Lq_current + 2 * data_per_round - 1) / data_per_round * data_per_round; + int kv_length = kv_end - kv_begin; + int bd_offset = (round % 2) * 8; + for (int cu = 0; cu < num_cu; cu++) { + int head_offset = head * num_cu + cu; + for (int col = 0; col < 2; col++) { + size_t y_offset = head_offset * DH + (round * data_per_round + col * lc * 4) * DH * Heads; + seq->npu_dma_memcpy_nd(2, 0, S2MM, IT[cu][col], (npu_bd_id)(bd_offset + 0), it_channel_0, + {0, 0, 0, (uint32_t)y_offset}, {1, 1, (uint32_t)4 * lc, (uint32_t)DH}, + {0, 0, (uint32_t)DH * Heads, 1}, -1, 0, true); + } + size_t q_offset = head_offset * DH + round * data_per_round * DH * Heads; + seq->npu_dma_memcpy_nd(2, 1, MM2S, IT[cu][0], (npu_bd_id)(bd_offset + 1), it_channel_0, + {0, 0, 0, (uint32_t)q_offset}, {1, 1, (uint32_t)lc * 4, (uint32_t)DH}, + {0, 0, (uint32_t)DH * Heads, 1}, -1, 0, false); + seq->npu_dma_memcpy_nd(2, 1, MM2S, IT[cu][0], (npu_bd_id)(bd_offset + 2), it_channel_1, + {0, 0, 0, (uint32_t)(q_offset + (size_t)lc * 4 * DH * Heads)}, {1, 1, (uint32_t)lc * 4, (uint32_t)DH}, + {0, 0, (uint32_t)DH * Heads, 1}, -1, 0, false); + } + for (int half = 0; half < num_cu / 2; half++) { + int kv_head_offset = (head * num_cu + 2 * half) / q_per_kv; + int kv_chunk_offset = kv_head_offset / Num_of_d_in_KV_cache; + int kv_head_offset_in_chunk = kv_head_offset % Num_of_d_in_KV_cache; + size_t k_offset = (size_t)kv_chunk_offset * MAX_L * DH * Num_of_d_in_KV_cache + + (size_t)kv_head_offset_in_chunk * DH + (size_t)kv_begin * DH * Num_of_d_in_KV_cache; + seq->npu_dma_memcpy_nd(2, 2, MM2S, IT[2 * half + 1][1], (npu_bd_id)(bd_offset + 3), it_channel_0, + {0, 0, 0, (uint32_t)k_offset}, {1, (uint32_t)kv_length / 128, (uint32_t)128, (uint32_t)DH}, + {0, (uint32_t)128 * DH * Num_of_d_in_KV_cache, (uint32_t)DH * Num_of_d_in_KV_cache, 1}, -1, 0, false); + size_t v_offset = k_offset + KV_CACHE_SIZE / 2; + seq->npu_dma_memcpy_nd(2, 2, MM2S, IT[2 * half + 1][1], (npu_bd_id)(bd_offset + 4), it_channel_1, + {0, 0, 0, (uint32_t)v_offset}, {1, (uint32_t)kv_length / 128, (uint32_t)128, (uint32_t)DH}, + {0, (uint32_t)128 * DH * Num_of_d_in_KV_cache, (uint32_t)DH * Num_of_d_in_KV_cache, 1}, -1, 0, false); + } + if (round > 0) { + for (int cu = 0; cu < num_cu; cu++) + for (int col = 0; col < 2; col++) seq->npu_dma_wait(IT[cu][col], S2MM, it_channel_0); + } + } + for (int cu = 0; cu < num_cu; cu++) + for (int col = 0; col < 2; col++) seq->npu_dma_wait(IT[cu][col], S2MM, it_channel_0); + } + seq->cmds2seq(); +} + +/// @brief register writes of one switch (for reporting) +inline size_t switch_writes(int to, int from) { + npu_sequence scratch(device_npu2, false); + return gen_switch(&scratch, to, from); +} + +} // namespace overlay diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/attn_tiles.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/attn_tiles.py new file mode 100644 index 000000000..6716c7751 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/attn_tiles.py @@ -0,0 +1,201 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""Prefill attention (Hy_mem_30BA3B/attention_prefill) DMA chains and locks, on arenas. + +Same chains, locks and dimensions as the original attn_tile.py; every buffer is +now (arena, offset) from layout.py. Only built into the "attn" variant. +""" +import aie.dialects.aie as aie + +from utils import lock_acquire, lock_release +from layout import CT_AT, MT_AT_EVEN, MT_AT_ODD, elems + +d = 128 # head dim +lq = 16 +lk = 16 +lk_mt = 128 +lq_mt = 64 +lq_ct = 32 + + +def bd(arena, off_bytes, length, dims=None, bd_id=None): + if dims is None: + aie.dma_bd(arena, offset=elems(off_bytes), len=length, bd_id=bd_id) + else: + aie.dma_bd(arena, offset=elems(off_bytes), len=length, dimensions=dims, bd_id=bd_id) + + +class BdIds: + """Fixed BD ids for attention, away from the ones aiecc gives dequant_mm + (which counts up from 0 / 24). Then most BDs of both ops can stay loaded + and a switch rewrites only the ids both ops use (host: overlay_host.hpp). + A mem tile's even channels use BDs 0..23, its odd channels 24..47.""" + + def __init__(self, even_first, odd_first): + self.next = {0: even_first, 1: odd_first} + + def take(self, channel): + i = self.next[channel % 2] + self.next[channel % 2] += 1 + return i + + +CT_BD_FIRST = 8 # dequant_mm's core BDs are 0..5 +MT_EVEN_BD_FIRST = dict(even=14, odd=36) # attn_memtile_even uses 10 + 12 +MT_ODD_BD_FIRST = dict(even=16, odd=40) # attn_memtile_odd uses 8 + 8 + + +def attn_core(arena, tile): + q_prod = aie.lock(tile, lock_id=0, init=1) + q_cons = aie.lock(tile, lock_id=1, init=0) + in_prod = aie.lock(tile, lock_id=2, init=2) + in_cons = aie.lock(tile, lock_id=3, init=0) + o_prod = aie.lock(tile, lock_id=4, init=2) + o_cons = aie.lock(tile, lock_id=5, init=0) + A = CT_AT + ids = iter(range(CT_BD_FIRST, CT_BD_FIRST + 5)) + + @aie.mem(tile) + def body(block): + aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest=block[1], chain=block[2]) + with block[1]: + lock_acquire(q_prod, 1) + bd(arena, A["q"], lq_ct * d, bd_id=next(ids)) + lock_release(q_cons, 1) + aie.next_bd(block[1]) + with block[2]: + aie.dma_start(aie.DMAChannelDir.S2MM, 1, dest=block[3], chain=block[5]) + for i, buf in enumerate(("in0", "in1")): + with block[3 + i]: + lock_acquire(in_prod, 1) + bd(arena, A[buf], lk * d, bd_id=next(ids)) + lock_release(in_cons, 1) + aie.next_bd(block[4 - i]) + with block[5]: + aie.dma_start(aie.DMAChannelDir.MM2S, 0, dest=block[6], chain=block[8]) + for i, buf in enumerate(("o0", "o1")): + with block[6 + i]: + lock_acquire(o_cons, 1) + bd(arena, A[buf], 64, bd_id=next(ids)) + lock_release(o_prod, 1) + aie.next_bd(block[7 - i]) + with block[8]: + aie.EndOp() + + +def _o_in_chains(block, first, arena, M, o_prod, o_cons, end_chain, ids): + """o from 4 cores (S2MM 2..5) into the two o buffers, then o out on MM2S 5""" + o_dims = [(lq // 8, 8 * d), (d // 8, 8), (8, d), (8, 1)] + heads = [first, first + 3, first + 6, first + 9] + for q in range(4): + head = heads[q] + with block[head]: + aie.dma_start(aie.DMAChannelDir.S2MM, 2 + q, dest=block[head + 1], chain=block[head + 3]) + acq = o_prod[q] + rel = o_prod[q + 1] if q < 3 else o_cons + for i, buf in enumerate(("o0", "o1")): + with block[head + 1 + i]: + lock_acquire(acq, 1) + bd(arena, M[buf] + 2 * q * lq * d, lq * d, o_dims, bd_id=ids.take(2 + q)) + lock_release(rel, 1) + aie.next_bd(block[head + 2 - i]) + out = first + 12 + with block[out]: + aie.dma_start(aie.DMAChannelDir.MM2S, 5, dest=block[out + 1], chain=block[end_chain]) + for i, buf in enumerate(("o0", "o1")): + with block[out + 1 + i]: + lock_acquire(o_cons, 1) + bd(arena, M[buf], 4 * lq * d, bd_id=ids.take(5)) + lock_release(o_prod[0], 1) + aie.next_bd(block[out + 2 - i]) + + +def attn_memtile_even(arena, tile): + """q in (S2MM 0, 1) -> 4 core slices (MM2S 0..3); o back from 4 cores""" + M = MT_AT_EVEN + q_prod_0 = aie.lock(tile, lock_id=0, init=2) + q_cons_0 = aie.lock(tile, lock_id=1, init=0) + q_cons_1 = aie.lock(tile, lock_id=3, init=0) + q_prod_1 = aie.lock(tile, lock_id=4, init=2) + q_cons_2 = aie.lock(tile, lock_id=5, init=0) + q_cons_3 = aie.lock(tile, lock_id=6, init=0) + o_prod = [aie.lock(tile, lock_id=7, init=2)] + [aie.lock(tile, lock_id=i, init=0) for i in (8, 9, 10)] + o_cons = aie.lock(tile, lock_id=11, init=0) + q_dims = [(lq_ct // 8, 8 * d), (d // 8, 8), (8, d), (8, 1)] + ids = BdIds(MT_EVEN_BD_FIRST["even"], MT_EVEN_BD_FIRST["odd"]) + + @aie.memtile_dma(tile) + def body(block): + # q in: first half (S2MM 0) and second half (S2MM 1) of each buffer + aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest=block[1], chain=block[3]) + for i, buf in enumerate(("q0", "q1")): + with block[1 + i]: + lock_acquire(q_prod_0, 1) + bd(arena, M[buf], lq_mt * d, bd_id=ids.take(0)) + lock_release(q_cons_0, 1) + aie.next_bd(block[2 - i]) + with block[3]: + aie.dma_start(aie.DMAChannelDir.S2MM, 1, dest=block[4], chain=block[6]) + for i, buf in enumerate(("q0", "q1")): + with block[4 + i]: + lock_acquire(q_prod_1, 1) + bd(arena, M[buf] + 2 * lq_mt * d, lq_mt * d, bd_id=ids.take(1)) + lock_release(q_cons_2, 1) + aie.next_bd(block[5 - i]) + # q out: quarter s of each buffer on MM2S s, chained cons_0 -> cons_1 -> prod_0, cons_2 -> cons_3 -> prod_1 + steps = [(q_cons_0, q_cons_1), (q_cons_1, q_prod_0), (q_cons_2, q_cons_3), (q_cons_3, q_prod_1)] + for s in range(4): + head = 6 + 3 * s + with block[head]: + aie.dma_start(aie.DMAChannelDir.MM2S, s, dest=block[head + 1], chain=block[head + 3]) + acq, rel = steps[s] + for i, buf in enumerate(("q0", "q1")): + with block[head + 1 + i]: + lock_acquire(acq, 1) + bd(arena, M[buf] + 2 * s * lq_ct * d, lq_ct * d, q_dims, bd_id=ids.take(s)) + lock_release(rel, 1) + aie.next_bd(block[head + 2 - i]) + _o_in_chains(block, 18, arena, M, o_prod, o_cons, 33, ids) + with block[33]: + aie.EndOp() + + +def attn_memtile_odd(arena, tile): + """k / v in (S2MM 0, 1) -> broadcast to the cores (MM2S 0); o back from 4 cores""" + M = MT_AT_ODD + in_prod = aie.lock(tile, lock_id=0, init=4) + in_cons = aie.lock(tile, lock_id=1, init=0) + o_prod = [aie.lock(tile, lock_id=2, init=2)] + [aie.lock(tile, lock_id=i, init=0) for i in (3, 4, 5)] + o_cons = aie.lock(tile, lock_id=6, init=0) + in_dims = [(lk_mt // lk, lk * d), (lk, 8), (d // 8, lk * 8), (8, 1)] + ids = BdIds(MT_ODD_BD_FIRST["even"], MT_ODD_BD_FIRST["odd"]) + + @aie.memtile_dma(tile) + def body(block): + aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest=block[1], chain=block[3]) + for i, buf in enumerate(("in0", "in1")): + with block[1 + i]: + lock_acquire(in_prod, 1) + bd(arena, M[buf], lk_mt * d, in_dims, bd_id=ids.take(0)) + lock_release(in_cons, 1) + aie.next_bd(block[2 - i]) + with block[3]: + aie.dma_start(aie.DMAChannelDir.S2MM, 1, dest=block[4], chain=block[6]) + for i, buf in enumerate(("in0", "in1")): + with block[4 + i]: + lock_acquire(in_prod, 1) + bd(arena, M[buf] + 2 * lk_mt * d, lk_mt * d, in_dims, bd_id=ids.take(1)) + lock_release(in_cons, 1) + aie.next_bd(block[5 - i]) + with block[6]: + aie.dma_start(aie.DMAChannelDir.MM2S, 0, dest=block[7], chain=block[9]) + for i, buf in enumerate(("in0", "in1")): + with block[7 + i]: + lock_acquire(in_cons, 2) + bd(arena, M[buf], 2 * lk_mt * d, [(2 * lk_mt // lk, lk * d), (lk, d), (d, 1)], bd_id=ids.take(0)) + lock_release(in_prod, 2) + aie.next_bd(block[8 - i]) + _o_in_chains(block, 9, arena, M, o_prod, o_cons, 24, ids) + with block[24]: + aie.EndOp() diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/dq_tiles.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/dq_tiles.py new file mode 100644 index 000000000..9042c4918 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/dq_tiles.py @@ -0,0 +1,211 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""bfp16 dequant_mm (FLM_Xclbin/dequant_mm_bfp16_rtm2_glu_512x512x512) DMA chains and locks, on arenas. + +Same chains, locks and dimensions as that design's dequant_mm_tile.py; every +buffer is (arena, offset) from layout.py instead of its own aie.buffer. Only +built into the "dq" variant (its configuration is replayed by the host). + +The host shortens a dispatch to m rows per core row by rewriting memtile BDs +(rtm_rearm in the engine), so the memtile BD ids are pinned to the standalone +design's: x S2MM0 0, 1; x MM2S0 2..5; y S2MM1 24, 25; S2MM2 6, 7; S2MM3 26, 27; +S2MM4 8, 9; y MM2S1 28, 29; qw S2MM5 30, 31; qw MM2S2 10, 11. Attention's +memtile BDs start at 14 / 36, its core BDs at 8 (attn_tiles.py). +""" +import aie.dialects.aie as aie + +from utils import lock_acquire, lock_release +from layout import CT_DQ_E, CT_DQ_O, MT_DQ, elems + +# shapes (bf16 elements unless noted), kernel/dq/common.hpp +m, k, n = 128, 512, 64 +m_slice, y_slice = 16, 256 +QW_BYTES = 4736 # one q4_k block (32 rows x 256) +X_CT = m_slice * 128 # x chunk per core buffer + +MT_BD = dict(x_in=(0, 1), x_out=(2, 3, 4, 5), + y_in=((24, 25), (6, 7), (26, 27), (8, 9)), y_out=(28, 29), + qw_in=(30, 31), qw_out=(10, 11)) + + +def bd(arena, off_bytes, length, dims=None, bd_id=None): + """aie.dma_bd on a bf16 arena at a byte offset""" + kw = {} if bd_id is None else dict(bd_id=bd_id) + if dims is None: + aie.dma_bd(arena, offset=elems(off_bytes), len=length, **kw) + else: + aie.dma_bd(arena, offset=elems(off_bytes), len=length, dimensions=dims, **kw) + + +def dq_core_pair(arena_e, arena_o, tile_e, tile_o): + """chains + locks of one (even, odd) core pair; core BDs 0..5""" + x_dims = [(m_slice, 8), (128 // 8, m_slice * 8), (8, 1)] + + x_prod = aie.lock(tile_e, lock_id=0, init=2) + x_cons = aie.lock(tile_e, lock_id=1, init=0) + qw_prod = aie.lock(tile_e, lock_id=2, init=4) + qw_cons = aie.lock(tile_e, lock_id=3, init=0) + y_prod = aie.lock(tile_e, lock_id=4, init=2) + y_cons = aie.lock(tile_e, lock_id=5, init=0) + aie.lock(tile_e, lock_id=6, init=0) # sync, used by the cores only + x_prod_o = aie.lock(tile_o, lock_id=0, init=2) + x_cons_o = aie.lock(tile_o, lock_id=1, init=0) + y_prod_o = aie.lock(tile_o, lock_id=4, init=2) + y_cons_o = aie.lock(tile_o, lock_id=5, init=0) + aie.lock(tile_o, lock_id=6, init=0) # sync + + E = CT_DQ_E + + @aie.mem(tile_e) + def mem_e(block): + aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest=block[1], chain=block[3]) + with block[1]: + lock_acquire(x_prod, 1) + bd(arena_e, E["x0"], X_CT, x_dims, bd_id=0) + lock_release(x_cons, 1) + aie.next_bd(block[2]) + with block[2]: + lock_acquire(x_prod, 1) + bd(arena_e, E["x1"], X_CT, x_dims, bd_id=1) + lock_release(x_cons, 1) + aie.next_bd(block[1]) + with block[3]: + aie.dma_start(aie.DMAChannelDir.S2MM, 1, dest=block[4], chain=block[6]) + # every block is read by both cores of the pair: 2 credits per buffer + with block[4]: + lock_acquire(qw_prod, 2) + bd(arena_e, E["qw0"], QW_BYTES // 2, bd_id=2) + lock_release(qw_cons, 2) + aie.next_bd(block[5]) + with block[5]: + lock_acquire(qw_prod, 2) + bd(arena_e, E["qw1"], QW_BYTES // 2, bd_id=3) + lock_release(qw_cons, 2) + aie.next_bd(block[4]) + with block[6]: + aie.dma_start(aie.DMAChannelDir.MM2S, 0, dest=block[7], chain=block[9]) + with block[7]: + lock_acquire(y_cons, 1) + bd(arena_e, E["y0"], y_slice, bd_id=4) + lock_release(y_prod, 1) + aie.next_bd(block[8]) + with block[8]: + lock_acquire(y_cons, 1) + bd(arena_e, E["y1"], y_slice, bd_id=5) + lock_release(y_prod, 1) + aie.next_bd(block[7]) + with block[9]: + aie.EndOp() + + O = CT_DQ_O + + @aie.mem(tile_o) + def mem_o(block): + aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest=block[1], chain=block[3]) + with block[1]: + lock_acquire(x_prod_o, 1) + bd(arena_o, O["x0"], X_CT, x_dims, bd_id=0) + lock_release(x_cons_o, 1) + aie.next_bd(block[2]) + with block[2]: + lock_acquire(x_prod_o, 1) + bd(arena_o, O["x1"], X_CT, x_dims, bd_id=1) + lock_release(x_cons_o, 1) + aie.next_bd(block[1]) + with block[3]: + aie.dma_start(aie.DMAChannelDir.MM2S, 0, dest=block[4], chain=block[6]) + with block[4]: + lock_acquire(y_cons_o, 1) + bd(arena_o, O["y0"], y_slice, bd_id=2) + lock_release(y_prod_o, 1) + aie.next_bd(block[5]) + with block[5]: + lock_acquire(y_cons_o, 1) + bd(arena_o, O["y1"], y_slice, bd_id=3) + lock_release(y_prod_o, 1) + aie.next_bd(block[4]) + with block[6]: + aie.EndOp() + + +def dq_memtile(arena, tile): + """mem tile chains + locks (x to a core row, y from 4 cores, q4_k weights)""" + M = MT_DQ + x_prod = aie.lock(tile, lock_id=0, init=2) + x_cons = [aie.lock(tile, lock_id=i, init=0) for i in (1, 2)] + aie.lock(tile, lock_id=3, init=0) # the standalone design's, unused; rtm_rearm resets 0..4 + aie.lock(tile, lock_id=4, init=0) + # y join: each of the 4 S2MM channels takes one of the 4 producer credits of + # a buffer and adds one consumer credit; the output waits for all 4 + y_prod = [aie.lock(tile, lock_id=5, init=4), aie.lock(tile, lock_id=6, init=4)] + y_cons = [aie.lock(tile, lock_id=7, init=0), aie.lock(tile, lock_id=8, init=0)] + qw_prod = aie.lock(tile, lock_id=10, init=2) + qw_cons = aie.lock(tile, lock_id=11, init=0) + + x_out_dims = [(m // 16, 16 * k), (2, 128), (16, k), (128, 1)] + y_in_dims = [(m // 8, 8 * n), (8, 8), (8, n), (8, 1)] + + @aie.memtile_dma(tile) + def body(block): + # x in: whole 128 x 512 slab, ping / pong + aie.dma_start(aie.DMAChannelDir.S2MM, 0, dest=block[1], chain=block[3]) + for i, buf in enumerate(("x0", "x1")): + with block[1 + i]: + lock_acquire(x_prod, 1) + bd(arena, M[buf], m * k, bd_id=MT_BD["x_in"][i]) + lock_release(x_cons[0], 1) + aie.next_bd(block[2 - i]) + # x out: one send per k half of each slab (both n slices of a k slice are + # resident in the cores, so every x chunk is consumed once) + with block[3]: + aie.dma_start(aie.DMAChannelDir.MM2S, 0, dest=block[4], chain=block[8]) + for b, buf in enumerate(("x0", "x1")): + for s in range(2): + idx = 4 + 2 * b + s + with block[idx]: + lock_acquire(x_cons[s], 1) + bd(arena, M[buf] + s * k, m * k // 2, x_out_dims, bd_id=MT_BD["x_out"][2 * b + s]) + lock_release(x_cons[1] if s == 0 else x_prod, 1) + aie.next_bd(block[idx + 1] if idx < 7 else block[4]) + # y in from the 4 cores of a row (S2MM 1..4), each a quarter of the slab + heads = [8, 11, 14, 17] + for q in range(4): + head = heads[q] + with block[head]: + aie.dma_start(aie.DMAChannelDir.S2MM, 1 + q, dest=block[head + 1], + chain=block[head + 3] if q < 3 else block[20]) + for i, buf in enumerate(("y0", "y1")): + with block[head + 1 + i]: + lock_acquire(y_prod[i], 1) + bd(arena, M[buf] + 2 * q * m * n, m * n, y_in_dims, bd_id=MT_BD["y_in"][q][i]) + lock_release(y_cons[i], 1) + aie.next_bd(block[head + 2 - i]) + # y out to the shim + with block[20]: + aie.dma_start(aie.DMAChannelDir.MM2S, 1, dest=block[21], chain=block[23]) + for i, buf in enumerate(("y0", "y1")): + with block[21 + i]: + lock_acquire(y_cons[i], 4) + bd(arena, M[buf], 4 * m * n, [(m, n), (4, m * n), (n, 1)], bd_id=MT_BD["y_out"][i]) + lock_release(y_prod[i], 4) + aie.next_bd(block[22 - i]) + # q4_k weights in / out + with block[23]: + aie.dma_start(aie.DMAChannelDir.S2MM, 5, dest=block[24], chain=block[26]) + for i, buf in enumerate(("qw0", "qw1")): + with block[24 + i]: + lock_acquire(qw_prod, 1) + bd(arena, M[buf], QW_BYTES // 2, bd_id=MT_BD["qw_in"][i]) + lock_release(qw_cons, 1) + aie.next_bd(block[25 - i]) + with block[26]: + aie.dma_start(aie.DMAChannelDir.MM2S, 2, dest=block[27], chain=block[29]) + for i, buf in enumerate(("qw0", "qw1")): + with block[27 + i]: + lock_acquire(qw_cons, 1) + bd(arena, M[buf], QW_BYTES // 2, bd_id=MT_BD["qw_out"][i]) + lock_release(qw_prod, 1) + aie.next_bd(block[28 - i]) + with block[29]: + aie.EndOp() diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/layout.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/layout.py new file mode 100644 index 000000000..244c00644 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/layout.py @@ -0,0 +1,75 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""Memory layout of the prefill overlay, shared by the IRON design and the core code. + +Each core tile has one arena that both ops lay their buffers into (only one op +runs at a time, and neither keeps state in L1 between runs). The arena starts +right after the 4 KB stack; the RTP block follows the arena. + +dequant_mm is the bfp16 runtime-m design (../../dequant_mm_bfp16_rtm2_glu_512x512x512), +packed tighter than its standalone addresses (no RTPs in the middle), same order +and so the same bank split: x first, then y_acc, the q4_k blocks, y and the bfp16 +w slice. Attention keeps the addresses of the Hy-Memory overlay it comes from. + + python3 layout.py > overlay_layout.h # the same numbers for the core code +""" + +STACK = 4096 # bytes; attention used 3 KB, dequant_mm 2 KB + +# ---- core tile arena (byte offsets from the arena start = address - STACK) ---- +# dequant_mm even core (rows 2, 4): q4_k blocks arrive here; w slice 0 (bfp16) +CT_DQ_E = dict(x0=0, x1=4096, y_acc=8192, qw0=40960, qw1=45696, y0=50432, y1=50944, ws=51456) +# dequant_mm odd core (rows 3, 5): w slice 1 and the converted x chunks of both cores +CT_DQ_O = dict(x0=0, x1=4096, y_acc=8192, ws=40960, xce=50176, xco=54784, y0=59392, y1=59904) +# attention (every core) +CT_AT = dict(q=0, s=8192, y=12288, m=20480, in0=28672, o0=32768, in1=45056, o1=49152) +CT_ARENA_BYTES = 60672 + +# ---- mem tile arena (byte offsets) --------------------------------------------- +MT_DQ = dict(x0=0, x1=131072, y0=262144, y1=327680, qw0=393216, qw1=397952) +MT_AT_EVEN = dict(q0=0, q1=65536, o0=131072, o1=196608) # q in, o out +MT_AT_ODD = dict(in0=0, in1=65536, o0=131072, o1=196608) # k / v in, o out +MT_ARENA_BYTES = 402688 + +# ---- per-core RTP block (int32 indices), right after the arena ------------------ +RTP_WORDS = 32 +RTP = dict(op=0, calls=1, switched=2, # dispatcher + dq_k_div_k=4, dq_m=5, dq_act=6, # dequant_mm (the kernel reads m at k_div_k + 1) + at_l_begin=8, at_l_chunks=9, at_window=10) # attention + +OPS = dict(none=0, dq=1, attn=2) +OP_LOCK = 15 # core lock the dispatcher waits on; the host sets it to 1 + + +def elems(byte_offset, elem_bytes=2): + """byte offset -> element offset in a bf16 arena""" + assert byte_offset % elem_bytes == 0 + return byte_offset // elem_bytes + + +def check(): + assert STACK + CT_ARENA_BYTES + 4 * RTP_WORDS <= 65536 + for d in (CT_DQ_E, CT_DQ_O, CT_AT, MT_DQ): + assert all(v % 64 == 0 for v in d.values()), d + assert RTP["dq_m"] == RTP["dq_k_div_k"] + 1 + + +def header(): + check() + L = ["// Generated by iron/layout.py. Do not edit.", "#pragma once", ""] + L.append(f"constexpr int OVERLAY_STACK = {STACK};") + L.append(f"constexpr int CT_ARENA_BYTES = {CT_ARENA_BYTES};") + for prefix, d in (("CT_DQ_E", CT_DQ_E), ("CT_DQ_O", CT_DQ_O), ("CT_AT", CT_AT)): + for k, v in d.items(): + L.append(f"constexpr int {prefix}_{k.upper()} = {v}; // bytes") + for k, v in RTP.items(): + L.append(f"constexpr int RTP_{k.upper()} = {v};") + for k, v in OPS.items(): + L.append(f"constexpr int OP_{k.upper()} = {v};") + L.append(f"constexpr int OP_LOCK = {OP_LOCK};") + return "\n".join(L) + "\n" + + +if __name__ == "__main__": + print(header(), end="") diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/overlay_aie.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/overlay_aie.py new file mode 100644 index 000000000..2599601a1 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/overlay_aie.py @@ -0,0 +1,153 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""MiniCPM5 prefill overlay: bfp16 dequant_mm and attention in ONE xclbin, no context switch. + + variant base : arenas, RTP blocks, op locks and the core programs (both + kernels + a dispatcher). No routes, no DMA chains. This is + the xclbin that runs. + variant dq : base + dequant_mm_bfp16_rtm2_glu_512x512x512's locks, chains + and routes (q4_k weights in the relaid order, see kernel/dq/q4_core.h) + variant attn : base + the Hy-Memory overlay's attention locks, chains and routes, + repeated on columns 4..7 (4 CUs, a K / V stream per half) + +The dq / attn variants are never run. aiecc --aie-generate-txn dumps their +load-time configuration, tools/extract_txn2.py turns it into host/op_configs.hpp, +and the host writes one op's configuration into the base xclbin when the op +changes (stream switches, BDs, lock values, chain starts -- see +../switch_proto2 for the mechanism and its measurements). + + python3 overlay_aie.py base | dq | attn +""" +import sys +import numpy as np +from ml_dtypes import bfloat16 + +from aie.extras.context import mlir_mod_ctx +from aie.extras import types as T +import aie.dialects.aie as aie +from aie.helpers.dialects.ext.scf import _for as range_ + +from utils import generate_tile_map, connect_dma +from layout import CT_ARENA_BYTES, MT_ARENA_BYTES, RTP_WORDS, OP_LOCK, STACK +from dq_tiles import dq_core_pair, dq_memtile +from attn_tiles import attn_core, attn_memtile_even, attn_memtile_odd + +COLS = 8 +ROWS = 4 +ATTN_COLS = 8 # 4 CUs of 2 columns + + +def flow_arch(variant): + dev = aie.AIEDevice.npu2 + bf16 = np.dtype[bfloat16] + + with mlir_mod_ctx() as ctx: + @aie.device(dev) + def device_body(): + IT, MT, CT = generate_tile_map(ROWS + 2, COLS) + + ct_arena_ty = np.ndarray[(CT_ARENA_BYTES // 2,), bf16] + mt_arena_ty = np.ndarray[(MT_ARENA_BYTES // 2,), bf16] + rtp_ty = np.ndarray[(RTP_WORDS,), np.dtype[np.int32]] + # fused(arena, neighbour arena, rtp, row, col): even rows get the + # north (odd) arena -- w slice 1 and the converted x -- and odd rows + # the south (even) arena -- the q4_k blocks and w slice 0 + fused = aie.external_func("fused", [ct_arena_ty, ct_arena_ty, rtp_ty, T.i32(), T.i32()]) + + # ---- arenas, RTP blocks, op locks: identical in every variant -------- + ct_arena = [[None] * COLS for _ in range(ROWS)] + ct_rtp = [[None] * COLS for _ in range(ROWS)] + for r in range(ROWS): + for c in range(COLS): + t = CT[r][c].tile + ct_arena[r][c] = aie.buffer(t, ct_arena_ty, name=f"arena_{r + 2}_{c}") + ct_rtp[r][c] = aie.buffer(t, rtp_ty, name=f"rtp_{r + 2}_{c}") + aie.lock(t, lock_id=OP_LOCK, init=0) + mt_arena = [aie.buffer(MT[c].tile, mt_arena_ty, name=f"mt_arena_{c}") for c in range(COLS)] + + def make_core(r, c): + # a function per core so the body captures r, c (the decorator + # would read default arguments as MLIR block arguments) + even = r % 2 == 0 + other = ct_arena[r + 1][c] if even else ct_arena[r - 1][c] + obj = "fused_e.o" if even else "fused_o.o" + + @aie.core(CT[r][c].tile, link_with=obj, stack_size=STACK) + def core_body(): + for _ in range_(0xFFFFFFFF): + fused(ct_arena[r][c], other, ct_rtp[r][c], r, c) + + for r in range(ROWS): + for c in range(COLS): + make_core(r, c) + + if variant == "base": + return + + if variant == "dq": + for c in range(COLS): + for r in range(0, ROWS, 2): + dq_core_pair(ct_arena[r][c], ct_arena[r + 1][c], CT[r][c].tile, CT[r + 1][c].tile) + dq_memtile(mt_arena[c], MT[c].tile) + # w: shim -> mem S2MM 5 -> mem MM2S 2 -> the even cores of the column + for c in range(COLS): + connect_dma(IT[c], MT[c], 1, 5) + for r in range(0, ROWS, 2): + connect_dma(MT[c], CT[r][c], 2, 1) + # x: one mem tile per core row, broadcast along the row + for r in range(ROWS): + connect_dma(IT[2 * r], MT[2 * r], 0, 0) + for c in range(COLS): + connect_dma(MT[2 * r], CT[r][c], 0, 0) + # y: 4 cores of a row into one mem tile, then to the shim + for r in range(ROWS): + for c in range(COLS): + connect_dma(CT[r][c], MT[r if c < 4 else r + 4], 0, 1 + c % 4) + for c in range(COLS): + connect_dma(MT[c], IT[c], 1, 0) + + elif variant == "attn": + for c in range(ATTN_COLS): + for r in range(ROWS): + attn_core(ct_arena[r][c], CT[r][c].tile) + if c % 2 == 0: + attn_memtile_even(mt_arena[c], MT[c].tile) + else: + attn_memtile_odd(mt_arena[c], MT[c].tile) + # q: shim 2j -> mem 2j (two halves) -> core rows of columns 2j, 2j + 1 + for j in range(ATTN_COLS // 2): + connect_dma(IT[2 * j], MT[2 * j], 0, 0) + connect_dma(IT[2 * j], MT[2 * j], 1, 1) + for r in range(ROWS): + connect_dma(MT[2 * j], CT[r][2 * j], r, 0) + connect_dma(MT[2 * j], CT[r][2 * j + 1], r, 0) + # k / v: per half of the array (columns 4h .. 4h + 3, two CUs that + # share a KV head), shim 4h + 3 -> mem 4h + 3 -> every core of the half + for h in range(ATTN_COLS // 4): + kv = 4 * h + 3 + connect_dma(IT[kv], MT[kv], 0, 0) + connect_dma(IT[kv], MT[kv], 1, 1) + for c in range(4 * h, 4 * h + 4): + for r in range(ROWS): + connect_dma(MT[kv], CT[r][c], 0, 1) + # o: rows 0, 1 into mem 2j, rows 2, 3 into mem 2j + 1, then to the shim + for j in range(ATTN_COLS // 2): + connect_dma(CT[0][2 * j], MT[2 * j], 0, 2) + connect_dma(CT[0][2 * j + 1], MT[2 * j], 0, 3) + connect_dma(CT[1][2 * j], MT[2 * j], 0, 4) + connect_dma(CT[1][2 * j + 1], MT[2 * j], 0, 5) + connect_dma(CT[2][2 * j], MT[2 * j + 1], 0, 2) + connect_dma(CT[2][2 * j + 1], MT[2 * j + 1], 0, 3) + connect_dma(CT[3][2 * j], MT[2 * j + 1], 0, 4) + connect_dma(CT[3][2 * j + 1], MT[2 * j + 1], 0, 5) + for c in range(ATTN_COLS): + connect_dma(MT[c], IT[c], 5, 0) + else: + raise ValueError(variant) + + print(ctx.module) + + +if __name__ == "__main__": + flow_arch(sys.argv[1] if len(sys.argv) > 1 else "base") diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/utils.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/utils.py new file mode 100644 index 000000000..bf57a48a0 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/iron/utils.py @@ -0,0 +1,145 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +from dataclasses import dataclass +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +from aie.dialects.aie import * +from aie.dialects.aiex import * +from aie.helpers.dialects.ext.scf import _for as range_ +import aie.utils.trace as trace_utils +from aie.utils.trace import MemTilePortEvent, MemTileEvent, PortEvent +from aie.utils.trace_events_enum import CoreEvent, MemEvent, ShimTileEvent, MemTileEvent +from aie.dialects import memref +from typing import Dict, Any, List, Optional +from aie.extras import types as T + +@dataclass +class tile_with_location: + tile: tile + row: int + col: int + +@dataclass +class dma_port: + tile: tile_with_location + channel: int + +class mlir_context: + def __init__(self): + self.data_tys = {} + self.funcs = {} + self.buffers = {} + self.parameters = {} + self.object_fifos = {} + self.packet_ids = {} + + def data_ty(self, name: str, shape: List[int], dtype: Any): + d_ty = np.ndarray[shape, dtype] + self.data_tys[name] = d_ty + if not hasattr(self, name): + setattr(self, name, d_ty) + else: + raise ValueError(f"Data type {name} already exists") + return d_ty + + def buffer(self, name: str, tile: tile_with_location, dtype: Any, use_write_rtp: bool = False): + new_buffer = aie.buffer(tile.tile, dtype, name = name, use_write_rtp = use_write_rtp) + self.buffers[name] = new_buffer + if not hasattr(self, name): + setattr(self, name, new_buffer) + else: + raise ValueError(f"Buffer {name} already exists") + + return new_buffer + + def func(self, name: str, inputs: List[Any]): + this_func = aie.external_func(name, inputs) + self.funcs[name] = this_func + if not hasattr(self, name): + setattr(self, name, this_func) + else: + raise ValueError(f"Function {name} already exists") + return this_func + + def parameter(self, name: str, value: Any): + self.parameters[name] = value + if not hasattr(self, name): + setattr(self, name, value) + else: + raise ValueError(f"Parameter {name} already exists") + return value + + def object_fifo(self, name: str, src_tile: tile_with_location, dst_tile: tile_with_location | List[tile_with_location], depth: int, data_ty: Any, *args, **kwargs): + if isinstance(dst_tile, tile_with_location): + fifo = object_fifo(name, src_tile.tile, dst_tile.tile, depth, data_ty, *args, **kwargs) + else: + fifo = object_fifo(name, src_tile.tile, [t.tile for t in dst_tile], depth, data_ty, *args, **kwargs) + self.object_fifos[name] = fifo + if not hasattr(self, name): + setattr(self, name, fifo) + else: + raise ValueError(f"Object fifo {name} already exists") + return fifo + + + +def dma_mm2s_ch(ch: int): + return { + "source_port": WireBundle.DMA, + "source_channel": ch + } + +def dma_s2mm_ch(ch: int): + return { + "dest_port": WireBundle.DMA, + "dest_channel": ch + } + +def flow_mm2s_ch(ch: int): + return { + "source_bundle": WireBundle.DMA, + "source_channel": ch + } + +def flow_s2mm_ch(ch: int): + return { + "dest_bundle": WireBundle.DMA, + "dest_channel": ch + } + +def generate_tile_map(total_rows: int, total_cols: int) -> Tuple[List[tile_with_location], List[tile_with_location], List[List[tile_with_location]]]: + # Tile declarations + ShimTiles = [] + MemTiles = [] + cores = [] + for col in range(total_cols): + ShimTiles.append(tile_with_location(tile(col, 0), 0, col)) + MemTiles.append(tile_with_location(tile(col, 1), 0, col)) + + for row in range(total_rows - 2): + ComputeTilesRow = [] + for col in range(total_cols): + ComputeTilesRow.append(tile_with_location(tile(col, row + 2), row + 2, col)) + + cores.append(ComputeTilesRow) + + return ShimTiles, MemTiles, cores + +def connect_dma(src: tile_with_location, dst: tile_with_location, src_ch: int, dst_ch: int, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile, **flow_mm2s_ch(src_ch), dest = dst.tile, **flow_s2mm_ch(dst_ch)) + else: + aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src_ch), dest = dst.tile, **dma_s2mm_ch(dst_ch), keep_pkt_header = keep_pkt_header) + +def connect_port(src: dma_port, dst: dma_port, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile, **flow_mm2s_ch(src.channel), dest = dst.tile, **flow_s2mm_ch(dst.channel)) + else: + aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src.channel), dest = dst.tile, **dma_s2mm_ch(dst.channel), keep_pkt_header = keep_pkt_header) + + +def lock_acquire(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.AcquireGreaterEqual, value = value) + +def lock_release(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.Release, value = value) diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/attn/attn.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/attn/attn.cc new file mode 100644 index 000000000..6702597ee --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/attn/attn.cc @@ -0,0 +1,130 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#include +#include "common.h" +#include +#include "attn_kernel.h" + +constexpr int q_prod_lock = 0; +constexpr int q_cons_lock = 1; +constexpr int in_prod_lock = 2; +constexpr int in_cons_lock = 3; +constexpr int o_prod_lock = 4; +constexpr int o_cons_lock = 5; + +// Which of ping / pong comes next. File scope (not function statics) so the +// overlay's dispatcher can put them back to ping when the op's DMA chains restart. +static bool is_in_ping = false; +static bool is_o_ping = false; + +extern "C" { + void attn( + bf16 *__restrict o_ping, + bf16 *__restrict o_pong, + bf16 *__restrict q, + bf16 *__restrict in_ping, + bf16 *__restrict in_pong, + bf16 * s, + bf16 * m, + float * y, + int * L_begin_buffer, + int * L_chunks_buffer, + int * window_size_buffer, + const int row, + const int col + ){ + // round to nearest even on every fp32 <-> bf16/bfp16 conversion (default: + // truncate) -- fixes the cos ~0.92 @8K / ~0.49 @128K drift, see + // ../../attention_prefill (and /tmp/attn_rne): cos > 0.998 through 8K keys + aie::set_rounding(aie::rounding_mode::conv_even); + alignas(aie::vector_decl_align) bf16 prev_m_local[lq]; + alignas(aie::vector_decl_align) bf16 new_m_local[lq]; + alignas(aie::vector_decl_align) bf16 c[lq]; + alignas(aie::vector_decl_align) bf16 l[lq]; + + // plain locals, not function statics: Peano's loader does not zero .bss, + // so a static's init guard can read as already done + const aie::vector neg_inf = aie::broadcast(-0x1.FEp127f); + const aie::vector neg_inf_64 = aie::broadcast(-0x1.FEp127f); + const aie::vector one = aie::broadcast(1.0f); + + int i = 0; + int L_div_l; + int pointer_block_q = 0; + int pointer_block_inner_q = 0; + int pointer_block_k = 0; + int pointer_block_inner_k = 0; + int block_location = 0; + int pointer_block_inner_k_current = 0; + do{ + aie::store_v(prev_m_local, neg_inf); + aie::store_v(new_m_local, neg_inf); + aie::store_v(c, one); + zero_vectorized(l); + zero_vectorized(y); + + _lock_acquire(q_cons_lock); + // apply softmax + // determine lq + pointer_block_q = L_begin_buffer[0] + i * 128; + pointer_block_inner_q = pointer_block_q + col * 16 + row * 32; + // determine lk + int window_size = window_size_buffer[0]; + pointer_block_k = pointer_block_q - window_size; + pointer_block_k = pointer_block_k > 0 ? pointer_block_k : 0; + // determine llk + pointer_block_inner_k = pointer_block_inner_q - window_size; + pointer_block_inner_k = pointer_block_inner_k > -16 ? pointer_block_inner_k : -16; + int kv_blocks = ((pointer_block_q + 128 + 128 - 1) - pointer_block_k) / 128; + for (int block_idx = 0; block_idx < kv_blocks; block_idx++){ + // seed the running max with -inf, not prev_m: prev_m is folded + // back in after the reduction, so the broadcast row fill goes away + aie::store_v(m, neg_inf_64); + aie::store_v(m + 64, neg_inf_64); + aie::store_v(m + 128, neg_inf_64); + aie::store_v(m + 192, neg_inf_64); + for (int j = 0; j < 8; j++){ + block_location = block_idx * 8 + j; + pointer_block_inner_k_current = pointer_block_k + block_location * 16; + _lock_acquire(in_cons_lock); + is_in_ping = !is_in_ping; + bf16 *k = is_in_ping ? in_ping : in_pong; + _attn_qk(s + j * lq * lk, q + col * lq * dh, k, + m, pointer_block_inner_k, pointer_block_inner_q, + pointer_block_inner_k_current); + _lock_release(in_prod_lock); + } + aie::store_v(new_m_local, aie::max(_block_row_max(m), + aie::load_v(prev_m_local))); + apply_softmax_reorder(s, new_m_local); + calculate_c(c, prev_m_local, new_m_local); + calculate_l(l, c, s); + calculate_y(y, c); + for (int j = 0; j < 8; j++){ + _lock_acquire(in_cons_lock); + is_in_ping = !is_in_ping; + bf16 *v = is_in_ping ? in_ping : in_pong; + _attn_fv(y, s + j * lq * lk, v); + _lock_release(in_prod_lock); + } + aie::vector prev_m_local_vec = aie::load_v(new_m_local); + aie::store_v(prev_m_local, prev_m_local_vec); + } + _lock_release(q_prod_lock); + aie::vector l_vec = aie::load_v(l); + l_vec = aie::inv(l_vec); + aie::store_v(l, l_vec); + for (int o_row = 0; o_row < lq / 8; o_row++){ + for (int o_col = 0; o_col < dh / 8; o_col++){ + _lock_acquire(o_prod_lock); + is_o_ping = !is_o_ping; + bf16 *o = is_o_ping ? o_ping : o_pong; + scale_div_aie(o, l + o_row * 8, y + o_row * 8 * dh + o_col * 64); + _lock_release(o_cons_lock); + } + } + i++; + L_div_l = L_chunks_buffer[0]; + } while (i < L_div_l); + } +} \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/attn/attn_kernel.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/attn/attn_kernel.h new file mode 100644 index 000000000..1e3012f8d --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/attn/attn_kernel.h @@ -0,0 +1,365 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef ATTN_KERNEL_H +#define ATTN_KERNEL_H +#include +#include "common.h" +#include + +// new_m_local[i0 .. i0+3], each broadcast across a row of lk, as one 64-lane +// vector -- the row-wise subtrahend for a 4-row group of S. +static inline aie::vector _row_broadcast(bf16*__restrict new_m_local, int i0) { + return aie::concat(aie::broadcast(*(new_m_local + i0 + 0)), + aie::broadcast(*(new_m_local + i0 + 1)), + aie::broadcast(*(new_m_local + i0 + 2)), + aie::broadcast(*(new_m_local + i0 + 3))); +} + +// f = exp(s - max), then the 16x16 -> 8x8x4 shuffle that _attn_fv and +// calculate_l expect, in one pass. +// +// The row max used to be a scalar broadcast per row, which pinned the whole +// chain to 16 lanes and left it with no independent work to hide the load / +// sub / exp2 latencies. Broadcasting it into a 4-row vector once instead lets +// four exp2 chains run in parallel per iteration, and the reorder's operands +// are already in registers by then, so its loads and stores disappear. +void apply_softmax_reorder( + bf16*__restrict pS, + bf16*__restrict new_m_local +){ + for (int h = 0; h < 2; h++){ + // rows 8h..8h+3 feed A, rows 8h+4..8h+7 feed B + const aie::vector MB_A = _row_broadcast(new_m_local, 8 * h + 0); + const aie::vector MB_B = _row_broadcast(new_m_local, 8 * h + 4); + + bf16 *pS1 = pS + h * 128; + for (int b = 0; b < 8; b++) + chess_prepare_for_pipelining chess_loop_range(8, 8) { + aie::vector A = aie::sub(aie::load_v<64>(pS1), MB_A); + aie::vector B = aie::sub(aie::load_v<64>(pS1 + 64), MB_B); + aie::accum A_acc = aie::mul(A, exp_scale); + aie::accum B_acc = aie::mul(B, exp_scale); + A = aie::exp2(A_acc.template to_vector()); + B = aie::exp2(B_acc.template to_vector()); + + aie::store_v(pS1, aie::concat(aie::filter_even(A, 8), aie::filter_even(B, 8))); + aie::store_v(pS1 + 64, aie::concat(aie::filter_odd(A, 8), aie::filter_odd(B, 8))); + pS1 += 256; + } + } +} + +// S is [query][key] row-major, and _attn_qk emits it four rows at a time. Both +// the causal bound and the sliding window depend only on (key - query), so +// tabulate that offset for one 4-row x lk group: d_offset[p] = p % lk - p / lk. +// Row group g just shifts the row index by 4*g, so every group reuses this one +// table against thresholds moved by 4*g. +alignas(aie::vector_decl_align) int16 d_offset[64] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, + -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, +}; + +// Mask one 4-row group of S and fold it into the running elementwise max, with +// S still in registers from the mmul. Keeps S[i][j] iff lo < (j - i) <= hi. +template +static inline void _qk_mask_max( + T_out *__restrict pS, + T_out *__restrict pM, + const aie::vector &D, + aie::vector S, + int hi, + int lo +){ + aie::mask<64> keep = aie::le(D, (int16)hi) & aie::gt(D, (int16)lo); + S = aie::select((T_out)(-0x1.FEp127f), S, keep); + aie::vector M = aie::load_v<64>(pM); + aie::store_v(pM, aie::max(M, S)); + aie::store_v(pS, S); +} + +// One 4-row x lk group of M reduced to 4 row maxima, held as 4 x 2 lanes so +// every intermediate stays at a native vector width. +static inline aie::vector _row_max_pairs(const bf16*__restrict pM) { + aie::vector v0 = aie::load_v<64>(pM); + aie::vector v1 = aie::max(aie::filter_even(v0, 8), aie::filter_odd(v0, 8)); + aie::vector v2 = aie::max(aie::filter_even(v1, 4), aie::filter_odd(v1, 4)); + return aie::max(aie::filter_even(v2, 2), aie::filter_odd(v2, 2)); +} + +// Row-wise max of the whole lq x lk block. Four independent reduction trees +// instead of lq serial aie::reduce_max calls. +static inline aie::vector _block_row_max(const bf16*__restrict pM) { + aie::vector p = aie::concat(_row_max_pairs(pM), _row_max_pairs(pM + 64), + _row_max_pairs(pM + 128), _row_max_pairs(pM + 192)); + return aie::max(aie::filter_even(p, 1), aie::filter_odd(p, 1)); +} + +void calculate_c(bf16* c, bf16* prev_m_local, bf16* new_m_local) { + // correct = exp(m_left - max), all lq rows in one pass + aie::vector prev_m_vec = aie::load_v(prev_m_local); + aie::vector new_m_vec = aie::load_v(new_m_local); + aie::vector inner_correct = aie::sub(prev_m_vec, new_m_vec); + aie::accum correct_acc = aie::mul(inner_correct, exp_scale); + aie::store_v(c, aie::exp2(correct_acc.template to_vector())); +} + +void calculate_l(bf16* l, bf16*__restrict c, bf16*__restrict pS) { + // calculate l + using MMUL = aie::mmul<8, 8, 8, bf16, bf16, accauto>; + + // calculte l = correct * l_left + sum(f) + aie::vector Ones = aie::broadcast(1.0f); + aie::vector acc_C0 = aie::zeros(); + aie::vector acc_C1 = aie::zeros(); + MMUL C0(acc_C0); + MMUL C1(acc_C1); + + for (int b = 0; b < 8; b++){ + bf16 *pS1 = pS + b * 256; + aie::vector S0 = aie::load_v<64>(pS1); + aie::vector S1 = aie::load_v<64>(pS1 + 64); + aie::vector S2 = aie::load_v<64>(pS1 + 128); + aie::vector S3 = aie::load_v<64>(pS1 + 192); + + C0.mac(S0, Ones); + C1.mac(S2, Ones); + + C0.mac(S1, Ones); + C1.mac(S3, Ones); + } + + auto sum0 = aie::filter_even(C0.template to_vector(), 4); + auto sum00 = aie::filter_even(sum0, 2); + auto sum01 = aie::filter_even(sum00, 1); + auto sum1 = aie::filter_even(C1.template to_vector(), 4); + auto sum10 = aie::filter_even(sum1, 2); + auto sum11 = aie::filter_even(sum10, 1); + auto sum2 = aie::concat(sum01, sum11); + aie::accum sum; + sum.from_vector(sum2); + + aie::vector c_float32 = aie::load_v<16>(c); + aie::vector l_float32 = aie::load_v<16>(l); + + aie::vector l_out; + l_out = aie::mac(sum, l_float32, c_float32); + aie::store_v(l, l_out); +} + +void calculate_y(float* y, bf16* c) { + // calculate y + for (int i = 0; i < lq / 8; i++) { + // whole 8-row group unscaled -> nothing to do + if (aie::equal(aie::load_v<8>(c + i * 8), (bf16)1.0f)) + continue; + + aie::vector c0 = aie::broadcast((bf16)c[i * 8]); + aie::vector c1 = aie::broadcast((bf16)c[i * 8 + 1]); + aie::vector c2 = aie::broadcast((bf16)c[i * 8 + 2]); + aie::vector c3 = aie::broadcast((bf16)c[i * 8 + 3]); + aie::vector c4 = aie::broadcast((bf16)c[i * 8 + 4]); + aie::vector c5 = aie::broadcast((bf16)c[i * 8 + 5]); + aie::vector c6 = aie::broadcast((bf16)c[i * 8 + 6]); + aie::vector c7 = aie::broadcast((bf16)c[i * 8 + 7]); + aie::vector CORRECT = aie::concat(c0, c1, c2, c3, c4, c5, c6, c7); + + // two 8x8 blocks per iteration: the hi/lo split is a long serial chain, + // so a second independent copy fills the latency slots + float* pY = y + i * 8 * dh; + for (unsigned j = 0; j < dh / 16; j += 1) + chess_prepare_for_pipelining chess_loop_range(8, 8) { + aie::accum A_acc, B_acc; + A_acc.from_vector(aie::load_v<64>(pY)); + B_acc.from_vector(aie::load_v<64>(pY + 64)); + aie::vector A_hi = A_acc.template to_vector(); + aie::vector B_hi = B_acc.template to_vector(); + aie::vector A_lo = aie::sub(A_acc, A_hi).template to_vector(); + aie::vector B_lo = aie::sub(B_acc, B_hi).template to_vector(); + aie::accum A_out = aie::mul(A_hi, CORRECT); + aie::accum B_out = aie::mul(B_hi, CORRECT); + A_out = aie::mac(A_out, A_lo, CORRECT); + B_out = aie::mac(B_out, B_lo, CORRECT); + aie::store_v(pY, A_out.template to_vector()); + aie::store_v(pY + 64, B_out.template to_vector()); + pY += 128; + } + } +} + +template +void _attn_fv(T_out *__restrict pY, T_in *__restrict pS, T_in *__restrict pV) { + using MMUL = aie::mmul; + + // load S and reorder s from 16 x 16 to 8 x 8 x 4 + aie::vector S0 = aie::load_v<64>(pS); + aie::vector S1 = aie::load_v<64>(pS + 64); + aie::vector S2 = aie::load_v<64>(pS + 128); + aie::vector S3 = aie::load_v<64>(pS + 192); + + T_out *__restrict pY1 = pY; + T_out *__restrict pY2 = pY + colB * MMUL::size_C; + + for (unsigned j = 0; j < colB; j += 2) + { + T_in *__restrict pV1 = pV + j * MMUL::size_B * colA; + T_in *__restrict pV2 = pV + (j + 1) * MMUL::size_B * colA; + + aie::vector V0 = aie::load_v(pV1); + pV1 += MMUL::size_B; + aie::vector V1 = aie::load_v(pV2); + pV2 += MMUL::size_B; + + aie::vector acc_Y00 = aie::load_v(pY1); + aie::vector acc_Y01 = aie::load_v(pY1 + MMUL::size_C); + aie::vector acc_Y10 = aie::load_v(pY2); + aie::vector acc_Y11 = aie::load_v(pY2 + MMUL::size_C); + + MMUL Y00(acc_Y00); + MMUL Y01(acc_Y01); + MMUL Y10(acc_Y10); + MMUL Y11(acc_Y11); + + Y00.mac(S0, V0); + Y01.mac(S0, V1); + Y10.mac(S2, V0); + Y11.mac(S2, V1); + + V0 = aie::load_v(pV1); + pV1 += MMUL::size_B; + V1 = aie::load_v(pV2); + pV2 += MMUL::size_B; + + Y00.mac(S1, V0); + Y01.mac(S1, V1); + Y10.mac(S3, V0); + Y11.mac(S3, V1); + + aie::store_v(pY1, Y00.template to_vector()); + pY1 += MMUL::size_C; + aie::store_v(pY1, Y01.template to_vector()); + pY1 += MMUL::size_C; + aie::store_v(pY2, Y10.template to_vector()); + pY2 += MMUL::size_C; + aie::store_v(pY2, Y11.template to_vector()); + pY2 += MMUL::size_C; + } +} + +template +void _attn_qk(T_out *__restrict pS, T_in *__restrict pQ, T_in *__restrict pK, + T_out *__restrict pM, int l_base, int q_base, int k_base) { + using MMUL = aie::mmul; + + // keep S[i][j] iff lo < (j - i) <= hi; (j - i) spans [-15, 15] over the tile + int hi = q_base - k_base; + int lo = l_base - k_base; + if (hi < -15 || lo >= 15) { + // no key in this block is visible to any query: skip the mmul entirely. + // -inf (not zero) so the later exp2(s - m) still turns these into zeros. + const aie::vector neg_inf = aie::broadcast((T_out)(-0x1.FEp127f)); + for (unsigned g = 0; g < rowA * colB; g++) + aie::store_v(pS + g * 64, neg_inf); + return; + } + hi = hi > 64 ? 64 : hi; // clamp so hi/lo + 4*g stay in int16 range + lo = lo < -64 ? -64 : lo; + const aie::vector D = aie::load_v<64>(d_offset); + + for (unsigned z = 0; z < rowA; z += 2){ + T_out *__restrict pS1 = pS + (z * colB + 0) * MMUL::size_C; + T_out *__restrict pS2 = pS + ((z + 1) * colB + 0) * MMUL::size_C; + + for (unsigned j = 0; j < colB; j += 2){ + const T_in *__restrict pQ1 = pQ + (z * colA + 0) * MMUL::size_A; + const T_in *__restrict pQ2 = pQ + ((z + 1) * colA + 0) * MMUL::size_A; + const T_in *__restrict pK1 = pK + (0 * colB + j) * MMUL::size_B; + const T_in *__restrict pK2 = pK + (0 * colB + (j + 1)) * MMUL::size_B; + + aie::vector Q0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + aie::vector Q1 = aie::load_v(pQ2); + pQ2 += MMUL::size_A; + aie::vector K00 = aie::load_v(pK1); + aie::vector K0 = aie::transpose(K00, 8, 8); + pK1 += MMUL::size_B * colB; + aie::vector K01 = aie::load_v(pK2); + aie::vector K1 = aie::transpose(K01, 8, 8); + pK2 += MMUL::size_B * colB; + + aie::vector acc_C00 = aie::zeros(); + aie::vector acc_C01 = aie::zeros(); + aie::vector acc_C10 = aie::zeros(); + aie::vector acc_C11 = aie::zeros(); + + MMUL C00(acc_C00); + MMUL C01(acc_C01); + MMUL C10(acc_C10); + MMUL C11(acc_C11); + + C00.mac(Q0, K0); + C01.mac(Q0, K1); + C10.mac(Q1, K0); + C11.mac(Q1, K1); + + for (unsigned i = 1; i < colA; ++i){ + Q0 = aie::load_v(pQ1); + pQ1 += MMUL::size_A; + Q1 = aie::load_v(pQ2); + pQ2 += MMUL::size_A; + K00 = aie::load_v(pK1); + K0 = aie::transpose(K00, 8, 8); + pK1 += MMUL::size_B * colB; + K01 = aie::load_v(pK2); + K1 = aie::transpose(K01, 8, 8); + pK2 += MMUL::size_B * colB; + + C00.mac(Q0, K0); + C01.mac(Q0, K1); + C10.mac(Q1, K0); + C11.mac(Q1, K1); + } + auto mout0 = aie::interleave_zip(C00.template to_vector(), C01.template to_vector(), 8); + auto mout1 = aie::interleave_zip(C10.template to_vector(), C11.template to_vector(), 8); + + auto mout2 = aie::mul(mout0.first, (T_out)scale).template to_vector(0); + auto mout3 = aie::mul(mout0.second, (T_out)scale).template to_vector(0); + auto mout4 = aie::mul(mout1.first, (T_out)scale).template to_vector(0); + auto mout5 = aie::mul(mout1.second, (T_out)scale).template to_vector(0); + + const int g0 = z * 2; + _qk_mask_max(pS1, pM + (g0 + 0) * 64, D, mout2, hi + 4 * (g0 + 0), lo + 4 * (g0 + 0)); + pS1 += MMUL::size_C; + _qk_mask_max(pS1, pM + (g0 + 1) * 64, D, mout3, hi + 4 * (g0 + 1), lo + 4 * (g0 + 1)); + pS1 += MMUL::size_C; + _qk_mask_max(pS2, pM + (g0 + 2) * 64, D, mout4, hi + 4 * (g0 + 2), lo + 4 * (g0 + 2)); + pS2 += MMUL::size_C; + _qk_mask_max(pS2, pM + (g0 + 3) * 64, D, mout5, hi + 4 * (g0 + 3), lo + 4 * (g0 + 3)); + pS2 += MMUL::size_C; + } + } +} + +void scale_div_aie(bf16* o, bf16 *l, float *y) { + constexpr int vec_factor = 64; + + // organize l + aie::vector L0 = aie::broadcast(l[0]); + aie::vector L1 = aie::broadcast(l[1]); + aie::vector L2 = aie::broadcast(l[2]); + aie::vector L3 = aie::broadcast(l[3]); + aie::vector L4 = aie::broadcast(l[4]); + aie::vector L5 = aie::broadcast(l[5]); + aie::vector L6 = aie::broadcast(l[6]); + aie::vector L7 = aie::broadcast(l[7]); + + auto LL00 = aie::concat(L0, L1, L2, L3, L4, L5, L6, L7); + + aie::vector Y00 = aie::load_v(y); + aie::accum Y00_acc; + Y00_acc.from_vector(Y00); + aie::accum AL00 = aie::mul(Y00_acc.template to_vector(), LL00); + aie::store_v(o, AL00.template to_vector()); +} +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/attn/common.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/attn/common.h new file mode 100644 index 000000000..fd8d67ea7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/attn/common.h @@ -0,0 +1,75 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef COMMON_H +#define COMMON_H + +#include +typedef bfloat16 bf16; + +inline void _lock_acquire(int lock_id){ + acquire_greater_equal(lock_id + 48, 1); +} + +inline void _lock_release(int lock_id){ + release(lock_id + 48, 1); +} + +inline void _left_lock_acquire(int lock_id){ + acquire_greater_equal(lock_id + 16, 1); +} + +inline void _left_lock_release(int lock_id){ + release(lock_id + 16, 1); +} + +inline void _up_lock_acquire(int lock_id){ + acquire_greater_equal(lock_id + 32, 1); +} + +inline void _up_lock_release(int lock_id){ + release(lock_id + 32, 1); +} + +inline void _down_lock_acquire(int lock_id){ + acquire_greater_equal(lock_id, 1); +} + +inline void _down_lock_release(int lock_id){ + release(lock_id, 1); +} + +template +void zero_vectorized(T *__restrict c) { + constexpr int r = 16; // one 256 bit store unit + static_assert((M) % r == 0); + const aie::vector zeros = aie::zeros(); + const T *__restrict c_end = c + M; + for (; c < c_end; c += r) { + aie::store_v(c, zeros); + } +} + + + +template +void passThrough_aie(T_in *restrict in, T_out *restrict out) { + event0(); + const int vec_factor = 64; + + aie::accum c_acc_in; + c_acc_in.from_vector(aie::load_v(in)); + aie::store_v(out, c_acc_in.template to_vector()); + event1(); +} + + + +constexpr int lq = 16; +constexpr int lk = 16; +constexpr int dh = 128; + +const float scale = 0.08838834764831843f; + +constexpr bf16 exp_scale = (bf16)1.4426950408889634f; + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dispatch.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dispatch.h new file mode 100644 index 000000000..b7660450b --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dispatch.h @@ -0,0 +1,78 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +// The overlay's dispatcher, shared by fused_e.cc (rows 2, 4) and fused_o.cc (rows 3, 5). +// +// The host configures the array for one op (see host/overlay_host.hpp), writes +// this core's RTP block, then sets OP_LOCK to 1. The core then runs `calls` +// calls of that op -- exactly what the op's standalone core loop would have run +// in that run -- and comes back here to wait for the next one. +// +// Buffers: every op lays its buffers into the same arena (layout.py); `other` is +// the neighbour's arena of the dequant_mm pair (north for even rows, south for odd). +#pragma once + +static inline void ovl_lock_acquire(int lock_id){ + acquire_greater_equal(lock_id + 48, 1); // the core sees its own locks at id + 48 +} + +template +static inline T* at_byte(bfloat16* arena, int offset){ + return (T*)((char*)arena + offset); +} + +extern "C" { + void fused(bfloat16* arena, bfloat16* other, int32* rtp, int row, int col){ + volatile int32* rtp_v = rtp; + ovl_lock_acquire(OP_LOCK); + const int op = rtp_v[RTP_OP]; + const int calls = rtp_v[RTP_CALLS]; + // After a switch the op's DMA chains start again at their ping BD, + // so the op's own ping / pong flags must too. + const bool switched = rtp_v[RTP_SWITCHED] != 0; + int* rtp_i = (int*)rtp; + + if (op == OP_DQ) { + // dequant_mm keeps its ping / pong flags local: each call starts at ping, + // which is where a switch leaves the DMA chains too. + // w slice 0 lives in the even core, w slice 1 and both cores' converted x + // chunks in the odd one; the q4_k blocks arrive in the even core. + for (int c = 0; c < calls; c++) { +#if DQ_EVEN + dq::dequant_mm_e( + at_byte(arena, CT_DQ_E_Y0), at_byte(arena, CT_DQ_E_Y1), + at_byte(arena, CT_DQ_E_X0), at_byte(arena, CT_DQ_E_X1), + at_byte(arena, CT_DQ_E_QW0), at_byte(arena, CT_DQ_E_QW1), + at_byte(arena, CT_DQ_E_WS), at_byte(other, CT_DQ_O_WS), + at_byte(other, CT_DQ_O_XCE), + at_byte(arena, CT_DQ_E_Y_ACC), + rtp_i + RTP_DQ_K_DIV_K, rtp_i + RTP_DQ_ACT); +#else + dq::dequant_mm_o( + at_byte(arena, CT_DQ_O_Y0), at_byte(arena, CT_DQ_O_Y1), + at_byte(arena, CT_DQ_O_X0), at_byte(arena, CT_DQ_O_X1), + at_byte(other, CT_DQ_E_QW0), at_byte(other, CT_DQ_E_QW1), + at_byte(other, CT_DQ_E_WS), at_byte(arena, CT_DQ_O_WS), + at_byte(arena, CT_DQ_O_XCO), + at_byte(arena, CT_DQ_O_Y_ACC), + rtp_i + RTP_DQ_K_DIV_K, rtp_i + RTP_DQ_ACT); +#endif + } + } else if (op == OP_ATTN) { + if (switched) { + at::is_in_ping = false; + at::is_o_ping = false; + } + for (int c = 0; c < calls; c++) { + at::attn( + at_byte(arena, CT_AT_O0), at_byte(arena, CT_AT_O1), + at_byte(arena, CT_AT_Q), + at_byte(arena, CT_AT_IN0), at_byte(arena, CT_AT_IN1), + at_byte(arena, CT_AT_S), at_byte(arena, CT_AT_M), + at_byte(arena, CT_AT_Y), + rtp_i + RTP_AT_L_BEGIN, rtp_i + RTP_AT_L_CHUNKS, rtp_i + RTP_AT_WINDOW, + row, col & 1); + } + } + } +} diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/aie_kernel_utils.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/aie_kernel_utils.h new file mode 100644 index 000000000..b84a96559 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/aie_kernel_utils.h @@ -0,0 +1,198 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. +// SPDX-License-Identifier: MIT + +#ifndef _AIE_KERNEL_UTILS_ +#define _AIE_KERNEL_UTILS_ + +#include +typedef bfloat16 bf16; + +#if defined(__chess__) +#define AIE_LOOP_UNROLL(x) [[chess::unroll_loop(x)]] +#define AIE_LOOP_UNROLL_FULL [[chess::unroll_loop()]] +#define AIE_LOOP_NO_UNROLL [[chess::no_unroll]] +#define AIE_LOOP_MIN_ITERATION_COUNT(x) [[chess::min_loop_count(x)]] +#define AIE_LOOP_MAX_ITERATION_COUNT(x) [[chess::max_loop_count(x)]] +#define AIE_LOOP_RANGE(a, ...) \ + [[chess::min_loop_count(a)]] __VA_OPT__( \ + [[chess::max_loop_count(__VA_ARGS__)]]) +#define AIE_PREPARE_FOR_PIPELINING [[chess::prepare_for_pipelining]] +#define AIE_NO_PREPARE_FOR_PIPELINING [[chess::no_prepare_for_pipelining]] +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) \ + [[chess::modulo_scheduling_budget_ratio(x)]] +#define AIE_KEEP_SW_LOOP [[chess::keep_sw_loop]] +#define AIE_PEEL_PIPELINED_LOOP(x) [[chess::peel_pipelined_loop(x)]] +#define AIE_KEEP_FREE_FOR_PIPELINING(x) [[chess::keep_free_for_pipelining(x)]] +#define AIE_ALLOCATE(x) [[chess::allocate(x)]] +#define AIE_NO_HW_LOOP [[chess::no_hw_loop]] +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN chess_flatten_loop + +#elif defined(__AIECC__) +#ifndef __STRINGIFY +#define __STRINGIFY(a) #a +#endif +#define AIE_LOOP_UNROLL(x) _Pragma(__STRINGIFY(clang loop unroll_count(x))) +#define AIE_LOOP_UNROLL_FULL _Pragma("clang loop unroll(full)") +#define AIE_LOOP_NO_UNROLL _Pragma("clang loop unroll(disable)") +#define AIE_LOOP_MIN_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop min_iteration_count(x))) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop max_iteration_count(x))) +#define AIE_LOOP_RANGE(a, ...) \ + AIE_LOOP_MIN_ITERATION_COUNT(a) \ + __VA_OPT__(AIE_LOOP_MAX_ITERATION_COUNT(__VA_ARGS__)) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) \ + _Pragma(__STRINGIFY(clang loop pipeline_initiation_interval(x))) +#define AIE_PREPARE_FOR_POSTPIPELINING _Pragma("clang loop pipeline(disable)") +#define AIE_LOOP_FLATTEN + +#else +#define AIE_LOOP_UNROLL(x) +#define AIE_LOOP_UNROLL_FULL +#define AIE_LOOP_NO_UNROLL +#define AIE_LOOP_MIN_ITERATION_COUNT(x) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) +#define AIE_LOOP_RANGE(a, ...) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN +#endif + +// Some lock utilities +/// \brief Acquire a lock with given lock ID on this CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 48, num_locks); +} + +/// \brief Release a lock with given lock ID on this CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 48, num_locks); +} + + +/// \brief Acquire a lock with given lock ID on left CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _left_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 16, num_locks); +} + +/// \brief Release a lock with given lock ID on left CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _left_lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 16, num_locks); +} + +/// \brief Acquire a lock with given lock ID on up CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _up_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 32, num_locks); +} + +/// \brief Release a lock with given lock ID on up CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _up_lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 32, num_locks); +} + +/// \brief Acquire a lock with given lock ID on down CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _down_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id, num_locks); +} + +/// \brief Release a lock with given lock ID on down CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _down_lock_release(int lock_id, int num_locks = 1){ + release(lock_id, num_locks); +} + +template +void zero_vectorized(T *__restrict c) { +#if defined(__chess__) + constexpr int r = 256 / (sizeof(T) * 8); // one 256 bit store unit + static_assert((M) % r == 0); + const aie::vector zeros = aie::zeros(); + const T *__restrict c_end = c + M; + for (; c < c_end; c += r) { + aie::store_v(c, zeros); + } +#else + // Peano left the loop above unpipelined (one store per 3 cycles); 512-bit + // stores unrolled by 4 run at one store per cycle. c must be 64-byte aligned. + constexpr int r = 512 / (sizeof(T) * 8); + static_assert((M) % (4 * r) == 0); + const aie::vector zeros = aie::zeros(); + AIE_LOOP_UNROLL(4) + for (int i = 0; i < M; i += r) { + aie::store_v(c + i, zeros); + } +#endif +} + +template +void _memcpy(uint8* dst, uint8* src){ + static constexpr int vec_size = 256; + for (int i = 0; i < SIZE; i += vec_size){ + aie::vector data = aie::load_v(src + i); + aie::store_v(dst + i, data); + } +} + +// Ping/pong buffer selectors. Peano's loader does not zero .bss, so under Peano +// they live in .data. They are volatile there too: Peano does not treat a lock +// acquire as a memory barrier, so if it can prove two picks give the same buffer +// it reuses the earlier load, even though the DMA has refilled the buffer in between. +#if defined(__chess__) +#define AIE_PING_FLAG bool +#else +#define AIE_PING_FLAG __attribute__((section(".data"))) volatile bool +#endif + +// bf16 8x8x8 mmul with the BFP16 emulation, for Peano. It issues the same +// intrinsic as aie_api's emulated mac but converts B with the accumulator +// constructor rather than a multiply by one, which would take a multiplier slot +// from the macs. The conversion is exact, so results are unchanged. +#if !defined(__chess__) && defined(AIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16) +#include +struct aie_mmul_bf16_888 { + aie::accum acc; + explicit aie_mmul_bf16_888(const aie::vector &c) { acc.from_vector(c); } + __attribute__((always_inline)) void mac(const aie::vector &a, const aie::vector &b) { + aie::accum acc_a(a); + aie::accum acc_b(aie::transpose(b, 8, 8)); + acc = ::mac_8x8_8x8T_conf(::to_v64bfp16ebs8(acc_a), ::to_v64bfp16ebs8(acc_b), acc, 0, 0, 0); + } + template aie::vector to_vector() const { return acc.template to_vector(); } +}; +#endif + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/common.hpp b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/common.hpp new file mode 100644 index 000000000..313f2b334 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/common.hpp @@ -0,0 +1,35 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +///@file typedef.hpp +///@brief Define the typedefs for the kernels +#ifndef __COMMON_HPP__ +#define __COMMON_HPP__ + +#include +#include + +typedef bfloat16 bf16; + +constexpr int QXNX_ROW_BLOCK_SIZE = 32; +constexpr int QXNX_COL_BLOCK_SIZE = 256; +constexpr int GGML_GROUP_SIZE = 32; + +// A packed q4_k column holds the block's whole row span, so the quants are +// column major with PARALLEL_ROWS nibbles per column. +constexpr int PARALLEL_ROWS = QXNX_ROW_BLOCK_SIZE; + +constexpr bfloat16 exp_scale = 1.44269504089; +// The tile of dequant_mm_bfp16_rtm2_glu_512x512x512: every MiniCPM5 matrix has a +// K (Din) that is a multiple of 512 (2048, 4096 and the experts' 512). The host +// shortens a dispatch to m rows per core row (K_div_k[1] = m / 16). +constexpr int NPU_M_TILE = 128; +constexpr int NPU_K_TILE = 512; +constexpr int NPU_N_TILE = 64; +constexpr int m_slice = 16; +constexpr int k_slice = QXNX_COL_BLOCK_SIZE; +constexpr int n_slice = QXNX_ROW_BLOCK_SIZE; +constexpr int y_slice = 256; +constexpr int y_num = NPU_M_TILE * NPU_N_TILE / y_slice; + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/dequant_mm_bfp16.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/dequant_mm_bfp16.h new file mode 100644 index 000000000..469c2cce1 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/dequant_mm_bfp16.h @@ -0,0 +1,189 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#pragma once +#include "aie_kernel_utils.h" +#include "q4_core.h" +#include "lut_based_ops.h" +#include "common.hpp" + +constexpr int x_prod_lock = 0; +constexpr int x_cons_lock = 1; +constexpr int qw_prod_lock = 2; +constexpr int qw_cons_lock = 3; +constexpr int y_prod_lock = 4; +constexpr int y_cons_lock = 5; +constexpr int sync_lock = 6; + +AIE_PING_FLAG is_y_ping = false; +AIE_PING_FLAG is_qw_ping = false; +AIE_PING_FLAG is_x_ping = false; + + +// y_acc layout: [m16 group][m8 row (2)][n8 tile (8)][64]; n slice s owns n8 tiles 4s..4s+3. +// A w slice buffer is two "n pairs" of 4608 B: region[pair][kt (32)][2 n blocks] of 72 B tiles. +// X chunk layout (DMA re-tiled): [k8 (16)][row (16)][k % 8], i.e. x + 128 k holds the A0 (rows 0-7) +// and A1 (rows 8-15) 8x8 tiles of k block k. +static constexpr int W_TILE_BYTES = 72; +static constexpr int W_REGION_BYTES = 32 * 2 * W_TILE_BYTES; // one n pair, all 32 k blocks of a 256 k slice + +static constexpr int XC_BYTES = 16 * 2 * W_TILE_BYTES; // one x chunk (16 rows x 128 k) as bfp16 A tiles +static constexpr int XC2_BYTES = 2 * XC_BYTES; // both chunks of a 256 k slice + +// bf16 x chunk -> bfp16 A tiles, [k8][A0, A1], converted once and then used by all four 2x2 blocks +static inline __attribute__((always_inline)) void +convert_x_chunk(const bf16 *__restrict px, uint8 *__restrict xc) { + aie::block_vector_output_buffer_stream xo((bfp16ebs8 *)xc); + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(16, 16) + for (int k = 0; k < 16; k++) { + auto a0 = ::to_v64bfp16ebs8(aie::accum(aie::load_v<64>(px))); + auto a1 = ::to_v64bfp16ebs8(aie::accum(aie::load_v<64>(px + 64))); + px += 128; + xo << a0; + xo << a1; + } +} + +// 2 m8 x 2 n8 blocks over all 32 k blocks of the 256 k slice (both x chunks converted), both operands +// bfp16: one accumulator load/store per 128 MMULs instead of per 64 +template +static inline __attribute__((always_inline)) void +mm_aie_bfp16(float *__restrict y_group, const uint8 *__restrict xc, const uint8 *__restrict w_slice0, const uint8 *__restrict w_slice1) { + for (int s = 0; s < 2; s++) { + const uint8 *w_slice = s == 0 ? w_slice0 : w_slice1; + for (int pair = 0; pair < 2; pair++) { + float *y0 = y_group + (4 * s + 2 * pair) * 64; // m8 row 0 + float *y1 = y0 + 8 * 64; // m8 row 1 + // FIRST: the first k slice of a call starts from zero instead of a zeroed y_acc (no 32 KB zeroing pass) + aie::accum c00, c01, c10, c11; + if constexpr (FIRST) { + c00 = aie::zeros(); c01 = aie::zeros(); + c10 = aie::zeros(); c11 = aie::zeros(); + } else { + c00 = aie::accum(aie::load_v<64>(y0)); c01 = aie::accum(aie::load_v<64>(y0 + 64)); + c10 = aie::accum(aie::load_v<64>(y1)); c11 = aie::accum(aie::load_v<64>(y1 + 64)); + } + aie::block_vector_input_buffer_stream xs((const bfp16ebs8 *)xc); + aie::block_vector_input_buffer_stream ws((const bfp16ebs8 *)(w_slice + pair * W_REGION_BYTES)); + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(16, 16) + for (int k = 0; k < 16; k++) { +#pragma clang loop unroll(full) + for (int u = 0; u < 2; u++) { + auto a0 = xs.pop(); + auto a1 = xs.pop(); + auto b0 = ws.pop(); + auto b1 = ws.pop(); + c00 = mac_8x8_8x8T(a0, b0, c00); + c01 = mac_8x8_8x8T(a0, b1, c01); + c10 = mac_8x8_8x8T(a1, b0, c10); + c11 = mac_8x8_8x8T(a1, b1, c11); + } + } + aie::store_v(y0, c00.template to_vector()); + aie::store_v(y0 + 64, c01.template to_vector()); + aie::store_v(y1, c10.template to_vector()); + aie::store_v(y1 + 64, c11.template to_vector()); + } + } +} + +void silu_aie(bf16 *__restrict x, bf16 *__restrict o, int D){ + + bf16 *x_it = x; + + constexpr int vector_size = 64; + + aie::vector x_vec; + aie::vector o_vec; + + const int F = D / vector_size; + + for (int i = 0; i < F; i++){ + x_vec = aie::load_v(x_it); + o_vec = getSiluBf16_nonLUT(x_vec); + aie::store_v(o, o_vec); + x_it += vector_size; + o += vector_size; + } +} + +void gelu_aie(bf16 *__restrict x, bf16 *__restrict o, int D){ + + bf16 *x_it = x; + + constexpr int vector_size = 64; + + aie::vector x_vec; + aie::vector o_vec; + + const int F = D / vector_size; + + for (int i = 0; i < F; i++){ + x_vec = aie::load_v(x_it); + o_vec = getGeluBf16_nonLUT(x_vec); + aie::store_v(o, o_vec); + x_it += vector_size; + o += vector_size; + } +} + +// GLU epilogue (rtp_activate == 3): the two n slices of a core hold the up channels (slice 0, n8 tiles 0-3) and +// the matching gate channels (slice 1, n8 tiles 4-7) of the same 32 hidden channels, so one m8 row group of +// y_acc ([8 n8 tiles][64]) yields one 256-element output chunk: silu(gate) * up on 4 tiles. +// sigmoid(g) = (g < 0 ? e : 1) / (1 + e), e = 2^(-|g| log2(e)) <= 1, so no 1 + tanh(g / 2) cancellation for g < 0 +// (the vector unit's tanh is also ~2 % off). 1 / (1 + e) by two Newton steps from 16/17 - 8/17 e (|error| <= 1/17 +// on [1, 2]), each r += r (1 - r (1 + e)) with the correction in fp32 accumulators: only r's own bf16 rounding is +// left. The caller rounds to nearest even (see dequant_mm_e.cc). +static inline __attribute__((always_inline)) void +glu_chunk_aie(const float *__restrict acc, bf16 *__restrict out) { + constexpr int V = 64; + using vbf = aie::vector; + using vacc = aie::accum; + const vbf zero = aie::zeros(); + const vbf one = aie::broadcast(1.0f); + // log2(e) = hi + lo, both bf16, for an fp32-exact exponent; -|g| log2(e) = g (-/+ log2(e)) (no bf16 negate + // in the backend) + const vbf log2e_hi_p = aie::broadcast(1.4453125f), log2e_hi_n = aie::broadcast(-1.4453125f); + const vbf log2e_lo_p = aie::broadcast(-0.00261746f), log2e_lo_n = aie::broadcast(0.00261746f); + const vbf r0_slope = aie::broadcast(-8.0f / 17.0f); + vacc r0_base, ones; + r0_base.from_vector(aie::broadcast(16.0f / 17.0f)); + ones.from_vector(aie::broadcast(1.0f)); + for (int t = 0; t < 4; t++) { + vacc au, ag; + au.from_vector(aie::load_v(acc + t * V)); + ag.from_vector(aie::load_v(acc + (t + 4) * V)); + const vbf up = au.template to_vector(); + const vbf gate = ag.template to_vector(); + const auto neg = aie::lt(gate, zero); + const vbf c_hi = aie::select(log2e_hi_n, log2e_hi_p, neg); + const vbf c_lo = aie::select(log2e_lo_n, log2e_lo_p, neg); + const vacc x = aie::mac(aie::mul(gate, c_hi), gate, c_lo); + const vbf e = aie::exp2(x.template to_vector()); + vbf r = aie::mac(r0_base, e, r0_slope).template to_vector(); + for (int it = 0; it < 2; it++) { + // d = 1 - r - e r, then r + r d + const vbf d = aie::msc(aie::msc(ones, r, one), e, r).template to_vector(); + vacc rr; + rr.from_vector(r); + r = aie::mac(rr, r, d).template to_vector(); + } + const vbf num = aie::select(one, e, neg); + const vbf sig = aie::mul(num, r).template to_vector(); + const vbf ug = aie::mul(up, gate).template to_vector(); + aie::store_v(out + t * V, aie::mul(ug, sig).template to_vector()); + } +} + +template +void passThrough_aie(const T_in *restrict in, T_out *restrict out) { + const int vec_factor = 64; + for (int c = 0; c < y_slice; c += vec_factor) { + aie::accum c_acc_in; + c_acc_in.from_vector(aie::load_v(in + c)); + aie::store_v(out + c, c_acc_in.template to_vector()); + } +} + diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/dequant_mm_e.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/dequant_mm_e.cc new file mode 100644 index 000000000..729645283 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/dequant_mm_e.cc @@ -0,0 +1,115 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "dequant_mm_bfp16.h" + +extern "C" { + + void dequant_mm_e( + bf16 * y_ping, + bf16 * y_pong, + bf16 * x_ping, + bf16 * x_pong, + uint8 * qw_ping, + uint8 * qw_pong, + uint8 * w_s0, + uint8 * w_s1, + uint8 * xc, + float * y_acc, + int * K_div_k, + int * rtp_activate + ) { + // Both cores of a row pair dequantise their n pair of BOTH n slices of the + // k slice into bfp16 tiles (slice 0 in the even tile, slice 1 in the odd + // tile), rendezvous, then each multiplies its own 128 x rows against the 64 n + // of both slices: every x chunk is streamed once per k slice, not once per + // n slice. + // Rows per core row of this dispatch, in m_slice (16-row) groups: RTP word 1. The host sequence + // writes it (and rewrites the memtile BD lengths to match) while this core is already in its next + // call, parked on the first weight tile, so it is read only once the weights of the dispatch have + // arrived (below). Unwritten / out of range = the full block. + // every conversion of this call (Q4_K scale/min and weight narrowing, the weight and x bfp16 conversion, the + // y narrowing) rounds to nearest even: the design's default mode, floor, biases each of them downwards. + // The mode is put back before the call returns, as the GLU epilogue below already did for itself. + const aie::rounding_mode kernel_rnd = aie::swap_rounding(aie::rounding_mode::conv_even); + int m_div_m_slice = NPU_M_TILE / m_slice; + // ping/pong parity: every call toggles each flag an even number of times, so it is `false` at every call + // start; local flags stay in registers (the global byte flags cost ~30 cycles per toggle) + bool is_qw_ping = false, is_x_ping = false, is_y_ping = false; + int k_div_k_slice = NPU_K_TILE / k_slice; + + int k = 0; + do { + for (int j = 0; j < k_div_k_slice; j++){ + for (int p = 0; p < 2; p++){ + _lock_acquire(qw_cons_lock, 1); + is_qw_ping = !is_qw_ping; + uint8* qw_using = is_qw_ping ? qw_ping : qw_pong; + uint8* w_slice = p == 0 ? w_s0 : w_s1; + _Q4_K_bfp16_relaid((bfp16ebs8*)(w_slice + 0 * W_REGION_BYTES), qw_using, 0); + _lock_release(qw_prod_lock, 1); + } + + // Barrier A: both halves of both w slices are written. + _up_lock_release(sync_lock, 1); + _lock_acquire(sync_lock, 1); + + { + int mr = ((volatile int *)K_div_k)[1]; + m_div_m_slice = ((unsigned)(mr - 1) < (unsigned)(NPU_M_TILE / m_slice)) ? mr : NPU_M_TILE / m_slice; + } + for (int i = 0; i < m_div_m_slice; i++){ + // the two 128 k chunks of this m16 group arrive back to back; each DMA buffer is + // released as soon as it is converted, so the next chunk streams in during the multiply + for (int v = 0; v < 2; v++){ + _lock_acquire(x_cons_lock); + is_x_ping = !is_x_ping; + const bf16 *x = is_x_ping ? x_ping : x_pong; + convert_x_chunk(x, xc + v * XC_BYTES); + _lock_release(x_prod_lock); + } + if (k == 0 && j == 0) mm_aie_bfp16(y_acc + i * m_slice * NPU_N_TILE, xc, w_s0, w_s1); + else mm_aie_bfp16(y_acc + i * m_slice * NPU_N_TILE, xc, w_s0, w_s1); + } + // Barrier B: neither core reads the w slices any more. + _up_lock_release(sync_lock, 1); + _lock_acquire(sync_lock, 1); + } + k += 1; + } while (k < K_div_k[0]); + int use_activation = rtp_activate[0]; + if (use_activation == 3){ + // one chunk per m8 row group: [up | gate] n8 tiles in, 4 fused n8 tiles out + const int glu_rt = m_div_m_slice * 2; + // every narrowing below rounds to nearest even (the design's default, floor, biases a chain of six + // roundings by about -1%); the mode is put back for the next dispatch's x conversion / y narrowing + const aie::rounding_mode old_rnd = aie::swap_rounding(aie::rounding_mode::conv_even); + for (int i = 0; i < glu_rt; i++){ + _lock_acquire(y_prod_lock); + is_y_ping = !is_y_ping; + bf16 *y = is_y_ping ? y_ping : y_pong; + glu_chunk_aie(y_acc + i * (8 * 64), y); + _lock_release(y_cons_lock); + } + aie::set_rounding(old_rnd); + aie::set_rounding(kernel_rnd); + return; + } + const int y_num_rt = m_div_m_slice * (m_slice * NPU_N_TILE / y_slice); + for (int i = 0; i < y_num_rt; i++){ + _lock_acquire(y_prod_lock); + is_y_ping = !is_y_ping; + bf16 *y = is_y_ping ? y_ping : y_pong; + + passThrough_aie(y_acc + i * y_slice, y); + if (use_activation == 1){ + silu_aie(y, y, y_slice); + } + else if (use_activation == 2){ + gelu_aie(y, y, y_slice); + } + _lock_release(y_cons_lock); + } + aie::set_rounding(kernel_rnd); + } +} \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/dequant_mm_o.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/dequant_mm_o.cc new file mode 100644 index 000000000..7c876870b --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/dequant_mm_o.cc @@ -0,0 +1,115 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "dequant_mm_bfp16.h" + +extern "C" { + + void dequant_mm_o( + bf16 * y_ping, + bf16 * y_pong, + bf16 * x_ping, + bf16 * x_pong, + uint8 * qw_ping, + uint8 * qw_pong, + uint8 * w_s0, + uint8 * w_s1, + uint8 * xc, + float * y_acc, + int * K_div_k, + int * rtp_activate + ) { + // Both cores of a row pair dequantise their n pair of BOTH n slices of the + // k slice into bfp16 tiles (slice 0 in the even tile, slice 1 in the odd + // tile), rendezvous, then each multiplies its own 128 x rows against the 64 n + // of both slices: every x chunk is streamed once per k slice, not once per + // n slice. + // Rows per core row of this dispatch, in m_slice (16-row) groups: RTP word 1. The host sequence + // writes it (and rewrites the memtile BD lengths to match) while this core is already in its next + // call, parked on the first weight tile, so it is read only once the weights of the dispatch have + // arrived (below). Unwritten / out of range = the full block. + // every conversion of this call (Q4_K scale/min and weight narrowing, the weight and x bfp16 conversion, the + // y narrowing) rounds to nearest even: the design's default mode, floor, biases each of them downwards. + // The mode is put back before the call returns, as the GLU epilogue below already did for itself. + const aie::rounding_mode kernel_rnd = aie::swap_rounding(aie::rounding_mode::conv_even); + int m_div_m_slice = NPU_M_TILE / m_slice; + // ping/pong parity: every call toggles each flag an even number of times, so it is `false` at every call + // start; local flags stay in registers (the global byte flags cost ~30 cycles per toggle) + bool is_qw_ping = false, is_x_ping = false, is_y_ping = false; + int k_div_k_slice = NPU_K_TILE / k_slice; + + int k = 0; + do { + for (int j = 0; j < k_div_k_slice; j++){ + for (int p = 0; p < 2; p++){ + _down_lock_acquire(qw_cons_lock, 1); + is_qw_ping = !is_qw_ping; + uint8* qw_using = is_qw_ping ? qw_ping : qw_pong; + uint8* w_slice = p == 0 ? w_s0 : w_s1; + _Q4_K_bfp16_relaid((bfp16ebs8*)(w_slice + 1 * W_REGION_BYTES), qw_using, 16); + _down_lock_release(qw_prod_lock, 1); + } + + // Barrier A: both halves of both w slices are written. + _down_lock_release(sync_lock, 1); + _lock_acquire(sync_lock, 1); + + { + int mr = ((volatile int *)K_div_k)[1]; + m_div_m_slice = ((unsigned)(mr - 1) < (unsigned)(NPU_M_TILE / m_slice)) ? mr : NPU_M_TILE / m_slice; + } + for (int i = 0; i < m_div_m_slice; i++){ + // the two 128 k chunks of this m16 group arrive back to back; each DMA buffer is + // released as soon as it is converted, so the next chunk streams in during the multiply + for (int v = 0; v < 2; v++){ + _lock_acquire(x_cons_lock); + is_x_ping = !is_x_ping; + const bf16 *x = is_x_ping ? x_ping : x_pong; + convert_x_chunk(x, xc + v * XC_BYTES); + _lock_release(x_prod_lock); + } + if (k == 0 && j == 0) mm_aie_bfp16(y_acc + i * m_slice * NPU_N_TILE, xc, w_s0, w_s1); + else mm_aie_bfp16(y_acc + i * m_slice * NPU_N_TILE, xc, w_s0, w_s1); + } + // Barrier B: neither core reads the w slices any more. + _down_lock_release(sync_lock, 1); + _lock_acquire(sync_lock, 1); + } + k += 1; + } while (k < K_div_k[0]); + int use_activation = rtp_activate[0]; + if (use_activation == 3){ + // one chunk per m8 row group: [up | gate] n8 tiles in, 4 fused n8 tiles out + const int glu_rt = m_div_m_slice * 2; + // every narrowing below rounds to nearest even (the design's default, floor, biases a chain of six + // roundings by about -1%); the mode is put back for the next dispatch's x conversion / y narrowing + const aie::rounding_mode old_rnd = aie::swap_rounding(aie::rounding_mode::conv_even); + for (int i = 0; i < glu_rt; i++){ + _lock_acquire(y_prod_lock); + is_y_ping = !is_y_ping; + bf16 *y = is_y_ping ? y_ping : y_pong; + glu_chunk_aie(y_acc + i * (8 * 64), y); + _lock_release(y_cons_lock); + } + aie::set_rounding(old_rnd); + aie::set_rounding(kernel_rnd); + return; + } + const int y_num_rt = m_div_m_slice * (m_slice * NPU_N_TILE / y_slice); + for (int i = 0; i < y_num_rt; i++){ + _lock_acquire(y_prod_lock); + is_y_ping = !is_y_ping; + bf16 *y = is_y_ping ? y_ping : y_pong; + + passThrough_aie(y_acc + i * y_slice, y); + if (use_activation == 1){ + silu_aie(y, y, y_slice); + } + else if (use_activation == 2){ + gelu_aie(y, y, y_slice); + } + _lock_release(y_cons_lock); + } + aie::set_rounding(kernel_rnd); + } +} \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/lut_based_ops.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/lut_based_ops.h new file mode 100644 index 000000000..c01d5603c --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/lut_based_ops.h @@ -0,0 +1,75 @@ +//===--- exp_lut.h - get exponential values from loopup tables ---===// +// +// This file is licensed under the Apache License v2.0 with LLVM Exceptions +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// +// +//===----------------------------------------------------------------------===// +// This is the implementation of getting exponential values for a bfloat16 +// vector from exponential lookup tables. +//===----------------------------------------------------------------------===// +#ifndef __LUT_BASED_OPS_H__ +#define __LUT_BASED_OPS_H__ + +#include "aie_api/aie.hpp" + + +// The tables _ab and _cd are copies of each other +// Also, each table has a copy of data seperated by 256-bit +// This effectively creates 4 copies of the table (located in 4 (256-bit) banks) +// This allows the user to use the "gather" read feature and read 4 values from +// 4 different banks at once Tables entries are in BF16 +// +template +__attribute__((always_inline)) aie::vector getSiluBf16_nonLUT(aie::vector x){ + const bfloat16 half = 0.5f; + const bfloat16 one = 1.0f; + aie::vector v_half = aie::broadcast(half); + aie::vector v_one = aie::broadcast(one); + aie::accum x_mul_half = aie::mul(x, v_half); + aie::vector tanh_x_half = aie::tanh(x_mul_half.template to_vector()); + + aie::vector tanh_x_half_plus_one = aie::add(tanh_x_half, v_one); + aie::vector tanh_x_half_plus_one_div_2 = aie::mul(tanh_x_half_plus_one, v_half).template to_vector(); + + aie::vector res = aie::mul(x, tanh_x_half_plus_one_div_2).template to_vector(); + return res; +} +template +__attribute__((always_inline)) aie::vector getGeluBf16_nonLUT(aie::vector x) { + // Constants + const bfloat16 k0_5 = 0.5f; + const bfloat16 k1 = 1.0f; + const bfloat16 sqrt_2_over_pi = 0.79788456f; // β‰ˆ sqrt(2/Ο€) + const bfloat16 kBeta = 0.044715f; + + auto v05 = aie::broadcast(k0_5); + auto v1 = aie::broadcast(k1); + auto vs2opi = aie::broadcast(sqrt_2_over_pi); + auto vBeta = aie::broadcast(kBeta); + + + // Compute x^3 + aie::vector x2 = aie::mul(x, x).template to_vector(); // x^2 + aie::vector x3 = aie::mul(x, x2).template to_vector(); // x^3 + + // inner = sqrt(2/pi) * (x + 0.044715 * x^3) + aie::vector x3_beta = aie::mul(x3, vBeta).template to_vector(); + aie::vector inner = aie::add(x, x3_beta); + auto inner1 = aie::mul(inner, vs2opi); + + // tanh_out = tanh(inner) + auto tanh_out = aie::tanh(inner1.template to_vector()); + + // result = 0.5 * x * (1 + tanh_out) + aie::vector one_plus_tanh = aie::add(tanh_out, v1); + // Multiply by x and 0.5 + aie::vector mul_v05 = aie::mul(v05, one_plus_tanh).template to_vector(); + auto result = aie::mul(x, mul_v05); + return result.template to_vector(); +} + +#endif //__LUT_BASED_OPS_H__ \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/q4_core.h b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/q4_core.h new file mode 100644 index 000000000..6e2371bd8 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/dq/q4_core.h @@ -0,0 +1,196 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __Q4_CORE_H__ +#define __Q4_CORE_H__ +#include "aie_kernel_utils.h" +#include "common.hpp" + +/// bf16 has an 8 bit exponent and a 7 bit mantissa, so the [128, 256) binade has +/// an ulp of exactly 1: the bit pattern 0x4300 | v *is* the number 128 + v, for +/// every v in [0, 15]. A uint4 -> bf16 conversion is therefore just byte +/// placement -- unpack the nibbles to bytes and zip 0x43 in as the high byte -- +/// instead of aie::to_float's convert chain through the accumulator files. The +/// weights come out biased by 128, which the caller pays back for free. +static constexpr uint8 Q4_BIASED_EXP_BYTE = 0x43; +static constexpr int NIBBLE_BIAS = 128; + +template +static inline __attribute__((always_inline)) aie::vector _q4_biased_bf16( + aie::vector nibble_bytes, + aie::vector bias_bytes +) { + // little endian: low byte is the nibble, high byte the 0x43 exponent field + return aie::vector_cast( + aie::concat(aie::interleave_zip(nibble_bytes, bias_bytes, 1))); +} + +/// @brief Dequantize one *relaid* Q4_K weight block into bfp16 mmul B tiles (transposed, ready to multiply). +/// +/// Format (see FLM_Q4NX_Converter/quant.md): a super-block is 256 weights of one +/// row -- here exactly one block row -- split into 8 groups of GGML_GROUP_SIZE. +/// Per group it stores a uint8 scale s' and a uint8 min m'; per super-block a +/// bf16 S' and a bf16 M'. The converter stores M' already negated, so the +/// dequantized weight is +/// +/// w = S' s'_j q + M' m'_j +/// +/// The prefill reads the decode weight buffers in place (no second copy), and +/// the MiniCPM5 engine relays every projection block for its decode kernel +/// (`q4k_relayout_for_mmul`, FLM_DLL/detail/minicpm5_moe_npu/minicpm5_moe_model_def.cpp): +/// +/// qs [k step 16][t 2][16 columns][CORE_ROWS / 2 bytes] column = 16 k + c +/// scales [h 2][t 2][a 4][CORE_ROWS] group = 4 h + a +/// mins, S, M not moved +/// +/// with t selecting rows CORE_ROWS t .. CORE_ROWS t + CORE_ROWS - 1: exactly one +/// core's share of the block, so core `row` reads only its own t and a single +/// 512 bit load is MM_BLK columns x CORE_ROWS rows, both of the core's n blocks. +/// +/// The output is what ../../../dequant_mm_bfp16_rtm2_glu_512x512x512/kernel/q4_core.h +/// (_Q4_K_bfp16, the plain-order reader) writes, tile for tile and with the same +/// rounding chain (bf16 round, 8x8 transpose, bfp16 conversion): +/// region[kt * 2 + (0: rows row..row+7, 1: rows row+8..row+15)], each the 8 n x 8 k +/// block transposed (n major), the operand layout of mac_8x8_8x8T. +/// +/// @param w_region bfp16 output tiles of this core's n pair +/// @param qw_buffer the packed block, relaid +/// @param row first row this core owns (0 or CORE_ROWS); it writes CORE_ROWS of them +void _Q4_K_bfp16_relaid( + bfp16ebs8* w_region, + uint8* qw_buffer, + int row +) { + static constexpr int GROUPS_PER_ROW = QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE; + static constexpr int SCALES_BYTES = QXNX_ROW_BLOCK_SIZE * GROUPS_PER_ROW; + static constexpr int MINS_BYTES = SCALES_BYTES; + static constexpr int QS_BYTES = QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE / 2; + + // the row pair splits the block in half, so a core owns this many rows + static constexpr int CORE_ROWS = QXNX_ROW_BLOCK_SIZE / 2; + // aie::mmul<8, 8, 8> B tile: 8 k rows x 8 n columns, n fastest + static constexpr int MM_BLK = 8; + static constexpr int LANES = MM_BLK * MM_BLK; + // one 512 bit load is 128 nibbles = MM_BLK columns of one core's CORE_ROWS + static constexpr int NIBBLES_PER_LOAD = 128; + // a relaid qs chunk: COLS_PER_CHUNK columns of one t, CORE_ROWS rows each + static constexpr int CHUNK_COL_BYTES = CORE_ROWS / 2; + static constexpr int COLS_PER_CHUNK = 16; + static constexpr int CHUNK_BYTES = COLS_PER_CHUNK * CHUNK_COL_BYTES; + static constexpr int LOADS_PER_CHUNK = COLS_PER_CHUNK / MM_BLK; + static constexpr int CHUNKS_PER_GROUP = GGML_GROUP_SIZE / COLS_PER_CHUNK; + + // a block is exactly one super-block, so there is one S'/M' per row + static_assert(QXNX_COL_BLOCK_SIZE == 256); + static_assert(PARALLEL_ROWS == QXNX_ROW_BLOCK_SIZE); + // one load must be whole columns of this core's half, and a whole tile pair + static_assert(NIBBLES_PER_LOAD == MM_BLK * CORE_ROWS); + static_assert(CORE_ROWS == 2 * MM_BLK); + static_assert(LOADS_PER_CHUNK == 2); + static_assert(CHUNKS_PER_GROUP == 2); + + uint8* it_min = qw_buffer + SCALES_BYTES; + bf16* p_S = (bf16*)(qw_buffer + SCALES_BYTES + MINS_BYTES + QS_BYTES); + bf16* p_M = p_S + QXNX_ROW_BLOCK_SIZE; + + // this core's half of the block: t = 0 reads rows 0..CORE_ROWS-1, t = 1 the + // rest. Our chunks are every other one, so the walk below steps over the + // partner core's chunk after each of ours. + const int t = row / CORE_ROWS; + uint8* it_scale = qw_buffer + t * (CORE_ROWS * GROUPS_PER_ROW / 2); + uint4* it_quant = (uint4*)(qw_buffer + SCALES_BYTES + MINS_BYTES + t * CHUNK_BYTES); + + aie::vector a_S = aie::load_v(p_S + row); + aie::vector a_M = aie::load_v(p_M + row); + + aie::block_vector_output_buffer_stream w_out(w_region); + + const aie::vector bias_bytes = + aie::broadcast(Q4_BIASED_EXP_BYTE); + + // One aligned load = MM_BLK columns x CORE_ROWS rows, column major. A + // single unzip of MM_BLK-element groups splits it by row into this core's + // two n blocks, each a [k % 8][n % 8] tile (the plain reader's lo / hi). + // The unzip is an element permutation, so run it in the byte domain and + // widen to bf16 only at the end. + auto load_tile_pair = [&]() { + aie::vector q_raw = aie::load_v(it_quant); + it_quant += NIBBLES_PER_LOAD / 2; // uint4* steps two nibbles + + aie::vector q_bytes = aie::unpack(q_raw); + auto blks = aie::interleave_unzip(q_bytes.template extract(0), + q_bytes.template extract(1), + MM_BLK); + return std::make_pair(_q4_biased_bf16(blks.first, bias_bytes), + _q4_biased_bf16(blks.second, bias_bytes)); + }; + + for (int sub_chunk = 0; sub_chunk < GROUPS_PER_ROW; sub_chunk++) { + // group g = 4 h + a sits at [h][t][a], and this core's t is fixed, so + // h = g / 4 steps by (2 halves x 4 x CORE_ROWS) and a = g % 4 by CORE_ROWS + const int h = sub_chunk / 4, a = sub_chunk % 4; + const int scale_off = (h * 2 * 4 + a) * CORE_ROWS; + // uint8 -> bf16 is exact for every value up to 255 + aie::accum s_acc; + s_acc.from_vector(aie::to_float( + aie::load_v(it_scale + scale_off), 0)); + // the mins were not relaid: still [group][row], plain + aie::accum m_acc; + m_acc.from_vector(aie::to_float( + aie::load_v(it_min + sub_chunk * QXNX_ROW_BLOCK_SIZE + row), 0)); + + // the effective per-group scale and min: S' s'_j and M' m'_j + aie::vector a_scales = + aie::mul(s_acc.template to_vector(), a_S).template to_vector(); + aie::vector a_mins = + aie::mul(m_acc.template to_vector(), a_M).template to_vector(); + + // lane n of a tile is row (row + n % 8), so each half of the metadata is + // splatted MM_BLK times across the tile + auto splat_rows = [](aie::vector v) { + aie::vector v32 = aie::concat(v, v); + aie::vector v64 = aie::concat(v32, v32); + return aie::interleave_unzip(v64, v64, MM_BLK); + }; + auto scale_vec = splat_rows(a_scales); + + auto min = splat_rows(a_mins); + aie::accum base_lo; + aie::accum base_hi; + base_lo.from_vector(min.first); + base_hi.from_vector(min.second); + // the MAC operand is 128 + q, so every lane carries an extra + // 128 S' s'_j; subtract it once per group, out of the tile loop. Both + // operands are bf16 exact and 128 is a power of two, so this is exact. + base_lo = aie::msc(base_lo, scale_vec.first, bfloat16(NIBBLE_BIAS)); + base_hi = aie::msc(base_hi, scale_vec.second, bfloat16(NIBBLE_BIAS)); + const aie::vector& scale_lo = scale_vec.first; + const aie::vector& scale_hi = scale_vec.second; + + auto emit = [&](const aie::accum& base, aie::vector q, + const aie::vector& scale) { + // w = S' s'_j (128 + q) + (M' m'_j - 128 S' s'_j), to bf16, transposed, to bfp16 + aie::vector w = aie::mac(base, q, scale).template to_vector(); + w_out << ::to_v64bfp16ebs8(aie::accum(aie::transpose(w, 8, 8))); + }; + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE( CHUNKS_PER_GROUP, CHUNKS_PER_GROUP ) + for (int chunk = 0; chunk < CHUNKS_PER_GROUP; chunk++) { + // columns 0..7 (k block 2 chunk), then 8..15 (k block 2 chunk + 1); + // per k block the low n block, then the high one + auto qa = load_tile_pair(); + auto qb = load_tile_pair(); + emit(base_lo, qa.first, scale_lo); + emit(base_hi, qa.second, scale_hi); + emit(base_lo, qb.first, scale_lo); + emit(base_hi, qb.second, scale_hi); + + // step over the partner core's chunk of the same 16 columns + // (a uint4* unit is two nibbles, so one unit is one byte) + it_quant += CHUNK_BYTES; + } + } // end of sub_chunk +} + +#endif // __Q4_CORE_H__ diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/fused_e.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/fused_e.cc new file mode 100644 index 000000000..cf7f9b571 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/fused_e.cc @@ -0,0 +1,24 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +// Overlay core program for the even core rows (2, 4): dequant_mm_e + attention. +// +// Trick: both kernel sources go into one object, each inside its own namespace, +// so their same-named helpers (_lock_acquire, passThrough_aie, zero_vectorized, +// the ping / pong globals, ...) don't clash. System headers come first: their +// include guards then keep them out of the namespaces. +#include +#include +#include +#include "overlay_layout.h" + +namespace dq { +#include "dequant_mm_e.cc" +} + +namespace at { +#include "attn.cc" +} + +#define DQ_EVEN 1 +#include "dispatch.h" diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/fused_o.cc b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/fused_o.cc new file mode 100644 index 000000000..47d568b4c --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/kernel/fused_o.cc @@ -0,0 +1,20 @@ +// Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +// Overlay core program for the odd core rows (3, 5): dequant_mm_o + attention. +// See fused_e.cc for why the kernels sit in namespaces. +#include +#include +#include +#include "overlay_layout.h" + +namespace dq { +#include "dequant_mm_o.cc" +} + +namespace at { +#include "attn.cc" +} + +#define DQ_EVEN 0 +#include "dispatch.h" diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/tools/check_memtile_bds.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/tools/check_memtile_bds.py new file mode 100644 index 000000000..fa03e557b --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/tools/check_memtile_bds.py @@ -0,0 +1,74 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""Fail the build unless the dq op's memtile configuration is what the host's re-arm assumes. + +rtm_rearm (host/overlay_host.hpp) rewrites the lengths of the memtile x / y +descriptors for a dispatch of m rows per core row and the GLU, then puts them +back to m = 128; it does so by descriptor id, lock id and channel. This checks +those ids and values in the generated op table (the dq op as the switch loads it). + + python3 check_memtile_bds.py host/op_configs.hpp +""" +import re +import sys + +M = 128 +# descriptor ids -> word 0 (length) at m = 128 +LENGTHS = [((0, 1), M * 256), ((2, 3, 4, 5), M * 128), ((6, 7, 8, 9, 24, 25, 26, 27), M * 32), ((28, 29), M * 128)] +Y_S2MM, Y_MM2S = (6, 7, 8, 9, 24, 25, 26, 27), (28, 29) +# channel start queue register -> start descriptor +STARTS = {0xA0604: 0, 0xA060C: 24, 0xA0614: 6, 0xA061C: 26, 0xA0624: 8, 0xA0634: 2, 0xA063C: 28} +# lock id -> initial value +LOCKS = {0: 2, 1: 0, 2: 0, 3: 0, 4: 0, 5: 4, 6: 4, 7: 0, 8: 0} + + +def main(path): + src = open(path).read() + dq = src[src.index("inline const op_config op_dq"):src.index("inline const op_config op_attn")] + bds, locks, starts = {}, {}, {} + for m in re.finditer(r"\{(\d+), 1, (0x[0-9A-F]+), (?:true|false), \{([^}]*)\}\}", dq): + off = int(m.group(2), 16) + if 0xA0000 <= off < 0xA0800: + bds[(int(m.group(1)), (off - 0xA0000) // 0x20)] = [int(x, 16) for x in m.group(3).split(",")] + for m in re.finditer(r"\{(\d+), 1, (0x[0-9A-F]+), (0x[0-9A-F]+|\d+)\}", dq): + off = int(m.group(2), 16) + if 0xC0000 <= off < 0xC0400: + locks[(int(m.group(1)), (off - 0xC0000) // 0x10)] = int(m.group(3), 0) + for m in re.finditer(r"\{(\d+), 1, (0x[0-9A-F]+), (0x[0-9A-F]+), (0x[0-9A-F]+), 1\}", dq): + starts[(int(m.group(1)), int(m.group(3), 16))] = int(m.group(4), 16) + + errors = [] + cols = sorted({c for c, _ in bds}) + if len(cols) != 8: + errors.append(f"memtile columns {cols}, want 8") + for col in cols: + for ids, want in LENGTHS: + for b in ids: + d = bds.get((col, b)) + if d is None or d[0] != want: + errors.append(f"col {col} bd {b}: length {d and hex(d[0])}, want {hex(want)}") + for b in Y_S2MM: + d = bds.get((col, b)) + if d and d[4] != ((8 << 17) | 3): + errors.append(f"col {col} bd {b}: word 4 {hex(d[4])}") + for b in Y_MM2S: + d = bds.get((col, b)) + if d and (d[2] != (32 << 17) or d[4] != ((M << 17) | 0x1F)): + errors.append(f"col {col} bd {b}: words 2/4 {hex(d[2])} {hex(d[4])}") + for q, bd in STARTS.items(): + if starts.get((col, q)) != bd: + errors.append(f"col {col} start {hex(q)}: {starts.get((col, q))}, want {bd}") + for lk, v in LOCKS.items(): + if locks.get((col, lk)) != v: + errors.append(f"col {col} lock {lk}: {locks.get((col, lk))}, want {v}") + for e in errors: + print("check_memtile_bds:", e) + if errors: + return 1 + print(f"check_memtile_bds: {len(cols)} memtiles: descriptors, channel starts and locks as rtm_rearm assumes") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1])) diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/tools/check_stack.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/tools/check_stack.py new file mode 100644 index 000000000..169232d10 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/tools/check_stack.py @@ -0,0 +1,68 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""Fail the build if a core's deepest call chain can overrun its stack (Peano builds). + +Like ../makefiles/check_peano_stack.sh, but it follows the call graph instead of +adding every frame in the ELF: the overlay links two kernels that never run at +the same time, so their frames are never on the stack together. See README.md. + + python3 check_stack.py core_*.elf +""" +import re +import subprocess +import sys + +HEAD = re.compile(r"^([0-9a-f]+) <(.+)>:") +FRAME = re.compile(r"padd[a-z]*\s*\[sp\], #(-?0x[0-9a-f]+|-?\d+)") +CALL = re.compile(r"\bjl\s+(#0x[0-9a-f]+|r\d+|p\d+)") + + +def parse(objdump, elf): + text = subprocess.run([objdump, "-d", "--no-show-raw-insn", elf], + capture_output=True, text=True, check=True).stdout + starts, frames, calls = {}, {}, {} + fn = None + indirect = False + for line in text.splitlines(): + m = HEAD.match(line) + if m and not m.group(2).startswith(".L"): # .L* are labels inside a function + fn = m.group(2) + starts[int(m.group(1), 16)] = fn + frames[fn], calls[fn] = 0, [] + continue + if m or fn is None: + continue + m = FRAME.search(line) + if m and int(m.group(1), 0) > 0: + frames[fn] += int(m.group(1), 0) + for target in CALL.findall(line): + if target.startswith("#"): + calls[fn].append(int(target[1:], 16)) + else: + indirect = True + return starts, frames, calls, indirect + + +def deepest(fn, starts, frames, calls, seen=()): + if fn in seen: + raise RuntimeError(f"recursion through {fn}") + below = [deepest(starts[a], starts, frames, calls, seen + (fn,)) for a in calls[fn] if a in starts] + return frames[fn] + max(below, default=0) + + +def main(): + objdump, stack = sys.argv[1], int(sys.argv[2]) + worst = 0 + for elf in sys.argv[3:]: + starts, frames, calls, indirect = parse(objdump, elf) + need = sum(frames.values()) if indirect else max(deepest(f, starts, frames, calls) for f in frames) + worst = max(worst, need) + if need > stack: + print(f"error: {elf}: deepest call chain needs {need} B of stack, only {stack} B") + sys.exit(1) + print(f"stack OK: deepest call chain {worst} B of {stack} B") + + +if __name__ == "__main__": + main() diff --git a/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/tools/extract_txn2.py b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/tools/extract_txn2.py new file mode 100644 index 000000000..37f0df89a --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/MiniCPM5/prefill_overlay/tools/extract_txn2.py @@ -0,0 +1,198 @@ +# Copyright Β© Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +"""Turn each op's load-time configuration into a C++ table the host can replay. + +aiecc --aie-generate-txn writes a design's whole configuration as register +writes. For every op variant we keep what changes between ops: + + sw stream switch registers (core / shim 0x3F000.., mem tile 0xB0000..) + mux shim mux / demux mask writes (0x1F000, 0x1F004 on row 0) + bds core tile / mem tile BD blockwrites + locks final (= init) lock values (core 0x1F000.., mem tile 0xC0000..) + starts per DMA channel: start queue value and the control value written after it + resets every DMA channel control register (to reset before a switch) + +The core program, program memory and data memory come from the base xclbin. + + python3 extract_txn2.py --base base/.../input_with_addresses.mlir --rtp ct_rtp:2:0 \ + --op A=A/txn.mlir --op B=B/txn.mlir -o op_configs.hpp +""" +import argparse +import re + + +def split_addr(addr): + """NPU2 register address = col << 25 | row << 20 | offset""" + return (addr >> 25) & 0x7F, (addr >> 20) & 0x1F, addr & 0xFFFFF + + +def kind_of(row): + return "shim" if row == 0 else "mem" if row == 1 else "core" + + +RANGES = { + "core": dict(sw=(0x3F000, 0x40000), bd=(0x1D000, 0x1D200), ctrl=(0x1DE00, 0x1DE20), lock=(0x1F000, 0x1F100)), + "mem": dict(sw=(0xB0000, 0xB1000), bd=(0xA0000, 0xA0600), ctrl=(0xA0600, 0xA0660), lock=(0xC0000, 0xC0400)), + "shim": dict(sw=(0x3F000, 0x40000), mux=(0x1F000, 0x1F010)), +} + + +def in_range(off, r): + return r is not None and r[0] <= off < r[1] + + +def parse_globals(text): + out = {} + for name, body in re.findall(r'memref\.global "private" constant @(\w+)\s*:\s*memref<\d+xi32>\s*=\s*dense<(.*?)>', text): + body = body.strip() + if body.startswith('"0x'): + raw = bytes.fromhex(body[3:-1]) + out[name] = [int.from_bytes(raw[i:i + 4], "little") for i in range(0, len(raw), 4)] + else: + out[name] = [int(v) & 0xFFFFFFFF for v in body.strip("[]").split(",")] + return out + + +def parse_txn(path): + text = open(path).read() + glob = parse_globals(text) + ssa = dict(re.findall(r'(%\w+)\s*=\s*memref\.get_global\s+@(\w+)', text)) + cfg = dict(sw={}, mux=[], bds=[], locks={}, starts=[], ctrls=set()) + pending = {} + lock_writes = {} + for line in text.splitlines(): + m = re.search(r'aiex\.npu\.blockwrite\((%\w+)\)\s*\{address = (\d+)', line) + if m: + col, row, off = split_addr(int(m.group(2))) + words = glob[ssa[m.group(1)]] + r = RANGES[kind_of(row)] + if in_range(off, r.get("bd")): + cfg["bds"].append((col, row, off, words)) + elif in_range(off, r.get("sw")): + for i, w in enumerate(words): + cfg["sw"][(col, row, off + 4 * i)] = w + continue + m = re.search(r'aiex\.npu\.maskwrite32 \{address = (\d+) : ui32, mask = (\d+) : ui32, value = (\d+)', line) + if m: + col, row, off = split_addr(int(m.group(1))) + r = RANGES[kind_of(row)] + if in_range(off, r.get("mux")): + cfg["mux"].append((col, row, off, int(m.group(2)), int(m.group(3)))) + elif in_range(off, r.get("ctrl")): + cfg["ctrls"].add((col, row, off)) + continue + m = re.search(r'aiex\.npu\.write32 \{address = (\d+) : ui32, value = (\d+)', line) + if not m: + continue + col, row, off = split_addr(int(m.group(1))) + value = int(m.group(2)) + r = RANGES[kind_of(row)] + if in_range(off, r.get("sw")): + cfg["sw"][(col, row, off)] = value + elif in_range(off, r.get("lock")): + cfg["locks"][(col, row, off)] = value + lock_writes[(col, row, off)] = lock_writes.get((col, row, off), 0) + 1 + elif in_range(off, r.get("ctrl")): + if off % 8 == 4: + pending[(col, row, off - 4)] = value + elif (col, row, off) in pending: + cfg["starts"].append((col, row, off, off + 4, pending.pop((col, row, off)), value)) + cfg["ctrls"].add((col, row, off)) + assert not pending, pending + # aie-rt zeroes all 16 locks of a core tile, then writes the declared ones + # again with their init value; mem tiles only get the declared ones. Keep + # only declared locks: the others stay 0 whichever op runs. + cfg["locks"] = {key: v for key, v in cfg["locks"].items() + if key[1] == 1 or lock_writes[key] >= 2} + return cfg + + +def rtp_address(path, sym): + m = re.search(r'aie\.buffer\(%\w+\) \{address = (\d+) : i32[^}]*sym_name = "' + sym + '"', open(path).read()) + assert m, f"{sym} not found" + return int(m.group(1)) + + +def emit(cfg, name, shared_bds): + L = [f"inline const op_config {name} = {{", + " // stream switch registers: (col, row, offset, value)", + " {"] + for (c, r, o), v in sorted(cfg["sw"].items()): + L.append(f" {{{c}, {r}, 0x{o:05X}, 0x{v:08X}}},") + L += [" },", " // shim mux / demux mask writes: (col, row, offset, mask, value)", " {"] + for c, r, o, mask, v in cfg["mux"]: + L.append(f" {{{c}, {r}, 0x{o:05X}, 0x{mask:08X}, 0x{v:08X}}},") + L += [" },", " // BD registers: (col, row, offset, shared, words)", " {"] + for c, r, o, words in cfg["bds"]: + sh = "true" if (c, r, o) in shared_bds else "false" + L.append(f" {{{c}, {r}, 0x{o:05X}, {sh}, {{{', '.join(f'0x{w:08X}' for w in words)}}}}},") + L += [" },", " // lock values: (col, row, offset, value)", " {"] + for (c, r, o), v in sorted(cfg["locks"].items()): + L.append(f" {{{c}, {r}, 0x{o:05X}, {v}}},") + L += [" },", " // channels: (col, row, control offset, start queue offset, queue value, control value)", " {"] + for c, r, ctrl, q, qv, cv in cfg["starts"]: + L.append(f" {{{c}, {r}, 0x{ctrl:05X}, 0x{q:05X}, 0x{qv:08X}, {cv}}},") + L += [" },", "};", ""] + return L + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--op", action="append", required=True, help="NAME=txn.mlir") + ap.add_argument("--base", required=True, help="base input_with_addresses.mlir") + ap.add_argument("--rtp", action="append", default=[], help="buffer symbol to export as an address") + ap.add_argument("-o", required=True) + args = ap.parse_args() + + ops = [] + for spec in args.op: + name, path = spec.split("=") + ops.append((name, parse_txn(path))) + + L = ["// Generated by tools/extract_txn2.py from aiecc --aie-generate-txn. Do not edit.", + "#pragma once", + "#include ", + "#include ", + "", + "struct reg_write { uint32_t col, row, offset, value; };", + "struct mask_write { uint32_t col, row, offset, mask, value; };", + "// shared: another op uses this BD register too -> rewrite it at every switch;", + "// otherwise it can stay loaded (write it once after the xclbin is loaded)", + "struct reg_block { uint32_t col, row, offset; bool shared; std::vector words; };", + "struct chain_start { uint32_t col, row, ctrl_offset, queue_offset, queue_value, ctrl_value; };", + "struct op_config {", + " std::vector sw;", + " std::vector mux;", + " std::vector bds;", + " std::vector locks;", + " std::vector starts;", + "};", + ""] + for spec in args.rtp: + sym = spec.split(":")[0] + L.append(f"constexpr uint32_t ADDR_{sym} = 0x{rtp_address(args.base, sym):05X};") + L.append("") + # every channel control register any op touches: reset these before a switch + ctrls = sorted(set().union(*[cfg["ctrls"] for _, cfg in ops])) + L += ["// all DMA channel control registers used by any op: (col, row, offset)", + "inline const std::vector all_channels = {"] + for c, r, o in ctrls: + L.append(f" {{{c}, {r}, 0x{o:05X}, 0}},") + L += ["};", ""] + # BD registers more than one op writes + seen = {} + for _, cfg in ops: + for c, r, o, _w in cfg["bds"]: + seen[(c, r, o)] = seen.get((c, r, o), 0) + 1 + shared_bds = {key for key, n in seen.items() if n > 1} + for name, cfg in ops: + L += emit(cfg, f"op_{name}", shared_bds) + n_sh = sum(1 for c, r, o, _w in cfg["bds"] if (c, r, o) in shared_bds) + print(f"op {name}: {len(cfg['sw'])} switch regs, {len(cfg['mux'])} mux writes, {len(cfg['bds'])} BDs ({n_sh} shared) " + f"({sum(len(b[3]) for b in cfg['bds'])} words), {len(cfg['locks'])} locks, {len(cfg['starts'])} channels") + open(args.o, "w").write("\n".join(L)) + print(f"-> {args.o}") + + +if __name__ == "__main__": + main() diff --git a/flm-dev-kit/FLM_Xclbin/build_units.json b/flm-dev-kit/FLM_Xclbin/build_units.json index 7b1dac6c9..e50007c55 100644 --- a/flm-dev-kit/FLM_Xclbin/build_units.json +++ b/flm-dev-kit/FLM_Xclbin/build_units.json @@ -505,6 +505,24 @@ "xclbins-MM_host7_mt_variant_bias_QWEN3_5-OMNI-VISION-MM-HIGH" ] }, + "MiniCPM5/lm_head_npu_bin": { + "model_types": [], + "artifacts": [ + "xclbins-MiniCPM5_lm_head_npu_bin" + ] + }, + "MiniCPM5/moe_decoding": { + "model_types": [], + "artifacts": [ + "xclbins-MiniCPM5_moe_decoding" + ] + }, + "MiniCPM5/prefill_overlay": { + "model_types": [], + "artifacts": [ + "xclbins-MiniCPM5_prefill_overlay" + ] + }, "MiniCPM_V/decoding": { "model_types": [ "QWEN3_5_08B_SL" diff --git a/flm-dev-kit/FLM_Xclbin/kernel_assignment.json b/flm-dev-kit/FLM_Xclbin/kernel_assignment.json index a132949cf..bdf4c691a 100644 --- a/flm-dev-kit/FLM_Xclbin/kernel_assignment.json +++ b/flm-dev-kit/FLM_Xclbin/kernel_assignment.json @@ -322,6 +322,14 @@ "prefill_overlay.xclbin": "xclbins-Hy_mem_30BA3B_prefill_overlay" } }, + "minicpm5:15b-a2.5b": { + "folder": "MiniCPM5-15B-A2.5B-NPU2", + "kernels": { + "moe_layer.xclbin": "xclbins-MiniCPM5_moe_decoding", + "lm_head.xclbin": "xclbins-MiniCPM5_lm_head_npu_bin", + "prefill_overlay.xclbin": "xclbins-MiniCPM5_prefill_overlay" + } + }, "gemma3:1b": { "folder": "Gemma3-1B-NPU2", "kernels": { diff --git a/flm-dev-kit/FLM_Xclbin/kernel_assignment.md b/flm-dev-kit/FLM_Xclbin/kernel_assignment.md index 0a237a15f..15c7b565d 100644 --- a/flm-dev-kit/FLM_Xclbin/kernel_assignment.md +++ b/flm-dev-kit/FLM_Xclbin/kernel_assignment.md @@ -66,6 +66,7 @@ the toolchain CI uses, or after `source setup.sh` with a local toolchain. The ke - [Qwen3.6 MoE](#qwen36-moe) - [Qwen3.8 MTP](#qwen38-mtp) - [Hy-Memory](#hy-memory) +- [MiniCPM5](#minicpm5) - [MiniCPM-V](#minicpm-v) - [GPT-OSS](#gpt-oss) - [LiquidAI/LFM](#liquidailfm) @@ -604,6 +605,22 @@ the sliding-window CU, so the array is never reconfigured mid-layer. | `lm_head.xclbin` | `xclbins-Hy_mem_30BA3B_lm_head_npu_bin` | Peano | | `prefill_overlay.xclbin` | `xclbins-Hy_mem_30BA3B_prefill_overlay` | Peano | +### MiniCPM5 + +#### `minicpm5:15b-a2.5b` β†’ `MiniCPM5-15B-A2.5B-NPU2` + +OpenBMB MiniCPM5-15B-A2.5B (MoE). One layer xclbin serves all 28 layers: layer 0's dense MLP +(8,192 wide) runs as 16 fixed experts of 512 on the MoE overlay. Batched prefill has its own +overlay: the Hy-Memory prefill attention (the same 32 q / 4 kv heads of 128 after the host +duplicates the 2 KV heads) beside a bfp16 dequant_mm with a run-time row count and a fused GLU, +reading the decode weight buffers. + +| Kernels | Artifacts | Compiler | +|---|---|---| +| `moe_layer.xclbin` | `xclbins-MiniCPM5_moe_decoding` | Peano | +| `lm_head.xclbin` | `xclbins-MiniCPM5_lm_head_npu_bin` | Peano | +| `prefill_overlay.xclbin` | `xclbins-MiniCPM5_prefill_overlay` | Peano | + ### MiniCPM-V #### `minicpm-v-4.7:1b` β†’ `MiniCPM-V-4.7-1B-NPU2` diff --git a/flm-dev-kit/FLM_Xclbin/rtp_addresses.lock.txt b/flm-dev-kit/FLM_Xclbin/rtp_addresses.lock.txt index 5952c1de5..c3c30b07d 100644 --- a/flm-dev-kit/FLM_Xclbin/rtp_addresses.lock.txt +++ b/flm-dev-kit/FLM_Xclbin/rtp_addresses.lock.txt @@ -825,6 +825,18 @@ RTP_L_attn_qk_core_4_4 5120 RTP_router_expert_bias 53248 RTP_router_layer 53760 +[xclbins-MiniCPM5_moe_decoding/rtp_addresses.txt] +RTP_L_attn_kv_core_3_3 34816 +RTP_L_attn_kv_core_3_4 34816 +RTP_L_attn_kv_core_5_3 34816 +RTP_L_attn_kv_core_5_4 34816 +RTP_L_attn_qk_core_2_3 5120 +RTP_L_attn_qk_core_2_4 5120 +RTP_L_attn_qk_core_4_3 5120 +RTP_L_attn_qk_core_4_4 5120 +RTP_router_expert_bias 53248 +RTP_router_layer 53888 + [xclbins-MiniCPM_V_BF16_bfp16_mm/rtp_addresses.txt] rtp_2_0 58112 rtp_2_1 58112 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c8511b6f4..0f8c85e88 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -639,6 +639,7 @@ list(APPEND FLM_ENGINE_LINK_LIBS hunyuan_npu hy_mem_npu inkling2_npu + minicpm5_moe_npu ) # The d3 decision engine (--decision d3:lite). Linked where its library is vendored; elsewhere diff --git a/src/common/AutoModel/builtin_backends.cpp b/src/common/AutoModel/builtin_backends.cpp index d3109b340..9e6bed461 100644 --- a/src/common/AutoModel/builtin_backends.cpp +++ b/src/common/AutoModel/builtin_backends.cpp @@ -22,6 +22,7 @@ #include "models/lfm2/flm/aie2p/lfm2_npu.hpp" #include "models/lfm3/flm/aie2p/lfm3_npu.hpp" #include "models/llama/flm/aie2p/llama_npu.hpp" +#include "models/minicpm5_moe/flm/aie2p/minicpm5_moe_npu.hpp" #include "models/minicpm_ocr/flm/aie2p/minicpm_ocr_npu.hpp" #include "models/minicpm_v_4_7/flm/aie2p/minicpm_v_4_7_npu.hpp" #include "models/minicpm_v_4_7_moe/flm/aie2p/minicpm_v_4_7_moe_npu.hpp" @@ -103,6 +104,7 @@ void register_builtin_backends(BackendRegistry& registry) { RegisterFlm(registry, "lfm2"); RegisterFlm(registry, "lfm2.5-tk"); RegisterFlm(registry, "lfm3"); + RegisterFlm(registry, "minicpm5"); RegisterFlm(registry, "nanbeige"); RegisterFlm(registry, "phi4"); diff --git a/src/common/AutoModel/builtin_frontends.cpp b/src/common/AutoModel/builtin_frontends.cpp index 37f19af40..b28ed933a 100644 --- a/src/common/AutoModel/builtin_frontends.cpp +++ b/src/common/AutoModel/builtin_frontends.cpp @@ -13,6 +13,7 @@ #include "AutoModel/modeling_lfm2.hpp" #include "AutoModel/modeling_lfm3.hpp" #include "AutoModel/modeling_llama3.hpp" +#include "AutoModel/modeling_minicpm5.hpp" #include "AutoModel/modeling_minicpm_ocr.hpp" #include "AutoModel/modeling_minicpm_v.hpp" #include "AutoModel/modeling_minicpm_v_moe.hpp" @@ -101,6 +102,7 @@ void register_builtin_frontends(FrontendRegistry& registry) { Register(registry, "lfm2"); Register(registry, "lfm2.5-tk"); Register(registry, "lfm3"); + Register(registry, "minicpm5"); Register(registry, "nanbeige"); Register(registry, "hunyuan"); Register(registry, "hy-memory"); diff --git a/src/common/AutoModel/modeling_minicpm5.cpp b/src/common/AutoModel/modeling_minicpm5.cpp new file mode 100644 index 000000000..f514aacbb --- /dev/null +++ b/src/common/AutoModel/modeling_minicpm5.cpp @@ -0,0 +1,112 @@ +/// \file modeling_minicpm5.cpp +/// \brief MiniCPM5 class +/// \author FastFlowLM Team +/// \date 2026-12-03 +/// \note Portions of this file consist of AI-generated content. +/// \note OpenBMB MiniCPM5: ChatML, `` opened by the template when thinking is on, MiniCPM XML tool calls +/// (`v`). + +#include "AutoModel/modeling_minicpm5.hpp" +#include "models/minicpm5_moe/flm/aie2p/minicpm5_moe_npu.hpp" +#include "utils/utils.hpp" +#include "metrices.hpp" + +/************ MiniCPM5 family **************/ +MiniCPM5::MiniCPM5(flm_rt::device* npu_device_inst) : AutoModel(npu_device_inst, "MiniCPM5") {} + +void MiniCPM5::load_model(std::string model_path, json model_info, int default_context_length, bool enable_preemption, const std::string& backend) { + this->_shared_load_backend(model_path, model_info, default_context_length, enable_preemption, backend); + this->_shared_setup_tokenizer(model_path); + this->sampler.reset(); + this->enable_think = true; // the upstream template thinks by default + + // the model card's general thinking-mode setting: temperature 1.0, top_p 0.95, min_p 0; + // no top_k, so transformers' 50 + sampler_config config; + config.top_k = 50; + config.top_p = 0.95f; + config.min_p = 0.0f; + config.temperature = 1.0f; + config.rep_penalty = 1.0f; + this->set_sampler(config); + for (size_t i = 0; i < PROFILER_TYPE_NUM; i++) { + this->profiler_list[i].reset(); + } + _prefix_attach(lm_engine, minicpm5_moe_npu_state_api(lm_engine)); +} + +std::string MiniCPM5::apply_chat_template(nlohmann::ordered_json& messages, nlohmann::ordered_json tools, bool continue_final_message) { + minja::chat_template_inputs inputs; + minja::chat_template_options opt; + opt.polyfill_tool_responses = false; + inputs.messages = messages; + inputs.extra_context = this->extra_context; + inputs.extra_context["enable_thinking"] = this->enable_think; + if (!tools.empty() && this->tools_enabled()) + inputs.tools = tools; + return this->_render_chat_template(inputs, continue_final_message, opt); +} + +bool MiniCPM5::insert(chat_meta_info_t& meta_info, lm_uniform_input_t& input, std::function is_cancelled) { + this->profiler_list[TKOEN_ENCODE_TIME].start(); + std::string templated_text; + if (input.messages.empty() && input.prompt.empty()) { + header_print("WARNING", "No messages or prompt provided"); + return false; + } + if (!input.messages.empty()) { // already formatted messages, usually from the REST API + templated_text = this->apply_chat_template(input.messages, input.tools, meta_info.continue_final_message); + } + else { // a plain text prompt, usually from the CLI + nlohmann::ordered_json messages; + messages.push_back({ {"role", "user"}, {"content", input.prompt} }); + templated_text = this->apply_chat_template(messages); + } + + std::vector tokens = this->tokenizer->encode(templated_text); + this->profiler_list[TKOEN_ENCODE_TIME].stop(tokens.size()); + + // Prefix slots. The next turn renders this reply as "<|im_start|>assistant\n" + "\n\n\n\n" (reasoning + // dropped, "\n\n" one token) or + "\n" + reasoning, so the "\n" ending a thinking generation prompt is held back and + // fed by generate(). "...\n\n\n\n" (thinking off) is rendered as is: save it whole. A continued + // message keeps all its tokens: they are the client's text. Boundary marker "<|im_start|>user". + const size_t n = tokens.size(); + this->think_nl_held = !meta_info.continue_final_message && n >= 2 && tokens[n - 1] == kNewlineId && + tokens[n - 2] == kThinkStartId; + const size_t trim = this->think_nl_held ? 1 : 0; + if (this->_prefix_slot_mode(meta_info, tokens.size(), trim)) { + return this->_prefix_text_insert(meta_info, tokens, trim, "<|im_start|>user", is_cancelled); + } + this->_prefix_legacy_path(); + tokens.resize(n - trim); + + return this->_shared_insert(meta_info, tokens, is_cancelled); +} + +std::string MiniCPM5::generate(chat_meta_info_t& meta_info, int length_limit, std::ostream& os, std::function is_cancelled) { + if (this->think_nl_held) { + this->think_nl_held = false; + if (this->total_tokens + 1 >= this->decode_cap()) { + header_print("WARNING", "Max length reached, stopping generation..."); + meta_info.stop_reason = MAX_LENGTH_REACHED; + return ""; + } + // the rest of the generation prompt: fed for the KV cache only, it never reaches the output + this->_skip_insert_sample(meta_info); + this->token_history.push_back(kNewlineId); + this->profiler_list[DECODING_TIME].start(); + buffer y = this->lm_engine->forward(kNewlineId); + this->profiler_list[DECODING_TIME].stop(1); + this->total_tokens++; + this->last_token = this->_sample(y, meta_info); + meta_info.insert_sample_pending = true; + } + return this->_shared_generate(meta_info, length_limit, os, is_cancelled); +} + +std::string MiniCPM5::generate_with_prompt(chat_meta_info_t& meta_info, lm_uniform_input_t& input, int length_limit, std::ostream& os) { + if (!this->insert(meta_info, input)) { + return ""; + } + return this->generate(meta_info, length_limit, os); +} diff --git a/src/common/chat/chat_format.cpp b/src/common/chat/chat_format.cpp index e7e665e21..3fca6ad2d 100644 --- a/src/common/chat/chat_format.cpp +++ b/src/common/chat/chat_format.cpp @@ -21,18 +21,22 @@ const format_name_entry FORMAT_NAMES[] = { {chat_format_kind::HARMONY, "harmony"}, {chat_format_kind::GLM_XML, "glm_xml"}, {chat_format_kind::INKLING, "inkling"}, + {chat_format_kind::MINICPM_XML, "minicpm_xml"}, }; bool is_call_space(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } +bool is_name_char(char c) { + return std::isalnum(static_cast(c)) || c == '_' || c == '-' || c == '.' || c == ':'; +} + /// \brief A GLM call opens with the function's name, then its first argument or the end of the call chat_call_head glm_call_head(const chat_format_spec& spec, const std::string& text, size_t pos) { static const std::string KEY_OPEN = ""; size_t end = pos; - while (end < text.size() && (std::isalnum(static_cast(text[end])) || text[end] == '_' || - text[end] == '-' || text[end] == '.' || text[end] == ':')) { + while (end < text.size() && is_name_char(text[end])) { end++; } if (end == pos) { @@ -56,6 +60,48 @@ chat_call_head glm_call_head(const chat_format_spec& spec, const std::string& te return chat_call_head::PROSE; } +/// \brief A MiniCPM call's opener goes on with the function's name and the attribute's close +chat_call_head minicpm_call_head(const std::string& text, size_t pos) { + static const std::string NAME_CLOSE = "\">"; + size_t end = pos; + while (end < text.size() && is_name_char(text[end])) { + end++; + } + if (end == text.size()) { + return chat_call_head::UNSURE; + } + if (end == pos) { + return chat_call_head::PROSE; + } + const size_t avail = text.size() - end; + if (text.compare(end, NAME_CLOSE.size(), NAME_CLOSE) == 0) { + return chat_call_head::CALL; + } + return avail < NAME_CLOSE.size() && NAME_CLOSE.compare(0, avail, text, end, avail) == 0 ? chat_call_head::UNSURE + : chat_call_head::PROSE; +} + +/// \brief The first "" from from on that no CDATA section holds +/// \note The template wraps a value that holds "<" in CDATA, so only there can the tag be text. +size_t minicpm_tool_end(const chat_format_spec& spec, const std::string& text, size_t from, bool is_partial) { + static const std::string CDATA_OPEN = ""; + size_t p = from; + while (true) { + const size_t end = text.find(spec.tool_end, p); + const size_t cdata = text.find(CDATA_OPEN, p); + if (cdata == std::string::npos || (end != std::string::npos && end < cdata)) { + return end; + } + const size_t close = text.find(CDATA_CLOSE, cdata + CDATA_OPEN.size()); + if (close == std::string::npos) { + // still inside the section; a finished output that never closed it ends at the first tag after it + return is_partial ? std::string::npos : text.find(spec.tool_end, cdata + CDATA_OPEN.size()); + } + p = close + CDATA_CLOSE.size(); + } +} + } // namespace const char* chat_format_name(chat_format_kind kind) { @@ -124,6 +170,11 @@ chat_format_spec chat_format_make(chat_format_kind kind, bool with_reasoning) { spec.tool_start = "<|content_invoke_tool_json|>"; spec.tool_end = "<|end_message|>"; break; + case chat_format_kind::MINICPM_XML: + // no block around the calls: each call is one, its name the rest of the opener + spec.tool_start = "") && known("<|channel>")) { return chat_format_make(chat_format_kind::GEMMA4, false); } + // MiniCPM5 names the function and its parameters in attributes, with no around the calls + if (in_template("* openers = spec.kind == chat_format_kind::QWEN_XML ? &QWEN_XML_OPENERS @@ -211,6 +269,9 @@ size_t chat_format_tool_end(const chat_format_spec& spec, const std::string& tex size_t& hold) { static const std::string FUNCTION_CLOSE = ""; hold = std::string::npos; + if (spec.kind == chat_format_kind::MINICPM_XML) { + return minicpm_tool_end(spec, text, from, is_partial); + } const size_t first = text.find(spec.tool_end, from); if (spec.kind != chat_format_kind::QWEN_XML || first == std::string::npos) { return first; diff --git a/src/common/chat/chat_grammar.cpp b/src/common/chat/chat_grammar.cpp index 9d896b490..ef663cd4e 100644 --- a/src/common/chat/chat_grammar.cpp +++ b/src/common/chat/chat_grammar.cpp @@ -780,6 +780,84 @@ json glm_arguments(const json& schema, const json& sent) { return sequence(std::move(pairs)); } +// ---------------------------------------------------------------- minicpm xml arguments + +json regex(const std::string& pattern) { + return {{"type", "regex"}, {"pattern", pattern}}; +} + +/// \brief A value as MiniCPM5 writes it: raw, or in a CDATA section when it holds "<", "&" or a newline +/// \param raw the value outside CDATA, which holds none of those +/// \param cdata the value inside the section, which the parser ends at its first "]]>" +json minicpm_value(json raw, json cdata) { + return {{"type", "or"}, {"elements", {std::move(raw), tag("")}}}; +} + +/// \brief The arguments of a MiniCPM call: v for each +/// \note MiniCPM5's template writes a string raw and anything else as JSON, with nothing +/// between the parts. As in the GLM dialect, declared properties come in their +/// order, each optional one free to be left out, and a string keeps its +/// minLength/maxLength (inside CDATA it may then hold no "]"); a schema without +/// declared properties takes any keys. +/// \param schema the parameters schema, normalized for xgrammar +/// \param sent the schema as the request sent it, where a string still has its bounds +json minicpm_arguments(const json& schema, const json& sent) { + static const std::string RAW = "[^<&\\n]*"; + const bool declared = schema.is_object() && schema.contains("properties") && schema["properties"].is_object() && + !schema["properties"].empty() && schema.value("additionalProperties", false) == false; + const json none; + const json& sent_properties = + sent.is_object() && sent.contains("properties") && sent["properties"].is_object() ? sent["properties"] : none; + if (!declared) { + return {{"type", "star"}, + {"content", sequence({tag("\\n]+"), "\">"), + minicpm_value(regex(RAW), any_text()), const_string("")})}}; + } + std::set required; + for (const auto& name : schema.value("required", json::array())) { + if (name.is_string()) required.insert(name.get()); + } + std::vector pairs; + for (const auto& [name, property] : schema["properties"].items()) { + json value; + const bool string_enum = property.is_object() && property.contains("enum") && property["enum"].is_array() && + !property["enum"].empty() && + std::all_of(property["enum"].begin(), property["enum"].end(), + [](const json& v) { return v.is_string(); }); + if (string_enum) { + std::vector options; + for (const auto& option : property["enum"]) { + const std::string text = option.get(); + const bool wrapped = text.find_first_of("<&\n") != std::string::npos; + options.push_back(const_string(wrapped ? "" : text)); + } + value = {{"type", "or"}, {"elements", std::move(options)}}; + } else if (glm_raw_value(property, schema)) { + std::optional> bounds; + if (sent_properties.contains(name) && sent_properties[name].is_object()) { + bounds = string_length_bounds(sent_properties[name]); + } + if (bounds) { + const std::string count = "{" + std::to_string(bounds->first) + "," + + (bounds->second < 0 ? "" : std::to_string(bounds->second)) + "}"; + value = minicpm_value(regex("[^<&\\n]" + count), regex("[^\\]]" + count)); + } else { + value = minicpm_value(regex(RAW), any_text()); + } + } else { + // a $ref in the property points into the schema it came from + json sub = property; + for (const char* defs : {"$defs", "definitions"}) { + if (schema.contains(defs) && !sub.contains(defs)) sub[defs] = schema[defs]; + } + value = minicpm_value(schema_content(sub), schema_content(sub)); + } + json pair = tag("", std::move(value), ""); + pairs.push_back(required.count(name) ? std::move(pair) : optional_format(std::move(pair))); + } + return sequence(std::move(pairs)); +} + // ---------------------------------------------------------------- per format tool tags /// \brief Where the request's grammar dictates the text, see decode_constraint::penalty_free() @@ -834,6 +912,11 @@ tool_syntax tool_tags(const chat_format_spec& spec, const std::vector& syntax.tags.push_back( tag("" + tool.name, glm_arguments(tool.parameters, tool.declared), "")); break; + case chat_format_kind::MINICPM_XML: + syntax.trigger = "", + minicpm_arguments(tool.parameters, tool.declared), "")); + break; case chat_format_kind::LFM2_PYTHONIC: case chat_format_kind::CONTENT_ONLY: case chat_format_kind::HARMONY: diff --git a/src/common/chat/chat_parser.cpp b/src/common/chat/chat_parser.cpp index 749e7424c..7ae26bf99 100644 --- a/src/common/chat/chat_parser.cpp +++ b/src/common/chat/chat_parser.cpp @@ -608,6 +608,100 @@ void parse_glm_xml_block(const std::string& body, bool closed, const param_types add_call(calls, name, out); } +// ---------------------------------------------------------------- minicpm xml + +const std::string MINICPM_NAME_CLOSE = "\">"; +const std::string MINICPM_PARAM_OPEN = "v... +/// \note The block starts after the opener's '", a CDATA one at its "]]>". +void parse_minicpm_xml_block(const std::string& body, bool closed, const param_types& types, + std::vector& calls) { + const size_t name_end = body.find(MINICPM_NAME_CLOSE); + if (name_end == npos && !closed) { + return; // the name may still be growing + } + const std::string name = trim(body.substr(0, name_end)); + if (name.empty()) { + return; + } + std::string out = "{"; + bool first = true; + size_t p = name_end == npos ? npos : name_end + MINICPM_NAME_CLOSE.size(); + while (p != npos) { + const size_t open = body.find(MINICPM_PARAM_OPEN, p); + if (open == npos) { + break; + } + const size_t key_begin = open + MINICPM_PARAM_OPEN.size(); + const size_t key_end = body.find(MINICPM_NAME_CLOSE, key_begin); + if (key_end == npos) { + if (!closed) { + add_call(calls, name, out); + return; // the key is still being written + } + break; + } + const std::string key = body.substr(key_begin, key_end - key_begin); + const size_t value_begin = key_end + MINICPM_NAME_CLOSE.size(); + + std::string raw; + size_t value_end = npos; // past the value's "" + bool value_closed = false; + if (starts_with_at(body, value_begin, CDATA_OPEN)) { + const size_t text_begin = value_begin + CDATA_OPEN.size(); + const size_t cdata_end = body.find(CDATA_CLOSE, text_begin); + raw = body.substr(text_begin, (cdata_end == npos ? body.size() : cdata_end) - text_begin); + if (cdata_end != npos) { + value_closed = true; + const size_t close = body.find(MINICPM_PARAM_CLOSE, cdata_end + CDATA_CLOSE.size()); + value_end = close == npos ? npos : close + MINICPM_PARAM_CLOSE.size(); + } else if (!closed) { + raw = cut_partial_marker(raw, {&CDATA_CLOSE}); + } + } else if (!closed && partial_marker_at(body, value_begin, body.size(), CDATA_OPEN)) { + raw.clear(); // a CDATA section, or text that starts like one: what follows will tell + } else { + const size_t close = body.find(MINICPM_PARAM_CLOSE, value_begin); + raw = body.substr(value_begin, (close == npos ? body.size() : close) - value_begin); + if (close != npos) { + value_closed = true; + value_end = close + MINICPM_PARAM_CLOSE.size(); + } else if (!closed) { + raw = cut_partial_marker(raw, {&MINICPM_PARAM_CLOSE}); + } + } + const type_set allowed = types.of(name, key); + + out += first ? "\"" : ",\""; + first = false; + chat_json_escape_append(out, key); + out += "\":"; + if (!value_closed && !closed) { + if (allowed == type_set{"string"}) { + // strings stream as they come; anything else waits for its end + out += '"'; + chat_json_escape_append(out, raw); + } + add_call(calls, name, out); + return; + } + out += xml_value_to_json(raw, allowed); + p = value_end; + } + if (closed) { + out += '}'; + } + add_call(calls, name, out); +} + // ---------------------------------------------------------------- lfm2 / gemma4 void parse_lfm2_block(const std::string& body, bool closed, std::vector& calls) { @@ -682,6 +776,9 @@ void parse_tool_block(const chat_format_spec& spec, const std::string& body, boo case chat_format_kind::GLM_XML: parse_glm_xml_block(body, closed, types, calls); break; + case chat_format_kind::MINICPM_XML: + parse_minicpm_xml_block(body, closed, types, calls); + break; case chat_format_kind::LFM2_PYTHONIC: parse_lfm2_block(body, closed, calls); break; diff --git a/src/include/AutoModel/modeling_minicpm5.hpp b/src/include/AutoModel/modeling_minicpm5.hpp new file mode 100644 index 000000000..25708077b --- /dev/null +++ b/src/include/AutoModel/modeling_minicpm5.hpp @@ -0,0 +1,68 @@ +/// \file modeling_minicpm5.hpp +/// \brief MiniCPM5 class +/// \author FastFlowLM Team +/// \date 2026-12-03 +/// \note Portions of this file consist of AI-generated content. +/// \note AutoModel wrapper for the MiniCPM5-15B-A2.5B engine (minicpm5_moe_npu): ChatML +/// turns, hybrid thinking (the template opens `` unless enable_thinking is +/// false) and MiniCPM XML tool calls. Text only. + +#pragma once +#include "AutoModel/automodel.hpp" + +/************ MiniCPM5 family **************/ +class MiniCPM5 : public AutoModel { +private: + /// the template opens a reasoning block (`\n`) by default; turning it off renders `\n\n\n\n` + bool enable_think = true; + /// insert() left the "\n" after the generation prompt's `` out of the prefill; generate() feeds it + bool think_nl_held = false; + static constexpr int kThinkStartId = 8; // + static constexpr int kNewlineId = 220; // "\n"; a past reply renders `` + "\n\n" (one token) or "\n" + reasoning + +public: + MiniCPM5(flm_rt::device* npu_device_inst); + + void load_model(std::string model_path, json model_inf, int default_context_length = -1, bool enable_preemption = false, const std::string& backend = "") override; + bool insert(chat_meta_info_t& meta_info, lm_uniform_input_t& input, std::function is_cancelled = [] { return false; }) override; + std::string generate(chat_meta_info_t& meta_info, int length_limit, std::ostream& os, std::function is_cancelled = [] { return false; }) override; + std::string generate_with_prompt(chat_meta_info_t& meta_info, lm_uniform_input_t& input, int length_limit, std::ostream& os = std::cout) override; + std::string apply_chat_template(nlohmann::ordered_json& messages, nlohmann::ordered_json tools = nlohmann::ordered_json::object(), bool continue_final_message = false) override; + bool thinking_enabled() const override { + return this->enable_think; + } + bool supports_continue_final_message() const override { + return true; + } + + /// \brief enable_think / toggle_think / reasoning_effort ("none" turns thinking off) and everything the base class handles + bool configure_parameter(std::string parameter_name, const std::any& value) override { + if (parameter_name == "enable_think") { + try { + this->enable_think = std::any_cast(value); + return true; + } catch (const std::bad_any_cast&) { + return false; + } + } + else if (parameter_name == "reasoning_effort") { + try { + const std::string effort = std::any_cast(value); + if (effort == "high" || effort == "medium" || effort == "low") + this->enable_think = true; + else if (effort == "none") + this->enable_think = false; + else + header_print("WARNING", "Reasoning effort must be 'none', 'low', 'medium' or 'high'!"); + return true; + } catch (const std::bad_any_cast&) { + return false; + } + } + else if (parameter_name == "toggle_think") { + this->enable_think = !this->enable_think; + return true; + } + return AutoModel::configure_parameter(parameter_name, value); + } +}; diff --git a/src/include/chat/chat_format.hpp b/src/include/chat/chat_format.hpp index ee4896eee..c31f738b9 100644 --- a/src/include/chat/chat_format.hpp +++ b/src/include/chat/chat_format.hpp @@ -19,6 +19,7 @@ enum class chat_format_kind { HARMONY, // <|channel|>analysis / commentary to=functions.f / final (gpt-oss) GLM_XML, // fkv (Laguna, GLM-4.5) INKLING, // <|message_model|>f<|content_invoke_tool_json|>{"name":"f","args":{..}}<|end_message|> (Inkling 2) + MINICPM_XML, // v, v in CDATA when it holds < & or \n (MiniCPM5) }; /// \brief Everything the parser needs to know about one model's output syntax @@ -84,7 +85,8 @@ chat_call_head chat_format_call_head(const chat_format_spec& spec, const std::st /// \return its index, or npos when the text does not close the block (yet) /// \note A Qwen XML value may hold the end tag itself: the block's own follows the /// call's "". A call that left that out ends at the first end tag, -/// which the next call, or the end of the output, settles. +/// which the next call, or the end of the output, settles. A MiniCPM XML call +/// ends at the first "" outside a CDATA section. size_t chat_format_tool_end(const chat_format_spec& spec, const std::string& text, size_t from, bool is_partial, size_t& hold); diff --git a/src/include/minja/chat-template.hpp b/src/include/minja/chat-template.hpp index 5d3a36e0c..2006f6540 100644 --- a/src/include/minja/chat-template.hpp +++ b/src/include/minja/chat-template.hpp @@ -201,10 +201,10 @@ class chat_template { // GLM-4.5 and Laguna-2.1 write the key as argument_needle. Missed, the // template counts as one without tool calls, and the polyfills rewrite its tool calls and // tool responses as JSON text. Hy-Memory's dialect, with after the name, keeps - // the polyfills: FLM does not parse its calls. + // the polyfills: FLM does not parse its calls. MiniCPM5 writes . const auto renders_argument = [&contains](const std::string & out) { return contains(out, "") || contains(out, "\"argument_needle\":") || - contains(out, "'argument_needle':") || + contains(out, "'argument_needle':") || contains(out, "") || (contains(out, ">argument_needle<") && !contains(out, "")); }; out = try_raw_render(json::array({ diff --git a/src/include/models/minicpm5_moe/flm/aie2p/minicpm5_moe_npu.hpp b/src/include/models/minicpm5_moe/flm/aie2p/minicpm5_moe_npu.hpp new file mode 100644 index 000000000..27318eb08 --- /dev/null +++ b/src/include/models/minicpm5_moe/flm/aie2p/minicpm5_moe_npu.hpp @@ -0,0 +1,79 @@ +/// \file minicpm5_moe_npu.hpp +/// \brief minicpm5_moe_npu class +/// \author FastFlowLM Team +/// \date 2026-12-03 +/// \note Portions of this file consist of AI-generated content. +/// \note The engine for MiniCPM5-15B-A2.5B (minicpm5_moe): 28 layers, layer 0 dense +/// (8192 wide, run as 16 fixed experts of 512) and layers 1..27 MoE (160 +/// experts, top 16, + a shared expert), gated attention, Q4_K body, Q8_0 +/// lm_head. Text only. Decode runs on two bitstreams (moe_layer / lm_head +/// .xclbin); prefill runs prompt chunks batched on prefill_overlay.xclbin. +#pragma once +#include "lm_config.hpp" +#include "npu_utils/npu_utils.hpp" +#include "tensor_utils/q4_npu_eXpress.hpp" +#include "modules/embedding.hpp" +#include "tensor_2d.hpp" +#include "utils/utils.hpp" +#include "causal_lm.hpp" +#include "flm_state_api.h" + + +class minicpm5_moe_npu : public causal_lm{ +public: + /// \brief initialize the minicpm5_moe_npu + /// \param config the configuration + /// \param npu_instance the npu instance + /// \param MAX_L KV cache length in tokens; rounded up to a power of two in + /// [4096, 131072] + minicpm5_moe_npu(LM_Config config, npu_xclbin_manager *npu_instance, int MAX_L = 16384); + ~minicpm5_moe_npu(); + + /// \brief decode one token + /// \param ids the token + /// \return the logits (vocab_size) + buffer forward(int ids) override; + + /// \brief run the prompt into the KV cache + /// \return the logits of the last prompt token + buffer prefill(std::vector& ids, void* payload = nullptr) override; + + /// \brief set the context length + /// \param L the context length + void set_context_length(int L) override; + + /// \brief load the weights + /// \param q4nx the q4nx + void load_weights(Q4NX& q4nx) override; + + /// \brief clear the context + void clear_context() override; + + /// \brief get the k cache + /// \param layer_idx the layer index + /// \param idx the token index + /// \return K of that token, all KV heads in head order + buffer get_k_cache(int layer_idx, int idx) override; + + /// \brief get the v cache + /// \param layer_idx the layer index + /// \param idx the token index + /// \return V of that token, all KV heads in head order + buffer get_v_cache(int layer_idx, int idx) override; + + /// \brief grow the KV caches, keeping the conversation + /// \param MAX_L the max length + void update_max_length(uint32_t MAX_L) override; + + /// \brief get the current context length + /// \return the current context length + int get_current_context_length() override; + int checkpoint() override; + int restore() override; +private: + struct Impl; + Impl* _impl; +}; + +/// \brief the saved-state table of this engine (flm_state_api.h); nullptr if `engine` is not a minicpm5_moe_npu +extern "C" const flm_state_api* minicpm5_moe_npu_state_api(void* engine); diff --git a/src/inno/flm.iss b/src/inno/flm.iss index cf7b6ed17..46f5321d1 100644 --- a/src/inno/flm.iss +++ b/src/inno/flm.iss @@ -82,6 +82,7 @@ Source: "gemma4e_12b_npu.dll"; DestDir: "{app}"; Flags: ignoreversion Source: "hunyuan_npu.dll"; DestDir: "{app}"; Flags: ignoreversion Source: "hy_mem_npu.dll"; DestDir: "{app}"; Flags: ignoreversion Source: "inkling2_npu.dll"; DestDir: "{app}"; Flags: ignoreversion +Source: "minicpm5_moe_npu.dll"; DestDir: "{app}"; Flags: ignoreversion Source: "lm_head.dll"; DestDir: "{app}"; Flags: ignoreversion Source: "dequant.dll"; DestDir: "{app}"; Flags: ignoreversion Source: "whisper_npu.dll"; DestDir: "{app}"; Flags: ignoreversion diff --git a/src/lib/hrx/libminicpm5_moe_npu.so b/src/lib/hrx/libminicpm5_moe_npu.so new file mode 100644 index 000000000..44a5b406b Binary files /dev/null and b/src/lib/hrx/libminicpm5_moe_npu.so differ diff --git a/src/lib/hrx/minicpm5_moe_npu.dll b/src/lib/hrx/minicpm5_moe_npu.dll new file mode 100644 index 000000000..1f5b0a87d Binary files /dev/null and b/src/lib/hrx/minicpm5_moe_npu.dll differ diff --git a/src/lib/hrx/minicpm5_moe_npu.lib b/src/lib/hrx/minicpm5_moe_npu.lib new file mode 100644 index 000000000..d5df3e91e Binary files /dev/null and b/src/lib/hrx/minicpm5_moe_npu.lib differ diff --git a/src/lib/xrt/libminicpm5_moe_npu.so b/src/lib/xrt/libminicpm5_moe_npu.so new file mode 100644 index 000000000..c047ba830 Binary files /dev/null and b/src/lib/xrt/libminicpm5_moe_npu.so differ diff --git a/src/lib/xrt/minicpm5_moe_npu.dll b/src/lib/xrt/minicpm5_moe_npu.dll new file mode 100644 index 000000000..dce55dc48 Binary files /dev/null and b/src/lib/xrt/minicpm5_moe_npu.dll differ diff --git a/src/lib/xrt/minicpm5_moe_npu.lib b/src/lib/xrt/minicpm5_moe_npu.lib new file mode 100644 index 000000000..207a66784 Binary files /dev/null and b/src/lib/xrt/minicpm5_moe_npu.lib differ diff --git a/src/model_info.json b/src/model_info.json index 9d762ed87..c52da5793 100644 --- a/src/model_info.json +++ b/src/model_info.json @@ -7079,5 +7079,61 @@ "xetHash": "c2f5e1aa42f5a3d05774571947477c4b691dae2c9e753a0ab6a432ddde1865eb", "path": "vision_weight.q4nx" } + ], + "minicpm5:15b-a2.5b": [ + { + "type": "file", + "oid": "2ace5b8c3964855369daf18f16907dfdba648708", + "size": 1566, + "path": ".gitattributes" + }, + { + "type": "file", + "oid": "86ba72f268fb036cc72f3931de32d4a5dad9b613", + "size": 3589, + "path": "README.md" + }, + { + "type": "file", + "oid": "4baf1cf2bd2e66ec9fdc67afcfdfeddfb60ffedf", + "size": 5862, + "path": "chat_template.jinja" + }, + { + "type": "file", + "oid": "a501944f13ae979f9eb4397b4498c0d4f89a0f30", + "size": 917, + "path": "config.json" + }, + { + "type": "file", + "oid": "a9c1751d464a2ab290379034299fb2f90a0b7b62", + "size": 49, + "path": "configuration.json" + }, + { + "type": "file", + "oid": "8f7d780d32f450a8a30daf88d843d9e792cd9bd8", + "size": 9195867824, + "lfs": { + "oid": "342ef21b574b76746e3fc697a999b713a7cf616c7970c99720cae55bccc9485b", + "size": 9195867824, + "pointerSize": 135 + }, + "xetHash": "742936bb5a08c3ceae4693cc4a0a58f17d99bb26cdf59c067237163ed888ab7f", + "path": "model.q4nx" + }, + { + "type": "file", + "oid": "ec0bf9a34dc884738494ed1f74d0c5327b06d690", + "size": 9894271, + "path": "tokenizer.json" + }, + { + "type": "file", + "oid": "29907ed4cee263bebac2074c9057a390e696d6b0", + "size": 94454, + "path": "tokenizer_config.json" + } ] } diff --git a/src/model_list.json b/src/model_list.json index 6d34692e5..0b45b8b6e 100644 --- a/src/model_list.json +++ b/src/model_list.json @@ -106,6 +106,43 @@ "footprint": 22.0 } }, + "minicpm5": { + "15b-a2.5b": { + "supported_platforms": ["aie2p"], + "tools": true, + "name": "MiniCPM5-15B-A2.5B-NPU2", + "url": "https://huggingface.co/FastFlowLM/MiniCPM5-15B-A2.5B-NPU2", + "file_url": "https://huggingface.co/api/models/FastFlowLM/MiniCPM5-15B-A2.5B-NPU2/tree/main", + "ms_url": "https://modelscope.cn/models/amd/MiniCPM5-15B-A2.5B-NPU2", + "modified_at": "2026-12-03T00:00:00Z", + "size": 9205863328, + "flm_min_version": "1.0.15", + "default_context_length": 131072, + "max_prefill_len": 4096, + "files": [ + "config.json", + "model.q4nx", + "tokenizer.json", + "tokenizer_config.json", + "chat_template.jinja" + ], + "vlm": false, + "asr": false, + "details": { + "format": "NPU2", + "family": "minicpm5", + "think": true, + "think_toggleable": true, + "parameter_size": "15B-A2.5B", + "quantization_level": "Q4_K" + }, + "label": [ + "reasoning", + "tool-calling" + ], + "footprint": 21.5 + } + }, "inkling-2": { "mini": { "supported_platforms": ["aie2p"], diff --git a/src/server/rest_handler.cpp b/src/server/rest_handler.cpp index 6b5cffe70..39cdf156e 100644 --- a/src/server/rest_handler.cpp +++ b/src/server/rest_handler.cpp @@ -36,6 +36,7 @@ #include "AutoModel/modeling_gpt_oss.hpp" #include "AutoModel/modeling_hy_memory.hpp" #include "AutoModel/modeling_inkling2.hpp" +#include "AutoModel/modeling_minicpm5.hpp" #include "AutoModel/modeling_minicpm_v.hpp" #include "AutoModel/modeling_minicpm_v_bf16.hpp" #include "AutoModel/modeling_qwen3_asr.hpp" @@ -1912,7 +1913,8 @@ void RestHandler::run_chat_turn(const json& request, chat_sink& protocol_sink, pre_is_inkling = dynamic_cast(current) != nullptr; pre_is_gpt_oss = dynamic_cast(current) != nullptr; pre_is_hy_memory = dynamic_cast(current) != nullptr; - pre_reads_template_think = dynamic_cast(current) != nullptr; + pre_reads_template_think = dynamic_cast(current) != nullptr || + dynamic_cast(current) != nullptr; } else { const auto info = supported_models.get_model_info(supported_models.rectify_model_tag(model)).second; const std::string family = info.contains("details") && info["details"].is_object() @@ -1920,7 +1922,7 @@ void RestHandler::run_chat_turn(const json& request, chat_sink& protocol_sink, pre_is_inkling = (family == "inkling-2" || family == "inkling-2-dflash2"); pre_is_gpt_oss = (family == "gpt-oss"); pre_is_hy_memory = (family == "hy-memory"); - pre_reads_template_think = (family == "qwen3.5" || family == "qwen3.5-dflash2"); + pre_reads_template_think = (family == "qwen3.5" || family == "qwen3.5-dflash2" || family == "minicpm5"); if (thinking_budget > 0) { bool supported = false; if (family == "qwen3") { @@ -1995,10 +1997,11 @@ void RestHandler::run_chat_turn(const json& request, chat_sink& protocol_sink, return; } - // The Qwen spelling of think, honored by the Qwen3.5 package only; any other model - // keeps ignoring it. Refused here, before anything streams. + // The Qwen spelling of think, honored by the Qwen3.5 and MiniCPM5 packages (both templates + // read enable_thinking); any other model keeps ignoring it. Refused here, before anything streams. std::optional nested_think; - if (dynamic_cast(auto_chat_engine.get()) != nullptr) { + if (dynamic_cast(auto_chat_engine.get()) != nullptr || + dynamic_cast(auto_chat_engine.get()) != nullptr) { if (!read_template_think(nested_think)) return; if (nested_think.has_value() && !*nested_think) { constraint_request.allow_reasoning = false; diff --git a/src/test/chat_tools/test_chat_tools.cpp b/src/test/chat_tools/test_chat_tools.cpp index b9b1296d5..678d1a275 100644 --- a/src/test/chat_tools/test_chat_tools.cpp +++ b/src/test/chat_tools/test_chat_tools.cpp @@ -1434,6 +1434,365 @@ void test_minja_template_exception() { CHECK(caught_runtime_only); } +// ---------------------------------------------------------------- minicpm xml (MiniCPM5) + +const chat_format_spec MINICPM_XML = chat_format_make(chat_format_kind::MINICPM_XML, true); + +// How MiniCPM5 renders an assistant's tool calls, verbatim from its chat_template.jinja +const std::string MINICPM_RENDER_CALLS = R"JINJA( +{{- content }} +{%- for tool_call in calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '' }} + {%- if tool_call.arguments is mapping %} + {%- set args_dict = tool_call.arguments %} + {%- for param_name, param_value in args_dict.items() %} + {%- if param_value is string %} + {%- set val_str = param_value %} + {%- else %} + {%- set val_str = param_value | tojson(ensure_ascii=False) %} + {%- endif %} + {{- '' }} + {%- if '<' in val_str or '&' in val_str or '\n' in val_str %} + {{- '' }} + {%- else %} + {{- val_str }} + {%- endif %} + {{- '' }} + {%- endfor %} + {%- endif %} + {{- '' }} +{%- endfor %} +)JINJA"; + +std::string render_minicpm_calls(const json& calls, const std::string& content = "") { + auto tmpl = minja::Parser::parse(MINICPM_RENDER_CALLS, {true, true, false}); + return tmpl->render(minja::Context::make(minja::Value(json{{"calls", calls}, {"content", content}}))); +} + +void test_minicpm_detection() { + std::printf("a template that writes is MiniCPM XML\n"); + auto no_token = [](const std::string&) { return false; }; + const chat_format_spec spec = chat_format_detect("" + MINICPM_RENDER_CALLS, no_token); + CHECK_EQ(chat_format_name(spec.kind), "minicpm_xml"); + CHECK(spec.has_reasoning()); + CHECK_EQ(spec.tool_start, ""); + chat_format_kind kind; + CHECK(chat_format_from_name("minicpm_xml", kind) && kind == chat_format_kind::MINICPM_XML); + // Qwen XML writes inside : it stays Qwen XML + CHECK(chat_format_detect("\n\n\n", no_token).kind == chat_format_kind::QWEN_XML); +} + +void test_minicpm_parse() { + std::printf("minicpm xml: the calls MiniCPM5's template renders parse back\n"); + auto one = [](const json& c) { + chat_msg msg = parse(MINICPM_XML, render_minicpm_calls(json::array({c}))); + return msg.tool_calls.size() == 1 ? msg.tool_calls[0].name + " " + msg.tool_calls[0].arguments + : std::string(""); + }; + CHECK_EQ(one(call("ping", json::object())), "ping {}"); + CHECK_EQ(one(call("get_weather", {{"city", "Paris"}, {"unit", "celsius"}})), + "get_weather {\"city\":\"Paris\",\"unit\":\"celsius\"}"); + CHECK_EQ(one(call("set_flag", {{"on", true}, {"count", 3}})), "set_flag {\"on\":true,\"count\":3}"); + // a string is written raw, so a string schema keeps what looks like a number; the rest is JSON + CHECK_EQ(one(call("lookup", {{"zip", "90210"}, {"limit", 5}, {"code", "007"}, {"filter", {{"a", 1}}}})), + "lookup {\"zip\":\"90210\",\"limit\":5,\"code\":\"007\",\"filter\":{\"a\":1}}"); + // a value with < & or a newline goes in CDATA, which may hold the end tags themselves + CHECK_EQ(one(call("write_file", {{"path", "a.md"}, {"content", "line 1\nuse & \n"}})), + "write_file {\"path\":\"a.md\",\"content\":\"line 1\\nuse & \\n\"}"); + CHECK_EQ(one(call("write_file", {{"path", "caf\xC3\xA9"}, {"content", "\xE2\x9C\x93"}})), + "write_file {\"path\":\"caf\xC3\xA9\",\"content\":\"\xE2\x9C\x93\"}"); + // JSON that holds < goes in CDATA too + CHECK_EQ(one(call("lookup", {{"filter", {{"a", 1}, {"b", ""}}}})), "lookup {\"filter\":{\"a\":1,\"b\":\"\"}}"); + + std::printf("minicpm xml: text, reasoning and parallel calls around it\n"); + const json pair = json::array({call("ping", json::object()), call("get_weather", {{"city", "Tokyo"}})}); + chat_msg msg = parse(MINICPM_XML, "\nNeed both.\n\n\n" + render_minicpm_calls(pair, "Checking.")); + CHECK_EQ(msg.reasoning, "Need both."); + CHECK_EQ(msg.content, "Checking."); + CHECK(msg.tool_calls.size() == 2); + // a call opens with a name and ">; the tag in prose is text + const std::string prose = "A tag is text."; + msg = parse(MINICPM_XML, prose); + CHECK_EQ(msg.content, prose); + CHECK(msg.tool_calls.empty()); + const std::string prose2 = "Write to call."; + msg = parse(MINICPM_XML, prose2); + CHECK_EQ(msg.content, prose2); + CHECK(msg.tool_calls.empty()); + check_prefix_stable(MINICPM_XML, prose2, "minicpm prose tag"); + + std::printf("minicpm xml: streams only grow\n"); + const std::vector texts = { + render_minicpm_calls(pair), + "\nplan\n\n\n" + + render_minicpm_calls(json::array({call("lookup", {{"zip", "90210"}, {"limit", 3}, {"filter", {{"a", 1}}}})}), + "Let me check."), + render_minicpm_calls(json::array({call("write_file", {{"path", "p"}, {"content", "abc\n]]"}})})), + render_minicpm_calls(json::array({call("set_flag", {{"on", false}}), call("write_file", {{"path", "q"}, {"content", "x&y"}})})), + }; + for (size_t i = 0; i < texts.size(); i++) { + check_prefix_stable(MINICPM_XML, texts[i], ("minicpm stream " + std::to_string(i)).c_str()); + } + // a string streams as it comes, held back from a close still being written + msg = parse(MINICPM_XML, "hello wor", true); + CHECK(msg.tool_calls.size() == 1 && msg.tool_calls[0].arguments == "{\"content\":\"hello wor"); + msg = parse(MINICPM_XML, "hellob]]", true); + CHECK(msg.tool_calls.size() == 1 && msg.tool_calls[0].arguments == "{\"content\":\"ab"); + // a name still being written is no call yet, nor text + msg = parse(MINICPM_XML, "Sure.Paris"); + CHECK(msg.tool_calls.size() == 1 && msg.tool_calls[0].arguments == "{\"city\":\"Paris\"}"); + // a continued message that stops inside a call hands the call on + CHECK_EQ(chat_format_prefill(MINICPM_XML, "Checking.\n", true, true), + ""); +} + +void test_minicpm_grammar() { + std::printf("minicpm xml grammar takes every call MiniCPM5's template renders\n"); + grammar_fixture grammar(MINICPM_XML); + const std::vector> calls = { + {"no arguments", json::array({call("ping", json::object())})}, + {"no parameters schema", json::array({call("now", json::object())})}, + {"bare object schema", json::array({call("status", {{"any", "thing"}, {"n", 2}})})}, + {"one argument", json::array({call("get_weather", {{"city", "Paris"}})})}, + {"optional argument", json::array({call("get_weather", {{"city", "Paris"}, {"unit", "celsius"}})})}, + {"value in CDATA", json::array({call("write_file", {{"path", "a.xml"}, {"content", "\n 1\n"}})})}, + {"boolean and integer", json::array({call("set_flag", {{"on", true}, {"count", 3}})})}, + {"raw strings and JSON values", + json::array({call("lookup", {{"zip", "90210"}, {"limit", 5}, {"code", "007"}, {"level", "2"}, {"note", "n"}, + {"anything", "x"}, {"filter", {{"a", 1}}}})})}, + {"JSON value in CDATA", json::array({call("status", {{"html", ""}, {"obj", {{"k", "a&b"}}}})})}, + {"parallel", json::array({call("ping", json::object()), call("get_weather", {{"city", "Tokyo"}})})}, + }; + for (const auto& [label, c] : calls) { + grammar.accepts(tools_request(), render_minicpm_calls(c), label); + grammar.accepts(tools_request(chat_tool_choice::REQUIRED), render_minicpm_calls(c), label); + } + grammar.accepts(tools_request(chat_tool_choice::FUNCTION, "get_weather"), + render_minicpm_calls(json::array({call("get_weather", {{"city", "Paris"}})})), "forced call"); + grammar.accepts(tools_request(), + render_minicpm_calls(json::array({call("ping", json::object())}), "Let me check."), + "text before the call"); + + std::printf("minicpm xml grammar holds a call to its tool's schema\n"); + auto takes = [&grammar](const json& c) { + return grammar.takes(tools_request(), render_minicpm_calls(json::array({c}))); + }; + CHECK(!takes(call("get_weather", {{"city", "Paris"}, {"unit", "kelvin"}}))); + CHECK(!takes(call("get_weather", {{"city", "Paris"}, {"country", "FR"}}))); + CHECK(!takes(call("get_weather", {{"unit", "celsius"}}))); + CHECK(!takes(call("set_flag", {{"on", "yes"}}))); + CHECK(!takes(call("unknown", json::object()))); + // a raw value holds neither < nor &, only CDATA does + CHECK(!grammar.takes(tools_request(), "p" + "a")); + CHECK(!grammar.takes(tools_request(), "p" + "ab")); + chat_constraint_request one_call = tools_request(); + one_call.parallel_tool_calls = false; + CHECK(!grammar.takes(one_call, + render_minicpm_calls(json::array({call("ping", json::object()), call("ping", json::object())})))); + + std::printf("minicpm xml grammar holds a string to its minLength/maxLength, raw or in CDATA\n"); + auto note = [](const std::string& text, const std::string& more = "") { + return "" + text + "" + more + ""; + }; + CHECK(grammar.takes(note_request(), note("ab"))); + CHECK(grammar.takes(note_request(), note("abcdef"))); + CHECK(!grammar.takes(note_request(), note("a"))); + CHECK(!grammar.takes(note_request(), note("abcdefg"))); + CHECK(grammar.takes(note_request(), note(""))); + CHECK(grammar.takes(note_request(), note(""))); + CHECK(!grammar.takes(note_request(), note(""))); + CHECK(!grammar.takes(note_request(), note(""))); + // array items, written as JSON, keep their bounds too + CHECK(grammar.takes(note_request(), note("ab", "[\"x\", \"xyz\"]"))); + CHECK(!grammar.takes(note_request(), note("ab", "[\"wxyz\"]"))); +} + +// MiniCPM5-15B-A2.5B's chat_template.jinja, verbatim +const std::string MINICPM5_TEMPLATE = R"JINJA({{- bos_token }}{%- if tools %} + {%- set tool_definitions %} + {{- "# Tools\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson(ensure_ascii=False) }} + {%- endfor %} + {{- '\n\n\nTool usage guidelines:\n- You may call zero or more functions. If no function calls are needed, just answer normally and do not include any .\n- When calling a function, return an XML object within using:\nparam-value\n- param-value may be multi-line. If it contains <, & or newline characters, wrap it in a CDATA block: ' }} + {%- endset %} + + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {%- if '' in messages[0].content %} + {{- messages[0].content.replace('', tool_definitions) }} + {%- else %} + {{- messages[0].content + '\n\n' + tool_definitions }} + {%- endif %} + {%- else %} + {{- tool_definitions.lstrip() }} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('') and message.content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + + {%- if reasoning_content %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} + {%- elif '' not in content and '' not in content %} + {{- '<|im_start|>' + message.role + '\n\n\n\n\n' + content.lstrip('\n') }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '' }} + {%- if tool_call.arguments is mapping %} + {%- set args_dict = tool_call.arguments %} + {%- for param_name, param_value in args_dict.items() %} + {%- if param_value is string %} + {%- set val_str = param_value %} + {%- else %} + {%- set val_str = param_value | tojson(ensure_ascii=False) %} + {%- endif %} + {{- '' }} + {%- if '<' in val_str or '&' in val_str or '\n' in val_str %} + {{- '' }} + {%- else %} + {{- val_str }} + {%- endif %} + {{- '' }} + {%- endfor %} + {%- elif tool_call.arguments is string and tool_call.arguments | trim %} + {{- raise_exception("tool_call.arguments must be a dict/mapping, got a string β€” please json.loads() it before calling apply_chat_template.") }} + {%- endif %} + {{- '' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {%- if message.content is string %} + {{- content }} + {%- else %} + {{- message.content | tojson(ensure_ascii=False) }} + {%- endif %} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} +)JINJA"; + +void test_minicpm_template() { + std::printf("minja renders MiniCPM5's template as HF transformers does\n"); + minja::chat_template minicpm(MINICPM5_TEMPLATE, "", ""); + const minja::chat_template_caps& caps = minicpm.original_caps(); + CHECK(caps.supports_tools); + CHECK(caps.supports_tool_calls); + CHECK(caps.requires_object_arguments); + CHECK(caps.supports_tool_responses); + minja::chat_template_inputs inputs; + // as an OpenAI client sends it back: the arguments are a JSON string + inputs.messages = json::array({ + {{"role", "user"}, {"content", "Weather in Paris?"}}, + {{"role", "assistant"}, {"content", ""}, + {"tool_calls", json::array({call("get_weather", "{\"city\": \"Paris\", \"days\": 3}")})}}, + {{"role", "tool"}, {"tool_call_id", "call_1"}, {"content", "18 C"}}, + }); + inputs.tools = json::array({tool("get_weather", object_schema({{"city", {{"type", "string"}}}}, {"city"}))}); + inputs.extra_context = {{"enable_thinking", false}}; + // expected: transformers' apply_chat_template on the same messages + CHECK_EQ(minicpm.apply(inputs), + "<|im_start|>system\n# Tools\n\nYou are provided with function signatures within XML " + "tags:\n\n{\"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"description\": " + "\"get_weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\"}}, " + "\"required\": [\"city\"]}}}\n\n\nTool usage guidelines:\n- You may call zero or more functions. If no " + "function calls are needed, just answer normally and do not include any .\n- When " + "calling a function, return an XML object within using:\nparam-value\n- param-value may be " + "multi-line. If it contains <, & or newline characters, wrap it in a CDATA block: <|im_end|>\n<|im_start|>user\nWeather in " + "Paris?<|im_end|>\n<|im_start|>assistant\n\n\n\n\nParis3<|im_end|>\n<|im_start|>user\n" + "\n18 C\n<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"); + + inputs.messages = json::array({ + {{"role", "user"}, {"content", "Save it"}}, + {{"role", "assistant"}, {"content", "Saving."}, + {"tool_calls", json::array({call("write_file", {{"path", "a.md"}, {"content", "x < y\nz"}}), + call("set_flag", {{"on", true}, {"count", 3}})})}}, + }); + inputs.tools = json(); + inputs.add_generation_prompt = false; + inputs.extra_context = json::object(); + CHECK_EQ(minicpm.apply(inputs), + "<|im_start|>user\nSave it<|im_end|>\n<|im_start|>assistant\n\n\n\n\nSaving.\na.md" + "\ntrue3" + "<|im_end|>\n"); +} + void test_inkling() { std::printf("inkling: typed messages, reasoning, answers and calls\n"); const chat_format_spec spec = chat_format_make(chat_format_kind::INKLING, false); @@ -1708,6 +2067,10 @@ int main() { test_minja_call_postfix(); test_glm_template_capabilities(); test_minja_template_exception(); + test_minicpm_detection(); + test_minicpm_parse(); + test_minicpm_grammar(); + test_minicpm_template(); test_inkling(); test_penalty_free_spans(); if (failures) { diff --git a/src/test/openai_api_test/test_reasoning.py b/src/test/openai_api_test/test_reasoning.py index f67c9edb4..6f9e4a862 100644 --- a/src/test/openai_api_test/test_reasoning.py +++ b/src/test/openai_api_test/test_reasoning.py @@ -219,15 +219,16 @@ def think_switch_is_per_request(api: Api) -> None: def reads_nested_switch(api: Api) -> bool: """Whether this model is declared to read chat_template_kwargs.enable_thinking. - FLM_TEST_NESTED_THINKING=on or off declares it; unset, the Qwen3.5 packages are taken to read it. + FLM_TEST_NESTED_THINKING=on or off declares it; unset, the Qwen3.5 and MiniCPM5 packages are taken + to read it. """ declared = os.environ.get("FLM_TEST_NESTED_THINKING", "").lower() if declared in ("on", "off"): return declared == "on" family = loaded_family(api) if family is not None: - return family == "qwen3.5" - return "qwen3.5" in api.model.lower() + return family in ("qwen3.5", "minicpm5") + return "qwen3.5" in api.model.lower() or "minicpm5" in api.model.lower() _families: dict[str, str | None] = {} @@ -287,7 +288,7 @@ def nested_body(api: Api, enable_thinking, **fields) -> dict: def nested_thinking_switch(api: Api) -> None: """chat_template_kwargs.enable_thinking is think: on gives reasoning_content, off gives none. - Only the Qwen3.5 packages read it; on any other model the field is ignored and this skips. + Only the Qwen3.5 and MiniCPM5 packages read it; on any other model the field is ignored and this skips. """ skip_always_thinking(api) on = api.ok(nested_body(api, True))["message"] diff --git a/src/wix/flm.wxs b/src/wix/flm.wxs index 7ba85e35f..d02fca926 100644 --- a/src/wix/flm.wxs +++ b/src/wix/flm.wxs @@ -195,6 +195,9 @@ + + + diff --git a/src/xclbins/MiniCPM5-15B-A2.5B-NPU2/lm_head.xclbin b/src/xclbins/MiniCPM5-15B-A2.5B-NPU2/lm_head.xclbin new file mode 100644 index 000000000..4d4881182 Binary files /dev/null and b/src/xclbins/MiniCPM5-15B-A2.5B-NPU2/lm_head.xclbin differ diff --git a/src/xclbins/MiniCPM5-15B-A2.5B-NPU2/moe_layer.xclbin b/src/xclbins/MiniCPM5-15B-A2.5B-NPU2/moe_layer.xclbin new file mode 100644 index 000000000..4c2a1db22 Binary files /dev/null and b/src/xclbins/MiniCPM5-15B-A2.5B-NPU2/moe_layer.xclbin differ diff --git a/src/xclbins/MiniCPM5-15B-A2.5B-NPU2/prefill_overlay.xclbin b/src/xclbins/MiniCPM5-15B-A2.5B-NPU2/prefill_overlay.xclbin new file mode 100644 index 000000000..f36de1119 Binary files /dev/null and b/src/xclbins/MiniCPM5-15B-A2.5B-NPU2/prefill_overlay.xclbin differ