okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
db137d917
main
1#!/usr/bin/env python3 2"""Hand fixes on top of the SYCLomatic output (sycl/tools/migrate.sh). Idempotent: re-run after a re-migration. 3 4Each entry is a thing dpct 2025.3 got wrong or could not do, with the reason. Upstream files are never touched. 5""" 6import re ,pathlib 7root = pathlib .Path (__file__ ).resolve ().parents [1 ] 8changed = 0 9 10def edit (rel ,fn ): 11global changed 12p = root / rel 13if not p .exists (): 14" (absent)" ,rel );return 15s = p .read_text ();t = fn (s ) 16if t != s : 17p .write_text (t );changed += 1 ;" fixed" ,rel ) 18 19def sub (pattern ,repl ,flags = 0 ): 20return lambda s :re .sub (pattern ,repl ,s ,flags = flags ) 21 22def all_sources (): 23return [p .relative_to (root )for p in (root / "src" ).rglob ("*.cpp" )] 24 25# 1. dpct's helper headers predate the 2026.1 compiler: the non-uniform group API was renamed. 26edit ("include/dpct/util.hpp" ,lambda s :s .replace ("experimental::get_tangle_group(" ,"experimental::entangle(" ) 27 .replace ("experimental::get_fixed_size_group<" ,"experimental::chunked_partition<" )) 28 29for rel in all_sources (): 30rel = str (rel ) 31# 2. `(dpct::queue_ptr)stream->memcpy(...)`: the cast binds to the member call result, not the pointer. 32edit (rel ,sub (r"\(dpct::queue_ptr\)\s*(\w+)\s*->" ,r"((dpct::queue_ptr)\1)->" )) 33# 3. cudaStreamSynchronize(x) came out as `(cudaStream_t)x->wait()`; a null stream is the default queue. 34edit (rel ,sub (r"\(cudaStream_t\)0->wait\(\)" ,"dpct::get_in_order_queue().wait()" )) 35edit (rel ,sub (r"\(cudaStream_t\)(\w+)->wait\(\)" ,r"((dpct::queue_ptr)\1)->wait()" )) 36edit (rel ,sub (r"DPCT_CHECK_ERROR\((main_cs|token_stream)->wait\(\)\)" ,r"DPCT_CHECK_ERROR(((dpct::queue_ptr)\1)->wait())" )) 37# a null stream: the default in-order queue 38edit (rel ,lambda s :s .replace ("(nullptr)->ext_oneapi_graph(" ,"dpct::get_in_order_queue().ext_oneapi_graph(" )) 39# cudaGraphUpload has no SYCL counterpart (an executable command_graph is ready when finalized). 40edit (rel ,sub (r"const dpct::err0 ue = cudaGraphUpload\(\w+(\[\w+\])?, \w+\);" ,"const dpct::err0 ue = 0; // no cudaGraphUpload on SYCL: a finalized command_graph is already resident" )) 41edit (rel ,sub (r"^(\s*)cudaGraphUpload\(\w+, \w+\);" ,r"\1// no cudaGraphUpload on SYCL: a finalized command_graph is already resident" ,re .M )) 42# __fadd_rn / __float_as_uint spellings 43for _ in range (3 ):# nested __fadd_rn(__fadd_rn(a, b), c) 44# the second operand parenthesised: `__fadd_rn(sum, c ? x : y)` must not become `(sum + c ? x : y)` 45# (2026-10-01: it did, in the QSA indexer's pooled sum and the QSA block scores - the sum was replaced, not added) 46edit (rel ,sub (r"__fadd_rn\((\([^()]*\)|[^,()]+),\s*([^()]+)\)" ,r"(\1 + (\2))" )) 47edit (rel ,lambda s :s .replace ("__float_as_uint(" ,"sycl::bit_cast<uint32_t>(" )) 48# 4. volatile casts on kernel arguments (the kernels take plain pointers). 49edit (rel ,lambda s :s .replace ("(const volatile sycl::float4 *)" ,"(const sycl::float4 *)" )) 50# 5. CUDA math intrinsics with no SYCL spelling. 51edit (rel ,lambda s :s .replace ("__isnanf(" ,"sycl::isnan(" ).replace ("__isinff(" ,"sycl::isinf(" )) 52# 6. __nanosleep inside a doorbell spin: spin without the nap. 53edit (rel ,sub (r"__nanosleep\(\d+\);" ,"/* spin (no __nanosleep on SYCL) */;" )) 54# 7. `__fadd_rn(a, b ? c : d)` lost its parentheses. 55edit (rel ,sub (r"= (\w+) \+ (\w+) \? (\w+\[\w+\]) : 0\.0f;" ,r"= \1 + (\2 ? \3 : 0.0f);" )) 56# 8. cudaStreamQuery(s): dpct writes `DPCT_CHECK_ERROR(s->ext_oneapi_empty())`, which is 0 whenever the call does not 57# throw, so the ring waits' `q != 1` guard (1 = still running) was always true and any wait over 2 ms "never rang". 58edit (rel ,sub (r"(const dpct::err0 q =)\s*DPCT_CHECK_ERROR\(\(+(\w+)\)*->ext_oneapi_empty\(\)\)+;" , 59r"\1 \2->ext_oneapi_empty() ? 0 : 1;" )) 60 61# 2b. every `(dpct::queue_ptr) stream` cast goes through strata::q_of(), which maps CUDA's null stream to the 62# default in-order queue instead of dereferencing a null sycl::queue* (include/strata/sycl_queue.hpp). 63def q_of (s ): 64t = re .sub (r"\(\(sycl::queue \*\)\(\(dpct::queue_ptr\)\s*(\w+)\)\)" ,r"strata::q_of(\1)" ,s ) 65t = re .sub (r"(?<!\w)\(\(dpct::queue_ptr\)\s*(\w+)\)" ,r"strata::q_of(\1)" ,t )# not a call's own paren 66t = re .sub (r"\(dpct::queue_ptr\)\s*((?:\w+(?:->|\.))*\w+)\b" ,r"strata::q_of(\1)" ,t ) 67t = re .sub (r"static_cast<dpct::queue_ptr>\((\w+)\)" ,r"strata::q_of(\1)" ,t ) 68if t != s and '#include "strata/sycl_queue.hpp"' not in t : 69t = t .replace ("#include <dpct/dpct.hpp>\n" ,'#include <dpct/dpct.hpp>\n#include "strata/sycl_queue.hpp"\n' ,1 ) 70return t 71for rel in all_sources (): 72edit (str (rel ),q_of ) 73 74# 7b. `__ldg((const float*) p)` lost its cast: dpct rewrote it as `*p`, reading one byte of the scale. 75edit ("src/kernels/cuda/s_gemv.dp.cpp" ,lambda s :s .replace ("const float d = *blk;" ,"const float d = *(const float*) blk;" ) 76 .replace ("Q8K ? *xb" ,"Q8K ? *(const float*) xb" )) 77 78# 7c. the doorbell: `volatile` device loads/stores of host-mapped flags do not bypass the GPU caches on Intel 79# (the spin never saw the host's write). System-scope atomic load/store do (include/strata/sycl_doorbell.hpp). 80def doorbell (s ): 81if "sycl_doorbell.hpp" not in s : 82s = s .replace ('#include "strata/sycl_queue.hpp"\n' ,'#include "strata/sycl_queue.hpp"\n#include "strata/sycl_doorbell.hpp"\n' ,1 ) 83s = s .replace (" *seq = *seq + 1u;" ," strata::sys_store(seq, strata::sys_load(seq) + 1u);" ) 84s = s .replace (" const uint32_t want = *seq;\n" ," const uint32_t want = strata::sys_load(seq);\n" ) 85s = s .replace (" while (*flag != want) /* spin (no __nanosleep on SYCL) */;" ," while (strata::sys_load(flag) != want) /* spin (no __nanosleep on SYCL) */;" ) 86s = s .replace (" while (*flag < value) /* spin (no __nanosleep on SYCL) */;" ," while (strata::sys_load(flag) < value) /* spin (no __nanosleep on SYCL) */;" ) 87s = s .replace (" if (*skip == value) return;" ," if (strata::sys_load(skip) == value) return;" ) 88s = s .replace (" *skip = ring;\n}" ," strata::sys_store(skip, ring);\n}" ) 89s = s .replace (" *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u;" ," strata::sys_store(seq, strata::sys_load(seq) + 1u);" ) 90# bounded spins (see kSpinMax in sycl_doorbell.hpp) 91s = s .replace (" while (strata::sys_load(flag) != want) /* spin (no __nanosleep on SYCL) */;" , 92" for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) != want; ++spin) {}" ) 93s = s .replace (" while (strata::sys_load(flag) < value) /* spin (no __nanosleep on SYCL) */;" , 94" for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) < value; ++spin) {}" ) 95# upstream 0.1.31 spells the waits `while (*flag ...) strata_spin_pause();` and the ring with 4-space indent: 96# same treatment (system-scope loads/stores, bounded: an unbounded orphaned spin wedges the B70's GT) 97s = s .replace (" *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u;" ," strata::sys_store(seq, strata::sys_load(seq) + 1u);" ) 98s = s .replace (" while (*flag != want) strata_spin_pause();" , 99" for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) != want; ++spin) strata_spin_pause();" ) 100s = s .replace (" while (*flag < value) strata_spin_pause();" , 101" for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) < value; ++spin) strata_spin_pause();" ) 102return s 103# 0.1.31: dp4a.hpp's spin pause is __nanosleep, which SYCL lacks: the bounded spin (kSpinMax) is the backoff 104edit ("include/strata/kernels/dp4a.hpp" ,lambda s :s .replace (" __nanosleep(100);\n" , 105" // SYCL port: no __nanosleep; the doorbell waits are bounded by strata::kSpinMax instead\n" )) 106# 0.1.31/0.1.32: fused_gr's per-block shared-memory query stays CUDA (dpct leaves the attribute untranslated) 107edit ("src/kernels/cuda/fused_gr.dp.cpp" ,lambda s :s .replace ( 108" cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev);\n" , 109" per_block = (int) dpct::get_device(dev).get_local_mem_size(); // SYCL: the work-group local memory\n" )) 110# upstream PR #413 / 0.1.36+: the key-head DeltaNet kernel's cp.async helpers keep CUDA's address conversion in the 111# non-NVPTX branch; the SYCL build takes the plain-copy form (upstream's own pre-sm_80 path) 112def gdn_plain_copies (s ): 113s = s .replace ("#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP < 800\n#define STRATA_GDN_CP_ASYNC 0" , 114"#if 1 // SYCL port: plain copies (no cp.async)\n#define STRATA_GDN_CP_ASYNC 0" ) 115return s .replace ("*reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);" , 116"*reinterpret_cast<sycl::float4*>(smem) = *reinterpret_cast<const sycl::float4*>(gmem);" ) 117edit ("src/prefill/kernels.dp.cpp" ,gdn_plain_copies ) 118# 0.1.38: upstream's sm_90 thread-block-cluster greedy sampler (cudaLaunchKernelEx with a cluster dimension) has no 119# SYCL counterpart: the HIP branch's "not available" answer, so the caller takes the plain greedy kernel 120edit ("src/kernels/cuda/sampler.dp.cpp" ,lambda s :s .replace ( 121" int *out, void *stream) try {\n#if defined(__HIPCC__)\n" , 122" int *out, void *stream) try {\n#if 1 // SYCL port: no thread-block clusters (sm_90): the caller takes the plain greedy kernel\n" )) 123edit ("src/kernels/cuda/qsa_select.dp.cpp" ,lambda s :s .replace ( 124" void *stream) try {\n#if defined(__HIPCC__)\n" , 125" void *stream) try {\n#if 1 // SYCL port: no thread-block clusters (sm_90): the caller takes the plain top-k\n" )) 126# 0.1.38: dpct could not deduce fused_gr's templated kernel names (the staged read and the MAX_T down kernels) 127def gr_kernel_names (s ): 128# the tile is a number (Flash-Next 1280 / 2560 before the geometry came from core/geometry.hpp) or the expression the source now 129# spells it as: `N`, `(N / 2)` (fused_gr.cu, Q4-SYCL) 130pat = re .compile (r",\s*dpct_placeholder /\*Fix the type mannually\*/>>\((.{0,900}?)\b(gr_down_staged_kernel|gr_down_multi_kernel<(\d+|\w+|\([^<>()]+\))>)\(" ,re .S ) 131return pat .sub (lambda m : (">>(" if m .group (2 )== "gr_down_staged_kernel" else f", dpct_kernel_scalar< { m . group ( 3 ) } >>>(" ) 132+ m .group (1 )+ m .group (2 )+ "(" ,s ) 133edit ("src/kernels/cuda/fused_gr.dp.cpp" ,gr_kernel_names ) 134# 7c'. #1397: the bound of those spins is chosen per device at run time (strata::spin_max(queue), sycl_doorbell.hpp), not the 135# build's constant kSpinMax: each waiting kernel takes it as a `uint32_t spin_max` argument and its launcher passes 136# strata::spin_max(*strata::q_of(stream)). Idempotent: a file that already has the argument is left alone. 137def spin_bound_at_run_time (s ): 138for kernel ,launcher in (("doorbell_wait_kernel" ,"doorbell_wait" ), ("wait_flag_ge_or_kernel" ,"wait_flag_ge_or" ), 139 ("wait_flag_ge_kernel" ,"wait_flag_ge" )): 140sig = re .compile (r"(__dpct_inline__ void " + kernel + r"\([^)]*?)\)(\s*\{)" ) 141m = sig .search (s ) 142if m and "spin_max" not in m .group (1 ): 143s = s [:m .start ()]+ m .group (1 )+ ", uint32_t spin_max)" + m .group (2 )+ s [m .end ():] 144call = re .compile (r"(\b" + kernel + r"\((?:[^()]|\([^()]*\))*?)\);" ) 145s = call .sub (lambda c :c .group (0 )if "spin_max" in c .group (1 )else c .group (1 )+ ", spin_max);" ,s ) 146head = re .compile (r"^(void " + launcher + r"\([^)]*\)(?: try)? \{\n)" ,re .M ) 147h = head .search (s ) 148if h and "strata::spin_max(" not in s [h .end ():h .end ()+ 200 ]: 149at = h .end () 150guard = re .match (r" if \([^\n]*\) return;\n" ,s [at :])# a null-argument guard stays first 151if guard : 152at += guard .end () 153s = s [:at ]+ " const uint32_t spin_max = strata::spin_max(*strata::q_of(stream));\n" + s [at :] 154return s .replace ("strata::kSpinMax" ,"spin_max" ) 155edit ("src/kernels/cuda/elementwise.dp.cpp" ,lambda s :spin_bound_at_run_time (doorbell (s ))) 156edit ("src/kernels/cuda/verify_kernels.dp.cpp" ,lambda s :spin_bound_at_run_time (doorbell (s ))) 157 158# 7d. cudaMemcpy / cudaMemset are synchronous; dpct emitted `get_in_order_queue().memcpy(...)` with no wait where 159# the source was pageable ("call wait() if needed"). The streaming expert source hands out ring-buffer blobs, 160# so an unwaited fill copies from a buffer that has already been reused (measured: non-deterministic experts). 161# Every default-queue memcpy/memset that is not already waited on gets its .wait() back. 162def wait_default_queue_copies (s ): 163out = [];i = 0 ;n = 0 164key = "dpct::get_in_order_queue()." 165while True : 166j = s .find (key ,i ) 167if j < 0 :out .append (s [i :]);break 168k = j + len (key ) 169if not (s .startswith ("memcpy(" ,k )or s .startswith ("memset(" ,k )): 170out .append (s [i :k ]);i = k ;continue 171p0 = s .find ("(" ,k );depth = 0 ;q = p0 172while q < len (s ): 173if s [q ]== "(" :depth += 1 174elif s [q ]== ")" : 175depth -= 1 176if depth == 0 :break 177q += 1 178tail = s [q + 1 :q + 8 ] 179if tail .startswith (".wait()" ): 180out .append (s [i :q + 1 ]);i = q + 1 ;continue 181out .append (s [i :q + 1 ]);out .append (".wait()" );i = q + 1 ;n += 1 182return "" .join (out ) 183for rel in all_sources (): 184edit (str (rel ),wait_default_queue_copies ) 185 186# 7e. dpct::dp4a is emulation (eight integer ops); sycl::ext::oneapi::dot_acc is the DP4A instruction on Xe. 187def native_dp4a (s ): 188if "dpct::dp4a(" not in s :return s 189s = s .replace ("dpct::dp4a(" ,"strata::dp4a(" ) 190if "sycl_math.hpp" not in s : 191s = s .replace ("#include <dpct/dpct.hpp>\n" ,'#include <dpct/dpct.hpp>\n#include "strata/sycl_math.hpp"\n' ,1 ) 192return s 193for rel in all_sources (): 194edit (str (rel ),native_dp4a ) 195 196# 7f. dpct's static global_memory/constant_memory objects destruct after the default queue at exit and segfault 197# in queue::get_device(). Heap-allocate them and never delete: the process is exiting anyway. 198edit ("src/kernels/cuda/native_mmvq.dp.cpp" ,lambda s :s .replace ( 199"inline dpct::global_memory<int8_t, 1>\n iq4nl_values(sycl::range(16), {" , 200"inline dpct::global_memory<int8_t, 1>& iq4nl_values = *new dpct::global_memory<int8_t, 1>(sycl::range(16), {" )) 201edit ("src/kernels/cuda/s2_gemv_fast.dp.cpp" ,lambda s :s .replace ( 202"inline dpct::constant_memory<float, 2> c_codes(256, 4);" , 203"inline dpct::constant_memory<float, 2>& c_codes = *new dpct::constant_memory<float, 2>(256, 4); // never freed: exit-order safe" )) 204 205# 8. ggml-common.h has a SYCL declaration mode (sycl::half instead of cuda_fp16.h). 206edit ("src/kernels/cuda/iq_kernels.dp.cpp" ,lambda s :s .replace ("#define GGML_COMMON_DECL_CUDA" ,"#define GGML_COMMON_DECL_SYCL" ) 207 .replace ("#define GGML_COMMON_IMPL_CUDA" ,"#define GGML_COMMON_IMPL_SYCL" )) 208 209# 8b. with the SYCL declaration mode the ggml tables are plain arrays, not dpct::global_memory objects. 210edit ("src/kernels/cuda/iq_kernels.dp.cpp" ,sub (r"\b(\w+)\.get_ptr\(\)" ,r"\1" )) 211 212edit ("src/kernels/cuda/iq_kernels.dp.cpp" ,sub (r"^\s*\w+\.init\([^;]*\);\n" ,"" ,re .M )) 213# ...and the kernels receive them as const pointers (dpct declared the parameters non-const). 214TABLES = r"(iq2xxs_grid|iq2xs_grid|iq2s_grid|iq3xxs_grid|iq3s_grid|iq1s_grid_gpu|kmask_iq2xs|ksigns_iq2xs|ksigns64|kvalues_iq4nl)" 215edit ("src/kernels/cuda/iq_kernels.dp.cpp" ,sub (r"(?<!const )\b(uint64_t|uint32_t|uint8_t|int8_t) \*" + TABLES + r"\b" ,r"const \1 *\2" )) 216# 8c. one nested __fadd_rn the generic rewrite above does not reach 217edit ("src/kernels/cuda/native_qsa_score.dp.cpp" ,lambda s :s .replace ( 218"float sum=__fadd_rn(((h[0] + h[1]) + h[2]),h[3]);" ,"float sum=(((h[0] + h[1]) + h[2]) + h[3]);" )) 219 220# 8d. dpct threaded every ggml table through kernel parameters, one name per template regardless of which table 221# that quant type needs. With plain `static const` arrays (usable from device code, as ggml-sycl does) the 222# device functions read the globals directly: drop the parameters, the arguments and the capture copies. 223def untangle_tables (s ): 224s = re .sub (r"^\s*auto \w+_ptr_ct\d+ = \w+;\n" ,"" ,s ,flags = re .M ) 225s = re .sub (r",\s*const (uint64_t|uint32_t|uint8_t|int8_t) \*" + TABLES + r"\b" ,"" ,s ) 226s = re .sub (r"\(\s*const (uint64_t|uint32_t|uint8_t|int8_t) \*" + TABLES + r"\s*\)" ,"()" ,s ) 227s = re .sub (r",\s*" + TABLES + r"(_ptr_ct\d+)?\b(?![\[\w(])" ,"" ,s ) 228s = re .sub (r"\(\s*" + TABLES + r"(_ptr_ct\d+)?\s*\)(?![\[\w])" ,"()" ,s ) 229return s 230edit ("src/kernels/cuda/iq_kernels.dp.cpp" ,untangle_tables ) 231# the one helper that took the table under another name keeps its parameter; the callers name the table 232edit ("src/kernels/cuda/iq_kernels.dp.cpp" ,lambda s :s .replace ("get_int_from_table_16(aux_q4);" ,"get_int_from_table_16(aux_q4, kvalues_iq4nl);" )) 233 234# 9. a ternary on the stream argument of cudaMemcpyAsync was migrated around the wrong operand. 235edit ("src/program/generate.cpp" ,lambda s :s .replace ( 236"gs ? gs->adapt_stream\n : adapt_stream->memcpy(" , 237"(gs ? gs->adapt_stream : adapt_stream)->memcpy(" )) 238 239# 9c. conversation_snapshot_test: dpct migrated cudaFreeHost(p) on sycl::malloc_host memory to libc free(p) - the 240# test aborted with "munmap_chunk(): invalid pointer". USM host memory goes back through sycl::free. 241edit ("src/core/conversation_snapshot_test.cpp" ,lambda s :s .replace ( 242"for (void *p : host) DPCT_CHECK_ERROR(free(p));" , 243"for (void *p : host) DPCT_CHECK_ERROR(sycl::free(p, dpct::get_in_order_queue())); // SYCL port: dpct wrote free(p) for cudaFreeHost" )) 244 245# 9d. s2_expert_grouped: the new transposed kernels (gu/down_grouped_t_kernel) write `acc += dw * dx * v` in one 246# expression, which -fp-model=precise contracts to an FMA; the previous kernels compute the product in 247# chunk_dot and add it in the caller, which it does not. nvcc contracts both, so on CUDA they are bitwise equal 248# (s2_expert_grouped_parity checks that); here they differed in the last bit. No contraction in the new ones. 249def s2_no_contract (s ): 250import re as _re 251note = " #pragma clang fp contract(off) // SYCL port: round as the previous kernels do (see tools/fixups.py)\n" 252for name in ("gu_grouped_t_kernel" ,"down_grouped_t_kernel" ): 253m = _re .search (r"__dpct_inline__ void " + name + r"\([^{]*\{\n" ,s ) 254if m and not s [m .end ():].startswith (note ): 255s = s [:m .end ()]+ note + s [m .end ():] 256return s 257edit ("src/kernels/cuda/s2_expert_grouped.dp.cpp" ,s2_no_contract ) 258 259# 10. %globaltimer: there is no device-side wall clock in SPIR-V; the verify-window stage profiler reads zeros. 260edit ("src/kernels/cuda/verify_kernels.dp.cpp" ,lambda s :s .replace ( 261'asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));' , 262"t = 0; // SYCL: no %globaltimer equivalent; the stage profiler is inert on this backend" )) 263 264# 11. The three tensor-core kernels (inline PTX: mma.sync, ldmatrix, cp.async). dpct cannot migrate assembly. 265# dpct.hpp defines DPCT_COMPATIBILITY_TEMP as 900, which selects the sm_80 path; select the other one, and 266# make the launchers that have no in-kernel fallback refuse the device (their callers then use the older 267# kernels, exactly as on a pre-Ampere card). The XMX joint_matrix versions are phase-4 follow-up work. 268OFF = "#if 0 // SYCL: inline PTX (mma/ldmatrix/cp.async) - the XMX port is pending; see tools/fixups.py" 269# 0.1.31: a Turing m16n8k8 branch (`#elif !STRATA_PA_SM80`) with its own inline PTX; dpct's DPCT_COMPATIBILITY_TEMP 270# selects it on SYCL. Unreachable there (qsa_prompt_attn_batch refuses the device), so it compiles to nothing. 271edit ("src/kernels/cuda/qsa_prompt_attn.dp.cpp" ,lambda s :s .replace ( 272'#elif !STRATA_PA_SM80\n asm volatile("mma.sync.aligned.m16n8k8' , 273'#elif 0 // SYCL: Turing\'s m16n8k8 PTX (unreachable: the launcher refuses this device)\n asm volatile("mma.sync.aligned.m16n8k8' )) 274ON = "#if 1 // SYCL: the scalar path (the PTX one above is not ported yet)" 275for rel in ["src/kernels/cuda/qsa_prompt_attn.dp.cpp" ,"src/kernels/cuda/qsa_select.dp.cpp" , 276"src/kernels/cuda/native_qsa_score.dp.cpp" ]: 277edit (rel ,lambda s :s .replace ("#if !defined(DPCT_COMPATIBILITY_TEMP) || DPCT_COMPATIBILITY_TEMP >= 800" ,OFF ) 278 .replace ("#elif !defined(DPCT_COMPATIBILITY_TEMP) || DPCT_COMPATIBILITY_TEMP >= 800" ,OFF .replace ("#if 0" ,"#elif 0" ))# after upstream's __HIPCC__ guard (0.1.27) 279 .replace ("#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP < 800" ,ON ) 280 .replace (" __trap();" ," /* unreachable on SYCL: the launcher refuses this device */" )) 281for rel in ["src/kernels/cuda/qsa_prompt_attn.dp.cpp" ,"src/kernels/cuda/qsa_select.dp.cpp" ]: 282edit (rel ,lambda s :s .replace (" if (cc_major[dev] < 8) return false;" , 283" (void) cc_major[dev];\n return false; // SYCL: the tensor-core kernel is not ported yet; the caller takes the older kernel" )) 284 285# 12. IQ4_XS: dpct turned the __constant__ table into a kernel argument and gave that trait a 3-argument load(), 286# which the shared multi-column kernel cannot call. A constexpr copy of the table restores the 2-argument form. 287def mmvq (s ): 288if "kIq4nlTable" in s :return s # already applied (the table is the marker) 289m = re .search (r"iq4nl_values[^;{]*\(sycl::range\(16\), \{([^}]*)\}" ,s ,re .S )# also after 8c's heap allocation 290vals = " " .join (m .group (1 ).split ()) 291table = "static constexpr int8_t kIq4nlTable[16] = {%s};\n" % vals 292s = s .replace ("__dpct_inline__ sycl::int2 iq4_table_lookup(" ,table + "__dpct_inline__ sycl::int2 iq4_table_lookup(" ,1 ) 293s = s .replace (" static float apply(const W &r, const Q81Block *__restrict__ x, int k,\n int8_t *iq4nl_values) {" , 294" static float apply(const W &r, const Q81Block *__restrict__ x, int k) { return apply(r, x, k, const_cast<int8_t*>(kIq4nlTable)); }\n" 295" static float apply(const W &r, const Q81Block *__restrict__ x, int k,\n int8_t *iq4nl_values) {" ,1 ) 296s = s .replace (" static W load(const Block* __restrict__ w, int iqs, int8_t *iq4nl_values) {" , 297" static W load(const Block* __restrict__ w, int iqs) { return load(w, iqs, const_cast<int8_t*>(kIq4nlTable)); }\n" 298" static W load(const Block* __restrict__ w, int iqs, int8_t *iq4nl_values) {" ,1 ) 299return s 300edit ("src/kernels/cuda/native_mmvq.dp.cpp" ,mmvq ) 301 302# 13. sycl::free takes void*; the parity harness frees const device pointers. 303edit ("src/kernels/qsa_prompt_attn_parity.cpp" ,sub (r"sycl::free\(([\w.]+)," ,r"sycl::free((void *)\1," )) 304 305# 14. verify.cpp: graph introspection (kernel names, a debug print) has no SYCL API; the node count stays. 306def verify (s ): 307a = s .find (" if (ty == sycl::ext::oneapi::experimental::node_type::kernel) {" ) 308b = s .find (" } else if (ty == sycl::ext::oneapi::experimental::node_type::memcpy)" ) 309if a > 0 and b > a : 310s = s [:a ]+ " if (ty == sycl::ext::oneapi::experimental::node_type::kernel) {\n name = \"kernel\"; // SYCL: no kernel-name introspection on graph nodes\n" + s [b :] 311# cudaLaunchHostFunc(stream, fn, &fs): the flag set lives in a ring on the verifier, so a pointer to it is safe 312s = s .replace (""" v->copy_->submit([&](sycl::handler &cgh) { 313cgh.host_task([=]() { 314[](void *p) { 315FlagSet *s = (FlagSet *)p; raise_flag(s->flag, s->value); 316}(&fs); 317}); 318});""" ,""" FlagSet* fsp = &fs; 319v->copy_->submit([&](sycl::handler &cgh) { 320cgh.host_task([=]() { raise_flag(fsp->flag, fsp->value); }); 321});""" ) 322return s 323edit ("src/core/verify.cpp" ,verify ) 324# 15. cudaInitDevice(spin-wait scheduling, mapped host memory): device flags with no SYCL equivalent. 325edit ("src/core/remote_experts.cpp" ,lambda s :s .replace ( 326" if (!(spin && spin[0] == '0'))\n cudaInitDevice(device, cudaDeviceScheduleSpin | cudaDeviceMapHost, 0);" , 327" (void) spin; // SYCL: no cudaInitDevice scheduling flags; the runtime picks its own wait policy" )) 328# 16. graph.hpp: the event's timestamp is written from a const launch(); dpct added the member without `mutable`. 329edit ("include/strata/core/graph.hpp" ,lambda s :s .replace ( 330" std::chrono::time_point<std::chrono::steady_clock> done__ct1;" ," mutable std::chrono::time_point<std::chrono::steady_clock> done__ct1;" )) 331"files changed:" ,changed ) 332 333# 0.1.29: a stream cast dpct leaves as cudaStream_t (sampler's capture check): the port's queue lookup. 334for rel in all_sources (): 335edit (str (rel ),sub (r"\(\(cudaStream_t\)(\w+)\)->" ,r"strata::q_of(\1)->" )) 336# 0.1.29: sycl::free takes void*; NativeEmbed frees a const device pointer. 337edit ("src/core/native_head.cpp" ,lambda s :s .replace ("sycl::free(dev_, dpct::get_in_order_queue())" ,"sycl::free((void *) dev_, dpct::get_in_order_queue())" )) 338 339# 2026-10-01: cudaMemcpy / cudaMemset on the legacy default stream wait for every earlier launch on the device's 340# blocking streams; dpct's `get_in_order_queue().memcpy(...)` does not wait for work on another queue. The parity 341# tests launch on their own queue (`s`, `cs`) and copy results back on the default one, so a slow kernel's output 342# could be read before it finished (iq_multi_parity's IQ2_XS reference, qsa_parity's sequential side). In the tests, 343# every default-queue copy/fill first drains the device's queues - cudaMemcpy's semantics. 344for p in sorted ((root / "src" / "kernels" ).glob ("*_parity.cpp" )): 345edit (str (p .relative_to (root )),sub (r"(?<!queues_wait_and_throw\(\), )dpct::get_in_order_queue\(\)(\s*)\.(memcpy|memset)\(" , 346r"(dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())\1.\2(" )) 347 348# 0.1.39 (#423, tmking01): generate.cpp's stage_room (the expert cache of every later stage of a layer split) lost its 349# cudaMemGetInfo in the migration - the DPCT1106 note stayed, the call did not - so every later GPU read 0 bytes free. 350edit ("src/program/generate.cpp" ,sub ( 351r"( const strata::core::OnDevice on\(dev\);\n size_t fb = 0, tb = 0;\n)(?! dpct::get_current_device)" , 352r"\1 dpct::get_current_device().get_memory_info(fb, tb); // #423 (tmking01): dpct dropped cudaMemGetInfo here\n" )) 353 354# A770: only subgroup row zero reaches the native router's synchronization. 355# CUDA's early-exit block pattern must not become a divergent SYCL work-group barrier. 356edit ("src/kernels/cuda/native_router.dp.cpp" ,lambda s :s .replace ( 357" item_ct1.barrier(sycl::access::fence_space::local_space);" , 358" sycl::group_barrier(item_ct1.get_sub_group()); // only subgroup row zero participates" )) 359 360# MtpDrafter: CUDA's `cudaStream_t cs_ = nullptr` came out as the device's default in-order queue. A drafter that never 361# loads (no --mtp) kept it, and its destructor waited on and destroyed that queue: exit 139 after the output. 362edit ("include/strata/core/mtp.hpp" ,lambda s :s .replace ( 363" dpct::queue_ptr cs_ = &dpct::get_in_order_queue();\n" , 364" dpct::queue_ptr cs_ = nullptr; // load() creates it; not the device's queue, which ~MtpDrafter would destroy\n" )) 365 366# `strata --version` must print before any GPU is touched (the engine smoke test of `strata update` runs it, and a user outside the 367# `render` group has no usable device). Two things in dpct's helper headers looked up the SYCL devices before main: 368# 1. blas::descriptor's `static inline queue_ptr _saved_queue_ptr = &get_default_queue();` (an inline variable): the default is 369# looked up in get_saved_queue() instead. 370def lazy_saved_queue (s ): 371s = s .replace (" static inline ::dpct::cs::queue_ptr _saved_queue_ptr =\n &::dpct::cs::get_default_queue();" , 372" static inline ::dpct::cs::queue_ptr _saved_queue_ptr = nullptr;" ) 373return s .replace (" static inline sycl::queue &get_saved_queue() noexcept {\n return *_saved_queue_ptr;" , 374" static inline sycl::queue &get_saved_queue() noexcept {\n" 375" if (!_saved_queue_ptr) _saved_queue_ptr = &::dpct::cs::get_default_queue();\n" 376" return *_saved_queue_ptr;" ) 377edit ("include/dpct/blas_utils.hpp" ,lazy_saved_queue ) 378 379# 2. dpct::device_memory (global_memory / constant_memory) sized its per-device pointer table, and so built mem_mgr and dev_mgr, in its 380# constructor. The engine's namespace-scope tables (iq4nl_values, c_codes) are heap objects built before main. Both now happen at the 381# first get_ptr_impl(); the destruction order the original comment protected does not arise for objects that are never freed. 382def lazy_device_memory (s ): 383s = s .replace (" _host_ptr(nullptr), _device_ptrs(get_ptrs_size(), nullptr) {\n" ," _host_ptr(nullptr) {\n" ) 384s = s .replace (" // Make sure that singleton class mem_mgr and dev_mgr will destruct later\n // than this.\n" 385" detail::mem_mgr::instance();\n dev_mgr::instance();\n }\n" , 386" // Strata: the pointer table, mem_mgr and dev_mgr are made at the first get_ptr_impl() (sycl/tools/fixups.py)\n }\n" ) 387s = s .replace (" std::vector<value_t *> _device_ptrs;\n sycl::queue _q;\n};" ,# a default-built sycl::queue picks a device 388" std::vector<value_t *> _device_ptrs;\n std::optional<sycl::queue> _q; // Strata: a default-built sycl::queue picks a device (sycl/tools/fixups.py)\n};" ) 389return s .replace (" value_t *get_ptr_impl(sycl::queue &q) {\n#ifdef DPCT_USM_LEVEL_NONE\n" , 390" value_t *get_ptr_impl(sycl::queue &q) {\n" 391" if (_device_ptrs.empty()) {\n detail::mem_mgr::instance();\n dev_mgr::instance();\n" 392" _device_ptrs.assign(get_ptrs_size(), nullptr);\n }\n#ifdef DPCT_USM_LEVEL_NONE\n" ) 393edit ("include/dpct/detail/memory_detail.hpp" ,lazy_device_memory ) 394 395# 3. the migrated generate.cpp has no `--version` (src/program/generate.cpp answers it before any GPU is touched): the engine printed its 396# usage and exited 2. Same lines as the CUDA tree, at the top of main(). 397def version_flag (s ): 398if '"--version"' in s : 399return s 400return s .replace (" std::setvbuf(stdout, nullptr, _IONBF, 0);\n#if (defined(STRATA_USE_HIP)" , 401" std::setvbuf(stdout, nullptr, _IONBF, 0);\n" 402" // `strata --version` / `-V` (also `strata generate --version`): the version and nothing else, before any GPU is touched, as the CUDA\n" 403" // and HIP engines have answered it. `strata update` runs it as the engine's smoke test, and the Intel package build runs it with\n" 404" // an empty environment.\n" 405" for (int i = 1; i < argc && i < 3; ++i) {\n" 406" if (std::strcmp(argv[i], \"--version\") == 0 || std::strcmp(argv[i], \"-V\") == 0) {\n" 407" std::printf(\"strata %s\\n\", STRATA_VERSION);\n" 408" return 0;\n" 409" }\n" 410" }\n" 411"#if (defined(STRATA_USE_HIP)" ,1 ) 412edit ("src/program/generate.cpp" ,version_flag ) 413 414# 14. No permanently excluded blocks in the port (cleanup 4.1). Three `#if 0` regions used to sit in the migrated sources: the AMD-tuned S26/S27 415# expert kernels in iq_kernels.dp.cpp (997 lines), the inline-PTX tile helpers that fixup 11 switches off in native_qsa_score.dp.cpp, and 416# the #542 CUDA-runtime mismatch warning in generate.cpp. Each is dead text here and has a canonical implementation in src/ (the .cu 417# file or src/program/generate.cpp). A re-migration or a 3-way merge could bring them back, so this removes each region (depth-aware: 418# through its matching #endif) and leaves one comment. Idempotent: the marker line is gone after the first run. 419# qsa_prompt_attn.dp.cpp and qsa_select.dp.cpp keep their `#elif 0` arms: those sit in a live #if chain and are not part of this item. 420def strip_dead_region (marker ,comment ,next_line = None ): 421def fn (s ): 422L = s .split ("\n" ) 423for i ,line in enumerate (L ): 424if line .lstrip ().startswith (marker )and (next_line is None or next_line in L [i + 1 ]): 425depth = 0 426for j in range (i ,len (L )): 427t = L [j ].lstrip () 428if re .match (r"#\s*(if|ifdef|ifndef)\b" ,t ):depth += 1 429elif re .match (r"#\s*endif\b" ,t ): 430depth -= 1 431if depth == 0 : 432return "\n" .join (L [:i ]+ [comment ]+ L [j + 1 :]) 433elif depth == 1 and re .match (r"#\s*(else|elif)\b" ,t ): 434return s # an #else arm would be live code: leave it for a person to read 435return s 436return s 437return fn 438edit ("src/kernels/cuda/iq_kernels.dp.cpp" ,strip_dead_region ("#if 0" ,"// (the S26/S27 kernels and their launchers are not here: the canonical code is src/kernels/cuda/iq_kernels.cu, STRATA_EXPERT_V2 / STRATA_EXPERT_V2K; sycl/tools/fixups.py keeps this block out)" ,"S26 STRATA_EXPERT_V2=1" )) 439edit ("src/kernels/cuda/native_qsa_score.dp.cpp" ,strip_dead_region ("#if 0 // SYCL: inline PTX" ,"// (no load_a/load_b/mma here: the inline-PTX tensor-core path is src/kernels/cuda/native_qsa_score.cu, and the SYCL port scores with the scalar path below; sycl/tools/fixups.py keeps this block out)" )) 440edit ("src/program/generate.cpp" ,strip_dead_region ("#if 0 // the SYCL port has no CUDA runtime" ,"// (the CUDA runtime/headers mismatch warning, #542, lives in src/program/generate.cpp; a SYCL port has no CUDA runtime to mismatch; sycl/tools/fixups.py keeps this block out)" ))