Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions docs/experiments/compute-output-buffer-reasons.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Named reasons for a compute output buffer range

A translated compute program's buffer output is bound only when a placed buffer aliases the title memory it
names, so the GPU writes reach the title. The single refusal `an output is not an aliased placed buffer range
with unordered access` is split into the condition that failed, in the same log and census lines, checked in
this order:

1. `an output buffer descriptor is a view token`
2. `an output buffer descriptor has zero records`
3. `an output buffer range is over 16 MiB or not whole dwords`
4. `an output range crosses the end of a placed buffer` (also a range that two placements claim)
5. `an output is in title memory outside any placed buffer`
6. `an output is in a placed buffer that does not alias title memory` (a copied placement)
7. `an output buffer's resource was not created in the common state` (also an aliased resource with no recorded
information, which no fixture reaches)
8. `an output buffer range is not 16-byte aligned in its resource`
9. `an output buffer has no unordered access`

Only the reason changes: what was bound is still bound and what was refused is still refused. Output view tokens
are lowered separately in #2961 (open), which binds a buffer UAV token before these checks; with it, reason 1 is
not reached. The census keeps one reason per key, the first one that key was refused with, and counts all of the
key's untranslated dispatches under it. A start-up run with this build therefore gives first-refusal buckets, not
a count per condition: a later dispatch of the same key can fail on another condition, and the per-call refusal
lines are capped.

`tests/startup_compute_dispatch_output_check.py` dispatches case A of `startup_gfx2hlsl_compute_check.py` through
the stand-in's list on WARP and on a physical adapter (exit 77 without one). The unchanged recording matches all
320 words. Each of the nine conditions is then produced by one change to the output descriptor or its buffer,
and each dispatch refuses with its own reason in the log and the census and leaves every output word at its
sentinel. The common-state case also checks that its buffer was aliased. `dispatch-swapped` in
`startup_compute_dispatch_check.py` now expects reason 9.

```powershell
ctest --preset dev --no-tests=error -R "^startup_compute_dispatch(_output)?_(warp|hardware)$" -V
```

Both tests pass on WARP (10.0.26100.9818) and on an RTX 4090 (driver 32.0.16.1088), Windows 11 build 26300,
debug layer on. With only the split reverted, the unchanged dispatch still matches and all nine cases are still
refused, each with the old reason, so all nine expectations fail: the set of refused cases is the same.

Local observation, one 300 s start-up run with this build (`79edac55`; translator at `ad306425`, whose `gfx2hlsl.py`
is unchanged since `2e12dd8e`), counts only. A run of the parent build with the same settings refused 25 keys and
505,473 of 5,490,863 compute dispatches with the old reason as their first refusal. With the split, the same 25
keys fall in these first-refusal buckets:

| First refusal of the key | Keys | Untranslated dispatches of those keys |
|---|---|---|
| 1, view token | 23 | 141,224 |
| 2, zero records | 2 | 2,015 |
| 3 to 9 | 0 (no key had one of these first refusals) | 0 |

The run made 1,490,517 compute dispatches in all, so the share in these buckets is about the same (9.2% and 9.6%).
In the first refused dispatch of each of the 23 keys, the token named a view created through device slot 19, the
form #2961 binds. In that of each of the two zero-record keys, the descriptor was all zero. No key had a copied
placement, the initial state, alignment or the unordered-access flag as its first refusal; later dispatches were
not recorded per condition.

The same run with #2961 merged locally (`51aef000`, not pushed; reason 1 dropped, #2961's token branch first):

| The 23 token keys | Keys | Dispatches |
|---|---|---|
| every dispatch translated, no refusal | 12 | 32,043 |
| first refusal: `an entry value reads the descriptor of an output named by a view token` | 10 | 9,372 untranslated |
| first refusal: `an output buffer view range is empty, unaligned or outside its resource` | 1 | 190,397 untranslated |

No key had `an output view token is not a buffer UAV of a desktop resource` as its first refusal: every dispatch of
the 12 translated keys, and the first refused dispatch of each of the other 11, named a buffer unordered access view
of a desktop resource. That run made 2,453,727 compute dispatches, so dispatch counts compare only within one run.
Whether the 12 translated keys write the right values was not checked.
19 changes: 14 additions & 5 deletions src/startup_stubs/d3d12_compute_dispatch.inl
Original file line number Diff line number Diff line change
Expand Up @@ -549,16 +549,25 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch&
}
// An output is written by the GPU: only a placed buffer that aliases the title's memory shows the result
// to the title. shortcut: view tokens and copied placements are refused, add them with their first user.
// Each refused condition has its own reason.
const u64 address = words[0] | (u64{words[1] & 0xffff} << 32);
const UINT stride = (words[1] >> 16) & 0x3fff;
const u64 bytes = u64{stride ? stride : 1} * words[2];
const auto placed = words[0] == view_token_magic || !bytes || bytes % 4 || bytes > (16u << 20)
? PlacedVertexView{} : placed_buffer_range(self->own().list_device, address, bytes);
const bool sized = words[0] != view_token_magic && bytes && bytes % 4 == 0 && bytes <= (16u << 20);
const auto placed = sized ? placed_buffer_range(self->own().list_device, address, bytes) : PlacedVertexView{};
const ResourceInfo* info = placed.alias ? resource_info(placed.owner) : nullptr;
const u64 offset = placed.alias ? address - reinterpret_cast<u64>(placed.owner->own().title_memory) : 0;
if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON || offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT ||
!(placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))
reason = "an output is not an aliased placed buffer range with unordered access";
if (words[0] == view_token_magic) reason = "an output buffer descriptor is a view token";
else if (!bytes) reason = "an output buffer descriptor has zero records";
else if (!sized) reason = "an output buffer range is over 16 MiB or not whole dwords";
else if (placed.reject) reason = "an output range crosses the end of a placed buffer";
else if (!placed.owner) reason = "an output is in title memory outside any placed buffer";
else if (!placed.alias) reason = "an output is in a placed buffer that does not alias title memory";
else if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON)
reason = "an output buffer's resource was not created in the common state";
else if (offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) reason = "an output buffer range is not 16-byte aligned in its resource";
else if (!(placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))
reason = "an output buffer has no unordered access";
for (std::size_t input = 0; input < inputs && !reason; ++input)
if (views[input].resource == placed.alias) reason = "an output buffer is also an input";
views[i] = {placed.alias, offset, bytes, true};
Expand Down
8 changes: 8 additions & 0 deletions tests/cmake/startup_compute_dispatch_output.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer)
foreach(adapter IN ITEMS warp hardware)
add_test(NAME startup_compute_dispatch_output_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_output_check.py" "$<TARGET_FILE:startup_stream_consumer>"
"${DXC_EXECUTABLE}" ${adapter})
set_tests_properties(startup_compute_dispatch_output_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
endif()
7 changes: 4 additions & 3 deletions tests/startup_compute_dispatch_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
2. after gfx2hlsl.py --pending with DXC: all 320 words equal the case's expectation;
3. dispatch-none (no Dispatch recorded): every word keeps the sentinel;
4. dispatch-swapped (the two descriptors exchanged, so the output names the buffer without unordered access):
refused with one logged reason, every word keeps the sentinel and the input is unchanged;
refused with "an output buffer has no unordered access", every word keeps the sentinel and the input is
unchanged;
5. dispatch-same-root (the same compute root set again after the constants): all 320 words still match;
6. five more refusals, each with its one logged reason and an untouched output: dispatch-missing-word (no slot 37
call), dispatch-root-changed (another compute root and back after the constants), dispatch-reset (list closed
Expand Down Expand Up @@ -120,9 +121,9 @@ def main(consumer, dxc, adapter):
refused = lines(result, 'refused: ')
census = lines(result, 'x2w-render compute census')
assert len(census) == 3 and census[1].endswith(
'reason "an output is not an aliased placed buffer range with unordered access": 1 keys, 1 dispatches') \
'reason "an output buffer has no unordered access": 1 keys, 1 dispatches') \
and '[00000000 00000000 ' not in census[2], census
assert len(refused) == 1 and 'an output is not an aliased placed buffer range with unordered access' in refused[0], \
assert len(refused) == 1 and 'an output buffer has no unordered access' in refused[0], \
result.stderr[-3000:]
got, result = dispatch(directory, consumer, env, 'dispatch-same-root')
assert got == expected and not lines(result, 'refused'), 'setting the same compute root again lost the constants'
Expand Down
92 changes: 92 additions & 0 deletions tests/startup_compute_dispatch_output_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Named reasons for a translated compute output that is not an aliased placed buffer range (list slot 14).
usage: startup_compute_dispatch_output_check.py <startup_stream_consumer> <dxc> <warp|hardware>
The consumer records case A of startup_gfx2hlsl_compute_check.py as startup_compute_dispatch_check.py does. After
gfx2hlsl.py --pending with DXC, the unchanged recording still matches all 320 words. Then the output descriptor or
its buffer is changed one condition at a time, and each dispatch is refused with its own reason in the log and the
census and writes no output word:
- dispatch-output-texture-token: the token of a texture view where the output descriptor was;
- zero records, a range over 16 MiB (stride 4, 4 Mi + 1 records) and a range 16 bytes past the placed output
buffer, through X2W_TEST_DISPATCH_FIELDS (synthetic values);
- dispatch-output-unplaced: memory between the two placed buffers;
- dispatch-output-copied: a buffer placed there at an offset the desktop cannot alias, so it is a separate copy;
- dispatch-output-state: the output buffer placed (and aliased) in the unordered access state;
- dispatch-output-unaligned: the output starts 8 bytes into its buffer;
- dispatch-swapped: the output names the input buffer, which has no unordered access.
A resource with an aliased placement and no recorded information also reports the common state reason; no
fixture reaches it. Exit 77 when the adapter is not available.
"""
from pathlib import Path
import os
import struct
import subprocess
import sys
import tempfile

import startup_gfx2hlsl_compute_check as C
from startup_compute_dispatch_check import dispatch, lines, prepare_case
from startup_stream_check import gfx2hlsl as G


def fields(records, stride=4):
return struct.pack('<6I', 4, C.WORDS, 0, stride, records, 0)


CONTROLS = (
('dispatch-output-texture-token', None, 'an output buffer descriptor is a view token'),
('dispatch', fields(0), 'an output buffer descriptor has zero records'),
('dispatch', fields((16 << 20) // 4 + 1), 'an output buffer range is over 16 MiB or not whole dwords'),
('dispatch', fields(C.WORDS + 4), 'an output range crosses the end of a placed buffer'),
('dispatch-output-unplaced', None, 'an output is in title memory outside any placed buffer'),
('dispatch-output-copied', None, 'an output is in a placed buffer that does not alias title memory'),
('dispatch-output-state', None, "an output buffer's resource was not created in the common state"),
('dispatch-output-unaligned', None, 'an output buffer range is not 16-byte aligned in its resource'),
('dispatch-swapped', None, 'an output buffer has no unordered access'),
)


def main(consumer, dxc, adapter):
with tempfile.TemporaryDirectory() as temporary:
directory = Path(temporary)
cache, env = prepare_case(directory, adapter)
untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A')

got, result = dispatch(directory, consumer, env, 'dispatch', probe=True)
print(result.stdout, end='')
assert got == untouched and len(lines(result, 'refused: no translation')) == 1, result.stderr[-3000:]
published = lines(result, 'x2w-draw compute request')
assert published and ' published ' in published[0], result.stderr[-3000:]
key = int(published[0].split()[3], 16)
out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True,
text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout
assert f'{key:016x}: ok' in out, out

got, result = dispatch(directory, consumer, env, 'dispatch')
assert got == expected and not lines(result, 'refused'), result.stderr[-3000:]

for mode, words, reason in CONTROLS:
case_env = dict(env)
if words:
(directory / 'fields').write_bytes(words)
case_env['X2W_TEST_DISPATCH_FIELDS'] = str(directory / 'fields')
got, result = dispatch(directory, consumer, case_env, mode)
name = mode if not words else f'{mode} fields {struct.unpack("<6I", words)[3:5]}'
assert got == untouched, f'{name}: a refused Dispatch wrote the output'
refused = lines(result, 'refused: ')
census = lines(result, 'x2w-render compute census')
assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), f'{name}:\n{result.stderr[-3000:]}'
assert len(census) == 3 and census[1].endswith(f'reason "{reason}": 1 keys, 1 dispatches'), (name, census)
if mode == 'dispatch-output-state': # the buffer is aliased, so only its state is refused
placed = [line for line in lines(result, 'Device::slot133') if ' state=0x8 ' in line]
assert len(placed) == 1 and '-> 0x00000000 aliased ' in placed[0], (name, placed)
print(f'startup_compute_dispatch_output: PASS on {adapter} (all {C.WORDS} words match; {len(CONTROLS)} outputs '
'refused, each with its own reason and an untouched output)')


if __name__ == '__main__':
if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'):
sys.exit(__doc__)
main(*sys.argv[1:])
Loading
Loading