mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 23:08:36 +00:00
Merge int-0225 (05361524ea) into f-ink-b70-c
No conflicts. The new int-0225 commits do not touch engine/src/inkling2/sycl. Register check clean.
This commit is contained in:
commit
36273f169d
93 files changed
+7675
-835
No files matched your search
+21
-5
@@ -10,7 +10,7 @@ debugging and are kept in `terminal/data/settings-register.json`.
|
||||
A number or a word is set like any environment variable, for example `STRATA_KVA=1`. In the Terminal, `strata launch --set NAME=value`
|
||||
puts it in the model's run configuration.
|
||||
|
||||
## Switches you can turn on (466)
|
||||
## Switches you can turn on (472)
|
||||
|
||||
Off unless you set them. The last column says where each one is described.
|
||||
|
||||
@@ -53,6 +53,7 @@ Off unless you set them. The last column says where each one is described.
|
||||
| `STRATA_DENSE_F32` | number | NVIDIA | [COMMUNITY_BENCHMARKS.md](COMMUNITY_BENCHMARKS.md), [OLDER_GPUS.md](OLDER_GPUS.md), [README.md](bench-results/2026-10-12-p40-sm61-kernels/README.md) |
|
||||
| `STRATA_DENSE_I8_TC` | number | NVIDIA and AMD | - |
|
||||
| `STRATA_DENSE_MMQ` | on / off | NVIDIA and AMD, Intel Arc | [AMD_HIP.md](AMD_HIP.md), [DETAILS.md](DETAILS.md), [prefill-ab.md](bench-results/2026-10-05-community-gfx1151/prefill-ab.md) |
|
||||
| `STRATA_DENSE_XMX` | on / off | Intel Arc | - |
|
||||
| `STRATA_DEQUANT_SIDE` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
|
||||
| `STRATA_DETERMINISTIC` | on / off | NVIDIA and AMD | [DETERMINISTIC.md](DETERMINISTIC.md) |
|
||||
| `STRATA_DF2_GEMM_TC` | on / off | NVIDIA and AMD | - |
|
||||
@@ -139,7 +140,10 @@ Off unless you set them. The last column says where each one is described.
|
||||
| `STRATA_INK_DFLASH2_FORCE` | on / off | NVIDIA and AMD | [MODELS.md](MODELS.md) |
|
||||
| `STRATA_INK_DYNAMIC_PINNED_MIB` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
|
||||
| `STRATA_INK_ELASTIC_1M` | text | NVIDIA and AMD | [INKLING_SM120.md](INKLING_SM120.md) |
|
||||
| `STRATA_INK_ELASTIC_COMPACT_MAX_CTX` | number | NVIDIA and AMD | - |
|
||||
| `STRATA_INK_ELASTIC_DRAFT_HOST_PCT` | number | NVIDIA and AMD | - |
|
||||
| `STRATA_INK_ELASTIC_HEAT` | on / off | NVIDIA and AMD | - |
|
||||
| `STRATA_INK_ELASTIC_HOST_GIB` | number | AMD | - |
|
||||
| `STRATA_INK_FAST_KERNELS` | on / off | NVIDIA and AMD | [AMD_HIP.md](AMD_HIP.md) |
|
||||
| `STRATA_INK_GGUF_DP4A` | on / off | Intel Arc | - |
|
||||
| `STRATA_INK_INTELARC` | text | Intel Arc | [INTEL_ARC.md](INTEL_ARC.md) |
|
||||
@@ -148,6 +152,7 @@ Off unless you set them. The last column says where each one is described.
|
||||
| `STRATA_INK_INTELARC_EXACT` | text | Intel Arc | - |
|
||||
| `STRATA_INK_INTELARC_FP8_KV` | text | Intel Arc | - |
|
||||
| `STRATA_INK_KV_FIRST` | on / off | NVIDIA and AMD | - |
|
||||
| `STRATA_INK_KV_FLOOR_MIB` | number | AMD | - |
|
||||
| `STRATA_INK_KV_K8V4` | on / off | NVIDIA and AMD | - |
|
||||
| `STRATA_INK_KV_PREALLOC` | on / off | NVIDIA and AMD | [INKLING_KV.md](INKLING_KV.md) |
|
||||
| `STRATA_INK_KV_RAM_MB` | number | NVIDIA and AMD | - |
|
||||
@@ -271,9 +276,10 @@ Off unless you set them. The last column says where each one is described.
|
||||
| `STRATA_KV_HOST_REGISTER` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
|
||||
| `STRATA_KV_PREFETCH` | number | NVIDIA and AMD, Intel Arc | [KV_PREFETCH.md](KV_PREFETCH.md), [README.md](bench-results/README.md), [README.md](bench-results/2026-10-06-community-rtx4090-opt-ins/README.md) |
|
||||
| `STRATA_KV_ROT` | on / off | NVIDIA and AMD, Intel Arc | [DETAILS.md](DETAILS.md), [SPLIT_SERVE.md](SPLIT_SERVE.md) |
|
||||
| `STRATA_L32_GPU_CAP_GIB` | number | NVIDIA and AMD | - |
|
||||
| `STRATA_L32_KDA_SEQ` | number | Intel Arc | - |
|
||||
| `STRATA_L32_MTP_ONLINE` | on / off | NVIDIA and AMD | - |
|
||||
| `STRATA_L32_SEGMENTED` | on / off | NVIDIA and AMD | - |
|
||||
| `STRATA_L32_SKIP_TAU` | number | NVIDIA and AMD | - |
|
||||
| `STRATA_L3_PF` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
|
||||
| `STRATA_L3_PF_TOP` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
|
||||
| `STRATA_LEND_MIRROR` | text | Intel Arc | [INTEL.md](INTEL.md), [INTEL_ARC.md](INTEL_ARC.md) |
|
||||
@@ -483,7 +489,7 @@ Off unless you set them. The last column says where each one is described.
|
||||
| `STRATA_WATCHDOG_S` | text | NVIDIA and AMD, Intel Arc | [DETAILS.md](DETAILS.md) |
|
||||
| `STRATA_WDDM_BUDGET` | number | AMD, Intel Arc | [AMD_HIP.md](AMD_HIP.md) |
|
||||
|
||||
## Switches that go back to earlier behaviour (179)
|
||||
## Switches that go back to earlier behaviour (187)
|
||||
|
||||
These behaviours are on by default. Setting the switch returns the earlier behaviour; the notes in the register say which
|
||||
version made it the default.
|
||||
@@ -497,6 +503,8 @@ version made it the default.
|
||||
| `STRATA_BATCH_MTP_SERIAL` | on / off | NVIDIA and AMD | v0.2.16 | [BATCHING.md](BATCHING.md) |
|
||||
| `STRATA_CONVERT_THREADS` | number | NVIDIA and AMD | v0.2.17 | - |
|
||||
| `STRATA_DEFAULTS` | on / off | NVIDIA and AMD | v0.2.16 | [AMD_HIP.md](AMD_HIP.md), [BATCHING.md](BATCHING.md), [DETAILS.md](DETAILS.md) |
|
||||
| `STRATA_DENSE_GEMM_ESIMD` | on / off | Intel Arc | - | - |
|
||||
| `STRATA_DENSE_GEMM_PK` | on / off | Intel Arc | - | - |
|
||||
| `STRATA_DEQUANT_WIDE` | number | NVIDIA and AMD | v0.2.16 | [DETAILS.md](DETAILS.md), [OLDER_GPUS.md](OLDER_GPUS.md), [release-notes-0.2.7.md](release-notes-0.2.7.md) |
|
||||
| `STRATA_DF2_ATTN_TC` | on / off | NVIDIA and AMD | v0.2.19 | - |
|
||||
| `STRATA_DF2_CTX_BATCH` | on / off | NVIDIA and AMD | v0.2.19 | - |
|
||||
@@ -527,7 +535,11 @@ version made it the default.
|
||||
| `STRATA_INK_B70_OFF` | text | Intel Arc | - | - |
|
||||
| `STRATA_INK_CHUNK_AUTO` | number | NVIDIA and AMD | v0.2.21 | - |
|
||||
| `STRATA_INK_DF2_NO_Q4_SCREEN` | on / off | Intel Arc | - | - |
|
||||
| `STRATA_INK_ELASTIC_COMPACT` | text | NVIDIA and AMD | - | - |
|
||||
| `STRATA_INK_ELASTIC_EXPERTS` | on / off | NVIDIA and AMD | - | [INKLING_KV.md](INKLING_KV.md) |
|
||||
| `STRATA_INK_ELASTIC_MACRO_HOST` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_INK_ELASTIC_MULTI` | on / off | AMD | - | - |
|
||||
| `STRATA_INK_ELASTIC_STAGE` | on / off | AMD | - | - |
|
||||
| `STRATA_INK_EXACT_GRAPH` | on / off | NVIDIA and AMD | v0.2.21 | - |
|
||||
| `STRATA_INK_EXACT_ROWS` | on / off | AMD | v0.2.21 | - |
|
||||
| `STRATA_INK_GGUF_CHUNK256` | on / off | NVIDIA and AMD | v0.2.23 | - |
|
||||
@@ -581,16 +593,18 @@ version made it the default.
|
||||
| `STRATA_L32_GATE_ROWS` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_LAZY_KV` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_MLA_EXPANDED` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_MLA_EXP_MODE` | number | Intel Arc | - | - |
|
||||
| `STRATA_L32_MLA_FD_ORIG` | on / off | Intel Arc | - | - |
|
||||
| `STRATA_L32_MTP_FLOOR` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_MTP_GROUPED` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_MTP_PLAIN` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_MTP_POOL` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_PF_VERIFY` | number | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_PRELOAD` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_PROBE_ALLOC` | on / off | AMD | - | - |
|
||||
| `STRATA_L32_SPAN_HINT` | number | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_SPEC_SPAN` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_TIER_GROUPED_OFF` | on / off | NVIDIA and AMD | - | - |
|
||||
| `STRATA_L32_W2_PACK` | number | NVIDIA and AMD | - | - |
|
||||
| `STRATA_MEM_CREDIT_INACTIVE` | text | NVIDIA and AMD | v0.2.16 | - |
|
||||
| `STRATA_METAL_LDB` | on / off | Mac | v0.2.16 | - |
|
||||
| `STRATA_METAL_MTP_OVERLAP` | on / off | Mac | v0.2.16 | - |
|
||||
@@ -670,7 +684,7 @@ version made it the default.
|
||||
| `STRATA_WDDM_SHARED_RESERVE_MIB` | number | NVIDIA and AMD | v0.2.17 | - |
|
||||
| `STRATA_XN_F16` | on / off | NVIDIA and AMD | v0.2.16 | [DETAILS.md](DETAILS.md) |
|
||||
|
||||
## Ling-3.2-Air options (27)
|
||||
## Ling-3.2-Air options (29)
|
||||
|
||||
These are command-line options and variables of `strata launch` and setup, not engine variables. Nothing here is on unless you ask,
|
||||
except the thinking default (off) and the memory tier (chosen for your computer when you say `auto`).
|
||||
@@ -683,6 +697,8 @@ except the thinking default (off) and the memory tier (chosen for your computer
|
||||
| `--ram-budget-gib N` | let the engine hold at most N GiB of RAM (default: the available RAM less 6 GiB) | launcher-flag | opt-in |
|
||||
| `--turbo-ssd` | faster, may change answers: in tier C the engine skips a cold expert read from the SSD once memory covers enough of the routing weight; off unless asked | launcher-flag | opt-in |
|
||||
| `--cpu-coexec N` | N CPU threads work on the experts that are not on the card; answers stay identical; off unless asked | launcher-flag | opt-in |
|
||||
| `--expert-skip LEVEL` | Ling-3.2-Air expert skip: medium = the engine's --skip-tau 0.05, faster (about +9 to 10 % on a 3090) and slightly less exact (about 1 word in 60 differs); offered only for an NVIDIA card of the 24 GB class (3090, 4090) on Linux when the plan streams experts (tier B or C); off unless asked; written into the saved run config as `--skip-tau 0.05` only when on | launcher-flag | opt-in |
|
||||
| `--expert-skip LEVEL (setup)` | Ling-3.2-Air expert skip: medium = the engine's --skip-tau 0.05, faster (about +9 to 10 % on a 3090) and slightly less exact (about 1 word in 60 differs); offered only for an NVIDIA card of the 24 GB class (3090, 4090) on Linux when the plan streams experts (tier B or C); off unless asked; written into the saved run config as `--skip-tau 0.05` only when on | setup-flag | opt-in |
|
||||
| `--tier / --vram-budget-gib / --ram-budget-gib / --turbo-ssd / --cpu-coexec / --thinking` | the same options for setup.py (the first install writes them into the run config) | setup-flag | opt-in |
|
||||
| `--tier vram/hybrid/nvme` | the engine's own words for tiers A / B / C (strata-ling32 --tier); passed only when the person chose one | engine-flag | default |
|
||||
| `--vram-budget-gib / --ram-budget-gib / --turbo-ssd / --cpu-coexec` | passed to strata-ling32 only when given | engine-flag | opt-in |
|
||||
|
||||
@@ -34,7 +34,7 @@ macro(strata_quant_layer)
|
||||
target_compile_definitions(strata_quant PRIVATE STRATA_SK_X86_TIERS=1)
|
||||
if(MSVC)
|
||||
set_source_files_properties(${_sq}/src/quant/x86/sk_codecs_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "^(Clang|IntelLLVM)$")
|
||||
set_source_files_properties(${_sq}/src/quant/x86/sk_codecs_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512;/clang:-mavx512vnni;/clang:-ffp-contract=off")
|
||||
else()
|
||||
set_source_files_properties(${_sq}/src/quant/x86/sk_codecs_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
|
||||
@@ -51,7 +51,7 @@ macro(strata_quant_layer)
|
||||
# so pass /clang:-mavx512vnni explicitly so dot_avx512.cpp emits VPDPBUSD.
|
||||
set_source_files_properties(${_sq}/src/quant/x86/dot_avx2.cpp ${_sq}/src/quant/x86/act_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
|
||||
set_source_files_properties(${_sq}/src/quant/x86/dot_avx.cpp ${_sq}/src/quant/x86/act_avx.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX")
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "^(Clang|IntelLLVM)$")
|
||||
set_source_files_properties(${_sq}/src/quant/x86/dot_avx512.cpp ${_sq}/src/quant/x86/act_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512;/clang:-mavx512vnni")
|
||||
else()
|
||||
set_source_files_properties(${_sq}/src/quant/x86/dot_avx512.cpp ${_sq}/src/quant/x86/act_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
|
||||
|
||||
@@ -255,7 +255,8 @@ inline TierPlan plan_tier(const TierHardware& hw, const TierRequestOpts& rq, con
|
||||
}
|
||||
if (rq.tier != TierRequest::Nvme && b_fits) {
|
||||
p.mode = TierMode::B;
|
||||
p.lookahead_k = 4; // measured on a 5090: the k = 4 predictor (more lead time, 1.8 ms) beats k = 2 (1.0 ms) by 8 points of decode speed in a gated prefetch
|
||||
// the pool layout (every card byte is a slot) takes the k = 2 predictor (recall 64.6 % top-8, lead 0.8 ms): +2.0 % decode on a 3090 and +2.6 % on a 5090 against k = 4 (recall 54 %, lead 1.7 ms), same ids (2026-12-03). The old layout (hot prefix + a small pool, --tier-pool off) keeps k = 4: measured on a 5090 before the pool layout, k = 4 beat k = 2 by 8 points there.
|
||||
p.lookahead_k = pool_mode ? 2 : 4;
|
||||
if (rq.prefetch_width < 0) p.prefetch_width = 4; // decode: gated (rank cut-off 8, 8 MB in flight): +4..5 % measured on a 5090; ungated width 4 or more is slower (see P2-RESULTS)
|
||||
p.ram_ranks = rt.n_exp - p.vram_ranks;
|
||||
p.ram_prefix_bytes = rest;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// include/strata/platform/posix_io_compat.hpp - open / pread / close on a plain file for code that is written against POSIX.
|
||||
// On Linux and Mac these are the system calls; on Windows they are the CRT descriptor plus ReadFile with an explicit offset
|
||||
// (no shared file position, so several threads may read one descriptor, as pread allows).
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <fcntl.h>
|
||||
#include <io.h>
|
||||
#include <sys/stat.h>
|
||||
#ifdef OUT
|
||||
#undef OUT
|
||||
#endif
|
||||
#ifdef IN
|
||||
#undef IN
|
||||
#endif
|
||||
#ifdef small
|
||||
#undef small
|
||||
#endif
|
||||
|
||||
namespace strata::platform {
|
||||
/// open a file read-only for pread; -1 on failure
|
||||
inline int posix_open_ro(const char* path) { return ::_open(path, _O_RDONLY | _O_BINARY | _O_RANDOM); }
|
||||
inline int posix_close(int fd) { return ::_close(fd); }
|
||||
/// pread(2): up to `n` bytes at `off`; the number read, 0 at the end of the file, -1 on an error. Reads are capped at 1 GiB per call.
|
||||
inline int64_t posix_pread(int fd, void* buf, size_t n, uint64_t off) {
|
||||
const intptr_t h = ::_get_osfhandle(fd);
|
||||
if (h == -1) return -1;
|
||||
const DWORD want = (DWORD) (n < (size_t) (1u << 30) ? n : (size_t) (1u << 30));
|
||||
OVERLAPPED ov{};
|
||||
ov.Offset = (DWORD) (off & 0xffffffffull);
|
||||
ov.OffsetHigh = (DWORD) (off >> 32);
|
||||
DWORD got = 0;
|
||||
if (!::ReadFile((HANDLE) h, buf, want, &got, &ov)) {
|
||||
if (::GetLastError() == ERROR_HANDLE_EOF) return 0;
|
||||
return -1;
|
||||
}
|
||||
return (int64_t) got;
|
||||
}
|
||||
} // namespace strata::platform
|
||||
#else
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
namespace strata::platform {
|
||||
inline int posix_open_ro(const char* path) { return ::open(path, O_RDONLY | O_CLOEXEC); }
|
||||
inline int posix_close(int fd) { return ::close(fd); }
|
||||
inline int64_t posix_pread(int fd, void* buf, size_t n, uint64_t off) { return (int64_t) ::pread(fd, buf, n, (off_t) off); }
|
||||
} // namespace strata::platform
|
||||
#endif
|
||||
@@ -0,0 +1,24 @@
|
||||
// include/strata/prefill/xmx_dense_gemm.hpp - the SYCL engine's own dense prompt GEMM on the XMX units (joint_matrix), the
|
||||
// replacement for the oneMKL call (dpct::blas::gemm) where oneMKL is not there (Windows, STRATA_SYCL_NO_ONEMKL) and an opt-in
|
||||
// alternative where it is.
|
||||
//
|
||||
// Y[t][n] = alpha * sum_k X[t][k] * W[n][k] + beta * Y[t][n] t < T, n < N, k < K
|
||||
//
|
||||
// the same product the engine's column-major call computes (Y^T = W^T . X, W stored K x N with leading dimension lda, X stored
|
||||
// K x T with leading dimension ldx, Y stored N x ldy). Inputs are BF16 or FP16 bit patterns, accumulation is FP32 on the
|
||||
// matrix units (every BF16 / FP16 product is exact in FP32, so only the summation order differs from oneMKL's).
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include <sycl/sycl.hpp>
|
||||
|
||||
namespace strata::prefill::xmxd {
|
||||
|
||||
enum class Elem { f16, bf16 };
|
||||
|
||||
/// true: the product was enqueued on `q`. false: the shape is not one the kernels take (nothing was enqueued).
|
||||
bool gemm_tn(sycl::queue& q, Elem e, const uint16_t* W, int64_t lda, const uint16_t* X, int64_t ldx, float* Y, int64_t ldy,
|
||||
int64_t N, int64_t T, int64_t K, float alpha, float beta);
|
||||
|
||||
} // namespace strata::prefill::xmxd
|
||||
@@ -21,8 +21,16 @@
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
// profiling build (-DSTRATA_SY_PROFILE, see sycl/ling32_sy.hpp sy::launch): the queues record kernel times; the normal build is unchanged
|
||||
#ifdef STRATA_SY_PROFILE
|
||||
#define STRATA_SY_QUEUE_PROPS sycl::property_list{sycl::property::queue::in_order(), sycl::property::queue::enable_profiling()}
|
||||
#else
|
||||
#define STRATA_SY_QUEUE_PROPS sycl::property_list{sycl::property::queue::in_order()}
|
||||
#endif
|
||||
|
||||
#ifndef STRATA_USE_SYCL
|
||||
#define STRATA_USE_SYCL 1
|
||||
#endif
|
||||
@@ -46,6 +54,8 @@ struct DevState {
|
||||
sycl::context ctx;
|
||||
Stream* def = nullptr; // the null stream
|
||||
std::atomic<uint64_t> allocated{0}; // bytes of cudaMalloc not yet freed (cudaMemGetInfo fallback when the driver gives no free-memory query)
|
||||
std::mutex amu;
|
||||
std::unordered_map<void*, size_t> asz; // size of every live cudaMalloc block: a cudaFree (the tier store's lazy-KV give-back) lowers `allocated` again
|
||||
explicit DevState(const sycl::device& d) : dev(d), ctx(d) {}
|
||||
};
|
||||
|
||||
@@ -68,7 +78,7 @@ struct Runtime {
|
||||
for (auto& d : sycl::device::get_devices(sycl::info::device_type::gpu))
|
||||
if (pass == 1 || d.get_backend() == sycl::backend::ext_oneapi_level_zero) devs.push_back(new DevState(d));
|
||||
for (size_t i = 0; i < devs.size(); ++i) {
|
||||
auto* s = new Stream{sycl::queue(devs[i]->ctx, devs[i]->dev, sycl::property_list{sycl::property::queue::in_order()}), static_cast<int>(i)};
|
||||
auto* s = new Stream{sycl::queue(devs[i]->ctx, devs[i]->dev, STRATA_SY_QUEUE_PROPS), static_cast<int>(i)};
|
||||
devs[i]->def = s;
|
||||
streams.push_back(s);
|
||||
}
|
||||
@@ -229,7 +239,7 @@ inline cudaError_t cudaMalloc(void** p, size_t n) {
|
||||
auto& ds = strata::sy::dev_state();
|
||||
cudaError_t e = strata::sy::guard([&] { *p = sycl::malloc_device(n ? n : 1, ds.dev, ds.ctx); }, cudaErrorMemoryAllocation);
|
||||
if (e == cudaSuccess && !*p) return strata::sy::fail(cudaErrorMemoryAllocation);
|
||||
if (e == cudaSuccess) ds.allocated += n;
|
||||
if (e == cudaSuccess) { ds.allocated += n; std::lock_guard<std::mutex> g(ds.amu); ds.asz[*p] = n; }
|
||||
return e;
|
||||
}
|
||||
template <class T>
|
||||
@@ -237,7 +247,12 @@ inline cudaError_t cudaMalloc(T** p, size_t n) { return cudaMalloc(reinterpret_c
|
||||
inline cudaError_t cudaFree(void* p) {
|
||||
if (!p) return cudaSuccess;
|
||||
auto& ds = strata::sy::dev_state();
|
||||
return strata::sy::guard([&] { sycl::free(p, ds.ctx); }); // the byte count of `allocated` is not tracked per pointer: the fallback free-memory figure only grows
|
||||
{
|
||||
std::lock_guard<std::mutex> g(ds.amu);
|
||||
auto it = ds.asz.find(p);
|
||||
if (it != ds.asz.end()) { ds.allocated -= it->second; ds.asz.erase(it); }
|
||||
}
|
||||
return strata::sy::guard([&] { sycl::free(p, ds.ctx); });
|
||||
}
|
||||
inline cudaError_t cudaHostAlloc(void** p, size_t n, unsigned = 0) {
|
||||
*p = nullptr;
|
||||
@@ -333,7 +348,7 @@ inline cudaError_t cudaMemsetAsync(void* p, int v, size_t n, cudaStream_t s = nu
|
||||
inline cudaError_t cudaStreamCreate(cudaStream_t* s) {
|
||||
return strata::sy::guard([&] {
|
||||
auto& ds = strata::sy::dev_state();
|
||||
auto* st = new strata::sy::Stream{sycl::queue(ds.ctx, ds.dev, sycl::property_list{sycl::property::queue::in_order()}), strata::sy::cur_dev()};
|
||||
auto* st = new strata::sy::Stream{sycl::queue(ds.ctx, ds.dev, STRATA_SY_QUEUE_PROPS), strata::sy::cur_dev()};
|
||||
{ std::lock_guard<std::mutex> g(strata::sy::rt().mu); strata::sy::rt().streams.push_back(st); }
|
||||
*s = st;
|
||||
});
|
||||
|
||||
@@ -711,6 +711,7 @@ public:
|
||||
|
||||
strata::ink::sm120_plan_slots_ref().store(max_slots_);
|
||||
strata::ink::sm120_plan_swa_host_bytes_ref().store(plan.swa_host_bytes);
|
||||
model_.compact_elastic_ctx = std::max(256, opts.max_ctx); // the COMPACT elastic pool is limited to the contexts it is proven for (STRATA_INK_ELASTIC_COMPACT_MAX_CTX, default 262144)
|
||||
// Load .strata v1.1 / .gguf (Unsloth + ggml-org) / HF safetensors trunk + experts (Single-GPU, EP2, Layer-Split, or 4-tier GPU+RAM+SSD!)
|
||||
// A card with too little free memory for even the shared layers (the trunk) is a refusal with a message, not the fatal GPU error that ends the engine (PLAN-0225 item 24).
|
||||
bool loaded_ok = false;
|
||||
@@ -1943,8 +1944,19 @@ public:
|
||||
return best_nd;
|
||||
}
|
||||
|
||||
// Principle 2's "hybrid" (experts in host memory). With the COMPACT elastic pool a few dozen experts are on the host only because the K/V took their chunks: a draft step reads a cold expert
|
||||
// rarely, the measured cost of principle 2 (a card with a third of the experts on the host) does not apply. The pool counts as hybrid only from STRATA_INK_ELASTIC_DRAFT_HOST_PCT percent of
|
||||
// the 3072 experts on the host (default 10, the share at which kDraftTierCutLimit calls a drafter's cost "noticeable"; 0 = any host expert, the old rule). Measured on a 5060 Ti 16 GB, SQ-20 v2, DFlash 2:
|
||||
// 8K prompt 74.7 -> 103.5 tok/s, 16K 23 -> 71 with 2-3% of the experts on the host, 4K level with the base; at 130K (15% on the host) the window governor drafts nothing either way.
|
||||
bool draft_hybrid_now() const {
|
||||
const size_t nh = model_.n_host_experts;
|
||||
if (nh == 0) return false;
|
||||
if (!model_.elastic_compact) return true;
|
||||
static const double pct = [] { const char* e = std::getenv("STRATA_INK_ELASTIC_DRAFT_HOST_PCT"); return e ? std::atof(e) : 10.0; }();
|
||||
return (double)nh * 100.0 > pct * 3072.0;
|
||||
}
|
||||
bool draft_plain_now(int ctx_pos) const override {
|
||||
return strata::core::ink_draft_plain_step(model_.n_host_experts > 0, ctx_pos, draft_forced_, dev_cc_);
|
||||
return strata::core::ink_draft_plain_step(draft_hybrid_now(), ctx_pos, draft_forced_, dev_cc_);
|
||||
}
|
||||
|
||||
int dspark_spec_step_greedy(
|
||||
@@ -1958,7 +1970,7 @@ public:
|
||||
if (!initialized_ || model_.ls_active || !dspark_ || !dspark_->ready || slot != 0 || dspark_slot_ != 0) return 0;
|
||||
// the ONE drafter rule, principle 2 (strata/core/ink_draft_rule.hpp): on a hybrid card (experts in host memory) a step from kDraftPlainCtxHybrid tokens of context on is a plain step.
|
||||
// Per step, so it follows every request; `--draft on` turns it off; with all experts in VRAM the window governor decides alone.
|
||||
if (strata::core::ink_draft_plain_step(model_.n_host_experts > 0, anchor_pos, draft_forced_, dev_cc_)) return 0;
|
||||
if (strata::core::ink_draft_plain_step(draft_hybrid_now(), anchor_pos, draft_forced_, dev_cc_)) return 0;
|
||||
const bool dspark_opt = strata::ink::rtx5090::dspark_opt_on() && (runner_->d_tree_anc32 != nullptr);
|
||||
const bool deep_tree = (runner_->d_tree_anc32 != nullptr); // deep verify tree allocated (5090 builder or the 5060 Ti PLD graft)
|
||||
const int want_cap = (deep_tree && anchor_pos + 24 < eff_max_ctx_ && anchor_pos + 24 < dspark_->max_ctx)
|
||||
|
||||
@@ -874,7 +874,17 @@ struct InkCudaModel {
|
||||
if (do_compact_vram && all_sf4_or_mx8 && vfree > compact_sec4_bytes + (768ull << 20)) {
|
||||
// 100.0% ALL-3,072-EXPERT GDDR7 RESIDENCY on 16 GB RTX 5060 Ti (0 host misses, GPU MX8->SF4 transcode < 20 ms)!
|
||||
sec4_bytes = compact_sec4_bytes;
|
||||
INK_CK(cudaMalloc(&d_sec4, sec4_bytes));
|
||||
// one slot: the experts live in the elastic pool (packed hottest first) so the global K/V can take chunks from the coldest ones instead of going to host RAM;
|
||||
// ce_off[directory index] = the expert's offset in d_sec4. Empty (pool off, several slots, no virtual memory): one cudaMalloc packed in directory order, as before.
|
||||
std::vector<uint64_t> ce_off;
|
||||
size_t ce_pack = 0;
|
||||
if (sm120_plan_slots_ref().load() == 1 && compact_elastic_layout(dir, rd, opt5060_ld.compact_xcode, sf4_body_c, sf4_dn_off_c, ce_pack, ce_off)) {
|
||||
d_sec4 = elastic_sec4.base();
|
||||
sec4_bytes = ce_pack;
|
||||
} else {
|
||||
ce_off.clear();
|
||||
INK_CK(cudaMalloc(&d_sec4, sec4_bytes));
|
||||
}
|
||||
uint8_t* d_mx8_tmp = nullptr;
|
||||
uint32_t* d_amax_u32 = nullptr;
|
||||
INK_CK(cudaMalloc(&d_mx8_tmp, 16ull << 20));
|
||||
@@ -889,13 +899,14 @@ struct InkCudaModel {
|
||||
const auto& e = dir[di];
|
||||
const int key = il * man.c.n_experts + e.expert_id;
|
||||
auto& dev = h_exp[key];
|
||||
const size_t at = ce_off.empty() ? v_cur : (size_t)ce_off[(size_t)di]; // where this expert goes in d_sec4
|
||||
if (!rd.read_at(hdr.sections[4].file_offset + e.body_offset, h_stg, e.body_bytes, err)) {
|
||||
cudaFreeHost(h_stg); cudaFree(d_mx8_tmp); cudaFree(d_amax_u32);
|
||||
return false;
|
||||
}
|
||||
if (opt5060_ld.compact_xcode && e.gu_code_id == FMT_MX8 && e.dn_code_id == FMT_MX8) {
|
||||
INK_CK(cudaMemcpy(d_mx8_tmp, h_stg, e.body_bytes, cudaMemcpyHostToDevice));
|
||||
uint8_t* dst = d_sec4 + v_cur;
|
||||
uint8_t* dst = d_sec4 + at;
|
||||
float* dst_hdr = reinterpret_cast<float*>(dst);
|
||||
// Gate+Up: [2304, 2304]
|
||||
const uint8_t* gu_sp = d_mx8_tmp;
|
||||
@@ -913,19 +924,19 @@ struct InkCudaModel {
|
||||
INK_CK(cudaMemset(d_amax_u32, 0, 4));
|
||||
k_ink_mx8_amax<<<256, 256>>>(dn_sp, dn_ss, kInkHidden, kInkInter, d_amax_u32);
|
||||
k_ink_mx8_to_sf4<<<kInkHidden, 256>>>(dn_sp, dn_ss, d_amax_u32, dn_dp, dn_ds, dst_hdr + 2, kInkHidden, kInkInter);
|
||||
dev.body_off = v_cur;
|
||||
dev.body_off = at;
|
||||
dev.dn_off = (uint32_t)sf4_dn_off_c;
|
||||
dev.gu_code = FMT_SF4;
|
||||
dev.dn_code = FMT_SF4;
|
||||
dev.tier = 0;
|
||||
v_cur += sf4_body_c;
|
||||
if (ce_off.empty()) v_cur += sf4_body_c;
|
||||
++n_transcoded;
|
||||
any_tr_layer = true;
|
||||
} else {
|
||||
INK_CK(cudaMemcpy(d_sec4 + v_cur, h_stg, e.body_bytes, cudaMemcpyHostToDevice));
|
||||
dev.body_off = v_cur;
|
||||
INK_CK(cudaMemcpy(d_sec4 + at, h_stg, e.body_bytes, cudaMemcpyHostToDevice));
|
||||
dev.body_off = at;
|
||||
dev.tier = 0;
|
||||
v_cur += e.body_bytes;
|
||||
if (ce_off.empty()) v_cur += e.body_bytes;
|
||||
}
|
||||
}
|
||||
if (any_tr_layer) {
|
||||
@@ -2577,6 +2588,86 @@ struct InkCudaModel {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- Elastic expert pool, COMPACT (all-SF4 on the card, 16 GB RTX 50) ----
|
||||
// Lays the 3072 experts out in descending heat order (rd.vram_load_order(): the 3x-looped core first) and makes the pool (one VmmRange over the whole expert section).
|
||||
// off_of_di[directory index] = the expert's offset in d_sec4; pack_bytes = the section's size. MX8 experts are held transcoded to SF4 on the card, so the pool slot and the facts of
|
||||
// the host copy (elastic_src) are the SF4 form: an expert that leaves the card is copied device-to-host as it is. false: the pool is off or could not be made (nothing is
|
||||
// left allocated); the caller keeps its one cudaMalloc packed in directory order. STRATA_INK_ELASTIC_COMPACT=0 turns this path off alone.
|
||||
template <class Dir, class Reader>
|
||||
bool compact_elastic_layout(const Dir& dir, Reader& rd, bool xcode, size_t sf4_body, size_t sf4_dn_off, size_t& pack_bytes, std::vector<uint64_t>& off_of_di) {
|
||||
const char* ec = std::getenv("STRATA_INK_ELASTIC_COMPACT");
|
||||
const char* kv_vmm_env = std::getenv("STRATA_INK_KV_VMM");
|
||||
if (!InkElasticSec4Pool::env_enabled() || (ec && ec[0] == '0') || (kv_vmm_env && kv_vmm_env[0] == '0') || !strata::core::vmm_available()) return false;
|
||||
// measured clean up to 262144 (200K prompt: 947 prefill tok/s, 22.7 decode); above STRATA_INK_ELASTIC_COMPACT_MAX_CTX (default 262144) COMPACT keeps its host K/V as before
|
||||
const char* lim = std::getenv("STRATA_INK_ELASTIC_COMPACT_MAX_CTX");
|
||||
const int ctx_limit = lim ? std::atoi(lim) : 262144;
|
||||
if (compact_elastic_ctx > ctx_limit) {
|
||||
std::fprintf(stderr, "[InkCUDA] COMPACT elastic expert pool off: max-context %d is above %d (STRATA_INK_ELASTIC_COMPACT_MAX_CTX); the K/V beyond the card stays in host memory as before\n", compact_elastic_ctx, ctx_limit);
|
||||
return false;
|
||||
}
|
||||
const int n_total = man.c.n_phys * man.c.n_experts;
|
||||
const auto& vorder = rd.vram_load_order();
|
||||
std::vector<uint16_t> order;
|
||||
if ((int)vorder.size() == n_total) {
|
||||
order = vorder;
|
||||
} else {
|
||||
order.reserve((size_t)n_total);
|
||||
for (int il = man.c.core_start; il < man.c.core_end; ++il)
|
||||
for (int r = 0; r < man.c.n_experts; ++r) order.push_back((uint16_t)(il * man.c.n_experts + r));
|
||||
for (int il = 0; il < man.c.core_start; ++il)
|
||||
for (int r = 0; r < man.c.n_experts; ++r) order.push_back((uint16_t)(il * man.c.n_experts + r));
|
||||
for (int il = man.c.core_end; il < man.c.n_phys; ++il)
|
||||
for (int r = 0; r < man.c.n_experts; ++r) order.push_back((uint16_t)(il * man.c.n_experts + r));
|
||||
}
|
||||
std::vector<uint16_t> key_order;
|
||||
std::vector<InkElasticSlot> eslots;
|
||||
key_order.reserve(order.size());
|
||||
eslots.reserve(order.size());
|
||||
off_of_di.assign((size_t)n_total, 0);
|
||||
std::vector<InkHostExpertMeta> src((size_t)n_total);
|
||||
size_t max_body = 0;
|
||||
uint64_t pack_off = 0;
|
||||
for (uint16_t di : order) {
|
||||
const auto& e = dir[di];
|
||||
const int il = di / man.c.n_experts;
|
||||
const int key = il * man.c.n_experts + e.expert_id;
|
||||
const bool tr = xcode && e.gu_code_id == FMT_MX8 && e.dn_code_id == FMT_MX8; // held as SF4 on the card
|
||||
const uint32_t bytes = tr ? (uint32_t)sf4_body : (uint32_t)e.body_bytes;
|
||||
key_order.push_back((uint16_t)key);
|
||||
InkElasticSlot s{};
|
||||
s.key = key;
|
||||
s.body_off = pack_off;
|
||||
s.body_bytes = bytes;
|
||||
s.gu_code = tr ? (uint8_t)FMT_SF4 : e.gu_code_id;
|
||||
s.dn_code = tr ? (uint8_t)FMT_SF4 : e.dn_code_id;
|
||||
s.resident = true;
|
||||
eslots.push_back(s);
|
||||
off_of_di[(size_t)di] = pack_off;
|
||||
src[(size_t)key].body_bytes = bytes;
|
||||
src[(size_t)key].dn_off = tr ? (uint32_t)sf4_dn_off : (uint32_t)e.dn_offset;
|
||||
src[(size_t)key].gu_code = s.gu_code;
|
||||
src[(size_t)key].dn_code = s.dn_code;
|
||||
max_body = std::max<size_t>(max_body, bytes);
|
||||
pack_off += bytes;
|
||||
}
|
||||
elastic_sec4.heat().init(man.c.n_phys, man.c.n_experts, man.c.core_start, man.c.core_end, key_order);
|
||||
if (!elastic_sec4.init_vmm(pack_off, pack_off, eslots)) {
|
||||
elastic_sec4.release();
|
||||
off_of_di.clear();
|
||||
return false;
|
||||
}
|
||||
elastic_src = std::move(src);
|
||||
elastic_max_body = std::max(elastic_max_body, max_body);
|
||||
pack_bytes = (size_t)pack_off;
|
||||
elastic_compact = true;
|
||||
elastic_compact_sf4_only = true;
|
||||
for (const auto& s : eslots) if (s.gu_code != FMT_SF4 || s.dn_code != FMT_SF4) { elastic_compact_sf4_only = false; break; }
|
||||
return true;
|
||||
}
|
||||
int compact_elastic_ctx = 0; // the context asked for (set by the backend before the load; 0 = not known): the COMPACT pool is limited to the contexts it is proven for
|
||||
bool elastic_compact = false; // the experts of the COMPACT all-SF4 load are in the elastic pool
|
||||
bool elastic_compact_sf4_only = false; // and every one of them is SF4 (the macro prefill's host pass runs the SF4 tensor-core kernels only)
|
||||
|
||||
// ---- Elastic expert pool (see ink_elastic_sec4.hpp) ----
|
||||
// What arming allocates on the card: the prefill staging pair, the exact lane's staging slots, the hybrid engine's small buffers. Nothing is set aside in
|
||||
// advance (an idle card would lose it for nothing, and the drafter's allocations are sized against the free memory): the first eviction frees this much
|
||||
@@ -2845,7 +2936,7 @@ struct InkCudaModel {
|
||||
if (d_elastic_heat) { ink_heat_cfg().dev = nullptr; cudaFree(d_elastic_heat); d_elastic_heat = nullptr; }
|
||||
if (elastic_sec4.active()) { elastic_sec4.release(); d_sec4 = nullptr; }
|
||||
h_exp_shadow.clear();
|
||||
elastic_src.clear(); elastic_arena_off.clear(); elastic_armed = false; elastic_arena_ready = false; elastic_tier = false; elastic_arena_used = 0;
|
||||
elastic_src.clear(); elastic_arena_off.clear(); elastic_armed = false; elastic_arena_ready = false; elastic_tier = false; elastic_arena_used = 0; elastic_compact = false; elastic_compact_sf4_only = false;
|
||||
if (d_sec4) { cudaFree(d_sec4); d_sec4 = nullptr; }
|
||||
if (h_sec4_pinned) { cudaFreeHost(h_sec4_pinned); h_sec4_pinned = nullptr; }
|
||||
if (h_embed_raw) { cudaFreeHost(h_embed_raw); h_embed_raw = nullptr; d_embed_mapped = nullptr; }
|
||||
@@ -2873,6 +2964,7 @@ struct InkCudaRunner {
|
||||
// the context grows. Nothing is copied, so the card never holds the old and the new buffer at once and growth reaches max_ctx with every free byte (the copy path needed one old visit
|
||||
// buffer extra and stopped 1.2 to 1.8 GB short). Off for several slots (the slot stride is the capacity), layer split, the elastic 1M mode and where the driver has no virtual memory.
|
||||
bool kv_vmm = false;
|
||||
bool ce_kv_vmm = false; // COMPACT elastic pool: the global K/V is in virtual memory beside the slab (the slab keeps the SWA rings and ShortConv state), grows by taking chunks from the coldest experts
|
||||
struct KvVmmBuf { strata::core::VmmRange r; size_t bpp = 0; };
|
||||
KvVmmBuf kv_vmm_buf[kInkVisits][4]; // per visit: K, V, K scales, V scales (FP16: only K and V)
|
||||
int kv_dev_ctx = 0; // Global KV positions resident in VRAM
|
||||
@@ -3414,6 +3506,24 @@ struct InkCudaRunner {
|
||||
kv_dev_ctx = std::max(256, std::min(max_ctx, (max_slots == 1) ? c1_init_dev_cap : 4096));
|
||||
kv_host_ctx = 0;
|
||||
kv_alloc_ctx = kv_dev_ctx;
|
||||
} else if (max_slots == 1 && !m.ls_active && !m.ep2_active && m.all_sf4_vram && kv_offload_mode == 0 && m.elastic_sec4.active() && m.n_host_experts == 0 &&
|
||||
strata::core::vmm_available() && elastic_fits_max_ctx(avail_glob, per_pos_glob, max_ctx)) {
|
||||
// COMPACT elastic pool (16 GB RTX 50, every expert on the card as SF4): the global K/V is no longer in the slab. It starts small (what the 128 MiB-free rule leaves, at most
|
||||
// c1_init_dev_cap tokens) in its own virtual memory and grows by taking chunks from the coldest experts (reclaim_experts_for_kv), never from mapped host RAM.
|
||||
// 200 MiB, not the 128 of the host-K/V rule: the K/V of the pool is mapped in whole 2 MiB chunks per buffer (a start of a few thousand tokens costs more than its bytes), and the first long prompt
|
||||
// needs the macro prefill's scratch (72 MiB + a 48 MiB guard, ensure_pf_attn) from what is free after the start: with less the prefill fell back to the chunked path (4K prompt 3.9K -> 2.2K tok/s)
|
||||
const double keep = 200.0 * 1048576.0;
|
||||
const double room_s = (double)vfree - (double)eff_swa_vram - (double)sconv_bytes - (double)ws_reserve - keep; // nothing is set aside for arming: the first eviction frees what it needs
|
||||
const int safe_start = room_s > 0.0 ? ((int)std::min<double>((double)(1 << 20), room_s / (double)std::max<size_t>(1, per_pos_glob)) & ~63) : 0;
|
||||
kv_dev_ctx = std::max(256, std::min(std::min(max_ctx, c1_init_dev_cap), std::max(256, safe_start)));
|
||||
kv_host_ctx = 0;
|
||||
kv_alloc_ctx = kv_dev_ctx;
|
||||
ce_kv_vmm = kv_dev_ctx < max_ctx;
|
||||
const size_t room_e = elastic_free_room(avail_glob);
|
||||
const size_t need_evict = (size_t)max_ctx * per_pos_glob > room_e ? (size_t)max_ctx * per_pos_glob - room_e : 0;
|
||||
m.elastic_arena_plan = std::min<uint64_t>(m.elastic_sec4.reclaimable_bytes(), (uint64_t)need_evict + need_evict / 8 + (96ull << 20));
|
||||
std::fprintf(stderr, "[InkCUDA] COMPACT elastic expert pool (kv_fmt=%d): K/V starts at %d tokens on the card (own virtual memory) and grows to %d with no host K/V; at most %.2f GiB of the coldest experts leave the card for it (%.2f GiB may)\n",
|
||||
(int)kv_dtype, kv_dev_ctx, max_ctx, (double)need_evict / 1073741824.0, (double)m.elastic_sec4.reclaimable_bytes() / 1073741824.0);
|
||||
} else if (max_slots == 1 && !m.ls_active && !m.ep2_active && !m.all_sf4_vram && kv_offload_mode == 0 && m.elastic_sec4.active() && (m.n_host_experts == 0 || m.elastic_tier) &&
|
||||
strata::core::vmm_available() && elastic_fits_max_ctx(avail_glob, per_pos_glob, max_ctx)) {
|
||||
// Elastic expert pool: the whole global K/V stays on the card (kv_host_ctx = 0). It starts small and grows through the K/V's virtual memory;
|
||||
@@ -3458,7 +3568,7 @@ struct InkCudaRunner {
|
||||
// 256-byte-aligned slab to eliminate ~240 separate 2 MiB cudaMalloc rounding slabs (~240+ MiB reclaimed)!
|
||||
const bool use_slab = m.all_sf4_vram && !m.ls_active;
|
||||
kv_vmm = false;
|
||||
if (max_slots == 1 && !m.ls_active && !use_slab && !elastic_kv.enabled && kv_host_ctx == 0 && kv_dev_ctx > 0 && kv_dev_ctx < max_ctx) {
|
||||
if (max_slots == 1 && !m.ls_active && (!use_slab || ce_kv_vmm) && !elastic_kv.enabled && kv_host_ctx == 0 && kv_dev_ctx > 0 && kv_dev_ctx < max_ctx) {
|
||||
const char* vmm_env = std::getenv("STRATA_INK_KV_VMM");
|
||||
if (!(vmm_env && vmm_env[0] == '0')) {
|
||||
cudaSetDevice(m.primary_gpu);
|
||||
@@ -3476,7 +3586,7 @@ struct InkCudaRunner {
|
||||
const int ip = ink_visit_phys(v);
|
||||
const bool swa = m.man.c.is_swa[ip] != 0;
|
||||
const int dcap = swa ? swa_ring : kv_dev_ctx;
|
||||
if (dcap > 0 && !(swa && swa_in_host && !swa_pinned[v])) {
|
||||
if (dcap > 0 && !(swa && swa_in_host && !swa_pinned[v]) && !(kv_vmm && !swa)) { // the global K/V of the COMPACT elastic pool is not in the slab
|
||||
const size_t elems = (size_t)max_slots * dcap * kInkKVHeads * kInkHeadDim;
|
||||
if (kv_dtype == InkKvDtype::FP16) {
|
||||
kv_bump(elems * sizeof(__half));
|
||||
@@ -3533,7 +3643,7 @@ struct InkCudaRunner {
|
||||
if (!ok_sw) {
|
||||
ink_alloc_failed(cudaErrorMemoryAllocation, elems, __FILE__, __LINE__);
|
||||
}
|
||||
} else if (use_slab) {
|
||||
} else if (use_slab && !(kv_vmm && !swa)) {
|
||||
if (kv_dtype == InkKvDtype::FP16) {
|
||||
kv_desc[v].k_f16 = reinterpret_cast<__half*>(kv_slice(elems * sizeof(__half)));
|
||||
kv_desc[v].v_f16 = reinterpret_cast<__half*>(kv_slice(elems * sizeof(__half)));
|
||||
@@ -4027,6 +4137,7 @@ struct InkCudaRunner {
|
||||
if (!m.elastic_sec4.active()) return;
|
||||
strata::platform::VramGuardConfig c = strata::platform::make_cuda_config(m.primary_gpu);
|
||||
c.chunk_bytes = strata::core::vmm_granularity();
|
||||
if (m.elastic_compact) { c.low_mib = 96; c.target_mib = 144; c.high_mib = 320; } // COMPACT starts with ~175 MiB free by design and lazy allocations of the first requests take ~60 MiB of it (117 MiB measured): the general 192 / 352 / 512 shed 350 MiB of experts at the first poll, 128 / 176 / 352 still 160 MiB, and the first request paid the arming (3 GiB pinned host copy, ~3 s: decode 89 -> 38 tok/s on a 128-token reply)
|
||||
if (vram_guard.init(c)) std::fprintf(stderr, "[InkElastic] VRAM guard on: %s (low %llu MiB, target %llu MiB, high %llu MiB)\n", vram_guard.status(),
|
||||
(unsigned long long)(vram_guard.low_bytes() >> 20), (unsigned long long)(vram_guard.target_bytes() >> 20), (unsigned long long)(vram_guard.high_bytes() >> 20));
|
||||
}
|
||||
@@ -6440,6 +6551,7 @@ struct InkCudaRunner {
|
||||
if (!ink_rtx5060ti_cfg(m.primary_gpu).prefill_lm || !sm120::available()) return false;
|
||||
if (m.ls_active || m.ep2_active || !m.hybrid.active || m.hybrid.ssd_only || m.hybrid.tier_on) return false;
|
||||
if (max_passes_override != 0 || m.n_host_experts == 0) return false;
|
||||
if (m.elastic_compact) return false; // the elastic pool takes experts from the middle of layers, not whole coda layers: this path streams whole layers only
|
||||
const int fhc = first_host_coda_layer();
|
||||
return (fhc >= m.man.c.core_end && fhc < m.man.c.n_phys);
|
||||
}
|
||||
@@ -6551,9 +6663,20 @@ struct InkCudaRunner {
|
||||
|
||||
bool can_allvram_macro_prefill() const noexcept {
|
||||
if (!ink_rtx5060ti_cfg(m.primary_gpu).prefill_lm || !sm120::available()) return false;
|
||||
if (!m.all_sf4_vram || m.ls_active || m.ep2_active || max_passes_override != 0 || m.n_host_experts != 0) return false;
|
||||
if (!m.all_sf4_vram || m.ls_active || m.ep2_active || max_passes_override != 0 || (m.n_host_experts != 0 && !macro_host_pass_ok())) return false;
|
||||
return (d_pf_slab != nullptr && d_pf_slab_bytes >= (72ull << 20));
|
||||
}
|
||||
// COMPACT elastic pool: experts that left the card for the K/V are streamed layer by layer inside the macro prefill (macro_host_pass), so a long prompt keeps its
|
||||
// single-sweep speed after the first eviction. Needs the exact lane's staging pair, a pinned host copy and SF4 experts only.
|
||||
bool macro_host_pass_ok() const noexcept {
|
||||
const auto& h = m.hybrid;
|
||||
return m.elastic_compact && m.elastic_compact_sf4_only && m.elastic_armed && h.d_pf_stage[0] && h.d_pf_stage[1] && h.pf_stage_bytes >= (8ull << 20) &&
|
||||
h.sec4_is_pinned && !h.tier_on && !h.ssd_only && !host_macro_off();
|
||||
}
|
||||
static bool host_macro_off() noexcept { // STRATA_INK_ELASTIC_MACRO_HOST=0: the evicted experts keep the generic chunked prefill (the old behaviour of this lane)
|
||||
const char* e = std::getenv("STRATA_INK_ELASTIC_MACRO_HOST");
|
||||
return e && e[0] == '0';
|
||||
}
|
||||
|
||||
// Visit-Major All-VRAM Macro-Prefill (W = 2048..4096 tokens per MoE weight sweep -> >15,000-20,000 ppts on 8K+!):
|
||||
// Runs Attn+ShortConv+Controllers+Router in micro-chunks (mc <= max_batch) reusing d_pf_slab for Flash-GQA,
|
||||
@@ -6731,6 +6854,57 @@ struct InkCudaRunner {
|
||||
const Sm120MoeSel mac_sel = macro_moe_sel(tile_rows);
|
||||
sm120::moe_sf4_gu_tc(m.d_sec4, m.d_experts[ip], tb, opt5060_macro.d_xa_fp4, d_ha_mac, max_tiles, tile_rows, st, &mac_sel);
|
||||
sm120::moe_sf4_dn_tc(m.d_sec4, m.d_experts[ip], tb, d_ha_mac, opt5060_macro.d_tw, d_y_acc, max_tiles, tile_rows, st, /*atomic_reduce=*/true, &mac_sel);
|
||||
if (m.n_host_experts > 0 && m.layer_has_host[ip]) {
|
||||
// The experts of this layer that left the card (COMPACT elastic pool): the same single W-token sweep, over the host copy streamed through the staging pair
|
||||
// in chunks of at most 24 MiB. The binning skips every expert whose table entry is tier 2, so each pass counts only the experts of its chunk.
|
||||
auto& hyb = m.hybrid;
|
||||
struct HostChunk { std::vector<int> eids; std::vector<size_t> offs; size_t total = 0; };
|
||||
std::vector<HostChunk> hchunks;
|
||||
{
|
||||
HostChunk cur;
|
||||
size_t used = 0;
|
||||
const size_t cap = std::min<size_t>(hyb.pf_stage_bytes, 24ull << 20);
|
||||
for (int e = 0; e < kInkExperts; ++e) {
|
||||
const auto& hm = hyb.host_meta[(size_t)ip * kInkExperts + e];
|
||||
if (!hm.body) continue;
|
||||
const size_t b = (hm.body_bytes + 255ull) & ~255ull;
|
||||
if (used + b > cap && !cur.eids.empty()) { cur.total = used; hchunks.push_back(std::move(cur)); cur = {}; used = 0; }
|
||||
cur.eids.push_back(e);
|
||||
cur.offs.push_back(used);
|
||||
used += b;
|
||||
}
|
||||
if (!cur.eids.empty()) { cur.total = used; hchunks.push_back(std::move(cur)); }
|
||||
}
|
||||
auto issue_host_dma = [&](size_t ci, int buf) {
|
||||
if (hyb.pf_buf_busy[buf]) { INK_CK(cudaEventSynchronize(hyb.pf_ev_done[buf])); hyb.pf_buf_busy[buf] = false; }
|
||||
const auto& ch = hchunks[ci];
|
||||
InkExpertDev* he = hyb.h_pf_exp_pin[buf];
|
||||
for (int e = 0; e < kInkExperts; ++e) { he[e] = {}; he[e].tier = 2; }
|
||||
for (size_t i = 0; i < ch.eids.size(); ++i) {
|
||||
const int e = ch.eids[i];
|
||||
const auto& hm = hyb.host_meta[(size_t)ip * kInkExperts + e];
|
||||
he[e].body_off = ch.offs[i];
|
||||
he[e].dn_off = hm.dn_off;
|
||||
he[e].gu_code = hm.gu_code;
|
||||
he[e].dn_code = hm.dn_code;
|
||||
he[e].tier = 0;
|
||||
INK_CK(cudaMemcpyAsync(hyb.d_pf_stage[buf] + ch.offs[i], hm.body, hm.body_bytes, cudaMemcpyHostToDevice, hyb.pf_dma_st));
|
||||
}
|
||||
INK_CK(cudaMemcpyAsync(hyb.d_pf_exp_tmp[buf], he, (size_t)kInkExperts * sizeof(InkExpertDev), cudaMemcpyHostToDevice, hyb.pf_dma_st));
|
||||
INK_CK(cudaEventRecord(hyb.pf_ev_dma[buf], hyb.pf_dma_st));
|
||||
};
|
||||
if (!hchunks.empty()) issue_host_dma(0, 0);
|
||||
for (size_t ci = 0; ci < hchunks.size(); ++ci) {
|
||||
const int buf = (int)(ci & 1);
|
||||
if (ci + 1 < hchunks.size()) issue_host_dma(ci + 1, 1 - buf);
|
||||
INK_CK(cudaStreamWaitEvent(st, hyb.pf_ev_dma[buf], 0));
|
||||
k_ink_moe_bin<<<1, 128, 0, st>>>(hyb.d_pf_exp_tmp[buf], opt5060_macro.d_tidx, W, tile_rows, tb);
|
||||
sm120::moe_sf4_gu_tc(hyb.d_pf_stage[buf], hyb.d_pf_exp_tmp[buf], tb, opt5060_macro.d_xa_fp4, d_ha_mac, max_tiles, tile_rows, st, &mac_sel);
|
||||
sm120::moe_sf4_dn_tc(hyb.d_pf_stage[buf], hyb.d_pf_exp_tmp[buf], tb, d_ha_mac, opt5060_macro.d_tw, d_y_acc, max_tiles, tile_rows, st, /*atomic_reduce=*/true, &mac_sel);
|
||||
INK_CK(cudaEventRecord(hyb.pf_ev_done[buf], st));
|
||||
hyb.pf_buf_busy[buf] = true;
|
||||
}
|
||||
}
|
||||
if (prof_prefill) { INK_CK(cudaStreamSynchronize(st)); tm_stepB += mms(tb0, mnow()); }
|
||||
auto tc0 = mnow();
|
||||
|
||||
|
||||
@@ -104,6 +104,9 @@ add_custom_command(
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/ink_hip_strixhalo_megakernel.hip.h"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/ink_hip_df2.hip.h"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../../../include/strata/hip_uma_guard.hpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../ink_elastic_sec4.hpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../../../include/strata/core/vmm.hpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../../core/vmm.cpp"
|
||||
COMMENT "Compiling strata-inkling multi-gen HIP backend (${STRATA_HIP_ARCHS})"
|
||||
VERBATIM
|
||||
)
|
||||
|
||||
@@ -29,6 +29,10 @@
|
||||
#include "strata/platform/cgroup_mem.hpp"
|
||||
#include "strata/platform/commit.hpp"
|
||||
#include "strata/quant/sk_codecs.hpp"
|
||||
#include "strata/core/vmm.hpp"
|
||||
#include "../ink_elastic_sec4.hpp"
|
||||
#include "strata/platform/vram_guard.hpp"
|
||||
#include "strata/platform/vram_guard_driver.hpp"
|
||||
#if defined(__linux__)
|
||||
#include "strata/platform/numa_balancing.hpp"
|
||||
#endif
|
||||
@@ -227,6 +231,21 @@ static bool hip_ok(hipError_t e, const char* ctx, std::string& err) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Where an elastic (virtual-memory) K/V pool gets its 2 MiB chunks (the backend: chunks other programs left free above a floor, chunks the expert pool
|
||||
// donated). reserve_chunks makes `n` chunks available (it may take them from the coldest experts) or says no; take_chunk then hands them out.
|
||||
struct KvChunkSource {
|
||||
virtual ~KvChunkSource() = default;
|
||||
virtual bool reserve_chunks(int64_t n, hipStream_t st, size_t min_free_headroom) = 0;
|
||||
virtual strata::core::VmmChunk take_chunk() = 0;
|
||||
};
|
||||
|
||||
// A VmmRange that can sit in a std::vector: the pools are resized (moved) before init() reserves anything, so moving only ever sees an empty range.
|
||||
struct VmmRangeBox : strata::core::VmmRange {
|
||||
VmmRangeBox() = default;
|
||||
VmmRangeBox(VmmRangeBox&&) noexcept {}
|
||||
VmmRangeBox& operator=(VmmRangeBox&&) noexcept { return *this; }
|
||||
};
|
||||
|
||||
// Growable on-demand GPU Paged KV Pool for ONE visit (SWA or Global) across all max_slots!
|
||||
struct VisitKvPool {
|
||||
bool is_swa = true;
|
||||
@@ -250,19 +269,41 @@ struct VisitKvPool {
|
||||
GpuBuffer k_scales;
|
||||
GpuBuffer v_scales;
|
||||
|
||||
void release() {
|
||||
free_gpu_buffer(d_pt);
|
||||
// Elastic K/V (STRATA_INK_KV_VMM, global pools of a discrete card): the whole address range is reserved once, 2 MiB chunks are mapped as pages are
|
||||
// needed. The base never moves (no copy, no new graph), the pool grows without the 3x peak of realloc + copy, and the chunks can come from the experts.
|
||||
bool vmm = false;
|
||||
int vmm_max_pages = 0;
|
||||
KvChunkSource* src = nullptr;
|
||||
VmmRangeBox r_k, r_v, r_ks, r_vs;
|
||||
|
||||
size_t page_bytes() const noexcept { return static_cast<size_t>(kKvPageTokens) * kv_dim * (is_fp8 ? 1u : 2u); }
|
||||
size_t scale_page_bytes() const noexcept { return static_cast<size_t>(kKvPageTokens) * sizeof(float); }
|
||||
|
||||
void drop_pool_buffers() {
|
||||
if (vmm) {
|
||||
k_pool = GpuBuffer{}; v_pool = GpuBuffer{}; k_scales = GpuBuffer{}; v_scales = GpuBuffer{};
|
||||
r_k.release(); r_v.release(); r_ks.release(); r_vs.release();
|
||||
vmm = false;
|
||||
return;
|
||||
}
|
||||
free_gpu_buffer(k_pool);
|
||||
free_gpu_buffer(v_pool);
|
||||
free_gpu_buffer(k_scales);
|
||||
free_gpu_buffer(v_scales);
|
||||
}
|
||||
|
||||
void release() {
|
||||
free_gpu_buffer(d_pt);
|
||||
drop_pool_buffers();
|
||||
free_pages.clear();
|
||||
h_pt.clear();
|
||||
cap_pages = used_pages = 0;
|
||||
host_offload = false;
|
||||
src = nullptr;
|
||||
vmm_max_pages = 0;
|
||||
}
|
||||
|
||||
bool init(bool swa, bool fp8, bool uma, int n_slots, int max_pages, int kvd, std::string& err) {
|
||||
bool init(bool swa, bool fp8, bool uma, int n_slots, int max_pages, int kvd, std::string& err, KvChunkSource* chunk_src = nullptr) {
|
||||
release();
|
||||
is_swa = swa;
|
||||
is_fp8 = fp8;
|
||||
@@ -273,9 +314,118 @@ struct VisitKvPool {
|
||||
kv_dim = kvd;
|
||||
h_pt.assign(static_cast<size_t>(max_slots) * max_pages_per_slot, -1);
|
||||
pt_dirty = true;
|
||||
if (chunk_src != nullptr && !swa && !uma && strata::core::vmm_available()) {
|
||||
const uint64_t tot_pages = static_cast<uint64_t>(max_slots) * static_cast<uint64_t>(max_pages_per_slot);
|
||||
if (r_k.reserve(tot_pages * page_bytes()) && r_v.reserve(tot_pages * page_bytes()) &&
|
||||
(!fp8 || (r_ks.reserve(tot_pages * scale_page_bytes()) && r_vs.reserve(tot_pages * scale_page_bytes())))) {
|
||||
vmm = true;
|
||||
vmm_max_pages = static_cast<int>(std::min<uint64_t>(tot_pages, 0x7fffffffu));
|
||||
src = chunk_src;
|
||||
k_pool.dev_ptr = r_k.base();
|
||||
v_pool.dev_ptr = r_v.base();
|
||||
if (fp8) { k_scales.dev_ptr = r_ks.base(); v_scales.dev_ptr = r_vs.base(); }
|
||||
} else {
|
||||
r_k.release(); r_v.release(); r_ks.release(); r_vs.release();
|
||||
}
|
||||
}
|
||||
return hip_ok(alloc_gpu_buffer(d_pt, h_pt.size() * sizeof(int32_t), is_uma), "kv d_pt alloc", err);
|
||||
}
|
||||
|
||||
// Maps chunks so that `pages` pages fit in every range; false when the chunks are not there (what was mapped stays mapped).
|
||||
bool map_pages_vmm(int pages, hipStream_t st, size_t headroom) {
|
||||
const uint64_t gran = strata::core::vmm_granularity();
|
||||
const int64_t n_k = static_cast<int64_t>((static_cast<uint64_t>(pages) * page_bytes() + gran - 1) / gran);
|
||||
const int64_t n_s = is_fp8 ? static_cast<int64_t>((static_cast<uint64_t>(pages) * scale_page_bytes() + gran - 1) / gran) : 0;
|
||||
const int64_t add = 2 * std::max<int64_t>(0, n_k - r_k.mapped_count()) + 2 * std::max<int64_t>(0, n_s - r_ks.mapped_count());
|
||||
if (add > 0) {
|
||||
if (!src->reserve_chunks(add, st, headroom)) return false;
|
||||
auto take = [this] { return src->take_chunk(); };
|
||||
if (!r_k.map_range(0, n_k, take) || !r_v.map_range(0, n_k, take)) return false;
|
||||
if (is_fp8 && (!r_ks.map_range(0, n_s, take) || !r_vs.map_range(0, n_s, take))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void refresh_vmm_view() {
|
||||
const uint64_t gran = strata::core::vmm_granularity();
|
||||
// pages that fit in every range, counted from the start (chunks are mapped front to back)
|
||||
auto front = [&](const strata::core::VmmRange& r) { int64_t n = 0; while (r.mapped(n)) ++n; return static_cast<uint64_t>(n) * gran; };
|
||||
const uint64_t kb = std::min(front(r_k), front(r_v));
|
||||
uint64_t cap = kb / page_bytes();
|
||||
k_pool.bytes = v_pool.bytes = static_cast<size_t>(kb);
|
||||
if (is_fp8) {
|
||||
const uint64_t sb = std::min(front(r_ks), front(r_vs));
|
||||
cap = std::min<uint64_t>(cap, sb / scale_page_bytes());
|
||||
k_scales.bytes = v_scales.bytes = static_cast<size_t>(sb);
|
||||
}
|
||||
cap_pages = static_cast<int>(std::min<uint64_t>(cap, static_cast<uint64_t>(vmm_max_pages)));
|
||||
}
|
||||
|
||||
// Unmaps the chunks behind the first `keep_pages` pages and hands them to `give` (nothing is copied; the caller knows no slot holds a page above that).
|
||||
template <class Give>
|
||||
int64_t trim_vmm(int keep_pages, Give give) {
|
||||
if (!vmm) return 0;
|
||||
const uint64_t gran = strata::core::vmm_granularity();
|
||||
auto keep = [&](uint64_t per_page) { return static_cast<int64_t>((static_cast<uint64_t>(keep_pages) * per_page + gran - 1) / gran); };
|
||||
int64_t freed = 0;
|
||||
auto cut = [&](strata::core::VmmRange& r, int64_t from) {
|
||||
for (int64_t c = r.chunks() - 1; c >= from; --c) {
|
||||
const strata::core::VmmChunk h = r.unmap(c);
|
||||
if (h != 0) { give(h); ++freed; }
|
||||
}
|
||||
};
|
||||
cut(r_k, keep(page_bytes())); cut(r_v, keep(page_bytes()));
|
||||
if (is_fp8) { cut(r_ks, keep(scale_page_bytes())); cut(r_vs, keep(scale_page_bytes())); }
|
||||
refresh_vmm_view();
|
||||
return freed;
|
||||
}
|
||||
|
||||
bool grow_vmm(int min_pages, hipStream_t st, size_t headroom) {
|
||||
const int step = std::max(128, min_pages / 8);
|
||||
const int want = std::min(vmm_max_pages, std::max(min_pages, cap_pages + step));
|
||||
bool ok = map_pages_vmm(want, st, headroom);
|
||||
if (!ok && want > min_pages) ok = map_pages_vmm(min_pages, st, headroom);
|
||||
refresh_vmm_view();
|
||||
return cap_pages >= min_pages;
|
||||
}
|
||||
|
||||
// The chunks are not there: the same last resort as before (this pool moves to host-mapped pinned memory), keeping what it holds.
|
||||
bool spill_vmm(int min_pages, hipStream_t st, std::string& err) {
|
||||
const int new_cap = std::min(std::max(min_pages, cap_pages + 32), std::max(min_pages, vmm_max_pages));
|
||||
GpuBuffer nk, nv, nks, nvs;
|
||||
int cap = new_cap;
|
||||
if (!try_alloc_pool_buffers(cap, true, nk, nv, nks, nvs)) {
|
||||
(void)hipGetLastError();
|
||||
cap = min_pages;
|
||||
if (!try_alloc_pool_buffers(cap, true, nk, nv, nks, nvs)) {
|
||||
err = "[ink-hip] kv grow failed in both VRAM and host-mapped pinned memory";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (cap_pages > 0) {
|
||||
const size_t old_b = static_cast<size_t>(cap_pages) * page_bytes();
|
||||
bool ok = hipMemcpyAsync(nk.dev_ptr, k_pool.dev_ptr, old_b, hipMemcpyDefault, st) == hipSuccess &&
|
||||
hipMemcpyAsync(nv.dev_ptr, v_pool.dev_ptr, old_b, hipMemcpyDefault, st) == hipSuccess;
|
||||
if (ok && is_fp8) {
|
||||
const size_t old_sc = static_cast<size_t>(cap_pages) * scale_page_bytes();
|
||||
ok = hipMemcpyAsync(nks.dev_ptr, k_scales.dev_ptr, old_sc, hipMemcpyDefault, st) == hipSuccess &&
|
||||
hipMemcpyAsync(nvs.dev_ptr, v_scales.dev_ptr, old_sc, hipMemcpyDefault, st) == hipSuccess;
|
||||
}
|
||||
if (!ok || hipStreamSynchronize(st) != hipSuccess) {
|
||||
free_gpu_buffer(nk); free_gpu_buffer(nv); free_gpu_buffer(nks); free_gpu_buffer(nvs);
|
||||
err = "[ink-hip] kv spill copy failed";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
drop_pool_buffers();
|
||||
k_pool = nk; v_pool = nv; k_scales = nks; v_scales = nvs;
|
||||
cap_pages = cap;
|
||||
host_offload = true;
|
||||
++pool_gen;
|
||||
std::fprintf(stderr, "[ink-hip] Global KV pool: the card has no chunks left for it (experts at their floor) -> spilled to host-mapped pinned KV (cap=%d pages)\n", cap);
|
||||
return true;
|
||||
}
|
||||
|
||||
void free_slot_pages(int slot) {
|
||||
if (slot < 0 || slot >= max_slots) return;
|
||||
int32_t* row = h_pt.data() + static_cast<size_t>(slot) * max_pages_per_slot;
|
||||
@@ -311,6 +461,10 @@ struct VisitKvPool {
|
||||
}
|
||||
|
||||
bool grow_pool(int min_pages, hipStream_t st, std::string& err, size_t min_vram_headroom = 0) {
|
||||
if (vmm) {
|
||||
if (grow_vmm(min_pages, st, min_vram_headroom)) return true;
|
||||
return spill_vmm(min_pages, st, err);
|
||||
}
|
||||
const int max_total_pages = std::max(min_pages, max_slots * max_pages_per_slot);
|
||||
const size_t elem_b = is_fp8 ? 1u : 2u;
|
||||
const size_t page_b = static_cast<size_t>(kKvPageTokens) * kv_dim * elem_b;
|
||||
@@ -526,6 +680,51 @@ struct GpuVisionState {
|
||||
}
|
||||
};
|
||||
|
||||
// ---- elastic experts: the exact lane of a decode visit (B == 1) ----
|
||||
// An expert that left the card lives in a pinned host arena the card can read. A layer that lost experts keeps its table (body == nullptr for them);
|
||||
// before the MoE kernels of a visit the router's picks are looked up: every pick that is not on the card is copied into one of a few staging slots and a copy
|
||||
// of the layer's table (the step table) points at the slot. The MoE kernels then run exactly as for a resident expert (same kernels, same bytes, same bits),
|
||||
// graph capture included (no host decision is made, the picks are read on the card).
|
||||
struct ElasticColdEnt {
|
||||
const uint8_t* src; // device-visible address of the host copy, nullptr = the expert is on the card
|
||||
uint32_t bytes;
|
||||
uint32_t pad;
|
||||
};
|
||||
|
||||
__global__ void __launch_bounds__(128) k_elastic_stage_plan(const GpuExpertDesc* tbl, const ElasticColdEnt* cold, const int32_t* tk_i, int n_pick,
|
||||
GpuExpertDesc* step, int32_t* plan, uint8_t* stage, size_t slot_bytes, int n_slots, int n_experts) {
|
||||
const int t = threadIdx.x;
|
||||
if (t < n_experts) step[t] = tbl[t];
|
||||
if (t < n_slots) plan[t] = -1;
|
||||
__syncthreads();
|
||||
if (t == 0) {
|
||||
int cnt = 0;
|
||||
for (int k = 0; k < n_pick; ++k) {
|
||||
const int e = tk_i[k];
|
||||
if (e < 0 || e >= n_experts) continue;
|
||||
if (step[e].body != nullptr || cold[e].src == nullptr) continue; // on the card, or already given a slot by an earlier pick
|
||||
if (cnt < n_slots) {
|
||||
plan[cnt] = e;
|
||||
step[e].body = stage + static_cast<size_t>(cnt) * slot_bytes;
|
||||
++cnt;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void __launch_bounds__(256) k_elastic_stage_copy(const ElasticColdEnt* cold, const int32_t* plan, uint8_t* stage, size_t slot_bytes) {
|
||||
const int e = plan[blockIdx.y];
|
||||
if (e < 0) return;
|
||||
const uint8_t* src = cold[e].src;
|
||||
const uint32_t n = cold[e].bytes;
|
||||
uint8_t* dst = stage + static_cast<size_t>(blockIdx.y) * slot_bytes;
|
||||
const uint32_t n16 = n >> 4;
|
||||
const uint4* s4 = reinterpret_cast<const uint4*>(src);
|
||||
uint4* d4 = reinterpret_cast<uint4*>(dst);
|
||||
for (uint32_t i = blockIdx.x * blockDim.x + threadIdx.x; i < n16; i += gridDim.x * blockDim.x) d4[i] = s4[i];
|
||||
if (blockIdx.x == 0 && threadIdx.x < (n & 15u)) dst[(n16 << 4) + threadIdx.x] = src[(n16 << 4) + threadIdx.x];
|
||||
}
|
||||
|
||||
class HipBackend final : public InkBackend {
|
||||
public:
|
||||
~HipBackend() override { cleanup(); }
|
||||
@@ -1989,8 +2188,41 @@ public:
|
||||
} else if (arena_bytes > 0) {
|
||||
// #6711: one contiguous arena can still fail on a discrete card whose free VRAM is fragmented or capped by the driver (Windows WDDM). Give up the
|
||||
// coldest GPU-planned experts in 5% steps (they go to the RAM tier, or the SSD tier when RAM is short) and try again, instead of failing the start.
|
||||
hipError_t arena_err = alloc_gpu_buffer(expert_gpu_arena_, arena_bytes, mem_info_.is_uma);
|
||||
while (arena_err == hipErrorOutOfMemory && !mem_info_.is_uma && !gpu_plan.empty() && arena_bytes > (1ULL << 30)) {
|
||||
// Elastic expert pool (STRATA_INK_ELASTIC_EXPERTS, ink_elastic_sec4.hpp): when every expert is in the card the arena is one virtual-memory range
|
||||
// (same bytes, same offsets, packed in load order), so its tail can be given to the K/V chunk by chunk when the K/V needs the room. Anything else
|
||||
// (hybrid, dual GPU, UMA, the in-place coda transcode) keeps the plain allocation below.
|
||||
bool arena_in_pool = false;
|
||||
if (gpu_plan.size() == n_dir && ram_plan.empty() && !ep2_active_ && !mem_info_.is_uma && !(r9700_ && r9700_->cfg.coda_sf4) &&
|
||||
strata::ink::InkElasticSec4Pool::env_enabled() && strata::core::vmm_available()) {
|
||||
std::vector<strata::ink::InkElasticSlot> slots;
|
||||
slots.reserve(gpu_plan.size());
|
||||
for (uint16_t idx : gpu_plan) {
|
||||
strata::ink::InkElasticSlot s;
|
||||
s.key = static_cast<int>(idx);
|
||||
s.body_off = expert_gpu_offset_[idx];
|
||||
s.body_bytes = static_cast<uint32_t>(dir[idx].body_bytes);
|
||||
s.gu_code = dir[idx].gu_code_id;
|
||||
s.dn_code = dir[idx].dn_code_id;
|
||||
slots.push_back(s);
|
||||
}
|
||||
if (elastic_.init_vmm(arena_bytes, arena_bytes, slots)) {
|
||||
elastic_.heat().init(c_.n_phys, c_.n_experts, c_.core_start, c_.core_end, model.vram_load_order);
|
||||
expert_gpu_arena_ = GpuBuffer{};
|
||||
expert_gpu_arena_.dev_ptr = elastic_.base();
|
||||
expert_gpu_arena_.bytes = arena_bytes;
|
||||
arena_in_pool = true;
|
||||
elastic_max_body_ = max_exp_bytes;
|
||||
std::fprintf(stderr, "[ink-hip] elastic expert pool: %zu experts, %.2f GiB in %lld chunks of %.0f MiB (virtual memory; the K/V may take chunks from the coldest experts)\n",
|
||||
gpu_plan.size(), static_cast<double>(arena_bytes) / 1073741824.0, static_cast<long long>(elastic_.mapped_chunks()),
|
||||
static_cast<double>(elastic_.granularity()) / 1048576.0);
|
||||
} else {
|
||||
elastic_.release();
|
||||
(void)hipGetLastError();
|
||||
}
|
||||
}
|
||||
hipError_t arena_err = hipSuccess;
|
||||
if (!arena_in_pool) arena_err = alloc_gpu_buffer(expert_gpu_arena_, arena_bytes, mem_info_.is_uma);
|
||||
while (!arena_in_pool && arena_err == hipErrorOutOfMemory && !mem_info_.is_uma && !gpu_plan.empty() && arena_bytes > (1ULL << 30)) {
|
||||
(void)hipGetLastError();
|
||||
const size_t target = arena_bytes - std::max<size_t>(arena_bytes / 20, 256ULL << 20);
|
||||
size_t dropped = 0;
|
||||
@@ -2381,8 +2613,28 @@ public:
|
||||
if (!swa_pools_[i].init(true, is_fp8, mem_info_.is_uma, max_slots_, max_swa_pages, kv_dim, err)) return false;
|
||||
}
|
||||
glob_pools_.resize(c_.n_global_visits);
|
||||
{
|
||||
const char* kv_vmm_env = std::getenv("STRATA_INK_KV_VMM");
|
||||
kv_vmm_on_ = !(kv_vmm_env && kv_vmm_env[0] == '0') && !mem_info_.is_uma && !ep2_active_ && strata::core::vmm_available();
|
||||
}
|
||||
for (int i = 0; i < c_.n_global_visits; ++i) {
|
||||
if (!glob_pools_[i].init(false, is_fp8, mem_info_.is_uma, max_slots_, max_glob_pages, kv_dim, err)) return false;
|
||||
if (!glob_pools_[i].init(false, is_fp8, mem_info_.is_uma, max_slots_, max_glob_pages, kv_dim, err, kv_vmm_on_ ? &kv_src_ : nullptr)) return false;
|
||||
}
|
||||
if (kv_vmm_on_ && !glob_pools_.empty() && glob_pools_[0].vmm) {
|
||||
std::fprintf(stderr, "[ink-hip] elastic K/V: the %d global pools reserve %.2f GiB of address space and map %.0f MiB chunks as the context grows (free floor %.0f MiB%s)\n",
|
||||
c_.n_global_visits,
|
||||
static_cast<double>(c_.n_global_visits) * 2.0 * static_cast<double>(glob_pools_[0].vmm_max_pages) * static_cast<double>(glob_pools_[0].page_bytes()) / 1073741824.0,
|
||||
static_cast<double>(strata::core::vmm_granularity()) / 1048576.0, static_cast<double>(kv_free_floor_bytes()) / 1048576.0,
|
||||
elastic_.active() ? ", the coldest experts give chunks when the card is full" : "");
|
||||
} else {
|
||||
kv_vmm_on_ = false;
|
||||
const char* off_env = std::getenv("STRATA_INK_KV_VMM");
|
||||
const char* off_env2 = std::getenv("STRATA_INK_ELASTIC_EXPERTS");
|
||||
if (!(off_env && off_env[0] == '0') && !(off_env2 && off_env2[0] == '0')) {
|
||||
std::fprintf(stderr, "[ink-hip] elastic K/V and expert pool: off (%s); the K/V and the experts are allocated as before\n",
|
||||
mem_info_.is_uma ? "this GPU shares system memory with the CPU: there is no card memory to give back"
|
||||
: (ep2_active_ ? "two GPUs (EP2)" : "virtual memory is not available here (ROCm older than 6, gfx906, or STRATA_HIP_VMM=0)"));
|
||||
}
|
||||
}
|
||||
|
||||
const size_t kv_all_b = static_cast<size_t>(c_.n_visits) * max_slots_ * 3 * kv_dim * sizeof(uint16_t);
|
||||
@@ -2921,6 +3173,7 @@ public:
|
||||
}
|
||||
if (halo_ && halo_->cfg.pld && slot < static_cast<int>(halo_->pld.size())) halo_->pld[slot].clear();
|
||||
if (halo_ && slot < static_cast<int>(halo_->slot_ewma_acc.size())) halo_->slot_ewma_acc[slot] = 2.0f;
|
||||
elastic_trim_kv_and_regrow();
|
||||
}
|
||||
|
||||
void reset_slot(int slot) override {
|
||||
@@ -2945,6 +3198,11 @@ public:
|
||||
}
|
||||
if (halo_ && halo_->cfg.pld && slot < static_cast<int>(halo_->pld.size())) halo_->pld[slot].clear();
|
||||
if (halo_ && slot < static_cast<int>(halo_->slot_ewma_acc.size())) halo_->slot_ewma_acc[slot] = 2.0f;
|
||||
if (elastic_have_evicted()) {
|
||||
// experts are off the card for this conversation's K/V: it starts again, so the K/V goes back to its start size and the experts come back
|
||||
for (auto& p : glob_pools_) if (p.vmm) p.free_slot_pages(slot);
|
||||
elastic_trim_kv_and_regrow(slot);
|
||||
}
|
||||
}
|
||||
|
||||
void snapshot_slot(int slot) override {
|
||||
@@ -7654,6 +7912,16 @@ private:
|
||||
// Pre-ensure KV pages exist for all tokens in batch across all 40 SWA & 8 Global pools
|
||||
// Keep >= 768 MiB free headroom on R9700 so amdgpu TTM never crosses the 31.8 GiB eviction cliff!
|
||||
const size_t kv_headroom = r9700_ ? (768ULL << 20) : 0u;
|
||||
if (elastic_.active() && max_slots_ == 1) elastic_guard_poll(); // other programs' memory: shed or take back experts (one clock read between samples)
|
||||
if (elastic_test_evict_mib_ > 0 && B == 1 && elastic_.active()) {
|
||||
// test hook (STRATA_INK_ELASTIC_TEST_EVICT_MIB=N): the first decode step gives N MiB of the coldest experts away, so decode runs on a layer table with cold experts
|
||||
// while the prompt was read with every expert on the card (isolates the exact lane of decode from the prompt's path)
|
||||
const int64_t n = static_cast<int64_t>((static_cast<uint64_t>(elastic_test_evict_mib_) << 20) / strata::core::vmm_granularity());
|
||||
elastic_test_evict_mib_ = 0;
|
||||
const int64_t got = shed_experts_for_chunks(n, stream_);
|
||||
kv_collect_donated();
|
||||
std::fprintf(stderr, "[ink-hip] test hook: %lld chunks of experts given away at the first decode step\n", static_cast<long long>(got));
|
||||
}
|
||||
for (int b = 0; b < B; ++b) {
|
||||
const int s = batch.slot_ids[b];
|
||||
const int p = batch.pos[b];
|
||||
@@ -7914,7 +8182,9 @@ private:
|
||||
|
||||
// Check eligibility for HIP Graph Capture (all distinct slots, all GPU-resident layers, no images/host-taps, want all logits)
|
||||
bool all_gpu_layers = true;
|
||||
for (bool ok_l : layer_all_gpu_) if (!ok_l) { all_gpu_layers = false; break; }
|
||||
for (int il_c = 0; il_c < static_cast<int>(layer_all_gpu_.size()); ++il_c) {
|
||||
if (!layer_all_gpu_[il_c] && !elastic_stageable(il_c, B)) { all_gpu_layers = false; break; }
|
||||
}
|
||||
bool all_want_logits = (logits_out != nullptr || cand_out != nullptr);
|
||||
for (int b = 0; b < B && all_want_logits; ++b) if (!batch.want_logits[b]) all_want_logits = false;
|
||||
const bool need_taps = (taps_out != nullptr) || ((has_dspark_ || has_df2_) && batch.capture_taps);
|
||||
@@ -8130,6 +8400,7 @@ private:
|
||||
|
||||
int visit = 0;
|
||||
auto run_visit = [&](int ip, bool has_msgs) -> bool {
|
||||
const bool lgpu = layer_all_gpu_[ip] || elastic_stageable(ip, B) || (!exact_rows_ && elastic_multipass_ok(ip, B)); // "all experts readable by the fast path in this visit" (cold ones staged)
|
||||
pmark(0);
|
||||
maybe_tap(visit, cur);
|
||||
const std::string p = "model.llm.layers." + std::to_string(ip);
|
||||
@@ -9573,7 +9844,7 @@ private:
|
||||
// MoE sublayer: fused single-read 576-thread AttnRes+mlp_norm + Q8 LoopCtrl + Q8 Router (0 ACQ_REL flushes!)
|
||||
const bool use_r9700_fast_rq =
|
||||
(r9700_v2() && r9700_->cfg.kcoal_moe && !exact_rows_ && !ep2_active_ &&
|
||||
layer_all_gpu_[ip] && B <= 256 && D == 2304 && c_.n_experts == 128 && c_.top_k == 8 &&
|
||||
lgpu && B <= 256 && D == 2304 && c_.n_experts == 128 && c_.top_k == 8 &&
|
||||
c_.inter <= 1536 && (c_.inter & 31) == 0 &&
|
||||
(r9700_->q8_router_ready || trunk_bf16_.count(p + ".mlp.gate.weight") > 0) &&
|
||||
(layer_gu_class_[ip] == 1 || layer_gu_class_[ip] == 2) &&
|
||||
@@ -9699,7 +9970,7 @@ private:
|
||||
dbg_hash(visit * 4 + 0, cur, B, D);
|
||||
dbg_hash(visit * 4 + 1, mlpin, B, D);
|
||||
pmark(5);
|
||||
const HipTailArgs tail_a = hip_tail_args(visit, layer_all_gpu_[ip] && (r9700_direct_b || exact_rows_) && !ep2_active_);
|
||||
const HipTailArgs tail_a = hip_tail_args(visit, lgpu && (r9700_direct_b || exact_rows_) && !ep2_active_);
|
||||
bool r9700_defer_topk_dir = false;
|
||||
bool r9700_defer_topk_hyb = false;
|
||||
if (use_r9700_fast_rq) {
|
||||
@@ -9733,7 +10004,7 @@ private:
|
||||
}
|
||||
dbg_hash(visit * 4 + 3, rlog, B, c_.n_experts);
|
||||
r9700_defer_topk_dir = false;
|
||||
r9700_defer_topk_hyb = (!tail_a.on && B >= 2 && B <= 15 && !ep2_active_ && layer_all_gpu_[ip] &&
|
||||
r9700_defer_topk_hyb = (!tail_a.on && B >= 2 && B <= 15 && !ep2_active_ && lgpu &&
|
||||
c_.top_k == 8 && c_.n_experts == 128 && r9700_->d_moe_small_eids.dev_ptr != nullptr);
|
||||
if (!r9700_defer_topk_dir && !r9700_defer_topk_hyb) {
|
||||
r9700::k_r9700_router_topk8_w32<<<B, 32, 0, stream_>>>(rlog, gb, tk_i, tk_w, B, c_.top_k, c_.route_scale, tail_a);
|
||||
@@ -9746,7 +10017,7 @@ private:
|
||||
launch_f32_linear(f32_ptr(p + ".mlp.gate.weight"), mlpin, nullptr, rlog, B, c_.n_experts, D, stream_, mem_info_.gen);
|
||||
}
|
||||
dbg_hash(visit * 4 + 3, rlog, B, c_.n_experts);
|
||||
fused_router_f16 = (layer_all_gpu_[ip] && (r9700_direct_b || exact_rows_) && (D & 3) == 0);
|
||||
fused_router_f16 = (lgpu && (r9700_direct_b || exact_rows_) && (D & 3) == 0);
|
||||
if (fused_router_f16) {
|
||||
k4_moe_router_topk_f16<<<B, 128, 0, stream_>>>(
|
||||
rlog, f32_ptr(p + ".mlp.gate.bias"), mlpin, mlpf16, tk_i, tk_w, B, D, c_.top_k, c_.route_scale, tail_a);
|
||||
@@ -9825,8 +10096,9 @@ private:
|
||||
}
|
||||
if (ep2_active_ && layer_all_ep2_[ip]) {
|
||||
// Already completed on GPU 0 || GPU 1 above!
|
||||
} else if (layer_all_gpu_[ip] && (r9700_direct_b || exact_rows_)) {
|
||||
const GpuExpertDesc* d_exps = reinterpret_cast<const GpuExpertDesc*>(d_layer_exps_[ip].dev_ptr);
|
||||
} else if (lgpu && (r9700_direct_b || exact_rows_)) {
|
||||
// (a layer that lost experts, B == 1: the router's cold picks are staged into the step table first, see moe_exps_table)
|
||||
const GpuExpertDesc* d_exps = moe_exps_table(ip, tk_i, B, stream_);
|
||||
const bool use_r9700_q8_dir = (r9700_v2() && r9700_->cfg.kcoal_moe && !exact_rows_ &&
|
||||
D == 2304 && c_.inter <= 1536 && (c_.inter & 31) == 0 &&
|
||||
(layer_gu_class_[ip] == 1 || layer_gu_class_[ip] == 2) &&
|
||||
@@ -10091,8 +10363,8 @@ private:
|
||||
|
||||
k_moe_reduce_buckets<<<dim3((D + 255) / 256, B), 256, 0, stream_>>>(
|
||||
d_by, d_s2b, tk_w, moeout, B, c_.top_k, D);
|
||||
} else if (layer_all_gpu_[ip]) {
|
||||
const GpuExpertDesc* d_exps = reinterpret_cast<const GpuExpertDesc*>(d_layer_exps_[ip].dev_ptr);
|
||||
} else if (lgpu) {
|
||||
const GpuExpertDesc* d_exps0 = reinterpret_cast<const GpuExpertDesc*>(d_layer_exps_[ip].dev_ptr);
|
||||
int32_t* d_off = reinterpret_cast<int32_t*>(sc_exp_off_.dev_ptr);
|
||||
int32_t* d_cur = reinterpret_cast<int32_t*>(sc_exp_cur_.dev_ptr);
|
||||
int32_t* d_btk = reinterpret_cast<int32_t*>(sc_bucket_tok_.dev_ptr);
|
||||
@@ -10109,6 +10381,38 @@ private:
|
||||
} else if (!r9700_defer_topk_hyb) {
|
||||
k_moe_build_buckets<<<1, 128, 0, stream_>>>(tk_i, d_off, d_btk, d_s2b, B, c_.top_k);
|
||||
}
|
||||
// A layer that lost experts (elastic pool), prompt-sized batch: the kernels below run once over the experts on the card (the table has body == nullptr for the others, which
|
||||
// every MoE kernel skips) and then once more per group of <= elastic_slots_ cold experts the batch routes to, each group copied into the staging slots first. Every expert is
|
||||
// computed by the same kernel from the same bytes as on the card, so the rows are the same bits; the reduce below runs once over all rows.
|
||||
std::vector<int> ecold_used;
|
||||
if (!layer_all_gpu_[ip] && elastic_cold_layer_[ip] && elastic_multipass_ok(ip, B)) {
|
||||
int32_t h_off_c[129];
|
||||
if (!hip_ok(hipMemcpyAsync(h_off_c, d_off, 129 * sizeof(int32_t), hipMemcpyDeviceToHost, stream_), "elastic moe off D2H", err) ||
|
||||
!hip_ok(hipStreamSynchronize(stream_), "elastic moe off sync", err)) {
|
||||
return false;
|
||||
}
|
||||
for (int e = 0; e < c_.n_experts; ++e) {
|
||||
if (h_off_c[e + 1] - h_off_c[e] > 0 && elastic_cold_ent_h_[ip][e].src != nullptr) ecold_used.push_back(e);
|
||||
}
|
||||
}
|
||||
const int ecold_passes = static_cast<int>((ecold_used.size() + elastic_slots_ - 1) / elastic_slots_);
|
||||
for (int epass = 0; epass <= ecold_passes; ++epass) {
|
||||
const GpuExpertDesc* d_exps = d_exps0;
|
||||
if (epass > 0) {
|
||||
std::vector<GpuExpertDesc> step(c_.n_experts);
|
||||
for (auto& s_e : step) s_e = GpuExpertDesc{nullptr, 0u, 0, 0, 0};
|
||||
const size_t g0 = static_cast<size_t>(epass - 1) * elastic_slots_;
|
||||
for (int s = 0; s < elastic_slots_ && g0 + s < ecold_used.size(); ++s) {
|
||||
const int e = ecold_used[g0 + s];
|
||||
const ElasticColdEnt& ce = elastic_cold_ent_h_[ip][e];
|
||||
uint8_t* slot_p = d_elastic_stage_.dev_ptr + static_cast<size_t>(s) * elastic_slot_bytes_;
|
||||
if (!hip_ok(hipMemcpyAsync(slot_p, ce.src, ce.bytes, hipMemcpyHostToDevice, stream_), "elastic expert H2D", err)) return false;
|
||||
step[e] = h_layer_exps_[ip][e];
|
||||
step[e].body = slot_p;
|
||||
}
|
||||
if (!hip_ok(hipMemcpyAsync(d_elastic_step_.dev_ptr, step.data(), step.size() * sizeof(GpuExpertDesc), hipMemcpyHostToDevice, stream_), "elastic step table H2D", err)) return false;
|
||||
d_exps = reinterpret_cast<const GpuExpertDesc*>(d_elastic_step_.dev_ptr);
|
||||
}
|
||||
const bool use_r9700_kcoal_moe = (r9700_v2() && r9700_->cfg.kcoal_moe && !exact_rows_ &&
|
||||
B <= 256 && D == 2304 && c_.inter <= 1536 && (c_.inter & 31) == 0 &&
|
||||
r9700_->d_moe_small_eids.dev_ptr != nullptr &&
|
||||
@@ -10529,6 +10833,7 @@ private:
|
||||
launch_moe_w13_rdna2(d_exps, d_off, d_btk, mlpf16, d_act, B, D, c_.inter, c_.n_experts, c_.situ_beta, c_.situ_lb, stream_);
|
||||
launch_moe_w2_rdna2(d_exps, d_off, d_act, d_by, B, D, c_.inter, c_.n_experts, stream_);
|
||||
}
|
||||
} // for (epass)
|
||||
|
||||
k_moe_reduce_buckets<<<dim3((D + 255) / 256, B), 256, 0, stream_>>>(
|
||||
d_by, d_s2b, tk_w, moeout, B, c_.top_k, D);
|
||||
@@ -10775,8 +11080,8 @@ private:
|
||||
gpu_exps.push_back({eid, dir_idx, beg, m_e, dev_p, nullptr});
|
||||
} else {
|
||||
const uint8_t* hp = nullptr;
|
||||
if (!expert_ram_bodies_[dir_idx].empty()) {
|
||||
hp = expert_ram_bodies_[dir_idx].data();
|
||||
if (const uint8_t* hb = host_body_of(dir_idx)) {
|
||||
hp = hb; // RAM tier, or the pinned copy of an expert that left the card
|
||||
} else if (cold_store_.is_open()) {
|
||||
int cslot = -1;
|
||||
const uint8_t* cp = cold_store_.demand_wait(dir_idx, ip, cold_gen_, cslot);
|
||||
@@ -10803,7 +11108,7 @@ private:
|
||||
const auto& ent = dir[ae.dir_idx];
|
||||
float sf4_w13 = expert_sf4_outer_[ae.dir_idx].first;
|
||||
float sf4_w2 = expert_sf4_outer_[ae.dir_idx].second;
|
||||
if (ae.host_ptr && expert_ram_bodies_[ae.dir_idx].empty() &&
|
||||
if (ae.host_ptr && host_body_of(ae.dir_idx) == nullptr &&
|
||||
(ent.gu_code_id == CODE_SF4 || ent.dn_code_id == CODE_SF4)) {
|
||||
float hdr[4];
|
||||
std::memcpy(hdr, ae.host_ptr, 16);
|
||||
@@ -14420,6 +14725,374 @@ private:
|
||||
std::unordered_set<const void*> r9700_tap_ws_; // bf16 weight pointers of the tapped layers that were also converted to FP8 (only with more than 16 slots)
|
||||
bool r9700_taps_fp8_now_ = false;
|
||||
|
||||
// ---- elastic K/V: where the chunks come from ----
|
||||
static size_t kv_free_floor_bytes() {
|
||||
size_t floor_b = 256ULL << 20; // the card keeps this much free for the driver, the desktop and the next allocations
|
||||
if (const char* e = std::getenv("STRATA_INK_KV_FLOOR_MIB")) {
|
||||
const long v = std::strtol(e, nullptr, 10);
|
||||
if (v >= 0 && v <= 8192) floor_b = static_cast<size_t>(v) << 20;
|
||||
}
|
||||
return floor_b;
|
||||
}
|
||||
|
||||
strata::core::VmmChunk kv_take_chunk() {
|
||||
if (kv_spare_.empty()) return 0;
|
||||
const strata::core::VmmChunk h = kv_spare_.back();
|
||||
kv_spare_.pop_back();
|
||||
return h;
|
||||
}
|
||||
|
||||
// Moves the chunks the pool gave up (donated by reclaim_chunks) to the K/V's list.
|
||||
void kv_collect_donated() {
|
||||
for (;;) {
|
||||
const strata::core::VmmChunk h = elastic_.take_donated_chunk();
|
||||
if (h == 0) break;
|
||||
kv_spare_.push_back(h);
|
||||
}
|
||||
}
|
||||
|
||||
// `n` chunks ready for the K/V: those already ready, then chunks of free memory above the floor, then the coldest experts. All or nothing is up to the
|
||||
// caller (a short count is left ready for the next try).
|
||||
bool kv_reserve_chunks(int64_t n, hipStream_t st, size_t headroom) {
|
||||
if (static_cast<int64_t>(kv_spare_.size()) >= n) return true;
|
||||
const uint64_t gran = strata::core::vmm_granularity();
|
||||
if (gran == 0) return false;
|
||||
int64_t need = n - static_cast<int64_t>(kv_spare_.size());
|
||||
const size_t floor_b = std::max(kv_free_floor_bytes(), headroom);
|
||||
size_t fr = 0, tot = 0;
|
||||
if (hipMemGetInfo(&fr, &tot) == hipSuccess && fr > floor_b) {
|
||||
int64_t spare = static_cast<int64_t>((fr - floor_b) / gran);
|
||||
if (elastic_.active()) {
|
||||
// the guard sees what the driver's number does not (other programs' memory on WDDM) and keeps its own low watermark
|
||||
if (!elastic_guard_started_) { elastic_guard_started_ = true; elastic_guard_init(); }
|
||||
if (vram_guard_.enabled()) spare = std::min<int64_t>(spare, static_cast<int64_t>(vram_guard_.spare_for_growth() / gran));
|
||||
}
|
||||
while (need > 0 && spare > 0) {
|
||||
const strata::core::VmmChunk h = strata::core::vmm_chunk_new();
|
||||
if (h == 0) break;
|
||||
kv_spare_.push_back(h);
|
||||
--need; --spare;
|
||||
}
|
||||
}
|
||||
if (need > 0 && elastic_.active()) {
|
||||
const int64_t got = shed_experts_for_chunks(need, st);
|
||||
(void)got;
|
||||
kv_collect_donated();
|
||||
need = n - static_cast<int64_t>(kv_spare_.size());
|
||||
}
|
||||
return need <= 0;
|
||||
}
|
||||
|
||||
// ---- elastic experts: leaving and returning ----
|
||||
static uint64_t host_mem_available_bytes() {
|
||||
uint64_t avail = 0;
|
||||
#ifdef __linux__
|
||||
if (FILE* fp = std::fopen("/proc/meminfo", "r")) {
|
||||
char key[64];
|
||||
unsigned long long kb = 0;
|
||||
char unit[32];
|
||||
while (std::fscanf(fp, "%63[^:]: %llu %31s\n", key, &kb, unit) == 3) {
|
||||
if (std::strcmp(key, "MemAvailable") == 0) { avail = kb * 1024ull; break; }
|
||||
}
|
||||
std::fclose(fp);
|
||||
}
|
||||
#elif defined(_WIN32)
|
||||
MEMORYSTATUSEX ms{};
|
||||
ms.dwLength = sizeof(ms);
|
||||
if (GlobalMemoryStatusEx(&ms)) avail = static_cast<uint64_t>(ms.ullAvailPhys);
|
||||
#endif
|
||||
return avail;
|
||||
}
|
||||
|
||||
bool elastic_have_evicted() const noexcept { return elastic_n_evicted_ > 0; }
|
||||
|
||||
// The host copy of the experts that leave: one pinned arena, sized from what the K/V can still ask for (and what the host can spare). A slot stays with its expert.
|
||||
bool elastic_prepare_arena() {
|
||||
if (h_elastic_arena_ != nullptr) return true;
|
||||
if (elastic_arena_failed_) return false;
|
||||
uint64_t kv_full = 0, kv_have = 0;
|
||||
for (const auto& p : glob_pools_) {
|
||||
if (!p.vmm) continue;
|
||||
const uint64_t per_page = 2ull * p.page_bytes() + (p.is_fp8 ? 2ull * p.scale_page_bytes() : 0ull);
|
||||
kv_full += static_cast<uint64_t>(p.vmm_max_pages) * per_page;
|
||||
kv_have += static_cast<uint64_t>(p.cap_pages) * per_page;
|
||||
}
|
||||
size_t fr = 0, tot = 0;
|
||||
(void)hipMemGetInfo(&fr, &tot);
|
||||
const uint64_t floor_b = kv_free_floor_bytes();
|
||||
const uint64_t free_above = fr > floor_b ? fr - floor_b : 0;
|
||||
const uint64_t deficit = kv_full > kv_have + free_above ? kv_full - kv_have - free_above : 0;
|
||||
uint64_t plan = std::min<uint64_t>(elastic_.reclaimable_bytes(), deficit + (1ull << 30));
|
||||
plan = std::max<uint64_t>(plan, 1ull << 30);
|
||||
if (const char* e = std::getenv("STRATA_INK_ELASTIC_HOST_GIB")) {
|
||||
const long g = std::strtol(e, nullptr, 10);
|
||||
if (g >= 1 && g <= 64) plan = static_cast<uint64_t>(g) << 30;
|
||||
}
|
||||
const uint64_t host_avail = host_mem_available_bytes();
|
||||
if (host_avail > 0) plan = std::min<uint64_t>(plan, host_avail / 3); // never take more than a third of the free RAM
|
||||
plan = std::min<uint64_t>(plan, 24ull << 30);
|
||||
plan = (plan + 255ull) & ~255ull;
|
||||
void* p = nullptr;
|
||||
while (plan >= (512ull << 20)) {
|
||||
if (hipHostMalloc(&p, static_cast<size_t>(plan), hipHostMallocMapped) == hipSuccess && p != nullptr) break;
|
||||
(void)hipGetLastError();
|
||||
p = nullptr;
|
||||
plan = (plan / 2 + 255ull) & ~255ull;
|
||||
}
|
||||
if (p == nullptr) {
|
||||
elastic_arena_failed_ = true;
|
||||
std::fprintf(stderr, "[ink-hip] elastic experts: no pinned host memory for the experts that would leave the card; the K/V spills to host as before\n");
|
||||
return false;
|
||||
}
|
||||
void* dp = nullptr;
|
||||
if (hipHostGetDevicePointer(&dp, p, 0) != hipSuccess || dp == nullptr) dp = p; // unified addressing: the same address
|
||||
h_elastic_arena_ = static_cast<uint8_t*>(p);
|
||||
d_elastic_arena_ = static_cast<const uint8_t*>(dp);
|
||||
elastic_arena_bytes_ = plan;
|
||||
elastic_arena_used_ = 0;
|
||||
elastic_arena_off_.assign(adj_dir_.size(), -1);
|
||||
elastic_evicted_.assign(adj_dir_.size(), 0);
|
||||
std::fprintf(stderr, "[ink-hip] elastic experts: pinned host copy %.2f GiB for the experts that leave the card\n", static_cast<double>(plan) / 1073741824.0);
|
||||
return true;
|
||||
}
|
||||
|
||||
// What leaving needs on the card (the swap buffer, the table of the step, the plan); the staging slots follow after the first chunks are freed.
|
||||
bool elastic_prepare_device_small() {
|
||||
if (elastic_small_ready_) return true;
|
||||
elastic_slot_bytes_ = (elastic_max_body_ + 255ull) & ~255ull;
|
||||
elastic_cold_ent_h_.assign(c_.n_phys, std::vector<ElasticColdEnt>(c_.n_experts, ElasticColdEnt{nullptr, 0u, 0u}));
|
||||
elastic_cold_ent_d_.assign(c_.n_phys, GpuBuffer{});
|
||||
elastic_cold_layer_.assign(c_.n_phys, 0);
|
||||
elastic_layer_cold_n_.assign(c_.n_phys, 0);
|
||||
if (d_exp_stage_.dev_ptr == nullptr && !hip_ok_log(alloc_gpu_buffer(d_exp_stage_, elastic_max_body_, false), "elastic swap buffer")) return false;
|
||||
for (int il = 0; il < c_.n_phys; ++il) {
|
||||
if (!hip_ok_log(alloc_gpu_buffer(elastic_cold_ent_d_[il], c_.n_experts * sizeof(ElasticColdEnt), false), "elastic cold table")) return false;
|
||||
(void)hipMemsetAsync(elastic_cold_ent_d_[il].dev_ptr, 0, elastic_cold_ent_d_[il].bytes, stream_);
|
||||
}
|
||||
if (!hip_ok_log(alloc_gpu_buffer(d_elastic_step_, c_.n_experts * sizeof(GpuExpertDesc), false), "elastic step table") ||
|
||||
!hip_ok_log(alloc_gpu_buffer(d_elastic_plan_, 64u * sizeof(int32_t), false), "elastic plan")) return false;
|
||||
elastic_small_ready_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool elastic_prepare_stage_slots() {
|
||||
if (elastic_stage_ready_) return true;
|
||||
if (!hip_ok_log(alloc_gpu_buffer(d_elastic_stage_, static_cast<size_t>(elastic_slots_) * elastic_slot_bytes_, false), "elastic staging slots")) return false;
|
||||
(void)hipStreamSynchronize(stream_);
|
||||
elastic_stage_ready_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool hip_ok_log(hipError_t e, const char* what) {
|
||||
if (e == hipSuccess) return true;
|
||||
(void)hipGetLastError();
|
||||
std::fprintf(stderr, "[ink-hip] elastic experts: %s allocation failed: %s\n", what, hipGetErrorString(e));
|
||||
return false;
|
||||
}
|
||||
|
||||
void elastic_upload_layer(int il) {
|
||||
(void)hipMemcpyAsync(d_layer_exps_[il].dev_ptr, h_layer_exps_[il].data(), h_layer_exps_[il].size() * sizeof(GpuExpertDesc), hipMemcpyHostToDevice, stream_);
|
||||
(void)hipMemcpyAsync(elastic_cold_ent_d_[il].dev_ptr, elastic_cold_ent_h_[il].data(), elastic_cold_ent_h_[il].size() * sizeof(ElasticColdEnt), hipMemcpyHostToDevice, stream_);
|
||||
}
|
||||
|
||||
// The experts of the arena that sit in the chunks to be given up: the hot ones move down (swap), the rest is copied to the host and turned off in the tables.
|
||||
// Returns the number of chunks that went to the donor list of the pool.
|
||||
int64_t elastic_reclaim(int64_t want_chunks) {
|
||||
if (!elastic_.active() || want_chunks <= 0) return 0;
|
||||
const auto& dir = adj_dir_;
|
||||
uint8_t* arena = const_cast<uint8_t*>(expert_gpu_arena_.dev_ptr);
|
||||
auto sync_fn = [&]() { (void)hipStreamSynchronize(stream_); };
|
||||
auto swap_fn = [&](uint64_t off_a, uint64_t off_b, uint32_t bytes) -> bool {
|
||||
if (d_exp_stage_.dev_ptr == nullptr || bytes > d_exp_stage_.bytes) return false;
|
||||
if (hipMemcpyAsync(d_exp_stage_.dev_ptr, arena + off_a, bytes, hipMemcpyDeviceToDevice, stream_) != hipSuccess) return false;
|
||||
if (hipMemcpyAsync(arena + off_a, arena + off_b, bytes, hipMemcpyDeviceToDevice, stream_) != hipSuccess) return false;
|
||||
return hipMemcpyAsync(arena + off_b, d_exp_stage_.dev_ptr, bytes, hipMemcpyDeviceToDevice, stream_) == hipSuccess;
|
||||
};
|
||||
auto publish_fn = [&](const std::vector<int>& evicted, const std::vector<std::pair<int, uint64_t>>& moved) {
|
||||
std::vector<char> touched(c_.n_phys, 0);
|
||||
for (const auto& mk : moved) {
|
||||
const int key = mk.first;
|
||||
const int il = key / c_.n_experts;
|
||||
const int eid = dir[key].expert_id;
|
||||
expert_gpu_offset_[key] = static_cast<size_t>(mk.second);
|
||||
h_layer_exps_[il][eid].body = arena + mk.second;
|
||||
touched[il] = 1;
|
||||
}
|
||||
for (const int key : evicted) {
|
||||
const int il = key / c_.n_experts;
|
||||
const int eid = dir[key].expert_id;
|
||||
const size_t bytes = dir[key].body_bytes;
|
||||
int64_t ao = elastic_arena_off_[key];
|
||||
if (ao < 0) {
|
||||
ao = static_cast<int64_t>(elastic_arena_used_);
|
||||
elastic_arena_used_ += (bytes + 255ull) & ~255ull;
|
||||
elastic_arena_off_[key] = ao;
|
||||
}
|
||||
(void)hipMemcpyAsync(h_elastic_arena_ + ao, arena + expert_gpu_offset_[key], bytes, hipMemcpyDeviceToHost, stream_);
|
||||
expert_gpu_offset_[key] = static_cast<size_t>(-1);
|
||||
elastic_evicted_[key] = 1;
|
||||
h_layer_exps_[il][eid].body = nullptr; // dn_offset and the codes stay: the staged copy has the same layout
|
||||
elastic_cold_ent_h_[il][eid] = ElasticColdEnt{d_elastic_arena_ + ao, static_cast<uint32_t>(bytes), 0u};
|
||||
++elastic_n_evicted_;
|
||||
++elastic_evicted_total_;
|
||||
++elastic_layer_cold_n_[il];
|
||||
elastic_cold_layer_[il] = 1;
|
||||
layer_all_gpu_[il] = false;
|
||||
touched[il] = 1;
|
||||
}
|
||||
for (int il = 0; il < c_.n_phys; ++il) if (touched[il]) elastic_upload_layer(il);
|
||||
};
|
||||
return elastic_.reclaim_chunks(want_chunks, /*release_to_os=*/false, sync_fn, swap_fn, publish_fn);
|
||||
}
|
||||
|
||||
// The K/V asks for `need` chunks: take them from the coldest experts. The first time, a little more is taken and handed to the OS, and what leaving
|
||||
// needs on the card (the staging slots) is allocated out of it: nothing is set aside in advance. Returns the chunks now donated for the K/V.
|
||||
int64_t shed_experts_for_chunks(int64_t need, hipStream_t /*st*/) {
|
||||
if (!elastic_.active() || elastic_off_ || need <= 0) return 0;
|
||||
const uint64_t gran = strata::core::vmm_granularity();
|
||||
if (!elastic_prepare_arena() || !elastic_prepare_device_small()) { elastic_off_ = true; return 0; }
|
||||
int64_t extra = 0;
|
||||
if (!elastic_stage_ready_) extra = static_cast<int64_t>((static_cast<uint64_t>(elastic_slots_) * elastic_slot_bytes_ + gran - 1) / gran) + 3;
|
||||
int64_t want = need + extra;
|
||||
// the host copy must have room for what could leave (new experts only; a returning expert keeps its slot)
|
||||
const uint64_t room = elastic_arena_bytes_ > elastic_arena_used_ ? elastic_arena_bytes_ - elastic_arena_used_ : 0;
|
||||
const int64_t fit = room > 2ull * elastic_slot_bytes_ ? static_cast<int64_t>((room - 2ull * elastic_slot_bytes_) / gran) : 0;
|
||||
if (fit < want) {
|
||||
if (fit < need) return 0;
|
||||
want = fit;
|
||||
extra = std::min<int64_t>(extra, want - need);
|
||||
}
|
||||
const int64_t got = elastic_reclaim(want);
|
||||
if (got <= 0) return 0;
|
||||
invalidate_graph(); // the layers that lost experts take other branches; a graph captured before holds the old ones
|
||||
int64_t kept = got;
|
||||
if (extra > 0) {
|
||||
// hand `extra` chunks to the OS and allocate the staging slots; more chunks are freed when the driver still says no
|
||||
int64_t freed = 0;
|
||||
for (int tries = 0; tries < 8 && !elastic_stage_ready_; ++tries) {
|
||||
for (; freed < extra + tries * 2 && kept > 0; ++freed) {
|
||||
const strata::core::VmmChunk h = elastic_.take_donated_chunk();
|
||||
if (h == 0) break;
|
||||
strata::core::vmm_chunk_free(h);
|
||||
--kept;
|
||||
}
|
||||
if (elastic_prepare_stage_slots()) break;
|
||||
}
|
||||
if (!elastic_stage_ready_) std::fprintf(stderr, "[ink-hip] elastic experts: no room for the staging slots; decode runs the host-copy path (not bit-identical) for the layers that lost experts\n");
|
||||
}
|
||||
std::fprintf(stderr, "[ink-hip] elastic experts: %lld chunks (%.0f MiB) of the coldest experts go to the K/V; %zu experts are off the card now\n",
|
||||
static_cast<long long>(kept), static_cast<double>(kept) * static_cast<double>(gran) / 1048576.0, elastic_n_evicted_);
|
||||
return kept;
|
||||
}
|
||||
|
||||
// Chunks the K/V gives back (the conversation ended): the experts come back into them, read from the host copy.
|
||||
int64_t elastic_regrow(int64_t add_chunks, bool allow_os = false) {
|
||||
if (!elastic_.active() || elastic_n_evicted_ == 0 || add_chunks <= 0) return 0;
|
||||
const auto& dir = adj_dir_;
|
||||
uint8_t* arena = const_cast<uint8_t*>(expert_gpu_arena_.dev_ptr);
|
||||
auto reload = [&](int key, uint64_t off, uint32_t bytes) -> bool {
|
||||
if (key < 0 || static_cast<size_t>(key) >= elastic_arena_off_.size() || elastic_arena_off_[key] < 0) return false;
|
||||
return hipMemcpyAsync(arena + off, h_elastic_arena_ + elastic_arena_off_[key], bytes, hipMemcpyHostToDevice, stream_) == hipSuccess;
|
||||
};
|
||||
auto sync_fn = [&]() { (void)hipStreamSynchronize(stream_); };
|
||||
auto publish_fn = [&](const std::vector<std::pair<int, uint64_t>>& restored) {
|
||||
std::vector<char> touched(c_.n_phys, 0);
|
||||
for (const auto& rk : restored) {
|
||||
const int key = rk.first;
|
||||
const int il = key / c_.n_experts;
|
||||
const int eid = dir[key].expert_id;
|
||||
expert_gpu_offset_[key] = static_cast<size_t>(rk.second);
|
||||
elastic_evicted_[key] = 0;
|
||||
h_layer_exps_[il][eid].body = arena + rk.second;
|
||||
elastic_cold_ent_h_[il][eid] = ElasticColdEnt{nullptr, 0u, 0u};
|
||||
if (elastic_n_evicted_ > 0) --elastic_n_evicted_;
|
||||
if (elastic_layer_cold_n_[il] > 0) --elastic_layer_cold_n_[il];
|
||||
touched[il] = 1;
|
||||
}
|
||||
for (int il = 0; il < c_.n_phys; ++il) {
|
||||
if (!touched[il]) continue;
|
||||
if (elastic_layer_cold_n_[il] == 0) { elastic_cold_layer_[il] = 0; layer_all_gpu_[il] = true; }
|
||||
elastic_upload_layer(il);
|
||||
}
|
||||
};
|
||||
const int64_t got = elastic_.regrow_chunks(add_chunks, /*allow_os_alloc=*/allow_os, reload, sync_fn, publish_fn);
|
||||
if (got > 0) invalidate_graph();
|
||||
if (got > 0) std::fprintf(stderr, "[ink-hip] elastic experts: %lld chunks back to the experts; %zu experts are off the card\n", static_cast<long long>(got), elastic_n_evicted_);
|
||||
return got;
|
||||
}
|
||||
|
||||
// ---- live VRAM pressure (strata/platform/vram_guard.hpp): another program took memory, or gave it back ----
|
||||
// Shed: idle chunks first, then the coldest experts (copied to the host first); the chunks go back to the OS. MayReclaim (only for what was shed): the experts come
|
||||
// back into chunks taken from the OS again. Polled once per batch (one clock read between samples).
|
||||
void elastic_guard_init() {
|
||||
if (!elastic_.active()) return;
|
||||
strata::platform::VramGuardConfig c = strata::platform::make_hip_config(gpu0_id_ >= 0 ? gpu0_id_ : 0);
|
||||
c.chunk_bytes = strata::core::vmm_granularity();
|
||||
if (vram_guard_.init(c)) {
|
||||
std::fprintf(stderr, "[ink-hip] VRAM guard on: %s (low %llu MiB, target %llu MiB, high %llu MiB)\n", vram_guard_.status(),
|
||||
static_cast<unsigned long long>(vram_guard_.low_bytes() >> 20), static_cast<unsigned long long>(vram_guard_.target_bytes() >> 20),
|
||||
static_cast<unsigned long long>(vram_guard_.high_bytes() >> 20));
|
||||
}
|
||||
}
|
||||
|
||||
void elastic_guard_poll() {
|
||||
if (!elastic_guard_started_) { elastic_guard_started_ = true; elastic_guard_init(); }
|
||||
if (!vram_guard_.enabled() || !elastic_.active() || elastic_off_) return;
|
||||
const uint64_t g = strata::core::vmm_granularity();
|
||||
if (g == 0) return;
|
||||
const strata::platform::VramAdvice adv = vram_guard_.poll(elastic_shed_bytes_);
|
||||
static const bool guard_dbg = [] { const char* e = std::getenv("STRATA_INK_GUARD_DEBUG"); return e && e[0] == '1'; }();
|
||||
if (guard_dbg && adv.snap.source != 0) {
|
||||
std::fprintf(stderr, "[ink-hip] guard sample: headroom %.0f MiB (driver free %.0f MiB) advice %d bytes %llu shed_total %.0f MiB\n",
|
||||
static_cast<double>(adv.snap.headroom_bytes) / 1048576.0, static_cast<double>(adv.snap.driver_free) / 1048576.0, adv.kind,
|
||||
static_cast<unsigned long long>(adv.bytes), static_cast<double>(elastic_shed_bytes_) / 1048576.0);
|
||||
}
|
||||
if (adv.kind == strata::platform::VramAdvice::Shed) {
|
||||
const int64_t want = static_cast<int64_t>(adv.bytes / g);
|
||||
int64_t done = 0;
|
||||
while (done < want && !kv_spare_.empty()) { strata::core::vmm_chunk_free(kv_take_chunk()); ++done; } // idle chunks first
|
||||
if (done < want) {
|
||||
const int64_t got = shed_experts_for_chunks(want - done, stream_);
|
||||
kv_collect_donated();
|
||||
for (int64_t i = 0; i < got && !kv_spare_.empty(); ++i) strata::core::vmm_chunk_free(kv_take_chunk());
|
||||
done += got;
|
||||
}
|
||||
elastic_shed_bytes_ += static_cast<uint64_t>(done) * g;
|
||||
vram_guard_.report_applied(static_cast<uint64_t>(done) * g, 0);
|
||||
std::fprintf(stderr, "[ink-hip] VRAM pressure (headroom %.0f MiB): %.0f MiB of experts / idle chunks went back to the OS (%.0f MiB shed in all)\n",
|
||||
static_cast<double>(adv.snap.headroom_bytes) / 1048576.0, static_cast<double>(done * static_cast<int64_t>(g)) / 1048576.0,
|
||||
static_cast<double>(elastic_shed_bytes_) / 1048576.0);
|
||||
} else if (adv.kind == strata::platform::VramAdvice::MayReclaim && elastic_shed_bytes_ > 0) {
|
||||
const int64_t want = static_cast<int64_t>(std::min<uint64_t>(adv.bytes, elastic_shed_bytes_) / g);
|
||||
const int64_t got = elastic_regrow(want, /*allow_os=*/true);
|
||||
elastic_shed_bytes_ -= std::min<uint64_t>(elastic_shed_bytes_, static_cast<uint64_t>(got) * g);
|
||||
vram_guard_.report_applied(0, static_cast<uint64_t>(got) * g);
|
||||
if (got > 0) std::fprintf(stderr, "[ink-hip] memory is free again (headroom %.0f MiB): %.0f MiB of experts are back on the card (%.0f MiB still shed)\n",
|
||||
static_cast<double>(adv.snap.headroom_bytes) / 1048576.0, static_cast<double>(got * static_cast<int64_t>(g)) / 1048576.0,
|
||||
static_cast<double>(elastic_shed_bytes_) / 1048576.0);
|
||||
}
|
||||
}
|
||||
|
||||
// A conversation ended and no slot holds a K/V page any more: the global K/V returns to its start size and the freed chunks go back to the experts.
|
||||
void elastic_trim_kv_and_regrow(int resetting_slot = -1) {
|
||||
if (!elastic_.active() || elastic_n_evicted_ == 0 || !kv_vmm_on_) return;
|
||||
for (int s = 0; s < max_slots_; ++s) if (s != resetting_slot && slots_[s].allocated) return;
|
||||
const int keep_pages = std::max(1, 8192 / kKvPageTokens);
|
||||
int64_t freed = 0;
|
||||
for (auto& p : glob_pools_) {
|
||||
if (!p.vmm || p.host_offload) continue;
|
||||
p.used_pages = 0;
|
||||
p.free_pages.clear();
|
||||
freed += p.trim_vmm(keep_pages, [&](strata::core::VmmChunk h) { kv_spare_.push_back(h); });
|
||||
}
|
||||
if (freed <= 0) return;
|
||||
int64_t n = 0;
|
||||
for (const strata::core::VmmChunk h : kv_spare_) { elastic_.donate_chunk(h); ++n; }
|
||||
kv_spare_.clear();
|
||||
elastic_regrow(n);
|
||||
kv_collect_donated(); // chunks the experts did not need stay ready for the K/V
|
||||
}
|
||||
|
||||
void cleanup() {
|
||||
invalidate_graph();
|
||||
if (r9700_) {
|
||||
@@ -14490,7 +15163,15 @@ private:
|
||||
static_sconv_.clear(); d_msg_queries_.clear(); dspark_bf16_.clear(); dspark_f32_.clear();
|
||||
d_layer_exps_.clear(); h_layer_exps_.clear();
|
||||
adj_dir_.clear();
|
||||
free_gpu_buffer(expert_gpu_arena_); free_gpu_buffer(d_exp_stage_);
|
||||
if (elastic_.active()) { expert_gpu_arena_ = GpuBuffer{}; elastic_.release(); } else { free_gpu_buffer(expert_gpu_arena_); }
|
||||
for (strata::core::VmmChunk h : kv_spare_) strata::core::vmm_chunk_free(h);
|
||||
kv_spare_.clear();
|
||||
for (auto& b : elastic_cold_ent_d_) free_gpu_buffer(b);
|
||||
elastic_cold_ent_d_.clear(); elastic_cold_ent_h_.clear();
|
||||
free_gpu_buffer(d_elastic_stage_); free_gpu_buffer(d_elastic_step_); free_gpu_buffer(d_elastic_plan_);
|
||||
if (h_elastic_arena_) { (void)hipHostFree(h_elastic_arena_); h_elastic_arena_ = nullptr; d_elastic_arena_ = nullptr; }
|
||||
elastic_n_evicted_ = 0; elastic_small_ready_ = elastic_stage_ready_ = false;
|
||||
free_gpu_buffer(d_exp_stage_);
|
||||
free_gpu_buffer(d_exp_w13_f16_); free_gpu_buffer(d_exp_w2_f16_);
|
||||
free_gpu_buffer(d_dspark_state_); free_gpu_buffer(d_dspark_state2_); free_gpu_buffer(d_dspark_latent_);
|
||||
free_gpu_buffer(d_dspark_corr_); free_gpu_buffer(d_dspark_toks_);
|
||||
@@ -14663,6 +15344,75 @@ private:
|
||||
size_t vram_experts_loaded_ = 0;
|
||||
size_t ram_experts_loaded_ = 0;
|
||||
|
||||
// Elastic memory (ink_elastic_sec4.hpp): the expert arena as a virtual-memory pool and the global K/V that grows through chunks.
|
||||
strata::ink::InkElasticSec4Pool elastic_;
|
||||
bool kv_vmm_on_ = false;
|
||||
std::vector<strata::core::VmmChunk> kv_spare_; // chunks made ready for the K/V (donated by the pool, or created above the free floor), not mapped yet
|
||||
struct KvSrcImpl final : KvChunkSource {
|
||||
HipBackend* b;
|
||||
explicit KvSrcImpl(HipBackend* p) : b(p) {}
|
||||
bool reserve_chunks(int64_t n, hipStream_t st, size_t headroom) override { return b->kv_reserve_chunks(n, st, headroom); }
|
||||
strata::core::VmmChunk take_chunk() override { return b->kv_take_chunk(); }
|
||||
};
|
||||
KvSrcImpl kv_src_{this};
|
||||
// Experts that left the card (see shed_experts_for_chunks). A layer that lost experts has layer_all_gpu_ false; a decode visit (B == 1) stages the router's cold picks
|
||||
// inside the fast path (k_elastic_stage_*), any other visit takes the host-copy path of the hybrid layers (batched, exact GPU compute after a copy-in).
|
||||
size_t elastic_max_body_ = 0;
|
||||
bool elastic_off_ = false;
|
||||
bool elastic_arena_failed_ = false;
|
||||
bool elastic_small_ready_ = false;
|
||||
bool elastic_stage_ready_ = false;
|
||||
int elastic_slots_ = 8; // top_k: one decode visit picks at most 8 experts
|
||||
size_t elastic_slot_bytes_ = 0;
|
||||
size_t elastic_n_evicted_ = 0; // experts off the card now
|
||||
uint64_t elastic_evicted_total_ = 0;
|
||||
uint8_t* h_elastic_arena_ = nullptr;
|
||||
const uint8_t* d_elastic_arena_ = nullptr;
|
||||
uint64_t elastic_arena_bytes_ = 0;
|
||||
uint64_t elastic_arena_used_ = 0;
|
||||
std::vector<int64_t> elastic_arena_off_; // per directory index: its slot in the host copy (-1 none yet)
|
||||
std::vector<uint8_t> elastic_evicted_; // per directory index: off the card now
|
||||
std::vector<std::vector<ElasticColdEnt>> elastic_cold_ent_h_;
|
||||
std::vector<GpuBuffer> elastic_cold_ent_d_;
|
||||
std::vector<uint8_t> elastic_cold_layer_; // per layer: some expert is off the card
|
||||
std::vector<int> elastic_layer_cold_n_;
|
||||
GpuBuffer d_elastic_stage_, d_elastic_step_, d_elastic_plan_;
|
||||
strata::platform::VramGuard vram_guard_;
|
||||
uint64_t elastic_shed_bytes_ = 0; // bytes of experts / chunks given back to the OS because other programs needed the memory
|
||||
bool elastic_guard_started_ = false;
|
||||
int elastic_test_evict_mib_ = [] { const char* e = std::getenv("STRATA_INK_ELASTIC_TEST_EVICT_MIB"); return e ? std::atoi(e) : 0; }();
|
||||
bool elastic_multi_off_ = [] { const char* e = std::getenv("STRATA_INK_ELASTIC_MULTI"); return e && e[0] == '0'; }(); // test: cold layers of prompt batches take the host-copy path
|
||||
bool elastic_stage_off_ = [] { const char* e = std::getenv("STRATA_INK_ELASTIC_STAGE"); return e && e[0] == '0'; }(); // test: no staging in the fast path (cold layers take the host-copy path)
|
||||
|
||||
// The host copy of an expert that is not on the card (RAM bodies of the hybrid tier, or the pinned copy of an expert that left); nullptr when none.
|
||||
const uint8_t* host_body_of(int dir_idx) const {
|
||||
if (dir_idx < 0) return nullptr;
|
||||
if (static_cast<size_t>(dir_idx) < expert_ram_bodies_.size() && !expert_ram_bodies_[dir_idx].empty()) return expert_ram_bodies_[dir_idx].data();
|
||||
if (static_cast<size_t>(dir_idx) < elastic_evicted_.size() && elastic_evicted_[dir_idx]) return h_elastic_arena_ + elastic_arena_off_[dir_idx];
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Can this decode visit run the layer's fast path although it lost experts (the cold picks are staged inside the visit)?
|
||||
// Prompt-sized batch (the routed rows fill the experts): the cold experts of the layer are computed in extra passes of the batched MoE kernels (see the epass loop).
|
||||
bool elastic_multipass_ok(int il, int B) const {
|
||||
return B >= 16 && elastic_stage_ready_ && !elastic_stage_off_ && !elastic_multi_off_ && il >= 0 && static_cast<size_t>(il) < elastic_cold_layer_.size() && elastic_cold_layer_[il] != 0;
|
||||
}
|
||||
bool elastic_stageable(int il, int B) const {
|
||||
return B == 1 && elastic_stage_ready_ && !elastic_stage_off_ && il >= 0 && static_cast<size_t>(il) < elastic_cold_layer_.size() && elastic_cold_layer_[il] != 0;
|
||||
}
|
||||
|
||||
// The table the MoE kernels of layer `ip` read in this visit: the layer's own, or (B == 1, experts off the card) the step table with the router's cold picks staged.
|
||||
const GpuExpertDesc* moe_exps_table(int ip, const int32_t* tk_i, int B, hipStream_t s) {
|
||||
const GpuExpertDesc* base = reinterpret_cast<const GpuExpertDesc*>(d_layer_exps_[ip].dev_ptr);
|
||||
if (!elastic_stageable(ip, B)) return base;
|
||||
k_elastic_stage_plan<<<1, 128, 0, s>>>(base, reinterpret_cast<const ElasticColdEnt*>(elastic_cold_ent_d_[ip].dev_ptr), tk_i, c_.top_k,
|
||||
reinterpret_cast<GpuExpertDesc*>(d_elastic_step_.dev_ptr), reinterpret_cast<int32_t*>(d_elastic_plan_.dev_ptr),
|
||||
d_elastic_stage_.dev_ptr, elastic_slot_bytes_, elastic_slots_, c_.n_experts);
|
||||
k_elastic_stage_copy<<<dim3(16, elastic_slots_), 256, 0, s>>>(reinterpret_cast<const ElasticColdEnt*>(elastic_cold_ent_d_[ip].dev_ptr),
|
||||
reinterpret_cast<const int32_t*>(d_elastic_plan_.dev_ptr), d_elastic_stage_.dev_ptr, elastic_slot_bytes_);
|
||||
return reinterpret_cast<const GpuExpertDesc*>(d_elastic_step_.dev_ptr);
|
||||
}
|
||||
|
||||
std::vector<VisitKvPool> swa_pools_;
|
||||
std::vector<VisitKvPool> glob_pools_;
|
||||
GpuBuffer d_sconv_k_all_, d_sconv_v_all_, d_sconv_attn_all_, d_sconv_mlp_all_;
|
||||
@@ -14798,3 +15548,10 @@ std::unique_ptr<InkBackend> make_hip_backend() {
|
||||
}
|
||||
|
||||
} // namespace ink2
|
||||
|
||||
// The ROCm 6+ virtual memory ranges (hipMemAddressReserve / hipMemCreate / hipMemMap) of the elastic K/V and expert pool: core/vmm.cpp is compiled
|
||||
// into this object, so the HIP package needs no extra object and no change to the packaging scripts. Its HIP branch is selected by STRATA_USE_HIP
|
||||
// (set for this include only); it reports "not available" on ROCm older than 6, on gfx906 and when STRATA_HIP_VMM=0.
|
||||
#define STRATA_USE_HIP 1
|
||||
#include "../../core/vmm.cpp"
|
||||
#undef STRATA_USE_HIP
|
||||
@@ -154,8 +154,17 @@ if(LING32_SYCL)
|
||||
add_executable(ling32_sy_mla_fd_test ${_tests_dir}/ling32_sy_mla_fd_test.cpp) # L32-SY-MLA: flash-decoding MLA attention against the original kernel
|
||||
target_link_libraries(ling32_sy_mla_fd_test PRIVATE ling32_gpu)
|
||||
add_test(NAME ling32_sy_mla_fd_test COMMAND ling32_sy_mla_fd_test)
|
||||
add_executable(ling32_sy_mla_exp_test ${_tests_dir}/ling32_sy_mla_exp_test.cpp) # L32-SY-MLA: expanded-form MLA prefill against the absorbed pipeline
|
||||
target_link_libraries(ling32_sy_mla_exp_test PRIVATE ling32_gpu)
|
||||
add_test(NAME ling32_sy_mla_exp_test COMMAND ling32_sy_mla_exp_test)
|
||||
add_executable(ling32_sy_kda_test ${_tests_dir}/ling32_sy_kda_test.cpp) # L32-SY-MLA: the chunk-parallel KDA prefill scan against the sequential recurrence, with timings
|
||||
target_link_libraries(ling32_sy_kda_test PRIVATE ling32_gpu)
|
||||
add_test(NAME ling32_sy_kda_test COMMAND ling32_sy_kda_test skip-big)
|
||||
add_executable(ling32_sy_bench ${_tests_dir}/ling32_sy_bench.cpp) # decode-step kernel cost model at the real shapes (not a ctest entry)
|
||||
target_link_libraries(ling32_sy_bench PRIVATE ling32_gpu)
|
||||
set_source_files_properties(${_tests_dir}/ling32_vision_gpu_test.cu PROPERTIES LANGUAGE CXX) # L32-SY-VISION: the GPU picture encoder against the golden set (the CUDA test, compiled as C++ against the shim; run by hand)
|
||||
add_executable(ling32_vision_gpu_test ${_tests_dir}/ling32_vision_gpu_test.cu)
|
||||
target_link_libraries(ling32_vision_gpu_test PRIVATE ling32_gpu)
|
||||
if(Python3_FOUND)
|
||||
set(_ids "5,17,100,42,7,300,12,9,33,2,64,201")
|
||||
add_test(NAME ling32_make_ref COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_pyref.py ref ${_fixture} --ids ${_ids} --out ${CMAKE_BINARY_DIR}/ref)
|
||||
@@ -179,6 +188,10 @@ if(LING32_SYCL)
|
||||
set_tests_properties(ling32_mtp_tier_regress PROPERTIES FIXTURES_REQUIRED ling32_wide_mtp TIMEOUT 600)
|
||||
add_test(NAME ling32_spec_span_regress COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_spec_span_test.py $<TARGET_FILE:strata-ling32> ${_wide} ${_wide_mtp} ${CMAKE_BINARY_DIR}/spec_span_work)
|
||||
set_tests_properties(ling32_spec_span_regress PROPERTIES FIXTURES_REQUIRED ling32_wide_mtp TIMEOUT 600)
|
||||
add_test(NAME ling32_mtp_auto_regress COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_mtp_auto_test.py $<TARGET_FILE:strata-ling32> ${_wide} ${_wide_mtp} ${CMAKE_BINARY_DIR}/mtp_auto_work)
|
||||
set_tests_properties(ling32_mtp_auto_regress PROPERTIES FIXTURES_REQUIRED ling32_wide_mtp TIMEOUT 600)
|
||||
add_test(NAME ling32_kv_grow_regress COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_kv_grow_test.py $<TARGET_FILE:strata-ling32> ${_wide} ${_wide_mtp} ${CMAKE_BINARY_DIR}/kv_grow_work)
|
||||
set_tests_properties(ling32_kv_grow_regress PROPERTIES FIXTURES_REQUIRED ling32_wide_mtp TIMEOUT 900)
|
||||
endif()
|
||||
add_test(NAME ling32_spec_test COMMAND ling32_spec_test)
|
||||
# L32-SY-TIER: the tier store driven without the engine's kernels (table slabs compared on the host and by a SYCL kernel); run by hand / sycl/tools/l32sy_tierbox.sh tiercheck
|
||||
|
||||
@@ -483,13 +483,32 @@ struct Ling32Engine::StageCtx {
|
||||
if (E.provider_) E.provider_->grow_bytes(~static_cast<size_t>(0));
|
||||
}
|
||||
|
||||
// lazy KV / scratch regrow: before an allocation, make room in the pool if the card has less than BYTES + a margin free (STRATA_L32_ALLOC_MARGIN_MB, default 0 = off: only STRATA_L32_REGROW_TRACE=1 prints the checks): the store releases whole chunks of pool
|
||||
// slots for the shortfall. Waiting for cudaMalloc to fail is not enough where the driver over-commits (Windows WDDM pages the allocation to shared system memory instead of failing, and the kernels then
|
||||
// read it over PCIe: a 33K-token prompt took 600 s instead of 100 s on a 12 GB card); the failure retry below stays as the backstop.
|
||||
void make_room(size_t bytes) {
|
||||
if (!E.provider_ || E.opt.kv_init_ctx <= 0) return;
|
||||
static const size_t margin = [] { const char* e = std::getenv("STRATA_L32_ALLOC_MARGIN_MB"); return static_cast<size_t>(e && e[0] ? std::max(0, std::atoi(e)) : 0) * 1048576ull; }();
|
||||
static const bool trace = [] { const char* f = std::getenv("STRATA_L32_REGROW_TRACE"); return f && f[0] == '1'; }();
|
||||
if (margin == 0 && !trace) return; // default: off, exactly the old behaviour (the failure retry below is the only release; a margin of 256 MiB cost 1-3 % of prefill and decode on a Linux 5070 and never fired on Windows, where the planner headroom is the fix)
|
||||
static int n_print = 0; // the first checks of a process are always printed (one short line each, at most 4): the numbers cudaMemGetInfo gives are what decides whether the pool makes room
|
||||
for (int t = 0; t < 64; ++t) {
|
||||
size_t fr = 0, tot = 0;
|
||||
if (cudaMemGetInfo(&fr, &tot) != cudaSuccess) { (void)cudaGetLastError(); return; }
|
||||
const bool low = fr < bytes + margin;
|
||||
if ((trace && bytes >= (8u << 20)) || (n_print < 4 && bytes >= (8u << 20))) { ++n_print; std::printf("[make_room] alloc %.1f MiB, card free %.0f of %.0f MiB, margin %.0f MiB: %s\n", bytes / 1048576.0, fr / 1048576.0, tot / 1048576.0, margin / 1048576.0, low ? "releasing pool chunks" : "room"); }
|
||||
if (!low) return;
|
||||
if (E.provider_->release_bytes(bytes + margin - fr) == 0) { if (trace) std::printf("[make_room] the pool has nothing more to give\n"); return; }
|
||||
}
|
||||
}
|
||||
|
||||
// one cudaMalloc; with a tier store attached (lazy KV / scratch regrow) a failure makes the store release whole chunks of pool slots and the allocation is tried again
|
||||
bool alloc_bytes(void** pp, size_t bytes, const char* what, std::string& err) {
|
||||
if (std::getenv("STRATA_L32_TRACE")) std::fprintf(stderr, "ling32: alloc %.1f MiB\n", bytes / 1048576.0);
|
||||
static const bool inject = [] { const char* f = std::getenv("STRATA_L32_LAZY_OOM"); return f && f[0] == '1'; }(); // test hook: the first allocation after the store is attached fails once, so the release-and-retry path runs
|
||||
cudaError_t e = cudaSuccess;
|
||||
if (inject && E.provider_ && E.opt.kv_init_ctx > 0 && !oom_injected) { oom_injected = true; e = cudaErrorMemoryAllocation; }
|
||||
else e = cudaMalloc(pp, bytes);
|
||||
else { make_room(bytes); e = cudaMalloc(pp, bytes); }
|
||||
// lazy latent KV: the tier store gave all the room the cache did not need to its pool; a later allocation (the prompt span's buffers, the prefill scratch, ...) takes chunks of pool slots back instead of failing
|
||||
for (int t = 0; e == cudaErrorMemoryAllocation && E.provider_ && E.opt.kv_init_ctx > 0 && t < 64; ++t) {
|
||||
(void)cudaGetLastError();
|
||||
@@ -705,6 +724,7 @@ struct Ling32Engine::StageCtx {
|
||||
for (size_t il = 0; il < cache.size(); ++il) {
|
||||
if (!cache[il] || kv_cap_l[il] >= ncap) continue;
|
||||
void* nb = nullptr;
|
||||
make_room(nbytes);
|
||||
cudaError_t e = cudaMalloc(&nb, nbytes);
|
||||
for (int t = 0; e != cudaSuccess && E.provider_ && t < 64; ++t) {
|
||||
(void)cudaGetLastError();
|
||||
@@ -921,6 +941,8 @@ struct Ling32Engine::StageCtx {
|
||||
gpu::gemv_f32(M.gate_w, c.n_exp, D, cur, N, rlog, st);
|
||||
gpu::alflb_route(rlog, nullptr, M.gate_bias, c.n_exp, c.n_group, c.topk_group, c.top_k, c.routed_scale, true, ridx, rw, N, st);
|
||||
}
|
||||
// opt-in, not exact (--skip-tau / STRATA_L32_SKIP_TAU): drop a decode / verify token's routed experts below tau of its routing weight (the tier store then fetches nothing for them)
|
||||
if (o.skip_tau > 0.0f && N <= 16 && il < c.n_layers) gpu::prune_experts(ridx, rw, N, c.top_k, o.skip_tau, st);
|
||||
if (uniq_on && N > 1 && il < c.n_layers) gpu::count_unique(ridx, N * c.top_k, c.n_exp, d_uniq + il, st);
|
||||
if (il < c.n_layers && h_ridx[il]) {
|
||||
cudaMemcpyAsync(h_ridx[il], ridx, static_cast<size_t>(N) * c.top_k * sizeof(int), cudaMemcpyDeviceToHost, st);
|
||||
@@ -1255,7 +1277,7 @@ bool Ling32Engine::init(GpuModel& model, const EngineOptions& o, std::string& er
|
||||
auto off = [](bool& f, const char* what) { if (f) { std::fprintf(stderr, "ling32: %s is not available on SYCL yet, ignored\n", what); f = false; } };
|
||||
off(opt.cuda_graph, "--graph");
|
||||
off(opt.pdl, "--pdl");
|
||||
off(opt.mla_expanded, "--mla-prefill expanded");
|
||||
if (opt.mla_expanded && !gpu::mla_exp_ok(128, 64, 128, 512)) off(opt.mla_expanded, "--mla-prefill expanded (needs the XMX engines)"); // the joint_matrix kernel of sycl/ling32_sy_k_mla_exp.cpp
|
||||
off(opt.fuse_experts, "--fuse-experts");
|
||||
// --tc (the trunk GEMMs of prefill chunks, sycl/ling32_sy_k_moe_xmx.cpp trunk_xmx_try) and --tc-moe (grouped experts) stay: XMX tiles where the device has them, else the float kernels.
|
||||
// STRATA_L32_TRUNK_XMX=0 keeps the scalar GEMV for the trunk (A/B).
|
||||
@@ -1277,6 +1299,9 @@ bool Ling32Engine::init(GpuModel& model, const EngineOptions& o, std::string& er
|
||||
if (wmma && std::strncmp(prop.gcnArchName, "gfx12", 5) == 0) {
|
||||
if (gpu::g_w2_nt == 0) gpu::g_w2_nt = 4; // 0 = not set by the env or a config part
|
||||
if (gpu::g_w2_etn == 0) gpu::g_w2_etn = 2;
|
||||
if (gpu::g_w2_pack < 0) gpu::g_w2_pack = 1; // the packed trunk GEMM (bit-identical, +12 % prompt reading at 4K on the R9700); STRATA_L32_W2_PACK=0 / config part pack0 turns it off
|
||||
} else {
|
||||
gpu::g_w2_pack = 0; // the packed kernel is written for the 8-half fragments of gfx12 only (gfx11 / Strix keep the unpacked kernel)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1652,7 +1677,19 @@ bool Ling32Engine::spec_init(const SpecParams& p, std::string& err) {
|
||||
I.m_probe = 0;
|
||||
spec_on_ = true;
|
||||
sstats_ = SpecStats{};
|
||||
if (p.adaptive && p.mtp_calibrate) { // measure the cycle time of every verify length now, once: the controller never changes its table during requests (seeded sampling stays reproducible)
|
||||
// HIP with NO tier store (tier A, every expert resident; integrated or discrete): NO calibration. Measured on the Strix Halo (Windows, gfx1151): with the calibration the adaptive controller ends on
|
||||
// the plain path or drafts that are all rejected (acceptance 0.000, 29.5 tok/s); with the same adaptive controller and the calibration off (--spec-sweep ...,calibrate=0) the real request picks K from
|
||||
// the cost model and its own acceptance and runs 42.1 tok/s (acceptance 0.633, ids exact); fixed K=1 / K=2 also run 41.4 / 42.1. The synthetic calibration cycles there cost 141..146 ms per verify of
|
||||
// 2..5 rows (real: 43.5 ms for 2 rows) or do not run as that length at all. Every other path (CUDA, every HIP tier-store run: tier B / C, e.g. the R9700 pool) keeps its calibration.
|
||||
bool hip_no_store = false;
|
||||
#if defined(STRATA_USE_HIP)
|
||||
hip_no_store = provider_ == nullptr;
|
||||
#endif
|
||||
if (hip_no_store && p.adaptive && p.mtp_calibrate) {
|
||||
I.sp.mtp_calibrate = false;
|
||||
std::fprintf(stderr, "ling32: MTP: HIP, all experts resident (no tier store): the adaptive K starts from the cost model (no calibration)\n");
|
||||
}
|
||||
if (p.adaptive && p.mtp_calibrate && !hip_no_store) { // measure the cycle time of every verify length now, once: the controller never changes its table during requests (seeded sampling stays reproducible)
|
||||
std::string e2;
|
||||
if (!spec_calibrate(e2)) std::fprintf(stderr, "ling32: MTP calibration failed (%s); the adaptive K uses the cost model\n", e2.c_str());
|
||||
}
|
||||
|
||||
@@ -64,6 +64,7 @@ struct EngineOptions {
|
||||
bool kda_chunked = true; // N > 1: the chunk-parallel KDA form (false: the sequential recurrence)
|
||||
bool lookahead_group_mask = true; // rank with the router's group-limited mask (top-4 of 8 groups); false: no mask (L32-ART: better at K >= 16, the tail a prefetcher fills)
|
||||
int lookahead_ks = 3; // which predictors to evaluate: bit 0 = k 2, bit 1 = k 4 (the tiers use one)
|
||||
float skip_tau = 0.0f; // --skip-tau T / STRATA_L32_SKIP_TAU (opt-in, NOT exact, default off): a decode / verify token's routed experts whose share of its routing weight is below T are dropped (top expert kept, weights renormalized, nothing fetched for them)
|
||||
bool lookahead_k1 = false; // L32-TIER: also a k = 1 prediction per MoE layer (its own router on the residual entering it); needs `lookahead` and a demand sink
|
||||
bool lookahead_stats = true; // log prediction vs truth (off in a tier run unless asked: it costs host time per layer)
|
||||
bool lookahead = false; // evaluate the Section 2 lookahead routers (needs LoadOptions::load_lookahead) and log prediction vs truth
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
namespace strata::ling32::gpu {
|
||||
int g_w2_nt = [] { const char* e = std::getenv("STRATA_L32_W2_NT"); return e ? std::atoi(e) : 0; }();
|
||||
int g_w2_pack = [] { const char* e = std::getenv("STRATA_L32_W2_PACK"); return e ? std::atoi(e) : -1; }(); // AMD trunk GEMM from a coalesced repack of the S8 weights: 1 on, 0 off, -1 = by the device (on for gfx12)
|
||||
int g_w2_etn = [] { const char* e = std::getenv("STRATA_L32_W2_ETN"); return e ? std::atoi(e) : 0; }();
|
||||
|
||||
#define L32_CHECK(call) \
|
||||
@@ -481,6 +482,7 @@ const void* w2_split_acts(const float* x, size_t rows_n, int K, int mode, cudaSt
|
||||
return (mode & 1) ? w2_split_impl<1>(x, rows_n, K, s, dl, dm) : w2_split_impl<0>(x, rows_n, K, s, dl, dm);
|
||||
}
|
||||
void w2_reserve(cudaStream_t s) {
|
||||
if (g_w2_pack > 0) (void)w2p_scratch(s); // the repack scratch of the packed trunk GEMM, taken here with the other scratch (before the KV cache); nullptr = no room, the unpacked kernel is used
|
||||
std::lock_guard<std::mutex> lk(w2_mu());
|
||||
W2Scratch& sc = w2_map()[s];
|
||||
if (!sc.p) {
|
||||
|
||||
@@ -93,6 +93,7 @@ inline bool prefer_one_stage(F2 kern2, size_t smem2, F1 kern1, size_t smem1, int
|
||||
return o1 > o2;
|
||||
}
|
||||
extern int g_w2_nt; // AMD WMMA GEMMs: tokens per block of the trunk GEMM = 16 x this (2 or 4; 0 = by the device: 4 on gfx12); STRATA_L32_W2_NT
|
||||
extern int g_w2_pack; // AMD trunk GEMM from a coalesced repack of the S8 weights (bit-identical to the unpacked one): 1 on, 0 off, -1 = by the device (on for gfx12); STRATA_L32_W2_PACK
|
||||
extern int g_w2_etn; // AMD WMMA routed experts: pairs per tile = 16 x this (1 or 2; 0 = by the device: 2 on gfx12); STRATA_L32_W2_ETN
|
||||
extern int g_kda_chunk_force; // tests: 0 = by the device (32 where the 91 KiB of the 32-token chunk fit, else 16), 16 or 32 = that chunk length
|
||||
|
||||
@@ -212,6 +213,8 @@ extern int g_alflb_ref; // 1: use the one-warp reference routing kernel (tests
|
||||
extern int g_alflb_look; // 1: the lookahead lists (top_n > 8) also use the parallel kernel (default: HIP 1, CUDA 0; STRATA_L32_ALFLB_LOOKAHEAD)
|
||||
void alflb_route(const float* logits, const float* add_bias, const float* sel_bias, int E, int n_group, int topk_group, int top_n, float scale, bool weights, int* out_idx,
|
||||
float* out_w, int N, cudaStream_t s);
|
||||
// dynamic expert skip (opt-in, not exact): drop the routed experts below tau of a token's routing weight (see the kernel); the dropped slot repeats the token's top expert with weight 0
|
||||
void prune_experts(int* ridx, float* rw, int N, int top_k, float tau, cudaStream_t s);
|
||||
|
||||
// ---- SwiGLU with the per-layer clamp (lim <= 0: none)
|
||||
// out[t][r] = swiglu(gate_r . x_t, up_r . x_t) over two S8_K matrices in one pass; float activations, N <= 16 per launch group
|
||||
|
||||
@@ -1805,6 +1805,39 @@ void alflb_route(const float* logits, const float* add_bias, const float* sel_bi
|
||||
alflb_kernel<<<N, 32, (2 * E) * sizeof(float) + E, s>>>(logits, add_bias, sel_bias, E, n_group, topk_group, top_n, scale, weights ? 1 : 0, out_idx, out_w);
|
||||
}
|
||||
|
||||
// Dynamic expert skip (opt-in measurement, STRATA_L32_SKIP_TAU; NOT exact): per token, a routed expert whose share of the token's routing weight is below tau is dropped (the top expert is always kept):
|
||||
// its slot gets the token's top expert id with weight 0 (the id is resident for the layer anyway, so the tier store fetches nothing for it, and the kernels add an exact zero), and the weights of the kept
|
||||
// experts are scaled so that the sum of the token's routing weights stays the same.
|
||||
__global__ void prune_experts_kernel(int* ridx, float* rw, int N, int top_k, float tau) {
|
||||
const int t = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (t >= N) return;
|
||||
int* ix = ridx + static_cast<size_t>(t) * top_k;
|
||||
float* w = rw + static_cast<size_t>(t) * top_k;
|
||||
float sum = 0.0f, wmax = -1.0f;
|
||||
int imax = 0;
|
||||
for (int j = 0; j < top_k; ++j) {
|
||||
sum += w[j];
|
||||
if (w[j] > wmax) { wmax = w[j]; imax = j; }
|
||||
}
|
||||
if (!(sum > 0.0f)) return;
|
||||
float kept = 0.0f;
|
||||
int drops = 0;
|
||||
for (int j = 0; j < top_k; ++j) {
|
||||
if (j != imax && w[j] < tau * sum) ++drops; else kept += w[j];
|
||||
}
|
||||
if (drops == 0 || !(kept > 0.0f)) return;
|
||||
const float scale = sum / kept;
|
||||
const int top_id = ix[imax];
|
||||
for (int j = 0; j < top_k; ++j) {
|
||||
if (j != imax && w[j] < tau * sum) { ix[j] = top_id; w[j] = 0.0f; }
|
||||
else w[j] *= scale;
|
||||
}
|
||||
}
|
||||
|
||||
void prune_experts(int* ridx, float* rw, int N, int top_k, float tau, cudaStream_t s) {
|
||||
prune_experts_kernel<<<(N + 31) / 32, 32, 0, s>>>(ridx, rw, N, top_k, tau);
|
||||
}
|
||||
|
||||
void swiglu(const float* g, int gs, const float* u, int us, float lim, bool post_silu, float* out, int os, int N, int I, cudaStream_t s) {
|
||||
swiglu_kernel<<<dim3((I + 255) / 256, N), 256, 0, s>>>(g, gs, u, us, lim, post_silu ? 1 : 0, out, os, I);
|
||||
}
|
||||
|
||||
@@ -88,7 +88,14 @@ int cmd_info_kv(const std::string& file) {
|
||||
Ling32File f;
|
||||
std::string err;
|
||||
if (!f.open(file, err, false)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
|
||||
std::printf("arch=ling32 layers=%d vocab=%d drafter=none mtp=1 mtp_auto=1 images=1 tiers=A,B,C\n", f.cfg().n_layers, f.cfg().V); // mtp=1: this engine takes --mtp FILE --spec mtp; mtp_auto=1: and --mtp-auto FILE
|
||||
// vision=gpu: pictures are encoded on the GPU by default on this machine (the GPU encoder exists in this build and device 0 has 24 GB or more: vision_default_backend); vision=cpu: the CPU encoder.
|
||||
// The launcher drops its pixel cap for the CPU encoder on the word gpu.
|
||||
#ifdef LING32_HAVE_CUDA
|
||||
const char* vis_enc = vision_default_backend(vision_gpu_total_bytes(0));
|
||||
#else
|
||||
const char* vis_enc = "cpu";
|
||||
#endif
|
||||
std::printf("arch=ling32 layers=%d vocab=%d drafter=none mtp=1 mtp_auto=1 images=1 vision=%s tiers=A,B,C\n", f.cfg().n_layers, f.cfg().V, vis_enc); // mtp=1: this engine takes --mtp FILE --spec mtp; mtp_auto=1: and --mtp-auto FILE
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -210,6 +217,7 @@ struct RunOpts {
|
||||
int logits_rows_opt = -1; // --logits-rows N: rows of the engine's logits buffer (0 = a whole chunk; -1 = 32 for --serve / --genjobs, which ask for few rows, else a whole chunk: the teacher-forced modes dump every row)
|
||||
int kv_init_opt = -1; // --kv-init N: lazy latent KV, initial capacity in rows (0 = reserve the whole context up front; -1 = 16384 in tier B / C, the cache then grows with the conversation and the tier store gives pool slots back); STRATA_L32_LAZY_KV=0 also switches it off
|
||||
int kv_plan_rows = 0; // set by make_plan: the rows make_sizes counts for the latent cache (0 = o.ctx)
|
||||
float skip_tau = -1.0f; // --skip-tau T: dynamic expert skip threshold (< 0: STRATA_L32_SKIP_TAU, default off)
|
||||
int regrow_opt = -1; // --regrow on|off: scratch regrow (the activation scratch of a chunk only while a prompt is prefilled, the memory goes back to the expert pool for decode); -1 = STRATA_L32_REGROW (default off), tier B / C with lazy KV only
|
||||
int decode_rows_opt = 64; // --decode-rows N: rows of the always-resident scratch set of scratch regrow
|
||||
bool regrow_plan = false; // set by make_plan: make_sizes counts decode_rows_opt rows of activation scratch instead of the chunk
|
||||
@@ -752,6 +760,18 @@ int cmd_run(const RunOpts& o_in) {
|
||||
#endif
|
||||
igpu_zero_copy = win_igpu && o.tier != "vram";
|
||||
uint64_t plan_vram = fr, plan_ram = host_ram_available(), win_ram_budget = 0;
|
||||
#if defined(_WIN32) && !defined(STRATA_USE_HIP)
|
||||
if (!integrated && o.tier != "vram") {
|
||||
// Windows (WDDM) with a discrete card: the planner filled the card to the last 0.4 GiB (a 12 GB RTX 5070: "GPU memory 11.54 / 11.91 GiB used" at ready), and WDDM does not fail an allocation
|
||||
// beyond the dedicated memory, it pages it into shared system memory: the prefill scratch, the graphs and the desktop's own use ended up there and a 33,784-token prompt took 620 s instead of 100 s.
|
||||
// Plan against the free memory minus a headroom (STRATA_L32_WDDM_HEADROOM_MB, default 1536; 0 switches it off).
|
||||
static const uint64_t headroom = [] { const char* e = std::getenv("STRATA_L32_WDDM_HEADROOM_MB"); return static_cast<uint64_t>(e && e[0] ? std::max(0, std::atoi(e)) : 1536) << 20; }();
|
||||
if (headroom > 0) {
|
||||
plan_vram = fr > headroom ? fr - headroom : 0;
|
||||
std::printf("Windows: the card is planned within %.2f of its %.2f GiB free (%.2f GiB headroom against WDDM paging)\n", plan_vram / 1073741824.0, fr / 1073741824.0, headroom / 1073741824.0);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (win_igpu && o.tier != "vram") {
|
||||
constexpr uint64_t kGiBu = 1ull << 30;
|
||||
l32::trace("main: probing the GPU allocation cap");
|
||||
@@ -839,13 +859,18 @@ int cmd_run(const RunOpts& o_in) {
|
||||
GpuModel M;
|
||||
LoadOptions lo;
|
||||
lo.load_lookahead = o.lookahead || o.coverage || (tiered && plan.prefetch);
|
||||
if (tiered) lo.lookahead_ks = (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1);
|
||||
int la_ks_env = -1; // STRATA_L32_LA_KS (measurement): bit mask of the lookahead predictors to compute (1: k=2, 2: k=4, 3: both), e.g. with STRATA_L32_PF_K=2 in a tier B run
|
||||
if (const char* e = std::getenv("STRATA_L32_LA_KS")) if (e[0]) la_ks_env = std::atoi(e) & 3;
|
||||
if (tiered) lo.lookahead_ks = la_ks_env >= 0 ? la_ks_env : (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1);
|
||||
lo.load_experts = !tiered;
|
||||
lo.verify_upload = false;
|
||||
lo.map_experts = o.map_experts;
|
||||
lo.lock_mapped = o.lock_mapped;
|
||||
lo.device = o.device;
|
||||
lo.reserve_bytes = (1ull << 30) + static_cast<uint64_t>(o.ctx) * 576 * 2 * 7 + static_cast<uint64_t>(o.chunk) * 157184 * 4 + (700ull << 20);
|
||||
// the card must hold the trunk and this reserve; with scratch regrow in a tiered run the always-resident scratch is decode_rows rows, a prompt takes pool slots for the big chunk scratch only while it is prefilled
|
||||
// (a card of 8 GB could not start at chunk 2048: the logits buffer of the chunk alone is 1.3 GiB)
|
||||
const int reserve_rows = (tiered && plan.kv_rows > 0 && o.regrow()) ? std::min(o.chunk, o.decode_rows_opt) : o.chunk;
|
||||
lo.reserve_bytes = (1ull << 30) + static_cast<uint64_t>(o.ctx) * 576 * 2 * 7 + static_cast<uint64_t>(reserve_rows) * 157184 * 4 + (700ull << 20);
|
||||
if (!o.vis.file.empty() && (o.vis.backend == "gpu" || (o.vis.backend == "auto" && vision_default_backend(vision_gpu_total_bytes(o.device))[0] == 'g')))
|
||||
lo.reserve_bytes += 1600ull << 20; // the GPU picture encoder: ~830 MiB of weights plus the activations of one picture
|
||||
const double t0 = now_s();
|
||||
@@ -887,9 +912,12 @@ int cmd_run(const RunOpts& o_in) {
|
||||
eo.max_tokens = o.chunk;
|
||||
eo.logits_rows = o.logits_rows();
|
||||
if (tiered && plan.kv_rows > 0) eo.kv_init_ctx = plan.kv_rows; // lazy latent KV (the plan counted only this)
|
||||
if (o.skip_tau >= 0.0f) eo.skip_tau = o.skip_tau;
|
||||
else if (const char* e = std::getenv("STRATA_L32_SKIP_TAU")) { if (e[0]) eo.skip_tau = static_cast<float>(std::atof(e)); }
|
||||
if (eo.skip_tau > 0.0f) std::printf("expert skip: tau %.3f (NOT exact: routed experts below that share of a token's routing weight are dropped at decode)\n", eo.skip_tau);
|
||||
if (tiered && plan.kv_rows > 0 && o.regrow()) { eo.scratch_regrow = true; eo.decode_rows = o.decode_rows_opt; } // the plan counted decode_rows rows of scratch only
|
||||
eo.lookahead = o.lookahead || o.coverage || (tiered && plan.prefetch);
|
||||
if (tiered) { eo.lookahead_ks = (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1); eo.lookahead_stats = o.lookahead; }
|
||||
if (tiered) { eo.lookahead_ks = la_ks_env >= 0 ? la_ks_env : (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1); eo.lookahead_stats = o.lookahead; }
|
||||
eo.lookahead_group_mask = !o.la_nomask;
|
||||
eo.kda_chunked = !o.kda_seq;
|
||||
eo.profile = o.profile;
|
||||
@@ -1384,6 +1412,7 @@ int cmd_run(const RunOpts& o_in) {
|
||||
else if (part == "kdaseq") e2.kda_chunked = false;
|
||||
else if (part == "nt2" || part == "nt4") gpu::g_w2_nt = part[2] - '0'; // AMD trunk GEMM: 32 / 64 tokens per block
|
||||
else if (part == "etn1" || part == "etn2") gpu::g_w2_etn = part[3] - '0'; // AMD experts: tiles of 16 / 32 pairs
|
||||
else if (part == "pack0" || part == "pack1") gpu::g_w2_pack = part[4] - '0'; // AMD trunk GEMM from a coalesced repack of the S8 weights off / on
|
||||
else if (part == "hx" || part == "nohx") e2.mla_hipx = part == "hx"; // expanded-form WMMA MLA on / off
|
||||
else if (part == "ttc" || part == "nottc") e2.tier_grouped = part == "ttc"; // grouped tensor-core experts in the tiers on / off
|
||||
else if (part == "span" || part == "nospan") { o2.span = part == "span"; o2.no_span = part == "nospan"; } // layer-major prefill on / off
|
||||
@@ -1671,6 +1700,7 @@ int main(int argc, char** argv) {
|
||||
else if (a == "--logits-rows") o.logits_rows_opt = std::atoi(nx().c_str());
|
||||
else if (a == "--kv-init") o.kv_init_opt = std::atoi(nx().c_str());
|
||||
else if (a == "--regrow") { const std::string v = nx(); o.regrow_opt = (v == "on" || v == "1") ? 1 : 0; }
|
||||
else if (a == "--skip-tau") o.skip_tau = static_cast<float>(std::atof(nx().c_str())); // dynamic expert skip, opt-in, NOT exact (see EngineOptions::skip_tau)
|
||||
else if (a == "--decode-rows") o.decode_rows_opt = std::max(1, std::atoi(nx().c_str()));
|
||||
else if (a == "--device") o.device = std::atoi(nx().c_str());
|
||||
else if (a == "--topk") o.topk = std::atoi(nx().c_str());
|
||||
@@ -1782,6 +1812,12 @@ int main(int argc, char** argv) {
|
||||
const char* ev = std::getenv("STRATA_L32_MLA_EXPANDED"); // =0: back to the absorbed form without a rebuild
|
||||
if (!(ev && ev[0] == '0')) { o.mla_expanded = true; o.mla_exp_min_n = 1024; }
|
||||
}
|
||||
#if defined(STRATA_USE_SYCL)
|
||||
if (!o.mla_prefill_set && !o.mla_expanded) { // Intel Battlemage (XMX): the expanded-form MLA prefill (joint_matrix, hi/lo fp16 splits, about fp32) for every prefill chunk; the absorbed original kernel is far slower there
|
||||
const char* ev = std::getenv("STRATA_L32_MLA_EXPANDED"); // =0: back to the absorbed form without a rebuild
|
||||
if (!(ev && ev[0] == '0') && gpu::mla_exp_ok(128, 64, 128, 512)) { o.mla_expanded = true; o.mla_exp_min_n = 32; }
|
||||
}
|
||||
#endif
|
||||
#if defined(STRATA_USE_HIP)
|
||||
{ // gfx12: the expanded-form WMMA MLA for prefill chunks is the default (owner decision 2026-12-02, after the R9700 goldens); gfx11 and the other AMD cards keep the absorbed kernel
|
||||
cudaDeviceProp dpx{};
|
||||
|
||||
@@ -51,7 +51,21 @@ public:
|
||||
|
||||
bool encode(const PreparedImage& im, std::vector<float>& out, std::string& err, double* ms = nullptr) {
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const bool ok = cpu_ ? vision_encode_cpu(*cpu_, im, out, err, o_.threads) : gpu_->encode(im, out, err, nullptr, &gpu_stats_);
|
||||
bool ok;
|
||||
if (cpu_) {
|
||||
ok = vision_encode_cpu(*cpu_, im, out, err, o_.threads);
|
||||
} else {
|
||||
std::string gerr;
|
||||
ok = gpu_->encode(im, out, gerr, nullptr, &gpu_stats_);
|
||||
if (!ok) { // the GPU encoder refuses a picture that does not fit in the free device memory (or fails): this picture goes to the CPU encoder, the next one tries the GPU again
|
||||
std::fprintf(stderr, "[vision] GPU encoder: %s; using the CPU encoder for this picture\n", gerr.c_str());
|
||||
if (!cpu_fb_) {
|
||||
cpu_fb_.reset(new VisionWeights);
|
||||
if (!cpu_fb_->load(o_.file, err)) { cpu_fb_.reset(); return false; }
|
||||
}
|
||||
ok = vision_encode_cpu(*cpu_fb_, im, out, err, o_.threads);
|
||||
}
|
||||
}
|
||||
if (ms) *ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
|
||||
return ok;
|
||||
}
|
||||
@@ -61,6 +75,7 @@ private:
|
||||
VisionCfg cfg_;
|
||||
std::string backend_;
|
||||
std::unique_ptr<VisionWeights> cpu_;
|
||||
std::unique_ptr<VisionWeights> cpu_fb_; // host weights of the CPU fallback of a GPU encoder (loaded on the first picture that needs it)
|
||||
std::unique_ptr<VisionGpu> gpu_;
|
||||
VisionGpuStats gpu_stats_;
|
||||
};
|
||||
|
||||
@@ -246,6 +246,141 @@ __global__ void __launch_bounds__(128) gemm_sk_w2_kernel(const uint8_t* __restri
|
||||
}
|
||||
}
|
||||
|
||||
// ---- coalesced repack of the S8 trunk weights (STRATA_L32_W2_PACK=1, tc-mode 2): the S8_K matrix (a 262-byte superblock per row: fp16 D, 4 group-scale bytes, 256 q) is rewritten, per GEMM call, into a scratch laid
|
||||
// out for the A fragments, so that one 16-byte load per lane (512 contiguous bytes per wave) delivers two k16 steps, and the 32 group scales (float, Dh * u / 255 computed by the same expression as the unpacked kernel) of a
|
||||
// superblock's 32 rows are consecutive. Per 32-row wave tile and superblock: q part 8192 bytes at [(s2 * 2 + t) * 512 + lane * 16 + sub * 8] (k16 step 2 s2 + sub, row tile t, lane = 16 h + row of the tile; the 8 bytes
|
||||
// are q bytes 16 (2 s2 + sub) + 8 h ..+7 of the row); scale part 4 groups x 32 floats [g * 32 + row of the wave tile]. Same bytes, same fragments, same arithmetic: bit-identical to w2_core.
|
||||
constexpr size_t kW2PackBytes = static_cast<size_t>(128) << 20; // scratch per stream; a matrix larger than this goes through in row blocks
|
||||
|
||||
__global__ void __launch_bounds__(256) w2_pack_q_kernel(const uint8_t* __restrict__ W, int rows, int nsb, int row0, int nrows_pad, uint8_t* __restrict__ dst) {
|
||||
const size_t gid = static_cast<size_t>(blockIdx.x) * 256 + threadIdx.x;
|
||||
if (gid >= static_cast<size_t>(nrows_pad / 32) * nsb * 1024) return;
|
||||
const int q8 = static_cast<int>(gid & 1023);
|
||||
const size_t blk = gid >> 10;
|
||||
const int sb = static_cast<int>(blk % nsb), wt = static_cast<int>(blk / nsb);
|
||||
const int sub = q8 & 1, l = (q8 >> 1) & 31, st = q8 >> 6, t = st & 1, s2 = st >> 1;
|
||||
const int s = 2 * s2 + sub, h = l >> 4, r16 = l & 15;
|
||||
int row = row0 + wt * 32 + t * 16 + r16;
|
||||
if (row >= rows) row = rows - 1;
|
||||
const uint8_t* src = W + (static_cast<size_t>(row) * nsb + sb) * 262 + 6 + 8 * (2 * s + h);
|
||||
uint2 v;
|
||||
v.x = w2_ldu32(src);
|
||||
v.y = w2_ldu32(src + 4);
|
||||
reinterpret_cast<uint2*>(dst)[gid] = v;
|
||||
}
|
||||
|
||||
__global__ void __launch_bounds__(256) w2_pack_eff_kernel(const uint8_t* __restrict__ W, int rows, int nsb, int row0, int nrows_pad, float* __restrict__ dst) {
|
||||
const size_t gid = static_cast<size_t>(blockIdx.x) * 256 + threadIdx.x;
|
||||
if (gid >= static_cast<size_t>(nrows_pad / 32) * nsb * 128) return;
|
||||
const int rl = static_cast<int>(gid & 31), g = static_cast<int>((gid >> 5) & 3);
|
||||
const size_t blk = gid >> 7;
|
||||
const int sb = static_cast<int>(blk % nsb), wt = static_cast<int>(blk / nsb);
|
||||
int row = row0 + wt * 32 + rl;
|
||||
if (row >= rows) row = rows - 1;
|
||||
const uint8_t* b = W + (static_cast<size_t>(row) * nsb + sb) * 262;
|
||||
const float Dh = __half2float(__ushort_as_half(static_cast<unsigned short>(b[0] | (b[1] << 8))));
|
||||
dst[gid] = group_scale<8>(b, Dh, g);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ wfrag_t w2_afrag_q8(uint32_t x, uint32_t y) {
|
||||
uint4 r;
|
||||
w2_ints4<8>(x, r.x, r.y);
|
||||
w2_ints4<8>(y, r.z, r.w);
|
||||
wfrag_t f;
|
||||
__builtin_memcpy(&f, &r, 16);
|
||||
return f;
|
||||
}
|
||||
|
||||
// qp / effp: the repacked block of rows_blk rows (out is already offset to its first row)
|
||||
__global__ void __launch_bounds__(128) gemm_sk_w2p_kernel(const uint8_t* __restrict__ qp, const float* __restrict__ effp, int rows_blk, int K, const __half* __restrict__ xh, const __half* __restrict__ xl,
|
||||
const float* __restrict__ isc, int N, float* __restrict__ out, int out_stride, int accumulate) {
|
||||
constexpr int NT = 4;
|
||||
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, h = lane >> 4;
|
||||
const int wt = blockIdx.x * kW2Waves + warp;
|
||||
const int row0 = wt * 32;
|
||||
if (row0 >= rows_blk) return;
|
||||
const int tok0 = blockIdx.y * 64;
|
||||
const int ntv = min(NT, (N - tok0 + 15) >> 4);
|
||||
const size_t dl = static_cast<size_t>(xl - xh);
|
||||
const __half* xrow[NT];
|
||||
const float* iscrow[NT];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < NT; ++nt) {
|
||||
const int tk = tok0 + nt * 16 + (lane & 15);
|
||||
xrow[nt] = xh + static_cast<size_t>(tk < N ? tk : N - 1) * K;
|
||||
iscrow[nt] = isc + static_cast<size_t>(tk < N ? tk : N - 1) * (K >> 6);
|
||||
}
|
||||
const int nsb = K >> 8;
|
||||
wacc_t tot[2][NT];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 2; ++t)
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < NT; ++nt) tot[t][nt] = wacc_t{0, 0, 0, 0, 0, 0, 0, 0};
|
||||
for (int sb = 0; sb < nsb; ++sb) {
|
||||
const uint8_t* qb = qp + (static_cast<size_t>(wt) * nsb + sb) * 8192 + lane * 16;
|
||||
const float* eb = effp + (static_cast<size_t>(wt) * nsb + sb) * 128;
|
||||
#pragma unroll 1
|
||||
for (int g = 0; g < 4; ++g) {
|
||||
wacc_t cg[2][NT];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 2; ++t)
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < NT; ++nt) cg[t][nt] = wacc_t{0, 0, 0, 0, 0, 0, 0, 0};
|
||||
#pragma unroll
|
||||
for (int sp = 0; sp < 2; ++sp) {
|
||||
const int s2 = g * 2 + sp;
|
||||
const uint4 v0 = *reinterpret_cast<const uint4*>(qb + (s2 * 2 + 0) * 512), v1 = *reinterpret_cast<const uint4*>(qb + (s2 * 2 + 1) * 512);
|
||||
#pragma unroll
|
||||
for (int sub = 0; sub < 2; ++sub) {
|
||||
const wfrag_t a0 = sub ? w2_afrag_q8(v0.z, v0.w) : w2_afrag_q8(v0.x, v0.y);
|
||||
const wfrag_t a1 = sub ? w2_afrag_q8(v1.z, v1.w) : w2_afrag_q8(v1.x, v1.y);
|
||||
const int k0 = sb * 256 + g * 64 + (sp * 2 + sub) * 16;
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < NT; ++nt) {
|
||||
if (nt < ntv) {
|
||||
const __half* p = xrow[nt] + k0;
|
||||
const wfrag_t bh = wmma_load(p, lane), bl = wmma_load(p + dl, lane);
|
||||
wacc_t c0 = wmma_f16(a0, bh, wacc_t{0, 0, 0, 0, 0, 0, 0, 0}), c1 = wmma_f16(a1, bh, wacc_t{0, 0, 0, 0, 0, 0, 0, 0});
|
||||
c0 = wmma_f16(a0, bl, c0);
|
||||
c1 = wmma_f16(a1, bl, c1);
|
||||
cg[0][nt] = cg[0][nt] + c0;
|
||||
cg[1][nt] = cg[1][nt] + c1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 2; ++t) {
|
||||
const float4* e4 = reinterpret_cast<const float4*>(eb + g * 32 + t * 16 + h * 8);
|
||||
const float4 e0 = e4[0], e1 = e4[1];
|
||||
const float eff[8] = {e0.x, e0.y, e0.z, e0.w, e1.x, e1.y, e1.z, e1.w};
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < NT; ++nt) {
|
||||
const float is = nt < ntv ? iscrow[nt][sb * 4 + g] : 1.0f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) tot[t][nt][i] += (eff[i] * is) * cg[t][nt][i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < NT; ++nt) {
|
||||
const int tk = tok0 + nt * 16 + (lane & 15);
|
||||
if (nt < ntv && tk < N) {
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 2; ++t)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const int r = row0 + t * 16 + wmma_row_of(i, lane);
|
||||
if (r < rows_blk) {
|
||||
float* o = out + static_cast<size_t>(tk) * out_stride + r;
|
||||
*o = accumulate ? *o + tot[t][nt][i] : tot[t][nt][i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Routed experts of a token batch, grouped by expert (tile = one expert, up to 16 pairs). DN: the activation rows are the pairs themselves (act [P][K]), else the token of the pair (x [N][K], token = pair / top_k).
|
||||
// xh / xl / xm: the split activations; out [P][rows].
|
||||
template <int CODE, bool DN, int MODE, int NT>
|
||||
@@ -317,6 +452,16 @@ static std::mutex& w2_mu() { static std::mutex m; return m; }
|
||||
|
||||
static size_t w2_scratch_halves(size_t cap) { return 3 * cap + cap / 32 + 64; } // hi | lo | mid | the inverse group scales (floats, one per 64 values)
|
||||
|
||||
static std::map<cudaStream_t, uint8_t*>& w2p_map() { static std::map<cudaStream_t, uint8_t*> m; return m; }
|
||||
|
||||
// the repack scratch of a stream (kW2PackBytes, allocated once; nullptr if the card has no room: the launch then takes the unpacked kernel)
|
||||
static uint8_t* w2p_scratch(cudaStream_t s) {
|
||||
std::lock_guard<std::mutex> lk(w2_mu());
|
||||
uint8_t*& p = w2p_map()[s];
|
||||
if (!p && cudaMalloc(reinterpret_cast<void**>(&p), kW2PackBytes) != cudaSuccess) p = nullptr;
|
||||
return p;
|
||||
}
|
||||
|
||||
template <int MODE>
|
||||
static const __half* w2_split_impl(const float* x, size_t rows_n, int K, cudaStream_t s, size_t* dl, size_t* dm) {
|
||||
const size_t per = rows_n * K;
|
||||
@@ -343,6 +488,24 @@ template <int CODE, int MODE>
|
||||
static void launch_w2(const uint8_t* W, int rows, int K, const float* x, int N, float* out, int out_stride, bool accumulate, cudaStream_t s) {
|
||||
size_t dl, dm;
|
||||
const __half* xh = w2_split_impl<MODE>(x, static_cast<size_t>(N), K, s, &dl, &dm);
|
||||
if constexpr (CODE == 8) {
|
||||
if (g_w2_pack > 0 && g_w2_nt >= 4 && MODE == 2 && N >= 128) { // S8 trunk matrices: repack the weights into the fragment layout, then the packed GEMM (row blocks if the repack exceeds the scratch)
|
||||
uint8_t* scr = w2p_scratch(s);
|
||||
if (scr) {
|
||||
const int nsb = K >> 8;
|
||||
const int rb = static_cast<int>(kW2PackBytes / (static_cast<size_t>(nsb) * 320) / 32 * 32);
|
||||
for (int r0 = 0; r0 < rows; r0 += rb) {
|
||||
const int nr = std::min(rb, rows - r0), nrp = (nr + 31) / 32 * 32;
|
||||
float* effp = reinterpret_cast<float*>(scr + static_cast<size_t>(nrp) * nsb * 256);
|
||||
w2_pack_q_kernel<<<static_cast<unsigned>((static_cast<size_t>(nrp / 32) * nsb * 1024 + 255) / 256), 256, 0, s>>>(W, rows, nsb, r0, nrp, scr);
|
||||
w2_pack_eff_kernel<<<static_cast<unsigned>((static_cast<size_t>(nrp / 32) * nsb * 128 + 255) / 256), 256, 0, s>>>(W, rows, nsb, r0, nrp, effp);
|
||||
const dim3 grid((nrp / 32 + kW2Waves - 1) / kW2Waves, (N + 63) / 64);
|
||||
gemm_sk_w2p_kernel<<<grid, 128, 0, s>>>(scr, effp, nr, K, xh, xh + dl, reinterpret_cast<const float*>(xh + 3 * dl), N, out + r0, out_stride, accumulate ? 1 : 0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (g_w2_nt >= 4) { // 64 tokens per block: every decoded weight fragment feeds twice the WMMAs (gfx12 only by default)
|
||||
const dim3 grid((rows + kW2Rows * kW2Waves - 1) / (kW2Rows * kW2Waves), (N + 63) / 64);
|
||||
gemm_sk_w2_kernel<CODE, MODE, 4><<<grid, 128, 0, s>>>(W, rows, K, xh, xh + dl, (MODE & 1) ? xh + dm : nullptr, reinterpret_cast<const float*>(xh + 3 * dl), N, out, out_stride, accumulate ? 1 : 0);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
# ab_env.sh PAIRS PROMPT BIN "ENV_A" "ENV_B": interleaved A / B of the 1 / 2 / 3 / 4 / 6 / 8-row step times in ms (--bench-rows, after a PROMPT-token prompt, ctx 131072, chunk 4096; the metric is the 1-row step, smaller is faster),
|
||||
# one binary, two environment settings (e.g. "L32_GEMV_UB=1" and "L32_GEMV_UB=4"; kernels are compiled at run time with the setting). Call it through l32run.sh (GPU lock) / bg_run3.sh.
|
||||
PAIRS=$1; TOK=$2; BIN=$3; EA=$4; EB=$5
|
||||
M=$HOME/strata-mac/ling32/models/Ling-3.2-Air-SQ-96.strata
|
||||
ra=(); rb=()
|
||||
for i in $(seq 1 $PAIRS); do
|
||||
for w in A B; do
|
||||
if [ $w = A ]; then e=$EA; else e=$EB; fi
|
||||
out=$(env $e $BIN --model $M --ctx 131072 --chunk 4096 --bench-prompt $TOK --gen 64 --reps 2 --bench-rows 1 2>&1)
|
||||
r=$(echo "$out" | grep "^rows" | sed 's/rows \([0-9]*\): \([0-9.]*\) ms.*/\1=\2/' | tr '\n' ' ')
|
||||
v=$(echo "$out" | grep "^rows 1:" | sed 's/rows 1: \([0-9.]*\) ms.*/\1/') # metric: ms of the 1-row step (smaller is faster)
|
||||
echo "pair $i $w ($e): 1-row step $v ms; rows $r"
|
||||
if [ $w = A ]; then ra+=($v); else rb+=($v); fi
|
||||
done
|
||||
done
|
||||
echo "A: ${ra[*]}"
|
||||
echo "B: ${rb[*]}"
|
||||
echo "${ra[*]}" | tr ' ' '\n' | sort -n | awk '{a[NR]=$1} END {printf "median A %s ", a[int((NR+1)/2)]}'
|
||||
echo "${rb[*]}" | tr ' ' '\n' | sort -n | awk '{a[NR]=$1} END {printf "median B %s\n", a[int((NR+1)/2)]}'
|
||||
n=0; for i in $(seq 0 $((PAIRS - 1))); do if awk -v x="${rb[$i]}" -v y="${ra[$i]}" 'BEGIN {exit !(x < y)}'; then n=$((n + 1)); fi; done
|
||||
echo "B faster in $n of $PAIRS pairs"
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
# decode_budget.sh: the data of the decode budget at the launcher's default maximum context (ctx 131072), after a 512-token prompt (a chat) and a 4000-token prompt (documents):
|
||||
# 1. the time of a verify-shaped step with 1..8 rows (weights read once, logits of every row): --bench-rows
|
||||
# 2. the per-dispatch profile of one KDA layer and one MLA layer of the decode step (N = 1), each dispatch alone in its own command buffer
|
||||
# Run through bg_run3.sh on m1002 (about 5 minutes).
|
||||
S=$HOME/strata-mac/ling32
|
||||
B=$S/bin/ling32-metal
|
||||
M=$S/models/Ling-3.2-Air-SQ-96.strata
|
||||
for P in 512 4000; do
|
||||
echo "=== rows benchmark, ctx 131072, prompt $P"
|
||||
$B --model $M --ctx 131072 --chunk 4096 --bench-prompt $P --bench-rows 1 2>&1 | grep -E "^rows"
|
||||
done
|
||||
echo "=== per-dispatch profile of the decode step, ctx 131072, prompt 512"
|
||||
$B --model $M --ctx 131072 --chunk 4096 --bench-prompt 512 --gen 2 --reps 1 --profile 2>&1 | grep -E "^\[layer [35]|^ [a-z_0-9]+ +[0-9.]+ us|^ sum |^prefill [0-9]" | head -60 | cut -c1-110
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
# gold_bitcmp.sh ONLY_IDS ENV_A ENV_B [engine args...]: (Windows, Git Bash) runs the golden jobs ONLY_IDS on m1002 twice (detached, bg_run3.sh, timeout 1500 s each) with the environment ENV_A (jobs cbA) and ENV_B (jobs cbB), then prints
|
||||
# the golden_compare table of each and whether the two output folders are byte-identical (cmp of every file). For changes that must be bit-identical.
|
||||
ONLY=$1; EA=$2; EB=$3; shift 3; EXTRA="$*"
|
||||
D=/c/w-ling32-metal/engine/src/ling32/metal
|
||||
run() { # name env
|
||||
ssh m1002 "S=~/strata-mac/ling32; $2 TMO=1500 bash \$S/bg_run3.sh $1 bash \$S/goldrun.sh $1 $ONLY $EXTRA" > /dev/null
|
||||
until ssh -o ConnectTimeout=20 m1002 "grep -qE '^bg-done|^bg-timeout' ~/strata-mac/ling32/logs/bg-$1.log" 2>/dev/null; do sleep 15; done
|
||||
ssh m1002 "tail -2 ~/strata-mac/ling32/logs/bg-$1.log" | grep -E "bg-done|bg-timeout"
|
||||
bash $D/goldcmp.sh $1 2>&1 | grep -E "^ALL|^long_|^id " | cut -c1-200
|
||||
}
|
||||
echo "== A: $EA"; run cbA "$EA"
|
||||
echo "== B: $EB"; run cbB "$EB"
|
||||
ssh m1002 'S=~/strata-mac/ling32; n=0; d=0; for f in $(cd $S/out/cbA && find . -type f); do n=$((n+1)); cmp -s $S/out/cbA/$f $S/out/cbB/$f || { d=$((d+1)); echo "differs: $f"; }; done; echo "files $n, different $d"'
|
||||
@@ -591,6 +591,33 @@ kernel void mla_qabs(device const float* q [[buffer(0)]], device const ushort* w
|
||||
for (int d = 0; d < L32_NOPE; ++d) acc += qs[d] * bf16f_(wk[((ulong)h * L32_NOPE + d) * L32_KVL + k]);
|
||||
qabs[(ulong)th * L32_KVL + k] = acc;
|
||||
}
|
||||
// the same for decode / verify rows (N <= 4): one simdgroup per (row x head, tile of 128 latent dims), 4 consecutive latent dims per lane (one 8-byte load per weight row), the weight loads of 8 rows in flight;
|
||||
// every output dimension keeps its own sequential sum over the 128 nope dims: bit-identical. grid (N*H, KVL/128), 32 threads
|
||||
kernel void mla_qabs_d(device const float* q [[buffer(0)]], device const ushort* wk [[buffer(1)]], device float* qabs [[buffer(2)]],
|
||||
device const int* d_pos0 [[buffer(3)]], constant int& absmin [[buffer(4)]], constant int& Nq [[buffer(5)]],
|
||||
uint2 gid [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
|
||||
if (*d_pos0 + Nq <= absmin) return;
|
||||
const int th = int(gid.x), h = th % L32_H;
|
||||
threadgroup float qs[L32_NOPE];
|
||||
for (int d = int(tid); d < L32_NOPE; d += 32) qs[d] = q[(ulong)th * (L32_NOPE + L32_ROPE) + d];
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
const int k = int(gid.y) * 128 + int(tid) * 4;
|
||||
float4 acc = float4(0.0f);
|
||||
for (int d0 = 0; d0 < L32_NOPE; d0 += 8) {
|
||||
ushort4 w[8];
|
||||
#pragma unroll
|
||||
for (int u = 0; u < 8; ++u) w[u] = *(device const ushort4*)(wk + ((ulong)h * L32_NOPE + d0 + u) * L32_KVL + k);
|
||||
#pragma unroll
|
||||
for (int u = 0; u < 8; ++u) {
|
||||
const float qv = qs[d0 + u];
|
||||
acc.x += qv * bf16f_(w[u].x);
|
||||
acc.y += qv * bf16f_(w[u].y);
|
||||
acc.z += qv * bf16f_(w[u].z);
|
||||
acc.w += qv * bf16f_(w[u].w);
|
||||
}
|
||||
}
|
||||
*(device float4*)(qabs + (ulong)th * L32_KVL + k) = acc;
|
||||
}
|
||||
// combine the splits: ctx[th][k] = sum_s acc_s[k] e^(m_s - M) / sum_s l_s e^(m_s - M). grid N*H, 256 threads
|
||||
kernel void mla_attn_combine(device const float* part [[buffer(0)]], device float* ctx [[buffer(1)]], constant int& S [[buffer(2)]], device const int* d_pos0 [[buffer(3)]],
|
||||
constant int& reg_lo [[buffer(4)]], constant int& reg_hi [[buffer(5)]], constant int& kc [[buffer(6)]], uint th [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
|
||||
@@ -862,6 +889,81 @@ kernel void add_rmsnorm(device float* x [[buffer(0)]], device const float* dlt [
|
||||
}
|
||||
}
|
||||
|
||||
// The same two kernels with 1024 threads per row (4 of the 16 element slots per thread: the latency chain of loads is 4x shorter, the row's threadgroup fills a whole core). The result is BIT-IDENTICAL to the 256-thread kernels:
|
||||
// the per-slot values go through threadgroup memory and the first 256 threads sum their 16 slots in the original order, then the same simdgroup / 8-partial reduction.
|
||||
constexpr constant int NW_ = (NV_ + 3) / 4; // slots per thread: thread q (0..3) of a column takes the slots q, q + 4, ... below NV_ (L32_D = 2560: NV_ = 10 slots)
|
||||
inline float rms_tail_w(threadgroup float* xs, threadgroup float* sm, uint tid) {
|
||||
if (tid < 256) {
|
||||
float ss = 0.0f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NV_; ++j) { const float v = xs[j * 256 + tid]; ss += v * v; }
|
||||
ss = simd_sum(ss);
|
||||
if ((tid & 31) == 0) sm[tid >> 5] = ss;
|
||||
}
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
float r = 0.0f;
|
||||
for (uint i = 0; i < 8; ++i) r += sm[i];
|
||||
return 1.0f / sqrt(r / float(L32_D) + L32_EPS);
|
||||
}
|
||||
kernel void moe_combine_norm_w(device float* x [[buffer(0)]], device const float* ye [[buffer(1)]], device const float* w [[buffer(2)]], device const float* ysh [[buffer(3)]],
|
||||
device const float* gamma [[buffer(4)]], device float* y [[buffer(5)]], constant int& has_norm [[buffer(6)]], device const int* posmap [[buffer(7)]], constant int& use_pos [[buffer(8)]],
|
||||
uint t [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
|
||||
threadgroup float xs[NV_ * 256];
|
||||
threadgroup float sm[8];
|
||||
const int t0 = int(tid) & 255, q = int(tid) >> 8;
|
||||
float xv[NW_];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NW_; ++i) {
|
||||
const int j = q + 4 * i;
|
||||
if (j >= NV_) break;
|
||||
const int d = t0 + j * 256;
|
||||
float s = 0.0f;
|
||||
for (int k = 0; k < L32_TOPK; ++k) s += w[t * L32_TOPK + k] * ye[(ulong)(use_pos ? posmap[t * L32_TOPK + k] : (t * L32_TOPK + k)) * L32_D + d];
|
||||
const ulong at = (ulong)t * L32_D + d;
|
||||
const float v = (x[at] + ysh[at]) + s;
|
||||
x[at] = v;
|
||||
xv[i] = v;
|
||||
xs[j * 256 + t0] = v;
|
||||
}
|
||||
if (!has_norm) return;
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
const float r = rms_tail_w(xs, sm, tid);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NW_; ++i) {
|
||||
const int j = q + 4 * i;
|
||||
if (j >= NV_) break;
|
||||
const int d = t0 + j * 256;
|
||||
y[(ulong)t * L32_D + d] = xv[i] * r * gamma[d];
|
||||
}
|
||||
}
|
||||
kernel void add_rmsnorm_w(device float* x [[buffer(0)]], device const float* dlt [[buffer(1)]], device const float* gamma [[buffer(2)]], device float* y [[buffer(3)]],
|
||||
constant int& has_d [[buffer(4)]], uint t [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
|
||||
threadgroup float xs[NV_ * 256];
|
||||
threadgroup float sm[8];
|
||||
const int t0 = int(tid) & 255, q = int(tid) >> 8;
|
||||
float xv[NW_];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NW_; ++i) {
|
||||
const int j = q + 4 * i;
|
||||
if (j >= NV_) break;
|
||||
const int d = t0 + j * 256;
|
||||
const ulong at = (ulong)t * L32_D + d;
|
||||
const float v = has_d ? x[at] + dlt[at] : x[at];
|
||||
if (has_d) x[at] = v;
|
||||
xv[i] = v;
|
||||
xs[j * 256 + t0] = v;
|
||||
}
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
const float r = rms_tail_w(xs, sm, tid);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NW_; ++i) {
|
||||
const int j = q + 4 * i;
|
||||
if (j >= NV_) break;
|
||||
const int d = t0 + j * 256;
|
||||
y[(ulong)t * L32_D + d] = xv[i] * r * gamma[d];
|
||||
}
|
||||
}
|
||||
|
||||
kernel void copy_row_k(device const float* src [[buffer(0)]], device float* dst [[buffer(1)]], constant int& n [[buffer(2)]], uint i [[thread_position_in_grid]]) {
|
||||
if (int(i) < n) dst[i] = src[i];
|
||||
}
|
||||
|
||||
@@ -332,6 +332,82 @@ kernel void alflb_route2(device const float* logits [[buffer(0)]], device const
|
||||
}
|
||||
}
|
||||
|
||||
// The same router with 1024 threads per token (decode / verify rows): the group selection by rank (8 threads instead of one serial loop: the same groups in the same order, ties to the lower index), and the candidate ranks counted by four
|
||||
// threads each over a quarter of the candidates (integer counts: any order is exact). Requires NCAND = 256. Same results as alflb_route2.
|
||||
kernel void alflb_route2w(device const float* logits [[buffer(0)]], device const float* sel_bias [[buffer(1)]], device int* out_idx [[buffer(2)]], device float* out_w [[buffer(3)]],
|
||||
uint t [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
|
||||
constexpr int E = L32_E, per = L32_E / L32_NGROUP, top_n = L32_TOPK, NCAND = L32_TOPKG * (L32_E / L32_NGROUP);
|
||||
static_assert(NCAND == 256, "alflb_route2w needs 256 candidates");
|
||||
threadgroup float sig[E], sc[E];
|
||||
threadgroup float4 scc4[NCAND / 4];
|
||||
threadgroup int4 eid4[NCAND / 4];
|
||||
threadgroup float* scc = (threadgroup float*)scc4;
|
||||
threadgroup int* eid = (threadgroup int*)eid4;
|
||||
threadgroup int chosen[L32_TOPK], glist[L32_NGROUP], rpart[4 * NCAND];
|
||||
threadgroup float gscore[L32_NGROUP];
|
||||
device const float* lg = logits + (ulong)t * E;
|
||||
const uint lane = tid & 31, warp = tid >> 5;
|
||||
for (int e = int(tid); e < E; e += 1024) {
|
||||
sig[e] = sigmoidf_(lg[e]);
|
||||
sc[e] = sig[e] + sel_bias[e];
|
||||
}
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
for (int g = int(warp); g < L32_NGROUP; g += 32) {
|
||||
float m1 = -FLT_MAX, m2 = -FLT_MAX;
|
||||
for (int i = int(lane); i < per; i += 32) {
|
||||
const float vv = sc[g * per + i];
|
||||
if (vv > m1) { m2 = m1; m1 = vv; } else if (vv > m2) m2 = vv;
|
||||
}
|
||||
for (ushort o = 16; o >= 1; o >>= 1) {
|
||||
const float b1 = simd_shuffle_xor(m1, o), b2 = simd_shuffle_xor(m2, o);
|
||||
const float n1 = max(m1, b1);
|
||||
m2 = max(min(m1, b1), max(m2, b2));
|
||||
m1 = n1;
|
||||
}
|
||||
if (lane == 0) gscore[g] = m1 + m2;
|
||||
}
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
if (tid < L32_NGROUP) { // the k-th kept group is the one with k groups ahead of it (a higher score, or the same score and a lower index)
|
||||
int r = 0;
|
||||
for (int g2 = 0; g2 < L32_NGROUP; ++g2) r += (gscore[g2] > gscore[tid] || (gscore[g2] == gscore[tid] && g2 < int(tid))) ? 1 : 0;
|
||||
if (r < L32_TOPKG) glist[r] = int(tid);
|
||||
}
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
if (tid < NCAND) {
|
||||
const int e = glist[tid / per] * per + int(tid) % per;
|
||||
eid[tid] = e;
|
||||
scc[tid] = sc[e];
|
||||
}
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
{
|
||||
const int c = int(tid) & (NCAND - 1), q = int(tid) / NCAND;
|
||||
const float vv = scc[c];
|
||||
const int e = eid[c];
|
||||
int r = 0;
|
||||
for (int f = q * (NCAND / 16); f < (q + 1) * (NCAND / 16); ++f) {
|
||||
const float4 sv = scc4[f];
|
||||
const int4 ev = eid4[f];
|
||||
r += (sv.x > vv || (sv.x == vv && ev.x < e)) ? 1 : 0;
|
||||
r += (sv.y > vv || (sv.y == vv && ev.y < e)) ? 1 : 0;
|
||||
r += (sv.z > vv || (sv.z == vv && ev.z < e)) ? 1 : 0;
|
||||
r += (sv.w > vv || (sv.w == vv && ev.w < e)) ? 1 : 0;
|
||||
}
|
||||
rpart[q * NCAND + c] = r;
|
||||
}
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
if (tid < NCAND) {
|
||||
const int r = rpart[tid] + rpart[NCAND + tid] + rpart[2 * NCAND + tid] + rpart[3 * NCAND + tid];
|
||||
if (r < top_n) chosen[r] = eid[tid];
|
||||
}
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
if (int(tid) < top_n) {
|
||||
float tot = 0.0f;
|
||||
for (int i = 0; i < top_n; ++i) tot += sig[chosen[i]];
|
||||
out_idx[(ulong)t * top_n + tid] = chosen[tid];
|
||||
out_w[(ulong)t * top_n + tid] = sig[chosen[tid]] * (L32_SCALE / (tot + 1e-20f));
|
||||
}
|
||||
}
|
||||
|
||||
// split-K attention for FOUR heads per threadgroup: every cache row is read once for the four queries (the rows are the same for all heads). grid (N, H / 4, S), 256 threads, kc <= 256
|
||||
kernel void mla_attn_part4(device const float* qabs [[buffer(0)]], device const float* q [[buffer(1)]], device const float* cache [[buffer(2)]], device const int* d_pos0 [[buffer(3)]],
|
||||
device float* part [[buffer(4)]], constant float& scale [[buffer(5)]], constant int& S [[buffer(6)]], constant int& kc [[buffer(7)]], constant int& reg_lo [[buffer(8)]], constant int& reg_hi [[buffer(9)]],
|
||||
|
||||
@@ -504,8 +504,11 @@ struct Engine {
|
||||
void add(const std::string& kernel, std::vector<mtl::Arg> args, uint32_t gx, uint32_t gy, uint32_t gz, uint32_t tgx) {
|
||||
static const std::string skip = std::getenv("L32_SKIP_DISP") ? std::getenv("L32_SKIP_DISP") : ""; // TIMING EXPERIMENT ONLY (results are wrong): ",name1,name2," drops these dispatches from the tape
|
||||
if (!skip.empty() && skip.find("," + kernel + ",") != std::string::npos) { nb_next = false; return; }
|
||||
static const int cnw = std::getenv("L32_CNW") ? std::atoi(std::getenv("L32_CNW")) : 1; // the combine / add + norm kernels of decode and verify rows (up to 4 rows) run with 1024 threads per row instead of 256 (bit-identical result, shorter load chain: 1-row step -5.1 %); env L32_CNW=0 turns it off (1 both, 2 add only, 3 combine only)
|
||||
std::string kname = kernel;
|
||||
if (cnw && gx <= 4 && ((kernel == "add_rmsnorm" && cnw != 3) || (kernel == "moe_combine_norm" && cnw != 2))) { kname += "_w"; tgx = 1024; }
|
||||
mtl::Dispatch d;
|
||||
d.p = &E.P(kernel);
|
||||
d.p = &E.P(kname);
|
||||
d.args = std::move(args);
|
||||
d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz;
|
||||
d.tg[0] = tgx;
|
||||
@@ -601,7 +604,9 @@ struct Engine {
|
||||
NB(t, N);
|
||||
t.add("mla_prep_q", {B(R(q)), B(R(rope_tab)), B(posr.b ? posr : R(pos))}, N, H, 1, 32);
|
||||
NB(t, N);
|
||||
t.add("mla_qabs", {B(R(q)), B(ar(M.wk_b)), B(R(qabs)), B(posref), I(absmin), I(N)}, N * H, c.kv_lora / 128, 1, 128);
|
||||
static const bool qabs_d = !std::getenv("L32_QABS_D") || std::atoi(std::getenv("L32_QABS_D")) != 0; // decode / verify rows: one simdgroup per tile, 8-byte weight loads (bit-identical); L32_QABS_D=0: the plain kernel
|
||||
if (qabs_d && N <= 4) t.add("mla_qabs_d", {B(R(q)), B(ar(M.wk_b)), B(R(qabs)), B(posref), I(absmin), I(N)}, N * H, c.kv_lora / 128, 1, 32);
|
||||
else t.add("mla_qabs", {B(R(q)), B(ar(M.wk_b)), B(R(qabs)), B(posref), I(absmin), I(N)}, N * H, c.kv_lora / 128, 1, 128);
|
||||
if (N <= 16 && mla_kc > 0) { // decode / verify: split-K over the keys (32 heads alone would leave the GPU idle)
|
||||
const float asc = 1.0f / std::sqrt(float(c.nope + c.rope));
|
||||
const bool use_mmah = mla_mmah && H % 8 == 0 && H % 4 == 0 && max_ctx > mla_thr; // long contexts only: the latency of one split block (about 160 us) loses to part4 below about 8K
|
||||
@@ -664,7 +669,11 @@ struct Engine {
|
||||
NB(t, N);
|
||||
gemv(t, L.su, R(cur), N, R(u), c.I_shared, false);
|
||||
if (N > 16 && fast_f32 && route_tol > 0.0f) t.add("alflb_route2x", {B(R(rlog)), B(ar(L.gate_bias)), B(R(ridx)), B(R(rw)), B(ar(L.gate_w)), B(R(cur)), Fl(route_tol)}, N, 1, 1, 256); // near ties: exact logits
|
||||
else t.add("alflb_route2", {B(R(rlog)), B(ar(L.gate_bias)), B(R(ridx)), B(R(rw))}, N, 1, 1, 256);
|
||||
else {
|
||||
static const bool route_w = !std::getenv("L32_ROUTE_W") || std::atoi(std::getenv("L32_ROUTE_W")) != 0; // decode / verify rows (<= 4): 1024 threads per token, same selection; L32_ROUTE_W=0: the plain kernel
|
||||
if (route_w && N <= 4) t.add("alflb_route2w", {B(R(rlog)), B(ar(L.gate_bias)), B(R(ridx)), B(R(rw))}, N, 1, 1, 1024);
|
||||
else t.add("alflb_route2", {B(R(rlog)), B(ar(L.gate_bias)), B(R(ridx)), B(R(rw))}, N, 1, 1, 256);
|
||||
}
|
||||
if (trace_row >= 0) {
|
||||
const size_t base_w = size_t(il) * trace_stride() + D + c.n_exp;
|
||||
t.add("copy_u32", {B(R(ridx, size_t(trace_row) * c.top_k * 4)), B(R(trace, base_w * 4)), I(c.top_k)}, 1, 1, 1, 32);
|
||||
@@ -945,6 +954,7 @@ struct Opts {
|
||||
bool mla_ht4 = false;
|
||||
int logits_rows = 0;
|
||||
int bench_prompt = 0;
|
||||
int bench_rows = 0; // --bench-rows 1: time the multi-row decode step (1..8 rows, logits of every row) at a fixed position after the prompt
|
||||
VisionRunOpts vis; // --vision FILE --image F [--image G ...] --vision-device auto|cpu|gpu --vision-threads N --vision-max-pixels N --newline-id N (the prompt's <|image_pad|> placeholders)
|
||||
std::string mm_runs; // --mm-runs FILE: a batch of picture / text prompts in one process (run_mm_batch)
|
||||
};
|
||||
@@ -1376,6 +1386,7 @@ int main(int argc, char** argv) {
|
||||
else if (a == "--trace-pos") o.trace_pos = std::atoi(nx().c_str());
|
||||
else if (a == "--bench-gemv") o.bench_gemv = true;
|
||||
else if (a == "--bench-prompt") o.bench_prompt = std::atoi(nx().c_str());
|
||||
else if (a == "--bench-rows") o.bench_rows = std::atoi(nx().c_str());
|
||||
else if (a == "--vision") o.vis.file = nx();
|
||||
else if (a == "--image") o.vis.images.push_back(nx());
|
||||
else if (a == "--vision-device") o.vis.backend = nx(); // auto | cpu | gpu: this engine has the CPU encoder only
|
||||
@@ -1646,6 +1657,22 @@ int main(int argc, char** argv) {
|
||||
std::printf("dumped %d tokens to %s\n", N, o.dump.c_str());
|
||||
return 0;
|
||||
}
|
||||
if (o.bench_rows > 0) { // the verify-shaped step: N rows through the whole trunk (weights read once), logits of every row, timed at a fixed position (the state keeps advancing: only the time matters)
|
||||
for (size_t at = 0; at < prompt.size(); at += size_t(E.Nmax)) {
|
||||
const int len = int(std::min<size_t>(size_t(E.Nmax), prompt.size() - at));
|
||||
if (!E.forward(prompt.data() + at, len, 1, err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 1; }
|
||||
}
|
||||
std::vector<int> bids(16, 1234);
|
||||
for (int n : {1, 2, 3, 4, 6, 8}) {
|
||||
for (int w = 0; w < 5; ++w) { E.forward(bids.data(), n, n, err); E.pos_ -= n; }
|
||||
const int reps = 60;
|
||||
const double tb = now_s();
|
||||
for (int r = 0; r < reps; ++r) { E.forward(bids.data(), n, n, err); E.pos_ -= n; }
|
||||
const double ms = (now_s() - tb) * 1000.0 / reps;
|
||||
std::printf("rows %d: %.3f ms per step (logits of all rows)\n", n, ms);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (E.mtp) { // speculative greedy generation
|
||||
const int gen_n = o.gen >= 0 ? o.gen : 16;
|
||||
for (int rep = 0; rep <= o.reps; ++rep) {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
# prof_layer.sh: the per-dispatch profile of one KDA layer and one MLA layer of the decode step (N = 1, each dispatch alone in its own command buffer) at ctx 131072 after a 512-token prompt. Run through bg_run3.sh on m1002 (about 1 minute).
|
||||
S=$HOME/strata-mac/ling32
|
||||
B=$S/bin/ling32-metal
|
||||
M=$S/models/Ling-3.2-Air-SQ-96.strata
|
||||
$B --model $M --ctx 131072 --chunk 4096 --bench-prompt 512 --gen 2 --reps 1 --profile 2>&1 | grep -E "^\[layer [35]|^ [a-z_0-9]+ +[0-9.]+ us|^ sum |^prefill [0-9]" | head -60 | cut -c1-110
|
||||
@@ -21,6 +21,16 @@
|
||||
#include <sycl/sycl.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#ifdef STRATA_SY_PROFILE
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#endif
|
||||
|
||||
namespace strata::ling32::gpu::sy {
|
||||
|
||||
@@ -52,15 +62,65 @@ struct Blk {
|
||||
};
|
||||
|
||||
// Launches `f(Blk, char* smem)` on `grid` blocks of `block` threads (block % 32 == 0) with `smem` bytes of shared memory (dynamic, 16-byte aligned by the accessor).
|
||||
#ifdef STRATA_SY_PROFILE
|
||||
// per-kernel profile (profiling build only): every launch records its sycl::event under "caller:line"; the totals are printed at exit (STRATA_SY_PROF_TOP lines, default 40)
|
||||
struct ProfLog {
|
||||
std::mutex m;
|
||||
std::vector<std::pair<std::string, sycl::event>> ev;
|
||||
std::vector<int> gridsum;
|
||||
~ProfLog() {}
|
||||
};
|
||||
inline ProfLog& prof_log() { static ProfLog* p = new ProfLog(); return *p; }
|
||||
inline void prof_dump() {
|
||||
ProfLog& L = prof_log();
|
||||
std::map<std::string, std::pair<double, long>> agg;
|
||||
double total = 0;
|
||||
for (auto& e : L.ev) {
|
||||
try {
|
||||
e.second.wait();
|
||||
const double ns = static_cast<double>(e.second.get_profiling_info<sycl::info::event_profiling::command_end>() - e.second.get_profiling_info<sycl::info::event_profiling::command_start>());
|
||||
auto& a = agg[e.first]; a.first += ns; a.second += 1; total += ns;
|
||||
} catch (...) {}
|
||||
}
|
||||
std::vector<std::pair<std::string, std::pair<double, long>>> v(agg.begin(), agg.end());
|
||||
std::sort(v.begin(), v.end(), [](auto& a, auto& b) { return a.second.first > b.second.first; });
|
||||
const char* t = std::getenv("STRATA_SY_PROF_TOP");
|
||||
const size_t top = t ? static_cast<size_t>(std::atoi(t)) : 40;
|
||||
std::printf("SYPROF kernel time total %.1f ms over %zu launches\n", total / 1e6, L.ev.size());
|
||||
for (size_t i = 0; i < v.size() && i < top; ++i)
|
||||
std::printf("SYPROF %8.1f ms %5.1f %% %7ld launches %9.1f us each %s\n", v[i].second.first / 1e6, 100.0 * v[i].second.first / (total > 0 ? total : 1), v[i].second.second, v[i].second.first / 1e3 / static_cast<double>(v[i].second.second), v[i].first.c_str());
|
||||
std::fflush(stdout);
|
||||
}
|
||||
inline void prof_record(const char* fn, int line, sycl::event e) {
|
||||
ProfLog& L = prof_log();
|
||||
std::lock_guard<std::mutex> g(L.m);
|
||||
static bool reg = (std::atexit(prof_dump), true);
|
||||
(void)reg;
|
||||
L.ev.emplace_back(std::string(fn) + ":" + std::to_string(line), e);
|
||||
}
|
||||
#endif
|
||||
|
||||
template <class F>
|
||||
#ifdef STRATA_SY_PROFILE
|
||||
inline void launch(cudaStream_t s, int grid, int block, size_t smem, F f, const char* pfn = __builtin_FUNCTION(), int pline = __builtin_LINE()) {
|
||||
#else
|
||||
inline void launch(cudaStream_t s, int grid, int block, size_t smem, F f) {
|
||||
#endif
|
||||
auto& q = strata::sy::queue_of(s);
|
||||
#ifdef STRATA_SY_PROFILE
|
||||
prof_record(pfn, pline, q.submit([&](sycl::handler& h) {
|
||||
#else
|
||||
q.submit([&](sycl::handler& h) {
|
||||
#endif
|
||||
sycl::local_accessor<char, 1> lm(sycl::range<1>(smem ? smem : 1), h);
|
||||
h.parallel_for(sycl::nd_range<1>(static_cast<size_t>(grid) * block, static_cast<size_t>(block)), [=](sycl::nd_item<1> it) L32_SG32 {
|
||||
f(Blk{it}, lm.get_multi_ptr<sycl::access::decorated::no>().get());
|
||||
});
|
||||
#ifdef STRATA_SY_PROFILE
|
||||
}));
|
||||
#else
|
||||
});
|
||||
#endif
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------- shared device primitives (ports of ling32_dev.cuh; helper owners extend, never fork)
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
namespace strata::ling32::gpu {
|
||||
int g_w2_nt = 0; // AMD WMMA tile knobs: no meaning on SYCL, kept so that shared code links
|
||||
int g_w2_etn = 0;
|
||||
int g_w2_pack = -1; // AMD trunk GEMM packed-weight switch: no meaning on SYCL, kept so that shared code links
|
||||
int g_tc_min_n = 0;
|
||||
int g_tc_mode = 0;
|
||||
int g_kda_chunk_force = 0;
|
||||
@@ -76,18 +77,4 @@ void SpecState::set_nacc(int nacc, int hrow, int grow) {
|
||||
}
|
||||
} // namespace strata::ling32
|
||||
|
||||
// ---- picture encoder on the GPU: not ported (the CPU encoder serves pictures; vision_gpu_total_bytes = 0 makes the backend choice pick it)
|
||||
namespace strata::ling32 {
|
||||
struct VisionGpu::Dev {};
|
||||
VisionGpu::VisionGpu(const std::string& vision_file, int device, double idle_seconds) : file_(vision_file), device_(device), idle_(idle_seconds) {}
|
||||
VisionGpu::~VisionGpu() {}
|
||||
bool VisionGpu::encode(const PreparedImage&, std::vector<float>&, std::string& err, VisionCheckpoints*, VisionGpuStats*) {
|
||||
err = "the picture encoder on the GPU is not available in the SYCL build (use the CPU encoder)";
|
||||
return false;
|
||||
}
|
||||
void VisionGpu::unload() {}
|
||||
bool VisionGpu::loaded() const { return false; }
|
||||
uint64_t VisionGpu::device_bytes() const { return 0; }
|
||||
void VisionGpu::set_idle_seconds(double s) { idle_ = s; }
|
||||
uint64_t vision_gpu_total_bytes(int) { return 0; }
|
||||
} // namespace strata::ling32
|
||||
// (the picture encoder on the GPU is in ling32_sy_k_vision.cpp)
|
||||
@@ -187,6 +187,7 @@ void launch_step(float* S, const float* qn, const float* kn, const float* vc, co
|
||||
// The state-independent part of a chunk (cumulative gate G, the A / Aq matrices, k e^G, q e^G, k e^(Gl - G), beta, e^Gl) is computed by one work-group per (head, chunk) into a scratch buffer; a second
|
||||
// kernel walks the chunks of a head in order (U, outputs, state update). Port of kda_chunk_pre_kernel / kda_chunk_seq_kernel (CH = 8), same expressions and summation order.
|
||||
constexpr int kChunk = 8;
|
||||
using float4 = sycl::float4;
|
||||
template <int HD, int CH>
|
||||
constexpr size_t kda_chunk_scr_floats() { return 3ull * CH * HD + 2ull * CH * CH + CH + HD; }
|
||||
|
||||
@@ -359,6 +360,154 @@ void launch_chunk_seq(float* S, const float* vc, const float* g_raw, int gs, con
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- the chunk scan split over the value columns (launch_chunk_seq2)
|
||||
// The delta-rule state update is independent per value column v given the state-independent chunk tiles of launch_chunk_pre, so the serial scan of a head runs as HD / 32 work-groups (one per 32 value columns),
|
||||
// each with G sub-groups: sub-group g owns the key rows d in [g HD / G, (g + 1) HD / G) of the state of its 32 columns (HD / G floats per lane, registers), lanes are the columns. Per chunk: the partial sums over
|
||||
// d of kE s (for U) and qE s (for the output) are exchanged through shared memory, every sub-group then computes U (8 steps) and the output row of its column redundantly, and updates its rows of the state.
|
||||
// The gated RMS norm of the output needs a whole row (all columns): the scan writes the raw output O into out, launch_chunk_norm normalises it in place. The chunk tiles of the next chunk are loaded into
|
||||
// registers before the compute of the current one and stored into the other shared-memory buffer after it (two barriers per chunk). The summation order over d differs from launch_chunk_seq (partial sums per
|
||||
// key-row group), the result is the same function in fp32 (the forward and kernel tests compare against the reference).
|
||||
template <int HD, int CH, int G>
|
||||
void launch_chunk_seq2(float* S, const float* vc, float* out, int N, int H, const float* scr, cudaStream_t st) {
|
||||
constexpr int VT = 32, NVT = HD / VT, NT = VT * G, DPT = HD / G, FL = static_cast<int>(kda_chunk_scr_floats<HD, CH>());
|
||||
constexpr int TAIL = 2 * CH * CH + CH + HD; // A, Aq, b, eGl: contiguous in the scratch
|
||||
constexpr int BUF = 3 * CH * HD + TAIL + CH * VT; // kE, qE, k, A, Aq, b, eGl, vc of one chunk
|
||||
constexpr int NKQ4 = 3 * CH * HD / 4, PKQ = (NKQ4 + NT - 1) / NT, TAIL4 = TAIL / 4, PVC = (CH * VT + NT - 1) / NT;
|
||||
static_assert(TAIL % 4 == 0 && FL % 4 == 0 && HD % (4 * G) == 0, "KDA chunk scan: tile sizes must be multiples of 4");
|
||||
const size_t smem = (2ull * BUF + static_cast<size_t>(G) * 16 * VT) * sizeof(float);
|
||||
sy::launch(st, H * NVT, NT, smem, [=](sy::Blk b, char* smemp) {
|
||||
float* buf0 = reinterpret_cast<float*>(smemp);
|
||||
float* buf1 = buf0 + BUF;
|
||||
float* part = buf1 + BUF; // [G][16][VT]: partial sums of kE s (0..7) and qE s (8..15)
|
||||
const int h = b.bid() % H, vt = b.bid() / H, tid = b.tid(), g = tid >> 5, lane = tid & 31, C = H * HD;
|
||||
const int v = vt * VT + lane;
|
||||
float s[DPT];
|
||||
float* Sh = S + static_cast<size_t>(h) * HD * HD;
|
||||
for (int j = 0; j < DPT; ++j) s[j] = Sh[static_cast<size_t>(g * DPT + j) * HD + v];
|
||||
const int nch = (N + CH - 1) / CH;
|
||||
|
||||
// chunk tiles -> registers (kq: kE, qE, k as float4; tail: A, Aq, b, eGl; vcr: the 32 value columns of this work-group)
|
||||
float4 kq[PKQ], tl;
|
||||
float vcr[PVC];
|
||||
auto fetch = [&](int ci) {
|
||||
const float* src = scr + (static_cast<size_t>(ci) * H + h) * FL;
|
||||
const int s0 = ci * CH, c = sycl::min(CH, N - s0);
|
||||
for (int i = 0; i < PKQ; ++i) {
|
||||
const int u = tid + i * NT;
|
||||
if (u < NKQ4) kq[i] = *reinterpret_cast<const float4*>(src + 4 * u);
|
||||
}
|
||||
if (tid < TAIL4) tl = *reinterpret_cast<const float4*>(src + 3 * CH * HD + 4 * tid);
|
||||
for (int i = 0; i < PVC; ++i) {
|
||||
const int u = tid + i * NT, t = u / VT, l = u % VT;
|
||||
vcr[i] = (u < CH * VT && t < c) ? vc[static_cast<size_t>(s0 + t) * C + h * HD + vt * VT + l] : 0.0f;
|
||||
}
|
||||
};
|
||||
auto stash = [&](float* dst) {
|
||||
for (int i = 0; i < PKQ; ++i) {
|
||||
const int u = tid + i * NT;
|
||||
if (u < NKQ4) *reinterpret_cast<float4*>(dst + 4 * u) = kq[i];
|
||||
}
|
||||
if (tid < TAIL4) *reinterpret_cast<float4*>(dst + 3 * CH * HD + 4 * tid) = tl;
|
||||
for (int i = 0; i < PVC; ++i) {
|
||||
const int u = tid + i * NT;
|
||||
if (u < CH * VT) dst[3 * CH * HD + TAIL + u] = vcr[i];
|
||||
}
|
||||
};
|
||||
fetch(0);
|
||||
stash(buf0);
|
||||
b.sync();
|
||||
for (int ci = 0; ci < nch; ++ci) {
|
||||
const float* cb = (ci & 1) ? buf1 : buf0;
|
||||
const int s0 = ci * CH, c = sycl::min(CH, N - s0);
|
||||
if (ci + 1 < nch) fetch(ci + 1);
|
||||
const float* kEb = cb;
|
||||
const float* qEb = cb + CH * HD;
|
||||
const float* kb = cb + 2 * CH * HD;
|
||||
const float* Ab = cb + 3 * CH * HD;
|
||||
const float* Aqb = Ab + CH * CH;
|
||||
const float* bb = Aqb + CH * CH;
|
||||
const float* eGlb = bb + CH;
|
||||
const float* vcb = cb + 3 * CH * HD + TAIL;
|
||||
// partial sums over the key rows of this sub-group (rows t >= c hold stale tiles: never used)
|
||||
float accd[CH], O[CH];
|
||||
for (int t = 0; t < CH; ++t) { accd[t] = 0.0f; O[t] = 0.0f; }
|
||||
for (int j4 = 0; j4 < DPT / 4; ++j4) {
|
||||
const int d0 = g * DPT + j4 * 4;
|
||||
for (int t = 0; t < CH; ++t) {
|
||||
const float4 ke = *reinterpret_cast<const float4*>(kEb + t * HD + d0);
|
||||
const float4 qe = *reinterpret_cast<const float4*>(qEb + t * HD + d0);
|
||||
float a = accd[t], o = O[t];
|
||||
a += ke.x() * s[4 * j4]; o += qe.x() * s[4 * j4];
|
||||
a += ke.y() * s[4 * j4 + 1]; o += qe.y() * s[4 * j4 + 1];
|
||||
a += ke.z() * s[4 * j4 + 2]; o += qe.z() * s[4 * j4 + 2];
|
||||
a += ke.w() * s[4 * j4 + 3]; o += qe.w() * s[4 * j4 + 3];
|
||||
accd[t] = a;
|
||||
O[t] = o;
|
||||
}
|
||||
}
|
||||
for (int t = 0; t < CH; ++t) {
|
||||
part[(g * 16 + t) * VT + lane] = accd[t];
|
||||
part[(g * 16 + CH + t) * VT + lane] = O[t];
|
||||
}
|
||||
b.sync();
|
||||
for (int t = 0; t < CH; ++t) {
|
||||
float a = part[t * VT + lane], o = part[(CH + t) * VT + lane];
|
||||
for (int gg = 1; gg < G; ++gg) {
|
||||
a += part[(gg * 16 + t) * VT + lane];
|
||||
o += part[(gg * 16 + CH + t) * VT + lane];
|
||||
}
|
||||
accd[t] = a;
|
||||
O[t] = o;
|
||||
}
|
||||
float U[CH];
|
||||
for (int t = 0; t < CH; ++t) {
|
||||
U[t] = 0.0f;
|
||||
if (t < c) {
|
||||
float sub = 0.0f;
|
||||
for (int i = 0; i < t; ++i) sub += Ab[t * CH + i] * U[i];
|
||||
const float bt = bb[t];
|
||||
U[t] = bt * (vcb[t * VT + lane] - accd[t]) - bt * sub;
|
||||
}
|
||||
}
|
||||
for (int t = 0; t < CH; ++t)
|
||||
if (t < c) {
|
||||
float o = O[t];
|
||||
for (int i = 0; i <= t; ++i) o += Aqb[t * CH + i] * U[i];
|
||||
O[t] = o;
|
||||
if (g == 0) out[static_cast<size_t>(s0 + t) * C + h * HD + v] = o;
|
||||
}
|
||||
for (int j4 = 0; j4 < DPT / 4; ++j4) {
|
||||
const int d0 = g * DPT + j4 * 4;
|
||||
const float4 eg = *reinterpret_cast<const float4*>(eGlb + d0);
|
||||
float a0 = eg.x() * s[4 * j4], a1 = eg.y() * s[4 * j4 + 1], a2 = eg.z() * s[4 * j4 + 2], a3 = eg.w() * s[4 * j4 + 3];
|
||||
for (int i = 0; i < CH; ++i)
|
||||
if (i < c) {
|
||||
const float4 kv = *reinterpret_cast<const float4*>(kb + i * HD + d0);
|
||||
a0 += kv.x() * U[i]; a1 += kv.y() * U[i]; a2 += kv.z() * U[i]; a3 += kv.w() * U[i];
|
||||
}
|
||||
s[4 * j4] = a0; s[4 * j4 + 1] = a1; s[4 * j4 + 2] = a2; s[4 * j4 + 3] = a3;
|
||||
}
|
||||
if (ci + 1 < nch) stash((ci & 1) ? buf0 : buf1);
|
||||
b.sync();
|
||||
}
|
||||
for (int j = 0; j < DPT; ++j) Sh[static_cast<size_t>(g * DPT + j) * HD + v] = s[j];
|
||||
});
|
||||
}
|
||||
|
||||
// out[tok][h][v] = O r o_norm[v] sigmoid(g): the gated RMS norm over the whole row of the raw output the scan left in out (same expressions as launch_chunk_seq)
|
||||
template <int HD>
|
||||
void launch_chunk_norm(const float* g_raw, int gs, const float* o_norm, float eps, float* out, int N, int H, cudaStream_t st) {
|
||||
sy::launch(st, N * H, HD, 40 * sizeof(float), [=](sy::Blk b, char* smemp) {
|
||||
float* sm = reinterpret_cast<float*>(smemp);
|
||||
const int tok = b.bid() % N, h = b.bid() / N, v = b.tid(), C = H * HD;
|
||||
const size_t o_i = static_cast<size_t>(tok) * C + h * HD + v;
|
||||
const float o = out[o_i];
|
||||
const float ss = block_sum(b, o * o, sm);
|
||||
const float r = 1.0f / sycl::sqrt(ss / static_cast<float>(HD) + eps);
|
||||
out[o_i] = o * r * o_norm[v] * sigmoidf(g_raw[static_cast<size_t>(tok) * gs + h * HD + v]);
|
||||
});
|
||||
}
|
||||
|
||||
[[noreturn]] void bad_hd(int hd) {
|
||||
std::fprintf(stderr, "ling32: KDA head dim %d is not built (64, 128)\n", hd);
|
||||
std::abort();
|
||||
@@ -366,6 +515,8 @@ void launch_chunk_seq(float* S, const float* vc, const float* g_raw, int gs, con
|
||||
|
||||
} // namespace
|
||||
|
||||
int g_sy_kda_seq_mode = -1; // tests / tuning: see kda_step (-1: STRATA_L32_KDA_SEQ, default 8)
|
||||
|
||||
void kda_prep(const float* proj, int ps, const float* qw, const float* kw, const float* vw, float* hist, float* qn, float* kn, float* vc, int N, int H, int hd, cudaStream_t s, float* hist_ext,
|
||||
int ext_len) {
|
||||
if (hd == 128) launch_prep<128>(proj, ps, qw, kw, vw, hist, qn, kn, vc, N, H, s);
|
||||
@@ -405,9 +556,26 @@ void kda_step(float* S, const float* qn, const float* kn, const float* vc, const
|
||||
const int nch = (N + kChunk - 1) / kChunk;
|
||||
const size_t need = static_cast<size_t>(nch) * H * (hd == 64 ? kda_chunk_scr_floats<64, kChunk>() : kda_chunk_scr_floats<128, kChunk>());
|
||||
if (need > scratch_floats) { std::fprintf(stderr, "ling32: KDA chunk scratch too small\n"); std::abort(); }
|
||||
if (hd == 128) { launch_chunk_pre<128, kChunk>(qn, kn, f_raw, fs, beta_raw, A_log, dt_bias, lower_bound, N, H, scratch, s); launch_chunk_seq<128, kChunk>(S, vc, g_raw, gs, o_norm, eps, out, N, H, scratch, s); }
|
||||
else if (hd == 64) { launch_chunk_pre<64, kChunk>(qn, kn, f_raw, fs, beta_raw, A_log, dt_bias, lower_bound, N, H, scratch, s); launch_chunk_seq<64, kChunk>(S, vc, g_raw, gs, o_norm, eps, out, N, H, scratch, s); }
|
||||
else bad_hd(hd);
|
||||
static const int env_mode = std::getenv("STRATA_L32_KDA_SEQ") ? std::atoi(std::getenv("STRATA_L32_KDA_SEQ")) : -1;
|
||||
if (g_sy_kda_seq_mode < 0) g_sy_kda_seq_mode = env_mode >= 0 ? env_mode : 0; // default 0 (the validated one-column-per-lane scan): the split scan (4 / 8) deviates from the float64 golden on long prompts (a 4096-token prompt, from position 2717 on: KL 2.7e-4, 127 positions above 1e-3), opt-in with STRATA_L32_KDA_SEQ=4 / 8 until fixed
|
||||
const int mode = g_sy_kda_seq_mode; // 0: the one-column-per-lane scan (launch_chunk_seq), 4 / 8: the scan split over the value columns with 4 / 8 key-row groups (launch_chunk_seq2) + the norm kernel
|
||||
if (hd == 128) {
|
||||
launch_chunk_pre<128, kChunk>(qn, kn, f_raw, fs, beta_raw, A_log, dt_bias, lower_bound, N, H, scratch, s);
|
||||
if (mode == 0) launch_chunk_seq<128, kChunk>(S, vc, g_raw, gs, o_norm, eps, out, N, H, scratch, s);
|
||||
else {
|
||||
if (mode == 4) launch_chunk_seq2<128, kChunk, 4>(S, vc, out, N, H, scratch, s);
|
||||
else launch_chunk_seq2<128, kChunk, 8>(S, vc, out, N, H, scratch, s);
|
||||
launch_chunk_norm<128>(g_raw, gs, o_norm, eps, out, N, H, s);
|
||||
}
|
||||
} else if (hd == 64) {
|
||||
launch_chunk_pre<64, kChunk>(qn, kn, f_raw, fs, beta_raw, A_log, dt_bias, lower_bound, N, H, scratch, s);
|
||||
if (mode == 0) launch_chunk_seq<64, kChunk>(S, vc, g_raw, gs, o_norm, eps, out, N, H, scratch, s);
|
||||
else {
|
||||
if (mode == 4) launch_chunk_seq2<64, kChunk, 4>(S, vc, out, N, H, scratch, s);
|
||||
else launch_chunk_seq2<64, kChunk, 8>(S, vc, out, N, H, scratch, s);
|
||||
launch_chunk_norm<64>(g_raw, gs, o_norm, eps, out, N, H, s);
|
||||
}
|
||||
} else bad_hd(hd);
|
||||
return;
|
||||
}
|
||||
if (hd == 128) launch_step<128>(S, qn, kn, vc, f_raw, fs, g_raw, gs, beta_raw, A_log, dt_bias, o_norm, lower_bound, eps, out, N, H, snap, s);
|
||||
|
||||
@@ -31,4 +31,34 @@ void argmax_rows(const float* logits, int N, int V, int* out, cudaStream_t s) {
|
||||
});
|
||||
}
|
||||
|
||||
// Dynamic expert skip (--skip-tau, opt-in, NOT exact; port of prune_experts_kernel of ling32_layers.cu, one token per thread, the same arithmetic): a routed expert whose share of the token's routing
|
||||
// weight is below tau is dropped (its slot gets the top expert's id with weight 0), the others are rescaled so that the weight sum stays the same.
|
||||
void prune_experts(int* ridx, float* rw, int N, int top_k, float tau, cudaStream_t s) {
|
||||
sy::launch(s, (N + 31) / 32, 32, 0, [=](sy::Blk b, char*) {
|
||||
const int t = b.bid() * b.bdim() + b.tid();
|
||||
if (t >= N) return;
|
||||
int* ix = ridx + static_cast<size_t>(t) * top_k;
|
||||
float* w = rw + static_cast<size_t>(t) * top_k;
|
||||
float sum = 0.0f, wmax = -1.0f;
|
||||
int imax = 0;
|
||||
for (int j = 0; j < top_k; ++j) {
|
||||
sum += w[j];
|
||||
if (w[j] > wmax) { wmax = w[j]; imax = j; }
|
||||
}
|
||||
if (!(sum > 0.0f)) return;
|
||||
float kept = 0.0f;
|
||||
int drops = 0;
|
||||
for (int j = 0; j < top_k; ++j) {
|
||||
if (j != imax && w[j] < tau * sum) ++drops; else kept += w[j];
|
||||
}
|
||||
if (drops == 0 || !(kept > 0.0f)) return;
|
||||
const float scale = sum / kept;
|
||||
const int top_id = ix[imax];
|
||||
for (int j = 0; j < top_k; ++j) {
|
||||
if (j != imax && w[j] < tau * sum) { ix[j] = top_id; w[j] = 0.0f; }
|
||||
else w[j] *= scale;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace strata::ling32::gpu
|
||||
@@ -0,0 +1,572 @@
|
||||
// src/ling32/sycl/ling32_sy_k_mla_exp.cpp - EXPANDED-form MLA attention for long prefill chunks on Intel GPUs (SYCL), the port of ling32_mla_exp.cu. Owner: L32-SY-MLA.
|
||||
//
|
||||
// The absorbed form (q_abs . c, 576-deep scores, 512-wide value) costs 2 x (576 + 512) flops per (query, key, head); the expanded form projects the latent cache once per chunk into per-head keys
|
||||
// K_nope = c . wk_b^T (128 wide) and values V = c . wv_b^T (128 wide) and runs attention with 192-deep scores (128 nope + 64 rope, the rope part is the shared k_pe) and a 128-wide value: 640 flops
|
||||
// per pair (3.4x fewer), plus the projection. Numerics as in the CUDA kernel: every fp32 operand is split into fp16 hi + lo (x = hi + lo / 2048, hi = fp16(x), lo = fp16((x - hi) 2048)); a product is
|
||||
// hi hi + (hi lo + lo hi) / 2048 accumulated in fp32 (~2^-22 per product, like an fp32 FMA chain). The BF16 weights are converted once to fp16 x 256 (exact) in the packed (VNNI-2) layout of the B operand.
|
||||
//
|
||||
// Structure (all kernels use 16-wide sub-groups; the matrix products are joint_matrix 8x16x16 on Battlemage / PVC, and a plain per-lane loop with the SAME tile layout everywhere else, so the logic
|
||||
// is testable on any Intel GPU; mla_exp_ok() only says yes when the XMX engines exist, unless STRATA_L32_MLA_EXP_MODE=1 forces the plain loop for tests). joint_matrix_apply is not used anywhere (the offline
|
||||
// compiler crashes on it in kernels of this size): accumulators are only filled, accumulated by mad and stored to shared memory; the combination of the main and the cross (lo) product and every
|
||||
// rescale happen in plain code on the stored tiles.
|
||||
// convert bf16 wk_b / wv_b [H][128][512] -> fp16 x 256 packed [H][256 k-pairs][128 outputs x 2] (element (k, n) at (k >> 1) * 256 + 2 n + (k & 1))
|
||||
// qprep q [N][H][192] fp32 -> hi / lo planes [H][NP][192] fp16 (rows beyond N zero), NP = N rounded up to kBM
|
||||
// proj per slab of S keys: grid (S / 16, H), 256 threads = 16 sub-groups, sub-group w = 16 of the 256 outputs (K_nope for w < 8, V for w >= 8) x 16 keys: main = c_hi W, cross = c_lo W over K = 512.
|
||||
// Output: K planes (hi, lo) packed as B operand [H][96 d-pairs][S keys x 2] (rows 0..63 K_nope, 64..95 k_pe from the cache), V planes packed [H][S / 2 key-pairs][128 dims x 2].
|
||||
// attn per slab: grid (NP / 32, H), 128 threads, sub-group w = (M tile w & 3 of 8 query rows) x (key half / dim half w >> 2). Per tile of 32 keys: K, V tiles to shared memory; scores
|
||||
// S = Q K^T (3 DPAS per product, main and cross accumulators stored to shared memory); online softmax in plain code (4 threads per row), P as hi / lo A tiles; the products P V of the tile
|
||||
// (fresh accumulators, stored through a small per-sub-group scratch) are added to the O state kept in registers (lane = column, 8 rows); (O, m, l) go to global memory between slabs.
|
||||
// final out = O / l * sigmoid(gate)
|
||||
// A row's arithmetic depends only on its own keys in 32-key tiles counted from key 0, so the result does not depend on the chunking of the prompt.
|
||||
#include "ling32_sy.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cfloat>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <type_traits>
|
||||
|
||||
#if __has_include(<sycl/ext/oneapi/matrix/matrix.hpp>)
|
||||
#include <sycl/ext/oneapi/matrix/matrix.hpp>
|
||||
#define L32X_HAVE_JM 1
|
||||
#else
|
||||
#define L32X_HAVE_JM 0
|
||||
#endif
|
||||
|
||||
#if L32X_HAVE_JM && defined(__SYCL_DEVICE_ONLY__)
|
||||
#if (defined(__SYCL_TARGET_INTEL_GPU_BMG_G21__) && __SYCL_TARGET_INTEL_GPU_BMG_G21__ == 1) || (defined(__SYCL_TARGET_INTEL_GPU_BMG_G31__) && __SYCL_TARGET_INTEL_GPU_BMG_G31__ == 1) || \
|
||||
(defined(__SYCL_TARGET_INTEL_GPU_LNL_M__) && __SYCL_TARGET_INTEL_GPU_LNL_M__ == 1) || (defined(__SYCL_TARGET_INTEL_GPU_PTL_H__) && __SYCL_TARGET_INTEL_GPU_PTL_H__ == 1) || \
|
||||
(defined(__SYCL_TARGET_INTEL_GPU_PTL_U__) && __SYCL_TARGET_INTEL_GPU_PTL_U__ == 1) || (defined(__SYCL_TARGET_INTEL_GPU_PVC__) && __SYCL_TARGET_INTEL_GPU_PVC__ == 1)
|
||||
#define L32X_PASS_JM16 1
|
||||
#endif
|
||||
#endif
|
||||
#ifndef L32X_PASS_JM16
|
||||
#define L32X_PASS_JM16 0
|
||||
#endif
|
||||
|
||||
#ifndef L32X_SKIP
|
||||
#define L32X_SKIP 0 // bisect aid for compiler crashes: 1 = no projection body, 2 = no attention body
|
||||
#endif
|
||||
|
||||
namespace strata::ling32::gpu {
|
||||
namespace {
|
||||
|
||||
constexpr int kNope = 128, kRope = 64, kQK = 192, kVD = 128, kR = 512;
|
||||
constexpr int kBM = 32; // query rows per attention work-group
|
||||
constexpr int kBK = 32; // keys per attention tile
|
||||
constexpr int kAttThreads = 128;
|
||||
constexpr int kProjThreads = 256;
|
||||
constexpr int kLdK = 72; // halves per packed K row (32 keys x 2 + 8)
|
||||
constexpr int kLdV = 264; // halves per packed V row (128 dims x 2 + 8)
|
||||
constexpr int kLdP = 40; // halves per P row (32 keys + 8)
|
||||
constexpr int kLdS = 36; // floats per score row
|
||||
constexpr int kLdA = 72; // projection: halves per A row (64 + 8)
|
||||
constexpr int kPK = 16; // projection: keys per work-group
|
||||
constexpr int kLdR = 264; // projection: floats per result row (256 + 8)
|
||||
constexpr float kInv2048 = 1.0f / 2048.0f;
|
||||
constexpr float kNeg = -3.0e38f;
|
||||
|
||||
using sy::f2h;
|
||||
using sy::h2f;
|
||||
|
||||
inline void split_h(float x, uint16_t& hi, uint16_t& lo) {
|
||||
hi = f2h(x);
|
||||
lo = f2h((x - h2f(hi)) * 2048.0f);
|
||||
}
|
||||
inline uint32_t pack2(uint16_t lo16, uint16_t hi16) { return static_cast<uint32_t>(lo16) | (static_cast<uint32_t>(hi16) << 16); }
|
||||
|
||||
#if L32X_PASS_JM16
|
||||
namespace jm = sycl::ext::oneapi::experimental::matrix;
|
||||
#endif
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------- 8x16x16 tile operations: joint_matrix (J = true) or a plain per-lane loop with the same layout (J = false)
|
||||
// accumulator 8 x 16 fp32 (logical element (row, col)); A operand 8 x 16 halves row-major; B operand 16 x 16 halves in the packed (VNNI-2) layout: element (k, n) at (k >> 1) * ld + 2 n + (k & 1)
|
||||
template <bool J> struct Acc;
|
||||
template <> struct Acc<false> { float v[8]; }; // lane = column, element i = row i
|
||||
#if L32X_PASS_JM16
|
||||
template <> struct Acc<true> { jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16> m; };
|
||||
#endif
|
||||
template <bool J> struct AOp;
|
||||
template <> struct AOp<false> { const uint16_t* p; int ld; };
|
||||
template <bool J> struct BOp;
|
||||
template <> struct BOp<false> { const uint16_t* p; int ld; };
|
||||
#if L32X_PASS_JM16
|
||||
template <> struct AOp<true> { jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::a, 8, 16, jm::layout::row_major> m; };
|
||||
template <> struct BOp<true> { jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, 16, jm::layout::ext_intel_packed> m; };
|
||||
#endif
|
||||
|
||||
template <bool J> inline void acc_fill(const sy::Blk& b, Acc<J>& c, float x) {
|
||||
if constexpr (J) {
|
||||
#if L32X_PASS_JM16
|
||||
jm::joint_matrix_fill(b.it.get_sub_group(), c.m, x);
|
||||
#endif
|
||||
} else {
|
||||
for (int i = 0; i < 8; ++i) c.v[i] = x;
|
||||
}
|
||||
}
|
||||
template <bool J, sycl::access::address_space AS> inline void acc_store(const sy::Blk& b, Acc<J>& c, float* p, int ld) {
|
||||
if constexpr (J) {
|
||||
#if L32X_PASS_JM16
|
||||
auto mp = sycl::address_space_cast<AS, sycl::access::decorated::no>(p);
|
||||
jm::joint_matrix_store(b.it.get_sub_group(), c.m, mp, ld, jm::layout::row_major);
|
||||
#endif
|
||||
} else {
|
||||
const int ln = b.lane();
|
||||
for (int i = 0; i < 8; ++i) p[static_cast<size_t>(i) * ld + ln] = c.v[i];
|
||||
}
|
||||
}
|
||||
template <bool J, sycl::access::address_space AS> inline void a_load(const sy::Blk& b, AOp<J>& a, const uint16_t* p, int ld) {
|
||||
if constexpr (J) {
|
||||
#if L32X_PASS_JM16
|
||||
auto mp = sycl::address_space_cast<AS, sycl::access::decorated::no>(const_cast<sycl::half*>(reinterpret_cast<const sycl::half*>(p)));
|
||||
jm::joint_matrix_load(b.it.get_sub_group(), a.m, mp, ld);
|
||||
#endif
|
||||
} else {
|
||||
a.p = p;
|
||||
a.ld = ld;
|
||||
}
|
||||
}
|
||||
template <bool J, sycl::access::address_space AS> inline void b_load(const sy::Blk& b, BOp<J>& bm, const uint16_t* p, int ld) {
|
||||
if constexpr (J) {
|
||||
#if L32X_PASS_JM16
|
||||
auto mp = sycl::address_space_cast<AS, sycl::access::decorated::no>(const_cast<sycl::half*>(reinterpret_cast<const sycl::half*>(p)));
|
||||
jm::joint_matrix_load(b.it.get_sub_group(), bm.m, mp, ld);
|
||||
#endif
|
||||
} else {
|
||||
bm.p = p;
|
||||
bm.ld = ld;
|
||||
}
|
||||
}
|
||||
template <bool J> inline void mad(const sy::Blk& b, Acc<J>& c, const AOp<J>& a, const BOp<J>& bm) {
|
||||
if constexpr (J) {
|
||||
#if L32X_PASS_JM16
|
||||
jm::joint_matrix_mad(b.it.get_sub_group(), c.m, a.m, bm.m, c.m);
|
||||
#endif
|
||||
} else {
|
||||
const int ln = b.lane();
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
float s = 0.0f;
|
||||
for (int k = 0; k < 16; ++k) s += h2f(a.p[i * a.ld + k]) * h2f(bm.p[(k >> 1) * bm.ld + ln * 2 + (k & 1)]);
|
||||
c.v[i] += s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
constexpr auto kLoc = sycl::access::address_space::local_space;
|
||||
constexpr auto kGlb = sycl::access::address_space::global_space;
|
||||
|
||||
// kernel launch with 16-wide sub-groups
|
||||
template <class F>
|
||||
inline void launch16(cudaStream_t s, int grid, int block, size_t smem, F f) {
|
||||
auto& q = strata::sy::queue_of(s);
|
||||
q.submit([&](sycl::handler& h) {
|
||||
sycl::local_accessor<char, 1> lm(sycl::range<1>(smem ? smem : 1), h);
|
||||
h.parallel_for(sycl::nd_range<1>(static_cast<size_t>(grid) * block, static_cast<size_t>(block)), [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] {
|
||||
f(sy::Blk{it}, lm.get_multi_ptr<sycl::access::decorated::no>().get());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------- weights: BF16 [H][128][512] -> fp16 x 256, packed [H][256][256]
|
||||
void convert_weights(const uint16_t* in, size_t n, uint16_t* out, cudaStream_t s) {
|
||||
const size_t per_head = static_cast<size_t>(kNope) * kR;
|
||||
auto& q = strata::sy::queue_of(s);
|
||||
if (n % per_head != 0) { // a model with other head dimensions (the small test fixtures): the expanded form is not available there (mla_exp_ok geometry), a plain conversion keeps the engine's buffers valid
|
||||
q.submit([&](sycl::handler& h) {
|
||||
h.parallel_for(sycl::range<1>(n), [=](sycl::id<1> id) {
|
||||
const float f = sycl::bit_cast<float>(static_cast<uint32_t>(in[id[0]]) << 16) * 256.0f;
|
||||
out[id[0]] = f2h(f);
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
q.submit([&](sycl::handler& h) {
|
||||
h.parallel_for(sycl::range<1>(n), [=](sycl::id<1> id) {
|
||||
const size_t i = id[0], hh = i / per_head, rem = i - hh * per_head;
|
||||
const int d = static_cast<int>(rem / kR), k = static_cast<int>(rem % kR);
|
||||
const float f = sycl::bit_cast<float>(static_cast<uint32_t>(in[i]) << 16) * 256.0f;
|
||||
out[hh * per_head + static_cast<size_t>(k >> 1) * 256 + d * 2 + (k & 1)] = f2h(f);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------- q -> hi / lo planes [H][NP][192]
|
||||
void qprep(const float* q, uint16_t* Qh, uint16_t* Ql, int N, int NP, int H, cudaStream_t s) {
|
||||
launch16(s, NP, kProjThreads, 0, [=](sy::Blk b, char*) {
|
||||
const int t = b.bid();
|
||||
for (int idx = b.tid(); idx < H * kQK; idx += kProjThreads) {
|
||||
const int h = idx / kQK, d = idx - h * kQK;
|
||||
uint16_t hi = 0, lo = 0;
|
||||
if (t < N) split_h(q[(static_cast<size_t>(t) * H + h) * kQK + d], hi, lo);
|
||||
const size_t o = (static_cast<size_t>(h) * NP + t) * kQK + d;
|
||||
Qh[o] = hi;
|
||||
Ql[o] = lo;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------- projection of a slab of keys
|
||||
template <bool K>
|
||||
void proj(const float* cache, int lat_stride, const uint16_t* wk16, const uint16_t* wv16, uint32_t* Kh, uint32_t* Kl, uint32_t* Vh, uint32_t* Vl, int H, int S, int k0, int nvalid, cudaStream_t s) {
|
||||
constexpr bool J = K && (L32X_PASS_JM16 != 0);
|
||||
constexpr bool kDead = (!K && (L32X_PASS_JM16 != 0)) || (L32X_SKIP & 1); // the plain-loop instance is never run in a joint_matrix pass (and the offline compiler need not compile it)
|
||||
const int gx = (nvalid + kPK - 1) / kPK;
|
||||
const size_t smem = static_cast<size_t>(2 * kPK * kLdA) * 2 + static_cast<size_t>(2 * kPK) * kLdR * 4;
|
||||
launch16(s, gx * H, kProjThreads, smem, [cache, lat_stride, wk16, wv16, Kh, Kl, Vh, Vl, H, S, k0, nvalid, gx](sy::Blk b, char* sm) { // explicit captures: the host and the device pass must capture the same set (the dead-instance stub does not use them)
|
||||
if constexpr (kDead) return;
|
||||
else {
|
||||
uint16_t* Ah = reinterpret_cast<uint16_t*>(sm); // [16 keys][kLdA] hi of the latent chunk
|
||||
uint16_t* Al = Ah + kPK * kLdA; // lo
|
||||
float* R = reinterpret_cast<float*>(sm + static_cast<size_t>(2 * kPK * kLdA) * 2); // [16 keys][kLdR]: main (hi) products
|
||||
float* RX = R + kPK * kLdR; // cross (lo) products
|
||||
const int bx = b.bid() % gx, h = b.bid() / gx, tid = b.tid(), w = tid >> 4, kb = bx * kPK;
|
||||
const uint16_t* W = (w < 8 ? wk16 : wv16) + static_cast<size_t>(h) * 65536 + (w & 7) * 32; // packed [256 k-pairs][256 halves]; this sub-group's 16 outputs
|
||||
// joint_matrix variables are declared once at the top of the kernel
|
||||
Acc<J> a0, a1, x0, x1;
|
||||
AOp<J> ah, al;
|
||||
BOp<J> bm;
|
||||
acc_fill<J>(b, a0, 0.0f);
|
||||
acc_fill<J>(b, a1, 0.0f);
|
||||
acc_fill<J>(b, x0, 0.0f);
|
||||
acc_fill<J>(b, x1, 0.0f);
|
||||
for (int kc = 0; kc < kR / 64; ++kc) {
|
||||
b.sync();
|
||||
{ // 16 keys x 64 floats of this k chunk, split into hi / lo (4 floats per thread)
|
||||
const int key = tid >> 4, c4 = tid & 15;
|
||||
float v[4];
|
||||
if (kb + key < nvalid) {
|
||||
const float* src = cache + static_cast<size_t>(k0 + kb + key) * lat_stride + kc * 64 + c4 * 4;
|
||||
for (int e = 0; e < 4; ++e) v[e] = src[e];
|
||||
} else {
|
||||
for (int e = 0; e < 4; ++e) v[e] = 0.0f;
|
||||
}
|
||||
for (int e = 0; e < 4; ++e) {
|
||||
uint16_t hi, lo;
|
||||
split_h(v[e], hi, lo);
|
||||
Ah[key * kLdA + c4 * 4 + e] = hi;
|
||||
Al[key * kLdA + c4 * 4 + e] = lo;
|
||||
}
|
||||
}
|
||||
b.sync();
|
||||
for (int ks = 0; ks < 4; ++ks) {
|
||||
b_load<J, kGlb>(b, bm, W + static_cast<size_t>(kc * 32 + ks * 8) * 256, 256);
|
||||
a_load<J, kLoc>(b, ah, Ah + ks * 16, kLdA);
|
||||
a_load<J, kLoc>(b, al, Al + ks * 16, kLdA);
|
||||
mad<J>(b, a0, ah, bm);
|
||||
mad<J>(b, x0, al, bm);
|
||||
a_load<J, kLoc>(b, ah, Ah + 8 * kLdA + ks * 16, kLdA);
|
||||
a_load<J, kLoc>(b, al, Al + 8 * kLdA + ks * 16, kLdA);
|
||||
mad<J>(b, a1, ah, bm);
|
||||
mad<J>(b, x1, al, bm);
|
||||
}
|
||||
}
|
||||
acc_store<J, kLoc>(b, a0, R + w * 16, kLdR);
|
||||
acc_store<J, kLoc>(b, a1, R + 8 * kLdR + w * 16, kLdR);
|
||||
acc_store<J, kLoc>(b, x0, RX + w * 16, kLdR);
|
||||
acc_store<J, kLoc>(b, x1, RX + 8 * kLdR + w * 16, kLdR);
|
||||
b.sync();
|
||||
// (main + cross / 2048) / 256 = the projected value; split again into the hi / lo planes of the attention
|
||||
auto val = [&](int key, int col) { return (R[key * kLdR + col] + RX[key * kLdR + col] * kInv2048) * (1.0f / 256.0f); };
|
||||
uint32_t* kh = Kh + static_cast<size_t>(h) * 96 * S;
|
||||
uint32_t* kl = Kl + static_cast<size_t>(h) * 96 * S;
|
||||
for (int u = tid; u < 64 * kPK; u += kProjThreads) { // K_nope: word (d pair p, key) = (d = 2p | d = 2p + 1 << 16)
|
||||
const int key = u & (kPK - 1), p = u / kPK;
|
||||
uint16_t h0, l0, h1, l1;
|
||||
split_h(val(key, 2 * p), h0, l0);
|
||||
split_h(val(key, 2 * p + 1), h1, l1);
|
||||
kh[static_cast<size_t>(p) * S + kb + key] = pack2(h0, h1);
|
||||
kl[static_cast<size_t>(p) * S + kb + key] = pack2(l0, l1);
|
||||
}
|
||||
uint32_t* vh = Vh + static_cast<size_t>(h) * (S / 2) * kVD;
|
||||
uint32_t* vl = Vl + static_cast<size_t>(h) * (S / 2) * kVD;
|
||||
for (int u = tid; u < (kPK / 2) * kVD; u += kProjThreads) { // V: word (key pair m, dim) = (key = 2m | key = 2m + 1 << 16)
|
||||
const int dim = u & 127, m = u >> 7;
|
||||
uint16_t h0, l0, h1, l1;
|
||||
split_h(val(2 * m, kNope + dim), h0, l0);
|
||||
split_h(val(2 * m + 1, kNope + dim), h1, l1);
|
||||
vh[static_cast<size_t>((kb >> 1) + m) * kVD + dim] = pack2(h0, h1);
|
||||
vl[static_cast<size_t>((kb >> 1) + m) * kVD + dim] = pack2(l0, l1);
|
||||
}
|
||||
for (int u = tid; u < kPK * 32; u += kProjThreads) { // k_pe (shared by the heads) -> d pairs 64 .. 95
|
||||
const int key = u & (kPK - 1), p = u / kPK;
|
||||
float r0 = 0.0f, r1 = 0.0f;
|
||||
if (kb + key < nvalid) {
|
||||
const float* src = cache + static_cast<size_t>(k0 + kb + key) * lat_stride + kR + 2 * p;
|
||||
r0 = src[0];
|
||||
r1 = src[1];
|
||||
}
|
||||
uint16_t h0, l0, h1, l1;
|
||||
split_h(r0, h0, l0);
|
||||
split_h(r1, h1, l1);
|
||||
kh[static_cast<size_t>(64 + p) * S + kb + key] = pack2(h0, h1);
|
||||
kl[static_cast<size_t>(64 + p) * S + kb + key] = pack2(l0, l1);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------- attention over one slab
|
||||
inline constexpr size_t attn_smem_bytes() {
|
||||
// K hi / lo [96][kLdK], V hi / lo [16][kLdV], P hi / lo [kBM][kLdP], scores main / cross [kBM][kLdS] (aliased by the PV scratch: 8 sub-groups x 2 x 128 floats), corr [kBM]
|
||||
return static_cast<size_t>(2) * 96 * kLdK * 2 + static_cast<size_t>(2) * 16 * kLdV * 2 + static_cast<size_t>(2) * kBM * kLdP * 2 + static_cast<size_t>(2) * kBM * kLdS * 4 + kBM * 4 + 64;
|
||||
}
|
||||
|
||||
template <bool K>
|
||||
void attn(const uint16_t* Qh, const uint16_t* Ql, const uint32_t* Kh, const uint32_t* Kl, const uint32_t* Vh, const uint32_t* Vl, float* Oacc, float* ML, int N, int NP, int H, int pos0, int k0, int S, int nk_valid,
|
||||
int first, float scale, cudaStream_t s) {
|
||||
constexpr bool J = K && (L32X_PASS_JM16 != 0);
|
||||
constexpr bool kDead = (!K && (L32X_PASS_JM16 != 0)) || (L32X_SKIP & 2);
|
||||
const int nbx = NP / kBM;
|
||||
launch16(s, nbx * H, kAttThreads, attn_smem_bytes(), [Qh, Ql, Kh, Kl, Vh, Vl, Oacc, ML, N, NP, H, pos0, k0, S, nk_valid, first, scale, nbx](sy::Blk b, char* sm) {
|
||||
if constexpr (kDead) return;
|
||||
else {
|
||||
uint16_t* sKh = reinterpret_cast<uint16_t*>(sm); // [96][kLdK]
|
||||
uint16_t* sKl = sKh + 96 * kLdK;
|
||||
uint16_t* sVh = sKl + 96 * kLdK; // [16][kLdV]
|
||||
uint16_t* sVl = sVh + 16 * kLdV;
|
||||
uint16_t* sPh = sVl + 16 * kLdV; // [kBM][kLdP]
|
||||
uint16_t* sPl = sPh + kBM * kLdP;
|
||||
float* sS = reinterpret_cast<float*>(sPl + kBM * kLdP); // [kBM][kLdS] scores, main products
|
||||
float* sX = sS + kBM * kLdS; // cross products
|
||||
float* sCorr = sX + kBM * kLdS; // [kBM]
|
||||
const int bx = b.bid() % nbx, h = b.bid() / nbx, tid = b.tid(), w = tid >> 4, lane = b.lane();
|
||||
const int row0 = bx * kBM;
|
||||
const int t_last = std::min(N - 1, row0 + kBM - 1);
|
||||
const int nvis = std::min(nk_valid, pos0 + t_last + 1 - k0);
|
||||
const int ntiles = nvis > 0 ? (nvis + kBK - 1) / kBK : 0;
|
||||
if (ntiles == 0 && !first) return;
|
||||
const int mt = w & 3, nd = w >> 2; // M tile (8 rows) and key half (scores) / dim half (PV)
|
||||
const int srow = tid >> 2, spart = tid & 3; // softmax: row, 8 keys
|
||||
float* scr = sS + w * 256; // PV scratch of this sub-group: main [8][16], cross [8][16] (aliases the scores, dead during the PV)
|
||||
const size_t qrow = static_cast<size_t>(h) * NP + row0 + mt * 8;
|
||||
const uint16_t* qh = Qh + qrow * kQK;
|
||||
const uint16_t* ql = Ql + qrow * kQK;
|
||||
|
||||
// joint_matrix variables are declared once at the top of the kernel
|
||||
Acc<J> c1, cx, pa, px;
|
||||
AOp<J> ah, al;
|
||||
BOp<J> bh, bl;
|
||||
|
||||
float m_run = kNeg, l_run = 0.0f;
|
||||
float o[4][8]; // O state: dims nd * 64 + 16 j + lane of rows mt * 8 + i
|
||||
const size_t obase = (static_cast<size_t>(row0 + mt * 8) * H + h) * kVD + nd * 64 + lane;
|
||||
const size_t ldo = static_cast<size_t>(H) * kVD;
|
||||
if (first) {
|
||||
for (int j = 0; j < 4; ++j)
|
||||
for (int i = 0; i < 8; ++i) o[j][i] = 0.0f;
|
||||
} else {
|
||||
for (int j = 0; j < 4; ++j)
|
||||
for (int i = 0; i < 8; ++i) o[j][i] = Oacc[obase + i * ldo + j * 16];
|
||||
const size_t ri = (static_cast<size_t>(row0 + srow) * H + h) * 2;
|
||||
m_run = ML[ri];
|
||||
l_run = ML[ri + 1];
|
||||
}
|
||||
const int qpos = pos0 + row0 + srow; // position of this thread's softmax row
|
||||
const bool qvalid = row0 + srow < N;
|
||||
|
||||
for (int j = 0; j < ntiles; ++j) {
|
||||
b.sync(); // the tile buffers of the previous tile are free
|
||||
// ---- K / V tile (hi, lo) into shared memory: K rows d-pair r, keys 32 j .. 32 j + 31 (64 halves); V is 16 key-pair rows of 256 halves, contiguous
|
||||
{
|
||||
const sycl::uint4* gkh = reinterpret_cast<const sycl::uint4*>(Kh + static_cast<size_t>(h) * 96 * S);
|
||||
const sycl::uint4* gkl = reinterpret_cast<const sycl::uint4*>(Kl + static_cast<size_t>(h) * 96 * S);
|
||||
for (int u = tid; u < 96 * 8; u += kAttThreads) {
|
||||
const int r = u >> 3, c = u & 7; // 8 chunks of 16 B = 32 words = 32 keys per row
|
||||
const size_t g = (static_cast<size_t>(r) * S + kBK * j) / 4 + c;
|
||||
*reinterpret_cast<sycl::uint4*>(sKh + r * kLdK + c * 8) = gkh[g];
|
||||
*reinterpret_cast<sycl::uint4*>(sKl + r * kLdK + c * 8) = gkl[g];
|
||||
}
|
||||
const sycl::uint4* gvh = reinterpret_cast<const sycl::uint4*>(Vh + (static_cast<size_t>(h) * (S / 2) + 16 * j) * kVD);
|
||||
const sycl::uint4* gvl = reinterpret_cast<const sycl::uint4*>(Vl + (static_cast<size_t>(h) * (S / 2) + 16 * j) * kVD);
|
||||
for (int u = tid; u < 16 * 32; u += kAttThreads) { // 16 rows x 32 chunks of 16 B
|
||||
const int r = u >> 5, c = u & 31;
|
||||
*reinterpret_cast<sycl::uint4*>(sVh + r * kLdV + c * 8) = gvh[u];
|
||||
*reinterpret_cast<sycl::uint4*>(sVl + r * kLdV + c * 8) = gvl[u];
|
||||
}
|
||||
}
|
||||
b.sync();
|
||||
// ---- scores of this sub-group's 8 rows against 16 keys (key half nd)
|
||||
acc_fill<J>(b, c1, 0.0f);
|
||||
acc_fill<J>(b, cx, 0.0f);
|
||||
for (int ks = 0; ks < kQK / 16; ++ks) {
|
||||
a_load<J, kGlb>(b, ah, qh + ks * 16, kQK);
|
||||
a_load<J, kGlb>(b, al, ql + ks * 16, kQK);
|
||||
b_load<J, kLoc>(b, bh, sKh + ks * 8 * kLdK + nd * 32, kLdK);
|
||||
b_load<J, kLoc>(b, bl, sKl + ks * 8 * kLdK + nd * 32, kLdK);
|
||||
mad<J>(b, c1, ah, bh);
|
||||
mad<J>(b, cx, ah, bl);
|
||||
mad<J>(b, cx, al, bh);
|
||||
}
|
||||
acc_store<J, kLoc>(b, c1, sS + mt * 8 * kLdS + nd * 16, kLdS);
|
||||
acc_store<J, kLoc>(b, cx, sX + mt * 8 * kLdS + nd * 16, kLdS);
|
||||
b.sync();
|
||||
// ---- online softmax: thread = (row srow, 8 keys spart * 8 ..)
|
||||
{
|
||||
float sv[8];
|
||||
float mx = kNeg;
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int key = spart * 8 + e;
|
||||
const int kl_ = kBK * j + key; // key index in the slab
|
||||
const bool vis = qvalid && kl_ < nk_valid && k0 + kl_ <= qpos;
|
||||
sv[e] = vis ? (sS[srow * kLdS + key] + sX[srow * kLdS + key] * kInv2048) * scale : kNeg;
|
||||
mx = sycl::fmax(mx, sv[e]);
|
||||
}
|
||||
mx = sycl::fmax(mx, b.shfl_xor(mx, 1));
|
||||
mx = sycl::fmax(mx, b.shfl_xor(mx, 2));
|
||||
const float mn = sycl::fmax(m_run, mx);
|
||||
float corr, ps = 0.0f;
|
||||
if (mn <= -1.0e38f) {
|
||||
corr = 1.0f;
|
||||
for (int e = 0; e < 8; ++e) sv[e] = 0.0f;
|
||||
} else {
|
||||
corr = (m_run <= -1.0e38f) ? 0.0f : sycl::exp(m_run - mn);
|
||||
for (int e = 0; e < 8; ++e) sv[e] = (sv[e] > -1.0e38f) ? sycl::exp(sv[e] - mn) : 0.0f;
|
||||
}
|
||||
for (int e = 0; e < 8; ++e) ps += sv[e];
|
||||
ps += b.shfl_xor(ps, 1);
|
||||
ps += b.shfl_xor(ps, 2);
|
||||
l_run = l_run * corr + ps;
|
||||
m_run = mn;
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
uint16_t hi, lo;
|
||||
split_h(sv[e], hi, lo);
|
||||
sPh[srow * kLdP + spart * 8 + e] = hi;
|
||||
sPl[srow * kLdP + spart * 8 + e] = lo;
|
||||
}
|
||||
if (spart == 0) sCorr[srow] = corr;
|
||||
}
|
||||
b.sync();
|
||||
// ---- O = O corr + P V (rows mt * 8 .., dims nd * 64 ..): fresh products per 16-dim tile, added to the state in plain code
|
||||
float cr[8];
|
||||
for (int i = 0; i < 8; ++i) cr[i] = sCorr[mt * 8 + i];
|
||||
for (int jj = 0; jj < 4; ++jj) {
|
||||
acc_fill<J>(b, pa, 0.0f);
|
||||
acc_fill<J>(b, px, 0.0f);
|
||||
for (int ks = 0; ks < kBK / 16; ++ks) {
|
||||
a_load<J, kLoc>(b, ah, sPh + mt * 8 * kLdP + ks * 16, kLdP);
|
||||
a_load<J, kLoc>(b, al, sPl + mt * 8 * kLdP + ks * 16, kLdP);
|
||||
b_load<J, kLoc>(b, bh, sVh + ks * 8 * kLdV + (nd * 64 + jj * 16) * 2, kLdV);
|
||||
b_load<J, kLoc>(b, bl, sVl + ks * 8 * kLdV + (nd * 64 + jj * 16) * 2, kLdV);
|
||||
mad<J>(b, pa, ah, bh);
|
||||
mad<J>(b, px, ah, bl);
|
||||
mad<J>(b, px, al, bh);
|
||||
}
|
||||
acc_store<J, kLoc>(b, pa, scr, 16);
|
||||
acc_store<J, kLoc>(b, px, scr + 128, 16);
|
||||
b.warp_sync();
|
||||
for (int i = 0; i < 8; ++i) o[jj][i] = o[jj][i] * cr[i] + (scr[i * 16 + lane] + scr[128 + i * 16 + lane] * kInv2048);
|
||||
b.warp_sync();
|
||||
}
|
||||
}
|
||||
// ---- state out: O, m, l
|
||||
for (int jj = 0; jj < 4; ++jj)
|
||||
for (int i = 0; i < 8; ++i) Oacc[obase + i * ldo + jj * 16] = o[jj][i];
|
||||
if (spart == 0) {
|
||||
const size_t ri = (static_cast<size_t>(row0 + srow) * H + h) * 2;
|
||||
ML[ri] = m_run;
|
||||
ML[ri + 1] = l_run;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// out[t][h][v] = O / l * sigmoid(gate[t][h]). grid (N * H), 128 threads
|
||||
void finalize(const float* Oacc, const float* ML, const float* gate, float* out, int N, int H, cudaStream_t s) {
|
||||
launch16(s, N * H, kVD, 0, [=](sy::Blk b, char*) {
|
||||
const size_t th = static_cast<size_t>(b.bid());
|
||||
const float l = ML[th * 2 + 1];
|
||||
const float mult = l > 0.0f ? 1.0f / l : 0.0f;
|
||||
const float gv = 1.0f / (1.0f + sycl::exp(-gate[th]));
|
||||
out[th * kVD + b.tid()] = Oacc[th * kVD + b.tid()] * mult * gv;
|
||||
});
|
||||
}
|
||||
|
||||
// which flavour runs here: 2 = joint_matrix (Battlemage, PVC, Lunar Lake), 1 = plain loops (any device, when forced: STRATA_L32_MLA_EXP_MODE=1), 0 = not available
|
||||
int exp_mode(cudaStream_t s) {
|
||||
static int cache[64];
|
||||
static bool done[64];
|
||||
int dev = 0;
|
||||
cudaGetDevice(&dev);
|
||||
dev &= 63;
|
||||
if (done[dev]) return cache[dev];
|
||||
int mode = 0;
|
||||
const char* e = std::getenv("STRATA_L32_MLA_EXP_MODE");
|
||||
const int env = e ? std::atoi(e) : -1; // 0 off, 1 force plain loops, else auto
|
||||
#if L32X_HAVE_JM
|
||||
namespace exo = sycl::ext::oneapi::experimental;
|
||||
switch (strata::sy::queue_of(s).get_device().get_info<exo::info::device::architecture>()) {
|
||||
case exo::architecture::intel_gpu_bmg_g21:
|
||||
case exo::architecture::intel_gpu_bmg_g31:
|
||||
case exo::architecture::intel_gpu_pvc:
|
||||
case exo::architecture::intel_gpu_lnl_m: mode = 2; break;
|
||||
default: break;
|
||||
}
|
||||
#endif
|
||||
if (env == 0) mode = 0;
|
||||
else if (env == 1 && mode == 0) mode = 1;
|
||||
done[dev] = true;
|
||||
cache[dev] = mode;
|
||||
return mode;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool mla_exp_ok(int nope, int rope, int vhead, int kv_lora) { return nope == kNope && rope == kRope && vhead == kVD && kv_lora == kR && exp_mode(0) != 0; }
|
||||
|
||||
// workspace for chunks of up to nmax tokens, H heads, slab keys per slab: K planes (hi, lo) [H][96][S] words, V planes [H][S / 2][128] words, Q planes [H][NP][192] halves, O state [NP][H][128], m / l [NP][H][2]
|
||||
size_t mla_exp_workspace_bytes(int nmax, int H, int slab) {
|
||||
const size_t np = (static_cast<size_t>(nmax) + kBM - 1) / kBM * kBM;
|
||||
const size_t kv = static_cast<size_t>(H) * slab * (2 * 96 + 2 * (kVD / 2)) * 4;
|
||||
const size_t qp = static_cast<size_t>(H) * np * kQK * 2 * 2;
|
||||
const size_t st = np * H * (kVD + 2) * 4;
|
||||
return kv + qp + st + 4096;
|
||||
}
|
||||
|
||||
void mla_exp_convert_weights(const uint16_t* bf16_in, size_t n, uint16_t* fp16_out, cudaStream_t s) { convert_weights(bf16_in, n, fp16_out, s); }
|
||||
|
||||
// q [N][H][192] (nope then rope), cache fp32 [kv][lat_stride] (c 512 then k_pe 64), out [N][H][128] (already times sigmoid(gate)). pos0 = cache position of token 0; the keys are 0 .. pos0 + N - 1.
|
||||
void mla_exp_prefill(const float* q, const float* cache, int lat_stride, const uint16_t* wk16, const uint16_t* wv16, const float* gate, float* out, int N, int H, int pos0, float scale, void* ws, size_t ws_bytes,
|
||||
int slab, cudaStream_t s) {
|
||||
if (slab <= 0 || (slab % 64) != 0) {
|
||||
std::fprintf(stderr, "ling32: expanded MLA slab must be a multiple of 64\n");
|
||||
std::abort();
|
||||
}
|
||||
const int mode = exp_mode(s);
|
||||
if (mode == 0) {
|
||||
std::fprintf(stderr, "ling32 (SYCL): the expanded MLA prefill needs XMX (or STRATA_L32_MLA_EXP_MODE=1 for the plain-loop test mode)\n");
|
||||
std::abort();
|
||||
}
|
||||
const int NP = (N + kBM - 1) / kBM * kBM;
|
||||
char* p = static_cast<char*>(ws);
|
||||
auto carve = [&](size_t bytes) { char* r = p; p += (bytes + 255) / 256 * 256; return r; };
|
||||
const size_t kplane = static_cast<size_t>(H) * 96 * slab * 4, vplane = static_cast<size_t>(H) * (slab / 2) * kVD * 4, qplane = static_cast<size_t>(H) * NP * kQK * 2;
|
||||
uint32_t* Kh = reinterpret_cast<uint32_t*>(carve(kplane));
|
||||
uint32_t* Kl = reinterpret_cast<uint32_t*>(carve(kplane));
|
||||
uint32_t* Vh = reinterpret_cast<uint32_t*>(carve(vplane));
|
||||
uint32_t* Vl = reinterpret_cast<uint32_t*>(carve(vplane));
|
||||
uint16_t* Qh = reinterpret_cast<uint16_t*>(carve(qplane));
|
||||
uint16_t* Ql = reinterpret_cast<uint16_t*>(carve(qplane));
|
||||
float* Oacc = reinterpret_cast<float*>(carve(static_cast<size_t>(NP) * H * kVD * 4));
|
||||
float* ML = reinterpret_cast<float*>(carve(static_cast<size_t>(NP) * H * 2 * 4));
|
||||
if (static_cast<size_t>(p - static_cast<char*>(ws)) > ws_bytes) {
|
||||
std::fprintf(stderr, "ling32: expanded MLA workspace too small\n");
|
||||
std::abort();
|
||||
}
|
||||
qprep(q, Qh, Ql, N, NP, H, s);
|
||||
const int total = pos0 + N;
|
||||
for (int k0 = 0; k0 < total; k0 += slab) {
|
||||
const int nvalid = std::min(slab, total - k0);
|
||||
if (mode == 2) {
|
||||
proj<true>(cache, lat_stride, wk16, wv16, Kh, Kl, Vh, Vl, H, slab, k0, nvalid, s);
|
||||
attn<true>(Qh, Ql, Kh, Kl, Vh, Vl, Oacc, ML, N, NP, H, pos0, k0, slab, nvalid, k0 == 0 ? 1 : 0, scale, s);
|
||||
} else {
|
||||
proj<false>(cache, lat_stride, wk16, wv16, Kh, Kl, Vh, Vl, H, slab, k0, nvalid, s);
|
||||
attn<false>(Qh, Ql, Kh, Kl, Vh, Vl, Oacc, ML, N, NP, H, pos0, k0, slab, nvalid, k0 == 0 ? 1 : 0, scale, s);
|
||||
}
|
||||
}
|
||||
finalize(Oacc, ML, gate, out, N, H, s);
|
||||
}
|
||||
|
||||
} // namespace strata::ling32::gpu
|
||||
@@ -259,7 +259,7 @@ void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int
|
||||
|
||||
void mla_attn(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, bool cache_f32_b, cudaStream_t s) {
|
||||
// the context length is on the device (d_pos0), so the choice is by geometry only; at a short context the flash kernel costs about the same as the original (slices beyond L return at once)
|
||||
static const bool force_orig = std::getenv("LING32_SY_MLA_ORIG") != nullptr; // A/B switch
|
||||
static const bool force_orig = std::getenv("STRATA_L32_MLA_FD_ORIG") != nullptr; // A/B switch
|
||||
if (!force_orig && mla_attn_fd_supported(N, H, rope, kv_lora, cache_f32_b)) mla_attn_fd(qabs, q, cache, d_pos0, ctx, N, H, nope, rope, kv_lora, scale, s, 3);
|
||||
else mla_attn_orig(qabs, q, cache, d_pos0, ctx, N, H, nope, rope, kv_lora, scale, cache_f32_b, s);
|
||||
}
|
||||
@@ -273,10 +273,10 @@ void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int
|
||||
std::abort();
|
||||
}
|
||||
const FdScratch& sc = fd_scratch(H);
|
||||
static const int rb_env = std::getenv("LING32_SY_MLA_FD_RB") ? std::atoi(std::getenv("LING32_SY_MLA_FD_RB")) : 1; // tuning switches: rows per QK batch (1, 2)
|
||||
static const int ns_env = std::getenv("LING32_SY_MLA_FD_NS") ? std::min(kFdMaxSplits, std::max(1, std::atoi(std::getenv("LING32_SY_MLA_FD_NS")))) : kFdSplitsDef; // slices
|
||||
static const int rb_env = std::getenv("STRATA_L32_MLA_FD_RB") ? std::atoi(std::getenv("STRATA_L32_MLA_FD_RB")) : 1; // tuning switches: rows per QK batch (1, 2)
|
||||
static const int ns_env = std::getenv("STRATA_L32_MLA_FD_NS") ? std::min(kFdMaxSplits, std::max(1, std::atoi(std::getenv("STRATA_L32_MLA_FD_NS")))) : kFdSplitsDef; // slices
|
||||
const int ns = ns_env;
|
||||
static const int pvu_env = std::getenv("LING32_SY_MLA_FD_PVU") ? std::atoi(std::getenv("LING32_SY_MLA_FD_PVU")) : 1; // and PV rows in flight (1, 2, 4)
|
||||
static const int pvu_env = std::getenv("STRATA_L32_MLA_FD_PVU") ? std::atoi(std::getenv("STRATA_L32_MLA_FD_PVU")) : 1; // and PV rows in flight (1, 2, 4)
|
||||
if (stages & 1) {
|
||||
const float* cf = static_cast<const float*>(cache);
|
||||
#define L32_FD_S1(RB_, PVU_) fd_stage1<RB_, PVU_>(qabs, q, cf, d_pos0, sc.part, sc.ml, N, H, nope, rope, scale, ns, s)
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
// src/ling32/sycl/ling32_sy_k_vision.cpp - the Ling-3.2-Air picture encoder on an Intel GPU (SYCL). The interface is ling32_vision_gpu.hpp (the CUDA / HIP one is ling32_vision_gpu.cu).
|
||||
//
|
||||
// Same structure as the CUDA encoder: float32 tiled SGEMM (BF16 or float weights), LayerNorm, 2-D rope, an online-softmax attention without an S x S matrix, GELU, the position grid. The SYCL
|
||||
// rules of ling32_sy.hpp apply (no double in a kernel: the position-grid weights and the rope tables are computed on the host in double, like the CPU encoder, and uploaded; sub-group 32).
|
||||
//
|
||||
// Device memory (the planner reserves 1600 MiB for the encoder, see ling32_main.cpp): the weights stay resident (about 830 MiB, freed by the idle thread or unload()); the activations of one
|
||||
// picture are allocated per call, about 34 KB per patch (4096 embeddings = 16384 patches: ~0.56 GiB, the MLP is done in row chunks). A picture that does not fit in the free device memory
|
||||
// is refused before anything is allocated (encode() returns false with a message: the caller falls back to the CPU encoder), and every allocation failure is caught the same way.
|
||||
#include "../ling32_vision_gpu.hpp"
|
||||
#include "ling32_sy.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace strata::ling32 {
|
||||
|
||||
namespace {
|
||||
|
||||
using gpu::sy::Blk;
|
||||
using gpu::sy::launch;
|
||||
|
||||
bool cuok(cudaError_t e, const char* what, std::string& err) {
|
||||
if (e == cudaSuccess) return true;
|
||||
err = std::string(what) + ": " + cudaGetErrorString(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
constexpr int BM = 64, BN = 64, BK = 16;
|
||||
constexpr int AQ = 8, AK = 64, AHD = 72;
|
||||
constexpr int kMlpRows = 4096; // rows of the MLP intermediate that exist at one time
|
||||
// the device memory the tier planner leaves to the encoder (ling32_main.cpp: reserve_bytes += 1600 MiB when the GPU picture encoder is in use): weights + the activations of one picture must fit in it.
|
||||
// The driver's free-memory query is not used for this: on some Level Zero setups it does not move when memory is allocated.
|
||||
constexpr uint64_t kBudgetBytes = 1600ull << 20;
|
||||
constexpr uint64_t kMinActivationBytes = 64ull << 20;
|
||||
|
||||
inline float bf2f(uint16_t v) { return sycl::bit_cast<float>(static_cast<uint32_t>(v) << 16); }
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------- SGEMM
|
||||
// C[m, n] = (add ? C : 0) + bias[n] + sum_k A[m, k] * W[n, k]; A float [M, lda], W BF16 or float [N, ldw]; K % 4 == 0, lda and ldw multiples of 4.
|
||||
// 64 x 64 tile, 16 deep, 256 threads, 4 x 4 per thread, plain fp32 FMA.
|
||||
void gemm(cudaStream_t s, int M, int N, int K, const float* A, int lda, const void* Wp, bool bf16, int ldw, const float* bias, float* C, int ldc, bool add) {
|
||||
const int gx = (N + BN - 1) / BN, gy = (M + BM - 1) / BM;
|
||||
const size_t smem = sizeof(float) * BK * (BM + 4) * 2;
|
||||
launch(s, gx * gy, 256, smem, [=](Blk b, char* sm) {
|
||||
float(*As)[BM + 4] = reinterpret_cast<float(*)[BM + 4]>(sm);
|
||||
float(*Bs)[BN + 4] = reinterpret_cast<float(*)[BN + 4]>(sm + sizeof(float) * BK * (BM + 4));
|
||||
const int tid = b.tid(), tx = tid & 15, ty = tid >> 4;
|
||||
const int n0 = (b.bid() % gx) * BN, m0 = (b.bid() / gx) * BM;
|
||||
const int lrow = tid >> 2, lk = (tid & 3) * 4;
|
||||
float acc[4][4] = {};
|
||||
for (int k0 = 0; k0 < K; k0 += BK) {
|
||||
float a[4] = {0.f, 0.f, 0.f, 0.f}, w[4] = {0.f, 0.f, 0.f, 0.f};
|
||||
if (m0 + lrow < M && k0 + lk < K) {
|
||||
const sycl::float4 v = *reinterpret_cast<const sycl::float4*>(A + static_cast<size_t>(m0 + lrow) * lda + k0 + lk);
|
||||
a[0] = v.x(); a[1] = v.y(); a[2] = v.z(); a[3] = v.w();
|
||||
}
|
||||
if (n0 + lrow < N && k0 + lk < K) {
|
||||
if (bf16) {
|
||||
const uint16_t* p = static_cast<const uint16_t*>(Wp) + static_cast<size_t>(n0 + lrow) * ldw + k0 + lk;
|
||||
const uint32_t u0 = *reinterpret_cast<const uint32_t*>(p), u1 = *reinterpret_cast<const uint32_t*>(p + 2);
|
||||
w[0] = sycl::bit_cast<float>(u0 << 16); w[1] = sycl::bit_cast<float>(u0 & 0xffff0000u);
|
||||
w[2] = sycl::bit_cast<float>(u1 << 16); w[3] = sycl::bit_cast<float>(u1 & 0xffff0000u);
|
||||
} else {
|
||||
const sycl::float4 v = *reinterpret_cast<const sycl::float4*>(static_cast<const float*>(Wp) + static_cast<size_t>(n0 + lrow) * ldw + k0 + lk);
|
||||
w[0] = v.x(); w[1] = v.y(); w[2] = v.z(); w[3] = v.w();
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < 4; ++i) { As[lk + i][lrow] = a[i]; Bs[lk + i][lrow] = w[i]; }
|
||||
b.sync();
|
||||
#pragma unroll
|
||||
for (int kk = 0; kk < BK; ++kk) {
|
||||
const sycl::float4 av = *reinterpret_cast<const sycl::float4*>(&As[kk][ty * 4]);
|
||||
const sycl::float4 bv = *reinterpret_cast<const sycl::float4*>(&Bs[kk][tx * 4]);
|
||||
const float ar[4] = {av.x(), av.y(), av.z(), av.w()}, br[4] = {bv.x(), bv.y(), bv.z(), bv.w()};
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) acc[i][j] = sycl::fma(ar[i], br[j], acc[i][j]);
|
||||
}
|
||||
b.sync();
|
||||
}
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const int m = m0 + ty * 4 + i;
|
||||
if (m >= M) continue;
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
const int n = n0 + tx * 4 + j;
|
||||
if (n >= N) continue;
|
||||
const float v = acc[i][j] + (bias ? bias[n] : 0.0f);
|
||||
float* c = C + static_cast<size_t>(m) * ldc + n;
|
||||
*c = add ? *c + v : v;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------- small kernels
|
||||
inline float warp_sum(const Blk& b, float v) {
|
||||
for (int o = 16; o > 0; o >>= 1) v += b.shfl_xor(v, o);
|
||||
return v;
|
||||
}
|
||||
inline float warp_max(const Blk& b, float v) {
|
||||
for (int o = 16; o > 0; o >>= 1) v = sycl::fmax(v, b.shfl_xor(v, o));
|
||||
return v;
|
||||
}
|
||||
|
||||
// LayerNorm over D per row; one warp per row, 8 rows per block of 256 threads; two passes, float accumulation in a fixed order
|
||||
void layernorm(cudaStream_t s, const float* x, const float* w, const float* bb, float* y, int rows, int D, float eps) {
|
||||
launch(s, (rows + 7) / 8, 256, 0, [=](Blk b, char*) {
|
||||
const int row = b.bid() * 8 + b.warp(), lane = b.lane();
|
||||
if (row >= rows) return;
|
||||
const float* xr = x + static_cast<size_t>(row) * D;
|
||||
float sum = 0;
|
||||
for (int i = lane; i < D; i += 32) sum += xr[i];
|
||||
const float mu = warp_sum(b, sum) / D;
|
||||
float v = 0;
|
||||
for (int i = lane; i < D; i += 32) { const float d = xr[i] - mu; v += d * d; }
|
||||
const float inv = 1.0f / sycl::sqrt(warp_sum(b, v) / D + eps);
|
||||
float* yr = y + static_cast<size_t>(row) * D;
|
||||
for (int i = lane; i < D; i += 32) yr[i] = (xr[i] - mu) * inv * w[i] + bb[i];
|
||||
});
|
||||
}
|
||||
|
||||
void gelu(cudaStream_t s, float* x, size_t n, bool erf_form) {
|
||||
const int blocks = static_cast<int>(std::min<size_t>(4096, (n + 255) / 256));
|
||||
launch(s, blocks, 256, 0, [=](Blk b, char*) {
|
||||
for (size_t i = static_cast<size_t>(b.bid()) * 256 + b.tid(); i < n; i += static_cast<size_t>(b.nblk()) * 256) {
|
||||
const float v = x[i];
|
||||
x[i] = erf_form ? 0.5f * v * (1.0f + sycl::erf(v * 0.7071067811865476f)) : 0.5f * v * (1.0f + sycl::tanh(0.7978845608028654f * (v + 0.044715f * v * v * v)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// position grid: x[patch] += w00 * pos[i00] + w01 * pos[i01] + w10 * pos[i10] + w11 * pos[i11] (BF16 rows); the table pt holds per patch 4 row indices and 4 weights (computed on the host in double). One block per patch.
|
||||
void pos_embed(cudaStream_t s, float* x, const uint16_t* pos, const int* pidx, const float* pw, int S, int D) {
|
||||
launch(s, S, 128, 0, [=](Blk b, char*) {
|
||||
const int p = b.bid();
|
||||
const int i00 = pidx[p * 4], i01 = pidx[p * 4 + 1], i10 = pidx[p * 4 + 2], i11 = pidx[p * 4 + 3];
|
||||
const float w00 = pw[p * 4], w01 = pw[p * 4 + 1], w10 = pw[p * 4 + 2], w11 = pw[p * 4 + 3];
|
||||
const uint16_t *p00 = pos + static_cast<size_t>(i00) * D, *p01 = pos + static_cast<size_t>(i01) * D, *p10 = pos + static_cast<size_t>(i10) * D, *p11 = pos + static_cast<size_t>(i11) * D;
|
||||
for (int i = b.tid(); i < D; i += 128) x[static_cast<size_t>(p) * D + i] += bf2f(p00[i]) * w00 + bf2f(p01[i]) * w01 + bf2f(p10[i]) * w10 + bf2f(p11[i]) * w11;
|
||||
});
|
||||
}
|
||||
|
||||
// 2-D rope on q and k inside qkv [S, 3D]: head dims 0..17 use the row angle, 18..35 the column angle (dim j pairs with j + 36). cs / sn: [position][nf] (host tables). grid S, block 128
|
||||
void rope(cudaStream_t s, float* qkv, const int* prow, const int* pcol, const float* cs, const float* sn, int S, int H, int hd, int D) {
|
||||
const int half = hd / 2, nf = half / 2;
|
||||
launch(s, S, 128, 0, [=](Blk b, char*) {
|
||||
const int sp = b.bid();
|
||||
for (int idx = b.tid(); idx < 2 * H * half; idx += 128) {
|
||||
const int part = idx / (H * half), hh = (idx / half) % H, j = idx % half;
|
||||
const int pos = j < nf ? prow[sp] : pcol[sp];
|
||||
const int f = j % nf;
|
||||
const float co = cs[pos * nf + f], si = sn[pos * nf + f];
|
||||
float* v = qkv + static_cast<size_t>(sp) * 3 * D + part * D + hh * hd;
|
||||
const float a = v[j], bq = v[j + half];
|
||||
v[j] = a * co - bq * si;
|
||||
v[j + half] = bq * co + a * si;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// full attention inside the picture, online softmax; one warp per query row, 8 queries and 64 keys per tile. hd must be 72 (3 values per lane: dims lane, lane + 32, lane + 64 < 72).
|
||||
void attention(cudaStream_t s, const float* qkv, float* out, int S, int H, int D, float scale) {
|
||||
const int gx = (S + AQ - 1) / AQ;
|
||||
const size_t smem = sizeof(float) * (AQ * AHD + AK * (AHD + 1) + AK * AHD + AQ * AK);
|
||||
launch(s, gx * H, 256, smem, [=](Blk b, char* sm) {
|
||||
float* qs = reinterpret_cast<float*>(sm); // [AQ][AHD]
|
||||
float* Ks = qs + AQ * AHD; // [AK][AHD + 1]
|
||||
float* Vs = Ks + AK * (AHD + 1); // [AK][AHD]
|
||||
float* ps = Vs + AK * AHD; // [AQ][AK]
|
||||
const int w = b.warp(), lane = b.lane(), hh = b.bid() / gx, q = (b.bid() % gx) * AQ + w;
|
||||
const size_t rs = static_cast<size_t>(3) * D;
|
||||
if (q < S)
|
||||
for (int d = lane; d < AHD; d += 32) qs[w * AHD + d] = qkv[q * rs + hh * AHD + d];
|
||||
float o[3] = {0.f, 0.f, 0.f}, m = -INFINITY, l = 0.f;
|
||||
for (int j0 = 0; j0 < S; j0 += AK) {
|
||||
b.sync();
|
||||
for (int i = b.tid(); i < AK * AHD; i += 256) {
|
||||
const int j = i / AHD, d = i % AHD;
|
||||
const bool ok = j0 + j < S;
|
||||
Ks[j * (AHD + 1) + d] = ok ? qkv[(j0 + j) * rs + D + hh * AHD + d] : 0.f;
|
||||
Vs[j * AHD + d] = ok ? qkv[(j0 + j) * rs + 2 * D + hh * AHD + d] : 0.f;
|
||||
}
|
||||
b.sync();
|
||||
if (q < S) {
|
||||
float s0 = 0.f, s1 = 0.f;
|
||||
#pragma unroll 8
|
||||
for (int d = 0; d < AHD; ++d) {
|
||||
const float qd = qs[w * AHD + d];
|
||||
s0 = sycl::fma(qd, Ks[lane * (AHD + 1) + d], s0);
|
||||
s1 = sycl::fma(qd, Ks[(lane + 32) * (AHD + 1) + d], s1);
|
||||
}
|
||||
s0 = (j0 + lane < S) ? s0 * scale : -INFINITY;
|
||||
s1 = (j0 + lane + 32 < S) ? s1 * scale : -INFINITY;
|
||||
const float mn = sycl::fmax(m, warp_max(b, sycl::fmax(s0, s1)));
|
||||
const float corr = sycl::exp(m - mn); // exp(-inf) = 0 on the first tile
|
||||
const float p0 = sycl::exp(s0 - mn), p1 = sycl::exp(s1 - mn);
|
||||
l = l * corr + warp_sum(b, p0 + p1);
|
||||
m = mn;
|
||||
ps[w * AK + lane] = p0;
|
||||
ps[w * AK + lane + 32] = p1;
|
||||
b.warp_sync();
|
||||
o[0] *= corr; o[1] *= corr; o[2] *= corr;
|
||||
#pragma unroll 8
|
||||
for (int j = 0; j < AK; ++j) {
|
||||
const float p = ps[w * AK + j];
|
||||
o[0] = sycl::fma(p, Vs[j * AHD + lane], o[0]);
|
||||
o[1] = sycl::fma(p, Vs[j * AHD + lane + 32], o[1]);
|
||||
if (lane < AHD - 64) o[2] = sycl::fma(p, Vs[j * AHD + lane + 64], o[2]);
|
||||
}
|
||||
b.warp_sync();
|
||||
}
|
||||
}
|
||||
if (q < S) {
|
||||
const float inv = 1.0f / l;
|
||||
float* op = out + static_cast<size_t>(q) * D + hh * AHD;
|
||||
op[lane] = o[0] * inv;
|
||||
op[lane + 32] = o[1] * inv;
|
||||
if (lane < AHD - 64) op[lane + 64] = o[2] * inv;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------- the encoder object
|
||||
struct VisionGpu::Dev {
|
||||
uint8_t* arena = nullptr;
|
||||
uint64_t bytes = 0;
|
||||
uint16_t *patch_w = nullptr, *pos = nullptr, *lp0_w = nullptr, *lp2_w = nullptr;
|
||||
float *patch_b = nullptr, *merger_w = nullptr, *merger_b = nullptr, *lp0_b = nullptr, *lp2_b = nullptr;
|
||||
struct Blk {
|
||||
float *n1w, *n1b, *n2w, *n2b, *qkv_b, *proj_b, *fc1_b, *fc2_b;
|
||||
uint16_t *qkv_w, *proj_w, *fc1_w, *fc2_w;
|
||||
};
|
||||
std::vector<Blk> blk;
|
||||
};
|
||||
|
||||
uint64_t vision_gpu_total_bytes(int device) {
|
||||
size_t f = 0, t = 0;
|
||||
if (cudaSetDevice(device) != cudaSuccess) return 0;
|
||||
if (cudaMemGetInfo(&f, &t) != cudaSuccess) t = 0;
|
||||
return t;
|
||||
}
|
||||
|
||||
VisionGpu::VisionGpu(const std::string& vision_file, int device, double idle_seconds) : file_(vision_file), device_(device), idle_(idle_seconds) {
|
||||
last_use_ = std::chrono::steady_clock::now();
|
||||
th_ = std::thread([this] { idle_loop(); });
|
||||
}
|
||||
|
||||
VisionGpu::~VisionGpu() {
|
||||
{
|
||||
std::lock_guard<std::mutex> g(mu_);
|
||||
stop_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
if (th_.joinable()) th_.join();
|
||||
std::lock_guard<std::mutex> g(mu_);
|
||||
unload_locked();
|
||||
}
|
||||
|
||||
bool VisionGpu::loaded() const {
|
||||
std::lock_guard<std::mutex> g(mu_);
|
||||
return d_ != nullptr;
|
||||
}
|
||||
uint64_t VisionGpu::device_bytes() const {
|
||||
std::lock_guard<std::mutex> g(mu_);
|
||||
return d_ ? d_->bytes : 0;
|
||||
}
|
||||
void VisionGpu::set_idle_seconds(double s) {
|
||||
{
|
||||
std::lock_guard<std::mutex> g(mu_);
|
||||
idle_ = s;
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
void VisionGpu::unload() {
|
||||
std::lock_guard<std::mutex> g(mu_);
|
||||
unload_locked();
|
||||
}
|
||||
|
||||
void VisionGpu::unload_locked() {
|
||||
if (!d_) return;
|
||||
cudaSetDevice(device_);
|
||||
cudaDeviceSynchronize();
|
||||
cudaFree(d_->arena);
|
||||
delete d_;
|
||||
d_ = nullptr;
|
||||
++unloads_;
|
||||
if (on_unload_) on_unload_();
|
||||
}
|
||||
|
||||
void VisionGpu::idle_loop() {
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
while (!stop_) {
|
||||
if (!d_ || idle_ <= 0) {
|
||||
cv_.wait(lk);
|
||||
continue;
|
||||
}
|
||||
const auto deadline = last_use_ + std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double>(idle_));
|
||||
if (std::chrono::steady_clock::now() >= deadline) {
|
||||
if (!busy_) unload_locked();
|
||||
else cv_.wait_for(lk, std::chrono::milliseconds(200));
|
||||
continue;
|
||||
}
|
||||
cv_.wait_until(lk, deadline);
|
||||
}
|
||||
}
|
||||
|
||||
bool VisionGpu::load_locked(std::string& err) {
|
||||
if (d_) return true;
|
||||
VisionWeights W; // host copy, released at the end of this function
|
||||
if (!W.load(file_, err)) return false;
|
||||
cfg_ = W.c;
|
||||
if (!cuok(cudaSetDevice(device_), "cudaSetDevice", err)) return false;
|
||||
auto up = [](uint64_t& total, size_t n) { const uint64_t o = total; total += (n + 255) & ~size_t(255); return o; };
|
||||
uint64_t total = 0;
|
||||
struct Item { const void* src; size_t bytes; uint64_t off; };
|
||||
std::vector<Item> items;
|
||||
auto add = [&](const void* p, size_t n) { items.push_back({p, n, up(total, n)}); return items.size() - 1; };
|
||||
const size_t i_patch_w = add(W.patch_w.data(), W.patch_w.size() * 2), i_patch_b = add(W.patch_b.data(), W.patch_b.size() * 4), i_pos = add(W.pos.data(), W.pos.size() * 2),
|
||||
i_mw = add(W.merger_w.data(), W.merger_w.size() * 4), i_mb = add(W.merger_b.data(), W.merger_b.size() * 4), i_l0w = add(W.lp0_w.data(), W.lp0_w.size() * 2),
|
||||
i_l0b = add(W.lp0_b.data(), W.lp0_b.size() * 4), i_l2w = add(W.lp2_w.data(), W.lp2_w.size() * 2), i_l2b = add(W.lp2_b.data(), W.lp2_b.size() * 4);
|
||||
struct BI { size_t n1w, n1b, n2w, n2b, qkv_b, proj_b, fc1_b, fc2_b, qkv_w, proj_w, fc1_w, fc2_w; };
|
||||
std::vector<BI> bi;
|
||||
for (const auto& b : W.blk)
|
||||
bi.push_back({add(b.n1w.data(), b.n1w.size() * 4), add(b.n1b.data(), b.n1b.size() * 4), add(b.n2w.data(), b.n2w.size() * 4), add(b.n2b.data(), b.n2b.size() * 4),
|
||||
add(b.qkv_b.data(), b.qkv_b.size() * 4), add(b.proj_b.data(), b.proj_b.size() * 4), add(b.fc1_b.data(), b.fc1_b.size() * 4), add(b.fc2_b.data(), b.fc2_b.size() * 4),
|
||||
add(b.qkv_w.data(), b.qkv_w.size() * 2), add(b.proj_w.data(), b.proj_w.size() * 2), add(b.fc1_w.data(), b.fc1_w.size() * 2), add(b.fc2_w.data(), b.fc2_w.size() * 2)});
|
||||
if (total + kMinActivationBytes > kBudgetBytes) {
|
||||
err = "vision gpu: the weights (" + std::to_string(total >> 20) + " MiB) do not fit in the encoder's device memory budget of " + std::to_string(kBudgetBytes >> 20) + " MiB";
|
||||
return false;
|
||||
}
|
||||
uint8_t* arena = nullptr;
|
||||
if (!cuok(cudaMalloc(reinterpret_cast<void**>(&arena), total), "cudaMalloc (vision weights)", err)) return false;
|
||||
for (const Item& it : items)
|
||||
if (!cuok(cudaMemcpy(arena + it.off, it.src, it.bytes, cudaMemcpyHostToDevice), "cudaMemcpy (vision weights)", err)) { cudaFree(arena); return false; }
|
||||
Dev* d = new Dev;
|
||||
d->arena = arena;
|
||||
d->bytes = total;
|
||||
auto P = [&](size_t i) { return arena + items[i].off; };
|
||||
d->patch_w = reinterpret_cast<uint16_t*>(P(i_patch_w));
|
||||
d->patch_b = reinterpret_cast<float*>(P(i_patch_b));
|
||||
d->pos = reinterpret_cast<uint16_t*>(P(i_pos));
|
||||
d->merger_w = reinterpret_cast<float*>(P(i_mw));
|
||||
d->merger_b = reinterpret_cast<float*>(P(i_mb));
|
||||
d->lp0_w = reinterpret_cast<uint16_t*>(P(i_l0w));
|
||||
d->lp0_b = reinterpret_cast<float*>(P(i_l0b));
|
||||
d->lp2_w = reinterpret_cast<uint16_t*>(P(i_l2w));
|
||||
d->lp2_b = reinterpret_cast<float*>(P(i_l2b));
|
||||
for (const BI& b : bi)
|
||||
d->blk.push_back({reinterpret_cast<float*>(P(b.n1w)), reinterpret_cast<float*>(P(b.n1b)), reinterpret_cast<float*>(P(b.n2w)), reinterpret_cast<float*>(P(b.n2b)),
|
||||
reinterpret_cast<float*>(P(b.qkv_b)), reinterpret_cast<float*>(P(b.proj_b)), reinterpret_cast<float*>(P(b.fc1_b)), reinterpret_cast<float*>(P(b.fc2_b)),
|
||||
reinterpret_cast<uint16_t*>(P(b.qkv_w)), reinterpret_cast<uint16_t*>(P(b.proj_w)), reinterpret_cast<uint16_t*>(P(b.fc1_w)), reinterpret_cast<uint16_t*>(P(b.fc2_w))});
|
||||
d_ = d;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VisionGpu::encode(const PreparedImage& img, std::vector<float>& out, std::string& err, VisionCheckpoints* ck, VisionGpuStats* st) {
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const bool was_loaded = d_ != nullptr;
|
||||
if (!load_locked(err)) return false;
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
busy_ = true;
|
||||
struct Done { VisionGpu* g; ~Done() { g->busy_ = false; g->last_use_ = std::chrono::steady_clock::now(); g->cv_.notify_all(); } } done{this};
|
||||
const VisionCfg& c = cfg_;
|
||||
if (c.head_dim() != AHD || c.hidden % 4 || c.ffn % 4 || img.gh % c.merge || img.gw % c.merge || img.pix.empty()) { err = "vision gpu: unsupported geometry"; return false; }
|
||||
if (!cuok(cudaSetDevice(device_), "cudaSetDevice", err)) return false;
|
||||
const int S = img.gh * img.gw, D = c.hidden, F = c.ffn, H = c.heads, PV = c.patch_vals(), T = S / (c.merge * c.merge), MD = c.merged_dim(), O = c.out_dim, M2 = c.merge, gh = img.gh, gw = img.gw;
|
||||
// activations for this picture: x, h, att, qkv (the pixels live in its first columns before it is used), the MLP chunk, the projector output
|
||||
const size_t n_x = static_cast<size_t>(S) * D, n_qkv = static_cast<size_t>(S) * 3 * D, n_mlp = static_cast<size_t>(std::min(S, kMlpRows)) * F, n_p0 = static_cast<size_t>(T) * O;
|
||||
const int np = std::max(gh, gw), nf = AHD / 4;
|
||||
const size_t extra = static_cast<size_t>(S) * (2 * 4 + 4 * 4 + 4 * 4) + static_cast<size_t>(np) * nf * 8; // prow / pcol, position-grid indices and weights, rope tables
|
||||
const size_t total_f = n_x * 3 + n_qkv + n_mlp + n_p0; // x, h, att (also the projector's hidden), qkv, mlp chunk, out
|
||||
if (d_->bytes + total_f * 4 + extra > kBudgetBytes) { // refused before anything is allocated: the planner gave the encoder kBudgetBytes, and an allocation that fails on a full card can wedge the queue
|
||||
err = "vision gpu: this picture needs " + std::to_string((total_f * 4 + extra) >> 20) + " MiB of activations on top of the " + std::to_string(d_->bytes >> 20) + " MiB of weights, the encoder's device memory budget is " +
|
||||
std::to_string(kBudgetBytes >> 20) + " MiB";
|
||||
return false;
|
||||
}
|
||||
float* buf = nullptr;
|
||||
char* aux = nullptr;
|
||||
if (!cuok(cudaMalloc(reinterpret_cast<void**>(&buf), total_f * 4), "cudaMalloc (vision activations)", err)) return false;
|
||||
if (!cuok(cudaMalloc(reinterpret_cast<void**>(&aux), extra), "cudaMalloc (vision tables)", err)) { cudaFree(buf); return false; }
|
||||
struct Free { float* b; char* a; ~Free() { cudaFree(b); cudaFree(a); } } fr_{buf, aux};
|
||||
float *x = buf, *h = x + n_x, *att = h + n_x, *qkv = att + n_x, *mlp = qkv + n_qkv, *dout = mlp + n_mlp;
|
||||
float* pix = qkv; // [S, PV]: used by the patch embedding only, before qkv is first written
|
||||
float* p0 = att; // [T, O] = S x 640 floats <= S x 1152: the attention output is dead when the projector runs
|
||||
int* prow = reinterpret_cast<int*>(aux);
|
||||
int* pcol = prow + S;
|
||||
int* pidx = pcol + S; // [S, 4]
|
||||
float* pw = reinterpret_cast<float*>(pidx + static_cast<size_t>(S) * 4); // [S, 4]
|
||||
float* cs = pw + static_cast<size_t>(S) * 4;
|
||||
float* sn = cs + static_cast<size_t>(np) * nf;
|
||||
{ // the tables the kernels read (double on the host, like the CPU encoder)
|
||||
std::vector<int> hr(static_cast<size_t>(S)), hc(static_cast<size_t>(S)), hi4(static_cast<size_t>(S) * 4);
|
||||
std::vector<float> hw4(static_cast<size_t>(S) * 4), hcs(static_cast<size_t>(np) * nf), hsn(static_cast<size_t>(np) * nf);
|
||||
const int side = c.pos_side;
|
||||
auto lin = [&](int i, int n, double& idx, int& fl, int& ce, double& d) {
|
||||
idx = n > 1 ? i * (static_cast<double>(side - 1) / (n - 1)) : 0.0;
|
||||
fl = static_cast<int>(idx);
|
||||
ce = std::min(fl + 1, side - 1);
|
||||
d = idx - fl;
|
||||
};
|
||||
for (int br = 0; br < gh / M2; ++br)
|
||||
for (int bc = 0; bc < gw / M2; ++bc)
|
||||
for (int dy = 0; dy < M2; ++dy)
|
||||
for (int dx = 0; dx < M2; ++dx) {
|
||||
const size_t i = ((static_cast<size_t>(br) * (gw / M2) + bc) * M2 + dy) * M2 + dx;
|
||||
const int row = br * M2 + dy, col = bc * M2 + dx;
|
||||
hr[i] = row;
|
||||
hc[i] = col;
|
||||
double hiv, wiv, dh, dw;
|
||||
int hf, hcc, wf, wc;
|
||||
lin(row, gh, hiv, hf, hcc, dh);
|
||||
lin(col, gw, wiv, wf, wc, dw);
|
||||
hi4[i * 4 + 0] = hf * side + wf;
|
||||
hi4[i * 4 + 1] = hf * side + wc;
|
||||
hi4[i * 4 + 2] = hcc * side + wf;
|
||||
hi4[i * 4 + 3] = hcc * side + wc;
|
||||
hw4[i * 4 + 0] = static_cast<float>(1 - dh - (dw - dh * dw)); // w00
|
||||
hw4[i * 4 + 1] = static_cast<float>(dw - dh * dw); // w01
|
||||
hw4[i * 4 + 2] = static_cast<float>(dh - dh * dw); // w10
|
||||
hw4[i * 4 + 3] = static_cast<float>(dh * dw); // w11
|
||||
}
|
||||
const int half = AHD / 2;
|
||||
for (int p = 0; p < np; ++p)
|
||||
for (int f = 0; f < nf; ++f) {
|
||||
const double inv = 1.0 / std::pow(10000.0, static_cast<double>(2 * f) / half);
|
||||
hcs[static_cast<size_t>(p) * nf + f] = static_cast<float>(std::cos(p * inv));
|
||||
hsn[static_cast<size_t>(p) * nf + f] = static_cast<float>(std::sin(p * inv));
|
||||
}
|
||||
cudaMemcpy(prow, hr.data(), static_cast<size_t>(S) * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(pcol, hc.data(), static_cast<size_t>(S) * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(pidx, hi4.data(), hi4.size() * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(pw, hw4.data(), hw4.size() * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(cs, hcs.data(), hcs.size() * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(sn, hsn.data(), hsn.size() * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(pix, img.pix.data(), static_cast<size_t>(S) * PV * 4, cudaMemcpyHostToDevice);
|
||||
}
|
||||
cudaStream_t s = nullptr;
|
||||
const Dev& W = *d_;
|
||||
auto fetch = [&](std::vector<float>& v, const float* dp, size_t n) { v.resize(n); cudaMemcpy(v.data(), dp, n * 4, cudaMemcpyDeviceToHost); };
|
||||
try {
|
||||
gemm(s, S, D, PV, pix, PV, W.patch_w, true, PV, W.patch_b, x, D, false);
|
||||
pos_embed(s, x, W.pos, pidx, pw, S, D);
|
||||
if (ck) fetch(ck->embed, x, n_x);
|
||||
const float scale = 1.0f / std::sqrt(static_cast<float>(AHD));
|
||||
for (int il = 0; il < c.depth; ++il) {
|
||||
const Dev::Blk& B = W.blk[static_cast<size_t>(il)];
|
||||
layernorm(s, x, B.n1w, B.n1b, h, S, D, c.eps);
|
||||
gemm(s, S, 3 * D, D, h, D, B.qkv_w, true, D, B.qkv_b, qkv, 3 * D, false);
|
||||
rope(s, qkv, prow, pcol, cs, sn, S, H, AHD, D);
|
||||
attention(s, qkv, att, S, H, D, scale);
|
||||
gemm(s, S, D, D, att, D, B.proj_w, true, D, B.proj_b, x, D, true);
|
||||
layernorm(s, x, B.n2w, B.n2b, h, S, D, c.eps);
|
||||
for (int r0 = 0; r0 < S; r0 += kMlpRows) { // fc1 -> GELU -> fc2 in row chunks (the intermediate is S x 4304 floats otherwise)
|
||||
const int rn = std::min(kMlpRows, S - r0);
|
||||
gemm(s, rn, F, D, h + static_cast<size_t>(r0) * D, D, B.fc1_w, true, D, B.fc1_b, mlp, F, false);
|
||||
gelu(s, mlp, static_cast<size_t>(rn) * F, false);
|
||||
gemm(s, rn, D, F, mlp, F, B.fc2_w, true, F, B.fc2_b, x + static_cast<size_t>(r0) * D, D, true);
|
||||
}
|
||||
if (ck && (il == 0 || il == 13 || il == 26)) fetch(il == 0 ? ck->blk0 : il == 13 ? ck->blk13 : ck->blk26, x, n_x);
|
||||
}
|
||||
layernorm(s, x, W.merger_w, W.merger_b, h, S, D, c.eps);
|
||||
if (ck) fetch(ck->merged, h, n_x);
|
||||
gemm(s, T, O, MD, h, MD, W.lp0_w, true, MD, W.lp0_b, p0, O, false);
|
||||
gelu(s, p0, n_p0, true);
|
||||
gemm(s, T, O, O, p0, O, W.lp2_w, true, O, W.lp2_b, dout, O, false);
|
||||
out.resize(n_p0);
|
||||
cudaMemcpy(out.data(), dout, n_p0 * 4, cudaMemcpyDeviceToHost);
|
||||
const cudaError_t e = cudaDeviceSynchronize();
|
||||
if (e != cudaSuccess) { err = std::string("vision gpu: ") + cudaGetErrorString(e); return false; }
|
||||
} catch (const std::exception& ex) {
|
||||
err = std::string("vision gpu: ") + ex.what();
|
||||
return false;
|
||||
}
|
||||
if (st) {
|
||||
const auto t2 = std::chrono::steady_clock::now();
|
||||
st->upload_ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
|
||||
st->encode_ms = std::chrono::duration<double, std::milli>(t2 - t1).count();
|
||||
st->weight_bytes = d_->bytes;
|
||||
st->scratch_bytes = total_f * 4 + extra;
|
||||
st->uploaded_now = !was_loaded;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace strata::ling32
|
||||
@@ -14,9 +14,5 @@ namespace strata::ling32::gpu {
|
||||
void gemv_s8p(const int8_t* q, const float* sc, int rows, int K, const float* x, int N, float* out, int out_stride, bool accumulate, cudaStream_t s) { l32_todo("gemv_s8p"); }
|
||||
size_t mla_attn_fast_workspace(int n_max, int H, int nope, int rope, int kv_lora, int max_ctx, LatentFmt fmt, int mode) { l32_todo("mla_attn_fast_workspace"); return 0; }
|
||||
void mla_attn_fast(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, LatentFmt fmt, int max_ctx, int mode, void* ws, size_t ws_bytes, cudaStream_t s, const void* cache_old, int recent) { l32_todo("mla_attn_fast"); }
|
||||
bool mla_exp_ok(int nope, int rope, int vhead, int kv_lora) { l32_todo("mla_exp_ok"); return false; }
|
||||
size_t mla_exp_workspace_bytes(int nmax, int H, int slab) { l32_todo("mla_exp_workspace_bytes"); return 0; }
|
||||
void mla_exp_convert_weights(const uint16_t* bf16_in, size_t n, uint16_t* fp16_out, cudaStream_t s) { l32_todo("mla_exp_convert_weights"); }
|
||||
void mla_exp_prefill(const float* q, const float* cache, int lat_stride, const uint16_t* wk16, const uint16_t* wv16, const float* gate, float* out, int N, int H, int pos0, float scale, void* ws, size_t ws_bytes, int slab, cudaStream_t s) { l32_todo("mla_exp_prefill"); }
|
||||
|
||||
} // namespace strata::ling32::gpu
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/bash
|
||||
# L32-SY-MLA: bash engine/src/ling32/sycl/tools/devlink.sh - configures a bmg_g31-only build dir, compiles only the mla_exp object, then runs the AOT device link of that one object (fast IGC crash check, seconds instead of minutes)
|
||||
set +u
|
||||
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
|
||||
cd "$(cd "$(dirname "$0")/../../../../.." && pwd)" || exit 2
|
||||
bld=bld_dl
|
||||
cmake -S engine/src/ling32 -B $bld -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DLING32_SYCL=ON -DLING32_SYCL_TARGETS=intel_gpu_bmg_g31 -DPython3_EXECUTABLE=$HOME/l32sy/venv/bin/python 2>&1 | tail -1
|
||||
ninja -C $bld CMakeFiles/ling32_gpu.dir/sycl/ling32_sy_k_mla_exp.cpp.o 2>&1 | grep -E "error|FAILED" | cut -c1-300 | head -20
|
||||
cd $bld
|
||||
icpx -fsycl -fsycl-targets=intel_gpu_bmg_g31 -fsycl-link CMakeFiles/ling32_gpu.dir/sycl/ling32_sy_k_mla_exp.cpp.o -o /tmp/l32_mlaexp_devlink.o > /tmp/l32_mlaexp_dl.txt 2>&1
|
||||
echo "devlink rc=$?"
|
||||
grep -nE 'warning|rror|Segm|Retry' /tmp/l32_mlaexp_dl.txt | sed -e 's/strata::ling32::gpu::(anonymous namespace):://g' | cut -c1-400 | head -20
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
# L32-SY-MLA: bash engine/src/ling32/sycl/tools/devlink2.sh "<extra -D flags>" [target, default intel_gpu_bmg_g31]
|
||||
# compiles only ling32_sy_k_mla_exp.cpp with the given defines (the flags of the CMake build dir bld_dl, made by devlink.sh) and runs the AOT device link of that object: a seconds-long crash check of IGC / ocloc
|
||||
set +u
|
||||
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
|
||||
cd "$(cd "$(dirname "$0")/../../../../.." && pwd)" || exit 2
|
||||
bld=bld_dl
|
||||
defs="$1"
|
||||
tgt=${2:-intel_gpu_bmg_g31}
|
||||
obj=CMakeFiles/ling32_gpu.dir/sycl/ling32_sy_k_mla_exp.cpp.o
|
||||
cmd=$(ninja -C $bld -t commands $obj | tail -1)
|
||||
cmd=${cmd/-o $obj/-o /tmp/l32x_variant.o}
|
||||
( cd $bld && eval "$cmd $defs" ) 2>&1 | grep -E "error" | cut -c1-300 | head -5
|
||||
( cd $bld && icpx -fsycl -fsycl-targets=$tgt -fsycl-link /tmp/l32x_variant.o -o /tmp/l32x_variant_link.o > /tmp/l32x_variant_dl.txt 2>&1; echo "defs [$defs] devlink rc=$?" )
|
||||
grep -cE "Segm" /tmp/l32x_variant_dl.txt
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
# L32-SY-MLA: bash engine/src/ling32/sycl/tools/fwd_exp_a750.sh (inside a built tree, bld/): forward tests f32 / q8 / wide with the expanded-form MLA prefill ON (--mla-exp --kda-seq 4: the 12-token fixture prompt
|
||||
# takes the prefill path) next to the same runs without it, in the plain-loop mode of a device without XMX (STRATA_L32_MLA_EXP_MODE=1; on a Battlemage the joint_matrix kernel runs and the variable is not needed).
|
||||
set +u
|
||||
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
|
||||
cd "$(cd "$(dirname "$0")/../../../../.." && pwd)/bld" || exit 2
|
||||
export ONEAPI_DEVICE_SELECTOR=level_zero:gpu
|
||||
ctest -R 'make_fixture|make_ref|make_wide|make_wide_ref' 2>&1 | tail -3
|
||||
ids=5,17,100,42,7,300,12,9,33,2,64,201
|
||||
export STRATA_L32_MLA_EXP_MODE=${STRATA_L32_MLA_EXP_MODE:-1}
|
||||
run() { # label fixture refdir extra...
|
||||
label=$1; fx=$2; rf=$3; shift 3
|
||||
echo "===== forward $label"
|
||||
./ling32_forward_test $fx $rf $ids "$@" 2>&1 | grep -E "layer [0-9]+ \(MLA|logits vs|token-by-token|PASS|FAIL|not available" | cut -c1-200
|
||||
}
|
||||
run "f32 --kda-seq 4 (absorbed MLA, control)" ling32_fixture.strata ref --kda-seq 4
|
||||
run "f32 --kda-seq 4 --mla-exp" ling32_fixture.strata ref --kda-seq 4 --mla-exp
|
||||
run "q8 --kda-seq 4 --mla-exp" ling32_fixture.strata ref --q8 --kda-seq 4 --mla-exp
|
||||
run "wide --kda-seq 4 (control)" ling32_wide.strata ref_wide --kda-seq 4
|
||||
run "wide --kda-seq 4 --mla-exp" ling32_wide.strata ref_wide --kda-seq 4 --mla-exp
|
||||
@@ -0,0 +1,122 @@
|
||||
// L32-SY-MLA: compiler probe, which joint_matrix construct crashes ocloc / IGC for a Battlemage target. Compile only (never run):
|
||||
// icpx -fsycl -fsycl-targets=intel_gpu_bmg_g31 -O3 -DCASE=n jm_probe.cpp -o /tmp/jm_probe_n (jm_probe.sh does all cases)
|
||||
// CASE 0 baseline (A, B from shared memory, result stored to shared memory), 1 B packed from global, 2 A from global, 3 accumulator loaded from global, 4 accumulator stored to global,
|
||||
// 5 joint_matrix_apply of two accumulators, 6 joint_matrix_apply of one accumulator with shared-memory reads in the lambda, 7 acc apply2 + store with the full set of the projection kernel
|
||||
#include <sycl/sycl.hpp>
|
||||
#include <sycl/ext/oneapi/matrix/matrix.hpp>
|
||||
|
||||
#ifndef CASE
|
||||
#define CASE 0
|
||||
#endif
|
||||
namespace jm = sycl::ext::oneapi::experimental::matrix;
|
||||
constexpr auto kLoc = sycl::access::address_space::local_space;
|
||||
constexpr auto kGlb = sycl::access::address_space::global_space;
|
||||
|
||||
template <class F> inline void ap1(sycl::sub_group sg, jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16>& c, F f) {
|
||||
int r = 0;
|
||||
jm::joint_matrix_apply(sg, c, [&](float& x) { f(x, r); ++r; });
|
||||
}
|
||||
template <class F> inline void ap2(sycl::sub_group sg, jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16>& c, jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16>& d, F f) {
|
||||
int r = 0;
|
||||
jm::joint_matrix_apply(sg, c, d, [&](float& x, float& y) { f(x, y, r); ++r; });
|
||||
}
|
||||
|
||||
int main() {
|
||||
sycl::queue q;
|
||||
sycl::half* gA = sycl::malloc_device<sycl::half>(8 * 16 * 64, q);
|
||||
sycl::half* gB = sycl::malloc_device<sycl::half>(16 * 16 * 64, q);
|
||||
float* gC = sycl::malloc_device<float>(8 * 16 * 64, q);
|
||||
q.submit([&](sycl::handler& h) {
|
||||
sycl::local_accessor<sycl::half, 1> lm(sycl::range<1>(8 * 80 + 8 * 80 + 8 * 16 * 2), h);
|
||||
h.parallel_for(sycl::nd_range<1>(16, 16), [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] {
|
||||
auto sg = it.get_sub_group();
|
||||
sycl::half* l = lm.get_multi_ptr<sycl::access::decorated::no>().get();
|
||||
sycl::half* lA = l;
|
||||
sycl::half* lB = l + 8 * 80;
|
||||
float* lC = reinterpret_cast<float*>(l + 16 * 80);
|
||||
auto pAl = sycl::address_space_cast<kLoc, sycl::access::decorated::no>(lA);
|
||||
auto pBl = sycl::address_space_cast<kLoc, sycl::access::decorated::no>(lB);
|
||||
auto pAg = sycl::address_space_cast<kGlb, sycl::access::decorated::no>(gA);
|
||||
auto pBg = sycl::address_space_cast<kGlb, sycl::access::decorated::no>(gB);
|
||||
auto pCl = sycl::address_space_cast<kLoc, sycl::access::decorated::no>(lC);
|
||||
auto pCg = sycl::address_space_cast<kGlb, sycl::access::decorated::no>(gC);
|
||||
jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16> c, x;
|
||||
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::a, 8, 16, jm::layout::row_major> a;
|
||||
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, 16, jm::layout::ext_intel_packed> b;
|
||||
#if CASE == 3
|
||||
jm::joint_matrix_load(sg, c, pCg, 128, jm::layout::row_major);
|
||||
#else
|
||||
jm::joint_matrix_fill(sg, c, 0.0f);
|
||||
#endif
|
||||
jm::joint_matrix_fill(sg, x, 0.0f);
|
||||
#if CASE == 2
|
||||
jm::joint_matrix_load(sg, a, pAg, 192);
|
||||
#else
|
||||
jm::joint_matrix_load(sg, a, pAl, 80);
|
||||
#endif
|
||||
#if CASE == 1 || CASE == 7
|
||||
jm::joint_matrix_load(sg, b, pBg, 256);
|
||||
#else
|
||||
jm::joint_matrix_load(sg, b, pBl, 80);
|
||||
#endif
|
||||
jm::joint_matrix_mad(sg, c, a, b, c);
|
||||
jm::joint_matrix_mad(sg, x, a, b, x);
|
||||
#if CASE == 8
|
||||
ap1(sg, c, [&](float& p, int r) { p *= static_cast<float>(lA[r]); });
|
||||
#endif
|
||||
#if CASE == 9
|
||||
ap2(sg, c, x, [&](float& p, float& q, int) { p = (p + q * 0.00048828125f) * 0.5f; });
|
||||
#endif
|
||||
#if CASE == 10
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
jm::joint_matrix_load(sg, a, pAl, 80);
|
||||
jm::joint_matrix_mad(sg, c, a, b, c);
|
||||
}
|
||||
ap1(sg, c, [&](float& p, int r) { p *= static_cast<float>(lA[r]); });
|
||||
#endif
|
||||
#if CASE == 11
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
jm::joint_matrix_load(sg, a, pAl, 80);
|
||||
jm::joint_matrix_load(sg, b, pBl, 80);
|
||||
jm::joint_matrix_mad(sg, c, a, b, c);
|
||||
jm::joint_matrix_mad(sg, x, a, b, x);
|
||||
}
|
||||
ap2(sg, c, x, [&](float& p, float& q, int) { p = (p + q * 0.00048828125f) * 0.5f; });
|
||||
#endif
|
||||
#if CASE == 12 || CASE == 13 || CASE == 14
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
sycl::group_barrier(it.get_group());
|
||||
lA[it.get_local_id(0) + i] = static_cast<sycl::half>(i);
|
||||
sycl::group_barrier(it.get_group());
|
||||
#if CASE == 13
|
||||
jm::joint_matrix_load(sg, b, pBg + i * 256, 256);
|
||||
#endif
|
||||
jm::joint_matrix_load(sg, a, pAl, 80);
|
||||
jm::joint_matrix_mad(sg, c, a, b, c);
|
||||
jm::joint_matrix_mad(sg, x, a, b, x);
|
||||
}
|
||||
#if CASE == 14
|
||||
ap1(sg, c, [&](float& p, int r) { p *= static_cast<float>(lA[r]); });
|
||||
#else
|
||||
ap2(sg, c, x, [&](float& p, float& q, int) { p = (p + q * 0.00048828125f) * 0.5f; });
|
||||
#endif
|
||||
#endif
|
||||
#if CASE == 5 || CASE == 7
|
||||
jm::joint_matrix_apply(sg, c, x, [&](float& p, float& r) { p = (p + r * 0.00048828125f) * 0.5f; });
|
||||
#endif
|
||||
#if CASE == 6
|
||||
int row = 0;
|
||||
jm::joint_matrix_apply(sg, c, [&](float& p) { p *= static_cast<float>(lA[row]); ++row; });
|
||||
#endif
|
||||
#if CASE == 4
|
||||
jm::joint_matrix_store(sg, c, pCg, 128, jm::layout::row_major);
|
||||
#else
|
||||
jm::joint_matrix_store(sg, c, pCl, 16, jm::layout::row_major);
|
||||
sycl::group_barrier(sg);
|
||||
gC[it.get_local_id(0)] = lC[it.get_local_id(0)];
|
||||
#endif
|
||||
});
|
||||
});
|
||||
q.wait();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
# L32-SY-MLA: compiles the joint_matrix probe cases for a Battlemage target (compile only) and prints which ones crash the offline compiler. bash jm_probe.sh [target]
|
||||
set +u
|
||||
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
tgt=${1:-intel_gpu_bmg_g31}
|
||||
for c in 12 13 14; do
|
||||
icpx -fsycl -fsycl-targets=$tgt -O3 -DCASE=$c "$here/jm_probe.cpp" -o /tmp/l32_jm_probe_$c > /tmp/l32_jm_probe_$c.txt 2>&1
|
||||
echo "case $c rc=$? segv=$(grep -c Segm /tmp/l32_jm_probe_$c.txt) errors=$(grep -c 'error' /tmp/l32_jm_probe_$c.txt)"
|
||||
done
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# L32-SY-MLA: bash engine/src/ling32/sycl/tools/kda_a750.sh (after l32sy_build.sh build): the KDA chunk-scan checks on the A750 box: ctest of the kernel / model / forward / kda tests, then the forward tests with the chunk
|
||||
# path forced (--kda-seq 4) for every scan mode (STRATA_L32_KDA_SEQ = 0 one column per lane, 4 / 8 the scan split over the value columns).
|
||||
set +u
|
||||
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
|
||||
cd "$(cd "$(dirname "$0")/../../../../.." && pwd)/bld" || exit 2
|
||||
export ONEAPI_DEVICE_SELECTOR=level_zero:gpu
|
||||
ctest -R 'make|kernel_test|model_test|forward_test|kda_test' 2>&1 | tail -22
|
||||
ids=5,17,100,42,7,300,12,9,33,2,64,201
|
||||
for m in 0 4 8; do
|
||||
echo "===== forward wide --kda-seq 4, scan mode $m"
|
||||
STRATA_L32_KDA_SEQ=$m ./ling32_forward_test ling32_wide.strata ref_wide $ids --kda-seq 4 2>&1 | grep -E "logits vs|token-by-token|PASS|FAIL" | cut -c1-200
|
||||
echo "===== forward f32 --kda-seq 4, scan mode $m"
|
||||
STRATA_L32_KDA_SEQ=$m ./ling32_forward_test ling32_fixture.strata ref $ids --kda-seq 4 2>&1 | grep -E "logits vs|token-by-token|PASS|FAIL" | cut -c1-200
|
||||
done
|
||||
echo "===== forward q8 --kda-seq 4, scan mode 8"
|
||||
STRATA_L32_KDA_SEQ=8 ./ling32_forward_test ling32_fixture.strata ref $ids --q8 --kda-seq 4 2>&1 | grep -E "logits vs|token-by-token|PASS|FAIL" | cut -c1-200
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Every leg of ling32_spec_span_test.py without stopping at the first difference (SYCL bring-up).
|
||||
python l32sy_spec_legs.py EXE WIDE MTP WORKDIR"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def run(exe, wide, jobs, out, extra, env_extra=None):
|
||||
os.makedirs(out, exist_ok=True)
|
||||
env = dict(os.environ)
|
||||
env.pop("STRATA_L32_SPEC_SPAN", None)
|
||||
if env_extra:
|
||||
env.update(env_extra)
|
||||
cmd = [exe, "--model", wide, "--genjobs", jobs, "--out", out, "--ctx", "400", "--no-selfcheck", "--chunk", "64", "--stop", "999999"] + extra
|
||||
p = subprocess.run(cmd, capture_output=True, text=True, errors="replace", env=env)
|
||||
txt = p.stdout + p.stderr
|
||||
gj = os.path.join(out, "p300.gen.json")
|
||||
if p.returncode != 0 or not os.path.exists(gj):
|
||||
return None, None, " | ".join(txt.strip().splitlines()[-4:]) + " (exit %d)" % p.returncode
|
||||
ids = json.load(open(gj)).get("gen_ids")
|
||||
m = re.search(r"tier store: (\d+) forwards", txt)
|
||||
return ids, int(m.group(1)) if m else None, ""
|
||||
|
||||
|
||||
def main():
|
||||
exe, wide, mtp, work = sys.argv[1:5]
|
||||
os.makedirs(work, exist_ok=True)
|
||||
rnd = random.Random(20261203)
|
||||
ids = [rnd.randrange(1, 500) for _ in range(300)]
|
||||
jobs = os.path.join(work, "jobs.jsonl")
|
||||
with open(jobs, "w") as f:
|
||||
f.write('{"id":"p300","prompt_ids":[' + ",".join(map(str, ids)) + '],"gen":24}\n')
|
||||
tier_b = ["--tier", "hybrid", "--vram-budget-gib", "0.2", "--ram-budget-gib", "4"]
|
||||
tier_c = ["--tier", "nvme", "--vram-budget-gib", "0.001", "--ram-budget-gib", "0.001"]
|
||||
spec = ["--mtp", mtp, "--spec", "mtp", "--spec-adaptive"]
|
||||
legs = [
|
||||
("plain, tier A", [], None),
|
||||
("plain, tier B", tier_b, None),
|
||||
("plain, tier C", tier_c, None),
|
||||
("spec, tier A", spec, None),
|
||||
("spec, tier B (spans)", spec + tier_b, None),
|
||||
("spec, tier B, SPEC_SPAN=0", spec + tier_b, {"STRATA_L32_SPEC_SPAN": "0"}),
|
||||
("spec, tier C (spans)", spec + tier_c, None),
|
||||
]
|
||||
ref = None
|
||||
for i, (name, extra, env) in enumerate(legs):
|
||||
got, nf, err = run(exe, wide, jobs, os.path.join(work, "leg%d" % i), extra, env)
|
||||
if got is None:
|
||||
print("%-28s FAIL: %s" % (name, err))
|
||||
continue
|
||||
if ref is None:
|
||||
ref = got
|
||||
print("%-28s %s forwards %s first %s" % (name, "SAME" if got == ref else "DIFF", nf, got[:8]))
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
# the whole tier lane on the dev box in one job (gpu lock): l32sy_push.py <wt> NAME --lock gpu -- "bash engine/src/ling32/sycl/tools/l32sy_tiersuite.sh"
|
||||
# build, 11 tier shapes on the narrow and the wide fixture (host + device-side slab checks), the tier regressions of ctest (MTP tiers, spec spans, MTP auto, lazy KV growth), every spec-span leg
|
||||
t=engine/src/ling32/sycl/tools
|
||||
bash $t/l32sy_build.sh build || exit 1
|
||||
bash $t/l32sy_build.sh test 'make_wide' >/dev/null
|
||||
bash $t/l32sy_tierbox.sh fixtures >/dev/null
|
||||
bash $t/l32sy_tierbox.sh tiercheck-all 2>&1 | grep -E "^PASS|^FAIL|SUMMARY" | cut -c1-200
|
||||
bash $t/l32sy_tierbox.sh tiercheck-all "$HOME/l32sy/fix/ling32_wide.strata" 2>&1 | grep -E "^PASS|^FAIL|SUMMARY" | cut -c1-200
|
||||
L32SY_TAIL=${L32SY_TAIL:-60} bash $t/l32sy_build.sh test "${L32SY_REGEX:-mtp_tier|spec_span|mtp_auto|kv_grow}"
|
||||
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
|
||||
export ONEAPI_DEVICE_SELECTOR=level_zero:gpu
|
||||
"$HOME/l32sy/venv/bin/python" -I $t/l32sy_spec_legs.py bld/strata-ling32 bld/ling32_wide.strata bld/ling32_wide_mtp.strata bld/spec_legs
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
# l32sy_vis.sh: build and run the SYCL picture encoder test (ling32_vision_gpu_test) on a Linux box with oneAPI DPC++ and an Intel GPU (the A750 box p1006).
|
||||
# python phaseA-tests/ling32/sycl/tools/l32sy_push.py <worktree> NAME --lock none -- "bash engine/src/ling32/sycl/tools/l32sy_vis.sh build"
|
||||
# python phaseA-tests/ling32/sycl/tools/l32sy_push.py <worktree> NAME --lock gpu -- "bash engine/src/ling32/sycl/tools/l32sy_vis.sh run [test args]"
|
||||
# env: L32SY_VISDATA (default ~/l32sy-vis: models/Ling-3.2-Air-Vision.strata, data/golden, data/images), L32SY_TARGETS (default spir64 = JIT), L32SY_JOBS
|
||||
set +u
|
||||
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
|
||||
root=$(cd "$(dirname "$0")/../../../../.." && pwd)
|
||||
cd "$root" || exit 2
|
||||
mode=${1:-build}
|
||||
bld=${L32SY_BLD:-bld}
|
||||
data=${L32SY_VISDATA:-$HOME/l32sy-vis}
|
||||
if [ "$mode" = build ]; then
|
||||
cmake -S engine/src/ling32 -B "$bld" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DLING32_SYCL=ON \
|
||||
"-DLING32_SYCL_TARGETS=${L32SY_TARGETS:-spir64}" "-DPython3_EXECUTABLE=${L32SY_FIX_PY:-$HOME/l32sy/venv/bin/python}" 2>&1 | tail -3
|
||||
cmake --build "$bld" -j "${L32SY_JOBS:-8}" --target ling32_vision_gpu_test -- -k 0 2>&1 | grep -E "error|FAILED|undefined reference|warning: (variable|unused|implicit)" | cut -c1-300 | head -100
|
||||
ls -la "$bld/ling32_vision_gpu_test" 2>&1 | tail -1
|
||||
else
|
||||
shift
|
||||
export ONEAPI_DEVICE_SELECTOR=${ONEAPI_DEVICE_SELECTOR:-level_zero:gpu}
|
||||
stdbuf -oL "$bld/ling32_vision_gpu_test" "$data/models/Ling-3.2-Air-Vision.strata" "$data/data/golden" "$data/data/images" "$@" 2>&1
|
||||
fi
|
||||
@@ -307,8 +307,23 @@ add_library(strata_prefill STATIC ${_prefill}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_fused_stub.cpp # upstream's fused int8 kernels: not built here
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/xmx_moe.dp.cpp # A770 port: grouped XMX expert GEMM
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/esimd_moe.dp.cpp) # 151-b70: fused int8 DPAS expert products (ESIMD, Battlemage)
|
||||
target_compile_options(strata_prefill PUBLIC -qmkl=sequential)
|
||||
target_link_options(strata_prefill PUBLIC -qmkl=sequential)
|
||||
# Windows has no oneMKL in the toolchain we build with: the dense prompt GEMM is then the engine's own XMX kernel
|
||||
# (src/prefill/xmx_dense_gemm.dp.cpp). Linux keeps oneMKL unless -DSTRATA_SYCL_NO_ONEMKL=ON; STRATA_DENSE_XMX=1 at run time takes the own
|
||||
# kernel in an oneMKL build, for A/B runs.
|
||||
if(WIN32)
|
||||
set(_no_mkl_default ON)
|
||||
else()
|
||||
set(_no_mkl_default OFF)
|
||||
endif()
|
||||
option(STRATA_SYCL_NO_ONEMKL "Build without oneMKL (the dense prompt GEMM is the engine's own XMX kernel)" ${_no_mkl_default})
|
||||
target_sources(strata_prefill PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/xmx_dense_gemm.dp.cpp)
|
||||
if(STRATA_SYCL_NO_ONEMKL)
|
||||
target_compile_definitions(strata_prefill PUBLIC STRATA_SYCL_NO_ONEMKL=1)
|
||||
message(STATUS "Strata SYCL: no oneMKL (own XMX dense GEMM)")
|
||||
else()
|
||||
target_compile_options(strata_prefill PUBLIC -qmkl=sequential)
|
||||
target_link_options(strata_prefill PUBLIC -qmkl=sequential)
|
||||
endif()
|
||||
target_link_libraries(strata_prefill PUBLIC strata_engine)
|
||||
|
||||
# Optional TLA data movement for exact FP32 sparse prompt attention on B70.
|
||||
|
||||
@@ -336,9 +336,14 @@ def install_two_card_spec():
|
||||
def engine_args(cfg, exe=None, *, announce=True): # the base signature (serve/server.py engine_args): start calls it with exe, the budget check with announce=False
|
||||
args = original(cfg, exe, announce=announce)
|
||||
try:
|
||||
if cfg.get("backend") == "sycl" and S.layer_split_of(cfg):
|
||||
if cfg.get("backend") == "sycl":
|
||||
sysfs = intel_spec.sysfs_cards()
|
||||
cards = [sysfs[i] for i in S.gpu_list(cfg) if isinstance(i, int) and 0 <= i < len(sysfs)]
|
||||
if S.layer_split_of(cfg):
|
||||
cards = [sysfs[i] for i in S.gpu_list(cfg) if isinstance(i, int) and 0 <= i < len(sysfs)]
|
||||
else: # one card: the config's index, else the first
|
||||
g = cfg.get("gpu")
|
||||
i = g if isinstance(g, int) and not isinstance(g, bool) else 0
|
||||
cards = [sysfs[i]] if 0 <= i < len(sysfs) else []
|
||||
new, note = intel_spec.plan(args, cfg.get("user_args"), cards, mtp_off=cfg.get("mtp") is False)
|
||||
if note:
|
||||
if announce: # (announce=False builds the arguments without any line)
|
||||
|
||||
@@ -563,6 +563,10 @@ def install(argv) -> None:
|
||||
spec_note = intel_spec.apply_to_config(cfg, cards_used)
|
||||
if spec_note:
|
||||
S.say(" " + spec_note)
|
||||
if not split: # one B-series card, no draft layer: --spec 2 (strata_control/intel_spec.py)
|
||||
spec_note = intel_spec.apply_to_config(cfg, [sel])
|
||||
if spec_note:
|
||||
S.say(" " + spec_note)
|
||||
need = S.MODELS.get(model, {}).get("ram_gb", 0)
|
||||
sel_alch = sel["driver"] == "i915" or sel.get("devid") in ALCHEMIST_IDS
|
||||
if sel_alch and need and real_ram < need:
|
||||
|
||||
@@ -7,8 +7,7 @@
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include "strata/platform/posix_io_compat.hpp"
|
||||
#include <dpct/dpct.hpp>
|
||||
#include <sycl/sycl.hpp>
|
||||
#include <thread>
|
||||
@@ -29,7 +28,7 @@ void GgufExpertSource::close() {
|
||||
for (uint8_t* c : mirror_chunks_) if (c) sycl::free(c, dpct::get_in_order_queue());
|
||||
mirror_chunks_.clear();
|
||||
mirror_bytes_ = 0; mirror_ptr_.clear(); layer_first_.clear();
|
||||
for (int fd : fds_) if (fd >= 0) ::close(fd);
|
||||
for (int fd : fds_) if (fd >= 0) strata::platform::posix_close(fd);
|
||||
fds_.clear(); names_.clear(); layer_fd_.clear(); ring_.clear(); ring_key_.clear(); where_.clear();
|
||||
ring_next_ = 0;
|
||||
}
|
||||
@@ -73,7 +72,7 @@ int GgufExpertSource::fd_of(int64_t layer, int role, std::string& err) {
|
||||
if (lay.gguf_file.size() > i && !lay.gguf_file[i].empty()) name = dir_ + lay.gguf_file[i];
|
||||
for (size_t k = 0; k < names_.size(); ++k)
|
||||
if (names_[k] == name) { layer_fd_[i] = (int) k; return fds_[k]; }
|
||||
const int fd = ::open(name.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
const int fd = strata::platform::posix_open_ro(name.c_str());
|
||||
if (fd < 0) { err = "--stream-experts: cannot open " + name; return -1; }
|
||||
names_.push_back(name);
|
||||
fds_.push_back(fd);
|
||||
@@ -111,7 +110,7 @@ const uint8_t* GgufExpertSource::blob(int64_t layer, int64_t expert) {
|
||||
const uint64_t src = lay.gguf_off[(size_t) (3 * layer + r)] + per[r] * (uint64_t) expert;
|
||||
uint64_t done = 0;
|
||||
while (done < per[r]) {
|
||||
const ssize_t n = ::pread(fd, buf.data() + at[r] + done, (size_t) (per[r] - done), (off_t) (src + done));
|
||||
const int64_t n = strata::platform::posix_pread(fd, buf.data() + at[r] + done, (size_t) (per[r] - done), src + done);
|
||||
if (n <= 0) { std::lock_guard<std::mutex> lk(mu_); where_.erase(key); ring_key_[slot] = -1; return nullptr; }
|
||||
done += (uint64_t) n;
|
||||
}
|
||||
@@ -234,7 +233,7 @@ bool GgufExpertSource::read_into(int64_t layer, int64_t expert, uint8_t* dst, si
|
||||
const uint64_t src = lay.gguf_off[(size_t) (3 * layer + r)] + per[r] * (uint64_t) expert;
|
||||
uint64_t done = 0;
|
||||
while (done < per[r]) {
|
||||
const ssize_t n = ::pread(fd, dst + at[r] + done, (size_t) (per[r] - done), (off_t) (src + done));
|
||||
const int64_t n = strata::platform::posix_pread(fd, dst + at[r] + done, (size_t) (per[r] - done), src + done);
|
||||
if (n <= 0) return false;
|
||||
done += (uint64_t) n;
|
||||
}
|
||||
|
||||
@@ -326,19 +326,8 @@ namespace {
|
||||
bool sliced_pin_limit(uint64_t& limit, std::string& why) {
|
||||
constexpr uint64_t GiB = 1ull << 30;
|
||||
char buf[256];
|
||||
int dev = 0;
|
||||
cudaDeviceProp p{};
|
||||
uint64_t budget = 0, usage = 0;
|
||||
std::string err = "no CUDA device properties";
|
||||
if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess &&
|
||||
strata::platform::gpu_shared_memory_budget(p.luid, budget, usage, err)) {
|
||||
limit = budget > usage + 4 * GiB ? budget - usage - 4 * GiB : 0;
|
||||
std::snprintf(buf, sizeof buf, "the GPU's shared-memory budget %.1f GiB - %.1f GiB in use - 4 GiB",
|
||||
(double) budget / GiB, (double) usage / GiB);
|
||||
why = buf;
|
||||
return true;
|
||||
}
|
||||
(void) cudaGetLastError();
|
||||
// SYCL port: there is no cudaHostRegister and no CUDA device properties; pinning is a no-op here, so only the RAM rule applies
|
||||
std::string err = "no GPU shared-memory budget on this backend";
|
||||
const uint64_t ram = strata::platform::total_physical_memory();
|
||||
if (ram == 0) return false;
|
||||
limit = ram / 2 > 8 * GiB ? ram / 2 - 8 * GiB : 0;
|
||||
|
||||
@@ -27,6 +27,9 @@
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#ifdef OUT
|
||||
#undef OUT // windows.h (via the SYCL headers): the kernels use OUT as a template parameter
|
||||
#endif
|
||||
|
||||
#ifndef STRATA_PLAN_LOCAL
|
||||
#define STRATA_PLAN_LOCAL 1 // 0: the original one-thread plan kernel (A/B)
|
||||
|
||||
@@ -8,7 +8,10 @@
|
||||
#include "strata/prefill/gemm.hpp"
|
||||
#include "strata/workload_trace.hpp"
|
||||
#include "strata/kernels/dequant_bf16.hpp"
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
#include <dpct/blas_utils.hpp>
|
||||
#endif
|
||||
#include "strata/prefill/xmx_dense_gemm.hpp"
|
||||
|
||||
#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)
|
||||
#include "strata/prefill/moe_mmq.hpp"
|
||||
@@ -40,7 +43,9 @@
|
||||
#include <memory>
|
||||
#include <cmath>
|
||||
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
#include <dpct/lib_common_utils.hpp>
|
||||
#endif
|
||||
|
||||
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
|
||||
#include "hipblaslt_tuning.hpp"
|
||||
@@ -392,7 +397,9 @@ Gemm::~Gemm() {
|
||||
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
|
||||
delete static_cast<HipLtState*>(hipblaslt_state_);
|
||||
#endif
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
if (handle_) delete ((dpct::blas::descriptor_ptr)handle_);
|
||||
#endif
|
||||
if (tc_w_) sycl::free(tc_w_, dpct::get_in_order_queue());
|
||||
if (tc_x_) sycl::free(tc_x_, dpct::get_in_order_queue());
|
||||
if (!external_) {
|
||||
@@ -404,6 +411,7 @@ Gemm::~Gemm() {
|
||||
bool Gemm::init_external(void *stream, uint16_t *scratch, int64_t scratch_elems,
|
||||
void *workspace, size_t ws_bytes,
|
||||
std::string &err) try {
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
dpct::blas::descriptor_ptr h = nullptr;
|
||||
if (const int s = DPCT_CHECK_ERROR(h = new dpct::blas::descriptor());
|
||||
s != 0) {
|
||||
@@ -411,18 +419,23 @@ bool Gemm::init_external(void *stream, uint16_t *scratch, int64_t scratch_elems,
|
||||
return false;
|
||||
}
|
||||
handle_ = h;
|
||||
#endif
|
||||
stream_ = stream;
|
||||
external_ = true;
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
note(DPCT_CHECK_ERROR(h->set_queue(strata::q_of(stream))),
|
||||
"cublasSetStream");
|
||||
#endif
|
||||
workspace_ = workspace;
|
||||
/*
|
||||
DPCT1027: The call to cublasSetWorkspace was replaced with 0 because
|
||||
this functionality is redundant in SYCL.
|
||||
*/
|
||||
note(0, "cublasSetWorkspace");
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
note(DPCT_CHECK_ERROR(h->set_math_mode(dpct::blas::math_mode::mm_default)),
|
||||
"cublasSetMathMode");
|
||||
#endif
|
||||
scratch_ = scratch;
|
||||
scratch_elems_ = scratch_elems;
|
||||
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
|
||||
@@ -455,6 +468,7 @@ void Gemm::rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, siz
|
||||
|
||||
bool Gemm::init(void *stream, int64_t scratch_elems, std::string &err) try {
|
||||
// #240: every failure names the call and the real status, so "no VRAM" can be told from a broken install
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
dpct::blas::descriptor_ptr h = nullptr;
|
||||
if (const int s = DPCT_CHECK_ERROR(h = new dpct::blas::descriptor());
|
||||
s != 0) {
|
||||
@@ -462,9 +476,12 @@ bool Gemm::init(void *stream, int64_t scratch_elems, std::string &err) try {
|
||||
return false;
|
||||
}
|
||||
handle_ = h;
|
||||
#endif
|
||||
stream_ = stream;
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
note(DPCT_CHECK_ERROR(h->set_queue(strata::q_of(stream))),
|
||||
"cublasSetStream");
|
||||
#endif
|
||||
// A fixed workspace so the handle never allocates on the way (and graphs could capture it later).
|
||||
const size_t ws = 32u << 20;
|
||||
/*
|
||||
@@ -492,8 +509,10 @@ bool Gemm::init(void *stream, int64_t scratch_elems, std::string &err) try {
|
||||
this functionality is redundant in SYCL.
|
||||
*/
|
||||
note(0, "cublasSetWorkspace");
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
note(DPCT_CHECK_ERROR(h->set_math_mode(dpct::blas::math_mode::mm_default)),
|
||||
"cublasSetMathMode");
|
||||
#endif
|
||||
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
|
||||
hipblaslt_state_ = create_hipblaslt_state(workspace_, ws).release();
|
||||
#endif
|
||||
@@ -802,8 +821,30 @@ uint8_t* gemm_stage(size_t need, sycl::queue& q) {
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
// One dense GEMM, Y[t][n] = alpha * sum_k X[t][k] W[n][k] + beta Y[t][n] (the column-major call Y^T = W^T X). oneMKL where this
|
||||
// build has it (STRATA_DENSE_XMX=1 takes the engine's own XMX kernel instead, for A/B runs); without oneMKL
|
||||
// (STRATA_SYCL_NO_ONEMKL, the Windows build) the own kernel always.
|
||||
enum class GemmDt { f16, bf16 };
|
||||
inline void gemm_run(sycl::queue& q, void* handle, GemmDt dt, const uint16_t* W, int64_t lda, const uint16_t* X, int64_t ldx,
|
||||
float* Y, int64_t ldy, int64_t N, int64_t T, int64_t K, float alpha, float beta) {
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
static const bool own = [] { const char* v = std::getenv("STRATA_DENSE_XMX"); return v && v[0] == '1'; }();
|
||||
if (!own) {
|
||||
const auto lt = dt == GemmDt::bf16 ? dpct::library_data_t::real_bfloat16 : dpct::library_data_t::real_half;
|
||||
dpct::blas::gemm((dpct::blas::descriptor_ptr) handle, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans,
|
||||
(int) N, (int) T, (int) K, &alpha, W, lt, (int) lda, X, lt, (int) ldx, &beta, Y,
|
||||
dpct::library_data_t::real_float, (int) ldy, dpct::compute_type::f32);
|
||||
return;
|
||||
}
|
||||
#else
|
||||
(void) handle;
|
||||
#endif
|
||||
strata::prefill::xmxd::gemm_tn(q, dt == GemmDt::bf16 ? strata::prefill::xmxd::Elem::bf16 : strata::prefill::xmxd::Elem::f16,
|
||||
W, lda, X, ldx, Y, ldy, N, T, K, alpha, beta);
|
||||
}
|
||||
inline bool staged_gemm(sycl::queue& q, void* handle, const uint16_t* W, int lda, const uint16_t* X, int ldb,
|
||||
dpct::library_data_t dt, int64_t N, int64_t T, int64_t K, float alpha, float beta,
|
||||
GemmDt dt, int64_t N, int64_t T, int64_t K, float alpha, float beta,
|
||||
float* Y, int64_t ldy) {
|
||||
// STRATA_SYCL_GEMM_NO_STAGE: the tests' negative control. 0.1.43: not on Battlemage either (the A770 oneMKL bug above did not
|
||||
// show on a B70: 4K and 49K prompts, operands at 18 GiB into the cache arena, first-token logits byte-identical with and
|
||||
@@ -830,10 +871,7 @@ inline bool staged_gemm(sycl::queue& q, void* handle, const uint16_t* W, int lda
|
||||
if (far_x) q.memcpy(sx, X, x_bytes);
|
||||
const uint16_t* Wu = far_w ? (const uint16_t*) sw : W;
|
||||
const uint16_t* Xu = far_x ? (const uint16_t*) sx : X;
|
||||
ck(DPCT_CHECK_ERROR(dpct::blas::gemm(
|
||||
(dpct::blas::descriptor_ptr) handle, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans,
|
||||
(int) N, (int) T, (int) K, &alpha, Wu, dt, lda, Xu, dt, ldb, &beta, Y,
|
||||
dpct::library_data_t::real_float, (int) ldy, dpct::compute_type::f32)),
|
||||
ck(DPCT_CHECK_ERROR(gemm_run(q, handle, dt, Wu, lda, Xu, ldb, Y, ldy, N, T, K, alpha, beta)),
|
||||
"cublasGemmEx (staged)");
|
||||
return true;
|
||||
}
|
||||
@@ -929,17 +967,11 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
if (staged_gemm(*strata::q_of(stream_), handle_, W, (int) K, X, (int) (ldx ? ldx : K), dpct::library_data_t::real_bfloat16, N, T, K,
|
||||
if (staged_gemm(*strata::q_of(stream_), handle_, W, (int) K, X, (int) (ldx ? ldx : K), GemmDt::bf16, N, T, K,
|
||||
alpha, beta, Y, ldy))
|
||||
return;
|
||||
// Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T].
|
||||
ck(DPCT_CHECK_ERROR(dpct::blas::gemm(
|
||||
(dpct::blas::descriptor_ptr)handle_, oneapi::mkl::transpose::trans,
|
||||
oneapi::mkl::transpose::nontrans, (int)N, (int)T, (int)K, &alpha, W,
|
||||
dpct::library_data_t::real_bfloat16, (int)K, X,
|
||||
dpct::library_data_t::real_bfloat16, (int)(ldx ? ldx : K), &beta, Y,
|
||||
dpct::library_data_t::real_float, (int)ldy,
|
||||
dpct::compute_type::f32)),
|
||||
ck(DPCT_CHECK_ERROR(gemm_run(*strata::q_of(stream_), handle_, GemmDt::bf16, W, K, X, ldx ? ldx : K, Y, ldy, N, T, K, alpha, beta)),
|
||||
"cublasGemmEx");
|
||||
STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx");
|
||||
}
|
||||
@@ -972,15 +1004,9 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (staged_gemm(*strata::q_of(stream_), handle_, W, (int) K, X, (int) K, dpct::library_data_t::real_half, N, T, K, alpha, beta, Y, ldy))
|
||||
if (staged_gemm(*strata::q_of(stream_), handle_, W, (int) K, X, (int) K, GemmDt::f16, N, T, K, alpha, beta, Y, ldy))
|
||||
return;
|
||||
ck(DPCT_CHECK_ERROR(dpct::blas::gemm(
|
||||
(dpct::blas::descriptor_ptr)handle_, oneapi::mkl::transpose::trans,
|
||||
oneapi::mkl::transpose::nontrans, (int)N, (int)T, (int)K, &alpha, W,
|
||||
dpct::library_data_t::real_half, (int)K, X,
|
||||
dpct::library_data_t::real_half, (int)K, &beta, Y,
|
||||
dpct::library_data_t::real_float, (int)ldy,
|
||||
dpct::compute_type::f32)),
|
||||
ck(DPCT_CHECK_ERROR(gemm_run(*strata::q_of(stream_), handle_, GemmDt::f16, W, K, X, K, Y, ldy, N, T, K, alpha, beta)),
|
||||
"cublasGemmEx f16");
|
||||
STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx f16");
|
||||
}
|
||||
@@ -1082,13 +1108,7 @@ void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float*
|
||||
auto multiply = [&](int64_t n, float* out) {
|
||||
workload_trace::Scope trace("gemm.native_f16_to_f32", stream_, T, n, K, ldx, ldy, ggml_type);
|
||||
const float alpha = 1.0f;
|
||||
ck(DPCT_CHECK_ERROR(dpct::blas::gemm(
|
||||
(dpct::blas::descriptor_ptr)handle_, oneapi::mkl::transpose::trans,
|
||||
oneapi::mkl::transpose::nontrans, (int)n, (int)T, (int)K, &alpha, scratch_,
|
||||
dpct::library_data_t::real_half, (int)K, X,
|
||||
dpct::library_data_t::real_half, (int)ldx, &beta, out,
|
||||
dpct::library_data_t::real_float, (int)ldy,
|
||||
dpct::compute_type::f32)),
|
||||
ck(DPCT_CHECK_ERROR(gemm_run(*strata::q_of(stream_), handle_, GemmDt::f16, scratch_, K, X, ldx, out, ldy, n, T, K, alpha, beta)),
|
||||
"cublasGemmEx native");
|
||||
};
|
||||
if (N * K > scratch_elems_) {
|
||||
|
||||
@@ -63,7 +63,9 @@
|
||||
#include "strata/prefill/kernels.hpp"
|
||||
#include "bmg_gdn_tiles.hpp"
|
||||
#include "bmg_gdn_residual.hpp"
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
#include <oneapi/mkl.hpp> // SYCL port: the QSA block scores as GEMM tiles
|
||||
#endif
|
||||
namespace strata::kernels { // SYCL port, kept out of the shared headers: qsa_select.dp.cpp, qsa_decode_attn.dp.cpp
|
||||
void qsa_block_scores_reduce(const float* S, int64_t ld, int64_t b0, int64_t nb, const float* dead, const float* q_idx,
|
||||
const int32_t* steps, int64_t nq, int64_t max_blocks, float* scores, void* stream);
|
||||
@@ -78,6 +80,7 @@ void qsa_prompt_attn_percell(const float* q, const QsaAttnPools& pools, const in
|
||||
#include <chrono>
|
||||
#include <stdexcept>
|
||||
#include <sys/stat.h>
|
||||
#include <filesystem>
|
||||
#include <tuple>
|
||||
#include "strata/prefill/f16_expert_pair.hpp"
|
||||
#include <chrono>
|
||||
@@ -993,7 +996,7 @@ void i8_cache_write(const std::string& key, const I8Cross& c) {
|
||||
}
|
||||
std::FILE* f = std::fopen(path.c_str(), "w");
|
||||
if (!f) {
|
||||
::mkdir(dir.c_str(), 0755);
|
||||
{ std::error_code ec; std::filesystem::create_directories(dir, ec); }
|
||||
f = std::fopen(path.c_str(), "w");
|
||||
if (!f) return;
|
||||
}
|
||||
@@ -3684,8 +3687,13 @@ bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0,
|
||||
// +0.6% (16K to 128K: its prompts are bound by expert streaming over PCIe), under the 5% bar.
|
||||
static const int sel_gemm_mode = [] { const char* v = std::getenv("STRATA_SELECT_GEMM"); return v ? std::atoi(v) : -1; }();
|
||||
static const int64_t sel_gemm_min = [] { const char* v = std::getenv("STRATA_SELECT_GEMM_MIN"); return v ? (int64_t) std::atoll(v) : (int64_t) 2048; }(); // blocks (4 cells each)
|
||||
#ifdef STRATA_SYCL_NO_ONEMKL
|
||||
const bool sel_gemm = false; // no oneMKL in this build: the warp / tensor-core block scores below
|
||||
(void) sel_gemm_mode; (void) sel_gemm_min;
|
||||
#else
|
||||
const bool sel_gemm = sel_gemm_mode > 0 || (sel_gemm_mode < 0 && active >= sel_gemm_min &&
|
||||
strata::intel_gpu_gen(m.cs->get_device()) == strata::IntelGpuGen::Battlemage);
|
||||
#endif
|
||||
const int64_t sel_tile = std::min<int64_t>(8192, (int64_t) ((uint64_t) m.attn_batch *
|
||||
strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s) / (uint64_t) (nb * 4)));
|
||||
bool sel_done = false;
|
||||
@@ -3694,11 +3702,13 @@ bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0,
|
||||
try {
|
||||
for (int64_t b0 = 0; b0 < active; b0 += sel_tile) {
|
||||
const int64_t nbk = std::min<int64_t>(sel_tile, active - b0);
|
||||
#ifndef STRATA_SYCL_NO_ONEMKL
|
||||
oneapi::mkl::blas::column_major::gemm(*m.cs, oneapi::mkl::transpose::trans,
|
||||
oneapi::mkl::transpose::nontrans, nbk, nb * 4, 128,
|
||||
1.0f, st.idx_pooled + b0 * 128, 128,
|
||||
m.q_idx + t0 * kIdxQW, 128, 0.0f, m.attn_scratch,
|
||||
sel_tile);
|
||||
#endif
|
||||
strata::kernels::qsa_block_scores_reduce(m.attn_scratch, sel_tile, b0, nbk, st.idx_dead,
|
||||
m.q_idx + t0 * kIdxQW, steps0, nb, m.max_blocks,
|
||||
m.sel_scores, m.cs);
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
// The dense prompt GEMM on the XMX units. See include/strata/prefill/xmx_dense_gemm.hpp.
|
||||
//
|
||||
// A SLM-tiled joint_matrix kernel in the shape of xmx_moe.dp.cpp's grouped FP16 GEMM, with what a dense product needs on top:
|
||||
// BF16 as well as FP16 inputs, any N and T (zero-filled edge tiles, bounded stores), K a multiple of 8 (16-byte loads; the
|
||||
// tail of a K step is zero-filled), alpha / beta in the epilogue. Shapes it does not take (K % 8 != 0, unaligned pointers or
|
||||
// leading dimensions) go to a plain tiled FMA kernel: slow, exact the same product, never wrong.
|
||||
#include <sycl/sycl.hpp>
|
||||
#include <sycl/ext/oneapi/matrix/matrix.hpp>
|
||||
#include <sycl/ext/oneapi/bfloat16.hpp>
|
||||
#include <sycl/ext/intel/experimental/grf_size_properties.hpp>
|
||||
#include <sycl/ext/intel/esimd.hpp>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include "strata/kprof.hpp"
|
||||
#include "strata/sycl_queue.hpp"
|
||||
#include "strata/prefill/xmx_dense_gemm.hpp"
|
||||
|
||||
namespace strata::prefill::xmxd {
|
||||
namespace {
|
||||
namespace jm = sycl::ext::oneapi::experimental::matrix;
|
||||
using half = sycl::half;
|
||||
using bf16 = sycl::ext::oneapi::bfloat16;
|
||||
|
||||
#ifdef STRATA_XMX_SG16
|
||||
constexpr int kSgW = 16;
|
||||
#else
|
||||
constexpr int kSgW = 8;
|
||||
#endif
|
||||
|
||||
template <int SGM_, int SGN_, int MT_, int NT_, int KS_>
|
||||
struct Cfg {
|
||||
static constexpr int SGM = SGM_, SGN = SGN_, MT = MT_, NT = NT_, KS = KS_;
|
||||
static constexpr int SG = kSgW;
|
||||
static constexpr int BM = SGM * MT * 8, BN = SGN * NT * kSgW, NSG = SGM * SGN, WG = NSG * SG;
|
||||
};
|
||||
|
||||
#ifdef STRATA_XMX_SG16
|
||||
using Small = Cfg<2, 4, 4, 2, 32>; // 64 x 128 tile
|
||||
using Big = Cfg<4, 2, 4, 4, 32>; // 128 x 128 tile
|
||||
#else
|
||||
using Small = Cfg<2, 8, 4, 2, 32>;
|
||||
using Big = Cfg<4, 4, 4, 4, 32>;
|
||||
#endif
|
||||
|
||||
template <class T, class C, class Name>
|
||||
void launch_xmx(sycl::queue& q, const T* W, int lda, const T* X, int ldx, float* Y, int ldy, int N, int Tn, int K, float alpha,
|
||||
float beta) {
|
||||
#ifndef STRATA_NO_DG2_XMX
|
||||
constexpr int BM = C::BM, BN = C::BN, KS = C::KS, WG = C::WG, SG = C::SG, TN = kSgW;
|
||||
constexpr int LDA = KS + 8, LDB = KS + 8;
|
||||
const int mt = (Tn + BM - 1) / BM, nb = (N + BN - 1) / BN;
|
||||
strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
|
||||
sycl::local_accessor<T, 1> sa(BM * LDA, h), sb(BN * LDB, h);
|
||||
auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>};
|
||||
h.parallel_for<Name>(sycl::nd_range<2>({(size_t) mt, (size_t) nb * WG}, {1, (size_t) WG}), props,
|
||||
[=](sycl::nd_item<2> it) [[sycl::reqd_sub_group_size(kSgW)]] {
|
||||
auto sg = it.get_sub_group();
|
||||
const int m0 = (int) it.get_group(0) * BM;
|
||||
const int n0 = (int) it.get_group(1) * BN;
|
||||
const int rows = sycl::min(BM, Tn - m0);
|
||||
const int cols = sycl::min(BN, N - n0);
|
||||
const T* Xe = X + (size_t) m0 * ldx;
|
||||
const T* We = W + (size_t) n0 * lda;
|
||||
const int lid = (int) it.get_local_id(1), sgid = lid / SG;
|
||||
const int sgm = sgid / C::SGN, sgn = sgid % C::SGN;
|
||||
jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, TN> acc[C::MT][C::NT];
|
||||
for (int i = 0; i < C::MT; ++i)
|
||||
for (int j = 0; j < C::NT; ++j) jm::joint_matrix_fill(sg, acc[i][j], 0.0f);
|
||||
T* pa = sa.template get_multi_ptr<sycl::access::decorated::no>().get();
|
||||
T* pb = sb.template get_multi_ptr<sycl::access::decorated::no>().get();
|
||||
for (int k0 = 0; k0 < K; k0 += KS) {
|
||||
constexpr int VA = BM * KS / 8, VB = BN * KS / 8;
|
||||
for (int v = lid; v < VA; v += WG) {
|
||||
const int r = v / (KS / 8), c = (v % (KS / 8)) * 8;
|
||||
sycl::vec<uint16_t, 8> x(0);
|
||||
if (r < rows && k0 + c < K) x = *reinterpret_cast<const sycl::vec<uint16_t, 8>*>(Xe + (size_t) r * ldx + k0 + c);
|
||||
*reinterpret_cast<sycl::vec<uint16_t, 8>*>(pa + r * LDA + c) = x;
|
||||
}
|
||||
for (int v = lid; v < VB; v += WG) {
|
||||
const int r = v / (KS / 8), c = (v % (KS / 8)) * 8;
|
||||
sycl::vec<uint16_t, 8> x(0);
|
||||
if (r < cols && k0 + c < K) x = *reinterpret_cast<const sycl::vec<uint16_t, 8>*>(We + (size_t) r * lda + k0 + c);
|
||||
*reinterpret_cast<sycl::vec<uint16_t, 8>*>(pb + r * LDB + c) = x;
|
||||
}
|
||||
it.barrier(sycl::access::fence_space::local_space);
|
||||
for (int kk = 0; kk < KS; kk += 16) {
|
||||
jm::joint_matrix<sycl::sub_group, T, jm::use::a, 8, 16, jm::layout::row_major> a[C::MT];
|
||||
jm::joint_matrix<sycl::sub_group, T, jm::use::b, 16, TN, jm::layout::col_major> b[C::NT];
|
||||
for (int i = 0; i < C::MT; ++i)
|
||||
jm::joint_matrix_load(sg, a[i], sa.template get_multi_ptr<sycl::access::decorated::no>() +
|
||||
(sgm * C::MT * 8 + i * 8) * LDA + kk, LDA);
|
||||
for (int j = 0; j < C::NT; ++j)
|
||||
jm::joint_matrix_load(sg, b[j], sb.template get_multi_ptr<sycl::access::decorated::no>() +
|
||||
(sgn * C::NT * TN + j * TN) * LDB + kk, LDB);
|
||||
for (int i = 0; i < C::MT; ++i)
|
||||
for (int j = 0; j < C::NT; ++j) jm::joint_matrix_mad(sg, acc[i][j], a[i], b[j], acc[i][j]);
|
||||
}
|
||||
it.barrier(sycl::access::fence_space::local_space);
|
||||
}
|
||||
// epilogue: each sub-group moves its 8 x TN accumulator tiles through its own SLM slice (the A tile's space,
|
||||
// free after the last barrier), then writes alpha * acc + beta * Y with the row and column bounds
|
||||
float* st = reinterpret_cast<float*>(pa) + sgid * 8 * TN;
|
||||
const int ln = (int) sg.get_local_linear_id();
|
||||
for (int i = 0; i < C::MT; ++i) {
|
||||
const int r = sgm * C::MT * 8 + i * 8;
|
||||
if (r >= rows) continue;
|
||||
for (int j = 0; j < C::NT; ++j) {
|
||||
const int c = sgn * C::NT * TN + j * TN;
|
||||
if (c >= cols) continue;
|
||||
jm::joint_matrix_store(sg, acc[i][j],
|
||||
sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(st),
|
||||
TN, jm::layout::row_major);
|
||||
sycl::group_barrier(sg);
|
||||
const int lim = sycl::min(8, rows - r);
|
||||
if (c + ln < cols) {
|
||||
for (int rr = 0; rr < lim; ++rr) {
|
||||
float* y = Y + (size_t) (m0 + r + rr) * ldy + n0 + c + ln;
|
||||
const float v = alpha * st[rr * TN + ln];
|
||||
*y = beta == 0.0f ? v : v + beta * *y;
|
||||
}
|
||||
}
|
||||
sycl::group_barrier(sg);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
#else
|
||||
(void) q; (void) W; (void) lda; (void) X; (void) ldx; (void) Y; (void) ldy; (void) N; (void) Tn; (void) K; (void) alpha; (void) beta;
|
||||
std::fprintf(stderr, "xmx dense gemm: the XMX kernel is not built for this device (STRATA_NO_DG2_XMX)\n");
|
||||
std::exit(1);
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
#ifdef STRATA_XMX_SG16
|
||||
// BM=128, BN=64, BK=32, 256 threads (16 sub-groups of 16): the weights go to SLM already in the VNNI-2 packed order the DPAS B operand wants
|
||||
// (a 32-bit word = two consecutive K values of one output column), so joint_matrix_load takes it with layout ext_intel_packed and no
|
||||
// repacking; the activation rows go to SLM as they are. Each sub-group owns 16 rows x 32 columns (2 x 2 accumulator tiles of 8 x 16).
|
||||
// 20 KiB of SLM: 6 work-groups per Xe2 core. Same layout idea as the owner's Inkling BM=128 GEMM (ink_sy_intelarc_xmx.h); written for
|
||||
// this engine's operands (activation and weights both BF16 or FP16, FP32 accumulate, alpha / beta epilogue). K must be a multiple of 32.
|
||||
constexpr int kSbLd = 136; // elements per packed row (64 columns x 2 + 8 pad: no bank conflicts on the packed stores)
|
||||
#ifndef STRATA_PK_KS
|
||||
#define STRATA_PK_KS 32 // K per step (32 or 64)
|
||||
#endif
|
||||
#ifndef STRATA_PK_GRF256
|
||||
#define STRATA_PK_GRF256 0 // large-GRF mode halves the resident threads; the 4 accumulator tiles do not need it
|
||||
#endif
|
||||
template <class T, class Name>
|
||||
void launch_pk(sycl::queue& q, const T* W, int lda, const T* X, int ldx, float* Y, int ldy, int N, int Tn, int K, float alpha, float beta) {
|
||||
constexpr int KS = STRATA_PK_KS, KP = KS / 2, NK16 = KS / 16;
|
||||
const int nbm = (Tn + 127) / 128, nbn = (N + 63) / 64;
|
||||
strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
|
||||
sycl::local_accessor<T, 1> sA(128 * KS, h);
|
||||
sycl::local_accessor<T, 1> sB(KP * kSbLd, h);
|
||||
sycl::local_accessor<float, 1> sC(16 * 128, h);
|
||||
auto kern = [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] {
|
||||
auto sg = it.get_sub_group();
|
||||
const int gid = (int) it.get_group(0);
|
||||
const int bn = gid % nbn, bm = gid / nbn;
|
||||
const int tid = (int) it.get_local_id(0);
|
||||
const int sgi = tid >> 4, lane = tid & 15;
|
||||
const int m_base = bm * 128, n_base = bn * 64;
|
||||
const int sg_m = sgi >> 1, sg_n = sgi & 1;
|
||||
auto sA_mp = sA.template get_multi_ptr<sycl::access::decorated::no>();
|
||||
uint16_t* sA_u16 = reinterpret_cast<uint16_t*>(sA_mp.get());
|
||||
auto sB_mp = sB.template get_multi_ptr<sycl::access::decorated::no>();
|
||||
uint32_t* sB_u32 = reinterpret_cast<uint32_t*>(sB_mp.get());
|
||||
float* sC_f = sC.template get_multi_ptr<sycl::access::decorated::no>().get();
|
||||
jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16> c00, c10, c01, c11;
|
||||
jm::joint_matrix<sycl::sub_group, T, jm::use::a, 8, 16, jm::layout::row_major> a0, a1;
|
||||
jm::joint_matrix<sycl::sub_group, T, jm::use::b, 16, 16, jm::layout::ext_intel_packed> b0, b1;
|
||||
jm::joint_matrix_fill(sg, c00, 0.0f);
|
||||
jm::joint_matrix_fill(sg, c10, 0.0f);
|
||||
jm::joint_matrix_fill(sg, c01, 0.0f);
|
||||
jm::joint_matrix_fill(sg, c11, 0.0f);
|
||||
const int ra = tid >> 1, ka = (tid & 1) * (KS / 2); // this thread's KS/2 activation values of the K step
|
||||
const int gm = m_base + ra;
|
||||
for (int k0 = 0; k0 < K; k0 += KS) {
|
||||
sycl::vec<uint16_t, 8> xv[KS / 16];
|
||||
#pragma unroll
|
||||
for (int v = 0; v < KS / 16; ++v) xv[v] = sycl::vec<uint16_t, 8>(0);
|
||||
if (gm < Tn) {
|
||||
const uint16_t* xp = reinterpret_cast<const uint16_t*>(X) + (size_t) gm * ldx + k0 + ka;
|
||||
#pragma unroll
|
||||
for (int v = 0; v < KS / 16; ++v) xv[v] = *reinterpret_cast<const sycl::vec<uint16_t, 8>*>(xp + 8 * v);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int v = 0; v < KS / 16; ++v) *reinterpret_cast<sycl::vec<uint16_t, 8>*>(&sA_u16[ra * KS + ka + 8 * v]) = xv[v];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < 4; ++p) {
|
||||
const int n = p * 16 + sgi;
|
||||
const int gn = n_base + n;
|
||||
const uint32_t* wp = reinterpret_cast<const uint32_t*>(reinterpret_cast<const uint16_t*>(W) + (size_t) gn * lda + k0);
|
||||
#pragma unroll
|
||||
for (int kb = 0; kb < KS / 32; ++kb)
|
||||
sB_u32[(lane + 16 * kb) * (kSbLd / 2) + n] = (gn < N) ? wp[lane + 16 * kb] : 0u;
|
||||
}
|
||||
sycl::group_barrier(it.get_group());
|
||||
#pragma unroll
|
||||
for (int ks = 0; ks < NK16; ++ks) {
|
||||
auto pB = sB_mp + ks * 8 * kSbLd + sg_n * 64;
|
||||
jm::joint_matrix_load(sg, b0, pB, kSbLd);
|
||||
jm::joint_matrix_load(sg, b1, pB + 32, kSbLd);
|
||||
jm::joint_matrix_load(sg, a0, sA_mp + (sg_m * 8) * KS + ks * 16, KS);
|
||||
jm::joint_matrix_load(sg, a1, sA_mp + (64 + sg_m * 8) * KS + ks * 16, KS);
|
||||
jm::joint_matrix_mad(sg, c00, a0, b0, c00);
|
||||
jm::joint_matrix_mad(sg, c10, a0, b1, c10);
|
||||
jm::joint_matrix_mad(sg, c01, a1, b0, c01);
|
||||
jm::joint_matrix_mad(sg, c11, a1, b1, c11);
|
||||
}
|
||||
sycl::group_barrier(it.get_group());
|
||||
}
|
||||
float* pS = sC_f + sgi * 128;
|
||||
const int col0 = n_base + sg_n * 32 + lane, col1 = col0 + 16;
|
||||
auto epi = [&](auto& acc, int m_off, int col) {
|
||||
jm::joint_matrix_store(sg, acc, sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(pS), 16,
|
||||
jm::layout::row_major);
|
||||
sycl::group_barrier(sg);
|
||||
float hv[8];
|
||||
for (int r = 0; r < 8; ++r) hv[r] = pS[r * 16 + lane];
|
||||
sycl::group_barrier(sg);
|
||||
if (col < N) {
|
||||
for (int r = 0; r < 8; ++r) {
|
||||
const int g = m_base + m_off + sg_m * 8 + r;
|
||||
if (g < Tn) {
|
||||
float* y = Y + (size_t) g * ldy + col;
|
||||
const float v = alpha * hv[r];
|
||||
*y = beta == 0.0f ? v : v + beta * *y;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
epi(c00, 0, col0);
|
||||
epi(c10, 0, col1);
|
||||
epi(c01, 64, col0);
|
||||
epi(c11, 64, col1);
|
||||
};
|
||||
#if STRATA_PK_GRF256
|
||||
auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>};
|
||||
h.parallel_for<Name>(sycl::nd_range<1>((size_t) nbm * nbn * 256, 256), props, kern);
|
||||
#else
|
||||
h.parallel_for<Name>(sycl::nd_range<1>((size_t) nbm * nbn * 256, 256), kern);
|
||||
#endif
|
||||
});
|
||||
}
|
||||
class k_pk_f16; class k_pk_bf16;
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef STRATA_XMX_SG16
|
||||
// ESIMD, no SLM, no barriers: one hardware thread computes a (ES_MT*8) x (ES_NT*16) tile of Y. The activation block (rows x 16 K) and the
|
||||
// weight blocks come straight from global memory with 2D block loads; the weights are loaded as 32-bit words TRANSPOSED, which is exactly
|
||||
// the VNNI-2 packed B operand (a dword = two consecutive K of one column), so there is no repacking at all. Out-of-range rows and columns
|
||||
// read as zero and out-of-range stores are dropped by the block unit. K % 16 == 0, 64-byte aligned bases, pitches multiple of 16 bytes.
|
||||
#ifndef STRATA_ES_MT
|
||||
#define STRATA_ES_MT 2
|
||||
#endif
|
||||
#ifndef STRATA_ES_NT
|
||||
#define STRATA_ES_NT 2
|
||||
#endif
|
||||
#ifndef STRATA_ES_GRF
|
||||
#define STRATA_ES_GRF 256
|
||||
#endif
|
||||
#ifndef STRATA_ES_PF
|
||||
#define STRATA_ES_PF 2 // K steps ahead for the prefetches (0 = none)
|
||||
#endif
|
||||
namespace es = sycl::ext::intel::esimd;
|
||||
template <bool BF16, class Name>
|
||||
void launch_esimd(sycl::queue& q, const uint16_t* W, int lda, const uint16_t* X, int ldx, float* Y, int ldy, int N, int Tn, int K, float alpha, float beta) {
|
||||
constexpr int MT = STRATA_ES_MT, NT = STRATA_ES_NT;
|
||||
constexpr int TM = MT * 8, TN = NT * 16;
|
||||
constexpr auto PA = BF16 ? es::xmx::dpas_argument_type::bf16 : es::xmx::dpas_argument_type::fp16;
|
||||
const int ntm = (Tn + TM - 1) / TM, ntn = (N + TN - 1) / TN;
|
||||
const int gmb = (ntm + 3) / 4, gnb = (ntn + 3) / 4; // blocks of 4 x 4 tiles
|
||||
const uint32_t* Au = reinterpret_cast<const uint32_t*>(X);
|
||||
const uint32_t* Wu = reinterpret_cast<const uint32_t*>(W);
|
||||
const unsigned a_w = (unsigned) K * 2 - 1, a_h = (unsigned) Tn - 1, a_p = (unsigned) ldx * 2 - 1;
|
||||
const unsigned b_w = (unsigned) K * 2 - 1, b_h = (unsigned) N - 1, b_p = (unsigned) lda * 2 - 1;
|
||||
const unsigned y_w = (unsigned) N * 4 - 1, y_h = (unsigned) Tn - 1, y_p = (unsigned) ldy * 4 - 1;
|
||||
auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<STRATA_ES_GRF>};
|
||||
strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
|
||||
h.parallel_for<Name>(sycl::nd_range<1>((size_t) gmb * gnb * 16, 1), props, [=](sycl::nd_item<1> it) SYCL_ESIMD_KERNEL {
|
||||
using namespace sycl::ext::intel::esimd;
|
||||
const int gid = (int) it.get_group(0);
|
||||
// 4 x 4 blocks of tiles per run of 16 consecutive threads: a row block of A and a column block of B stay in the cache together
|
||||
const int grp = 4;
|
||||
const int per = grp * grp;
|
||||
const int g = gid / per, r = gid % per;
|
||||
const int gm = gmb;
|
||||
const int mt = ((g % gm) * grp + r / grp), nt = ((g / gm) * grp + r % grp);
|
||||
if (mt >= ntm || nt >= ntn) return;
|
||||
const int m0 = mt * TM, n0 = nt * TN;
|
||||
simd<float, 128> acc[MT][NT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NT; ++j) acc[i][j] = 0.0f;
|
||||
for (int k = 0; k < K; k += 16) {
|
||||
const int kd = k / 2;
|
||||
simd<uint32_t, TM * 8> a = load_2d<uint32_t, 8, TM, 1, false, false>(Au, a_w, a_h, a_p, kd, m0);
|
||||
simd<int, 128> b[NT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NT; ++j) {
|
||||
simd<uint32_t, 128> bw = load_2d<uint32_t, 8, 16, 1, true, false>(Wu, b_w, b_h, b_p, kd, n0 + 16 * j);
|
||||
b[j] = bw.template bit_cast_view<int>();
|
||||
}
|
||||
#if STRATA_ES_PF > 0
|
||||
if (k + 16 * STRATA_ES_PF < K) {
|
||||
sycl::ext::oneapi::experimental::properties pfp{cache_hint_L1<cache_hint::cached>, cache_hint_L2<cache_hint::cached>};
|
||||
const int kp = (k + 16 * STRATA_ES_PF) / 2;
|
||||
prefetch_2d<uint32_t, 8, TM, 1>(Au, a_w, a_h, a_p, kp, m0, pfp);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NT; ++j) prefetch_2d<uint32_t, 8, 16, 1>(Wu, b_w, b_h, b_p, kp, n0 + 16 * j, pfp);
|
||||
}
|
||||
#endif
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; ++i) {
|
||||
simd<uint32_t, 64> au = a.template select<64, 1>(64 * i);
|
||||
simd<int, 64> ai = au.template bit_cast_view<int>();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NT; ++j)
|
||||
acc[i][j] = xmx::dpas<8, 8, float, float, int, int, PA, PA>(acc[i][j], b[j], ai);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NT; ++j) {
|
||||
simd<float, 128> v = acc[i][j] * alpha;
|
||||
if (beta != 0.0f) {
|
||||
simd<float, 128> o = load_2d<float, 16, 8, 1, false, false>(Y, y_w, y_h, y_p, n0 + 16 * j, m0 + 8 * i);
|
||||
v += o * beta;
|
||||
}
|
||||
store_2d<float, 16, 8>(Y, y_w, y_h, y_p, n0 + 16 * j, m0 + 8 * i, v);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
class k_es_f16; class k_es_bf16;
|
||||
#endif
|
||||
|
||||
// the plain kernel: a 16 x 16 output tile per work-group, K in steps of 16 through SLM
|
||||
template <class T>
|
||||
float to_f32(T v);
|
||||
template <> inline float to_f32<half>(half v) { return (float) v; }
|
||||
template <> inline float to_f32<bf16>(bf16 v) { return (float) v; }
|
||||
|
||||
template <class T, class Name>
|
||||
void launch_plain(sycl::queue& q, const T* W, int64_t lda, const T* X, int64_t ldx, float* Y, int64_t ldy, int64_t N, int64_t Tn,
|
||||
int64_t K, float alpha, float beta) {
|
||||
constexpr int B = 16;
|
||||
const size_t gn = (size_t) ((N + B - 1) / B) * B, gt = (size_t) ((Tn + B - 1) / B) * B;
|
||||
strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
|
||||
sycl::local_accessor<float, 2> sw(sycl::range<2>(B, B), h), sx(sycl::range<2>(B, B), h);
|
||||
h.parallel_for<Name>(sycl::nd_range<2>({gt, gn}, {B, B}), [=](sycl::nd_item<2> it) {
|
||||
const int64_t t = (int64_t) it.get_global_id(0), n = (int64_t) it.get_global_id(1);
|
||||
const int lt = (int) it.get_local_id(0), ln = (int) it.get_local_id(1);
|
||||
const int64_t t0 = (int64_t) it.get_group(0) * B, n0 = (int64_t) it.get_group(1) * B;
|
||||
float acc = 0.0f;
|
||||
for (int64_t k0 = 0; k0 < K; k0 += B) {
|
||||
const int64_t k = k0 + ln;
|
||||
sx[lt][ln] = (t0 + lt < Tn && k < K) ? to_f32<T>(X[(t0 + lt) * ldx + k]) : 0.0f;
|
||||
const int64_t k2 = k0 + lt;
|
||||
sw[lt][ln] = (n0 + ln < N && k2 < K) ? to_f32<T>(W[(n0 + ln) * lda + k2]) : 0.0f;
|
||||
it.barrier(sycl::access::fence_space::local_space);
|
||||
for (int kk = 0; kk < B; ++kk) acc = sycl::fma(sx[lt][kk], sw[kk][ln], acc);
|
||||
it.barrier(sycl::access::fence_space::local_space);
|
||||
}
|
||||
if (t < Tn && n < N) {
|
||||
float* y = Y + t * ldy + n;
|
||||
const float v = alpha * acc;
|
||||
*y = beta == 0.0f ? v : v + beta * *y;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
class k_x_f16_s; class k_x_f16_b; class k_x_bf16_s; class k_x_bf16_b; class k_p_f16; class k_p_bf16;
|
||||
|
||||
bool aligned16(const void* p) { return (reinterpret_cast<uintptr_t>(p) & 15u) == 0; }
|
||||
} // namespace
|
||||
|
||||
bool gemm_tn(sycl::queue& q, Elem e, const uint16_t* W, int64_t lda, const uint16_t* X, int64_t ldx, float* Y, int64_t ldy,
|
||||
int64_t N, int64_t T, int64_t K, float alpha, float beta) {
|
||||
if (N <= 0 || T <= 0 || K <= 0) return true;
|
||||
static const bool force_plain = [] { const char* v = std::getenv("STRATA_DENSE_GEMM_PLAIN"); return v && v[0] == '1'; }();
|
||||
#ifndef STRATA_NO_DG2_XMX
|
||||
const bool xmx_ok = !force_plain && K % 8 == 0 && lda % 8 == 0 && ldx % 8 == 0 && aligned16(W) && aligned16(X) &&
|
||||
N < (1 << 30) && T < (1 << 30) && K < (1 << 30) && lda < (1 << 30) && ldx < (1 << 30) && ldy < (1 << 30);
|
||||
#else
|
||||
const bool xmx_ok = false;
|
||||
#endif
|
||||
#ifdef STRATA_XMX_SG16
|
||||
// the ESIMD kernel (about 70 TFLOP/s against 31 for the SLM one in the standalone bench); STRATA_DENSE_GEMM_ESIMD=0 turns it off
|
||||
static const bool es_on = [] { const char* v = std::getenv("STRATA_DENSE_GEMM_ESIMD"); return !(v && v[0] == '0'); }();
|
||||
if (xmx_ok && es_on && T >= 32 && K % 16 == 0 && ldy % 4 == 0 && (reinterpret_cast<uintptr_t>(W) & 63u) == 0 &&
|
||||
(reinterpret_cast<uintptr_t>(X) & 63u) == 0 && (reinterpret_cast<uintptr_t>(Y) & 63u) == 0 && N >= 16) {
|
||||
if (e == Elem::f16) launch_esimd<false, k_es_f16>(q, W, (int) lda, X, (int) ldx, Y, (int) ldy, (int) N, (int) T, (int) K, alpha, beta);
|
||||
else launch_esimd<true, k_es_bf16>(q, W, (int) lda, X, (int) ldx, Y, (int) ldy, (int) N, (int) T, (int) K, alpha, beta);
|
||||
return true;
|
||||
}
|
||||
static const bool pk_off = [] { const char* v = std::getenv("STRATA_DENSE_GEMM_PK"); return v && v[0] == '0'; }();
|
||||
if (xmx_ok && !pk_off && T >= 128 && K % STRATA_PK_KS == 0 && lda % 2 == 0) {
|
||||
if (e == Elem::f16)
|
||||
launch_pk<half, k_pk_f16>(q, reinterpret_cast<const half*>(W), (int) lda, reinterpret_cast<const half*>(X), (int) ldx, Y, (int) ldy, (int) N,
|
||||
(int) T, (int) K, alpha, beta);
|
||||
else
|
||||
launch_pk<bf16, k_pk_bf16>(q, reinterpret_cast<const bf16*>(W), (int) lda, reinterpret_cast<const bf16*>(X), (int) ldx, Y, (int) ldy, (int) N,
|
||||
(int) T, (int) K, alpha, beta);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
if (xmx_ok) {
|
||||
const bool few = T <= 64;
|
||||
if (e == Elem::f16) {
|
||||
auto w = reinterpret_cast<const half*>(W);
|
||||
auto x = reinterpret_cast<const half*>(X);
|
||||
if (few) launch_xmx<half, Small, k_x_f16_s>(q, w, (int) lda, x, (int) ldx, Y, (int) ldy, (int) N, (int) T, (int) K, alpha, beta);
|
||||
else launch_xmx<half, Big, k_x_f16_b>(q, w, (int) lda, x, (int) ldx, Y, (int) ldy, (int) N, (int) T, (int) K, alpha, beta);
|
||||
} else {
|
||||
auto w = reinterpret_cast<const bf16*>(W);
|
||||
auto x = reinterpret_cast<const bf16*>(X);
|
||||
if (few) launch_xmx<bf16, Small, k_x_bf16_s>(q, w, (int) lda, x, (int) ldx, Y, (int) ldy, (int) N, (int) T, (int) K, alpha, beta);
|
||||
else launch_xmx<bf16, Big, k_x_bf16_b>(q, w, (int) lda, x, (int) ldx, Y, (int) ldy, (int) N, (int) T, (int) K, alpha, beta);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (e == Elem::f16)
|
||||
launch_plain<half, k_p_f16>(q, reinterpret_cast<const half*>(W), lda, reinterpret_cast<const half*>(X), ldx, Y, ldy, N, T, K, alpha, beta);
|
||||
else
|
||||
launch_plain<bf16, k_p_bf16>(q, reinterpret_cast<const bf16*>(W), lda, reinterpret_cast<const bf16*>(X), ldx, Y, ldy, N, T, K, alpha, beta);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace strata::prefill::xmxd
|
||||
@@ -0,0 +1,69 @@
|
||||
// Standalone timing and check of the dense prompt GEMM (xmx_dense_gemm.dp.cpp) on the card: ms and TFLOP/s per shape, and the max error
|
||||
// against a double-precision reference on sampled outputs. Not part of the engine build (built by hand, see the lane's scripts).
|
||||
// xmx_dense_gemm_bench [bf16|f16] [iters]
|
||||
#include <sycl/sycl.hpp>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
#include "strata/prefill/xmx_dense_gemm.hpp"
|
||||
|
||||
static uint16_t f2bf(float f) { uint32_t u; std::memcpy(&u, &f, 4); u += 0x7fff + ((u >> 16) & 1); return (uint16_t) (u >> 16); }
|
||||
static float bf2f(uint16_t h) { uint32_t u = (uint32_t) h << 16; float f; std::memcpy(&f, &u, 4); return f; }
|
||||
static uint16_t f2h(float f) { return sycl::bit_cast<uint16_t>(sycl::half(f)); }
|
||||
static float h2f(uint16_t h) { return (float) sycl::bit_cast<sycl::half>(h); }
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const bool bf = !(argc > 1 && std::strcmp(argv[1], "f16") == 0);
|
||||
const int iters = argc > 2 ? std::atoi(argv[2]) : 10;
|
||||
sycl::queue q{sycl::gpu_selector_v, sycl::property_list{sycl::property::queue::in_order{}}};
|
||||
std::printf("device %s, %s\n", q.get_device().get_info<sycl::info::device::name>().c_str(), bf ? "bf16" : "f16");
|
||||
struct Shape { const char* what; int T, N, K; };
|
||||
const Shape shapes[] = {
|
||||
{"gdn qkv-like ", 4096, 8192, 2560}, {"gdn z-like ", 4096, 4096, 2560}, {"out proj ", 4096, 2560, 4096},
|
||||
{"hc down ", 4096, 320, 10240}, {"hc up ", 4096, 10240, 320}, {"hc inject ", 4096, 4, 10240},
|
||||
{"qsa q proj ", 4096, 8192, 2560}, {"square 4096 ", 4096, 4096, 4096}, {"T=512 8192x2560 ", 512, 8192, 2560},
|
||||
};
|
||||
std::mt19937 rng(7);
|
||||
std::uniform_real_distribution<float> U(-1.f, 1.f);
|
||||
int bad = 0;
|
||||
for (const Shape& s : shapes) {
|
||||
const size_t nw = (size_t) s.N * s.K, nx = (size_t) s.T * s.K, ny = (size_t) s.T * s.N;
|
||||
std::vector<uint16_t> w(nw), x(nx);
|
||||
for (auto& v : w) { const float f = U(rng) * 0.1f; v = bf ? f2bf(f) : f2h(f); }
|
||||
for (auto& v : x) { const float f = U(rng); v = bf ? f2bf(f) : f2h(f); }
|
||||
uint16_t* dw = sycl::malloc_device<uint16_t>(nw, q);
|
||||
uint16_t* dx = sycl::malloc_device<uint16_t>(nx, q);
|
||||
float* dy = sycl::malloc_device<float>(ny, q);
|
||||
q.memcpy(dw, w.data(), nw * 2); q.memcpy(dx, x.data(), nx * 2); q.memset(dy, 0, ny * 4).wait();
|
||||
using strata::prefill::xmxd::Elem;
|
||||
const Elem e = bf ? Elem::bf16 : Elem::f16;
|
||||
for (int i = 0; i < 3; ++i) strata::prefill::xmxd::gemm_tn(q, e, dw, s.K, dx, s.K, dy, s.N, s.N, s.T, s.K, 1.0f, 0.0f);
|
||||
q.wait();
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
for (int i = 0; i < iters; ++i) strata::prefill::xmxd::gemm_tn(q, e, dw, s.K, dx, s.K, dy, s.N, s.N, s.T, s.K, 1.0f, 0.0f);
|
||||
q.wait();
|
||||
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / iters;
|
||||
std::vector<float> y(ny);
|
||||
q.memcpy(y.data(), dy, ny * 4).wait();
|
||||
double maxrel = 0;
|
||||
for (int k = 0; k < 64; ++k) {
|
||||
const int t = (int) (rng() % s.T), n = (int) (rng() % s.N);
|
||||
double ref = 0;
|
||||
for (int kk = 0; kk < s.K; ++kk) ref += (double) (bf ? bf2f(x[(size_t) t * s.K + kk]) : h2f(x[(size_t) t * s.K + kk])) *
|
||||
(double) (bf ? bf2f(w[(size_t) n * s.K + kk]) : h2f(w[(size_t) n * s.K + kk]));
|
||||
const double got = y[(size_t) t * s.N + n];
|
||||
maxrel = std::fmax(maxrel, std::fabs(got - ref) / (std::fabs(ref) + 1e-3 * std::sqrt((double) s.K)));
|
||||
}
|
||||
if (maxrel > 2e-3) ++bad;
|
||||
const double tf = 2.0 * s.T * s.N * s.K / (ms * 1e-3) / 1e12;
|
||||
std::printf("%s T=%5d N=%5d K=%5d %8.3f ms %6.1f TFLOP/s max rel err %.2e%s\n", s.what, s.T, s.N, s.K, ms, tf, maxrel,
|
||||
maxrel > 2e-3 ? " <-- WRONG" : "");
|
||||
sycl::free(dw, q); sycl::free(dx, q); sycl::free(dy, q);
|
||||
}
|
||||
std::printf(bad ? "RESULT: %d shapes wrong\n" : "RESULT: all ok\n", bad);
|
||||
return bad ? 1 : 0;
|
||||
}
|
||||
@@ -147,6 +147,27 @@ namespace strata::prefill { void set_nonresident_share(double share); } // SYC
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <vector>
|
||||
#ifdef _WIN32
|
||||
// windows.h (pulled in by the SYCL headers) defines these as macros; the engine uses them as names
|
||||
#ifdef small
|
||||
#undef small
|
||||
#endif
|
||||
#ifdef OUT
|
||||
#undef OUT
|
||||
#endif
|
||||
#ifdef IN
|
||||
#undef IN
|
||||
#endif
|
||||
// memmem is a GNU extension
|
||||
static const void* memmem(const void* h, size_t hn, const void* n, size_t nn) {
|
||||
if (nn == 0) return h;
|
||||
const unsigned char* hp = static_cast<const unsigned char*>(h);
|
||||
const unsigned char* np = static_cast<const unsigned char*>(n);
|
||||
for (size_t i = 0; i + nn <= hn; ++i)
|
||||
if (hp[i] == np[0] && std::memcmp(hp + i, np, nn) == 0) return hp + i;
|
||||
return nullptr;
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
bool sycl_mirror_adapt() {
|
||||
@@ -627,6 +648,7 @@ struct Options {
|
||||
/// and the KV state, minus this reserve for the graphs, the hit scratch and the head.
|
||||
int vram_reserve_mib = 700;
|
||||
bool vram_reserve_given = false; ///< --vram-reserve-mib on the command line (#496: no smaller automatic reserve)
|
||||
int vram_reserve_floor_mib = 0; ///< --vram-reserve-floor-mib N: with --expert-cache auto, a reserve above N shrinks (down to N) when that holds EVERY expert of the profile in VRAM (the zero-doorbell window graph); 0 = off
|
||||
/// #533 (opt-in): the expert cache in physical segments (CUDA virtual memory management), so the serve loop's
|
||||
/// `VRAM <reserve_mib>` command can give part of it back to other programs and take it again. Off: one cudaMalloc.
|
||||
bool vram_elastic = false;
|
||||
@@ -1184,6 +1206,24 @@ struct GpuStage {
|
||||
int32_t* mrope = nullptr; ///< --vision: the image-position table on its device
|
||||
};
|
||||
|
||||
// The RAM the process can still get (bytes; 0 = unknown). Windows: the available physical memory (the Linux build reads
|
||||
// /proc/meminfo, which Windows does not have: without this the pinned expert mirror and the KV streaming rule saw 0 bytes).
|
||||
static uint64_t host_avail_bytes() {
|
||||
#if defined(_WIN32)
|
||||
strata::core::detail::HostMemory hm;
|
||||
return strata::core::detail::host_available_memory(hm) ? hm.available : 0;
|
||||
#else
|
||||
uint64_t avail = 0;
|
||||
if (FILE* f = std::fopen("/proc/meminfo", "r")) {
|
||||
char key[64]; unsigned long long kb = 0;
|
||||
while (std::fscanf(f, "%63s %llu kB", key, &kb) == 2)
|
||||
if (std::strcmp(key, "MemAvailable:") == 0) { avail = kb << 10; break; }
|
||||
std::fclose(f);
|
||||
}
|
||||
return avail;
|
||||
#endif
|
||||
}
|
||||
|
||||
// ---- issue #31: what the watchdog prints before it stops a stalled engine
|
||||
struct MemSample {
|
||||
unsigned long long faults = 0, rss_mib = 0, avail_mib = 0, commit_mib = 0; // faults: hard (Linux) / all (Windows)
|
||||
@@ -2013,6 +2053,7 @@ int main(int argc, char **argv) try {
|
||||
else if (a == "--expert-cache-remote-placement")
|
||||
o.expert_cache_remote_placement = next("--expert-cache-remote-placement");
|
||||
else if (a == "--vram-reserve-mib") { o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib")); o.vram_reserve_given = true; }
|
||||
else if (a == "--vram-reserve-floor-mib") o.vram_reserve_floor_mib = std::max(0, std::atoi(next("--vram-reserve-floor-mib")));
|
||||
else if (a == "--vram-reserve-later-mib")
|
||||
o.vram_reserve_later_mib = std::atoi(next("--vram-reserve-later-mib"));
|
||||
else if (a == "--prefill") {
|
||||
@@ -4254,14 +4295,7 @@ int main(int argc, char **argv) try {
|
||||
if (pick > 0) {
|
||||
// the pinned RAM the streamed K/V takes (it is a copy of the whole context per session): 1.8 GB a session at 128K int8
|
||||
int64_t host_avail = -1;
|
||||
if (std::FILE* mf = std::fopen("/proc/meminfo", "r")) {
|
||||
char line[256];
|
||||
while (std::fgets(line, sizeof(line), mf)) {
|
||||
long long kb = 0;
|
||||
if (std::sscanf(line, "MemAvailable: %lld kB", &kb) == 1) { host_avail = (int64_t) kb << 10; break; }
|
||||
}
|
||||
std::fclose(mf);
|
||||
}
|
||||
if (const uint64_t ha = host_avail_bytes(); ha > 0) host_avail = (int64_t) ha;
|
||||
const int64_t host_need = n_sess * (int64_t) o.max_context * 13 * 1056 + (6ll << 30);
|
||||
if (host_avail >= 0 && host_avail < host_need) {
|
||||
std::fprintf(stderr, "strata generate: the context does not fit in VRAM and %.1f GiB of free RAM is less than the %.1f GiB KV streaming would take: not turned on\n",
|
||||
@@ -4880,6 +4914,23 @@ int main(int argc, char **argv) try {
|
||||
std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved (+%lld MiB for the "
|
||||
"draft head) -> %d slots\n",
|
||||
(double) free_b / 1073741824.0, o.vram_reserve_mib, (long long) (mtp_bind >> 20), o.expert_cache);
|
||||
// --vram-reserve-floor-mib: a card that holds every expert of the profile once the reserve is cut to the floor runs the
|
||||
// zero-doorbell window graph (no host round trip per layer: Arc Pro B70, Coder IQ1_M, 4 K context: decode +13% at the
|
||||
// default window, +35% for one-token steps). What is allocated after the cache (the prompt path's own buffers, the draft
|
||||
// head, the pipeline's window) is priced into the reserve above, so the floor is only the margin for the driver and the graphs.
|
||||
if (o.vram_reserve_floor_mib > 0 && o.vram_reserve_mib > o.vram_reserve_floor_mib && !profile.empty() &&
|
||||
o.expert_cache < (int64_t) profile.size()) {
|
||||
const int64_t short_b = ((int64_t) profile.size() - (int64_t) o.expert_cache) * blob;
|
||||
const int64_t need_mib = (short_b + (1 << 20) - 1) >> 20;
|
||||
const int64_t r = (int64_t) o.vram_reserve_mib - need_mib;
|
||||
if (r >= o.vram_reserve_floor_mib) {
|
||||
std::fprintf(stderr, "strata generate: expert cache auto: every expert of the profile (%lld) fits with a %lld MiB reserve (the floor is %d MiB): "
|
||||
"%d MiB reserve instead of %d -> %lld slots, all in VRAM\n",
|
||||
(long long) profile.size(), (long long) r, o.vram_reserve_floor_mib, (int) r, o.vram_reserve_mib, (long long) profile.size());
|
||||
o.vram_reserve_mib = (int) r;
|
||||
o.expert_cache = (int) profile.size();
|
||||
}
|
||||
}
|
||||
// #496: the verify window cannot start without a cache (#174), and a cache too small to lend the prompt path
|
||||
// a 256-token chunk's buffers (plus the 128 slots a loan leaves; one slot without --prefill) makes it
|
||||
// allocate its own on top - more than the reserve. When the default reserve leaves less than that (a 6 GB
|
||||
@@ -5465,15 +5516,16 @@ int main(int argc, char **argv) try {
|
||||
miss.push_back({l, e});
|
||||
}
|
||||
}
|
||||
uint64_t avail = 0;
|
||||
if (FILE* f = std::fopen("/proc/meminfo", "r")) {
|
||||
char key[64]; unsigned long long kb = 0;
|
||||
while (std::fscanf(f, "%63s %llu kB", key, &kb) == 2)
|
||||
if (std::strcmp(key, "MemAvailable:") == 0) { avail = kb << 10; break; }
|
||||
std::fclose(f);
|
||||
}
|
||||
const uint64_t avail = host_avail_bytes();
|
||||
const char* mv = std::getenv("STRATA_MIRROR_MIB");
|
||||
uint64_t cap = mv ? (uint64_t) std::atoll(mv) << 20 : (avail > (4ull << 30) ? avail - (4ull << 30) : 0);
|
||||
#if defined(_WIN32)
|
||||
// Windows counts the file cache as available and the OS needs room for the engine's own working set, the KV and the page cache of
|
||||
// the GGUF reads: keep 8 GiB free (Linux: 4 GiB). IQ3_S on a 32 GB PC with the 4 GiB rule pinned 17.8 GiB and ran out of RAM.
|
||||
const uint64_t mirror_keep = 8ull << 30;
|
||||
#else
|
||||
const uint64_t mirror_keep = 4ull << 30;
|
||||
#endif
|
||||
uint64_t cap = mv ? (uint64_t) std::atoll(mv) << 20 : (avail > mirror_keep ? avail - mirror_keep : 0);
|
||||
// #6448: on an integrated GPU the mirror comes out of the pool the cache was sized from. An auto cache took what
|
||||
// the pool allows, so what it left is the reserve of the allocations still to come, not room for a mirror: the
|
||||
// experts it could not hold are read from the file by the host, or, with STRATA_VERIFY_NO_HOST, refused below
|
||||
|
||||
@@ -145,6 +145,42 @@ int main(int argc, char** argv) {
|
||||
std::printf(" ALF-LB top-32 lookahead route, %d groups (1 token): reference %7.2f us, parallel %7.2f us\n", tg, ta, tb);
|
||||
}
|
||||
}
|
||||
{ // dynamic expert skip (--skip-tau): the prune kernel against a CPU reference (same operations in the same order: bit-identical), tau 0.03 / 0.05 / 0.08
|
||||
long pbad = 0, ptotal = 0, pdropped = 0;
|
||||
for (float tau : {0.03f, 0.05f, 0.08f}) {
|
||||
const int PN = 512, PK = 8;
|
||||
std::vector<float> pw(static_cast<size_t>(PN) * PK), prw;
|
||||
std::vector<int> pix(pw.size()), prix;
|
||||
std::mt19937 pr(1234 + static_cast<int>(tau * 1000));
|
||||
for (size_t i = 0; i < pw.size(); ++i) { pw[i] = 0.01f + 0.4f * ((pr() & 0xFFFF) / 65535.0f); pix[i] = static_cast<int>(pr() % 512); }
|
||||
prw = pw; prix = pix;
|
||||
for (int t = 0; t < PN; ++t) { // CPU reference
|
||||
float* w = prw.data() + static_cast<size_t>(t) * PK;
|
||||
int* ix = prix.data() + static_cast<size_t>(t) * PK;
|
||||
float sum = 0.0f, wmax = -1.0f;
|
||||
int imax = 0;
|
||||
for (int j = 0; j < PK; ++j) { sum += w[j]; if (w[j] > wmax) { wmax = w[j]; imax = j; } }
|
||||
float kept = 0.0f;
|
||||
int drops = 0;
|
||||
for (int j = 0; j < PK; ++j) { if (j != imax && w[j] < tau * sum) ++drops; else kept += w[j]; }
|
||||
if (drops == 0 || !(kept > 0.0f)) continue;
|
||||
const float scale = sum / kept;
|
||||
const int top_id = ix[imax];
|
||||
for (int j = 0; j < PK; ++j) { if (j != imax && w[j] < tau * sum) { ix[j] = top_id; w[j] = 0.0f; ++pdropped; } else w[j] *= scale; }
|
||||
}
|
||||
float* dw; int* dix;
|
||||
CK(cudaMalloc(&dw, pw.size() * 4)); CK(cudaMalloc(&dix, pix.size() * 4));
|
||||
CK(cudaMemcpy(dw, pw.data(), pw.size() * 4, cudaMemcpyHostToDevice)); CK(cudaMemcpy(dix, pix.data(), pix.size() * 4, cudaMemcpyHostToDevice));
|
||||
gpu::prune_experts(dix, dw, PN, PK, tau, 0);
|
||||
CK(cudaDeviceSynchronize());
|
||||
std::vector<float> gw(pw.size()); std::vector<int> gix(pix.size());
|
||||
CK(cudaMemcpy(gw.data(), dw, gw.size() * 4, cudaMemcpyDeviceToHost)); CK(cudaMemcpy(gix.data(), dix, gix.size() * 4, cudaMemcpyDeviceToHost));
|
||||
for (size_t i = 0; i < gw.size(); ++i) { ++ptotal; if (gix[i] != prix[i] || std::memcmp(&gw[i], &prw[i], 4) != 0) ++pbad; }
|
||||
cudaFree(dw); cudaFree(dix);
|
||||
}
|
||||
std::printf(" expert skip (prune_experts) vs CPU reference: %ld of %ld (expert, weight) pairs differ (%ld slots dropped) %s\n", pbad, ptotal, pdropped, pbad == 0 && pdropped > 0 ? "IDENTICAL" : "MISMATCH");
|
||||
if (pbad || pdropped == 0) return 1;
|
||||
}
|
||||
cudaFree(lg); cudaFree(w1); cudaFree(w2); cudaFree(i1); cudaFree(i2);
|
||||
if (bad) return 1;
|
||||
}
|
||||
|
||||
@@ -53,6 +53,7 @@ int main(int argc, char** argv) {
|
||||
bool q8 = false, tc = false, graph = false, e2e = false, trunk_only = false, lat16 = false, mla_exp = false;
|
||||
int mla_kernel = 0; // --mla K: the MLA attention kernel (1 simt, 2 tensor cores split, 3 tensor cores fast)
|
||||
int n_layers_test = 0; // --layers K: only the first K layers (with --trunk-only: the real file on a card too small for the experts)
|
||||
int kda_seq = 0; // --kda-seq K: batches of more than K tokens take the chunk-parallel KDA and the expanded MLA (the 12-token fixture prompt is below the default 16)
|
||||
for (int i = 4; i < argc; ++i) {
|
||||
q8 = q8 || std::string(argv[i]) == "--q8";
|
||||
tc = tc || std::string(argv[i]) == "--tc";
|
||||
@@ -63,6 +64,7 @@ int main(int argc, char** argv) {
|
||||
mla_exp = mla_exp || std::string(argv[i]) == "--mla-exp"; // the expanded-form MLA prefill (needs the fp32 latent cache; chunks of more than kda_seq_max_n tokens)
|
||||
if (std::string(argv[i]) == "--layers" && i + 1 < argc) n_layers_test = std::atoi(argv[i + 1]);
|
||||
if (std::string(argv[i]) == "--mla" && i + 1 < argc) mla_kernel = std::atoi(argv[i + 1]);
|
||||
if (std::string(argv[i]) == "--kda-seq" && i + 1 < argc) kda_seq = std::atoi(argv[i + 1]);
|
||||
} // --e2e: long prompt, chunked, logits only
|
||||
const int T = static_cast<int>(ids.size());
|
||||
Ling32File f;
|
||||
@@ -86,6 +88,7 @@ int main(int argc, char** argv) {
|
||||
eo.latent = lat16 ? strata::ling32::LatentFmt::F16 : strata::ling32::LatentFmt::F32; // --lat16: the fp16 latent cache (looser tolerances)
|
||||
eo.max_tokens = 64;
|
||||
eo.mla_kernel = mla_kernel;
|
||||
if (kda_seq > 0) { eo.kda_seq_max_n = kda_seq; eo.graph_max_n = kda_seq; } // the expanded MLA needs N above both
|
||||
if (mla_exp) { eo.mla_expanded = true; eo.mla_prefill_kernel = 2; eo.mla_exp_slab = 64; if (eo.mla_kernel == 0) eo.mla_kernel = 2; }
|
||||
eo.lookahead = !trunk_only;
|
||||
eo.capture = true;
|
||||
|
||||
@@ -816,6 +816,24 @@ void bench_batches() {
|
||||
}
|
||||
}
|
||||
|
||||
// the route + grouped-experts cases at the real batch sizes; only_chunk: just the 16384-pair case (L32MOE_ONLY_CHUNK=1, to run the largest case alone)
|
||||
static void run_big_section(bool only_chunk) {
|
||||
std::printf("[route + grouped experts at the real batch sizes: P = 1024 .. 16384 pairs, E = 512 experts, a hot expert with 100+ pairs, unused experts]\n");
|
||||
BigRoute B;
|
||||
B.S = make_slabs(512, 512, 256, 0, {4, 5, 6, 8});
|
||||
B.dsec = dev(B.S.buf);
|
||||
B.ddesc = dev(B.S.desc);
|
||||
if (!only_chunk) {
|
||||
run_big_route(B, 128, 8, 25, "hot 25 percent");
|
||||
run_big_route(B, 512, 8, 12, "hot 12 percent");
|
||||
run_big_route(B, 512, 8, 0, "uniform");
|
||||
run_big_route(B, 64, 8, 60, "hot 60 percent");
|
||||
}
|
||||
run_big_route(B, 2048, 8, 5, "chunk of 2048 tokens");
|
||||
cudaFree(B.dsec);
|
||||
cudaFree(B.ddesc);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (!std::getenv("L32MOE_BENCH")) setenv("STRATA_L32_TRUNK_XMX_TILES", "0", 0); // the small trunk shapes of the test must reach the XMX kernel (the default needs 128 tiles)
|
||||
if (argc < 2) { std::printf("usage: ling32_moe_sy_test DATA_DIR\n"); return 2; }
|
||||
@@ -830,6 +848,7 @@ int main(int argc, char** argv) {
|
||||
for (int code : {4, 5, 6, 8})
|
||||
if (!slurp(std::string(argv[1]) + "/pack_s" + std::to_string(code) + ".bin", g_pack[code])) { std::printf("pack_s%d.bin missing\n", code); return 2; }
|
||||
|
||||
if (std::getenv("L32MOE_ONLY_CHUNK")) { run_big_section(true); std::printf("%s (%d failed)\n", g_fail ? "FAIL" : "PASS", g_fail); return g_fail ? 1 : 0; }
|
||||
std::printf("[routed experts: moe_gu / moe_act / moe_dn / moe_tc_*, small shape D=512 I=256, mixed S4/S5/S6/S8 slabs, N = 1..16 pairs]\n");
|
||||
{
|
||||
const Slabs S = make_slabs(12, 512, 256, 7, {4, 5, 6, 8});
|
||||
@@ -864,20 +883,7 @@ int main(int argc, char** argv) {
|
||||
std::printf("[trunk GEMM: gemm_sk_tc (XMX tiles where the device has them) against the float GEMV, row counts that are no multiple of the 128-row tile, token counts around the tile widths]\n");
|
||||
for (int code : {8, 5, 4, 6, 2, 3})
|
||||
for (int N : {1, 31, 33, 40, 100, 129}) run_trunk(code, code == 8 ? 200 : 392, code == 8 ? 768 : 512, N, N % 2 == 0);
|
||||
std::printf("[route + grouped experts at the real batch sizes: P = 1024 .. 16384 pairs, E = 512 experts, a hot expert with 100+ pairs, unused experts]\n");
|
||||
{
|
||||
BigRoute B;
|
||||
B.S = make_slabs(512, 512, 256, 0, {4, 5, 6, 8});
|
||||
B.dsec = dev(B.S.buf);
|
||||
B.ddesc = dev(B.S.desc);
|
||||
run_big_route(B, 128, 8, 25, "hot 25 percent");
|
||||
run_big_route(B, 512, 8, 12, "hot 12 percent");
|
||||
run_big_route(B, 512, 8, 0, "uniform");
|
||||
run_big_route(B, 64, 8, 60, "hot 60 percent");
|
||||
run_big_route(B, 2048, 8, 5, "chunk of 2048 tokens");
|
||||
cudaFree(B.dsec);
|
||||
cudaFree(B.ddesc);
|
||||
}
|
||||
run_big_section(false);
|
||||
std::printf("%s (%d failed)\n", g_fail ? "FAIL" : "PASS", g_fail);
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// tests/ling32/ling32_sy_kda_test.cpp - the SYCL chunk-parallel KDA prefill scan (sycl/ling32_sy_k_kda.cpp): the scan split over the value columns (modes 4 and 8, launch_chunk_seq2 + launch_chunk_norm) and the
|
||||
// one-column-per-lane scan (mode 0, launch_chunk_seq) against the sequential recurrence (kda_step without chunking), outputs and final state, at head dim 64 and 128 and N = 40 / 100 (no multiple of the chunk);
|
||||
// then, at the real shape (32 heads, head dim 128, 2048 tokens), the accuracy of every mode and the time of the pre + scan (+ norm) launches. usage: ling32_sy_kda_test [skip-big]
|
||||
#include "ling32_kernels.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace strata::ling32::gpu;
|
||||
|
||||
namespace strata::ling32::gpu {
|
||||
extern int g_sy_kda_seq_mode;
|
||||
}
|
||||
|
||||
namespace {
|
||||
int g_fail = 0;
|
||||
void check(bool ok, const std::string& what, double v) {
|
||||
std::printf(" %-110s %s (%.3g)\n", what.c_str(), ok ? "ok" : "FAIL", v);
|
||||
if (!ok) ++g_fail;
|
||||
}
|
||||
template <class T> T* up(const std::vector<T>& h) {
|
||||
void* p = nullptr;
|
||||
if (cudaMalloc(&p, h.size() * sizeof(T)) != cudaSuccess) { std::fprintf(stderr, "alloc failed\n"); std::exit(1); }
|
||||
cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice);
|
||||
return static_cast<T*>(p);
|
||||
}
|
||||
std::vector<float> down(const float* d, size_t n) {
|
||||
std::vector<float> h(n);
|
||||
cudaMemcpy(h.data(), d, n * 4, cudaMemcpyDeviceToHost);
|
||||
return h;
|
||||
}
|
||||
double now_ms() { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
|
||||
|
||||
struct Case {
|
||||
int H, hd, N, C;
|
||||
std::vector<float> qn, kn, vc, fr, gr, br, Al, db, on, S0;
|
||||
float *dq, *dk, *dv, *df, *dg, *dbeta, *dA, *ddb, *don, *dout, *dS, *dscr;
|
||||
size_t scr_floats;
|
||||
Case(int H_, int hd_, int N_, unsigned seed) : H(H_), hd(hd_), N(N_), C(H_ * hd_) {
|
||||
std::mt19937 rng(seed);
|
||||
auto rnd = [&](size_t n, float lo, float hi) {
|
||||
std::vector<float> v(n);
|
||||
for (auto& x : v) x = lo + (hi - lo) * ((rng() & 0xFFFF) / 65535.0f);
|
||||
return v;
|
||||
};
|
||||
const float ks = 1.0f / std::sqrt(static_cast<float>(hd));
|
||||
qn = rnd(size_t(N) * C, -ks, ks); kn = rnd(size_t(N) * C, -ks, ks); vc = rnd(size_t(N) * C, -1.f, 1.f); fr = rnd(size_t(N) * C, -1.f, 1.f); gr = rnd(size_t(N) * C, -1.f, 1.f);
|
||||
br = rnd(size_t(N) * H, -1.f, 1.f); Al = rnd(H, -1.f, 0.f); db = rnd(C, -0.5f, 0.5f); on = rnd(hd, 0.5f, 1.5f); S0 = rnd(size_t(H) * hd * hd, -0.05f, 0.05f);
|
||||
dq = up(qn); dk = up(kn); dv = up(vc); df = up(fr); dg = up(gr); dbeta = up(br); dA = up(Al); ddb = up(db); don = up(on); dS = up(S0);
|
||||
cudaMalloc(reinterpret_cast<void**>(&dout), size_t(N) * C * 4);
|
||||
scr_floats = kda_chunk_scratch_floats(N, H, hd);
|
||||
cudaMalloc(reinterpret_cast<void**>(&dscr), scr_floats * 4);
|
||||
}
|
||||
void run(bool chunked, int mode, std::vector<float>& o, std::vector<float>& st) {
|
||||
g_sy_kda_seq_mode = mode;
|
||||
cudaMemcpy(dS, S0.data(), S0.size() * 4, cudaMemcpyHostToDevice);
|
||||
kda_step(dS, dq, dk, dv, df, C, dg, C, dbeta, dA, ddb, don, -5.0f, 1e-6f, dout, N, H, hd, chunked, 0, nullptr, chunked ? dscr : nullptr, chunked ? scr_floats : 0);
|
||||
cudaDeviceSynchronize();
|
||||
o = down(dout, size_t(N) * C);
|
||||
st = down(dS, S0.size());
|
||||
}
|
||||
double time_ms(int mode, int reps) {
|
||||
g_sy_kda_seq_mode = mode;
|
||||
auto once = [&] { kda_step(dS, dq, dk, dv, df, C, dg, C, dbeta, dA, ddb, don, -5.0f, 1e-6f, dout, N, H, hd, true, 0, nullptr, dscr, scr_floats); };
|
||||
once();
|
||||
cudaDeviceSynchronize();
|
||||
const double t0 = now_ms();
|
||||
for (int i = 0; i < reps; ++i) once();
|
||||
cudaDeviceSynchronize();
|
||||
return (now_ms() - t0) / reps;
|
||||
}
|
||||
~Case() { cudaFree(dq); cudaFree(dk); cudaFree(dv); cudaFree(df); cudaFree(dg); cudaFree(dbeta); cudaFree(dA); cudaFree(ddb); cudaFree(don); cudaFree(dout); cudaFree(dS); cudaFree(dscr); }
|
||||
};
|
||||
|
||||
double relerr(const std::vector<float>& x, const std::vector<float>& y) {
|
||||
double num = 0, den = 0;
|
||||
for (size_t i = 0; i < x.size(); ++i) {
|
||||
if (!std::isfinite(x[i])) return 1e30;
|
||||
num = std::fmax(num, std::fabs(double(x[i]) - y[i]));
|
||||
den += double(y[i]) * y[i];
|
||||
}
|
||||
return num / (std::sqrt(den / x.size()) + 1e-30);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
cudaDeviceProp prop;
|
||||
cudaGetDeviceProperties(&prop, 0);
|
||||
std::printf("device: %s\n", prop.name);
|
||||
bool big = true;
|
||||
for (int i = 1; i < argc; ++i)
|
||||
if (std::string(argv[i]) == "skip-big") big = false;
|
||||
for (int hd : {64, 128})
|
||||
for (int N : {40, 100}) {
|
||||
Case c(2, hd, N, 7 + hd + N);
|
||||
std::vector<float> o_ref, s_ref;
|
||||
c.run(false, 0, o_ref, s_ref);
|
||||
for (int mode : {0, 4, 8}) {
|
||||
std::vector<float> o, st;
|
||||
c.run(true, mode, o, st);
|
||||
const double e = std::fmax(relerr(o, o_ref), relerr(st, s_ref));
|
||||
check(e < 2e-4, "KDA chunk scan mode " + std::to_string(mode) + " hd " + std::to_string(hd) + " N " + std::to_string(N) + ": max rel error vs the sequential recurrence (outputs and state)", e);
|
||||
}
|
||||
}
|
||||
if (big) {
|
||||
Case c(32, 128, 2048, 99);
|
||||
std::vector<float> o_ref, s_ref;
|
||||
c.run(false, 0, o_ref, s_ref);
|
||||
for (int mode : {0, 4, 8}) {
|
||||
std::vector<float> o, st;
|
||||
c.run(true, mode, o, st);
|
||||
const double e = std::fmax(relerr(o, o_ref), relerr(st, s_ref));
|
||||
check(e < 2e-4, "KDA chunk scan mode " + std::to_string(mode) + " at 32 heads, hd 128, N 2048: max rel error vs the sequential recurrence", e);
|
||||
}
|
||||
for (int mode : {0, 4, 8}) std::printf(" chunk path (pre + scan%s) mode %d, 32 heads, hd 128, 2048 tokens: %.3f ms per call\n", mode ? " + norm" : "", mode, c.time_ms(mode, mode == 0 ? 3 : 10));
|
||||
}
|
||||
std::printf(g_fail ? "FAIL (%d failures)\n" : "PASS (0 failures)\n", g_fail);
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// tests/ling32/ling32_sy_mla_exp_test.cpp - the expanded-form MLA prefill on SYCL (sycl/ling32_sy_k_mla_exp.cpp) against the engine's absorbed pipeline (mla_qabs + mla_attn original kernel + mla_out) on random data
|
||||
// of the real geometry (H heads, nope 128, rope 64, vhead 128, kv_lora 512, fp32 latent cache), for several (tokens, position) shapes and slab sizes. Port of ling32_mla_exp_test.cu.
|
||||
// ling32_sy_mla_exp_test [full] [bench] "full": also the big cases (H = 32, 300 tokens at position 3000); "bench": times a 2048-token chunk at 16384 context against the absorbed path
|
||||
// On a device without XMX the test needs STRATA_L32_MLA_EXP_MODE=1 (plain loops, slow); it skips otherwise.
|
||||
#include "ling32_kernels.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace strata::ling32::gpu;
|
||||
|
||||
namespace {
|
||||
int g_fail = 0;
|
||||
void check(bool ok, const char* what, double v) {
|
||||
std::printf(" %-100s %s (%.3g)\n", what, ok ? "ok" : "FAIL", v);
|
||||
if (!ok) ++g_fail;
|
||||
}
|
||||
uint16_t f2bf(float f) { uint32_t u; std::memcpy(&u, &f, 4); u += 0x7fffu + ((u >> 16) & 1u); return static_cast<uint16_t>(u >> 16); }
|
||||
template <class T> T* dalloc(size_t n) {
|
||||
void* p = nullptr;
|
||||
if (cudaMalloc(&p, n * sizeof(T)) != cudaSuccess) { std::fprintf(stderr, "alloc of %zu bytes failed\n", n * sizeof(T)); std::exit(1); }
|
||||
return static_cast<T*>(p);
|
||||
}
|
||||
template <class T> T* up(const std::vector<T>& h) {
|
||||
T* p = dalloc<T>(h.size());
|
||||
cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice);
|
||||
return p;
|
||||
}
|
||||
template <class F> double time_ms(F f, int reps) {
|
||||
f();
|
||||
cudaDeviceSynchronize();
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
for (int i = 0; i < reps; ++i) f();
|
||||
cudaDeviceSynchronize();
|
||||
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / reps;
|
||||
}
|
||||
|
||||
struct Data {
|
||||
int H, kv_cap;
|
||||
std::vector<float> q, cache, gate;
|
||||
std::vector<uint16_t> wk, wv;
|
||||
float *dq, *dcache, *dgate;
|
||||
uint16_t *dwk, *dwv, *dwk16, *dwv16;
|
||||
};
|
||||
|
||||
Data make_data(int H, int N_cap, int kv_cap, unsigned seed) {
|
||||
Data d;
|
||||
d.H = H;
|
||||
d.kv_cap = kv_cap;
|
||||
const int NOPE = 128, ROPE = 64, QW = NOPE + ROPE, R = 512, W = R + ROPE, V = 128;
|
||||
std::mt19937 rng(seed);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
d.q.resize(static_cast<size_t>(N_cap) * H * QW);
|
||||
d.cache.resize(static_cast<size_t>(kv_cap) * W);
|
||||
d.gate.resize(static_cast<size_t>(N_cap) * H);
|
||||
d.wk.resize(static_cast<size_t>(H) * NOPE * R);
|
||||
d.wv.resize(static_cast<size_t>(H) * V * R);
|
||||
for (auto& v : d.q) v = nd(rng) * 0.5f;
|
||||
for (auto& v : d.cache) v = nd(rng);
|
||||
for (auto& v : d.gate) v = nd(rng);
|
||||
for (auto& v : d.wk) v = f2bf(nd(rng) * 0.06f);
|
||||
for (auto& v : d.wv) v = f2bf(nd(rng) * 0.06f);
|
||||
d.dq = up(d.q); d.dcache = up(d.cache); d.dgate = up(d.gate);
|
||||
d.dwk = up(d.wk); d.dwv = up(d.wv);
|
||||
d.dwk16 = dalloc<uint16_t>(d.wk.size()); d.dwv16 = dalloc<uint16_t>(d.wv.size());
|
||||
mla_exp_convert_weights(d.dwk, d.wk.size(), d.dwk16, 0);
|
||||
mla_exp_convert_weights(d.dwv, d.wv.size(), d.dwv16, 0);
|
||||
cudaDeviceSynchronize();
|
||||
return d;
|
||||
}
|
||||
|
||||
void run_case(const Data& d, int N, int pos0, int slab) {
|
||||
const int H = d.H, NOPE = 128, ROPE = 64, R = 512, W = R + ROPE, V = 128;
|
||||
const float scale = 1.0f / std::sqrt(192.0f);
|
||||
float* qabs = dalloc<float>(static_cast<size_t>(N) * H * R);
|
||||
float* ctx = dalloc<float>(static_cast<size_t>(N) * H * R);
|
||||
float* ref = dalloc<float>(static_cast<size_t>(N) * H * V);
|
||||
float* out = dalloc<float>(static_cast<size_t>(N) * H * V);
|
||||
int* dpos = dalloc<int>(1);
|
||||
cudaMemcpy(dpos, &pos0, 4, cudaMemcpyHostToDevice);
|
||||
mla_qabs(d.dq, d.dwk, qabs, N, H, NOPE, ROPE, R, 0);
|
||||
mla_attn(qabs, d.dq, d.dcache, dpos, ctx, N, H, NOPE, ROPE, R, scale, true, 0);
|
||||
mla_out(ctx, d.dwv, d.dgate, ref, N, H, V, R, 0);
|
||||
const size_t eb = mla_exp_workspace_bytes(N, H, slab);
|
||||
void* ews = dalloc<char>(eb);
|
||||
mla_exp_prefill(d.dq, d.dcache, W, d.dwk16, d.dwv16, d.dgate, out, N, H, pos0, scale, ews, eb, slab, 0);
|
||||
cudaDeviceSynchronize();
|
||||
std::vector<float> r(static_cast<size_t>(N) * H * V), o(r.size());
|
||||
cudaMemcpy(r.data(), ref, r.size() * 4, cudaMemcpyDeviceToHost);
|
||||
cudaMemcpy(o.data(), out, r.size() * 4, cudaMemcpyDeviceToHost);
|
||||
double md = 0, mr = 0;
|
||||
bool finite = true;
|
||||
for (size_t i = 0; i < r.size(); ++i) {
|
||||
if (!std::isfinite(o[i])) finite = false;
|
||||
md = std::max(md, static_cast<double>(std::fabs(o[i] - r[i])));
|
||||
mr = std::max(mr, static_cast<double>(std::fabs(r[i])));
|
||||
}
|
||||
char buf[160];
|
||||
std::snprintf(buf, sizeof(buf), "H=%d N=%d pos0=%d slab=%d: expanded vs absorbed fp32 scalar (max |ref| %.3f)", H, N, pos0, slab, mr);
|
||||
check(finite && md < 2e-5 * std::max(1.0, mr), buf, md);
|
||||
cudaFree(qabs); cudaFree(ctx); cudaFree(ref); cudaFree(out); cudaFree(dpos); cudaFree(ews);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
cudaDeviceProp prop;
|
||||
cudaGetDeviceProperties(&prop, 0);
|
||||
std::printf("device: %s\n", prop.name);
|
||||
bool full = false, bench = false;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (std::string(argv[i]) == "full") full = true;
|
||||
if (std::string(argv[i]) == "bench") bench = true;
|
||||
}
|
||||
if (!mla_exp_ok(128, 64, 128, 512)) {
|
||||
std::printf("no XMX on this device (STRATA_L32_MLA_EXP_MODE=1 forces the plain-loop mode): skipped\n");
|
||||
return 0;
|
||||
}
|
||||
{
|
||||
Data d = make_data(4, 96, 1500, 11);
|
||||
run_case(d, 40, 0, 64); // first chunk
|
||||
run_case(d, 70, 0, 256);
|
||||
run_case(d, 96, 1000, 128); // later chunk: keys of earlier chunks in several slabs
|
||||
run_case(d, 33, 1400, 512);
|
||||
run_case(d, 17, 63, 64); // ragged edges
|
||||
}
|
||||
{
|
||||
Data d = make_data(32, 300, full ? 3600 : 800, 5); // the real head count
|
||||
run_case(d, 129, 0, 2048);
|
||||
run_case(d, 100, 700, 128);
|
||||
if (full) run_case(d, 300, 3000, 1024);
|
||||
}
|
||||
if (bench) {
|
||||
const int H = 32, N = 2048, pos0 = 14336, W = 576, R = 512, NOPE = 128, ROPE = 64, V = 128;
|
||||
Data d = make_data(H, N, pos0 + N, 3);
|
||||
const float scale = 1.0f / std::sqrt(192.0f);
|
||||
float* out = dalloc<float>(static_cast<size_t>(N) * H * V);
|
||||
for (int slab : {1024, 2048, 4096}) {
|
||||
const size_t eb = mla_exp_workspace_bytes(N, H, slab);
|
||||
void* ews = dalloc<char>(eb);
|
||||
const double t = time_ms([&] { mla_exp_prefill(d.dq, d.dcache, W, d.dwk16, d.dwv16, d.dgate, out, N, H, pos0, scale, ews, eb, slab, 0); }, 2);
|
||||
std::printf(" expanded, N=%d context=%d slab %d keys (workspace %.0f MB): %.2f ms\n", N, pos0 + N, slab, eb / 1048576.0, t);
|
||||
cudaFree(ews);
|
||||
}
|
||||
if (std::getenv("STRATA_L32_MLA_EXP_ABS")) { // the absorbed path (slow: minutes at this size)
|
||||
float* qabs = dalloc<float>(static_cast<size_t>(N) * H * R);
|
||||
float* ctx = dalloc<float>(static_cast<size_t>(N) * H * R);
|
||||
float* ref = dalloc<float>(static_cast<size_t>(N) * H * V);
|
||||
int* dpos = dalloc<int>(1);
|
||||
cudaMemcpy(dpos, &pos0, 4, cudaMemcpyHostToDevice);
|
||||
const double t = time_ms([&] {
|
||||
mla_qabs(d.dq, d.dwk, qabs, N, H, NOPE, ROPE, R, 0);
|
||||
mla_attn(qabs, d.dq, d.dcache, dpos, ctx, N, H, NOPE, ROPE, R, scale, true, 0);
|
||||
mla_out(ctx, d.dwv, d.dgate, ref, N, H, V, R, 0);
|
||||
}, 1);
|
||||
std::printf(" absorbed original path (qabs + attention + out): %.2f ms\n", t);
|
||||
}
|
||||
}
|
||||
std::printf(g_fail ? "FAIL (%d failures)\n" : "PASS (0 failures)\n", g_fail);
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
@@ -82,7 +82,7 @@ struct Verifier {
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 2) { std::printf("usage: ling32_sy_tier_check FILE.strata [--vr N] [--rr N] [--dyn N] [--ring N] [--fwds N] [--zc 0|1] [--pf 0|1] [--seed S] [--tokens a,b,c] [--noisy 0|1]\n"); return 2; }
|
||||
const std::string path = argv[1];
|
||||
int vr = 0, rr = 0, dyn = 24, ring = 0, fwds = 12, zc = 0, pf = 1, noisy = 1;
|
||||
int vr = 0, rr = 0, dyn = 24, ring = 0, fwds = 12, zc = 0, pf = 1, noisy = 1, adapt = -1;
|
||||
unsigned seed = 7;
|
||||
std::vector<int> tokens = {1, 1, 1, 2, 5, 32, 130, 256};
|
||||
for (int i = 2; i + 1 < argc; i += 2) {
|
||||
@@ -96,6 +96,7 @@ int main(int argc, char** argv) {
|
||||
else if (a == "--zc") zc = std::atoi(v.c_str());
|
||||
else if (a == "--pf") pf = std::atoi(v.c_str());
|
||||
else if (a == "--noisy") noisy = std::atoi(v.c_str());
|
||||
else if (a == "--adapt") adapt = std::atoi(v.c_str());
|
||||
else if (a == "--seed") seed = static_cast<unsigned>(std::atoi(v.c_str()));
|
||||
else if (a == "--tokens") {
|
||||
tokens.clear();
|
||||
@@ -143,6 +144,16 @@ int main(int argc, char** argv) {
|
||||
std::printf("plan: %s, vram ranks %d (%.3f MiB), ram ranks %d (%.3f MiB), ssd %.3f MiB, dyn slots %d, ring slots %d, slab %llu B max; zero copy %d, prefetch %d\n", tier_name(plan.mode), vr, plan.vram_prefix_bytes / 1048576.0, rr,
|
||||
plan.ram_prefix_bytes / 1048576.0, plan.ssd_bytes / 1048576.0, dyn, plan.ring_slots, static_cast<unsigned long long>(rt.max_slab), zc, pf);
|
||||
|
||||
// the adaptive warm tier (on by default with in-place reads) takes the coldest RAM slots as spares and relies on those experts being on the SSD: with no SSD tier (Mode B) it makes them unreachable
|
||||
// ("the dynamic slots / ring are too small for one expert"), also on CUDA; --miss zc is opt-in there. Off by default here in Mode B; --adapt 1 forces it.
|
||||
if (adapt < 0 && plan.mode == TierMode::B) adapt = 0;
|
||||
if (adapt >= 0) {
|
||||
#ifdef _WIN32
|
||||
_putenv_s("STRATA_L32_ADAPT", adapt ? "1" : "0");
|
||||
#else
|
||||
setenv("STRATA_L32_ADAPT", adapt ? "1" : "0", 1);
|
||||
#endif
|
||||
}
|
||||
GpuModel M;
|
||||
LoadOptions lo;
|
||||
lo.load_experts = false;
|
||||
|
||||
@@ -87,7 +87,7 @@ int main(int argc, char** argv) {
|
||||
p = plan_tier(hw, rq, rt, sz);
|
||||
std::printf("%s\n", p.describe().c_str());
|
||||
// the default for cards up to 30 GiB is the pool layout: no static prefix, every card byte for experts is a slot
|
||||
CHECK(p.ok && p.mode == TierMode::B && p.lookahead_k == 4 && p.pool_mode && p.vram_ranks == 0 && p.dyn_slots > 1000);
|
||||
CHECK(p.ok && p.mode == TierMode::B && p.lookahead_k == 2 && p.pool_mode && p.vram_ranks == 0 && p.dyn_slots > 1000);
|
||||
CHECK(p.vram_prefix_bytes == 0 && p.ram_prefix_bytes == rt.total && p.ssd_bytes == 0 && p.ring_slots == 0);
|
||||
CHECK(p.vram_total_planned <= p.vram_budget);
|
||||
// the old layout (hot prefix + a small pool) is --tier-pool off
|
||||
|
||||
@@ -60,17 +60,19 @@ static size_t free_mib() {
|
||||
static double now() { return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 4) { std::printf("usage: %s VISION.strata GOLDEN_DIR IMAGE_DIR [--tol T] [--device N] [--idle S] [--no-cpu] [stem...]\n", argv[0]); return 2; }
|
||||
if (argc < 4) { std::printf("usage: %s VISION.strata GOLDEN_DIR IMAGE_DIR [--tol T] [--device N] [--idle S] [--no-cpu] [--lowmem] [--time IMAGE]... [stem...]\n", argv[0]); return 2; }
|
||||
const std::string vis = argv[1], gold = argv[2], imgs = argv[3];
|
||||
double tol = 1e-4, idle = 2.0;
|
||||
int device = 0;
|
||||
bool cpu = true;
|
||||
std::vector<std::string> stems;
|
||||
bool cpu = true, lowmem = false;
|
||||
std::vector<std::string> stems, timed; // timed: --time IMAGE (a picture without a golden file: encode time, the CPU comparison, no float64 reference)
|
||||
for (int i = 4; i < argc; ++i) {
|
||||
if (!std::strcmp(argv[i], "--tol") && i + 1 < argc) tol = std::atof(argv[++i]);
|
||||
else if (!std::strcmp(argv[i], "--device") && i + 1 < argc) device = std::atoi(argv[++i]);
|
||||
else if (!std::strcmp(argv[i], "--idle") && i + 1 < argc) idle = std::atof(argv[++i]);
|
||||
else if (!std::strcmp(argv[i], "--no-cpu")) cpu = false;
|
||||
else if (!std::strcmp(argv[i], "--lowmem")) lowmem = true;
|
||||
else if (!std::strcmp(argv[i], "--time") && i + 1 < argc) timed.push_back(argv[++i]);
|
||||
else stems.push_back(argv[i]);
|
||||
}
|
||||
if (stems.empty()) stems = {"tiny_100x60", "noise_250x370", "grad_300x500", "shapes_448", "doc_480x640"};
|
||||
@@ -124,6 +126,49 @@ int main(int argc, char** argv) {
|
||||
std::printf(" cpu %.2f s; gpu %.1f ms (second run %.1f ms); gpu vs cpu rel L2 %.2e (max abs %.2e)\n", dt, st.encode_ms, st2.encode_ms, rc, mx2);
|
||||
}
|
||||
}
|
||||
if (lowmem) { // the memory budget (SYCL encoder): a picture too big for it (30000 patches, ~1 GiB of activations; the preparation never makes one that big, the planner's budget is 1600 MiB with the weights) is
|
||||
// refused before anything is allocated, with a message; the next picture works. The CUDA encoder has no such check (this option is for the SYCL build).
|
||||
std::printf("== memory budget\n");
|
||||
PreparedImage big;
|
||||
big.gh = 150;
|
||||
big.gw = 200;
|
||||
big.h = big.gh * 16;
|
||||
big.w = big.gw * 16;
|
||||
big.pix.assign(static_cast<size_t>(big.gh) * big.gw * C.patch_vals(), 0.0f);
|
||||
std::vector<float> ob, o2;
|
||||
const bool ok = G.encode(big, ob, err);
|
||||
std::printf(" %d patches: encode %s%s\n", big.gh * big.gw, ok ? "worked" : "refused: ", ok ? "" : err.c_str());
|
||||
CHECK(!ok && err.find("MiB") != std::string::npos, "the encoder should refuse a picture that does not fit in its budget, with a message");
|
||||
PreparedImage im;
|
||||
err.clear();
|
||||
if (!vision_prepare_file(C, imgs + "/" + stems.front() + ".png", im, err)) { std::printf(" prepare: %s\n", err.c_str()); ++g_fail; }
|
||||
else CHECK(G.encode(im, o2, err), "the encoder must work after a refusal (%s)", err.c_str());
|
||||
}
|
||||
for (const std::string& path : timed) { // big pictures: time, stages against the CPU encoder, and the memory refusal
|
||||
std::printf("== time %s\n", path.c_str());
|
||||
PreparedImage im;
|
||||
if (!vision_prepare_file(C, path, im, err)) { std::printf(" prepare: %s\n", err.c_str()); ++g_fail; continue; }
|
||||
std::vector<float> o1, o2;
|
||||
VisionCheckpoints ck;
|
||||
VisionGpuStats st;
|
||||
double t0 = now();
|
||||
if (!G.encode(im, o1, err, cpu ? &ck : nullptr, &st)) { std::printf(" gpu: %s (the caller would use the CPU encoder)\n", err.c_str()); continue; }
|
||||
const double t_first = now() - t0;
|
||||
t0 = now();
|
||||
G.encode(im, o2, err, nullptr, &st);
|
||||
const double t_second = now() - t0;
|
||||
std::printf(" gpu: %dx%d patches, %zu embeddings, first call %.0f ms, second %.0f ms (scratch %.0f MiB)\n", im.gh, im.gw, o1.size() / static_cast<size_t>(C.out_dim), t_first * 1000, t_second * 1000, st.scratch_bytes / 1048576.0);
|
||||
CHECK(o1 == o2, "two runs of the same picture differ");
|
||||
if (cpu) {
|
||||
VisionCheckpoints cc;
|
||||
std::vector<float> oc;
|
||||
t0 = now();
|
||||
vision_encode_cpu(W, im, oc, err, 0, &cc);
|
||||
std::printf(" cpu %.1f s; gpu vs cpu rel L2: embed %.2e blk0 %.2e blk13 %.2e blk26 %.2e merged %.2e OUT %.2e\n", now() - t0, rel_ff(ck.embed, cc.embed), rel_ff(ck.blk0, cc.blk0), rel_ff(ck.blk13, cc.blk13),
|
||||
rel_ff(ck.blk26, cc.blk26), rel_ff(ck.merged, cc.merged), rel_ff(o1, oc));
|
||||
CHECK(rel_ff(o1, oc) <= tol, "gpu vs cpu above %.1e", tol);
|
||||
}
|
||||
}
|
||||
// memory / idle unload
|
||||
{
|
||||
const size_t held = free0 - free_mib();
|
||||
|
||||
+1524
-554
File diff suppressed because it is too large.
Load diff
@@ -162,8 +162,16 @@ class EngineArgs(unittest.TestCase):
|
||||
cfg["args"] = [*cfg["args"], "--vision", vis, *extra]
|
||||
cfg.pop("ling32_mtp")
|
||||
return ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False)
|
||||
a = args_for("sycl") # Intel: no GPU encoder yet
|
||||
a = args_for("sycl") # Intel: no GPU encoder yet (the engine gives no vision= word)
|
||||
self.assertEqual(a[a.index("--vision-max-pixels"):], ["--vision-max-pixels", "1000000"])
|
||||
os.environ["LING32_MOCK_CAPS"] = "images=1 vision=gpu" # the Intel engine with its GPU encoder says so in --info --kv: the cap is lifted at the start
|
||||
ling32_kind._PROBES.clear()
|
||||
self.assertNotIn("--vision-max-pixels", args_for("sycl"))
|
||||
os.environ["LING32_MOCK_CAPS"] = "images=1 vision=cpu"
|
||||
ling32_kind._PROBES.clear()
|
||||
self.assertIn("--vision-max-pixels", args_for("sycl"))
|
||||
os.environ["LING32_MOCK_CAPS"] = "images=1"
|
||||
ling32_kind._PROBES.clear()
|
||||
a = args_for("metal", ["--vision-device", "cpu"]) # the Mac encodes on the GPU now: capped only when the CPU encoder is forced
|
||||
self.assertEqual(a[a.index("--vision-max-pixels") + 1], "1000000")
|
||||
a = args_for("cuda", ["--vision-device", "cpu"]) # any --vision-device cpu
|
||||
|
||||
+88
-42
@@ -9597,6 +9597,33 @@ def _select_sycl_cards(a, cards: list[dict]) -> list[dict]:
|
||||
return list(cards[:1])
|
||||
|
||||
|
||||
INTEL_FAST_MIN_RAM_GB = 32 # IQ2_XS / IQ3_S with the DFlash2 drafter on an Intel Arc (the default since 2026-12-03): QFN-B70's B70 box with 32 GB: free RAM down to 10.6 GiB (IQ2_XS) and 6.2 GiB (IQ3_S, commit 44 GiB): said, not refused
|
||||
INTEL_GGUF_MIN_RAM_GB = 24 # an Arc run of a Qwen size keeps about 20 GB of the PC's RAM busy (QFN-B70, the B70 box with 32 GB: 20 GB free at the lowest with IQ3_S): said, not refused
|
||||
|
||||
|
||||
def intel_download_gguf(a, family: str, fam: dict, model: str, model_dir: Path) -> list:
|
||||
"""The files of a GGUF model for an Intel Arc card are not on the computer: check the disk (what is still missing plus the pack and a margin) and the RAM (said, not refused), then download them the way an
|
||||
NVIDIA / AMD install does (fetch_gguf_shards: the pinned sources, SHA-256 and finish marks, resumable). Returns the shards (intel_app.model_files_in), [] when they are still not there."""
|
||||
from strata_control import intel_app
|
||||
if getattr(a, "models_dir", None) is None:
|
||||
a.models_dir = str(model_dir.parent)
|
||||
shards = [model_dir / model_file(fam, model, i) for i in range(1, model_shards(fam, model) + 1)]
|
||||
model_dir.mkdir(parents=True, exist_ok=True)
|
||||
on_disk = sum(f.stat().st_size for s in shards for f in (s, s.with_name(s.name + ".part")) if f.is_file()) / 1e9 # a download that resumes needs room only for what is still missing
|
||||
to_fetch = max(MODELS[model]["download_gb"] - on_disk, 0.0)
|
||||
pack_dir = model_dir.parent.parent / "packs" / run_tag(a, family, fam, model).lower()
|
||||
problem = disk_room_problem(model_dir, pack_dir, to_fetch + 8, 0.0, (f" ({on_disk:.0f} GB of the model is already there)" if on_disk >= 1 else "")) # 8 GB: the pack and working room
|
||||
if problem:
|
||||
fail(*problem, kind="no_space", path=str(model_dir), free_bytes=int(free_gb(model_dir) * 1e9), needed_bytes=int((to_fetch + 8) * 1e9))
|
||||
ram = ram_gb()
|
||||
if ram and ram < INTEL_GGUF_MIN_RAM_GB:
|
||||
warn(f"this computer has {ram:.0f} GB of RAM: a {model} run on an Intel Arc card keeps about 20 GB of it busy, so it may run slowly or not start")
|
||||
step(2, f"downloading {fam['title']} {model} ({to_fetch:.0f} GB)")
|
||||
fetch_gguf_shards(a, family, fam, model, shards, model_dir)
|
||||
check_shards(shards)
|
||||
return intel_app.model_files_in(model_dir, family, fam)
|
||||
|
||||
|
||||
def intel_control_setup(a) -> int:
|
||||
"""`--backend sycl` in the app's CONTROL mode (tools/strata_mcp.py passes it for an Intel Arc PC): what the Terminal does for an Arc
|
||||
(strata_cli/launch/runner.py adopt_prepared_files): the pack from the model's GGUF files (`--prepare-pack`'s step), then the run config
|
||||
@@ -9607,9 +9634,10 @@ def intel_control_setup(a) -> int:
|
||||
from strata_control import intel_app
|
||||
say("Strata on an Intel Arc card (the SYCL engine)")
|
||||
step(1, "checking this computer")
|
||||
if not intel_app.supported_here():
|
||||
fail("the Intel Arc engine runs on Linux only", "there is no Windows or Mac Intel engine yet")
|
||||
family = a.family or "qwen"
|
||||
kind = "inkling" if family in INKLING_FAMILIES else "hy4" if family in HY4_FAMILIES else "qwen"
|
||||
if not intel_app.route_here(kind, model=a.model if kind == "qwen" else None, family=family if kind == "qwen" else None):
|
||||
fail("this model has no Intel Arc engine for this computer yet", "Linux runs every Intel route; Windows runs Ling-3.2-Air, Inkling-2-Mini and the Qwen3.8-Flash-Next Coder IQ1_M, IQ2_XS and IQ3_S sizes; there is no Mac Intel engine")
|
||||
if family in HY4_FAMILIES or family in INKLING_FAMILIES:
|
||||
cards = intel_app.arc_cards()
|
||||
if not cards:
|
||||
@@ -9638,6 +9666,8 @@ def intel_control_setup(a) -> int:
|
||||
if model_dir.is_file():
|
||||
model_dir = model_dir.parent
|
||||
shards = intel_app.model_files_in(model_dir, family, fam)
|
||||
if not shards and not a.gguf_dir and intel_app.can_download(family, model, fam):
|
||||
shards = intel_download_gguf(a, family, fam, model, model_dir)
|
||||
if not shards:
|
||||
fail(intel_app.NO_DOWNLOAD)
|
||||
ok(f"model files: {model_dir} ({len(shards)} file{'s' if len(shards) != 1 else ''})")
|
||||
@@ -9645,6 +9675,11 @@ def intel_control_setup(a) -> int:
|
||||
sel_cards = _select_sycl_cards(a, cards) if cards else []
|
||||
vram = max((float(c.get("vram_gb") or 0) for c in (sel_cards or cards)), default=0.0)
|
||||
ok("graphics card: " + (", ".join(f"{c['name']} ({c['vram_gb']:g} GB)" for c in cards) or "an Intel Arc"))
|
||||
from strata_control import drafting as _drafting
|
||||
_ram = ram_gb()
|
||||
if model in ("IQ2_XS", "IQ3_S") and family in ("qwen", "coder") and not _drafting.INTEL_PLAIN_BY_DEFAULT and _ram and _ram < INTEL_FAST_MIN_RAM_GB:
|
||||
warn(f"this computer has {_ram:.0f} GB of RAM: {model} with the fast drafter (DFlash2) on an Intel Arc needs about {INTEL_FAST_MIN_RAM_GB} GB; with less it may run slowly or not start. "
|
||||
"Choose drafting Off for the plain mode, which needs less.")
|
||||
if a.check:
|
||||
return 0
|
||||
SHAPE_ENGINE.clear()
|
||||
@@ -10848,14 +10883,15 @@ def ling32_fetch_mtp(a, folder: Path, own: bool, model: Path | None = None, extr
|
||||
|
||||
|
||||
def ling32_engine_args(a, vram_gib, ram_gib, unified, ctx, vision: bool = False, vision_device: str = "auto", gpu_cap_gib: float | None = None, mtp: bool = False,
|
||||
backend: str = "cuda") -> tuple[list, dict]:
|
||||
backend: str = "cuda", card_gib: float | None = None, pin_half: bool | None = None) -> tuple[list, dict]:
|
||||
"""The engine arguments of a Ling-3.2-Air start and the plan they come from: the fast path (explicit, so a start never depends on a default that may move), the context and
|
||||
chunk, then the person's tier choices as flags (ling32_fit.tier_args: nothing for `auto`: the engine plans by itself with the same rule). Returns (args, advise()'s dict)."""
|
||||
adv = ling32_fit.advise(vram_gib, ram_gib, unified=unified, tier=getattr(a, "tier", None) or "auto", vram_budget_gib=getattr(a, "vram_budget_gib", None) or 0.0,
|
||||
ram_budget_gib=getattr(a, "ram_budget_gib", None) or 0.0, turbo_ssd=bool(getattr(a, "turbo_ssd", False)), ctx=ctx, vision=vision, vision_device=vision_device, gpu_cap_gib=gpu_cap_gib, mtp=mtp, backend=backend)
|
||||
ram_budget_gib=getattr(a, "ram_budget_gib", None) or 0.0, turbo_ssd=bool(getattr(a, "turbo_ssd", False)), ctx=ctx, vision=vision, vision_device=vision_device, gpu_cap_gib=gpu_cap_gib, mtp=mtp, backend=backend, card_gib=card_gib, pin_half=WIN if pin_half is None else pin_half)
|
||||
args = ["--ctx", str(ctx), "--chunk", str(adv["plan"]["chunk"]), *ling32_family.ENGINE_FLAGS.get(backend, ling32_family.ENGINE_FLAGS["cuda"])]
|
||||
if backend == "metal": # no tiers on a Mac: the whole model is in memory
|
||||
return args, adv
|
||||
args += ling32_fit.skip_tau_args(getattr(a, "expert_skip", None), backend, card_gib or vram_gib, adv["tier"]) # the expert skip: only when asked (--expert-skip medium) and offered here
|
||||
args += ling32_fit.tier_args(tier=getattr(a, "tier", None) or "auto", vram_budget_gib=getattr(a, "vram_budget_gib", None) or 0.0,
|
||||
ram_budget_gib=getattr(a, "ram_budget_gib", None) or 0.0, turbo_ssd=bool(getattr(a, "turbo_ssd", False)),
|
||||
cpu_coexec=getattr(a, "cpu_coexec", None) or 0,
|
||||
@@ -10877,12 +10913,7 @@ def ling32_intel_cards(platform: str | None = None) -> list[dict]:
|
||||
if platform.startswith("linux"):
|
||||
return [dict(c) for c in intel_app.arc_cards()]
|
||||
if platform.startswith("win"):
|
||||
from strata_control import engine_component as ec
|
||||
cards = []
|
||||
for ad in ec.windows_display_adapters():
|
||||
if ad.get("vendor") == "8086" and "arc" in str(ad.get("name", "")).lower() and float(ad.get("vram_gb") or 0) >= 4.0:
|
||||
cards.append({"vendor": "intel", "name": str(ad["name"]), "vram_gb": float(ad["vram_gb"]), "usable": True, "index": len(cards)})
|
||||
return cards
|
||||
return intel_app.windows_arc_cards() # the same list the app's hardware report uses
|
||||
except Exception: # noqa: BLE001 - a probe that fails lists nothing
|
||||
pass
|
||||
return []
|
||||
@@ -10920,6 +10951,7 @@ def install_ling32_air(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adop
|
||||
fail(f"{fam['title']} has no {a.model} model file", "choose: " + ling32_family.BUILD)
|
||||
ok(f"size: {model}")
|
||||
vision, vision_device = ling32_vision_choice(a) # pictures are on by default (the Vision shard is in the download set); --vision no leaves it out
|
||||
plan_vision_device = vision_device # what the memory plan assumes (an Intel card: the processor until its engine advertises a GPU encoder)
|
||||
backend = ling32_backend(a, hip, amd)
|
||||
if backend == "sycl" and not ling32_family.sycl_available():
|
||||
warn("Ling-3.2-Air has no Intel engine yet (it runs on NVIDIA, AMD and Apple Silicon): the engine will not start on this PC until one exists")
|
||||
@@ -10928,7 +10960,9 @@ def install_ling32_air(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adop
|
||||
if level != "tested":
|
||||
warn(words)
|
||||
if vision_device == "auto":
|
||||
vision_device = "cpu" # the Intel engine reads pictures on the processor (no GPU encoder yet)
|
||||
if ling32_family.SYCL_VISION_DEVICE == "cpu":
|
||||
vision_device = "cpu" # written into the config: the engine reads pictures on the processor whatever it could do
|
||||
plan_vision_device = "cpu" # the plan counts the picture reader on the processor (the Intel GPU encoder is not advertised yet); the config keeps the engine's own choice (auto): `vision=gpu` then lifts the cap and uses the GPU
|
||||
elif backend == "hip":
|
||||
level, words = ling32_family.hip_support((gpu or {}).get("arch"))
|
||||
if level != "tested":
|
||||
@@ -10984,7 +11018,7 @@ def install_ling32_air(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adop
|
||||
pv = folder / ling32_family.VISION_FILE
|
||||
if not ling32_have(a, pv):
|
||||
left += (ling32_family.FILES[ling32_family.VISION_FILE][0] - (pv.with_name(pv.name + ".part").stat().st_size if pv.with_name(pv.name + ".part").is_file() else 0)) / 1e9
|
||||
args_fit, adv = ling32_engine_args(a, vram_gib, ram_gib, unified, ctx, vision, vision_device, mtp=mtp_plan, backend=backend)
|
||||
args_fit, adv = ling32_engine_args(a, vram_gib, ram_gib, unified, ctx, vision, plan_vision_device, mtp=mtp_plan, backend=backend, card_gib=(gpu or {}).get("vram_gb"))
|
||||
say()
|
||||
p = adv["plan"]
|
||||
if backend == "metal": # a Mac keeps the whole model in one memory pool, no tiers: no hard minimum, a clear warning below the recommendation
|
||||
@@ -11024,7 +11058,7 @@ def install_ling32_air(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adop
|
||||
if WIN and unified and engine_program.is_file(): # a Windows integrated GPU (Strix Halo): the engine probes how much one process can allocate for the GPU (a few seconds), the plan follows it
|
||||
cap = ling32_fit.probe_cap(engine_program)
|
||||
if cap:
|
||||
args_fit, adv = ling32_engine_args(a, None, ram_gib, True, ctx, vision, vision_device, gpu_cap_gib=cap, mtp=mtp_plan, backend=backend)
|
||||
args_fit, adv = ling32_engine_args(a, None, ram_gib, True, ctx, vision, plan_vision_device, gpu_cap_gib=cap, mtp=mtp_plan, backend=backend)
|
||||
p = adv["plan"]
|
||||
ok(f"Windows integrated GPU: a process can allocate {cap:.1f} GiB for the GPU: tier {adv['tier']}, {p['vram_gb']:.1f} GB in the card part, {p['ram_gb']:.1f} GB in RAM, {p['ssd_gb']:.1f} GB read from the SSD")
|
||||
for w in adv["warnings"]:
|
||||
@@ -11054,8 +11088,11 @@ def install_ling32_air(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adop
|
||||
if vision_device in ("gpu", "cpu"):
|
||||
args += ["--vision-device", vision_device]
|
||||
planned = ((adv.get("plan") or {}).get("vision") or {}).get("device")
|
||||
args = ling32_family.with_pixel_cap(args, backend, planned if vision_device == "auto" else vision_device) # the CPU encoder: a big picture is downscaled to about 1 MP
|
||||
if ling32_family.VISION_PIXELS_FLAG in args:
|
||||
device = None if (backend == "sycl" and vision_device == "auto") else (planned if vision_device == "auto" else vision_device) # Intel: serve decides from the engine's word
|
||||
# the CPU encoder: a big picture is downscaled to about 1 MP. Written here only for a CPU encoder the plan or the person chose (a card under 24 GiB, --vision cpu): for a backend whose engine may say
|
||||
# `vision=gpu` (Intel: its GPU encoder; Metal) serve decides at every start from the engine's own `--info --kv` word, so the cap is lifted without a new setup
|
||||
args = ling32_family.with_pixel_cap(args, "", device)
|
||||
if ling32_family.VISION_PIXELS_FLAG in args or ling32_family.uses_cpu_encoder(backend, args, device):
|
||||
say(" " + ling32_family.CPU_ENCODER_NOTE)
|
||||
ok("pictures: " + (f"on ({vis_path.name})" if vis_path is not None else "off"))
|
||||
mtp_path = None
|
||||
@@ -12491,6 +12528,39 @@ def mac_ling32_setup(a) -> int:
|
||||
return install_ling32_air(a, a.family or ling32_family.FAMILY, gpu, False, False, None, False, a.port or 8080, ram, None)
|
||||
|
||||
|
||||
def fetch_gguf_shards(a, family: str, fam: dict, model: str, shards: list, models_dir: Path) -> None:
|
||||
"""Step 5 of an install of a GGUF model (Qwen, Swift, Coder, Gyro, Unsloth): download the shards that are not on the disk yet, each into `shards`' own place, with the finish mark of a
|
||||
download that completed (done() / mark()), from the pinned sources (Hugging Face at the pinned revision, or ModelScope with its own hashes); the original's shard 2, the same file for all its
|
||||
sizes and the Coder, is linked from a size that is already here. Used by main() (NVIDIA / AMD) and by intel_control_setup() (an Intel Arc card). `a.models_dir` is the folder of the sizes."""
|
||||
missing = [s.name for s in shards if not (s.exists() and done(s))]
|
||||
if missing: # #495: files downloaded by hand go here, or --gguf-dir
|
||||
say(f" The model files go in {models_dir}")
|
||||
say(f" Files you already have: put them here with their original names ({', '.join(missing)}), or use "
|
||||
"--gguf-dir <their folder>.")
|
||||
if model_source() == "modelscope":
|
||||
say(f" Downloading from ModelScope ({ms_endpoint()}); --source huggingface downloads from Hugging Face")
|
||||
warn("ModelScope serves the repositories' current files, not the pinned revisions: each file is checked "
|
||||
"against the SHA-256 ModelScope itself publishes (self-attested); the MTP tensors against the "
|
||||
"pinned checkpoint's own hashes")
|
||||
elif hf_endpoint() != HF_DEFAULT:
|
||||
say(f" Downloading from {hf_endpoint()} (HF_ENDPOINT)")
|
||||
for s in shards:
|
||||
if s.exists() and done(s):
|
||||
ok(f"{s.name} already downloaded")
|
||||
continue
|
||||
# the original's shard 2 is the same file for all its sizes and the Coder: reuse one that is already here
|
||||
other = [p for p in Path(a.models_dir).glob("*/Qwen3.8-Flash-Next-GSQ-RCO-*-00002-of-00002.gguf") if done(p)]
|
||||
if family in ("qwen", "coder") and s.name.endswith("00002-of-00002.gguf") and other and not s.exists():
|
||||
try:
|
||||
os.link(other[0], s)
|
||||
mark(s)
|
||||
ok(f"{s.name} shared with {other[0].parent.name} (identical file)")
|
||||
continue
|
||||
except OSError:
|
||||
pass
|
||||
download(model_hf(fam, model) + s.name, s)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try: # the engine programs setup runs start no debugger on a user's machine (strata_control/childenv.py)
|
||||
from strata_control.childenv import quiet_crash_env
|
||||
@@ -12658,6 +12728,8 @@ def main() -> int:
|
||||
"B = hot ones in video memory and the rest in RAM, C = the rest read from the SSD (slow)")
|
||||
ap.add_argument("--vram-budget-gib", type=float, metavar="N", help="Ling-3.2-Air only: use at most N GiB of the card (default: what is free)")
|
||||
ap.add_argument("--ram-budget-gib", type=float, metavar="N", help="Ling-3.2-Air only: let the engine hold at most N GiB of RAM (default: the available RAM less 6 GiB)")
|
||||
ap.add_argument("--expert-skip", choices=("off", "medium"), default=None,
|
||||
help="Ling-3.2-Air only: medium = faster, slightly less exact (about 1 word in 60 differs); offered for an NVIDIA card of the 24 GB class on Linux when the plan streams experts. Off unless asked")
|
||||
ap.add_argument("--turbo-ssd", action="store_true",
|
||||
help="Ling-3.2-Air only: faster, may change answers. In tier C the engine skips a cold expert read from the SSD once the experts in memory cover enough of the "
|
||||
"routing weight. Off unless you ask")
|
||||
@@ -13512,33 +13584,7 @@ def main() -> int:
|
||||
warn("these packs are on Hugging Face only: downloading them from " + hf_endpoint())
|
||||
ready_fetch(model, models_dir)
|
||||
elif not a.gguf_dir:
|
||||
missing = [s.name for s in shards if not (s.exists() and done(s))]
|
||||
if missing: # #495: files downloaded by hand go here, or --gguf-dir
|
||||
say(f" The model files go in {models_dir}")
|
||||
say(f" Files you already have: put them here with their original names ({', '.join(missing)}), or use "
|
||||
"--gguf-dir <their folder>.")
|
||||
if model_source() == "modelscope":
|
||||
say(f" Downloading from ModelScope ({ms_endpoint()}); --source huggingface downloads from Hugging Face")
|
||||
warn("ModelScope serves the repositories' current files, not the pinned revisions: each file is checked "
|
||||
"against the SHA-256 ModelScope itself publishes (self-attested); the MTP tensors against the "
|
||||
"pinned checkpoint's own hashes")
|
||||
elif hf_endpoint() != HF_DEFAULT:
|
||||
say(f" Downloading from {hf_endpoint()} (HF_ENDPOINT)")
|
||||
for s in shards:
|
||||
if s.exists() and done(s):
|
||||
ok(f"{s.name} already downloaded")
|
||||
continue
|
||||
# the original's shard 2 is the same file for all its sizes and the Coder: reuse one that is already here
|
||||
other = [p for p in Path(a.models_dir).glob("*/Qwen3.8-Flash-Next-GSQ-RCO-*-00002-of-00002.gguf") if done(p)]
|
||||
if family in ("qwen", "coder") and s.name.endswith("00002-of-00002.gguf") and other and not s.exists():
|
||||
try:
|
||||
os.link(other[0], s)
|
||||
mark(s)
|
||||
ok(f"{s.name} shared with {other[0].parent.name} (identical file)")
|
||||
continue
|
||||
except OSError:
|
||||
pass
|
||||
download(model_hf(fam, model) + s.name, s)
|
||||
fetch_gguf_shards(a, family, fam, model, shards, models_dir)
|
||||
if not ready:
|
||||
check_shards(shards)
|
||||
for s in ([] if ready else shards): # the Unsloth files: pinned sizes and SHA-256
|
||||
|
||||
@@ -244,6 +244,7 @@ def run(a) -> int:
|
||||
needed = drafting.needs_pack(**want, **sig) or drafting.needs_tuned(**want, **sig) # (the tuned drafter is a download of its own, where the set and the card use it)
|
||||
tuned_needed = drafting.needs_tuned(**want, **sig)
|
||||
mtp_needed = drafting.needs_mtp(**want, **sig) or (not needed and want["mtp_here"] is False and drafting.normalize(want["mode"]) != "off"
|
||||
and not drafting.intel_plain(want["backend"], want["model_name"])
|
||||
and drafting.decide(**want, **sig).drafter == "off") # the start's safety net (runner.fetch_missing_drafter): never no drafter unless Off was chosen
|
||||
if a.drafting_command == "plan":
|
||||
decision = drafting.decide(**want, **sig)
|
||||
|
||||
@@ -13,6 +13,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SHARD = re.compile(r"^(?P<stem>.+)-(?P<i>\d{5})-of-(?P<n>\d{5})\.gguf$")
|
||||
@@ -136,7 +137,7 @@ def model_files(folder: Path, family: str, family_def: dict | None = None) -> li
|
||||
|
||||
def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path, context: int, kv: str | None, model_name: str, family_def: dict,
|
||||
log: Path, backend: str | None, vram_gb: float = 0.0, notes: list | None = None, pack_name: str | None = None,
|
||||
drafting: str | None = None) -> tuple[dict | None, list[str]]:
|
||||
drafting: str | None = None, platform: str | None = None, ram_gb: float = 0.0, pin_half: bool | None = None) -> tuple[dict | None, list[str]]:
|
||||
"""(config, problems): the config to write, or None with plain-words problems (what is missing). `pack_name`: the pack folder under
|
||||
packs/ (default the model's name in lower case; Gyro's is its tag, gyro-gyro-s)."""
|
||||
problems: list[str] = []
|
||||
@@ -254,6 +255,13 @@ def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path,
|
||||
if problems:
|
||||
return None, problems
|
||||
chunk = ling32_fit.chunk_for(vram_gb or None, backend=backend)
|
||||
if ram_gb and vram_gb and backend in (None, "cuda"): # NVIDIA: the plan decides the chunk like setup does (Windows, 8 GB class, tier C: 256)
|
||||
import sys as _sys
|
||||
try:
|
||||
got = ling32_fit.plan(float(vram_gb), float(ram_gb), ctx=context, backend=backend, card_gib=float(vram_gb), pin_half=(_sys.platform == "win32") if pin_half is None else pin_half)
|
||||
chunk = int(got["chunk"])
|
||||
except Exception: # noqa: BLE001 - no plan, the card class's chunk
|
||||
pass
|
||||
flags = ling32_family.ENGINE_FLAGS.get(backend or "cuda", ling32_family.ENGINE_FLAGS["cuda"]) if backend in ("hip", "metal", "sycl") else ling32_family.ENGINE_FLAGS["cuda"] # the tuned set of the backend (Intel and Metal: none; HIP: --graph)
|
||||
args = ["--model", str(native), "--ctx", str(context), "--chunk", str(chunk), *flags]
|
||||
cfg = {"exe": f"component:{ling32_family.COMPONENT}", "args": args, "cwd": str(src), "tokenizer": str(tokenizer),
|
||||
@@ -283,7 +291,6 @@ def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path,
|
||||
return None, problems
|
||||
if feed:
|
||||
# a model of another shape than the shipped profile's (48 x 512) gets a neutral profile in its pack folder, as setup.py does for it (the owner's line)
|
||||
import sys
|
||||
tools = str(Path(src) / "tools")
|
||||
if tools not in sys.path:
|
||||
sys.path.insert(0, tools)
|
||||
@@ -301,8 +308,21 @@ def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path,
|
||||
args += ["--expert-profile", str(profile), "--expert-cache", "64", "--prefill", "auto", "--spec", "2", "--suffix-draft", "0",
|
||||
"--max-context", str(context), "--mmap-experts"]
|
||||
else:
|
||||
args += ["--expert-profile", str(profile), "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5"]
|
||||
if mtp.exists() and not feed: # the Flash-Next draft layer is not a feed model's own (a feed entry carries no MTP head yet)
|
||||
win_sycl = backend == "sycl" and str(platform or sys.platform).startswith("win")
|
||||
if win_sycl:
|
||||
# Windows Intel (QFN-B70's tested flags, literally): --prefill 4096 (auto was not tested on the B70), --spec 2 written here (the sysfs rule of strata_control/intel_spec.py cannot fire on
|
||||
# Windows), no --spec-min-p (no draft head to filter, no data), no --mtp, the Coder pack its own profile and every other pack the SYCL one (the shared expert-profile.bin was not used)
|
||||
prof = profile if family_def.get("profile") else Path(src) / "data" / "expert-profile-sycl.bin"
|
||||
if not prof.exists():
|
||||
return None, [f"the expert profile {prof} is missing"]
|
||||
from strata_control import intel_app
|
||||
args += ["--expert-profile", str(prof), "--expert-cache", "auto", "--prefill", "4096", "--spec", "2"]
|
||||
from strata_control import drafting as _drafting
|
||||
if not intel_app.QWEN_SYCL_WINDOWS_PACKS.get(str(model), True) and (_drafting.INTEL_PLAIN_BY_DEFAULT or _drafting.normalize(drafting) == "off"):
|
||||
args += ["--suffix-draft", "0"] # IQ2_XS / IQ3_S: plain decode (a 2-token window with the suffix drafter off; the engine needs T >= 2 for a native pack), when it is the default or Off was chosen
|
||||
else:
|
||||
args += ["--expert-profile", str(profile), "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5"]
|
||||
if mtp.exists() and not feed and not win_sycl: # the Flash-Next draft layer is not a feed model's own (a feed entry carries no MTP head yet)
|
||||
args += ["--mtp", str(mtp)]
|
||||
args += ["--max-context", str(context), "--kv", kv or ("int8" if context > 8192 else "fp16")]
|
||||
if backend == "sycl":
|
||||
|
||||
@@ -401,7 +401,7 @@ class Ctx:
|
||||
from serve.server import engine_args
|
||||
import contextlib
|
||||
import io
|
||||
d = derive_config(apply_choices(cfg, s), s, bool_flags=tune_knobs.BOOL_FLAGS, gpus=cards_for_launch(s, self.catalog, base=cfg))
|
||||
d = derive_config(apply_choices(cfg, s), s, bool_flags=tune_knobs.BOOL_FLAGS, gpus=cards_for_launch(s, self.catalog, base=cfg), expert_skip_ok=S.expert_skip_applies(s, self.catalog.computer()))
|
||||
if s.parallel:
|
||||
d["parallel"] = s.parallel
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
|
||||
@@ -163,6 +163,9 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser]
|
||||
g.add_argument("--turbo-ssd", action="store_true",
|
||||
help="Ling-3.2-Air tier C only: faster, may change answers. The engine skips a cold expert read from the SSD once the experts in memory cover enough of the "
|
||||
"routing weight. Off unless you ask")
|
||||
g.add_argument("--expert-skip", choices=("off", "medium"), metavar="LEVEL",
|
||||
help="Ling-3.2-Air only: medium = faster, slightly less exact (about 1 word in 60 differs): the engine leaves out an expert that carries little of a token's routing weight. "
|
||||
"Offered for an NVIDIA card of the 24 GB class (3090, 4090) on Linux when the plan streams experts (tier B or C). Off unless you ask")
|
||||
g.add_argument("--cpu-coexec", type=_parallel, metavar="N", help="Ling-3.2-Air only: N CPU threads work on the experts that are not on the card (answers stay identical; off unless you ask)")
|
||||
g.add_argument("--speed", metavar="WORD", help=argparse.SUPPRESS) # DeepSeek (no longer run): accepted, answered in plain words
|
||||
g.add_argument("--full-quality", action="store_true", help=argparse.SUPPRESS) # DeepSeek (no longer run): accepted, answered in plain words
|
||||
@@ -371,6 +374,8 @@ def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSet
|
||||
s.ram_budget = a.ram_budget_gib
|
||||
if getattr(a, "turbo_ssd", False):
|
||||
s.turbo_ssd = True
|
||||
if getattr(a, "expert_skip", None):
|
||||
s.expert_skip = a.expert_skip
|
||||
if getattr(a, "cpu_coexec", None):
|
||||
s.extra = {**s.extra, "--cpu-coexec": str(a.cpu_coexec)}
|
||||
if a.gpu and getattr(a, "gpu_roles", None):
|
||||
|
||||
@@ -769,7 +769,7 @@ def _pairs(argv: list[str]) -> dict[str, str]:
|
||||
|
||||
|
||||
def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str], log: str | None = None, gpus: "list[int] | dict | None" = None,
|
||||
prev: dict | None = None, defaults: dict | None = None) -> dict:
|
||||
prev: dict | None = None, defaults: dict | None = None, expert_skip_ok: bool = False) -> dict:
|
||||
"""The private run config of this launch: the installed one plus the choices that are not setup's (host, port, key, cards, advanced).
|
||||
`prev` is the config this launch wrote last time: its calibrated values, hand edits and the values the Settings view
|
||||
saved (serve/runconfig.py, carry_settings) are kept (strata_control/arg_layers.py: explicit launch values, then
|
||||
@@ -857,6 +857,14 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str]
|
||||
cfg["thinking"] = s.thinking
|
||||
mine = ling32_fit.tier_args(tier=s.tier or "auto", vram_budget_gib=s.vram_budget or 0.0, ram_budget_gib=s.ram_budget or 0.0, turbo_ssd=bool(s.turbo_ssd))
|
||||
extra = {**extra, **{k: (v if v else "on") for k, v in _pairs(mine).items() if k not in extra}}
|
||||
if s.expert_skip == "medium" and expert_skip_ok and "--skip-tau" not in extra: # the expert skip: only where it is offered (ling32_fit.expert_skip_applies), written only when the person asked
|
||||
extra["--skip-tau"] = f"{ling32_fit.SKIP_TAU_MEDIUM:g}"
|
||||
elif s.expert_skip == "off" and isinstance(cfg.get("args"), list): # turned off: nothing is written, an earlier value goes
|
||||
cargs0 = [str(a) for a in cfg["args"]]
|
||||
while "--skip-tau" in cargs0:
|
||||
at = cargs0.index("--skip-tau")
|
||||
del cargs0[at:at + (2 if at + 1 < len(cargs0) and not cargs0[at + 1].startswith("--") else 1)]
|
||||
cfg["args"] = cargs0
|
||||
cfg.pop("mtp", None)
|
||||
from strata_control import ling32_family
|
||||
if s.mtp == "off": # the MTP sidecar (strata_control/ling32_family.py): off drops the config keys serve makes the engine flags from
|
||||
@@ -1481,13 +1489,15 @@ class Runner:
|
||||
args += ["--drafter", "off"]
|
||||
if self.is_inkling() and s.parallel and int(s.parallel) > 1:
|
||||
args += ["--parallel", str(int(s.parallel))] # setup plans the experts in graphics memory with room for these slots
|
||||
if self.is_native_strata_family() and (not WINDOWS or self.is_ling32()) and sys.platform != "darwin": # (Windows: Ling-3.2-Air only; the Inkling / Hy4 Intel engines are Linux packages)
|
||||
if self.is_native_strata_family() and (not WINDOWS or self.intel_route_here()) and sys.platform != "darwin": # (Windows: the families with a Windows Intel engine, intel_app.route_here)
|
||||
try:
|
||||
from strata_control import engine_component
|
||||
if engine_component.detect_backend()[0] == "sycl":
|
||||
args += ["--backend", "sycl"] # #6691: route Inkling-2-Mini & Hy4-Flash through setup.py's Intel SYCL control path
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
elif self.intel_chosen() and self.intel_downloads(): # a GGUF model for an Intel Arc card whose files are not here: setup's Intel path downloads, prepares and writes the settings (intel_control_setup)
|
||||
args += ["--backend", "sycl"]
|
||||
if fam in ("qwen", "coder"):
|
||||
args += ["--experimental-speed-projection", "off"]
|
||||
if s.draft_vocab and fam in modelstate.HELPER_FAMILIES:
|
||||
@@ -1833,7 +1843,7 @@ class Runner:
|
||||
adopted = self.adopt_prepared_files("no Mac model installer in this Terminal")
|
||||
if adopted is not None:
|
||||
return adopted
|
||||
if self.intel_chosen():
|
||||
if self.intel_chosen() and not self.intel_downloads():
|
||||
adopted = self.adopt_prepared_files("", chosen=True)
|
||||
if adopted is not None:
|
||||
return adopted
|
||||
@@ -1977,10 +1987,42 @@ class Runner:
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
def intel_route_here(self) -> bool:
|
||||
"""Does this model's Intel Arc route run on this PC (strata_control/intel_app.py route_here: Linux every family and pack, Windows the families with a gated engine and their gated packs). Never raises."""
|
||||
try:
|
||||
from strata_control import intel_app
|
||||
s = self.s
|
||||
fd = self.catalog.tables()[1].get(s.family or "", {})
|
||||
kind = intel_app.family_kind({"ling32": self.is_ling32(), "inkling": self.is_inkling(), "hy4": self.is_hy4()} if self.is_native_strata_family() else fd)
|
||||
return bool(intel_app.route_here(kind, model=str(s.model) if kind == "qwen" else None, family=str(s.family) if kind == "qwen" else None))
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
def intel_downloads(self) -> bool:
|
||||
"""An Intel Arc launch of a GGUF model whose files are not on this computer and that Strata downloads there (intel_app.can_download): the installer runs (setup.py --backend sycl) instead of the prepared-files path."""
|
||||
try:
|
||||
from strata_cli.launch import adopt
|
||||
from strata_control import intel_app
|
||||
s, cat = self.s, self.catalog
|
||||
if s.model_path or s.custom_id or s.custom_label: # the person's own files
|
||||
return False
|
||||
_models, families, _ctx, _src = cat.tables()
|
||||
fam = families.get(s.family or "", {})
|
||||
if not intel_app.can_download(s.family or "", str(s.model), fam):
|
||||
return False
|
||||
data_dir = Path(s.data_dir) if s.data_dir else cat.data_dir()
|
||||
model_dir = data_dir / "models" / (fam.get("tag", "") + str(s.model))
|
||||
files = adopt.model_files(model_dir, s.family or "", fam) if fam.get("feed") else adopt.find_shards(model_dir)
|
||||
return not files
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
def intel_chosen(self) -> bool:
|
||||
"""The engine for this launch is the Intel Arc one (chosen with --backend intel, saved, or the only make here), and the model is one
|
||||
the built-in downloader sets up for NVIDIA and AMD only: Strata prepares the model files itself instead (adopt_prepared_files)."""
|
||||
if self.is_native_strata_family() or sys.platform == "darwin" or WINDOWS:
|
||||
if self.is_native_strata_family() or sys.platform == "darwin":
|
||||
return False
|
||||
if WINDOWS and not self.intel_route_here(): # Windows: only the Qwen packs that were gated on a Windows Arc (intel_app.QWEN_SYCL_WINDOWS_PACKS)
|
||||
return False
|
||||
try:
|
||||
from strata_control import engine_component
|
||||
@@ -2069,7 +2111,7 @@ class Runner:
|
||||
context=s.context or 32768, kv=s.kv, model_name=(custom_alias(s) if s.custom_id else f"{fam.get('name', s.family)}-{s.model.lower()}"), family_def=fam,
|
||||
log=cat.root / f"strata-{tag}.log", backend=backend,
|
||||
vram_gb=float(cat.computer().main_vram_gb or 0), notes=self.notices, pack_name=tag.lower(),
|
||||
drafting=s.drafting)
|
||||
drafting=s.drafting, ram_gb=float(cat.computer().ram_gb or 0))
|
||||
if cfg is None:
|
||||
if backend == "sycl":
|
||||
raise LaunchError("Strata cannot start this model on the Intel Arc card yet: " + "; ".join(problems) + ".",
|
||||
@@ -2402,7 +2444,7 @@ class Runner:
|
||||
self.emit("config", note, None, level="warn")
|
||||
cfg = derive_config(base, self.s, bool_flags=tune_knobs.BOOL_FLAGS,
|
||||
log=str(launch_dir() / f"{self.name}.engine.log"), gpus=cards_for_launch(self.s, self.catalog, base=base),
|
||||
prev=previous, defaults=defaults)
|
||||
prev=previous, defaults=defaults, expert_skip_ok=S.expert_skip_applies(self.s, self.catalog.computer()))
|
||||
if self.is_inkling(): # a --kv the Inkling engine does not take is said, never dropped quietly
|
||||
kv_note = S.inkling_kv_note(self.s.kv, cfg.get("backend"))
|
||||
if kv_note:
|
||||
@@ -3395,7 +3437,7 @@ class Runner:
|
||||
try:
|
||||
cfg = read_config(base_path)
|
||||
want = self.drafting_inputs(cfg)
|
||||
if not cfg or drafting.normalize(want["mode"]) == "off" or want.get("mtp_here") is not False or self.feed_without_draft_layer() \
|
||||
if not cfg or drafting.normalize(want["mode"]) == "off" or drafting.intel_plain(want["backend"], want["model_name"]) or want.get("mtp_here") is not False or self.feed_without_draft_layer() \
|
||||
or self.s.family not in modelstate.HELPER_FAMILIES or drafting.decide(**want, **self.drafting_signals(cfg, want)).drafter != "off":
|
||||
return base_path
|
||||
except Exception: # noqa: BLE001 - a question asked early is never a reason to stop a launch
|
||||
@@ -3446,8 +3488,8 @@ class Runner:
|
||||
try:
|
||||
cfg = read_config(base_path)
|
||||
want = self.drafting_inputs(cfg)
|
||||
if drafting.normalize(want["mode"]) == "off" or drafting.decide(**want, **self.drafting_signals(cfg, want)).drafter != "off":
|
||||
return # Off was chosen, or another drafter runs: nothing to say
|
||||
if drafting.normalize(want["mode"]) == "off" or drafting.intel_plain(want["backend"], want["model_name"]) or drafting.decide(**want, **self.drafting_signals(cfg, want)).drafter != "off":
|
||||
return # Off was chosen (or is what Auto means on this Intel pack), or another drafter runs: nothing to say
|
||||
except Exception: # noqa: BLE001 - a note is never a reason to stop a launch
|
||||
return
|
||||
self._mtp_offline_said = True
|
||||
|
||||
@@ -12,6 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from dataclasses import asdict, dataclass, field, fields
|
||||
from typing import Any
|
||||
@@ -178,6 +179,7 @@ class LaunchSettings:
|
||||
tier: str | None = None # Ling-3.2-Air: auto | A | B | C (None = auto: Strata chooses from video memory, RAM and disk)
|
||||
vram_budget: float | None = None # Ling-3.2-Air: GiB of the card the engine may use (None = what is free)
|
||||
ram_budget: float | None = None # Ling-3.2-Air: GiB of RAM the engine may hold (None = the available RAM less 6 GiB)
|
||||
expert_skip: str | None = None # Ling-3.2-Air expert skip: None = as installed (off), "off", "medium" (--skip-tau 0.05: faster, slightly less exact; the NVIDIA 24 GB class in tier B / C on Linux only)
|
||||
turbo_ssd: bool = False # Ling-3.2-Air tier C: skip cold experts once memory covers enough of the routing weight: faster, may change answers (off unless asked)
|
||||
mtp: str | None = None # None = as installed (draft layer on); "off" starts without it (less graphics memory and RAM, slower); "on" overrides an installed "off"
|
||||
tune: str = "skip" # quick | thorough | skip
|
||||
@@ -417,6 +419,22 @@ def old_nvidia_cards(cards) -> list[dict]:
|
||||
return out
|
||||
|
||||
|
||||
def expert_skip_applies(s: LaunchSettings, comp) -> bool:
|
||||
"""Is the Ling expert skip offered on this computer for these settings (ling32_fit.expert_skip_applies: NVIDIA, Linux, the 24 GB class, a plan in tier B or C). Never raises."""
|
||||
try:
|
||||
if s.family != "ling-3.2-air" or str(getattr(comp, "engine_vendor", "") or "").lower() != "nvidia":
|
||||
return False
|
||||
from strata_control import ling32_family, ling32_fit
|
||||
vram_gb = getattr(comp, "main_vram_gb", None) or None
|
||||
mtp_mode = ling32_fit.mtp_mode(s.mtp, default_on=ling32_family.DEFAULT_MTP, vram_gib=vram_gb, unified=False)
|
||||
adv = ling32_fit.advise(vram_gb, float(getattr(comp, "ram_gb", 0.0) or 0.0), unified=False, tier=s.tier or "auto", vram_budget_gib=s.vram_budget or 0.0, ram_budget_gib=s.ram_budget or 0.0,
|
||||
turbo_ssd=bool(s.turbo_ssd), ctx=s.context, vision=s.vision not in ("off", "no"), vision_device=s.vision if s.vision in ("gpu", "cpu") else "auto",
|
||||
mtp="auto" if mtp_mode == "auto" else mtp_mode == "on", backend="cuda", card_gib=vram_gb)
|
||||
return ling32_fit.expert_skip_applies("cuda", vram_gb, adv.get("tier"))
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def check_ling32(s: LaunchSettings, *, vram_gb: float | None, ram_gb: float | None, disk_free_gb: float | None = None, unified: bool = False, vendor: str | None = None,
|
||||
cards=None) -> list[Notice]:
|
||||
"""Ling-3.2-Air: what the memory tier will be on this computer and what the person chose for it (strata_control/ling32_fit.py, the engine's planner): the tier and its
|
||||
@@ -436,7 +454,7 @@ def check_ling32(s: LaunchSettings, *, vram_gb: float | None, ram_gb: float | No
|
||||
engine_backend = {"amd": "hip", "intel": "sycl" if ling32_family.sycl_available() else "cuda", "apple": "metal"}.get(str(vendor or "").lower(), "cuda") # the chunk of the card class follows the backend (Intel only once its engine ships: the notice below says it)
|
||||
adv = ling32_fit.advise(vram_gb, float(ram_gb or 0.0), unified=unified, disk_free_gb=disk_free_gb, tier=s.tier or "auto", vram_budget_gib=s.vram_budget or 0.0,
|
||||
ram_budget_gib=s.ram_budget or 0.0, turbo_ssd=bool(s.turbo_ssd), ctx=s.context, vision=s.vision not in ("off", "no"),
|
||||
vision_device=s.vision if s.vision in ("gpu", "cpu") else "auto", mtp="auto" if mtp_mode == "auto" else mtp_mode == "on", backend=engine_backend)
|
||||
vision_device=s.vision if s.vision in ("gpu", "cpu") else "auto", mtp="auto" if mtp_mode == "auto" else mtp_mode == "on", backend=engine_backend, pin_half=sys.platform == "win32")
|
||||
except Exception: # noqa: BLE001 - a plan that cannot be worked out stays silent rather than wrong
|
||||
return out
|
||||
v = str(vendor or "").lower()
|
||||
@@ -473,6 +491,9 @@ def check_ling32(s: LaunchSettings, *, vram_gb: float | None, ram_gb: float | No
|
||||
out.append(Notice("warn", ling32_fit.MTP_SMALL_CARD_NOTE, ""))
|
||||
from strata_control import ling32_family
|
||||
out.append(Notice("warn", f"MTP sidecar licence: {ling32_family.MTP_LICENSE['spdx']}. {ling32_family.MTP_LICENSE['attribution']}", ""))
|
||||
if s.expert_skip == "medium":
|
||||
out.append(Notice("warn", ling32_fit.EXPERT_SKIP_NOTE if ling32_fit.expert_skip_applies(engine_backend, vram_gb, adv["tier"]) else
|
||||
"--expert-skip changes nothing here: it is offered for an NVIDIA card of the 24 GB class (3090, 4090) on Linux when the plan streams experts (tier B or C).", ""))
|
||||
if s.turbo_ssd:
|
||||
out.append(Notice("warn", ling32_fit.TURBO_SSD_NOTE if adv["tier"] == "C" else "--turbo-ssd changes nothing here: it only acts in tier C and this computer plans another tier.",
|
||||
"Take the flag away to get exact answers again."))
|
||||
@@ -607,6 +628,8 @@ def flags_text(s: LaunchSettings, *, preset: str | None = None) -> str:
|
||||
parts.append(f"--ram-budget-gib {s.ram_budget:g}")
|
||||
if s.turbo_ssd:
|
||||
parts.append("--turbo-ssd")
|
||||
if s.expert_skip:
|
||||
parts.append(f"--expert-skip {s.expert_skip}")
|
||||
parts.append(f"--tune {s.tune}")
|
||||
if s.tune_allow_small:
|
||||
parts.append("--tune-allow-small")
|
||||
|
||||
@@ -1547,6 +1547,28 @@ def canonical_pack(args: list[Any] | None = None) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
#: Owner decision 2026-12-03 09:05: Qwen IQ2_XS and IQ3_S on an Intel Arc on Windows default to FAST mode (DFlash2, --spec 6), the same as Linux Arc, so this is False; plain decode stays available (below).
|
||||
#: Intel Arc (the SYCL engine), Qwen3.8-Flash-Next IQ2_XS and IQ3_S: True = Auto is NO drafter, the plain decode QFN-B70 gated on the B70. With DFlash2 (Auto's pick wherever the engine has it) the Windows run starts with
|
||||
#: `--spec 6` and the drafter (decode 77-114 tok/s, about twice plain, acceptance 90 %), which was not gated: speculation with this pack is not bit-equal to plain decode (near-tie flips from token 56 to 185 with spec 2).
|
||||
#: ONE switch: False (now) = Auto is DFlash2 on Intel (speed); True = plain decode by default (exact). The person can name a drafter or Off in Settings either way: with Off a Windows Intel IQ2_XS / IQ3_S install is written
|
||||
#: with `--suffix-draft 0` (strata_cli/launch/adopt.py), which is the plain decode (a 2-token window, no draft proposed).
|
||||
INTEL_PLAIN_BY_DEFAULT = False
|
||||
#: The platforms it applies to (sys.platform prefixes). Windows only for now: that is where the B70 gate measured it and where the app's Load put DFlash2 on without a gate. Linux Arc keeps its tuned
|
||||
#: DFlash2 default for IQ3_S (CLASS_DEFAULTS, tests/terminal/test_drafting_tuned.py); add "linux" here, and update those tests, if the owner wants the plain decode there too.
|
||||
INTEL_PLAIN_PLATFORMS = ("win",)
|
||||
INTEL_PLAIN_PACKS = re.compile(r"^qwen3\.8-flash-next-(iq2_xs|iq3_s)$")
|
||||
|
||||
|
||||
def _host_platform() -> str:
|
||||
return sys.platform
|
||||
|
||||
|
||||
def intel_plain(backend: str | None, model_name: str | None) -> bool:
|
||||
"""Does Auto mean no drafter for this model on this engine (INTEL_PLAIN_BY_DEFAULT): the SYCL engine, one of INTEL_PLAIN_PACKS, on a platform of INTEL_PLAIN_PLATFORMS."""
|
||||
return bool(INTEL_PLAIN_BY_DEFAULT and str(backend or "").strip().lower() == "sycl" and _host_platform().startswith(INTEL_PLAIN_PLATFORMS)
|
||||
and INTEL_PLAIN_PACKS.match(str(model_name or "").strip().lower()))
|
||||
|
||||
|
||||
def choice_of(mode: Any, *, model_name: str | None = None, family: str | None = None, backend: str | None = None, archs: Any = None,
|
||||
args: list[Any] | None = None, vram_mib: float | None = None, canonical: bool | None = None) -> str:
|
||||
"""The drafter the choice means for this model on this computer, before anything is looked up on disk: ``dflash2``, ``mtp`` or ``off``. Auto is DFlash2 wherever
|
||||
@@ -1558,6 +1580,8 @@ def choice_of(mode: Any, *, model_name: str | None = None, family: str | None =
|
||||
return "off"
|
||||
if asked == "mtp":
|
||||
return "mtp"
|
||||
if asked == "auto" and intel_plain(backend, model_name):
|
||||
return "off" # Intel Arc IQ2_XS / IQ3_S: the plain decode that was gated (INTEL_PLAIN_BY_DEFAULT)
|
||||
if asked == "auto" and str(backend or "").strip().lower() != "metal" and (canonical_pack(args) if canonical is None else canonical):
|
||||
return "mtp" # the canonical pack (the AVX-512 Q2_0): DFlash2 would end the start (#7090)
|
||||
entry = default_for(backend, model_name)
|
||||
@@ -1583,6 +1607,8 @@ def decide(mode: Any, *, klass: str = "other", model_name: str | None = None, fa
|
||||
asked = normalize(mode)
|
||||
if asked == "off":
|
||||
return Decision(asked, "off")
|
||||
if asked == "auto" and intel_plain(backend, model_name):
|
||||
return Decision(asked, "off") # no drafter, no note: it is what Auto means here
|
||||
want = choice_of(asked, model_name=model_name, family=family, backend=backend, archs=archs, args=args, vram_mib=vram_mib)
|
||||
have_mtp = mtp_here is not False
|
||||
# DFlash2 stands in for a missing MTP layer wherever it may run on this card: also where Auto picks the MTP for the card class (the 12 GB card with IQ3_S), so a
|
||||
|
||||
@@ -16,7 +16,7 @@ import sys
|
||||
|
||||
#: What the install says when an Arc card is chosen and the model's files are not on the computer (the Terminal's own sentence, "Intel cards do not
|
||||
#: download models yet", in the app's words: the picker's entry is "Use your own GGUF…").
|
||||
NO_DOWNLOAD = ("Strata can't download models for an Intel Arc card yet. Choose \"Use your own GGUF…\" and pick the folder that holds the model's "
|
||||
NO_DOWNLOAD = ("Strata can't download this model for an Intel Arc card on this computer yet. Choose \"Use your own GGUF…\" and pick the folder that holds the model's "
|
||||
".gguf files; Strata prepares them for this card.")
|
||||
|
||||
#: The families the run config can be written for (strata_cli/launch/adopt.py FAMILIES): the Qwen3.8-Flash-Next sizes, Swift, Coder, Gyro and Unsloth's sets.
|
||||
@@ -41,14 +41,98 @@ def model_files_in(folder, family: str, family_def: dict | None = None) -> list:
|
||||
return adopt.model_files(folder, family, family_def)
|
||||
|
||||
|
||||
def can_download(family: str, model: str | None = None, family_def: dict | None = None, platform: str | None = None) -> bool:
|
||||
"""Does Strata download this model's files for an Intel Arc card on this PC. Ling-3.2-Air, Inkling-2-Mini and Hy4-Flash download through their own installs (setup.py install_ling32_air / install_inkling2 /
|
||||
install_hy4_flash, the same steps as for NVIDIA and AMD) wherever their Arc route runs. The GGUF families (Qwen3.8-Flash-Next, Swift, Coder, Gyro, Unsloth) download from the pinned sources of setup.py
|
||||
(fetch_gguf_shards) where their Arc route runs for this pack: Linux every pack, Windows the gated ones (QWEN_SYCL_WINDOWS_PACKS, only the qwen and coder families); a model of the signed feed has no such
|
||||
source here and stays on "use your own files". Never raises."""
|
||||
try:
|
||||
fd = family_def or {}
|
||||
kind = ("ling32" if family == "ling-3.2-air" or fd.get("ling32") else "inkling" if family == "inkling-2-mini" or fd.get("inkling")
|
||||
else "hy4" if family == "hy4-flash" or fd.get("hy4") else "qwen")
|
||||
if kind != "qwen":
|
||||
return route_here(kind, platform)
|
||||
if fd.get("feed"):
|
||||
return False
|
||||
return route_here("qwen", platform, model, family)
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def supported_here(platform: str | None = None) -> bool:
|
||||
"""Intel Arc engines ship for Linux x86_64 only (no Windows or Mac package in the feed)."""
|
||||
"""The Intel Arc engines of the Qwen families ship for Linux x86_64 only (no Windows or Mac package in the feed)."""
|
||||
return (platform or sys.platform).startswith("linux")
|
||||
|
||||
|
||||
def arc_cards(root: str = "/sys/class/drm") -> list[dict]:
|
||||
"""The Intel Arc cards in this Linux computer, as the Terminal lists them (strata_cli/launch/catalog.py intel_arc_cards): vendor "intel", name,
|
||||
vram_gb (the card's own memory where it can be read, else the PCI id table's figure), usable True."""
|
||||
#: THE Windows Intel switches, one per model family (0.2.25 scope, owner / coordinator 2026-12-03): Ling-3.2-Air has its own (ling32_family.SYCL_ENGINE_SHIPPED); Inkling-2-Mini ships on the Windows B70 (INK-B70 gated
|
||||
#: f-ink-b70 e3b494577a on devcloud2: all five packs identical); Qwen3.8-Flash-Next waits for QFN-B70's B70 gate (flip when it passes); Hy4-Flash only if a gated Windows Intel engine exists. Linux is on for all.
|
||||
INKLING_SYCL_WINDOWS_SHIPPED = True
|
||||
QWEN_SYCL_WINDOWS_SHIPPED = True
|
||||
HY4_SYCL_WINDOWS_SHIPPED = False
|
||||
#: The Qwen packs that ship on Windows Intel, each with its drafting (QFN-B70's gates on the B70 with the shipping package, coordinator decision 2026-12-03): Coder IQ1_M is bit-identical to the first Windows build on
|
||||
#: 7 of 7 prompts with --spec 2 and with spec off, so it runs with --spec 2 and the suffix drafter on (True; 64 tok/s decode). IQ2_XS and IQ3_S are deterministic (45-51 and 39-45 tok/s) but --spec 2 with the drafter
|
||||
#: is not bit-equal to plain decode on them (near-tie flips from token 56 to 185), so they run plain: False = `--spec 2 --suffix-draft 0` (the engine refuses a native pack without a spec window, T >= 2; with the suffix drafter
|
||||
#: off a 2-token window is allocated, no draft is ever proposed and it decodes one token per step: the arm QFN-B70 measured as "spec off"). Q2_0 and IQ3_XXS stay off.
|
||||
QWEN_SYCL_WINDOWS_PACKS = {"IQ1_M": True, "IQ2_XS": False, "IQ3_S": False}
|
||||
|
||||
|
||||
#: The families whose packs QWEN_SYCL_WINDOWS_PACKS names: Qwen3.8-Flash-Next (IQ2_XS, IQ3_S) and its Coder (IQ1_M). Swift, Gyro and Unsloth have packs of the same names but were not gated.
|
||||
QWEN_SYCL_WINDOWS_FAMILIES = ("qwen", "coder")
|
||||
|
||||
|
||||
def route_here(kind: str, platform: str | None = None, model: str | None = None, family: str | None = None) -> bool:
|
||||
"""Can the Intel Arc route of this model family (`kind`: "ling32", "inkling", "hy4", "qwen") run on this PC: Linux yes; Windows by the family's switch; a Mac never. Never raises."""
|
||||
plat = platform or sys.platform
|
||||
if plat.startswith("linux"):
|
||||
return True
|
||||
if not plat.startswith("win"):
|
||||
return False
|
||||
try:
|
||||
if kind == "qwen" and model and (str(model) not in QWEN_SYCL_WINDOWS_PACKS or (family and str(family) not in QWEN_SYCL_WINDOWS_FAMILIES)): # Windows: the packs QFN-B70 gated, no others
|
||||
return False
|
||||
from strata_control import ling32_family
|
||||
return {"ling32": bool(ling32_family.sycl_available()), "inkling": bool(INKLING_SYCL_WINDOWS_SHIPPED), "hy4": bool(HY4_SYCL_WINDOWS_SHIPPED),
|
||||
"qwen": bool(QWEN_SYCL_WINDOWS_SHIPPED)}.get(kind, False)
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def cards_supported_here(platform: str | None = None) -> bool:
|
||||
"""Is an Intel Arc card part of this computer's hardware report: Linux (the SYCL engines), and Windows when at least one family's Windows Intel engine ships (route_here)."""
|
||||
plat = platform or sys.platform
|
||||
if plat.startswith("linux"):
|
||||
return True
|
||||
return any(route_here(k, plat) for k in ("ling32", "inkling", "hy4", "qwen"))
|
||||
|
||||
|
||||
def family_kind(md: dict | None) -> str:
|
||||
"""The route kind of a model-table entry (strata_mcp): "ling32", "inkling", "hy4" or "qwen" (every other family)."""
|
||||
md = md or {}
|
||||
return "ling32" if md.get("ling32") else "inkling" if md.get("inkling") else "hy4" if md.get("hy4") else "qwen"
|
||||
|
||||
|
||||
def windows_arc_cards(adapters=None) -> list[dict]:
|
||||
"""The Intel Arc cards (discrete, with their own memory) of this Windows PC, from the display adapters' registry entries (engine_component.windows_display_adapters): vendor 8086, "Arc"
|
||||
in the name, 4 GB of memory or more (an integrated Arc Graphics shares the system memory and is left out). The same list setup.py (ling32_intel_cards) uses to choose the SYCL engine.
|
||||
Never raises: a failed probe lists nothing. `adapters`: a mocked list (tests)."""
|
||||
try:
|
||||
if adapters is None:
|
||||
from strata_control import engine_component as ec
|
||||
adapters = ec.windows_display_adapters()
|
||||
cards = []
|
||||
for ad in adapters:
|
||||
if ad.get("vendor") == "8086" and "arc" in str(ad.get("name", "")).lower() and float(ad.get("vram_gb") or 0) >= 4.0:
|
||||
cards.append({"vendor": "intel", "name": str(ad["name"]), "vram_gb": float(ad["vram_gb"]), "usable": True, "index": len(cards)})
|
||||
return cards
|
||||
except Exception: # noqa: BLE001 - a probe that fails lists nothing
|
||||
return []
|
||||
|
||||
|
||||
def arc_cards(root: str = "/sys/class/drm", platform: str | None = None) -> list[dict]:
|
||||
"""The Intel Arc cards of this computer, as the Terminal lists them: Linux from the kernel's device list (strata_cli/launch/catalog.py intel_arc_cards), Windows from the display adapters
|
||||
(windows_arc_cards): vendor "intel", name, vram_gb (the card's own memory where it can be read, else the PCI id table's figure), usable True."""
|
||||
if str(platform or sys.platform).startswith("win"):
|
||||
return windows_arc_cards()
|
||||
from strata_cli.launch.catalog import intel_arc_cards
|
||||
return intel_arc_cards(root)
|
||||
|
||||
@@ -63,11 +147,12 @@ def engine_is_intel() -> bool:
|
||||
def cards_to_add(nvidia: list[dict], amd: list[dict], *, platform: str | None = None, cards=None, intel_engine=None) -> list[dict]:
|
||||
"""The Arc cards to put in the hardware report beside `nvidia` and `amd`: none when either make has a usable card (those PCs are exactly what they
|
||||
were), none off Linux, none when the engine is not the Intel one. Never raises: a probe that fails adds nothing."""
|
||||
if not supported_here(platform):
|
||||
if not cards_supported_here(platform):
|
||||
return []
|
||||
if any(g.get("usable") for g in nvidia) or any(g.get("usable") for g in amd):
|
||||
return []
|
||||
cards, intel_engine = cards or arc_cards, intel_engine or engine_is_intel
|
||||
plat = platform or sys.platform
|
||||
cards, intel_engine = cards or (windows_arc_cards if plat.startswith("win") else arc_cards), intel_engine or engine_is_intel
|
||||
try:
|
||||
found = cards()
|
||||
if not found or not intel_engine():
|
||||
|
||||
@@ -79,6 +79,8 @@ def plan(args: Any, user: Any, cards: list[dict], mtp_off: bool = False) -> tupl
|
||||
when nothing changed. `user` is the config's "user_args"; `cards` the cards the run uses (exactly two to qualify);
|
||||
`mtp_off` is the config's "mtp": false. `args` is not changed in place."""
|
||||
out = [str(a) for a in args] if isinstance(args, list) else []
|
||||
if len(cards) == 1 and is_battlemage(cards[0].get("driver", ""), cards[0].get("devid", "")) and "--mtp" not in out:
|
||||
return _single_card_no_draft(out, user)
|
||||
if not exactly_two_battlemage(cards) or mtp_off:
|
||||
return out, ""
|
||||
if "--mtp" not in out: # the pipeline needs the draft layer
|
||||
@@ -94,6 +96,23 @@ def plan(args: Any, user: Any, cards: list[dict], mtp_off: bool = False) -> tupl
|
||||
"\"--spec\" and its number in the config's \"user_args\".")
|
||||
|
||||
|
||||
def _single_card_no_draft(out: list[str], user: Any) -> tuple[list[str], str]:
|
||||
"""One Arc B-series card and no draft layer (the Intel engine has none: only the suffix drafter proposes tokens): --spec 4
|
||||
becomes --spec 2. A verify window costs about the same at 2 and at 6 tokens on a B70 (30 ms per window, Coder IQ1_M, every
|
||||
expert in VRAM), and without a draft layer the 3 extra draft slots are rarely right, so the 2-token window gives the
|
||||
most tokens per second: 50.4 against 42.7 tok/s (median of 7 prompts, 2 against 4; 2 won on every prompt). The
|
||||
answers of different window sizes can differ at a near-tie, as they already do between today's --spec 3 and 4."""
|
||||
if any(user_args.flag_of(g) == "--spec" for g in user_args.groups(user)):
|
||||
return out, ""
|
||||
i = _spec_group(out)
|
||||
if i < 0 or out[i] != SETUP_DEFAULT_SPEC:
|
||||
return out, ""
|
||||
out[i] = TWO_CARD_SPEC
|
||||
return out, ("One Arc B-series card without a draft layer: --spec 2 instead of 4. A verify window costs about the same at 2 and at "
|
||||
"6 tokens here and the extra draft slots are rarely right, so --spec 2 is faster (on a B70: 50 against 43 tok/s). "
|
||||
"To keep your own value, put \"--spec\" and its number in the config's \"user_args\".")
|
||||
|
||||
|
||||
def apply_for_launch(cfg: dict, sysfs: list[dict] | None = None) -> str:
|
||||
"""The launcher's run config: the cards in cfg["gpu"] (a list of two numbers after a layer split) looked up in sysfs, then
|
||||
`apply_to_config`. Nothing happens for a single card, another backend or a card list that sysfs cannot place."""
|
||||
|
||||
@@ -120,8 +120,16 @@ def with_pixel_cap(args, backend, planned_device: str | None = None, engine_visi
|
||||
#: Battlemage (bmg_g31 ahead of time) and Alchemist (acm_g10) and carries SPIR-V that any Intel GPU compiles at the first start (the first start is slower). Anything else: "unverified".
|
||||
SYCL_TESTED = ("b70",)
|
||||
SYCL_BUILT_FOR = ("a750", "a770", "a580", "a380", "b580", "b570", "b60", "b50")
|
||||
#: MTP on the Intel engine: ported, its accept kernel passes, the real sidecar was not run there yet. False: an Intel card starts without MTP unless `--mtp on` is given.
|
||||
SYCL_MTP_VERIFIED = False
|
||||
#: MTP on the Intel engine: verified (L32-SYCL's forced B70 gate, 2026-12-03: draft ids identical 30/30, 3.1 tokens per verify, slot-0 acceptance 0.90). True: Intel gets the same `--mtp-auto` plus the adaptive
|
||||
#: controller as every backend (it turns the draft on only where it pays: on the 32 GB-RAM devcloud2 box, tier C, a verify costs 233 ms against 72.7 ms plain, so it runs plain there; a B70 with the RAM for tier B can
|
||||
#: gain). False would start an Intel card without MTP unless `--mtp on` is given.
|
||||
SYCL_MTP_VERIFIED = True
|
||||
|
||||
|
||||
#: Where the Intel engine reads pictures, as the saved config says it: "auto" leaves the choice to the engine (its `--info --kv` `vision=gpu|cpu` word; the cap is lifted for gpu), "cpu" writes
|
||||
#: `--vision-device cpu`. The memory plan counts the reader on the processor either way. Set to "cpu" if the frozen package's planner and the launcher's plan disagree about the ~1600 MiB the GPU encoder takes
|
||||
#: (a B70 at chunk 2048 could then run out of VRAM on a big picture): one word.
|
||||
SYCL_VISION_DEVICE = "auto"
|
||||
|
||||
|
||||
def sycl_support(name) -> tuple[str, str]:
|
||||
|
||||
@@ -313,13 +313,28 @@ def describe(p: dict) -> str:
|
||||
|
||||
#: The card classes by NOMINAL size. A card reports a little less than its name (a 16 GB card 15.9 GiB, a 24 GB card 23.5, a 32 GB card 31.4, a 48 GB card 47.5) and the launcher passes the memory free
|
||||
#: after the desktop took its share, so each class starts well below its name: 14 GiB and up is a 16 GB card, 20 and up a 24 GB card, 27 and up a 32 GB card, 44 and up a 48 GB card. No card is made in between.
|
||||
CLASS_12_GIB = 11.5 # a real 12 GB card (3060 12G, 4070, 5070, 3080 12G: 11.6 to 12.0 GiB); the 11 GB cards (2080 Ti, 1080 Ti) and the 10 GB 3080 stay below it
|
||||
CLASS_16_GIB = 14.0
|
||||
CLASS_8_GIB = 7.5 # a real 8 GB card (3060 Ti, 3070, 4060: 7.6 to 8.0 GiB; the 6 GB cards stay below it). The 8 GB class takes 2048 since L32-SMALL's loader-reserve fix (f-ling32-int 03006f62ed; the 3060 Ti 8 GB, tier C on Linux: prefill 1.2 to 2.0x, no OOM)
|
||||
# Variant (c): with the engine's Windows planner headroom (STRATA_L32_WDDM_HEADROOM_MB 1536, f-ling32-int c966eccc17; WDDM over-commits cudaMalloc when the planner fills the card) the 12 GB class and up take
|
||||
# 2048 with the regrow on in tier C on Windows too (the owner's 5070: 577-622 s at 2048 without the headroom, about 100-117 s with it), so there is no Windows exception for them. The 8 GB class on Windows in tier C
|
||||
# keeps the small chunk (untested with the headroom; its loader reserve needs the regrow on). The plan is made with the engine's half-RAM pin cap on Windows (plan(..., pin_half=True), set by setup and the Terminal).
|
||||
WINDOWS_TIER_C_CHUNK = 256 # the 8 GB class on Windows in tier C: the chunk the launcher passes there. ONE constant
|
||||
CLASS_8_TOP_GIB = 9.0 # the 9 and 10 GB cards are between the measured classes and keep 256
|
||||
CLASS_24_GIB = 20.0
|
||||
CLASS_32_GIB = 27.0
|
||||
CLASS_48_GIB = 44.0
|
||||
|
||||
|
||||
def chunk_for(vram_gib: float | None, unified: bool = False, backend: str | None = None) -> int:
|
||||
def small_card_class(vram_gib: float | None, card_gib: float | None = None, backend: str | None = None) -> bool:
|
||||
"""A real 8 GB (CLASS_8_GIB up to CLASS_8_TOP_GIB) NVIDIA card, by the card's own size, else the memory free: the class whose chunk depends on the plan's tier on Windows (the 12 GB class and up take 2048 there too, with the engine's headroom)."""
|
||||
if str(backend or "").lower() in ("hip", "sycl", "metal"):
|
||||
return False
|
||||
size = max(float(vram_gib or 0.0), float(card_gib or 0.0))
|
||||
return CLASS_8_GIB <= size < CLASS_8_TOP_GIB
|
||||
|
||||
|
||||
def chunk_for(vram_gib: float | None, unified: bool = False, backend: str | None = None, card_gib: float | None = None) -> int:
|
||||
"""The prompt chunk the launcher starts the engine with, by the card's nominal class. The activation buffers scale with it (0.6 GiB at 256, about 2 GiB at 2048), and on a card that runs the pool
|
||||
layout every byte of them is a pool slot, so a card with little memory takes a small chunk: the 8 and 12 GB classes 256. But the layer-major span prefill runs sub-chunks of `--chunk` rows, so a
|
||||
small chunk multiplies the per-sub-chunk work and starves the tensor-core tiles: L32-CUDA measured on an RTX 5090 (tier B, plain decode unaffected) a 4062-token prompt 33 % slower and a
|
||||
@@ -327,15 +342,20 @@ def chunk_for(vram_gib: float | None, unified: bool = False, backend: str | None
|
||||
(1525 with 2048) for 1 to 3 % better decode. L32-CUDA then measured 1024 / 2048 / 4096 on an RTX 3090 and 4090 (24 GB, ctx 131072, tier B pool, PCIe 4.0 x16): 2048 reads a 16K prompt 19 % /
|
||||
24 % faster than 1024 and a 4K prompt 8 % faster for 0.7 / 2.6 % less decode, 4096 adds only 11 % more for 8 % less decode; a 120K prompt at 2048 ran through with no allocation failure (the lazy
|
||||
KV gives pool slots back as it grows). The pool regrow (f-ling32-int 9d71124e4c: on NVIDIA wherever the chunk is 2048 or more, it gives the bigger chunk's scratch back to the pool after the prefill) took away the decode cost: on an RTX 3090
|
||||
24 GB decode +3.4 % and prefill +13 / +15 % at 4K / 16K, on an RTX A4000 16 GB prefill +21 / +18 % with decode flat (L32-SMALL, greedy ids identical). So on NVIDIA: the 8 and 12 GB classes 256, the 16 GB
|
||||
24 GB decode +3.4 % and prefill +13 / +15 % at 4K / 16K, on an RTX A4000 16 GB prefill +21 / +18 % with decode flat (L32-SMALL, greedy ids identical). L32-SMALL then measured the 12 GB class with the regrow: an RTX 5070 on PCIe 5.0 prefill 4K / 16K / 32K 595 / 583 / 493 tok/s at chunk 256 against 915 / 1237 / 1134 at 2048, decode 38.8 against 39.4; the same card on
|
||||
PCIe 4.0 x4 (tier C) 187 / 335 / 350 against 284 / 669 / 777, decode 10.9 against 11.0. So on NVIDIA: the 6 GB and the 9 / 10 / 11 GB cards 256, the 8 GB class 2048 since L32-SMALL's loader-reserve fix (03006f62ed) and the 12 GB class 2048 (both 256 only on Windows in tier C, where the plan is made with the engine's half-RAM pin cap: the owner's 5070, 33,784 tokens, 83 tok/s at 256 against 54.5 at 2048, real SSD reads for the misses; on Linux the page cache serves them), the 12 GB class (11.5 GiB and up) and the 16 GB
|
||||
class and up the engine's own default 2048, from the 48 GB class the static layout keeps 1024 (a bigger chunk takes hot ranks). AMD keeps 1024 below its 32 GB class (no regrow on a Radeon yet), Intel Arc 1024 below 20 GiB."""
|
||||
if unified or not vram_gib:
|
||||
return 1024
|
||||
if card_gib and float(card_gib) > vram_gib: # the class is the card's own size where it is known (the memory free after the desktop took its share must not move a 12 GB card to the 11 GB class)
|
||||
vram_gib = float(card_gib)
|
||||
if str(backend or "").lower() == "hip" and vram_gib < CLASS_32_GIB: # AMD: the pool regrow (it gives the bigger chunk's scratch back after the prefill) is NVIDIA-only until it has run on a Radeon (L32-CUDA): the 16 and 24 GB classes keep 1024 (the 32 GB class is the engine's own default, the R9700 measurement)
|
||||
return 256 if vram_gib < CLASS_16_GIB else 1024
|
||||
if str(backend or "").lower() == "sycl" and vram_gib < CLASS_24_GIB: # Intel Arc (L32-SYCL): 1024 on the 8 to 16 GiB cards (A750, B580); the 20 to 44 GiB class takes 2048 like everywhere
|
||||
return 1024
|
||||
if vram_gib < CLASS_16_GIB:
|
||||
if CLASS_8_GIB <= vram_gib < CLASS_8_TOP_GIB:
|
||||
return 2048
|
||||
if vram_gib < CLASS_12_GIB:
|
||||
return 256
|
||||
return 2048 if vram_gib < CLASS_48_GIB else 1024
|
||||
|
||||
@@ -411,7 +431,7 @@ def mtp_status_line(spec: str | None, h2d_gbps: float | None, mode: str | None =
|
||||
|
||||
def plan(vram_gib: float | None, ram_gib: float, *, unified: bool = False, tier: str = "auto", vram_budget_gib: float = 0.0, ram_budget_gib: float = 0.0,
|
||||
turbo_ssd: bool = False, ctx: int | None = None, chunk: int | None = None, prefetch: bool = True, vision: bool = False, vision_device: str = "auto",
|
||||
gpu_cap_gib: float | None = None, ram_floor_gib: float | None = None, mtp: bool = False, spec_block: int | None = None, backend: str | None = None) -> dict:
|
||||
gpu_cap_gib: float | None = None, ram_floor_gib: float | None = None, mtp: bool = False, spec_block: int | None = None, backend: str | None = None, card_gib: float | None = None, pin_half: bool = False) -> dict:
|
||||
"""The tier plan for a PC. `mtp`: the sidecar is in the start (`mtp_bytes`: the file, its cache for `ctx`, the snapshot ring for `spec_block`, default 4), counted on the card in every tier. `gpu_cap_gib` (a Windows iGPU such as Strix Halo, L32-HIP's measurements; `probe_cap(engine)` gets it: `strata-ling32 --probe-cap`): the most one process can
|
||||
allocate for the GPU in all (about 63 GiB on a 96 GiB carve-out; what DXGI and hipMemGetInfo say is wrong). The rule of the engine's `--tier auto` on such a GPU: the card budget is
|
||||
`min(free, cap - 4 GiB)` (the engine keeps 4 GiB), the RAM tier is the available RAM less 8 GiB (the floor, `ram_floor_gib`) less 1.5 GiB, and the RAM tier is NOT counted against the
|
||||
@@ -422,7 +442,7 @@ def plan(vram_gib: float | None, ram_gib: float, *, unified: bool = False, tier:
|
||||
# `--mtp auto`: the engine loads the sidecar in tier A and in one memory pool, never in tier C, and in tier B only with a big card pool (4500 experts and more) over a link it measures at start (16 GB/s and more). The plan
|
||||
# counts it where it is certain (A, unified) and leaves it out otherwise (the common PCIe 4.0 card does not load it), with one note.
|
||||
args = dict(unified=unified, tier=tier, vram_budget_gib=vram_budget_gib, ram_budget_gib=ram_budget_gib, turbo_ssd=turbo_ssd, ctx=ctx, chunk=chunk, prefetch=prefetch,
|
||||
vision=vision, vision_device=vision_device, gpu_cap_gib=gpu_cap_gib, ram_floor_gib=ram_floor_gib, spec_block=spec_block, backend=backend)
|
||||
vision=vision, vision_device=vision_device, gpu_cap_gib=gpu_cap_gib, ram_floor_gib=ram_floor_gib, spec_block=spec_block, backend=backend, card_gib=card_gib)
|
||||
base = plan(vram_gib, ram_gib, mtp=False, **args)
|
||||
if base["ok"] and (base["mode"] == "A" or unified):
|
||||
got = plan(vram_gib, ram_gib, mtp=True, **args)
|
||||
@@ -451,7 +471,7 @@ def plan(vram_gib: float | None, ram_gib: float, *, unified: bool = False, tier:
|
||||
vision_vram=ev + eh + mv, vision_host=0)
|
||||
got["notes"].append("one memory pool: the part of the file that does not fit it is read from the SSD")
|
||||
else:
|
||||
ch = chunk or chunk_for(vram_gib, backend=backend)
|
||||
ch = chunk or chunk_for(vram_gib, backend=backend, card_gib=card_gib)
|
||||
ram_hw = float(ram_gib)
|
||||
if gpu_cap_gib:
|
||||
# the engine hands plan_tier these as HARDWARE (its own 600 MiB margin and 6 GiB headroom come on top): card = min(free, cap - 4 GiB), RAM = available - 8 GiB floor - 1.5 GiB
|
||||
@@ -465,6 +485,16 @@ def plan(vram_gib: float | None, ram_gib: float, *, unified: bool = False, tier:
|
||||
got = plan_tier(int((vram_gib or 0.0) * GIB), int(ram_hw * GIB), tier=engine_tier, vram_budget=int(vram_budget_gib * GIB), ram_budget=int(ram_budget_gib * GIB),
|
||||
turbo_ssd=turbo_ssd, ctx=n, chunk=ch, prefetch=prefetch, vision_vram=ev, vision_host=eh, pool="auto", kv_init=KV_INIT_ROWS,
|
||||
logits_rows=SERVE_LOGITS_ROWS, mtp_file_bytes=MTP_SIDECAR_BYTES if mtp else 0, mtp_expert_bytes=MTP_EXPERT_BYTES if mtp else 0, mtp_vram=mv)
|
||||
if chunk is None and ch == 2048 and pin_half and small_card_class(vram_gib, card_gib, backend) and plan_tier(
|
||||
int((vram_gib or 0.0) * GIB), int(min(ram_hw, float(ram_gib) / 2.0) * GIB), tier=engine_tier, vram_budget=int(vram_budget_gib * GIB), ram_budget=int(ram_budget_gib * GIB),
|
||||
turbo_ssd=turbo_ssd, ctx=n, chunk=ch, prefetch=prefetch, vision_vram=ev, vision_host=eh, pool="auto", kv_init=KV_INIT_ROWS,
|
||||
logits_rows=SERVE_LOGITS_ROWS, mtp_file_bytes=MTP_SIDECAR_BYTES if mtp else 0, mtp_expert_bytes=MTP_EXPERT_BYTES if mtp else 0, mtp_vram=mv)["mode"] == "C":
|
||||
# Windows (pin_half), the tier predicted with the engine's pin cap (half of the system RAM) is C: the small chunk; the plan itself keeps the real RAM (the chunk is the only change). The misses are real SSD reads there (NO_BUFFERING) and the larger scratch takes pool slots, so the hit rate costs I/O (the owner's 5070, tier C
|
||||
# on a 64 GB Windows PC, 33,784 tokens: 83 tok/s at 256, 54.5 at 2048). On Linux the page cache serves the misses and 2048 wins in tier C too (the 3060 Ti 8 GB, 62 GB RAM: 1.2 to 2.0x)
|
||||
ch = WINDOWS_TIER_C_CHUNK
|
||||
got = plan_tier(int((vram_gib or 0.0) * GIB), int(ram_hw * GIB), tier=engine_tier, vram_budget=int(vram_budget_gib * GIB), ram_budget=int(ram_budget_gib * GIB),
|
||||
turbo_ssd=turbo_ssd, ctx=n, chunk=ch, prefetch=prefetch, vision_vram=ev, vision_host=eh, pool="auto", kv_init=KV_INIT_ROWS,
|
||||
logits_rows=SERVE_LOGITS_ROWS, mtp_file_bytes=MTP_SIDECAR_BYTES if mtp else 0, mtp_expert_bytes=MTP_EXPERT_BYTES if mtp else 0, mtp_vram=mv)
|
||||
if gpu_cap_gib and not unified and got["ok"] and got["mode"] != "A":
|
||||
counted = got["vram_total_planned"] + got["ring_bytes"] # the card part and the ring / staging count against the cap; the RAM tier does not
|
||||
if counted > (gpu_cap_gib - IGPU_CAP_RESERVE_GIB) * GIB:
|
||||
@@ -485,12 +515,36 @@ def plan(vram_gib: float | None, ram_gib: float, *, unified: bool = False, tier:
|
||||
for big in [c for c in (top, 2048) if got["chunk"] < c <= top]: # the engine's own, else half of it: the largest that still keeps every expert on the card
|
||||
again = plan(vram_gib, ram_gib, unified=unified, tier=tier, vram_budget_gib=vram_budget_gib, ram_budget_gib=ram_budget_gib, turbo_ssd=turbo_ssd, ctx=ctx, chunk=big,
|
||||
prefetch=prefetch, vision=vision, vision_device=vision_device, gpu_cap_gib=gpu_cap_gib, ram_floor_gib=ram_floor_gib, mtp=mtp,
|
||||
spec_block=spec_block, backend=backend)
|
||||
spec_block=spec_block, backend=backend, card_gib=card_gib)
|
||||
if again["ok"] and again["mode"] == "A":
|
||||
return again
|
||||
return got
|
||||
|
||||
|
||||
#: Expert skip (the engine's `--skip-tau T`, f-ling32-int c966eccc17; env STRATA_L32_SKIP_TAU): at decode and speculative-verify rows only, a token's routed experts whose routing-weight share is below T are dropped (the top expert
|
||||
#: is always kept, the weights are rescaled). NOT exact. One level, "medium" = 0.05 (L32-CUDA, an RTX 3090 24 GB, PCIe 4.0, tier B, ctx 131072, plain decode: 0 / 0.03 / 0.05 / 0.08 = 53.0 / 53.5 / 58.0 / 70.8 tok/s;
|
||||
#: top-1 agreement with the unpruned run 100 / 98-100 / 97.5-98 %, mean KL 1e-4 / 1e-3 / 1.6e-2: medium is +9 to 10 % for about 1 word in 60 different on code). Off by default; the person turns it on.
|
||||
SKIP_TAU_MEDIUM = 0.05
|
||||
EXPERT_SKIP_WORDS = ("off", "medium")
|
||||
EXPERT_SKIP_PLATFORMS = ("linux",) # measured on Linux only; Windows, HIP, SYCL and Metal are not offered until they are measured
|
||||
EXPERT_SKIP_NOTE = "Faster, slightly less exact (about 1 word in 60 differs)."
|
||||
|
||||
|
||||
def expert_skip_applies(backend: str | None, card_gib: float | None, tier: str | None, platform: str | None = None) -> bool:
|
||||
"""Is the expert skip offered here: the NVIDIA CUDA engine on Linux, a card of the 24 GB class (CLASS_24_GIB up to CLASS_32_GIB: the 3090 and 4090), and a plan that streams experts (tier B or C; tier A gains nothing)."""
|
||||
import sys as _sys
|
||||
if str(backend or "cuda").lower() != "cuda" or not str(platform or _sys.platform).startswith(EXPERT_SKIP_PLATFORMS):
|
||||
return False
|
||||
return bool(card_gib and CLASS_24_GIB <= float(card_gib) < CLASS_32_GIB and tier in ("B", "C"))
|
||||
|
||||
|
||||
def skip_tau_args(word: str | None, backend: str | None, card_gib: float | None, tier: str | None, platform: str | None = None) -> list[str]:
|
||||
"""`--skip-tau 0.05` when the person chose "medium" and the expert skip is offered here, else nothing."""
|
||||
if str(word or "").lower() == "medium" and expert_skip_applies(backend, card_gib, tier, platform):
|
||||
return ["--skip-tau", f"{SKIP_TAU_MEDIUM:g}"]
|
||||
return []
|
||||
|
||||
|
||||
def tier_args(*, tier: str = "auto", vram_budget_gib: float = 0.0, ram_budget_gib: float = 0.0, turbo_ssd: bool = False, cpu_coexec: int = 0,
|
||||
map_experts: bool = False) -> list[str]:
|
||||
"""The engine flags for the person's choices, and nothing for the defaults (the engine plans by itself, with the rules above)."""
|
||||
@@ -556,12 +610,12 @@ def disk_gb(vision: bool = True) -> float:
|
||||
|
||||
def advise(vram_gib: float | None, ram_gib: float, *, unified: bool = False, disk_free_gb: float | None = None, ssd_gbps: float | None = None, tier: str = "auto",
|
||||
vram_budget_gib: float = 0.0, ram_budget_gib: float = 0.0, turbo_ssd: bool = False, ctx: int | None = None, vision: bool = True, vision_device: str = "auto", backend: str = "cuda",
|
||||
gpu_cap_gib: float | None = None, mtp: bool = False) -> dict:
|
||||
gpu_cap_gib: float | None = None, mtp: bool = False, card_gib: float | None = None, pin_half: bool = False) -> dict:
|
||||
"""What the launcher shows for a PC: the plan, the speed class, the engine flags the choices need and the warnings (never a refusal). `vision` (on by default, like the download
|
||||
set): the picture encoder's memory is in the plan (GPU encoder: 829 MiB of weights + activations on a card of 24 GiB or more; CPU encoder: about 1 GiB of host memory) and the
|
||||
Vision shard is in the disk need. Returns {"plan", "tier", "speed", "args", "warnings", "fits", "download_gb"}."""
|
||||
p = plan(vram_gib, ram_gib, unified=unified, tier=tier, vram_budget_gib=vram_budget_gib, ram_budget_gib=ram_budget_gib, turbo_ssd=turbo_ssd, ctx=ctx, vision=vision,
|
||||
vision_device=vision_device, gpu_cap_gib=gpu_cap_gib, mtp=mtp, backend=backend)
|
||||
vision_device=vision_device, gpu_cap_gib=gpu_cap_gib, mtp=mtp, backend=backend, card_gib=card_gib, pin_half=pin_half)
|
||||
warns: list[str] = list(p["notes"])
|
||||
if not p["ok"]:
|
||||
warns.append(p["error"])
|
||||
|
||||
@@ -28,6 +28,8 @@
|
||||
"131072",
|
||||
"--vision",
|
||||
"no",
|
||||
"--backend",
|
||||
"sycl",
|
||||
"--drafter",
|
||||
"dflash2",
|
||||
"--data-dir",
|
||||
|
||||
@@ -28,6 +28,8 @@
|
||||
"131072",
|
||||
"--vision",
|
||||
"no",
|
||||
"--backend",
|
||||
"sycl",
|
||||
"--drafter",
|
||||
"dflash2",
|
||||
"--data-dir",
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
{
|
||||
"nv_12gb_linux_tier_b_128gb": {
|
||||
"card_gib": 11.95,
|
||||
"launch": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
]
|
||||
},
|
||||
"platform": "linux",
|
||||
"ram_gib": 128.0,
|
||||
"setup": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
],
|
||||
"chunk": 2048,
|
||||
"regrow_off": false,
|
||||
"tier": "B"
|
||||
},
|
||||
"what": "12 GB card, Linux, 128 GB RAM"
|
||||
},
|
||||
"nv_12gb_linux_tier_c_64gb": {
|
||||
"card_gib": 11.95,
|
||||
"launch": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
]
|
||||
},
|
||||
"platform": "linux",
|
||||
"ram_gib": 64.0,
|
||||
"setup": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
],
|
||||
"chunk": 2048,
|
||||
"regrow_off": false,
|
||||
"tier": "C"
|
||||
},
|
||||
"what": "12 GB card, Linux, 64 GB RAM"
|
||||
},
|
||||
"nv_12gb_win_tier_b_192gb": {
|
||||
"card_gib": 11.95,
|
||||
"launch": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
]
|
||||
},
|
||||
"platform": "windows",
|
||||
"ram_gib": 192.0,
|
||||
"setup": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
],
|
||||
"chunk": 2048,
|
||||
"regrow_off": false,
|
||||
"tier": "B"
|
||||
},
|
||||
"what": "12 GB card, Windows, 192 GB RAM"
|
||||
},
|
||||
"nv_12gb_win_tier_c_64gb": {
|
||||
"card_gib": 11.95,
|
||||
"launch": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
]
|
||||
},
|
||||
"platform": "windows",
|
||||
"ram_gib": 64.0,
|
||||
"setup": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
],
|
||||
"chunk": 2048,
|
||||
"regrow_off": false,
|
||||
"tier": "C"
|
||||
},
|
||||
"what": "RTX 5070 / 3060 12 GB, Windows, 64 GB RAM (the owner's PC)"
|
||||
},
|
||||
"nv_16gb_linux_tier_c_64gb": {
|
||||
"card_gib": 15.9,
|
||||
"launch": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
]
|
||||
},
|
||||
"platform": "linux",
|
||||
"ram_gib": 64.0,
|
||||
"setup": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
],
|
||||
"chunk": 2048,
|
||||
"regrow_off": false,
|
||||
"tier": "C"
|
||||
},
|
||||
"what": "16 GB card, Linux, 64 GB RAM"
|
||||
},
|
||||
"nv_16gb_win_tier_c_64gb": {
|
||||
"card_gib": 15.9,
|
||||
"launch": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
]
|
||||
},
|
||||
"platform": "windows",
|
||||
"ram_gib": 64.0,
|
||||
"setup": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
],
|
||||
"chunk": 2048,
|
||||
"regrow_off": false,
|
||||
"tier": "C"
|
||||
},
|
||||
"what": "RTX 5070 Ti / A4000 16 GB, Windows, 64 GB RAM"
|
||||
},
|
||||
"nv_8gb_linux_tier_c_64gb": {
|
||||
"card_gib": 7.8,
|
||||
"launch": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
]
|
||||
},
|
||||
"platform": "linux",
|
||||
"ram_gib": 64.0,
|
||||
"setup": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"2048",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
],
|
||||
"chunk": 2048,
|
||||
"regrow_off": false,
|
||||
"tier": "C"
|
||||
},
|
||||
"what": "RTX 3060 Ti 8 GB, Linux, 64 GB RAM"
|
||||
},
|
||||
"nv_8gb_win_tier_c_64gb": {
|
||||
"card_gib": 7.8,
|
||||
"launch": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"256",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
]
|
||||
},
|
||||
"platform": "windows",
|
||||
"ram_gib": 64.0,
|
||||
"setup": {
|
||||
"args": [
|
||||
"--ctx",
|
||||
"32768",
|
||||
"--chunk",
|
||||
"256",
|
||||
"--tc",
|
||||
"16",
|
||||
"--tc-moe",
|
||||
"128",
|
||||
"--graph",
|
||||
"--mla-kernel",
|
||||
"simt"
|
||||
],
|
||||
"chunk": 256,
|
||||
"regrow_off": false,
|
||||
"tier": "C"
|
||||
},
|
||||
"what": "RTX 3060 Ti 8 GB, Windows, 64 GB RAM"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
"""The chunk and regrow rules of the Ling-3.2-Air launcher for the NVIDIA cards the machine-class snapshot does not cover (its Ling goldens only record what the host hands to Control, not the engine
|
||||
arguments the launcher's plan writes): for every row below, what setup writes (`setup.ling32_engine_args`: the app's install and the Terminal's setup) and what the Terminal's own config writer
|
||||
writes (`strata_cli.launch.adopt.plan`), as the engine's flags after `--ctx`. Own golden file (golden_ling32_chunk/chunk_rows.json); a change of the plan's chunk, of `--regrow` or of the tier
|
||||
the plan predicts shows up here as a diff.
|
||||
|
||||
Rows: the cards of the 8, 12 and 16 GB classes with the RAM that makes tier B or C, on Linux and on Windows (the engine's pin cap there is half of the system RAM).
|
||||
Nothing real is used: no GPU, no model file, no engine. Write the golden file after an intended change with STRATA_SNAPSHOT_UPDATE=1 and review the diff."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
GOLDEN = Path(__file__).resolve().parent / "golden_ling32_chunk" / "chunk_rows.json"
|
||||
UPDATE = os.environ.get("STRATA_SNAPSHOT_UPDATE") == "1"
|
||||
|
||||
#: key -> (what it is, the card's own size in GiB as the hardware report gives it, system RAM in GiB, Windows?)
|
||||
ROWS = {
|
||||
"nv_12gb_win_tier_c_64gb": ("RTX 5070 / 3060 12 GB, Windows, 64 GB RAM (the owner's PC)", 11.95, 64.0, True),
|
||||
"nv_12gb_linux_tier_b_128gb": ("12 GB card, Linux, 128 GB RAM", 11.95, 128.0, False),
|
||||
"nv_12gb_linux_tier_c_64gb": ("12 GB card, Linux, 64 GB RAM", 11.95, 64.0, False),
|
||||
"nv_12gb_win_tier_b_192gb": ("12 GB card, Windows, 192 GB RAM", 11.95, 192.0, True),
|
||||
"nv_8gb_linux_tier_c_64gb": ("RTX 3060 Ti 8 GB, Linux, 64 GB RAM", 7.8, 64.0, False),
|
||||
"nv_8gb_win_tier_c_64gb": ("RTX 3060 Ti 8 GB, Windows, 64 GB RAM", 7.8, 64.0, True),
|
||||
"nv_16gb_win_tier_c_64gb": ("RTX 5070 Ti / A4000 16 GB, Windows, 64 GB RAM", 15.9, 64.0, True),
|
||||
"nv_16gb_linux_tier_c_64gb": ("16 GB card, Linux, 64 GB RAM", 15.9, 64.0, False),
|
||||
}
|
||||
|
||||
|
||||
def setup_row(card_gib: float, ram_gib: float, windows: bool) -> dict:
|
||||
import setup
|
||||
a = types.SimpleNamespace(tier=None, vram_budget_gib=None, ram_budget_gib=None, turbo_ssd=False, cpu_coexec=None)
|
||||
args, adv = setup.ling32_engine_args(a, round(card_gib * 0.93, 2), ram_gib, False, 32768, backend="cuda", card_gib=card_gib, pin_half=windows)
|
||||
return {"args": [str(x) for x in args], "tier": adv["tier"], "chunk": adv["plan"]["chunk"], "regrow_off": bool(adv["plan"].get("regrow_off"))}
|
||||
|
||||
|
||||
def launch_row(card_gib: float, ram_gib: float, windows: bool) -> dict:
|
||||
from strata_cli.launch import adopt
|
||||
from strata_control import ling32_family
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root = Path(d)
|
||||
models = root / "models"
|
||||
models.mkdir()
|
||||
(models / ling32_family.MODEL_FILE).write_bytes(b"x")
|
||||
tok = root / "data" / "packs" / "ling-3.2-air-sq-96" / "tokenizer"
|
||||
tok.mkdir(parents=True)
|
||||
(tok / "vocab.json").write_text("{}")
|
||||
cfg, problems = adopt.plan(family="ling-3.2-air", model="SQ-96", model_dir=models, data_dir=root / "data", src=root, context=32768, kv=None, model_name="Ling",
|
||||
family_def={"name": "ling"}, log=root / "x.log", backend="cuda", vram_gb=card_gib, ram_gb=ram_gib, pin_half=windows, pack_name="ling-3.2-air-sq-96")
|
||||
if cfg is None:
|
||||
return {"problems": problems}
|
||||
args = [str(x) for x in cfg["args"]]
|
||||
return {"args": args[2:]} # without --model <path>
|
||||
|
||||
|
||||
def build_rows() -> dict:
|
||||
out = {}
|
||||
for key, (what, card, ram, windows) in ROWS.items():
|
||||
out[key] = {"what": what, "card_gib": card, "ram_gib": ram, "platform": "windows" if windows else "linux",
|
||||
"setup": setup_row(card, ram, windows), "launch": launch_row(card, ram, windows)}
|
||||
return out
|
||||
|
||||
|
||||
def dump(rows: dict) -> str:
|
||||
return json.dumps(rows, indent=1, sort_keys=True) + "\n"
|
||||
|
||||
|
||||
class Ling32ChunkSnapshot(unittest.TestCase):
|
||||
maxDiff = None
|
||||
|
||||
def test_the_rows_match_the_golden_file(self):
|
||||
got = dump(build_rows())
|
||||
if UPDATE:
|
||||
GOLDEN.parent.mkdir(parents=True, exist_ok=True)
|
||||
GOLDEN.write_text(got, encoding="utf-8", newline="\n")
|
||||
self.assertTrue(GOLDEN.is_file(), f"{GOLDEN} is missing: write it with STRATA_SNAPSHOT_UPDATE=1")
|
||||
self.assertEqual(got, GOLDEN.read_text(encoding="utf-8"))
|
||||
|
||||
def test_setup_and_the_terminal_write_the_same_chunk_and_regrow(self):
|
||||
for key, row in build_rows().items():
|
||||
la = row["launch"]["args"]
|
||||
sa = row["setup"]["args"]
|
||||
self.assertEqual(la[la.index("--chunk") + 1], sa[sa.index("--chunk") + 1], key)
|
||||
self.assertEqual("--regrow" in la, "--regrow" in sa, key)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -81,6 +81,28 @@ def test_no_draft_layer_no_change():
|
||||
assert intel_spec.plan(ARGS, None, [B65, B65], mtp_off=True) == (ARGS, "")
|
||||
|
||||
|
||||
NO_MTP = ARGS[:ARGS.index("--mtp")] + ARGS[ARGS.index("--mtp") + 2:]
|
||||
|
||||
|
||||
def test_one_b_series_card_without_a_draft_layer_gets_spec_2():
|
||||
for card in (B65, B70, B50, B580):
|
||||
args, note = intel_spec.plan(NO_MTP, None, [card])
|
||||
assert spec_of(args) == "2" and note, card
|
||||
assert spec_of(NO_MTP) == "4" # the input list is not changed
|
||||
# with a draft layer, or on a card that is not a B-series one, or with the person's own --spec, nothing changes
|
||||
assert intel_spec.plan(ARGS, None, [B70]) == (ARGS, "")
|
||||
for card in (A750, A770, IGPU):
|
||||
assert intel_spec.plan(NO_MTP, None, [card]) == (NO_MTP, ""), card
|
||||
assert intel_spec.plan(NO_MTP, ["--spec", "4"], [B70]) == (NO_MTP, "")
|
||||
mine = list(NO_MTP)
|
||||
mine[mine.index("--spec") + 1] = "3"
|
||||
assert intel_spec.plan(mine, None, [B70]) == (mine, "")
|
||||
# apply_to_config keeps the written copy in step, and a second call says nothing
|
||||
cfg = {"args": list(NO_MTP), "args_written": list(NO_MTP)}
|
||||
assert intel_spec.apply_to_config(cfg, [B70]) and spec_of(cfg["args"]) == "2" and spec_of(cfg["args_written"]) == "2"
|
||||
assert intel_spec.apply_to_config(cfg, [B70]) == ""
|
||||
|
||||
|
||||
def test_apply_to_config_keeps_the_written_copy_in_step():
|
||||
cfg = {"args": list(ARGS), "args_written": list(ARGS), "env": {}}
|
||||
note = intel_spec.apply_to_config(cfg, [B65, B65])
|
||||
@@ -204,6 +226,23 @@ def test_server_wrapper_one_a_series_card_stays(monkeypatch):
|
||||
|
||||
|
||||
|
||||
def test_server_wrapper_one_b_series_card_without_a_draft_layer(monkeypatch):
|
||||
mod = _server_intel()
|
||||
S = mod.S
|
||||
monkeypatch.setattr(S, "engine_args", _base_engine_args)
|
||||
monkeypatch.setattr(intel_spec, "sysfs_cards", lambda *a, **k: [dict(B70, index=0)])
|
||||
mod.install_two_card_spec()
|
||||
cfg = {"backend": "sycl", "args": list(NO_MTP)}
|
||||
assert spec_of(S.engine_args(cfg)) == "2"
|
||||
assert spec_of(cfg["args"]) == "4" # the config in memory is not rewritten by a start
|
||||
assert spec_of(S.engine_args({**cfg, "gpu": 0})) == "2"
|
||||
assert spec_of(S.engine_args({**cfg, "user_args": ["--spec", "4"]})) == "4"
|
||||
assert spec_of(S.engine_args({**cfg, "args": list(ARGS)})) == "4" # a draft layer: unchanged
|
||||
assert spec_of(S.engine_args({**cfg, "backend": "hip"})) == "4"
|
||||
monkeypatch.setattr(intel_spec, "sysfs_cards", lambda *a, **k: [dict(A750, index=0)])
|
||||
assert spec_of(S.engine_args(cfg)) == "4" # an Alchemist card
|
||||
|
||||
|
||||
def _derive(base, settings, cards):
|
||||
from unittest import mock
|
||||
from strata_cli.launch.runner import derive_config
|
||||
|
||||
@@ -48,8 +48,11 @@ class CardList(unittest.TestCase):
|
||||
self.assertEqual(self.add([], [AMD]), [])
|
||||
self.assertEqual(self.add([NVIDIA], [AMD]), [])
|
||||
|
||||
def test_only_linux_and_only_when_the_engine_is_the_intel_one(self):
|
||||
self.assertEqual(self.add([], [], platform="win32"), []) # no Windows Intel engine in the feed
|
||||
def test_only_linux_and_windows_with_ling_and_only_when_the_engine_is_the_intel_one(self):
|
||||
self.assertEqual([c["name"] for c in self.add([], [], platform="win32")], ["Intel Arc A750"]) # Windows: the Ling Intel engine ships (ling32_family.SYCL_ENGINE_SHIPPED)
|
||||
from strata_control import ling32_family
|
||||
with mock.patch.object(ling32_family, "SYCL_ENGINE_SHIPPED", False), mock.patch.object(intel_app, "INKLING_SYCL_WINDOWS_SHIPPED", False), mock.patch.object(intel_app, "QWEN_SYCL_WINDOWS_SHIPPED", False):
|
||||
self.assertEqual(self.add([], [], platform="win32"), []) # every Windows switch off: no Windows Intel engine
|
||||
self.assertEqual(self.add([], [], platform="darwin"), [])
|
||||
self.assertEqual(self.add([], [], intel=False), []) # the engine Control would pick is not SYCL (STRATA_ENGINE_BACKEND, a saved choice)
|
||||
self.assertEqual(self.add([], [], cards=()), [])
|
||||
@@ -74,12 +77,85 @@ class CardList(unittest.TestCase):
|
||||
self.assertEqual([g["name"] for g in s.engine_gpus(hw)], ["Intel Arc A750"])
|
||||
|
||||
|
||||
B70_ADAPTERS = [{"vendor": "8086", "device": 0xE223, "name": "Intel(R) Arc(TM) Pro B70 Graphics", "vram_gb": 32.0},
|
||||
{"vendor": "8086", "device": 0x7D55, "name": "Intel(R) Arc(TM) Graphics", "vram_gb": 0.12}] # the card and the integrated one (left out)
|
||||
|
||||
|
||||
class WindowsIntel(unittest.TestCase):
|
||||
"""A Windows PC with an Intel Arc Pro B70 (the app run of GUI-LING on devcloud2: the hardware report listed no GPU, so the Ling row said cuda / no_card and the engine ran with no card-aware plan)."""
|
||||
|
||||
def test_the_windows_intel_routes_follow_each_familys_switch(self):
|
||||
self.assertTrue(intel_app.route_here("ling32", "win32")) # Ling-3.2-Air ships on Windows Intel (ling32_family.SYCL_ENGINE_SHIPPED)
|
||||
self.assertTrue(intel_app.route_here("inkling", "win32")) # Inkling-2-Mini: INK-B70 gated it on the Windows B70
|
||||
self.assertTrue(intel_app.route_here("qwen", "win32")) # QFN-B70's shipping package passed its gate (the packs: intel_app.QWEN_SYCL_WINDOWS_PACKS)
|
||||
self.assertFalse(intel_app.route_here("hy4", "win32")) # no gated Windows Hy4 engine
|
||||
self.assertFalse(intel_app.route_here("inkling", "darwin"))
|
||||
for kind in ("ling32", "inkling", "hy4", "qwen"):
|
||||
self.assertTrue(intel_app.route_here(kind, "linux"), kind)
|
||||
with mock.patch.object(intel_app, "QWEN_SYCL_WINDOWS_SHIPPED", False):
|
||||
self.assertFalse(intel_app.route_here("qwen", "win32")) # one word turns the Windows Qwen route off
|
||||
with mock.patch.object(intel_app, "INKLING_SYCL_WINDOWS_SHIPPED", False):
|
||||
self.assertFalse(intel_app.route_here("inkling", "win32"))
|
||||
self.assertEqual([intel_app.family_kind(m) for m in ({"ling32": True}, {"inkling": True}, {"hy4": True}, {})], ["ling32", "inkling", "hy4", "qwen"])
|
||||
|
||||
def test_the_windows_model_rows_offer_only_the_routes_that_can_run(self):
|
||||
s = M.Strata(ROOT)
|
||||
hw = {"ram_gb": 64.0, "gpus": [{"vendor": "intel", "name": "Intel(R) Arc(TM) Pro B70 Graphics", "vram_gb": 32.0, "usable": True, "index": 0, "id": "intel:0"}], "engine_vendor": "intel", "cpu": {"avx2": True}}
|
||||
import types
|
||||
with mock.patch.object(intel_app, "sys", types.SimpleNamespace(platform="win32")):
|
||||
rows = {r["family"]: r for r in s.model_table(hw)}
|
||||
def offered(family):
|
||||
return [x.get("offered", True) for x in rows[family]["sizes"]]
|
||||
by_size = {x["model"]: x.get("offered", True) for fam in ("qwen", "coder") if fam in rows for x in rows[fam]["sizes"]}
|
||||
for pack in ("IQ1_M", "IQ2_XS", "IQ3_S"): # the gated packs are offered on a Windows Arc PC
|
||||
if pack in by_size:
|
||||
self.assertTrue(by_size[pack], pack)
|
||||
for pack in ("Q2_0", "IQ3_XXS"): # the others are not (no Windows engine run for them)
|
||||
if pack in by_size:
|
||||
self.assertFalse(by_size[pack], pack)
|
||||
self.assertTrue(any("Linux" in str(x.get("offered_note")) for x in rows["qwen"]["sizes"]))
|
||||
if "inkling-2-mini" in rows:
|
||||
self.assertTrue(all(offered("inkling-2-mini"))) # Inkling: the owner's own Windows B70 work, offered
|
||||
if "ling-3.2-air" in rows:
|
||||
self.assertTrue(all(offered("ling-3.2-air")))
|
||||
with mock.patch.object(intel_app, "sys", types.SimpleNamespace(platform="linux")): # Linux: everything as before
|
||||
linux = {r["family"]: r for r in s.model_table(hw)}
|
||||
self.assertTrue(all(x.get("offered", True) for x in linux["qwen"]["sizes"]))
|
||||
|
||||
def test_the_windows_adapters_give_the_arc_card_with_its_memory(self):
|
||||
cards = intel_app.windows_arc_cards(B70_ADAPTERS)
|
||||
self.assertEqual([(c["vendor"], c["name"], c["vram_gb"], c["index"]) for c in cards], [("intel", "Intel(R) Arc(TM) Pro B70 Graphics", 32.0, 0)])
|
||||
self.assertEqual(intel_app.windows_arc_cards([]), [])
|
||||
|
||||
def test_the_hardware_report_of_a_windows_arc_pc_carries_the_card_and_the_ling_row_follows_it(self):
|
||||
s = M.Strata(ROOT)
|
||||
S = s.setup_module()
|
||||
import types
|
||||
with mock.patch.object(intel_app, "sys", types.SimpleNamespace(platform="win32")), mock.patch.object(M, "WIN", True), \
|
||||
mock.patch.object(S, "gpus", lambda: []), mock.patch.object(S, "amd_gpus", lambda: []), \
|
||||
mock.patch.object(M, "windows_video_controllers", lambda: []), mock.patch.object(M, "windows_desktop_adapters", lambda: []), \
|
||||
mock.patch("strata_control.engine_component.windows_display_adapters", lambda: [dict(x) for x in B70_ADAPTERS]), \
|
||||
mock.patch.object(intel_app, "engine_is_intel", lambda: True), \
|
||||
mock.patch("strata_control.engine_component.status", lambda: {"usable": False}):
|
||||
hw = s._hardware()
|
||||
self.assertEqual([(g["vendor"], g["vram_gb"], g["id"]) for g in hw["gpus"]], [("intel", 32.0, "intel:0")])
|
||||
self.assertEqual(hw["engine_vendor"], "intel")
|
||||
row = s.ling32_fit_row("SQ-96", 32.0, s.engine_gpus(hw))
|
||||
self.assertIsNotNone(row)
|
||||
self.assertEqual(row["tier"], "C") # a 32 GB card with 32 GB of RAM: the pool layout, tier C
|
||||
self.assertGreater(row["placement"]["vram_gb"], 20.0) # the card's memory is in the plan (it was 0.15 GB with no card)
|
||||
self.assertFalse([w for w in row["warnings"] if "no engine yet" in w])
|
||||
|
||||
|
||||
class Recommendation(unittest.TestCase):
|
||||
def test_an_arc_is_a_sycl_pc_and_says_there_is_no_download(self):
|
||||
def test_an_arc_is_a_sycl_pc_and_says_there_is_no_download_only_where_there_is_none(self):
|
||||
s = M.Strata(ROOT)
|
||||
rec = s.recommend({"ram_gb": 64.0, "gpus": [dict(A750)], "engine_vendor": "intel", "cpu": {"avx2": True}})
|
||||
self.assertEqual(rec["backend"], "sycl")
|
||||
self.assertIn(intel_app.NO_DOWNLOAD, rec["notes"])
|
||||
self.assertNotIn(intel_app.NO_DOWNLOAD, rec["notes"]) # Linux: the Qwen sizes download (setup.py fetch_gguf_shards), so nothing says "can't download"
|
||||
with mock.patch.object(intel_app, "can_download", lambda *a, **k: False):
|
||||
rec = s.recommend({"ram_gb": 64.0, "gpus": [dict(A750)], "engine_vendor": "intel", "cpu": {"avx2": True}})
|
||||
self.assertIn(intel_app.NO_DOWNLOAD, rec["notes"]) # a model that does not (a pack not gated on a Windows Arc, a feed model): the block stays, with its words
|
||||
self.assertTrue(rec["setup_command"].endswith(" --backend sycl"))
|
||||
|
||||
def test_nvidia_and_amd_recommendations_are_unchanged(self):
|
||||
@@ -134,9 +210,11 @@ class InstallPlan(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
data = Path(t) / "Strata-data"
|
||||
data.mkdir()
|
||||
with self.assertRaises(M.ToolError) as raised:
|
||||
with mock.patch.object(intel_app, "can_download", lambda *a, **k: False), self.assertRaises(M.ToolError) as raised: # not downloadable: the block, with its words
|
||||
self.plan([A750], data_dir=str(data))
|
||||
self.assertEqual(str(raised.exception), intel_app.NO_DOWNLOAD)
|
||||
plan, args = self.plan([A750], data_dir=str(data)) # downloadable (Linux, every Qwen size): the install goes on and setup downloads
|
||||
self.assertEqual(args[-2:], ["--backend", "sycl"])
|
||||
shards(data / "models" / "Q2_0") # the files are where the Terminal looks (<data>/models/<tag>)
|
||||
plan, args = self.plan([A750], data_dir=str(data))
|
||||
self.assertEqual(args[-2:], ["--backend", "sycl"])
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
"""Models for an Intel Arc card are downloaded (0.2.25): the GGUF families download from setup.py's pinned sources (fetch_gguf_shards, the step NVIDIA and AMD installs run) where their Arc route runs for
|
||||
the pack (Linux every pack, Windows the gated ones: intel_app.QWEN_SYCL_WINDOWS_PACKS), Ling-3.2-Air, Inkling-2-Mini and Hy4-Flash through their own installs; a model without such a route keeps the
|
||||
block with its words (intel_app.NO_DOWNLOAD). What these tests pin:
|
||||
* intel_app.can_download for every family, pack and platform;
|
||||
* fetch_gguf_shards (moved out of main() step 5): downloads what is missing from the pinned URL, skips finished shards, links the original's shard 2 from a size that is already there;
|
||||
* setup.intel_download_gguf and intel_control_setup: the disk is checked first (nothing is downloaded when it does not fit), the RAM is said, the shards are fetched, then the pack and the run config as before;
|
||||
* the block stays for a pack that is not gated on a Windows Arc (with its words), and the Terminal's launcher runs the installer (setup --backend sycl) for a download and the prepared-files path otherwise.
|
||||
Offline: nothing is downloaded, the download function is replaced."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tools"))
|
||||
import setup # noqa: E402
|
||||
from strata_control import intel_app # noqa: E402
|
||||
|
||||
A750 = {"vendor": "intel", "name": "Intel Arc A750", "vram_gb": 8.0, "usable": True, "index": 0}
|
||||
WIN = types.SimpleNamespace(platform="win32")
|
||||
|
||||
|
||||
class CanDownload(unittest.TestCase):
|
||||
def test_the_families_and_packs_that_download(self):
|
||||
win = lambda *a, **k: intel_app.can_download(*a, platform="win32", **k) # noqa: E731
|
||||
lin = lambda *a, **k: intel_app.can_download(*a, platform="linux", **k) # noqa: E731
|
||||
for pack, fam in (("IQ1_M", "coder"), ("IQ2_XS", "qwen"), ("IQ3_S", "qwen")):
|
||||
self.assertTrue(win(fam, pack), pack) # the gated Windows packs
|
||||
for pack, fam in (("Q2_0", "qwen"), ("IQ3_XXS", "qwen"), ("IQ3_S", "swift"), ("IQ3_S", "unsloth"), ("UD-Q4_K_XL", "unsloth")):
|
||||
self.assertFalse(win(fam, pack), (fam, pack)) # not gated on a Windows Arc: the block, with its words
|
||||
self.assertTrue(lin(fam, pack), (fam, pack)) # Linux: every GGUF size
|
||||
self.assertFalse(lin("qwen4", "IQ2_XS", {"feed": True})) # a model of the signed feed has no source here
|
||||
self.assertTrue(win("ling-3.2-air", "SQ-96") and win("inkling-2-mini", "Q4") and lin("hy4-flash", "x")) # their own installs download
|
||||
self.assertFalse(intel_app.can_download("hy4-flash", "x", platform="win32")) # (no Windows Intel Hy4 engine: nothing to download for)
|
||||
with mock.patch.object(intel_app, "QWEN_SYCL_WINDOWS_SHIPPED", False):
|
||||
self.assertFalse(win("coder", "IQ1_M"))
|
||||
self.assertFalse(intel_app.can_download("qwen", "IQ2_XS", platform="darwin"))
|
||||
|
||||
|
||||
class Fetch(unittest.TestCase):
|
||||
def test_only_the_missing_shards_download_and_shard_2_is_shared(self):
|
||||
fam = setup.FAMILIES["qwen"]
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
t = Path(t)
|
||||
models = t / "models"
|
||||
other = models / "iq3_s"
|
||||
other.mkdir(parents=True)
|
||||
donor = other / setup.model_file(setup.FAMILIES["qwen"], "IQ3_S", 2)
|
||||
donor.write_bytes(b"shard two")
|
||||
setup.mark(donor)
|
||||
folder = models / "iq2_xs"
|
||||
folder.mkdir()
|
||||
shards = [folder / setup.model_file(fam, "IQ2_XS", i) for i in range(1, setup.model_shards(fam, "IQ2_XS") + 1)]
|
||||
asked = []
|
||||
|
||||
def fake_download(url, dst, what=None):
|
||||
asked.append((url, Path(dst).name))
|
||||
Path(dst).write_bytes(b"x")
|
||||
setup.mark(Path(dst))
|
||||
|
||||
a = types.SimpleNamespace(models_dir=str(models), gguf_dir=None)
|
||||
with mock.patch.object(setup, "download", fake_download):
|
||||
setup.fetch_gguf_shards(a, "qwen", fam, "IQ2_XS", shards, folder)
|
||||
self.assertEqual([n for _u, n in asked], [shards[0].name]) # shard 1 downloaded; shard 2 linked from the IQ3_S folder
|
||||
self.assertTrue(shards[1].exists() and setup.done(shards[1]))
|
||||
asked.clear()
|
||||
setup.fetch_gguf_shards(a, "qwen", fam, "IQ2_XS", shards, folder)
|
||||
self.assertEqual(asked, []) # everything is there: nothing downloads
|
||||
self.assertTrue(asked == [] and shards[0].name.endswith("-00001-of-00002.gguf"))
|
||||
|
||||
def test_the_url_is_the_pinned_one(self):
|
||||
fam = setup.FAMILIES["coder"]
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
t = Path(t)
|
||||
folder = t / "models" / "coder-iq1_m"
|
||||
folder.mkdir(parents=True)
|
||||
shards = [folder / setup.model_file(fam, "IQ1_M", i) for i in range(1, setup.model_shards(fam, "IQ1_M") + 1)]
|
||||
urls = []
|
||||
a = types.SimpleNamespace(models_dir=str(t / "models"), gguf_dir=None)
|
||||
with mock.patch.object(setup, "download", lambda url, dst, what=None: (urls.append(url), Path(dst).write_bytes(b"x"), setup.mark(Path(dst)))):
|
||||
setup.fetch_gguf_shards(a, "coder", fam, "IQ1_M", shards, folder)
|
||||
self.assertEqual(urls, [setup.model_hf(fam, "IQ1_M") + s.name for s in shards])
|
||||
|
||||
|
||||
class ArcInstall(unittest.TestCase):
|
||||
def args(self, **kw):
|
||||
base = dict(family="qwen", model="IQ2_XS", gguf_dir=None, models_dir=None, data_dir=None, context=32768, kv="int8", port=None, host=None,
|
||||
api_key=None, browser=None, check=False, yes=True, move_data=False, set_default_data_dir=False, prepare_pack=None)
|
||||
base.update(kw)
|
||||
return mock.Mock(**base)
|
||||
|
||||
def run_setup(self, a, data, home, *, windows=True, free=500.0, ram=64.0):
|
||||
self.fetched, self.packed, self.said = [], None, []
|
||||
|
||||
def fake_fetch(args, family, fam, model, shards, models_dir):
|
||||
self.fetched.append((model, [s.name for s in shards]))
|
||||
for s in shards:
|
||||
s.parent.mkdir(parents=True, exist_ok=True)
|
||||
s.write_bytes(b"x")
|
||||
|
||||
def fake_pack(args):
|
||||
pack = Path(args.prepare_pack)
|
||||
(pack / "tokenizer").mkdir(parents=True, exist_ok=True)
|
||||
(pack / "tokenizer" / "vocab.json").write_text("{}")
|
||||
(pack / "index.txt").write_text("x")
|
||||
self.packed = args.prepare_pack
|
||||
return 0
|
||||
|
||||
def fake_fail(message, hint=None, **kw):
|
||||
self.said.append(message)
|
||||
raise SystemExit(1)
|
||||
|
||||
patches = [mock.patch.object(setup, "CONTROL", True), mock.patch.object(setup, "_CONTROL_HOME", home), mock.patch.object(setup, "data_folder_for", lambda a: (data, [])),
|
||||
mock.patch.object(setup, "prepare_pack_only", fake_pack), mock.patch.object(setup, "fetch_gguf_shards", fake_fetch), mock.patch.object(setup, "check_shards", lambda shards: None), mock.patch.object(setup, "fail", fake_fail),
|
||||
mock.patch.object(setup, "free_gb", lambda p: free), mock.patch.object(setup, "ram_gb", lambda: ram),
|
||||
mock.patch.object(setup, "warn", lambda m, *a, **k: self.said.append("WARN " + m)),
|
||||
mock.patch.object(intel_app, "arc_cards", lambda root="", platform=None: [dict(A750)]),
|
||||
mock.patch("strata_cli.launch.adopt.intel_driver", lambda: "xe"), mock.patch.object(intel_app, "supported_here", lambda platform=None: True)]
|
||||
if windows:
|
||||
patches += [mock.patch.object(intel_app, "sys", WIN), mock.patch("strata_cli.launch.adopt.sys", WIN)]
|
||||
for p in patches:
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
return setup.intel_control_setup(a)
|
||||
|
||||
def test_a_gated_pack_without_its_files_downloads_prepares_and_writes_the_settings(self):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
t = Path(t)
|
||||
data, home = t / "Strata-data", t / "install"
|
||||
data.mkdir()
|
||||
home.mkdir()
|
||||
self.assertEqual(self.run_setup(self.args(), data, home), 0)
|
||||
self.assertEqual([m for m, _n in self.fetched], ["IQ2_XS"])
|
||||
self.assertEqual(self.packed, str(data / "packs" / "iq2_xs"))
|
||||
cfg = json.loads((home / "strata-iq2_xs.json").read_text(encoding="utf-8"))
|
||||
a = cfg["args"]
|
||||
self.assertEqual((cfg["backend"], a[a.index("--spec") + 1]), ("sycl", "2"))
|
||||
self.assertNotIn("--suffix-draft", a) # IQ2_XS on Windows: fast mode by default (owner, 2026-12-03): the drafting rule adds DFlash2 at Load, nothing forces plain
|
||||
|
||||
def test_a_pack_that_is_not_gated_on_windows_keeps_the_block_with_its_words(self):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
t = Path(t)
|
||||
data, home = t / "Strata-data", t / "install"
|
||||
data.mkdir()
|
||||
home.mkdir()
|
||||
with self.assertRaises(SystemExit):
|
||||
self.run_setup(self.args(model="Q2_0"), data, home)
|
||||
self.assertEqual(self.fetched, [])
|
||||
self.assertTrue(any("no Intel Arc engine" in m for m in self.said), self.said) # the route check says it first, with the sizes that run on a Windows Arc in its hint
|
||||
|
||||
def test_linux_downloads_every_size(self):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
t = Path(t)
|
||||
data, home = t / "Strata-data", t / "install"
|
||||
data.mkdir()
|
||||
home.mkdir()
|
||||
self.assertEqual(self.run_setup(self.args(model="Q2_0"), data, home, windows=False), 0)
|
||||
self.assertEqual([m for m, _n in self.fetched], ["Q2_0"])
|
||||
|
||||
def test_the_disk_is_checked_before_anything_downloads_and_the_ram_is_said(self):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
t = Path(t)
|
||||
data, home = t / "Strata-data", t / "install"
|
||||
data.mkdir()
|
||||
home.mkdir()
|
||||
with self.assertRaises(SystemExit):
|
||||
self.run_setup(self.args(), data, home, free=20.0) # 68 GB to fetch, 20 GB free
|
||||
self.assertEqual(self.fetched, [])
|
||||
self.assertTrue(any("not enough free disk space" in m for m in self.said), self.said)
|
||||
self.run_setup(self.args(), data, home, ram=16.0)
|
||||
self.assertTrue(any(m.startswith("WARN") and "16 GB of RAM" in m for m in self.said), self.said)
|
||||
|
||||
def test_the_fast_drafter_ram_note(self):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
t = Path(t)
|
||||
data, home = t / "Strata-data", t / "install"
|
||||
data.mkdir()
|
||||
home.mkdir()
|
||||
self.run_setup(self.args(model="IQ3_S"), data, home, ram=16.0)
|
||||
self.assertTrue(any(m.startswith("WARN") and "32 GB" in m and "DFlash2" in m for m in self.said), self.said)
|
||||
self.run_setup(self.args(model="IQ3_S"), data, home, ram=64.0)
|
||||
self.assertFalse(any("DFlash2" in m for m in self.said), self.said)
|
||||
self.run_setup(self.args(model="IQ2_XS", family="qwen"), data, home, ram=64.0)
|
||||
self.assertFalse(any("32 GB" in m for m in self.said), self.said)
|
||||
|
||||
def test_files_that_are_there_download_nothing(self):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
t = Path(t)
|
||||
data, home = t / "Strata-data", t / "install"
|
||||
fam = setup.FAMILIES["qwen"]
|
||||
folder = data / "models" / "IQ2_XS"
|
||||
folder.mkdir(parents=True)
|
||||
for i in range(1, setup.model_shards(fam, "IQ2_XS") + 1):
|
||||
(folder / setup.model_file(fam, "IQ2_XS", i)).write_bytes(b"x")
|
||||
home.mkdir()
|
||||
self.assertEqual(self.run_setup(self.args(), data, home), 0)
|
||||
self.assertEqual(self.fetched, [])
|
||||
|
||||
|
||||
class Terminal(unittest.TestCase):
|
||||
"""The Terminal's launcher: the installer (setup --backend sycl) for a download, the prepared-files path when the files are there."""
|
||||
|
||||
def runner(self, **kw):
|
||||
from strata_cli.launch import runner as R
|
||||
from strata_cli.launch import settings as S
|
||||
r = object.__new__(R.Runner)
|
||||
r.s = S.LaunchSettings(**kw)
|
||||
return R, r
|
||||
|
||||
def test_the_windows_routes_and_the_download_decision(self):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
R, r = self.runner(family="qwen", model="IQ2_XS", data_dir=t)
|
||||
cat = mock.Mock()
|
||||
cat.tables.return_value = ({}, {"qwen": setup.FAMILIES["qwen"]}, None, None)
|
||||
cat.data_dir.return_value = Path(t)
|
||||
with mock.patch.object(R, "WINDOWS", True), mock.patch.object(intel_app, "sys", WIN), mock.patch.object(R.Runner, "catalog", new_callable=mock.PropertyMock, return_value=cat):
|
||||
self.assertTrue(r.intel_route_here())
|
||||
self.assertTrue(r.intel_downloads()) # gated pack, files missing
|
||||
folder = Path(t) / "models" / (setup.FAMILIES["qwen"].get("tag", "") + "IQ2_XS")
|
||||
folder.mkdir(parents=True)
|
||||
for i in range(1, setup.model_shards(setup.FAMILIES["qwen"], "IQ2_XS") + 1):
|
||||
(folder / setup.model_file(setup.FAMILIES["qwen"], "IQ2_XS", i)).write_bytes(b"x")
|
||||
self.assertFalse(r.intel_downloads()) # files there: the prepared-files path
|
||||
r.s.model = "Q2_0"
|
||||
self.assertFalse(r.intel_route_here() or r.intel_downloads()) # not gated on a Windows Arc
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Ling-3.2-Air expert skip, "Medium" (0.2.25, owner decision 2026-12-03): the engine's `--skip-tau 0.05` (f-ling32-int c966eccc17: at decode and speculative-verify rows, a token's experts with a routing-weight
|
||||
share below 0.05 are dropped, the top expert kept; NOT exact; +9 to 10 % on a 3090, about 1 word in 60 different). An optional setting, off by default, offered only where it was measured: the NVIDIA CUDA engine on
|
||||
Linux, a card of the 24 GB class, a plan that streams experts (tier B or C). What these tests pin:
|
||||
* the rule (ling32_fit.expert_skip_applies / skip_tau_args) for every class of card, tier, backend and platform;
|
||||
* the Terminal: `--expert-skip medium` reaches the saved run config as `--skip-tau 0.05` only where it is offered; off, unset or not offered write nothing; "off" removes an earlier pair; the default rows are unchanged;
|
||||
* setup writes the same pair for the same rows; the notice says what it costs, or that it changes nothing here;
|
||||
* the saved representation is the one the app reads: the two entries in the engine args, no other key.
|
||||
Offline: nothing runs but Python."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tools"))
|
||||
from strata_cli.launch import cmd as C # noqa: E402
|
||||
from strata_cli.launch import runner as R # noqa: E402
|
||||
from strata_cli.launch import settings as S # noqa: E402
|
||||
from strata_control import ling32_fit, tune_knobs # noqa: E402
|
||||
|
||||
BASE = {"exe": "component:strata-ling32", "arch": "ling32", "model_name": "ling-3.2-air-sq-96", "port": 8095, "drafting": "off", "thinking": "off",
|
||||
"args": ["--model", "C:/m/Ling-3.2-Air-SQ-96.strata", "--ctx", "32768", "--chunk", "2048", "--tc", "16", "--tc-moe", "128", "--graph", "--mla-kernel", "simt"]}
|
||||
|
||||
|
||||
def derive(base=BASE, ok=True, **kw):
|
||||
return R.derive_config(base, S.LaunchSettings(family="ling-3.2-air", port=8123, **kw), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log", expert_skip_ok=ok)
|
||||
|
||||
|
||||
def computer(vendor="nvidia", vram=23.5, ram=64.0):
|
||||
return types.SimpleNamespace(engine_vendor=vendor, main_vram_gb=vram, ram_gb=ram)
|
||||
|
||||
|
||||
class Rule(unittest.TestCase):
|
||||
def test_where_it_is_offered(self):
|
||||
F = ling32_fit
|
||||
for card in (23.5, 24.0, 20.0, 26.9): # the 24 GB class: 3090, 4090 (23.x GiB), the edges of CLASS_24_GIB .. CLASS_32_GIB
|
||||
for tier in ("B", "C"):
|
||||
self.assertTrue(F.expert_skip_applies("cuda", card, tier, "linux"), (card, tier))
|
||||
self.assertFalse(F.expert_skip_applies("cuda", 23.5, "A", "linux")) # tier A gains nothing
|
||||
for card in (8.0, 11.95, 15.9, 19.9, 27.0, 31.4, 47.5, 96.0, None, 0):
|
||||
self.assertFalse(F.expert_skip_applies("cuda", card, "B", "linux"), card)
|
||||
for backend in ("hip", "sycl", "metal"):
|
||||
self.assertFalse(F.expert_skip_applies(backend, 23.5, "B", "linux"), backend)
|
||||
for platform in ("win32", "darwin"):
|
||||
self.assertFalse(F.expert_skip_applies("cuda", 23.5, "B", platform), platform) # measured on Linux only
|
||||
|
||||
def test_the_flag_and_its_level(self):
|
||||
F = ling32_fit
|
||||
self.assertEqual(F.SKIP_TAU_MEDIUM, 0.05)
|
||||
self.assertEqual(F.EXPERT_SKIP_WORDS, ("off", "medium")) # one level: no light, no strong
|
||||
self.assertEqual(F.skip_tau_args("medium", "cuda", 23.5, "B", "linux"), ["--skip-tau", "0.05"])
|
||||
for word in (None, "", "off", "light", "strong"):
|
||||
self.assertEqual(F.skip_tau_args(word, "cuda", 23.5, "B", "linux"), [], word)
|
||||
self.assertEqual(F.skip_tau_args("medium", "cuda", 15.9, "B", "linux"), [])
|
||||
self.assertIn("1 word in 60", F.EXPERT_SKIP_NOTE)
|
||||
|
||||
def test_the_helper_the_launcher_uses(self):
|
||||
with mock.patch.object(ling32_fit, "EXPERT_SKIP_PLATFORMS", ("",)): # any platform: the tests run on Linux and Windows
|
||||
s = S.LaunchSettings(family="ling-3.2-air")
|
||||
self.assertTrue(S.expert_skip_applies(s, computer("nvidia", 23.5, 64.0))) # a 3090 with 64 GB: the experts stream (tier B or C)
|
||||
self.assertFalse(S.expert_skip_applies(s, computer("nvidia", 15.9, 64.0)))
|
||||
self.assertFalse(S.expert_skip_applies(s, computer("nvidia", 47.5, 128.0)))
|
||||
self.assertFalse(S.expert_skip_applies(s, computer("amd", 23.5, 64.0)))
|
||||
self.assertFalse(S.expert_skip_applies(s, computer("intel", 23.5, 64.0)))
|
||||
self.assertFalse(S.expert_skip_applies(s, computer(None, 23.5, 64.0)))
|
||||
self.assertFalse(S.expert_skip_applies(S.LaunchSettings(family="qwen"), computer()))
|
||||
self.assertFalse(S.expert_skip_applies(s, object())) # a computer record without the fields: no crash
|
||||
with mock.patch.object(ling32_fit, "EXPERT_SKIP_PLATFORMS", ("linux",)), mock.patch.object(sys, "platform", "win32"):
|
||||
self.assertFalse(S.expert_skip_applies(S.LaunchSettings(family="ling-3.2-air"), computer()))
|
||||
|
||||
|
||||
class Terminal(unittest.TestCase):
|
||||
def test_default_rows_are_unchanged(self):
|
||||
for kw in ({}, {"expert_skip": None}):
|
||||
self.assertNotIn("--skip-tau", derive(**kw)["args"])
|
||||
self.assertEqual(derive()["args"][:len(BASE["args"])], BASE["args"])
|
||||
self.assertIsNone(S.LaunchSettings().expert_skip)
|
||||
|
||||
def test_medium_writes_the_pair_only_where_it_is_offered(self):
|
||||
a = derive(expert_skip="medium")["args"]
|
||||
self.assertEqual(a[a.index("--skip-tau"):a.index("--skip-tau") + 2], ["--skip-tau", "0.05"])
|
||||
self.assertEqual(a.count("--skip-tau"), 1)
|
||||
self.assertNotIn("--skip-tau", derive(ok=False, expert_skip="medium")["args"]) # not the 24 GB class / not tier B or C / not Linux CUDA: nothing
|
||||
self.assertNotIn("--skip-tau", derive(expert_skip="off")["args"])
|
||||
|
||||
def test_off_removes_an_earlier_pair_and_unset_leaves_it(self):
|
||||
base = {**BASE, "args": [*BASE["args"], "--skip-tau", "0.05"]}
|
||||
self.assertNotIn("--skip-tau", derive(base, expert_skip="off")["args"])
|
||||
self.assertNotIn("0.05", derive(base, expert_skip="off")["args"])
|
||||
self.assertIn("--skip-tau", derive(base)["args"]) # as installed: kept (the app writes the same pair)
|
||||
|
||||
def test_other_families_never_get_it(self):
|
||||
cfg = R.derive_config({"exe": "component:strata-engine", "args": []}, S.LaunchSettings(family="qwen", port=8123, expert_skip="medium"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log", expert_skip_ok=True)
|
||||
self.assertNotIn("--skip-tau", cfg["args"])
|
||||
|
||||
def test_the_command_line_flag_and_the_summary(self):
|
||||
ap = argparse.ArgumentParser()
|
||||
C.add_parsers(ap.add_subparsers(dest="cmd"))
|
||||
a = ap.parse_args(["launch", "--family", "ling-3.2-air", "--expert-skip", "medium"])
|
||||
self.assertEqual(a.expert_skip, "medium")
|
||||
self.assertIsNone(ap.parse_args(["launch", "--family", "ling-3.2-air"]).expert_skip)
|
||||
with self.assertRaises(SystemExit), mock.patch("sys.stderr"):
|
||||
ap.parse_args(["launch", "--family", "ling-3.2-air", "--expert-skip", "strong"])
|
||||
self.assertIn("--expert-skip medium", S.flags_text(S.LaunchSettings(family="ling-3.2-air", expert_skip="medium")))
|
||||
self.assertNotIn("--expert-skip", S.flags_text(S.LaunchSettings(family="ling-3.2-air")))
|
||||
|
||||
def test_the_notice(self):
|
||||
s = S.LaunchSettings(family="ling-3.2-air", expert_skip="medium")
|
||||
with mock.patch.object(ling32_fit, "EXPERT_SKIP_PLATFORMS", ("",)):
|
||||
on = S.check_ling32(s, vram_gb=23.5, ram_gb=64.0, vendor="nvidia")
|
||||
off_card = S.check_ling32(s, vram_gb=15.9, ram_gb=64.0, vendor="nvidia")
|
||||
self.assertTrue(any("1 word in 60" in n.line() for n in on))
|
||||
self.assertTrue(any("--expert-skip changes nothing here" in n.line() for n in off_card))
|
||||
self.assertFalse(any("expert-skip" in n.line() for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=23.5, ram_gb=64.0, vendor="nvidia")))
|
||||
|
||||
|
||||
class Setup(unittest.TestCase):
|
||||
def test_setup_writes_the_same_pair(self):
|
||||
import setup
|
||||
a = argparse.Namespace(tier=None, vram_budget_gib=None, ram_budget_gib=None, turbo_ssd=False, cpu_coexec=None, expert_skip="medium")
|
||||
with mock.patch.object(ling32_fit, "EXPERT_SKIP_PLATFORMS", ("",)):
|
||||
args, adv = setup.ling32_engine_args(a, 23.0, 64.0, False, 32768, backend="cuda", card_gib=23.5)
|
||||
self.assertEqual(args[args.index("--skip-tau") + 1], "0.05")
|
||||
self.assertIn(adv["tier"], ("B", "C"))
|
||||
a.expert_skip = None
|
||||
self.assertNotIn("--skip-tau", setup.ling32_engine_args(a, 23.0, 64.0, False, 32768, backend="cuda", card_gib=23.5)[0])
|
||||
a.expert_skip = "medium"
|
||||
self.assertNotIn("--skip-tau", setup.ling32_engine_args(a, 15.0, 64.0, False, 32768, backend="cuda", card_gib=15.9)[0]) # not the 24 GB class
|
||||
self.assertNotIn("--skip-tau", setup.ling32_engine_args(a, 23.0, 64.0, False, 32768, backend="hip", card_gib=23.5)[0]) # not CUDA
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -291,15 +291,46 @@ def test_engine_chunk_rule_and_the_launchers_use_of_it():
|
||||
|
||||
def test_the_launcher_chunk_by_card_size():
|
||||
# L32-CUDA, RTX 5090 tier B: --chunk 256 made a 4062-token prefill 33 % slower and a 32K one 115 % slower than the engine's default; the small chunk stays where memory is the limit
|
||||
assert [F.chunk_for(g) for g in (8, 11.6, 12, 13.9, 14, 15.0, 15.5, 15.9, 16, 19.9, 20, 22.4, 23.3, 24, 26.9, 27, 29.9, 30, 31.4, 32, 39.5, 43.9, 44, 47.5, 47.9, 48, 96)] == [
|
||||
256, 256, 256, 256, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 1024, 1024, 1024, 1024, 1024]
|
||||
assert [F.chunk_for(g) for g in (8, 11.4, 11.5, 11.6, 12, 13.9, 14, 15.0, 15.5, 15.9, 16, 19.9, 20, 22.4, 23.3, 24, 26.9, 27, 29.9, 30, 31.4, 32, 39.5, 43.9, 44, 47.5, 47.9, 48, 96)] == [
|
||||
2048, 256, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 1024, 1024, 1024, 1024, 1024]
|
||||
# the nominal classes: a 16 GB card reports 15.9 GiB (an RTX 5070 Ti), a 24 GB card 23.x, a 32 GB card 31.4, a 48 GB card 47.5; the free memory after the desktop is a little less still
|
||||
for reported, nominal in ((15.9, 16), (15.5, 16), (14.4, 16), (23.5, 24), (22.4, 24), (20.5, 24), (31.4, 32), (29.0, 32), (47.5, 48), (45.0, 48)):
|
||||
assert F.chunk_for(reported) == F.chunk_for(nominal), (reported, nominal)
|
||||
assert F.chunk_for(23.5) == 2048 and F.chunk_for(15.9) == 2048 and F.chunk_for(12) == 256 # 24 GB: L32-CUDA's 3090 / 4090 sweep; 16 GB: MID2 + L32-SMALL's A4000 gate (prefill +18 to +21 % with the pool regrow, decode flat)
|
||||
assert F.chunk_for(23.5) == 2048 and F.chunk_for(15.9) == 2048 and F.chunk_for(12) == 2048 and F.chunk_for(11.0) == 256 and F.chunk_for(9.8) == 256 and F.chunk_for(7.6) == 2048 and F.chunk_for(8.9) == 2048 and F.chunk_for(5.9) == 256 and F.chunk_for(9.0) == 256 # 24 GB: L32-CUDA's 3090 / 4090 sweep; 16 GB: MID2 + L32-SMALL's A4000 gate (prefill +18 to +21 % with the pool regrow, decode flat)
|
||||
|
||||
assert F.chunk_for(None) == 1024 and F.chunk_for(0) == 1024 and F.chunk_for(96, unified=True) == 1024
|
||||
assert p(32, 128)["chunk"] == 2048 and p(24, 128)["chunk"] == 2048 and p(12, 128)["chunk"] == 256
|
||||
assert p(32, 128)["chunk"] == 2048 and p(24, 128)["chunk"] == 2048 and p(12, 128)["chunk"] == 2048 and p(8, 128)["chunk"] == 2048
|
||||
# the card's own size decides the class where it is known: a 12 GB card with 1.2 GiB used by the desktop (10.8 GiB free) still takes 2048, an 11 GB or 10 GB card does not
|
||||
assert F.chunk_for(10.8, card_gib=11.95) == 2048 and F.chunk_for(10.0, card_gib=10.7) == 256 and F.chunk_for(9.0, card_gib=9.8) == 256
|
||||
assert F.plan(10.8, 128, card_gib=11.95)["chunk"] == 2048 and F.advise(10.8, 128, card_gib=11.95)["plan"]["chunk"] == 2048
|
||||
# variant (c): the 12 GB class and up take 2048 everywhere, Windows tier C included (the engine's planner headroom, f-ling32-int c966eccc17, is what keeps the card from over-committing); no flag besides --chunk
|
||||
for ram, pin in ((32, False), (64, False), (96, False), (128, False), (64, True), (128, True), (192, True)):
|
||||
got = F.plan(11.95, ram, ctx=131072, card_gib=11.95, pin_half=pin)
|
||||
assert got["chunk"] == 2048, (ram, pin, got["mode"], got["chunk"])
|
||||
# the pin cap moves nothing but the 8 GB class's chunk (and what follows from it: the pool numbers)
|
||||
for card in (6, 10, 12, 16, 20, 24, 32, 48):
|
||||
for ram in (16, 64, 128, 256):
|
||||
assert F.advise(card * 0.9, ram, ctx=131072, card_gib=float(card)) == F.advise(card * 0.9, ram, ctx=131072, card_gib=float(card), pin_half=True), (card, ram)
|
||||
for ram in (16, 64, 128):
|
||||
a, b = F.advise(7.2, ram, ctx=131072, card_gib=8.0), F.advise(7.2, ram, ctx=131072, card_gib=8.0, pin_half=True)
|
||||
moved = {k for k in set(a["plan"]) | set(b["plan"]) if a["plan"].get(k) != b["plan"].get(k)}
|
||||
assert moved <= {"chunk", "dyn_bytes", "dyn_slots", "vram_fixed", "vram_gb", "vram_total_planned"}, moved
|
||||
assert {k: v for k, v in a.items() if k != "plan"} == {k: v for k, v in b.items() if k != "plan"}
|
||||
# the 8 GB class (L32-SMALL's 3060 Ti, tier C, 62 GB RAM, loader-reserve fix 03006f62ed: 2048 beats 256 by 1.2 to 2.0x on Linux): 2048 except Windows in tier C
|
||||
got = F.plan(7.6, 62, ctx=131072, card_gib=8.0)
|
||||
assert (got["mode"], got["chunk"]) == ("C", 2048), (got["mode"], got["chunk"])
|
||||
got = F.plan(7.6, 64, ctx=131072, card_gib=8.0, pin_half=True)
|
||||
assert (got["mode"], got["chunk"]) == ("C", F.WINDOWS_TIER_C_CHUNK), (got["mode"], got["chunk"])
|
||||
# whichever chunk the Windows tier C constant names, the planner (the loader-reserve rule of 03006f62ed) must fit it on the 8 and 12 GB cards at the default context
|
||||
for card in (7.6, 11.95):
|
||||
for chunk in (256, 2048, 4096, F.WINDOWS_TIER_C_CHUNK):
|
||||
fit = F.plan(card, 64, ctx=131072, card_gib=card, pin_half=True, chunk=chunk)
|
||||
assert fit["ok"], (card, chunk, fit.get("notes"))
|
||||
assert F.plan(7.6, 64, ctx=131072, card_gib=8.0, pin_half=True, chunk=2048)["chunk"] == 2048
|
||||
assert F.plan(5.6, 62, ctx=131072, card_gib=6.0)["chunk"] == 256 and F.plan(9.4, 62, ctx=131072, card_gib=10.0)["chunk"] == 256
|
||||
assert F.plan(15.9, 64, card_gib=15.9)["chunk"] == 2048 and F.plan(15.9, 64, card_gib=15.9)["mode"] == "C" # the 16 GB class keeps 2048 in tier C (L32-SMALL's A4000 gate)
|
||||
assert F.plan(11.95, 64, card_gib=11.95, chunk=2048)["chunk"] == 2048 # an explicit chunk is never changed
|
||||
assert F.small_card_class(7.6, 8.0) and F.small_card_class(7.0, 8.0) and not F.small_card_class(11.95) and not F.small_card_class(15.9) and not F.small_card_class(5.9) and not F.small_card_class(10.8) and not F.small_card_class(7.6, None, "hip")
|
||||
# the bigger chunk costs pool slots (its activation buffers), a few percent on a 24 GB card
|
||||
small, big = F.plan(24, 128, chunk=256, ctx=32768), F.plan(24, 128, chunk=1024, ctx=32768)
|
||||
assert 0 < small["dyn_slots"] - big["dyn_slots"] < 0.1 * small["dyn_slots"]
|
||||
|
||||
@@ -254,10 +254,13 @@ class PlatformCodes(unittest.TestCase):
|
||||
|
||||
def test_intel_has_no_engine_until_the_family_names_the_backend(self):
|
||||
card = [{"vendor": "intel", "vram_gb": 16.0, "usable": True, "arch": "xe", "name": "Arc B70"}]
|
||||
# the Intel engine ships (0.2.25): the row says so and carries no "no Intel engine yet" note (GUI-LING's B70 app run found the note beside a working row)
|
||||
out = self.platform(card, 16.0, 64.0)
|
||||
self.assertEqual((out["backend"], out["engine_exists"], self.codes(out)[0]), ("sycl", False, "intel_no_engine"))
|
||||
with mock.patch.object(ling32_family, "BACKENDS", ling32_family.BACKENDS + ("sycl",)): # the day the SYCL engine exists: no app change
|
||||
self.assertTrue(self.platform(card, 16.0, 64.0)["engine_exists"])
|
||||
self.assertEqual((out["backend"], out["engine_exists"]), ("sycl", True))
|
||||
self.assertNotIn("intel_no_engine", self.codes(out))
|
||||
with mock.patch.object(ling32_family, "BACKENDS", tuple(b for b in ling32_family.BACKENDS if b != "sycl")), mock.patch.object(ling32_family, "SYCL_ENGINE_SHIPPED", False):
|
||||
off = self.platform(card, 16.0, 64.0) # the switches off: the old words
|
||||
self.assertEqual((off["engine_exists"], self.codes(off)[0]), (False, "intel_no_engine"))
|
||||
|
||||
def test_no_card_is_said_and_no_text_carries_a_speed_figure(self):
|
||||
out = self.platform([], None, 32.0)
|
||||
|
||||
@@ -333,6 +333,35 @@ class Mtp(unittest.TestCase):
|
||||
self.assertTrue(with_mtp)
|
||||
|
||||
|
||||
class WindowsChunkInTheTerminal(unittest.TestCase):
|
||||
"""Variant (c): the Terminal writes the same chunk as setup: 2048 for the 12 GB class and up on Windows too (no extra flag), 256 for the 8 GB class on Windows in tier C."""
|
||||
|
||||
def plan(self, vram, ram, pin_half):
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from strata_cli.launch import adopt
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root = Path(d)
|
||||
model = root / "models"
|
||||
model.mkdir()
|
||||
(model / ling32_family.MODEL_FILE).write_bytes(b"x")
|
||||
tok = root / "data" / "packs" / "ling-3.2-air-sq-96" / "tokenizer"
|
||||
tok.mkdir(parents=True)
|
||||
(tok / "vocab.json").write_text("{}")
|
||||
cfg, problems = adopt.plan(family="ling-3.2-air", model="SQ-96", model_dir=model, data_dir=root / "data", src=root, context=32768, kv=None, model_name="Ling", family_def={"name": "ling"},
|
||||
log=root / "x.log", backend="cuda", vram_gb=vram, ram_gb=ram, pin_half=pin_half, pack_name="ling-3.2-air-sq-96")
|
||||
self.assertEqual(problems, [])
|
||||
return cfg["args"]
|
||||
|
||||
def test_the_windows_rows(self):
|
||||
for vram, ram, pin, chunk in ((11.95, 64.0, True, "2048"), (15.9, 64.0, True, "2048"), (23.5, 64.0, True, "2048"), (11.95, 64.0, False, "2048"), (11.95, 192.0, True, "2048"),
|
||||
(7.8, 64.0, True, "256"), (7.8, 64.0, False, "2048"), (47.5, 64.0, True, "1024")):
|
||||
a = self.plan(vram, ram, pin)
|
||||
self.assertEqual(a[a.index("--chunk") + 1], chunk, (vram, ram, pin))
|
||||
self.assertNotIn("--regrow", a)
|
||||
self.assertNotIn("--vram-budget-gib", a)
|
||||
|
||||
|
||||
class Flags(unittest.TestCase):
|
||||
def parse(self, *argv):
|
||||
ap = argparse.ArgumentParser()
|
||||
@@ -582,13 +611,14 @@ class FamilyData(unittest.TestCase):
|
||||
def test_intel_cards_get_the_chunk_of_their_class_and_no_cuda_tuning_flags(self):
|
||||
# L32-SYCL: the 20 to 44 GiB class (the 32 GB B70) 2048 like everywhere, the 8 to 16 GiB cards (A750, B580) 1024 (the CUDA rule gives them 256: pool slots), no --tc / --graph / --mla-kernel
|
||||
self.assertEqual([ling32_fit.chunk_for(g, backend="sycl") for g in (8, 12, 15.9, 19.9, 20, 31.16, 43.9, 44, 96)], [1024, 1024, 1024, 1024, 2048, 2048, 2048, 1024, 1024])
|
||||
self.assertEqual([ling32_fit.chunk_for(g) for g in (8, 12, 15.9)], [256, 256, 2048]) # NVIDIA: the 16 GB class takes 2048 with the pool regrow
|
||||
self.assertEqual([ling32_fit.chunk_for(g) for g in (8, 12, 15.9)], [2048, 2048, 2048]) # NVIDIA: the 12 GB class (11.5 GiB and up) and the 16 GB class take 2048 with the pool regrow
|
||||
self.assertEqual([ling32_fit.chunk_for(g, backend="hip") for g in (8, 15.9, 23.5, 26.9, 27, 31.9, 43.9, 47.5)], [256, 1024, 1024, 1024, 2048, 2048, 2048, 1024]) # AMD: no 2048 below the 32 GB class (no pool regrow on a Radeon yet)
|
||||
self.assertEqual(ling32_fit.plan(23.5, 64.0, backend="hip")["chunk"], 1024)
|
||||
self.assertEqual(ling32_fit.plan(23.5, 64.0)["chunk"], 2048)
|
||||
self.assertEqual(ling32_fit.plan(8.0, 32.0, backend="sycl")["chunk"], 1024)
|
||||
self.assertEqual(ling32_fit.plan(31.16, 64.0, backend="sycl")["chunk"], 2048)
|
||||
self.assertEqual(ling32_fit.plan(8.0, 32.0)["chunk"], 256)
|
||||
self.assertEqual(ling32_fit.plan(8.0, 32.0)["chunk"], 2048) # the 8 GB class: 2048 since the loader-reserve fix (03006f62ed)
|
||||
self.assertEqual(ling32_fit.plan(5.9, 32.0)["chunk"], 256)
|
||||
from strata_cli.launch import adopt
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td:
|
||||
td = Path(td)
|
||||
@@ -626,7 +656,9 @@ class FamilyData(unittest.TestCase):
|
||||
return S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp=mtp), vram_gb=16.0, ram_gb=64.0, vendor="intel", cards=[{"vendor": "intel", "name": name}])
|
||||
b70 = notes("Intel Arc Pro B70 Graphics")
|
||||
self.assertEqual([n for n in b70 if "on Intel Arc:" in n.text], []) # the tested card: no card line
|
||||
self.assertEqual(len([n for n in b70 if "without MTP" in n.text]), 1) # MTP is not verified on Intel: said once
|
||||
self.assertEqual([n for n in b70 if "without MTP" in n.text], []) # MTP is verified on Intel: no such line
|
||||
with mock.patch.object(ling32_family, "SYCL_MTP_VERIFIED", False):
|
||||
self.assertEqual(len([n for n in notes("Intel Arc Pro B70 Graphics") if "without MTP" in n.text]), 1) # the switch off: said once
|
||||
self.assertEqual([n for n in notes("Intel Arc Pro B70 Graphics", mtp="on") if "without MTP" in n.text], [])
|
||||
a750 = notes("Intel Arc A750 Graphics")
|
||||
self.assertEqual(len([n for n in a750 if "on Intel Arc:" in n.text]), 1)
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Qwen3.8-Flash-Next on a Windows Intel Arc card (prepared for 0.2.25 while QFN-B70's gate runs; the switch intel_app.QWEN_SYCL_WINDOWS_SHIPPED stays False until it passes).
|
||||
|
||||
What these tests pin (QFN-B70's tested flags, literally):
|
||||
* the run config on Windows: --prefill 4096, --kv int8, --vram-reserve-mib 1024 (2048 above 32K), --stream-experts, --expert-cache auto and --spec 2 written explicitly (the sysfs rule cannot fire there), no
|
||||
--spec-min-p, no --mtp; the Coder pack gets expert-profile-coder.bin, every other pack expert-profile-sycl.bin;
|
||||
* Linux keeps its flags (--prefill auto, --spec 4, --spec-min-p 0.5);
|
||||
* the Windows route is offered for the gated packs only (QWEN_SYCL_WINDOWS_PACKS: IQ1_M with --spec 2 and the suffix drafter, IQ2_XS and IQ3_S with --spec 2 --suffix-draft 0 = plain decode), and only when the switch is on.
|
||||
Offline: nothing runs but Python."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tools"))
|
||||
import setup # noqa: E402
|
||||
from strata_cli.launch import adopt # noqa: E402
|
||||
from strata_control import intel_app # noqa: E402
|
||||
|
||||
|
||||
class Tree:
|
||||
def __init__(self, root: Path, family: str, pack_name: str):
|
||||
self.root, self.family = root, family
|
||||
self.data = root / "Strata-data"
|
||||
self.pack = self.data / "packs" / pack_name
|
||||
(self.pack / "tokenizer").mkdir(parents=True)
|
||||
(self.pack / "tokenizer" / "vocab.json").write_text("{}")
|
||||
(self.pack / "index.txt").write_text("x")
|
||||
self.models = root / "models"
|
||||
self.models.mkdir()
|
||||
self.src = root / "control"
|
||||
(self.src / "data").mkdir(parents=True)
|
||||
for name in ("expert-profile.bin", "expert-profile-coder.bin", "expert-profile-sycl.bin"):
|
||||
(self.src / "data" / name).write_bytes(b"STRP")
|
||||
for i in (1, 2):
|
||||
(self.models / f"Qwen3.8-Flash-Next-GSQ-RCO-{pack_name.split('-')[-1].upper()}-0000{i}-of-00002.gguf").write_bytes(b"x")
|
||||
|
||||
def plan(self, model: str, platform: str, context: int = 32768, vram_gb: float = 32.0, drafting=None):
|
||||
fam = setup.FAMILIES[self.family]
|
||||
return adopt.plan(family=self.family, model=model, model_dir=self.models, data_dir=self.data, src=self.src, context=context, kv="int8",
|
||||
model_name=f"{fam.get('name', self.family)}-{model.lower()}", family_def=fam, log=self.root / "x.log", backend="sycl",
|
||||
pack_name=self.pack.name, vram_gb=vram_gb, platform=platform, drafting=drafting)
|
||||
|
||||
|
||||
def value(args, flag):
|
||||
return args[args.index(flag) + 1]
|
||||
|
||||
|
||||
class WindowsFlags(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
p = mock.patch("strata_cli.launch.adopt.intel_driver", lambda: "") # Windows: no kernel driver to read, so the xe route (--stream-experts)
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def test_coder_iq1_m_gets_the_tested_flags_and_its_own_profile(self):
|
||||
t = Tree(self.root, "coder", "coder-iq1_m")
|
||||
(t.data / "mtp" / "rt").mkdir(parents=True) # a draft layer on the PC is not passed on Windows Intel
|
||||
cfg, problems = t.plan("IQ1_M", "win32")
|
||||
self.assertEqual(problems, [])
|
||||
a = cfg["args"]
|
||||
self.assertEqual(value(a, "--expert-profile"), str(t.src / "data" / "expert-profile-coder.bin"))
|
||||
self.assertEqual((value(a, "--prefill"), value(a, "--spec"), value(a, "--kv"), value(a, "--vram-reserve-mib"), value(a, "--expert-cache")), ("4096", "2", "int8", "1024", "auto"))
|
||||
self.assertIn("--stream-experts", a)
|
||||
self.assertNotIn("--spec-min-p", a)
|
||||
self.assertNotIn("--suffix-draft", a) # Coder IQ1_M keeps the suffix drafter (the engine's default)
|
||||
self.assertNotIn("--mtp", a)
|
||||
self.assertEqual(cfg["backend"], "sycl")
|
||||
|
||||
def test_the_reserve_is_2048_above_32k_and_other_packs_use_the_sycl_profile(self):
|
||||
t = Tree(self.root, "qwen", "iq2_xs")
|
||||
cfg, problems = t.plan("IQ2_XS", "win32", context=65536)
|
||||
self.assertEqual(problems, [])
|
||||
a = cfg["args"]
|
||||
self.assertEqual(value(a, "--vram-reserve-mib"), "2048")
|
||||
self.assertEqual(value(a, "--expert-profile"), str(t.src / "data" / "expert-profile-sycl.bin"))
|
||||
self.assertEqual((value(a, "--spec"), value(a, "--prefill")), ("2", "4096"))
|
||||
self.assertNotIn("--suffix-draft", a) # IQ2_XS: fast mode by default (DFlash2 at Load, owner 2026-12-03); plain decode is the Off choice or the constant
|
||||
cfg2, _p = t.plan("IQ2_XS", "win32", context=65536, drafting="off")
|
||||
self.assertEqual(value(cfg2["args"], "--suffix-draft"), "0") # Off: the plain decode (a 2-token window, no draft proposed)
|
||||
from strata_control import drafting
|
||||
with mock.patch.object(drafting, "INTEL_PLAIN_BY_DEFAULT", True):
|
||||
cfg3, _p = t.plan("IQ2_XS", "win32", context=65536)
|
||||
self.assertEqual(value(cfg3["args"], "--suffix-draft"), "0") # the constant: plain by default again
|
||||
self.assertNotIn("--spec-min-p", a)
|
||||
|
||||
def test_linux_keeps_its_flags(self):
|
||||
t = Tree(self.root, "coder", "coder-iq1_m")
|
||||
cfg, problems = t.plan("IQ1_M", "linux")
|
||||
self.assertEqual(problems, [])
|
||||
a = cfg["args"]
|
||||
self.assertEqual((value(a, "--prefill"), value(a, "--spec"), value(a, "--spec-min-p")), ("auto", "4", "0.5"))
|
||||
self.assertEqual(value(a, "--expert-profile"), str(t.src / "data" / "expert-profile-coder.bin"))
|
||||
|
||||
|
||||
class WindowsRoute(unittest.TestCase):
|
||||
def test_only_the_gated_pack_is_offered_and_only_with_the_switch_on(self):
|
||||
self.assertEqual(intel_app.QWEN_SYCL_WINDOWS_PACKS, {"IQ1_M": True, "IQ2_XS": False, "IQ3_S": False}) # the pack -> the suffix drafter (off where spec 2 is not bit-equal to plain decode)
|
||||
self.assertTrue(intel_app.QWEN_SYCL_WINDOWS_SHIPPED)
|
||||
for pack in ("IQ1_M", "IQ2_XS", "IQ3_S"):
|
||||
self.assertTrue(intel_app.route_here("qwen", "win32", pack), pack)
|
||||
self.assertTrue(intel_app.route_here("qwen", "win32")) # no model named: the family
|
||||
for pack in ("IQ3_XXS", "Q2_0"):
|
||||
self.assertFalse(intel_app.route_here("qwen", "win32", pack), pack)
|
||||
self.assertTrue(intel_app.route_here("ling32", "win32", "IQ3_S")) # other families ignore the pack name
|
||||
self.assertTrue(intel_app.route_here("qwen", "win32", "IQ3_S", "qwen") and intel_app.route_here("qwen", "win32", "IQ1_M", "coder"))
|
||||
for fam in ("swift", "gyro", "unsloth"): # same pack names, not gated
|
||||
self.assertFalse(intel_app.route_here("qwen", "win32", "IQ3_S", fam), fam)
|
||||
with mock.patch.object(intel_app, "QWEN_SYCL_WINDOWS_SHIPPED", False):
|
||||
self.assertFalse(intel_app.route_here("qwen", "win32", "IQ1_M")) # the one word that turns it off
|
||||
for pack in ("IQ1_M", "IQ2_XS", "IQ3_S", "IQ3_XXS", "Q2_0"):
|
||||
self.assertTrue(intel_app.route_here("qwen", "linux", pack), pack) # Linux: every pack
|
||||
|
||||
|
||||
class PlainDecodeOnIntel(unittest.TestCase):
|
||||
"""IQ2_XS and IQ3_S on the SYCL engine on Windows: fast mode (DFlash2) by default since the owner's decision of 2026-12-03 (drafting.INTEL_PLAIN_BY_DEFAULT = False), like Linux Arc. The plain-decode machinery stays behind
|
||||
the constant (Auto = no drafter on a platform of INTEL_PLAIN_PLATFORMS), and Off is the plain decode in the install's flags."""
|
||||
|
||||
NAMES = ("qwen3.8-flash-next-iq2_xs", "qwen3.8-flash-next-iq3_s")
|
||||
|
||||
def setUp(self):
|
||||
from strata_control import drafting
|
||||
p = mock.patch.object(drafting, "_host_platform", lambda: "win32")
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def test_the_default_is_fast_mode_on_windows_intel(self):
|
||||
from strata_control import drafting
|
||||
self.assertFalse(drafting.INTEL_PLAIN_BY_DEFAULT)
|
||||
for name in self.NAMES:
|
||||
self.assertFalse(drafting.intel_plain("sycl", name), name)
|
||||
d = drafting.decide("auto", model_name=name, backend="sycl", data_dir=None, mtp_here=False)
|
||||
self.assertEqual(d.drafter, drafting.decide("auto", model_name=name, backend="sycl", data_dir=None, mtp_here=False).drafter)
|
||||
self.assertNotEqual(drafting.choice_of("auto", model_name=name, backend="sycl"), "off") # the engine's own Auto rule: DFlash2 where it runs, else the MTP
|
||||
|
||||
def test_the_constant_brings_plain_back_and_leaves_the_other_cards_alone(self):
|
||||
from strata_control import drafting
|
||||
with mock.patch.object(drafting, "INTEL_PLAIN_BY_DEFAULT", True):
|
||||
for name in self.NAMES:
|
||||
self.assertTrue(drafting.intel_plain("sycl", name), name)
|
||||
self.assertEqual(drafting.choice_of("auto", model_name=name, backend="sycl"), "off")
|
||||
d = drafting.decide("auto", model_name=name, backend="sycl", data_dir=None, mtp_here=False)
|
||||
self.assertEqual((d.drafter, d.note, d.flags), ("off", "", ()))
|
||||
for backend in ("cuda", "hip", "metal", None):
|
||||
self.assertFalse(drafting.intel_plain(backend, name), (backend, name))
|
||||
for name in ("qwen3.8-flash-next-q2_0", "qwen3.8-flash-next-coder-iq1_m", "swift-iq3_s", None):
|
||||
self.assertFalse(drafting.intel_plain("sycl", name), name)
|
||||
with mock.patch.object(drafting, "_host_platform", lambda: "linux"):
|
||||
self.assertFalse(drafting.intel_plain("sycl", self.NAMES[0])) # platforms: Windows only
|
||||
|
||||
def test_a_named_drafter_and_off_are_the_persons_own(self):
|
||||
from strata_control import drafting
|
||||
name = self.NAMES[0]
|
||||
self.assertEqual(drafting.choice_of("mtp", model_name=name, backend="sycl"), "mtp")
|
||||
self.assertEqual(drafting.choice_of("off", model_name=name, backend="sycl"), "off")
|
||||
self.assertEqual(drafting.choice_of("dflash2", model_name=name, backend="sycl"), "dflash2")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -81,7 +81,7 @@ def main(argv=None) -> int:
|
||||
if args[:1] == ["--info"]: # `exe --info FILE --kv`: the facts serve reads before a start
|
||||
caps = caps_of(os.environ)
|
||||
if "--kv" in args:
|
||||
say(f"arch=ling32 layers=42 vocab=157184 drafter=none images={caps.get('images', '0')} tiers=A,B,C" + (" mtp=1" if caps.get("mtp") == "1" else "") + (" mtp_auto=1" if caps.get("mtp_auto") == "1" else ""))
|
||||
say(f"arch=ling32 layers=42 vocab=157184 drafter=none images={caps.get('images', '0')}" + (f" vision={caps['vision']}" if caps.get("vision") in ("gpu", "cpu") else "") + " tiers=A,B,C" + (" mtp=1" if caps.get("mtp") == "1" else "") + (" mtp_auto=1" if caps.get("mtp_auto") == "1" else ""))
|
||||
else:
|
||||
say("arch=ling32 model=Ling-3.2-Air layers=42 kda=35 mla=7 dense=2 moe=40 hidden=2560 vocab=157184 experts=512 top_k=8 ctx_max=262144")
|
||||
return 0
|
||||
|
||||
@@ -573,6 +573,15 @@ def system_folders() -> list[Path]:
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ Strata
|
||||
def _intel_route_here(md: dict | None = None, model: str | None = None, family: str | None = None) -> bool:
|
||||
"""Can the Intel route of this model family run on this PC (strata_control/intel_app.py route_here: Linux, or the family's Windows switch)? Never raises."""
|
||||
try:
|
||||
from strata_control import intel_app
|
||||
return bool(intel_app.route_here(intel_app.family_kind(md), model=model, family=family))
|
||||
except Exception: # noqa: BLE001
|
||||
return True
|
||||
|
||||
|
||||
class Strata:
|
||||
"""One Strata folder: what is installed there, the PC, and the processes this server started."""
|
||||
|
||||
@@ -770,7 +779,9 @@ class Strata:
|
||||
vram_gib, ram_gib, unified = None, float(uma.get("vram_gb") or ram) / ling32_fit.GIB_TO_GB, True
|
||||
else:
|
||||
vram_gib, ram_gib, unified = max((float(g["vram_gb"]) for g in usable), default=0.0), float(ram), False
|
||||
adv = ling32_fit.advise(vram_gib, ram_gib, unified=unified, ctx=ctx, vision=vision)
|
||||
vendor = str(next((g.get("vendor") for g in usable if g.get("vendor")), "") or "").lower()
|
||||
backend = {"amd": "hip", "intel": "sycl", "apple": "metal"}.get(vendor, "cuda") # the chunk and the words of the card's engine (an Intel card: the SYCL engine, pictures read on the processor in the plan)
|
||||
adv = ling32_fit.advise(vram_gib, ram_gib, unified=unified, ctx=ctx, vision=vision, vision_device="cpu" if backend == "sycl" else "auto", backend=backend)
|
||||
p = adv["plan"]
|
||||
return {"tier": adv["tier"], "placement": {"vram_gb": p["vram_gb"], "ram_gb": p["ram_gb"], "ssd_gb": p["ssd_gb"]}, "mode": "cross_tier_ssd" if p["mode"] == "C" else "ram_vram_zero_ssd",
|
||||
"speed": adv["speed"], "recommended": True, "unified": unified, "context": p["ctx"], "warnings": adv["warnings"], "feasible": bool(p["ok"]), "vision": p["vision"],
|
||||
@@ -787,8 +798,10 @@ class Strata:
|
||||
vendor = str((card or {}).get("vendor") or "").lower()
|
||||
notes: list[dict] = []
|
||||
backend = {"apple": "metal", "amd": "hip", "intel": "sycl"}.get(vendor, "cuda")
|
||||
engine_exists = backend in ling32_family.BACKENDS or (backend == "sycl" and bool(getattr(ling32_family, "SYCL_ENGINE_SHIPPED", False))) # Intel lights up when the family says its engine ships
|
||||
if backend == "sycl":
|
||||
notes.append({"code": "intel_no_engine"})
|
||||
if not engine_exists: # the note follows the same test as engine_exists (a shipped Intel engine has no "no engine yet")
|
||||
notes.append({"code": "intel_no_engine"})
|
||||
elif backend == "hip":
|
||||
level, _words = ling32_family.hip_support((card or {}).get("arch"))
|
||||
if level != "tested":
|
||||
@@ -806,7 +819,7 @@ class Strata:
|
||||
if backend != "metal" and ling32_fit.mtp_small_card(vram_gib, unified):
|
||||
notes.append({"code": "mtp_off_small_card"})
|
||||
# engine_exists: Intel lights up when the family says its engine ships (SYCL_ENGINE_SHIPPED)
|
||||
return {"backend": backend, "engine_exists": backend in ling32_family.BACKENDS or (backend == "sycl" and bool(getattr(ling32_family, "SYCL_ENGINE_SHIPPED", False))), "notes": notes, "mtp_default": ling32_fit.mtp_wanted(None, default_on=ling32_family.DEFAULT_MTP, vram_gib=vram_gib, unified=unified),
|
||||
return {"backend": backend, "engine_exists": engine_exists, "notes": notes, "mtp_default": ling32_fit.mtp_wanted(None, default_on=ling32_family.DEFAULT_MTP, vram_gib=vram_gib, unified=unified),
|
||||
"mac": backend == "metal", "mac_advice": ling32_family.metal_ram_advice() if backend == "metal" else None}
|
||||
|
||||
def ling32_size(self, family, model) -> dict | None:
|
||||
@@ -1482,7 +1495,7 @@ class Strata:
|
||||
except Exception: # noqa: BLE001 - an older Control folder: no field, the app keeps its own floor
|
||||
pass
|
||||
arc = []
|
||||
if not WIN: # an Intel Arc (Linux, the SYCL engine): only a PC with no usable NVIDIA or AMD card gets one (strata_control/intel_app.py)
|
||||
if True: # an Intel Arc (the SYCL engine; Linux, and Windows since Ling on Intel ships): only a PC with no usable NVIDIA or AMD card gets one (strata_control/intel_app.py cards_to_add decides the platform)
|
||||
try:
|
||||
if str(self.src) not in sys.path:
|
||||
sys.path.insert(0, str(self.src))
|
||||
@@ -1824,7 +1837,8 @@ class Strata:
|
||||
notes.append("AMD (experimental): pictures are on; the reader runs on the CPU under 24 GB of VRAM and on the GPU from 24 GB")
|
||||
if backend == "sycl":
|
||||
from strata_control import intel_app
|
||||
notes.append(intel_app.NO_DOWNLOAD)
|
||||
if not intel_app.can_download(fam, model, families.get(fam)): # Ling, Inkling and the gated Qwen packs download; the rest stay on "use your own files"
|
||||
notes.append(intel_app.NO_DOWNLOAD)
|
||||
cmd = (("START-HERE.bat --setup" if WIN else "./setup.sh --setup") +
|
||||
f" --yes --family {fam} --model {model} --context {ctx}" + (f" --backend {backend}" if backend in ("hip", "sycl") else ""))
|
||||
return {"family": fam, "model": model, "title": families[fam]["title"] + " " + model, "context": ctx,
|
||||
@@ -1874,7 +1888,9 @@ class Strata:
|
||||
memory_gb, fit_gb = d["footprint_gb"], d["footprint_gb"]
|
||||
ink = self.inkling_fit_row(m, ram, usable)
|
||||
verdict = None if ink is None else ("may run slower" if ink["mode"] == "cross_tier_ssd" else "fits")
|
||||
intel_blocked = any(g.get("vendor") == "intel" for g in usable) and not _intel_route_here(d, m, f)
|
||||
sizes.append({"model": m, "about": d["about"], "download_gb": d["download_gb"],
|
||||
**({"offered": False, "offered_note": "No Intel Arc engine for Windows yet for this model: it runs on Linux; Ling-3.2-Air, Inkling-2-Mini and the Qwen3.8-Flash-Next Coder IQ1_M, IQ2_XS and IQ3_S sizes run on an Arc card on Windows."} if intel_blocked else {}),
|
||||
**({"hy4": hy4} if hy4 else {}),
|
||||
**({"inkling": ink} if ink else {}),
|
||||
**({"ling32": ling} if ling else {}),
|
||||
@@ -2991,19 +3007,22 @@ class Tools:
|
||||
have_dir = target / "models" / tag
|
||||
ready_dir = ready_pack_dir(target, md) # a ready-made pack (NVFP4): setup keeps it under <owner>--<repo>, not under the family tag (#4892)
|
||||
# An Intel Arc (Linux, the SYCL engine): setup.py's `--backend sycl` in its CONTROL mode prepares the model's files and writes the run config, as the
|
||||
# Terminal does (strata_control/intel_app.py); it downloads nothing. NVIDIA and AMD never come here.
|
||||
# Terminal does (strata_control/intel_app.py); it downloads the files that are not there when intel_app.can_download says so (the gated Qwen packs). NVIDIA and AMD never come here.
|
||||
arc = backend == "sycl" or (backend in (None, "auto") and any(g.get("vendor") == "intel" for g in hw.get("gpus", [])))
|
||||
if arc:
|
||||
from strata_control import intel_app
|
||||
if mac or not intel_app.supported_here() or not any(g.get("vendor") == "intel" for g in hw.get("gpus", [])):
|
||||
raise ToolError("no Intel Arc card Strata can use was found in this computer (the Intel Arc engine runs on Linux)")
|
||||
if not intel_app.can_set_up(family, families[family]):
|
||||
ling_arc = bool(md.get("ling32")) # Ling-3.2-Air: its own Intel engine (setup.py routes it before the GGUF route)
|
||||
if mac or not any(g.get("vendor") == "intel" for g in hw.get("gpus", [])):
|
||||
raise ToolError("no Intel Arc card Strata can use was found in this computer")
|
||||
if not intel_app.route_here(intel_app.family_kind(md), model=model, family=family):
|
||||
raise ToolError(f"{families[family]['title']} {model} has no Intel Arc engine for Windows yet (it runs on Linux); Ling-3.2-Air, Inkling-2-Mini and the Qwen3.8-Flash-Next Coder IQ1_M, IQ2_XS and IQ3_S sizes run on an Arc card on Windows")
|
||||
if not ling_arc and not intel_app.can_set_up(family, families[family]):
|
||||
raise ToolError(f"{families[family]['title']} {model} can't be set up for an Intel Arc card yet; "
|
||||
"the Qwen3.8-Flash-Next, Swift, Coder, Gyro, Unsloth, Hy4-Flash and Inkling-2-Mini sizes can")
|
||||
backend = "sycl"
|
||||
if not md.get("hy4") and not md.get("inkling"):
|
||||
if not md.get("hy4") and not md.get("inkling") and not md.get("ling32"):
|
||||
vision = "no" # pictures stay off on an Arc for GGUF families (strata_cli/launch/adopt.py)
|
||||
if not gguf_dir and not intel_app.model_files_in(have_dir, family, families[family]):
|
||||
if not gguf_dir and not intel_app.model_files_in(have_dir, family, families[family]) and not intel_app.can_download(family, model, families[family]):
|
||||
raise ToolError(intel_app.NO_DOWNLOAD)
|
||||
if md.get("hy4") and md.get("gguf"): # AngelSlim's GGUF build: both shards and the picture reader in <models>/hy4-flash; a folder of the person's own files downloads nothing
|
||||
from strata_control import hy4_gguf
|
||||
|
||||
@@ -117,8 +117,13 @@ class VendorNotices(unittest.TestCase):
|
||||
self.assertTrue(notice.startswith("Intel oneAPI runtime libraries"))
|
||||
self.assertIn("libiomp5.so <- " + str(iomp), notice)
|
||||
self.assertNotIn("libstdc++", notice)
|
||||
self.assertEqual((out / "licenses" / "intel-oneapi-license.txt").read_text(encoding="utf-8"), "INTEL LICENSE TEXT\n")
|
||||
self.assertEqual((out / "licenses" / "intel-oneapi-third-party-programs.txt").read_text(encoding="utf-8"), "THIRD PARTY TEXT\n")
|
||||
# the licence texts are the CHECKED-IN set of tools/packaging/notices/intel-oneapi/<platform>/ (never the build machine's: a package must not depend on it), byte for byte
|
||||
import lib_notices
|
||||
texts = lib_notices.intel_license_files("linux")
|
||||
self.assertTrue(texts)
|
||||
for src in texts:
|
||||
self.assertEqual((out / "licenses" / src.name).read_bytes(), src.read_bytes(), src.name)
|
||||
self.assertFalse((out / "licenses" / "intel-oneapi-license.txt").exists()) # the installation's own licence files are no longer copied
|
||||
|
||||
def test_add_notices_writes_licenses_for_a_staging_folder(self):
|
||||
import tempfile
|
||||
@@ -133,7 +138,7 @@ class VendorNotices(unittest.TestCase):
|
||||
(root / "licensing" / "2026.1" / "license.txt").write_text("L\n", encoding="utf-8")
|
||||
wrote = add_notices.add(stage, [str(root)])
|
||||
self.assertIn("licenses/intel-oneapi.txt", wrote)
|
||||
self.assertIn("licenses/intel-oneapi-license.txt", wrote)
|
||||
self.assertIn("licenses/intel-oneapi-license.htm", wrote) # a checked-in oneAPI licence text (tools/packaging/notices/intel-oneapi/)
|
||||
self.assertIn("licenses/microsoft-vc-runtime.txt", wrote)
|
||||
text = (stage / "licenses" / "intel-oneapi.txt").read_text(encoding="utf-8")
|
||||
self.assertIn("libiomp5.so", text)
|
||||
|
||||
@@ -360,8 +360,12 @@ class EngineArgs(unittest.TestCase):
|
||||
self.assertEqual(args, ["--ctx", "32768", "--chunk", "4096", "--tc", "16", "--tc-moe", "128", "--graph", "--mla-kernel", "simt"])
|
||||
|
||||
def test_a_small_card_gets_a_small_chunk_and_the_plan_is_in_the_result(self):
|
||||
args, adv = setup.ling32_engine_args(ns(), 8.0, 16.0, False, 32768)
|
||||
self.assertEqual(args[args.index("--chunk") + 1], "256")
|
||||
args, adv = setup.ling32_engine_args(ns(), 5.9, 16.0, False, 32768)
|
||||
self.assertEqual(args[args.index("--chunk") + 1], "256") # a 6 GB card: the small chunk
|
||||
args, adv = setup.ling32_engine_args(ns(), 8.0, 16.0, False, 32768, pin_half=False)
|
||||
self.assertEqual(args[args.index("--chunk") + 1], "2048") # the 8 GB class on Linux: 2048 (the loader-reserve fix)
|
||||
args, adv = setup.ling32_engine_args(ns(), 8.0, 64.0, False, 32768, pin_half=True)
|
||||
self.assertEqual(args[args.index("--chunk") + 1], str(setup.ling32_fit.WINDOWS_TIER_C_CHUNK)) # Windows in tier C: the one constant
|
||||
self.assertEqual(adv["tier"], "C")
|
||||
self.assertNotIn("--tier", args) # auto: the engine plans by itself with the same rule
|
||||
|
||||
@@ -452,8 +456,17 @@ class Install(unittest.TestCase):
|
||||
for flag in ("--graph", "--tc", "--tc-moe", "--mla-kernel"):
|
||||
self.assertNotIn(flag, cfg["args"]) # the SYCL engine ignores them: they stay out of the arguments
|
||||
self.assertEqual(cfg["args"][cfg["args"].index("--ctx") + 1], "65536")
|
||||
self.assertEqual(cfg["args"][cfg["args"].index("--vision-device") + 1], "cpu") # no GPU picture encoder on Intel yet
|
||||
self.assertNotIn(ling32_family.MTP_CONFIG_KEY, cfg) # MTP is not verified on Intel: off unless asked
|
||||
self.assertNotIn("--vision-device", cfg["args"]) # the engine chooses where it reads pictures (its vision= word); the plan counts the processor
|
||||
with mock.patch.object(ling32_family, "SYCL_ENGINE_SHIPPED", True), mock.patch.object(ling32_family, "SYCL_VISION_DEVICE", "cpu"): # the one-word fallback
|
||||
_, w2, _, _ = self.run_install(backend="sycl", gpu_name="Intel Arc Pro B70", vram_gb=32.0, vision_beside=True)
|
||||
a2 = w2["cfg"]["args"]
|
||||
self.assertEqual(a2[a2.index("--vision-device") + 1], "cpu")
|
||||
self.assertEqual(a2[a2.index("--vision-max-pixels") + 1], "1000000")
|
||||
self.assertIn(ling32_family.MTP_CONFIG_KEY, cfg) # MTP is verified on Intel (SYCL_MTP_VERIFIED): the sidecar, mode auto (the engine's controller decides)
|
||||
self.assertEqual(cfg.get(ling32_family.MTP_MODE_KEY), "auto")
|
||||
with mock.patch.object(ling32_family, "SYCL_ENGINE_SHIPPED", True), mock.patch.object(ling32_family, "SYCL_MTP_VERIFIED", False):
|
||||
_, w3, _, _ = self.run_install(backend="sycl", gpu_name="Intel Arc Pro B70", vram_gb=32.0, mtp_beside=True)
|
||||
self.assertNotIn(ling32_family.MTP_CONFIG_KEY, w3["cfg"]) # the switch off: off unless asked
|
||||
self.assertFalse(any(s.startswith("warn Intel Arc") for s in says)) # the B70 is the tested card
|
||||
self.assertTrue(any("Memory plan for this PC: tier" in s for s in says))
|
||||
|
||||
@@ -463,7 +476,8 @@ class Install(unittest.TestCase):
|
||||
args = w["cfg"]["args"]
|
||||
return (args[args.index("--vision-max-pixels") + 1] if "--vision-max-pixels" in args else None), says
|
||||
with mock.patch.object(ling32_family, "SYCL_ENGINE_SHIPPED", True):
|
||||
self.assertEqual(cap(backend="sycl", gpu_name="Intel Arc Pro B70", vram_gb=32.0)[0], "1000000") # Intel: no GPU encoder yet
|
||||
self.assertIsNone(cap(backend="sycl", gpu_name="Intel Arc Pro B70", vram_gb=32.0)[0]) # Intel: serve adds the cap at the start unless the engine says vision=gpu (serve test)
|
||||
self.assertTrue(any("downscaled to about 1 megapixel" in s for s in cap(backend="sycl", gpu_name="Intel Arc Pro B70", vram_gb=32.0)[1])) # and setup says so
|
||||
self.assertEqual(cap(vram_gb=12.0)[0], "1000000") # a card under 24 GiB: the engine picks the CPU encoder
|
||||
self.assertEqual(cap(vram_gb=32.0, vision="cpu")[0], "1000000") # any --vision-device cpu
|
||||
self.assertIsNone(cap(vram_gb=32.0)[0]) # CUDA with the GPU encoder: uncapped
|
||||
@@ -705,7 +719,7 @@ class Install(unittest.TestCase):
|
||||
rc, w, says, _ = self.run_install(vram_gb=8.0, ram=16)
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertTrue(any("warn" in s and "read from the SSD" in s for s in says))
|
||||
self.assertEqual(w["cfg"]["args"][w["cfg"]["args"].index("--chunk") + 1], "256")
|
||||
self.assertEqual(w["cfg"]["args"][w["cfg"]["args"].index("--chunk") + 1], str(setup.ling32_fit.WINDOWS_TIER_C_CHUNK) if setup.WIN else "2048") # 8 GB: 2048, Windows tier C the constant
|
||||
|
||||
|
||||
class ConfigAndCatalog(unittest.TestCase):
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the Windows Intel Arc (SYCL) engine package of the Qwen3.8-Flash-Next engine (strata.exe, entry strata-engine). Local only: nothing is uploaded.
|
||||
|
||||
python tools/packaging/build_sycl_windows.py --oneapi C:/oneapi --vcvars "C:/.../VC/Auxiliary/Build/vcvars64.bat" --out out-engine-sycl-win
|
||||
python tools/packaging/build_sycl_windows.py --oneapi ... --vcvars ... --exe C:/path/strata.exe --out ... # package a strata.exe that is already built
|
||||
|
||||
Without --exe it configures and builds engine/sycl (icx 2026.x under the Visual Studio environment of --vcvars, AOT for --aot, default bmg-g31 = Arc Pro B70)
|
||||
with `-DSTRATA_SYCL_PARITY=OFF` and no oneMKL (the Windows build uses the engine's own XMX dense GEMM), at most --jobs compile jobs (default 8: the AOT device
|
||||
code is memory hungry; start with 20 GB of RAM free). Then it stages strata.exe + BUILD.json + licences, copies the Unified Runtime adapters (ur_*.dll,
|
||||
umf*.dll: loaded by name at run time), lets package_engine.py bundle everything strata.exe imports (sycl9.dll and its friends from the oneAPI runtime, the
|
||||
Visual C++ runtime), and checks the result with package_engine.py --verify and binary_deps.py. The Level Zero loader (ze_loader.dll) and the compute runtime stay the
|
||||
PC's own (the Intel graphics driver). The package runs with a minimal PATH and no ONEAPI_ROOT: `--smoke` does that (strata.exe --help under `cmd /c` with PATH=System32 only).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PACK = REPO / "tools" / "packaging"
|
||||
|
||||
|
||||
def engine_version() -> str:
|
||||
text = (REPO / "engine" / "CMakeLists.txt").read_text(encoding="utf-8", errors="replace")
|
||||
m = re.search(r"^\s*project\s*\([^)]*VERSION\s+([0-9][0-9.]*)", text, re.M)
|
||||
if not m:
|
||||
raise SystemExit("build_sycl_windows.py: no project VERSION in engine/CMakeLists.txt")
|
||||
return m.group(1)
|
||||
|
||||
|
||||
def run(cmd: list[str], vcvars: str | None, setvars: str | None, cwd: Path | None = None) -> None:
|
||||
if vcvars:
|
||||
line = 'call "{}" >nul && '.format(vcvars.replace("/", "\\"))
|
||||
if setvars:
|
||||
line += 'call "{}" --force >nul && '.format(setvars.replace("/", "\\"))
|
||||
line += subprocess.list2cmdline(cmd)
|
||||
print("+", line, flush=True)
|
||||
subprocess.run('cmd /d /s /c "' + line + '"', check=True, cwd=cwd)
|
||||
else:
|
||||
print("+", subprocess.list2cmdline(cmd), flush=True)
|
||||
subprocess.run(cmd, check=True, cwd=cwd)
|
||||
|
||||
|
||||
def vc_redist_dirs(vcvars: str) -> list[str]:
|
||||
""".../VC/Redist/MSVC/<newest>/x64/Microsoft.VC14x.CRT of the Visual Studio of `vcvars` (msvcp140, vcruntime140, vcruntime140_1)."""
|
||||
if not vcvars:
|
||||
return []
|
||||
vc = Path(vcvars).resolve().parents[2]
|
||||
found = sorted((vc / "Redist" / "MSVC").glob("*/x64/Microsoft.VC*.CRT"))
|
||||
return [str(found[-1])] if found else []
|
||||
|
||||
|
||||
def smoke(folder: Path, exe_name: str) -> int:
|
||||
"""strata.exe --help with a minimal PATH (System32 only) and ONEAPI_ROOT empty: every DLL must come from the package (or the OS / driver)."""
|
||||
env = {"SystemRoot": os.environ.get("SystemRoot", r"C:\Windows"), "PATH": os.environ.get("SystemRoot", r"C:\Windows") + r"\System32", "ONEAPI_ROOT": ""}
|
||||
r = subprocess.run([str(folder / exe_name), "--help"], capture_output=True, text=True, timeout=120, env=env, cwd=str(folder))
|
||||
first = (r.stdout or r.stderr).strip().splitlines()[:1]
|
||||
print("smoke:", exe_name, "--help with PATH=System32 and ONEAPI_ROOT empty ->", r.returncode, first)
|
||||
return 0 if first and "strata generate" in first[0] else 1
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--oneapi", required=True, help="the Intel oneAPI folder (setvars.bat, compiler/latest/bin; DPC++ icx 2026.x)")
|
||||
ap.add_argument("--vcvars", required=True, help="vcvars64.bat of Visual Studio")
|
||||
ap.add_argument("--aot", default="bmg-g31", help="the AOT device list of the GPU code, e.g. bmg-g31 (Arc Pro B70); the Windows package has no SPIR-V fallback")
|
||||
ap.add_argument("--exe", type=Path, default=None, help="package this strata.exe instead of building (its build must be the Windows no-oneMKL one)")
|
||||
ap.add_argument("--build-dir", type=Path, default=None)
|
||||
ap.add_argument("--out", type=Path, default=None)
|
||||
ap.add_argument("--jobs", type=int, default=8)
|
||||
ap.add_argument("--python", default=sys.executable)
|
||||
ap.add_argument("--extra-cmake", default="")
|
||||
ap.add_argument("--smoke", action="store_true", help="after packaging, run the minimal-PATH check")
|
||||
a = ap.parse_args(argv)
|
||||
|
||||
ver = engine_version()
|
||||
setvars = str(Path(a.oneapi) / "setvars.bat")
|
||||
if not Path(setvars).is_file():
|
||||
ap.error(f"no setvars.bat in {a.oneapi}")
|
||||
out = a.out or REPO / "out-engine-sycl-win"
|
||||
build = a.build_dir or REPO / "engine" / "build-sycl-win"
|
||||
exe = a.exe
|
||||
if exe is None:
|
||||
cfg = ["-DCMAKE_BUILD_TYPE=Release", "-DCMAKE_C_COMPILER=icx", "-DCMAKE_CXX_COMPILER=icx", "-DSTRATA_SYCL_PARITY=OFF", f"-DSTRATA_SYCL_AOT={a.aot}"] + a.extra_cmake.split()
|
||||
run(["cmake", "-G", "Ninja", "-S", str(REPO / "engine" / "sycl"), "-B", str(build), *cfg], a.vcvars, setvars)
|
||||
run(["cmake", "--build", str(build), "--target", "strata", "--", "-j", str(a.jobs)], a.vcvars, setvars)
|
||||
exe = build / "strata.exe"
|
||||
if not exe.is_file():
|
||||
print(f"build_sycl_windows.py: {exe} does not exist", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
stage = Path(tempfile.mkdtemp(prefix="strata-sycl-win-stage-"))
|
||||
try:
|
||||
shutil.copy2(exe, stage / "strata.exe")
|
||||
(stage / "BUILD.json").write_text(
|
||||
'{"version": "%s", "source": "tools/packaging/build_sycl_windows.py", "backend": "sycl", "sycl": "oneAPI DPC++ (AOT %s)", "portable": false}\n' % (ver, a.aot),
|
||||
encoding="utf-8")
|
||||
(stage / "licenses").mkdir()
|
||||
lic = REPO / "LICENSE"
|
||||
if lic.is_file():
|
||||
shutil.copy2(lic, stage / "licenses" / "LICENSE-strata.txt")
|
||||
sbin = Path(a.oneapi) / "compiler" / "latest" / "bin"
|
||||
# the Unified Runtime loads its Level Zero adapter by name at run time (not an import of the exe): copy it, and the memory-framework pieces it needs
|
||||
for pattern in ("ur_*.dll", "umf*.dll"):
|
||||
for dll in sorted(sbin.glob(pattern)):
|
||||
if dll.stem.lower().endswith("d"): # the debug builds need the debug C runtime: never shipped
|
||||
continue
|
||||
shutil.copy2(dll, stage / dll.name)
|
||||
search = ["--search", str(sbin), "--search", str(Path(a.oneapi) / "tcm" / "latest" / "bin")]
|
||||
for d in vc_redist_dirs(a.vcvars):
|
||||
search += ["--search", d]
|
||||
archs = [x.strip() for x in a.aot.replace(";", ",").split(",") if x.strip()]
|
||||
arch_args = [item for x in archs for item in ("--arch", x)]
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
cmd = [a.python, str(PACK / "package_engine.py"), "--src", str(stage), "--backend", "sycl", "--version", ver, "--out", str(out), *arch_args,
|
||||
"--platform", "windows-x86_64", "--build-id", f"release-{ver}-sycl-win", "--entrypoint", "strata.exe", "--include", "licenses/*", *search]
|
||||
print("+", subprocess.list2cmdline(cmd), flush=True)
|
||||
subprocess.run(cmd, check=True)
|
||||
finally:
|
||||
shutil.rmtree(stage, ignore_errors=True)
|
||||
folders = sorted(p for p in out.iterdir() if p.is_dir() and not p.name.startswith("."))
|
||||
for folder in folders:
|
||||
subprocess.run([a.python, str(PACK / "package_engine.py"), "--verify", str(folder)], check=True)
|
||||
subprocess.run([a.python, str(PACK / "binary_deps.py"), str(folder)], check=True)
|
||||
if a.smoke and smoke(folder, "strata.exe") != 0:
|
||||
return 1
|
||||
print("built:", out)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user