Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

perf: retain clean NGX core across same-device graph rebuilds

Veyra Goal Agentfbaffeb10158
diff --git a/CMakeLists.txt b/CMakeLists.txt
index c3291a58..d4be51c8 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -146,6 +146,7 @@ if(VEYRA_ENABLE_EXPERIMENTAL_DLSSNR)
endif()
add_library(veyra_ngx STATIC
src/ngx/NgxCoreHost.cpp
+ src/ngx/NgxCoreCache.cpp
src/ngx/DlssNrRuntimeAdapter.cpp
src/ngx/DlssSrBackend.cpp
src/ngx/VideoSrBackend.cpp
@@ -169,7 +170,7 @@ add_library(veyra_ngx STATIC
target_link_libraries(veyra_ngx PRIVATE
"$<IF:$<CONFIG:Debug>,${VEYRA_DLSS_SDK_ROOT}/lib/Windows_x86_64/x64/nvsdk_ngx_s_dbg.lib,${VEYRA_DLSS_SDK_ROOT}/lib/Windows_x86_64/x64/nvsdk_ngx_s.lib>")
target_compile_definitions(veyra_ngx PUBLIC
- VEYRA_EXPERIMENTAL_LOCAL_DLSSNR=1)
+ VEYRA_EXPERIMENTAL_LOCAL_DLSSNR=1 VEYRA_HAS_NGX_CORE_CACHE=1)
# Diagnostic: exercises the Ada multi-frame unlock against the local DLSS-G
# runtime image without involving NGX (works on any NVIDIA adapter).
diff --git a/docs/PERF_2A_CORE_REUSE_2026-10-04.md b/docs/PERF_2A_CORE_REUSE_2026-10-04.md
index ea4997be..3b148ed5 100644
--- a/docs/PERF_2A_CORE_REUSE_2026-10-04.md
+++ b/docs/PERF_2A_CORE_REUSE_2026-10-04.md
@@ -20,4 +20,4 @@
先只在同设备、同 runtime、同 NR 模块与相同补帧配置下保留 NGX 核心;功能及参数仍释放。设备移除、初始化失败、运行库/补帧配置改变或未释放参数均清空核心。Ada/Ampere 补丁会话先保持完整原流程,待实卡验证后再扩大。候选必须支持同一二进制 `VEYRA_TEST_DISABLE_NGX_CORE_REUSE=1` 对照,参数销毁与最终核心关闭顺序必须可核对。
-尚未实现产品候选或测得收益;本记录中的时间全部是优化前数据。
+候选将核心所有者放在 EngineController 的设备会话中,Graph 使用共享借用;缓存仅一份,借用者未释放时拒绝下一次 prepare,旧图全部参数释放且设备正常才 retain。普通 Graph 消费者默认不启用。NR 适配器仍每次重建加载/释放,是否允许在保留核心时重新 Init_Ext 必须实测。benchmark 通过显式缓存注入测试,B-off 同一 EXE 环境开关;最终关闭发生在设备销毁之前。此时尚未测得收益;上述时间全部是优化前数据。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 08257a24..afb2c786 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,11 @@
# Veyra 工作记录
+## 2026-10-04 NR优化2a:设备会话核心缓存候选
+
+- A-baseline commit181e4ab/tag与增量bundle验证后,添加render线程限定NgxCoreCache、Graph可选借用和Engine设备会话生命周期。无缓存的所有现有Graph构造调用维持完整原流程。核心key含设备/规范绝对runtime/NR模块/补帧开关后端倍率;设备错误、失败、参数残留或key变化完整关闭。Ada/Ampere补丁型号主动不缓存。
+- 功能/参数/适配器仍按原序释放,只有成功图、liveParameters=0和设备正常才保留核心;再次prepare时存在借用者就拒绝,不并行初始化第二核心。退出显式coreCache.close在device.shutdown前。B-off test env同一EXE禁用,无新增UI选项。
+- native测试仅在B编译宏接入缓存,A封存EXE不重编;nr-rebuild支持B-off引用同B构建路径。候选尚未构建和实测,不计为保留优化。
+
## 2026-10-04 NR优化2a:重建基线完整封存
- `nr-rebuild.py A A-rebuild-v1` 12/12 exit0,四组20次×三轮,240次真实Graph重建/720源帧;debug0/设备正常/NR和SR计数符合请求。native EXE2d7177…5e27,runtime F95FEB/驱动616.56;图像读回在创建/释放计时段外,不含实际Present。
diff --git a/include/veyra/ngx/NgxCoreCache.h b/include/veyra/ngx/NgxCoreCache.h
new file mode 100644
index 00000000..ab9be1c7
--- /dev/null
+++ b/include/veyra/ngx/NgxCoreCache.h
@@ -0,0 +1,34 @@
+#pragma once
+
+#include "veyra/ngx/NgxCoreHost.h"
+#include <memory>
+#include <string>
+
+namespace veyra::ngx {
+
+// Render-thread-only, device-lifetime owner. Features and parameter blocks
+// still belong to a graph; a core may be borrowed only after their release.
+// Compatibility-patched FG sessions opt out until their full lifetime is shared.
+class NgxCoreCache {
+public:
+ struct Key {
+ ID3D12Device* device = nullptr;
+ std::wstring runtimeDirectory;
+ int nrRuntime = 0;
+ bool frameGeneration = false;
+ int fgBackend = 0;
+ unsigned fgMultiplier = 1;
+ bool operator==(const Key&) const = default;
+ };
+ ~NgxCoreCache();
+ bool prepare(Key key, bool enabled);
+ std::shared_ptr<NgxCoreHost> borrow();
+ void publish(const std::shared_ptr<NgxCoreHost>& core);
+ bool owns(const std::shared_ptr<NgxCoreHost>& core) const;
+ bool close(const char* reason = "device-close");
+private:
+ Key key_;
+ bool enabled_ = false;
+ std::shared_ptr<NgxCoreHost> core_;
+};
+}
diff --git a/include/veyra/ngx/NgxCoreHost.h b/include/veyra/ngx/NgxCoreHost.h
index bc6d2212..8cf24173 100644
--- a/include/veyra/ngx/NgxCoreHost.h
+++ b/include/veyra/ngx/NgxCoreHost.h
@@ -34,6 +34,7 @@ public:
bool initialized() const { return initialized_; }
uint64_t initResult() const { return initResult_; }
+ uint32_t liveParameterBlockCount() const { return liveParameterBlockCount_; }
// Parameter blocks are tracked; shutdown() destroys any still-live block
// before core Shutdown1 (defense in depth; consumers should destroy them
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 50ed80af..92b25fec 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -56,6 +56,7 @@ class FsrFgPresenter;
namespace veyra::ngx {
class NgxCoreHost;
+class NgxCoreCache;
class DlssSrBackend;
class VideoSrBackend;
class TrueHdrBackend;
@@ -392,7 +393,8 @@ struct EnhanceGraphDesc {
class EnhanceGraph {
public:
- EnhanceGraph(gfx::D3D12DeviceContext& context, gfx::CommandSlotRing& ring);
+ EnhanceGraph(gfx::D3D12DeviceContext& context, gfx::CommandSlotRing& ring,
+ ngx::NgxCoreCache* coreCache = nullptr);
~EnhanceGraph();
EnhanceGraph(const EnhanceGraph&) = delete;
@@ -619,6 +621,7 @@ private:
gfx::D3D12DeviceContext& context_;
gfx::CommandSlotRing& ring_;
+ ngx::NgxCoreCache* coreCache_ = nullptr; // non-owning; device session outlives graph
EnhanceGraphDesc desc_{};
bool initialized_ = false;
@@ -754,7 +757,7 @@ private:
std::unique_ptr<ngx::NvOfSession> nvof_;
ComPtr<ID3D12Fence> nvofOutFence_;
HANDLE nvofOutEvent_ = nullptr;
- std::unique_ptr<ngx::NgxCoreHost> coreHost_;
+ std::shared_ptr<ngx::NgxCoreHost> coreHost_;
std::unique_ptr<ngx::DlssNrRuntimeAdapter> nrAdapter_;
std::unique_ptr<ngx::DlssSrBackend> srBackend_;
std::unique_ptr<guidance::AmdOpticalFlow> amdOf_;
diff --git a/scripts/perf/nr-rebuild.py b/scripts/perf/nr-rebuild.py
index c62a6e57..d96572e6 100644
--- a/scripts/perf/nr-rebuild.py
+++ b/scripts/perf/nr-rebuild.py
@@ -17,7 +17,8 @@ variant,label=sys.argv[1:3];assert all(x.replace('-','').isalnum() for x in (var
app=BASE/'tests'/TASK/(label+'-app');assert not app.exists()
package=BASE/'test-packages'/TASK/'Veyra-2.0.3-perf-baseline-A-NVIDIA-win64-portable'
shutil.copytree(package,app,copy_function=matrix.copy_dependency)
-exe=app/'veyra_nr_rebuild_benchmark.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)
+build_variant=variant.removesuffix('-off')
+exe=app/'veyra_nr_rebuild_benchmark.exe';shutil.copy2(BASE/'build'/TASK/build_variant/exe.name,exe)
results=[]
def percentile(values,p):
values=sorted(values);at=(len(values)-1)*p/100;low=int(at);high=min(low+1,len(values)-1)
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 31449a8f..23fc468a 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -30,6 +30,7 @@
#include "veyra/gfx/XessMfgUnlock.h"
#include "veyra/ngx/AmpereMfgUnlock.h"
#include "veyra/ngx/DlssgTransfusion.h"
+#include "veyra/ngx/NgxCoreCache.h"
#include "veyra/diagnostics/ResetCause.h"
#include "veyra/diagnostics/CpuStallTrace.h"
#include "veyra/sink/WasapiAudioSink.h"
@@ -291,7 +292,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
status(L"正在初始化GPU与本地运行时…");
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;
sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;
- pipeline::EnhanceGraph graph(ctx,ring);AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;
+ ngx::NgxCoreCache coreCache;
+ pipeline::EnhanceGraph graph(ctx,ring,&coreCache);AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;
source::CaptureCardSource captureSource;const bool physicalCapture=path.starts_with(L"capture:")||path.starts_with(L"capture2:");
source::ScreenCaptureSource screenSource;const bool isScreen=path.starts_with(L"screen:");
// Set when a live parameter change arrives while paused (or on a still
@@ -2163,6 +2165,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// play failure left "graph shutdown complete" as its last line.
audioPipe.stopThread();audio.shutdown();veyra::log::info("engine","teardown: audio stopped");
ring.drainQueue();presenter.close();graph.shutdown();
+ (void)coreCache.close();
veyra::log::info("engine","teardown: closing sources");
captureSource.close();screenSource.close();source.close();av_frame_free(&cachedFrame);av_frame_free(&imageFrame);
veyra::log::info("engine","teardown: sources closed");
diff --git a/src/ngx/NgxCoreCache.cpp b/src/ngx/NgxCoreCache.cpp
new file mode 100644
index 00000000..b57c46e4
--- /dev/null
+++ b/src/ngx/NgxCoreCache.cpp
@@ -0,0 +1,57 @@
+#include "veyra/ngx/NgxCoreCache.h"
+#include "veyra/Log.h"
+#include <format>
+#include <utility>
+
+namespace veyra::ngx {
+NgxCoreCache::~NgxCoreCache() { (void)close(); }
+
+bool NgxCoreCache::close(const char* reason) {
+ if (!core_) return true;
+ if (core_.use_count() != 1) {
+ log::error("ngx-core-cache", std::format("event=refused-close reason={} borrowers={}", reason, core_.use_count()-1));
+ return false;
+ }
+ log::info("ngx-core-cache", std::format("event=close reason={} liveParameters={}", reason, core_->liveParameterBlockCount()));
+ core_->shutdown();
+ core_.reset();
+ return true;
+}
+
+bool NgxCoreCache::prepare(Key key, bool enabled) {
+ // Prevent a second NGX Init on this device while a graph still uses it.
+ if (core_ && core_.use_count() != 1) {
+ log::error("ngx-core-cache", "event=refused-prepare active graph must release its core first");
+ return false;
+ }
+ if ((!enabled || !(key == key_)) && !close(enabled ? "key-changed" : "disabled-or-compatibility")) return false;
+ key_ = std::move(key);
+ enabled_ = enabled;
+ return true;
+}
+
+std::shared_ptr<NgxCoreHost> NgxCoreCache::borrow() {
+ if (!enabled_ || !core_) return {};
+ if (!core_->initialized() || core_->liveParameterBlockCount() != 0 ||
+ !key_.device || FAILED(key_.device->GetDeviceRemovedReason())) {
+ (void)close("invalid-core-or-parameters");
+ return {};
+ }
+ log::info("ngx-core-cache", "event=hit liveParameters=0");
+ return core_;
+}
+
+void NgxCoreCache::publish(const std::shared_ptr<NgxCoreHost>& core) {
+ if (!enabled_ || !core || !core->initialized()) return;
+ if (core_ && core_ != core) {
+ log::error("ngx-core-cache", "event=refused-publish different core already retained");
+ return;
+ }
+ if (!core_) log::info("ngx-core-cache", "event=publish initialized graph owns all live parameters");
+ core_ = core;
+}
+
+bool NgxCoreCache::owns(const std::shared_ptr<NgxCoreHost>& core) const {
+ return enabled_ && core && core_ == core;
+}
+}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index d05528a4..0c04fefb 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -39,6 +39,7 @@
#include "veyra/ngx/VideoSrBackend.h"
#include "veyra/ngx/TrueHdrBackend.h"
#include "veyra/ngx/NgxCoreHost.h"
+#include "veyra/ngx/NgxCoreCache.h"
#include "veyra/ngx/NgxParameters.h"
#include "veyra/ngx/NvOfSession.h"
#include "veyra/guidance/AmdOpticalFlow.h"
@@ -98,9 +99,11 @@ uint8_t packedIngressLuma(const uint8_t* data,ptrdiff_t linesize,uint32_t code,u
} // namespace
-EnhanceGraph::EnhanceGraph(gfx::D3D12DeviceContext& context, gfx::CommandSlotRing& ring)
+EnhanceGraph::EnhanceGraph(gfx::D3D12DeviceContext& context, gfx::CommandSlotRing& ring,
+ ngx::NgxCoreCache* coreCache)
: context_(context)
, ring_(ring)
+ , coreCache_(coreCache)
{
}
@@ -502,6 +505,7 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
initialized_ = true;
failedBackend_=engine::FailedBackend::None;
+ if(coreCache_)coreCache_->publish(coreHost_);
veyra::log::info("graph", std::format("initialized src={}x{} work={}x{} sr={} nr={} fg={} nvof={}",
srcW_, srcH_, workW_, workH_, srEnabled_ ? 1 : 0, nrEnabled_ ? 1 : 0,
fgEnabled_ ? 1 : 0, (nvof_ && nvof_->initialized()) ? 1 : 0));
@@ -1048,6 +1052,19 @@ bool EnhanceGraph::initNgxFeatures()
{
Status st = Status::Ok;
failedBackend_=engine::FailedBackend::NgxCore;
+ if(coreCache_){
+ ngx::NgxCoreCache::Key key;
+ key.device=context_.device();
+ key.runtimeDirectory=std::filesystem::absolute(desc_.runtimeAbsPath).lexically_normal().wstring();
+ key.nrRuntime=int(engine::currentNrRuntime(desc_.nrRuntime));
+ key.frameGeneration=desc_.enableFg;
+ key.fgBackend=int(desc_.frameGenerationBackend);key.fgMultiplier=desc_.fgMultiplier;
+ // Patched driver/provider state currently belongs to the graph. Keep
+ // its complete init/shutdown contract even when FG is temporarily off.
+ const bool enabled=!ngx::FgCompatibilitySession::requested(context_.adapter().vendorId,context_.adapter().deviceId)&&
+ !GetEnvironmentVariableW(L"VEYRA_TEST_DISABLE_NGX_CORE_REUSE",nullptr,0);
+ if(!coreCache_->prepare(std::move(key),enabled))return false;
+ }
if(desc_.convertVideoHdr()&&(desc_.noNgx||desc_.noFeatures)){failedBackend_=engine::FailedBackend::VideoHdr;return false;}
if ((desc_.noNgx && !lmxxfNr_) || desc_.noFeatures || (!nrEnabled_&&!srEnabled_&&!fgEnabled_&&!desc_.convertVideoHdr())) {
veyra::log::info("graph", "NGX core/features skipped by disabled-feature configuration");
@@ -1110,8 +1127,10 @@ bool EnhanceGraph::initNgxFeatures()
}
failedBackend_=engine::FailedBackend::NgxCore;
- coreHost_ = std::make_unique<ngx::NgxCoreHost>();
+ coreHost_ = coreCache_?coreCache_->borrow():nullptr;
Status st = Status::Ok;
+ if(!coreHost_){
+ coreHost_ = std::make_shared<ngx::NgxCoreHost>();
if(fgCompatibility_&&!fgCompatibility_->beginInitialization())return false;
const bool initialized=coreHost_->initialize(context_.device(), desc_.runtimeAbsPath.c_str(),
projectId.c_str(), engineVersion.c_str(), st);
@@ -1119,6 +1138,7 @@ bool EnhanceGraph::initNgxFeatures()
if (!initialized || !initRestored) {
return false;
}
+ }
if(!vfgBackend_){fgCapsAvailable_ = false;fgMultiFrameMax_ = 0;}
if (fgEnabled_ && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) {
@@ -3059,7 +3079,7 @@ ID3D12Resource* EnhanceGraph::generatedFrameResource(uint32_t slot) const
// ---------------------------------------------------------------------------
void EnhanceGraph::shutdown()
{
- if (!initialized_ && !nrAdapter_ && !nvof_ && !srcRgba_) return;
+ if (!initialized_ && !coreHost_ && !nrAdapter_ && !nvof_ && !srcRgba_) return;
for(unsigned i=0;i<2;++i)if(presentationFences_[i]){
const HRESULT hr=context_.directQueue()->Wait(presentationFences_[i].Get(),presentationValues_[i]);
if(FAILED(hr))veyra::log::error("graph",std::format("presentation teardown wait hr=0x{:X}",unsigned(hr)));
@@ -3134,7 +3154,18 @@ void EnhanceGraph::shutdown()
nrAdapter_->restoreCallerCompatibility();
nrAdapter_->unload();
}
- if (coreHost_) coreHost_->shutdown();
+ const bool retainCore=coreCache_&&coreCache_->owns(coreHost_)&&initialized_&&
+ failedBackend_==engine::FailedBackend::None&&SUCCEEDED(context_.device()->GetDeviceRemovedReason())&&
+ coreHost_->liveParameterBlockCount()==0;
+ if(retainCore){
+ log::info("ngx-core-cache","event=retain liveParameters=0 featuresReleased=1");
+ }else if(coreHost_){
+ // Remove the graph's borrow before asking the session to close. On a
+ // failed graph it must not survive for a later rebuild.
+ if(coreCache_&&coreCache_->owns(coreHost_)){
+ coreHost_.reset();(void)coreCache_->close("graph-failure-or-device-removed");
+ }else coreHost_->shutdown();
+ }
// Restore the DLSS-G runtime image only after the NGX core released the
// feature (the unlock is process memory only; the file on disk is untouched).
fgCompatibility_.reset();
diff --git a/tests/perf/NrRebuildBenchmark.cpp b/tests/perf/NrRebuildBenchmark.cpp
index 2302077a..535512ec 100644
--- a/tests/perf/NrRebuildBenchmark.cpp
+++ b/tests/perf/NrRebuildBenchmark.cpp
@@ -7,6 +7,9 @@
#include "veyra/gfx/CommandSlotRing.h"
#include "veyra/RuntimePaths.h"
#include "veyra/Log.h"
+#ifdef VEYRA_HAS_NGX_CORE_CACHE
+#include "veyra/ngx/NgxCoreCache.h"
+#endif
#include <dxgi1_4.h>
#include <d3d12sdklayers.h>
#include <chrono>
@@ -36,7 +39,12 @@ int wmain(int argc,wchar_t** argv){
Microsoft::WRL::ComPtr<IDXGIFactory4> factory;Microsoft::WRL::ComPtr<IDXGIAdapter3> adapter;
if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))||FAILED(factory->EnumAdapterByLuid(ctx.device()->GetAdapterLuid(),IID_PPV_ARGS(&adapter))))return 2;
auto usage=[&](){DXGI_QUERY_VIDEO_MEMORY_INFO info{};return SUCCEEDED(adapter->QueryVideoMemoryInfo(0,DXGI_MEMORY_SEGMENT_GROUP_LOCAL,&info))?info.CurrentUsage:UINT64_MAX;};
+#ifdef VEYRA_HAS_NGX_CORE_CACHE
+ ngx::NgxCoreCache coreCache;
+ pipeline::EnhanceGraph graph(ctx,ring,&coreCache);
+#else
pipeline::EnhanceGraph graph(ctx,ring);
+#endif
std::ofstream csv(out/L"rebuild.csv");csv<<"cycle,nr,sr,layers,policy,destroyMs,createMs,totalMs,vramBefore,vramLive,vramAfter,nrEvaluations,srEvaluations,frameCount\n";
bool pass=true;
for(unsigned i=0;i<20&&pass;++i){
@@ -78,6 +86,9 @@ int wmain(int argc,wchar_t** argv){
std::cout<<"CYCLE i="<<i<<" createMs="<<created-destroyed<<" destroyMs="<<releaseEnd-releaseStart<<" pass="<<pass<<std::endl;
}
ring.drainQueue();graph.shutdown();media.close();
+#ifdef VEYRA_HAS_NGX_CORE_CACHE
+ if(!coreCache.close("test-final-close"))pass=false;
+#endif
Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;
if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;
for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){SIZE_T size=0;debug->GetMessage(i,nullptr,&size);