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: prepare owned GPU competition for measured priority decisions
Veyra Goal Agent4b9958778ee1
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 68a34c04..e2dd9b78 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1030,6 +1030,10 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_compile_features(veyra_paused_present_experiment PRIVATE cxx_std_20)target_compile_options(veyra_paused_present_experiment PRIVATE /utf-8)target_link_libraries(veyra_paused_present_experiment PRIVATE veyra_engine)+ add_executable(veyra_nr_gpu_competition_load tests/perf/NrGpuCompetitionLoad.cpp)+ target_compile_features(veyra_nr_gpu_competition_load PRIVATE cxx_std_20)+ target_compile_options(veyra_nr_gpu_competition_load PRIVATE /utf-8)+ target_link_libraries(veyra_nr_gpu_competition_load PRIVATE veyra_engine)add_executable(veyra_nr_core_cache_contract_tests tests/perf/NrCoreCacheContractTests.cpp)target_compile_features(veyra_nr_core_cache_contract_tests PRIVATE cxx_std_20)target_compile_options(veyra_nr_core_cache_contract_tests PRIVATE /utf-8)diff --git a/docs/PERF_3A_GPU_PRIORITY_2026-10-04.md b/docs/PERF_3A_GPU_PRIORITY_2026-10-04.mdnew file mode 100644index 00000000..a94effed--- /dev/null+++ b/docs/PERF_3A_GPU_PRIORITY_2026-10-04.md@@ -0,0 +1,7 @@+# 3a:进程GPU优先级竞争实验++前存档f5e7c47/checkpoint/perf-nr-3a-before-20261004。先用真实本进程GPU调度API实验,未确认收益前不加入产品默认和设置。对已封存5c产品EXE,启动时只用本轮Popen返回的子进程句柄设置Normal(2)/High(4)/Realtime(5),Set/Get NTSTATUS和实际读回class全部入日志。不提权、不改用户应用/全局驱动设置。依据:[微软SchedulingPriorityClass](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/d3dkmthk/ne-d3dkmthk-_d3dkmt_schedulingpriorityclass)、[SetProcessSchedulingPriorityClass](https://learn.microsoft.com/zh-cn/windows-hardware/drivers/ddi/d3dkmthk/nf-d3dkmthk-d3dkmtsetprocessschedulingpriorityclass)。++本轮拥有的竞争程序用实际产品Graph:M1首张自然输入、三层原生1080p NR/NVOF,源PTS/id继续推进,连续提交并等完成,30帧预热。完整NR求值数、设备/debug、每秒完成Graph吞吐CSV;此吞吐不是游戏或屏幕FPS。目标播放器M1/S3单NR+DLSS SR到4K,50秒;对方保持正常GPU优先级。三轮交错顺序Normal/High/Realtime、Realtime/Normal/High、High/Realtime/Normal;记录目标真实成功Present软件返回间隔P50/P95/P99/max、跳帧及GPU处理、对方同稳态时间窗吞吐、GPU频率/功耗/显存,避免只用播放器改善判断。++仅本轮竞争程序PID允许与播放器共存,其他测试/构建仍不得重叠;对方连续存活由句柄/退出码核验;各GPU进程最长120或270秒,driver不执行GPU命令。优先级只是提交调度改动,完整画面回归归入R0,不能用软件Present宣称物理显示节奏。结果待填。diff --git a/docs/PERF_EXECUTION_NR_2026-10-04.md b/docs/PERF_EXECUTION_NR_2026-10-04.mdindex af4ac1d1..fde189f1 100644--- a/docs/PERF_EXECUTION_NR_2026-10-04.md+++ b/docs/PERF_EXECUTION_NR_2026-10-04.md@@ -30,7 +30,7 @@| E3 | 真实来源精确重复比例 | completed-screen-awaiting-card | 真实WGC三阶段各60秒通过,静止99.932%/移动内容0.540%/窗口位置99.937%;PERF_E3_DUPLICATE_SOURCE;实卡待来源确认 || 1a | 精确重复帧整链复用 | rejected-unchanged-output | 自然同像素300帧×五组×三轮,A-A噪声0;NR/SR复用299帧不同;PERF_1A_DUPLICATE_REUSE;无生产改动 || 5a | 黑边检测与有效区域处理 | pending | 防暗场误裁,先测准确性与重建收益 |-| 3a | 进程GPU调度优先级 | pending | 只改本进程,有竞争负载的实际A/B |+| 3a | 进程GPU调度优先级 | in-progress | 九组交错Normal/High/Realtime,本轮三NR竞争Graph,Set/Get/P95/P99及对方吞吐;PERF_3A_GPU_PRIORITY || 2a | 跨重建保留NGX核心 | retained-pending-R0 | v2三轮A/B/B-off完整输出0差异;暖创建减少75.83/71.23/64.58/72.04%;真实UI及SDK拒绝路径通过;导出待R0 || 2c | 最近配置实例缓存 | pending | 有界预算/复用reset/压力回退 || 2d | 空闲预热 | pending | 首帧收益与开关关闭时显存 |diff --git a/scripts/perf/nr-matrix.py b/scripts/perf/nr-matrix.pyindex 1e86789a..96c4ada2 100644--- a/scripts/perf/nr-matrix.py+++ b/scripts/perf/nr-matrix.py@@ -46,23 +46,45 @@ def gpu_query():values = [v.strip() for v in p.stdout.strip().split(',')]return dict(zip(('name','driver','gpuPercent','memoryMiB','memoryTotalMiB','graphicsMHz','memoryMHz','powerW'), values))-def assert_gpu_tests_idle():+def assert_gpu_tests_idle(allowed_pids=()):# Timing must never overlap another owned GPU test. A future competition# test explicitly exempts only its own load process at its call site.prefix=str(BASE/'tests'/TASK).replace('\\','/').lower()+'/'+ allowed=set(allowed_pids)+ for pid in allowed:+ owned=psutil.Process(pid)+ exe=owned.exe().replace('\\','/').lower()+ assert exe.startswith(prefix) and Path(exe).name=='veyra_nr_gpu_competition_load.exe', 'Only this task competition fixture may overlap'active=[]for proc in psutil.process_iter(['pid','name','exe']):try:exe=(proc.info['exe'] or '').replace('\\','/').lower()- if exe.startswith(prefix) and (proc.info['name'] or '').lower().startswith('veyra_'):+ if proc.pid not in allowed and exe.startswith(prefix) and (proc.info['name'] or '').lower().startswith('veyra_'):active.append({'pid':proc.pid,'exe':exe})except psutil.Error:continueassert not active, f'Another owned GPU test is running: {active}'+def set_owned_gpu_priority(proc, priority):+ # Native API changes only the child handle returned by our own Popen.+ # No elevation, driver settings or other process priority changes.+ import ctypes+ from ctypes import wintypes+ gdi=ctypes.WinDLL('gdi32',use_last_error=True)+ get=gdi.D3DKMTGetProcessSchedulingPriorityClass+ get.argtypes=[wintypes.HANDLE,ctypes.POINTER(ctypes.c_int)];get.restype=wintypes.LONG+ set_value=gdi.D3DKMTSetProcessSchedulingPriorityClass+ set_value.argtypes=[wintypes.HANDLE,ctypes.c_int];set_value.restype=wintypes.LONG+ before=ctypes.c_int(-1);after=ctypes.c_int(-1)+ a=get(int(proc._handle),ctypes.byref(before));b=set_value(int(proc._handle),priority);c=get(int(proc._handle),ctypes.byref(after))+ return {'pid':proc.pid,'beforeStatus':hex(a&0xffffffff),'beforeClass':before.value,+ 'setStatus':hex(b&0xffffffff),'afterStatus':hex(c&0xffffffff),'afterClass':after.value,+ 'applied':a==b==c==0 and after.value==priority}+def stage(variant):path = BASE / 'tests' / TASK / ('app-' + variant)if path.exists():+ assert digest(path/'veyra_qml_ui.exe')==digest(BUILD/variant/'veyra_qml_ui.exe'), 'Existing stage executable is stale; use a fresh variant'return pathshutil.copytree(PACKAGE, path, copy_function=copy_dependency,ignore=shutil.ignore_patterns('*.log', 'logs', 'user-data-2.0.0', '*.dmp'))@@ -81,8 +103,8 @@ def stage(variant):main.write_text(text, encoding='utf-8')return path-def run(variant, material, setting, label, seconds):- assert_gpu_tests_idle()+def run(variant, material, setting, label, seconds, gpuPriority=None, allowedGpuPids=()):+ assert_gpu_tests_idle(allowedGpuPids)subprocess.run([sys.executable, '-B', str(ROOT / 'scripts/perf/nr-control.py'), 'guard'], check=True)app = stage(variant)media = SOURCES.get(material, BASE / 'tests/perf-matrix/media' / (material + '.mkv'))@@ -109,12 +131,14 @@ def run(variant, material, setting, label, seconds):'runtimeSha256': digest(app / 'runtime/experimental/nvngx_dlssnr.dll'),'beforeGpu': before, 'secondsRequested': seconds, 'measurement': 'GPU timestamps and CPU submission, not display scanout','sourceCommit': subprocess.check_output(['git', '-C', str(ROOT), 'rev-parse', 'HEAD']).decode().strip()}- start = time.monotonic()+ start = time.monotonic();receipt['startUtc']=time.time()with (logs / 'console.log').open('xb') as out:proc = subprocess.Popen([str(app / 'veyra_qml_ui.exe'), '--data-dir', str(profile),'--page', 'pro', '--size', '1280x800', '--exit-after', '270000'],cwd=app, env=env, stdout=out, stderr=subprocess.STDOUT)receipt['pid'] = proc.pid+ if gpuPriority is not None:+ receipt['gpuPriority']=set_owned_gpu_priority(proc,gpuPriority)meter = psutil.Process(proc.pid); meter.cpu_percent(None)samples = []try:diff --git a/scripts/perf/nr-priority.py b/scripts/perf/nr-priority.pynew file mode 100644index 00000000..400e3819--- /dev/null+++ b/scripts/perf/nr-priority.py@@ -0,0 +1,79 @@+"""Controlled, intentionally concurrent GPU competition; only owned processes."""+from pathlib import Path+import ctypes+from ctypes import wintypes+import csv+import importlib.util+import json+import os+import re+import shutil+import statistics+import subprocess+import sys+import time+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='perf-nr-20261004'+spec=importlib.util.spec_from_file_location('matrix',ROOT/'scripts/perf/nr-matrix.py');matrix=importlib.util.module_from_spec(spec);spec.loader.exec_module(matrix)+gdi=ctypes.WinDLL('gdi32',use_last_error=True)+get=gdi.D3DKMTGetProcessSchedulingPriorityClass;get.argtypes=[wintypes.HANDLE,ctypes.POINTER(ctypes.c_int)];get.restype=wintypes.LONG+set_priority=gdi.D3DKMTSetProcessSchedulingPriorityClass;set_priority.argtypes=[wintypes.HANDLE,ctypes.c_int];set_priority.restype=wintypes.LONG+def set_owned(proc,priority):+ before=ctypes.c_int(-1);after=ctypes.c_int(-1)+ a=get(int(proc._handle),ctypes.byref(before));b=set_priority(int(proc._handle),priority);c=get(int(proc._handle),ctypes.byref(after))+ return {'pid':proc.pid,'beforeStatus':hex(a&0xffffffff),'beforeClass':before.value,'setStatus':hex(b&0xffffffff),'afterStatus':hex(c&0xffffffff),'afterClass':after.value,'applied':a==b==c==0 and after.value==priority}+variant,label=sys.argv[1:3];matrix.assert_gpu_tests_idle()+app=BASE/'tests'/TASK/(label+'-load-app');assert not app.exists()+shutil.copytree(BASE/'test-packages'/TASK/'Veyra-2.0.3-perf-baseline-A-NVIDIA-win64-portable',app,copy_function=matrix.copy_dependency)+shutil.copy2(BASE/'build'/TASK/variant/'veyra_nr_gpu_competition_load.exe',app/'veyra_nr_gpu_competition_load.exe')+matrix.stage(variant);results=[]+# Counterbalanced order avoids using an increasing GPU temperature as a benefit.+orders=[('normal','high','realtime'),('realtime','normal','high'),('high','realtime','normal')]+classes={'normal':2,'high':4,'realtime':5}+for repeat,order in enumerate(orders,1):+ for name in order:+ matrix.assert_gpu_tests_idle();run_label=f'{label}-{name}-r{repeat}'+ out=BASE/'logs'/TASK/(run_label+'-load');tmp=BASE/'tmp'/TASK/(run_label+'-load')+ out.mkdir(parents=True,exist_ok=False);tmp.mkdir(parents=True,exist_ok=False)+ env=os.environ.copy()+ for key in tuple(env):+ if key.upper().startswith('VEYRA_'):env.pop(key)+ env.update(TEMP=str(tmp),TMP=str(tmp))+ command=[str(app/'veyra_nr_gpu_competition_load.exe'),str(matrix.SOURCES['M1']),str(out),'100']+ print('LOAD_START',run_label,flush=True);started=time.monotonic()+ with (out/'console.log').open('xb') as console:+ load=subprocess.Popen(command,cwd=app,env=env,stdout=console,stderr=subprocess.STDOUT)+ priority=set_owned(load,2)+ try:+ while time.monotonic()-started<40 and load.poll() is None:+ if 'LOAD_READY' in (out/'console.log').read_text(encoding='utf-8',errors='replace'):break+ time.sleep(.25)+ assert load.poll() is None and 'LOAD_READY' in (out/'console.log').read_text(encoding='utf-8',errors='replace'),'competition load did not start'+ target_begin=time.monotonic()+ matrix.run(variant,'M1','S3',run_label,50,gpuPriority=classes[name],allowedGpuPids=(load.pid,))+ target_end=time.monotonic()+ assert load.poll() is None,'competition load ended before target'+ (out/'stop').write_text('owned fixture completed',encoding='utf-8');rc=load.wait(timeout=20)+ finally:+ if load.poll() is None:load.kill();load.wait(timeout=8)+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace');assert rc==0 and 'LOAD_RESULT pass=1' in text,text[-4000:]+ target=BASE/'logs'/TASK/run_label;receipt=json.loads((target/'result.json').read_text(encoding='utf-8'))+ log=(target/'player.log').read_text(encoding='utf-8',errors='replace');timestamps=[]+ for line in log.splitlines():+ if '[submit]' not in line:continue+ fields=dict(re.findall(r'(\w+)=(-?\d+)',line));pts=int(fields.get('pts100ns','-1'))+ if 100000000<=pts<=480000000:timestamps.append(int(fields['host100ns']))+ intervals=[(b-a)/10000 for a,b in zip(timestamps,timestamps[1:])];assert len(intervals)>100+ def percentile(values,p):+ v=sorted(values);return v[min(len(v)-1,int(len(v)*p))]+ with (out/'completed.csv').open(encoding='utf-8') as f:rows=list(csv.DictReader(f))+ ready_utc=int(re.search(r'NR_PERF_READY (\d+)',log).group(1))/1000+ stable=[float(row['completedFps']) for row in rows if ready_utc+10<float(row['wallUtc'])<ready_utc+45];assert len(stable)>15+ result={'label':run_label,'priorityRequested':name,'loadPriority':priority,'targetPriority':receipt['gpuPriority'],+ 'loadExeSha256':matrix.digest(app/'veyra_nr_gpu_competition_load.exe'),'targetExeSha256':receipt['exeSha256'],+ 'loadCompletedFpsMedian':statistics.median(stable),'loadCompletedFpsRange':[min(stable),max(stable)],+ 'presentIntervalsMs':{'p50':percentile(intervals,.5),'p95':percentile(intervals,.95),'p99':percentile(intervals,.99),'max':max(intervals),'count':len(intervals)},+ 'targetSummary':receipt['summary'],'loadRawLog':str(out),'targetRawLog':str(target),+ 'passed':receipt['passed'] and priority['applied'] and receipt['gpuPriority']['applied'],'measurement':'Actual successful Present software return intervals; load completed NR graphs; neither is display scanout'}+ (out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8');results.append(result)+ print('PRIORITY_RESULT',json.dumps({k:result[k] for k in ('label','targetPriority','loadCompletedFpsMedian','presentIntervalsMs','passed')},ensure_ascii=False),flush=True)+with (BASE/'logs'/TASK/(label+'-summary.json')).open('x',encoding='utf-8') as f:json.dump(results,f,ensure_ascii=False,indent=2)diff --git a/tests/perf/NrGpuCompetitionLoad.cpp b/tests/perf/NrGpuCompetitionLoad.cppnew file mode 100644index 00000000..f809550e--- /dev/null+++ b/tests/perf/NrGpuCompetitionLoad.cpp@@ -0,0 +1,66 @@+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/engine/GraphDescription.h"+#include "veyra/engine/EffectChain.h"+#include "veyra/source/MediaFileSource.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/RuntimePaths.h"+#include "veyra/Log.h"+#include <d3d12sdklayers.h>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <chrono>+#include <iomanip>+#include <vector>++// Bounded competition fixture. All GPU load is the actual product graph;+// counters describe completed work, never display refresh or a game FPS.+int wmain(int argc,wchar_t** argv){+ using namespace veyra;using Clock=std::chrono::steady_clock;+ if(argc!=4)return 2;const unsigned seconds=std::stoul(argv[3]);+ if(seconds<5||seconds>120)return 2;+ const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);+ Logger::instance().openFile((out/L"engine.log").wstring());+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;+ gfx::DeviceContextDesc device;device.enableDebugLayer=true;+ if(!ctx.initialize(device,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,status))return 2;+ source::MediaFileSource media;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;+ if(!media.open(open))return 2;pipeline::FramePacket packet;const AVFrame* input=nullptr;+ if(media.read(packet,&input)!=source::SourceReadStatus::Frame)return 2;+ engine::EffectChain chain;chain.nodeCount=3;+ for(unsigned i=0;i<3;++i){chain.nodes[i].type=engine::EffectType::NrEnhance;chain.nodes[i].enabled=true;+ chain.nodes[i].nr.temporal=false;chain.nodes[i].nr.sizePolicy=pipeline::NrSizePolicy::Native;}+ engine::EnhancementSettings settings;engine::fromChain(chain,settings);settings.multiplier=1;+ engine::StageRequest request;request.width=media.info().width;request.height=media.info().height;request.nr=true;+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);+ desc.enableNvofStandalone=true;desc.enableFg=false;desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ pipeline::EnhanceGraph graph(ctx,ring);if(!graph.initialize(desc)||!graph.createViews())return 2;+ bool pass=true;unsigned frames=0;double totalMs=0;+ for(unsigned i=0;i<30&&pass;++i){pipeline::EnhanceGraph::FrameOutputs output;+ pass=graph.process(input,i*1000.0/60,i==0,output,i+1,&packet.colorInfo)&&ring.waitIdle();}+ if(!pass)return 2;+ std::ofstream csv(out/L"completed.csv");csv<<"elapsedSeconds,frames,completedFps,nrEvaluations,cpuProcessWithWaitMs,wallUtc\n";csv<<std::setprecision(12);+ std::cout<<"LOAD_READY"<<std::endl;+ const auto start=Clock::now();auto last=start;unsigned previous=0;+ while(pass&&std::chrono::duration<double>(Clock::now()-start).count()<seconds&&!std::filesystem::exists(out/L"stop")){+ pipeline::EnhanceGraph::FrameOutputs output;const auto begin=Clock::now();+ pass=graph.process(input,(frames+30)*1000.0/60,false,output,frames+31,&packet.colorInfo)&&ring.waitIdle();+ if(!pass)break;++frames;totalMs+=std::chrono::duration<double,std::milli>(Clock::now()-begin).count();+ const auto now=Clock::now();const double dt=std::chrono::duration<double>(now-last).count();+ if(dt>=1){csv<<std::chrono::duration<double>(now-start).count()<<','<<frames<<','<<(frames-previous)/dt<<','<<graph.metrics().nrEvaluateCount<<','<<totalMs<<','<<std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch()).count()<<'\n';csv.flush();last=now;previous=frames;}+ }+ const double elapsed=std::chrono::duration<double>(Clock::now()-start).count();const auto metrics=graph.metrics();+ pass=pass&&metrics.nrEvaluateCount==uint64_t(frames+30)*3;+ ring.drainQueue();graph.shutdown();media.close();+ 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);+ std::vector<unsigned char> data(size);auto* m=reinterpret_cast<D3D12_MESSAGE*>(data.data());+ if(FAILED(debug->GetMessage(i,m,&size)))return 2;+ if(m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<m->pDescription<<std::endl;}}+ const auto removed=ctx.device()->GetDeviceRemovedReason();pass=pass&&errors==0&&SUCCEEDED(removed);+ std::cout<<"LOAD_RESULT pass="<<pass<<" frames="<<frames<<" seconds="<<elapsed<<" completedFps="<<frames/elapsed+ <<" nrEvaluations="<<metrics.nrEvaluateCount<<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;+ return pass?0:1;+}