Merge f-143-intel: B70 prompt and decode speed (copy engine, wide kv_append, no GEMM staging on bmg, lend mirror, fused dequant, lean verify graph, the xe expert ranking); same output tokens, B70 4K prompt 8.5 -> 3.3 s (128K config), decode +14-21% on prompts outside the ranking's corpus

This commit is contained in:
Niko1221 committed 2026-10-11 09:27:15 +02:00
commit 2eba71548d
22 files changed
+736 -49

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
[
{"d":"code","p":"Write a Python function that merges two sorted lists into one sorted list without using sort(). Include type hints and a short docstring."},
{"d":"code","p":"Implement an LRU cache in Python using OrderedDict with get and put methods, and write three unit tests with pytest."},
{"d":"code","p":"Write a JavaScript function debounce(fn, wait) and explain how it differs from throttle, with a small usage example."},
{"d":"code","p":"Write a C++ class template for a fixed-capacity ring buffer with push, pop and size, using std::array. Mention thread-safety."},
{"d":"code","p":"Show a Rust function that reads a file line by line, counts word frequencies in a HashMap and prints the top 5 words."},
{"d":"code","p":"Write a Go HTTP handler that returns JSON {\"status\":\"ok\"} and a middleware that logs the request duration."},
{"d":"code","p":"Write a SQL query that returns the top 3 customers by total order value per country from tables customers(id,country) and orders(id,customer_id,amount)."},
{"d":"code","p":"Write a bash script that finds all files larger than 100 MB under /var/log, sorted by size, and prints them in human readable form."},
{"d":"code","p":"Explain this Python error and how to fix it:\nTraceback (most recent call last):\n File \"app.py\", line 12, in <module>\n print(data['users'][0]['name'])\nKeyError: 'users'"},
{"d":"code","p":"Refactor this function to be more readable:\ndef f(a):\n r=[]\n for i in range(len(a)):\n if a[i]%2==0:\n r.append(a[i]*a[i])\n return r"},
{"d":"code","p":"Write a regular expression that matches ISO 8601 dates like 2026-10-11 and explain each part."},
{"d":"code","p":"Write a TypeScript interface for a paginated API response and a generic fetch helper that validates the shape at runtime."},
{"d":"math","p":"A train leaves a station at 9:15 and travels at 80 km/h. A second train leaves the same station at 10:00 on the same track at 120 km/h. At what time does the second catch the first? Show the steps."},
{"d":"math","p":"Prove that the sum of the first n odd numbers is n squared, using induction."},
{"d":"math","p":"Solve the system: 3x + 2y = 16 and x - y = 2. Then check the solution."},
{"d":"math","p":"What is the probability of getting exactly two heads in five fair coin flips? Explain the formula you use."},
{"d":"reason","p":"Three friends, Ann, Ben and Cara, each own exactly one of a cat, a dog and a parrot. Ann does not own the dog. Ben owns neither the cat nor the parrot. Who owns what? Explain your reasoning."},
{"d":"reason","p":"I have a 3 liter jug and a 5 liter jug and unlimited water. How can I measure exactly 4 liters?"},
{"d":"chat","p":"I have a job interview tomorrow for a junior data analyst role and I am nervous. Can you give me practical advice?"},
{"d":"chat","p":"What are some good ways to learn a new language as an adult with only 30 minutes a day?"},
{"d":"chat","p":"Recommend a weekly meal prep plan for someone who wants high protein, vegetarian meals on a budget."},
{"d":"chat","p":"My laptop gets very hot and the fan is loud when I open many browser tabs. What can I check?"},
{"d":"creative","p":"Write a short story (about 300 words) about a lighthouse keeper who discovers that the light attracts something other than ships."},
{"d":"creative","p":"Write a poem about autumn rain in the style of a haiku sequence, five stanzas."},
{"d":"creative","p":"Describe a bustling night market in a fantasy city, using all five senses."},
{"d":"science","p":"Explain how a transformer neural network processes a sentence, from tokens to the next-token prediction, for a software engineer who has not studied machine learning."},
{"d":"science","p":"Why is the sky blue and sunsets red? Explain Rayleigh scattering without heavy math."},
{"d":"science","p":"Explain how CRISPR-Cas9 edits a gene, and name two ethical concerns."},
{"d":"history","p":"Summarize the causes and consequences of the fall of the Western Roman Empire in a few paragraphs."},
{"d":"history","p":"Compare the economic policies of the New Deal with those of the Reagan era."},
{"d":"law","p":"Explain the difference between a trademark, a copyright and a patent, with one everyday example of each."},
{"d":"business","p":"Draft a polite email to a customer whose order is delayed by two weeks, offering a 10 percent discount and a new delivery date."},
{"d":"business","p":"Write a one-page project proposal outline for migrating a small company's file server to a cloud storage service."},
{"d":"data","p":"Create a markdown table comparing PostgreSQL, MySQL and SQLite on concurrency, typical use cases, licensing and scaling."},
{"d":"data","p":"Return a JSON object describing a fictional book with fields title, author, year, genres (array) and a nested publisher object. Only output JSON."},
{"d":"tool","p":"You are an assistant with a tool get_weather(city, unit). The user asks: 'Do I need an umbrella in Hamburg tomorrow?' Write the tool call you would make as JSON and then explain what you would tell the user once you get the result."},
{"d":"summ","p":"Summarize in three bullet points: Photosynthesis converts light energy into chemical energy. In the light-dependent reactions, chlorophyll absorbs photons and splits water, releasing oxygen and producing ATP and NADPH. In the Calvin cycle, these carriers drive the fixation of carbon dioxide into sugars. The rate of photosynthesis depends on light intensity, carbon dioxide concentration and temperature."},
{"d":"fr","p":"Explique en français comment fonctionne un moteur à combustion à quatre temps, avec des phrases simples."},
{"d":"de","p":"Schreibe eine kurze, freundliche E-Mail auf Deutsch, in der du einen Termin beim Zahnarzt von Dienstag auf Donnerstag verschiebst."},
{"d":"es","p":"Dame una receta sencilla de tortilla española y explica los errores más comunes al hacerla."},
{"d":"zh","p":"请用中文解释什么是区块链,并举一个日常生活中的例子。"},
{"d":"ja","p":"日本語で、初心者向けにPythonのリスト内包表記を説明してください。"},
{"d":"ru","p":"Объясни простыми словами, чем отличается процесс от потока в операционной системе."},
{"d":"trivia","p":"Who wrote 'The Master and Margarita', and what is the novel about? Answer in a short paragraph."},
{"d":"essay","p":"Write a balanced essay of about 350 words on whether remote work is better than office work for software teams."}
]
Binary file not shown.
+29
View File
@@ -803,6 +803,35 @@ on this card for this model is the dequant kernels (at ~200 GB/s against a 600 G
prompt attention (14%); the multi-column int8 DPAS decode kernels of llama.cpp PR 29864 target K-quant and Q8_0 weights, not
the IQ-quant experts, and were not ported.
## Arc Pro B70, Flash-Next IQ3_S: prompt and decode speed in 0.1.43 (branch f-143-intel)
Measured on the B70 (xe, 32 GB, 60 GB RAM, IQ3_S, 11.5k of 24.6k experts in VRAM, the rest in the pinned mirror; unitrace from pti-gpu
for the kernel timelines). All the changes below leave the tokens as they were (first-token logits compared byte for byte, the 10-prompt
gate identical in the 32K and the 128K configuration); every one has an off switch.
- **Prompt: the expert copies run on the card's copy engine** (`sycl/include/strata/copy_queue.hpp`). The Level Zero v2 adapter runs every
SYCL queue on the compute engine, a copy-only queue included: the ~10,000 expert DMAs of a 4K prompt (2 MB, ~80 us each) sat between the
expert kernels and never overlapped one (unitrace: 0 of 2,000 copies overlapped a kernel). An immediate command list on the copy-only queue
group (ordinal 1) wrapped with `sycl::make_queue` puts them on `Copy Engine<1,0>`; events work across the two queues as before. 4K prompt
3.82 -> 3.25 s, 16K 15.5 -> 13.5 s. On by default for a Battlemage card; `STRATA_COPY_ENGINE=1` forces it elsewhere, `=0` turns it off (an A750
gained 1.4% and the prompt hung there once the stager's completion flag was a copy-engine memcpy, so Alchemist stays off).
- **The 128K configuration setup writes** (`--kv-resident 32768`, the prompt borrows cache slots) paid three more costs: `kv_append` wrote the
host copy of the KV with 1-byte stores (2 s of a 4K prompt, now 4-byte lane stores), every expert GEMM staged two 6.5/3.3 MB operands because they
sit past 4 GiB in the borrowed region (an A770 oneMKL bug that did not show on this card: off on Battlemage, `STRATA_SYCL_GEMM_STAGE=1`
brings it back), and the lent slots were refilled by a single-threaded GGUF read (0.9 s for 930 slots, now a DMA from the pinned mirror:
the experts in the last 10% of the cache slots are mirrored too, `STRATA_LEND_MIRROR=0` off). 4K prompt incl. the refill 7.2 -> 3.3 s,
1K 3.1 -> 1.6 s, 16K 25.5 -> 13.5 s, 49K 78 -> 44 s; a 684-token request through the server 2.64 -> 1.59 s, a 3,083-token one 6.1 -> 2.95 s (the same answer).
- **Decode: `data/expert-profile-sycl.bin`.** The shipped profile ranks the experts for a document summary; a chat, code or non-English prompt finds
only 60% of its routed experts in the cache (85% for a summary). `tools/make_profile_mix.py` builds a ranking from several routing traces with
every trace counting the same, `tools/collect_profile_traces.py` records them (`bench/profile_corpus.json`: 45 prompts) through the engine's
device-side routing counts (`STRATA_USAGE_DUMP=PATH`). The profile built from the 45 prompts and eight summaries holds 71% / 84%
(leave-one-out) and gave +5% to +64% decode (mean +21%) on 12 prompts that were in neither set, identical tokens; setup_intel writes it for a
card on xe (the i915 A750 keeps the shipped one: its CPU computes the misses, so the residency moves roundings).
- Decode graph without the nodes nobody answers under `STRATA_VERIFY_NO_HOST` (`STRATA_VERIFY_LEAN=0` off): -2%.
- Tried and not worth it on this card: the grouped XMX expert GEMM for Battlemage (built, `STRATA_PF_XMX=1/2`, correct to 6e-7, 11-15% slower), a
miss-first or hit-first group order in the device plan (-3% / -7%), spreading the expert chains over several queues (one compute engine),
`STRATA_LFUSE`, `STRATA_VERIFY_EAGER`.
## Measured, 2026-10-01, Arc Pro B70, Coder IQ1_M, 32K context, INT8 KV: the SYCL port (engine 0.1.31-sycl)
| | |
+5 -2
View File
@@ -37,7 +37,9 @@ if(STRATA_SYCL_SPIN_MAX)
add_compile_definitions(STRATA_SYCL_SPIN_MAX=${STRATA_SYCL_SPIN_MAX}u)
endif()
set(_sycl_flags -fsycl)
if(STRATA_SYCL_AOT MATCHES "^(bmg|lnl|pvc)")
if(STRATA_SYCL_AOT MATCHES "^(bmg|lnl)")
add_compile_definitions(STRATA_XMX_SG16=1) # the grouped XMX kernels on sub-group 16, joint_matrix 8x16x16 (Xe2)
elseif(STRATA_SYCL_AOT MATCHES "^pvc")
add_compile_definitions(STRATA_NO_DG2_XMX=1) # the grouped XMX kernels (sub-group 8, 8x8x16) do not compile for Xe2 / Xe-HPC
endif()
if(STRATA_SYCL_AOT)
@@ -222,7 +224,8 @@ strata_resolve(_engine src/core/layer.cpp src/core/session.cpp src/core/expert_s
src/core/arch_defaults.cpp src/core/vmm.cpp # vmm.cpp is the port's stub: no driver VMM on Level Zero
src/core/conversation_file.cpp
src/core/peer_experts.cpp src/core/remote_expert_opt_stub.cpp) # 0.1.36+: --peer-device (a stub in the port: no second GPU tier yet)
add_library(strata_engine STATIC ${_engine} ${CMAKE_CURRENT_SOURCE_DIR}/src/core/gguf_expert_source.cpp)
add_library(strata_engine STATIC ${_engine} ${CMAKE_CURRENT_SOURCE_DIR}/src/core/gguf_expert_source.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/core/copy_queue.cpp) # 0.1.43: a queue on the copy engine
target_include_directories(strata_engine PRIVATE ${STRATA_ROOT}/src/core) # conversation_checked.hpp (#include "...")
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu)
+27
View File
@@ -0,0 +1,27 @@
// include/strata/copy_queue.hpp - SYCL port, 0.1.43: a queue on the GPU's dedicated copy (blitter) engine.
//
// WHY. With the Level Zero "v2" adapter (the default on Xe2 / Battlemage and newer), every SYCL queue, including a queue
// that only holds host-to-device copies, runs on the compute engine: a 2 MB expert copy (~80 us at 25 GB/s) blocks the
// kernels behind it for that long. A prompt chunk streams ~10,000 experts: ~0.8 s of the 3.8 s of a 4K prompt on an Arc
// Pro B70 is the compute engine waiting for its own copies (unitrace: every H2D copy sits on "L0 Compute Engine<0,0>"
// and none overlaps a kernel). The device does expose a copy-only queue group (zeDeviceGetCommandQueueGroupProperties:
// group 1, flags COPY, 1 queue); the v2 adapter just does not use it for in-order queues.
//
// WHAT. make_copy_engine_queue() creates an immediate command list on that group and wraps it with
// sycl::make_queue<ext_oneapi_level_zero>, so everything built on SYCL queues (memcpy, events, ext_oneapi_submit_barrier
// across queues) keeps working, only the engine changes. It returns nullptr (the caller keeps an ordinary in-order queue)
// when the backend is not Level Zero, the device has no copy-only group, the loader or the call fails, or
// STRATA_COPY_ENGINE=0 (default: on for a Battlemage card, which is where it was measured; =1 forces it on any Level Zero
// device, =0 off). Same bytes, same kernels: the tokens do not change.
#pragma once
#include <sycl/sycl.hpp>
namespace strata {
/// `what` names the first user in the one log line. One queue per process (an in-order queue, the same one for every
/// caller: copies are serial on one engine anyway); never freed, so a caller must not delete it.
sycl::queue* make_copy_engine_queue(const char* what);
/// true once a copy-engine queue has been made in this process
bool copy_engine_active();
/// true for the queue make_copy_engine_queue() returned: it runs copies and barriers only, no kernel (not even queue::fill)
bool is_copy_engine_queue(const sycl::queue* q);
} // namespace strata
@@ -0,0 +1,11 @@
// SYCL port, 0.1.43: one expert's gate/up and down matrices dequantized to FP16 in ONE launch (the prompt path's FP16 expert
// path used two: iq_dequant_gu_f16 then iq_dequant_f16). The values are the two launches' values, byte for byte; only the
// launch count changes (one kernel boundary less per expert, ~24,500 per 4K prompt).
#pragma once
#include <cstdint>
namespace strata::kernels {
/// gate/up -> dst_gu (interleaved rows 2r = gate r, 2r+1 = up r, as iq_dequant_gu_f16), down (n_embd x n_ff values, n a multiple
/// of 256) -> dst_d (as iq_dequant_f16). Same argument rules as the two functions.
void iq_dequant_expert_f16(int gu_type, int d_type, const void* gate, const void* up, const void* down, int64_t n_ff,
int64_t n_embd, uint16_t* dst_gu, uint16_t* dst_d, void* stream);
} // namespace strata::kernels
@@ -6,5 +6,5 @@ namespace strata::kernels {
/// that is not in the VRAM cache but has a non-zero entry in `mirror_table` ([n_layers][n_expert] device-readable
/// addresses, 0 = none) as planned: the expert kernels read it from that address, over PCIe. `d_res` is the residency
/// table whose per-layer slices resident_plan receives, so the layer of a call is found from its pointer.
void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mirror_table);
void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mirror_table, int32_t* usage = nullptr);
}
+11
View File
@@ -121,6 +121,7 @@ def drop(args, name, value=False):
del args[i:i + 1 + int(value)]
SYCL_PROFILE = "expert-profile-sycl.bin" # data/: the xe cards' expert ranking (to_sycl)
SMALL_CARD_GB = 12.0 # under this the engine's own advice is --vram-reserve-mib 300 (a 1024 MiB reserve leaves an
# 8 GB card no room for even one expert slot) and the English draft vocabulary
SMALL_RESERVE_MIB = 300
@@ -149,6 +150,16 @@ def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0,
for f in ("--resident-experts", "--mmap-experts"): # setup's low-RAM mode is the CUDA engine's
drop(args, f)
drop(args, "--kv-resident", True) # decided below on the real RAM
if driver != "i915" and "--expert-profile" in args and (ROOT / "data" / SYCL_PROFILE).is_file():
# 0.1.43: a card on xe runs every expert on the GPU (the ones the cache does not hold are read from the pinned mirror
# by the same kernels), so WHICH experts the cache holds changes speed and no token: data/expert-profile-sycl.bin
# ranks them from the routing of 45 varied prompts (chat, code, maths, six languages) and eight document summaries,
# where the shipped profile holds 60% of a chat prompt's experts and 85% of a summary's (B70: +9..25% decode on prompts left
# out of it, same tokens). Another profile the user chose is kept; i915 keeps the shipped one (there the CPU
# computes the misses, so the residency moves roundings).
i = args.index("--expert-profile") + 1
if args[i].replace("\\", "/").rsplit("/", 1)[-1] == "expert-profile.bin":
args[i] = args[i][:-len("expert-profile.bin")] + SYCL_PROFILE
for f in ("--pack", "--native", "--ple-gguf", "--expert-profile", "--mtp", "--control-vector-scaled"):
if f in args:
v = args[args.index(f) + 1]
+142
View File
@@ -0,0 +1,142 @@
// src/core/copy_queue.cpp - see include/strata/copy_queue.hpp.
#include "strata/copy_queue.hpp"
#include "strata/sycl_queue.hpp"
#include <dpct/dpct.hpp>
#include <sycl/ext/oneapi/backend/level_zero.hpp>
#if defined(__has_include)
#if __has_include(<level_zero/ze_api.h>)
#include <level_zero/ze_api.h>
#define STRATA_HAVE_ZE_API 1
#endif
#endif
#include <atomic>
#include <mutex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#ifdef STRATA_HAVE_ZE_API
#if defined(_WIN32)
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#endif
namespace strata {
namespace {
std::atomic<bool> g_active{false};
#ifdef STRATA_HAVE_ZE_API
struct ZeFns {
decltype(&zeDeviceGetCommandQueueGroupProperties) get_groups = nullptr;
decltype(&zeCommandListCreateImmediate) create_imm = nullptr;
};
bool load_ze(ZeFns& f) {
#if defined(_WIN32)
HMODULE h = LoadLibraryA("ze_loader.dll");
if (!h) return false;
auto sym = [&](const char* n) { return (void*) GetProcAddress(h, n); };
#else
void* h = dlopen("libze_loader.so.1", RTLD_NOW | RTLD_NOLOAD); // already loaded by the SYCL runtime
if (!h) h = dlopen("libze_loader.so.1", RTLD_NOW);
if (!h) return false;
auto sym = [&](const char* n) { return dlsym(h, n); };
#endif
f.get_groups = (decltype(f.get_groups)) sym("zeDeviceGetCommandQueueGroupProperties");
f.create_imm = (decltype(f.create_imm)) sym("zeCommandListCreateImmediate");
return f.get_groups && f.create_imm;
}
#endif
} // namespace
bool copy_engine_active() { return g_active.load(); }
namespace {
// one copy-engine queue per device (a layer split calls this once per card): device -> queue; a device that has none maps to nullptr
struct DevQ { sycl::device dev; sycl::queue* q; };
std::vector<DevQ>& dev_queues() { static std::vector<DevQ> v; return v; }
std::mutex& dev_mu() { static std::mutex m; return m; }
} // namespace
bool is_copy_engine_queue(const sycl::queue* q) {
if (q == nullptr) return false;
std::lock_guard<std::mutex> lk(dev_mu());
for (const DevQ& d : dev_queues()) if (d.q == q) return true;
return false;
}
sycl::queue* make_copy_engine_queue(const char* what) {
static const bool off = [] { const char* v = std::getenv("STRATA_COPY_ENGINE"); return v && v[0] == '0'; }();
if (off) return nullptr;
#ifndef STRATA_HAVE_ZE_API
(void) what;
return nullptr;
#else
std::lock_guard<std::mutex> lk(dev_mu());
sycl::device dev = dpct::get_current_device();
for (const DevQ& d : dev_queues()) if (d.dev == dev) return d.q; // asked before for this card (nullptr: it has none)
dev_queues().push_back({dev, nullptr});
const size_t slot = dev_queues().size() - 1;
try {
if (dev.get_backend() != sycl::backend::ext_oneapi_level_zero) return nullptr;
// Battlemage only unless STRATA_COPY_ENGINE=1: on an Arc A750 (i915, JIT) the prompt path hung with it once the stager's
// completion flag became a copy-engine memcpy (4K and 600-token prompts, 10+ minutes, GPU not hung), and the measured gain
// there was 1.4% (a prompt there is compute bound).
{
const char* force = std::getenv("STRATA_COPY_ENGINE");
if (!(force && force[0] == '1') && strata::intel_gpu_gen(dev) != strata::IntelGpuGen::Battlemage) return nullptr;
}
// The legacy Level Zero adapter already puts memcpy on the copy engine (and its kernel launches are slower); only
// the v2 adapter needs this. SYCL_UR_USE_LEVEL_ZERO_V2=0 selects the legacy one.
const char* v2 = std::getenv("SYCL_UR_USE_LEVEL_ZERO_V2");
if (v2 && v2[0] == '0') return nullptr;
ZeFns zf;
if (!load_ze(zf)) return nullptr;
sycl::context ctx = dpct::get_default_context();
auto zctx = sycl::get_native<sycl::backend::ext_oneapi_level_zero>(ctx);
auto zdev = sycl::get_native<sycl::backend::ext_oneapi_level_zero>(dev);
uint32_t ng = 0;
if (zf.get_groups(zdev, &ng, nullptr) != ZE_RESULT_SUCCESS || ng == 0) return nullptr;
std::vector<ze_command_queue_group_properties_t> g(ng);
for (auto& x : g) { std::memset(&x, 0, sizeof(x)); x.stype = ZE_STRUCTURE_TYPE_COMMAND_QUEUE_GROUP_PROPERTIES; }
if (zf.get_groups(zdev, &ng, g.data()) != ZE_RESULT_SUCCESS) return nullptr;
int ord = -1;
for (uint32_t i = 0; i < ng; ++i)
if ((g[i].flags & ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COPY) &&
!(g[i].flags & ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE) && g[i].numQueues > 0) { ord = (int) i; break; }
if (ord < 0) return nullptr;
ze_command_queue_desc_t d;
std::memset(&d, 0, sizeof(d));
d.stype = ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC;
d.ordinal = (uint32_t) ord;
d.index = 0;
d.flags = ZE_COMMAND_QUEUE_FLAG_IN_ORDER;
d.mode = ZE_COMMAND_QUEUE_MODE_ASYNCHRONOUS;
d.priority = ZE_COMMAND_QUEUE_PRIORITY_NORMAL;
ze_command_list_handle_t cl = nullptr;
if (zf.create_imm(zctx, zdev, &d, &cl) != ZE_RESULT_SUCCESS || cl == nullptr) return nullptr;
sycl::backend_input_t<sycl::backend::ext_oneapi_level_zero, sycl::queue> in(
cl, dev, sycl::ext::oneapi::level_zero::ownership::keep,
sycl::property_list{sycl::property::queue::in_order{}});
auto* q = new sycl::queue(sycl::make_queue<sycl::backend::ext_oneapi_level_zero>(in, ctx));
dev_queues()[slot].q = q;
g_active.store(true);
static std::atomic<bool> said{false};
if (!said.exchange(true))
std::fprintf(stderr, "strata: copy engine: %s copies run on the GPU's copy engine (queue group %d), not the "
"compute engine (STRATA_COPY_ENGINE=0 turns it off)\n", what, ord);
return q;
} catch (const std::exception& e) {
std::fprintf(stderr, "strata: copy engine queue not available (%s): ordinary queue\n", e.what());
return nullptr;
}
#endif
}
} // namespace strata
+14 -7
View File
@@ -800,6 +800,13 @@ const float* Verifier::final_R(int t) const { return R_ + (size_t) t * (size_t)
bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
using namespace strata::kernels;
const ModelGeometry& g = *g_;
// 0.1.43 (STRATA_VERIFY_LEAN=0 turns it off): with the device plan under STRATA_VERIFY_NO_HOST no host ever answers a doorbell, so
// a layer's doorbell publish, the three flag waits, the plan copy, the PCIe-share group and its staging kernels are nodes of
// the graph that only wait for each other or do nothing: ~9 nodes (~1.4 ms) per layer-window less. The VRAM / mirror groups, the
// combine and the answers are the same kernels on the same data.
static const bool lean_env = [] { const char* v = std::getenv("STRATA_VERIFY_LEAN"); return !(v && v[0] == '0'); }();
static const bool no_host_env = [] { const char* v = std::getenv("STRATA_VERIFY_NO_HOST"); return v && *v && std::strcmp(v, "0") != 0; }();
const bool lean = lean_env && no_host_env && device_plan_ && !step_hook_ && !step_hook2_ && !remote_opt_ && !always_publish_ && !g_stepped;
const WeightTable& wt = *wt_;
SessionState& ss = *ss_;
const int64_t N = g.n_embd, HC = g.hc, K = ss.k, C = g.ssm_conv_channels, ZV = g.ssm_value_dim;
@@ -1346,7 +1353,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
if (remote_opt_ || always_publish_)
doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,
m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);
else {
else if (!lean) { // (lean: nobody reads the doorbell)
const int32_t* layer_res = hits_.d_res != nullptr ? (hits_.d_res + l * g.n_expert) : nullptr;
doorbell_publish_res(xm, ids_ + tb * K, layer_res, (int) g.n_expert, (int64_t) n * N, (int64_t) n * K,
m_x_ + tb * N, m_ids_ + tb * K, m_seq_, cs);
@@ -1444,8 +1451,8 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
stamp(l, 20, grp);
} else {
if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident)
wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);
copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);
if (!lean) wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);
if (!lean) copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);
} else {
wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan
copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
@@ -1455,9 +1462,9 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
stamp(l, 20, grp);
// stepped mode: the plan copy + VRAM groups end a segment, so they run while the CPU computes its rows
if (step_hook2_ && !step_hook2_(l, grp)) { if (err.empty()) err = "verify: stepped split failed"; return false; }
if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);
if (device_plan_) { if (!lean) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs); }
else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped
if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging
if (!lean && sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging
const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;
uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob;
fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs);
@@ -1466,10 +1473,10 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
stamp(l, 21, grp);
// the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at
// pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them
grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out);
if (!lean) grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out); // (lean: the device plan leaves it empty)
stamp(l, 22, grp);
if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros
wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);
if (!lean) wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);
copy_or_zero_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N,
skip_ + grp, ring, cs);
} else {
+68 -10
View File
@@ -10,6 +10,7 @@
#include "strata/sycl_math.hpp"
#include "strata/sycl_queue.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/iq_dequant_expert.hpp"
#include "strata/kernels/dp4a.hpp"
#include "strata/kernels/q8_1_finite.hpp"
#include "s26_tsum.dp.hpp"
@@ -4418,6 +4419,51 @@ void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, in
check("iq_dequant_gu_f16");
}
// 0.1.43: gate/up and down of one expert in one launch. Work-group g of the first 2 * n_ff * per_row is the gu kernel's
// (row-superblock g / 2, parity g % 2); the rest are the flat kernel's superblocks of the down matrix.
namespace {
__dpct_inline__ void dequant_expert_kernel(int gt, int dt, const void *__restrict__ gate, const void *__restrict__ up,
const void *__restrict__ down, int64_t per_row, int64_t gu_wgs,
sycl::half *__restrict__ ygu, sycl::half *__restrict__ yd) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int64_t g = item_ct1.get_group(2);
if (g < gu_wgs) {
const int64_t i = g >> 1;
const int parity = (int) (g & 1);
const int64_t r = i / per_row, c = i % per_row;
dq_dispatch<sycl::half>(gt, parity ? up : gate, i, ygu + ((2 * r + parity) * per_row + c) * QK_K,
item_ct1.get_local_id(2));
} else {
const int64_t j = g - gu_wgs;
dq_dispatch<sycl::half>(dt, down, j, yd + j * QK_K, item_ct1.get_local_id(2));
}
}
} // namespace
void iq_dequant_expert_f16(int gt, int dt, const void* gate, const void* up, const void* down, int64_t n_ff,
int64_t n_embd, uint16_t* dst_gu, uint16_t* dst_d, void* stream) {
if (n_embd % 256 != 0 || (n_ff * n_embd) % 256 != 0 || !is_iq(gt) || !is_iq(dt)) {
std::fprintf(stderr, "iq_dequant_expert_f16: types %d/%d, %lld x %lld\n", gt, dt, (long long) n_ff, (long long) n_embd);
std::exit(1);
}
const int64_t per_row = n_embd / 256, gu_wgs = 2 * n_ff * per_row, d_wgs = n_ff * n_embd / 256;
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
dpct::has_capability_or_fail(strata::q_of(stream)->get_device(), {sycl::aspect::fp16});
strata::q_of(stream)->submit([&](sycl::handler &cgh) {
cgh.parallel_for<dpct_kernel_name<class dequant_expert_kernel_7d2c41>>(
sycl::nd_range<3>(sycl::range(1, 1, (unsigned) (gu_wgs + d_wgs)) * sycl::range(1, 1, 32),
sycl::range(1, 1, 32)),
exp_props, [=](sycl::nd_item<3> item_ct1) {
dequant_expert_kernel(gt, dt, gate, up, down, per_row, gu_wgs, (sycl::half *) dst_gu,
(sycl::half *) dst_d);
});
});
}
check("iq_dequant_expert_f16");
}
bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept {
const int qg = gu_qk(gu_type), qd = d_qk(d_type);
return qg > 0 && qd > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 &&
@@ -5195,6 +5241,12 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
// 8x8x16 (DG2), 256 GRF. Per expert i of the group: Y_i = X_i . W_i^T, rows back to back (cnt[i] each).
// gate/up: up_i != nullptr, virtual row 2r = gate row r, 2r+1 = up row r (iq_dequant_gu_f16's interleave).
namespace xmxg {
// Sub-group width = the XMX tile N: 8 (DG2, 8x8x16) or 16 (Xe2, 8x16x16; CMake STRATA_XMX_SG16 for an AOT bmg / lnl build)
#ifdef STRATA_XMX_SG16
constexpr int kSgW = 16;
#else
constexpr int kSgW = 8;
#endif
namespace jm = sycl::ext::oneapi::experimental::matrix;
struct Grp {
const uint8_t* a[kXmxGroupMax];
@@ -5205,8 +5257,8 @@ struct Grp {
};
template <int SGM_, int SGN_, int MT_, int NT_>
struct Cfg {
static constexpr int SGM = SGM_, SGN = SGN_, MT = MT_, NT = NT_, KS = 32, SG = 8;
static constexpr int BM = SGM * MT * 8, BN = SGN * NT * 8, WG = SGM * SGN * 8;
static constexpr int SGM = SGM_, SGN = SGN_, MT = MT_, NT = NT_, KS = 32, SG = kSgW;
static constexpr int BM = SGM * MT * 8, BN = SGN * NT * kSgW, WG = SGM * SGN * kSgW;
};
template <class C, class Name>
void launch(sycl::queue& q, int ty, bool gu, const sycl::half* X, float* Y, const Grp& gp, int ntiles, int N, int K) {
@@ -5214,11 +5266,12 @@ void launch(sycl::queue& q, int ty, bool gu, const sycl::half* X, float* Y, cons
constexpr int LDA = KS + 8, LDB = KS + 8;
const int nb = N / BN;
#ifndef STRATA_NO_DG2_XMX
constexpr int TN = kSgW;
q.submit([&](sycl::handler& h) {
sycl::local_accessor<sycl::half, 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) ntiles, (size_t) nb * WG}, {1, (size_t) WG}), props,
[=](sycl::nd_item<2> it) [[sycl::reqd_sub_group_size(8)]] {
[=](sycl::nd_item<2> it) [[sycl::reqd_sub_group_size(kSgW)]] {
auto sg = it.get_sub_group();
const int t = (int) it.get_group(0);
int e = 0;
@@ -5232,7 +5285,7 @@ void launch(sycl::queue& q, int ty, bool gu, const sycl::half* X, float* Y, cons
const int n0 = (int) it.get_group(1) * BN;
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, 8> acc[C::MT][C::NT];
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);
sycl::half* pa = sa.template get_multi_ptr<sycl::access::decorated::no>().get();
@@ -5264,13 +5317,13 @@ void launch(sycl::queue& q, int ty, bool gu, const sycl::half* X, float* Y, cons
it.barrier(sycl::access::fence_space::local_space);
for (int kk = 0; kk < KS; kk += 16) {
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::a, 8, 16, jm::layout::row_major> am[C::MT];
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, 8, jm::layout::col_major> bm[C::NT];
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, TN, jm::layout::col_major> bm[C::NT];
for (int i = 0; i < C::MT; ++i)
jm::joint_matrix_load(sg, am[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, bm[j], sb.template get_multi_ptr<sycl::access::decorated::no>() +
(sgn * C::NT * 8 + j * 8) * LDB + kk, LDB);
(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], am[i], bm[j], acc[i][j]);
}
@@ -5280,19 +5333,19 @@ void launch(sycl::queue& q, int ty, bool gu, const sycl::half* X, float* Y, cons
const int r = sgm * C::MT * 8 + i * 8;
if (r >= rows) continue;
for (int j = 0; j < C::NT; ++j) {
const int c = n0 + sgn * C::NT * 8 + j * 8;
const int c = n0 + sgn * C::NT * TN + j * TN;
if (r + 8 <= rows) {
jm::joint_matrix_store(sg, acc[i][j],
sycl::address_space_cast<sycl::access::address_space::global_space, sycl::access::decorated::no>(
Ye + (size_t) r * N + c), N, jm::layout::row_major);
} else {
float* st = reinterpret_cast<float*>(pa) + sgid * 64;
float* st = reinterpret_cast<float*>(pa) + sgid * 8 * TN;
jm::joint_matrix_store(sg, acc[i][j],
sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(st),
8, jm::layout::row_major);
TN, jm::layout::row_major);
sycl::group_barrier(sg);
const int lim = rows - r, ln = (int) sg.get_local_linear_id();
for (int rr = 0; rr < lim; ++rr) Ye[(size_t) (r + rr) * N + c + ln] = st[rr * 8 + ln];
for (int rr = 0; rr < lim; ++rr) Ye[(size_t) (r + rr) * N + c + ln] = st[rr * TN + ln];
sycl::group_barrier(sg);
}
}
@@ -5306,8 +5359,13 @@ void launch(sycl::queue& q, int ty, bool gu, const sycl::half* X, float* Y, cons
#endif
}
class k_xg_small; class k_xg_big;
#ifdef STRATA_XMX_SG16
using Small = Cfg<2, 4, 4, 2>; // 64 x 128 (8 sub-groups of 16)
using Big = Cfg<4, 2, 4, 4>; // 128 x 128
#else
using Small = Cfg<2, 8, 4, 2>; // 64 x 128
using Big = Cfg<4, 4, 4, 4>; // 128 x 128
#endif
template <class C>
int fill(Grp& gp, const int32_t* cnt, int n) {
int t = 0, o = 0;
+10 -3
View File
@@ -2084,7 +2084,7 @@ resident_plan_kernel(const int32_t *__restrict__ ids, int n, int k,
const unsigned long long *slot_off, long long blob,
int32_t *__restrict__ pl, long long capx, uint32_t *skip,
uint32_t ring, const unsigned long long *__restrict__ mir,
volatile uint32_t *plan_err) {
volatile uint32_t *plan_err, int32_t *usage) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
auto &s_ids = *sycl::ext::oneapi::group_local_memory_for_overwrite<
int32_t[kResidentPlanMax]>(
@@ -2109,6 +2109,9 @@ auto &s_ids = *sycl::ext::oneapi::group_local_memory_for_overwrite<
s_ids[tid] = eid;
slot = (eid >= 0 && eid < n_expert) ? res[eid] : -1;
if (slot < 0 && eid >= 0 && eid < n_expert && mir != nullptr) maddr = mir[eid];
if (usage != nullptr && eid >= 0 && eid < n_expert) // the adaptive tier's routing counts (device side)
sycl::atomic_ref<int32_t, sycl::memory_order::relaxed, sycl::memory_scope::device,
sycl::access::address_space::global_space>(usage[eid]).fetch_add(1);
if (slot < 0 && maddr == 0)
dpct::atomic_fetch_or<sycl::access::address_space::generic_space>(
&s_bad, 1);
@@ -2360,8 +2363,10 @@ __dpct_inline__ void copy_or_zero_kernel(sycl::float4 *__restrict__ dst,
namespace {
const int32_t* g_mirror_res = nullptr;
const unsigned long long* g_mirror_table = nullptr;
int32_t* g_usage = nullptr;
}
void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mirror_table) {
void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mirror_table, int32_t* usage) {
g_usage = usage;
g_mirror_res = d_res;
g_mirror_table = mirror_table;
}
@@ -2369,8 +2374,10 @@ void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_
const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan,
long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err) {
const unsigned long long* mir = nullptr; // SYCL port: the layer's slice of the host-mirror table, if any
int32_t* use = nullptr; // the layer's slice of the device routing counts, if on
if (g_mirror_table != nullptr && g_mirror_res != nullptr && res_layer >= g_mirror_res)
mir = g_mirror_table + (res_layer - g_mirror_res);
if (g_usage != nullptr && g_mirror_res != nullptr && res_layer >= g_mirror_res) use = g_usage + (res_layer - g_mirror_res);
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -2384,7 +2391,7 @@ void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_
[[sycl::reqd_sub_group_size(32)]] {
resident_plan_kernel(
ids, n_entries, k, res_layer, n_expert, cache_base,
slot_off, blob, plan, capx, skip, ring, mir, plan_err);
slot_off, blob, plan, capx, skip, ring, mir, plan_err, use);
});
}
check("resident_plan");
+3 -1
View File
@@ -21,10 +21,12 @@ int main(int argc, char** argv) {
std::printf("xmx_group_parity: SKIP (the sub-group 8 / 8x8x16 kernels are not built for this AOT device)");
return 0;
#else
#ifndef STRATA_XMX_SG16
if (strata::intel_gpu_gen(q->get_device()) == strata::IntelGpuGen::Battlemage) {
std::printf("xmx_group_parity: SKIP (Battlemage has no sub-group 8 / 8x8x16 joint_matrix)");
std::printf("xmx_group_parity: SKIP (this build has the sub-group 8 / 8x8x16 kernels; Battlemage needs the AOT bmg build)");
return 0;
}
#endif
#endif
dpct::blas::descriptor_ptr hd = new dpct::blas::descriptor();
hd->set_queue(q);
+5 -1
View File
@@ -709,7 +709,11 @@ uint8_t* gemm_stage(size_t need, sycl::queue& q) {
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,
float* Y, int64_t ldy) {
static const bool no_stage = std::getenv("STRATA_SYCL_GEMM_NO_STAGE") != nullptr; // tests' negative control
// 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
// without staging; the 10 MB copy per expert was ~10% of a prompt). STRATA_SYCL_GEMM_STAGE=1 stages there as before.
static const bool no_stage = std::getenv("STRATA_SYCL_GEMM_NO_STAGE") != nullptr ||
(strata::intel_gpu_gen(q.get_device()) == strata::IntelGpuGen::Battlemage && !(std::getenv("STRATA_SYCL_GEMM_STAGE") && std::getenv("STRATA_SYCL_GEMM_STAGE")[0] == '1'));
constexpr size_t k4G = 4ull << 30;
const size_t es = 2;
const size_t w_bytes = (size_t) lda * (size_t) N * es; // W stored K x N, col-major (lda = K)
+39 -2
View File
@@ -1951,7 +1951,7 @@ kv_append_kernel(const float *__restrict__ K, const float *__restrict__ V,
int64_t page_size, uint16_t *k_pool, uint16_t *v_pool,
int8_t *k_q, int8_t *v_q, uint16_t *k_scale, uint16_t *v_scale,
strata::kernels::KvHostPools host,
strata::kernels::KvHostPools stage) {
strata::kernels::KvHostPools stage, bool wide_host) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int64_t t = item_ct1.get_group(2);
const int kvh = item_ct1.get_group(1), g = item_ct1.get_group(0) >> 1;
@@ -1962,9 +1962,27 @@ kv_append_kernel(const float *__restrict__ K, const float *__restrict__ V,
const int64_t page = table[pos / page_size];
const int64_t row = (page * 2 + kvh) * page_size + pos % page_size;
const int64_t row_id = ((pos / page_size) * 2 + kvh) * page_size + pos % page_size;
// 0.1.43: the host copy and the staging pool are written 4 bytes a lane, 64 contiguous bytes a group, instead of one
// 1- or 2-byte store per lane: on a B70 the 1-byte stores into the pinned host KV (--kv-resident) ran at ~30 MB/s
// (kv_append: 161 ms a layer for 4,096 tokens, 2 s of a 4K prompt), the same bytes in 4-byte stores are a few ms.
const int lid = (int) item_ct1.get_local_id(2);
if (k_pool != nullptr) {
const uint16_t h = hf(x);
if (page >= 0) (is_v ? v_pool : k_pool)[row * 256 + d] = h;
if (wide_host && (host.k_pool != nullptr || stage.k_pool != nullptr)) {
auto &s16 = *sycl::ext::oneapi::group_local_memory_for_overwrite<uint16_t[64]>(
sycl::ext::oneapi::this_work_item::get_work_group<3>());
s16[lid] = h;
item_ct1.barrier(sycl::access::fence_space::local_space);
if (lid < 32) {
const uint32_t w = (uint32_t) s16[2 * lid] | ((uint32_t) s16[2 * lid + 1] << 16);
if (host.k_pool != nullptr)
((uint32_t *) ((is_v ? host.v_pool : host.k_pool) + row_id * 256 + g * 64))[lid] = w;
if (stage.k_pool != nullptr)
((uint32_t *) ((is_v ? stage.v_pool : stage.k_pool) + row_id * 256 + g * 64))[lid] = w;
}
return;
}
if (host.k_pool != nullptr) (is_v ? host.v_pool : host.k_pool)[row_id * 256 + d] = h;
if (stage.k_pool != nullptr) (is_v ? stage.v_pool : stage.k_pool)[row_id * 256 + d] = h;
return;
@@ -2006,6 +2024,23 @@ runtimes. You may need to adjust the code.
if (item_ct1.get_local_id(2) == 0)(is_v ? v_scale
: k_scale)[row * 4 + g] = sb;
}
if (wide_host && (host.k_q != nullptr || stage.k_q != nullptr)) {
auto &s8 = *sycl::ext::oneapi::group_local_memory_for_overwrite<int8_t[64]>(
sycl::ext::oneapi::this_work_item::get_work_group<3>());
s8[lid] = (int8_t) q;
item_ct1.barrier(sycl::access::fence_space::local_space);
if (lid < 16) {
const uint32_t w = (uint32_t) (uint8_t) s8[4 * lid] | ((uint32_t) (uint8_t) s8[4 * lid + 1] << 8) |
((uint32_t) (uint8_t) s8[4 * lid + 2] << 16) | ((uint32_t) (uint8_t) s8[4 * lid + 3] << 24);
if (host.k_q != nullptr) ((uint32_t *) ((is_v ? host.v_q : host.k_q) + row_id * 256 + g * 64))[lid] = w;
if (stage.k_q != nullptr) ((uint32_t *) ((is_v ? stage.v_q : stage.k_q) + row_id * 256 + g * 64))[lid] = w;
}
if (lid == 0) {
if (host.k_q != nullptr) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb;
if (stage.k_q != nullptr) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb;
}
return;
}
if (host.k_q != nullptr) {
(is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q;
if (item_ct1.get_local_id(2) ==
@@ -2134,6 +2169,8 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in
uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale,
void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) {
if (T <= 0) return;
static const bool wide_env = [] { const char* v = std::getenv("STRATA_KV_WIDE_HOST"); return !(v && v[0] == '0'); }();
const bool wide = wide_env;
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -2159,7 +2196,7 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in
K, V, pos0, page_table, page_size, k_pool,
v_pool, k_q, v_q, k_scale, v_scale,
host_host_strata_kernels_KvHostPools_ct11,
stage_stage_strata_kernels_KvHostPools_ct12);
stage_stage_strata_kernels_KvHostPools_ct12, wide);
});
});
}
+31 -6
View File
@@ -3,6 +3,7 @@
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include "strata/sycl_queue.hpp"
#include "strata/copy_queue.hpp"
#include "strata/prefill/xmx_moe.hpp"
#include "strata/prefill/prefill.hpp"
#include "strata/core/gguf_expert_source.hpp"
@@ -20,6 +21,7 @@
#include "strata/kernels/ple.hpp"
#include "strata/kernels/native_ple_postops.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/iq_dequant_expert.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/kv_stream.hpp"
@@ -360,6 +362,7 @@ struct Stager {
std::vector<std::vector<uint8_t>> pageable; // the fallback when no more RAM can be pinned
std::vector<dpct::event_ptr> dma_done;
uint64_t* done_seq = nullptr; // page-locked: the copy queue's last finished DMA per buffer
uint64_t* src_seq = nullptr; // page-locked: the values a copy-engine queue copies into done_seq (it cannot run a fill kernel)
std::vector<uint64_t> want; // the sequence number each buffer's last DMA writes
uint64_t issue_seq = 0;
std::vector<Job> jobs;
@@ -385,6 +388,9 @@ struct Stager {
done_seq = sycl::malloc_host<uint64_t>((size_t) kRing, dpct::get_in_order_queue());
if (done_seq == nullptr) return false;
for (int i = 0; i < kRing; ++i) done_seq[i] = 0;
src_seq = sycl::malloc_host<uint64_t>((size_t) 4 * kRing, dpct::get_in_order_queue());
if (src_seq == nullptr) return false;
for (int i = 0; i < 4 * kRing; ++i) src_seq[i] = 0;
pageable.resize(kRing);
for (int i = 0; i < kRing; ++i) {
/*
@@ -417,6 +423,7 @@ struct Stager {
cv.notify_all();
for (auto& t : threads) t.join();
if (done_seq) sycl::free(done_seq, dpct::get_in_order_queue());
if (src_seq) sycl::free(src_seq, dpct::get_in_order_queue());
for (int i = 0; i < kRing; ++i) {
if (dma_done[i]) dpct::destroy_event(dma_done[i]);
if (buf[i] && pinned[i])
@@ -503,7 +510,13 @@ struct Stager {
void issued_one(int j, dpct::queue_ptr copy) {
const uint64_t s = ++issue_seq;
want[(size_t) (j % kRing)] = s;
copy->fill<uint64_t>(done_seq + j % kRing, s, 1);
if (strata::is_copy_engine_queue(copy)) { // a copy-only command list runs no kernels (a fill is one): a copy of the value
uint64_t* v = src_seq + (size_t) (s % (uint64_t) (4 * kRing));
*v = s;
copy->memcpy(done_seq + j % kRing, v, sizeof(uint64_t));
} else {
copy->fill<uint64_t>(done_seq + j % kRing, s, 1);
}
issued.store(j + 1, std::memory_order_release);
}
bool buffer_free(int b) const {
@@ -971,8 +984,12 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g,
DPCT1025: The SYCL queue is created ignoring the flag and priority
options.
*/
if (DPCT_CHECK_ERROR(
m.copy = dpct::get_current_device().create_queue(true)) != 0) {
// 0.1.43: the expert copies on the GPU's copy engine when the device has one the SYCL runtime does not use itself
// (the Level Zero v2 adapter runs every queue on the compute engine: ~0.8 s of a 4K prompt on a B70 is the compute
// engine waiting for its own DMA). nullptr: the ordinary in-order queue. STRATA_COPY_ENGINE=0 turns it off.
m.copy = strata::make_copy_engine_queue("the prompt path's expert");
if (m.copy == nullptr &&
DPCT_CHECK_ERROR(m.copy = dpct::get_current_device().create_queue(true)) != 0) {
err = "prefill: copy stream"; return false;
}
const size_t T = (size_t) chunk;
@@ -4069,9 +4086,17 @@ bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0,
if (lay.native) {
// plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas
const auto& f = lay.fmt[(size_t) l];
strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd,
m.dq_gu[q], m.cs);
strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs);
// 0.1.43: both matrices in one launch (the same values; STRATA_PF_DQ_FUSED=0: two launches)
static const bool dq_one = [] { const char* v = std::getenv("STRATA_PF_DQ_FUSED"); return !(v && v[0] == '0'); }();
if (dq_one) {
strata::kernels::iq_dequant_expert_f16(f.gu_type, f.d_type, blob_dev, blob_dev + f.up_off,
blob_dev + f.down_off, f.n_ff, f.n_embd, m.dq_gu[q],
m.dq_d[q], m.cs);
} else {
strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd,
m.dq_gu[q], m.cs);
strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs);
}
} else {
blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs);
}
+28 -12
View File
@@ -15,6 +15,13 @@ namespace strata::prefill::xmx {
namespace {
using half = sycl::half;
namespace jm = sycl::ext::oneapi::experimental::matrix;
// Sub-group width = the XMX tile's N: 8 on Alchemist (DG2, joint_matrix 8x8x16), 16 on Xe2 (Battlemage, 8x16x16; the
// CMake switch STRATA_XMX_SG16 for an AOT bmg / lnl build). A build has one shape: the other is not valid there.
#ifdef STRATA_XMX_SG16
constexpr int kSgW = 16;
#else
constexpr int kSgW = 8;
#endif
struct Grp {
const half* w[kMaxGroup];
@@ -26,8 +33,8 @@ struct Grp {
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 = 8;
static constexpr int BM = SGM * MT * 8, BN = SGN * NT * 8, NSG = SGM * SGN, WG = NSG * SG;
static constexpr int SG = kSgW;
static constexpr int BM = SGM * MT * 8, BN = SGN * NT * kSgW, NSG = SGM * SGN, WG = NSG * SG;
};
template <class C, class Name>
@@ -36,11 +43,12 @@ void launch(sycl::queue& q, const half* X, float* Y, const Grp& gp, int ntiles,
constexpr int LDA = KS + 8, LDB = KS + 8;
const int nb = N / BN;
#ifndef STRATA_NO_DG2_XMX
constexpr int TN = kSgW;
q.submit([&](sycl::handler& h) {
sycl::local_accessor<half, 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) ntiles, (size_t) nb * WG}, {1, (size_t) WG}), props,
[=](sycl::nd_item<2> it) [[sycl::reqd_sub_group_size(8)]] {
[=](sycl::nd_item<2> it) [[sycl::reqd_sub_group_size(kSgW)]] {
auto sg = it.get_sub_group();
const int t = (int) it.get_group(0);
int e = 0;
@@ -53,7 +61,7 @@ void launch(sycl::queue& q, const half* X, float* Y, const Grp& gp, int ntiles,
const int n0 = (int) it.get_group(1) * BN;
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, 8> acc[C::MT][C::NT];
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);
half* pa = sa.template get_multi_ptr<sycl::access::decorated::no>().get();
@@ -74,13 +82,13 @@ void launch(sycl::queue& q, const half* X, float* Y, const Grp& gp, int ntiles,
it.barrier(sycl::access::fence_space::local_space);
for (int kk = 0; kk < KS; kk += 16) {
jm::joint_matrix<sycl::sub_group, half, jm::use::a, 8, 16, jm::layout::row_major> a[C::MT];
jm::joint_matrix<sycl::sub_group, half, jm::use::b, 16, 8, jm::layout::col_major> b[C::NT];
jm::joint_matrix<sycl::sub_group, half, 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 * 8 + j * 8) * LDB + kk, LDB);
(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]);
}
@@ -90,19 +98,19 @@ void launch(sycl::queue& q, const half* X, float* Y, const Grp& gp, int ntiles,
const int r = sgm * C::MT * 8 + i * 8;
if (r >= rows) continue;
for (int j = 0; j < C::NT; ++j) {
const int c = n0 + sgn * C::NT * 8 + j * 8;
const int c = n0 + sgn * C::NT * TN + j * TN;
if (r + 8 <= rows) {
jm::joint_matrix_store(sg, acc[i][j],
sycl::address_space_cast<sycl::access::address_space::global_space, sycl::access::decorated::no>(
Ye + (size_t) r * N + c), N, jm::layout::row_major);
} else { // partial rows: through this sub-group's own SLM slice
float* st = reinterpret_cast<float*>(pa) + sgid * 64;
float* st = reinterpret_cast<float*>(pa) + sgid * 8 * TN;
jm::joint_matrix_store(sg, acc[i][j],
sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(st),
8, jm::layout::row_major);
TN, jm::layout::row_major);
sycl::group_barrier(sg);
const int lim = rows - r, ln = (int) sg.get_local_linear_id();
for (int rr = 0; rr < lim; ++rr) Ye[(size_t) (r + rr) * N + c + ln] = st[rr * 8 + ln];
for (int rr = 0; rr < lim; ++rr) Ye[(size_t) (r + rr) * N + c + ln] = st[rr * TN + ln];
sycl::group_barrier(sg);
}
}
@@ -117,8 +125,13 @@ void launch(sycl::queue& q, const half* X, float* Y, const Grp& gp, int ntiles,
}
class k_small; class k_big;
#ifdef STRATA_XMX_SG16
using Small = Cfg<2, 4, 4, 2, 32>; // 64 x 128 tile: few rows per expert (8 sub-groups of 16)
using Big = Cfg<4, 2, 4, 4, 32>; // 128 x 128 tile
#else
using Small = Cfg<2, 8, 4, 2, 32>; // 64 x 128 tile: few rows per expert
using Big = Cfg<4, 4, 4, 4, 32>; // 128 x 128 tile
#endif
template <class C>
int fill(Grp& gp, const int32_t* cnt, int n) {
@@ -133,7 +146,8 @@ int fill(Grp& gp, const int32_t* cnt, int n) {
} // namespace
int mode() {
// The kernels are joint_matrix 8x8x16 on sub-group 8: DG2 (Arc A-series) only. Battlemage has neither.
// The kernels are joint_matrix 8x8x16 on sub-group 8 (DG2, Arc A-series) or, in a STRATA_XMX_SG16 build, 8x16x16 on
// sub-group 16 (Xe2, Battlemage).
static const int v = [] {
const char* e = std::getenv("STRATA_PF_XMX");
const int want = e ? std::atoi(e) : 0;
@@ -142,10 +156,12 @@ int mode() {
std::fprintf(stderr, "STRATA_PF_XMX ignored: this build is AOT for a device without the sub-group 8 XMX kernels\n");
return 0;
#else
#ifndef STRATA_XMX_SG16
if (strata::intel_gpu_gen(strata::q_of(nullptr)->get_device()) == strata::IntelGpuGen::Battlemage) {
std::fprintf(stderr, "STRATA_PF_XMX ignored: Battlemage has no sub-group 8 / 8x8x16 joint_matrix (Arc A-series only)\n");
std::fprintf(stderr, "STRATA_PF_XMX ignored: this build has the sub-group 8 / 8x8x16 kernels (Arc A-series); Battlemage needs the AOT bmg build\n");
return 0;
}
#endif
return want;
#endif
}();
+47 -4
View File
@@ -4775,6 +4775,7 @@ int main(int argc, char **argv) try {
// miss: 20 GiB of RAM for experts the other card then holds, or one 39 GiB pinned allocation that fails).
const int64_t mirror_end = multi_gpu && !split_at.empty() ? split_at[0] : g.n_layers;
std::vector<std::pair<int64_t, int64_t>> miss;
size_t n_true_miss = 0; // the experts no slot holds; what follows them in `miss` are the lend candidates (below)
for (const auto& pr : profile) // the profile's order: the most-routed misses first, if the cap is reached
if (pr.first < mirror_end && xcache.slot_of(pr.first, pr.second) == strata::core::kNotResident)
miss.push_back({pr.first, pr.second});
@@ -4783,6 +4784,24 @@ int main(int argc, char **argv) try {
if (xcache.slot_of(l, e) == strata::core::kNotResident &&
std::find(miss.begin(), miss.end(), std::pair<int64_t, int64_t>{l, e}) == miss.end())
miss.push_back({l, e});
n_true_miss = miss.size();
// 0.1.43: the experts in the last slots - the ones a prompt's loan takes (Prefill::relayout lends the TAIL of the
// cache) - are mirrored too, after the real misses (the cap drops them first). A lent expert is streamed during
// the prompt and put back after it; from the GGUF that was a pread at ~2.3 GB/s per expert (~1 s for a 4K prompt's
// 930 slots, 0.26 s for a 600-token prompt's 284), from the pinned mirror it is a DMA. Their mirror entries are never
// read by a decode window: it only looks at a mirror address for an expert that has no slot.
// STRATA_LEND_MIRROR=0 turns it off; =N: the last N slots (default 10% of the cache with a loan, at most 1,200).
if (!o.no_prefill_borrow && o.prefill_chunk > 0 && !multi_gpu) {
const char* lm = std::getenv("STRATA_LEND_MIRROR");
const int64_t want_tail = lm ? std::atoll(lm) : std::min<int64_t>(xcache.slots() / 10, 1200);
if (want_tail > 0) {
const int64_t first_tail = xcache.slots() - std::min<int64_t>(want_tail, xcache.slots());
for (int64_t l = 0; l < mirror_end; ++l)
for (int64_t e = 0; e < g.n_expert; ++e)
if (const int64_t sl = xcache.slot_of(l, e); sl != strata::core::kNotResident && sl >= first_tail)
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;
@@ -4800,8 +4819,8 @@ int main(int argc, char **argv) try {
err.c_str());
err.clear();
} else {
std::fprintf(stderr, "strata generate: %lld of %zu experts missing from VRAM mirrored in pinned host memory "
"(%.2f GiB, %.1f s); the GPU reads them over PCIe\n", (long long) got, miss.size(),
std::fprintf(stderr, "strata generate: %lld of %zu experts missing from VRAM (+ %zu in the prompt loan's slots) mirrored in pinned host memory "
"(%.2f GiB, %.1f s); the GPU reads them over PCIe\n", (long long) got, n_true_miss, miss.size() - n_true_miss,
(double) gguf_src.mirrored_bytes() / 1073741824.0,
std::chrono::duration<double>(Clock::now() - tm).count());
// the device-built verify plan's view of it: each (layer, expert) -> its mirror address, 0 = none
@@ -4814,7 +4833,7 @@ int main(int argc, char **argv) try {
dpct::get_in_order_queue().memcpy(mirror_table_d, tab.data(), tab.size() * sizeof(unsigned long long)).wait();
}
}
unmirrored_misses = (int64_t) miss.size() - (int64_t) (gguf_src.mirrored_bytes() ? std::count_if(miss.begin(), miss.end(),
unmirrored_misses = (int64_t) n_true_miss - (int64_t) (gguf_src.mirrored_bytes() ? std::count_if(miss.begin(), miss.begin() + (ptrdiff_t) n_true_miss,
[&](const std::pair<int64_t, int64_t>& pr) { return gguf_src.pinned(pr.first, pr.second); }) : 0);
const bool no_host = [] { const char* v = std::getenv("STRATA_VERIFY_NO_HOST"); return v && *v && std::strcmp(v, "0") != 0; }();
if (unmirrored_misses > 0 && no_host) {
@@ -12037,7 +12056,13 @@ int main(int argc, char **argv) try {
strata::core::Verifier ver;
strata::core::VerifyHits vh;
vh.d_res = thits.d_res;
if (mirror_table_d) strata::kernels::resident_plan_set_mirror(thits.d_res, mirror_table_d);
int32_t* usage_dev = nullptr; // STRATA_USAGE_DUMP=PATH: the device plan counts every routed expert (measurement)
const char* usage_dump = std::getenv("STRATA_USAGE_DUMP");
if (mirror_table_d && usage_dump && *usage_dump) {
usage_dev = sycl::malloc_device<int32_t>((size_t) (g.n_layers * g.n_expert), dpct::get_in_order_queue());
dpct::get_in_order_queue().memset(usage_dev, 0, (size_t) (g.n_layers * g.n_expert) * 4).wait();
}
if (mirror_table_d) strata::kernels::resident_plan_set_mirror(thits.d_res, mirror_table_d, usage_dev);
vh.h_res = host_res.empty() ? nullptr : host_res.data();
vh.cache_base = thits.cache_base;
vh.blob = thits.blob;
@@ -12484,6 +12509,24 @@ int main(int argc, char **argv) try {
std::printf("%-24s plan %.3f activation quantize %.3f jobs %.3f run %.3f ms/round\n", "dispatch",
drive.d.ms_plan / rounds, drive.d.ms_actq / rounds, drive.d.ms_jobs / rounds,
drive.d.ms_run / rounds);
if (usage_dev != nullptr) { // STRATA_USAGE_DUMP: the window's routing as make_profile.py reads it (layer, k=1, id, weight)
std::vector<int32_t> uh((size_t) (g.n_layers * g.n_expert));
dpct::get_in_order_queue().memcpy(uh.data(), usage_dev, uh.size() * 4).wait();
if (FILE* uf = std::fopen(usage_dump, "wb")) {
int64_t total = 0;
for (int64_t l = 0; l < g.n_layers; ++l)
for (int64_t e = 0; e < g.n_expert; ++e)
for (int32_t c = 0; c < uh[(size_t) (l * g.n_expert + e)]; ++c, ++total) {
const int32_t hdr[3] = {(int32_t) l, 1, (int32_t) e};
const float wgt[2] = {0.0f, 0.0f};
std::fwrite(hdr, 4, 3, uf);
std::fwrite(wgt, 4, 1, uf); // (layer, k) + k ids + k weights: 8 + 8 bytes
}
std::fclose(uf);
std::printf("%-24s %s (%lld routed entries counted on the device)\n", "usage dumped", usage_dump,
(long long) total);
}
}
if (rounds > 0 && !drive.d.usage.empty())
std::printf("%-24s %lld experts swapped into the VRAM tier (every %d rounds, %.3f ms/round)\n", "adaptive tier",
(long long) swaps_total, o.adapt_every, ms_adapt / rounds);
+92
View File
@@ -0,0 +1,92 @@
"""tools/collect_profile_traces.py - routing traces of a varied set of prompts, for tools/make_profile_mix.py.
For every prompt of a corpus (default bench/profile_corpus.json: 45 chat, code, maths, reasoning, writing, science, tool
use and six-language prompts) it runs the engine once (greedy, --max-new tokens) and keeps the routed experts of the
generated text:
python tools/collect_profile_traces.py CONFIG.json OUTDIR [--corpus FILE] [--max-new 250] [--mode usage|routing]
CONFIG.json is a run config setup wrote (strata-*.json: "exe", "args", "env", "tokenizer", "cwd"). The engine is run as
`exe args... --tokens-file F --max-new N --greedy` (--serve and --batch are dropped). `--mode usage` (default) is the
SYCL engine's STRATA_USAGE_DUMP=PATH, which counts on the device and works with STRATA_VERIFY_NO_HOST; `--mode routing`
adds `--dump-routing PATH` (the CUDA/HIP engines and the SYCL host path). Then, for example:
python tools/make_profile_mix.py OUTDIR/c*.trace:1 --out data/expert-profile-new.bin
A prompt takes a start-up of the engine (20-60 s) and ~10 s of decoding; 45 prompts are ~30 minutes. The traces are the
generated text's routing only (decode windows); the prompt's own routing is not counted.
"""
import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
import strata_tokenizer as ST # noqa: E402
def load_tokenizer(tdir):
tdir = Path(tdir)
vocab = json.loads((tdir / "vocab.json").read_text(encoding="utf-8"))
toks = [None] * len(vocab)
for t, i in vocab.items():
toks[i] = t
return ST.Tokenizer(toks, (tdir / "merges.txt").read_text(encoding="utf-8").split("\n"),
json.loads((tdir / "token_type.json").read_text()))
def drop(args, flag, with_value=False):
args = list(args)
while flag in args:
i = args.index(flag)
del args[i:i + (2 if with_value else 1)]
return args
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("config")
ap.add_argument("outdir")
ap.add_argument("--corpus", default=str(ROOT / "bench" / "profile_corpus.json"))
ap.add_argument("--max-new", type=int, default=250)
ap.add_argument("--mode", choices=("usage", "routing"), default="usage")
ap.add_argument("--only", help="comma-separated prompt numbers (default all)")
a = ap.parse_args()
cfg = json.load(open(a.config, encoding="utf-8-sig"))
tok = load_tokenizer(cfg["tokenizer"])
corpus = json.load(open(a.corpus, encoding="utf-8"))
out = Path(a.outdir)
out.mkdir(parents=True, exist_ok=True)
args = drop(drop(cfg["args"], "--serve"), "--batch", True)
only = {int(x) for x in a.only.split(",")} if a.only else None
env0 = dict(os.environ)
env0.update({k: str(v) for k, v in cfg.get("env", {}).items()})
for n, c in enumerate(corpus):
if only is not None and n not in only:
continue
trace = out / f"c{n:02d}.trace"
if trace.exists() and trace.stat().st_size > 0:
continue
ids = tok.encode(f"<|im_start|>user\n{c['p']}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
parse_special=True)
tf = out / f"c{n:02d}.tok"
tf.write_text(",".join(str(i) for i in ids))
cmd = [cfg["exe"]] + args + ["--tokens-file", str(tf), "--max-new", str(a.max_new), "--greedy"]
env = dict(env0)
if a.mode == "usage":
env["STRATA_USAGE_DUMP"] = str(trace)
else:
cmd += ["--dump-routing", str(trace)]
print(f"[{n + 1}/{len(corpus)}] {c['d']}: {len(ids)} prompt tokens", flush=True)
r = subprocess.run(cmd, cwd=cfg.get("cwd") or None, env=env, capture_output=True, text=True)
if r.returncode != 0 or not trace.exists():
print(f" failed (rc {r.returncode}): {r.stderr[-300:]}", file=sys.stderr)
sys.exit(1)
print(f"traces in {out}")
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
"""tools/make_profile_mix.py - an expert-cache profile from several routing traces, each trace counting the same.
`make_profile.py` adds the traces' raw counts, so the longest trace decides the ranking. A cache profile should
rank the experts by how often a USER's tokens need them, across the kinds of text that user writes, so here every
trace is first turned into a distribution (its counts / its total) and multiplied by its weight; the ranking is the
weighted sum. Weights are per trace, so a kind of text with more traces counts more - give a group of N traces the
weight 1/N each to make the group count once.
python tools/make_profile_mix.py TRACE[:WEIGHT] [TRACE[:WEIGHT] ...] [--out PATH] [--n-expert 512]
A trace is a `--dump-routing` file, or a `STRATA_USAGE_DUMP` file of the SYCL engine (same record format). The output
is a profile for `--expert-profile`; the pairs no trace uses are appended in make_profile.py's fill order.
Measured on an Arc Pro B70 (IQ3_S, 11.5k cached experts, decode of 250-300 tokens): the shipped profile holds 60% of the
experts 45 chat/code/language prompts route and 85% of those a document summary routes; a profile from the 45 chat prompts
and the 8 summaries (weight 1 : 2 per prompt), tested on prompts left out of it, holds 71% and 84%.
"""
import argparse
import sys
from collections import defaultdict
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import make_profile as mp # noqa: E402
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("traces", nargs="+", help="TRACE or TRACE:WEIGHT")
ap.add_argument("--out", required=True)
ap.add_argument("--n-expert", type=int, default=mp.N_EXPERT)
a = ap.parse_args()
ne = a.n_expert
score = defaultdict(float)
for spec in a.traces:
path, weight = spec, 1.0
head, sep, tail = spec.rpartition(":")
if sep: # TRACE:WEIGHT (a Windows drive letter's colon is not followed by a number)
try:
path, weight = head, float(tail)
except ValueError:
pass
freq = mp.read_trace(path, ne)
total = float(sum(freq.values()))
if total <= 0:
print(f"{path}: empty trace, skipped")
continue
for p, c in freq.items():
score[p] += weight * c / total
ranked = [p for p, _ in sorted(score.items(), key=lambda kv: (-kv[1], kv[0]))]
seen = set(ranked)
for e in range(ne): # the fill, as make_profile.py: the pairs no trace used
for layer in range(mp.N_LAYER):
if (layer, e) not in seen:
ranked.append((layer, e))
mp.write_profile(a.out, ranked, ne)
assert mp.read_profile(a.out, ne) == ranked, "the profile did not survive the round trip"
print(f"wrote {a.out}: {len(ranked)} ranked pairs, {len(score)} from {len(a.traces)} traces")
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
"""Tests for tools/make_profile_mix.py, without a model: synthetic routing traces.
python -m unittest tools.test_make_profile_mix
"""
from __future__ import annotations
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools"))
import make_profile as MP # noqa: E402
from test_make_profile import write_trace # noqa: E402
NE = 4
def run(args):
r = subprocess.run([sys.executable, str(ROOT / "tools" / "make_profile_mix.py")] + args, capture_output=True, text=True)
assert r.returncode == 0, r.stderr
return r.stdout
class MixProfile(unittest.TestCase):
def test_a_long_trace_does_not_outvote_a_short_one(self):
with tempfile.TemporaryDirectory() as d:
long_t, short_t, out = Path(d, "long"), Path(d, "short"), Path(d, "p.bin")
# the long trace uses pair (0, 1) 1000 times and (0, 2) 100 times; the short one uses (0, 3) 5 times
write_trace(long_t, [(0, [1] * 10)] * 100 + [(0, [2] * 10)] * 10)
write_trace(short_t, [(0, [3] * 5)])
run([str(long_t), str(short_t), "--out", str(out), "--n-expert", str(NE)])
ranked = MP.read_profile(out, NE)
# as distributions: (0,1) 0.909, (0,2) 0.091 in the long one; (0,3) 1.0 in the short one -> (0,3) first
self.assertEqual(ranked[:3], [(0, 3), (0, 1), (0, 2)])
self.assertEqual(len(ranked), MP.N_LAYER * NE) # every pair, once
self.assertEqual(len(set(ranked)), len(ranked))
def test_weights(self):
with tempfile.TemporaryDirectory() as d:
a, b, out = Path(d, "a"), Path(d, "b"), Path(d, "p.bin")
write_trace(a, [(1, [0] * 4)])
write_trace(b, [(1, [2] * 4)])
run([f"{a}:1", f"{b}:3", "--out", str(out), "--n-expert", str(NE)])
self.assertEqual(MP.read_profile(out, NE)[:2], [(1, 2), (1, 0)])
run([f"{a}:3", f"{b}:1", "--out", str(out), "--n-expert", str(NE)])
self.assertEqual(MP.read_profile(out, NE)[:2], [(1, 0), (1, 2)])
if __name__ == "__main__":
unittest.main()
+11
View File
@@ -179,6 +179,17 @@ class ToSycl(unittest.TestCase):
self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "1024")
self.assertNotIn("STRATA_VERIFY_NO_HOST", c.get("env", {}))
def test_xe_ranks_the_experts_with_the_sycl_profile_and_i915_keeps_the_shipped_one(self):
m = self.mod()
shipped = str(m.MOUNT / "data" / "expert-profile.bin")
other = str(m.MOUNT / "mine" / "learned.bin")
c = m.to_sycl(self.cfg(m, ["--expert-profile", shipped]), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe")
self.assertTrue(c["args"][c["args"].index("--expert-profile") + 1].endswith("expert-profile-sycl.bin"))
c = m.to_sycl(self.cfg(m, ["--expert-profile", other]), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe")
self.assertTrue(c["args"][c["args"].index("--expert-profile") + 1].endswith("learned.bin")) # the user's own file stays
c = m.to_sycl(self.cfg(m, ["--expert-profile", shipped]), m.ROOT / "build-sycl" / "strata", 64.0, {}, 8.0, "i915")
self.assertTrue(c["args"][c["args"].index("--expert-profile") + 1].endswith("expert-profile.bin")) # the CPU computes the misses there
def test_an_explicit_reserve_is_kept_on_both_drivers(self):
m = self.mod()
for vram, drv in ((32.0, "xe"), (8.0, "i915")):