From 37bc6de8b1629d41e6c33ec122f42816189c0256 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 16 Oct 2026 19:59:42 +0200 Subject: [PATCH] cultmath: lavapipe shader generator, Vulkan host and job script tools/device/gen.py spells one HLSL and one GLSL ES 3.10 compute shader per work item, vkrun.c dispatches it on the first Vulkan device, run-lavapipe.sh runs the whole conforming job. None of them compares. Also fixes the metric test's family choice. Not yet run: these may not build or run. Co-Authored-By: Claude Sonnet 5.5 --- .../CultMath.Tests/GlslMirrorTests.Device.cs | 16 ++- packages/cultmath/tools/device/gen.py | 118 ++++++++++++++++++ .../cultmath/tools/device/run-lavapipe.sh | 59 +++++++++ packages/cultmath/tools/device/vkrun.c | 83 ++++++++++++ 4 files changed, 270 insertions(+), 6 deletions(-) create mode 100644 packages/cultmath/tools/device/gen.py create mode 100644 packages/cultmath/tools/device/run-lavapipe.sh create mode 100644 packages/cultmath/tools/device/vkrun.c diff --git a/packages/cultmath/tests/CultMath.Tests/GlslMirrorTests.Device.cs b/packages/cultmath/tests/CultMath.Tests/GlslMirrorTests.Device.cs index d4d9b849..9d561b66 100644 --- a/packages/cultmath/tests/CultMath.Tests/GlslMirrorTests.Device.cs +++ b/packages/cultmath/tests/CultMath.Tests/GlslMirrorTests.Device.cs @@ -449,12 +449,16 @@ public sealed partial class GlslMirrorTests { // The metric divides by max(|fixture|, 1): a result of twice a fixture value of at least 2 is 2^23 away, // and of twice a fixture value under 1 is |fixture| 2^23 away. - var f = BoundFamily(); - var cases = FixtureFamilies()[f]!["cases"]!.AsArray(); - float Fixture(int c) => BitConverter.UInt32BitsToSingle(DevWords(Sides(cases[c])[1])[0]); - var large = Enumerable.Range(0, cases.Count).First(c => Math.Abs(Fixture(c)) is >= 2.0f and < 1e30f); - var small = Enumerable.Range(0, cases.Count).First(c => Math.Abs(Fixture(c)) is > 1e-3f and < 1.0f); - foreach (var (c, expected) in new[] { (large, Math.ScaleB(1.0, 23)), (small, Math.Abs((double)Fixture(small)) * Math.ScaleB(1.0, 23)) }) + var fixture = FixtureFamilies(); + float Fixture(int family, int c) => BitConverter.UInt32BitsToSingle(DevWords(Sides(fixture[family]!["cases"]![c])[1])[0]); + int Find(int family, Func wanted) => Enumerable.Range(0, Points).FirstOrDefault(c => wanted(Math.Abs(Fixture(family, c))), -1); + bool Large(float v) => v is >= 2.0f and < 1e30f; + bool Small(float v) => v is > 1e-3f and < 1.0f; + var f = Enumerable.Range(0, Families.Length).First(g => Families[g].Tolerance == "ulp-bounded" && Families[g].Verify is null + && FloatWords(Resolve(Families[g].Glsl).ReturnType).First() && Find(g, Large) >= 0 && Find(g, Small) >= 0); + var large = Find(f, Large); + var small = Find(f, Small); + foreach (var (c, expected) in new[] { (large, Math.ScaleB(1.0, 23)), (small, Math.Abs((double)Fixture(f, small)) * Math.ScaleB(1.0, 23)) }) { using var device = Simulate((_, item, words) => { diff --git a/packages/cultmath/tools/device/gen.py b/packages/cultmath/tools/device/gen.py new file mode 100644 index 00000000..4dfd70ca --- /dev/null +++ b/packages/cultmath/tools/device/gen.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Spell one compute shader per work item, in HLSL and in GLSL ES 3.10. It compares and judges nothing. + +usage: gen.py + +/manifest.txt (written by GlslMirrorTests.WriteDeviceWork) has one tab-separated line per item: +tag, fixture index, glsl signature, n, words in, words out. For each item this writes .hlsl (cs_6_0, +includes CultMath.hlsl) and .comp (#version 310 es, the committed GLSL files, then the body). An item +reads n argument tuples of 32-bit words from binding 0 and writes n result tuples to binding 1. Struct +arguments and results are built and flattened in field order, from the struct definitions in the HLSL.""" +import glob +import os +import re +import sys + +HLSL_VEC = re.compile(r'(float|int|uint)([234])$') +GLSL_VEC = re.compile(r'(i|u|)vec([234])$') +KIND = {'float': 'f', 'int': 'i', 'uint': 'u'} + + +def structs(root): + """struct name -> [(field, type, hlsl)] from every shader's struct definitions, GLSL type names.""" + found = {} + for path in sorted(glob.glob(os.path.join(root, 'shaders', '*.hlsl'))): + for name, body in re.findall(r'(?m)^struct (\w+)\s*\{(.*?)\};', open(path).read(), re.S): + found[name] = [(f, t) for t, f in re.findall(r'(\w+)\s+(\w+);', body)] + return found + + +def leaves(t, defs, path=''): + """Flatten a type (GLSL spelling for scalars and vectors, HLSL for struct fields) to scalar leaves: + (accessor path, kind) in field order. A vector's components are path[i]; a mat3 is read row by row.""" + if t in KIND: + return [(path, KIND[t], None)] + m = HLSL_VEC.match(t) or GLSL_VEC.match(t) + if m: + k = {'float': 'f', 'int': 'i', 'uint': 'u', '': 'f', 'i': 'i', 'u': 'u'}[m.group(1)] + return [(path, k, i) for i in range(int(m.group(2)))] + if t in ('mat3', 'float3x3'): + return [(path, 'f', (i, j)) for i in range(3) for j in range(3)] + if t in defs: + out = [] + for field, ft in defs[t]: + out += leaves(ft, defs, path + '.' + field) + return out + raise SystemExit('unsupported type ' + t) + + +def access(leaf, glsl): + path, _, index = leaf + if index is None: + return path + if isinstance(index, tuple): # row i, column j; GLSL matrices index the column first + return '%s[%d][%d]' % ((path,) + ((index[1], index[0]) if glsl else index)) + return '%s[%d]' % (path, index) + + +def read(kind, glsl, word): + if glsl: + return {'f': 'uintBitsToFloat(%s)', 'i': 'int(%s)', 'u': '%s'}[kind] % word + return {'f': 'asfloat(%s)', 'i': 'asint(%s)', 'u': '%s'}[kind] % word + + +def write(kind, glsl, value): + if glsl: + return {'f': 'floatBitsToUint(%s)', 'i': 'uint(%s)', 'u': '%s'}[kind] % value + return {'f': 'asuint(%s)', 'i': 'asuint(%s)', 'u': '%s'}[kind] % value + + +def body(sig, n, win, wout, defs, glsl): + m = re.fullmatch(r'(\w+)\s+(\w+)\((.*)\)', sig) + ret, name, params = m.group(1), m.group(2), [p.strip() for p in m.group(3).split(',') if p.strip()] + lines, offset, args = [], 0, [] + for j, p in enumerate(params): + ptype = p if glsl else re.sub(r'\bvec([234])\b', r'float\1', re.sub(r'\bmat3\b', 'float3x3', p)) + ptype = ptype if glsl else re.sub(r'\bivec([234])\b', r'int\1', ptype) + lines.append(' %s a%d;' % (ptype, j)) + for leaf in leaves(p, defs): + word = ('In.a[b + %du]' if glsl else 'In[b + %d]') % offset + lines.append(' a%d%s = %s;' % (j, access(leaf, glsl), read(leaf[1], glsl, word))) + offset += 1 + args.append('a%d' % j) + rtype = ret if glsl else re.sub(r'\bvec([234])\b', r'float\1', re.sub(r'\bmat3\b', 'float3x3', ret)) + lines.append(' %s r = %s(%s);' % (rtype, name, ', '.join(args))) + produced = leaves(ret, defs) + for k, leaf in enumerate(produced): + target = ('Out.a[o + %du]' if glsl else 'Out[o + %d]') % k + lines.append(' %s = %s;' % (target, write(leaf[1], glsl, 'r' + access(leaf, glsl)))) + if offset != win or len(produced) != wout: + raise SystemExit('%s: %d words in and %d out, the manifest says %d and %d' % (sig, offset, len(produced), win, wout)) + head = 'uint i = id.x; if (i >= %du) return; uint b = i * %du; uint o = i * %du;' % (n, win, wout) + return head, '\n'.join(lines) + + +def main(work, root): + defs = structs(root) + shaders = os.path.join(root, 'shaders') + library = ''.join(open(os.path.join(shaders, f)).read() for f in ('CultMath.glsl', 'CultMath.Cycles.glsl', 'CultMath.Phacelle.glsl')) + count = 0 + for line in open(os.path.join(work, 'manifest.txt')): + tag, _, sig, n, win, wout = line.rstrip('\n').split('\t') + n, win, wout = int(n), int(win), int(wout) + head, code = body(sig, n, win, wout, defs, False) + open(os.path.join(work, tag + '.hlsl'), 'w').write( + '#include "CultMath.hlsl"\n[[vk::binding(0)]] StructuredBuffer In;\n[[vk::binding(1)]] RWStructuredBuffer Out;\n' + '[numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) {\n %s\n%s\n}\n' % (head, code)) + head, code = body(sig, n, win, wout, defs, True) + open(os.path.join(work, tag + '.comp'), 'w').write( + '#version 310 es\nprecision highp float;\nprecision highp int;\n' + library + + 'layout(local_size_x = 64) in;\nlayout(std430, binding = 0) readonly buffer IB { uint a[]; } In;\n' + 'layout(std430, binding = 1) buffer OB { uint a[]; } Out;\n' + 'void main() {\n uint i = gl_GlobalInvocationID.x; %s\n%s\n}\n' % (head.replace('uint i = id.x; ', ''), code)) + count += 1 + print('generated', count, 'work items') + + +if __name__ == '__main__': + main(sys.argv[1], sys.argv[2]) diff --git a/packages/cultmath/tools/device/run-lavapipe.sh b/packages/cultmath/tools/device/run-lavapipe.sh new file mode 100644 index 00000000..bc4fd55f --- /dev/null +++ b/packages/cultmath/tools/device/run-lavapipe.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# The lavapipe conforming run: every fixture family, through HLSL (dxc) and GLSL (glslang), on Mesa lavapipe, +# judged by GlslMirrorTests.DeviceResultsHoldFixture. This script spells, compiles and dispatches; the C# judge +# is the only thing that compares. +# +# Run from the CultLib root inside mcr.microsoft.com/dotnet/sdk:10.0 (Ubuntu 24.04), for example +# SUMMARY= tools/stopgap/ygg-verify.sh mcr.microsoft.com/dotnet/sdk:10.0 'bash packages/cultmath/tools/device/run-lavapipe.sh' +# WRITE_BOUNDS=1 re-records packages/cultmath/tests/CultMath.Tests/fixtures/device-bounds-lavapipe.txt and prints it +# between BOUNDS-BEGIN and BOUNDS-END, because the job's clone is discarded. +set -euo pipefail +ROOT=$(pwd) +CM=$ROOT/packages/cultmath +TESTS=$CM/tests/CultMath.Tests +DEV=$CM/tools/device +W=/tmp/device +SNAPSHOT=20261016T000000Z +DXC_URL=https://github.com/microsoft/DirectXShaderCompiler/releases/download/v1.9.2607/linux_dxc_2026_07_29.x86_x64.tar.gz +DXC_SHA=55665c87824051ed4774ff3280a79ccbbb7d39243b9736ca5e98222134112d54 +mkdir -p "$W/dxc" "$W/results/lavapipe-hlsl" "$W/results/lavapipe-glsl" + +export DEBIAN_FRONTEND=noninteractive +apt-get update -qq --snapshot "$SNAPSHOT" >/dev/null +apt-get install -y -qq --no-install-recommends mesa-vulkan-drivers libvulkan-dev glslang-tools spirv-tools gcc libc6-dev curl ca-certificates python3 >/dev/null + +curl -sL --fail -o "$W/dxc.tgz" "$DXC_URL" +echo "$DXC_SHA $W/dxc.tgz" | sha256sum -c - >/dev/null || { echo "dxc tarball sha256 differs from the pinned one"; exit 1; } +tar xzf "$W/dxc.tgz" -C "$W/dxc" +DXC=$(find "$W/dxc" -name dxc -type f | head -1) +export LD_LIBRARY_PATH=$(dirname "$DXC")/../lib:$(dirname "$DXC")${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} +gcc -O2 -o "$W/vkrun" "$DEV/vkrun.c" -lvulkan + +dotnet build "$TESTS" -nologo -v q >/dev/null +export CULTMATH_DEVICE_WORK=$W/work +dotnet test "$TESTS" --no-build --filter "FullyQualifiedName~GlslMirrorTests.WriteDeviceWork" +python3 "$DEV/gen.py" "$W/work" "$CM" + +while IFS=$'\t' read -r tag _ _ n _ wout; do + in=$W/work/$tag.in + "$DXC" -T cs_6_0 -E main -HV 2021 -spirv -fspv-target-env=vulkan1.2 -I "$CM/shaders" "$W/work/$tag.hlsl" -Fo "$W/work/$tag.h.spv" >"$W/work/$tag.h.log" 2>&1 \ + || { echo "dxc failed for $tag"; head -5 "$W/work/$tag.h.log"; exit 1; } + glslangValidator -V --target-env vulkan1.2 -o "$W/work/$tag.g.spv" "$W/work/$tag.comp" >"$W/work/$tag.g.log" 2>&1 \ + || { echo "glslang failed for $tag"; head -5 "$W/work/$tag.g.log"; exit 1; } + "$W/vkrun" "$W/work/$tag.h.spv" "$in" "$W/results/lavapipe-hlsl/$tag.out" "$n" "$wout" >>"$W/device.txt" + "$W/vkrun" "$W/work/$tag.g.spv" "$in" "$W/results/lavapipe-glsl/$tag.out" "$n" "$wout" >>"$W/device.txt" +done <"$W/work/manifest.txt" + +RENDERER=$(sort -u "$W/device.txt") +[ "$(echo "$RENDERER" | wc -l)" = 1 ] || { echo "the runs saw more than one device: $RENDERER"; exit 1; } +export CULTMATH_DEVICE_NAME=${RENDERER#device=} +export CULTMATH_DEVICE_IDENTITY="$(dpkg-query -W -f='${Package} ${Version}; ' mesa-vulkan-drivers glslang-tools)dxc $("$DXC" --version | head -1); apt snapshot $SNAPSHOT" +export CULTMATH_DEVICE_RESULTS=$W/results +echo "device: $CULTMATH_DEVICE_NAME" +echo "identity: $CULTMATH_DEVICE_IDENTITY" + +if [ "${WRITE_BOUNDS:-0}" = 1 ]; then + export CULTMATH_WRITE_DEVICE_BOUNDS=1 + trap 'echo BOUNDS-BEGIN; cat "$TESTS/fixtures/device-bounds-lavapipe.txt"; echo BOUNDS-END' EXIT +fi +dotnet test "$TESTS" --no-build --filter "FullyQualifiedName~GlslMirrorTests.DeviceResultsHoldFixture" --logger "console;verbosity=detailed" diff --git a/packages/cultmath/tools/device/vkrun.c b/packages/cultmath/tools/device/vkrun.c new file mode 100644 index 00000000..6ba6a336 --- /dev/null +++ b/packages/cultmath/tools/device/vkrun.c @@ -0,0 +1,83 @@ +// Vulkan compute host for the conforming run: one dispatch of a generated shader on the first Vulkan device, +// binding 0 = input words, binding 1 = output words. It prints the device's name on stdout and judges nothing. +// usage: vkrun +#include +#include +#include +#include +#define CK(x) do { VkResult r_ = (x); if (r_ != VK_SUCCESS) { fprintf(stderr, "FAIL %s = %d\n", #x, r_); exit(2); } } while (0) + +static void *slurp(const char *p, size_t *n) { + FILE *f = fopen(p, "rb"); if (!f) { perror(p); exit(2); } + fseek(f, 0, SEEK_END); *n = ftell(f); fseek(f, 0, SEEK_SET); + void *b = malloc(*n ? *n : 4); fread(b, 1, *n, f); fclose(f); return b; +} + +int main(int argc, char **argv) { + if (argc != 6) { fprintf(stderr, "usage\n"); return 2; } + size_t spvn, inn; void *spv = slurp(argv[1], &spvn); void *in = slurp(argv[2], &inn); + unsigned ncases = atoi(argv[4]), ow = atoi(argv[5]); const char *entry = "main"; + size_t outn = (size_t)ncases * ow * 4; + + VkApplicationInfo ai = { VK_STRUCTURE_TYPE_APPLICATION_INFO, 0, "vkrun", 1, "vkrun", 1, VK_API_VERSION_1_2 }; + VkInstanceCreateInfo ici = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, 0, 0, &ai }; + VkInstance inst; CK(vkCreateInstance(&ici, 0, &inst)); + uint32_t np = 1; VkPhysicalDevice pd; vkEnumeratePhysicalDevices(inst, &np, &pd); if (!np) { fprintf(stderr, "no device\n"); return 2; } + VkPhysicalDeviceProperties props; + vkGetPhysicalDeviceProperties(pd, &props); + printf("device=%s\n", props.deviceName); + + float prio = 1; VkDeviceQueueCreateInfo qci = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, 0, 0, 0, 1, &prio }; + VkDeviceCreateInfo dci = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, 0, 0, 1, &qci }; + VkDevice dev; CK(vkCreateDevice(pd, &dci, 0, &dev)); VkQueue q; vkGetDeviceQueue(dev, 0, 0, &q); + + VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); + VkBuffer buf[2]; VkDeviceMemory mem[2]; size_t sz[2] = { inn, outn }; void *map[2]; + for (int i = 0; i < 2; i++) { + VkBufferCreateInfo bci = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, 0, 0, sz[i], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT }; + CK(vkCreateBuffer(dev, &bci, 0, &buf[i])); VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, buf[i], &mr); + uint32_t t = 0; VkMemoryPropertyFlags want = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + for (; t < mp.memoryTypeCount; t++) if ((mr.memoryTypeBits & (1u << t)) && (mp.memoryTypes[t].propertyFlags & want) == want) break; + VkMemoryAllocateInfo mai = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, 0, mr.size, t }; + CK(vkAllocateMemory(dev, &mai, 0, &mem[i])); CK(vkBindBufferMemory(dev, buf[i], mem[i], 0)); + CK(vkMapMemory(dev, mem[i], 0, sz[i], 0, &map[i])); + } + memcpy(map[0], in, inn); memset(map[1], 0xEE, outn); + + VkDescriptorSetLayoutBinding b[2] = { { 0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT }, + { 1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT } }; + VkDescriptorSetLayoutCreateInfo lci = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, 0, 0, 2, b }; + VkDescriptorSetLayout dsl; CK(vkCreateDescriptorSetLayout(dev, &lci, 0, &dsl)); + VkPipelineLayoutCreateInfo plci = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, 0, 0, 1, &dsl }; + VkPipelineLayout pl; CK(vkCreatePipelineLayout(dev, &plci, 0, &pl)); + VkShaderModuleCreateInfo smci = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, 0, 0, spvn, spv }; + VkShaderModule sm; CK(vkCreateShaderModule(dev, &smci, 0, &sm)); + VkComputePipelineCreateInfo cpci = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, 0, 0, + { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, 0, 0, VK_SHADER_STAGE_COMPUTE_BIT, sm, entry }, pl }; + VkPipeline pipe; CK(vkCreateComputePipelines(dev, 0, 1, &cpci, 0, &pipe)); + + VkDescriptorPoolSize ps = { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2 }; + VkDescriptorPoolCreateInfo dpci = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, 0, 0, 1, 1, &ps }; + VkDescriptorPool dp; CK(vkCreateDescriptorPool(dev, &dpci, 0, &dp)); + VkDescriptorSetAllocateInfo dsai = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, 0, dp, 1, &dsl }; + VkDescriptorSet ds; CK(vkAllocateDescriptorSets(dev, &dsai, &ds)); + VkDescriptorBufferInfo dbi[2] = { { buf[0], 0, VK_WHOLE_SIZE }, { buf[1], 0, VK_WHOLE_SIZE } }; + VkWriteDescriptorSet w[2]; + for (int i = 0; i < 2; i++) { VkWriteDescriptorSet x = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, 0, ds, i, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, &dbi[i] }; w[i] = x; } + vkUpdateDescriptorSets(dev, 2, w, 0, 0); + + VkCommandPoolCreateInfo cpi = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, 0, 0, 0 }; + VkCommandPool cp; CK(vkCreateCommandPool(dev, &cpi, 0, &cp)); + VkCommandBufferAllocateInfo cbai = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, 0, cp, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1 }; + VkCommandBuffer cb; CK(vkAllocateCommandBuffers(dev, &cbai, &cb)); + VkCommandBufferBeginInfo cbbi = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; + CK(vkBeginCommandBuffer(cb, &cbbi)); + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, 0); + vkCmdDispatch(cb, (ncases + 63) / 64, 1, 1); + CK(vkEndCommandBuffer(cb)); + VkSubmitInfo si = { VK_STRUCTURE_TYPE_SUBMIT_INFO, 0, 0, 0, 0, 1, &cb }; + CK(vkQueueSubmit(q, 1, &si, 0)); CK(vkQueueWaitIdle(q)); + FILE *f = fopen(argv[3], "wb"); fwrite(map[1], 1, outn, f); fclose(f); + return 0; +}