diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 10cc6689..9db4e779 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -356,13 +356,14 @@ endif() # ================================================================== libr4d's kernels, on the host # # Some libr4d ops (the sandwich-norm joins, expert_scale) have no libref oracle by design -# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of five units written +# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of six units written # against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins, -# expert_scale and the QSA block selection, whose four kernels a card-less build otherwise never -# runs. emu/hip/hip_runtime.h supplies the HIP names, each GPU thread is a fiber, and -# __syncthreads and cross-lane ops are barriers (one not reached uniformly is reported as a -# deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select, the host -# arithmetic in ref_host.cpp, and, for the joins, the unfused chain bit for bit. +# expert_scale, the QSA block selection, whose four kernels a card-less build otherwise never +# runs, and the runtime-LoRA pair. emu/hip/hip_runtime.h supplies the HIP names, each GPU thread +# is a fiber, and __syncthreads and cross-lane ops are barriers (one not reached uniformly is +# reported as a deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select, +# the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, and for the +# LoRA pair libref itself when the test can load it. # # Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang # C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so @@ -374,8 +375,8 @@ set(R4D_DIR ${CMAKE_SOURCE_DIR}/libr4d) set(R4D_EMU ${CMAKE_CURRENT_SOURCE_DIR}/r4d_emu) set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_f32.hip ${R4D_DIR}/r4d_norm_join_bf16.hip ${R4D_DIR}/r4d_expert_scale_bf16.hip - ${R4D_DIR}/r4d_qsa_select_bf16.hip) -set(R4D_EMU_TESTS attn pick norm escale qsa) + ${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip) +set(R4D_EMU_TESTS attn pick norm escale qsa lora) set(R4D_EMU_BUILT OFF) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") # No fiber switch for this ISA. @@ -388,7 +389,7 @@ elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND NOT RAD_ASAN AND NOT RAD_TSAN) target_compile_options(r4d_emu_kernels PRIVATE -ffp-contract=off -Wno-psabi) foreach(t ${R4D_EMU_TESTS}) add_executable(r4d_emu_${t} ${R4D_EMU}/test_${t}.cpp) - target_link_libraries(r4d_emu_${t} PRIVATE r4d_emu_kernels) + target_link_libraries(r4d_emu_${t} PRIVATE r4d_emu_kernels ${CMAKE_DL_LIBS}) target_compile_options(r4d_emu_${t} PRIVATE -ffp-contract=off -Wno-psabi) set_target_properties(r4d_emu_${t} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests) endforeach() @@ -411,7 +412,7 @@ else() set(objs "") foreach(src ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/emu/emu.cpp ${R4D_EMU}/test_attn.cpp ${R4D_EMU}/test_pick.cpp ${R4D_EMU}/test_norm.cpp - ${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp) + ${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp) get_filename_component(stem ${src} NAME_WE) set(lang "") if(src MATCHES "\\.hip$") @@ -428,11 +429,16 @@ else() list(APPEND objs ${dir}/${stem}.o) endif() endforeach() + # test_lora opens libref with dlopen to hold the emulated kernels to it. + set(dl "") + foreach(l ${CMAKE_DL_LIBS}) + list(APPEND dl -l${l}) + endforeach() set(exes "") foreach(t ${R4D_EMU_TESTS}) set(exe ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t}) add_custom_command(OUTPUT ${exe} - COMMAND ${R4D_EMU_CXX} ${dir}/test_${t}.o ${objs} -o ${exe} + COMMAND ${R4D_EMU_CXX} ${dir}/test_${t}.o ${objs} ${dl} -o ${exe} DEPENDS ${dir}/test_${t}.o ${objs} COMMENT "Linking r4d_emu_${t}" VERBATIM) @@ -443,7 +449,7 @@ else() endif() endif() if(R4D_EMU_BUILT) - foreach(t pick norm escale qsa) + foreach(t pick norm escale qsa lora) add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t}) endforeach() # The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel, @@ -453,8 +459,12 @@ if(R4D_EMU_BUILT) COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_attn --shard ${k}/3) endforeach() set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick - r4d_emu_norm r4d_emu_escale r4d_emu_qsa + r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT}) + # The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can + # load one -- expand bit for bit, shrink to its bound. + set_tests_properties(r4d_emu_lora PROPERTIES + ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home") # A seeded random sweep, mostly prefill shapes on the WMMA kernel, which the emulator runs at # about 2 s a case: `slow`. `r4d_emu_attn sweep 200` is a longer run by hand, a superset of it. add_test(NAME r4d_emu_attn_sweep COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_attn sweep 40) diff --git a/tests/lora_test.cpp b/tests/lora_test.cpp new file mode 100644 index 00000000..1f01b32e --- /dev/null +++ b/tests/lora_test.cpp @@ -0,0 +1,94 @@ +/* lora_test.cpp -- lora_shrink and lora_expand in libref and libavx, over one case matrix. + * + * The matrix and the checks are tests/r4d_emu/lora_cases.h's, the same ones the r4d emulator test + * holds libr4d's kernels to: M in {1, 3, 17, 64, 130}, R in {16, 32, 48}, S = 4, K and N in + * {64, 256, 1000}, `a` bf16 or E4M3 with a 128-column scale stream (and f16, f32, E5M2, i8 once), + * `y` bf16, f32 (and f16), `a`/`y` as column slices, slots mixing -1, -5, 0..3 and S. Each library + * is held separately to the same double-precision sums -- so libref and libavx agree with each + * other to twice the bound -- and to the base-row contract by bytes: shrink leaves a sentinel NaN + * in a base row of `t`, expand leaves a base row of `y` exactly as it was, -0 included. + * + * avx_check already compares libavx with libref at every ISA level on drawn geometries; what this + * adds is the hand-built part a draw cannot reach: the -1 and -5 spellings of a base row (a draw + * never produces a negative slot), the sentinel and -0 bytes, and wide row strides on `a`, its + * scale and `y`. libavx is run at every level this machine executes. + */ +#include "rad_test.h" +#include "rad_abi.h" +#include "r4d_emu/lora_cases.h" + +#include +#include +#include +#include + +namespace { + +struct Lib { + void* h = nullptr; + lora_cases::LaunchFn shrink = nullptr, expand = nullptr; + int (*isa_force)(int) = nullptr; + const char* (*isa_name)(int) = nullptr; +}; + +Lib open_lib(const char* so) { + Lib L; + std::vector paths; + if (const char* home = std::getenv("RADIANCE_HOME")) + paths.push_back(std::string(home) + "/kernels/" + so); + paths.push_back(std::string("radiance_home/kernels/") + so); + paths.push_back(std::string("build/radiance_home/kernels/") + so); + for (auto& p : paths) { + L.h = dlopen(p.c_str(), RTLD_NOW | RTLD_LOCAL); + if (L.h) break; + } + if (!L.h) return L; + /* As the loader does: libavx builds its fp8 decode table here, and a launch before it reads + * every scalar-path fp8 code as 0. */ + auto open = (int (*)(void))dlsym(L.h, "rad_plugin_open"); + if (open && open() < 0) return L; + auto cnt = (int (*)(void))dlsym(L.h, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(L.h, "rad_kernel_at"); + L.isa_force = (int (*)(int))dlsym(L.h, "avx_isa_force"); + L.isa_name = (const char* (*)(int))dlsym(L.h, "avx_isa_name"); + if (!cnt || !at) return L; + for (int i = 0; i < cnt(); ++i) { + const RadKernelInfo* k = at(i); + if (!k || !k->op) continue; + if (!std::strcmp(k->op, "lora_shrink")) L.shrink = k->launch; + if (!std::strcmp(k->op, "lora_expand")) L.expand = k->launch; + } + return L; +} + +} /* namespace */ + +TEST(lora_libref_and_libavx_over_the_matrix) { + const Lib ref = open_lib("libref.so"); + REQUIRE(ref.shrink != nullptr); + REQUIRE(ref.expand != nullptr); + const Lib avx = open_lib("libavx.so"); + REQUIRE(avx.shrink != nullptr); + REQUIRE(avx.expand != nullptr); + /* Every ISA level the machine executes; a level the CPU lacks is clamped by avx_isa_force and + * then not counted, as avx_check does. Without the symbol, the level libavx picked itself. */ + const int levels = avx.isa_force ? 4 : 1; + for (int lvl = 0; lvl < levels; ++lvl) { + if (avx.isa_force && avx.isa_force(lvl) != lvl) continue; + std::vector impls = { + { "libref", ref.shrink, ref.expand, false }, + { "libavx", avx.shrink, avx.expand, false }, + }; + lora_cases::Tally T; + lora_cases::run_matrix(T, impls, 11 + (unsigned)lvl); + std::fprintf(stderr, " libavx at %s: %d implementation-cases, %d failure(s); worst " + "|err|/tol shrink %.3f, expand %.3f\n", + avx.isa_name ? avx.isa_name(lvl) : "its own level", T.cases, T.fails, + T.worst_shrink, T.worst_expand); + CHECK(T.cases > 0); + CHECK_EQ(T.fails, 0); + } + if (avx.isa_force) avx.isa_force(3); /* back to the highest the machine allows */ +} + +RAD_TEST_MAIN() diff --git a/tests/r4d_emu/lora_cases.h b/tests/r4d_emu/lora_cases.h new file mode 100644 index 00000000..242a0efb --- /dev/null +++ b/tests/r4d_emu/lora_cases.h @@ -0,0 +1,297 @@ +/* lora_cases.h -- the runtime-LoRA case matrix and what every implementation is held to, shared by + * tests/lora_test.cpp (libref and libavx, at every ISA level the machine runs) and + * tests/r4d_emu/test_lora.cpp (libr4d's source on the SIMT emulator, beside libref and the host + * restatement in ref_host.cpp). One matrix and one checker, so "the same cases" is a fact and not + * an intention. + * + * THE MATRIX. M in {1, 3, 17, 64, 130}, R in {16, 32, 48}, S = 4, K (and N) in {64, 256, 1000}; + * `a` bf16, or E4M3 with an f32 scale every 128 columns (1000 leaves a partial group, 64 a row + * narrower than one group); `y` bf16 and f32. Then the other dtypes once over a smaller grid: `a` + * f16, f32, E5M2 and i8 (the last two with scales), `y` f16. `a`, its scale stream and `y` are + * COLUMN SLICES of wider buffers. Slots cycle through -1, -5, 0..3 and 4 (= S): three spellings + * of a base row beside the adapter rows, M = 1 once as an adapter row and twice as a base one. + * + * WHAT IS CHECKED, per implementation, per case: + * * BASE ROWS ARE UNTOUCHED, BY BYTES. Shrink leaves the sentinel NaN pattern `t` was filled + * with; expand leaves `y` -- every third element a -0, which `y + 0` would turn into +0 -- and + * every column outside the slice as they were. + * * ADAPTER ROWS AGAINST A DOUBLE-PRECISION SUM of the same f32 terms (x(m, k) is the code times + * its scale rounded to f32, as the contract defines it). Shrink: |t - sum| <= (K + 2) 2^-24 + * sum|terms|, the worst case of an f32 dot in any summation order, so no implementation can + * fail it by choosing an order and every one fails it by reading a wrong element. Expand: + * |y - want| <= h (|want| + e) + 2 e with e = 4 (R + 2) 2^-24 (|y| + |scale| sum|terms|) and h + * half an ulp of y's dtype relative (2^-8 bf16, 2^-11 f16, 0 f32). + * * An implementation marked `ref_bytes` must also produce, for expand, exactly the bytes of the + * first implementation in the list -- the claim libr4d's expand makes about libref's order. + */ +#pragma once + +#include "rad_abi.h" +#include "rad_plugin.h" + +#include +#include +#include +#include +#include +#include + +namespace lora_cases { + +typedef int (*LaunchFn)(const RadArgs*, RadStream); + +struct Impl { + const char* name; + LaunchFn shrink, expand; + bool ref_bytes; /* expand must match the first implementation bit for bit */ +}; + +struct Tally { + int cases = 0, fails = 0; + double worst_shrink = 0, worst_expand = 0; /* the largest |err| / tolerance seen */ +}; + +static const int kS = 4; +static const int32_t kSlots[] = { -1, 0, 1, 2, 3, 4, 2, -5, 1 }; +static inline int32_t slot_of(int m, int off) { return kSlots[(m * 7 + off) % 9]; } +static inline bool base(int32_t s) { return s < 0 || s >= kS; } +static const uint32_t kSentinel = 0x7fc0deadu; /* a quiet NaN with a payload: "unwritten" */ + +static inline size_t esize(uint32_t dt) { return (size_t)rad_dtype_bits(dt) / 8; } + +static inline void put(uint32_t dt, void* p, size_t i, float v) { + switch (dt) { + case RAD_BF16: ((uint16_t*)p)[i] = rad_f32_to_bf16(v); break; + case RAD_F16: ((uint16_t*)p)[i] = rad_f32_to_f16(v); break; + case RAD_F32: ((float*)p)[i] = v; break; + case RAD_F8E4M3: ((uint8_t*)p)[i] = rad_f32_to_fp8e4m3(v); break; + case RAD_F8E5M2: ((uint8_t*)p)[i] = rad_f32_to_fp8e5m2(v); break; + case RAD_I8: { + float r = std::nearbyintf(v); + r = r < -127.f ? -127.f : (r > 127.f ? 127.f : r); + ((int8_t*)p)[i] = (int8_t)r; + break; + } + default: break; + } +} + +static inline float get(uint32_t dt, const void* p, size_t i) { + switch (dt) { + case RAD_BF16: return rad_bf16_to_f32(((const uint16_t*)p)[i]); + case RAD_F16: return rad_f16_to_f32(((const uint16_t*)p)[i]); + case RAD_F32: return ((const float*)p)[i]; + case RAD_F8E4M3: return rad_fp8e4m3_to_f32(((const uint8_t*)p)[i]); + case RAD_F8E5M2: return rad_fp8e5m2_to_f32(((const uint8_t*)p)[i]); + case RAD_I8: return (float)((const int8_t*)p)[i]; + default: return 0.0f; + } +} + +static inline bool coded(uint32_t dt) { + return dt == RAD_F8E4M3 || dt == RAD_F8E5M2 || dt == RAD_I8; +} + +static inline RadTensor mk(void* data, uint32_t dt, std::vector shape, + std::vector stride) { + RadTensor t{}; + t.data = data; t.dtype = dt; t.rank = (uint32_t)shape.size(); + for (size_t i = 0; i < shape.size(); ++i) { t.shape[i] = shape[i]; t.stride[i] = stride[i]; } + return t; +} + +struct Params { + std::vector p; + std::vector keep; + Params() { keep.reserve(8); } /* sval points into `keep`: no reallocation */ + void i(const char* k, long long v) { + RadParam q{}; q.key = k; q.kind = RAD_P_INT; q.ival = v; p.push_back(q); + } + void s(const char* k, const char* v) { + keep.emplace_back(v); + RadParam q{}; q.key = k; q.kind = RAD_P_STR; q.sval = keep.back().c_str(); p.push_back(q); + } +}; + +static inline void fail(Tally& T, const Impl& im, const char* what, int M, int R, int K, + uint32_t dt, int m, int j) { + ++T.fails; + if (T.fails <= 20) + std::printf("FAIL %-8s %s: M %d R %d K/N %d %s at row %d col %d\n", im.name, what, M, R, K, + rad_dtype_name(dt), m, j); +} + +/* ------------------------------------------------------------------------------- lora_shrink */ +static inline void shrink_case(Tally& T, const std::vector& impls, std::mt19937& rng, int M, + int R, int K, uint32_t adt, int off) { + std::normal_distribution nd(0.f, 1.f); + std::uniform_real_distribution ud(0.01f, 0.05f); + const bool sc = coded(adt); + const int group = 128, groups = (K + group - 1) / group; + const int lda = K + 7, a_off = 3, lds = groups + 3, s_off = 1; + const size_t es = esize(adt); + const float amp = adt == RAD_I8 ? 40.0f : (sc ? 4.0f : 1.0f); + std::vector abuf((size_t)(M * lda + a_off) * es); + for (int i = 0; i < M * lda + a_off; ++i) put(adt, abuf.data(), (size_t)i, amp * nd(rng)); + std::vector sbuf((size_t)(M * lds + s_off)); + for (auto& v : sbuf) v = ud(rng); + std::vector slot((size_t)M); + for (int m = 0; m < M; ++m) slot[(size_t)m] = slot_of(m, off); + std::vector la((size_t)kS * R * K); + for (auto& v : la) v = rad_f32_to_bf16(0.05f * nd(rng)); + + RadTensor t[5]{}; + t[0] = mk(abuf.data() + a_off * es, adt, {M, K}, {lda, 1}); + if (sc) t[1] = mk(sbuf.data() + s_off, RAD_F32, {M, groups}, {lds, 1}); + t[2] = mk(slot.data(), RAD_I32, {M}, {1}); + t[3] = mk(la.data(), RAD_BF16, {kS, R, K}, {(int64_t)R * K, K, 1}); + Params P; + P.i("M", M); P.i("K", K); P.i("R", R); P.i("S", kS); P.i("group", sc ? group : 0); + P.s("dtype", rad_dtype_name(adt)); + RadArgs a{}; a.t = t; a.n_t = 5; a.p = P.p.data(); a.n_p = (int)P.p.size(); a.world_size = 1; + + /* The double sums, once: they do not depend on the implementation. */ + std::vector want((size_t)M * R, 0.0), tol((size_t)M * R, 0.0); + for (int m = 0; m < M; ++m) { + const int32_t s = slot[(size_t)m]; + if (base(s)) continue; + for (int j = 0; j < R; ++j) { + double sum = 0, mag = 0; + for (int k = 0; k < K; ++k) { + float x = get(adt, abuf.data(), (size_t)(a_off + m * lda + k)); + if (sc) x = x * sbuf[(size_t)(s_off + m * lds + k / group)]; + const double term = (double)x * rad_bf16_to_f32(la[((size_t)s * R + j) * K + k]); + sum += term; mag += std::fabs(term); + } + want[(size_t)m * R + j] = sum; + tol[(size_t)m * R + j] = (K + 2) * std::ldexp(1.0, -24) * mag + 1e-30; + } + } + for (const Impl& im : impls) { + if (!im.shrink) continue; + std::vector tv((size_t)M * R); + for (auto& x : tv) std::memcpy(&x, &kSentinel, 4); + t[4] = mk(tv.data(), RAD_F32, {M, R}, {R, 1}); + ++T.cases; + const int rc = im.shrink(&a, nullptr); + if (rc != RAD_OK) { + fail(T, im, "shrink returned an error", M, R, K, adt, rc, -1); + continue; + } + for (int m = 0; m < M; ++m) + for (int j = 0; j < R; ++j) { + const size_t o = (size_t)m * R + j; + if (base(slot[(size_t)m])) { + if (std::memcmp(&tv[o], &kSentinel, 4)) + fail(T, im, "shrink wrote a base row", M, R, K, adt, m, j); + continue; + } + const double e = std::fabs((double)tv[o] - want[o]); + if (e / tol[o] > T.worst_shrink) T.worst_shrink = e / tol[o]; + if (!(e <= tol[o])) fail(T, im, "shrink value", M, R, K, adt, m, j); + } + } +} + +/* ------------------------------------------------------------------------------- lora_expand */ +static inline void expand_case(Tally& T, const std::vector& impls, std::mt19937& rng, int M, + int R, int N, uint32_t ydt, int off) { + std::normal_distribution nd(0.f, 1.f); + std::uniform_real_distribution ud(0.5f, 2.0f); + const int ldy = N + 5, y_off = 2; + const size_t es = esize(ydt), ny = (size_t)(M * ldy + y_off); + std::vector y0(ny * es); + for (size_t i = 0; i < ny; ++i) put(ydt, y0.data(), i, i % 3 == 0 ? -0.0f : nd(rng)); + std::vector slot((size_t)M); + for (int m = 0; m < M; ++m) slot[(size_t)m] = slot_of(m, off); + std::vector tv((size_t)M * R); + for (int m = 0; m < M; ++m) + for (int j = 0; j < R; ++j) { + float v = 0.5f * nd(rng); + if (base(slot[(size_t)m])) std::memcpy(&v, &kSentinel, 4); /* never read */ + tv[(size_t)m * R + j] = v; + } + std::vector lb((size_t)kS * N * R); + for (auto& v : lb) v = rad_f32_to_bf16(0.05f * nd(rng)); + std::vector scl((size_t)kS * N); + for (auto& v : scl) v = ud(rng); + + RadTensor t[5]{}; + t[0] = mk(tv.data(), RAD_F32, {M, R}, {R, 1}); + t[1] = mk(slot.data(), RAD_I32, {M}, {1}); + t[2] = mk(lb.data(), RAD_BF16, {kS, N, R}, {(int64_t)N * R, R, 1}); + t[3] = mk(scl.data(), RAD_F32, {kS, N}, {N, 1}); + Params P; + P.i("M", M); P.i("N", N); P.i("R", R); P.i("S", kS); P.s("dtype", rad_dtype_name(ydt)); + RadArgs a{}; a.t = t; a.n_t = 5; a.p = P.p.data(); a.n_p = (int)P.p.size(); a.world_size = 1; + + const double h = ydt == RAD_BF16 ? std::ldexp(1.0, -8) : ydt == RAD_F16 ? std::ldexp(1.0, -11) + : 0.0; + std::vector first; + for (size_t ii = 0; ii < impls.size(); ++ii) { + const Impl& im = impls[ii]; + if (!im.expand) continue; + std::vector yb = y0; + t[4] = mk(yb.data() + y_off * es, ydt, {M, N}, {ldy, 1}); + ++T.cases; + const int rc = im.expand(&a, nullptr); + if (rc != RAD_OK) { + fail(T, im, "expand returned an error", M, R, N, ydt, rc, -1); + continue; + } + const bool cmp_first = im.ref_bytes && !first.empty(); + for (size_t i = 0; i < ny; ++i) { + const long long q = (long long)i - y_off; + const int m = q < 0 ? -1 : (int)(q / ldy), n = q < 0 ? -1 : (int)(q % ldy); + if (cmp_first && std::memcmp(&yb[i * es], &first[i * es], es)) + fail(T, im, "expand is not the first implementation's bytes", M, R, N, ydt, m, n); + const bool inside = m >= 0 && m < M && n < N && !base(slot[(size_t)m]); + if (!inside) { + if (std::memcmp(&yb[i * es], &y0[i * es], es)) + fail(T, im, "expand touched a base row or the slice's neighbours", M, R, N, ydt, + m, n); + continue; + } + const int32_t s = slot[(size_t)m]; + double sum = 0, mag = 0; + for (int j = 0; j < R; ++j) { + const double term = (double)tv[(size_t)m * R + j] * + rad_bf16_to_f32(lb[((size_t)s * N + n) * R + j]); + sum += term; mag += std::fabs(term); + } + const double yin = get(ydt, y0.data(), i), sc = scl[(size_t)s * N + n]; + const double want = yin + sc * sum; + const double e = + 4.0 * (R + 2) * std::ldexp(1.0, -24) * (std::fabs(yin) + std::fabs(sc) * mag); + const double tol = h * (std::fabs(want) + e) + 2 * e + 1e-30; + const double err = std::fabs((double)get(ydt, yb.data(), i) - want); + if (err / tol > T.worst_expand) T.worst_expand = err / tol; + if (!(err <= tol)) fail(T, im, "expand value", M, R, N, ydt, m, n); + } + if (first.empty()) first = yb; + } +} + +/* The whole matrix over `impls`. */ +static inline void run_matrix(Tally& T, const std::vector& impls, unsigned seed) { + std::mt19937 rng(seed); + for (int M : {1, 3, 17, 64, 130}) + for (int R : {16, 32, 48}) + for (int K : {64, 256, 1000}) + for (int off : {2, 0, 5}) { + if (off != 2 && M != 1) continue; /* M = 1 also as a -1 and an S row */ + shrink_case(T, impls, rng, M, R, K, RAD_BF16, off); + shrink_case(T, impls, rng, M, R, K, RAD_F8E4M3, off); + expand_case(T, impls, rng, M, R, K, RAD_BF16, off); + expand_case(T, impls, rng, M, R, K, RAD_F32, off); + } + for (int M : {1, 17}) + for (int K : {256, 1000}) { + for (uint32_t adt : {(uint32_t)RAD_F16, (uint32_t)RAD_F32, (uint32_t)RAD_F8E5M2, + (uint32_t)RAD_I8}) + shrink_case(T, impls, rng, M, 32, K, adt, 2); + expand_case(T, impls, rng, M, 32, K, RAD_F16, 2); + } +} + +} /* namespace lora_cases */ diff --git a/tests/r4d_emu/ref_host.cpp b/tests/r4d_emu/ref_host.cpp index 8078a462..4cd69f9d 100644 --- a/tests/r4d_emu/ref_host.cpp +++ b/tests/r4d_emu/ref_host.cpp @@ -1,5 +1,5 @@ /* ref_host.cpp -- ref_host.h's functions: the rules and roundings of r4d_pair_argmax_f32.hip, - * r4d_norm_join_bf16.hip and r4d_expert_scale_bf16.hip, one element at a time. */ + * r4d_norm_join_bf16.hip, r4d_expert_scale_bf16.hip and r4d_lora_bf16.hip, one element at a time. */ #include "ref_host.h" #include "rad_plugin.h" @@ -200,3 +200,88 @@ int host_expert_scale(const RadArgs* a) { } return RAD_OK; } + +/* lora_shrink / lora_expand: libref's arithmetic (libref/ref_lora.cpp) over the dense-last-axis + * operands the test hands over -- k ascending and j ascending, one f32 accumulator, every product + * and sum rounded. Expand's kernel sums in the same order, so its bytes are these; shrink's sums + * k in 32 lane strides and a butterfly, so its are these to a tolerance. A row whose slot is + * outside [0, S) is not touched. */ +static float host_act(uint32_t dt, const void* p, int64_t i) { + switch (dt) { + case RAD_BF16: return rad_bf16_to_f32(((const uint16_t*)p)[i]); + case RAD_F16: return rad_f16_to_f32(((const uint16_t*)p)[i]); + case RAD_F32: return ((const float*)p)[i]; + case RAD_F8E4M3: return rad_fp8e4m3_to_f32(((const uint8_t*)p)[i]); + case RAD_F8E5M2: return rad_fp8e5m2_to_f32(((const uint8_t*)p)[i]); + case RAD_I8: return (float)((const int8_t*)p)[i]; + default: return 0.0f; + } +} + +int host_lora_shrink(const RadArgs* a) { + if (!a || a->n_t < 5) return RAD_E_INVAL; + const RadTensor *X = rad_arg_in(a, 0), *XS = rad_arg_in(a, 1), *SL = rad_arg_in(a, 2); + const RadTensor *LA = rad_arg_in(a, 3), *T = rad_arg_in(a, 4); + if (!X || !SL || !LA || !T || X->rank != 2 || T->rank != 2) return RAD_E_INVAL; + if (XS && XS->dtype == RAD_DT_INVALID) XS = nullptr; + const int64_t K = rad_args_geti_or(a, "K", 0), R = rad_args_geti_or(a, "R", 0); + const int64_t S = rad_args_geti_or(a, "S", 0); + const int64_t M = T->shape[0]; + /* libref's grid_block: the power of two whose ceiling division gives the stream's groups. */ + const int64_t groups = XS ? XS->shape[1] : 1; + int64_t group = K; + if (groups > 1) { + const int64_t lo = (K + groups - 1) / groups; + int64_t b = 1; + while (b < lo) b <<= 1; + group = (K + b - 1) / b == groups ? b : lo; + } + for (int64_t m = 0; m < M; ++m) { + const int32_t s = ((const int32_t*)SL->data)[m * SL->stride[0]]; + if (s < 0 || s >= S) continue; + for (int64_t j = 0; j < R; ++j) { + const uint16_t* ar = (const uint16_t*)LA->data + (s * R + j) * K; + float acc = 0.0f; + for (int64_t k = 0; k < K; ++k) { + float x = host_act(X->dtype, X->data, m * X->stride[0] + k); + if (XS) x = x * ((const float*)XS->data)[m * XS->stride[0] + k / group]; + acc += x * rad_bf16_to_f32(ar[k]); + } + ((float*)T->data)[m * T->stride[0] + j] = acc; + } + } + return RAD_OK; +} + +int host_lora_expand(const RadArgs* a) { + if (!a || a->n_t < 5 || !rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *T = rad_arg_in(a, 0), *SL = rad_arg_in(a, 1), *LB = rad_arg_in(a, 2); + const RadTensor *SC = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4); + if (T->rank != 2 || Y->rank != 2) return RAD_E_INVAL; + const int64_t N = rad_args_geti_or(a, "N", 0), R = rad_args_geti_or(a, "R", 0); + const int64_t S = rad_args_geti_or(a, "S", 0); + const int64_t M = Y->shape[0]; + for (int64_t m = 0; m < M; ++m) { + const int32_t s = ((const int32_t*)SL->data)[m * SL->stride[0]]; + if (s < 0 || s >= S) continue; + const float* tr = (const float*)T->data + m * T->stride[0]; + for (int64_t n = 0; n < N; ++n) { + const uint16_t* br = (const uint16_t*)LB->data + (s * N + n) * R; + float acc = 0.0f; + for (int64_t j = 0; j < R; ++j) acc += tr[j] * rad_bf16_to_f32(br[j]); + const float d = ((const float*)SC->data)[s * N + n] * acc; + const int64_t o = m * Y->stride[0] + n; + if (Y->dtype == RAD_BF16) { + uint16_t* y = (uint16_t*)Y->data + o; + *y = rad_f32_to_bf16(rad_bf16_to_f32(*y) + d); + } else if (Y->dtype == RAD_F16) { + uint16_t* y = (uint16_t*)Y->data + o; + *y = rad_f32_to_f16(rad_f16_to_f32(*y) + d); + } else { + float* y = (float*)Y->data + o; + *y = *y + d; + } + } + } + return RAD_OK; +} diff --git a/tests/r4d_emu/ref_host.h b/tests/r4d_emu/ref_host.h index c4c2d65e..79f871b0 100644 --- a/tests/r4d_emu/ref_host.h +++ b/tests/r4d_emu/ref_host.h @@ -19,3 +19,5 @@ int host_norm_add_norm(const RadArgs* a); int host_norm_add_norm_route(const RadArgs* a); int host_join_add_scale(const RadArgs* a); int host_expert_scale(const RadArgs* a); +int host_lora_shrink(const RadArgs* a); +int host_lora_expand(const RadArgs* a); diff --git a/tests/r4d_emu/test_lora.cpp b/tests/r4d_emu/test_lora.cpp new file mode 100644 index 00000000..fe29bb4b --- /dev/null +++ b/tests/r4d_emu/test_lora.cpp @@ -0,0 +1,65 @@ +/* tests/r4d_emu: lora_shrink / lora_expand (r4d_lora_bf16.hip) on the host SIMT emulator. + * + * The case matrix and every check are lora_cases.h's, shared with tests/lora_test.cpp (libref and + * libavx): base rows untouched by bytes, adapter rows against a double-precision sum within the + * bounds stated there. Here the implementations are the emulated kernels, ref_host.cpp's + * restatement of libref's arithmetic, and libref itself when $RADIANCE_HOME holds one (ctest sets + * it) -- and the emulated EXPAND is held to the first of those bit for bit, because its + * j-ascending sum and its roundings are libref's. Shrink sums k in 32 lane strides and a fixed + * butterfly, so it is held to the bound rather than to libref's bytes. + */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include "lora_cases.h" + +#include +#include +#include +#include +#include +#include + +using lora_cases::Impl; +using lora_cases::LaunchFn; + +static int host_shrink(const RadArgs* a, RadStream) { return host_lora_shrink(a); } +static int host_expand(const RadArgs* a, RadStream) { return host_lora_expand(a); } + +/* libref's two rows, through the plugin's own exports, or nulls. */ +static void load_libref(LaunchFn* shrink, LaunchFn* expand) { + *shrink = *expand = nullptr; + const char* home = std::getenv("RADIANCE_HOME"); + if (!home || !*home) return; + const std::string p = std::string(home) + "/kernels/libref.so"; + void* h = dlopen(p.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) return; + auto open = (int (*)(void))dlsym(h, "rad_plugin_open"); /* as the loader does */ + if (open && open() < 0) return; + auto cnt = (int (*)(void))dlsym(h, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at"); + if (!cnt || !at) return; + for (int i = 0; i < cnt(); ++i) { + const RadKernelInfo* k = at(i); + if (!k || !k->op) continue; + if (!std::strcmp(k->op, "lora_shrink")) *shrink = k->launch; + if (!std::strcmp(k->op, "lora_expand")) *expand = k->launch; + } +} + +int main() { + LaunchFn rs = nullptr, re = nullptr; + load_libref(&rs, &re); + std::printf("lora: libref %s\n", rs && re + ? "loaded: the emulated kernels are held to it as well" + : "not found ($RADIANCE_HOME): held to ref_host.cpp and the double sums only"); + std::vector impls = { { "host", host_shrink, host_expand, true } }; + if (rs && re) impls.push_back({ "libref", rs, re, true }); + impls.push_back({ "r4d-emu", r4d_rad_lora_shrink, r4d_rad_lora_expand, true }); + lora_cases::Tally T; + lora_cases::run_matrix(T, impls, 11); + std::printf("lora: %d implementation-cases, %d failure(s); worst |err|/tol shrink %.3f, " + "expand %.3f\n", T.cases, T.fails, T.worst_shrink, T.worst_expand); + return T.fails != 0; +}