bench.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. //! A frame's worth of one-record indirect draws on the host GPU, clamped one
  2. //! at a time and in windows, recorded as `main` does (the scratch buffer
  3. //! back to the common state after every execution, the clamp charging the
  4. //! budget record by record) and as this tree does (readable until the next
  5. //! clamp, one charge per group). Ignored by default; run it with
  6. //! `cargo test -p victory-gpu --release --lib indirect::bench -- --ignored --nocapture`.
  7. //! It needs no title files: the draws are tiny triangles of ours.
  8. use super::*;
  9. use windows::Win32::Foundation::RECT;
  10. use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC};
  11. use windows::Win32::Graphics::Dxgi::{
  12. CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIFactory4,
  13. };
  14. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  15. use windows::core::{Interface, PCSTR};
  16. /// Draws a frame (the title's gameplay frames hold about 3,200 indirect
  17. /// executions, #107), records a window holds, and how far apart the
  18. /// records are (the title keeps them 32 bytes apart).
  19. const DRAWS: u32 = 3200;
  20. const WINDOW: u32 = 32;
  21. const STEP: u32 = 32;
  22. const RUNS: usize = 9;
  23. const SHADERS: &str = r#"
  24. #define RS "RootFlags(0)"
  25. [RootSignature(RS)]
  26. float4 vs(uint v : SV_VertexID, uint i : SV_InstanceID) : SV_Position {
  27. float2 p = float2((v & 1) ? 0.05 : 0.0, (v & 2) ? 0.05 : 0.0) - 0.5;
  28. return float4(p, 0.5, 1);
  29. }
  30. float4 ps() : SV_Target { return float4(1, 0.5, 0.25, 1); }
  31. "#;
  32. fn compile(entry: &str, target: &str) -> Vec<u8> {
  33. let entry = std::ffi::CString::new(entry).unwrap();
  34. let target = std::ffi::CString::new(target).unwrap();
  35. let mut code: Option<ID3DBlob> = None;
  36. // SAFETY: the source and names outlive the call.
  37. unsafe {
  38. D3DCompile(
  39. SHADERS.as_ptr().cast(),
  40. SHADERS.len(),
  41. s!("bench"),
  42. None,
  43. None,
  44. PCSTR(entry.as_ptr().cast()),
  45. PCSTR(target.as_ptr().cast()),
  46. 0,
  47. 0,
  48. &mut code,
  49. None,
  50. )
  51. .unwrap();
  52. let code = code.unwrap();
  53. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  54. .to_vec()
  55. }
  56. }
  57. /// The clamp as it was before it charged the budget once per group
  58. /// (record by record, every thread racing for the budget word), kept
  59. /// here to measure against.
  60. const OLD_SOURCE: &str = r#"
  61. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
  62. cbuffer Record : register(b0) {
  63. uint kind;
  64. uint stride;
  65. uint records;
  66. uint args_offset;
  67. // Bit 0: a count buffer bounds the records. Bit 1: the records are a
  68. // window clamped ahead of their draws: one that asks for more than can
  69. // run is left empty and costs nothing.
  70. uint has_count;
  71. uint count_offset;
  72. };
  73. ByteAddressBuffer src_args : register(t0);
  74. ByteAddressBuffer count_buf : register(t1);
  75. RWByteAddressBuffer dst_args : register(u0);
  76. // The list's work so far (vertex instances, threads): past the budget,
  77. // records run empty.
  78. RWByteAddressBuffer budget : register(u1);
  79. static const uint BUDGET = 1u << 27;
  80. // Groups of one dispatch; more run empty.
  81. static const uint GROUPS = 1u << 20;
  82. [RootSignature(RS)]
  83. [numthreads(64, 1, 1)]
  84. void main(uint3 id : SV_DispatchThreadID) {
  85. uint eff_count = records;
  86. bool ahead = (has_count & 2u) != 0;
  87. if ((has_count & 1u) != 0) {
  88. eff_count = min(eff_count, count_buf.Load(count_offset));
  89. }
  90. if (id.x >= eff_count) return;
  91. uint src_at = args_offset + id.x * stride;
  92. uint dst_at = id.x * stride;
  93. uint cost;
  94. uint2 draw_counts = uint2(0, 0);
  95. uint3 groups = uint3(0, 0, 0);
  96. if (kind <= 1) {
  97. // Draws: vertex or index count, then instances.
  98. uint2 asked = src_args.Load2(src_at);
  99. if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) {
  100. asked = uint2(0, 0);
  101. }
  102. uint count = min(asked.x, 1u << 24);
  103. uint instances = min(asked.y, (1u << 26) / max(count, 1u));
  104. cost = count * instances;
  105. draw_counts = uint2(count, instances);
  106. } else if (kind == 2) {
  107. uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u));
  108. // x * y fits 32 bits; the whole count may not.
  109. if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
  110. g = uint3(0, 0, 0);
  111. }
  112. cost = g.x * g.y * g.z * 64u;
  113. groups = g;
  114. } else {
  115. // Mesh dispatches: the console's are one-dimensional.
  116. uint3 g = src_args.Load3(src_at);
  117. // Ahead of its draw, a record over the most a dispatch runs is a
  118. // slot the title has not filled (the title leaves all
  119. // ones there): empty, and not counted below either.
  120. if (ahead && g.x > 65535u) {
  121. g = uint3(0, 0, 0);
  122. }
  123. // Diagnostics, in the budget buffer's next words: the largest
  124. // group count a mesh record asked for, and the groups asked in all.
  125. uint was;
  126. budget.InterlockedMax(4, g.x, was);
  127. budget.InterlockedAdd(8, min(g.x, 1u << 24), was);
  128. g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
  129. cost = g.x * g.y * g.z * 128u;
  130. groups = g;
  131. }
  132. bool over = false;
  133. if (cost > 0) {
  134. uint before;
  135. budget.InterlockedOr(0, 0, before);
  136. [allow_uav_condition]
  137. while (before < BUDGET) {
  138. uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost);
  139. uint prev;
  140. budget.InterlockedCompareExchange(0, before, next, prev);
  141. if (prev == before) break;
  142. before = prev;
  143. }
  144. over = before >= BUDGET || BUDGET - before < cost;
  145. }
  146. if (kind <= 1) {
  147. if (over) {
  148. draw_counts = uint2(0, 0);
  149. }
  150. dst_args.Store2(dst_at, draw_counts);
  151. for (uint off = 8; off < stride; off += 4) {
  152. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  153. }
  154. } else {
  155. if (over) {
  156. groups = uint3(0, 0, 0);
  157. }
  158. dst_args.Store3(dst_at, groups);
  159. for (uint off = 12; off < stride; off += 4) {
  160. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  161. }
  162. }
  163. }
  164. "#;
  165. #[derive(Clone, Copy, PartialEq, Eq, Debug)]
  166. enum Barriers {
  167. /// Back to the common state after every execution (as before).
  168. Old,
  169. /// Readable as arguments until the next clamp, common at the end.
  170. New,
  171. }
  172. #[test]
  173. #[ignore = "benchmark; see the module notes"]
  174. fn bench_indirect_draw_barriers() {
  175. let Some(host) = super::host() else {
  176. eprintln!("no host GPU");
  177. return;
  178. };
  179. let device = &host.device;
  180. let clamps = [
  181. make_from(device, OLD_SOURCE).expect("the old clamp"),
  182. make_for(device).expect("the clamp"),
  183. ];
  184. // SAFETY: plain D3D12 object creation with valid descriptions; the
  185. // objects outlive every list recorded and run below.
  186. unsafe {
  187. let adapter = {
  188. let luid = device.GetAdapterLuid();
  189. CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  190. .and_then(|f| {
  191. f.EnumAdapterByLuid::<windows::Win32::Graphics::Dxgi::IDXGIAdapter1>(luid)
  192. })
  193. .and_then(|a| a.GetDesc1())
  194. .map(|d| {
  195. String::from_utf16_lossy(&d.Description)
  196. .trim_end_matches('\0')
  197. .to_owned()
  198. })
  199. .unwrap_or_else(|_| "an unnamed adapter".to_owned())
  200. };
  201. let queue: ID3D12CommandQueue = device
  202. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  203. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  204. ..Default::default()
  205. })
  206. .unwrap();
  207. let allocator: ID3D12CommandAllocator = device
  208. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)
  209. .unwrap();
  210. let list: ID3D12GraphicsCommandList = device
  211. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  212. .unwrap();
  213. list.Close().unwrap();
  214. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
  215. let event = CreateEventW(None, false, false, None).unwrap();
  216. let frequency = queue.GetTimestampFrequency().unwrap() as f64;
  217. // The pipeline: tiny triangles into a small target.
  218. let (vs, ps) = (compile("vs", "vs_5_1"), compile("ps", "ps_5_1"));
  219. let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap();
  220. let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  221. pRootSignature: std::mem::transmute_copy(&root),
  222. VS: D3D12_SHADER_BYTECODE {
  223. pShaderBytecode: vs.as_ptr().cast(),
  224. BytecodeLength: vs.len(),
  225. },
  226. PS: D3D12_SHADER_BYTECODE {
  227. pShaderBytecode: ps.as_ptr().cast(),
  228. BytecodeLength: ps.len(),
  229. },
  230. SampleMask: u32::MAX,
  231. RasterizerState: D3D12_RASTERIZER_DESC {
  232. FillMode: D3D12_FILL_MODE_SOLID,
  233. CullMode: D3D12_CULL_MODE_NONE,
  234. DepthClipEnable: true.into(),
  235. ..Default::default()
  236. },
  237. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  238. NumRenderTargets: 1,
  239. SampleDesc: DXGI_SAMPLE_DESC {
  240. Count: 1,
  241. Quality: 0,
  242. },
  243. ..Default::default()
  244. };
  245. desc.BlendState.RenderTarget[0].RenderTargetWriteMask =
  246. D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8;
  247. desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  248. let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
  249. let target_desc = D3D12_RESOURCE_DESC {
  250. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  251. Width: 256,
  252. Height: 256,
  253. DepthOrArraySize: 1,
  254. MipLevels: 1,
  255. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  256. SampleDesc: DXGI_SAMPLE_DESC {
  257. Count: 1,
  258. Quality: 0,
  259. },
  260. Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
  261. ..Default::default()
  262. };
  263. let mut target: Option<ID3D12Resource> = None;
  264. device
  265. .CreateCommittedResource(
  266. &D3D12_HEAP_PROPERTIES {
  267. Type: D3D12_HEAP_TYPE_DEFAULT,
  268. ..Default::default()
  269. },
  270. D3D12_HEAP_FLAG_NONE,
  271. &target_desc,
  272. D3D12_RESOURCE_STATE_RENDER_TARGET,
  273. None,
  274. &mut target,
  275. )
  276. .unwrap();
  277. let target = target.unwrap();
  278. let rtvs: ID3D12DescriptorHeap = device
  279. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  280. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  281. NumDescriptors: 1,
  282. ..Default::default()
  283. })
  284. .unwrap();
  285. let rtv = rtvs.GetCPUDescriptorHandleForHeapStart();
  286. device.CreateRenderTargetView(&target, None, rtv);
  287. // The title's records: three vertices, one instance, 32 bytes apart.
  288. let (src, src_ptr) = host.shared_buffer(u64::from(DRAWS * STEP)).unwrap();
  289. for i in 0..DRAWS as usize {
  290. let words = [3u32, 1, 0, 0];
  291. std::ptr::copy_nonoverlapping(
  292. words.as_ptr().cast::<u8>(),
  293. src_ptr.add(i * STEP as usize),
  294. 16,
  295. );
  296. }
  297. let (budget, budget_ptr) = host.shared_buffer(256).unwrap();
  298. let budget_gpu = budget.GetGPUVirtualAddress();
  299. // The same words in the card's own memory (zeroed when made; the
  300. // runs below charge far less than the budget).
  301. let card_budget = host.uav_buffer(256).unwrap();
  302. let card_budget_gpu = card_budget.GetGPUVirtualAddress();
  303. let scratch = host
  304. .uav_buffer(u64::from(WINDOW * STEP).max(64 << 10))
  305. .unwrap();
  306. let signature = {
  307. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  308. Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW,
  309. ..Default::default()
  310. };
  311. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  312. ByteStride: 16,
  313. NumArgumentDescs: 1,
  314. pArgumentDescs: &arg,
  315. NodeMask: 0,
  316. };
  317. let mut sig: Option<ID3D12CommandSignature> = None;
  318. device
  319. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  320. .unwrap();
  321. sig.unwrap()
  322. };
  323. let stamps: ID3D12QueryHeap = {
  324. let mut heap: Option<ID3D12QueryHeap> = None;
  325. device
  326. .CreateQueryHeap(
  327. &D3D12_QUERY_HEAP_DESC {
  328. Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
  329. Count: 2,
  330. NodeMask: 0,
  331. },
  332. &mut heap,
  333. )
  334. .unwrap();
  335. heap.unwrap()
  336. };
  337. let mut back: Option<ID3D12Resource> = None;
  338. device
  339. .CreateCommittedResource(
  340. &D3D12_HEAP_PROPERTIES {
  341. Type: D3D12_HEAP_TYPE_READBACK,
  342. ..Default::default()
  343. },
  344. D3D12_HEAP_FLAG_NONE,
  345. &D3D12_RESOURCE_DESC {
  346. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  347. Width: 16,
  348. Height: 1,
  349. DepthOrArraySize: 1,
  350. MipLevels: 1,
  351. SampleDesc: DXGI_SAMPLE_DESC {
  352. Count: 1,
  353. Quality: 0,
  354. },
  355. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  356. ..Default::default()
  357. },
  358. D3D12_RESOURCE_STATE_COPY_DEST,
  359. None,
  360. &mut back,
  361. )
  362. .unwrap();
  363. let back = back.unwrap();
  364. let mut submitted = 0u64;
  365. // One frame's lists: GPU ms (timestamps around the list), CPU ms
  366. // recording it, ms from submission to the end of its run.
  367. let mut frame = |barriers: Barriers, clamp: &Clamp, window: u32, card: bool| -> [f64; 3] {
  368. allocator.Reset().unwrap();
  369. list.Reset(&allocator, None).unwrap();
  370. let recording = std::time::Instant::now();
  371. list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0);
  372. list.OMSetRenderTargets(1, Some(&rtv), false, None);
  373. list.RSSetViewports(&[D3D12_VIEWPORT {
  374. Width: 256.0,
  375. Height: 256.0,
  376. MaxDepth: 1.0,
  377. ..Default::default()
  378. }]);
  379. list.RSSetScissorRects(&[RECT {
  380. left: 0,
  381. top: 0,
  382. right: 256,
  383. bottom: 256,
  384. }]);
  385. list.IASetPrimitiveTopology(
  386. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
  387. );
  388. list.SetGraphicsRootSignature(&root);
  389. let mut state = D3D12_RESOURCE_STATE_COMMON;
  390. for first in (0..DRAWS).step_by(window as usize) {
  391. let records = window.min(DRAWS - first);
  392. assert!(record_clamp_as(
  393. clamp,
  394. &list,
  395. (&scratch, state),
  396. if card { card_budget_gpu } else { budget_gpu },
  397. (&src, u64::from(first * STEP)),
  398. None,
  399. (0, STEP, records),
  400. window > 1,
  401. ));
  402. state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  403. list.SetPipelineState(&pso);
  404. for k in 0..records {
  405. list.ExecuteIndirect(&signature, 1, &scratch, u64::from(k * STEP), None, 0);
  406. if barriers == Barriers::Old {
  407. list.ResourceBarrier(&[transition(
  408. &scratch,
  409. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  410. D3D12_RESOURCE_STATE_COMMON,
  411. )]);
  412. state = D3D12_RESOURCE_STATE_COMMON;
  413. }
  414. }
  415. }
  416. if state != D3D12_RESOURCE_STATE_COMMON {
  417. list.ResourceBarrier(&[transition(&scratch, state, D3D12_RESOURCE_STATE_COMMON)]);
  418. }
  419. list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1);
  420. list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &back, 0);
  421. list.Close().unwrap();
  422. let recorded = recording.elapsed().as_secs_f64() * 1e3;
  423. let running = std::time::Instant::now();
  424. queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())]);
  425. submitted += 1;
  426. queue.Signal(&fence, submitted).unwrap();
  427. fence.SetEventOnCompletion(submitted, event).unwrap();
  428. WaitForSingleObject(event, INFINITE);
  429. let ran = running.elapsed().as_secs_f64() * 1e3;
  430. let mut data = std::ptr::null_mut();
  431. back.Map(0, None, Some(&mut data)).unwrap();
  432. let t = std::slice::from_raw_parts(data.cast::<u64>(), 2);
  433. let gpu = t[1].saturating_sub(t[0]) as f64 / frequency * 1e3;
  434. back.Unmap(0, None);
  435. (budget_ptr as *mut u32).write_volatile(0);
  436. [gpu, recorded, ran]
  437. };
  438. // What `main` records, then this branch; the windows a step at a
  439. // time (barriers, then the clamp's one charge per group).
  440. let (old, new) = (&clamps[0], &clamps[1]);
  441. // The last two keep the budget in the card's memory instead of
  442. // memory the CPU maps (where the list's budget is now).
  443. let cases: [(&str, Barriers, &Clamp, u32, bool); 7] = [
  444. ("one at a time, main", Barriers::Old, old, 1, false),
  445. ("one at a time, this", Barriers::New, new, 1, false),
  446. ("windows of 32, main", Barriers::Old, old, WINDOW, false),
  447. ("windows, new barriers", Barriers::New, old, WINDOW, false),
  448. ("windows of 32, this", Barriers::New, new, WINDOW, false),
  449. ("one at a time, card", Barriers::New, new, 1, true),
  450. ("windows of 32, card", Barriers::New, new, WINDOW, true),
  451. ];
  452. // Warm up, then the cases in turn, so drift falls on all alike.
  453. for &(_, barriers, clamp, window, card) in &cases {
  454. frame(barriers, clamp, window, card);
  455. }
  456. let mut times: Vec<Vec<[f64; 3]>> = vec![Vec::new(); cases.len()];
  457. for _ in 0..RUNS {
  458. for (i, &(_, barriers, clamp, window, card)) in cases.iter().enumerate() {
  459. times[i].push(frame(barriers, clamp, window, card));
  460. }
  461. }
  462. let median = |v: &[[f64; 3]], k: usize| {
  463. let mut x: Vec<f64> = v.iter().map(|t| t[k]).collect();
  464. x.sort_by(f64::total_cmp);
  465. x[x.len() / 2]
  466. };
  467. eprintln!(
  468. "indirect draw barriers on {adapter}: {DRAWS} one-record draws a frame, \
  469. medians of {RUNS} frames"
  470. );
  471. for (i, (name, ..)) in cases.iter().enumerate() {
  472. let gpu = median(&times[i], 0);
  473. eprintln!(
  474. " {name:<22} GPU {gpu:7.2} ms ({:5.2} us a draw), recording {:6.2} ms, \
  475. submit to done {:7.2} ms",
  476. gpu * 1e3 / f64::from(DRAWS),
  477. median(&times[i], 1),
  478. median(&times[i], 2),
  479. );
  480. }
  481. for (from, to) in [(0, 1), (2, 3), (3, 4), (2, 4), (1, 5), (4, 6)] {
  482. let (a, b) = (median(&times[from], 0), median(&times[to], 0));
  483. eprintln!(
  484. " {} -> {}: GPU time {:+.1} %",
  485. cases[from].0,
  486. cases[to].0,
  487. (b / a - 1.0) * 100.0
  488. );
  489. }
  490. }
  491. }