Repository navigation
Recompiler: direct DXIL lowers a repeating compute program's blocks once - #2034
Conversation
Revised author head verified:
|
| Snapshot | Passed / failed / ignored | Explicit skips |
|---|---|---|
| PR head + probe | 5 / 1 / 0 | 0 |
| PortBridge candidate + probe | 4 / 4 / 0 | 0 |
| Candidate + SSA follow-up + probe | 8 / 0 / 0 | 0 |
The finite GPU loop increments a scalar counter and every lane's v1, then writes marker42 on natural exit. Plain and compact agree at limits65,535 and65,536. At65,537, the head's plain form gives counter65,536/marker0, while compact gives65,537/marker42 and all64 lanes have one extra increment. The final candidate gives65,536/marker0 and correct v1 on all64 lanes. Six boundary dispatches ran per complete probe, with CPU checks for both forms.
The initial candidate builds but fails DXIL validation, before compact GPU dispatch: Instruction does not dominate all uses!. Four emitting tests fail, including existing tests. done is registered with two SSA predecessors, so epilogue register reads traverse the dispatch loop even though compact registers live in memory slots. The fix makes done an independent SSA root like the class/latch blocks, emitting its two incoming branches without SSA edges while retaining the dispatch/continuation edges. The epilogue then loads current slots in done. This preserves the original candidate's header-bit budgeting and table encoding.
The final eight tests include your signed-offset and shared-class-header controls, existing generated-DXIL size/validation controls in wave32/native64/split64, existing GPU plain/compact comparison, and the new boundary/selection probes. For our synthetic repeated(3000) and repeated(5000), table sizes remain947/1572words, four step keys and five classes in all snapshots; automatic selection remainsfalse/true respectively.
Not tested — your two real shader workloads/table counts, full workspace, retail smoke/gameplay, AMD GPU execution, acyclic backwards-layout GPU exhaustion, production compute-entry ABI, or performance/memory cost of the new guard. The GPU loop deliberately forces compact on a small fixture to isolate the budget. The selection check uses public synthetic programs, not the unavailable real shaders. Local GPU diagnostic fails without GPU prerequisites and is not proposed unchanged for GPU-less CI. The existing retail/full-suite gates remain separate.
AI use — Codex (GPT-6) wrote the independent GPU/selection probes, diagnosed and corrected the candidate's SSA exit, ran/verified the comparisons, and drafted this report. Original loop-budget diagnosis and candidate remain credited to akimfomin / PortBridge; its local GPLv2 license and exact patch are preserved with the evidence.
SSA follow-up applied after the PortBridge candidate
--- a/crates/xcl/src/gpu/dxil/compact.rs
+++ b/crates/xcl/src/gpu/dxil/compact.rs
@@ -182,9 +182,11 @@
let left = lw.s.m.load(budget, 4);
let none = lw.cmpc(Pred::Eq, left, 0);
let spent = lw.and(header, none);
- let done = lw.block(Some(2));
+ // Registers live in slots: the common exit is an independent SSA root, like each class.
+ let done = lw.block(Some(0));
let dispatch = lw.block(Some(1));
- lw.cond_br(spent, done, dispatch);
+ lw.s.m.cond_br(spent, done, dispatch);
+ lw.edge(head, dispatch);
lw.s.m.set_block(dispatch);
let one = lw.c(1);
let less = lw.sub(left, one);
@@ -221,7 +223,8 @@
let next = lw.s.m.load(to, 4);
let past = lw.cmpc(Pred::UGe, next, n as u32);
let cont = lw.block(Some(1));
- lw.cond_br(past, done, cont);
+ lw.s.m.cond_br(past, done, cont);
+ lw.edge(latch, cont);
lw.s.m.set_block(cont);
lw.s.m.store(at, next, 4);
lw.br(head);Independent local GPU and selection probe against the original PR head
diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs
index 2fd26c9..8ec19cf 100644
--- a/crates/xcl/src/gpu/dxil/compact_tests.rs
+++ b/crates/xcl/src/gpu/dxil/compact_tests.rs
@@ -95,3 +95,48 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() {
assert_eq!(p.order.len(), 4);
assert_ne!(p.class[0], p.class[2]);
}
+
+#[test]
+fn gpu_compact_loop_budget_matches_plain_at_boundary() {
+ // Local diagnostic: a real GPU is required; do not silently skip this comparison.
+ println!("LOOP adapter={} native64={:?}", runner::adapter().unwrap(), runner::wave64_supported());
+ let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 };
+ let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap();
+ let mut code = i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0)]);
+ code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)]));
+ code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]));
+ code.extend(i("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 2)]));
+ code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)]));
+ code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 170)]));
+ code.extend(i("S_ENDPGM", "ENC_SOPP", &[]));
+ let mut bad = Vec::new();
+ for limit in [65_535u32, 65_536, 65_537] {
+ let mut st = KernelState::default();
+ st.sgpr[2] = limit;
+ for compact in [false, true] {
+ let k = translate_full_as(&code, o, compact).unwrap();
+ let out = runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).unwrap();
+ let count = limit.min(65_536);
+ let marker = if limit <= 65_536 { 42 } else { 0 };
+ let wrong_lanes = (0..KERNEL_LANES).filter(|&lane| out.vgpr[lane][1] != count).count();
+ println!("LOOP limit={limit} compact={compact} count={} marker={} wrong_lanes={wrong_lanes}", out.sgpr[0], out.sgpr[3]);
+ if out.sgpr[0] != count || out.sgpr[3] != marker || wrong_lanes != 0 { bad.push((limit, compact)); }
+ }
+ }
+ assert!(bad.is_empty(), "loop-budget mismatches: {bad:?}");
+}
+
+#[test]
+fn compact_loop_guard_preserves_synthetic_selection() {
+ let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
+ for copies in [3000, 5000] {
+ let code = repeated(copies);
+ let cfg = super::cfg::Cfg::build(&code).unwrap();
+ let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect();
+ let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel);
+ let p = super::compact::plan(&cfg, &lw).unwrap();
+ let wanted = super::compact::wanted(&cfg, &p);
+ println!("LOOP_PLAN copies={copies} blocks={} classes={} steps={} words={} wanted={wanted}", p.order.len(), p.rep.len(), p.steps.len(), p.words());
+ assert_eq!(wanted, copies == 5000);
+ }
+}Follow-up: avoid building a plan that cannot be used
The source review found a small avoidable cost in the same exact head 0e4e10e53b2f0f7d9a8bf2b09f1f0d137bde2d62: translate_on_this_thread always calls compact::plan for compute/kernel entries before filtering it, even when XCL_DIRECT_COMPACT=0 or automatic mode has fewer than 20,000 reachable non-branch instructions. That allocates/classifies keys and builds successor tables only to discard them.
Candidate below: 7 runtime additions / 2 deletions in two files. Share the existing 20,000 threshold with an early eligibility check; disabled mode never plans, forced-on mode still plans small programs, and automatic mode counts the same reachable cfg.rpo instructions that Plan::order uses. The full repetition/table-size decision remains in wanted().
Verified on the same Windows/RTX 3090 environment as the original report below, debug, exact head + identical local probe versus head + candidate + probe. Four fresh processes per snapshot, auto/disabled/disabled/auto. Automatic uses 3,000 copies (below threshold); disabled uses 5,000 copies. Each of the eight processes passed 1/0/0, zero skips, all 64 lane/scalar CPU checks. Generated DXIL SHA256 and full output-state hashes are unchanged between head and candidate for each fixture.
| Mode | Translation ms: head | Translation ms: candidate | DXIL bytes (both) |
|---|---|---|---|
| Automatic,3,000 copies | 417.590 /420.476 | 386.210 /380.038 | 178,140 |
| Disabled,5,000 copies | 697.009 /698.332 | 635.282 /677.048 | 300,848 |
Pre-GPU peak process commit: automatic head 30,601,216/30,490,624B versus candidate 30,564,352/30,474,240B (essentially unchanged); disabled 49,885,184/49,635,328B versus 48,881,664/48,930,816B. This is a small ordered experiment, not a claimed pack-wide speedup or significant general memory reduction.
The four existing compact tests also passed on candidate (4/0/0, zero skips), with the override unset: block sharing in all three wave modes, natural 5,000/3,000-copy threshold behavior, GPU plain/compact equality, and whole-mask class separation. Both 316-file snapshots matched SHA256 before/after and XCL recompiled. The two-file runtime patch and local diagnostic are included below; no source commit/push or competing PR.
Probe command remains cargo test --locked -p xcl --lib -- gpu_large_repeated_program_auto_output_and_cost --test-threads=1 --show-output, with XCL_ADAPTER=3090, XCL_DIRECT_COMPACT unset/0, XCL_COST_COPIES=3000/5000, and XCL_COST_DXIL_OUT set to a distinct local output file per process. Existing controls were run as these four filters in one test command:
the_compact_form_lowers_a_repeated_block_once
a_large_program_that_repeats_itself_takes_the_compact_form
gpu_compact_form_runs_as_the_plain_form
a_mask_read_whole_after_one_copy_only_splits_the_class
Not tested — full workspace, release, retail shaders/smoke, AMD, production compute-entry output or driver cold-compilation cost for this candidate. Translation timings and process memory use the same definitions as the earlier report. Local diagnostic requires GPU; it is not proposed as an unguarded CI test.
AI use — Codex (GPT-6) found the eager planning, wrote the candidate/probe adaptation, ran native comparisons and controls, verified source/DXIL/output hashes, and prepared this update.
Runtime candidate, 7 additions / 2 deletions
diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs
index a439789..406c12b 100644
--- a/crates/xcl/src/gpu/dxil/compact.rs
+++ b/crates/xcl/src/gpu/dxil/compact.rs
@@ -22,6 +22,9 @@ pub struct Plan {
/// Most 32-bit words of tables a program may need to take the form by itself.
const MAX_TABLE_WORDS: usize = 8192;
+/// Below this size automatic selection cannot use a plan.
+pub const MIN_INSTRUCTIONS: usize = 20_000;
+
impl Plan {
/// Bits of a table entry: the class, and the index of the pair of offsets.
fn widths(&self) -> (u32, u32) {
@@ -40,7 +43,7 @@ pub fn wanted(cfg: &Cfg, p: &Plan) -> bool {
let insts = |n: usize| cfg.blocks[p.order[n]].insts.len();
let all: usize = (0..p.order.len()).map(insts).sum();
let once: usize = p.rep.iter().map(|&n| insts(n)).sum();
- all >= 20_000 && once * 10 < all * 3 && p.words() <= MAX_TABLE_WORDS
+ all >= MIN_INSTRUCTIONS && once * 10 < all * 3 && p.words() <= MAX_TABLE_WORDS
}
pub const END: u32 = u32::MAX;
diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs
index 83c5e77..976656f 100644
--- a/crates/xcl/src/gpu/dxil/kernel.rs
+++ b/crates/xcl/src/gpu/dxil/kernel.rs
@@ -236,7 +236,9 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact
}
}
- let plan = if compute || kernel { super::compact::plan(&cfg, &lw) } else { None };
+ let may_compact = (compute || kernel) && compact != Some(false)
+ && (compact == Some(true) || cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::<usize>() >= super::compact::MIN_INSTRUCTIONS);
+ let plan = if may_compact { super::compact::plan(&cfg, &lw) } else { None };
let plan = plan.filter(|p| compact.unwrap_or_else(|| super::compact::wanted(&cfg, p)));
if let Some(p) = &plan {
crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len());Updated local diagnostic, 36 added lines
diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs
index 2fd26c9..3f374c7 100644
--- a/crates/xcl/src/gpu/dxil/compact_tests.rs
+++ b/crates/xcl/src/gpu/dxil/compact_tests.rs
@@ -95,3 +95,39 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() {
assert_eq!(p.order.len(), 4);
assert_ne!(p.class[0], p.class[2]);
}
+
+#[test]
+fn gpu_large_repeated_program_auto_output_and_cost() {
+ use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX};
+ let memory = || unsafe {
+ let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed();
+ c.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32;
+ assert_ne!(K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb), 0);
+ (c.PrivateUsage, c.PeakPagefileUsage, c.WorkingSetSize, c.PeakWorkingSetSize)
+ };
+ assert_ne!(compact_mode(), Some(true), "compare automatic selection with disabled compact form");
+ let copies = std::env::var("XCL_COST_COPIES").unwrap().parse::<usize>().unwrap();
+ let code = repeated(copies);
+ let mut st = KernelState::default();
+ (st.sgpr[1], st.sgpr[2]) = (3, 12);
+ for lane in 0..KERNEL_LANES { st.vgpr[lane][0] = lane as u32; }
+ // Explicit split-wave64, with no GPU initialization before translation memory sampling.
+ let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
+ println!("LARGE mode={:?} copies={copies} input_bytes={} memory_before={:?}", compact_mode(), code.len(), memory());
+ let start = std::time::Instant::now();
+ let k = translate_full(&code, o).expect("large program translation");
+ let ms = start.elapsed().as_secs_f64() * 1000.0;
+ println!("LARGE translation_ms={ms:.3} dxil_bytes={} memory_after={:?}", k.dxil.len(), memory());
+ std::fs::write(std::env::var("XCL_COST_DXIL_OUT").unwrap(), &k.dxil).unwrap();
+ println!("LARGE adapter={}", runner::adapter().expect("GPU required for this local cost probe"));
+ let out = runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("large program GPU run");
+ assert_eq!(&out.sgpr[..5], &[3 * copies as u32, 3, 12, 1, 0]);
+ assert_eq!(out.scc, 0);
+ for lane in 0..KERNEL_LANES {
+ assert_eq!(&out.vgpr[lane][..3], &[lane as u32, copies as u32 * lane as u32, 5 * lane as u32], "lane {lane}");
+ }
+ // Compare the entire output state across isolated processes as well as the CPU oracle.
+ let hash = out.sgpr.iter().chain(out.vgpr.iter().flatten()).chain(std::iter::once(&out.scc))
+ .fold(0xcbf29ce484222325u64, |h, &v| (h ^ v as u64).wrapping_mul(0x100000001b3));
+ println!("LARGE output_hash={hash:016x} all_64_lanes_correct=true");
+}Original automatic-path comparison (unchanged head, earlier diagnostic)
Independent RTX 3090 automatic-path output and translation-cost check on exact head 0e4e10e53b2f0f7d9a8bf2b09f1f0d137bde2d62 + the local diagnostic below. No runtime changes.
The existing GPU test uses 40 repetitions with a forced form. This probe instead uses repeated(5000) (20,004 non-branch instructions, 100,024 input bytes) and calls translate_full, with XCL_DIRECT_COMPACT unset versus 0. Both automatic runs logged 10,003 blocks of 5 kinds, confirming that wanted() selected the compact form. This is the test-kernel ABI, not a title shader's compute ABI.
Tested — Windows 10 Home 19045, Ryzen 7 7800X3D, RTX 3090 driver 591.74, Rust 1.98.1 MSVC, DXC/DXIL 1.8.2502.11, debug, explicit split-wave64. Four separate test processes in order auto/disabled/disabled/auto:
XCL_ADAPTER=3090
XCL_DIRECT_COMPACT unset (automatic) or 0 (disabled)
cargo test --locked -p xcl --lib -- gpu_large_repeated_program_auto_output_and_cost --test-threads=1 --show-output
Each process: 1 passed / 0 failed / 0 ignored, zero skips. All 64 lanes matched the CPU register oracle, scalar loop/branch outputs matched, and the whole output-state hash was identical (9db32686f1edca7b) in all four runs.
| Form | DXIL bytes | Translation ms, runs 1 / 2 | Pre-GPU peak process commit bytes, runs 1 / 2 |
|---|---|---|---|
| Disabled | 300,848 | 730.468 /683.160 | 49,938,432 /49,770,496 |
| Automatic | 5,948 | 247.927 /245.590 | 12,607,488 /12,750,848 |
The timer wraps translate_full (including its worker/validation), before GPU initialization or PSO creation. Memory is PROCESS_MEMORY_COUNTERS_EX.PeakPagefileUsage sampled immediately after translation: the entire process, including fixture, retained DXIL and validator, not translator-exclusive allocations. Fresh processes keep the two forms' high-water marks separate. All 316 source hashes matched before/after and match the worktree; XCL recompiled.
Not tested — Retail shaders or gameplay, real compute-entry ABI output, AMD, full workspace, release builds, GPU throughput, or cold driver PSO compilation. Driver-cache disabling is unavailable on this machine; no PSO timing is claimed. This highly repetitive synthetic program supports automatic-path correctness and local translation cost at the threshold; it does not establish the magnitude of benefits in game shaders. The local diagnostic deliberately requires a GPU and is offered for reproduction, not as an unguarded CI test. Required retail smoke gates remain separate.
AI use — Codex (GPT-6) inspected the implementation, added and ran the local probe, checked logs/source hashes and CPU/output-state comparisons, and prepared this report.
Local reproduction probe: one test-only file, 35 added lines
diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs
index 2fd26c9..7572a6e 100644
--- a/crates/xcl/src/gpu/dxil/compact_tests.rs
+++ b/crates/xcl/src/gpu/dxil/compact_tests.rs
@@ -95,3 +95,38 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() {
assert_eq!(p.order.len(), 4);
assert_ne!(p.class[0], p.class[2]);
}
+
+#[test]
+fn gpu_large_repeated_program_auto_output_and_cost() {
+ use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX};
+ let memory = || unsafe {
+ let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed();
+ c.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32;
+ assert_ne!(K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb), 0);
+ (c.PrivateUsage, c.PeakPagefileUsage, c.WorkingSetSize, c.PeakWorkingSetSize)
+ };
+ assert_ne!(compact_mode(), Some(true), "compare automatic selection with disabled compact form");
+ let copies = 5000;
+ let code = repeated(copies);
+ let mut st = KernelState::default();
+ (st.sgpr[1], st.sgpr[2]) = (3, 12);
+ for lane in 0..KERNEL_LANES { st.vgpr[lane][0] = lane as u32; }
+ // Explicit split-wave64, with no GPU initialization before translation memory sampling.
+ let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
+ println!("LARGE mode={:?} copies={copies} input_bytes={} memory_before={:?}", compact_mode(), code.len(), memory());
+ let start = std::time::Instant::now();
+ let k = translate_full(&code, o).expect("large program translation");
+ let ms = start.elapsed().as_secs_f64() * 1000.0;
+ println!("LARGE translation_ms={ms:.3} dxil_bytes={} memory_after={:?}", k.dxil.len(), memory());
+ println!("LARGE adapter={}", runner::adapter().expect("GPU required for this local cost probe"));
+ let out = runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("large program GPU run");
+ assert_eq!(&out.sgpr[..5], &[3 * copies as u32, 3, 12, 1, 0]);
+ assert_eq!(out.scc, 0);
+ for lane in 0..KERNEL_LANES {
+ assert_eq!(&out.vgpr[lane][..3], &[lane as u32, copies as u32 * lane as u32, 5 * lane as u32], "lane {lane}");
+ }
+ // Compare the entire output state across isolated processes as well as the CPU oracle.
+ let hash = out.sgpr.iter().chain(out.vgpr.iter().flatten()).chain(std::iter::once(&out.scc))
+ .fold(0xcbf29ce484222325u64, |h, &v| (h ^ v as u64).wrapping_mul(0x100000001b3));
+ println!("LARGE output_hash={hash:016x} all_64_lanes_correct=true");
+}|
Royalflamejlh, PortBridge reviewed compact and plain loop limits at A standalone CPU model of those exact predicates shows the difference at the stock limit. In a finite counter loop whose natural exit is at 65,537 iterations, the plain form stops with counter 65,536 and no exit marker. The compact rule reaches 65,537 and the marker. Controls at 65,535 and 65,536 agree. A smaller acyclic backwards-layout case and a shared-class header case cover the other boundaries. There is a pinned patch that charges before dispatch and puts the header flag in the low bit of the packed taken offset. It preserves two words per step. It can split a step pair used by both header kinds, so the exact table sizes of your two automatically selected workloads still need a check. The CPU model, patch application and two focused Rust tests passed. The initial source patch then failed internal DXIL validation on a new end-to-end fixture because of the exit SSA join. Please use the linked patch as historical evidence. WebIdentity1’s independent check and repair reproduces the original difference on an RTX 3090 and verifies the repaired candidate. Reproduction and patch AI assistance: OpenAI Codex (GPT-6 family) assisted with source analysis, the CPU model and the proposed patch. |
fd0534e to
87023c3
Compare
The two largest compute programs of a retail pack are about 14,000 blocks of about 600 kinds: one code many times, each copy lowered again, 4.3 MB of DXIL each. A program of at least 20,000 instructions with under 30 % of them in its distinct blocks (the HLSL compact form's thresholds) now takes a compact form: each distinct block once, inside one loop that reads the block's class and its two successors from constant tables and switches to the class. The two come out under 0.5 MB each. Two blocks are of one class when the lowering would emit the same for both: the same instruction words, the same kind of end, and the same of what it looks up by address (static samplers, whether a mask written there is read whole in the split form, s_getpc_b64). Registers are local variables across the loop; as SSA values each was a phi with an edge from every class, and the form came out larger than the plain one for programs with little repetition. The tables are constant data the driver has to take, and xcl-dev#1316 measured an RTX 5070 Ti accepting a table of 12,288 words and refusing one of 15,360, so a program takes the form by itself only when its two tables are at most 8,192 words together (the HLSL compact form's limit). The third largest program repeats itself too, but its branches go to thousands of different offsets and its tables would be about 24,000 words: it keeps the plain form. XCL_DIRECT_COMPACT=1 forces the form on every compute program and 0 turns it off. Part of xcl-dev#1269. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
87023c3 to
e591a8c
Compare
|
Both taken, in @akimfomin: you are right, the two forms spent the loop budget by different rules. A loop head no longer shares a class with a block that is not one (head or not is part of a class's key) and its code begins with the plain form's check, so the budget is spent on every entry into a head, the first included, and nowhere else. It needs no table bit. @WebIdentity1: the plan is now made only when it can be used. Both findings were made on AI use: Claude Code (Claude Fable 5.2) wrote the changes and this comment. Posted without review by a person: the account owner was away and reads replies later. |
gsucristo
left a comment
There was a problem hiding this comment.
Reviewed the diff — very clean, self-contained Direct DXIL compact form (+431 lines) with strong measured wins (4.3 MB -> 0.44-0.48 MB DXIL, 5-6 s -> 0.1 s in dxil-spirv) and solid unit + GPU tests. Using local stack slots (Init::slot) across the loop instead of wide SSA phis and the shl(shlc(hi, 1), 31 - sh) trick to avoid 32-bit shift UB are both really clean.
One minor hardening suggestion:
crates/xcl/src/gpu/dxil/compact.rs(plan, lines 77-88):static_samplers,whole_live, andS_GETPC_B64are pushed ontokeywithout a tag/length delimiter. Adding a short discriminant or length word before each optional section would prevent any theoretical key collision between blocks with different combinations of those optional properties.
Also worth noting that this cleanly supersedes #1316's routing of XCL_DIRECT_DXIL=1 compute shaders back through HLSL+DXC. Looks ready to merge once any remaining checks are green.
(AI disclosure: review drafted with Antigravity — exact model name not provided to the agent — and checked by the reviewer before posting.)
|
@gsucristo: thank you. Of the three, only the static sampler can be present at one instruction and absent at another with the same words. It is set by moves earlier in the same block, which are in the key, so no two blocks collide today, but a presence flag keeps it that way: three lines in AI use: Claude Code (Claude Fable 5.2) wrote the line, ran the comparison and wrote this comment. Posted without review by a person: the account owner was away and reads replies later. |
The third-largest compute program of a retail pack repeats itself as the two largest do (13,890 blocks of 2,643 kinds), but its branches go to 6,530 different pairs of offsets. As an index into a table of pairs its tables were about 24,000 words, over the limit, and it kept the plain form: 3.9 MB of DXIL. In it, as in the other large programs, a block's second successor is always the next block. For such a program a table entry now holds the taken successor itself when that makes the tables smaller, about 11,300 words here. The limit goes from 8,192 to 12,288 words, the size xcl-dev#1316 measured an RTX 5070 Ti accepting, and the program takes the form. A class's key also marks whether an instruction has a static sampler (from the review of xcl-dev#2034): the one section an instruction can have and another with the same words lack. Part of xcl-dev#1269. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Hardening from the review of xcl-dev#2034. Whether an instruction has a static sampler follows from the moves before it in its block, which are in the key, so no two blocks share a key today; the flag makes the key's sections delimit themselves. The six largest compute programs of a retail pack come out byte for byte as before. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
Driver time, which the description left open: on an RTX 5070 Ti the driver built the compact form of the two programs in 5.4 s and 6.0 s and their plain direct form in 370 s and 980 s, all in one run on a machine that was not quiet. Setup: native Windows 11, RTX 5070 Ti 16 GB (driver 621.24), Ryzen 7 9800X3D, 32 GB RAM, debug build of
Not tested: a quiet machine, the driver's cache off, what the loop costs at run time, and a title run that waits on these two programs. AI use: Claude Code (Claude Fable 5.2) wrote the test, ran it and wrote this comment. Posted without review by a person: the account owner was away and reads replies later. |
|
Cache-disabled PSO comparison on an RTX 5070 Ti Laptop GPU A complement to the driver timings above. On native Windows, driver 621.24, 12 GB, DXC 1.8.2502.11, I measured a synthetic compute-entry shader with repeated control flow and a final UAV store. Base was
These are medians of three The samples force compact mode below the automatic threshold. This measures pipeline creation on the production compute-entry ABI. Retail shaders, automatic routing and dispatch throughput were outside this run. AI use — OpenAI Codex (GPT-6) assisted with the measurement option, fixtures, runs and report. |
A compute program whose HLSL is longer than 8 MB is compiled by DXC at -O0 (the safety net in dxc::compile_here), and the unoptimised DXIL is left for the driver to optimise. A retail title's fully unrolled screen-probe passes (up to 88 863 RDNA2 instructions: one block of ~27 repeated ~3 280 times) become 15 - 30 MB of HLSL. On an RTX 3090 the NVIDIA driver did not finish building one: on main 6987e49 the 30 MB one was stopped at 23 GB after 451 s, and the title ran the machine out of memory (40 GB working set) when it bound the pipeline. -O1 is no way out: 10.5 min of DXC, 5 GB, still 14.7 MB of DXIL. The direct DXIL translator (gpu::dxil::kernel, opt-in with XCL_DIRECT_DXIL) translates the same programs in seconds, and with the compact form of #2034 two of them shrink to under 0.5 MB: ActivateProbes HLSL 30.3 MB -> 473 KB, driver 11 s, 1.6 GB ActivateProbesTarget HLSL 30.2 MB -> 432 KB, driver 11 s, 1.5 GB ActivateRays HLSL 15.0 MB -> 3.8 MB (plain form), 21 min, 8.3 GB So a compute program whose HLSL would be compiled unoptimised (dxc::UNOPTIMISED_ABOVE, now shared with compile_here) is translated by the direct translator; where that fails, the HLSL path goes on as before. Its translation-cache entry is kept under its own identity, which follows what the direct translator's output depends on (its version and sources, a forced compact form, the per-lane form), since the HLSL path's identity does not hash the gpu/dxil sources. TRANSLATION_GLUE_REVISION is bumped: an HLSL-path entry of such a program cached before this change would otherwise still be found. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NmY9ce9uQcXiFj5qSSBfmV
Hardening from the review of xcl-dev#2034. Whether an instruction has a static sampler follows from the moves before it in its block, which are in the key, so no two blocks share a key today; the flag makes the key's sections delimit themselves. The six largest compute programs of a retail pack come out byte for byte as before. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The two largest compute programs of a retail pack go from 4.3 MB of direct DXIL each to 0.48 and 0.44 MB, and vkd3d-proton's dxil-spirv converts each in 0.1 s where it took 5 to 6 s. They are one code many times (14,377 and 14,346 blocks of 617 and 590 kinds), and the direct translator lowered every copy. A program like that now takes a compact form: each distinct block is lowered once, inside one loop that reads the block's class and its two successors from constant tables and switches to the class. It is the direct counterpart of the HLSL compact form (#1315, #1316, #1448), with its thresholds and no DXC run. Part of #1269.
Head
e591a8c. Every number below was taken on it unless it says otherwise. The GPU tests agree on one card, and both regression blocks are below.What is in it
crates/xcl/src/gpu/dxil/compact.rs(new):plansorts the reachable blocks into classes,wantedis the rule,emitbuilds the loop. Two blocks are of one class when the lowering would emit the same for both: the same instruction words, the same kind of end, both loop heads or neither, and the same of what it looks up by address (static samplers, whether a mask written there is read whole in the split form,s_getpc_b64). A loop head's class begins with the plain form's loop-budget check. A table entry is a class and an index into a second table of successor offsets, packed end to end.crates/xcl/src/gpu/dxil/lower.rs,Init: in the compact form a register is a local variable across the loop; a class loads what it reads where it begins and stores what it wrote where it ends. As SSA values every register was a phi with an edge from every class, and three of the six programs below came out larger than their plain form.crates/xcl/src/gpu/dxil/kernel.rs: the block walk is skipped for a planned program, with one[SHADER]log line; the plan is made only for a program of 20,000 instructions or more, or when forced;XCL_DIRECT_COMPACT=1forces the form on every compute program (and the kernel tests),0turns it off; noTRANSLATOR_VERSIONbump: since Recompiler: direct DXIL cache entries change when its sources do #1947 the cache identity follows thegpu/dxilsources.crates/xcl/src/gpu/recomp/pso.rs: the forced modes get their own translation-cache identity.crates/xcl/src/gpu/dxil/compact_tests.rs(new), five tests: 64 more copies of a block cost under a twentieth of what they cost in the plain form (it fails if blocks are not shared); the rule picks a program of 2,500 copies and leaves one of 2,000; two copies of a compare are two classes when the mask is read whole after one of them only (it fails with the key I had first);gpu_compact_form_runs_as_the_plain_formruns 40 copies of four blocks (scalar and vector adds, a compare into VCC, a saved EXEC mask, a region skipped ons_cbranch_execz) and a loop in both forms, and compares the registers with each other and with the values worked out by hand.gpu_compact_form_spends_the_loop_budget_as_the_plain_formruns a loop that would leave on its 65,537th entry: both forms must stop at 65,536.Tested
x86_64-pc-windows-gnu.mainisaa9ab8a. The change ise591a8c.XCL_DIRECT_DXIL=1 xcl shaders <folder> --precompile --only cs --split 1from an empty cache, 1 translation each:mainXCL_DIRECT_COMPACT=1)A program not taken is byte for byte
main's (SHA-256), and so are all six withXCL_DIRECT_COMPACT=0.xcl shaders <pack> --direct --validate --only cs --split 1 --max-bytes 0 --sample 100000(26,698 programs, 2,689 of them compute): with the form forced on every compute program all 26,698 translated and DXC's validator accepted every one (148 s, 8 threads); with the rule deciding, 2 of the 2,689 took the form and all were accepted (155 s). While this branch was written the forced sweep ran six times on five commits: five passed, and one, on an earlier commit, stopped part-way with a page fault that Wine reported without a backtrace. I have not found the cause.mainand 226,007,872 B with the change; 2 translations differ in size, by the 7,696,844 B of the table.spirv-val --target-env vulkan1.3accepts the two new ones:main: time, SPIR-Vcargo test --workspace -- compact_tests: 5 passed, the two card tests among them.cargo test --workspace -- gpu_ --test-threads=4withXCL_DIRECT_DXIL=1: 113 passed, 6 failed, 1 ignored. WithXCL_DIRECT_COMPACT=1added, 99 kernels took the compact form, 88 of them a single block and 10 of 2 to 5 blocks: 113 passed, 6 failed, 1 ignored, the same six with the same messages (fourfuzz_validate_and_gpu_*atCreateComputePipelineStatewith 0x8007000E on the same seeds,gpu_fmt_encode_int_sat_and_f16_rtz,gpu_image_get_resinfo_1d_array). 2 SKIPPED lines in both runs (no native wave64). So that run shows the loop and the local variables on a card, and little of the sharing; the card test above is what shows that.cargo test --workspace --release --target x86_64-pc-windows-gnu --no-fail-fast -- --test-threads=8under Wine, no card: 1,082 passed, 5 failed, 46 ignored;main: 1,077 passed, 5 failed, 46 ignored. The same five fail on both:disk_free_space_ex_reports_pls_quota,directed_reference_basics,gpu_depth_buffer_created_for_unordered_access_is_placed,stale_blob_cannot_bypass_the_offline_pipeline_cap,test_title_runs_and_game_folder_is_untouched. SKIPPED lines: 279 (277 onmain), no GPU or a missing wave size.XCL_DIRECT_DXIL=1 XCL_DIRECT_COMPACT=1, so every kernel they translate takes the compact form and DXC's validator: 113 passed, 1 failed (directed_reference_basics, which translates nothing and fails onmaintoo), 3 ignored.7edb1aconmain80f4819, where the two programs were 471,764 and 436,512 B), each merged locally:f090104, its conflict inpso.rsresolved by keeping itsdefer_direct_compute()?line) + Recompiler: direct DXIL gives every loop head and block one back edge #1860, no switches set, so Recompiler: route huge compute programs through the direct DXIL translator #1809's routing decides: the six were 19,798,084 B without this change and 12,091,120 B with it.d899eb5, tree onmain6567c5f) merges the repeateds_cbranch_execzregions into large blocks before this change sees them: the 88,863-instruction program becomes 195 blocks of 149 kinds and 3,775,108 B, and the rule then picks nothing. With the plan made on the blocks before that collapse (9 lines intranslate_on_this_thread, andcompact.rstaking dxil: collapse forward s_cbranch_execz regions and make read-only loads branchless #1834's two block operations; a local tree, not in this pull request) the two programs are 471,764 and 436,512 B again and every other program keeps dxil: collapse forward s_cbranch_execz regions and make read-only loads branchless #1834's collapse: 18,620,216 B for the six with the compact form off, 12,006,660 B with it. Whichever of the two merges second needs those lines.Regression run
scripts/smoke.ps1, unchanged, 60 s on the RTX 5070 Ti PC above, 1 run each.smoke.ps1sets noXCL_DIRECT_DXIL, so neither run reaches this code.main:
PR:
Not tested
0e4e10e) withXCL_DIRECT_DXIL=1on the same PC (release, A from 32 s) did not get to them: it reached the world start asmaindoes (first#101at 84.9 s, last present 88.0 s, 1,820 frames, exit 0, no device removal), and then one thread built 300 to 400 KB programs in the driver at 4.7 to 7.7 s each; neither of the two was asked for by 300 s. In DXIL instructions the first went from 605,253 to 65,038 and from 31,464 blocks to 2,089 on that head (dxc -dumpbin).mainwas not run there.XCL_HEAP_WINDOWS=1,XCL_PER_LANE=1(the per-lane form is tried first and is not changed).AI use