diff --git a/src/common/npu_device.cpp b/src/common/npu_device.cpp index 75467d410..dc6973fad 100644 --- a/src/common/npu_device.cpp +++ b/src/common/npu_device.cpp @@ -6,6 +6,10 @@ #include #include +#if defined(_WIN32) && !defined(FLM_USE_HRX) +#include "xrt/experimental/xrt_ini.h" +#endif + #if defined(_WIN32) && defined(FLM_ENABLE_OGA_HIPEP) #include @@ -27,6 +31,30 @@ bool valid_npu_power_mode(std::string_view mode) { mode == "performance" || mode == "turbo"; } +#if defined(_WIN32) && !defined(FLM_USE_HRX) +/// \brief Keep every XRT buffer resident in NPU memory for its whole life. +/// \note The Windows (MCDM) XRT shim makes each BO resident when it is allocated. Its residency +/// controller, on by default since late 2025, then evicts the BOs of any command not run since +/// the last trim when Windows sends a trim notification (periodic or memory pressure), and +/// makes them resident again at the next submit. A model whose runs are built before its +/// weights load (qwen3.6-moe) can see its weights evicted back to system memory during the +/// load and re-paged on the first request. Turning the controller off keeps the residency the +/// BOs get at allocation, which is how FastFlowLM's engines expect their buffers. ryzenai-corelib +/// turns it off for the same reason. XRT reads the key once, at the process's first buffer +/// allocation, so it is set before the device opens; set() throws once the key has been read. +static void disable_xrt_residency_controller() { + static std::once_flag once; + std::call_once(once, [] { + try { + xrt::ini::set("Runtime.disable_residency_controller", "true"); + } catch (const std::exception& e) { + header_print("WARNING", "Could not disable the XRT residency controller (" << e.what() + << "); NPU buffers may be evicted to system memory when idle"); + } + }); +} +#endif + static flm_rt::device* open_npu_device() { try { #if defined(_WIN32) && defined(FLM_ENABLE_OGA_HIPEP) @@ -34,6 +62,9 @@ static flm_rt::device* open_npu_device() { if (FAILED(status)) { throw std::system_error(HRESULT_CODE(status), std::system_category(), "xrt_coreutil.dll"); } +#endif +#if defined(_WIN32) && !defined(FLM_USE_HRX) + disable_xrt_residency_controller(); #endif static flm_rt::device device(0); return &device;