Skip to content
Open
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
27 changes: 27 additions & 0 deletions docs/experiments/direct-compute-exact-width-image-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,30 @@ starts at physical slice 1. Every other texel retains its sentinel.
The format cases use R32_FLOAT, R32G32_FLOAT, and R11G11B10_FLOAT. The
RGBA8 control leaves the complete image untouched and checks the runtime
channel-count refusal.

## Published one- and two-channel D16 stores

The direct compiler already emits scalar and two-channel D16 image stores.
The published manifest uses
`uav <index> <tex1d|tex2d|tex2da|tex3d> half table <parameter> <byte> channels <1|2>`.
The runtime requires an `R16_FLOAT` or `R16G16_FLOAT` UAV of the corresponding
typed or typeless resource and checks desktop typed-store support on the
view format. Dispatch retains the UAV's mip, first array slice or W slice,
and range.

The source-built fixture writes 1.0 and, for two channels, -2.0 to even
columns of mip 1. It checks 1D, 2D, 2D array and volume readbacks, including
an R16 typeless backing resource. The layered tests bind a view that starts
at physical slice 1 and write relative slice 1. All other pixels and slices
keep their original halfwords. The R32_FLOAT and R32G32_FLOAT controls
exercise the format refusal with the same channel counts.
The scalar 2D fixture also verifies mip 0 remains untouched. Shifting the
3D view's first W slice from 1 to 0 moves the writes to the adjacent slice.
A compiled 1D-array D16 store is refused at manifest publication.

The translated descriptor follows the [D3D12 UAV contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_unordered_access_view_desc),
including the [W range of 3D views](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_tex3d_uav).

```powershell
ctest --preset release --no-tests=error -R '^startup_compute_half_image_uav_' -V
```
12 changes: 12 additions & 0 deletions src/direct_compute_cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,18 @@ std::optional<std::string> format_compute_runtime_manifest(const NativeComputeSh
} else if (b.kind == ComputeViewKind::uint_texture_uav && b.image_dimension == 1 && b.array_count == 1) {
uav_lines << "uav " << b.shader_register << " tex2d uint table " << b.root_parameter << ' '
<< b.byte_offset << " channels 1\n";
} else if ((b.kind == ComputeViewKind::half_scalar_uav || b.kind == ComputeViewKind::half2_texture_uav) &&
b.array_count == 1) {
const char *dimension;
switch (b.image_dimension) {
case 0: dimension = "tex1d"; break;
case 1: dimension = "tex2d"; break;
case 2: dimension = "tex3d"; break;
case 5: dimension = "tex2da"; break;
default: return refuse(view_shape("UAV", b));
}
uav_lines << "uav " << b.shader_register << ' ' << dimension << " half table " << b.root_parameter
<< ' ' << b.byte_offset << " channels " << (b.kind == ComputeViewKind::half_scalar_uav ? 1 : 2) << '\n';
} else if (const auto channels = exact_texture_uav_channels(b.kind); channels && b.array_count == 1 &&
(b.image_dimension == 1 || b.image_dimension == 2 || b.image_dimension == 5)) {
const char *dimension = b.image_dimension == 2 ? "tex3d" : b.image_dimension == 5 ? "tex2da" : "tex2d";
Expand Down
29 changes: 24 additions & 5 deletions src/startup_stubs/d3d12_compute_dispatch.inl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
// buffers (`srv <i> buf table <param> <byte>` and `srv <i> buf root <param>` inputs, `uav <i> table <param> <byte>`
// outputs, or `uav <i> bufhalf table <param> <byte> bytes <stride>` for typed half stores)
// named by hardware buffer descriptors or 64-bit root SRV addresses, and textures
// (`srv <i> tex1d|tex2d|tex2da|tex3d table <param> <byte>` inputs, `uav <i> tex1d/tex2d/tex2da/tex3d float table <param> <byte> channels <n>` outputs) named
// (`srv <i> <tex1d|tex2d|tex2da|tex3d> table <param> <byte>` inputs,
// `uav <i> <dimension> <float|half> table <param> <byte> channels <n>` outputs) named
// by the token of a view the title created (device slots 18 and 19). `smp`, `smpl` and `smpc` lines become static samplers. Entry
// values come from the compute root constants of slots 37 and 39, or from the descriptor a buffer input or output is
// bound from: its stride and word 3 (`stride`, `descword3`), and word 3, the upper half of word 1 and the record
Expand Down Expand Up @@ -37,6 +38,7 @@ struct ComputeTranslation {
D3D12_UAV_DIMENSION uav_dimension = D3D12_UAV_DIMENSION_UNKNOWN;
bool root = false;
bool atomic_uint_texture = false;
bool narrow_half_texture = false;
unsigned channels = 4;
D3D12_SRV_DIMENSION srv_dimension = D3D12_SRV_DIMENSION_UNKNOWN;
unsigned half_buffer_bytes = 0;
Expand Down Expand Up @@ -227,6 +229,13 @@ const char* load_compute_translation(ComputeTranslation& tr)
tr.uavs.back().uav_dimension = uav_dimension();
tr.uavs.back().channels = x;
}
else if (std::sscanf(line.c_str(), "uav %u %15s half table %d %d channels %u%n", &i, name, &a, &b, &x, &used) == 5 &&
whole() && i == tr.uavs.size() && (x == 1 || x == 2) && uav_dimension() != D3D12_UAV_DIMENSION_UNKNOWN) {
tr.uavs.push_back({a, b, true});
tr.uavs.back().uav_dimension = uav_dimension();
tr.uavs.back().channels = x;
tr.uavs.back().narrow_half_texture = true;
}
else if (std::sscanf(line.c_str(), "srv %u %15s table %d %d%n", &i, name, &a, &b, &used) == 4 && whole() &&
i == tr.srvs.size() && srv_dimension() != D3D12_SRV_DIMENSION_UNKNOWN) {
tr.srvs.push_back({a, b, true});
Expand Down Expand Up @@ -622,15 +631,25 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch&
if (!reason && slot.atomic_uint_texture && format != DXGI_FORMAT_R32_UINT)
reason = "an image atomic requires an R32_UINT UAV";
if (!reason && slot.channels < 4) {
if (float_output_channels(format) != slot.channels || float_output_channels(resource.Format) != slot.channels)
auto store_format = resource.Format;
if (slot.narrow_half_texture) {
const auto kind = slot.channels == 1 ? x2w::ComputeViewKind::half_scalar_uav
: x2w::ComputeViewKind::half2_texture_uav;
const auto half = x2w::native_half_store_format(kind);
if (!half.accepts(format, resource.Format))
reason = "a D16 image store requires a matching half-float UAV and resource";
store_format = half.typed;
} else if (float_output_channels(format) != slot.channels ||
float_output_channels(resource.Format) != slot.channels) {
reason = "an exact-width image store requires a matching output texture channel count";
else {
D3D12_FEATURE_DATA_FORMAT_SUPPORT support{resource.Format};
}
if (!reason) {
D3D12_FEATURE_DATA_FORMAT_SUPPORT support{store_format};
if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support,
sizeof(support))) ||
!(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE))
reason = "an exact-width image store requires typed UAV store support";
desc.Format = resource.Format;
desc.Format = store_format;
}
}
if (!reason && !slot.atomic_uint_texture && !float_output_channels(format))
Expand Down
1 change: 1 addition & 0 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
#include "title_heap_memory.h"
#include "startup_stubs/xmem_section_buffer.h"
#include "native_buffer_store_view.h"
#include "native_texture_store_view.h"
#include "native_compute_output.h"
#ifdef X2W_NATIVE_SHADERS // d3d12_xs_shim only: the C++ shader compiler (startup_stubs/d3d12_compute_dispatch.inl)
#include "gfx1013_compute_native.h"
Expand Down
15 changes: 15 additions & 0 deletions tests/cmake/startup_compute_half_image_uav.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}"
AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll")
set(half_image_check "${CMAKE_SOURCE_DIR}/tests/startup_compute_half_image_uav_check.py")
add_test(NAME startup_compute_half_image_uav_controls COMMAND "${INTAKE_PYTHON}" -B
"${half_image_check}" compile "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
set_tests_properties(startup_compute_half_image_uav_controls PROPERTIES TIMEOUT 60)
if(TARGET startup_stream_consumer AND TARGET offscreen_check)
foreach(adapter IN ITEMS warp hardware)
add_test(NAME startup_compute_half_image_uav_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${half_image_check}" "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:startup_stream_consumer>"
"$<TARGET_FILE:offscreen_check>" "${DXC_BIN_DIR}" ${adapter})
set_tests_properties(startup_compute_half_image_uav_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
endif()
endif()
156 changes: 156 additions & 0 deletions tests/startup_compute_half_image_uav_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
"""Check published D16 image stores on narrow typed UAVs."""

from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory

from native_direct_container_check import words
from native_gather_lod_check import render
from startup_compute_dispatch_check import lines
from startup_compute_dispatch_texture_check import clean, run
from startup_compute_image_store_check import ARRAY_END, ARRAY_PROLOGUE, ARRAY_SLICE, RSRC2
from startup_compute_request_check import DATA, prepare
from startup_compute_translate_check import state_a, write_request
from startup_gfx2hlsl_compute_check import root_blob


# Each selected mip is 32 wide. The layered paths select a view starting at
# physical layer 1 and write its relative layer 1.
CASES = (
('r-line', 1, 0, 'tex1d', 1, 1),
('r', 1, 1, 'tex2d', 8, 1),
('rg', 2, 1, 'tex2d', 8, 1),
('r-typeless', 1, 1, 'tex2d', 8, 1),
('rg-array', 2, 5, 'tex2da', 8, 6),
('r-volume', 1, 2, 'tex3d', 8, 6),
)
ROOT = root_blob(3, table_range=True)


def program(channels, dimension):
return (
words(0xbefe03c1) # s_mov_b32 exec_lo, -1, before the vector prologue
+ ARRAY_PROLOGUE + ARRAY_SLICE[1]
+ words(0xbf8cc07f, 0x7e1c02ff, 0xc0003c00, 0xbefe03ff, 0x55)
+ words(0xf0201000 | (((1 << channels) - 1) << 8) | (dimension << 3), 0x80060e08)
+ ARRAY_END
)


def state(height):
return state_a((4, 1 if height == 1 else 2, 1), RSRC2)


def compile_request(cli, sdk, cache):
return subprocess.run([cli, sdk, cache.parent / 'compiler-cache', 'gfx1013-direct-cs@0',
'--requests', cache, cache], capture_output=True, text=True, timeout=30)


def publish(cli, sdk, cache, key, channels, dimension):
result = compile_request(cli, sdk, cache)
manifest = cache / f'{key}.txt'
assert result.returncode == 0 and manifest.is_file(), result.stdout + result.stderr
expected = f'uav 0 {dimension} half table 1 64 channels {channels}'
assert expected in manifest.read_text().splitlines(), manifest.read_text()


def controls(cli, sdk):
with TemporaryDirectory() as directory:
for name, channels, dimension, view, height, _ in CASES:
cache = Path(directory) / name
cache.mkdir()
key = write_request(cache, program(channels, dimension), state(height), root=ROOT)
publish(cli, sdk, cache, f'{key:016x}', channels, view)
cache = Path(directory) / 'unsupported-1d-array'
cache.mkdir()
key = f'{write_request(cache, program(2, 4), state(8), root=ROOT):016x}'
result = compile_request(cli, sdk, cache)
reason = 'unsupported startup runtime manifest bindings: UAV kind half2_texture_uav 1d-array'
assert result.returncode == 0 and reason in result.stdout, result.stdout + result.stderr
assert (cache / f'{key}.cs.cso').read_bytes().startswith(b'DXBC')
assert not (cache / f'{key}.txt').exists()
print('1D-array D16 store compiled and was refused at manifest publication')


def compare(got, expected, label, result):
if got != expected:
word = next(i for i, (a, b) in enumerate(zip(got, expected)) if a != b)
raise AssertionError(f'{label}: component {word} expected {expected[word]:04x}, '
f'read {got[word]:04x}\n{result.stderr[-3000:]}')


def stored(initial, channels, height, layer, start):
expected = initial.copy()
values = [0x3c00, 0xc000][:channels]
for y in range(min(height, 2)):
for x in (0, 2, 4, 6):
i = start + ((layer * height + y) * 32 + x) * channels
expected[i:i + channels] = values
return expected


def check(directory, cli, sdk, consumer, adapter, case):
name, channels, dimension, view, height, layers = case
cache, env = prepare(directory)
env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1',
X2W_TEST_COMPUTE_ROOT=str(directory / 'compute_root'))
for flag in ('X2W_NATIVE_SHADERS', 'X2W_NATIVE_SHADERS_ONLY', 'X2W_TEST_DISPATCH_HARDWARE'):
env.pop(flag, None)
if adapter == 'hardware':
env['X2W_TEST_DISPATCH_HARDWARE'] = '1'
(directory / 'compute_root').write_bytes(ROOT)
(directory / 'program').write_bytes(program(channels, dimension))
(directory / 'data').write_bytes(DATA)
(directory / 'state').write_bytes(state(height))
mode = 'texture-exact-half-' + name
base_mip = [0x7000 + i for i in range(64 * 16)] if name == 'r' else []
initial = base_mip + [0x5000 + i for i in range(layers * 32 * height * channels)]
layout = f'<{len(initial)}H'

got, result = run(directory, consumer, env, mode, layout)
compare(got, initial, name + ' before translation', result)
assert lines(result, 'Dispatch(2, 1, 1) refused: no translation'), result.stderr
key = lines(result, 'x2w-draw compute request')[0].split()[3]
publish(cli, sdk, cache, key, channels, view)

expected = stored(initial, channels, height, 2 if layers > 1 else 0, len(base_mip))
got, result = run(directory, consumer, env, mode, layout)
compare(got, expected, name, result)
assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr
layer = clean(result)
print(f'{adapter} {name}: all {len(expected)} halfwords match including mip 1 (debug layer {layer})')

if name == 'r-volume':
got, result = run(directory, consumer, env, mode + '-shifted-w', layout)
compare(got, stored(initial, channels, height, 1, 0), 'shifted volume W range', result)
assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr
clean(result)
changed = [i for i, (a, b) in enumerate(zip(got, expected)) if a != b]
assert len(changed) == 16, changed
first = changed[0]
print(f'{adapter} shifted W control: {len(changed)} differences, first component {first} '
f'expected {expected[first]:04x}, read {got[first]:04x}')

if name in ('r', 'rg'):
# Same channel count, but an R32/R32G32 view is from a different format family.
untouched = [0x30000000 + i for i in range(32 * height * channels)]
got, result = run(directory, consumer, env, 'texture-exact-' + name, f'<{len(untouched)}I')
compare(got, untouched, name + ' wrong format', result)
assert len(lines(result, 'Dispatch(2, 1, 1) refused: a D16 image store requires a matching '
'half-float UAV and resource')) == 1, result.stderr


def main(cli, consumer, renderer, sdk, adapter):
wave = render(renderer, adapter, '--shader-wave32')
assert wave.returncode == 0, wave.stdout + wave.stderr
with TemporaryDirectory() as directory:
for case in CASES:
check(Path(directory) / case[0], cli, sdk, consumer, adapter, case)


if __name__ == '__main__':
if sys.argv[1] == 'compile':
controls(*sys.argv[2:])
else:
main(*sys.argv[1:])
Loading
Loading