Skip to content

Commit 0341c55

Browse files
committed
test(oot): W1 flatten pass in the translator — sgid->global-lane for addressing, block-scaled stage header
MeshStage.cs (behind TOTK_MESH_THREADS_SCALE): the mesh body's subgroup lane id used for addressing becomes dm_lid (subgroup masks keep the per-32-lane id), and the wrapper's mem[0] is scaled by threads/32 so one group covers that many 32-blocks; 32-lane strides stay, stage layout unchanged. fed302d7 variant: compiles, reflection matches the seed except threadgroup_size, mode 3 loads it — but 64-thread execution still faults at main+0x1c4280 (raw-pool address path still 32-lane). Documented in mesh-threads-poc.md with the next step.
1 parent 3865baa commit 0341c55

3 files changed

Lines changed: 45 additions & 3 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,4 @@ games/totk/tools/totk_xlate/bin/
3030
games/totk/scripts/shader_inventory/obj/
3131
games/totk/scripts/shader_inventory/bin/
3232
ultracode.md
33+
obj/

‎games/oot/docs/mesh-threads-poc.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,20 @@ Bench limits are now printed by failing compiles on any Mac: 512 verts/group is
7070
and 256 verts x 10 float4 exceeds the 32 KB mesh-size cap on the M2. The `g*` variants (body lane id
7171
= `thread_index_in_simdgroup` only, like the real guest body) show the real shape gains nothing from
7272
more threads without the IR lane flattening: g32 41.7 / g64 36.4 / g128 42.3 ms vs t128 16.6 ms.
73+
74+
## Update (2026-11-26, later): lane-flattening pass implemented in the translator, variant loads but still faults at 64 threads
75+
76+
`MeshStage.cs` gained a flattening pass (behind the existing `TOTK_MESH_THREADS_SCALE`): when the scaled
77+
thread count is a power of two > 32, the body's subgroup lane id used for addressing is replaced by the
78+
global thread id (`dm_lid`, passed in as a new `dm_flat` parameter; subgroup *mask* lines keep the
79+
per-32-lane subgroup id), and the wrapper's stage header `mem[0]` is scaled by `threads/32` so one
80+
threadgroup covers that many 32-vertex blocks (the guest grid stays sized for 32, out-of-range groups
81+
no-op via the body's bounds check). All 32-lane strides/decompositions in the body stay at 32, so the
82+
stage layout and export loops are unchanged.
83+
84+
Validated on fed302d7: the variant generates, compiles standalone (`xcrun metal`), its reflection
85+
equals the seed's except `threadgroup_size`/`mesh_stage.threads`, and mode 3 **loads** it
86+
("loaded mode=3"). But running at 64 threads still SIGSEGVs the guest at `main+0x1c4280` (fault=0x1)
87+
at world entry — the raw-pool address path in the body (not just the `_77` vertex id) still assumes 32
88+
lanes. Next step: trace that faulting access (watch/`mscan` on the pool table read) and flatten it too;
89+
the acceptance stays probe-gpu-mesh + pixel-identical foliage vs the 32-thread build.

‎games/oot/tools/totk_xlate/MeshStage.cs‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ sealed class MeshStage
1010
{
1111
readonly string kind;
1212
int threads; readonly int payload, maxV, maxP; // threads is scaled by TOTK_MESH_THREADS_SCALE (PoC, 2026-11-26)
13+
int flatShift; // W1 flattening (PoC): when threads>32, the body's 32-lane stride becomes 2^(5+flatShift) and the lane id becomes the global thread id (dm_lid); subgroup masks stay per-32-lane
1314
readonly bool task, deviceAllowed; // deviceAllowed: the request may say stage_device=false (tests reading the stage memory from a compute wrapper)
1415
readonly List<(int n,int c)> vertex = new(), primitive = new();
1516
readonly int[] layout;
@@ -60,6 +61,9 @@ public MeshStage(JsonObject rq,JsonObject job,string outDir) {
6061
// follow, so the generated body stays consistent; the reflection reports the scaled count.
6162
var e = Environment.GetEnvironmentVariable("TOTK_MESH_THREADS_SCALE");
6263
if (!string.IsNullOrEmpty(e)) { int k = int.Parse(e.Trim()); if (k > 1) { threads = Math.Min(threads * k, 1024); rq["local"] = new JsonArray(threads, 1, 1); } }
64+
if (threads > 32 && (threads & (threads - 1)) == 0 && threads % 32 == 0 && threads <= 512) {
65+
flatShift = 0; while ((32 << flatShift) < threads) flatShift++; // stride shift 5 -> 5+flatShift
66+
}
6367
}
6468
int output=16+Align(payload,16), prim;
6569
if(kind=="ts") {prim=output+payload;shared=output+Align(payload,4);}
@@ -95,7 +99,7 @@ public MeshStage(JsonObject rq,JsonObject job,string outDir) {
9599
string path=Path.Combine(outDir,(string)rq["variant"]+".mesh.code");File.WriteAllBytes(path,code[0x80..]);job["code"]=path;
96100
job["local"]=new JsonArray(threads,1,1);job["shared"]=shared;job["stage_memory"]=new JsonArray(layout.Select(x=>(JsonNode)JsonValue.Create(x)).ToArray());
97101
}
98-
public JsonObject Reflection()=>new(){["kind"]=kind,["threads"]=threads,["payload"]=payload,["task"]=task,["device"]=Device,["byte_stores"]=ByteStores};
102+
public JsonObject Reflection()=>new(){["kind"]=kind,["threads"]=threads,["payload"]=payload,["task"]=task,["device"]=Device,["byte_stores"]=ByteStores}; // flat_shift stays internal: the mode-3 loader requires the candidate reflection to equal the original except threadgroup_size / mesh_stage.threads
99103
static List<string> Params(string t) {
100104
var r=new List<string>();int depth=0,at=0;
101105
for(int i=0;i<t.Length;i++){char c=t[i];if(c==','&&depth==0){r.Add(t[at..i].Trim());at=i+1;}if("([<".Contains(c))depth++;if(")]>".Contains(c))depth--;}
@@ -125,14 +129,33 @@ public string Wrap(string msl) {
125129
}
126130
Device=device;
127131
src=ByteStores_(src);
132+
int flatLane=0, flatStride=0;
133+
if (flatShift > 0) {
134+
// W1 lane flattening (PoC): the guest body addresses the stage with (instance << 5) + subgroup-lane.
135+
// With threads = 2^(5+flatShift) per group, use the global thread id (dm_lid) as the lane and scale the
136+
// instance stride << 5 -> << (5+flatShift), so every thread owns a distinct vertex and no two threads race.
137+
// Subgroup masks (lines containing "Mask") keep the per-32-lane subgroup id: their semantics are per SIMD group.
138+
string sgid = pars.Select(p => Regex.Match(p, @"(uint3?)\s+(\w+)\s*\[\[thread_index_in_simdgroup\]\]$"))
139+
.Where(x => x.Success).Select(x => x.Groups[2].Value).FirstOrDefault();
140+
if (sgid != null) {
141+
src = Regex.Replace(src, @"dm_stage_body\(([^)]*)\)", m => $"dm_stage_body({m.Groups[1].Value}, uint dm_flat)"); // the flat lane comes in as a parameter
142+
var lines = src.Split('\n').ToList();
143+
for (int i = 0; i < lines.Count; i++) {
144+
if (lines[i].Contains("Mask") || lines[i].Contains("dm_stage_body(")) continue;
145+
if (lines[i].Contains(sgid)) { lines[i] = lines[i].Replace(sgid, "dm_flat"); flatLane++; }
146+
}
147+
src = string.Join("\n", lines);
148+
flatStride = 0; // strides stay x32: each thread owns vertex (mem[0]<<5)+lid, and the wrapper lets one group cover threads/32 blocks
149+
}
150+
}
128151
string lid="dm_lid",tg="dm_tg";var extras=new List<string>();
129152
foreach(string attr in new[]{"thread_position_in_threadgroup","threadgroup_position_in_grid"}){
130153
var t=pars.Select(p=>Regex.Match(p,@"(uint3?)\s+(\w+)\s*\[\[("+attr+@")\]\]$")).FirstOrDefault(x=>x.Success);
131154
string name=t!=null?t.Groups[2].Value+(t.Groups[1].Value=="uint3"?".x":""):attr=="thread_position_in_threadgroup"?"dm_lid":"dm_tg";
132155
if(t==null)extras.Add($"uint {name} [[{attr}]]");if(attr=="thread_position_in_threadgroup")lid=name;else tg=name;
133156
}
134157
int pay=(payload+3)/4,output=layout[2]/4,prim=layout[3],input=4;
135-
string call=$"dm_stage_body({string.Join(", ",names.Append(mem))});";
158+
string call=$"dm_stage_body({string.Join(", ",names.Append(mem))}{(flatShift>0?", "+lid:"")});";
136159
string bar=device?"threadgroup_barrier(mem_flags::mem_threadgroup | mem_flags::mem_device);":"threadgroup_barrier(mem_flags::mem_threadgroup);";
137160
string start=device
138161
?$" threadgroup uint dm_slot_tg;\n if({lid}==0u){{ uint s, tries=0u; for(;;){{ s=atomic_fetch_add_explicit((device atomic_uint*)dm_scratch,1u,memory_order_relaxed)&dm_scratch[1]; if(atomic_exchange_explicit((device atomic_uint*)(dm_scratch+{ScratchFlagsWord}u+s),1u,memory_order_relaxed)==0u)break; if(++tries=={ScratchSpinLimit}u){{atomic_fetch_add_explicit((device atomic_uint*)(dm_scratch+{ScratchForcedWord}u),1u,memory_order_relaxed);break;}} }} dm_slot_tg=s; }}\n threadgroup_barrier(mem_flags::mem_threadgroup);\n device spvUnsafeArray<uint, {words}>& {mem}=*reinterpret_cast<device spvUnsafeArray<uint, {words}>*>(dm_scratch+{ScratchSlotsWord}u+dm_slot_tg*dm_scratch[2]);\n for(uint i={lid}; i<{words}u;i+={threads}u) {mem}[i]=0u;\n {bar}\n"
@@ -161,7 +184,8 @@ public string Wrap(string msl) {
161184
string sets=string.Concat(vn.Select(n=>$"v.{(n<0?"position":"a"+n)}={Vec(vertex,n)};\n"));
162185
string psets=string.Concat(pn.Select(n=>$"p.p{n}={Vec(primitive,n)};\n"));
163186
string Entry(string name,bool gl){
164-
string fill=task?$"for(uint i={lid};i<{pay}u;i+={threads}u){mem}[{input}u+i]=dm_payload.w[i];\n{bar}\nif({lid}==0u){{{mem}[0]={tg};{mem}[{input}]={tg};}}\n":$"if({lid}==0u){mem}[0]=dm_first[0]+{tg};\n";
187+
string blockscale=flatShift>0?"*"+(threads/32).ToString():"";
188+
string fill=task?$"for(uint i={lid};i<{pay}u;i+={threads}u){mem}[{input}u+i]=dm_payload.w[i];\n{bar}\nif({lid}==0u){{{mem}[0]={tg};{mem}[{input}]={tg};}}\n":$"if({lid}==0u){mem}[0]=dm_first[0]+{tg}{blockscale};\n";
165189
return $"[[mesh]] void {name}({sig}, dm_mesh_t dm_out, "+(task?"const object_data dm_payload_t& dm_payload [[payload]]":first)+scratch+$")\n{{\n{start}{fill}{bar}\n{call}\n{bar}\nuint np=min({mem}[{prim/4}]>>24,{maxP}u);\nif({lid}==0u)dm_out.set_primitive_count(np);\nfor(uint n={lid};n<{maxV}u;n+={threads}u){{uint b={output}u+(n/32u)*{vstride}u+n%32u; dm_vertex_t v;\n{sets}"+(gl?"v.position.z=fma(v.position.z,0.5,v.position.w*0.5);\n":"")+"dm_out.set_vertex(n,v);}\n"+(pn.Count>0?$"for(uint n={lid};n<np;n+={threads}u){{uint b={pbase}u+(n/32u)*{pstride}u+n%32u;dm_prim_t p;{psets}dm_out.set_primitive(n,p);}}\n":"")+$"for(uint n={lid};n<np*3u;n+={threads}u){{uint at={prim+4}u+n;dm_out.set_index(n,({mem}[at>>2]>>((at&3u)*8u))&255u);}}\n{release}}}\n";
166190
}
167191
return src+"\n"+head+Entry("main0",true)+"\n"+Entry("main0_z",false);

0 commit comments

Comments
 (0)