Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3af00ae761
|
||
|
|
6bd73a6ae5
|
||
|
|
22db152022
|
||
|
|
ee8322dba8
|
||
|
|
e06b901722
|
||
|
|
e956d2f0e6
|
||
|
|
0739ee5e66
|
@@ -16,6 +16,11 @@ path = "src/main.rs"
|
||||
# Not shipped in the RPM: it loads a checkpoint directly and reports
|
||||
# numbers, and exists so the go/no-go gate is a measurement rather than
|
||||
# an argument.
|
||||
[[bin]]
|
||||
name = "neuron-strata-expert-probe"
|
||||
path = "src/bin/strata_expert_probe.rs"
|
||||
required-features = ["strata-kernels"]
|
||||
|
||||
[[bin]]
|
||||
name = "neuron-mtp-probe"
|
||||
path = "src/bin/mtp_probe.rs"
|
||||
@@ -48,6 +53,9 @@ flash-attn = [
|
||||
"candle-transformers/flash-attn",
|
||||
"dep:candle-flash-attn",
|
||||
]
|
||||
# The expert kernels vendored from Strata (`vendor/strata`, MIT). Needs
|
||||
# nvcc with C++20 and `CUDA_COMPUTE_CAP`.
|
||||
strata-kernels = ["cuda"]
|
||||
# Reserved for GPU-only integration tests in later stages.
|
||||
cuda-integration = ["cuda"]
|
||||
|
||||
|
||||
@@ -54,6 +54,8 @@ fn main() {
|
||||
.expect("neuron cuda build failed");
|
||||
println!("cargo:rustc-link-search={}", build_dir.display());
|
||||
println!("cargo:rustc-link-lib=neuroncuda");
|
||||
#[cfg(feature = "strata-kernels")]
|
||||
build_strata_kernels(&build_dir);
|
||||
println!("cargo:rustc-link-lib=dylib=cudart");
|
||||
|
||||
if target.contains("msvc") {
|
||||
@@ -71,6 +73,72 @@ fn main() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Compile the vendored Strata expert kernels and neuron's C shim.
|
||||
///
|
||||
/// They need C++20 and must not get the `--use_fast_math` the kernels
|
||||
/// above are built with: upstream builds this file without it, and
|
||||
/// contraction would change the rounding its parity relies on.
|
||||
#[cfg(feature = "strata-kernels")]
|
||||
fn build_strata_kernels(build_dir: &std::path::Path) {
|
||||
println!("cargo:rerun-if-changed=vendor/strata");
|
||||
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/strata_shim.cu");
|
||||
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/strata_probe.cu");
|
||||
println!("cargo:rerun-if-env-changed=CUDA_COMPUTE_CAP");
|
||||
let cap = std::env::var("CUDA_COMPUTE_CAP").expect("strata-kernels needs CUDA_COMPUTE_CAP");
|
||||
let root = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
|
||||
let vendor = root.join("vendor/strata/engine");
|
||||
let sources = [
|
||||
// UD-IQ4_XS has no NVFP4 experts, so upstream's stub satisfies
|
||||
// the reference from the grouped dispatch.
|
||||
(
|
||||
"strata_nvfp4_absent.o",
|
||||
vendor.join("src/kernels/cuda/nvfp4_decode_sm120_absent.cpp"),
|
||||
),
|
||||
(
|
||||
"strata_iq_kernels.o",
|
||||
vendor.join("src/kernels/cuda/iq_kernels.cu"),
|
||||
),
|
||||
(
|
||||
"strata_shim.o",
|
||||
root.join("src/cuda/strata_adapter/strata_shim.cu"),
|
||||
),
|
||||
(
|
||||
"strata_probe.o",
|
||||
root.join("src/cuda/strata_adapter/strata_probe.cu"),
|
||||
),
|
||||
];
|
||||
let mut objects = Vec::new();
|
||||
for (name, source) in &sources {
|
||||
let object = build_dir.join(name);
|
||||
let status = Command::new("nvcc")
|
||||
.args(["-O3", "-DNDEBUG", "-std=c++20"])
|
||||
.arg(format!(
|
||||
"--generate-code=arch=compute_{cap},code=[compute_{cap},sm_{cap}]"
|
||||
))
|
||||
.args(["-DSTRATA_Q6K_EXPERTS=1", "-DSTRATA_VERIFY_MAX_T=8"])
|
||||
.arg(format!("-I{}", vendor.join("third_party/ggml").display()))
|
||||
.arg(format!("-I{}", vendor.join("include").display()))
|
||||
.args(["--compiler-options", "-fPIC", "-c"])
|
||||
.arg(source)
|
||||
.arg("-o")
|
||||
.arg(&object)
|
||||
.status()
|
||||
.expect("run nvcc");
|
||||
assert!(status.success(), "nvcc failed on {}", source.display());
|
||||
objects.push(object);
|
||||
}
|
||||
let library = build_dir.join("libneuronstrata.a");
|
||||
let _ = std::fs::remove_file(&library);
|
||||
let status = Command::new("ar")
|
||||
.arg("rcs")
|
||||
.arg(&library)
|
||||
.args(&objects)
|
||||
.status()
|
||||
.expect("run ar");
|
||||
assert!(status.success(), "ar failed");
|
||||
println!("cargo:rustc-link-lib=static=neuronstrata");
|
||||
}
|
||||
|
||||
/// Emit `cargo:rustc-env=` vars consumed by `env!()` in `src/version.rs`
|
||||
/// so the daemon can report its own build identity from `GET /version`.
|
||||
///
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Checks the vendored Strata expert kernels against real GGUF weights.
|
||||
//!
|
||||
//! ```sh
|
||||
//! neuron-strata-expert-probe SHARD GU_TYPE DOWN_TYPE GATE_OFF UP_OFF DOWN_OFF [EXPERT] [TOKENS]
|
||||
//! ```
|
||||
//!
|
||||
//! Offsets are the absolute file offsets of the layer's fused tensors.
|
||||
|
||||
use std::ffi::CString;
|
||||
|
||||
use neuron::cuda::strata::neuron_strata_expert_probe;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.len() < 7 {
|
||||
eprintln!(
|
||||
"usage: {} SHARD GU DOWN GATE_OFF UP_OFF DOWN_OFF [EXPERT] [TOKENS]",
|
||||
args[0]
|
||||
);
|
||||
std::process::exit(64);
|
||||
}
|
||||
let int = |i: usize, default: u64| -> u64 {
|
||||
args.get(i)
|
||||
.map(|v| v.parse().expect("integer argument"))
|
||||
.unwrap_or(default)
|
||||
};
|
||||
let path = CString::new(args[1].as_str()).expect("path");
|
||||
let (mut error, mut ms) = (f64::NAN, f64::NAN);
|
||||
let (expert, tokens) = (int(7, 0) as i32, int(8, 8) as i32);
|
||||
// SAFETY: the path is NUL-terminated and both out-pointers are live
|
||||
// for the call; the probe owns every device allocation it makes.
|
||||
let rc = unsafe {
|
||||
neuron_strata_expert_probe(
|
||||
path.as_ptr(),
|
||||
int(2, 0) as i32,
|
||||
int(3, 0) as i32,
|
||||
int(4, 0),
|
||||
int(5, 0),
|
||||
int(6, 0),
|
||||
expert,
|
||||
tokens,
|
||||
&mut error,
|
||||
&mut ms,
|
||||
)
|
||||
};
|
||||
if rc != 0 {
|
||||
eprintln!("probe failed: code {rc}");
|
||||
std::process::exit(rc);
|
||||
}
|
||||
println!(
|
||||
"gu={} down={} expert={expert} tokens={tokens} relative_error={error:.5} kernel_ms={ms:.3}",
|
||||
args[2], args[3]
|
||||
);
|
||||
}
|
||||
@@ -13,3 +13,5 @@
|
||||
pub mod ffi;
|
||||
#[cfg(feature = "cuda")]
|
||||
pub mod gdn;
|
||||
#[cfg(feature = "strata-kernels")]
|
||||
pub mod strata;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! FFI to the expert kernels vendored from Strata (`vendor/strata`).
|
||||
//!
|
||||
//! Pointers are device addresses unless a parameter says otherwise, and
|
||||
//! `stream` is a CUDA stream handle (null for the default stream).
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
|
||||
unsafe extern "C" {
|
||||
/// Parity of two real experts against a CPU recomputation. Returns 0
|
||||
/// on success.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn neuron_strata_expert_probe(
|
||||
path: *const c_char,
|
||||
gu: i32,
|
||||
down: i32,
|
||||
gate_off: u64,
|
||||
up_off: u64,
|
||||
down_off: u64,
|
||||
first_expert: i32,
|
||||
tokens: i32,
|
||||
relative_error: *mut f64,
|
||||
kernel_ms: *mut f64,
|
||||
) -> i32;
|
||||
pub fn neuron_strata_pinned_alloc(bytes: usize) -> *mut c_void;
|
||||
pub fn neuron_strata_pinned_free(p: *mut c_void);
|
||||
/// Queues a copy on `stream`. `pinned_src` must stay unchanged until
|
||||
/// the stream has passed it. Returns the CUDA status.
|
||||
pub fn neuron_strata_copy_to_device(
|
||||
dst: *mut c_void,
|
||||
pinned_src: *const c_void,
|
||||
bytes: usize,
|
||||
stream: *mut c_void,
|
||||
) -> i32;
|
||||
pub fn neuron_strata_expert_supported(gu_type: i32, d_type: i32, n_embd: i64, n_ff: i64)
|
||||
-> i32;
|
||||
pub fn neuron_strata_row_bytes(ggml_type: i32, n: i64) -> usize;
|
||||
pub fn neuron_strata_expert_bytes(gu_type: i32, d_type: i32, n_embd: i64, n_ff: i64) -> usize;
|
||||
pub fn neuron_strata_expert_scratch_bytes(cap_entries: i64, n_ff: i64) -> usize;
|
||||
pub fn neuron_strata_quantize_q8_1(
|
||||
x: *const f32,
|
||||
n_rows: i64,
|
||||
n_cols: i64,
|
||||
y: *mut c_void,
|
||||
stream: *mut c_void,
|
||||
);
|
||||
/// Whether `neuron_strata_mmvq` takes weights of `ggml_type`.
|
||||
pub fn neuron_strata_mmvq_supported(ggml_type: i32) -> i32;
|
||||
/// `y[c][r] = W[r] . x[c]` for `ncols` q8_1 activation rows.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn neuron_strata_mmvq(
|
||||
ggml_type: i32,
|
||||
w: *const c_void,
|
||||
x_q8_1: *const c_void,
|
||||
y: *mut f32,
|
||||
n_in: i32,
|
||||
n_out: i32,
|
||||
ncols: i32,
|
||||
stream: *mut c_void,
|
||||
);
|
||||
pub fn neuron_strata_dequant_f32(
|
||||
ggml_type: i32,
|
||||
src: *const c_void,
|
||||
n: i64,
|
||||
dst: *mut f32,
|
||||
stream: *mut c_void,
|
||||
);
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn neuron_strata_expert_grouped(
|
||||
gu_type: i32,
|
||||
d_type: i32,
|
||||
n_embd: i64,
|
||||
n_ff: i64,
|
||||
grp_ptr: *const u64,
|
||||
grp_start: *const i32,
|
||||
n_groups: *const i32,
|
||||
ent_dst: *const i32,
|
||||
ent_tok: *const i32,
|
||||
cap_groups: i64,
|
||||
cap_entries: i64,
|
||||
x_q8_1: *const c_void,
|
||||
scratch: *mut c_void,
|
||||
out: *mut f32,
|
||||
stream: *mut c_void,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// Parity probe for the vendored expert kernels on real GGUF weights.
|
||||
//
|
||||
// Runs two experts over random activations through the grouped kernels,
|
||||
// then recomputes the SwiGLU on the CPU from independently dequantised
|
||||
// weights. The kernels read 8-bit activations, so a small error is
|
||||
// expected; a wrong layout or block format produces a large one.
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
|
||||
namespace k = strata::kernels;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int64_t kEmbd = 2560;
|
||||
constexpr int64_t kFf = 640;
|
||||
constexpr size_t kQ81Block = 36; // fp16 scale, fp16 sum, 32 int8 values
|
||||
|
||||
template <typename T>
|
||||
T* device_alloc(size_t count) {
|
||||
T* p = nullptr;
|
||||
if (cudaMalloc(&p, count * sizeof(T)) != cudaSuccess) return nullptr;
|
||||
return p;
|
||||
}
|
||||
|
||||
bool read_at(int fd, uint8_t* dst, size_t bytes, uint64_t offset) {
|
||||
size_t done = 0;
|
||||
while (done < bytes) {
|
||||
const ssize_t n = pread(fd, dst + done, bytes - done, offset + done);
|
||||
if (n <= 0) return false;
|
||||
done += static_cast<size_t>(n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<float> dequant(int type, const uint8_t* device_src, int64_t n) {
|
||||
float* d = device_alloc<float>(n);
|
||||
std::vector<float> host(n);
|
||||
k::iq_dequant_f32(type, device_src, n, d, nullptr);
|
||||
cudaMemcpy(host.data(), d, n * sizeof(float), cudaMemcpyDeviceToHost);
|
||||
cudaFree(d);
|
||||
return host;
|
||||
}
|
||||
|
||||
float silu(float x) { return x / (1.0f + std::exp(-x)); }
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int neuron_strata_expert_probe(const char* path, int gu, int dn, uint64_t gate_off, uint64_t up_off,
|
||||
uint64_t down_off, int first_expert, int tokens, double* relative_error,
|
||||
double* kernel_ms) {
|
||||
if (!k::native_expert_supported(gu, dn, kEmbd, kFf) || tokens < 1) return 2;
|
||||
const k::NativeExpertLayout L = k::native_expert_layout(gu, dn, kEmbd, kFf);
|
||||
const size_t gate_bytes = kFf * L.gu_row, down_bytes = kEmbd * L.d_row;
|
||||
const int fd = open(path, O_RDONLY);
|
||||
if (fd < 0) return 3;
|
||||
constexpr int groups = 2;
|
||||
std::vector<uint8_t> blobs(groups * L.bytes);
|
||||
for (int g = 0; g < groups; ++g) {
|
||||
const uint64_t e = first_expert + g;
|
||||
uint8_t* blob = blobs.data() + g * L.bytes;
|
||||
if (!read_at(fd, blob, gate_bytes, gate_off + e * gate_bytes) ||
|
||||
!read_at(fd, blob + L.up_off, gate_bytes, up_off + e * gate_bytes) ||
|
||||
!read_at(fd, blob + L.down_off, down_bytes, down_off + e * down_bytes)) {
|
||||
close(fd);
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
|
||||
std::mt19937 rng(1234);
|
||||
std::uniform_real_distribution<float> dist(-2.0f, 2.0f);
|
||||
std::vector<float> x(tokens * kEmbd);
|
||||
for (float& v : x) v = dist(rng);
|
||||
|
||||
const int64_t entries = groups * tokens;
|
||||
auto* d_blobs = device_alloc<uint8_t>(blobs.size());
|
||||
auto* d_x = device_alloc<float>(x.size());
|
||||
auto* d_q = device_alloc<uint8_t>(tokens * (kEmbd / 32) * kQ81Block);
|
||||
auto* d_ptr = device_alloc<unsigned long long>(groups);
|
||||
auto* d_start = device_alloc<int32_t>(groups + 1);
|
||||
auto* d_n = device_alloc<int32_t>(1);
|
||||
auto* d_dst = device_alloc<int32_t>(entries);
|
||||
auto* d_tok = device_alloc<int32_t>(entries);
|
||||
auto* d_out = device_alloc<float>(entries * kEmbd);
|
||||
auto* d_scratch = device_alloc<uint8_t>(k::native_expert_scratch_bytes(entries, kFf));
|
||||
if (!d_blobs || !d_x || !d_q || !d_ptr || !d_start || !d_n || !d_dst || !d_tok || !d_out || !d_scratch) return 5;
|
||||
|
||||
std::vector<unsigned long long> ptrs(groups);
|
||||
std::vector<int32_t> start(groups + 1), dst(entries), tok(entries);
|
||||
for (int g = 0; g < groups; ++g) {
|
||||
ptrs[g] = reinterpret_cast<unsigned long long>(d_blobs + g * L.bytes);
|
||||
start[g] = g * tokens;
|
||||
for (int t = 0; t < tokens; ++t) {
|
||||
dst[g * tokens + t] = g * tokens + t;
|
||||
tok[g * tokens + t] = t;
|
||||
}
|
||||
}
|
||||
start[groups] = entries;
|
||||
const int32_t n_groups = groups;
|
||||
cudaMemcpy(d_blobs, blobs.data(), blobs.size(), cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(d_ptr, ptrs.data(), groups * sizeof(unsigned long long), cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(d_start, start.data(), start.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(d_n, &n_groups, sizeof(int32_t), cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(d_dst, dst.data(), dst.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(d_tok, tok.data(), tok.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
||||
k::quantize_q8_1_rows(d_x, tokens, kEmbd, d_q, nullptr);
|
||||
cudaDeviceSynchronize();
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
k::native_expert_grouped(L, d_ptr, d_start, d_n, d_dst, d_tok, groups, entries, d_q, d_scratch, d_out, nullptr);
|
||||
if (cudaDeviceSynchronize() != cudaSuccess) return 6;
|
||||
*kernel_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
|
||||
|
||||
std::vector<float> out(entries * kEmbd);
|
||||
cudaMemcpy(out.data(), d_out, out.size() * sizeof(float), cudaMemcpyDeviceToHost);
|
||||
|
||||
double err = 0.0, norm = 0.0;
|
||||
std::vector<float> h(kFf);
|
||||
for (int g = 0; g < groups; ++g) {
|
||||
const uint8_t* blob = d_blobs + g * L.bytes;
|
||||
const auto gate = dequant(L.gu_type, blob, kFf * kEmbd);
|
||||
const auto up = dequant(L.gu_type, blob + L.up_off, kFf * kEmbd);
|
||||
const auto down = dequant(L.d_type, blob + L.down_off, kEmbd * kFf);
|
||||
for (int t = 0; t < tokens; ++t) {
|
||||
const float* xt = x.data() + t * kEmbd;
|
||||
for (int64_t r = 0; r < kFf; ++r) {
|
||||
float a = 0.0f, b = 0.0f;
|
||||
for (int64_t c = 0; c < kEmbd; ++c) {
|
||||
a += gate[r * kEmbd + c] * xt[c];
|
||||
b += up[r * kEmbd + c] * xt[c];
|
||||
}
|
||||
h[r] = silu(a) * b;
|
||||
}
|
||||
const float* got = out.data() + (g * tokens + t) * kEmbd;
|
||||
for (int64_t r = 0; r < kEmbd; ++r) {
|
||||
float y = 0.0f;
|
||||
for (int64_t c = 0; c < kFf; ++c) y += down[r * kFf + c] * h[c];
|
||||
err += (double(got[r]) - y) * (double(got[r]) - y);
|
||||
norm += double(y) * y;
|
||||
}
|
||||
}
|
||||
}
|
||||
*relative_error = std::sqrt(err / norm);
|
||||
|
||||
for (void* p : {static_cast<void*>(d_blobs), static_cast<void*>(d_x), static_cast<void*>(d_q),
|
||||
static_cast<void*>(d_ptr), static_cast<void*>(d_start), static_cast<void*>(d_n),
|
||||
static_cast<void*>(d_dst), static_cast<void*>(d_tok), static_cast<void*>(d_out),
|
||||
static_cast<void*>(d_scratch)}) {
|
||||
cudaFree(p);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// C ABI over the vendored Strata expert kernels (`vendor/strata`).
|
||||
//
|
||||
// Rust cannot name the C++ layout struct or its default arguments, so
|
||||
// every call here takes the expert's formats and rebuilds the layout.
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
|
||||
namespace k = strata::kernels;
|
||||
|
||||
extern "C" {
|
||||
|
||||
int neuron_strata_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
|
||||
return k::native_expert_supported(gu_type, d_type, n_embd, n_ff) ? 1 : 0;
|
||||
}
|
||||
|
||||
size_t neuron_strata_row_bytes(int ggml_type, int64_t n) { return k::iq_row_bytes(ggml_type, n); }
|
||||
|
||||
size_t neuron_strata_expert_bytes(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
|
||||
return k::native_expert_layout(gu_type, d_type, n_embd, n_ff).bytes;
|
||||
}
|
||||
|
||||
size_t neuron_strata_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff) {
|
||||
return k::native_expert_scratch_bytes(cap_entries, n_ff);
|
||||
}
|
||||
|
||||
void neuron_strata_quantize_q8_1(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) {
|
||||
k::quantize_q8_1_rows(x, n_rows, n_cols, y, stream);
|
||||
}
|
||||
|
||||
int neuron_strata_mmvq_supported(int ggml_type) {
|
||||
switch (ggml_type) {
|
||||
// iq_kernels.cu's STRATA_MMVQ_FMTS.
|
||||
case 16: case 17: case 18: case 20: case 21: case 22: case 23: case 29: case 42:
|
||||
case 10: case 11: case 12: case 13: case 7: case 6: case 2: case 3: case 8: case 40:
|
||||
case 144: case 145: case 146: case 147: case 148: case 149:
|
||||
return 1;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void neuron_strata_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols,
|
||||
void* stream) {
|
||||
k::iq_mmvq(ggml_type, w, x_q8_1, y, n_in, n_out, ncols, stream);
|
||||
}
|
||||
|
||||
void neuron_strata_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream) {
|
||||
k::iq_dequant_f32(ggml_type, src, n, dst, stream);
|
||||
}
|
||||
|
||||
void neuron_strata_expert_grouped(int gu_type, int d_type, int64_t n_embd, int64_t n_ff,
|
||||
const unsigned long long* grp_ptr, const int32_t* grp_start,
|
||||
const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok,
|
||||
int64_t cap_groups, int64_t cap_entries, const void* x_q8_1, void* scratch,
|
||||
float* out, void* stream) {
|
||||
const k::NativeExpertLayout layout = k::native_expert_layout(gu_type, d_type, n_embd, n_ff);
|
||||
k::native_expert_grouped(layout, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, cap_groups, cap_entries, x_q8_1,
|
||||
scratch, out, stream);
|
||||
}
|
||||
|
||||
void* neuron_strata_pinned_alloc(size_t bytes) {
|
||||
void* p = nullptr;
|
||||
return cudaHostAlloc(&p, bytes, cudaHostAllocDefault) == cudaSuccess ? p : nullptr;
|
||||
}
|
||||
|
||||
void neuron_strata_pinned_free(void* p) { cudaFreeHost(p); }
|
||||
|
||||
int neuron_strata_copy_to_device(void* dst, const void* pinned_src, size_t bytes, void* stream) {
|
||||
return cudaMemcpyAsync(dst, pinned_src, bytes, cudaMemcpyHostToDevice, static_cast<cudaStream_t>(stream));
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,324 @@
|
||||
//! A byte-budgeted VRAM tier for host-resident routed experts (#318).
|
||||
//!
|
||||
//! A model whose experts exceed VRAM keeps all of them in host memory.
|
||||
//! Routing is skewed, so a modest share of them serves most tokens, and
|
||||
//! each expert held on the device is one the CPU does not have to
|
||||
//! compute. The tier is shared by every MoE block of a model because the
|
||||
//! budget is a property of the card and heat varies between layers.
|
||||
//!
|
||||
//! Slots are sized in bytes rather than counted: expert sizes differ
|
||||
//! between layers and quantisation types, and a slot count sized for the
|
||||
//! largest wastes VRAM on the rest.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// The VRAM budget from `NEURON_EXPERT_CACHE_MB`, when one is set.
|
||||
pub fn configured_budget_mb() -> Option<u64> {
|
||||
std::env::var("NEURON_EXPERT_CACHE_MB")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.filter(|&mb| mb > 0)
|
||||
}
|
||||
|
||||
/// `(block, expert)`. Blocks are numbered as they register.
|
||||
type Key = (u32, u32);
|
||||
|
||||
struct Entry<T> {
|
||||
value: Arc<T>,
|
||||
bytes: u64,
|
||||
stamp: u64,
|
||||
}
|
||||
|
||||
/// Least-recently-used map with a byte budget.
|
||||
struct ByteLru<T> {
|
||||
capacity: u64,
|
||||
used: u64,
|
||||
clock: u64,
|
||||
entries: HashMap<Key, Entry<T>>,
|
||||
by_age: BTreeMap<u64, Key>,
|
||||
}
|
||||
|
||||
impl<T> ByteLru<T> {
|
||||
fn new(capacity: u64) -> Self {
|
||||
Self {
|
||||
capacity,
|
||||
used: 0,
|
||||
clock: 0,
|
||||
entries: HashMap::new(),
|
||||
by_age: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&mut self) -> u64 {
|
||||
self.clock += 1;
|
||||
self.clock
|
||||
}
|
||||
|
||||
fn get(&mut self, key: Key) -> Option<Arc<T>> {
|
||||
let stamp = self.tick();
|
||||
let entry = self.entries.get_mut(&key)?;
|
||||
self.by_age.remove(&entry.stamp);
|
||||
entry.stamp = stamp;
|
||||
self.by_age.insert(stamp, key);
|
||||
Some(entry.value.clone())
|
||||
}
|
||||
|
||||
/// Bytes that must be released before `bytes` more can be held.
|
||||
/// Returns how many entries were evicted.
|
||||
fn make_room(&mut self, bytes: u64) -> u64 {
|
||||
let mut evicted = 0;
|
||||
while self.used + bytes > self.capacity {
|
||||
let Some((_, key)) = self.by_age.pop_first() else {
|
||||
break;
|
||||
};
|
||||
if let Some(entry) = self.entries.remove(&key) {
|
||||
self.used -= entry.bytes;
|
||||
evicted += 1;
|
||||
}
|
||||
}
|
||||
evicted
|
||||
}
|
||||
|
||||
fn insert(&mut self, key: Key, value: Arc<T>, bytes: u64) {
|
||||
let stamp = self.tick();
|
||||
self.used += bytes;
|
||||
self.by_age.insert(stamp, key);
|
||||
self.entries.insert(
|
||||
key,
|
||||
Entry {
|
||||
value,
|
||||
bytes,
|
||||
stamp,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Cumulative counters, for measurement.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct TierStats {
|
||||
pub hits: u64,
|
||||
pub misses: u64,
|
||||
pub evictions: u64,
|
||||
/// Lookups that may not admit: a prompt chunk's.
|
||||
pub prompt_hits: u64,
|
||||
pub prompt_misses: u64,
|
||||
pub used_bytes: u64,
|
||||
pub entries: u64,
|
||||
}
|
||||
|
||||
struct State<T> {
|
||||
lru: ByteLru<T>,
|
||||
hits: u64,
|
||||
misses: u64,
|
||||
evictions: u64,
|
||||
prompt_hits: u64,
|
||||
prompt_misses: u64,
|
||||
next_block: u32,
|
||||
}
|
||||
|
||||
/// The tier itself. `T` is the device-resident expert.
|
||||
pub struct ExpertTier<T> {
|
||||
state: Mutex<State<T>>,
|
||||
}
|
||||
|
||||
impl<T> ExpertTier<T> {
|
||||
pub fn new(capacity_bytes: u64) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
state: Mutex::new(State {
|
||||
lru: ByteLru::new(capacity_bytes),
|
||||
hits: 0,
|
||||
misses: 0,
|
||||
evictions: 0,
|
||||
prompt_hits: 0,
|
||||
prompt_misses: 0,
|
||||
next_block: 0,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// A number identifying one MoE block's experts within the tier.
|
||||
pub fn register_block(&self) -> u32 {
|
||||
let mut state = self.state.lock().expect("expert tier lock");
|
||||
let block = state.next_block;
|
||||
state.next_block += 1;
|
||||
block
|
||||
}
|
||||
|
||||
/// The expert, from the tier or from `load`.
|
||||
///
|
||||
/// Room is made *before* `load` runs, so the outgoing expert's VRAM
|
||||
/// is available to the incoming one. An expert larger than the whole
|
||||
/// budget is returned without being retained.
|
||||
pub fn get_or_load<E>(
|
||||
&self,
|
||||
block: u32,
|
||||
expert: u32,
|
||||
bytes: u64,
|
||||
load: impl FnOnce() -> Result<T, E>,
|
||||
) -> Result<Arc<T>, E> {
|
||||
let key = (block, expert);
|
||||
let retain = {
|
||||
let mut state = self.state.lock().expect("expert tier lock");
|
||||
if let Some(value) = state.lru.get(key) {
|
||||
state.hits += 1;
|
||||
return Ok(value);
|
||||
}
|
||||
state.misses += 1;
|
||||
let retain = bytes <= state.lru.capacity;
|
||||
if retain {
|
||||
let evicted = state.lru.make_room(bytes);
|
||||
state.evictions += evicted;
|
||||
}
|
||||
retain
|
||||
};
|
||||
let value = Arc::new(load()?);
|
||||
if retain {
|
||||
let mut state = self.state.lock().expect("expert tier lock");
|
||||
state.lru.insert(key, value.clone(), bytes);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// The expert if it is held, without admitting it or refreshing it.
|
||||
///
|
||||
/// A prompt chunk touches more experts than the tier holds, once
|
||||
/// each. Letting that scan admit or reorder would replace the set
|
||||
/// decode keeps returning to with experts it may never use again.
|
||||
pub fn peek(&self, block: u32, expert: u32) -> Option<Arc<T>> {
|
||||
let mut state = self.state.lock().expect("expert tier lock");
|
||||
let value = state
|
||||
.lru
|
||||
.entries
|
||||
.get(&(block, expert))
|
||||
.map(|entry| entry.value.clone());
|
||||
if value.is_some() {
|
||||
state.prompt_hits += 1;
|
||||
} else {
|
||||
state.prompt_misses += 1;
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
/// The byte budget.
|
||||
pub fn capacity_bytes(&self) -> u64 {
|
||||
self.state.lock().expect("expert tier lock").lru.capacity
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> TierStats {
|
||||
let state = self.state.lock().expect("expert tier lock");
|
||||
TierStats {
|
||||
hits: state.hits,
|
||||
misses: state.misses,
|
||||
evictions: state.evictions,
|
||||
prompt_hits: state.prompt_hits,
|
||||
prompt_misses: state.prompt_misses,
|
||||
used_bytes: state.lru.used,
|
||||
entries: state.lru.entries.len() as u64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
fn fetch(tier: &ExpertTier<u32>, expert: u32, bytes: u64, loads: &Cell<u32>) -> u32 {
|
||||
*tier
|
||||
.get_or_load::<()>(0, expert, bytes, || {
|
||||
loads.set(loads.get() + 1);
|
||||
Ok(expert)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hit_does_not_load_again() {
|
||||
let tier = ExpertTier::new(100);
|
||||
let loads = Cell::new(0);
|
||||
assert_eq!(fetch(&tier, 7, 10, &loads), 7);
|
||||
assert_eq!(fetch(&tier, 7, 10, &loads), 7);
|
||||
assert_eq!(loads.get(), 1);
|
||||
let stats = tier.stats();
|
||||
assert_eq!((stats.hits, stats.misses, stats.used_bytes), (1, 1, 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_least_recently_used_expert_is_evicted() {
|
||||
let tier = ExpertTier::new(30);
|
||||
let loads = Cell::new(0);
|
||||
fetch(&tier, 1, 10, &loads);
|
||||
fetch(&tier, 2, 10, &loads);
|
||||
fetch(&tier, 3, 10, &loads);
|
||||
// Touching 1 leaves 2 as the oldest.
|
||||
fetch(&tier, 1, 10, &loads);
|
||||
fetch(&tier, 4, 10, &loads);
|
||||
assert_eq!(loads.get(), 4);
|
||||
fetch(&tier, 1, 10, &loads);
|
||||
assert_eq!(loads.get(), 4, "1 was recently used and must survive");
|
||||
fetch(&tier, 2, 10, &loads);
|
||||
assert_eq!(loads.get(), 5, "2 was the oldest and must have gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_budget_is_in_bytes_and_is_never_exceeded() {
|
||||
let tier = ExpertTier::new(50);
|
||||
let loads = Cell::new(0);
|
||||
for (expert, bytes) in [(1, 20), (2, 20), (3, 30), (4, 5), (5, 45)] {
|
||||
fetch(&tier, expert, bytes, &loads);
|
||||
assert!(tier.stats().used_bytes <= 50);
|
||||
}
|
||||
assert_eq!(tier.stats().used_bytes, 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_expert_larger_than_the_budget_is_served_but_not_kept() {
|
||||
let tier = ExpertTier::new(10);
|
||||
let loads = Cell::new(0);
|
||||
fetch(&tier, 1, 5, &loads);
|
||||
assert_eq!(fetch(&tier, 2, 11, &loads), 2);
|
||||
let stats = tier.stats();
|
||||
assert_eq!((stats.used_bytes, stats.entries), (5, 1));
|
||||
fetch(&tier, 1, 5, &loads);
|
||||
assert_eq!(loads.get(), 2, "the oversized expert must not evict 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocks_do_not_share_experts() {
|
||||
let tier: Arc<ExpertTier<u32>> = ExpertTier::new(100);
|
||||
let (a, b) = (tier.register_block(), tier.register_block());
|
||||
assert_ne!(a, b);
|
||||
let first = tier.get_or_load::<()>(a, 3, 10, || Ok(30)).unwrap();
|
||||
let second = tier.get_or_load::<()>(b, 3, 10, || Ok(40)).unwrap();
|
||||
assert_eq!((*first, *second), (30, 40));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prompt_scan_neither_admits_nor_reorders() {
|
||||
let tier = ExpertTier::new(20);
|
||||
let loads = Cell::new(0);
|
||||
fetch(&tier, 1, 10, &loads);
|
||||
fetch(&tier, 2, 10, &loads);
|
||||
// Peeking at 1 must not make it newer than 2.
|
||||
assert_eq!(tier.peek(0, 1).as_deref(), Some(&1));
|
||||
assert!(tier.peek(0, 9).is_none());
|
||||
let stats = tier.stats();
|
||||
assert_eq!(
|
||||
(stats.prompt_hits, stats.prompt_misses, stats.entries),
|
||||
(1, 1, 2)
|
||||
);
|
||||
fetch(&tier, 3, 10, &loads);
|
||||
assert!(tier.peek(0, 1).is_none(), "1 was still the oldest");
|
||||
assert!(tier.peek(0, 2).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_load_retains_nothing() {
|
||||
let tier: Arc<ExpertTier<u32>> = ExpertTier::new(100);
|
||||
assert!(tier.get_or_load(0, 1, 10, || Err("oom")).is_err());
|
||||
let stats = tier.stats();
|
||||
assert_eq!((stats.used_bytes, stats.entries), (0, 0));
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,10 @@ pub(crate) fn attention_context(
|
||||
}
|
||||
}
|
||||
|
||||
if let AttnMask::Additive(m) = attn_mask {
|
||||
return masked_attention(q, k, v, m, num_kv_groups, scale);
|
||||
}
|
||||
|
||||
// Eager fallback: materialise GQA-repeated K/V and the score matrix.
|
||||
let k = repeat_kv(k.clone(), num_kv_groups)?.contiguous()?;
|
||||
let v = repeat_kv(v.clone(), num_kv_groups)?.contiguous()?;
|
||||
@@ -165,6 +169,77 @@ pub(crate) fn attention_context(
|
||||
probs.matmul(&v)
|
||||
}
|
||||
|
||||
/// Score elements one query tile may hold: 2^26, about 0.75 GB across
|
||||
/// the bf16 scores and the f32 softmax. A tile is as many queries as fit.
|
||||
const SCORE_TILE_ELEMENTS: usize = 1 << 26;
|
||||
|
||||
/// Attention under an arbitrary additive mask, `(B, 1, L, S)` — the
|
||||
/// path every [`AttnMask::Additive`] takes.
|
||||
///
|
||||
/// Equal to plain eager attention, with two changes
|
||||
/// that bound its memory so long prompts can be read in large chunks:
|
||||
///
|
||||
/// - GQA without copying K/V: each KV head's query heads are folded
|
||||
/// into the row axis, so the matmul reads the shared K/V once rather
|
||||
/// than a 12x repeat of the whole cache.
|
||||
/// - Queries are processed in tiles sized to [`SCORE_TILE_ELEMENTS`],
|
||||
/// so a chunk of `L` queries over `S` positions never holds the full
|
||||
/// `heads * L * S` scores.
|
||||
///
|
||||
/// The mask add and softmax run in f32, as the reference does.
|
||||
fn masked_attention(
|
||||
q: &Tensor,
|
||||
k: &Tensor,
|
||||
v: &Tensor,
|
||||
mask: &Tensor,
|
||||
num_kv_groups: usize,
|
||||
scale: f64,
|
||||
) -> candle_core::Result<Tensor> {
|
||||
masked_attention_tiled(q, k, v, mask, num_kv_groups, scale, SCORE_TILE_ELEMENTS)
|
||||
}
|
||||
|
||||
fn masked_attention_tiled(
|
||||
q: &Tensor,
|
||||
k: &Tensor,
|
||||
v: &Tensor,
|
||||
mask: &Tensor,
|
||||
num_kv_groups: usize,
|
||||
scale: f64,
|
||||
tile_elements: usize,
|
||||
) -> candle_core::Result<Tensor> {
|
||||
let (b, heads, l, d) = q.dims4()?;
|
||||
let (_, kv_heads, s, _) = k.dims4()?;
|
||||
let kt = k.transpose(2, 3)?.contiguous()?;
|
||||
let v = v.contiguous()?;
|
||||
let tile = (tile_elements / (heads * s).max(1)).clamp(1, l);
|
||||
let mut out = Vec::with_capacity(l.div_ceil(tile));
|
||||
let mut start = 0;
|
||||
while start < l {
|
||||
let t = tile.min(l - start);
|
||||
// (B, H, t, D) -> (B, Hkv, G * t, D): head h = kv * G + g.
|
||||
let qt =
|
||||
q.narrow(2, start, t)?
|
||||
.contiguous()?
|
||||
.reshape((b, kv_heads, num_kv_groups * t, d))?;
|
||||
let scores = (qt.matmul(&kt)? * scale)?
|
||||
.to_dtype(candle_core::DType::F32)?
|
||||
.reshape((b, kv_heads, num_kv_groups, t, s))?;
|
||||
let m = mask
|
||||
.narrow(2, start, t)?
|
||||
.to_dtype(candle_core::DType::F32)?
|
||||
.unsqueeze(1)?;
|
||||
let probs = candle_nn::ops::softmax_last_dim(&scores.broadcast_add(&m)?)?
|
||||
.to_dtype(q.dtype())?
|
||||
.reshape((b, kv_heads, num_kv_groups * t, s))?;
|
||||
out.push(probs.matmul(&v)?.reshape((b, heads, t, d))?);
|
||||
start += t;
|
||||
}
|
||||
if out.len() == 1 {
|
||||
return Ok(out.remove(0));
|
||||
}
|
||||
Tensor::cat(&out, 2)
|
||||
}
|
||||
|
||||
pub struct Qwen3_5Attention {
|
||||
q_proj: Linear,
|
||||
k_proj: Linear,
|
||||
@@ -334,3 +409,94 @@ fn load_linear_no_bias(
|
||||
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
|
||||
Ok(Linear::new(weight, None))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use candle_core::Device;
|
||||
|
||||
/// Plain eager attention: K/V repeated per query head, one score
|
||||
/// matrix, f32 throughout. Independent of the code under test.
|
||||
fn reference(
|
||||
q: &Tensor,
|
||||
k: &Tensor,
|
||||
v: &Tensor,
|
||||
mask: &Tensor,
|
||||
groups: usize,
|
||||
scale: f64,
|
||||
) -> Vec<f32> {
|
||||
let k = repeat_kv(k.clone(), groups).unwrap();
|
||||
let v = repeat_kv(v.clone(), groups).unwrap();
|
||||
let scores = (q.matmul(&k.transpose(2, 3).unwrap()).unwrap() * scale)
|
||||
.unwrap()
|
||||
.broadcast_add(mask)
|
||||
.unwrap();
|
||||
candle_nn::ops::softmax_last_dim(&scores)
|
||||
.unwrap()
|
||||
.matmul(&v.contiguous().unwrap())
|
||||
.unwrap()
|
||||
.flatten_all()
|
||||
.unwrap()
|
||||
.to_vec1()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The tiled, copy-free GQA attention equals plain eager attention
|
||||
/// under an arbitrary mask, for every tile size: one query per tile,
|
||||
/// a ragged tail, and the whole chunk at once. Each KV head and each
|
||||
/// row's mask differ, so a wrong head fold or a misaligned mask tile
|
||||
/// changes the answer.
|
||||
#[test]
|
||||
fn masked_attention_matches_eager_attention_at_any_tile() {
|
||||
let dev = Device::Cpu;
|
||||
let (heads, kv_heads, l, s, d) = (4, 2, 5, 7, 8);
|
||||
let values = |n: usize, seed: u32| -> Vec<f32> {
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let x = (i as u32).wrapping_mul(2_654_435_761).wrapping_add(seed);
|
||||
((x >> 8) % 1000) as f32 / 500.0 - 1.0
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let q = Tensor::from_vec(values(heads * l * d, 1), (1, heads, l, d), &dev).unwrap();
|
||||
let k = Tensor::from_vec(values(kv_heads * s * d, 2), (1, kv_heads, s, d), &dev).unwrap();
|
||||
let v = Tensor::from_vec(values(kv_heads * s * d, 3), (1, kv_heads, s, d), &dev).unwrap();
|
||||
// Row i sees an irregular subset that always includes position i.
|
||||
let mut mask = vec![f32::NEG_INFINITY; l * s];
|
||||
for i in 0..l {
|
||||
for p in 0..s {
|
||||
if p == i || (p * 3 + i) % 4 == 0 {
|
||||
mask[i * s + p] = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mask = Tensor::from_vec(mask, (1, 1, l, s), &dev).unwrap();
|
||||
let scale = 0.35;
|
||||
let want = reference(&q, &k, &v, &mask, 2, scale);
|
||||
for tile_queries in [1, 2, l] {
|
||||
let got: Vec<f32> =
|
||||
masked_attention_tiled(&q, &k, &v, &mask, 2, scale, tile_queries * heads * s)
|
||||
.unwrap()
|
||||
.flatten_all()
|
||||
.unwrap()
|
||||
.to_vec1()
|
||||
.unwrap();
|
||||
for (g, w) in got.iter().zip(&want) {
|
||||
assert!(
|
||||
(g - w).abs() < 1e-5,
|
||||
"tile of {tile_queries}: got {got:?} want {want:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
// And the dispatcher routes an additive mask here.
|
||||
let routed: Vec<f32> = attention_context(&q, &k, &v, AttnMask::Additive(&mask), 2, scale)
|
||||
.unwrap()
|
||||
.flatten_all()
|
||||
.unwrap()
|
||||
.to_vec1()
|
||||
.unwrap();
|
||||
for (g, w) in routed.iter().zip(&want) {
|
||||
assert!((g - w).abs() < 1e-5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ use candle_nn::var_builder::ShardedVarBuilder;
|
||||
#[cfg(test)]
|
||||
use super::RopeParameters;
|
||||
use super::TextConfig;
|
||||
use super::proj::{LinearSource, Proj, load_proj};
|
||||
use super::rmsnorm::{OutputGate, Qwen3_5RmsNormGated, l2norm};
|
||||
|
||||
/// Per-rank, per-layer state for the linear-attention block.
|
||||
@@ -81,11 +82,11 @@ pub struct GatedDeltaNetState {
|
||||
|
||||
pub struct GatedDeltaNet {
|
||||
// Projections.
|
||||
in_proj_qkv: Linear,
|
||||
in_proj_z: Linear,
|
||||
in_proj_qkv: Proj,
|
||||
in_proj_z: Proj,
|
||||
in_proj_b: Linear,
|
||||
in_proj_a: Linear,
|
||||
out_proj: Linear,
|
||||
out_proj: Proj,
|
||||
|
||||
// Depthwise causal Conv1d weight; shape (conv_dim, 1, kernel_size).
|
||||
// No bias (Python sets bias=False).
|
||||
@@ -170,6 +171,16 @@ impl GatedDeltaNet {
|
||||
}
|
||||
|
||||
pub fn load_with_params(cfg: GatedDeltaNetParams, vb: &ShardedVarBuilder) -> Result<Self> {
|
||||
Self::load_with_source(cfg, vb, None)
|
||||
}
|
||||
|
||||
/// As [`Self::load_with_params`], taking `in_proj_qkv`, `in_proj_z`
|
||||
/// and `out_proj` from `source` where it has them.
|
||||
pub fn load_with_source(
|
||||
cfg: GatedDeltaNetParams,
|
||||
vb: &ShardedVarBuilder,
|
||||
source: Option<&dyn LinearSource>,
|
||||
) -> Result<Self> {
|
||||
let num_v_heads = cfg.num_value_heads;
|
||||
let num_k_heads = cfg.num_key_heads;
|
||||
let head_k_dim = cfg.key_head_dim;
|
||||
@@ -216,20 +227,20 @@ impl GatedDeltaNet {
|
||||
split_fused_qkvz(&qkvz, num_k_heads, num_v_heads, head_k_dim, head_v_dim)?;
|
||||
let (b_w, a_w) = split_fused_ba(&ba, num_k_heads, num_v_heads)?;
|
||||
(
|
||||
Linear::new(qkv_w, None),
|
||||
Linear::new(z_w, None),
|
||||
Linear::new(qkv_w, None).into(),
|
||||
Linear::new(z_w, None).into(),
|
||||
Linear::new(b_w, None),
|
||||
Linear::new(a_w, None),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
load_linear_no_bias(vb, "in_proj_qkv", cfg.hidden_size, conv_dim)?,
|
||||
load_linear_no_bias(vb, "in_proj_z", cfg.hidden_size, value_dim)?,
|
||||
load_proj(vb, "in_proj_qkv", cfg.hidden_size, conv_dim, source)?,
|
||||
load_proj(vb, "in_proj_z", cfg.hidden_size, value_dim, source)?,
|
||||
load_linear_no_bias(vb, "in_proj_b", cfg.hidden_size, num_v_heads)?,
|
||||
load_linear_no_bias(vb, "in_proj_a", cfg.hidden_size, num_v_heads)?,
|
||||
)
|
||||
};
|
||||
let out_proj = load_linear_no_bias(vb, "out_proj", value_dim, cfg.hidden_size)?;
|
||||
let out_proj = load_proj(vb, "out_proj", value_dim, cfg.hidden_size, source)?;
|
||||
|
||||
// ----- Conv1d weight (depthwise, bias=False). -----
|
||||
let conv1d_weight = vb
|
||||
@@ -1435,11 +1446,11 @@ mod tests {
|
||||
let value_dim = cfg.linear_value_head_dim * cfg.linear_num_value_heads;
|
||||
let conv_dim = key_dim * 2 + value_dim;
|
||||
let mut net = GatedDeltaNet {
|
||||
in_proj_qkv: Linear::new(zeros(&[conv_dim, cfg.hidden_size]), None),
|
||||
in_proj_z: Linear::new(zeros(&[value_dim, cfg.hidden_size]), None),
|
||||
in_proj_qkv: Linear::new(zeros(&[conv_dim, cfg.hidden_size]), None).into(),
|
||||
in_proj_z: Linear::new(zeros(&[value_dim, cfg.hidden_size]), None).into(),
|
||||
in_proj_b: Linear::new(zeros(&[cfg.linear_num_value_heads, cfg.hidden_size]), None),
|
||||
in_proj_a: Linear::new(zeros(&[cfg.linear_num_value_heads, cfg.hidden_size]), None),
|
||||
out_proj: Linear::new(zeros(&[cfg.hidden_size, value_dim]), None),
|
||||
out_proj: Linear::new(zeros(&[cfg.hidden_size, value_dim]), None).into(),
|
||||
conv1d_weight: zeros(&[conv_dim, 1, cfg.linear_conv_kernel_dim]),
|
||||
dt_bias: zeros(&[cfg.linear_num_value_heads]),
|
||||
a_log: zeros(&[cfg.linear_num_value_heads]),
|
||||
|
||||
@@ -3,17 +3,17 @@
|
||||
//! Identical to plain Qwen3's MLP: `down(silu(gate(x)) * up(x))` with
|
||||
//! no bias on any of the three projections.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::Result;
|
||||
use candle_core::{Module, Tensor};
|
||||
use candle_nn::Linear;
|
||||
use candle_nn::var_builder::ShardedVarBuilder;
|
||||
|
||||
use super::TextConfig;
|
||||
use super::proj::{LinearSource, Proj, load_proj};
|
||||
|
||||
pub struct Qwen3_5MLP {
|
||||
gate_proj: Linear,
|
||||
up_proj: Linear,
|
||||
down_proj: Linear,
|
||||
gate_proj: Proj,
|
||||
up_proj: Proj,
|
||||
down_proj: Proj,
|
||||
}
|
||||
|
||||
impl Qwen3_5MLP {
|
||||
@@ -25,11 +25,15 @@ impl Qwen3_5MLP {
|
||||
/// test that proves banking neutral still needs it, to express the
|
||||
/// same weights in the layout it is being compared against.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn from_weights(gate_proj: Linear, up_proj: Linear, down_proj: Linear) -> Self {
|
||||
pub(crate) fn from_weights(
|
||||
gate_proj: candle_nn::Linear,
|
||||
up_proj: candle_nn::Linear,
|
||||
down_proj: candle_nn::Linear,
|
||||
) -> Self {
|
||||
Self {
|
||||
gate_proj,
|
||||
up_proj,
|
||||
down_proj,
|
||||
gate_proj: gate_proj.into(),
|
||||
up_proj: up_proj.into(),
|
||||
down_proj: down_proj.into(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,9 +50,20 @@ impl Qwen3_5MLP {
|
||||
hidden: usize,
|
||||
intermediate: usize,
|
||||
) -> Result<Self> {
|
||||
let gate_proj = load_linear_no_bias(vb, "gate_proj", hidden, intermediate)?;
|
||||
let up_proj = load_linear_no_bias(vb, "up_proj", hidden, intermediate)?;
|
||||
let down_proj = load_linear_no_bias(vb, "down_proj", intermediate, hidden)?;
|
||||
Self::load_with_source(vb, hidden, intermediate, None)
|
||||
}
|
||||
|
||||
/// As [`Self::load_with_dims`], taking projections from `source`
|
||||
/// where it has them.
|
||||
pub fn load_with_source(
|
||||
vb: &ShardedVarBuilder,
|
||||
hidden: usize,
|
||||
intermediate: usize,
|
||||
source: Option<&dyn LinearSource>,
|
||||
) -> Result<Self> {
|
||||
let gate_proj = load_proj(vb, "gate_proj", hidden, intermediate, source)?;
|
||||
let up_proj = load_proj(vb, "up_proj", hidden, intermediate, source)?;
|
||||
let down_proj = load_proj(vb, "down_proj", intermediate, hidden, source)?;
|
||||
Ok(Self {
|
||||
gate_proj,
|
||||
up_proj,
|
||||
@@ -64,16 +79,3 @@ impl Module for Qwen3_5MLP {
|
||||
self.down_proj.forward(&(lhs * rhs)?)
|
||||
}
|
||||
}
|
||||
|
||||
fn load_linear_no_bias(
|
||||
vb: &ShardedVarBuilder,
|
||||
name: &str,
|
||||
in_dim: usize,
|
||||
out_dim: usize,
|
||||
) -> Result<Linear> {
|
||||
let weight = vb
|
||||
.pp(name)
|
||||
.get((out_dim, in_dim), "weight")
|
||||
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
|
||||
Ok(Linear::new(weight, None))
|
||||
}
|
||||
|
||||
@@ -73,11 +73,13 @@ use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub mod decoder;
|
||||
pub mod expert_tier;
|
||||
pub mod full_attn;
|
||||
pub mod linear_attn;
|
||||
pub mod mlp;
|
||||
pub mod moe;
|
||||
pub mod mtp;
|
||||
pub mod proj;
|
||||
pub mod rmsnorm;
|
||||
pub mod rope;
|
||||
pub mod vision;
|
||||
|
||||
@@ -70,6 +70,11 @@ pub(crate) enum Experts {
|
||||
/// dropped once its 512 experts are quantised, so the full 241.6 GB
|
||||
/// never exists at once.
|
||||
Quantized(Vec<QuantizedExpert>),
|
||||
/// Weights and execution live outside candle.
|
||||
External {
|
||||
count: usize,
|
||||
inner: Box<dyn ExternalExperts>,
|
||||
},
|
||||
Banked {
|
||||
/// `(num_experts, 2 * intermediate, hidden)` — gate rows first,
|
||||
/// then up. Reversing them computes `silu(up) * gate`, which is
|
||||
@@ -81,8 +86,32 @@ pub(crate) enum Experts {
|
||||
},
|
||||
}
|
||||
|
||||
/// Routed experts executed outside candle.
|
||||
///
|
||||
/// Routing stays with the block. `xs` is `(tokens, hidden)`;
|
||||
/// `tokens_for[e]` and `weights_for[e]` are expert `e`'s rows and mixing
|
||||
/// weights. Returns the weighted sum of each token's `k` experts,
|
||||
/// `(tokens, hidden)`.
|
||||
pub trait ExternalExperts: Send + Sync {
|
||||
fn forward(
|
||||
&self,
|
||||
xs: &Tensor,
|
||||
tokens_for: &[Vec<u32>],
|
||||
weights_for: &[Vec<f32>],
|
||||
k: usize,
|
||||
) -> candle_core::Result<Tensor>;
|
||||
}
|
||||
|
||||
/// Supplies each MoE layer's [`ExternalExperts`] at load.
|
||||
pub trait ExternalExpertSource: Send + Sync {
|
||||
fn block(&self, layer: usize) -> Result<Box<dyn ExternalExperts>>;
|
||||
}
|
||||
|
||||
/// The VRAM tier as host-resident quantised experts use it (#318).
|
||||
pub type DeviceExpertTier = super::expert_tier::ExpertTier<QuantizedExpert>;
|
||||
|
||||
/// One expert's three projections, quantised.
|
||||
pub(crate) struct QuantizedExpert {
|
||||
pub struct QuantizedExpert {
|
||||
gate: QMatMul,
|
||||
up: QMatMul,
|
||||
down: QMatMul,
|
||||
@@ -100,6 +129,36 @@ impl QuantizedExpert {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of quantised weights, for the tier's budget.
|
||||
fn storage_bytes(&self) -> u64 {
|
||||
[&self.gate, &self.up, &self.down]
|
||||
.into_iter()
|
||||
.map(|m| match m {
|
||||
QMatMul::QTensor(t) => t.storage_size_in_bytes() as u64,
|
||||
_ => 0,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// A copy of this expert on `device`.
|
||||
fn on_device(&self, device: &Device) -> candle_core::Result<Self> {
|
||||
Ok(Self {
|
||||
gate: quantized_on(&self.gate, device)?,
|
||||
up: quantized_on(&self.up, device)?,
|
||||
down: quantized_on(&self.down, device)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The SwiGLU on `xs`, which must be on this expert's device. The
|
||||
/// kernels accumulate in f32; the result returns in `xs`'s dtype.
|
||||
fn forward_here(&self, xs: &Tensor) -> candle_core::Result<Tensor> {
|
||||
let dtype = xs.dtype();
|
||||
let xs32 = xs.to_dtype(DType::F32)?;
|
||||
let lhs = candle_nn::ops::silu(&self.gate.forward(&xs32)?)?;
|
||||
let rhs = self.up.forward(&xs32)?;
|
||||
self.down.forward(&(lhs * rhs)?)?.to_dtype(dtype)
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows at which host-resident experts run on the GPU instead (#318).
|
||||
@@ -119,6 +178,18 @@ fn expert_stream_min_rows() -> Option<usize> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The most rows a forward may have and still admit experts to the VRAM
|
||||
/// tier. Decode windows are below it; prompt chunks are not.
|
||||
pub(crate) const TIER_ADMIT_MAX_ROWS: usize = 16;
|
||||
|
||||
/// Whether a prompt chunk may have left transient expert copies in the
|
||||
/// allocator pool, which holds freed VRAM until it is trimmed.
|
||||
pub(crate) fn prompt_chunk_streams_experts(rows: usize) -> bool {
|
||||
rows > TIER_ADMIT_MAX_ROWS
|
||||
&& (expert_stream_min_rows().is_some()
|
||||
|| super::expert_tier::configured_budget_mb().is_some())
|
||||
}
|
||||
|
||||
/// A transient copy of a quantised projection on `device`.
|
||||
fn quantized_on(m: &QMatMul, device: &Device) -> candle_core::Result<QMatMul> {
|
||||
match m {
|
||||
@@ -201,6 +272,7 @@ impl Experts {
|
||||
Experts::PerExpert(v) => v.len(),
|
||||
Experts::Banked { gate_up, .. } => gate_up.dims()[0],
|
||||
Experts::Quantized(v) => v.len(),
|
||||
Experts::External { count, .. } => *count,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,6 +425,9 @@ impl Experts {
|
||||
pub(crate) fn forward_one(&self, e: usize, xs: &Tensor) -> candle_core::Result<Tensor> {
|
||||
match self {
|
||||
Experts::PerExpert(v) => v[e].forward(xs),
|
||||
Experts::External { .. } => {
|
||||
candle_core::bail!("external experts run per layer, not per expert")
|
||||
}
|
||||
Experts::Banked {
|
||||
gate_up,
|
||||
down,
|
||||
@@ -396,19 +471,36 @@ impl Experts {
|
||||
/// Expert `e` computed on `xs`'s device from a transient copy of
|
||||
/// its weights. Layouts that are not quantised run as usual.
|
||||
pub(crate) fn forward_streamed(&self, e: usize, xs: &Tensor) -> candle_core::Result<Tensor> {
|
||||
let Experts::Quantized(v) = self else {
|
||||
return self.forward_one(e, xs);
|
||||
};
|
||||
v[e].on_device(xs.device())?.forward_here(xs)
|
||||
}
|
||||
|
||||
/// Expert `e` computed on `xs`'s device from the VRAM tier, loading
|
||||
/// it there if it is not already held.
|
||||
pub(crate) fn forward_tiered(
|
||||
&self,
|
||||
e: usize,
|
||||
xs: &Tensor,
|
||||
tier: &DeviceExpertTier,
|
||||
block: u32,
|
||||
admit: bool,
|
||||
) -> candle_core::Result<Tensor> {
|
||||
let Experts::Quantized(v) = self else {
|
||||
return self.forward_one(e, xs);
|
||||
};
|
||||
let q = &v[e];
|
||||
let device = xs.device();
|
||||
let dtype = xs.dtype();
|
||||
let gate = quantized_on(&q.gate, device)?;
|
||||
let up = quantized_on(&q.up, device)?;
|
||||
let down = quantized_on(&q.down, device)?;
|
||||
let xs32 = xs.to_dtype(DType::F32)?;
|
||||
let lhs = candle_nn::ops::silu(&gate.forward(&xs32)?)?;
|
||||
let rhs = up.forward(&xs32)?;
|
||||
down.forward(&(lhs * rhs)?)?.to_dtype(dtype)
|
||||
if !admit {
|
||||
return match tier.peek(block, e as u32) {
|
||||
Some(resident) => resident.forward_here(xs),
|
||||
None => q.on_device(xs.device())?.forward_here(xs),
|
||||
};
|
||||
}
|
||||
let resident = tier.get_or_load(block, e as u32, q.storage_bytes(), || {
|
||||
q.on_device(xs.device())
|
||||
})?;
|
||||
resident.forward_here(xs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,6 +518,8 @@ pub struct Qwen3_5MoeBlock {
|
||||
shared_expert_gate: Option<Linear>,
|
||||
num_experts_per_tok: usize,
|
||||
norm_topk_prob: bool,
|
||||
/// The model's VRAM tier and this block's number in it (#318).
|
||||
tier: Option<(std::sync::Arc<DeviceExpertTier>, u32)>,
|
||||
}
|
||||
|
||||
impl Qwen3_5MoeBlock {
|
||||
@@ -452,9 +546,19 @@ impl Qwen3_5MoeBlock {
|
||||
shared_expert_gate,
|
||||
num_experts_per_tok,
|
||||
norm_topk_prob,
|
||||
tier: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve this block's host-resident experts through `tier`.
|
||||
pub(crate) fn with_tier(mut self, tier: Option<std::sync::Arc<DeviceExpertTier>>) -> Self {
|
||||
self.tier = tier.map(|t| {
|
||||
let block = t.register_block();
|
||||
(t, block)
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
pub fn load(cfg: &TextConfig, vb: &ShardedVarBuilder) -> Result<Self> {
|
||||
anyhow::ensure!(
|
||||
cfg.num_experts > 0 && cfg.num_experts_per_tok > 0 && cfg.moe_intermediate_size > 0,
|
||||
@@ -511,6 +615,7 @@ impl Qwen3_5MoeBlock {
|
||||
shared_expert_gate,
|
||||
num_experts_per_tok: cfg.num_experts_per_tok,
|
||||
norm_topk_prob: cfg.norm_topk_prob,
|
||||
tier: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -580,6 +685,20 @@ impl Module for Qwen3_5MoeBlock {
|
||||
self.norm_topk_prob,
|
||||
)?;
|
||||
|
||||
if let Experts::External { inner, .. } = &self.experts {
|
||||
let ys = inner
|
||||
.forward(
|
||||
&xs_flat,
|
||||
&tokens_for,
|
||||
&weights_for,
|
||||
self.num_experts_per_tok,
|
||||
)?
|
||||
.to_dtype(xs.dtype())?;
|
||||
return self
|
||||
.add_shared_expert(ys, &xs_flat)?
|
||||
.reshape((b, l, hidden));
|
||||
}
|
||||
|
||||
// Cross to the experts once for the whole layer, not once per
|
||||
// expert (#318). With host-resident experts the old shape was
|
||||
// 10 round trips per layer and 480 per token; this is one in
|
||||
@@ -592,10 +711,12 @@ impl Module for Qwen3_5MoeBlock {
|
||||
// dominates.
|
||||
let home = self.experts.device();
|
||||
let off_device = home.is_some();
|
||||
let stream = xs.device().is_cuda()
|
||||
&& home.as_ref().is_some_and(Device::is_cpu)
|
||||
&& expert_stream_min_rows()
|
||||
.is_some_and(|min_rows| xs_flat.dim(0).is_ok_and(|n| n >= min_rows));
|
||||
let host_resident = xs.device().is_cuda() && home.as_ref().is_some_and(Device::is_cpu);
|
||||
let tier = self.tier.as_ref().filter(|_| host_resident);
|
||||
let stream = tier.is_some()
|
||||
|| host_resident
|
||||
&& expert_stream_min_rows()
|
||||
.is_some_and(|min_rows| xs_flat.dim(0).is_ok_and(|n| n >= min_rows));
|
||||
let routed_dev = if stream {
|
||||
xs.device().clone()
|
||||
} else {
|
||||
@@ -611,7 +732,11 @@ impl Module for Qwen3_5MoeBlock {
|
||||
}
|
||||
let rows = Tensor::new(tokens_for[e].as_slice(), &routed_dev)?;
|
||||
let picked = xs_routed.index_select(&rows, 0)?;
|
||||
let out = if stream {
|
||||
let out = if let Some((tier, block)) = tier {
|
||||
let admit = xs_routed.dim(0)? <= TIER_ADMIT_MAX_ROWS;
|
||||
self.experts
|
||||
.forward_tiered(e, &picked, tier, *block, admit)?
|
||||
} else if stream {
|
||||
self.experts.forward_streamed(e, &picked)?
|
||||
} else {
|
||||
self.experts.forward_one(e, &picked)?
|
||||
@@ -634,18 +759,31 @@ impl Module for Qwen3_5MoeBlock {
|
||||
rows = xs_routed.dims()[0],
|
||||
active = tokens_for.iter().filter(|t| !t.is_empty()).count(),
|
||||
stream,
|
||||
tier_hits = tier.map_or(0, |(t, _)| t.stats().hits),
|
||||
tier_misses = tier.map_or(0, |(t, _)| t.stats().misses),
|
||||
tier_prompt_hits = tier.map_or(0, |(t, _)| t.stats().prompt_hits),
|
||||
tier_prompt_misses = tier.map_or(0, |(t, _)| t.stats().prompt_misses),
|
||||
tier_mb = tier.map_or(0, |(t, _)| t.stats().used_bytes >> 20),
|
||||
"moe: routed experts (#318)"
|
||||
);
|
||||
}
|
||||
let mut ys = ys.to_device(xs.device())?;
|
||||
let ys = ys.to_device(xs.device())?;
|
||||
self.add_shared_expert(ys, &xs_flat)?
|
||||
.reshape((b, l, hidden))
|
||||
}
|
||||
}
|
||||
|
||||
if let (Some(shared), Some(gate)) = (&self.shared_expert, &self.shared_expert_gate) {
|
||||
let mix = candle_nn::ops::sigmoid(&gate.forward(&xs_flat)?)?;
|
||||
let shared_out = shared.forward(&xs_flat)?.broadcast_mul(&mix)?;
|
||||
ys = (ys + shared_out)?;
|
||||
impl Qwen3_5MoeBlock {
|
||||
/// Adds the sigmoid-gated shared expert, when the model has one.
|
||||
fn add_shared_expert(&self, ys: Tensor, xs_flat: &Tensor) -> candle_core::Result<Tensor> {
|
||||
match (&self.shared_expert, &self.shared_expert_gate) {
|
||||
(Some(shared), Some(gate)) => {
|
||||
let mix = candle_nn::ops::sigmoid(&gate.forward(xs_flat)?)?;
|
||||
let shared_out = shared.forward(xs_flat)?.broadcast_mul(&mix)?;
|
||||
ys + shared_out
|
||||
}
|
||||
_ => Ok(ys),
|
||||
}
|
||||
|
||||
ys.reshape((b, l, hidden))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -682,6 +820,7 @@ mod tests {
|
||||
shared_expert_gate: Some(Linear::new(randn(&[1, hidden]), None)),
|
||||
num_experts_per_tok: top_k,
|
||||
norm_topk_prob: true,
|
||||
tier: None,
|
||||
};
|
||||
|
||||
let (b, l) = (2, 3);
|
||||
@@ -767,6 +906,7 @@ mod tests {
|
||||
shared_expert_gate: None,
|
||||
num_experts_per_tok: 1,
|
||||
norm_topk_prob: false,
|
||||
tier: None,
|
||||
};
|
||||
let xs = randn(&[1, 1, hidden]);
|
||||
let got: Vec<f32> = block
|
||||
@@ -977,6 +1117,89 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// External experts receive the block's routing and their result is
|
||||
/// mixed with the shared expert exactly as resident experts' is.
|
||||
#[test]
|
||||
fn external_experts_receive_the_routing_and_join_the_shared_expert() {
|
||||
struct Fixed;
|
||||
impl ExternalExperts for Fixed {
|
||||
fn forward(
|
||||
&self,
|
||||
xs: &Tensor,
|
||||
tokens_for: &[Vec<u32>],
|
||||
weights_for: &[Vec<f32>],
|
||||
k: usize,
|
||||
) -> candle_core::Result<Tensor> {
|
||||
let routed: usize = tokens_for.iter().map(Vec::len).sum();
|
||||
assert_eq!(routed, xs.dim(0)? * k);
|
||||
assert_eq!(tokens_for.len(), 6);
|
||||
for (t, w) in tokens_for.iter().zip(weights_for) {
|
||||
assert_eq!(t.len(), w.len());
|
||||
}
|
||||
xs.ones_like()
|
||||
}
|
||||
}
|
||||
let (hidden, inter, n_exp, top_k) = (8, 4, 6, 2);
|
||||
let shared = rand_mlp(hidden, inter);
|
||||
let shared_gate = Linear::new(randn(&[1, hidden]), None);
|
||||
let xs = randn(&[1, 3, hidden]);
|
||||
let flat = xs.reshape(((), hidden)).unwrap();
|
||||
let mix = candle_nn::ops::sigmoid(&shared_gate.forward(&flat).unwrap()).unwrap();
|
||||
let expected = (shared.forward(&flat).unwrap().broadcast_mul(&mix).unwrap()
|
||||
+ flat.ones_like().unwrap())
|
||||
.unwrap();
|
||||
let block = Qwen3_5MoeBlock {
|
||||
gate: Linear::new(randn(&[n_exp, hidden]), None),
|
||||
experts: Experts::External {
|
||||
count: n_exp,
|
||||
inner: Box::new(Fixed),
|
||||
},
|
||||
shared_expert: Some(shared),
|
||||
shared_expert_gate: Some(shared_gate),
|
||||
num_experts_per_tok: top_k,
|
||||
norm_topk_prob: true,
|
||||
tier: None,
|
||||
};
|
||||
let got: Vec<Vec<f32>> = block
|
||||
.forward(&xs)
|
||||
.unwrap()
|
||||
.reshape(((), hidden))
|
||||
.unwrap()
|
||||
.to_vec2()
|
||||
.unwrap();
|
||||
let want: Vec<Vec<f32>> = expected.to_vec2().unwrap();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
/// The tiered path runs the same arithmetic as the resident one,
|
||||
/// and a second use of an expert comes from the tier.
|
||||
#[test]
|
||||
fn tiered_expert_matches_the_resident_forward() {
|
||||
let (n_experts, hidden, inter) = (2usize, 2560usize, 640usize);
|
||||
let gate_up = randn(&[n_experts, inter * 2, hidden]);
|
||||
let down = randn(&[n_experts, hidden, inter]);
|
||||
let experts =
|
||||
Experts::quantize_banked_onto(&gate_up, &down, inter, GgmlDType::Q4K, &Device::Cpu)
|
||||
.unwrap();
|
||||
let tier = DeviceExpertTier::new(1 << 30);
|
||||
let block = tier.register_block();
|
||||
let xs = randn(&[3, hidden]);
|
||||
for e in 0..n_experts {
|
||||
let resident: Vec<Vec<f32>> = experts.forward_one(e, &xs).unwrap().to_vec2().unwrap();
|
||||
for _ in 0..2 {
|
||||
let tiered: Vec<Vec<f32>> = experts
|
||||
.forward_tiered(e, &xs, &tier, block, true)
|
||||
.unwrap()
|
||||
.to_vec2()
|
||||
.unwrap();
|
||||
assert_eq!(resident, tiered, "expert {e}");
|
||||
}
|
||||
}
|
||||
let stats = tier.stats();
|
||||
assert_eq!((stats.misses, stats.hits, stats.entries), (2, 2, 2));
|
||||
assert!(stats.used_bytes > 0);
|
||||
}
|
||||
|
||||
/// Host-resident experts compute the same function as device-
|
||||
/// resident ones (#318).
|
||||
///
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! A bias-free projection that is either a dense candle [`Linear`] or a
|
||||
//! weight held in another format and run by its own kernels.
|
||||
//!
|
||||
//! The second form exists so a model can take its dense weights from a
|
||||
//! quantized file (a GGUF's Q8_0 blocks, say) while keeping the
|
||||
//! checkpoint's names and the rest of its load path. A [`LinearSource`]
|
||||
//! is asked for each projection by its checkpoint name; when it has one,
|
||||
//! the dense tensor is never read.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use candle_core::{Module, Tensor};
|
||||
use candle_nn::Linear;
|
||||
use candle_nn::var_builder::ShardedVarBuilder;
|
||||
|
||||
/// `y = x W^T` for a weight held outside candle.
|
||||
pub trait ExternalLinear: Send + Sync {
|
||||
/// `x` is `(.., in_dim)`; the result is `(.., out_dim)` in `x`'s dtype.
|
||||
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor>;
|
||||
}
|
||||
|
||||
/// Supplies projections by checkpoint name, e.g.
|
||||
/// `model.language_model.layers.3.self_attn.q_proj.weight`.
|
||||
pub trait LinearSource: Send + Sync {
|
||||
/// The projection, or `None` to load the checkpoint's own tensor.
|
||||
/// `(out_dim, in_dim)` is the shape the checkpoint would have.
|
||||
fn linear(
|
||||
&self,
|
||||
name: &str,
|
||||
in_dim: usize,
|
||||
out_dim: usize,
|
||||
) -> Result<Option<Arc<dyn ExternalLinear>>>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum Proj {
|
||||
Dense(Linear),
|
||||
External(Arc<dyn ExternalLinear>),
|
||||
}
|
||||
|
||||
impl Module for Proj {
|
||||
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor> {
|
||||
match self {
|
||||
Self::Dense(linear) => linear.forward(x),
|
||||
Self::External(linear) => linear.forward(x),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Linear> for Proj {
|
||||
fn from(linear: Linear) -> Self {
|
||||
Self::Dense(linear)
|
||||
}
|
||||
}
|
||||
|
||||
/// `{prefix}.{name}.weight`, from `source` when it has it, else from the
|
||||
/// checkpoint.
|
||||
pub fn load_proj(
|
||||
vb: &ShardedVarBuilder,
|
||||
name: &str,
|
||||
in_dim: usize,
|
||||
out_dim: usize,
|
||||
source: Option<&dyn LinearSource>,
|
||||
) -> Result<Proj> {
|
||||
if let Some(source) = source {
|
||||
let prefix = vb.prefix();
|
||||
let full = if prefix.is_empty() {
|
||||
format!("{name}.weight")
|
||||
} else {
|
||||
format!("{prefix}.{name}.weight")
|
||||
};
|
||||
if let Some(linear) = source.linear(&full, in_dim, out_dim)? {
|
||||
return Ok(Proj::External(linear));
|
||||
}
|
||||
}
|
||||
let weight = vb
|
||||
.pp(name)
|
||||
.get((out_dim, in_dim), "weight")
|
||||
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
|
||||
Ok(Proj::Dense(Linear::new(weight, None)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use candle_core::{DType, Device};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
struct Doubling;
|
||||
impl ExternalLinear for Doubling {
|
||||
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor> {
|
||||
x * 2.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the names it is asked for and serves only one of them.
|
||||
struct OneName(Mutex<Vec<String>>);
|
||||
impl LinearSource for OneName {
|
||||
fn linear(
|
||||
&self,
|
||||
name: &str,
|
||||
_in_dim: usize,
|
||||
_out_dim: usize,
|
||||
) -> Result<Option<Arc<dyn ExternalLinear>>> {
|
||||
self.0.lock().unwrap().push(name.to_string());
|
||||
Ok(
|
||||
(name == "a.b.served.weight")
|
||||
.then(|| Arc::new(Doubling) as Arc<dyn ExternalLinear>),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The source is asked by the full checkpoint name; what it serves
|
||||
/// replaces the tensor, which is never read (the checkpoint here has
|
||||
/// none for it), and what it declines comes from the checkpoint.
|
||||
#[test]
|
||||
fn a_source_is_asked_by_full_name_and_the_checkpoint_fills_the_rest() {
|
||||
let dev = Device::Cpu;
|
||||
let mut tensors = HashMap::new();
|
||||
tensors.insert(
|
||||
"a.b.kept.weight".to_string(),
|
||||
Tensor::ones((2, 2), DType::F32, &dev).unwrap(),
|
||||
);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("model.safetensors");
|
||||
candle_core::safetensors::save(&tensors, &path).unwrap();
|
||||
let vb = unsafe {
|
||||
candle_nn::var_builder::ShardedSafeTensors::var_builder(&[&path], DType::F32, &dev)
|
||||
.unwrap()
|
||||
}
|
||||
.pp("a")
|
||||
.pp("b");
|
||||
let source = OneName(Mutex::new(Vec::new()));
|
||||
let x = Tensor::new(&[[1f32, 3.]], &dev).unwrap();
|
||||
|
||||
let served = load_proj(&vb, "served", 2, 2, Some(&source)).unwrap();
|
||||
assert!(matches!(served, Proj::External(_)));
|
||||
assert_eq!(
|
||||
served.forward(&x).unwrap().to_vec2::<f32>().unwrap(),
|
||||
[[2., 6.]]
|
||||
);
|
||||
|
||||
let kept = load_proj(&vb, "kept", 2, 2, Some(&source)).unwrap();
|
||||
assert!(matches!(kept, Proj::Dense(_)));
|
||||
assert_eq!(
|
||||
kept.forward(&x).unwrap().to_vec2::<f32>().unwrap(),
|
||||
[[4., 4.]]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
*source.0.lock().unwrap(),
|
||||
["a.b.served.weight", "a.b.kept.weight"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -110,12 +110,17 @@ impl DecoderLayer {
|
||||
opts: &super::LoadOptions<'_>,
|
||||
) -> Result<Self> {
|
||||
let mixer = match layer_type {
|
||||
"full_attention" => {
|
||||
Mixer::Full(Box::new(Attention::load(cfg, rotary, &vb.pp("self_attn"))?))
|
||||
}
|
||||
"linear_attention" => {
|
||||
Mixer::Linear(Box::new(linear_attn::load(cfg, &vb.pp("linear_attn"))?))
|
||||
}
|
||||
"full_attention" => Mixer::Full(Box::new(Attention::load(
|
||||
cfg,
|
||||
rotary,
|
||||
&vb.pp("self_attn"),
|
||||
opts.dense.as_deref(),
|
||||
)?)),
|
||||
"linear_attention" => Mixer::Linear(Box::new(linear_attn::load(
|
||||
cfg,
|
||||
&vb.pp("linear_attn"),
|
||||
opts.dense.as_deref(),
|
||||
)?)),
|
||||
other => anyhow::bail!(
|
||||
"unknown layer_type '{other}' (expected 'full_attention' or \
|
||||
'linear_attention')"
|
||||
@@ -132,6 +137,7 @@ impl DecoderLayer {
|
||||
// Decoder hyper-connections always scatter back; only
|
||||
// the top-level mixer does not.
|
||||
true,
|
||||
opts.dense.as_deref(),
|
||||
)
|
||||
};
|
||||
|
||||
|
||||
@@ -26,14 +26,14 @@
|
||||
//!
|
||||
//! See `doc/qwen4_exp-port-spec.md` §3 and §4.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::Result;
|
||||
use candle_core::{Module, Tensor};
|
||||
use candle_nn::Linear;
|
||||
use candle_nn::kv_cache::ConcatKvCache;
|
||||
use candle_nn::var_builder::ShardedVarBuilder;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::harness::arch::qwen3_5::full_attn::{AttnMask, attention_context};
|
||||
use crate::harness::arch::qwen3_5::proj::{LinearSource, Proj, load_proj};
|
||||
use crate::harness::arch::qwen3_5::rmsnorm::Qwen3_5RmsNorm;
|
||||
use crate::harness::arch::qwen3_5::rope::RotaryEmbedding;
|
||||
|
||||
@@ -41,10 +41,10 @@ use super::config::TextConfig;
|
||||
use super::qsa::Indexer;
|
||||
|
||||
pub struct Attention {
|
||||
q_proj: Linear,
|
||||
k_proj: Linear,
|
||||
v_proj: Linear,
|
||||
o_proj: Linear,
|
||||
q_proj: Proj,
|
||||
k_proj: Proj,
|
||||
v_proj: Proj,
|
||||
o_proj: Proj,
|
||||
q_norm: Qwen3_5RmsNorm,
|
||||
k_norm: Qwen3_5RmsNorm,
|
||||
/// The sparse-attention side channel. Owns its own KV cache, which
|
||||
@@ -66,6 +66,7 @@ impl Attention {
|
||||
cfg: &TextConfig,
|
||||
rotary: Arc<RotaryEmbedding>,
|
||||
vb: &ShardedVarBuilder,
|
||||
source: Option<&dyn LinearSource>,
|
||||
) -> Result<Self> {
|
||||
let head_dim = cfg.head_dim;
|
||||
let num_heads = cfg.num_attention_heads;
|
||||
@@ -78,10 +79,22 @@ impl Attention {
|
||||
let attn_width = num_heads * head_dim;
|
||||
Ok(Self {
|
||||
// Doubled output: query and gate, interleaved per head.
|
||||
q_proj: linear(vb, "q_proj", cfg.hidden_size, attn_width * 2)?,
|
||||
k_proj: linear(vb, "k_proj", cfg.hidden_size, num_kv_heads * head_dim)?,
|
||||
v_proj: linear(vb, "v_proj", cfg.hidden_size, num_kv_heads * head_dim)?,
|
||||
o_proj: linear(vb, "o_proj", attn_width, cfg.hidden_size)?,
|
||||
q_proj: load_proj(vb, "q_proj", cfg.hidden_size, attn_width * 2, source)?,
|
||||
k_proj: load_proj(
|
||||
vb,
|
||||
"k_proj",
|
||||
cfg.hidden_size,
|
||||
num_kv_heads * head_dim,
|
||||
source,
|
||||
)?,
|
||||
v_proj: load_proj(
|
||||
vb,
|
||||
"v_proj",
|
||||
cfg.hidden_size,
|
||||
num_kv_heads * head_dim,
|
||||
source,
|
||||
)?,
|
||||
o_proj: load_proj(vb, "o_proj", attn_width, cfg.hidden_size, source)?,
|
||||
q_norm: Qwen3_5RmsNorm::load(&vb.pp("q_norm"), head_dim, cfg.rms_norm_eps)?,
|
||||
k_norm: Qwen3_5RmsNorm::load(&vb.pp("k_norm"), head_dim, cfg.rms_norm_eps)?,
|
||||
// The indexer is a submodule of the attention block, not a
|
||||
@@ -210,20 +223,13 @@ impl Attention {
|
||||
}
|
||||
}
|
||||
|
||||
fn linear(vb: &ShardedVarBuilder, name: &str, in_dim: usize, out_dim: usize) -> Result<Linear> {
|
||||
let weight = vb
|
||||
.pp(name)
|
||||
.get((out_dim, in_dim), "weight")
|
||||
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
|
||||
Ok(Linear::new(weight, None))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::harness::arch::qwen3_5::TextConfig as Qwen3_5TextConfig;
|
||||
use crate::harness::arch::qwen4_exp::qsa::BlockSelector;
|
||||
use candle_core::{DType, Device};
|
||||
use candle_nn::Linear;
|
||||
|
||||
const HIDDEN: usize = 4;
|
||||
const HEADS: usize = 2;
|
||||
@@ -272,10 +278,10 @@ mod tests {
|
||||
fn layer(budget: usize) -> Attention {
|
||||
let attn_width = HEADS * HEAD_DIM;
|
||||
Attention {
|
||||
q_proj: from_first_column(&[1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0], HIDDEN),
|
||||
k_proj: from_first_column(&[0.0; HEAD_DIM], HIDDEN),
|
||||
v_proj: from_first_column(&[1.0; HEAD_DIM], HIDDEN),
|
||||
o_proj: eye(attn_width),
|
||||
q_proj: from_first_column(&[1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0], HIDDEN).into(),
|
||||
k_proj: from_first_column(&[0.0; HEAD_DIM], HIDDEN).into(),
|
||||
v_proj: from_first_column(&[1.0; HEAD_DIM], HIDDEN).into(),
|
||||
o_proj: eye(attn_width).into(),
|
||||
q_norm: Qwen3_5RmsNorm::from_weight(
|
||||
Tensor::zeros(HEAD_DIM, DType::F32, &Device::Cpu).unwrap(),
|
||||
1e-6,
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
//! Dense projections from a GGUF's quantized blocks, run on Strata's
|
||||
//! kernels: a quantized matrix-vector product (`mmvq`) for decode-sized
|
||||
//! inputs, and dequantize + cuBLAS for prompt chunks.
|
||||
//!
|
||||
//! Most of the model's dense tensors are stored as Q8_0 in the UD packs,
|
||||
//! half of BF16. They map to the checkpoint by name, each in its own
|
||||
//! layout, except the linear-attention value heads: llama.cpp's
|
||||
//! converter stores them tiled by key head where the checkpoint groups
|
||||
//! them. With `r = value_heads / key_heads`, GGUF head `g * key_heads +
|
||||
//! k` holds checkpoint head `r * k + g`. That is undone at load by
|
||||
//! moving whole quantized rows (or whole blocks within each row, where
|
||||
//! the heads are the input dimension), so no value is requantized.
|
||||
|
||||
use anyhow::{Result, ensure};
|
||||
|
||||
/// How a GGUF tensor's value heads must move to match the checkpoint.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Reorder {
|
||||
None,
|
||||
/// Output rows, after the first `skip_rows` (the q and k of a fused
|
||||
/// qkv projection, which are stored in order).
|
||||
Rows {
|
||||
skip_rows: usize,
|
||||
},
|
||||
/// Input columns: within every row, per head of `head_dim` values.
|
||||
Cols,
|
||||
}
|
||||
|
||||
/// The GGUF tensor holding checkpoint tensor `name`, and its reorder.
|
||||
pub(crate) fn gguf_name(name: &str) -> Option<(String, Reorder, bool)> {
|
||||
// The bool says whether `skip_rows` must be filled in from the
|
||||
// config: only the fused qkv knows its q and k widths.
|
||||
if name == "lm_head.weight" {
|
||||
return Some(("output.weight".into(), Reorder::None, false));
|
||||
}
|
||||
if let Some(rest) = name.strip_prefix("model.language_model.hyper_connection_mixer.") {
|
||||
let gguf = match rest {
|
||||
"input_mix_weight_up.weight" => "output_hc_up.weight",
|
||||
"input_mix_weight_down.weight" => "output_hc_down.weight",
|
||||
_ => return None,
|
||||
};
|
||||
return Some((gguf.into(), Reorder::None, false));
|
||||
}
|
||||
let rest = name.strip_prefix("model.language_model.layers.")?;
|
||||
let (layer, rest) = rest.split_once('.')?;
|
||||
let layer: usize = layer.parse().ok()?;
|
||||
let (gguf, reorder, needs_skip) = match rest {
|
||||
"linear_attn.in_proj_qkv.weight" => ("attn_qkv", Reorder::Rows { skip_rows: 0 }, true),
|
||||
"linear_attn.in_proj_z.weight" => ("attn_gate", Reorder::Rows { skip_rows: 0 }, false),
|
||||
"linear_attn.out_proj.weight" => ("ssm_out", Reorder::Cols, false),
|
||||
"self_attn.q_proj.weight" => ("attn_q", Reorder::None, false),
|
||||
"self_attn.k_proj.weight" => ("attn_k", Reorder::None, false),
|
||||
"self_attn.v_proj.weight" => ("attn_v", Reorder::None, false),
|
||||
"self_attn.o_proj.weight" => ("attn_output", Reorder::None, false),
|
||||
"mlp.shared_expert.gate_proj.weight" => ("ffn_gate_shexp", Reorder::None, false),
|
||||
"mlp.shared_expert.up_proj.weight" => ("ffn_up_shexp", Reorder::None, false),
|
||||
"mlp.shared_expert.down_proj.weight" => ("ffn_down_shexp", Reorder::None, false),
|
||||
"attn_hyper_connection.input_mix_weight_up.weight" => ("hc_attn_up", Reorder::None, false),
|
||||
"attn_hyper_connection.input_mix_weight_down.weight" => {
|
||||
("hc_attn_down", Reorder::None, false)
|
||||
}
|
||||
"mlp_hyper_connection.input_mix_weight_up.weight" => ("hc_ffn_up", Reorder::None, false),
|
||||
"mlp_hyper_connection.input_mix_weight_down.weight" => {
|
||||
("hc_ffn_down", Reorder::None, false)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some((format!("blk.{layer}.{gguf}.weight"), reorder, needs_skip))
|
||||
}
|
||||
|
||||
/// The linear-attention head geometry the reorder needs.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Heads {
|
||||
pub key_heads: usize,
|
||||
pub value_heads: usize,
|
||||
pub head_dim: usize,
|
||||
}
|
||||
|
||||
impl Heads {
|
||||
/// The GGUF head that holds checkpoint head `h`.
|
||||
fn source(&self, h: usize) -> usize {
|
||||
let r = self.value_heads / self.key_heads;
|
||||
(h % r) * self.key_heads + h / r
|
||||
}
|
||||
}
|
||||
|
||||
/// Reorders a tensor of `n_out` rows of `row_bytes` into the
|
||||
/// checkpoint's layout. `head_bytes` is one head's span within a row
|
||||
/// (only read for [`Reorder::Cols`]).
|
||||
pub(crate) fn reorder(
|
||||
src: &[u8],
|
||||
n_out: usize,
|
||||
row_bytes: usize,
|
||||
head_bytes: usize,
|
||||
how: Reorder,
|
||||
heads: Heads,
|
||||
) -> Result<Vec<u8>> {
|
||||
ensure!(src.len() == n_out * row_bytes, "tensor is not n_out rows");
|
||||
match how {
|
||||
Reorder::None => Ok(src.to_vec()),
|
||||
Reorder::Rows { skip_rows } => {
|
||||
let per_head = heads.head_dim * row_bytes;
|
||||
ensure!(
|
||||
n_out == skip_rows + heads.value_heads * heads.head_dim,
|
||||
"{n_out} rows are not {skip_rows} + {} value heads of {}",
|
||||
heads.value_heads,
|
||||
heads.head_dim
|
||||
);
|
||||
let mut out = src[..skip_rows * row_bytes].to_vec();
|
||||
let base = skip_rows * row_bytes;
|
||||
for h in 0..heads.value_heads {
|
||||
let at = base + heads.source(h) * per_head;
|
||||
out.extend_from_slice(&src[at..at + per_head]);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
Reorder::Cols => {
|
||||
ensure!(
|
||||
row_bytes == heads.value_heads * head_bytes,
|
||||
"a {row_bytes}-byte row is not {} heads of {head_bytes}",
|
||||
heads.value_heads
|
||||
);
|
||||
let mut out = Vec::with_capacity(src.len());
|
||||
for row in src.chunks_exact(row_bytes) {
|
||||
for h in 0..heads.value_heads {
|
||||
let at = heads.source(h) * head_bytes;
|
||||
out.extend_from_slice(&row[at..at + head_bytes]);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "strata-kernels")]
|
||||
pub use kernels::GgufDenseSource;
|
||||
|
||||
#[cfg(feature = "strata-kernels")]
|
||||
mod kernels {
|
||||
use std::ffi::c_void;
|
||||
use std::fs::File;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
|
||||
use candle_core::{CudaDevice, CudaStorage, DType, Device, Storage, Tensor};
|
||||
use memmap2::{Advice, Mmap};
|
||||
|
||||
use super::{Heads, gguf_name, reorder};
|
||||
use crate::cuda::strata as ffi;
|
||||
use crate::harness::arch::qwen3_5::proj::{ExternalLinear, LinearSource};
|
||||
use crate::harness::arch::qwen4_exp::gguf_index::GgufIndex;
|
||||
|
||||
const Q8_1_BLOCK_BYTES: usize = 36;
|
||||
/// Inputs of up to this many rows take the matrix-vector kernel;
|
||||
/// larger ones dequantize the weight and use a matmul.
|
||||
const MMVQ_MAX_ROWS: usize = 8;
|
||||
|
||||
fn address<T>(slice: &CudaSlice<T>) -> u64 {
|
||||
slice.device_ptr(slice.stream()).0
|
||||
}
|
||||
|
||||
pub struct GgufDenseSource {
|
||||
device: CudaDevice,
|
||||
index: GgufIndex,
|
||||
maps: Vec<Mmap>,
|
||||
heads: Heads,
|
||||
key_dim: usize,
|
||||
}
|
||||
|
||||
impl GgufDenseSource {
|
||||
pub fn open(first: &Path, device: &Device, heads: Heads, key_dim: usize) -> Result<Self> {
|
||||
let device = device.as_cuda_device()?.clone();
|
||||
let index = GgufIndex::open(first)?;
|
||||
let mut maps = Vec::with_capacity(index.shards.len());
|
||||
for path in &index.shards {
|
||||
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
|
||||
// SAFETY: model files are not modified while serving.
|
||||
let map = unsafe { Mmap::map(&file) }
|
||||
.with_context(|| format!("map {}", path.display()))?;
|
||||
map.advise(Advice::Sequential).context("advise dense map")?;
|
||||
maps.push(map);
|
||||
}
|
||||
tracing::info!(
|
||||
shards = maps.len(),
|
||||
"dense projections from GGUF on native kernels"
|
||||
);
|
||||
Ok(Self {
|
||||
device,
|
||||
index,
|
||||
maps,
|
||||
heads,
|
||||
key_dim,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl LinearSource for GgufDenseSource {
|
||||
fn linear(
|
||||
&self,
|
||||
name: &str,
|
||||
in_dim: usize,
|
||||
out_dim: usize,
|
||||
) -> Result<Option<Arc<dyn ExternalLinear>>> {
|
||||
let Some((gguf, mut how, needs_skip)) = gguf_name(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(tensor) = self.index.tensors.get(&gguf) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let ty = tensor.ggml_type as i32;
|
||||
// SAFETY: a pure function of its argument.
|
||||
if unsafe { ffi::neuron_strata_mmvq_supported(ty) } == 0 {
|
||||
tracing::info!(
|
||||
name,
|
||||
ggml_type = ty,
|
||||
"no native kernel for this type; dense"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
ensure!(
|
||||
tensor.dims == [in_dim as u64, out_dim as u64],
|
||||
"{gguf} is {:?}, the checkpoint's {name} is [{in_dim}, {out_dim}]",
|
||||
tensor.dims
|
||||
);
|
||||
if needs_skip {
|
||||
how = super::Reorder::Rows {
|
||||
skip_rows: 2 * self.key_dim,
|
||||
};
|
||||
}
|
||||
// SAFETY: pure functions of their integer arguments.
|
||||
let (row_bytes, head_bytes) = unsafe {
|
||||
(
|
||||
ffi::neuron_strata_row_bytes(ty, in_dim as i64),
|
||||
ffi::neuron_strata_row_bytes(ty, self.heads.head_dim as i64),
|
||||
)
|
||||
};
|
||||
ensure!(row_bytes > 0, "{gguf}: no row size for type {ty}");
|
||||
if how == super::Reorder::Cols && head_bytes * self.heads.value_heads != row_bytes {
|
||||
bail!(
|
||||
"{gguf}: type {ty} blocks do not divide a {}-wide head",
|
||||
self.heads.head_dim
|
||||
);
|
||||
}
|
||||
let start = tensor.offset as usize;
|
||||
let bytes = out_dim * row_bytes;
|
||||
let map = &self.maps[tensor.shard];
|
||||
ensure!(start + bytes <= map.len(), "{gguf} runs past its shard");
|
||||
let host = reorder(
|
||||
&map[start..start + bytes],
|
||||
out_dim,
|
||||
row_bytes,
|
||||
head_bytes,
|
||||
how,
|
||||
self.heads,
|
||||
)
|
||||
.with_context(|| format!("reorder {gguf}"))?;
|
||||
// SAFETY: written in full by the copy below.
|
||||
let mut weight = unsafe { self.device.alloc::<u8>(bytes) }?;
|
||||
self.device.memcpy_htod(&host, &mut weight)?;
|
||||
Ok(Some(Arc::new(QuantLinear {
|
||||
device: self.device.clone(),
|
||||
weight,
|
||||
ty,
|
||||
n_in: in_dim,
|
||||
n_out: out_dim,
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
struct QuantLinear {
|
||||
device: CudaDevice,
|
||||
weight: CudaSlice<u8>,
|
||||
ty: i32,
|
||||
n_in: usize,
|
||||
n_out: usize,
|
||||
}
|
||||
|
||||
impl QuantLinear {
|
||||
fn stream(&self) -> *mut c_void {
|
||||
self.device.cuda_stream().cu_stream() as *mut c_void
|
||||
}
|
||||
|
||||
/// `(rows, n_in)` f32 activations to `(rows, n_out)` f32.
|
||||
fn mmvq(&self, x: &Tensor, rows: usize) -> candle_core::Result<Tensor> {
|
||||
let (storage, layout) = x.storage_and_layout();
|
||||
let Storage::Cuda(storage) = &*storage else {
|
||||
candle_core::bail!("native dense projections need activations on the GPU");
|
||||
};
|
||||
let x_slice = storage.as_cuda_slice::<f32>()?;
|
||||
let x_ptr = (address(x_slice) as usize + layout.start_offset() * 4) as *const f32;
|
||||
// SAFETY: both are written in full before they are read.
|
||||
let q8 = unsafe {
|
||||
self.device
|
||||
.alloc::<u8>(rows * (self.n_in / 32) * Q8_1_BLOCK_BYTES)?
|
||||
};
|
||||
// SAFETY: as above.
|
||||
let out = unsafe { self.device.alloc::<f32>(rows * self.n_out)? };
|
||||
// SAFETY: every pointer is a live device allocation of the
|
||||
// size the kernels read or write; the stream orders them.
|
||||
unsafe {
|
||||
ffi::neuron_strata_quantize_q8_1(
|
||||
x_ptr,
|
||||
rows as i64,
|
||||
self.n_in as i64,
|
||||
address(&q8) as *mut c_void,
|
||||
self.stream(),
|
||||
);
|
||||
ffi::neuron_strata_mmvq(
|
||||
self.ty,
|
||||
address(&self.weight) as *const c_void,
|
||||
address(&q8) as *const c_void,
|
||||
address(&out) as *mut f32,
|
||||
self.n_in as i32,
|
||||
self.n_out as i32,
|
||||
rows as i32,
|
||||
self.stream(),
|
||||
);
|
||||
}
|
||||
// `q8` is freed stream-ordered, after the kernel has read it.
|
||||
drop(q8);
|
||||
Ok(Tensor::from((
|
||||
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
|
||||
(rows, self.n_out),
|
||||
)))
|
||||
}
|
||||
|
||||
/// The weight as a `(n_out, n_in)` tensor of `dtype`.
|
||||
fn dense(&self, dtype: DType) -> candle_core::Result<Tensor> {
|
||||
let n = self.n_in * self.n_out;
|
||||
// SAFETY: written in full by the dequantize below.
|
||||
let out = unsafe { self.device.alloc::<f32>(n)? };
|
||||
// SAFETY: the weight holds `n` values of `ty`; `out` holds n.
|
||||
unsafe {
|
||||
ffi::neuron_strata_dequant_f32(
|
||||
self.ty,
|
||||
address(&self.weight) as *const c_void,
|
||||
n as i64,
|
||||
address(&out) as *mut f32,
|
||||
self.stream(),
|
||||
);
|
||||
}
|
||||
Tensor::from((
|
||||
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
|
||||
(self.n_out, self.n_in),
|
||||
))
|
||||
.to_dtype(dtype)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalLinear for QuantLinear {
|
||||
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor> {
|
||||
let dims = x.dims().to_vec();
|
||||
let Some((&n_in, lead)) = dims.split_last() else {
|
||||
candle_core::bail!("a projection needs at least one dimension");
|
||||
};
|
||||
if n_in != self.n_in {
|
||||
candle_core::bail!("input is {n_in} wide, the weight takes {}", self.n_in);
|
||||
}
|
||||
let rows: usize = lead.iter().product();
|
||||
let x2 = x.reshape((rows, n_in))?;
|
||||
let y = if rows <= MMVQ_MAX_ROWS {
|
||||
let x32 = x2.to_dtype(DType::F32)?.contiguous()?;
|
||||
self.mmvq(&x32, rows)?.to_dtype(x.dtype())?
|
||||
} else {
|
||||
let w = self.dense(x.dtype())?;
|
||||
x2.contiguous()?.matmul(&w.t()?)?
|
||||
};
|
||||
let mut out_dims = lead.to_vec();
|
||||
out_dims.push(self.n_out);
|
||||
y.reshape(out_dims)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const HEADS: Heads = Heads {
|
||||
key_heads: 2,
|
||||
value_heads: 6,
|
||||
head_dim: 1,
|
||||
};
|
||||
|
||||
/// The mapping recovered from the shipped GGUF (16 key heads, 48
|
||||
/// value heads): GGUF head `g * 16 + k` is checkpoint head `3k + g`.
|
||||
#[test]
|
||||
fn the_shipped_geometry_matches_the_measured_permutation() {
|
||||
let heads = Heads {
|
||||
key_heads: 16,
|
||||
value_heads: 48,
|
||||
head_dim: 128,
|
||||
};
|
||||
// Checkpoint heads 0, 1, 2 are GGUF 0, 16, 32; checkpoint 3 is 1.
|
||||
assert_eq!(
|
||||
(0..5).map(|h| heads.source(h)).collect::<Vec<_>>(),
|
||||
[0, 16, 32, 1, 17]
|
||||
);
|
||||
// And measured directly: GGUF position 1 holds checkpoint head 3.
|
||||
let gguf_holds: Vec<usize> = (0..48)
|
||||
.map(|p| (0..48).find(|&h| heads.source(h) == p).unwrap())
|
||||
.collect();
|
||||
assert_eq!(&gguf_holds[..4], [0, 3, 6, 9]);
|
||||
assert_eq!(gguf_holds[16], 1);
|
||||
}
|
||||
|
||||
/// Rows after the skipped q/k move as whole heads; the skipped rows
|
||||
/// keep their place.
|
||||
#[test]
|
||||
fn rows_move_by_head_after_the_skip() {
|
||||
// Two skipped rows, then six value heads of one row each, two
|
||||
// bytes per row. GGUF value position p holds head `gguf_holds[p]`.
|
||||
let gguf_holds = [0u8, 3, 1, 4, 2, 5];
|
||||
let mut src = vec![100, 101, 102, 103];
|
||||
for h in gguf_holds {
|
||||
src.extend_from_slice(&[h, h]);
|
||||
}
|
||||
let got = reorder(&src, 8, 2, 0, Reorder::Rows { skip_rows: 2 }, HEADS).unwrap();
|
||||
assert_eq!(
|
||||
got,
|
||||
[100, 101, 102, 103, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
|
||||
);
|
||||
}
|
||||
|
||||
/// Columns move as whole head spans within every row.
|
||||
#[test]
|
||||
fn columns_move_by_head_within_each_row() {
|
||||
let gguf_holds = [0u8, 3, 1, 4, 2, 5];
|
||||
let mut src = Vec::new();
|
||||
for row in 0..2u8 {
|
||||
for h in gguf_holds {
|
||||
src.extend_from_slice(&[10 * row + h, 10 * row + h]);
|
||||
}
|
||||
}
|
||||
let got = reorder(&src, 2, 12, 2, Reorder::Cols, HEADS).unwrap();
|
||||
let want: Vec<u8> = (0..2u8)
|
||||
.flat_map(|row| (0..6u8).flat_map(move |h| [10 * row + h, 10 * row + h]))
|
||||
.collect();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_map_to_their_gguf_tensors() {
|
||||
assert_eq!(
|
||||
gguf_name("model.language_model.layers.7.linear_attn.out_proj.weight"),
|
||||
Some(("blk.7.ssm_out.weight".into(), Reorder::Cols, false))
|
||||
);
|
||||
assert_eq!(
|
||||
gguf_name("model.language_model.layers.3.self_attn.q_proj.weight"),
|
||||
Some(("blk.3.attn_q.weight".into(), Reorder::None, false))
|
||||
);
|
||||
assert_eq!(
|
||||
gguf_name("model.language_model.layers.0.linear_attn.in_proj_qkv.weight"),
|
||||
Some((
|
||||
"blk.0.attn_qkv.weight".into(),
|
||||
Reorder::Rows { skip_rows: 0 },
|
||||
true
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
gguf_name("model.language_model.hyper_connection_mixer.input_mix_weight_up.weight"),
|
||||
Some(("output_hc_up.weight".into(), Reorder::None, false))
|
||||
);
|
||||
// Unmapped names — the indexer, the MTP head — stay dense.
|
||||
assert_eq!(
|
||||
gguf_name("model.language_model.layers.3.self_attn.indexer.index_qk_proj.weight"),
|
||||
None
|
||||
);
|
||||
assert_eq!(gguf_name("mtp.layers.0.self_attn.q_proj.weight"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tensor_of_the_wrong_size_is_refused() {
|
||||
assert!(reorder(&[0; 5], 2, 2, 0, Reorder::None, HEADS).is_err());
|
||||
assert!(reorder(&[0; 14], 7, 2, 0, Reorder::Rows { skip_rows: 2 }, HEADS).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
//! Where each tensor of a split GGUF lies.
|
||||
//!
|
||||
//! A deliberately small reader: the native expert path needs names,
|
||||
//! shapes, types and absolute offsets, and must accept quantisation
|
||||
//! types candle's GGUF reader has no enum value for.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Read, Seek, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
|
||||
/// One tensor's location.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct GgufTensor {
|
||||
pub shard: usize,
|
||||
pub offset: u64,
|
||||
/// In GGUF order, innermost dimension first.
|
||||
pub dims: Vec<u64>,
|
||||
pub ggml_type: u32,
|
||||
}
|
||||
|
||||
/// Every tensor of a model, across its shards.
|
||||
#[derive(Debug)]
|
||||
pub struct GgufIndex {
|
||||
pub shards: Vec<PathBuf>,
|
||||
pub tensors: HashMap<String, GgufTensor>,
|
||||
}
|
||||
|
||||
fn read_u32(r: &mut impl Read) -> Result<u32> {
|
||||
let mut b = [0; 4];
|
||||
r.read_exact(&mut b)?;
|
||||
Ok(u32::from_le_bytes(b))
|
||||
}
|
||||
|
||||
fn read_u64(r: &mut impl Read) -> Result<u64> {
|
||||
let mut b = [0; 8];
|
||||
r.read_exact(&mut b)?;
|
||||
Ok(u64::from_le_bytes(b))
|
||||
}
|
||||
|
||||
fn read_string(r: &mut impl Read) -> Result<String> {
|
||||
let len = read_u64(r)?;
|
||||
ensure!(len <= 1 << 30, "implausible GGUF string length {len}");
|
||||
let mut b = vec![0; len as usize];
|
||||
r.read_exact(&mut b)?;
|
||||
String::from_utf8(b).context("GGUF string is not UTF-8")
|
||||
}
|
||||
|
||||
fn skip(r: &mut (impl Read + Seek), bytes: i64) -> Result<()> {
|
||||
r.seek(SeekFrom::Current(bytes))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn scalar_size(value_type: u32) -> Option<i64> {
|
||||
match value_type {
|
||||
0 | 1 | 7 => Some(1),
|
||||
2 | 3 => Some(2),
|
||||
4..=6 => Some(4),
|
||||
10..=12 => Some(8),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Skips one value, returning it when it is an unsigned 32-bit integer
|
||||
/// (the type `general.alignment` is stored as).
|
||||
fn skip_value(r: &mut (impl Read + Seek), value_type: u32) -> Result<Option<u32>> {
|
||||
if value_type == 4 {
|
||||
return Ok(Some(read_u32(r)?));
|
||||
}
|
||||
if let Some(size) = scalar_size(value_type) {
|
||||
skip(r, size)?;
|
||||
return Ok(None);
|
||||
}
|
||||
match value_type {
|
||||
8 => {
|
||||
let len = read_u64(r)?;
|
||||
skip(r, i64::try_from(len)?)?;
|
||||
}
|
||||
9 => {
|
||||
let element = read_u32(r)?;
|
||||
let count = read_u64(r)?;
|
||||
if let Some(size) = scalar_size(element) {
|
||||
skip(
|
||||
r,
|
||||
size.checked_mul(i64::try_from(count)?)
|
||||
.context("GGUF array size")?,
|
||||
)?;
|
||||
} else if element == 8 {
|
||||
for _ in 0..count {
|
||||
let len = read_u64(r)?;
|
||||
skip(r, i64::try_from(len)?)?;
|
||||
}
|
||||
} else {
|
||||
bail!("unsupported GGUF array element type {element}");
|
||||
}
|
||||
}
|
||||
other => bail!("unknown GGUF value type {other}"),
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn read_shard(path: &Path, shard: usize, out: &mut HashMap<String, GgufTensor>) -> Result<()> {
|
||||
let mut r =
|
||||
BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
|
||||
let mut magic = [0; 4];
|
||||
r.read_exact(&mut magic)?;
|
||||
ensure!(&magic == b"GGUF", "{} is not a GGUF file", path.display());
|
||||
let version = read_u32(&mut r)?;
|
||||
ensure!(version == 3, "{}: GGUF version {version}", path.display());
|
||||
let n_tensors = read_u64(&mut r)?;
|
||||
let n_kv = read_u64(&mut r)?;
|
||||
|
||||
let mut alignment = 32_u64;
|
||||
for _ in 0..n_kv {
|
||||
let key = read_string(&mut r)?;
|
||||
let value_type = read_u32(&mut r)?;
|
||||
if let Some(v) = skip_value(&mut r, value_type)?
|
||||
&& key == "general.alignment"
|
||||
{
|
||||
ensure!(v > 0 && v.is_power_of_two(), "bad GGUF alignment {v}");
|
||||
alignment = u64::from(v);
|
||||
}
|
||||
}
|
||||
|
||||
let mut found = Vec::with_capacity(n_tensors as usize);
|
||||
for _ in 0..n_tensors {
|
||||
let name = read_string(&mut r)?;
|
||||
let n_dims = read_u32(&mut r)?;
|
||||
ensure!(n_dims <= 8, "{name}: {n_dims} dimensions");
|
||||
let dims = (0..n_dims)
|
||||
.map(|_| read_u64(&mut r))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let ggml_type = read_u32(&mut r)?;
|
||||
let offset = read_u64(&mut r)?;
|
||||
found.push((name, dims, ggml_type, offset));
|
||||
}
|
||||
let header_end = r.stream_position()?;
|
||||
let data_start = header_end.div_ceil(alignment) * alignment;
|
||||
for (name, dims, ggml_type, offset) in found {
|
||||
out.insert(
|
||||
name,
|
||||
GgufTensor {
|
||||
shard,
|
||||
offset: data_start + offset,
|
||||
dims,
|
||||
ggml_type,
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The sibling paths of a `name-00001-of-0000N.gguf` shard, or the file
|
||||
/// itself when it is not split.
|
||||
fn shard_paths(first: &Path) -> Result<Vec<PathBuf>> {
|
||||
let name = first
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.context("GGUF path has no file name")?;
|
||||
let Some(stem) = name.strip_suffix(".gguf") else {
|
||||
bail!("{name} is not a .gguf file");
|
||||
};
|
||||
let parts: Vec<&str> = stem.rsplitn(4, '-').collect();
|
||||
if parts.len() == 4
|
||||
&& parts[1] == "of"
|
||||
&& parts[0].len() == 5
|
||||
&& parts[2].len() == 5
|
||||
&& let Ok(total) = parts[0].parse::<usize>()
|
||||
{
|
||||
let dir = first.parent().unwrap_or_else(|| Path::new("."));
|
||||
return Ok((1..=total)
|
||||
.map(|i| dir.join(format!("{}-{i:05}-of-{total:05}.gguf", parts[3])))
|
||||
.collect());
|
||||
}
|
||||
Ok(vec![first.to_path_buf()])
|
||||
}
|
||||
|
||||
impl GgufIndex {
|
||||
/// Reads every shard of the model whose first shard is `first`.
|
||||
pub fn open(first: &Path) -> Result<Self> {
|
||||
let shards = shard_paths(first)?;
|
||||
let mut tensors = HashMap::new();
|
||||
for (i, path) in shards.iter().enumerate() {
|
||||
read_shard(path, i, &mut tensors)?;
|
||||
}
|
||||
Ok(Self { shards, tensors })
|
||||
}
|
||||
}
|
||||
|
||||
/// The `(layer, expert)` pairs of a Strata expert profile, hottest first.
|
||||
pub fn read_expert_profile(path: &Path, layers: usize, experts: usize) -> Result<Vec<(u16, u16)>> {
|
||||
let blob = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
|
||||
parse_expert_profile(&blob, layers, experts)
|
||||
.with_context(|| format!("parse {}", path.display()))
|
||||
}
|
||||
|
||||
fn parse_expert_profile(blob: &[u8], layers: usize, experts: usize) -> Result<Vec<(u16, u16)>> {
|
||||
const HEADER: usize = 24;
|
||||
ensure!(
|
||||
blob.len() >= HEADER && &blob[..4] == b"STRP",
|
||||
"not an expert profile"
|
||||
);
|
||||
let field = |i: usize| {
|
||||
u32::from_le_bytes(blob[4 + i * 4..8 + i * 4].try_into().expect("four bytes")) as usize
|
||||
};
|
||||
ensure!(field(0) == 1, "profile version {}", field(0));
|
||||
ensure!(
|
||||
(field(1), field(2)) == (layers, experts),
|
||||
"profile is {}x{}, the model is {layers}x{experts}",
|
||||
field(1),
|
||||
field(2)
|
||||
);
|
||||
let count = field(4);
|
||||
ensure!(count <= layers * experts, "profile ranks {count} pairs");
|
||||
ensure!(blob.len() >= HEADER + count * 4, "profile is truncated");
|
||||
blob[HEADER..HEADER + count * 4]
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|pair| {
|
||||
let layer = u16::from_le_bytes([pair[0], pair[1]]);
|
||||
let expert = u16::from_le_bytes([pair[2], pair[3]]);
|
||||
ensure!(
|
||||
(layer as usize) < layers && (expert as usize) < experts,
|
||||
"pair ({layer}, {expert}) is out of range"
|
||||
);
|
||||
Ok((layer, expert))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
fn string(out: &mut Vec<u8>, s: &str) {
|
||||
out.extend((s.len() as u64).to_le_bytes());
|
||||
out.extend(s.as_bytes());
|
||||
}
|
||||
|
||||
/// A GGUF with one of each key shape the skipper must cross.
|
||||
fn shard(alignment: u32, tensors: &[(&str, &[u64], u32, u64)]) -> Vec<u8> {
|
||||
let mut b = b"GGUF".to_vec();
|
||||
b.extend(3_u32.to_le_bytes());
|
||||
b.extend((tensors.len() as u64).to_le_bytes());
|
||||
b.extend(4_u64.to_le_bytes());
|
||||
string(&mut b, "a.string");
|
||||
b.extend(8_u32.to_le_bytes());
|
||||
string(&mut b, "value");
|
||||
string(&mut b, "a.array");
|
||||
b.extend(9_u32.to_le_bytes());
|
||||
b.extend(8_u32.to_le_bytes());
|
||||
b.extend(2_u64.to_le_bytes());
|
||||
string(&mut b, "x");
|
||||
string(&mut b, "yz");
|
||||
string(&mut b, "a.numbers");
|
||||
b.extend(9_u32.to_le_bytes());
|
||||
b.extend(5_u32.to_le_bytes());
|
||||
b.extend(3_u64.to_le_bytes());
|
||||
b.extend([0_u8; 12]);
|
||||
string(&mut b, "general.alignment");
|
||||
b.extend(4_u32.to_le_bytes());
|
||||
b.extend(alignment.to_le_bytes());
|
||||
for (name, dims, ty, offset) in tensors {
|
||||
string(&mut b, name);
|
||||
b.extend((dims.len() as u32).to_le_bytes());
|
||||
for d in *dims {
|
||||
b.extend(d.to_le_bytes());
|
||||
}
|
||||
b.extend(ty.to_le_bytes());
|
||||
b.extend(offset.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offsets_are_absolute_and_follow_the_alignment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("m.gguf");
|
||||
let bytes = shard(64, &[("t", &[2560, 640, 512], 21, 128)]);
|
||||
let data_start = (bytes.len() as u64).div_ceil(64) * 64;
|
||||
File::create(&path).unwrap().write_all(&bytes).unwrap();
|
||||
let index = GgufIndex::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
index.tensors["t"],
|
||||
GgufTensor {
|
||||
shard: 0,
|
||||
offset: data_start + 128,
|
||||
dims: vec![2560, 640, 512],
|
||||
ggml_type: 21,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_models_are_read_from_every_shard() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (i, name) in ["a", "b"].iter().enumerate() {
|
||||
let path = dir.path().join(format!("m-Q-{:05}-of-00002.gguf", i + 1));
|
||||
let bytes = shard(32, &[(name, &[1], 8, 0)]);
|
||||
File::create(path).unwrap().write_all(&bytes).unwrap();
|
||||
}
|
||||
let index = GgufIndex::open(&dir.path().join("m-Q-00001-of-00002.gguf")).unwrap();
|
||||
assert_eq!(index.shards.len(), 2);
|
||||
assert_eq!((index.tensors["a"].shard, index.tensors["b"].shard), (0, 1));
|
||||
}
|
||||
|
||||
fn profile(version: u32, layers: u32, experts: u32, pairs: &[(u16, u16)]) -> Vec<u8> {
|
||||
let mut b = b"STRP".to_vec();
|
||||
for v in [
|
||||
version,
|
||||
layers,
|
||||
experts,
|
||||
layers * experts,
|
||||
pairs.len() as u32,
|
||||
] {
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
for (l, e) in pairs {
|
||||
b.extend(l.to_le_bytes());
|
||||
b.extend(e.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_keeps_its_rank_order() {
|
||||
let blob = profile(1, 2, 4, &[(1, 3), (0, 2)]);
|
||||
assert_eq!(
|
||||
parse_expert_profile(&blob, 2, 4).unwrap(),
|
||||
vec![(1, 3), (0, 2)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_for_another_shape_or_out_of_range_is_refused() {
|
||||
assert!(parse_expert_profile(&profile(1, 2, 4, &[]), 3, 4).is_err());
|
||||
assert!(parse_expert_profile(&profile(2, 2, 4, &[]), 2, 4).is_err());
|
||||
assert!(parse_expert_profile(&profile(1, 2, 4, &[(2, 0)]), 2, 4).is_err());
|
||||
let truncated = profile(1, 2, 4, &[(1, 1)]);
|
||||
assert!(parse_expert_profile(&truncated[..truncated.len() - 1], 2, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_not_gguf_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("m.gguf");
|
||||
File::create(&path).unwrap().write_all(b"NOPE0000").unwrap();
|
||||
assert!(GgufIndex::open(&path).is_err());
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ use candle_core::{D, Module, Tensor};
|
||||
use candle_nn::Linear;
|
||||
use candle_nn::var_builder::ShardedVarBuilder;
|
||||
|
||||
use crate::harness::arch::qwen3_5::proj::{LinearSource, Proj, load_proj};
|
||||
use crate::harness::arch::qwen3_5::rmsnorm::Qwen3_5RmsNorm;
|
||||
|
||||
/// What a hyper-connection hands its sublayer.
|
||||
@@ -56,8 +57,8 @@ pub struct HyperSplit {
|
||||
/// `Qwen4ExpTextGatedResidual`.
|
||||
pub struct HyperConnection {
|
||||
hc_norm: Qwen3_5RmsNorm,
|
||||
mix_down: Linear,
|
||||
mix_up: Linear,
|
||||
mix_down: Proj,
|
||||
mix_up: Proj,
|
||||
/// Absent on the top-level `hyper_connection_mixer`, which collapses
|
||||
/// the streams for the LM head instead of feeding a sublayer.
|
||||
block_inject: Option<Linear>,
|
||||
@@ -73,12 +74,13 @@ impl HyperConnection {
|
||||
hc_lowrank: usize,
|
||||
eps: f64,
|
||||
use_combine: bool,
|
||||
source: Option<&dyn LinearSource>,
|
||||
) -> Result<Self> {
|
||||
let wide = hidden_size * hc_count;
|
||||
let hc_norm = Qwen3_5RmsNorm::load_grouped(&vb.pp("hc_norm"), wide, hidden_size, eps)
|
||||
.with_context(|| format!("load '{}/hc_norm'", vb.prefix()))?;
|
||||
let mix_down = linear(vb, "input_mix_weight_down", wide, hc_lowrank)?;
|
||||
let mix_up = linear(vb, "input_mix_weight_up", hc_lowrank, wide)?;
|
||||
let mix_down = load_proj(vb, "input_mix_weight_down", wide, hc_lowrank, source)?;
|
||||
let mix_up = load_proj(vb, "input_mix_weight_up", hc_lowrank, wide, source)?;
|
||||
let block_inject = if use_combine {
|
||||
Some(linear(vb, "block_inject_weight", wide, hc_count)?)
|
||||
} else {
|
||||
@@ -123,8 +125,8 @@ impl HyperConnection {
|
||||
1e-6,
|
||||
Some(hidden_size),
|
||||
),
|
||||
mix_down: z(hc_lowrank, wide),
|
||||
mix_up: z(wide, hc_lowrank),
|
||||
mix_down: z(hc_lowrank, wide).into(),
|
||||
mix_up: z(wide, hc_lowrank).into(),
|
||||
block_inject: use_combine.then(|| z(hc_count, wide)),
|
||||
hidden_size,
|
||||
hc_count,
|
||||
|
||||
@@ -31,10 +31,15 @@ use crate::harness::arch::qwen3_5::linear_attn::{
|
||||
};
|
||||
|
||||
use super::config::TextConfig;
|
||||
use crate::harness::arch::qwen3_5::proj::LinearSource;
|
||||
|
||||
/// `vb` should be `.pp(...)`-ed to the layer's `linear_attn` prefix.
|
||||
pub fn load(cfg: &TextConfig, vb: &ShardedVarBuilder) -> Result<GatedDeltaNet> {
|
||||
GatedDeltaNet::load_with_params(params(cfg)?, vb)
|
||||
pub fn load(
|
||||
cfg: &TextConfig,
|
||||
vb: &ShardedVarBuilder,
|
||||
source: Option<&dyn LinearSource>,
|
||||
) -> Result<GatedDeltaNet> {
|
||||
GatedDeltaNet::load_with_source(params(cfg)?, vb, source)
|
||||
}
|
||||
|
||||
/// The settings this architecture asks for, as opposed to the ones
|
||||
|
||||
@@ -37,11 +37,17 @@
|
||||
pub mod config;
|
||||
pub mod decoder;
|
||||
pub mod full_attn;
|
||||
#[cfg(any(test, feature = "strata-kernels"))]
|
||||
pub mod gguf_dense;
|
||||
#[cfg(any(test, feature = "strata-kernels"))]
|
||||
pub mod gguf_index;
|
||||
pub mod hyper;
|
||||
pub mod linear_attn;
|
||||
pub mod model;
|
||||
pub mod moe;
|
||||
pub mod mtp;
|
||||
#[cfg(feature = "strata-kernels")]
|
||||
pub mod native_experts;
|
||||
pub mod ple;
|
||||
pub mod qsa;
|
||||
|
||||
@@ -87,4 +93,14 @@ pub struct LoadOptions<'a> {
|
||||
/// Reading them straight into host memory removes the transit
|
||||
/// rather than managing it.
|
||||
pub experts_vb: Option<&'a candle_nn::var_builder::ShardedVarBuilder<'a>>,
|
||||
/// VRAM tier for host-resident experts (#318). `None` computes them
|
||||
/// where they live.
|
||||
pub expert_tier: Option<std::sync::Arc<super::qwen3_5::moe::DeviceExpertTier>>,
|
||||
/// Routed experts served outside candle. When set, the checkpoint's
|
||||
/// expert tensors are not read at all.
|
||||
pub external_experts: Option<std::sync::Arc<dyn super::qwen3_5::moe::ExternalExpertSource>>,
|
||||
/// Dense projections served outside candle (a GGUF's quantized
|
||||
/// blocks). Each is asked for by checkpoint name; what it declines
|
||||
/// is read from the checkpoint.
|
||||
pub dense: Option<std::sync::Arc<dyn super::qwen3_5::proj::LinearSource>>,
|
||||
}
|
||||
|
||||
@@ -35,10 +35,11 @@
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use candle_core::{DType, Device, IndexOp, Module, Tensor};
|
||||
use candle_nn::Embedding;
|
||||
use candle_nn::var_builder::ShardedVarBuilder;
|
||||
use candle_nn::{Embedding, Linear};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::harness::arch::qwen3_5::proj::{Proj, load_proj};
|
||||
use crate::harness::arch::qwen3_5::rope::RotaryEmbedding;
|
||||
|
||||
use super::config::{Config, TextConfig};
|
||||
@@ -116,7 +117,7 @@ pub struct Qwen4ExpForCausalLM {
|
||||
/// `hyper_connection_mixer` — `use_combine = false`, so it collapses
|
||||
/// rather than scatters, and there is no final norm beside it.
|
||||
mixer: HyperConnection,
|
||||
lm_head: Linear,
|
||||
lm_head: Proj,
|
||||
ngram: Option<NGramEmbedding>,
|
||||
rotary: Arc<RotaryEmbedding>,
|
||||
hc_count: usize,
|
||||
@@ -191,19 +192,24 @@ impl Qwen4ExpForCausalLM {
|
||||
// No block_inject_weight in the checkpoint: this one ends
|
||||
// the streams rather than feeding a sublayer.
|
||||
false,
|
||||
opts.dense.as_deref(),
|
||||
)
|
||||
.context("load hyper_connection_mixer")?;
|
||||
|
||||
let lm_head_weight = vb
|
||||
.pp("lm_head")
|
||||
.get((text.vocab_size, text.hidden_size), "weight")
|
||||
.context("load 'lm_head.weight'")?;
|
||||
let lm_head = load_proj(
|
||||
vb,
|
||||
"lm_head",
|
||||
text.hidden_size,
|
||||
text.vocab_size,
|
||||
opts.dense.as_deref(),
|
||||
)
|
||||
.context("load 'lm_head.weight'")?;
|
||||
|
||||
Ok(Self {
|
||||
embed_tokens,
|
||||
layers,
|
||||
mixer,
|
||||
lm_head: Linear::new(lm_head_weight, None),
|
||||
lm_head,
|
||||
ngram,
|
||||
rotary,
|
||||
hc_count: text.hc_count,
|
||||
@@ -849,6 +855,9 @@ mod tests {
|
||||
isq_cache: None,
|
||||
experts_onto: &Device::Cpu,
|
||||
experts_vb: None,
|
||||
expert_tier: None,
|
||||
external_experts: None,
|
||||
dense: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn load(
|
||||
// A hit skips reading the fused tensors at all, which is the point:
|
||||
// the cost being avoided is the 5.03 GB read *and* the ~32 s of
|
||||
// quantisation, not just the latter.
|
||||
let cached = match (quant, isq_cache) {
|
||||
let cached = match (quant, isq_cache.filter(|_| opts.external_experts.is_none())) {
|
||||
(Some(_), Some(cache)) => cache.load(&cache_key, experts_onto).and_then(|entries| {
|
||||
match Experts::from_cache_entries(entries, cfg.num_experts) {
|
||||
Ok(e) => Some(e),
|
||||
@@ -113,7 +113,19 @@ pub fn load(
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let experts = match cached {
|
||||
let external = match &opts.external_experts {
|
||||
Some(source) => {
|
||||
let layer = layer_of(&vb.prefix())
|
||||
.with_context(|| format!("no layer index in '{}'", vb.prefix()))?;
|
||||
Some(Experts::External {
|
||||
count: cfg.num_experts,
|
||||
inner: source.block(layer)?,
|
||||
})
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let experts = match external.or(cached) {
|
||||
Some(experts) => experts,
|
||||
None => {
|
||||
let gate_up = experts_vb
|
||||
@@ -151,10 +163,11 @@ pub fn load(
|
||||
};
|
||||
|
||||
let (shared_expert, shared_expert_gate) = if cfg.shared_expert_intermediate_size > 0 {
|
||||
let shared = Qwen3_5MLP::load_with_dims(
|
||||
let shared = Qwen3_5MLP::load_with_source(
|
||||
&vb.pp("shared_expert"),
|
||||
h,
|
||||
cfg.shared_expert_intermediate_size,
|
||||
opts.dense.as_deref(),
|
||||
)
|
||||
.context("load shared_expert")?;
|
||||
let gate_w = vb
|
||||
@@ -173,7 +186,16 @@ pub fn load(
|
||||
shared_expert_gate,
|
||||
cfg.num_experts_per_tok,
|
||||
cfg.norm_topk_prob,
|
||||
))
|
||||
)
|
||||
.with_tier(opts.expert_tier.clone()))
|
||||
}
|
||||
|
||||
/// The layer index in a tensor prefix such as
|
||||
/// `model.language_model.layers.7.mlp`.
|
||||
fn layer_of(prefix: &str) -> Option<usize> {
|
||||
let mut parts = prefix.split('.');
|
||||
parts.find(|p| *p == "layers")?;
|
||||
parts.next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Validate the fused pair before it is banked.
|
||||
@@ -208,6 +230,12 @@ mod tests {
|
||||
/// The loader validates the fused pair up front. Without this the
|
||||
/// first token to route to a bad expert fails mid-forward, which is
|
||||
/// a worse place to learn the checkpoint disagrees with the config.
|
||||
#[test]
|
||||
fn the_layer_index_comes_from_the_tensor_prefix() {
|
||||
assert_eq!(layer_of("model.language_model.layers.17.mlp"), Some(17));
|
||||
assert_eq!(layer_of("mtp.mlp"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fused_pair_that_disagrees_with_the_config_is_rejected() {
|
||||
let dev = Device::Cpu;
|
||||
|
||||
@@ -124,6 +124,9 @@ impl MtpHead {
|
||||
isq_cache: None,
|
||||
experts_onto: vb.device(),
|
||||
experts_vb: None,
|
||||
expert_tier: None,
|
||||
external_experts: None,
|
||||
dense: None,
|
||||
},
|
||||
)
|
||||
.context("load mtp.layers.0")?,
|
||||
@@ -134,6 +137,7 @@ impl MtpHead {
|
||||
cfg.hc_lowrank,
|
||||
cfg.rms_norm_eps,
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.context("load mtp.hyper_connection_mixer")?,
|
||||
hidden_size: h,
|
||||
|
||||
@@ -0,0 +1,684 @@
|
||||
//! Routed experts on Strata's grouped kernels, from a GGUF's own blocks.
|
||||
//!
|
||||
//! Neuron keeps routing. For each layer this module groups the routed
|
||||
//! tokens by expert, makes each active expert's `[gate | up | down]`
|
||||
//! blob addressable on the device, and runs them all in one
|
||||
//! `native_expert_grouped` launch.
|
||||
//!
|
||||
//! An expert comes from the VRAM tier when it is held. Decode-sized
|
||||
//! forwards admit what they miss. A prompt chunk must not (see
|
||||
//! [`ExpertTier::peek`]), so its misses are copied into a reusable arena
|
||||
//! for the duration of that layer.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::fs::File;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use candle_core::cuda_backend::cudarc::driver::result::mem_pool;
|
||||
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr, DeviceSlice, sys};
|
||||
use candle_core::{CudaDevice, CudaStorage, DType, Device, Storage, Tensor};
|
||||
use memmap2::{Advice, Mmap};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use super::gguf_index::{GgufIndex, GgufTensor, read_expert_profile};
|
||||
use crate::cuda::strata as ffi;
|
||||
use crate::harness::arch::qwen3_5::expert_tier::ExpertTier;
|
||||
use crate::harness::arch::qwen3_5::moe::{
|
||||
ExternalExpertSource, ExternalExperts, TIER_ADMIT_MAX_ROWS,
|
||||
};
|
||||
|
||||
const Q8_1_BLOCK_BYTES: usize = 36;
|
||||
const Q8_1_BLOCK_VALUES: usize = 32;
|
||||
/// Pinned host memory expert blobs are staged through. Pinned because
|
||||
/// an unpinned source makes the driver stage it again, at a fraction of
|
||||
/// the link's speed.
|
||||
const STAGING_BYTES: usize = 2 << 30;
|
||||
|
||||
/// Pinned host memory. Freed on the device worker with the model.
|
||||
struct PinnedBuffer {
|
||||
ptr: *mut u8,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
// SAFETY: the buffer is plain host memory, and every access is made
|
||||
// while holding the workspace lock.
|
||||
unsafe impl Send for PinnedBuffer {}
|
||||
|
||||
impl PinnedBuffer {
|
||||
fn new(len: usize) -> candle_core::Result<Self> {
|
||||
// SAFETY: returns null or an allocation of `len` bytes.
|
||||
let ptr = unsafe { ffi::neuron_strata_pinned_alloc(len) }.cast::<u8>();
|
||||
if ptr.is_null() {
|
||||
candle_core::bail!("cannot pin {len} bytes of staging memory");
|
||||
}
|
||||
Ok(Self { ptr, len })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PinnedBuffer {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: allocated by `neuron_strata_pinned_alloc`, freed once.
|
||||
unsafe { ffi::neuron_strata_pinned_free(self.ptr.cast()) };
|
||||
}
|
||||
}
|
||||
|
||||
/// An expert's blob held in VRAM.
|
||||
pub struct ExpertSlot {
|
||||
blob: CudaSlice<u8>,
|
||||
}
|
||||
|
||||
/// A CUDA memory pool for the tier's experts alone.
|
||||
///
|
||||
/// Thousands of long-lived expert blobs allocated from the default pool
|
||||
/// sit among the forward pass's transient tensors and pin the blocks
|
||||
/// they share, so the pool cannot hand those blocks back: measured on
|
||||
/// one 5090, 29 GB reserved against a 21 GB peak of live data. With
|
||||
/// their own pool the experts only ever share blocks with each other,
|
||||
/// and the default pool's trims return the transients' memory.
|
||||
struct TierPool(sys::CUmemoryPool);
|
||||
|
||||
// SAFETY: a pool handle may be used from any thread of its context, and
|
||||
// the source is only used from its device worker.
|
||||
unsafe impl Send for TierPool {}
|
||||
// SAFETY: as above; allocation from a pool is thread-safe in the driver.
|
||||
unsafe impl Sync for TierPool {}
|
||||
|
||||
impl TierPool {
|
||||
fn new(ordinal: usize) -> candle_core::Result<Self> {
|
||||
// SAFETY: an all-zero props struct is valid; the fields that
|
||||
// matter are set below, and zero handle types means none.
|
||||
let mut props: sys::CUmemPoolProps = unsafe { std::mem::zeroed() };
|
||||
props.allocType = sys::CUmemAllocationType::CU_MEM_ALLOCATION_TYPE_PINNED;
|
||||
props.location.type_ = sys::CUmemLocationType::CU_MEM_LOCATION_TYPE_DEVICE;
|
||||
props.location.id = ordinal as i32;
|
||||
// SAFETY: `props` describes this device.
|
||||
let pool = unsafe { mem_pool::create(&props) }.map_err(candle_err)?;
|
||||
// Keep what eviction frees: the next admission reuses it.
|
||||
let mut keep = u64::MAX;
|
||||
// SAFETY: the release threshold is a cuuint64_t.
|
||||
unsafe {
|
||||
mem_pool::set_attribute(
|
||||
pool,
|
||||
sys::CUmemPool_attribute::CU_MEMPOOL_ATTR_RELEASE_THRESHOLD,
|
||||
(&raw mut keep).cast(),
|
||||
)
|
||||
}
|
||||
.map_err(candle_err)?;
|
||||
Ok(Self(pool))
|
||||
}
|
||||
|
||||
fn alloc(&self, device: &CudaDevice, bytes: usize) -> candle_core::Result<CudaSlice<u8>> {
|
||||
let stream = device.cuda_stream();
|
||||
let mut ptr: sys::CUdeviceptr = 0;
|
||||
// SAFETY: the pool and stream belong to this device's context.
|
||||
unsafe { sys::cuMemAllocFromPoolAsync(&mut ptr, bytes, self.0, stream.cu_stream()) }
|
||||
.result()
|
||||
.map_err(candle_err)?;
|
||||
// SAFETY: `ptr` is a fresh allocation of `bytes` bytes. Its drop
|
||||
// frees it stream-ordered, which returns it to this pool.
|
||||
Ok(unsafe { stream.upgrade_device_ptr(ptr, bytes) })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TierPool {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: created by `new`; the driver defers the destruction
|
||||
// until every allocation from it has been freed.
|
||||
let _ = unsafe { mem_pool::destroy(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
fn device_address<T: candle_core::cuda_backend::cudarc::driver::DeviceRepr + 'static>(
|
||||
slice: &CudaSlice<T>,
|
||||
) -> u64 {
|
||||
slice.device_ptr(slice.stream()).0
|
||||
}
|
||||
|
||||
/// Per-layer timing, from `NEURON_EXPERT_TIMING`.
|
||||
fn timing_enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("NEURON_EXPERT_TIMING").is_some())
|
||||
}
|
||||
|
||||
fn candle_err(e: impl std::fmt::Display) -> candle_core::Error {
|
||||
candle_core::Error::msg(e.to_string())
|
||||
}
|
||||
|
||||
/// Where one projection of a layer's experts lies.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Role {
|
||||
shard: usize,
|
||||
offset: usize,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
struct Layer {
|
||||
gu_type: i32,
|
||||
d_type: i32,
|
||||
gate: Role,
|
||||
up: Role,
|
||||
down: Role,
|
||||
blob_bytes: usize,
|
||||
}
|
||||
|
||||
/// One expert blob to copy to the device.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Upload {
|
||||
expert: usize,
|
||||
address: u64,
|
||||
in_arena: bool,
|
||||
}
|
||||
|
||||
/// Device buffers reused from layer to layer.
|
||||
///
|
||||
/// Reuse is safe because each layer synchronizes the stream before
|
||||
/// returning, so no queued kernel still reads them.
|
||||
#[derive(Default)]
|
||||
struct Workspace {
|
||||
q8: Option<CudaSlice<u8>>,
|
||||
scratch: Option<CudaSlice<u8>>,
|
||||
grp_ptr: Option<CudaSlice<u64>>,
|
||||
grp_start: Option<CudaSlice<i32>>,
|
||||
n_groups: Option<CudaSlice<i32>>,
|
||||
ent_dst: Option<CudaSlice<i32>>,
|
||||
ent_tok: Option<CudaSlice<i32>>,
|
||||
arena: Option<CudaSlice<u8>>,
|
||||
staging: Option<PinnedBuffer>,
|
||||
}
|
||||
|
||||
fn ensure_capacity<T: candle_core::cuda_backend::cudarc::driver::DeviceRepr + 'static>(
|
||||
device: &CudaDevice,
|
||||
slot: &mut Option<CudaSlice<T>>,
|
||||
len: usize,
|
||||
) -> candle_core::Result<()> {
|
||||
if slot.as_ref().is_none_or(|s| s.len() < len) {
|
||||
*slot = None;
|
||||
// SAFETY: every user writes the range it later reads.
|
||||
*slot = Some(unsafe { device.alloc::<T>(len.max(1))? });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn upload<T: candle_core::cuda_backend::cudarc::driver::DeviceRepr + 'static>(
|
||||
device: &CudaDevice,
|
||||
slot: &mut Option<CudaSlice<T>>,
|
||||
data: &[T],
|
||||
) -> candle_core::Result<u64> {
|
||||
ensure_capacity(device, slot, data.len())?;
|
||||
let buffer = slot.as_mut().expect("capacity was just ensured");
|
||||
device.memcpy_htod(data, &mut buffer.slice_mut(..data.len()))?;
|
||||
Ok(device_address(buffer))
|
||||
}
|
||||
|
||||
/// The model's GGUF experts, shared by its MoE blocks.
|
||||
pub struct GgufExpertSource {
|
||||
device: CudaDevice,
|
||||
n_embd: usize,
|
||||
n_ff: usize,
|
||||
maps: Vec<Mmap>,
|
||||
layers: Vec<Layer>,
|
||||
tier: Option<Arc<ExpertTier<ExpertSlot>>>,
|
||||
workspace: Mutex<Workspace>,
|
||||
/// Declared after `tier`, so the experts are freed first.
|
||||
tier_pool: TierPool,
|
||||
}
|
||||
|
||||
fn role(
|
||||
index: &GgufIndex,
|
||||
layer: usize,
|
||||
name: &str,
|
||||
want_dims: [u64; 3],
|
||||
) -> Result<(GgufTensor, usize)> {
|
||||
let key = format!("blk.{layer}.ffn_{name}_exps.weight");
|
||||
let tensor = index
|
||||
.tensors
|
||||
.get(&key)
|
||||
.with_context(|| format!("GGUF has no {key}"))?;
|
||||
ensure!(
|
||||
tensor.dims == want_dims,
|
||||
"{key} is {:?}, expected {want_dims:?}",
|
||||
tensor.dims
|
||||
);
|
||||
// SAFETY: a pure function of its integer arguments.
|
||||
let row = unsafe { ffi::neuron_strata_row_bytes(tensor.ggml_type as i32, want_dims[0] as i64) };
|
||||
ensure!(row > 0, "{key}: unsupported type {}", tensor.ggml_type);
|
||||
Ok((tensor.clone(), row * want_dims[1] as usize))
|
||||
}
|
||||
|
||||
impl GgufExpertSource {
|
||||
/// Indexes the GGUF whose first shard is `first` and maps its shards.
|
||||
pub fn open(
|
||||
first: &Path,
|
||||
device: &Device,
|
||||
layers: usize,
|
||||
experts: usize,
|
||||
n_embd: usize,
|
||||
n_ff: usize,
|
||||
tier_budget_mb: Option<u64>,
|
||||
) -> Result<Self> {
|
||||
let device = device.as_cuda_device()?.clone();
|
||||
let index = GgufIndex::open(first)?;
|
||||
let mut maps = Vec::with_capacity(index.shards.len());
|
||||
for path in &index.shards {
|
||||
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
|
||||
// SAFETY: model files are not modified while serving.
|
||||
let map =
|
||||
unsafe { Mmap::map(&file) }.with_context(|| format!("map {}", path.display()))?;
|
||||
map.advise(Advice::Random).context("advise expert map")?;
|
||||
maps.push(map);
|
||||
}
|
||||
let (e, h, f) = (experts as u64, n_embd as u64, n_ff as u64);
|
||||
let mut parsed = Vec::with_capacity(layers);
|
||||
for layer in 0..layers {
|
||||
let (gate, gate_bytes) = role(&index, layer, "gate", [h, f, e])?;
|
||||
let (up, up_bytes) = role(&index, layer, "up", [h, f, e])?;
|
||||
let (down, down_bytes) = role(&index, layer, "down", [f, h, e])?;
|
||||
ensure!(
|
||||
gate.ggml_type == up.ggml_type,
|
||||
"layer {layer}: gate and up differ in type"
|
||||
);
|
||||
let (gu_type, d_type) = (gate.ggml_type as i32, down.ggml_type as i32);
|
||||
// SAFETY: pure functions of their integer arguments.
|
||||
let (supported, blob_bytes) = unsafe {
|
||||
(
|
||||
ffi::neuron_strata_expert_supported(
|
||||
gu_type,
|
||||
d_type,
|
||||
n_embd as i64,
|
||||
n_ff as i64,
|
||||
),
|
||||
ffi::neuron_strata_expert_bytes(gu_type, d_type, n_embd as i64, n_ff as i64),
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
supported != 0,
|
||||
"layer {layer}: no kernels for types {gu_type}/{d_type}"
|
||||
);
|
||||
ensure!(
|
||||
blob_bytes == gate_bytes + up_bytes + down_bytes,
|
||||
"layer {layer}: blob is {blob_bytes} bytes, roles sum to {}",
|
||||
gate_bytes + up_bytes + down_bytes
|
||||
);
|
||||
for (tensor, bytes) in [(&gate, gate_bytes), (&up, up_bytes), (&down, down_bytes)] {
|
||||
let end = tensor.offset + (bytes * experts) as u64;
|
||||
ensure!(
|
||||
end <= maps[tensor.shard].len() as u64,
|
||||
"layer {layer}: expert tensor runs past the end of its shard"
|
||||
);
|
||||
}
|
||||
let as_role = |t: &GgufTensor, bytes| Role {
|
||||
shard: t.shard,
|
||||
offset: t.offset as usize,
|
||||
bytes,
|
||||
};
|
||||
parsed.push(Layer {
|
||||
gu_type,
|
||||
d_type,
|
||||
gate: as_role(&gate, gate_bytes),
|
||||
up: as_role(&up, up_bytes),
|
||||
down: as_role(&down, down_bytes),
|
||||
blob_bytes,
|
||||
});
|
||||
}
|
||||
let tier = tier_budget_mb.map(|mb| ExpertTier::new(mb << 20));
|
||||
let tier_pool = TierPool::new(device.cuda_stream().context().ordinal())?;
|
||||
let profile = std::env::var_os("NEURON_EXPERT_PROFILE")
|
||||
.map(|path| read_expert_profile(Path::new(&path), layers, experts))
|
||||
.transpose()?;
|
||||
tracing::info!(
|
||||
shards = maps.len(),
|
||||
layers,
|
||||
tier_budget_mb,
|
||||
"native expert kernels enabled, reading experts from GGUF"
|
||||
);
|
||||
let source = Self {
|
||||
device,
|
||||
n_embd,
|
||||
n_ff,
|
||||
maps,
|
||||
layers: parsed,
|
||||
tier,
|
||||
workspace: Mutex::new(Workspace::default()),
|
||||
tier_pool,
|
||||
};
|
||||
if let Some(ranked) = profile {
|
||||
let started = std::time::Instant::now();
|
||||
let filled = source.warm_tier(&ranked)?;
|
||||
tracing::info!(
|
||||
filled,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"VRAM expert tier filled from profile"
|
||||
);
|
||||
}
|
||||
Ok(source)
|
||||
}
|
||||
|
||||
fn copy_blob(&self, layer: &Layer, expert: usize, dst: &mut [u8]) {
|
||||
let (gate, rest) = dst.split_at_mut(layer.gate.bytes);
|
||||
let (up, down) = rest.split_at_mut(layer.up.bytes);
|
||||
for (out, role) in [(gate, layer.gate), (up, layer.up), (down, layer.down)] {
|
||||
let start = role.offset + expert * role.bytes;
|
||||
out.copy_from_slice(&self.maps[role.shard][start..start + role.bytes]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues blob copies on the stream.
|
||||
///
|
||||
/// The last batch's staging memory stays in use until the caller
|
||||
/// synchronizes. Neighbouring arena blobs are copied as one; slots
|
||||
/// are separate allocations even when their addresses adjoin, and a
|
||||
/// copy may not span two allocations.
|
||||
fn stage_blobs(
|
||||
&self,
|
||||
staging: &mut Option<PinnedBuffer>,
|
||||
layer: &Layer,
|
||||
items: &[Upload],
|
||||
) -> candle_core::Result<()> {
|
||||
if items.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if staging.is_none() {
|
||||
*staging = Some(PinnedBuffer::new(STAGING_BYTES)?);
|
||||
}
|
||||
let pinned = staging.as_ref().expect("allocated above");
|
||||
let stream = self.device.cuda_stream();
|
||||
let per_batch = pinned.len / layer.blob_bytes;
|
||||
for (b, batch) in items.chunks(per_batch).enumerate() {
|
||||
if b > 0 {
|
||||
stream.synchronize().map_err(candle_err)?;
|
||||
}
|
||||
// SAFETY: the stream has passed any earlier use of this
|
||||
// range, and the lock gives this call the only reference.
|
||||
let host = unsafe {
|
||||
std::slice::from_raw_parts_mut(pinned.ptr, batch.len() * layer.blob_bytes)
|
||||
};
|
||||
host.par_chunks_mut(layer.blob_bytes)
|
||||
.zip(batch.par_iter())
|
||||
.for_each(|(dst, item)| self.copy_blob(layer, item.expert, dst));
|
||||
let mut i = 0;
|
||||
while i < batch.len() {
|
||||
let mut run = 1;
|
||||
while batch[i].in_arena
|
||||
&& i + run < batch.len()
|
||||
&& batch[i + run].in_arena
|
||||
&& batch[i + run].address == batch[i].address + (run * layer.blob_bytes) as u64
|
||||
{
|
||||
run += 1;
|
||||
}
|
||||
// SAFETY: both ranges are live for `run` blobs, and the
|
||||
// staging range is not rewritten before a synchronize.
|
||||
let status = unsafe {
|
||||
ffi::neuron_strata_copy_to_device(
|
||||
batch[i].address as *mut c_void,
|
||||
host.as_ptr().add(i * layer.blob_bytes).cast(),
|
||||
run * layer.blob_bytes,
|
||||
stream.cu_stream() as *mut c_void,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
candle_core::bail!("expert upload failed with CUDA status {status}");
|
||||
}
|
||||
i += run;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fills the tier with the profile's hottest experts, so the first
|
||||
/// requests do not pay for its warm-up.
|
||||
fn warm_tier(&self, ranked: &[(u16, u16)]) -> candle_core::Result<usize> {
|
||||
let Some(tier) = &self.tier else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut workspace = self.workspace.lock().map_err(candle_err)?;
|
||||
let capacity = tier.capacity_bytes();
|
||||
let mut used = 0_u64;
|
||||
let mut by_layer: Vec<Vec<Upload>> = vec![Vec::new(); self.layers.len()];
|
||||
let mut filled = 0;
|
||||
for &(l, e) in ranked {
|
||||
let (l, e) = (l as usize, e as usize);
|
||||
let bytes = self.layers[l].blob_bytes as u64;
|
||||
if used + bytes > capacity {
|
||||
break;
|
||||
}
|
||||
used += bytes;
|
||||
let pending = &mut by_layer[l];
|
||||
tier.get_or_load(l as u32, e as u32, bytes, || -> candle_core::Result<_> {
|
||||
// Filled by `stage_blobs` before first use.
|
||||
let blob = self.tier_pool.alloc(&self.device, bytes as usize)?;
|
||||
pending.push(Upload {
|
||||
expert: e,
|
||||
address: device_address(&blob),
|
||||
in_arena: false,
|
||||
});
|
||||
Ok(ExpertSlot { blob })
|
||||
})?;
|
||||
filled += 1;
|
||||
}
|
||||
for (l, pending) in by_layer.iter().enumerate() {
|
||||
self.stage_blobs(&mut workspace.staging, &self.layers[l], pending)?;
|
||||
self.device
|
||||
.cuda_stream()
|
||||
.synchronize()
|
||||
.map_err(candle_err)?;
|
||||
}
|
||||
Ok(filled)
|
||||
}
|
||||
|
||||
fn forward_layer(
|
||||
&self,
|
||||
layer_index: usize,
|
||||
xs: &Tensor,
|
||||
tokens_for: &[Vec<u32>],
|
||||
weights_for: &[Vec<f32>],
|
||||
k: usize,
|
||||
) -> candle_core::Result<Tensor> {
|
||||
let started = std::time::Instant::now();
|
||||
let layer = &self.layers[layer_index];
|
||||
let (rows, hidden) = xs.dims2()?;
|
||||
if hidden != self.n_embd {
|
||||
candle_core::bail!(
|
||||
"activations are {hidden} wide, experts take {}",
|
||||
self.n_embd
|
||||
);
|
||||
}
|
||||
let entries = rows * k;
|
||||
let active: Vec<usize> = (0..tokens_for.len())
|
||||
.filter(|&e| !tokens_for[e].is_empty())
|
||||
.collect();
|
||||
let admit = rows <= TIER_ADMIT_MAX_ROWS;
|
||||
|
||||
let mut workspace = self.workspace.lock().map_err(candle_err)?;
|
||||
let ws = &mut *workspace;
|
||||
|
||||
// Resolve every active expert to a device address.
|
||||
let mut held = Vec::with_capacity(active.len());
|
||||
let mut addresses = vec![0_u64; active.len()];
|
||||
let mut misses = Vec::new();
|
||||
let mut uploads: Vec<Upload> = Vec::new();
|
||||
for (g, &e) in active.iter().enumerate() {
|
||||
let slot = match &self.tier {
|
||||
Some(tier) if admit => Some(tier.get_or_load(
|
||||
layer_index as u32,
|
||||
e as u32,
|
||||
layer.blob_bytes as u64,
|
||||
|| -> candle_core::Result<_> {
|
||||
// Filled by `stage_blobs` before the launch.
|
||||
let blob = self.tier_pool.alloc(&self.device, layer.blob_bytes)?;
|
||||
uploads.push(Upload {
|
||||
expert: e,
|
||||
address: device_address(&blob),
|
||||
in_arena: false,
|
||||
});
|
||||
Ok(ExpertSlot { blob })
|
||||
},
|
||||
)?),
|
||||
Some(tier) => tier.peek(layer_index as u32, e as u32),
|
||||
None => None,
|
||||
};
|
||||
match slot {
|
||||
Some(slot) => {
|
||||
addresses[g] = device_address(&slot.blob);
|
||||
held.push(slot);
|
||||
}
|
||||
None => misses.push((g, e)),
|
||||
}
|
||||
}
|
||||
let resolved = started.elapsed();
|
||||
if !misses.is_empty() {
|
||||
ensure_capacity(&self.device, &mut ws.arena, misses.len() * layer.blob_bytes)?;
|
||||
let arena_address = device_address(ws.arena.as_ref().expect("allocated above"));
|
||||
for (i, &(g, e)) in misses.iter().enumerate() {
|
||||
let address = arena_address + (i * layer.blob_bytes) as u64;
|
||||
addresses[g] = address;
|
||||
uploads.push(Upload {
|
||||
expert: e,
|
||||
address,
|
||||
in_arena: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.stage_blobs(&mut ws.staging, layer, &uploads)?;
|
||||
let streamed = started.elapsed();
|
||||
|
||||
// Each token writes its k outputs side by side, so the mix below
|
||||
// is one multiply and one sum rather than a scatter.
|
||||
let mut grp_start = Vec::with_capacity(active.len() + 1);
|
||||
let mut ent_dst = Vec::with_capacity(entries);
|
||||
let mut ent_tok = Vec::with_capacity(entries);
|
||||
let mut weights = vec![0_f32; entries];
|
||||
let mut rank = vec![0_usize; rows];
|
||||
for &e in &active {
|
||||
grp_start.push(ent_dst.len() as i32);
|
||||
for (&token, &weight) in tokens_for[e].iter().zip(&weights_for[e]) {
|
||||
let token = token as usize;
|
||||
let dst = token * k + rank[token];
|
||||
rank[token] += 1;
|
||||
ent_dst.push(dst as i32);
|
||||
ent_tok.push(token as i32);
|
||||
weights[dst] = weight;
|
||||
}
|
||||
}
|
||||
grp_start.push(ent_dst.len() as i32);
|
||||
if ent_dst.len() != entries || rank.iter().any(|&r| r != k) {
|
||||
candle_core::bail!("routing did not give every token {k} experts");
|
||||
}
|
||||
|
||||
let grp_ptr = upload(&self.device, &mut ws.grp_ptr, &addresses)?;
|
||||
let grp_start_ptr = upload(&self.device, &mut ws.grp_start, &grp_start)?;
|
||||
let n_groups = upload(&self.device, &mut ws.n_groups, &[active.len() as i32])?;
|
||||
let ent_dst_ptr = upload(&self.device, &mut ws.ent_dst, &ent_dst)?;
|
||||
let ent_tok_ptr = upload(&self.device, &mut ws.ent_tok, &ent_tok)?;
|
||||
ensure_capacity(
|
||||
&self.device,
|
||||
&mut ws.q8,
|
||||
rows * (hidden / Q8_1_BLOCK_VALUES) * Q8_1_BLOCK_BYTES,
|
||||
)?;
|
||||
// SAFETY: a pure function of its integer arguments.
|
||||
let scratch_bytes =
|
||||
unsafe { ffi::neuron_strata_expert_scratch_bytes(entries as i64, self.n_ff as i64) };
|
||||
ensure_capacity(&self.device, &mut ws.scratch, scratch_bytes)?;
|
||||
|
||||
let prepared = started.elapsed();
|
||||
let x = xs.to_dtype(DType::F32)?.contiguous()?;
|
||||
let (storage, x_layout) = x.storage_and_layout();
|
||||
let Storage::Cuda(storage) = &*storage else {
|
||||
candle_core::bail!("native experts need activations on the GPU");
|
||||
};
|
||||
let x_slice = storage.as_cuda_slice::<f32>()?;
|
||||
let x_ptr = x_slice
|
||||
.slice(x_layout.start_offset()..)
|
||||
.device_ptr(x_slice.stream())
|
||||
.0 as *const f32;
|
||||
|
||||
// SAFETY: the kernel writes `entries * hidden` values.
|
||||
let out = unsafe { self.device.alloc::<f32>(entries * hidden)? };
|
||||
let stream = self.device.cuda_stream().cu_stream() as *mut c_void;
|
||||
// SAFETY: every pointer is a live device allocation sized above
|
||||
// and owned for the call. `held` keeps tier slots alive until
|
||||
// the synchronize below, including any evicted while resolving.
|
||||
unsafe {
|
||||
let q8 = device_address(ws.q8.as_ref().expect("allocated")) as *mut c_void;
|
||||
ffi::neuron_strata_quantize_q8_1(x_ptr, rows as i64, hidden as i64, q8, stream);
|
||||
ffi::neuron_strata_expert_grouped(
|
||||
layer.gu_type,
|
||||
layer.d_type,
|
||||
self.n_embd as i64,
|
||||
self.n_ff as i64,
|
||||
grp_ptr as *const u64,
|
||||
grp_start_ptr as *const i32,
|
||||
n_groups as *const i32,
|
||||
ent_dst_ptr as *const i32,
|
||||
ent_tok_ptr as *const i32,
|
||||
active.len() as i64,
|
||||
entries as i64,
|
||||
q8 as *const c_void,
|
||||
device_address(ws.scratch.as_ref().expect("allocated")) as *mut c_void,
|
||||
device_address(&out) as *mut f32,
|
||||
stream,
|
||||
);
|
||||
}
|
||||
self.device
|
||||
.cuda_stream()
|
||||
.synchronize()
|
||||
.map_err(candle_err)?;
|
||||
drop(held);
|
||||
if timing_enabled() {
|
||||
let finished = started.elapsed();
|
||||
tracing::info!(
|
||||
layer = layer_index,
|
||||
rows,
|
||||
active = active.len(),
|
||||
misses = misses.len(),
|
||||
resolve_us = resolved.as_micros() as u64,
|
||||
arena_us = (streamed - resolved).as_micros() as u64,
|
||||
arrays_us = (prepared - streamed).as_micros() as u64,
|
||||
kernel_us = (finished - prepared).as_micros() as u64,
|
||||
"native experts"
|
||||
);
|
||||
}
|
||||
|
||||
let out = Tensor::from((
|
||||
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
|
||||
(rows, k, hidden),
|
||||
));
|
||||
let weights = Tensor::from_vec(weights, (rows, k, 1), xs.device())?;
|
||||
out.broadcast_mul(&weights)?.sum(1)
|
||||
}
|
||||
}
|
||||
|
||||
struct NativeBlock {
|
||||
source: Arc<GgufExpertSource>,
|
||||
layer: usize,
|
||||
}
|
||||
|
||||
impl ExternalExperts for NativeBlock {
|
||||
fn forward(
|
||||
&self,
|
||||
xs: &Tensor,
|
||||
tokens_for: &[Vec<u32>],
|
||||
weights_for: &[Vec<f32>],
|
||||
k: usize,
|
||||
) -> candle_core::Result<Tensor> {
|
||||
self.source
|
||||
.forward_layer(self.layer, xs, tokens_for, weights_for, k)
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands each MoE block its view of one [`GgufExpertSource`].
|
||||
pub struct NativeExpertFactory(pub Arc<GgufExpertSource>);
|
||||
|
||||
impl ExternalExpertSource for NativeExpertFactory {
|
||||
fn block(&self, layer: usize) -> Result<Box<dyn ExternalExperts>> {
|
||||
ensure!(
|
||||
layer < self.0.layers.len(),
|
||||
"no GGUF experts for layer {layer}"
|
||||
);
|
||||
Ok(Box::new(NativeBlock {
|
||||
source: self.0.clone(),
|
||||
layer,
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -3067,6 +3067,9 @@ impl CandleHarness {
|
||||
// choice here.
|
||||
experts_onto: &device_for_load,
|
||||
experts_vb: None,
|
||||
expert_tier: None,
|
||||
external_experts: None,
|
||||
dense: None,
|
||||
},
|
||||
)
|
||||
.context("build qwen4_exp model")?;
|
||||
@@ -4489,8 +4492,18 @@ impl Harness for CandleHarness {
|
||||
// Publish the KV budget while nothing is in flight (#257) —
|
||||
// the only moment a free-VRAM reading is not already net of
|
||||
// some running sequence's reservations.
|
||||
// The expert tier fills after this reading, so what it may
|
||||
// come to hold is not available to KV.
|
||||
let tier_reserved_mb = if matches!(
|
||||
spec.expert_residency,
|
||||
Some(cortex_core::harness::ExpertResidency::Host)
|
||||
) {
|
||||
super::arch::qwen3_5::expert_tier::configured_budget_mb().unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let budget = kv_budget_mb(
|
||||
free_mb,
|
||||
free_mb.saturating_sub(tier_reserved_mb),
|
||||
&self.context_limit_cfg,
|
||||
prefix_cache_reserved_mb(&self.prefix_cache_cfg),
|
||||
);
|
||||
@@ -4498,6 +4511,7 @@ impl Harness for CandleHarness {
|
||||
tracing::info!(
|
||||
model = %spec.model_id,
|
||||
free_at_load_mb = free_mb,
|
||||
tier_reserved_mb,
|
||||
kv_budget_mb = budget,
|
||||
"admission: KV budget published"
|
||||
);
|
||||
|
||||
@@ -319,6 +319,10 @@ pub(crate) fn run(device_index: u32, rx: Receiver<Job>, poisoned: Arc<AtomicBool
|
||||
reply,
|
||||
} => {
|
||||
let result = forward_logits(&mut state, handle, &tokens, offset);
|
||||
trace_device_pool(&state, "forward", tokens.len());
|
||||
if crate::harness::arch::qwen3_5::moe::prompt_chunk_streams_experts(tokens.len()) {
|
||||
trim_device_pool(&state);
|
||||
}
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
Job::AssembleKvBatch {
|
||||
@@ -892,6 +896,14 @@ pub(crate) fn run(device_index: u32, rx: Receiver<Job>, poisoned: Arc<AtomicBool
|
||||
// semantics in mod.rs for the Phase 3+ refinement.
|
||||
}
|
||||
|
||||
/// `NEURON_CUDA_EVENT_TRACKING=0` turns cudarc's cross-stream event
|
||||
/// tracking off for the worker's context. On by default until measured
|
||||
/// across the fleet's models.
|
||||
#[cfg(feature = "cuda")]
|
||||
fn cuda_event_tracking() -> bool {
|
||||
std::env::var("NEURON_CUDA_EVENT_TRACKING").map_or(true, |v| v != "0")
|
||||
}
|
||||
|
||||
fn init_state(device_index: u32) -> DeviceWorkerState {
|
||||
#[cfg(feature = "cuda")]
|
||||
{
|
||||
@@ -901,6 +913,23 @@ fn init_state(device_index: u32) -> DeviceWorkerState {
|
||||
// CudaContext::new and Device::new_cuda end up sharing state.
|
||||
let (device, ctx) = match candle_core::Device::new_cuda(device_index as usize) {
|
||||
Ok(device) => match CudaContext::new(device_index as usize) {
|
||||
Ok(ctx) if !cuda_event_tracking() => {
|
||||
// cudarc gives every allocation two events and waits
|
||||
// on them when it is freed, which only matters when
|
||||
// a buffer crosses streams. All of this worker's
|
||||
// work runs on candle's one stream, and the events
|
||||
// cost ~74k driver calls per qwen4_exp decode token.
|
||||
if let Ok(cuda) = device.as_cuda_device() {
|
||||
// SAFETY: nothing has been allocated yet, and
|
||||
// this context's work is on a single stream.
|
||||
unsafe { cuda.disable_event_tracking() };
|
||||
tracing::info!(device_index, "CUDA event tracking off");
|
||||
}
|
||||
if let Err(e) = ctx.bind_to_thread() {
|
||||
tracing::warn!(device_index, error = ?e, "device worker: bind_to_thread failed");
|
||||
}
|
||||
(device, Some(ctx))
|
||||
}
|
||||
Ok(ctx) => {
|
||||
if let Err(e) = ctx.bind_to_thread() {
|
||||
tracing::warn!(
|
||||
@@ -1063,6 +1092,63 @@ fn trim_device_pool(state: &DeviceWorkerState) {
|
||||
);
|
||||
}
|
||||
|
||||
/// Logs the device pool after a job when `NEURON_VRAM_TRACE` is set:
|
||||
/// bytes live now, the job's peak, and bytes the pool holds from the
|
||||
/// driver. The peak counter is reset, so each line covers one job.
|
||||
/// Memory the driver reports used beyond `reserved` was allocated
|
||||
/// outside the pool (context, library workspaces, synchronous allocs).
|
||||
#[cfg(feature = "cuda")]
|
||||
fn trace_device_pool(state: &DeviceWorkerState, job: &str, tokens: usize) {
|
||||
use candle_core::cuda::cudarc::driver::{
|
||||
result::{device, mem_pool},
|
||||
sys::CUmemPool_attribute,
|
||||
};
|
||||
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if !*ENABLED.get_or_init(|| std::env::var_os("NEURON_VRAM_TRACE").is_some()) {
|
||||
return;
|
||||
}
|
||||
let Some(ctx) = state.ctx.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let Ok(pool) = (unsafe { device::get_default_mem_pool(ctx.cu_device()) }) else {
|
||||
return;
|
||||
};
|
||||
let read = |attr: CUmemPool_attribute| -> u64 {
|
||||
let mut value = 0_u64;
|
||||
// SAFETY: these attributes are all cuuint64_t.
|
||||
match unsafe { mem_pool::get_attribute(pool, attr, (&raw mut value).cast()) } {
|
||||
Ok(()) => value >> 20,
|
||||
Err(_) => 0,
|
||||
}
|
||||
};
|
||||
let used = read(CUmemPool_attribute::CU_MEMPOOL_ATTR_USED_MEM_CURRENT);
|
||||
let peak = read(CUmemPool_attribute::CU_MEMPOOL_ATTR_USED_MEM_HIGH);
|
||||
let reserved = read(CUmemPool_attribute::CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT);
|
||||
let mut zero = 0_u64;
|
||||
// SAFETY: writing zero resets the high-water mark.
|
||||
let _ = unsafe {
|
||||
mem_pool::set_attribute(
|
||||
pool,
|
||||
CUmemPool_attribute::CU_MEMPOOL_ATTR_USED_MEM_HIGH,
|
||||
(&raw mut zero).cast(),
|
||||
)
|
||||
};
|
||||
let (free, total) = query_vram(state).unwrap_or((0, 0));
|
||||
tracing::info!(
|
||||
device_index = state.device_index,
|
||||
job,
|
||||
tokens,
|
||||
pool_used_mb = used,
|
||||
pool_peak_mb = peak,
|
||||
pool_reserved_mb = reserved,
|
||||
device_used_mb = total.saturating_sub(free),
|
||||
"vram trace"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "cuda"))]
|
||||
fn trace_device_pool(_state: &DeviceWorkerState, _job: &str, _tokens: usize) {}
|
||||
|
||||
#[cfg(not(feature = "cuda"))]
|
||||
fn trim_device_pool(_state: &DeviceWorkerState) {}
|
||||
|
||||
@@ -1348,6 +1434,19 @@ fn load_dense_inner(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A byte budget, because what else the card must hold (KV,
|
||||
// activations) is the operator's trade to make.
|
||||
let tier_budget = crate::harness::arch::qwen3_5::expert_tier::configured_budget_mb()
|
||||
.filter(|_| experts_on_host);
|
||||
let external_experts =
|
||||
native_expert_source(&cfg, device, experts_on_host, tier_budget)?;
|
||||
let dense = native_dense_source(&cfg, device, external_experts.is_some())?;
|
||||
let expert_tier = tier_budget
|
||||
.filter(|_| external_experts.is_none())
|
||||
.map(|mb| {
|
||||
tracing::info!(budget_mb = mb, "VRAM expert tier enabled (#318)");
|
||||
crate::harness::arch::qwen3_5::moe::DeviceExpertTier::new(mb << 20)
|
||||
});
|
||||
let model = crate::harness::arch::qwen4_exp::model::Qwen4ExpForCausalLM::load(
|
||||
&cfg,
|
||||
dtype,
|
||||
@@ -1358,6 +1457,9 @@ fn load_dense_inner(
|
||||
safetensors_paths,
|
||||
isq_cache,
|
||||
experts_vb: host_vb.as_ref(),
|
||||
expert_tier,
|
||||
external_experts,
|
||||
dense,
|
||||
// Host residency (#318) is what makes a model whose
|
||||
// experts exceed VRAM loadable; everything else in
|
||||
// the model still lands on the device.
|
||||
@@ -1379,6 +1481,83 @@ fn load_dense_inner(
|
||||
}
|
||||
}
|
||||
|
||||
/// Strata's kernels over the GGUF named by `NEURON_STRATA_EXPERT_GGUF`.
|
||||
#[cfg(feature = "strata-kernels")]
|
||||
fn native_expert_source(
|
||||
cfg: &crate::harness::arch::qwen4_exp::config::Config,
|
||||
device: &candle_core::Device,
|
||||
experts_on_host: bool,
|
||||
tier_budget_mb: Option<u64>,
|
||||
) -> anyhow::Result<
|
||||
Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::moe::ExternalExpertSource>>,
|
||||
> {
|
||||
use crate::harness::arch::qwen4_exp::native_experts::{GgufExpertSource, NativeExpertFactory};
|
||||
let Some(path) = std::env::var_os("NEURON_STRATA_EXPERT_GGUF").filter(|_| experts_on_host)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let text = &cfg.text_config;
|
||||
let source = GgufExpertSource::open(
|
||||
std::path::Path::new(&path),
|
||||
device,
|
||||
text.num_hidden_layers,
|
||||
text.num_experts,
|
||||
text.hidden_size,
|
||||
text.moe_intermediate_size,
|
||||
tier_budget_mb,
|
||||
)?;
|
||||
Ok(Some(std::sync::Arc::new(NativeExpertFactory(
|
||||
std::sync::Arc::new(source),
|
||||
))))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "strata-kernels"))]
|
||||
fn native_expert_source(
|
||||
_cfg: &crate::harness::arch::qwen4_exp::config::Config,
|
||||
_device: &candle_core::Device,
|
||||
_experts_on_host: bool,
|
||||
_tier_budget_mb: Option<u64>,
|
||||
) -> anyhow::Result<
|
||||
Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::moe::ExternalExpertSource>>,
|
||||
> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The GGUF's quantized dense weights, when `NEURON_STRATA_DENSE=1`
|
||||
/// and the experts already come from that GGUF.
|
||||
#[cfg(feature = "strata-kernels")]
|
||||
fn native_dense_source(
|
||||
cfg: &crate::harness::arch::qwen4_exp::config::Config,
|
||||
device: &candle_core::Device,
|
||||
native_experts: bool,
|
||||
) -> anyhow::Result<Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::proj::LinearSource>>> {
|
||||
use crate::harness::arch::qwen4_exp::gguf_dense::{GgufDenseSource, Heads};
|
||||
let text = &cfg.text_config;
|
||||
let enabled = std::env::var("NEURON_STRATA_DENSE").is_ok_and(|v| v == "1");
|
||||
let Some(path) =
|
||||
std::env::var_os("NEURON_STRATA_EXPERT_GGUF").filter(|_| enabled && native_experts)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let heads = Heads {
|
||||
key_heads: text.linear_num_key_heads,
|
||||
value_heads: text.linear_num_value_heads,
|
||||
head_dim: text.linear_value_head_dim,
|
||||
};
|
||||
let key_dim = text.linear_num_key_heads * text.linear_key_head_dim;
|
||||
let source = GgufDenseSource::open(std::path::Path::new(&path), device, heads, key_dim)?;
|
||||
Ok(Some(std::sync::Arc::new(source)))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "strata-kernels"))]
|
||||
fn native_dense_source(
|
||||
_cfg: &crate::harness::arch::qwen4_exp::config::Config,
|
||||
_device: &candle_core::Device,
|
||||
_native_experts: bool,
|
||||
) -> anyhow::Result<Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::proj::LinearSource>>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Load the leader's TP shard on the worker thread. Reads the Comm
|
||||
/// directly from `state.nccl`; no cross-thread Arc<Comm> transfer.
|
||||
#[cfg(feature = "cuda")]
|
||||
|
||||
@@ -423,6 +423,9 @@ fn qwen4_exp_case(name: &str, max_abs_bound: f32) {
|
||||
isq_cache: None,
|
||||
experts_onto: &device,
|
||||
experts_vb: None,
|
||||
expert_tier: None,
|
||||
external_experts: None,
|
||||
dense: None,
|
||||
},
|
||||
)
|
||||
.expect("load the fixture through the production loader");
|
||||
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Niko1221 and the Strata contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
# Vendored from Strata
|
||||
|
||||
These files are an unmodified subset of [Strata](https://github.com/Niko1221/Strata)
|
||||
at commit `6a6db7ff58c283cf28d2b913404b5fa31a767eaa`, kept at their upstream paths so
|
||||
their relative includes work and so they can be diffed against upstream.
|
||||
|
||||
- Strata is MIT licensed. See `LICENSE`.
|
||||
- Its quantised-block layouts and dot products derive from llama.cpp / ggml, also MIT
|
||||
licensed. See `engine/third_party/ggml/LICENSE` and `VERSION.txt`.
|
||||
|
||||
To update, copy the same paths from a newer upstream commit and change the commit above.
|
||||
Do not edit these files in place; neuron's adapter is `crates/neuron/src/cuda/strata_adapter/strata_shim.cu`.
|
||||
@@ -0,0 +1,77 @@
|
||||
// include/strata/artifact/model_family.hpp - which model family a GGUF holds, from its general.architecture.
|
||||
//
|
||||
// Strata was written for one model (Qwen3.8-Flash-Next, `qwen4exp`). Qwen3.6-35B-A3B (`qwen35moe`) is a close
|
||||
// cousin (same tokenizer, the same Gated-DeltaNet + gated-attention 3:1 layer pattern, the same head dims), so the
|
||||
// reader, the geometry and the layout tables know both. The ENGINE runs only the families `model_family_runs`
|
||||
// names; a recognised family it does not run yet is refused with `model_family_not_supported`, not mis-run.
|
||||
//
|
||||
// No dependencies: the GGUF reader (the architecture guard) and the core geometry both include this.
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace strata {
|
||||
|
||||
enum class ModelFamily {
|
||||
Unknown = 0,
|
||||
Qwen4Exp, ///< Qwen3.8-Flash-Next and its fine-tunes / pruned variants (Swift 1.5, the Coder)
|
||||
Qwen35Moe, ///< Qwen3.6-35B-A3B (Unsloth's MTP GGUFs): plain pre-norm residual, dense attention, nextn MTP block
|
||||
Hy4Flash, ///< Tencent Hy4-Flash 220B-A12B (LatentMoE + Hybrid MLA/IndexPool + 4-Module Engram + 5L DFly2)
|
||||
Inkling2Loop, ///< Thinking Machines Inkling 2 Mini 26.4B-A3.4B/5.4B (24->48 Looped MoE + SITU + AttnRes + ShortConv + DSpark)
|
||||
};
|
||||
|
||||
inline ModelFamily model_family_from_arch(const std::string& arch) {
|
||||
if (arch == "qwen4exp") return ModelFamily::Qwen4Exp;
|
||||
if (arch == "qwen35moe") return ModelFamily::Qwen35Moe;
|
||||
if (arch == "hy_v4_flash") return ModelFamily::Hy4Flash;
|
||||
if (arch == "inkling2" || arch == "inkling2_loop" || arch == "inkling2_loop_text") return ModelFamily::Inkling2Loop;
|
||||
return ModelFamily::Unknown;
|
||||
}
|
||||
|
||||
/// The GGUF architecture string (also the metadata key prefix: "<arch>.block_count").
|
||||
inline const char* model_family_arch(ModelFamily f) {
|
||||
switch (f) {
|
||||
case ModelFamily::Qwen4Exp:
|
||||
return "qwen4exp";
|
||||
case ModelFamily::Qwen35Moe:
|
||||
return "qwen35moe";
|
||||
case ModelFamily::Hy4Flash:
|
||||
return "hy_v4_flash";
|
||||
case ModelFamily::Inkling2Loop:
|
||||
return "inkling2_loop";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/// The model's name for messages.
|
||||
inline const char* model_family_title(ModelFamily f) {
|
||||
switch (f) {
|
||||
case ModelFamily::Qwen4Exp:
|
||||
return "Qwen3.8-Flash-Next";
|
||||
case ModelFamily::Qwen35Moe:
|
||||
return "Qwen3.6-35B-A3B";
|
||||
case ModelFamily::Hy4Flash:
|
||||
return "Tencent Hy4-Flash";
|
||||
case ModelFamily::Inkling2Loop:
|
||||
return "Thinking Machines Inkling 2 Mini";
|
||||
default:
|
||||
return "an unknown model";
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Flash-Next's engine path runs the family. Qwen3.6 has an engine path of its own (src/qwen35), which the
|
||||
/// CUDA and HIP builds of `strata` switch to at the top of main(); the Intel Arc (SYCL) build has none yet, so there
|
||||
/// (and on Flash-Next's path) the family is refused with `model_family_not_supported`.
|
||||
inline bool model_family_runs(ModelFamily f) { return f == ModelFamily::Qwen4Exp; }
|
||||
|
||||
/// The refusal for a recognised family the engine does not run (empty when it runs it).
|
||||
inline std::string model_family_not_supported(ModelFamily f) {
|
||||
if (model_family_runs(f)) return {};
|
||||
if (f == ModelFamily::Unknown) return "this is not a model family Strata knows";
|
||||
return std::string(model_family_title(f)) + " (architecture '" + model_family_arch(f) +
|
||||
"') runs on the NVIDIA (CUDA) and AMD (HIP) builds of Strata; this build does not run it yet (the Intel "
|
||||
"Arc / SYCL port is in development). Use a CUDA or HIP build, or a Qwen3.8-Flash-Next model file";
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -0,0 +1,41 @@
|
||||
// include/strata/core/defaults_026.hpp - STRATA_DEFAULTS=026: the master switch of the Qwen engine's 0.2.7 defaults.
|
||||
//
|
||||
// Every default the Qwen engine (`strata`) changed since v0.2.6 goes back to what v0.2.6 did when STRATA_DEFAULTS=026 is in the
|
||||
// environment (the app's "off" for its speed switches sends it): the wide
|
||||
// hyper-connection up read (STRATA_GR_UP_WIDE), the stream-split hyper-connection read (STRATA_GR_V3), the int8 prompt attention
|
||||
// (STRATA_PROMPT_ATTN_IMMA), the four gfx12 decode switches of the arch table, the PLE residency policy (STRATA_PLE_AUTO_RAM), and the
|
||||
// gfx12 decode miss split of 0.15 (back to 0.55). KVA is off by default in 0.2.7 and stays whatever STRATA_KVA says.
|
||||
// The residency-biased routing (STRATA_ROUTE_PRIOR) was in this set in 0.2.7; it is off by default again (owner, 2026-10-29), so the master switch
|
||||
// has nothing to take back there, and route_prior_default() answers 0 with the switch on or off.
|
||||
// An explicit per-feature variable (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, STRATA_PLE_AUTO_RAM=1, ...) or flag (--pcie-frac, --ple-io)
|
||||
// still wins over the master switch. Each rule is a pure function that takes the answer of qwen_defaults_026() as its `v026`
|
||||
// argument, so a test can check both settings without touching the environment (src/core/arch_defaults_test.cpp,
|
||||
// src/core/ple_residency_test.cpp).
|
||||
#pragma once
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace strata {
|
||||
|
||||
/// "026", "0.2.6" and "v0.2.6" name version 0.2.6; anything else (unset, "", "0", "027") does not.
|
||||
inline bool is_026_token(const char* v) {
|
||||
return v != nullptr && (std::strcmp(v, "026") == 0 || std::strcmp(v, "0.2.6") == 0 || std::strcmp(v, "v0.2.6") == 0);
|
||||
}
|
||||
|
||||
/// STRATA_DEFAULTS=026 (read once).
|
||||
inline bool qwen_defaults_026() {
|
||||
static const bool on = is_026_token(std::getenv("STRATA_DEFAULTS"));
|
||||
return on;
|
||||
}
|
||||
|
||||
/// The decode miss split's start value (the share of a native pack's missing experts the CPU pool takes) when --pcie-frac is not given:
|
||||
/// NVFP4 packs 0.25, other native packs 0.55 (the x16 share), and 0.15 on gfx12 (0.2.7) unless STRATA_PCIE_FRAC_DEFAULT=old or the master
|
||||
/// switch is 026; a canonical pack 0.2.
|
||||
inline double pcie_start_frac(bool nvfp4_pack, bool native_pack, bool gfx12_default, bool pf_old, bool v026 = false) {
|
||||
if (nvfp4_pack) return 0.25;
|
||||
if (!native_pack) return 0.2;
|
||||
return gfx12_default && !pf_old && !v026 ? 0.15 : 0.55;
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -0,0 +1,154 @@
|
||||
// strata/core/dispatch_stats.hpp - aggregate dispatch counters (BW-MEASURE, P0.2 of the Blackwell plan).
|
||||
//
|
||||
// Which kernel path a run really took: the dense projection kernel by type and shape, the grouped expert path, the hyper-connection
|
||||
// format, the head, the all-resident or partial window graph, and why a fast path was declined. Counted where a path is CHOSEN:
|
||||
// * inside a graph capture (Verifier::record_window): once per recorded window, binned by the window width T and the graph kind;
|
||||
// a run's total calls = counts of that bin x how often that graph was launched (graph_launch(), one increment per launch);
|
||||
// * outside a capture (the draft head, the prompt path): every call, bin "eager".
|
||||
// Nothing is read back from the device and nothing runs inside a timed device region. A call costs one mutex and one hash lookup
|
||||
// (tens of ns, against a kernel launch of microseconds); STRATA_DISPATCH_STATS=0 turns it off.
|
||||
//
|
||||
// The report is JSON, written at exit when STRATA_DISPATCH_REPORT=<path> is set (and by the CLI's --stats to stdout as "dispatch").
|
||||
// Header only, standard C++17, no CUDA / HIP / SYCL / Metal types: every backend compiles it.
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::dispatch {
|
||||
|
||||
struct Key {
|
||||
uint16_t cat = 0, var = 0, scope = 0, t = 0, ncols = 0, pad = 0;
|
||||
uint32_t n_in = 0, n_out = 0;
|
||||
bool operator==(const Key& o) const { return std::memcmp(this, &o, sizeof(Key)) == 0; }
|
||||
};
|
||||
struct KeyHash {
|
||||
size_t operator()(const Key& k) const {
|
||||
uint64_t a, b;
|
||||
std::memcpy(&a, reinterpret_cast<const char*>(&k), 8);
|
||||
std::memcpy(&b, reinterpret_cast<const char*>(&k) + 8, 8);
|
||||
uint64_t h = a * 0x9E3779B97F4A7C15ull ^ (b + 0x7F4A7C159E3779B9ull + (a << 6) + (a >> 2));
|
||||
h ^= h >> 29;
|
||||
return (size_t) h;
|
||||
}
|
||||
};
|
||||
|
||||
enum Cat : uint16_t { kStr = 0, kDense = 1, kExpert = 2, kHc = 3, kHead = 4, kWindow = 5 };
|
||||
|
||||
class Stats {
|
||||
public:
|
||||
// leaked on purpose: the atexit report must not run after the maps are destroyed
|
||||
static Stats& get() { static Stats* s = new Stats(); return *s; }
|
||||
bool on() const { return on_; }
|
||||
|
||||
// the current thread's bin: 0 = eager, else 1 + (T * 4 + kind) of the graph being captured
|
||||
static uint16_t& scope() { thread_local uint16_t s = 0; return s; }
|
||||
|
||||
void count(const Key& k, uint64_t n = 1) {
|
||||
if (!on_) return;
|
||||
std::lock_guard<std::mutex> lk(m_);
|
||||
map_[k] += n;
|
||||
}
|
||||
// a free-text path / reason; interned once per distinct text
|
||||
void note(const char* text, uint64_t n = 1) {
|
||||
if (!on_) return;
|
||||
std::lock_guard<std::mutex> lk(m_);
|
||||
auto it = intern_.find(text);
|
||||
uint16_t id;
|
||||
if (it == intern_.end()) { id = (uint16_t) names_.size(); names_.push_back(text); intern_.emplace(text, id); }
|
||||
else id = it->second;
|
||||
Key k; k.cat = kStr; k.var = id; k.scope = scope();
|
||||
map_[k] += n;
|
||||
}
|
||||
void graph_launch(int T, int kind) { // kind: 0 all-resident graph, 1 doorbell (partial) graph, 2 other
|
||||
if (!on_) return;
|
||||
if (T < 0 || T > 63) return;
|
||||
launches_[T][kind & 3].fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
void graph_capture(int T, int kind) { note_capture_(T, kind); }
|
||||
|
||||
std::string json() {
|
||||
std::lock_guard<std::mutex> lk(m_);
|
||||
std::string o = "{\n \"launches\": {";
|
||||
bool first = true;
|
||||
for (int t = 0; t < 64; ++t)
|
||||
for (int k = 0; k < 4; ++k) {
|
||||
const uint64_t n = launches_[t][k].load();
|
||||
if (n == 0) continue;
|
||||
char b[96];
|
||||
std::snprintf(b, sizeof b, "%s\"T%d/k%d\": %llu", first ? "" : ", ", t, k, (unsigned long long) n);
|
||||
o += b; first = false;
|
||||
}
|
||||
o += "},\n \"counts\": [\n";
|
||||
first = true;
|
||||
for (const auto& kv : map_) {
|
||||
const Key& k = kv.first;
|
||||
char b[512];
|
||||
const int sc = k.scope == 0 ? -1 : (k.scope - 1) / 4, kd = k.scope == 0 ? -1 : (k.scope - 1) % 4;
|
||||
if (k.cat == kStr)
|
||||
std::snprintf(b, sizeof b, "%s {\"scope\": [%d, %d], \"cat\": \"str\", \"key\": \"%s\", \"n\": %llu}", first ? "" : ",\n",
|
||||
sc, kd, k.var < names_.size() ? names_[k.var].c_str() : "?", (unsigned long long) kv.second);
|
||||
else
|
||||
std::snprintf(b, sizeof b,
|
||||
"%s {\"scope\": [%d, %d], \"cat\": %u, \"var\": %u, \"type\": %u, \"ncols\": %u, \"n_in\": %u, \"n_out\": %u, \"n\": %llu}",
|
||||
first ? "" : ",\n", sc, kd, k.cat, k.var, k.t, k.ncols, k.n_in, k.n_out, (unsigned long long) kv.second);
|
||||
o += b; first = false;
|
||||
}
|
||||
o += "\n ]\n}\n";
|
||||
return o;
|
||||
}
|
||||
void write_report() {
|
||||
const char* p = std::getenv("STRATA_DISPATCH_REPORT");
|
||||
if (!on_ || p == nullptr || p[0] == '\0') return;
|
||||
const std::string j = json();
|
||||
if (std::FILE* f = std::fopen(p, "wb")) { std::fwrite(j.data(), 1, j.size(), f); std::fclose(f); }
|
||||
}
|
||||
|
||||
private:
|
||||
Stats() {
|
||||
const char* e = std::getenv("STRATA_DISPATCH_STATS");
|
||||
on_ = e == nullptr || e[0] != '0';
|
||||
for (auto& r : launches_) for (auto& c : r) c.store(0);
|
||||
if (on_) std::atexit([] { Stats::get().write_report(); });
|
||||
}
|
||||
void note_capture_(int T, int kind) { note(("capture T" + std::to_string(T) + "/k" + std::to_string(kind)).c_str()); }
|
||||
bool on_ = true;
|
||||
std::mutex m_;
|
||||
std::unordered_map<Key, uint64_t, KeyHash> map_;
|
||||
std::unordered_map<std::string, uint16_t> intern_;
|
||||
std::vector<std::string> names_;
|
||||
std::atomic<uint64_t> launches_[64][4];
|
||||
};
|
||||
|
||||
// RAII: while alive, this thread's counts go to the bin of a T-token graph of the given kind
|
||||
struct Scope {
|
||||
uint16_t prev;
|
||||
Scope(int T, int kind) : prev(Stats::scope()) { Stats::scope() = (uint16_t) (1 + T * 4 + (kind & 3)); }
|
||||
~Scope() { Stats::scope() = prev; }
|
||||
};
|
||||
|
||||
// a kernel-level choice: a dense projection / expert / hc / head launch with its shape
|
||||
inline void kernel(Cat cat, int variant, int type, int n_in, int n_out, int ncols) {
|
||||
Stats& s = Stats::get();
|
||||
if (!s.on()) return;
|
||||
Key k; k.cat = cat; k.var = (uint16_t) variant; k.t = (uint16_t) type; k.ncols = (uint16_t) ncols;
|
||||
k.n_in = (uint32_t) n_in; k.n_out = (uint32_t) n_out; k.scope = Stats::scope();
|
||||
s.count(k);
|
||||
}
|
||||
inline void note(const char* text) { Stats::get().note(text); }
|
||||
inline void notef(const char* fmt, long a = 0, long b = 0, long c = 0) {
|
||||
Stats& s = Stats::get();
|
||||
if (!s.on()) return;
|
||||
char buf[200];
|
||||
std::snprintf(buf, sizeof buf, fmt, a, b, c);
|
||||
s.note(buf);
|
||||
}
|
||||
|
||||
} // namespace strata::dispatch
|
||||
@@ -0,0 +1,94 @@
|
||||
// strata/core/emulate.hpp - STRATA_EMULATE_CC: another GPU generation's code paths, run on this card (tests only).
|
||||
//
|
||||
// A build whose device code is PTX for an older architecture (CMAKE_CUDA_ARCHITECTURES=86-virtual) runs on a newer
|
||||
// card through the driver's JIT, and every kernel then sees __CUDA_ARCH__ = 860. What the host decides from the
|
||||
// device must agree with that, or it picks paths and shared-memory sizes the device code was not built for:
|
||||
// STRATA_EMULATE_CC=75|80|86|89 makes each such query (compute capability, shared memory per block) answer as that
|
||||
// card would. Speed under it says nothing about the real card; results do - the kernels are the real card's.
|
||||
#pragma once
|
||||
|
||||
#include <cstdlib>
|
||||
#if defined(__linux__) && !defined(__HIPCC__) && !defined(STRATA_GPU_METAL)
|
||||
#include <dlfcn.h>
|
||||
#include <string>
|
||||
#endif
|
||||
|
||||
namespace strata {
|
||||
|
||||
/// nbald/volta-forever version string when running under the CUDA 13 Volta compatibility proxy (libcuda.so.1
|
||||
/// exports volta_forever_version()), or "" when not loaded. Cached once per process.
|
||||
inline const char* volta_forever_version() {
|
||||
#if defined(__linux__) && !defined(__HIPCC__) && !defined(STRATA_GPU_METAL)
|
||||
static const std::string ver = []() -> std::string {
|
||||
using Fn = const char* (*)();
|
||||
auto probe = [](void* handle) -> std::string {
|
||||
if (!handle) return {};
|
||||
void* sym = dlsym(handle, "volta_forever_version");
|
||||
if (!sym) return {};
|
||||
const char* s = reinterpret_cast<Fn>(sym)();
|
||||
return s ? std::string(s) : std::string();
|
||||
};
|
||||
std::string out;
|
||||
#ifdef RTLD_DEFAULT
|
||||
out = probe(RTLD_DEFAULT);
|
||||
if (!out.empty()) return out;
|
||||
#endif
|
||||
#ifdef RTLD_NOLOAD
|
||||
if (void* h = dlopen("libcuda.so.1", RTLD_LAZY | RTLD_NOLOAD)) {
|
||||
out = probe(h);
|
||||
dlclose(h);
|
||||
if (!out.empty()) return out;
|
||||
}
|
||||
#endif
|
||||
if (void* h = dlopen("libcuda.so.1", RTLD_LAZY | RTLD_LOCAL)) {
|
||||
out = probe(h);
|
||||
dlclose(h);
|
||||
if (!out.empty()) return out;
|
||||
}
|
||||
return {};
|
||||
}();
|
||||
return ver.c_str();
|
||||
#else
|
||||
return "";
|
||||
#endif
|
||||
}
|
||||
|
||||
inline bool volta_forever_active() { return volta_forever_version()[0] != '\0'; }
|
||||
|
||||
/// the emulated compute capability as 10 * major + minor, or 0 (off)
|
||||
inline int emulated_cc() {
|
||||
static const int cc = [] {
|
||||
const char* e = std::getenv("STRATA_EMULATE_CC");
|
||||
const int v = e ? std::atoi(e) : 0;
|
||||
return v >= 75 && v < 120 ? v : 0;
|
||||
}();
|
||||
return cc;
|
||||
}
|
||||
/// Effective compute capability (10 * major + minor). STRATA_EMULATE_CC wins; otherwise under
|
||||
/// nbald/volta-forever (which spoofs physical Volta 7.0 as 7.5 for CUDA 13 binaries), remap 7.5 -> 7.0.
|
||||
inline int cc_of(int real_major, int real_minor, bool vf_active) {
|
||||
if (const int e = emulated_cc()) return e;
|
||||
if (vf_active && real_major == 7 && real_minor == 5) return 70;
|
||||
return 10 * real_major + real_minor;
|
||||
}
|
||||
inline int cc_of(int real_major, int real_minor) {
|
||||
return cc_of(real_major, real_minor, volta_forever_active());
|
||||
}
|
||||
inline int cc_major_of(int real_major) { return emulated_cc() ? emulated_cc() / 10 : real_major; }
|
||||
inline int cc_minor_of(int real_minor) {
|
||||
if (const int e = emulated_cc()) return e % 10;
|
||||
if (volta_forever_active() && real_minor == 5) return 0;
|
||||
return real_minor;
|
||||
}
|
||||
/// cudaDevAttrMaxSharedMemoryPerBlockOptin as the emulated card reports it: 64 KB on Turing, 163 KB on the A100,
|
||||
/// 99 KB on the other Ampere and Ada cards
|
||||
inline int smem_optin_of(int real) {
|
||||
switch (emulated_cc()) {
|
||||
case 0: return real;
|
||||
case 75: return 65536;
|
||||
case 80: return 166912;
|
||||
default: return real < 101376 ? real : 101376;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -0,0 +1,457 @@
|
||||
// include/strata/core/expert_nibble.hpp - STRATA_EXPERT_NIBBLE=1 (opt-in, default off): the gate/up experts of
|
||||
// IQ2_S / IQ3_XXS / IQ3_S layers kept as 4-bit codes in their VRAM slots, for Pascal GP100 (sm_60).
|
||||
//
|
||||
// **WHY.** On a GP100 the decode window's gate/up expert kernels are not held by memory bandwidth: they use a small
|
||||
// part of it and wait on each block's serial chain (the weights, the codebook lookups, the emulated dp4a, the
|
||||
// reduction). Re-encoding each 32-weight item of these three formats as sixteen bytes of 4-bit codes (one aligned
|
||||
// 16-byte load) and keeping the integer scale and the fp16 d as they are makes the slot 1.25-1.68x the GGUF bytes and
|
||||
// the decode of four weights 1-4 integer instructions instead of two codebook lookups.
|
||||
//
|
||||
// **WHY IT IS LOSSLESS.** Their grids have only 3 (IQ2_S) or 8 (IQ3_XXS, IQ3_S) magnitudes, so each int8 weight the
|
||||
// production `Split<TG>::load` decodes is one of at most 16 signed values. At every start the transcoder decodes every
|
||||
// item of every converted slot with the production load, encodes it, decodes the written code again and compares; and
|
||||
// the GGUF blocks are rebuilt from every slot and compared with the blob byte for byte (`check_gguf`). The decode
|
||||
// kernels run the production integer chain and float tail in the production order: every gate / up value is the
|
||||
// production kernel's, bit for bit. The prompt path's MMQ reads the GGUF blocks rebuilt from the slot (`gather_gguf`,
|
||||
// in place of the copy it does today): the same bytes, so the same bits.
|
||||
//
|
||||
// **OFF IS TODAY.** Unset or 0: no layer is converted, `slot_bytes(l)` is `expert_layout().blob_bytes(l)`, nothing is
|
||||
// transcoded, sealed or hashed, and none of the new branches is entered. Only a CUDA build with
|
||||
// STRATA_EXPERIMENTAL_SM60 has the kernels (STRATA_EXPERT_NIBBLE_BUILT); every other build refuses the switch at start.
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/cpu/expert_layout.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#if defined(STRATA_EXPERIMENTAL_SM60) && !defined(__HIPCC__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \
|
||||
!defined(STRATA_GPU_METAL)
|
||||
#define STRATA_EXPERT_NIBBLE_BUILT 1
|
||||
#else
|
||||
#define STRATA_EXPERT_NIBBLE_BUILT 0
|
||||
#endif
|
||||
|
||||
#if defined(__CUDACC__) || defined(__HIPCC__)
|
||||
#define STRATA_NIB_HD __host__ __device__
|
||||
#else
|
||||
#define STRATA_NIB_HD
|
||||
#endif
|
||||
|
||||
namespace strata::core::nibble {
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ the slot layout
|
||||
//
|
||||
// A converted layer's expert slot, in order (the host arena and the pack keep the GGUF blocks):
|
||||
//
|
||||
// codes kRows x kItems x 16 B row r, item k at (r * kItems + k) * 16; rows 0..kNFf-1 gate, kNFf..kRows-1 up
|
||||
// scales kRows x kItems x 1 B row r, item k at kScOff + r * kItems + k (the production scale step's input)
|
||||
// d kRows x kSuper x 2 B row r, superblock s at kDOff + (r * kSuper + s) * 2: the block's fp16 d, bit for bit
|
||||
// ------ kGuBytes = 1,766,400 B (6900 x 256: the down part starts 256-aligned)
|
||||
// down the GGUF down rows, copied verbatim from the raw blob's [down_off, bytes)
|
||||
// ------ slot_bytes = round_up(kGuBytes + down bytes, kSlotAlign)
|
||||
//
|
||||
// One item = 32 weights of a row, one 16-byte code (four 32-bit words, see `encode_item`). Only the expert shape
|
||||
// n_embd 2560, n_ff 640 is converted: every other layer keeps its GGUF blob and its kernels.
|
||||
|
||||
inline constexpr int64_t kNEmbd = 2560; ///< the gate/up rows' width (the activation)
|
||||
inline constexpr int64_t kNFf = 640; ///< gate rows = up rows = n_ff
|
||||
inline constexpr int64_t kRows = 2 * kNFf; ///< 1280: gate, then up
|
||||
inline constexpr int64_t kItems = kNEmbd / 32; ///< 80 items of 32 weights per row
|
||||
inline constexpr int64_t kSuper = kNEmbd / 256; ///< 10 superblocks (one fp16 d each) per row
|
||||
inline constexpr uint64_t kItemBytes = 16; ///< one item's code: four words, one 16-byte load
|
||||
|
||||
inline constexpr uint64_t kCodesOff = 0;
|
||||
inline constexpr uint64_t kUpCodesOff = (uint64_t) kNFf * kItems * kItemBytes; ///< 819,200: row kNFf
|
||||
inline constexpr uint64_t kScOff = (uint64_t) kRows * kItems * kItemBytes; ///< 1,638,400
|
||||
inline constexpr uint64_t kDOff = kScOff + (uint64_t) kRows * kItems; ///< 1,740,800
|
||||
inline constexpr uint64_t kGuBytes = kDOff + (uint64_t) kRows * kSuper * 2; ///< 1,766,400
|
||||
inline constexpr uint64_t kDownOff = kGuBytes; ///< the down rows
|
||||
inline constexpr uint64_t kSlotAlign = 256; ///< every slot's size
|
||||
|
||||
static_assert(kGuBytes == 1766400, "the slot layout above");
|
||||
static_assert(kGuBytes % kSlotAlign == 0, "the down part starts 256-aligned");
|
||||
static_assert(kScOff % 16 == 0 && kDOff % 16 == 0, "each region starts 16-aligned");
|
||||
|
||||
/// Byte offset of row `row` (0..kRows-1; up rows are kNFf + r) item `k`'s code inside the slot.
|
||||
STRATA_NIB_HD constexpr uint64_t code_off(int64_t row, int64_t k) {
|
||||
return kCodesOff + ((uint64_t) row * kItems + (uint64_t) k) * kItemBytes;
|
||||
}
|
||||
/// Byte offset of row `row` item `k`'s scale byte.
|
||||
STRATA_NIB_HD constexpr uint64_t scale_off(int64_t row, int64_t k) { return kScOff + (uint64_t) row * kItems + (uint64_t) k; }
|
||||
/// Byte offset of row `row` superblock `s`'s fp16 d (s = k / 8 for item k).
|
||||
STRATA_NIB_HD constexpr uint64_t d_off(int64_t row, int64_t s) { return kDOff + ((uint64_t) row * kSuper + (uint64_t) s) * 2; }
|
||||
/// A converted slot's size for a raw blob whose down rows are `down_bytes` long.
|
||||
STRATA_NIB_HD constexpr uint64_t slot_bytes_for(uint64_t down_bytes) {
|
||||
return (kGuBytes + down_bytes + kSlotAlign - 1) / kSlotAlign * kSlotAlign;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ the formats
|
||||
|
||||
inline constexpr int kIQ3_XXS = 18;
|
||||
inline constexpr int kIQ3_S = 21;
|
||||
inline constexpr int kIQ2_S = 22;
|
||||
|
||||
/// Whether `gu_type` is converted (the three formats whose weights take at most 16 values).
|
||||
STRATA_NIB_HD constexpr bool fmt_built(int gu_type) { return gu_type == kIQ2_S || gu_type == kIQ3_XXS || gu_type == kIQ3_S; }
|
||||
/// The GGUF gate/up row bytes of `gu_type` at kNEmbd (a converted layer's raw blob must agree; 0 = not a format here).
|
||||
STRATA_NIB_HD constexpr uint64_t raw_gu_row(int gu_type) {
|
||||
return gu_type == kIQ2_S ? 820 : gu_type == kIQ3_XXS ? 980 : gu_type == kIQ3_S ? 1100 : 0;
|
||||
}
|
||||
inline const char* fmt_name(int gu_type) {
|
||||
switch (gu_type) {
|
||||
case kIQ3_XXS: return "IQ3_XXS";
|
||||
case kIQ3_S: return "IQ3_S";
|
||||
case kIQ2_S: return "IQ2_S";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ the item code
|
||||
//
|
||||
// `g[32]` below is one item as the production `Split<TG>::load` leaves it: g[4 * j + b] is byte b of W.g[j]
|
||||
// (j = 0..7, the dp4a order against the q8_1 block's qs words). Word m (0..3) of the 16-byte code holds W.g[2m]
|
||||
// and W.g[2m + 1]:
|
||||
//
|
||||
// IQ2_S bits 4b..4b+3 = c(g[8m + b]), bits 16+4b.. = c(g[8m + 4 + b]), b = 0..3
|
||||
// c = magnitude index of {8, 25, 43} | sign << 2: the PRMT selector into {8,25,43,0} {-8,-25,-43,0}
|
||||
// IQ3_XXS same nibble positions; c = index of {4, 12, 20, 28, 36, 44, 52, 62} | sign << 3
|
||||
// IQ3_S byte b = u(g[8m + b]) | u(g[8m + 4 + b]) << 4, u = (v + 15) / 2 (v odd, -15..15); v = 2u - 15
|
||||
//
|
||||
// The scale byte keeps the production integer scale step's input:
|
||||
// IQ2_S the block's scales byte for the item: ls0 | ls1 << 4 (W.ls0, W.ls1)
|
||||
// IQ3_XXS aux32 >> 28 (0..15, W.ls)
|
||||
// IQ3_S 1 + 2 * nibble (1..31, W.ls)
|
||||
|
||||
/// Encodes one item; false when a weight is outside the format's code set (the conversion then refuses to start).
|
||||
inline bool encode_item(int gu_type, const int8_t g[32], uint32_t q[4]) {
|
||||
bool ok = true;
|
||||
auto code = [&](int8_t v) -> uint32_t {
|
||||
const int a = v < 0 ? -(int) v : (int) v;
|
||||
if (gu_type == kIQ3_S) {
|
||||
if ((v & 1) == 0 || v < -15 || v > 15) { ok = false; return 0; }
|
||||
return (uint32_t) (((int) v + 15) / 2);
|
||||
}
|
||||
if (gu_type == kIQ3_XXS) {
|
||||
static constexpr int mag[8] = { 4, 12, 20, 28, 36, 44, 52, 62 };
|
||||
for (uint32_t i = 0; i < 8; ++i)
|
||||
if (a == mag[i]) return i | (v < 0 ? 8u : 0u);
|
||||
ok = false;
|
||||
return 0;
|
||||
}
|
||||
const uint32_t m = a == 8 ? 0u : a == 25 ? 1u : a == 43 ? 2u : 3u; // IQ2_S
|
||||
if (m == 3u) { ok = false; return 0; }
|
||||
return m | (v < 0 ? 4u : 0u);
|
||||
};
|
||||
for (int m = 0; m < 4; ++m) {
|
||||
uint32_t w = 0;
|
||||
for (int b = 0; b < 4; ++b) {
|
||||
const uint32_t c0 = code(g[8 * m + b]), c1 = code(g[8 * m + 4 + b]);
|
||||
if (gu_type == kIQ3_S) w |= (c0 | c1 << 4) << (8 * b);
|
||||
else w |= c0 << (4 * b) | c1 << (16 + 4 * b);
|
||||
}
|
||||
q[m] = w;
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// Decodes one item's code back to the production W.g bytes (the host reference the parity program compares with;
|
||||
/// the device decoders give the same bytes). Codes outside the set decode as the PRMT does: IQ2_S index 3 -> 0.
|
||||
inline void decode_item(int gu_type, const uint32_t q[4], int8_t g[32]) {
|
||||
static constexpr int8_t iq2[8] = { 8, 25, 43, 0, -8, -25, -43, 0 };
|
||||
static constexpr int8_t iq3[8] = { 4, 12, 20, 28, 36, 44, 52, 62 };
|
||||
for (int m = 0; m < 4; ++m)
|
||||
for (int b = 0; b < 4; ++b) {
|
||||
uint32_t c0, c1;
|
||||
if (gu_type == kIQ3_S) {
|
||||
c0 = q[m] >> (8 * b) & 15u;
|
||||
c1 = q[m] >> (8 * b + 4) & 15u;
|
||||
} else {
|
||||
c0 = q[m] >> (4 * b) & 15u;
|
||||
c1 = q[m] >> (16 + 4 * b) & 15u;
|
||||
}
|
||||
auto val = [&](uint32_t c) -> int8_t {
|
||||
if (gu_type == kIQ3_S) return (int8_t) (2 * (int) c - 15);
|
||||
if (gu_type == kIQ3_XXS) return (int8_t) ((c & 8u) ? -iq3[c & 7u] : iq3[c & 7u]);
|
||||
return iq2[c & 7u];
|
||||
};
|
||||
g[8 * m + b] = val(c0);
|
||||
g[8 * m + 4 + b] = val(c1);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ the slot hash
|
||||
//
|
||||
// STRATA_EXPERT_NIBBLE_RECHECK's fingerprint of a slot: over the slot's first `hashed` bytes (kGuBytes plus the down
|
||||
// rows; the alignment tail is not written and not hashed) as little-endian 32-bit words w_i, the last one
|
||||
// zero-extended, H = sum_i (uint64) (w_i ^ i) * kHashMul mod 2^64. A sum, so the device's order of adding does not
|
||||
// change it; the index term makes a moved word count.
|
||||
|
||||
inline constexpr uint64_t kHashMul = 0x9E3779B97F4A7C15ull;
|
||||
|
||||
/// The host reference of the slot hash (the device hash gives the same value for the same bytes).
|
||||
inline uint64_t hash_host(const void* p, uint64_t bytes) {
|
||||
const uint8_t* s = (const uint8_t*) p;
|
||||
uint64_t h = 0;
|
||||
const uint64_t n = (bytes + 3) / 4;
|
||||
for (uint64_t i = 0; i < n; ++i) {
|
||||
uint32_t w = 0;
|
||||
const uint64_t at = 4 * i, take = bytes - at < 4 ? bytes - at : 4;
|
||||
std::memcpy(&w, s + at, (size_t) take); // little-endian hosts only
|
||||
h += (uint64_t) (w ^ (uint32_t) i) * kHashMul;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ the switches
|
||||
|
||||
struct Config {
|
||||
bool on = false; ///< STRATA_EXPERT_NIBBLE=1
|
||||
bool recheck = false; ///< STRATA_EXPERT_NIBBLE_RECHECK=1 (debug: every slot's hash per request)
|
||||
std::vector<int> fmts{ kIQ2_S, kIQ3_XXS, kIQ3_S }; ///< STRATA_EXPERT_NIBBLE_FMTS (default 22,18,21)
|
||||
std::vector<int64_t> skip; ///< STRATA_EXPERT_NIBBLE_SKIP: layers kept in their GGUF blocks
|
||||
std::string error; ///< non-empty: a malformed value - the start is refused
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
/// "a,b,c" -> integers; false on anything else (empty = an empty list).
|
||||
inline bool parse_list(const char* s, std::vector<int64_t>& out) {
|
||||
out.clear();
|
||||
while (s != nullptr && *s != '\0') {
|
||||
char* end = nullptr;
|
||||
const long long v = std::strtoll(s, &end, 10);
|
||||
if (end == s) return false;
|
||||
out.push_back((int64_t) v);
|
||||
s = end;
|
||||
if (*s == ',') ++s;
|
||||
else if (*s != '\0') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace detail
|
||||
|
||||
/// The switches, read once (generate.cpp reads them before anything is allocated).
|
||||
inline const Config& config() {
|
||||
static const Config c = [] {
|
||||
Config r;
|
||||
const char* e = std::getenv("STRATA_EXPERT_NIBBLE");
|
||||
if (e != nullptr && e[0] != '\0' && std::strcmp(e, "0") != 0) {
|
||||
if (std::strcmp(e, "1") == 0) r.on = true;
|
||||
else r.error = std::string("STRATA_EXPERT_NIBBLE=") + e + ": expected 0 or 1";
|
||||
}
|
||||
const char* rc = std::getenv("STRATA_EXPERT_NIBBLE_RECHECK");
|
||||
r.recheck = rc != nullptr && std::strcmp(rc, "1") == 0;
|
||||
std::vector<int64_t> v;
|
||||
if (const char* f = std::getenv("STRATA_EXPERT_NIBBLE_FMTS"); f != nullptr && f[0] != '\0') {
|
||||
if (!detail::parse_list(f, v)) {
|
||||
if (r.error.empty()) r.error = std::string("STRATA_EXPERT_NIBBLE_FMTS=") + f + ": expected ggml types, e.g. 22,18,21";
|
||||
} else {
|
||||
r.fmts.clear();
|
||||
for (const int64_t t : v) {
|
||||
if (!fmt_built((int) t) && r.error.empty())
|
||||
r.error = "STRATA_EXPERT_NIBBLE_FMTS: type " + std::to_string(t) +
|
||||
" is not converted (22 IQ2_S, 18 IQ3_XXS, 21 IQ3_S)";
|
||||
r.fmts.push_back((int) t);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (const char* k = std::getenv("STRATA_EXPERT_NIBBLE_SKIP"); k != nullptr && k[0] != '\0') {
|
||||
if (!detail::parse_list(k, r.skip) && r.error.empty())
|
||||
r.error = std::string("STRATA_EXPERT_NIBBLE_SKIP=") + k + ": expected layer numbers, e.g. 40,44";
|
||||
}
|
||||
return r;
|
||||
}();
|
||||
return c;
|
||||
}
|
||||
|
||||
/// With the switch on, the first environment setting it refuses, as a message (empty = none): the paths that would
|
||||
/// read a converted slot as GGUF blocks, write GGUF bytes into one, or run other kernels for the converted layers
|
||||
/// than the ones the 4-bit kernels are bit for bit. The command-line half (--peer-device, remote expert caches,
|
||||
/// --kv-grow, --vram-elastic), the cc 6.0 check, full residency and no loan are generate.cpp's checks; the prompt
|
||||
/// path's own (MMQ on every converted layer) is Prefill::nibble_prompt_check.
|
||||
inline std::string env_conflicts() {
|
||||
auto set = [](const char* n) -> const char* {
|
||||
const char* v = std::getenv(n);
|
||||
return v != nullptr && v[0] != '\0' ? v : nullptr;
|
||||
};
|
||||
const char* v = set("STRATA_MMQ_DIRECT");
|
||||
if (v != nullptr && std::atoi(v) != 0)
|
||||
return "STRATA_MMQ_DIRECT (the prompt MMQ would read a converted slot in place as GGUF blocks)";
|
||||
v = set("STRATA_PREFILL_MMQ");
|
||||
if (v != nullptr && std::atoi(v) == 0) return "STRATA_PREFILL_MMQ=0 (the FP16 prompt path reads GGUF blocks)";
|
||||
v = set("STRATA_PF_FUSED");
|
||||
if (v != nullptr && v[0] == '1') return "STRATA_PF_FUSED=1 (the fused prompt kernels read GGUF blocks)";
|
||||
v = set("STRATA_FS_SLOTS");
|
||||
if (v != nullptr && std::atoi(v) > 0) return "STRATA_FS_SLOTS (Foresight swaps GGUF blobs into slots)";
|
||||
v = set("STRATA_EXPERT_V2");
|
||||
if (v != nullptr && v[0] == '1') return "STRATA_EXPERT_V2=1 (the S26 kernels, not the CUDA layout, on IQ3_S)";
|
||||
v = set("STRATA_KV_GROW");
|
||||
if (v != nullptr && v[0] != '0') return "STRATA_KV_GROW (the elastic K/V moves slots at their GGUF size)";
|
||||
v = set("STRATA_EXP_MODE");
|
||||
if (v != nullptr && std::atoi(v) != 0 && std::atoi(v) != 8)
|
||||
return "STRATA_EXP_MODE other than 0 or 8 (another layout's gate/up kernels)";
|
||||
return {};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ the VRAM table
|
||||
|
||||
/// One layer's slots. `on` false: the GGUF blob, `slot_bytes == raw_bytes`, the production kernels.
|
||||
struct LayerVram {
|
||||
bool on = false;
|
||||
int gu_type = -1, d_type = -1;
|
||||
uint64_t down_off = 0; ///< in the slot: kDownOff when on, else the raw blob's down_off
|
||||
uint64_t down_bytes = 0; ///< the down rows (raw_bytes - raw_down_off)
|
||||
uint64_t hashed = 0; ///< bytes the slot hash covers: kGuBytes + down_bytes when on, else 0
|
||||
uint64_t slot_bytes = 0; ///< what the expert cache allocates per slot (`open_sized`, every estimate)
|
||||
// the raw blob as the arena and the pack hold it (expert_layout().fmt[l]); the transcoder reads these
|
||||
uint64_t raw_bytes = 0, raw_gu_row = 0, raw_up_off = 0, raw_down_off = 0;
|
||||
};
|
||||
|
||||
/// One layer's entry from its GGUF format and the switches (pure; `plan_layers` calls it per layer).
|
||||
inline LayerVram plan_layer(int64_t l, const strata::kernels::cpu::NativeFmt& f, const Config& c) {
|
||||
LayerVram v;
|
||||
v.gu_type = f.gu_type;
|
||||
v.d_type = f.d_type;
|
||||
v.raw_bytes = f.bytes;
|
||||
v.raw_gu_row = f.gu_row;
|
||||
v.raw_up_off = f.up_off;
|
||||
v.raw_down_off = f.down_off;
|
||||
v.down_bytes = f.bytes - f.down_off;
|
||||
v.down_off = f.down_off;
|
||||
v.slot_bytes = f.bytes;
|
||||
bool listed = false, skipped = false;
|
||||
for (const int t : c.fmts) listed = listed || t == f.gu_type;
|
||||
for (const int64_t s : c.skip) skipped = skipped || s == l;
|
||||
// [gate | up | down] exactly, no NVFP4 tail, the down rows a whole number of 16-byte words (the gathers copy them so)
|
||||
const bool shape = f.n_embd == kNEmbd && f.n_ff == kNFf && f.gu_row == raw_gu_row(f.gu_type) &&
|
||||
f.up_off == (uint64_t) kNFf * f.gu_row && f.down_off == 2 * f.up_off && f.bytes > f.down_off &&
|
||||
f.tail_off == 0 && (f.bytes - f.down_off) % 16 == 0;
|
||||
if (c.on && c.error.empty() && listed && !skipped && fmt_built(f.gu_type) && shape) {
|
||||
v.on = true;
|
||||
v.down_off = kDownOff;
|
||||
v.hashed = kGuBytes + v.down_bytes;
|
||||
v.slot_bytes = slot_bytes_for(v.down_bytes);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/// Every layer's entry for this pack (all off for a Q2_0 pack or with the switch off). `err`: a SKIP layer out of
|
||||
/// range, or the switch on with a Q2_0 pack.
|
||||
inline std::vector<LayerVram> plan_layers(const strata::kernels::cpu::ExpertLayout& lay, std::string& err) {
|
||||
const Config& c = config();
|
||||
std::vector<LayerVram> out((size_t) (lay.n_layers > 0 ? lay.n_layers : 0));
|
||||
for (int64_t l = 0; l < (int64_t) out.size(); ++l) {
|
||||
if (lay.native && (size_t) l < lay.fmt.size()) out[(size_t) l] = plan_layer(l, lay.fmt[(size_t) l], c);
|
||||
else out[(size_t) l].slot_bytes = out[(size_t) l].raw_bytes = lay.blob_bytes(l);
|
||||
}
|
||||
if (c.on && !lay.native) err = "STRATA_EXPERT_NIBBLE needs a native pack (native_experts.txt)";
|
||||
for (const int64_t s : c.skip)
|
||||
if (c.on && (s < 0 || s >= lay.n_layers) && err.empty())
|
||||
err = "STRATA_EXPERT_NIBBLE_SKIP: layer " + std::to_string(s) + " is not in the model";
|
||||
return out;
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
inline std::vector<LayerVram>& table() {
|
||||
static std::vector<LayerVram> t;
|
||||
return t;
|
||||
}
|
||||
} // namespace detail
|
||||
|
||||
/// generate.cpp only: the table, once, after `expert_layout_load` and BEFORE the first slot estimate (placement
|
||||
/// search, can_start, the cache's auto size, every `open_sized`). Not thread-safe: set before any other thread.
|
||||
inline void set_layers(std::vector<LayerVram> v) { detail::table() = std::move(v); }
|
||||
|
||||
/// Layer `l`'s entry (an off entry when the table is not set or `l` is outside it). Read-only after `set_layers`.
|
||||
inline const LayerVram& layer(int64_t l) {
|
||||
static const LayerVram off;
|
||||
const auto& t = detail::table();
|
||||
return l >= 0 && (size_t) l < t.size() ? t[(size_t) l] : off;
|
||||
}
|
||||
|
||||
/// Whether any layer is converted (the switch on and the table set).
|
||||
inline bool any_on() {
|
||||
for (const LayerVram& v : detail::table())
|
||||
if (v.on) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Bytes of one of layer `l`'s VRAM slots: the converted size for a converted layer, else the layout's blob bytes
|
||||
/// (exactly `expert_layout().blob_bytes(l)`: with the switch off every caller sizes what it sized before).
|
||||
inline uint64_t slot_bytes(int64_t l) {
|
||||
const auto& t = detail::table();
|
||||
if (l >= 0 && (size_t) l < t.size()) return t[(size_t) l].slot_bytes;
|
||||
return strata::kernels::cpu::expert_layout().blob_bytes(l);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ fatal paths
|
||||
|
||||
/// A converted layer reached a path that would compute or copy it as GGUF blocks: say where and stop. Never a
|
||||
/// silent wrong answer.
|
||||
[[noreturn]] inline void fatal(int64_t l, const char* where, const char* why) {
|
||||
std::fprintf(stderr, "strata: STRATA_EXPERT_NIBBLE: layer %lld (%s, 4-bit slots) reached %s: %s - stopping\n",
|
||||
(long long) l, fmt_name(layer(l).gu_type), where != nullptr ? where : "?", why != nullptr ? why : "");
|
||||
std::fflush(stderr);
|
||||
std::abort();
|
||||
}
|
||||
|
||||
/// Before each raw slot copy that bypasses the ExpertCache API (the adaptive tier's copies, the elastic K/V's slot
|
||||
/// moves): fatal when `l` is a converted layer. The startup refusals keep these paths off; this is the backstop
|
||||
/// (with `ExpertCache::seal()` for the API's own fills).
|
||||
inline void guard_raw(int64_t l, const char* where) {
|
||||
if (layer(l).on) fatal(l, where, "a raw slot copy at the GGUF size");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ the decode kernels
|
||||
//
|
||||
// Two skeletons in the shape of native_gu_multi_kernel (16 lanes a row, a group's entries GRP_NC at a time), both bit
|
||||
// for bit the production gate/up: S stages the entries' q8_1 blocks in shared memory and decodes each item where it
|
||||
// is used (IQ3_S: v = 2u - 15 restored per byte, then the production apply); P loads the lane's codes, scales and d
|
||||
// before staging the qs words as 16-byte rows (IQ3_S: sum = 2 dot(u, x) - 15 sum(x), the same int32). Per format the
|
||||
// faster one on 4x GP100 at T = 1..6 (native_expert_bench --nibble): IQ2_S P, IQ3_XXS S, IQ3_S S.
|
||||
|
||||
inline constexpr int kSkelS = 0, kSkelP = 1;
|
||||
STRATA_NIB_HD constexpr int gu_skeleton(int gu_type) { return gu_type == kIQ2_S ? kSkelP : kSkelS; }
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ iq_kernels.cu
|
||||
//
|
||||
// Device addresses are `unsigned long long` (as native_expert_grouped's grp_ptr), streams `void*`; each returns the
|
||||
// CUDA error code (0 = success) so the caller can name the layer. A build without STRATA_EXPERT_NIBBLE_BUILT
|
||||
// returns cudaErrorInvalidValue (1) from each.
|
||||
|
||||
/// The reverse codebooks (grid magnitudes -> GGUF grid index) `check_gguf` and `gather_gguf` use, built on the CURRENT
|
||||
/// device (once per device; call it at load, before any capture). Non-zero also when a grid entry is not unique.
|
||||
int prepare(void* stream);
|
||||
|
||||
/// Converts `n` raw blobs of layer `L` (device `staging`, `L.raw_bytes` apart, as the host arena holds them) into
|
||||
/// the converted slots at `slot_ptrs[0..n)` (a device array): codes, scales, d. The down rows are not touched (the
|
||||
/// caller copies them to `slot + kDownOff`). Every item is decoded with the production `Split<TG>::load`, encoded,
|
||||
/// decoded from the written code again and compared with W.g[0..7], the scale and d; each item that differs or holds
|
||||
/// a weight outside the code set adds 1 to `*bad` (device). L.on must be true.
|
||||
int transcode(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs,
|
||||
unsigned long long* bad, void* stream);
|
||||
|
||||
/// The GGUF gate/up blocks rebuilt from each of the `n` (<= 64) converted slots at `slot_ptrs` and its down rows,
|
||||
/// compared with the raw blobs in `staging` (`L.raw_bytes` apart) byte for byte: each 32-bit word that differs adds 1
|
||||
/// to `*bad`. `prepare` first.
|
||||
int check_gguf(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs,
|
||||
unsigned long long* bad, void* stream);
|
||||
|
||||
/// The prompt path's gather of a converted layer's experts (prefill.cpp, MMQ): for q in [first, n) (n <= 16), the
|
||||
/// GGUF [gate | up] blocks rebuilt from slot `slots[q]` (host array of device addresses) into gu_dst + q * gu_stride -
|
||||
/// the bytes the raw blob holds, byte for byte - and its down rows copied to d_dst + q * d_stride; `zero_bytes` zeroed
|
||||
/// after expert n - 1's gate/up and down (MMQ's tail). Every address, stride and size 16-byte aligned. `prepare`
|
||||
/// on this device first.
|
||||
int gather_gguf(const LayerVram& L, const uint8_t* const* slots, int first, int n, void* gu_dst, uint64_t gu_stride,
|
||||
void* d_dst, uint64_t d_stride, uint64_t zero_bytes, void* stream);
|
||||
|
||||
/// The slot hash (`hash_host`'s value) of the `L.hashed` bytes at each `slot_ptrs[i]`, into device `out[0..n)`.
|
||||
int hash_slots(const LayerVram& L, const unsigned long long* slot_ptrs, int64_t n, unsigned long long* out,
|
||||
void* stream);
|
||||
|
||||
} // namespace strata::core::nibble
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
// include/strata/core/geometries/flash_next.hpp - Qwen3.8-Flash-Next (qwen4exp), the shape the engine ships for.
|
||||
// The values are ModelGeometry's member defaults (geometry.hpp); this header exists so that every shape is a header,
|
||||
// and so that the default build is byte-for-byte the build it was before shapes were selectable.
|
||||
#pragma once
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
inline constexpr const char* kGeometryName = "flash_next";
|
||||
inline constexpr ModelGeometry kCompiledGeometry{};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -0,0 +1,92 @@
|
||||
// include/strata/core/geometry.hpp - the model's geometry: one struct for the shape a model file declares and
|
||||
// the shape the kernels are compiled for.
|
||||
//
|
||||
// A model file's geometry is read from its own metadata (`strata::read_geometry`, gguf_reader.hpp), and the
|
||||
// engine passes that struct everywhere it needs a dimension. The CUDA/HIP kernels still fix most of these
|
||||
// numbers at compile time (`constexpr int N = 2560` and the like); `kCompiledGeometry` is that shape, written
|
||||
// once, and each kernel that pins a number `static_assert`s it against this struct. So a kernel and this file
|
||||
// cannot drift apart without the build failing, and a model file of another shape is refused at load with the
|
||||
// metadata key that differs (`strata::geometry_unsupported`) instead of mis-running.
|
||||
//
|
||||
// Dependency-free on purpose: the kernels include it.
|
||||
#pragma once
|
||||
|
||||
#include "strata/artifact/model_family.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// Every field is a number a kernel depends on, so a change to the compiled values is a change to a kernel
|
||||
/// contract and not a tuning knob. The defaults are Qwen3.8-Flash-Next's (qwen4exp), the shape the kernels
|
||||
/// are compiled for; the GGUF key each field is read from is named beside it.
|
||||
struct ModelGeometry {
|
||||
int64_t n_embd = 2560; ///< embedding_length
|
||||
int64_t n_layers = 48; ///< block_count (the trunk; an in-file MTP block is counted in n_mtp_layers)
|
||||
int64_t qsa_interval = 4; ///< full_attention_interval: every 4th layer is full attention, 3, 7, ... 47
|
||||
int64_t n_vocab = 248320; ///< the length of tokenizer.ggml.tokens
|
||||
double rms_eps = 1e-6; ///< attention.layer_norm_rms_epsilon
|
||||
|
||||
// GDN (36 layers)
|
||||
int64_t ssm_state_size = 128; ///< ssm.state_size: the key head width, and the value head width
|
||||
int64_t ssm_k_heads = 16; ///< ssm.group_count
|
||||
int64_t ssm_v_heads = 48; ///< ssm.time_step_rank
|
||||
int64_t ssm_d_conv = 4; ///< ssm.conv_kernel
|
||||
int64_t ssm_conv_channels = 10240; ///< 2*128*16 + 128*48, derived
|
||||
int64_t ssm_value_dim = 6144; ///< ssm.inner_size, 128 * 48
|
||||
|
||||
// QSA (12 layers)
|
||||
int64_t n_head = 24; ///< attention.head_count
|
||||
int64_t n_head_kv = 2; ///< attention.head_count_kv
|
||||
int64_t head_dim = 256; ///< attention.key_length (= attention.value_length)
|
||||
int64_t n_rot = 64; ///< rope.dimension_count: the rotated slice of head_dim and of idx_key_dim
|
||||
int64_t idx_q_heads = 4; ///< attention.indexer.head_count
|
||||
int64_t idx_key_dim = 128; ///< attention.indexer.key_length
|
||||
int64_t idx_block = 4; ///< the non-zero attention.compress_ratios entry: one pooled key per 4 cells
|
||||
int64_t idx_top_k = 2048; ///< attention.indexer.top_k: cells of selection budget
|
||||
|
||||
// gated residual, on every layer
|
||||
int64_t hc = 4; ///< hyper_connection.count
|
||||
int64_t hc_lr = 320; ///< hyper_connection.low_rank
|
||||
|
||||
// MoE, on every layer
|
||||
int64_t n_expert = 512; ///< expert_count; pruned variants (GSQ-RCO Coder) ship fewer
|
||||
int64_t n_expert_used = 10; ///< expert_used_count
|
||||
int64_t n_ff = 640; ///< expert_feed_forward_length (= expert_shared_feed_forward_length)
|
||||
|
||||
// appended for the model families (Qwen3.6 = qwen35moe); the defaults keep Flash-Next's values
|
||||
int64_t n_ff_shexp = 640; ///< the shared expert's FFN width (qwen4exp: equal to n_ff, read_geometry checks)
|
||||
ModelFamily family = ModelFamily::Qwen4Exp;
|
||||
int64_t n_mtp_layers = 0; ///< MTP blocks inside the model file, after the trunk (qwen35moe: blk.40)
|
||||
|
||||
constexpr bool has_indexer() const { return idx_q_heads > 0; } ///< false: dense attention only
|
||||
constexpr bool has_hyper_connections() const { return hc > 0; } ///< false: plain pre-norm residual
|
||||
constexpr int64_t hc_dim() const { return hc * n_embd; }
|
||||
/// `layer % qsa_interval == qsa_interval - 1` is full attention. Derived, not a second list.
|
||||
constexpr int64_t n_qsa_layers() const { return n_layers / qsa_interval; }
|
||||
constexpr int64_t n_gdn_layers() const { return n_layers - n_qsa_layers(); }
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
|
||||
// The shape the kernels are compiled for: `kCompiledGeometry`, defined by the geometry header chosen at configure
|
||||
// time (`-DSTRATA_GEOMETRY=<name>` selects include/strata/core/geometries/<name>.hpp, `-DSTRATA_GEOMETRY_FILE=<path>`
|
||||
// takes any header; cmake/strata_geometry.cmake writes geometry_selected.hpp into the build tree for either). With
|
||||
// neither option the build uses Flash-Next's header and adds no compile flag. A kernel that fixes a dimension at
|
||||
// compile time asserts it against `kCompiledGeometry`; geometry_checks.hpp holds the constraints every shape must meet.
|
||||
#if __has_include("strata/core/geometry_selected.hpp")
|
||||
#include "strata/core/geometry_selected.hpp"
|
||||
#else
|
||||
#include "strata/core/geometries/flash_next.hpp"
|
||||
#endif
|
||||
#include "strata/core/geometry_checks.hpp"
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// True for the full-attention layers. `docs/semantics.md` gives this twice over - `full_attention_interval
|
||||
/// = 4` and an explicit `attention.compress_ratios` array - and `read_geometry` checks that the two agree.
|
||||
inline bool is_qsa_layer(const ModelGeometry& g, int64_t layer) {
|
||||
return layer % g.qsa_interval == g.qsa_interval - 1;
|
||||
}
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -0,0 +1,52 @@
|
||||
// include/strata/core/geometry_checks.hpp - what every compiled shape must satisfy.
|
||||
//
|
||||
// The kernels are written for a family of shapes, not for one number each: some values are the same in every Qwen
|
||||
// model of this layer design (the GDN state width, the attention head width, the conv width) and are held fixed
|
||||
// here; the others have to be divisible or within a range the tiles, the shared-memory plans and the register
|
||||
// arrays were written for. A geometry header that breaks one of these fails the build with the line below that
|
||||
// names the field, instead of compiling a kernel that mis-runs. Included by geometry.hpp, after the header.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/geometry.hpp"
|
||||
|
||||
namespace strata::core::geometry_checks {
|
||||
|
||||
inline constexpr const ModelGeometry& g = kCompiledGeometry;
|
||||
|
||||
// ---- held fixed: the same in every published Qwen3-Next / 3.5 / 3.6 config and in Flash-Next; the kernels unroll them
|
||||
static_assert(g.ssm_state_size == 128, "geometry: ssm.state_size must be 128 (GDN kernels: 4 rows per lane, 128-thread blocks, 32x32 state tiles)");
|
||||
static_assert(g.ssm_k_heads == 16, "geometry: ssm.group_count must be 16 (GDN key heads)");
|
||||
static_assert(g.ssm_d_conv == 4, "geometry: ssm.conv_kernel must be 4 (3 history taps and 4 weights are unrolled)");
|
||||
static_assert(g.head_dim == 256, "geometry: attention.key_length must be 256 (attention kernels: thread per dim, 4 warps x 64)");
|
||||
static_assert(g.n_rot == 64, "geometry: rope.dimension_count must be 64");
|
||||
static_assert(g.qsa_interval == 4, "geometry: full_attention_interval must be 4");
|
||||
static_assert(g.hc == 4, "geometry: hyper_connection.count must be 4 (register and shared arrays hold 4 streams)");
|
||||
static_assert(g.idx_q_heads == 4 && g.idx_key_dim == 128,
|
||||
"geometry: the indexer must be 4 heads x 128 (one float4 per lane, one warp per head)");
|
||||
static_assert(g.idx_block == 4, "geometry: the indexer pooling block must be 4 cells");
|
||||
|
||||
// ---- ranges and divisibility the tiles were written for
|
||||
static_assert(g.n_embd % 256 == 0 && g.n_embd >= 1024 && g.n_embd <= 4096,
|
||||
"geometry: embedding_length must be a multiple of 256 within 1024..4096 (K-quant rows, 8x512 partial sums, 4096-half shared staging)");
|
||||
static_assert(g.n_ff % 64 == 0 && g.n_ff >= 256 && g.n_ff <= 1100,
|
||||
"geometry: expert_feed_forward_length must be a multiple of 64 within 256..1100 (Q2 blobs, 64-wide act groups, 1024-byte act buffer)");
|
||||
static_assert(g.n_ff_shexp == g.n_ff, "geometry: the shared expert must be as wide as the routed experts");
|
||||
static_assert(g.hc_lr % 64 == 0 && g.hc_lr / 8 >= 32 && g.hc_lr / 8 <= 64 && g.hc_lr % 8 == 0,
|
||||
"geometry: hyper_connection.low_rank must be a multiple of 64 with 32 <= low_rank/8 <= 64 (fused_gr lane rule)");
|
||||
static_assert(g.n_head_kv >= 1 && g.n_head % g.n_head_kv == 0 && g.n_head / g.n_head_kv <= 16,
|
||||
"geometry: attention.head_count / head_count_kv must be a whole number <= 16 (one M16 tile of query heads)");
|
||||
static_assert(g.ssm_v_heads % g.ssm_k_heads == 0 && g.ssm_v_heads / g.ssm_k_heads >= 1 && g.ssm_v_heads / g.ssm_k_heads <= 4,
|
||||
"geometry: ssm.time_step_rank must be 1..4 times ssm.group_count");
|
||||
static_assert(g.n_expert % 32 == 0 && g.n_expert >= 32 && g.n_expert <= 512,
|
||||
"geometry: expert_count must be a multiple of 32 up to 512 (router: one lane per 32 experts)");
|
||||
static_assert(g.n_expert_used >= 1 && g.n_expert_used <= 16 && g.n_expert_used <= g.n_expert,
|
||||
"geometry: expert_used_count must be 1..16");
|
||||
static_assert(g.n_layers % g.qsa_interval == 0 && g.n_layers >= g.qsa_interval,
|
||||
"geometry: block_count must be a multiple of full_attention_interval");
|
||||
|
||||
// ---- derived fields written out in the header must agree
|
||||
static_assert(g.ssm_conv_channels == 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_state_size * g.ssm_v_heads,
|
||||
"geometry: ssm_conv_channels must be 2*state*k_heads + state*v_heads");
|
||||
static_assert(g.ssm_value_dim == g.ssm_state_size * g.ssm_v_heads, "geometry: ssm_value_dim must be state*v_heads");
|
||||
|
||||
} // namespace strata::core::geometry_checks
|
||||
@@ -0,0 +1,221 @@
|
||||
// strata/core/sm120_series.hpp - bitwise kernel switches that are ON by default on a compute capability 12.0 card
|
||||
// (RTX 50 series / RTX PRO Blackwell workstation cards).
|
||||
//
|
||||
// 147-verify measured these exact switches on an RTX PRO 5000 Blackwell 72 GB (IQ3_S, every expert in VRAM): together
|
||||
// a verify round of 4 tokens 13.70 -> 12.23 ms with the same text (notes-147-l620.md). Each one is bitwise equal to
|
||||
// the kernels it replaces (their own parity tests and the identity gate), so only the speed changes:
|
||||
// STRATA_SIDE_MIXER=2 the mixer's input-only work on branches of the verify graph
|
||||
// STRATA_ATTN_DAILY=1 the Daily's decode attention (attn_chunk_kernel_pre75 + merge v2)
|
||||
// STRATA_GR_UP75=1 the hyper-connection up projection with its rows' loads hoisted
|
||||
// STRATA_GR_DOWN_TG=1 the hyper-connection down projection with one token a block row (T times the blocks); =2 (token
|
||||
// pairs) on a 12.0 card with fewer than 80 SMs
|
||||
// STRATA_GU_SWIGLU=1 gate/up, SwiGLU and the q8_1 blocks of the routed experts in one launch
|
||||
// STRATA_GR_UP_WIDE=1 the hyper-connection up projection with one warp a row (1,280 blocks instead of 160; +1.9%
|
||||
// story / +0.7% code decode on the RTX PRO 5000, 5 pairs, token ids identical; bitwise)
|
||||
// and one that rounds differently (KL-checked, the AMD gfx12 rule): STRATA_PF_FUSED (the native packs' prompt experts on the
|
||||
// fused int8 kernels, IQ2_S / IQ3_XXS / IQ3_S / IQ4_XS gate/up only, 12.0 cards with 80+ SMs only; =0 keeps MMQ, =1 takes every
|
||||
// covered format on any card).
|
||||
//
|
||||
// STRATA_SM120_PERF=0 turns the whole set off on a 12.0 card (the defaults every other card has).
|
||||
// Each switch's own variable still wins in both directions (=0 off, =1 / =2 on), on any card, as before.
|
||||
// Nothing here changes a card that is not a 12.0, except the two switches the GB10 (sm_121) measured as well (kGb10AttnDaily, kGb10GrDownTg below;
|
||||
// STRATA_SM121_PERF=0 or STRATA_DEFAULTS=026 give the GB10 its earlier defaults back); an sm_100 card keeps its defaults.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/defaults_026.hpp"
|
||||
#include "strata/core/emulate.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace strata {
|
||||
|
||||
/// STRATA_SM120_PERF (read once): unset or anything but "0" = on
|
||||
inline bool sm120_series() {
|
||||
static const bool on = [] {
|
||||
const char* e = std::getenv("STRATA_SM120_PERF");
|
||||
return e == nullptr || std::atoi(e) != 0;
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
/// the device (raw cudaDevAttrComputeCapabilityMajor / Minor) is a 12.0 card, or emulates one (STRATA_EMULATE_CC=120)
|
||||
inline bool is_sm120(int major, int minor) { return cc_major_of(major) == 12 && cc_minor_of(minor) == 0; }
|
||||
|
||||
/// STRATA_PLE_BATCH (the prompt path's batched PLE post-ops) when the user set nothing. ON everywhere except one toolchain: an engine built with CUDA 12.8
|
||||
/// (CUDART_VERSION 12080..12089) running on a compute capability 12.0 card faults in the prompt path with it ("an illegal memory access", first error in the
|
||||
/// native PLE postops launch; RTX PRO 6000, driver 580, srv118; issues #220, #224; CMake already warns for a CUDA < 13.0 sm_120 build). The same source built
|
||||
/// with CUDA 13.0 (the released cuda13 package) and 13.2 runs it at every prompt length, and it is worth ~23% of the prompt speed there, so it stays on there.
|
||||
/// `cudart_version`: CUDART_VERSION of the toolkit the engine was built with (0 in a HIP build); `hip`: a HIP build (a gfx12 card reports 12.0 as well).
|
||||
inline bool ple_batch_default(int cudart_version, bool hip, int major, int minor) {
|
||||
const bool cuda_12_8 = !hip && cudart_version >= 12080 && cudart_version < 12090;
|
||||
return !(cuda_12_8 && is_sm120(major, minor));
|
||||
}
|
||||
|
||||
/// The decision: STRATA_PLE_BATCH wins in both directions (text that reads as 0 is off, anything else on, as before); unset is ple_batch_default.
|
||||
inline bool ple_batch_resolve(const char* env, int cudart_version, bool hip, int major, int minor) {
|
||||
if (env != nullptr) return std::atoi(env) != 0;
|
||||
return ple_batch_default(cudart_version, hip, major, minor);
|
||||
}
|
||||
|
||||
/// the default of a bitwise switch of the set: on for a 12.0 card unless STRATA_SM120_PERF=0
|
||||
inline bool sm120_default(int major, int minor) { return is_sm120(major, minor) && sm120_series(); }
|
||||
|
||||
/// the device is a GB10 (NVIDIA DGX Spark, compute capability 12.1, or emulates one)
|
||||
inline bool is_sm121(int major, int minor) { return cc_major_of(major) == 12 && cc_minor_of(minor) == 1; }
|
||||
|
||||
/// STRATA_SM121_PERF (read once): unset or anything but "0" = on. The GB10 table of nv_defaults.cpp reads the same variable.
|
||||
inline bool sm121_series() {
|
||||
static const bool on = [] {
|
||||
const char* e = std::getenv("STRATA_SM121_PERF");
|
||||
return e == nullptr || std::atoi(e) != 0;
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
/// The default of a bitwise switch of the 12.0 set that was ALSO measured on a GB10 (BW-7, phaseA-tests/bw/RESULTS-BW-B.md): on for a 12.0 card unless
|
||||
/// STRATA_SM120_PERF=0, and on for a GB10 when `gb10_measured` (the caller's constant: the switch won there and passed its gate) unless
|
||||
/// STRATA_SM121_PERF=0 or STRATA_DEFAULTS=026 (the same off switches as the GB10 table of nv_defaults.cpp). `v026`: qwen_defaults_026().
|
||||
inline bool sm12x_default_v(int major, int minor, bool gb10_measured, bool v026) {
|
||||
return sm120_default(major, minor) || (gb10_measured && is_sm121(major, minor) && sm121_series() && !v026);
|
||||
}
|
||||
inline bool sm12x_default(int major, int minor, bool gb10_measured) { return sm12x_default_v(major, minor, gb10_measured, qwen_defaults_026()); }
|
||||
|
||||
/// Which switches of the 12.0 set are on for a GB10 (compute capability 12.1, DGX Spark) as well. BW-7, 11-19, a rented GB10 (IQ3_S, all 24,576 experts resident,
|
||||
/// DFlash2 Q4_0 drafter, --spec 6, fixed draft-cost table, fresh engine per start, arms interleaved, 4 requests x 300 tokens per kind a start, token ids identical to
|
||||
/// the default's); numbers and gates in phaseA-tests/bw/RESULTS-BW-B.md. Each constant is one measured verdict, so a later measurement flips one line.
|
||||
/// Decode against the GB10 default (3 paired rounds, median; chat / code / json / agent):
|
||||
/// STRATA_ATTN_DAILY +0.3 / +0.9 / +0.7 / +1.2 % (json, agent 3 of 3 pairs) -> ON
|
||||
/// STRATA_GR_DOWN_TG -0.1 / +0.7 / +1.1 / +0.9 % (json, agent 3 of 3 pairs; token pairs, the GB10 has 48 SMs) -> ON
|
||||
/// STRATA_GU_SWIGLU -0.2 / -1.0 / 0.0 / +0.1 %, STRATA_GR_UP75 -0.7 / -0.2 / -0.4 / -0.6 %, STRATA_GR_UP_WIDE -0.4 / -0.3 / -0.1 / -0.2 %,
|
||||
/// STRATA_SMALL_UNR +0.1 / -0.9 / +0.2 / 0.0 %, STRATA_DF_PDL +0.1 / -0.6 / 0.0 / +0.3 %: level or slower here (inside the 0.2-1 % scatter) -> stay off
|
||||
/// STRATA_GR_V3 (another summation order, KL-gated; text changes) and STRATA_GR_V3_PF (E15, acts only with GR_V3): mixed, E15 itself level (v3 with / without PF
|
||||
/// chat +1.0 %, code -0.9 %, json -0.4 %, agent -0.5 %) -> stay off
|
||||
constexpr bool kGb10GuSwiglu = false; ///< STRATA_GU_SWIGLU
|
||||
constexpr bool kGb10AttnDaily = true; ///< STRATA_ATTN_DAILY
|
||||
constexpr bool kGb10GrUp75 = false; ///< STRATA_GR_UP75
|
||||
constexpr bool kGb10GrDownTg = true; ///< STRATA_GR_DOWN_TG
|
||||
constexpr bool kGb10GrUpWide = false; ///< STRATA_GR_UP_WIDE
|
||||
constexpr bool kGb10SmallUnr = false; ///< STRATA_SMALL_UNR
|
||||
constexpr bool kGb10DfPdl = false; ///< STRATA_DF_PDL
|
||||
constexpr bool kGb10GrV3Pf = false; ///< STRATA_GR_V3_PF (E15: the v3 HC read's load ordering; bitwise, but it only acts when the v3 read runs)
|
||||
constexpr bool kGb10GrV3 = false; ///< STRATA_GR_V3 (the stream-split HC read: another summation order, KL-gated)
|
||||
|
||||
// ---- 0.2.7 defaults of the CUDA speed work (pure rules; the engine reads the device and calls these; tests in arch_defaults_test)
|
||||
// `hip`: a HIP build, where a gfx1200 / gfx1201 reports compute capability 12.0 as well and none of these is measured or wanted.
|
||||
// `v026`: STRATA_DEFAULTS=026 (defaults_026.hpp qwen_defaults_026()): every one of these is then off, as in v0.2.6. An explicit variable
|
||||
// (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, ...) is decided by the caller before it asks the rule, so it still wins.
|
||||
// `total_bytes`: the card's memory (cudaDeviceProp::totalGlobalMem); `integrated`: a GPU that shares the PC's memory.
|
||||
constexpr double kSmallCardGiB = 13.0; // "a 12 GB card": 12 GB cards report 11.6 - 12.0 GiB, 16 GB ones 15.6 - 16.0
|
||||
|
||||
/// The residency-bias bonus the user can ask for on a discrete CUDA card of 13 GiB or less (STRATA_ROUTE_PRIOR=1.5; the app's Expert-settings row
|
||||
/// "Faster answers on 12 GB NVIDIA cards" writes it): THE one place the value lives. 1.5 since the owner decision of 2026-10-26 (2.0 had real defects in
|
||||
/// the copy and code check on the RTX 3060 12 GB with IQ3_XXS; none in 19 tasks at 1.5 or 1.0). Speed against off: story +15%, code +37%.
|
||||
/// It was the default on those cards in 0.2.7 only. Owner decision of 2026-10-29: OFF by default again (#4402: repetition loops and weaker results in long
|
||||
/// agent sessions; our own 0.2.7 agent check passed 4.5 of 10 tasks with it on against 5.6 with it off). It stays an opt-in.
|
||||
constexpr float kRoutePriorSmallCard = 1.5f;
|
||||
|
||||
/// STRATA_ROUTE_PRIOR when the user set nothing: 0 on every card (residency-biased routing changes which experts run, so it is only on when asked for:
|
||||
/// STRATA_ROUTE_PRIOR=1.5, or the Expert-settings row). The same answer as v0.2.6 and as 0.2.7 with STRATA_ROUTE_PRIOR=0 or STRATA_DEFAULTS=026.
|
||||
/// The arguments are kept so a caller and the table test (arch_defaults_test) still ask the same question per card; none of them changes the answer.
|
||||
inline float route_prior_default(bool /*hip*/, bool /*integrated*/, double /*total_bytes*/, bool /*v026*/ = false) { return 0.0f; }
|
||||
|
||||
/// The lambda the engine uses given the text of STRATA_ROUTE_PRIOR (nullptr = unset): any set value is the user's own and wins on every card
|
||||
/// (atof; "0" and text that reads as 0 are off; "1.5" is what the Expert-settings row writes), unset is route_prior_default (0).
|
||||
inline float route_prior_resolve(const char* env, bool hip, bool integrated, double total_bytes, bool v026 = false) {
|
||||
return env != nullptr ? (float) std::atof(env) : route_prior_default(hip, integrated, total_bytes, v026);
|
||||
}
|
||||
|
||||
/// The window warm-up before READY (generate.cpp, lane DRAFT-COSTS): one dummy window per width on token id 1, whose misses page that token's experts into the GPU expert
|
||||
/// cache. "Speed only" while routing ignores residency; with STRATA_ROUTE_PRIOR on, the first request is routed towards what is resident, so the dummy token's experts bend its
|
||||
/// answer (#6171: P(<|im_end|>) summed over the 8 digits of a long passkey answer 4.8 - 7.4 % in the first request after a start against 1.4 - 1.7 % with the warm-up off or the prior off;
|
||||
/// 8 starts per arm, RTX 3090, IQ4_XS). warm_env is STRATA_WINDOW_WARM (nullptr unset): "0" off, "1" on whatever the prior says; unset: on, except while the prior is on (prior > 0).
|
||||
/// The cost of skipping it is the graph build of a width that the policy first picks inside a request (tens of ms, once).
|
||||
inline bool window_warm_on(const char* warm_env, float prior) {
|
||||
if (warm_env != nullptr && warm_env[0] == '0') return false;
|
||||
if (warm_env != nullptr && warm_env[0] == '1') return true;
|
||||
return !(prior > 0.0f);
|
||||
}
|
||||
|
||||
/// STRATA_GR_V3 (the stream-split hyper-connection read, another summation order) when the user set nothing: ON for a discrete compute capability
|
||||
/// 12.0 card (STRATA_SM120_PERF=0 turns the set off) with more than 13 GiB, CUDA builds only. Measured: RTX PRO 5000 72 GB +1.2% decode clean,
|
||||
/// -3.0% / -5.9% on 2x RTX A4000 (sm_86), +1.0% / -3.4% on an RTX 3060 (sm_86): so not those; a 12 GB sm_120 card is unmeasured.
|
||||
inline bool gr_v3_default(bool hip, int major, int minor, bool integrated, double total_bytes, bool v026 = false) {
|
||||
return !v026 && !hip && ((!integrated && sm120_default(major, minor) && total_bytes / 1073741824.0 > kSmallCardGiB) || (kGb10GrV3 && is_sm121(major, minor) && sm121_series()));
|
||||
}
|
||||
|
||||
/// STRATA_PROMPT_ATTN_IMMA (the prompt attention on int8 tensor cores, another summation order) when the user set nothing: ON for every CUDA card of
|
||||
/// compute capability 8.0 or newer (the int8 m16n8k32 MMA), not Turing / Volta / Pascal, not HIP. `cc` = 10 * major + minor as the engine
|
||||
/// resolves it (an emulated or forced Turing counts as 75). Measured on sm_120 (RTX PRO 5000) and sm_86 (2x RTX A4000): +1.1 .. +1.8% prompt.
|
||||
inline bool prompt_attn_imma_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc >= 80; }
|
||||
|
||||
/// STRATA_MMVQ_IL_89 (#3453: the decode kernel row tables of an Ada card, the cells where an RTX 4070 and an RTX 4080 agreed; bitwise the same
|
||||
/// output, only the rows-a-warp split differs) when the user set nothing: ON for compute capability 8.9 only (owner decision, 26 October: not yet
|
||||
/// measured on an Ada card by us), off under STRATA_DEFAULTS=026 and in HIP builds. `cc` = 10 * major + minor as the engine resolves it.
|
||||
inline bool mmvq_il_89_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc == 89; }
|
||||
|
||||
/// The two sm_80-only defaults of 0.2.7 (#3779: the wide dense dequant and the MMVQ-IL sm_80 tables, both bitwise the old output, measured on a
|
||||
/// CMP 170HX only) given the text of their variable (nullptr = unset): "1" on and "0" off win, unset is on unless STRATA_DEFAULTS=026.
|
||||
inline bool sm80_default_on(const char* env, bool v026 = false) {
|
||||
if (env != nullptr && env[0] == '1') return true;
|
||||
if (env != nullptr && env[0] == '0') return false;
|
||||
return !v026;
|
||||
}
|
||||
|
||||
/// The answer for STRATA_MMVQ_IL_89 given the variable's text (nullptr = unset): "1" on and "0" off win over everything, anything else (unset,
|
||||
/// empty, other text) is the rule above.
|
||||
inline bool mmvq_il_89_resolve(const char* env, bool hip, int cc, bool v026 = false) {
|
||||
if (env != nullptr && env[0] == '1') return true;
|
||||
if (env != nullptr && env[0] == '0') return false;
|
||||
return mmvq_il_89_default(hip, cc, v026);
|
||||
}
|
||||
|
||||
/// STRATA_GR_UP_WIDE (the hyper-connection up projection, one warp a row; bitwise the old kernel) when the user set nothing: ON for a compute
|
||||
/// capability 12.0 card (STRATA_SM120_PERF=0 turns the set off), CUDA builds only.
|
||||
inline bool gr_up_wide_default(bool hip, int major, int minor, bool v026 = false) { return !v026 && !hip && sm12x_default_v(major, minor, kGb10GrUpWide, v026); }
|
||||
|
||||
/// STRATA_PREFILL_LAYER_MAJOR (#3976: the layer-major prompt walk, which reads each layer's streamed experts once per super-chunk instead of once
|
||||
/// per chunk; another summation order of the routed experts, so KL-checked, not bitwise) when the user set nothing: OFF everywhere (owner's yes 2026-11-02).
|
||||
/// It was ON for a CUDA layer split (`stages` = the number of GPUs the prompt path runs on, 2 or more; measured 2026-10-24 on 2x RTX A4000 with IQ3_XXS and
|
||||
/// streamed experts only), but on 2x RTX A6000 (IQ3_S, MTP, three residency levels) the chunk-major path reads a 32K prompt 37-55% sooner and is level at 8K
|
||||
/// (DF2-MGPU, boston). The one place the walk wins by default is the single-card small-cache rule (small_card_prompt_path below), which sets
|
||||
/// STRATA_PREFILL_LAYER_MAJOR=1 itself. STRATA_PREFILL_LAYER_MAJOR=1 still turns it on, "0" off, by hand, on any build that has it. The parameters stay so that
|
||||
/// the callers and the resolve rule below keep their shape. The engine adds its own per-prompt declines (image prompts, KVA, a batch read that yields,
|
||||
/// a peer GPU, no VRAM for a super-chunk): those read the chunk-major path as before.
|
||||
inline bool prefill_layer_major_default(bool /*hip*/, int /*stages*/, bool /*v026*/ = false) { return false; }
|
||||
|
||||
/// The answer for STRATA_PREFILL_LAYER_MAJOR given the variable's text (nullptr = unset): any text that starts a number other than 0 is on, "0" (or any
|
||||
/// text that reads as 0) is off, both win over everything; unset or empty is the rule above. An explicit "1" is honoured on one GPU too (the
|
||||
/// opt-in of the first ports); a HIP build still declines at run time.
|
||||
inline bool prefill_layer_major_resolve(const char* env, bool hip, int stages, bool v026 = false) {
|
||||
if (env != nullptr && env[0] != '\0') return std::atoi(env) != 0;
|
||||
return prefill_layer_major_default(hip, stages, v026);
|
||||
}
|
||||
|
||||
|
||||
/// The small-card prompt path (owner's yes 2026-11-02; DF2-MEM, phaseA-tests/blackwell/RESULTS-DF2MEM.md sections 5-10). On one CUDA card whose expert
|
||||
/// cache is small, the default prompt path has to read prompts in chunks below 8,192 tokens and streams every expert again for every chunk; reading them
|
||||
/// with the unfused experts (STRATA_PF_FUSED=0) and, from two chunks on, the layer-major walk (each layer's experts once per super-chunk) is faster:
|
||||
/// IQ3_S on an RTX PRO 5000 with the cache held to ~1.3K / ~1.6K / ~1.9K engine slots (default chunks 2048 / 3840 / 5888): time to first token of a 20K / 32K
|
||||
/// prompt -44% / -50%, -41% / -42%, -14% / -12% (and -26% on a real 12 GB RTX 5070 at 20K); from a default chunk of 8,192 on (2.3K slots and up) the default
|
||||
/// path wins and the same change costs +1..+25%. Not bitwise (first-token KL against the FP16 prompt path 0.012-0.018 for every path including the default;
|
||||
/// top-1 47 of 48), hence the owner's yes. `default_chunk` is the chunk the DEFAULT path got from the cache sizing (0: none, e.g. no borrowing or an explicit
|
||||
/// --prefill). One GPU, CUDA, a native (IQ) pack only (what was measured), not under STRATA_DEFAULTS=026. The user's own variables win both ways:
|
||||
/// `fused_env_set` (STRATA_PF_FUSED named, either value) leaves the expert path alone and with it the walk (a fused layout declines it anyway);
|
||||
/// `lm_env_set` (STRATA_PREFILL_LAYER_MAJOR named) leaves the walk alone.
|
||||
struct SmallCardPromptPath {
|
||||
bool fused_off = false; ///< read the prompt with the unfused experts (STRATA_PF_FUSED=0 as far as the engine is concerned)
|
||||
bool layer_major = false; ///< and take the layer-major walk for a prompt of two chunks or more (STRATA_PREFILL_LAYER_MAJOR=1)
|
||||
bool any() const { return fused_off || layer_major; }
|
||||
};
|
||||
inline constexpr long long kSmallCardChunkBelow = 8192;
|
||||
inline SmallCardPromptPath small_card_prompt_path(long long default_chunk, bool hip, int stages, bool native_pack, bool v026, bool fused_env_set,
|
||||
bool lm_env_set) {
|
||||
SmallCardPromptPath r;
|
||||
if (hip || v026 || !native_pack || stages > 1 || default_chunk <= 0 || default_chunk >= kSmallCardChunkBelow) return r;
|
||||
if (fused_env_set) return r;
|
||||
r.fused_off = true;
|
||||
r.layer_major = !lm_env_set;
|
||||
return r;
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -0,0 +1,46 @@
|
||||
// strata/core/sm75_series.hpp - the Turing (RTX 20, compute capability 7.5) kernel series: one opt-in switch.
|
||||
//
|
||||
// The Turing kernels of PRs #2069-#2072, #2081, #2091-#2093, #2145-#2146, #2220-#2223, #1821 were measured on one RTX
|
||||
// 2080 Ti (and a CMP 50HX) and are bitwise equal to the kernels they replace. We have no sm_75 card to confirm them, so
|
||||
// they are ON ONLY WHEN ASKED FOR:
|
||||
//
|
||||
// STRATA_SM75_PERF=1 turns on every bitwise Turing kernel of the series on a compute capability 7.5 card.
|
||||
//
|
||||
// Each kernel keeps the author's own switch, which wins over STRATA_SM75_PERF in both directions (=0 off, =1 on, on any
|
||||
// card where the PR said so for tests). Nothing here changes a card that is not a 7.5: the check is the card's compute
|
||||
// capability (STRATA_EMULATE_CC=75 counts, so a 75-virtual build on an sm_86 card runs the series for tests).
|
||||
//
|
||||
// The numerics-changing Turing options are NOT part of this switch and keep their own explicit opt-ins:
|
||||
// STRATA_SELECT_SIMT=1|2 (FP32 tiled block scorer), STRATA_PA_V2T=1 (v2 prompt attention), STRATA_PF_FUSED_SM75=1
|
||||
// (fused int8 prompt experts), STRATA_BF16_TC=1 (FP16 tensor-core projections).
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/emulate.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace strata {
|
||||
|
||||
/// STRATA_SM75_PERF=1 (read once)
|
||||
inline bool sm75_series() {
|
||||
static const bool on = [] {
|
||||
const char* e = std::getenv("STRATA_SM75_PERF");
|
||||
return e != nullptr && std::atoi(e) != 0;
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
/// the device (raw cudaDevAttrComputeCapabilityMajor / Minor) is a Turing card, or emulates one (STRATA_EMULATE_CC=75)
|
||||
inline bool is_sm75(int major, int minor) { return cc_of(major, minor) == 75; }
|
||||
|
||||
/// the default of a bitwise Turing kernel switch: on for a Turing card when STRATA_SM75_PERF=1
|
||||
inline bool sm75_default(int major, int minor) { return is_sm75(major, minor) && sm75_series(); }
|
||||
|
||||
/// a Turing switch with its own variable: `name` set means 0 off / anything else on (Turing only); unset follows the series
|
||||
inline bool sm75_switch(const char* name, int major, int minor) {
|
||||
if (!is_sm75(major, minor)) return false;
|
||||
const char* v = std::getenv(name);
|
||||
return v != nullptr ? std::atoi(v) != 0 : sm75_series();
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -0,0 +1,207 @@
|
||||
// include/strata/kernels/cpu/expert.hpp - P2.S3: the CPU expert path.
|
||||
//
|
||||
// This is the Q2_0 expert kernel promoted out of `bench/micro/cpu_s2.cpp`, which is the instrument that
|
||||
// measured `c` (Memory/LEDGER.md L9/L10: 15.03 ms for one token's full routed set on 6 cores, DRAM-bound at
|
||||
// 44.14 GB/s) and whose P0.T2 parity passes at 1.461e-06.
|
||||
//
|
||||
// IT IS THE SAME CODE, NOT A COPY. Keeping a second implementation next to a validated one is how a project
|
||||
// ends up with two answers and no way to say which is right, so `cpu_s2.cpp` is expected to become a thin
|
||||
// benchmark over these functions. (Until it is, the two exist side by side and this header says so.)
|
||||
//
|
||||
// WHAT MAKES IT FAST, and each of the three was paid for once:
|
||||
//
|
||||
// * `vpdpbusd` (AVX512-VNNI) does four int8 MACs per instruction. The scalar loop it replaces ran at
|
||||
// 9.89 GB/s on one core; VNNI is the reason the 6-core figure is 42.55 GB/s.
|
||||
// * `vpmultishiftqb` (AVX512-VBMI) unpacks the 2-bit codes eight at a time. Its ARGUMENT ORDER is
|
||||
// (control, data) and was determined empirically - the Intel guide states the opposite, and following the
|
||||
// guide produced 43 of 64 wrong codes.
|
||||
// * The row accumulator stays a FLOAT VECTOR and is reduced ONCE at the end of the row. Reducing per
|
||||
// 64-weight block cost more than the dot products themselves: it made the kernel compute-bound at
|
||||
// 21 GB/s instead of DRAM-bound at 32.
|
||||
//
|
||||
// THE CONTRACT THAT MATTERS, because collapsing it is invisible and cannot match ggml's logits: one Q2_0
|
||||
// WEIGHT block is QK=64 weights with one fp16 scale, while one ACTIVATION chunk is QKA=32 elements with
|
||||
// its OWN scale. So a weight block spans TWO activation chunks with two different scales. Using one scale
|
||||
// per weight block is the natural-looking mistake.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/geometry.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
// ---- geometry, all of it fixed by the artifact (tools/verify_q2_0_geometry.py: 202/202 tensors at QK=64) ----
|
||||
inline constexpr int H = strata::core::kCompiledGeometry.n_embd; // 2560 in Flash-Next
|
||||
inline constexpr int FF = strata::core::kCompiledGeometry.n_ff; // expert intermediate width, 640
|
||||
inline constexpr int NE = strata::core::kCompiledGeometry.n_expert; // routed experts per layer, 512
|
||||
static_assert(H == strata::core::kCompiledGeometry.n_embd && FF == strata::core::kCompiledGeometry.n_ff,
|
||||
"the CPU expert path is compiled for core/geometry.hpp");
|
||||
inline constexpr int QK = 64; // QK2_0: weights per fp16 scale
|
||||
inline constexpr int QKA = 32; // QK8_1/QK8_0: ACTIVATION elements per scale
|
||||
inline constexpr int BB = 18; // bytes per 64-weight Q2_0 block: 2 fp16-scale + 16 codes
|
||||
inline constexpr int MAXC = H / QKA; // 80 activation chunks across the widest reduction
|
||||
inline constexpr int ROW_GU = H * 2 / 8; // 640 B of codes per gate/up row
|
||||
inline constexpr int ROW_D = FF * 2 / 8; // 160 B of codes per down row
|
||||
inline constexpr int SC_GU = H / QK; // 40 weight blocks per gate/up row
|
||||
inline constexpr int SC_D = FF / QK; // 10 weight blocks per down row
|
||||
inline constexpr size_t BLOB = 3ull * (H * FF * BB / QK); // 1,382,400
|
||||
|
||||
// ---- the blob's internal layout (one expert) ----
|
||||
inline constexpr size_t O_GU_CODES = 0;
|
||||
inline constexpr size_t O_D_CODES = 2ull * FF * ROW_GU;
|
||||
inline constexpr size_t O_GU_SCALES = O_D_CODES + 1ull * H * ROW_D;
|
||||
inline constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2;
|
||||
|
||||
/// One activation in Strata's planar storage: `QKA` elements per chunk.
|
||||
/// The default legacy quantizer uses FP32 scales and half-away rounding. It is
|
||||
/// not the pinned ggml CPU Q8_0 contract; expert_set_oracle_q8_0 selects that
|
||||
/// experimental contract (FP16-rounded scales and x86 nearest-even codes).
|
||||
///
|
||||
/// The historical function name `act_quant_q8_1` does not describe a native
|
||||
/// ggml block layout. One 64-weight block always spans two 32-element chunks.
|
||||
///
|
||||
/// `hx[k] = scale[k] * sum[k]` is the weight-independent correction the Q2_0 identity needs
|
||||
/// (`sum (c-1) d_w xhat d_x = d_w (d_x*sum(c*xhat) - d_x*sum(xhat))`), precomputed once per layer rather than
|
||||
/// once per row: 640 rows would otherwise recompute it 640 times.
|
||||
struct ActQ {
|
||||
alignas(64) int8_t q[H];
|
||||
float scale[MAXC];
|
||||
int32_t sum[MAXC];
|
||||
float hx[MAXC];
|
||||
int nchunks;
|
||||
/// The AVX-2 "bit-plane" image of `q` (src/kernels/cpu/q2_avx2.cpp explains it), filled only by
|
||||
/// `act_quant_q8_1_avx2` with STRATA_Q2_BITPLANE=1 and read only by `q2_0_gguf_rows_multi_avx2`. Per pair p of 64-value blocks:
|
||||
/// `qp[128p + 32k + 16h + i] = q[128p + 64h + 4i + k]`, `psum[8p + 4h + m]` = the sum of q[128p + 64h + 16m ..
|
||||
/// + 16), `pscale[8p + 2c + e] = scale[4p + c]`. `bp_pairs` is 0 when the image is absent (n % 128 != 0).
|
||||
alignas(32) int8_t qp[H];
|
||||
alignas(32) int32_t psum[H / 16];
|
||||
alignas(32) float pscale[H / 16];
|
||||
int bp_pairs = 0;
|
||||
};
|
||||
|
||||
/// Per-worker scratch. Owned by the caller and passed in, so the token path performs NO allocations
|
||||
/// (P2.T10) - the kernel itself allocates nothing.
|
||||
struct ExpertScratch {
|
||||
ActQ a1;
|
||||
ActQ a2;
|
||||
alignas(64) float ff[FF];
|
||||
};
|
||||
|
||||
/// Runtime CPU feature check. The kernel uses AVX512-VNNI + AVX512-VBMI + AVX512VL, and code compiled with
|
||||
/// `/arch:AVX512` can emit AVX-512 anywhere in its translation unit, so a machine without them must be
|
||||
/// REFUSED rather than silently run. `s2_expert_scalar` is the fallback and exists for tests.
|
||||
struct CpuFeatures {
|
||||
bool avx512f = false;
|
||||
bool avx512bw = false;
|
||||
bool avx512vl = false;
|
||||
bool avx512_vnni = false;
|
||||
bool avx512_vbmi = false;
|
||||
bool usable() const { return avx512f && avx512bw && avx512vl && avx512_vnni && avx512_vbmi; }
|
||||
/// A one-line description of what is missing, or "ok".
|
||||
const char* reason() const;
|
||||
};
|
||||
CpuFeatures cpu_features();
|
||||
|
||||
/// Exits with a clear message if the CPU cannot run `s2_expert_vnni`. Called once at startup, so a user on an
|
||||
/// older CPU learns why at second zero instead of seeing an illegal instruction at token 4000.
|
||||
void cpu_require_expert_support();
|
||||
|
||||
/// Select the pinned x86 Q8_0 activation contract at BOTH expert quantization
|
||||
/// boundaries and the pinned generic CPU Q2_0 dot reduction in all projections.
|
||||
/// Default false preserves the legacy quantizer and eight-lane FP32 reduction.
|
||||
/// Configure before starting worker threads and do not change during a request.
|
||||
/// GPU expert-cache parity is not established for this mode; the driver must
|
||||
/// reject combining it with that cache. No allocation occurs in either mode.
|
||||
void expert_set_oracle_q8_0(bool enabled);
|
||||
|
||||
/// `x` -> `a` in the configured contract. The function name is historical;
|
||||
/// `n` must be a multiple of QKA and at most H. No allocation occurs.
|
||||
void act_quant_q8_1(const float* x, int n, ActQ& a);
|
||||
|
||||
/// One expert: `out(H) = down( swiglu( gate(x), up(x) ) )`, all three projections Q2_0,
|
||||
/// with the configured activation and dot contracts at both quantization boundaries.
|
||||
///
|
||||
/// `blob` is one 1,382,400-byte expert in the pack's layout; `x` is the H-wide input; `out` is H-wide.
|
||||
void s2_expert_vnni(const uint8_t* blob, const float* x, float* out, ExpertScratch& ws);
|
||||
|
||||
/// The same, with the activation ALREADY quantized in the configured contract.
|
||||
/// Workers may share this read-only activation; each must own its scratch/output.
|
||||
///
|
||||
/// This split exists for the pool. A layer runs TEN experts against ONE activation, so quantizing inside
|
||||
/// `s2_expert_vnni` would do the same 2560-element conversion ten times per layer per token - 480 redundant
|
||||
/// conversions per token. P2.S3's work item is `(blob, x-hat quantized, block sums, weight, out)`, and this
|
||||
/// is the entry point that matches it.
|
||||
void s2_expert_vnni_q(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws);
|
||||
|
||||
/// Plan v0.3 P6: ONE expert applied to up to MAXT tokens that were all routed to it (a speculative verify
|
||||
/// window routes ~1.5 tokens to each distinct expert). The 1.38 MB blob is read and its 2-bit codes unpacked
|
||||
/// ONCE per block for all tokens; only the VNNI dot and the accumulation run per token. Every token's output
|
||||
/// is bitwise equal to `s2_expert_vnni_q` on that token (same operation order per token). Legacy activation
|
||||
/// contract only; with `expert_set_oracle_q8_0(true)` it falls back to one `s2_expert_vnni_q` per token.
|
||||
inline constexpr int MAXT = 8;
|
||||
/// Plan v0.3 P4: the expert in row ranges, so several threads can share one expert. `s2_expert_gu_rows` writes
|
||||
/// ff[r] = silu(gate_r . x) * (up_r . x) for r in [r0, r1) (of FF); `s2_expert_down_rows` writes out[r] for r in
|
||||
/// [r0, r1) (of H) from the intermediate's quantized image. Together with `act_quant_q8_1(ff, FF, a2)` in
|
||||
/// between they are exactly `s2_expert_vnni_q`, row for row (same `row_dot`), so the result is bitwise the same.
|
||||
bool expert_oracle_q8_0_enabled();
|
||||
void s2_expert_gu_rows(const uint8_t* blob, const ActQ& a1, float* ff, int r0, int r1);
|
||||
void s2_expert_down_rows(const uint8_t* blob, const ActQ& a2, float* out, int r0, int r1);
|
||||
|
||||
/// Plan v0.3 P6: the row-range kernels for up to MAXT tokens routed to the same expert (legacy contract only).
|
||||
/// Each token's rows are bitwise the single-token `s2_expert_gu_rows` / `s2_expert_down_rows`.
|
||||
void s2_expert_gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* ff, int r0,
|
||||
int r1);
|
||||
void s2_expert_down_rows_multi(const uint8_t* blob, const ActQ* const* a2, int n_tokens, float* const* out, int r0,
|
||||
int r1);
|
||||
|
||||
struct ExpertScratchMulti {
|
||||
ActQ a2[MAXT];
|
||||
alignas(64) float ff[MAXT][FF];
|
||||
ExpertScratch single; // the oracle-contract fallback
|
||||
};
|
||||
void s2_expert_vnni_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* out,
|
||||
ExpertScratchMulti& ws);
|
||||
|
||||
/// The scalar transcription of ggml's formula - NOT a second opinion, but the ORACLE the VNNI path is checked
|
||||
/// against, and the only path available on a CPU without AVX-512.
|
||||
///
|
||||
/// `quant_acts` makes the oracle consume the SAME INT8 activation values the VNNI path uses, **at BOTH
|
||||
/// stages**. With it OFF the oracle is exact-FP32-activation and the gap between them IS the activation
|
||||
/// contract; with it ON the two differ only by FP32 evaluation order, so a small gap there proves the kernel
|
||||
/// itself correct. That separation is the whole point of P0.T2 and it is why this parameter exists rather
|
||||
/// than two functions.
|
||||
///
|
||||
/// CORRECTION TO THE ORIGINAL: `bench/micro/cpu_s2.cpp`'s comment says "at both stages" but its code
|
||||
/// quantizes only the intermediate, leaving the gate/up projections on raw f32 `x`. That is invisible when
|
||||
/// the caller passes an already-quantized input - which the engine does - and shows up as a ~1.2% gap when it
|
||||
/// does not, which reads as a kernel bug and is not one. This version quantizes both.
|
||||
/// Plan v0.3 P6: rows [r0, r1) of a Q2_0 matrix in the GGUF block layout (18 bytes per 64 weights, `row_bytes`
|
||||
/// per row, `nblocks` blocks each) against `nt` activations: out[t][r].
|
||||
void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
/// The same two for CPUs without AVX-512 (src/kernels/cpu/q2_avx2.cpp, compiled for AVX2 only).
|
||||
void q2_0_gguf_rows_multi_avx2(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
/// STRATA_Q2_BITPLANE=1 (read once): the AVX-2 Q2_0 kernel reads the bit-plane image instead of the legacy one.
|
||||
bool q2_bitplane_enabled();
|
||||
/// The pre-bit-plane AVX-2 kernel (the default), kept for A/B and parity.
|
||||
void q2_0_gguf_rows_multi_avx2_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
/// The same rows with AVX-VNNI on or off, not as cpu_avxvnni_ok() says (tests and benches; on only where it holds).
|
||||
void q2_0_gguf_rows_multi_avx2_v(bool vnni, const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a,
|
||||
int nt, float* const* out, int r0, int r1);
|
||||
void act_quant_q8_1_avx2(const float* x, int n, ActQ& a);
|
||||
/// The same for CPUs with AVX but no AVX2 (src/kernels/cpu/q2_avx1.cpp, the third rung of q2_rows_any /
|
||||
/// act_quant_any, issue #1699): same arithmetic, 128-bit integer lanes, mul+add instead of FMA (last bits),
|
||||
/// software fp16 conversion. Called only behind cpu_avx1_ok() && !cpu_avx2_ok().
|
||||
void q2_0_gguf_rows_multi_avx1(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
void q2_0_gguf_rows_multi_avx1_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
void act_quant_q8_1_avx1(const float* x, int n, ActQ& a);
|
||||
|
||||
void s2_expert_scalar(const uint8_t* blob, const float* x, float* out, bool quant_acts);
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
// include/strata/kernels/cpu/expert_layout.hpp - plan v0.3 P6: where each routed expert lives in experts.bin.
|
||||
//
|
||||
// A Q2_0 pack (tools/strata_pack.py) has one blob size for every layer, `BLOB`, in the Strata expert form. A
|
||||
// native pack (tools/iq_pack.py, the IQ2_XS / IQ3_XXS files) keeps each expert's raw GGUF slices, so the blob
|
||||
// size and the formats change from layer to layer; `native_experts.txt` says how. Everything that touches an
|
||||
// expert blob - the arena, the VRAM tier, the prompt path, the CPU pool, the GPU window - asks this table.
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/cpu/expert.hpp"
|
||||
#include "strata/kernels/cpu/native_expert.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
struct ExpertLayout {
|
||||
bool native = false;
|
||||
int64_t n_layers = 0, n_expert = NE;
|
||||
std::vector<NativeFmt> fmt; ///< per layer (native packs)
|
||||
std::vector<uint64_t> offset, bytes; ///< per layer: where its 512 blobs start, bytes per blob
|
||||
/// Plan v0.3 P6: per layer, the absolute offsets of the gate / up / down tensors in their GGUF files, so the
|
||||
/// arena can be filled from the GGUF itself when the pack has no experts.bin (3 x n_layers, 0 = unknown).
|
||||
std::vector<uint64_t> gguf_off;
|
||||
/// Per layer PER ROLE (3 x n_layers, `3 * layer + role`, matching `gguf_off`), the GGUF file - a name beside
|
||||
/// the --native shard - that holds that role's tensor. Empty = the --native shard itself. Per role because a
|
||||
/// shard boundary can fall inside a layer: Unsloth's UD-Q4_K_XL has layer 11's down in shard 2 and its gate
|
||||
/// and up in shard 3 (native_experts.txt v4, the `gate,up,down` shard column).
|
||||
std::vector<std::string> gguf_file;
|
||||
int version = 0; ///< native_experts.txt's header version (0 = none given)
|
||||
uint64_t max_blob = BLOB;
|
||||
uint64_t total = 0; ///< experts.bin size
|
||||
|
||||
uint64_t blob_bytes(int64_t layer) const { return native ? bytes[(size_t) layer] : (uint64_t) BLOB; }
|
||||
uint64_t layer_offset(int64_t layer) const {
|
||||
return native ? offset[(size_t) layer] : (uint64_t) layer * (uint64_t) n_expert * (uint64_t) BLOB;
|
||||
}
|
||||
uint64_t blob_offset(int64_t layer, int64_t expert) const {
|
||||
return layer_offset(layer) + (uint64_t) expert * blob_bytes(layer);
|
||||
}
|
||||
};
|
||||
|
||||
/// Plan v0.3 P6: whether this CPU (and its OS) runs the AVX-512 kernels (F, BW, VL, VNNI, VBMI). Probed in a
|
||||
/// file compiled without AVX-512, so asking is safe everywhere; STRATA_FORCE_AVX2=1 answers no (for tests).
|
||||
bool cpu_avx512_ok();
|
||||
/// The same probes with VBMI required only (the multishift unpack and other byte-permute shuffles): a CPU may run
|
||||
/// every other feature the kernels use and miss it (Cascade Lake Xeon).
|
||||
bool cpu_vbmi_ok();
|
||||
/// AVX-512F + DQ + BW + VL + VNNI, VBMI NOT required: the dpbusd row dots, the q8 quantizer and the dq/bw arithmetic
|
||||
/// need no byte-permute shuffles (the q2 unpack's op has a substitute in expert.cpp). A CPU this answers yes on
|
||||
/// used to run every expert through the AVX-2 fallback. Without VBMI, STRATA_VNNI_TIER=1 opts in; unset keeps
|
||||
/// the AVX-2 rows' rounding. STRATA_FORCE_AVX2 and STRATA_FORCE_ISA still cap this probe.
|
||||
bool cpu_vnni_ok();
|
||||
/// Scattered pieces: the copy above is a declaration only (defined in expert.cpp, the AVX-512 TU, because it reads
|
||||
/// its STRATA_CPU_YMM switch): whether the 512-bit q2 row dot may run at all (VNNI and not the YMM env).
|
||||
bool q2_rows_512_ok();
|
||||
/// Whether this CPU runs AVX-512F + AVX-512BW + AVX-512VL + AVX-512DQ (e.g. Skylake-X i9-9920X) for iq_avx512.cpp.
|
||||
bool cpu_avx512bw_ok();
|
||||
/// Whether this CPU (and its OS) runs the AVX2 kernels (AVX, AVX2, FMA, F16C): the floor of every expert kernel
|
||||
/// (q2_avx2.cpp, iq_avx2.cpp, and ggml-cpu in the portable build). STRATA_FORCE_AVX2 does not change it.
|
||||
bool cpu_avx2_ok();
|
||||
/// Whether this CPU (and its OS) runs AVX (Sandy Bridge and newer): the AVX1 router dot (kq_avx1.cpp) and ggml-cpu in
|
||||
/// a STRATA_ISA_FLOOR=avx build. The other expert rows then run on ggml-cpu (experimental, slow).
|
||||
bool cpu_avx1_ok();
|
||||
/// SSE4.2 + POPCNT: ggml-cpu in a STRATA_ISA_FLOOR=none build.
|
||||
bool cpu_sse42_ok();
|
||||
/// STRATA_FORCE_ISA=avx2|avx|sse caps the probes above (3 = no cap, 2 = AVX2, 1 = AVX, 0 = SSE4.2), so the older-CPU
|
||||
/// paths run on any PC: tests and the experimental builds' checks. ggml-cpu keeps what it was compiled for.
|
||||
int cpu_isa_cap();
|
||||
/// The experimental older-CPU build this engine is ("avx", "sse4.2"), or "" for the normal build (AVX2 floor).
|
||||
const char* isa_floor_build();
|
||||
/// STRATA_IQ256_GATHER, the AVX-2 i-quant kernels' gathered grid decode (iq_avx2.cpp): -1 unset (auto, see
|
||||
/// cpu_gather_fast_here), 0 the scalar decode on every core, 1 the gathered one on every core.
|
||||
int iq256_gather_setting();
|
||||
/// Whether this CPU's performance cores gather the IQ grid entries faster than they assemble them from scalar loads:
|
||||
/// an Intel CPU with AVX-VNNI, i.e. Alder Lake / Sapphire Rapids or newer, and not one of the E-core-only parts.
|
||||
/// The older Intel cores gather slowly (Haswell, Broadwell) or under the Downfall (GDS) microcode (Skylake to Tiger
|
||||
/// Lake), AMD Zen 2/3 gather slowly, and Zen 4/5 run the AVX-512 kernels. STRATA_FORCE_ISA answers no.
|
||||
bool cpu_gather_fast();
|
||||
/// cpu_gather_fast() and the CALLING THREAD runs on a performance core: CPUID 1Ah core type 40h on a hybrid CPU (its
|
||||
/// E-cores, 20h, gather slower than they assemble). Probed once per thread: the pool pins each worker to one core.
|
||||
bool cpu_gather_fast_here();
|
||||
/// Whether the AVX-2 expert kernels take their AVX-VNNI forms (vpdpwssd / vpdpbusd: Alder Lake, Sapphire Rapids and
|
||||
/// later, P- and E-cores alike; the same integer sums): cpu_avx2_ok() and CPUID 7.1:EAX[4], not capped by
|
||||
/// STRATA_FORCE_ISA, and not an older-CPU build (STRATA_ISA_FLOOR, which stays on its floor and AVX2).
|
||||
/// STRATA_NO_AVXVNNI=1 answers no.
|
||||
bool cpu_avxvnni_ok();
|
||||
/// Whether a native pack's layer of this ggml type runs on Strata's own Q2_0 kernels (AVX-512 / AVX2, and the AVX1
|
||||
/// rung of q2_rows_any / act_quant_any on a CPU with AVX but no AVX2: Sandy / Ivy Bridge). Only a CPU without AVX
|
||||
/// (STRATA_ISA_FLOOR=none) takes ggml-cpu's own Q2_0 vec_dot, which on an i7-3770 took 0.98 ms per expert at one
|
||||
/// token against 0.52 ms for the AVX1 rows (0.42 with STRATA_Q2_BITPLANE=1; kq_cpu_bench --pairs q2_0/q2_0).
|
||||
inline bool q2_native_kernels(int type) { return type == 42 && (cpu_avx2_ok() || cpu_avx1_ok()); }
|
||||
/// The CPU's brand string (CPUID 0x80000002..4), for messages; "unknown" when it has none.
|
||||
std::string cpu_name();
|
||||
/// Q2_0 GGUF rows / activation quantizer on the kernels this CPU has.
|
||||
void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out,
|
||||
int r0, int r1);
|
||||
void act_quant_any(const float* x, int n, ActQ& a);
|
||||
/// The same dispatch, always the pre-bit-plane kernel (tests and A/B; the bit-plane switch off by construction).
|
||||
void q2_rows_any_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out,
|
||||
int r0, int r1);
|
||||
|
||||
/// The process-wide layout (canonical Q2_0 until `expert_layout_load` finds a native pack).
|
||||
const ExpertLayout& expert_layout();
|
||||
/// Reads `<pack_dir>/native_experts.txt` when it exists (a native pack), else sets the canonical layout.
|
||||
/// Versions up to kExpertLayoutVersion are read; a newer one is refused (a newer packer wrote it).
|
||||
bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err);
|
||||
/// The newest native_experts.txt this engine reads. v4 = v3 plus the per-role shard column `gate,up,down`,
|
||||
/// written only when some layer's roles are in different shards (every other pack stays v3, byte for byte).
|
||||
/// v5 = v4 plus `hadamard.txt` beside it: Hadamard-folded experts (hadamard.hpp), written only for such models,
|
||||
/// so an engine that cannot rotate the activations refuses the pack instead of running it wrong.
|
||||
inline constexpr int kExpertLayoutVersion = 5;
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
// include/strata/kernels/cpu/native_expert.hpp - plan v0.3 P6: one routed expert in its GGUF form on the CPU.
|
||||
//
|
||||
// The IQ2_XS / IQ3_XXS model files keep their experts in i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS,
|
||||
// IQ3_S gate/up; Q2_0 or IQ4_NL down) whose values cannot be re-expressed in the Q2_0 pack form. A native expert
|
||||
// blob is the three GGUF slices back to back, [gate rows | up rows | down rows]. Activations use the weight type's
|
||||
// ggml `vec_dot_type`; dispatch selects a format-specific kernel or ggml's per-token dot. The arithmetic mode
|
||||
// controls whether grouping tokens may change the selected row arithmetic.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
#include "strata/core/geometry.hpp"
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
/// Bytes of the quantized activation of a row of `n` values: the larger of Q8_K (292 bytes per 256) and a 32-block
|
||||
/// format at 36 bytes per 32 (Q8_1 and friends).
|
||||
constexpr size_t native_act_bytes_for(int64_t n) {
|
||||
const size_t q8k = (size_t) (n / 256) * 292, q81 = (size_t) (n / 32) * 36;
|
||||
return q8k > q81 ? q8k : q81;
|
||||
}
|
||||
/// Bytes of the largest quantized activation any native layer uses (2560 values as Q8_K: 10 x 292); never below the
|
||||
/// 4096 of the Flash-Next engine, and it grows with the compiled hidden size (4096 values need 4672).
|
||||
inline constexpr size_t kNativeActBytes =
|
||||
native_act_bytes_for(strata::core::kCompiledGeometry.n_embd) > 4096 ? native_act_bytes_for(strata::core::kCompiledGeometry.n_embd) : 4096;
|
||||
/// Bytes of the largest quantized down activation (640 values as Q8_0: 20 x 34, or Q8_K 3 x 292); never below 1024,
|
||||
/// and it grows with the compiled expert width (1024 values as Q8_K need 1168).
|
||||
inline constexpr size_t kNativeHBytes =
|
||||
native_act_bytes_for(strata::core::kCompiledGeometry.n_ff) > 1024 ? native_act_bytes_for(strata::core::kCompiledGeometry.n_ff) : 1024;
|
||||
|
||||
/// Arithmetic fixed for one pool batch. WindowInvariant preserves the legacy singleton result at every width.
|
||||
enum class NativeArithmetic { Default, WindowInvariant };
|
||||
|
||||
/// One layer's native expert geometry.
|
||||
struct NativeFmt {
|
||||
int gu_type = -1, d_type = -1; ///< ggml types of gate/up and of down
|
||||
int gu_act = -1, d_act = -1; ///< their vec_dot_type (the activation formats)
|
||||
int64_t n_embd = 0, n_ff = 0;
|
||||
size_t gu_row = 0, d_row = 0; ///< bytes per weight row
|
||||
size_t up_off = 0, down_off = 0; ///< inside the blob
|
||||
size_t bytes = 0; ///< the whole blob
|
||||
size_t act_bytes = 0, h_bytes = 0; ///< quantized activation sizes (n_embd of gu_act, n_ff of d_act)
|
||||
/// NVFP4 (ggml type 40) only: the blob ends with {s_gate, s_up, s_down, 0} at this offset, the per-expert
|
||||
/// weight_scale_2 the block format has no room for (tools/iq_pack.py). 0 = no tail. Each scale goes on its own
|
||||
/// projection's FP32 output: gate * s_gate, up * s_up, down * s_down. Do not fold s_down into up: the hidden
|
||||
/// drops to ~1e-5 and its q8 block scale becomes an FP16 subnormal (expert error 2-12% instead of 1.1%).
|
||||
size_t tail_off = 0;
|
||||
/// prism.hadamard (hadamard.hpp): the experts of this layer are stored in a rotated basis, and
|
||||
/// native_quant_act / native_quant_h apply y = H_block (signs * x) before quantizing. had_block 0 = none.
|
||||
int had_block = 0;
|
||||
bool had_gu = false, had_d = false;
|
||||
int layer = -1; ///< the layer this format belongs to (set by expert_layout_load; STRATA_ACT_DUMP only)
|
||||
const float* gu_signs = nullptr; ///< n_embd signs for x (nullptr: identity)
|
||||
const float* d_signs = nullptr; ///< n_ff signs for h (nullptr: identity)
|
||||
};
|
||||
constexpr int kNvfp4Type = 40;
|
||||
constexpr size_t kNvfp4Tail = 16;
|
||||
|
||||
/// Whether this build has the ggml-cpu path.
|
||||
bool native_experts_available() noexcept;
|
||||
/// Fills `f` for a layer; false (with a reason) when ggml-cpu has no dot product for a type.
|
||||
bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err);
|
||||
|
||||
/// x (n_embd floats) -> the gate/up activation (act_bytes), rotated first when the layer is Hadamard-folded.
|
||||
void native_quant_act(const NativeFmt& f, const float* x, void* dst);
|
||||
/// h (n_ff floats) -> the down activation (h_bytes), rotated first when the layer is Hadamard-folded.
|
||||
void native_quant_h(const NativeFmt& f, const float* h, void* dst);
|
||||
|
||||
/// From how many tokens native_gu_rows gives this gate/up type to a multi-token kernel (#152; ggml-cpu's per-token dot
|
||||
/// below that). 1: a token's rows are the same alone and in any group.
|
||||
int native_gu_mt_min(int gu_type);
|
||||
/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]) for rows r in [r0, r1), `nt` tokens.
|
||||
void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt, float* const* ff,
|
||||
int r0, int r1);
|
||||
/// out[t][r] = down_r . hq[t] for rows r in [r0, r1).
|
||||
void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt, float* const* out,
|
||||
int r0, int r1);
|
||||
|
||||
/// Same per-token result as the corresponding legacy nt=1 call on this build and CPU.
|
||||
/// Kernels that already satisfy this contract retain their grouped execution.
|
||||
void native_gu_rows_invariant(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt,
|
||||
float* const* ff, int r0, int r1);
|
||||
void native_down_rows_invariant(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -0,0 +1,55 @@
|
||||
// include/strata/kernels/dp4a.hpp - the two instructions the kernels use that Pascal (sm_60) does not have.
|
||||
//
|
||||
// The engine is written for compute capability 7.5 and newer and refuses older cards at CMake configure time
|
||||
// (a Pascal build passes -DSTRATA_EXPERIMENTAL_SM60=ON). A GP100-class card is compute capability 6.0, which is
|
||||
// missing exactly two things the i-quant kernels rely on:
|
||||
//
|
||||
// * `__dp4a`, a byte-wise dot product, available from 6.1 (Pascal GP10x/GV11x). The reference for its
|
||||
// fallback is llama.cpp's own (`ggml/src/ggml-cuda/common.cuh`), since the kernels in this directory are
|
||||
// transcribed from llama.cpp's vecdotq.cuh and that wrapper's operands are the same sites: it reinterprets
|
||||
// the operands as SIGNED bytes and accumulates in int32, which is what `__dp4a` does for these calls. The
|
||||
// fallback below computes exactly that with four PTX `vmad` byte-select instructions, so it is bit-exact
|
||||
// rather than merely close (tools/sm60_dp4a_check.cu checks it against the byte-wise form).
|
||||
// * `__nanosleep`, available from 7.0 (Volta). It only paces single-thread doorbell waits, so a loop that
|
||||
// spins without it is correct, merely busier.
|
||||
//
|
||||
// Both are compile-time selections on `__CUDA_ARCH__`, so one source tree builds for Pascal and for RTX
|
||||
// 20/30/40/50 without a #define at the call sites. A HIP build never takes either fallback: `__CUDA_ARCH__` is
|
||||
// undefined there, so `STRATA_DP4A` is `__dp4a` (which `hip_compat/intrinsics.hpp` provides) and the pause is
|
||||
// HIP's own `__nanosleep`.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
#include <cuda_runtime.h> // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a)
|
||||
#endif
|
||||
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610
|
||||
__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) {
|
||||
// PTX vmad with byte selectors: compiles to four VMAD.S8.S8 (cuobjdump -sass), no byte extraction.
|
||||
// Bit-exact with the byte-wise form it replaces: 1.07e9 cases (edge bytes, every per-lane byte pair, random),
|
||||
// 0 mismatches, ~2.2x faster in isolation on a Tesla P100 (tools/sm60_dp4a_check.cu).
|
||||
int r = c;
|
||||
asm("vmad.s32.s32.s32 %0, %1.b0, %2.b0, %0;\n\t"
|
||||
"vmad.s32.s32.s32 %0, %1.b1, %2.b1, %0;\n\t"
|
||||
"vmad.s32.s32.s32 %0, %1.b2, %2.b2, %0;\n\t"
|
||||
"vmad.s32.s32.s32 %0, %1.b3, %2.b3, %0;"
|
||||
// The first instruction writes r before the remaining instructions
|
||||
// have read a/b. Equal-valued operands must not share its register.
|
||||
: "+&r"(r) : "r"(a), "r"(b));
|
||||
return r;
|
||||
}
|
||||
#define STRATA_DP4A(a, b, c) strata_dp4a((a), (b), (c))
|
||||
#else
|
||||
#define STRATA_DP4A(a, b, c) __dp4a((a), (b), (c))
|
||||
#endif
|
||||
|
||||
/// Yield the thread while a doorbell flag is being polled. The length of the pause is a backoff hint, not a
|
||||
/// contract, and only pre-Volta CUDA has no `__nanosleep` at all.
|
||||
__device__ __forceinline__ void strata_spin_pause() {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 700
|
||||
// sm_6x: the loop spins. Every call site is a single-thread doorbell wait, so nothing else is delayed.
|
||||
#else
|
||||
__nanosleep(100);
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// include/strata/kernels/gfx_arch.hpp - which AMD architecture names the gfx11 matrix-core code (and the gfx12 native
|
||||
// prompt-expert kernels) was built for.
|
||||
//
|
||||
// The WMMA kernels select their intrinsic with `#if defined(__gfx1100__) || ... || defined(__gfx1151__)`: a gfx11 part
|
||||
// outside that list (gfx1152, ...) gets an empty or trapping body. The runtime gates therefore match the SAME
|
||||
// list, not the "gfx11" prefix, so such a part falls back to hipBLASLt / the portable kernels instead of launching code
|
||||
// that is not there. Pure string matching (no HIP headers), usable from host code of any build.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// `gcn` is hipDeviceProp_t::gcnArchName ("gfx1151", or "gfx1151:sramecc-:xnack-"): true when it is exactly `name`.
|
||||
inline bool gfx_arch_is(const char* gcn, const char* name) {
|
||||
if (gcn == nullptr) return false;
|
||||
const std::size_t n = std::strlen(name);
|
||||
return std::strncmp(gcn, name, n) == 0 && (gcn[n] == '\0' || gcn[n] == ':');
|
||||
}
|
||||
|
||||
/// Discrete RDNA3 desktop / workstation GPUs (RX 7900 XTX / XT / GRE / W7900 = gfx1100,
|
||||
/// RX 7800 XT / 7700 XT = gfx1101, RX 7600 / 7600 XT = gfx1102).
|
||||
inline bool gfx_arch_is_discrete_rdna3(const char* gcn) {
|
||||
return gfx_arch_is(gcn, "gfx1100") || gfx_arch_is(gcn, "gfx1101") || gfx_arch_is(gcn, "gfx1102");
|
||||
}
|
||||
|
||||
/// The gfx11 targets the matrix-core kernels (prompt GEMM / attention / scorer / fused experts) are compiled for.
|
||||
inline bool gfx_arch_is_gfx11_wmma(const char* gcn) {
|
||||
return gfx_arch_is(gcn, "gfx1100") || gfx_arch_is(gcn, "gfx1101") || gfx_arch_is(gcn, "gfx1102") || gfx_arch_is(gcn, "gfx1103") ||
|
||||
gfx_arch_is(gcn, "gfx1150") || gfx_arch_is(gcn, "gfx1151");
|
||||
}
|
||||
|
||||
/// The gfx12 (RDNA4) targets the gfx12 matrix-core kernels are compiled for (`#if defined(__gfx1200__) ||
|
||||
/// defined(__gfx1201__)`): the R9700 / 9070 (XT) are gfx1201, the 9060 (XT) gfx1200.
|
||||
inline bool gfx_arch_is_gfx12_wmma(const char* gcn) { return gfx_arch_is(gcn, "gfx1200") || gfx_arch_is(gcn, "gfx1201"); }
|
||||
|
||||
/// Strix Halo (Ryzen AI Max, RDNA3.5): the part the gfx1151 defaults (docs/STRIX_HALO.md) are measured on.
|
||||
inline bool gfx_arch_is_gfx1151(const char* gcn) { return gfx_arch_is(gcn, "gfx1151"); }
|
||||
|
||||
/// RDNA4 (Radeon AI PRO R9700 = gfx1201, RX 9070 / 9070 XT = gfx1201, RX 9060 = gfx1200).
|
||||
inline bool gfx_arch_is_gfx12(const char* gcn) { return gfx_arch_is(gcn, "gfx1200") || gfx_arch_is(gcn, "gfx1201"); }
|
||||
|
||||
} // namespace strata::kernels
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
// include/strata/kernels/i8_expert_rule.hpp - when a prompt layer's expert groups take our own int8 dot-product kernels (native_expert_i8,
|
||||
// src/kernels/cuda/i8_expert.cuh) in place of MMQ.
|
||||
//
|
||||
// STRATA_EXPERT_I8 = 1 asks for them on any card, 0 turns them off, unset (or empty) leaves the card class to decide: on the HIP cards gfx1030 / gfx1031 /
|
||||
// gfx1032 (RDNA2: no matrix cores, the byte dot product `v_dot4_i32_i8` only) the covered formats take them by default. Measured on the RX 6700 XT
|
||||
// (gfx1031, one MoE layer of Flash-Next's shape, tokens 2,048 / 8,192 / 20,000): 1.10 - 1.35 times MMQ for the IQ2_S / IQ2_XXS packs with a Q2_0 down and
|
||||
// for the IQ3_S / IQ3_XXS packs with an IQ4_NL down (par/RESULTS-OWN-I8.md). gfx1034 / 1035 / 1036 were not compiled or timed: they stay on MMQ.
|
||||
//
|
||||
// Both kinds of call keep the size floor: a launch of experts averaging fewer than kI8MinGroupEntries entries stays on today's path (no timing below
|
||||
// 2,048 tokens exists on this class; the P100 / V100 numbers say the grouped / MMQ kernels win at 300 tokens). Pure functions: no GPU and no
|
||||
// environment read here (the caller passes the variable's text and the device's gcnArchName), so the rule is unit-tested without a card.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "strata/kernels/gfx_arch.hpp"
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// Groups (a launch of up to 16 experts) averaging fewer entries than this keep today's path.
|
||||
inline constexpr int64_t kI8MinGroupEntries = 256;
|
||||
|
||||
/// The RDNA2 parts that take the int8 kernels by default. `gcn` is hipDeviceProp_t::gcnArchName (a CUDA card has none: nullptr or "").
|
||||
inline bool gfx_arch_is_gfx103x_i8(const char* gcn) {
|
||||
return gfx_arch_is(gcn, "gfx1030") || gfx_arch_is(gcn, "gfx1031") || gfx_arch_is(gcn, "gfx1032");
|
||||
}
|
||||
|
||||
/// STRATA_EXPERT_I8 read as a state: 1 = on (any non-empty text that does not start with '0'), 0 = off (starts with '0'), -1 = not set (null or empty).
|
||||
inline int i8_switch_parse(const char* text) {
|
||||
return text == nullptr || text[0] == '\0' ? -1 : (text[0] == '0' ? 0 : 1);
|
||||
}
|
||||
|
||||
/// A build without llama.cpp's MMQ (-DSTRATA_MMQ=OFF, or HIP without STRATA_PREFILL_MMQ; prefill.cpp's STRATA_PF_OWN_ONLY): the int8 kernels are the default prompt-expert kernels on every
|
||||
/// card that covers the layer's formats, because MMQ is what they replace; without them the layer runs each expert on the FP16 path (4 - 5 times slower on an RX 6700 XT). `state` is
|
||||
/// i8_switch_parse's answer; a value the user set (0 or 1) is kept, an unset switch reads as 1 in such a build. "Default on" is not "forced": see i8_order_allows.
|
||||
inline int i8_switch_effective(int state, bool mmq_free) { return state == -1 && mmq_free ? 1 : state; }
|
||||
|
||||
/// Does the build / card class alone (switch not set) take the int8 kernels: the RDNA2 class, or any card in a build without MMQ.
|
||||
inline bool i8_expert_class_default(int state, const char* gcn, bool mmq_free = false) { return state == -1 && (mmq_free || gfx_arch_is_gfx103x_i8(gcn)); }
|
||||
|
||||
/// The order of the prompt-expert paths for one layer of one chunk: the fused kernels (a long chunk on a layer they cover) and the staged group entry (a short chunk, the fused kernels'
|
||||
/// entry) come first, the int8 kernels take what is left, the FP16 path what even they do not cover. This holds for a value the user set too (STRATA_EXPERT_I8=1 asks for the int8 kernels
|
||||
/// where nothing faster takes the layer: R9700, 2,048 tokens, fused 1,144.6 ms against int8 1,624.5); it is the order prefill.cpp's `i8_l` condition has.
|
||||
inline bool i8_order_allows(bool fused_takes, bool staged_takes) { return !fused_takes && !staged_takes; }
|
||||
|
||||
inline bool i8_expert_takes(int state, const char* gcn, int64_t group_entries, bool supported); // (defined below)
|
||||
/// The whole question for one layer of one chunk, as the pure rule (the engine asks the two halves where it has them: i8_order_allows in prefill.cpp, i8_expert_takes in iq_kernels.cu).
|
||||
inline bool i8_layer_takes(int raw_state, bool mmq_free, const char* gcn, int64_t group_entries, bool supported, bool fused_takes, bool staged_takes) {
|
||||
return i8_order_allows(fused_takes, staged_takes) && i8_expert_takes(i8_switch_effective(raw_state, mmq_free), gcn, group_entries, supported);
|
||||
}
|
||||
|
||||
/// Do the expert groups of a layer take `native_expert_i8`? `state` = i8_switch_parse(getenv), `gcn` the device's gcnArchName, `group_entries` the entries
|
||||
/// of one launch on average, `supported` = native_expert_i8_supported(layout) (formats, sizes, the device's shared memory).
|
||||
inline bool i8_expert_takes(int state, const char* gcn, int64_t group_entries, bool supported) {
|
||||
if (state == 0 || !supported || group_entries < kI8MinGroupEntries) return false;
|
||||
return state == 1 || i8_expert_class_default(state, gcn);
|
||||
}
|
||||
|
||||
// The few-rows route. A layer whose experts average fewer routed rows than a crossing runs on the grouped kernels (native_expert_grouped, no shared-memory
|
||||
// staging: one launch pair per 16 experts like the int8 kernel's, the q8_1 image of the rows made by quantize_q8_1_rows); from the crossing up it runs on the
|
||||
// int8 kernel. Measured on one MoE layer of Flash-Next's shape (average rows per expert where both take equal time), WITHOUT the 8-entry slices (N8): Tesla P100 (sm_60) 8.4, A4000 10.2 - 11.7,
|
||||
// RX 6700 XT 10.2 - 10.8, R9700 11.7 (par/RESULTS-I8-RESEARCH.md); WITH them (STRATA_I8_N8, on by default in this range, see i8_n8_takes) P100 5.7 - 5.8, A4000 6.9 - 7.4, R9700 6.9 - 7.4 (par/RESULTS-I8-MMQOFF.md). The limits below are the crossings with N8; the int8 side never loses more than 5 %.
|
||||
// Without the route the int8 kernel keeps the size floor above (256 entries per group of 16 experts = 16 rows per expert) and the layers under it stay on today's path.
|
||||
inline constexpr int kI8FewRowsDefault = 7; ///< every card but the Tesla P100 (10 with STRATA_I8_N8=0)
|
||||
inline constexpr int kI8FewRowsSm60 = 6; ///< compute capability 6.0 (the P100): its crossing is lower (8 with STRATA_I8_N8=0)
|
||||
|
||||
/// STRATA_I8_FEWROWS read as the limit: not set (or empty, or text that is no number) = the card class's own `class_default`, 0 = no route, N = a limit of N rows per expert.
|
||||
inline int i8_fewrows_limit(const char* text, int class_default) {
|
||||
if (text == nullptr || text[0] == '\0') return class_default;
|
||||
if (text[0] < '0' || text[0] > '9') return class_default;
|
||||
long v = 0;
|
||||
for (const char* p = text; *p >= '0' && *p <= '9'; ++p) {
|
||||
v = v * 10 + (*p - '0');
|
||||
if (v > 100000) break;
|
||||
}
|
||||
return (int) v;
|
||||
}
|
||||
|
||||
/// The class's default limit: the P100 (compute capability 6.0) 6, every other card 7.
|
||||
inline int i8_fewrows_class_default(int cc_major, int cc_minor) { return cc_major == 6 && cc_minor == 0 ? kI8FewRowsSm60 : kI8FewRowsDefault; }
|
||||
|
||||
/// Does a layer with `rows` routed rows over `experts` experts (those with at least one row) take the grouped kernels? limit 0 = the route is off.
|
||||
inline bool i8_fewrows_takes(int limit, int64_t rows, int64_t experts) { return limit > 0 && experts > 0 && rows < (int64_t) limit * experts; }
|
||||
|
||||
// The 8-entry slices of the tile-2..4 int8 kernel (N8: two weight rows and one entry of each 8-entry slice per thread; bit-identical output). Measured on the A4000, the P100 and
|
||||
// the R9700 (par/RESULTS-I8-MMQOFF.md, I8 column of the expert-paths bench, Flash-Next's shape, IQ2_XXS / Q2_0 and IQ3_S / IQ4_NL): tile 2 (up to 39 entries per expert on average, about
|
||||
// 1,950 tokens) 23 - 33 % faster at 100 - 300 tokens, 12 - 17 % at 1,000 and 6 - 13 % at 1,500 on all three; tile 3 (2,048 tokens) 3 - 6 % faster on the A4000 and the P100 but
|
||||
// 1.6 - 2.9 % SLOWER on the R9700. So the default is tile 2 only; STRATA_I8_N8=1 asks for tiles 2 - 4, STRATA_I8_N8=0 for none.
|
||||
/// STRATA_I8_N8 read as a state (1 / 0 / -1 not set), the tile code the call settled on (2, 3, 4 = rows of 16 entries per thread; 8 = the 128-entry kernel, which has no 8-entry form).
|
||||
inline bool i8_n8_takes(int state, int tile) {
|
||||
if (state == 0) return false;
|
||||
return state == 1 ? tile >= 2 && tile <= 4 : tile == 2;
|
||||
}
|
||||
|
||||
// Volta (compute capability 7.0: 96 KB of shared memory per multiprocessor, no int8 matrix cores, so every routed expert of a prompt runs on these kernels). The tile the
|
||||
// other cards take from 96 entries a group on average (tile 8, 128 x 128, 54-62 KB) and tile 4 (51-59 KB) leave one block of 8 warps per multiprocessor there; tiles 2 and 3 of
|
||||
// the IQ3 formats (43 / 48 KB) run two. Tesla V100-SXM2 32 GB, one layer of Flash-Next's shape, uniform routing, MMQ time / int8 time (above 1: ours faster), the call's
|
||||
// own pick against tile 3 (phaseA-tests/tune0216, bench1-v100): IQ3_S / IQ4_NL 0.745 -> 0.949 at 8,192 tokens and 0.795 -> 0.820 at 26,000, IQ3_XXS / IQ4_NL 0.721 -> 0.955 and
|
||||
// 0.795 -> 0.831; output bits equal at every tile (the tile only groups entries). The big-grid formats (IQ2_S's 8 KB grid table) read their grid from global memory there
|
||||
// (I8Smem GG: the same words, the same bits), so their tile 3 fits two blocks too. So on Volta the call's pick is lowered to the largest tile that still gives two blocks per
|
||||
// multiprocessor (tile 8 counts as 4 first); a tile set by STRATA_I8_TM is kept as given.
|
||||
/// `tm` the pick (2, 3, 4 or 8), `bytes2/3/4` the dynamic shared memory of tiles 2-4 for the layer's formats, `smem_sm` the multiprocessor's shared memory, `reserved` the
|
||||
/// driver's reservation per block (cudaDevAttrReservedSharedMemoryPerBlock).
|
||||
inline int i8_tile_two_blocks(int tm, std::size_t bytes2, std::size_t bytes3, std::size_t bytes4, std::size_t smem_sm, std::size_t reserved) {
|
||||
int t = tm >= 4 ? 4 : tm <= 2 ? 2 : 3;
|
||||
auto fits = [&](int k) { const std::size_t b = (k == 2 ? bytes2 : k == 3 ? bytes3 : bytes4) + reserved; return 2 * b <= smem_sm; };
|
||||
while (t > 2 && !fits(t)) --t;
|
||||
return t;
|
||||
}
|
||||
/// Volta's tensor-core form of the kernels (tile code 5, src/kernels/cuda/i8h_volta.cuh: the same products on the FP16 tensor cores, bit-identical output) from this many
|
||||
/// entries a launch's expert has on average. Tesla V100, one layer of Flash-Next's shape, uniform routing, MMQ time / time (phaseA-tests/tune0216 bench5), tile 3 -> tile 5:
|
||||
/// at 40 entries (2,048 tokens) 1.38 -> 1.22 (slower), at 160 (8,192) 0.95 -> 0.96 (IQ3_S), 0.95 -> 0.94 (IQ3_XXS), 0.90 -> 0.94 (IQ2_S), at 508 (26,000) 0.82 -> 0.86,
|
||||
/// 0.83 -> 0.84, 0.82 -> 0.89; output hashes equal at every size.
|
||||
inline constexpr int64_t kI8hMinAvg = 160;
|
||||
/// The Volta pick: tile 5 from kI8hMinAvg entries on average when the formats have it (`h_ok`), else the two-block tile of i8_tile_two_blocks.
|
||||
inline int i8_tile_volta(int two_block_tile, int64_t avg, bool h_ok) { return h_ok && avg >= kI8hMinAvg ? 5 : two_block_tile; }
|
||||
/// STRATA_I8_SM70 read as a state (1 / 0 / -1 not set): the Volta tile rule above and the global grid are on unless it is 0.
|
||||
inline bool i8_volta_rule_on(int state) { return state != 0; }
|
||||
|
||||
// The Tesla P100 (compute capability 6.0) in a build without MMQ. There the build WITH MMQ takes the FP16 prompt path by default (prefill.cpp gp100_fp16_default: GP100 has no
|
||||
// dp4a), so the unset-switch int8 default of a build without MMQ (i8_switch_effective) must not replace it where the int8 kernel loses to it. Measured on the P100 (OUT build,
|
||||
// prompt read ms int8 / FP16, par/RESULTS-P100-GATE.md): 300 0.874, 600 0.865, 1,000 0.844, then 1,200 1.196, 1,500 1.142, 2,048 1.085, 8,192 1.081: the step sits at the chunk size from
|
||||
// which every expert streams (stream_all_min, 1,024 tokens, prefill.cpp), so the limit is that floor and no constant of its own: the int8 default applies to chunks BELOW it
|
||||
// (the staged per-layer path), the FP16 path from it up, as the build with MMQ does. A value the user set wins at every size (STRATA_EXPERT_I8=1 keeps the int8 kernels, =0 turns
|
||||
// them off); every other card class has no such limit.
|
||||
|
||||
/// May the int8 default (switch NOT set, build without MMQ) take a chunk of `chunk_tokens` tokens on this device? `raw_state` = i8_switch_parse(getenv): a set value (0 or 1) is
|
||||
/// not this rule's to decide (true); a build with MMQ, or a card that is not the P100 (`sm60`), has no limit (true); otherwise the chunk must be under `limit`.
|
||||
inline bool i8_chunk_default_allows(int raw_state, bool mmq_free, bool sm60, int64_t chunk_tokens, int64_t limit) {
|
||||
if (raw_state != -1 || !mmq_free || !sm60) return true;
|
||||
return chunk_tokens < limit;
|
||||
}
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -0,0 +1,197 @@
|
||||
// include/strata/kernels/iq_kernels.hpp - the i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S,
|
||||
// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files, and Q4_K / Q5_K / Q5_1 / Q8_0 for Unsloth's
|
||||
// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding).
|
||||
//
|
||||
// The block layouts, codebook grids and dot products are llama.cpp's (ggml-common.h, ggml-cuda/vecdotq.cuh,
|
||||
// ggml-cuda/dequantize.cuh; MIT, see third_party/ggml/LICENSE and VERSION.txt), so a weight means exactly what it
|
||||
// means in llama.cpp. Activations are q8_1 (32 values, fp16 scale and fp16 sum), the llama.cpp CUDA contract.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// ggml type ids handled here.
|
||||
bool iq_supported(int ggml_type) noexcept;
|
||||
/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30).
|
||||
bool embed_type_supported(int ggml_type) noexcept;
|
||||
/// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block).
|
||||
size_t iq_row_bytes(int ggml_type, int64_t n) noexcept;
|
||||
|
||||
/// q8_1 blocks for `n_rows` rows of `n_cols` floats (n_cols a multiple of 32): y is n_rows * n_cols/32 blocks.
|
||||
void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream);
|
||||
|
||||
/// y[c][r] = W[r] . x[c] for `ncols` columns of q8_1 activations (x stride n_in/32 blocks per column).
|
||||
void iq_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream);
|
||||
|
||||
/// Dequantize `n` contiguous values (n a multiple of 256) to fp16 / fp32; fp16 times `*scale` when given (device:
|
||||
/// an NVFP4 expert's s_down, read by the kernel itself so the source may be released right after it).
|
||||
void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, void* stream, const float* scale = nullptr);
|
||||
void iq_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream);
|
||||
/// Rows `tokens[0..n_tok)` (device ids) of a GGUF embedding table (`row_bytes` per row; the table may be mapped
|
||||
/// host memory) dequantized to fp32, `n_embd` per row (a multiple of 256).
|
||||
void iq_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok,
|
||||
int64_t n_embd, float* out, void* stream);
|
||||
/// One expert's gate and up matrices (n_ff rows of n_embd each) into the interleaved fp16 layout the prompt path
|
||||
/// uses: row 2r = gate row r, row 2r+1 = up row r. `tail` (device, NVFP4 only): the blob's {s_gate, s_up,
|
||||
/// s_down, 0}; gate rows are scaled by s_gate and up rows by s_up (s_down goes on the down matrix: folded into up,
|
||||
/// the up weights would sit near 1e-8, deep in FP16's subnormals).
|
||||
void iq_dequant_gu_f16(int ggml_type, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst,
|
||||
void* stream, const float* tail = nullptr);
|
||||
|
||||
/// The layout of one native expert blob: [gate rows | up rows | down rows], raw GGUF blocks.
|
||||
struct NativeExpertLayout {
|
||||
int gu_type = -1, d_type = -1;
|
||||
int64_t n_embd = 0, n_ff = 0;
|
||||
size_t gu_row = 0, d_row = 0; // bytes per row
|
||||
size_t up_off = 0, down_off = 0; // byte offsets inside the blob
|
||||
size_t bytes = 0; // the whole blob
|
||||
size_t tail_off = 0; // NVFP4: {s_gate, s_up, s_down, 0} at the blob's end; 0 = none
|
||||
// APR (prism.hadamard): the down weights are Hadamard-folded, so native_expert_grouped rotates h before
|
||||
// quantizing it (hadamard_rows). had_block 0 = none; d_signs is a DEVICE vector of n_ff signs or nullptr.
|
||||
int had_block = 0;
|
||||
bool gu_nib = false; // STRATA_EXPERT_NIBBLE: gate/up as 4-bit codes (strata/core/expert_nibble.hpp's
|
||||
// slot); set only by native_expert_layout_nib
|
||||
const float* d_signs = nullptr;
|
||||
};
|
||||
NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);
|
||||
/// STRATA_EXPERT_NIBBLE: a converted VRAM slot - gate/up as 4-bit codes, scales and d (expert_nibble.hpp's layout:
|
||||
/// up_off = the up rows' codes, down_off = kGuBytes, bytes = the slot), the GGUF down rows after them. IQ2_S /
|
||||
/// IQ3_XXS / IQ3_S at n_embd 2560, n_ff 640 only, and only in a build with the kernels (`native_expert_nib_supported`).
|
||||
NativeExpertLayout native_expert_layout_nib(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);
|
||||
bool native_expert_nib_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept;
|
||||
/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the
|
||||
/// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated).
|
||||
bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept;
|
||||
|
||||
/// Bytes of scratch `native_expert_grouped` needs for `cap_entries` entries.
|
||||
size_t native_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff);
|
||||
|
||||
/// A770 port (STRATA_PF_XMX=2): up to kXmxGroupMax experts' products in one XMX launch, the weights decoded from the
|
||||
/// quantized rows into local memory. Expert i: Y_i[cnt[i]][N] = X_i . W_i^T (X FP16, Y FP32, rows back to back).
|
||||
/// gate/up: b != nullptr (a = gate, b = up rows of n_embd = K; the output's virtual rows interleave gate/up);
|
||||
/// down: b == nullptr, a = the [N][K] rows. N a multiple of 128, K of 32 (and a whole number of rows per 256 block).
|
||||
constexpr int kXmxGroupMax = 16;
|
||||
void iq_xmx_grouped(int ty, const uint8_t* const* a, const uint8_t* const* b, const int32_t* cnt, int n,
|
||||
const uint16_t* X, float* Y, int N, int K, void* stream);
|
||||
|
||||
/// Grouped experts in the native format: group g's blob at device address grp_ptr[g]; its entries
|
||||
/// [grp_start[g], grp_start[g+1]) read token ent_tok[e]'s q8_1 activation (n_embd/32 blocks per token in x_q8_1)
|
||||
/// and write row ent_dst[e] of `out` (n_embd floats). Counts are read on the device.
|
||||
/// `grid_groups` (1 .. cap_groups; 0 = cap_groups) groups run side by side, a block row each striding over the rest:
|
||||
/// a call that usually has few groups or none (the verify window's PCIe share) launches less for the ones it does
|
||||
/// not have. The results do not depend on it.
|
||||
void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start,
|
||||
const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups,
|
||||
int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream,
|
||||
int64_t grid_groups = 0);
|
||||
/// OWN-I8 (research, off by default): the same call as `native_expert_grouped` on our own int8 dot-product kernels - a tile of
|
||||
/// 64 weight rows x 32..64 entries per block, each weight sub-block decoded once per tile into int8 in shared memory, `dp4a`
|
||||
/// products, SwiGLU and the q8_1 quantization of H in the gate/up epilogue (gate/up never go to memory). For cards with no
|
||||
/// matrix cores the fused prompt kernels can use. `scratch` as for native_expert_grouped (native_expert_scratch_bytes).
|
||||
/// Covered: gate/up IQ2_XXS / IQ2_XS / IQ3_XXS / IQ3_S / IQ2_S with a down of IQ4_NL / Q2_0 (`native_expert_i8_supported`);
|
||||
/// no NVFP4 tail, no APR Hadamard, no 4-bit slots. STRATA_EXPERT_I8=1 makes `native_expert_grouped` itself take it for a call of
|
||||
/// 256 entries or more (the prompt chunk of a Qwen3.6 engine without MMQ); STRATA_I8_TM = 2 | 3 | 4 forces the tile.
|
||||
bool native_expert_i8_supported(const NativeExpertLayout& L) noexcept;
|
||||
/// OWN-I8, the prompt path's question (once per layer, src/prefill/prefill.cpp): do the expert groups of this layer take `native_expert_i8`
|
||||
/// on this device, for groups of about `group_entries` entries (rows of one launch)? STRATA_EXPERT_I8=1 asks for it on any card, =0 never; unset:
|
||||
/// the HIP cards gfx1030 / gfx1031 / gfx1032 take it, every other card keeps MMQ (include/strata/kernels/i8_expert_rule.hpp). The formats and the
|
||||
/// device's shared memory still have to allow it (`native_expert_i8_supported`); groups under 256 entries keep the other path.
|
||||
/// Shared prompt code, no device work: a Metal build answers false.
|
||||
bool native_expert_i8_prompt(const NativeExpertLayout& L, int64_t group_entries) noexcept;
|
||||
/// OWN-I8: true when the answer above is "yes" because of the card class or the build (STRATA_EXPERT_I8 not set), not because the variable names it; the engine's
|
||||
/// start line differs. A Metal build answers false.
|
||||
bool native_expert_i8_by_default() noexcept;
|
||||
/// OWN-I8: called once, before main, by a build without llama.cpp's MMQ (prefill.cpp, STRATA_PF_OWN_ONLY): an unset STRATA_EXPERT_I8 then reads as 1 (i8_expert_rule.hpp,
|
||||
/// i8_switch_effective); a build with MMQ never calls it. A Metal build ignores it.
|
||||
void native_expert_i8_set_mmq_free() noexcept;
|
||||
/// OWN-I8, the few-rows route (include/strata/kernels/i8_expert_rule.hpp): the average routed rows per expert under which a prompt layer that takes the int8 kernels
|
||||
/// runs on the grouped kernels instead; 0 = no route (STRATA_I8_FEWROWS=0, or the int8 kernels are off). The class default: 6 on a Tesla P100, 7 elsewhere.
|
||||
/// Shared prompt code, no device work for a build that has none: a Metal build answers 0.
|
||||
int native_expert_i8_few_rows_limit() noexcept;
|
||||
/// OWN-I8 (tests, logs; CUDA / HIP builds only, no Metal definition: nothing shared calls these three): the dynamic shared memory per block the current device
|
||||
/// lets `native_expert_i8` use, in bytes (the device's opt-in attribute, 48 KB where it reports less; STRATA_I8_SMEM_LIMIT can lower it).
|
||||
size_t native_expert_i8_smem_limit() noexcept;
|
||||
/// What the last `native_expert_i8` call asked its two launches for: the tile code, the dynamic shared memory passed as each launch's third argument, and each
|
||||
/// launch's own status (cudaPeekAtLastError right after it, 0 = accepted).
|
||||
struct NativeExpertI8Launch {
|
||||
int tile;
|
||||
size_t gu_bytes, down_bytes;
|
||||
int gu_err, down_err;
|
||||
};
|
||||
NativeExpertI8Launch native_expert_i8_last_launch() noexcept;
|
||||
/// Does a launch of an empty kernel with this much dynamic shared memory run on the current device? 1 yes, 0 refused, -1 not available (a HIP build). A
|
||||
/// diagnostic for native_i8_parity; the attribute call is tried and its refusal ignored, the launch decides; the context is left clean.
|
||||
int native_expert_i8_probe_launch(size_t bytes) noexcept;
|
||||
/// Bytes of scratch `native_expert_i8` needs (it is smaller than native_expert_scratch_bytes: H goes out as q8_1 blocks only): `cap_entries`
|
||||
/// entries, at most `cap_groups` groups, `n_ff` features.
|
||||
size_t native_expert_i8_scratch_bytes(int64_t cap_entries, int64_t cap_groups, int64_t n_ff);
|
||||
/// The activation image `native_expert_i8` reads (its `x_q8_1` argument): `n_rows` x `n_cols` floats as blocks of 32 values {float d; int8 q[32]} (36 bytes), MMQ's numbers
|
||||
/// (d_inv = 127 / amax, q = round(x * d_inv), d = 1 / d_inv, the scale in FP32). NOT the q8_1 block of the other kernels (half2 ds); `n_cols` a multiple of 32.
|
||||
void native_expert_i8_quantize(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream);
|
||||
/// A launch record of at most kI8PutRecordMax bytes (a multiple of 4) written to `dst` (device) on `stream` by a one-block kernel that takes the bytes as its argument:
|
||||
/// no host-to-device copy, so the write does not queue behind other copies in the copy engine (the prompt path's streamed experts). False: too many bytes, or the launch failed.
|
||||
constexpr size_t kI8PutRecordMax = 512;
|
||||
bool native_expert_i8_put_record(void* dst, const void* src, size_t bytes, void* stream);
|
||||
void native_expert_i8(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,
|
||||
const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries, const void* x_q8_1,
|
||||
void* scratch, float* out, void* stream);
|
||||
/// true: `native_expert_grouped`'s launches before the group stride (STRATA_GROUPED_V1=1 at startup) - a block row
|
||||
/// per possible group, SwiGLU and the q8_1 quantization as two kernels over all cap_entries. Bitwise the same results
|
||||
/// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs.
|
||||
void native_grouped_set_v1(bool v1);
|
||||
/// The bench / parity only: the 4-bit gate/up kernel of every format (-1 = expert_nibble.hpp's gu_skeleton, the
|
||||
/// default; 0 = the S skeleton; 1 = the P skeleton). Bitwise the same results; set before graph capture.
|
||||
void native_expert_nib_set_variant(int v);
|
||||
/// gu-proto (nib_gu_proto.cuh): variant v's registers, local bytes and resident 256-thread blocks per SM for gu_type;
|
||||
/// false when v is not a gu-proto id (>= 10) or the type has none.
|
||||
bool native_expert_nib_variant_attr(int v, int gu_type, int* regs, int* local_bytes, int* blocks_per_sm);
|
||||
|
||||
/// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase
|
||||
/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down, 3 gate/up only).
|
||||
void native_expert_set_mode(int mode, int phase);
|
||||
|
||||
/// APR (prism.hadamard): y = H_block (signs * x) per block of `block` values of each of `rows` rows of `width`
|
||||
/// (x == y allowed). `signs`: a device vector of `width` signs, or nullptr (identity). The same floats as the CPU's
|
||||
/// hadamard_rotate. The f16 form rotates in place, computing in float.
|
||||
void hadamard_rows(const float* x, float* y, int64_t rows, int64_t width, int block, const float* signs, void* stream);
|
||||
void hadamard_rows_f16(uint16_t* x, int64_t rows, int64_t width, int block, const float* signs, void* stream);
|
||||
/// A device copy (on the current device) of the host sign vector `host` of `width` signs, made on first use and
|
||||
/// kept for the process. Call it at setup, not inside a CUDA graph capture. nullptr for a nullptr `host`.
|
||||
const float* hadamard_device_signs(const float* host, int width);
|
||||
|
||||
/// EXPDEC (STRATA_EXPDEC, docs/EXPERTDEC.md): `native_expert_grouped` stages the group's q8_1 activations in shared
|
||||
/// memory and computes several rows per lane, the same sums per (row, entry) as the default kernels (bitwise), for
|
||||
/// gate/up IQ2_XXS / IQ2_XS / IQ3_XXS / IQ3_S / IQ2_S at n_embd 2560 and down IQ4_NL / Q2_0 at n_ff 640; other layouts
|
||||
/// keep the default kernels. Enabled by default on gfx12 (STRATA_EXPDEC=0 disables it) and opt-in elsewhere
|
||||
/// (STRATA_EXPDEC=1). Set before graph capture; captured graphs keep the kernels they captured.
|
||||
void native_expert_set_expdec(int on);
|
||||
int native_expert_expdec();
|
||||
/// Its knobs, read from the environment at startup (STRATA_EXPDEC_R 1 | 2, _DR 1 | 2 | 4, _MINB 2 | 4, _D20 0 | 1,
|
||||
/// _RB, _DRB, _MINBLK): gate/up and down rows per lane, the gate/up kernel's __launch_bounds__ minimum blocks per SM
|
||||
/// (2 = up to 128 registers, 4 = up to 64), EXPDEC for the IQ4_NL down too, gate/up and down rows per block (0 = auto
|
||||
/// from the launch's groups), the auto rule's minimum blocks. In the setter a field <= 0 (< 0 for the two rows per
|
||||
/// block and down_iq4_nl) keeps the current value.
|
||||
/// `down` (STRATA_EXPDEC_DOWN, default 1 on gfx12 for Q2_0 down and 0 elsewhere; STRATA_EXPDEC_DOWN=0/1 overrides):
|
||||
/// EXPDEC for the down too; `down_iq4_nl` (STRATA_EXPDEC_D20, default 0) remains opt-in everywhere.
|
||||
struct NativeExpertExpdecParams {
|
||||
int gu_rows_per_lane = 0, down_rows_per_lane = 0, gu_min_blocks_per_sm = 0, down_iq4_nl = -1, down = -1;
|
||||
int gu_rows_per_block = -1, down_rows_per_block = -1, min_blocks = 0;
|
||||
};
|
||||
void native_expert_set_expdec_params(const NativeExpertExpdecParams& p);
|
||||
NativeExpertExpdecParams native_expert_expdec_params();
|
||||
/// Whether EXPDEC has kernels for this layout's gate/up and down (the bench's check).
|
||||
bool native_expert_expdec_takes(const NativeExpertLayout& L, bool& gu, bool& down);
|
||||
/// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry;
|
||||
/// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give
|
||||
/// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured.
|
||||
/// Volta prompt experts (STRATA_PF_WMMA): Y[rows of expert e] = X[rows] . W_e^T for a group of experts, W_e at
|
||||
/// W + e * expert_bytes (n_out rows of K values of type ty, GGUF blocks), X FP16 (ldx), rows bounds[e]..bounds[e+1],
|
||||
/// Y FP32 (ldy). FP16 tensor cores, FP32 sums. false: not launched (shape or type not covered). CUDA only.
|
||||
bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx,
|
||||
const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream);
|
||||
void iq_set_old_kernels(bool old);
|
||||
bool iq_old_kernels();
|
||||
|
||||
} // namespace strata::kernels
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// include/strata/kernels/nvfp4_decode_sm120.hpp - Clean-room MIT Blackwell sm_120a hardware NVFP4 grouped decode/verify.
|
||||
//
|
||||
// MIT License
|
||||
// Copyright (c) 2026 Niko1221 and the Strata contributors
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// True when compiled with sm_120a/sm_121a hardware FP4 decode support and running on a Blackwell sm_120/sm_121 GPU
|
||||
/// (STRATA_NVFP4_DEC_SM120=0 disables at runtime).
|
||||
bool nvfp4_decode_sm120_available() noexcept;
|
||||
|
||||
/// Test/benchmark override: -1 = follow STRATA_NVFP4_DEC_SM120 env (default), 0 = disable, 1 = enable.
|
||||
void nvfp4_decode_sm120_set_override(int mode) noexcept;
|
||||
|
||||
/// Hardware Blackwell sm_120a grouped NVFP4 (type 40) MoE decode/verify (fused gate+up+SwiGLU+Q8_1 -> down).
|
||||
/// Uses native PTX cvt.rn.f16x2.e2m1x2 + K-chunked split-half FP16 shared-memory activation caching across up to
|
||||
/// 8 tokens per expert group, reading weights once per group. Returns false if unsupported shape/device.
|
||||
bool nvfp4_decode_sm120_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr,
|
||||
const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst,
|
||||
const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries,
|
||||
const void* x_q8_1, void* hq_scratch, float* out, void* stream);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -0,0 +1,50 @@
|
||||
// include/strata/kernels/q8_1_finite.hpp - #606: the q8_1 activation block's scale and sum, kept finite.
|
||||
//
|
||||
// A q8_1 block stores its scale d = amax / 127 and the sum of its 32 raw activations as fp16. A sum past 65504 (one
|
||||
// massive-activation dimension among 32 values is enough) rounds to inf, and d does past amax = 8.3M; the dot
|
||||
// products then read inf * 0 = NaN, and a NaN in the residual ends as one token repeated (ggml-org/llama.cpp#23606
|
||||
// is the same defect). Clamped to the largest finite half, such a block gives an approximate product instead of NaN,
|
||||
// and the values are held to the int8 range they then exceed. Every block that was finite before is stored bit for
|
||||
// bit as before: values in (65504, 65520) round to 65504 anyway, and a finite block's |x / d| is at most 127. A NaN
|
||||
// stays NaN (the comparisons are false for it), so STRATA_DBG_NAN still sees one.
|
||||
#pragma once
|
||||
|
||||
#include <cuda_fp16.h>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
constexpr float kHalfMax = 65504.0f;
|
||||
|
||||
__device__ __forceinline__ float q8_1_finite(const float v) {
|
||||
return fabsf(v) > kHalfMax ? copysignf(kHalfMax, v) : v;
|
||||
}
|
||||
|
||||
/// #3948: native_mmvq.cu (native_quantize_q8_1, the separate quantiser every consumer of a q8_1 image was written for)
|
||||
/// is compiled with --use_fast_math, which makes `a / b` the fast full-range division (div.full.f32, up to 2 ulp off). The
|
||||
/// fused producers (fused_gr.cu's hyper-connection read, verify_kernels.cu's GDN output norm: STRATA_QFUSE) are not, so
|
||||
/// their IEEE division gave a different code at the rare element whose x / d lies next to a rounding boundary (found by
|
||||
/// gr_parity: one code in about 10^6, off by one). A translation unit that defines STRATA_Q81_FASTMATH_DIV before including
|
||||
/// this header divides the way the fast-math one does; every other one, and every HIP build, keeps `a / b` (so nothing
|
||||
/// that compiled before this changes).
|
||||
__device__ __forceinline__ float q81_div(const float a, const float b) {
|
||||
#if defined(STRATA_Q81_FASTMATH_DIV) && defined(__CUDA_ARCH__) && !defined(__HIPCC__)
|
||||
float r;
|
||||
asm("div.full.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b));
|
||||
return r;
|
||||
#else
|
||||
return a / b;
|
||||
#endif
|
||||
}
|
||||
|
||||
/// The block's quantized value of `xi` for the (finite) scale `d`; `amax` = 0 is an all-zero block.
|
||||
__device__ __forceinline__ int8_t q8_1_quant(const float xi, const float d, const float amax) {
|
||||
if (amax == 0.0f) return 0;
|
||||
const float q = roundf(q81_div(xi, d));
|
||||
return (int8_t) (q > 127.0f ? 127.0f : q < -127.0f ? -127.0f : q);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ half2 q8_1_ds(const float d, const float sum) {
|
||||
return make_half2(__float2half(q8_1_finite(d)), __float2half(q8_1_finite(sum)));
|
||||
}
|
||||
|
||||
} // namespace strata::kernels
|
||||
+1910
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,268 @@
|
||||
// src/kernels/cuda/i8h_volta.cuh - the Volta form of the int8 expert kernels (TUNE-0216): the same products as i8_kernel, on the tensor cores.
|
||||
// Included by i8_expert.cuh (inside iq_kernels.cu's anonymous namespace) after the tile kernels; it uses their decode (i8_load / i8_pack / i8_convert), their
|
||||
// activation image and their tile tables. CUDA only; the device code is Volta's (__CUDA_ARCH__ 700): every other architecture compiles a trap.
|
||||
//
|
||||
// Why. On a Tesla V100 (no int8 matrix cores) the dp4a tile kernels read prompts of 8,192+ tokens at 0.75-0.95 of MMQ's speed per layer, and with every expert
|
||||
// resident (#6053's 6x V100) a 26K prompt's expert products took 1.30 times MMQ's time. Volta's FP16 tensor cores do 512 FMA a clock per SM against dp4a's 256.
|
||||
//
|
||||
// Exact, by construction. The weights' int8 codes (the decoded sub-blocks i8_convert writes) and the activations' int8 codes become FP16 values (integers of
|
||||
// -128..127: exact), mma.m8n8k4 multiplies them exactly and adds them in FP32; every partial sum is an integer below 2^24 (32 products of at most 127 x 127), so it is
|
||||
// exact in any order. A fresh accumulator collects each 32-value sub-block (each 16-value half for the two-scale formats), and the epilogue then does what the dp4a
|
||||
// kernels do with their integer sums, in the same order: t = s1 m1 + s0 m0 (or s m, or s), acc = fmaf(t, base * d_x, acc), sub-block after sub-block. The products
|
||||
// t are integers below 2^24 as well (the dp4a kernels' own bound), so t is the same number whether made in int or float: the output is bit-identical to i8_kernel's.
|
||||
//
|
||||
// Shape. A block of 256 threads (8 warps) owns 64 weight rows (gate/up: 32 gate + the same 32 up features, as i8_kernel) x 64 entries of one expert, K in stages of
|
||||
// 128 values (4 sub-blocks). Warp w: rows 16 (w % 4) .. +16, entries 32 (w / 4) .. +32. Per k-step of 4 values each of the warp's four quad pairs computes one 8 x 8
|
||||
// tile; two mma per k-step cover the warp's 16 x 32. FP16 operands in shared memory (one buffer, the next stage's raw bytes held in registers meanwhile): 44 KB, two
|
||||
// blocks per SM.
|
||||
//
|
||||
// The m8n8k4 fragments (PTX ISA, mma.m8n8k4 .row.col, f16 inputs, f32 accumulators; checked on the V100 by phaseA-tests/tune0216/probe_m884.cu): quad pair
|
||||
// q = (lane % 16) / 4 holds lanes 4q..4q+3 and 4q+16..4q+19, local index t = lane % 4 + 4 (lane / 16); thread t supplies row t of A (k 0..3) and column t of B
|
||||
// (k 0..3); accumulator element i of thread (g = lane % 4, h = lane / 16) is row (g & 1) + (i & 2) + 4 h, column (i & 4) + (g & 2) + (i & 1).
|
||||
#pragma once
|
||||
|
||||
constexpr int I8H_BM = 64; // entries of a tile
|
||||
constexpr int I8H_LDH = 136; // halves per shared row: 128 + 8 (bank spread)
|
||||
constexpr int I8H_RS = 16; // words per row of the scale records: 4 sub-blocks x {m0, m1, base, 0}
|
||||
// formats of the Volta form: the decodes with no per-32 minimum (the minimum formats Q4_K / Q5_K / Q5_1 keep the dp4a kernels)
|
||||
__host__ __device__ constexpr bool i8h_type(int t) { return !i8_min_type(t) && (i8_gu_type(t) || i8_d_type(t)); }
|
||||
|
||||
template <int T>
|
||||
struct I8HSmem {
|
||||
static constexpr int GW = i8_gg_type(T) ? 0 : (i8_grid_words(T) + 3) / 4 * 4; // a big grid is read from global memory (as I8Smem's GG)
|
||||
static constexpr int SG = i8_sign_type(T) ? 512 : 0;
|
||||
static constexpr int SZ_W = 64 * I8H_LDH / 2, SZ_A = I8H_BM * I8H_LDH / 2; // words
|
||||
static constexpr int SZ_R = 64 * I8H_RS, SZ_D = I8H_BM * 4;
|
||||
static constexpr int o_sg = GW, o_w = o_sg + SG, o_a = o_w + SZ_W, o_r = o_a + SZ_A, o_d = o_r + SZ_R, o_src = o_d + SZ_D,
|
||||
total = (o_src + I8H_BM + 3) / 4 * 4;
|
||||
static constexpr size_t bytes = (size_t) total * 4;
|
||||
};
|
||||
|
||||
// four int8 (bytes of w) as four FP16 values, exactly: x + 128 is the mantissa of 1024 + x + 128, minus 1152
|
||||
__device__ __forceinline__ uint2 i8h_cvt4(uint32_t w) {
|
||||
const uint32_t c = w ^ 0x80808080u;
|
||||
const uint32_t lo = __byte_perm(c, 0x64646464u, 0x5140), hi = __byte_perm(c, 0x64646464u, 0x7362);
|
||||
const __half2 m = __floats2half2_rn(1152.0f, 1152.0f);
|
||||
const __half2 l = __hsub2(*(const __half2*) &lo, m), h = __hsub2(*(const __half2*) &hi, m);
|
||||
return make_uint2(*(const uint32_t*) &l, *(const uint32_t*) &h);
|
||||
}
|
||||
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ == 700
|
||||
__device__ __forceinline__ void i8h_mma(float (&d)[8], uint2 a, uint2 b) {
|
||||
asm volatile("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, {%0,%1,%2,%3,%4,%5,%6,%7};\n"
|
||||
: "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]), "+f"(d[4]), "+f"(d[5]), "+f"(d[6]), "+f"(d[7])
|
||||
: "r"(a.x), "r"(a.y), "r"(b.x), "r"(b.y));
|
||||
}
|
||||
#endif
|
||||
|
||||
template <int T, bool GU>
|
||||
__global__ void __launch_bounds__(I8_NT, 2)
|
||||
i8h_kernel(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, const int32_t* __restrict__ n_groups,
|
||||
const int32_t* __restrict__ tile_off, const int32_t* __restrict__ ent_idx, const block_q8_1* __restrict__ A,
|
||||
block_q8_1* __restrict__ hq, float* __restrict__ out, NativeExpertLayout L) {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ == 700
|
||||
using SM = I8HSmem<T>;
|
||||
extern __shared__ uint4 i8_dyn[];
|
||||
uint32_t* const smem = (uint32_t*) i8_dyn;
|
||||
uint32_t* const s_grid = smem;
|
||||
uint32_t* const s_sg = smem + SM::o_sg;
|
||||
__half* const s_w = (__half*) (smem + SM::o_w);
|
||||
__half* const s_a = (__half*) (smem + SM::o_a);
|
||||
uint32_t* const s_r = smem + SM::o_r;
|
||||
float* const s_ad = (float*) (smem + SM::o_d);
|
||||
int* const s_src = (int*) (smem + SM::o_src);
|
||||
const uint32_t* const grid_rd = i8_gg_type(T) ? i8_grid_src<T>() : s_grid;
|
||||
|
||||
const int ng = *n_groups;
|
||||
const int ti = blockIdx.x;
|
||||
if (ti >= tile_off[ng]) return;
|
||||
int lo = 0, hi = ng - 1;
|
||||
while (lo < hi) {
|
||||
const int mid = (lo + hi + 1) >> 1;
|
||||
if (tile_off[mid] <= ti) lo = mid; else hi = mid - 1;
|
||||
}
|
||||
const int g = lo;
|
||||
const int e_lo = grp_start[g] + (ti - tile_off[g]) * I8H_BM;
|
||||
const int e_hi = min(grp_start[g + 1], e_lo + I8H_BM);
|
||||
const int nv = e_hi - e_lo;
|
||||
I8P blob = i8_uniform(I8_GPTR(grp_ptr[g]));
|
||||
const int tid = threadIdx.x;
|
||||
const int K = GU ? (int) L.n_embd : (int) L.n_ff;
|
||||
const int ns = K / I8_KS;
|
||||
const size_t wrb = GU ? L.gu_row : L.d_row;
|
||||
|
||||
if constexpr (i8_grid_words(T) > 4 && !i8_gg_type(T)) {
|
||||
const uint32_t* src = i8_grid_src<T>();
|
||||
for (int i = tid; i < i8_grid_words(T); i += I8_NT) s_grid[i] = src[i];
|
||||
}
|
||||
if constexpr (i8_sign_type(T)) { // as i8_kernel's table
|
||||
const uint32_t b = (uint32_t) tid;
|
||||
uint32_t sb = b;
|
||||
if constexpr (T != 21 && T != 22) sb = (b & 127u) | (((uint32_t) __popc(b & 127u) & 1u) << 7);
|
||||
uint32_t mlo = 0, mhi = 0;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 4; ++k) {
|
||||
mlo |= ((sb >> k) & 1u) ? (0xFFu << (8 * k)) : 0u;
|
||||
mhi |= ((sb >> (4 + k)) & 1u) ? (0xFFu << (8 * k)) : 0u;
|
||||
}
|
||||
*(uint2*) (s_sg + 2 * b) = make_uint2(mlo, mhi);
|
||||
}
|
||||
uint32_t kv[4] = {0, 0, 0, 0};
|
||||
if constexpr (T == 20 || T == 23) {
|
||||
const uint32_t* t = (const uint32_t*) kvalues_iq4nl;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) kv[i] = t[i];
|
||||
}
|
||||
if (tid < I8H_BM) s_src[tid] = (e_lo + tid < e_hi) ? (GU ? ent_idx[e_lo + tid] : e_lo + tid) : -1;
|
||||
__syncthreads();
|
||||
|
||||
// decode thread: row wr of the tile, sub-block wp of the stage (as i8_kernel); activation thread: q8_1 block (tid & 3) of entry (tid >> 2)
|
||||
const int wr = tid >> 2, wp = tid & 3;
|
||||
uint32_t row_off;
|
||||
if constexpr (GU) row_off = (uint32_t) ((wr >= 32 ? L.up_off : (size_t) 0) + (size_t) (blockIdx.y * 32 + (wr & 31)) * wrb);
|
||||
else row_off = (uint32_t) (L.down_off + (size_t) (blockIdx.y * 64 + wr) * wrb);
|
||||
const I8Off woff = i8_offs<T>(row_off, wp);
|
||||
I8P const abase = I8_GPTR(A);
|
||||
uint32_t a_vo;
|
||||
{
|
||||
const int src = s_src[tid >> 2];
|
||||
a_vo = (uint32_t) ((size_t) (src >= 0 ? src : 0) * (size_t) ((K / 32) * 36) + (size_t) (tid & 3) * 36);
|
||||
}
|
||||
auto store_w = [&](int st, const uint32_t (&r)[I8NR<T>]) {
|
||||
uint32_t q[8], w[I8NW<T>];
|
||||
int m0, m1;
|
||||
float base, minv = 0.0f;
|
||||
const int ibs = (st * 4 + wp) & 7;
|
||||
i8_pack<T>(r, ibs, w);
|
||||
i8_convert<T>(w, grid_rd, (const uint2*) s_sg, kv, q, m0, m1, base, ibs, &minv);
|
||||
uint2* dst = (uint2*) (s_w + wr * I8H_LDH + wp * 32);
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 8; ++k) dst[k] = i8h_cvt4(q[k]);
|
||||
*(uint4*) (s_r + wr * I8H_RS + wp * 4) = make_uint4((uint32_t) m0, (uint32_t) m1, __float_as_uint(base), 0u);
|
||||
};
|
||||
auto store_a = [&](const uint32_t (&ar)[9]) {
|
||||
uint2* d = (uint2*) (s_a + (tid >> 2) * I8H_LDH + (tid & 3) * 32);
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 8; ++k) d[k] = i8h_cvt4(ar[1 + k]);
|
||||
s_ad[tid] = __uint_as_float(ar[0]);
|
||||
};
|
||||
|
||||
const int lane = tid & 31, warp = tid >> 5;
|
||||
const int qp = (lane & 15) >> 2, tl = (lane & 3) + 4 * (lane >> 4);
|
||||
const int gg = lane & 3, hh = lane >> 4;
|
||||
const int r0 = 16 * (warp & 3) + 8 * (qp & 1); // the quad pair's 8 rows
|
||||
const int c0 = 32 * (warp >> 2) + 8 * (qp >> 1); // its 8 entries of the first 16-entry half (the second: + 16)
|
||||
const __half* const a_row = s_w + (r0 + tl) * I8H_LDH; // A: row tl of the quad pair's rows
|
||||
const __half* const b_col0 = s_a + (c0 + tl) * I8H_LDH; // B: column tl (an entry) of the first half
|
||||
const __half* const b_col1 = b_col0 + 16 * I8H_LDH; // ... of the second half
|
||||
float acc[2][8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 2; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) acc[j][i] = 0.0f;
|
||||
|
||||
uint32_t wraw[I8NR<T>], ar[9];
|
||||
i8_load<T>(blob, woff, 0, wraw);
|
||||
{
|
||||
I8P p = abase + a_vo;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 9; ++k) ar[k] = i8_ldw(p + 4 * k);
|
||||
}
|
||||
store_w(0, wraw);
|
||||
store_a(ar);
|
||||
__syncthreads();
|
||||
for (int st = 0; st < ns; ++st) {
|
||||
if (st + 1 < ns) { // the next stage's raw bytes into registers while this one computes
|
||||
i8_load<T>(blob, woff, st + 1, wraw);
|
||||
I8P p = abase + (size_t) (st + 1) * 144 + a_vo;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 9; ++k) ar[k] = i8_ldw(p + 4 * k);
|
||||
}
|
||||
#pragma unroll 1
|
||||
for (int blk = 0; blk < 4; ++blk) {
|
||||
float p0[2][8], p1[2][8]; // the sub-block's sums: values 0-15 (p0) and 16-31 (p1), or all 32 in p0 for the one-scale formats
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 2; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) { p0[j][i] = 0.0f; p1[j][i] = 0.0f; }
|
||||
#pragma unroll
|
||||
for (int kk = 0; kk < 8; ++kk) {
|
||||
const int k = 32 * blk + 4 * kk;
|
||||
const uint2 a = *(const uint2*) (a_row + k);
|
||||
const uint2 b0 = *(const uint2*) (b_col0 + k), b1 = *(const uint2*) (b_col1 + k);
|
||||
if (i8_two_scales(T) && kk >= 4) { i8h_mma(p1[0], a, b0); i8h_mma(p1[1], a, b1); }
|
||||
else { i8h_mma(p0[0], a, b0); i8h_mma(p0[1], a, b1); }
|
||||
}
|
||||
// epilogue of the sub-block: the dp4a kernels' arithmetic on the same integers, in the same order
|
||||
float axv[2][4]; // the activation scales of the thread's eight entries for this sub-block
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 2; ++j)
|
||||
#pragma unroll
|
||||
for (int cc = 0; cc < 4; ++cc) axv[j][cc] = s_ad[(c0 + 16 * j + ((cc & 2) << 1) + (gg & 2) + (cc & 1)) * 4 + blk];
|
||||
#pragma unroll
|
||||
for (int rr = 0; rr < 2; ++rr) { // the thread's two rows: (g & 1) + 2 rr + 4 h
|
||||
const int row = r0 + (gg & 1) + 2 * rr + 4 * hh;
|
||||
const uint4 rc = *(const uint4*) (s_r + row * I8H_RS + blk * 4);
|
||||
const float base = __uint_as_float(rc.z);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 2; ++j)
|
||||
#pragma unroll
|
||||
for (int cc = 0; cc < 4; ++cc) { // the thread's four entries: (cc & 2) * 2 + (g & 2) + (cc & 1)
|
||||
const int i = (cc & 1) | (rr << 1) | ((cc & 2) << 1); // element index: col bit 0 = i & 1, row bit 1 = i & 2, col bit 2 = i & 4
|
||||
const float ax = axv[j][cc];
|
||||
float t;
|
||||
if constexpr (i8_two_scales(T)) t = p1[j][i] * (float) (int) rc.y + p0[j][i] * (float) (int) rc.x;
|
||||
else if constexpr (i8_unit_scale(T)) t = p0[j][i];
|
||||
else t = p0[j][i] * (float) (int) rc.x;
|
||||
acc[j][i] = fmaf(t, base * ax, acc[j][i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (st + 1 < ns) {
|
||||
__syncthreads();
|
||||
store_w(st + 1, wraw);
|
||||
store_a(ar);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
// epilogues
|
||||
if constexpr (GU) {
|
||||
// the 64 rows x 64 entries of sums through shared memory (the weight and activation buffers are free now): F[row][entry]
|
||||
float* const F = (float*) s_w; // 64 x 65 floats (16.6 KB) inside the two buffers (34.8 KB)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 2; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const int row = r0 + (gg & 1) + (i & 2) + 4 * hh, col = c0 + 16 * j + (i & 4) + (gg & 2) + (i & 1);
|
||||
F[row * 65 + col] = acc[j][i];
|
||||
}
|
||||
__syncthreads();
|
||||
const int nb = (int) (L.n_ff / 32);
|
||||
for (int e8 = 0; e8 < 8; ++e8) { // warp w: entries 8 w .. 8 w + 7; lane: feature (gate row lane, up row 32 + lane)
|
||||
const int el = 8 * warp + e8;
|
||||
if (el >= nv) break; // uniform per warp
|
||||
const float gv = F[lane * 65 + el], uv = F[(32 + lane) * 65 + el];
|
||||
const float h = (gv / (1.0f + __expf(-gv))) * uv;
|
||||
float amax = fabsf(h);
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
|
||||
const float d_inv = 127.0f / amax;
|
||||
block_q8_1* hb = hq + (size_t) (e_lo + el) * nb + blockIdx.y;
|
||||
hb->qs[lane] = i8_code(h, d_inv, amax);
|
||||
if (lane == 0) i8_put_scale(hb, amax, d_inv);
|
||||
}
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 2; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const int row = r0 + (gg & 1) + (i & 2) + 4 * hh, col = c0 + 16 * j + (i & 4) + (gg & 2) + (i & 1);
|
||||
if (col < nv) out[(size_t) ent_idx[e_lo + col] * L.n_embd + (size_t) blockIdx.y * 64 + row] = acc[j][i];
|
||||
}
|
||||
}
|
||||
#else
|
||||
(void) grp_ptr; (void) grp_start; (void) n_groups; (void) tile_off; (void) ent_idx; (void) A; (void) hq; (void) out; (void) L;
|
||||
__trap();
|
||||
#endif
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+19
@@ -0,0 +1,19 @@
|
||||
// src/kernels/cuda/nvfp4_decode_sm120_absent.cpp - Fallback stub when sm_120a/sm_121a is not in CUDA_ARCHITECTURES.
|
||||
//
|
||||
// MIT License
|
||||
// Copyright (c) 2026 Niko1221 and the Strata contributors
|
||||
#include "strata/kernels/nvfp4_decode_sm120.hpp"
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
void nvfp4_decode_sm120_set_override(int) noexcept {}
|
||||
|
||||
bool nvfp4_decode_sm120_available() noexcept { return false; }
|
||||
|
||||
bool nvfp4_decode_sm120_grouped(const NativeExpertLayout&, const unsigned long long*, const int32_t*,
|
||||
const int32_t*, const int32_t*, const int32_t*, int64_t, int64_t,
|
||||
const void*, void*, float*, void*) {
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -0,0 +1,71 @@
|
||||
// S26: several warp sums at once (P per-lane values -> P sums), bitwise equal to P separate xor-butterfly warp sums
|
||||
// (`for (o = 16; o > 0; o >>= 1) v += shfl_xor(v, o)`). At offset 16 a lane keeps half of its P values and adds the
|
||||
// partner's copy of that half, at 8 half again, ... until one value is left, then plain xor steps for the remaining
|
||||
// offsets. Every level adds the same pair of values as the butterfly does (fp add commutes, so x + y == y + x
|
||||
// bitwise), only each lane carries fewer of them: P - 1 + (5 - log2 P) cross-lane moves instead of 5 P. Value j's sum
|
||||
// ends in the lanes whose bits 4, 3, .. (MSB first) spell j: tsum_lane<P>(j) is one of them. On AMD the moves are
|
||||
// DPP row_xmask / permlanex16 instead of ds_bpermute.
|
||||
#pragma once
|
||||
|
||||
#include <cuda_runtime.h> // (before the first use of __forceinline__ / __float_as_int: a gfx906 build gets them from its shim)
|
||||
|
||||
namespace strata::kernels::s26ts {
|
||||
|
||||
#if defined(__HIP_PLATFORM_AMD__) && !defined(STRATA_HIP_GFX906) // (permlanex16 / DPP row_xmask: gfx10+ only)
|
||||
__device__ __forceinline__ float xmov16(float v) {
|
||||
return __int_as_float(__builtin_amdgcn_permlanex16(__float_as_int(v), __float_as_int(v), 0x76543210u, 0xfedcba98u,
|
||||
false, false));
|
||||
}
|
||||
template <int O>
|
||||
__device__ __forceinline__ float xmov(float v) {
|
||||
if constexpr (O == 16) return xmov16(v);
|
||||
else return __int_as_float(__builtin_amdgcn_update_dpp(0, __float_as_int(v), 0x160 + O, 0xf, 0xf, false));
|
||||
}
|
||||
#else
|
||||
template <int O>
|
||||
__device__ __forceinline__ float xmov(float v) { return __shfl_xor_sync(0xffffffffu, v, O); }
|
||||
#endif
|
||||
|
||||
__host__ __device__ constexpr int pow2_ceil(int t) { return t <= 1 ? 1 : t <= 2 ? 2 : t <= 4 ? 4 : t <= 8 ? 8 : t <= 16 ? 16 : 32; }
|
||||
__host__ __device__ constexpr int log2c(int p) { return p <= 1 ? 0 : p == 2 ? 1 : p == 4 ? 2 : p == 8 ? 3 : p == 16 ? 4 : 5; }
|
||||
|
||||
template <int O>
|
||||
__device__ __forceinline__ float tplain(float x) {
|
||||
if constexpr (O >= 1) { x += xmov<O>(x); return tplain<O / 2>(x); }
|
||||
else return x;
|
||||
}
|
||||
// v[0..CNT) (CNT a power of two <= 32): this lane's values; returns the sum of value tsum_token<CNT>(lane)
|
||||
template <int CNT, int O = 16>
|
||||
__device__ __forceinline__ float tsum(float* v, int lane) {
|
||||
if constexpr (CNT > 1) {
|
||||
constexpr int H = CNT / 2;
|
||||
const bool hi = (lane & O) != 0;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < H; ++j) {
|
||||
const float send = hi ? v[j] : v[j + H];
|
||||
const float keep = hi ? v[j + H] : v[j];
|
||||
v[j] = keep + xmov<O>(send);
|
||||
}
|
||||
return tsum<H, O / 2>(v, lane);
|
||||
} else {
|
||||
return tplain<O>(v[0]);
|
||||
}
|
||||
}
|
||||
template <int P>
|
||||
__device__ __forceinline__ int tsum_token(int lane) {
|
||||
constexpr int L = log2c(P);
|
||||
int k = 0;
|
||||
#pragma unroll
|
||||
for (int b = 0; b < L; ++b) k = (k << 1) | ((lane >> (4 - b)) & 1);
|
||||
return k;
|
||||
}
|
||||
template <int P>
|
||||
__device__ __forceinline__ int tsum_lane(int k) {
|
||||
constexpr int L = log2c(P);
|
||||
int lane = 0;
|
||||
#pragma unroll
|
||||
for (int b = 0; b < L; ++b) lane |= ((k >> (L - 1 - b)) & 1) << (4 - b);
|
||||
return lane;
|
||||
}
|
||||
|
||||
} // namespace strata::kernels::s26ts
|
||||
@@ -0,0 +1,137 @@
|
||||
#pragma once
|
||||
// int8 copy of the TQ codebook tq2t_lut_f16 (2048 2-D points): point i = (lo byte, hi byte) as int8,
|
||||
// value ~= TQ_LUT_I8_SCALE * int8. One global scale (max |point| = 3.984375 -> 127); relative RMS error
|
||||
// 0.0085 of the codebook std, far below the trellis quantization error.
|
||||
// Generated from ggml-common.h (the tq2t codebook).
|
||||
#include <cstdint>
|
||||
#define TQ_LUT_I8_SCALE (3.984375f/127.0f)
|
||||
alignas(16) static const __device__ uint16_t tq_lut_i8[2048] = {
|
||||
0xecd6, 0x27f2, 0x76d3, 0xed2e, 0xf815, 0x2e1f, 0x25eb, 0x1bdb, 0xed27, 0x30e3, 0xe41a, 0x2dd5, 0x1ec7, 0x0df8, 0xfef8, 0x0b4f,
|
||||
0x16bb, 0x16cf, 0xe9eb, 0x2415, 0xd155, 0xd8f5, 0x41f8, 0x361e, 0x41f3, 0xcf1c, 0xf72d, 0xedee, 0x13f6, 0x0906, 0x1208, 0x13e7,
|
||||
0x1dd9, 0x2a07, 0x263a, 0xea05, 0x160e, 0xf2f2, 0xd3cc, 0xd0da, 0x430d, 0x35f6, 0x1623, 0xd5f3, 0x0b36, 0xe158, 0xfa04, 0x06ef,
|
||||
0xe0f5, 0xfc27, 0x3b14, 0xf91e, 0xf3fb, 0x0701, 0xebe2, 0xff0a, 0x0fbc, 0x2406, 0x2303, 0x0304, 0xd502, 0x320f, 0x27ec, 0x13da,
|
||||
0xd206, 0xd80e, 0x13ca, 0x11eb, 0x0408, 0x0d0f, 0x3a04, 0xcb19, 0xdd20, 0xd9e3, 0x24ff, 0xed12, 0x0803, 0xf20d, 0xede2, 0x15eb,
|
||||
0x1615, 0xf51c, 0x95fd, 0xe80a, 0xf208, 0xfa11, 0xfcee, 0xdd19, 0x0b18, 0x0747, 0xfb12, 0xfcfb, 0xf4fe, 0x2a20, 0xf5fa, 0xe0f8,
|
||||
0x3a29, 0x13dd, 0xf2ed, 0xd103, 0x01cb, 0xe322, 0x031e, 0xfa6f, 0x07f5, 0xd312, 0x0b03, 0x11ed, 0xf318, 0xd537, 0xd60c, 0x1019,
|
||||
0x0414, 0x1010, 0xdf00, 0x0c01, 0xef03, 0x12ef, 0x2520, 0x0fac, 0x38f8, 0x23c0, 0x1bd3, 0x00fb, 0xf3e9, 0xf711, 0xff19, 0xe8da,
|
||||
0x21d8, 0x0a04, 0xd2dd, 0xd1e1, 0xebf7, 0xd3f5, 0xd20a, 0x3d1f, 0x1f18, 0x02f3, 0x1b40, 0x0c2a, 0xf405, 0xe2d7, 0x26fb, 0xf918,
|
||||
0x2af6, 0x01fa, 0xcc11, 0xf0dc, 0xfb06, 0x05e1, 0x10db, 0x0310, 0x559c, 0x19d9, 0xd22d, 0x22fa, 0xc041, 0xfb1f, 0x10d6, 0xffeb,
|
||||
0x2823, 0x680b, 0xdbe9, 0x0bea, 0xfce8, 0xe00c, 0x16f3, 0x0123, 0xf3fd, 0x2eee, 0xf40c, 0x070d, 0x1b15, 0xf5e4, 0xff38, 0x2227,
|
||||
0xfa4b, 0xe7e6, 0x2ad1, 0x2010, 0xd9d4, 0x0de7, 0xcff0, 0xd4e7, 0x091e, 0xf0a4, 0x0f09, 0x00f7, 0x09ea, 0xeaf8, 0x0614, 0x30ff,
|
||||
0x2f01, 0xd215, 0xf8f1, 0xf5e8, 0xb1ed, 0x0fd4, 0x360d, 0x22d0, 0x0e1b, 0x4709, 0x03d3, 0x261b, 0xff0e, 0xdbdb, 0xf600, 0x060a,
|
||||
0xfb43, 0x08e5, 0xda2f, 0xdddd, 0x1b39, 0x1812, 0x272d, 0xccee, 0xf120, 0xe4ef, 0xe60e, 0x0af4, 0xc60a, 0xd8ec, 0x0ff5, 0xd8ef,
|
||||
0x16c8, 0x2b37, 0x1fe3, 0xf0c4, 0x1545, 0x04fc, 0xf3dc, 0x020a, 0xe021, 0x06c2, 0xf21a, 0xd3eb, 0x221b, 0x0f12, 0x312e, 0x01f0,
|
||||
0xccff, 0xf1f4, 0xdb13, 0xeb19, 0x0ad1, 0xf51e, 0x0416, 0x00fd, 0x1ff0, 0x0318, 0xe3e3, 0xfbd3, 0xe510, 0x040f, 0xe5d4, 0x092b,
|
||||
0xe728, 0xecfd, 0xf2d0, 0xf6bb, 0x040c, 0x17ed, 0x34ed, 0x134d, 0xfee6, 0xfaf3, 0xf4b5, 0x2811, 0x0006, 0xe208, 0xefe6, 0x3511,
|
||||
0xeeaf, 0x03d0, 0xed00, 0x0cf6, 0xfc11, 0x09dc, 0x052b, 0x0eb5, 0x40fc, 0x3525, 0xf4d6, 0x2f28, 0x0639, 0x05eb, 0x03f0, 0xf3f9,
|
||||
0x0af1, 0x9be8, 0x24df, 0x0ccb, 0x49af, 0xc705, 0x06d0, 0x04f4, 0x0b23, 0x0507, 0x9b21, 0xe125, 0x0109, 0x520f, 0x0605, 0xfd03,
|
||||
0xc2e1, 0xcdfb, 0xe3fb, 0xc828, 0x18d2, 0x0141, 0x16f1, 0xbae1, 0x01e5, 0x2ff3, 0xfed7, 0x2f58, 0x2c31, 0xfefc, 0xf613, 0x88eb,
|
||||
0x28c9, 0xfafe, 0xcb03, 0xe1cf, 0x1ac5, 0x2ce0, 0x0bf6, 0xbe11, 0xf0ec, 0x1e07, 0x1bf2, 0xf413, 0x25f8, 0x3900, 0x02ee, 0x15f9,
|
||||
0x3ad2, 0x17df, 0x04de, 0xecf8, 0x24b9, 0xf8f3, 0xf229, 0xf310, 0xcaf9, 0x07e7, 0xf01b, 0xcef8, 0x4aea, 0xe7f4, 0xf41c, 0x15d4,
|
||||
0x03e7, 0xede4, 0xfd02, 0x12d4, 0xbffe, 0x230d, 0xe504, 0xf914, 0xc307, 0xfffe, 0x13fc, 0x0a28, 0xfd1d, 0xfa54, 0xe7f9, 0x1802,
|
||||
0xef47, 0xf7e9, 0xe800, 0xd6f9, 0x04e5, 0x3409, 0xf300, 0xd806, 0xddef, 0x3b9f, 0xcc2d, 0x0715, 0xeb00, 0x0f35, 0x14fd, 0x2bf0,
|
||||
0x0817, 0x5ec1, 0xf737, 0xeee9, 0xb30d, 0x46f5, 0x23e6, 0x1beb, 0xf031, 0xfb0b, 0x22ed, 0xfc00, 0x0519, 0xeb02, 0x3be1, 0x30ed,
|
||||
0xb9f9, 0xda4f, 0x1c09, 0xd814, 0x12df, 0xd83c, 0xfc08, 0xee24, 0xec0d, 0x0cef, 0xde0d, 0x18f3, 0x24f9, 0xf104, 0x0b07, 0x1529,
|
||||
0xc314, 0x2fc0, 0xfc19, 0x2ccd, 0xd090, 0x29fb, 0xf111, 0x1b4f, 0xbeed, 0x31ea, 0xd1e5, 0xf0d6, 0xcff4, 0xfeec, 0x1040, 0x6e2a,
|
||||
0xfaf9, 0xfebd, 0xb9d7, 0x0ef2, 0x06e5, 0xf015, 0x0617, 0xf7d8, 0x2310, 0xe414, 0x121d, 0xff02, 0xf71d, 0x269c, 0x1bfa, 0xcc0e,
|
||||
0x0a63, 0x1f1b, 0x0f1f, 0x27da, 0x411b, 0xc21a, 0xe9f0, 0xc8c4, 0xfff2, 0xf420, 0xf036, 0xdb0a, 0x13e5, 0xebf4, 0x3930, 0x04f0,
|
||||
0xdbfe, 0x2ce4, 0xd6db, 0xe0e3, 0xe91a, 0xfd0f, 0xc8ea, 0xddd0, 0x0be8, 0x0ee4, 0xf822, 0x23ee, 0x3319, 0xed1a, 0x090a, 0x234c,
|
||||
0xdecc, 0x00e7, 0xf2ea, 0xe011, 0x18f7, 0xb05a, 0x0324, 0x1bde, 0x190e, 0x0ef4, 0x21e9, 0xfbe1, 0x07fa, 0x2116, 0xf511, 0x2927,
|
||||
0x3dea, 0xfb30, 0x1125, 0xfd09, 0x1a1e, 0x07e3, 0x1b0a, 0xe8f2, 0x0eda, 0x0cee, 0x1ad0, 0x0f1d, 0x14f2, 0xf4f7, 0x0f06, 0x1215,
|
||||
0x02f1, 0xefe0, 0xe215, 0x12f2, 0x0212, 0x0cfe, 0x1be9, 0xedf4, 0x3fba, 0xef1e, 0x1eec, 0xf1fc, 0x21e4, 0x16f6, 0xb3e5, 0xd1f7,
|
||||
0xbfe7, 0xdb10, 0x1bf8, 0x3202, 0xed1e, 0x1a13, 0xf225, 0x10e4, 0xfbe6, 0xfb15, 0xef11, 0x0c17, 0x021c, 0x1e0f, 0x10ff, 0x5df0,
|
||||
0x1b04, 0xffdb, 0x0ec7, 0x09ef, 0xd5f7, 0xf6fd, 0xe5ed, 0xd5ff, 0x2633, 0x0800, 0x21fe, 0x00e9, 0xf416, 0xedf1, 0x0401, 0x01d6,
|
||||
0xe520, 0x0cf1, 0xf60e, 0xfbef, 0xb5cc, 0x31f1, 0x31fc, 0x1ddf, 0x06a9, 0x0c0d, 0xf2f7, 0xf81a, 0x4604, 0xd6ed, 0x171e, 0xfdcb,
|
||||
0xfb1c, 0x0dfc, 0xe5d1, 0xd50f, 0x26dd, 0x030b, 0xe82b, 0xfeea, 0xf9c5, 0xab0b, 0x0707, 0xf1e8, 0x1022, 0x0720, 0xdf1e, 0xd71d,
|
||||
0x17e9, 0xe506, 0x0cfa, 0xfd14, 0xf2ef, 0xe1e6, 0x0e08, 0xabfc, 0xf11c, 0xdef7, 0xf5c4, 0xdb24, 0x23da, 0xfb17, 0xf50f, 0xdaf4,
|
||||
0x381b, 0x0abf, 0xf312, 0x07eb, 0xd2ef, 0x5118, 0x00d9, 0x0210, 0xfffa, 0x2df7, 0xf6ed, 0xf30e, 0x0efa, 0x0ffe, 0xdc2c, 0xeae8,
|
||||
0x0723, 0xfca7, 0xd4d7, 0x311d, 0xf3e6, 0x0a02, 0x01f9, 0xc24e, 0xf4f0, 0x1a26, 0xfa08, 0x0e21, 0x4aff, 0x22f0, 0x0532, 0xe8e9,
|
||||
0xe624, 0xfd16, 0xe7c1, 0x2c09, 0xc3f5, 0x06ed, 0x091c, 0xf52a, 0x022d, 0x2b17, 0x1bf6, 0x1ffd, 0x00d2, 0x11e9, 0xb1dd, 0x1631,
|
||||
0xff2e, 0xbfc7, 0x17eb, 0x3e0c, 0x2af8, 0x20db, 0x07d6, 0x0a3b, 0x1132, 0xef08, 0x000f, 0x10f3, 0x38b0, 0x13eb, 0x1ff7, 0xe706,
|
||||
0x12c6, 0x0bc4, 0xdeed, 0x48d4, 0xfbf3, 0xe5fe, 0xeb21, 0x19ec, 0x38f4, 0xe512, 0x36bc, 0xe6f2, 0xfbea, 0xf702, 0x2fe7, 0x1bcd,
|
||||
0x12f7, 0x232b, 0x23f6, 0xf0cd, 0x0230, 0xde31, 0xf20b, 0x2dc7, 0x06d9, 0x03f8, 0xeefe, 0xf407, 0xf50a, 0x17e6, 0xc7f2, 0x03d9,
|
||||
0x4134, 0xe3eb, 0x0309, 0x1c47, 0xea1e, 0xd921, 0x2135, 0x14d1, 0x3214, 0x30df, 0xe80f, 0xed07, 0x0931, 0x0ae6, 0x29e5, 0xcdea,
|
||||
0xa204, 0xd0d0, 0x04f2, 0xcd24, 0x2e0b, 0xf4f5, 0xf6f8, 0xf9fa, 0x16f8, 0x28d6, 0x1c17, 0xd701, 0x2bd9, 0xf4ee, 0xf60c, 0x0bf7,
|
||||
0x1313, 0x17ef, 0x1fff, 0x24fc, 0x0302, 0xf8e3, 0xe102, 0xd725, 0xe229, 0xd0ec, 0x2b11, 0xb2f5, 0x0923, 0x01ea, 0x11d1, 0x3938,
|
||||
0x21f7, 0xc9fd, 0x0119, 0xf0fe, 0xf646, 0xfa23, 0xe50b, 0xe206, 0x2f12, 0xf109, 0xe81f, 0x00f1, 0xec0f, 0x26d3, 0x1127, 0x0404,
|
||||
0x0afe, 0x43e9, 0xdc03, 0xc9f5, 0x0b09, 0x1e0a, 0x070b, 0x1835, 0xed40, 0x0b2e, 0xe20b, 0x100b, 0xdee6, 0x08fb, 0x2200, 0x19d5,
|
||||
0xe8b4, 0xd745, 0xee21, 0x0e13, 0x0201, 0x0d1d, 0xbe0a, 0x45cb, 0xffde, 0xc932, 0xe3fe, 0x4df2, 0x0ff8, 0xe4f7, 0x0825, 0x1be6,
|
||||
0x14df, 0xb5c0, 0xefee, 0x0113, 0x46ef, 0x65fc, 0x231e, 0x20e6, 0xe6fb, 0xf42d, 0x2fd1, 0x1407, 0x4b0d, 0xe40e, 0xe2fc, 0xa1f7,
|
||||
0x493b, 0xfd2d, 0x0015, 0x4add, 0x19f9, 0x1104, 0xf305, 0x8111, 0xfff0, 0x04dc, 0xca0a, 0x2706, 0xfd3d, 0xf12d, 0x11f5, 0x1111,
|
||||
0x04d7, 0xf9e8, 0xf2d3, 0x1bee, 0xcf0c, 0x0c11, 0x2501, 0xd521, 0x0b05, 0x1c1c, 0x36e4, 0x23c6, 0x0f2a, 0xd6c6, 0x1520, 0x2009,
|
||||
0xe409, 0xe6c6, 0xeb64, 0xb61c, 0x07f2, 0x05f5, 0xed0b, 0x2daa, 0x24f1, 0xf7eb, 0x2103, 0x03fd, 0xe6dd, 0xfbce, 0x33db, 0x3f25,
|
||||
0xe1c4, 0x3fee, 0x4c1f, 0xe31f, 0x26ee, 0xfae4, 0x1419, 0x27fd, 0xd4d3, 0xd3fc, 0xec2b, 0xd514, 0x03f6, 0xcf33, 0x0d09, 0xf2e4,
|
||||
0xc30e, 0x09fc, 0x10fa, 0x08e9, 0x3716, 0xf2f4, 0x1302, 0x000d, 0x2add, 0xf1f1, 0xecec, 0x0c1f, 0xd5b9, 0x16d9, 0x28e0, 0x0107,
|
||||
0x52d8, 0xf0c9, 0x35f1, 0x0af2, 0x2508, 0xe4f2, 0xdfd9, 0x1435, 0x1fe9, 0x0e15, 0x16e1, 0x3f40, 0xea3a, 0xcf17, 0xf9f7, 0x051b,
|
||||
0x4cf9, 0x1e21, 0x1718, 0x5128, 0xe20d, 0x1924, 0x20f5, 0x1b29, 0xef85, 0x0d03, 0xd4f9, 0x2cfa, 0x25d7, 0x090f, 0xf525, 0x4d07,
|
||||
0x4201, 0xff03, 0xed14, 0x2007, 0xe3dd, 0xdfe0, 0x010f, 0x2ff6, 0x3601, 0xd2f2, 0xe426, 0x0329, 0xc2bc, 0x0ec2, 0xfd07, 0x29bc,
|
||||
0x023b, 0x1c0f, 0xbd05, 0x1311, 0xfe21, 0xe9e1, 0x1503, 0x4b14, 0x0011, 0xe804, 0x1a0c, 0x1217, 0x38e9, 0xdac0, 0x15e6, 0xfef4,
|
||||
0x0a00, 0xe3f8, 0xf1e1, 0x08e1, 0xf3bf, 0x08ff, 0x2db5, 0xf2ff, 0xd9e9, 0xf804, 0x040a, 0xc127, 0x098e, 0xd224, 0x180f, 0xfe15,
|
||||
0xd61a, 0xf698, 0xc302, 0xebdb, 0x06e9, 0x12fe, 0x0804, 0xec32, 0x05e7, 0xbd18, 0xf71b, 0xf106, 0xc6af, 0xfcfc, 0x0321, 0xdd1c,
|
||||
0x14f4, 0x3cf1, 0xc71c, 0x2787, 0x0125, 0xd00f, 0xb926, 0xaa39, 0x0a20, 0x28f6, 0x04bd, 0x11f9, 0xdba4, 0x3708, 0xfe00, 0xf123,
|
||||
0xe9f5, 0x02e8, 0xfe11, 0x59fe, 0x1409, 0x21a7, 0xf102, 0xcc15, 0xd6fc, 0x1b2d, 0x23eb, 0x0528, 0xdd10, 0xef05, 0x290f, 0x435d,
|
||||
0x20f9, 0xde05, 0xedfa, 0x2a45, 0x0120, 0xa8f0, 0x052e, 0xd6ea, 0xeb07, 0xd013, 0xb90d, 0xdd08, 0xb714, 0x1425, 0x95cf, 0xf810,
|
||||
0x1dfe, 0x01ec, 0xd30d, 0x39ee, 0xaf04, 0x18f1, 0x1d05, 0x05f9, 0x1706, 0x040d, 0xe014, 0x08ee, 0x20ee, 0xe711, 0x041d, 0x127a,
|
||||
0xfb0d, 0xecf0, 0xd1e9, 0x64e2, 0x090e, 0xa71e, 0x0610, 0x4512, 0x2be7, 0x0de9, 0x1016, 0x10ec, 0x0e0d, 0xf82a, 0x26e5, 0xfdd1,
|
||||
0xfb02, 0x12e1, 0xcae5, 0x2b0c, 0x250b, 0x2aea, 0x260f, 0x412c, 0x140f, 0x051f, 0xfafb, 0x1a08, 0xf216, 0x0b13, 0xeccc, 0xcea2,
|
||||
0xcccc, 0xeb16, 0xfa1a, 0x0a0d, 0xdaf1, 0xf5fc, 0xe8ca, 0x4fe3, 0xb347, 0xc661, 0x0a08, 0xf60f, 0xf7f6, 0x1d35, 0xffe8, 0xe90d,
|
||||
0x08f9, 0x203b, 0xef19, 0x30d8, 0xdcb9, 0xe00e, 0x0d01, 0x010c, 0xe8f7, 0x19ee, 0xd704, 0x120f, 0xee1c, 0xff21, 0x00ee, 0xfcf9,
|
||||
0xfc0f, 0xfbb7, 0x5d08, 0x09f1, 0xe62f, 0xeafc, 0x0e3a, 0x6ceb, 0xf5dd, 0x0b1d, 0x2cf4, 0x01ff, 0xfe1b, 0x26ce, 0xe6ef, 0x0aee,
|
||||
0xea2f, 0x16a5, 0xa72a, 0x33f9, 0xd8f2, 0xe6aa, 0x2f17, 0xf5c8, 0xece7, 0x0c1b, 0xe9fb, 0x19e7, 0xfac9, 0xe59a, 0x1829, 0x1401,
|
||||
0x22f4, 0xe0fe, 0x0fe9, 0xf408, 0xd6e0, 0x1102, 0x19ea, 0xead8, 0x19c0, 0xfd0d, 0x7714, 0x1357, 0x2e1a, 0xeef8, 0xfb35, 0x2205,
|
||||
0x1dea, 0x2cfc, 0x09f5, 0xf43b, 0x1219, 0xddfc, 0xea11, 0xf8ed, 0x0feb, 0xe84e, 0x4719, 0xdff1, 0xfddd, 0xe818, 0x323a, 0xde28,
|
||||
0x34ea, 0xf118, 0xdd0b, 0xe61a, 0xd507, 0xe925, 0x06d4, 0xd9d8, 0xe6f7, 0xe0dc, 0xea0e, 0xccf6, 0xfad9, 0x1f05, 0xe538, 0xc21f,
|
||||
0xc4fd, 0x02fc, 0x9432, 0x51cc, 0xda1d, 0xd72c, 0x0f0e, 0x1916, 0xda03, 0x2628, 0x390b, 0xfb5f, 0x33e6, 0x31f8, 0x0336, 0xdcfa,
|
||||
0xbd20, 0xe4da, 0x2213, 0x201e, 0x0117, 0xebd1, 0x0e46, 0xfdf0, 0xc813, 0x100c, 0x2902, 0x10e8, 0x1006, 0x16e4, 0xf5ea, 0x0df0,
|
||||
0x1dee, 0x0911, 0xf41a, 0x1ebd, 0x001e, 0xd1fe, 0x0b40, 0x08fd, 0x22d4, 0x1d1e, 0x12e3, 0xe81c, 0x3c08, 0x000a, 0xff1d, 0x2424,
|
||||
0xef27, 0x1417, 0xe417, 0xfaec, 0xe21c, 0x571f, 0x060e, 0xdcf8, 0x15e8, 0xe617, 0x58e3, 0x07f4, 0xe1e9, 0x270c, 0xdaf6, 0xfe31,
|
||||
0xe902, 0x0522, 0x080a, 0xf6d0, 0x1cf4, 0x0ed7, 0x0e24, 0xed18, 0x693e, 0xc70f, 0x2517, 0xf83e, 0xe2ee, 0xf916, 0xf4d9, 0xf813,
|
||||
0x4827, 0xeff2, 0xd21a, 0xf909, 0x031a, 0xf434, 0x33cb, 0x17fb, 0xe7ff, 0xd020, 0xff17, 0xd531, 0x5c2c, 0xca07, 0xdefa, 0xeaf2,
|
||||
0x2d06, 0x1a11, 0x2914, 0xcf01, 0xe9cf, 0xe1f0, 0x0be1, 0xafd4, 0xfdf4, 0xefb9, 0xf7ae, 0xf113, 0x1be4, 0x1008, 0x1900, 0x1af6,
|
||||
0x34e1, 0xdcf2, 0x4949, 0x08cd, 0x172d, 0x0047, 0x22fc, 0xe036, 0x2715, 0x3543, 0xf920, 0xfadc, 0x2c03, 0xe2c9, 0xe213, 0xfbdf,
|
||||
0xf9ef, 0x35fb, 0x1ddc, 0x04e3, 0x0ef7, 0x13ce, 0xfeee, 0xe51d, 0x071b, 0x0da0, 0x0e0b, 0x034e, 0xfbf5, 0xcee6, 0xfcff, 0x03fa,
|
||||
0x3fc4, 0x14ef, 0x07de, 0xf30a, 0x09f7, 0xf00e, 0xf733, 0x060c, 0x0813, 0xea14, 0x5b14, 0xfaf1, 0x140d, 0xffb0, 0xd9cb, 0xeedd,
|
||||
0xef3b, 0x122b, 0xfdfe, 0xd901, 0xef13, 0xb9e9, 0xf71f, 0x1797, 0x5407, 0x131b, 0x1de5, 0xf61a, 0x2b2b, 0xeff5, 0x0102, 0xd80b,
|
||||
0xf70a, 0xf4cc, 0xfd17, 0xfef6, 0x090c, 0x150a, 0x04ec, 0x0ce5, 0x2512, 0x130c, 0xd8f8, 0x04ee, 0x0ddc, 0x0612, 0xe601, 0x0603,
|
||||
0x29f1, 0xcf4a, 0xf4e2, 0x22e1, 0xe2f4, 0x2001, 0x02c2, 0xf80b, 0x11fc, 0x05f3, 0xfa28, 0xf518, 0x38d8, 0x0c08, 0x3008, 0x3bcb,
|
||||
0xff05, 0xf906, 0x0600, 0x24b1, 0xec09, 0x1113, 0x001b, 0x02b7, 0xfec7, 0x0eef, 0x09b9, 0x161a, 0x17cc, 0xbef4, 0xe7e3, 0x1904,
|
||||
0xe3e7, 0x29f4, 0x1c0c, 0x1b20, 0x1af0, 0x15fb, 0xedf6, 0x0cd4, 0xfc04, 0x14b5, 0xe714, 0xe049, 0x0ceb, 0xb49e, 0xe5e5, 0x00f8,
|
||||
0xc6dc, 0xdc00, 0xeeeb, 0xff08, 0x0658, 0x0af9, 0xee15, 0xe52b, 0xff23, 0x09d3, 0x16c4, 0x160c, 0xe834, 0xbed0, 0x06dc, 0x29e2,
|
||||
0xdbeb, 0xc3f0, 0xfa0b, 0x08f7, 0xe4e9, 0x0ffc, 0x20fb, 0x2efe, 0x06f6, 0xeafe, 0x1a1a, 0x2d6a, 0x3305, 0x030f, 0x0307, 0xf1e5,
|
||||
0x07f0, 0xe22e, 0xcf28, 0xd8cf, 0xcad8, 0x0de2, 0x4015, 0x0e10, 0x1e30, 0xf902, 0xbd2e, 0xf9bf, 0x1808, 0xee0d, 0xfee2, 0xd428,
|
||||
0xeefc, 0xe1bf, 0xf9e1, 0x2bed, 0x03e1, 0x14ed, 0x1af4, 0xb706, 0x3c18, 0x0e05, 0x9612, 0xfbf7, 0x3cf6, 0xfa00, 0x0ce3, 0xe70b,
|
||||
0x00ce, 0xd5f0, 0xf303, 0xae16, 0x0f02, 0xccf2, 0x2342, 0x09e8, 0xebea, 0xefea, 0xc5e6, 0xf0f6, 0xf24e, 0x2600, 0x1a02, 0xc337,
|
||||
0x19fb, 0xe009, 0x063f, 0x002b, 0xf000, 0x071d, 0x0d31, 0xe02c, 0xda28, 0xf40d, 0xee0f, 0x24f3, 0xe8f0, 0xfd0b, 0x04cd, 0x04e9,
|
||||
0x29fd, 0xf8fe, 0x54f7, 0xf622, 0x0bfc, 0xe0f3, 0x1fe1, 0x2818, 0x0b0e, 0x18dd, 0xf323, 0x1322, 0xfd05, 0xe9d4, 0x0efe, 0x029e,
|
||||
0xf7db, 0x1239, 0xf4f3, 0x1d00, 0xfdf2, 0xfe26, 0xd517, 0xe400, 0x101b, 0xe0ef, 0xb8b2, 0x1611, 0xf925, 0x0e00, 0xe946, 0x0625,
|
||||
0x0811, 0x0d12, 0x2df1, 0xf9f5, 0xf6e6, 0x07c6, 0xec10, 0xc42d, 0x0fde, 0xfde0, 0x2c24, 0x1819, 0x42dd, 0x3321, 0xfcda, 0x06fc,
|
||||
0xc7ee, 0xfce4, 0x0919, 0xdefe, 0x2c3f, 0xc717, 0xfdc2, 0xeff0, 0x0ff1, 0xf314, 0x15dc, 0xeb0b, 0xd9de, 0x09e3, 0x0028, 0x0502,
|
||||
0xdef4, 0x0719, 0x1303, 0x22dd, 0xe9e5, 0x14e3, 0xecc6, 0xfa0f, 0x0df5, 0x181c, 0x19e2, 0x03c7, 0x10f7, 0xd23e, 0x3f10, 0xf608,
|
||||
0xca42, 0xfb2a, 0x13e9, 0x0cf3, 0x1bd7, 0x173a, 0xecdf, 0xf10f, 0xdafc, 0x12f4, 0x13f0, 0xf9fc, 0xe5f9, 0xeaee, 0xc5cc, 0x26f5,
|
||||
0xb8f1, 0x0412, 0xe478, 0x0106, 0xf8de, 0x1ed6, 0xf240, 0x3a4d, 0x151d, 0x5a52, 0x1a30, 0xf6f2, 0xdd15, 0x0e27, 0xf0f8, 0x0d06,
|
||||
0x1814, 0x13f9, 0xf616, 0xdffc, 0xff0c, 0x163f, 0xb22e, 0x1100, 0x1b00, 0xda07, 0xeed9, 0x5fd5, 0xd8e6, 0xa9e5, 0xf4df, 0xdbe5,
|
||||
0xe2b8, 0x563b, 0xcb20, 0x3923, 0x50ff, 0xcfc7, 0x17db, 0xe0ec, 0x17f9, 0x641c, 0xfdf6, 0x0a0b, 0x1405, 0xa7c9, 0x11e6, 0xec24,
|
||||
0xf724, 0x2208, 0x0fe6, 0x00f5, 0x40d4, 0x3f04, 0x1f2b, 0x102e, 0x09df, 0xee2a, 0x1120, 0xe916, 0xf1d9, 0xfc1b, 0x06f2, 0x1604,
|
||||
0x2b00, 0x1f0c, 0xe310, 0xf9ea, 0x1bb6, 0x4b30, 0x08d9, 0xee09, 0x0b25, 0xfed4, 0xffe4, 0xfb09, 0xf705, 0xe200, 0xf730, 0x4421,
|
||||
0x1609, 0xecf2, 0x13d7, 0x4bc0, 0xe342, 0x3234, 0xf21e, 0x1e03, 0xfd12, 0x1b06, 0xea28, 0x0a15, 0xe104, 0x10d9, 0xdf02, 0x142e,
|
||||
0xe2f6, 0x12fb, 0xef17, 0xf9d6, 0xe6eb, 0x0d2d, 0x2efa, 0x0d19, 0x271d, 0xcffe, 0x1ed3, 0x0c0b, 0x0728, 0x03ea, 0x0eed, 0x1cf0,
|
||||
0xd2c0, 0xedc0, 0x072e, 0x09f3, 0x0808, 0xb3fe, 0x280a, 0x180d, 0x03ff, 0x1df6, 0x10e2, 0xf7fb, 0xfefa, 0x23cb, 0xdeea, 0x1ecf,
|
||||
0xc4d5, 0x14f7, 0x07b2, 0x0508, 0x46e4, 0xcfd5, 0xdd12, 0xe007, 0x2f04, 0xf800, 0x1906, 0xe5cd, 0x26e2, 0x35d0, 0xdc05, 0x210e,
|
||||
0xcde2, 0x05fd, 0x01f7, 0xe922, 0xdf17, 0x2d14, 0xdb0d, 0xf727, 0x40e4, 0x0c15, 0xddd6, 0xd817, 0x9652, 0x10cb, 0x08ec, 0x19e5,
|
||||
0x45fb, 0x3023, 0x18f5, 0xe6e8, 0x0000, 0x22f2, 0xd809, 0xf6f6, 0x020d, 0xd1fb, 0x2deb, 0xf6e0, 0xe304, 0xd3af, 0xa312, 0xeed3,
|
||||
0x0bde, 0x3cfb, 0xb838, 0xdbe0, 0x02e3, 0xe4fc, 0xf6f4, 0x0e17, 0x15ff, 0x0bec, 0xe0d3, 0xf718, 0x3a0f, 0x120b, 0x0c04, 0xdb16,
|
||||
0x29ff, 0x20de, 0x2024, 0xa3da, 0x2221, 0xf2fa, 0x180b, 0xe2e0, 0xce05, 0x1a18, 0x0008, 0x02de, 0x1965, 0xe73e, 0x15f5, 0xfd23,
|
||||
0xfa2d, 0xe6d7, 0x320c, 0x32f4, 0x0709, 0x0bdb, 0x24e8, 0x14e1, 0xcc39, 0xf7cc, 0x0ad6, 0xce09, 0x2edc, 0xc801, 0x23e4, 0xe609,
|
||||
0x20eb, 0xe5f4, 0x34fe, 0xe9bb, 0xeed0, 0xe9de, 0xfc25, 0xf80d, 0x06fe, 0xf912, 0x1ef4, 0xed05, 0xfc21, 0x2a1b, 0x28e7, 0xeb12,
|
||||
0xea09, 0x1e15, 0x1bfd, 0x1726, 0x1109, 0x05f7, 0xf514, 0x1ce2, 0xcddd, 0xf6d3, 0x0034, 0xf91b, 0x1de7, 0xf427, 0x1001, 0x35c5,
|
||||
0xe913, 0x0cff, 0xc0db, 0xdde3, 0x130a, 0x11f0, 0x33d5, 0xe119, 0x1c23, 0x3604, 0xc3eb, 0x1efb, 0x0215, 0x52ec, 0x27f0, 0x131f,
|
||||
0xe6e0, 0xfa39, 0xda1a, 0xebfa, 0x1004, 0x06ca, 0x16d7, 0x1415, 0x10ee, 0x0806, 0x13ff, 0xf7f9, 0x050b, 0xccba, 0x0fce, 0x1cfc,
|
||||
0xfa0d, 0x02f5, 0x19af, 0xf606, 0xddc6, 0x0104, 0xf501, 0xa4b7, 0xdbee, 0x1306, 0x06f8, 0x1c02, 0xc723, 0x1e12, 0x1821, 0x2e0e,
|
||||
0x2218, 0x28ee, 0xc9d2, 0xd201, 0x26e9, 0xe8fd, 0x1513, 0xe1fa, 0x05ff, 0x01dc, 0xfbfd, 0x070f, 0x4207, 0x28c3, 0x19fe, 0x2330,
|
||||
0x0ac9, 0x0ddf, 0xeb1c, 0x2013, 0x2158, 0x0fe0, 0x0b10, 0x220b, 0x13c0, 0xd31d, 0x02fe, 0x16ed, 0xe402, 0x1e27, 0x38fd, 0x27f9,
|
||||
0xee02, 0x3ae6, 0xe433, 0xc0f9, 0xdd41, 0xff13, 0x1d19, 0x2d4d, 0xee57, 0xd405, 0xf9e6, 0xec36, 0x05fa, 0xf430, 0x1fcc, 0xfe29,
|
||||
0xe3f2, 0x78fa, 0x0dd1, 0x120d, 0x0326, 0x0306, 0xd8fb, 0xd5e4, 0x2905, 0xd8fe, 0xc8e1, 0x1ec2, 0xddf6, 0x2604, 0xdeb0, 0x1df2,
|
||||
0xf614, 0x1c11, 0x0735, 0xd50a, 0xdc39, 0x0bd9, 0xc6f9, 0xd811, 0x1601, 0xf6ef, 0x0a17, 0x1aca, 0xb122, 0xfcd7, 0x0afa, 0xdf1b,
|
||||
0xf4ec, 0xefe3, 0xfceb, 0x342a, 0xf0fa, 0x0cce, 0x1607, 0xf603, 0x1ae0, 0xdaf9, 0xf807, 0x00e1, 0x37de, 0xfe1f, 0xf9d1, 0x3cdb,
|
||||
0xba00, 0xef0b, 0xe13b, 0x1df9, 0x00f3, 0xdb34, 0xe7ed, 0xd863, 0x3d00, 0x16fd, 0xe907, 0x1014, 0xde24, 0xf1de, 0x17ff, 0x20f2,
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023-2026 The ggml authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1 @@
|
||||
3cf03257f219afbe7334045ff7c6a06ac68c627d Sun Sep 20 16:08:11 2026 +0800
|
||||
@@ -0,0 +1,319 @@
|
||||
// third_party/ggml/ggml-common-tq.h - the trellis (APR) expert formats of Agention's llama.cpp fork
|
||||
// (agentionai/llama.cpp 073bc9e68, ggml/src/ggml-common.h; MIT, the same license as the rest of third_party/ggml).
|
||||
// The block structs and the 2048-point "Hyb" codebook, unchanged, for Strata's device kernels and its CPU trellis
|
||||
// kernels (src/kernels/cpu/tq_*.cpp). ggml-cpu takes them from the fork itself (-DSTRATA_GGML_DIR).
|
||||
//
|
||||
// TQ2_T / TQK6 / TQK7: 128 weights per block, {fp16 d; qs}. qs is 32 trellis steps of K bits (K = 8 / 6 / 7;
|
||||
// TQ2_T byte-aligned, TQK bit-packed LSB-first, circular, step t's 16-bit window at bit (31 - t)*K; TQ2_T's state
|
||||
// s_t = qs[(t + 31) % 32] << 8 | qs[t]). Step t gives weights 4t..4t+3: x = (s & 0x7fff) * 0x9e3779b1, points
|
||||
// lut[x >> 21] and lut[(x >> 10) & 2047] (fp16 pairs), times d.
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define QK_TQ2_T 128
|
||||
#define QK_TQK 128
|
||||
#define TQ_STATE_BITS 15
|
||||
#define TQ_STATE_MASK ((1u << TQ_STATE_BITS) - 1u)
|
||||
|
||||
typedef struct {
|
||||
uint16_t d; // fp16 scale
|
||||
uint8_t qs[QK_TQ2_T/4]; // one trellis byte per 4 weights
|
||||
} block_tq2_t;
|
||||
static_assert(sizeof(block_tq2_t) == 34, "wrong tq2_t block size/padding");
|
||||
typedef struct {
|
||||
uint16_t d;
|
||||
uint8_t qs[4*6]; // 32 steps x 6 bits
|
||||
} block_tqk6;
|
||||
static_assert(sizeof(block_tqk6) == 26, "wrong tqk6 block size/padding");
|
||||
typedef struct {
|
||||
uint16_t d;
|
||||
uint8_t qs[4*7]; // 32 steps x 7 bits
|
||||
} block_tqk7;
|
||||
static_assert(sizeof(block_tqk7) == 30, "wrong tqk7 block size/padding");
|
||||
|
||||
// Gyro-L pair trellis (agentionai llama.cpp release/gyro-l): 64 steps of K bits, 2 weights per step
|
||||
// (the TQ2_T codebook's first pair). Defined in the fork's ggml-common.h; repeated here so Strata's
|
||||
// device and CPU kernels compile without GGML_COMMON_IMPL.
|
||||
#define QK_TQP 128
|
||||
typedef struct {
|
||||
uint16_t d;
|
||||
uint8_t qs[8*5]; // 64 steps x 5 bits
|
||||
} block_tqp5;
|
||||
static_assert(sizeof(block_tqp5) == 42, "wrong tqp5 block size/padding");
|
||||
typedef struct {
|
||||
uint16_t d;
|
||||
uint8_t qs[8*6]; // 64 steps x 6 bits
|
||||
} block_tqp6;
|
||||
static_assert(sizeof(block_tqp6) == 50, "wrong tqp6 block size/padding");
|
||||
typedef struct {
|
||||
uint16_t d;
|
||||
uint8_t qs[8*7]; // 64 steps x 7 bits
|
||||
} block_tqp7;
|
||||
static_assert(sizeof(block_tqp7) == 58, "wrong tqp7 block size/padding");
|
||||
|
||||
// device memory in a CUDA / HIP translation unit, ordinary host data everywhere else
|
||||
#if defined(__CUDACC__) || defined(__HIPCC__)
|
||||
#define STRATA_TQ_LUT_SPACE __device__
|
||||
#else
|
||||
#define STRATA_TQ_LUT_SPACE
|
||||
#endif
|
||||
// point i = (tq_lut_f16[2i], tq_lut_f16[2i+1]) as fp16 bit patterns; 16-byte aligned so a point reads as one u32
|
||||
alignas(16) static const STRATA_TQ_LUT_SPACE uint16_t tq_lut_f16[4096] = {
|
||||
0xbd4d, 0xb8f7, 0xb6ce, 0x3cd5, 0xbd9e, 0x4368, 0x3dce, 0xb8a6, 0x395e, 0xb430, 0x3bc1, 0x3dbc, 0xb92b, 0x3c9c, 0xbca2, 0x3aaa,
|
||||
0x3cdb, 0xb8e1, 0xbb33, 0x3dfb, 0x3a8d, 0xbb18, 0xbd64, 0x3da0, 0xbf1a, 0x3b83, 0xb389, 0x3659, 0xb40f, 0xabd7, 0x40ee, 0x35a2,
|
||||
0xc057, 0x3972, 0xbe17, 0x3996, 0xb926, 0xb9b5, 0x393b, 0x3c75, 0x4151, 0xbdef, 0xb5a3, 0xbd09, 0xb408, 0x4012, 0x3b7f, 0x3ece,
|
||||
0xb688, 0x4011, 0x3b17, 0xbe30, 0x3d9b, 0xb4bf, 0xb870, 0xb8c8, 0xb537, 0x38b2, 0x31be, 0x34b0, 0x3389, 0x3871, 0xba33, 0x38b8,
|
||||
0xbce0, 0x3b3d, 0x3367, 0x3d3d, 0x3f50, 0x3cbe, 0x30b0, 0xb991, 0x3733, 0x3986, 0xb70e, 0xb6d9, 0xbe8c, 0xbd98, 0xbcca, 0xbe04,
|
||||
0x36a9, 0x403c, 0xb527, 0x3eae, 0x3c6a, 0x3982, 0xb655, 0xbd5b, 0x3ebb, 0x3596, 0x417e, 0xbbbd, 0x2fe0, 0xb1d3, 0xb858, 0x31c0,
|
||||
0xb54e, 0xbc10, 0x3cf0, 0xaf8b, 0x38e6, 0x3f5f, 0x3b87, 0xb2f6, 0xb114, 0xb675, 0x29bf, 0x3298, 0xbb7b, 0xb955, 0x34e9, 0xa984,
|
||||
0xc04a, 0x378f, 0x31a0, 0x3c8c, 0x2dea, 0x3c68, 0x2fe1, 0x2d29, 0x2c33, 0xbd72, 0x379d, 0x3e3e, 0xb918, 0x3cf2, 0xbcbe, 0x38bf,
|
||||
0x3284, 0xbdd5, 0x3707, 0xbd01, 0xbec1, 0x38c1, 0xb960, 0x3838, 0x3413, 0x3010, 0x376d, 0x3672, 0x302f, 0x3f42, 0x3a61, 0xbe9a,
|
||||
0x3c06, 0xbc71, 0xbb57, 0xbcf2, 0xa9dc, 0x3c85, 0x3873, 0xb8b2, 0x2d1e, 0x340d, 0x3661, 0xb73f, 0xbb91, 0xb8b7, 0xb956, 0x3943,
|
||||
0x3958, 0x3985, 0x3b26, 0xb556, 0xae17, 0xc2b9, 0x34e9, 0xb9ea, 0x33d5, 0xb6f4, 0x3826, 0xb1af, 0xb8a4, 0xaf98, 0x3a2d, 0xbc69,
|
||||
0x3a25, 0x358e, 0x406d, 0x32fd, 0x38a4, 0xb11a, 0xb170, 0xb02e, 0xaa0a, 0xb5cb, 0x3c04, 0x3d45, 0xb258, 0xb55b, 0xb412, 0xbbf5,
|
||||
0x3d33, 0x3f4b, 0xbc6e, 0x38a9, 0xb8c0, 0xb715, 0x2ec6, 0xbdd9, 0xbeb3, 0x2980, 0x3c54, 0xbb3c, 0x3ba0, 0x2d68, 0x42f9, 0xb209,
|
||||
0xb557, 0x3337, 0x3870, 0xbda7, 0x2d57, 0x35bd, 0xb8cd, 0x385e, 0x39fe, 0xb68e, 0x3eda, 0xbd74, 0x3643, 0xbd54, 0x3a32, 0x37d4,
|
||||
0x38f8, 0x2f7f, 0x37f3, 0x380f, 0x1b1e, 0xbc23, 0x25c7, 0x35c8, 0x2e3e, 0xb82a, 0xb85f, 0x3897, 0x3c0c, 0x3cb3, 0xc13e, 0x377b,
|
||||
0xb3a4, 0x3f09, 0xc006, 0x3c73, 0xbda5, 0x3ad1, 0xb0c6, 0xa3cf, 0xb9d5, 0xb680, 0x384b, 0xb493, 0x3a3c, 0xa985, 0xbcb5, 0xba24,
|
||||
0xbd0c, 0x3c21, 0x2f68, 0x34dc, 0xbc5d, 0xbdb7, 0xbbbf, 0xbddb, 0xb4c4, 0xb95a, 0xb59b, 0xbdaa, 0x34cf, 0xbdce, 0x3bad, 0x3f9d,
|
||||
0x3a05, 0x3bd5, 0xb69c, 0x2c64, 0x4003, 0x3adb, 0x3d4c, 0x35e8, 0x308d, 0xb5cc, 0xbd2d, 0xbb86, 0xb124, 0x3cd3, 0x3a0a, 0xb2ab,
|
||||
0xb507, 0x3d4b, 0xb190, 0x284c, 0x384c, 0xbe83, 0xbc94, 0xb806, 0x31e4, 0xb146, 0xbbe0, 0x3178, 0xbc9d, 0x3819, 0x3824, 0x2e8f,
|
||||
0xc246, 0x4150, 0xbcf3, 0x3a43, 0x3da9, 0xbdd5, 0xb229, 0x3c47, 0x400e, 0xc001, 0x3bb2, 0xb0c3, 0xbd46, 0x3822, 0xb92d, 0xa4a9,
|
||||
0x3c72, 0x3cfa, 0x3550, 0x4284, 0xb9e5, 0xbc97, 0xb996, 0x357a, 0xba03, 0xaf70, 0x35e7, 0xbc07, 0xb663, 0x397b, 0x3c59, 0x2942,
|
||||
0xadf7, 0xb689, 0xb875, 0x3db8, 0x35ea, 0xb63c, 0x3674, 0x3349, 0x3926, 0x3ae0, 0xbb20, 0xb56e, 0x3f05, 0xa9ae, 0x3ce5, 0x3c38,
|
||||
0x40b8, 0xb1ef, 0xba73, 0xba2b, 0xbdd7, 0x3d3f, 0x3822, 0x3c09, 0xbd87, 0xbce4, 0xba38, 0x36be, 0xb808, 0xbe23, 0xba33, 0xbd77,
|
||||
0x3b90, 0x3466, 0xc1c5, 0xb805, 0x34c0, 0x375b, 0xb4be, 0xa2db, 0xb96c, 0x3495, 0xb38a, 0xb99a, 0x390a, 0x31d5, 0xa910, 0x3e16,
|
||||
0x2878, 0x3dd6, 0x3964, 0xbdc0, 0xb783, 0xb3ef, 0xba12, 0xb571, 0xb8ce, 0xc0f2, 0xbd8f, 0x3771, 0x3656, 0x3eba, 0xbe0e, 0x3c39,
|
||||
0x3ac5, 0x371b, 0x3469, 0x4071, 0xbd99, 0x2e19, 0x3ab2, 0x3cb8, 0x36d9, 0xa92c, 0xbcb4, 0xbc9b, 0xa0fa, 0xb4e2, 0x34ed, 0x31fd,
|
||||
0x4033, 0xb0a0, 0xbac8, 0x342e, 0x3df5, 0xbccd, 0xbc5a, 0xbc5f, 0x3f32, 0x3ada, 0x3878, 0x39ec, 0x3db1, 0x3ce5, 0xb891, 0xbe93,
|
||||
0x3c11, 0xb75e, 0xb82c, 0xbb27, 0x36d6, 0xba67, 0xb602, 0x352c, 0x3507, 0xbf3a, 0xb8e9, 0xbcf5, 0xb55e, 0x3773, 0xb832, 0xbd0a,
|
||||
0xbf01, 0x3989, 0x3edf, 0x3d73, 0xbb3d, 0x3bc8, 0xbf82, 0xb7e0, 0x4053, 0x393f, 0xb07d, 0x2f91, 0xbc8b, 0xb6af, 0x3538, 0x2a46,
|
||||
0x3c2f, 0xbbfd, 0xbfc9, 0x324e, 0x3a8f, 0xb702, 0xb939, 0xbda9, 0x3ac3, 0x3c3f, 0x3875, 0x3798, 0x3dc4, 0x3e1b, 0xb820, 0x255e,
|
||||
0xa7e2, 0xbe92, 0xb63f, 0xb7c7, 0x38bd, 0xbcb4, 0x3a2f, 0xb958, 0xbdf2, 0x34fc, 0x3ba1, 0xb5a8, 0x3975, 0x3047, 0xaecc, 0x21da,
|
||||
0xb7f7, 0x3bc4, 0x39f8, 0x2eb6, 0xbb3f, 0xbb3a, 0xbd9b, 0xb13d, 0x37fa, 0xbab2, 0x3794, 0x3074, 0xbd7e, 0xbad3, 0x3d65, 0x346b,
|
||||
0x3cfd, 0xba61, 0xadd5, 0xb8fe, 0xbe09, 0xb6ec, 0xc05b, 0xb544, 0x360c, 0x2fdb, 0xb8ba, 0x39e5, 0xb8a8, 0x3e96, 0x40cf, 0x38cf,
|
||||
0xba8b, 0xac5a, 0xb691, 0xb284, 0xc0b9, 0xb5d5, 0x3864, 0x3d00, 0x3220, 0xa382, 0x3422, 0xbb8f, 0xba85, 0xb85e, 0x3854, 0x3eb3,
|
||||
0xc110, 0xb885, 0xbdf8, 0x2e60, 0x1cb3, 0xb8ba, 0xb4d3, 0x3636, 0x382a, 0xaf93, 0xbc81, 0x346a, 0x3d66, 0x3148, 0xc0b3, 0x36fe,
|
||||
0xaf70, 0x4001, 0x3caf, 0x3eac, 0xbd48, 0xb614, 0x3d04, 0x3de8, 0x3f2b, 0x31d0, 0xb955, 0x30ce, 0xb81b, 0x2d33, 0xb328, 0xb657,
|
||||
0xb7c2, 0x3527, 0xb9f6, 0xc255, 0xbc1a, 0x3c90, 0xbe9c, 0x35f3, 0xc11d, 0x409a, 0x30db, 0xbf2f, 0xbe02, 0x3285, 0xb607, 0x2f14,
|
||||
0x3c56, 0x35c2, 0x3288, 0x30ac, 0x3c1c, 0xc25c, 0x3ca4, 0xbbd6, 0x3465, 0x29c8, 0x37a3, 0x4129, 0x3151, 0x3225, 0x2ef2, 0xad41,
|
||||
0xbbcb, 0xbfc1, 0xb0c0, 0xbe71, 0xb17d, 0xbb59, 0x3cfe, 0xbefb, 0xbdb8, 0x39f0, 0x4014, 0x28a7, 0xb771, 0x396a, 0xbbdc, 0xc063,
|
||||
0xbabe, 0x2898, 0xb683, 0x3de9, 0xbd1f, 0xaa78, 0x4187, 0x3ded, 0x3e18, 0x3d7b, 0xaf3c, 0xab0c, 0x38a7, 0xb524, 0xb964, 0xc38f,
|
||||
0xbeda, 0x3d02, 0xaa74, 0xb25d, 0x2d90, 0xbe9a, 0xbe23, 0xbbb0, 0xbf6a, 0x3a8c, 0xbbfa, 0x3d87, 0xb53c, 0x3571, 0x385c, 0xc027,
|
||||
0xb903, 0xb801, 0x3368, 0x3b7b, 0xb70c, 0x3ab8, 0x38b5, 0xb625, 0xb436, 0x3cb1, 0x8d2a, 0x3f2c, 0xb88e, 0x2c53, 0xb2c8, 0x393b,
|
||||
0xbdbf, 0x3f40, 0xbc1b, 0x39d9, 0xbc3a, 0x306d, 0xb3ba, 0xb8fc, 0xc07b, 0x3c75, 0xb655, 0xb421, 0x3d34, 0xb720, 0x37f1, 0xb6a0,
|
||||
0xb338, 0xbec7, 0xba58, 0x334e, 0x3aab, 0xb810, 0xb3d7, 0xbe3d, 0xb984, 0x40a2, 0xb5cd, 0xba54, 0x3afa, 0xb63e, 0xbd80, 0x394d,
|
||||
0xba54, 0x2dda, 0xbaec, 0xb8e4, 0x2b2a, 0xad38, 0xbd82, 0x3886, 0xac6b, 0xc015, 0x368b, 0x3c72, 0x2fb3, 0xbaa7, 0x38fb, 0xb2cb,
|
||||
0x335d, 0xbfb5, 0xaba9, 0xa535, 0xafb8, 0x38b7, 0x3d00, 0x3524, 0x3b42, 0xaeac, 0x4144, 0xb1a6, 0xb352, 0xba3a, 0x2c72, 0x39f3,
|
||||
0x4079, 0xb82c, 0xb9e5, 0xb45f, 0x9d20, 0xb9f5, 0xb2ee, 0xbd36, 0xbad5, 0x2f11, 0x3450, 0x3e80, 0x213f, 0xb684, 0x3200, 0xbd07,
|
||||
0xb839, 0xbc5e, 0xc217, 0x3f5d, 0x3d9a, 0xbe94, 0x3947, 0x3381, 0x9081, 0xb943, 0x3eac, 0x3795, 0xad61, 0x3915, 0xb810, 0x3d5d,
|
||||
0x39cb, 0x33f2, 0xbfe8, 0x41ed, 0x3ee7, 0xb4a2, 0xb9e5, 0xb88a, 0x36b3, 0xc0da, 0xb57f, 0x406c, 0xba70, 0x3c5c, 0xb936, 0x3ae4,
|
||||
0x3e2c, 0xb7ff, 0x35b6, 0xb08e, 0xb8d1, 0x3c3a, 0x227e, 0xafed, 0x3a3d, 0x310a, 0x2d00, 0xb926, 0xbbe1, 0x3f76, 0xb8aa, 0x3e15,
|
||||
0xb31c, 0xc074, 0x40ee, 0xbcb6, 0x3449, 0x3b03, 0x38f5, 0xbd01, 0xbc2d, 0x386a, 0x3f94, 0xbcfc, 0x33a2, 0xb049, 0x3c77, 0xb86e,
|
||||
0x366c, 0xb91c, 0xb832, 0x35c6, 0x36ab, 0xbc4c, 0xb6b9, 0x3a04, 0xb2c9, 0x3c84, 0x3006, 0xb762, 0x330e, 0x3580, 0x3d32, 0x3926,
|
||||
0x38f9, 0xbfb2, 0xc00a, 0x3de6, 0x3a35, 0xafad, 0xbe69, 0x3d88, 0xc30f, 0xbe12, 0xb13d, 0x3d26, 0x382a, 0xb7a5, 0x40fa, 0x3ac3,
|
||||
0xb8a9, 0xc028, 0xb979, 0x3e19, 0xbac1, 0xbdd7, 0xbd42, 0xb802, 0xb631, 0xbe1a, 0xb8fb, 0xac7a, 0x3ff8, 0x3819, 0x3d3f, 0x42e8,
|
||||
0xb312, 0xb1dc, 0xc036, 0xaa42, 0xbd28, 0xc078, 0xb6f5, 0x36dd, 0xbad4, 0x31fd, 0x3933, 0xb7e9, 0x39b4, 0x31d4, 0xbd13, 0xb4ae,
|
||||
0x37d3, 0x3c5d, 0x3925, 0xbafd, 0x3b52, 0x3875, 0x2a38, 0xa581, 0x3b51, 0xb450, 0xc248, 0x3ccc, 0xb1aa, 0x3ad2, 0x36eb, 0xbe90,
|
||||
0x423c, 0x34e3, 0x3ac2, 0x3bc1, 0x3be5, 0x3749, 0xbcd1, 0x3cee, 0x3ac7, 0x4017, 0x3a67, 0xbfc4, 0xb7eb, 0xb9a8, 0xbf94, 0xbf08,
|
||||
0xb711, 0xa983, 0x3c0f, 0xb609, 0x3ebd, 0xb7f7, 0x34f4, 0xbca7, 0xbac3, 0x38b1, 0xb5d0, 0xb93f, 0x3e04, 0x3f1d, 0xb7fd, 0x305c,
|
||||
0xaae3, 0xbcaa, 0xbb0f, 0x3d8c, 0xbca4, 0xbd3f, 0xbb3b, 0xbc08, 0x3a90, 0xb9de, 0x377f, 0xad25, 0xb988, 0xbefe, 0xbdf7, 0xbc6c,
|
||||
0xba23, 0x35c3, 0xbb14, 0x370a, 0x3c45, 0xb3a9, 0xb889, 0x3c72, 0x3a36, 0x3e71, 0x3a90, 0xb8e0, 0x34cb, 0x34a6, 0x40be, 0x3c6c,
|
||||
0xbe95, 0xbc3f, 0xba4d, 0x2284, 0xb96e, 0xb73e, 0x384d, 0xbc04, 0xb452, 0x3a03, 0x41a8, 0xc100, 0x3c75, 0x2ed2, 0xbc47, 0x3ab6,
|
||||
0x3746, 0x3a63, 0xb62f, 0x3735, 0xb9dd, 0x3c2f, 0xbba8, 0xb08f, 0xb270, 0x3289, 0x3972, 0x3c1e, 0x3844, 0xb5ae, 0x3cee, 0x3d30,
|
||||
0xb98f, 0x3fa2, 0x3e16, 0xb150, 0x3c9c, 0x382c, 0x3483, 0xae2e, 0x3b71, 0x3a84, 0xbb53, 0x32f4, 0x3540, 0x3ab2, 0xb6e0, 0xba06,
|
||||
0xbcc9, 0x3701, 0xb89a, 0x361a, 0xbe12, 0x3a74, 0x3b56, 0x37ae, 0xb6ec, 0x38ee, 0xb47a, 0xb60a, 0x3247, 0x374a, 0x394d, 0x3883,
|
||||
0xb76f, 0x2c41, 0xbc07, 0xb862, 0x395e, 0xbba5, 0xb71f, 0x3865, 0x3897, 0x2cbc, 0xac7a, 0x35c9, 0xb9df, 0x3ac5, 0xb63b, 0xb8b9,
|
||||
0xc064, 0x3ff6, 0x3ba3, 0xb829, 0xb904, 0x3b7e, 0xafdb, 0xb78e, 0xbaec, 0x3c22, 0xb53d, 0x39a5, 0xbab6, 0xc0d4, 0xb47e, 0xbddb,
|
||||
0xba66, 0xc01c, 0x37ec, 0xbcb0, 0xb409, 0x3ac3, 0x2b2b, 0x3e47, 0x3b8a, 0xb8e0, 0x38cd, 0x3a77, 0x3cb0, 0xb724, 0xbaef, 0x381f,
|
||||
0xba7a, 0xb0f9, 0x3940, 0xb138, 0x3855, 0xb840, 0x39af, 0x35f4, 0x3b0f, 0x2c19, 0x3760, 0x3b83, 0xa813, 0x3801, 0xb801, 0x41d6,
|
||||
0x3026, 0x3ab3, 0xbca3, 0xa9f5, 0xbf1e, 0x370e, 0xb82b, 0x3467, 0xb4c3, 0xbd57, 0xad4c, 0xb4e9, 0xb8c4, 0xbad6, 0xa8f7, 0xbd66,
|
||||
0x3e70, 0x3cd2, 0x236c, 0x3421, 0xaa8a, 0x3c22, 0xb9c2, 0x9661, 0x3988, 0xb622, 0xb797, 0xb8aa, 0x254c, 0x305c, 0xbd53, 0x271b,
|
||||
0x3c11, 0xbaa9, 0xb75b, 0x3601, 0x36d1, 0xb4e9, 0xb856, 0xb15d, 0xbe96, 0xc0b2, 0xb7c5, 0x3e32, 0xb069, 0x3e22, 0xbc18, 0x3b41,
|
||||
0xc16e, 0x31ca, 0x365a, 0x35f9, 0xb491, 0xb700, 0x3a6a, 0xb41b, 0x2f26, 0x406a, 0xb8a6, 0xbd54, 0x3b9b, 0x39e3, 0xbeae, 0xad0f,
|
||||
0x3b1b, 0xb166, 0xafd4, 0x3655, 0xbde7, 0xbaa7, 0x37c1, 0xbd6c, 0xbc6d, 0x3cbf, 0x3584, 0x2dbd, 0x3d69, 0xb9f9, 0xb992, 0xac53,
|
||||
0xbf6b, 0xb2a2, 0x35b5, 0xc157, 0x331a, 0x328e, 0xba14, 0xb7b3, 0x3c44, 0x3809, 0x3c08, 0x3361, 0x3b93, 0xbc1c, 0x3b53, 0xbd21,
|
||||
0xb9d1, 0x39b2, 0x326b, 0xbad9, 0xb1c8, 0x35e6, 0x38ff, 0xaeff, 0xb831, 0xb734, 0xba96, 0xbbe1, 0x33f8, 0x36fb, 0xb049, 0xc15a,
|
||||
0x3b22, 0xb7a3, 0xb462, 0xbc3d, 0xbf97, 0xb57c, 0x3c86, 0xbcaa, 0xbcb9, 0x3c6e, 0x39ca, 0xb0f5, 0x379f, 0xb5bf, 0xb629, 0xbcb6,
|
||||
0x3aab, 0x3f0f, 0xc01a, 0x34fc, 0x3869, 0xb6be, 0xb953, 0x32f4, 0xb85f, 0xbdb7, 0x39f4, 0x411a, 0xbce8, 0x203c, 0x3824, 0x2a59,
|
||||
0xb26f, 0xa60c, 0xb47f, 0x3d96, 0xb8d0, 0xb53f, 0x3706, 0xb69f, 0xb1c9, 0x36cf, 0xad03, 0x37c1, 0x3d80, 0xbc90, 0xba26, 0xb98e,
|
||||
0x3c5b, 0x334b, 0xc196, 0xb051, 0xbd24, 0xbd79, 0x3b38, 0x3e2f, 0xba82, 0xb64d, 0x2a56, 0x34ed, 0xb36f, 0x2a01, 0x40e9, 0xbfbc,
|
||||
0xb7ce, 0xb600, 0x3cce, 0x3a9c, 0x33c6, 0xb23c, 0x3c33, 0x36c8, 0xa776, 0x409e, 0xb822, 0x3c35, 0x3e43, 0x30ef, 0xb9b2, 0xb9f7,
|
||||
0x3c79, 0xba81, 0x3973, 0xaedb, 0xbfe1, 0xba33, 0x348e, 0x3d8a, 0xb5ac, 0xbfa1, 0xb8d9, 0x31b7, 0x3aee, 0x3481, 0x3d3b, 0xb56e,
|
||||
0x3d98, 0x2c65, 0x39e0, 0x3d74, 0xb51a, 0x3ae2, 0xae6c, 0x3bb9, 0xbdc8, 0x1d86, 0xb9d9, 0x3840, 0xbc60, 0xc0f1, 0x3e26, 0x396d,
|
||||
0x3dc5, 0xa478, 0xbf35, 0xc01b, 0xb938, 0x39c8, 0x35d1, 0x3fd0, 0xb3bc, 0x3d41, 0xbca8, 0x3bf9, 0xbd36, 0x32f5, 0x3f59, 0x34c8,
|
||||
0x3e38, 0x3854, 0x338e, 0xb82e, 0x37b2, 0xa3ce, 0xb683, 0x37fd, 0xc104, 0x3f02, 0xb92f, 0x38b3, 0xb454, 0x3bcd, 0x31f4, 0xba42,
|
||||
0xbf4d, 0x3878, 0xbf7f, 0x3559, 0xb8e0, 0xbc53, 0xbd77, 0x407e, 0xb69e, 0xb0c6, 0xacce, 0xbabd, 0x3c1b, 0xb92f, 0xb8fa, 0x3a5f,
|
||||
0xb628, 0x3f13, 0x3893, 0xbacd, 0xc047, 0x3ec8, 0xb70b, 0xba7f, 0xb997, 0xb140, 0x2c0c, 0xb466, 0xba3f, 0x3dde, 0xbe75, 0x3ae1,
|
||||
0xb466, 0x3879, 0x3d68, 0x3c55, 0xb4d9, 0x3c6e, 0xbe71, 0xb803, 0x3e15, 0x2a52, 0x3e1b, 0xbc37, 0x3585, 0xb747, 0xbf22, 0x3db4,
|
||||
0xbcdb, 0x31a6, 0xb415, 0x2e23, 0xab25, 0xb884, 0x329e, 0xb5ef, 0x3525, 0xb59c, 0xba76, 0x39c2, 0xb6f5, 0xbf1e, 0xbcdf, 0x2dad,
|
||||
0x3e8c, 0x4019, 0xb92c, 0xbb4a, 0x3494, 0x2ddb, 0x406e, 0x3afd, 0x3b91, 0xb97a, 0x3c1f, 0xbce1, 0x3eae, 0x3c34, 0xbddd, 0x38ec,
|
||||
0x390f, 0x3e4f, 0xbc20, 0x3e04, 0x378c, 0xba0b, 0x330d, 0xb8aa, 0x3e34, 0x348e, 0xbaa5, 0x352f, 0xbac3, 0x3d2b, 0xb982, 0xbe71,
|
||||
0x305c, 0xc1e1, 0xbe05, 0xbe12, 0xb70b, 0x2fc1, 0x3c8b, 0xbe71, 0x35ad, 0x3dcc, 0xb581, 0xb612, 0xb42c, 0xb50c, 0xb1c9, 0xb36c,
|
||||
0xb443, 0x3977, 0xbd4c, 0x3d11, 0x39b8, 0x3b17, 0x269a, 0xbd27, 0xbce0, 0x3d6c, 0xb86d, 0xb611, 0x35e7, 0xb50c, 0xb453, 0x359c,
|
||||
0x38c6, 0x38bf, 0xb82a, 0x39a6, 0xa8c2, 0x3bb1, 0xb020, 0x3c8b, 0x2c82, 0x2dfa, 0xbb37, 0xb43e, 0x2b23, 0xbbbd, 0x3c97, 0xbd25,
|
||||
0x3d21, 0xbb81, 0xb8e5, 0xbe12, 0x3845, 0x3d6a, 0xb571, 0xc0ec, 0x3c69, 0x34ba, 0xb96f, 0x2818, 0xbdde, 0x382d, 0x3f0c, 0x3f33,
|
||||
0xb44b, 0x3c30, 0xaebd, 0xbef5, 0x3a3b, 0x2683, 0xaaf0, 0xb7f8, 0x405e, 0xb4f5, 0x3c5b, 0xb197, 0x359f, 0xbada, 0x3227, 0xbb77,
|
||||
0x3877, 0x3dec, 0x34a2, 0xb7c6, 0x3bde, 0xba0e, 0xb758, 0x20cc, 0x3760, 0xb8e8, 0xbdaf, 0x3cb8, 0x3cf3, 0x385d, 0x306f, 0x3078,
|
||||
0xac7a, 0x34d1, 0xb9b8, 0x402f, 0x2d2e, 0xbc80, 0xb55d, 0xbeef, 0x348e, 0x356a, 0x3511, 0x3b68, 0x35a4, 0x32ea, 0x3e99, 0x3a13,
|
||||
0x4002, 0xb8c9, 0x3dc1, 0x355a, 0x3556, 0xbb78, 0x3560, 0x37ee, 0xba6e, 0xbc4a, 0xb14d, 0x33eb, 0x22a9, 0x3c4a, 0xbd5b, 0x3a27,
|
||||
0xc0ca, 0xba1d, 0x4053, 0xbd31, 0x3c1a, 0xb87b, 0x38de, 0x36e3, 0x2663, 0x2b95, 0x3b4f, 0x3685, 0x353c, 0xc020, 0xbe97, 0x4050,
|
||||
0xbc48, 0xa53a, 0x3e4e, 0xbeea, 0xac24, 0xbb52, 0xb743, 0x40d2, 0xb389, 0x3762, 0xb493, 0xbb02, 0x3cb4, 0x342f, 0xba83, 0x3ace,
|
||||
0xbc28, 0x3923, 0xc004, 0xc0af, 0xb898, 0xb842, 0x38d0, 0x2760, 0xb83e, 0x405e, 0xaffb, 0x4254, 0x3b69, 0x3c6f, 0xba70, 0x3bed,
|
||||
0xb0de, 0xba70, 0x3d9c, 0xb635, 0xbde3, 0x3de8, 0x3321, 0x38e5, 0x369f, 0x40ae, 0x36e3, 0xbaf2, 0xaf7b, 0xbb9b, 0xb484, 0xc1f3,
|
||||
0x3f5a, 0x4097, 0x3da5, 0xaead, 0x3934, 0x1e3a, 0xbc67, 0x409f, 0xb2ed, 0x3a55, 0x3009, 0x385a, 0x3166, 0xb6ac, 0x3832, 0xc3f8,
|
||||
0xb800, 0xa95f, 0xbc8a, 0x2f61, 0x353c, 0xbeba, 0x3284, 0x3ce3, 0x3fad, 0xade8, 0x3da0, 0xb7c1, 0xb56e, 0x382d, 0x385f, 0x3855,
|
||||
0xbd34, 0x2ff5, 0xba07, 0xb290, 0xbda4, 0xb6f4, 0xb89b, 0x3ad2, 0x3613, 0xbe27, 0x3838, 0x35fc, 0x28e1, 0x3c96, 0x3c1e, 0xbd62,
|
||||
0x315a, 0x356b, 0x3b05, 0x3b16, 0xbaf3, 0x3ed5, 0xbf42, 0x3c65, 0x3d3f, 0x378a, 0xbf4e, 0xbd43, 0x3c0d, 0x3964, 0x34c3, 0x3c00,
|
||||
0x345a, 0xbafe, 0xbf4f, 0xba8b, 0x4240, 0xb95b, 0x3b21, 0xc0a2, 0xb6ed, 0x331d, 0xb57a, 0x3111, 0x3594, 0xb8ca, 0xc16a, 0x3d96,
|
||||
0xb7a9, 0x3c86, 0xb949, 0xb498, 0x2d89, 0x3c1e, 0xad06, 0x2eeb, 0xbc5b, 0xba8a, 0xbe54, 0xb0b9, 0xbc9a, 0x3e71, 0x3ca7, 0x3ff4,
|
||||
0xbf8b, 0xbbbc, 0xb894, 0x3fef, 0x3bda, 0x40c9, 0x3bc7, 0xbb66, 0xb87e, 0x3cbb, 0xbb1e, 0xb1f7, 0x3a3d, 0x38f6, 0xad22, 0x3cd9,
|
||||
0xbdb4, 0xbd81, 0xb005, 0xbd96, 0x3d6e, 0xb91c, 0x38f2, 0xbd5e, 0xb513, 0x2e27, 0x3e5b, 0xbe1c, 0x34b3, 0x366e, 0xbb24, 0xb6cd,
|
||||
0x36f7, 0xbfb4, 0xb00c, 0x34a3, 0xb1bf, 0x37df, 0xb9d6, 0x33d3, 0x396f, 0x3edf, 0xb5d1, 0xb6f7, 0x2aa1, 0x38b2, 0x36b1, 0x223d,
|
||||
0xbc6a, 0x3d3e, 0xb777, 0xb7b5, 0xb8ed, 0xb91c, 0x3be6, 0x35f5, 0xc077, 0xbd74, 0xbcdc, 0x3966, 0xbc12, 0x3d0b, 0x3312, 0x28cb,
|
||||
0xbd0d, 0x4128, 0xbef1, 0xb80e, 0xb758, 0x3eb4, 0xb6d3, 0x352f, 0x343d, 0x3ca3, 0xb733, 0xbaef, 0xbce4, 0xbc1d, 0x3eac, 0x38fa,
|
||||
0xb9d1, 0x3bce, 0x3953, 0x36ec, 0xbbb4, 0x3985, 0x4005, 0x3fe2, 0x3f4e, 0xb991, 0x39d5, 0xbe2c, 0xb44e, 0xb37f, 0x3acf, 0x30aa,
|
||||
0xb358, 0x40c3, 0x3c1f, 0x3b9b, 0x39ec, 0x39a7, 0x3d01, 0x4111, 0x367d, 0xbb76, 0x3c75, 0x3a48, 0xb547, 0x3c01, 0x3d2f, 0x3ae0,
|
||||
0xc3b1, 0xb837, 0x2e1d, 0x36c1, 0xb2d3, 0xbd8e, 0xb23a, 0x3d80, 0xbd29, 0x3c9b, 0x37a8, 0x348c, 0x3c9e, 0xb5aa, 0x3311, 0x40d3,
|
||||
0x256d, 0x4028, 0x2e47, 0xa66e, 0x390a, 0xb8de, 0x3306, 0x3c03, 0xbc58, 0xbb3f, 0xbc05, 0xbc21, 0x376c, 0x28e2, 0xb536, 0x3dda,
|
||||
0x2427, 0x3ebb, 0xb70a, 0xbdbf, 0x3cc4, 0xbb10, 0x3d33, 0x2d29, 0xc044, 0xbfd0, 0xbfd3, 0x3726, 0x32d9, 0xad34, 0xc040, 0x3d32,
|
||||
0x3f66, 0x2b12, 0x377a, 0x3ae9, 0x3088, 0xc02d, 0x384f, 0x38e2, 0x3c2b, 0xacfb, 0xbbda, 0xb9de, 0x2d0a, 0x3945, 0x38f1, 0x40ba,
|
||||
0x3858, 0x1b91, 0x2f58, 0xba15, 0x3642, 0x3a7f, 0x39d4, 0x387a, 0xb9af, 0x3efc, 0xc007, 0xbcc6, 0xba9b, 0x3938, 0xb635, 0xaa27,
|
||||
0xa2e3, 0x3509, 0xb38b, 0xbb66, 0xbbc3, 0xb775, 0xbbc7, 0x33f5, 0xc014, 0xb6ba, 0xa91a, 0x340b, 0xc0ad, 0x3dad, 0xa94d, 0xb70e,
|
||||
0xb9b4, 0xbcf0, 0x2f73, 0xb38a, 0x34f1, 0x304e, 0x3cdf, 0xbfe6, 0xc329, 0x34c3, 0x3c80, 0xbdc0, 0x37bd, 0x39ed, 0x393d, 0xaaa3,
|
||||
0x3a94, 0xbd49, 0xc288, 0xb4d2, 0x2c3e, 0xbfb6, 0xbca0, 0xb93d, 0xb9d6, 0x3200, 0xac36, 0x3875, 0x3072, 0x33f7, 0x3e47, 0xb8f7,
|
||||
0xba54, 0x3116, 0x3a12, 0xc037, 0x3ad7, 0xb48c, 0x323b, 0xb798, 0xc11c, 0xbf50, 0xaf13, 0xaf0b, 0x3c1c, 0x2efc, 0x3b04, 0xbc68,
|
||||
0xb611, 0x38fa, 0xb74f, 0x3f8c, 0x3b22, 0xbf1a, 0xc394, 0x3cef, 0x3ca6, 0x2614, 0x37c3, 0xbe03, 0x3cd0, 0xc072, 0x3f2e, 0xc15f,
|
||||
0x3c11, 0x34da, 0xb4e7, 0x3cf5, 0xc030, 0x3030, 0xb32a, 0x3837, 0xc1c0, 0xbca2, 0x33dd, 0x3ef1, 0x982a, 0xac37, 0x3c5e, 0xb7b3,
|
||||
0xb5b6, 0xb9cd, 0xb9e9, 0x2c0c, 0x3832, 0xab2a, 0xacea, 0x419a, 0x3458, 0x3922, 0xc18e, 0x3c1f, 0x2ae8, 0xb762, 0x393d, 0xbe8c,
|
||||
0xb009, 0xbd47, 0x3d9b, 0x3abd, 0xb95a, 0x3c56, 0x3cfe, 0x3107, 0x37d9, 0xbc56, 0x312d, 0xb846, 0x3752, 0x3d2e, 0x41d2, 0x4030,
|
||||
0xb2d1, 0x3bf0, 0x30c5, 0xbc39, 0xb1ee, 0xb8aa, 0x405a, 0x3d48, 0x3c11, 0x2a02, 0xb800, 0xc184, 0x3dd2, 0x308d, 0xb975, 0xbd48,
|
||||
0x32b5, 0xb942, 0x38c6, 0xbe0e, 0x3688, 0xc06f, 0x33b3, 0xbc61, 0x3910, 0xc094, 0x3cb1, 0x38f8, 0xbe18, 0xc2b8, 0x37d6, 0xb3de,
|
||||
0xab85, 0x3b2e, 0xb8f6, 0x299c, 0x3676, 0xbdb1, 0xb87d, 0x3f26, 0x3068, 0xc117, 0xb7ae, 0x3a16, 0x30ea, 0x3b44, 0xb347, 0x30a9,
|
||||
0x31a2, 0x39c3, 0x36bf, 0x3021, 0x38f6, 0xbc13, 0xb882, 0x338d, 0xb892, 0x3bf4, 0x385d, 0xba38, 0x3b4e, 0x305d, 0x43aa, 0x387b,
|
||||
0x36a4, 0xb0c4, 0xb800, 0xb925, 0xb9d7, 0xbdef, 0xbba6, 0x4244, 0x36da, 0x3452, 0x3b75, 0xc191, 0x381f, 0x318b, 0x38a3, 0x405a,
|
||||
0xba2a, 0x3d74, 0xb9b5, 0x3666, 0x3990, 0x3802, 0xb8ed, 0x37cc, 0x3697, 0x36e9, 0x3d43, 0xb3ef, 0xbaa8, 0x3cbf, 0xbdf3, 0xadc4,
|
||||
0x2c73, 0xb0b6, 0xbbd5, 0x386a, 0xbaaf, 0xbece, 0x35f2, 0x3d58, 0x358e, 0x3ca3, 0xb987, 0x3d37, 0x3770, 0x3cba, 0x3d8a, 0x400f,
|
||||
0x37a5, 0x3910, 0x3bce, 0x3148, 0xb10b, 0xb1f2, 0x343f, 0x3a6d, 0x399b, 0xb733, 0x38b6, 0x3550, 0xbe87, 0xb90a, 0xc1ea, 0xbe4b,
|
||||
0xbe96, 0xbe8f, 0x3999, 0xb92a, 0x3a77, 0xb1c8, 0x366c, 0x3508, 0xb7aa, 0xbcc4, 0xb03d, 0xb591, 0xbecf, 0xb9fc, 0xbb2f, 0x40f5,
|
||||
0x4073, 0xc0db, 0x421c, 0xbf44, 0x339f, 0x34cd, 0x37bd, 0xb4dc, 0xb531, 0xb44c, 0x3e9d, 0x3b38, 0xba12, 0xa9ff, 0x3655, 0xb9ce,
|
||||
0xb32e, 0x3441, 0x3f6f, 0x3c08, 0x3a43, 0xb860, 0xbcf7, 0x3dfe, 0xc07a, 0xbc86, 0x3745, 0xbbf6, 0x2987, 0x36a6, 0x35e0, 0x267f,
|
||||
0xb4b8, 0xb9f1, 0xb865, 0x3a39, 0x2f53, 0xbd26, 0x37b5, 0x388c, 0x3b0e, 0xb889, 0x3c18, 0xa422, 0xb894, 0x1666, 0xb37f, 0xaf72,
|
||||
0x3772, 0xb081, 0xc090, 0xb0ea, 0x33ad, 0x41d0, 0xb75b, 0x345f, 0x3de3, 0xba82, 0xafd1, 0xb979, 0x3f52, 0x36ec, 0xb928, 0x42c7,
|
||||
0xbc71, 0xb54e, 0x3b45, 0x356d, 0xb63d, 0x3d77, 0xa722, 0x2873, 0x3ab5, 0xac22, 0xbe38, 0x3ccb, 0xb82f, 0xba9d, 0xb88a, 0x34f9,
|
||||
0x3dde, 0xb997, 0xc1b1, 0x399d, 0x3d55, 0xc19a, 0xb380, 0x3e72, 0xb701, 0xbd0a, 0xc16c, 0xba7f, 0x39a8, 0x3df0, 0xbf04, 0xb595,
|
||||
0xba46, 0xb904, 0x3ab7, 0x35c9, 0xb181, 0xb9da, 0xba29, 0x3a40, 0xbee1, 0xb257, 0xc262, 0xbabb, 0x3d35, 0x39fa, 0x2661, 0x3922,
|
||||
0xb5da, 0x3c35, 0xac1e, 0xbc02, 0xb9c2, 0x375b, 0x343c, 0xb5e8, 0xbc03, 0xbd4a, 0x2c70, 0x3840, 0xb98c, 0x3a48, 0xbd06, 0xb987,
|
||||
0xc008, 0x3a3f, 0x3676, 0xadf0, 0x391e, 0x437f, 0x4179, 0x38df, 0x3a92, 0x3dd2, 0xb42f, 0xb870, 0x3e99, 0xb0b3, 0x3136, 0x3c3b,
|
||||
0xb98b, 0x3b57, 0xaf33, 0x3d80, 0xb578, 0x3475, 0x3f58, 0xb620, 0x3a60, 0x386c, 0xaf9c, 0xbc68, 0x3826, 0xb99a, 0xb8c8, 0xb414,
|
||||
0xb952, 0x374b, 0x40e7, 0xba0c, 0x3a49, 0x4072, 0xb76d, 0xbc2a, 0xbc67, 0xaebb, 0x3a0b, 0xba0d, 0x3f56, 0x3e43, 0x3d02, 0xbc43,
|
||||
0xb9a2, 0x3e82, 0x3a1f, 0xb796, 0x355d, 0xbc5c, 0x3a70, 0xba8a, 0x333c, 0xbd61, 0x3caf, 0xb9c7, 0xbd93, 0x31f0, 0xbd05, 0xbce5,
|
||||
0xb4b9, 0xba81, 0xbc7d, 0xbbf2, 0x3740, 0xb976, 0xb53f, 0xbe7b, 0xbced, 0xb266, 0x30be, 0x3bda, 0x3f03, 0xbab0, 0x3bdf, 0xbfc7,
|
||||
0xadc6, 0xbf88, 0xb00b, 0x2c42, 0x3e4d, 0xc2c9, 0xbe94, 0x4114, 0x3b5a, 0xbcba, 0x3d7c, 0xbd31, 0x3726, 0x37ac, 0x397e, 0x3a3a,
|
||||
0x2f06, 0xbcd0, 0x3d0c, 0x3cb9, 0x35a6, 0x3f37, 0x41f6, 0xb161, 0xba84, 0x3e57, 0xb423, 0x3e1e, 0x3eb8, 0x2e08, 0xb1c0, 0xbc7f,
|
||||
0x3bef, 0xc03a, 0xbcc4, 0xbb16, 0x38a5, 0x3c4a, 0x3b7f, 0x3bf8, 0x39c9, 0x2964, 0xbddc, 0xb944, 0x406a, 0x3717, 0xb80f, 0xaef2,
|
||||
0x38c2, 0xbf14, 0x3633, 0x37eb, 0x2c27, 0x3d19, 0xba23, 0x37d2, 0x31dd, 0x3823, 0xbb12, 0x39a3, 0xb985, 0xb57c, 0xb7fa, 0x36a5,
|
||||
0xb882, 0x3b5b, 0x3856, 0x34c0, 0x3a69, 0xb60d, 0xc03c, 0x3b6e, 0x3b95, 0x219c, 0xac3a, 0xbdd6, 0x4008, 0x356f, 0xae4c, 0x33cb,
|
||||
0xbd84, 0x3c41, 0x3ba0, 0x3b3c, 0xbb56, 0x387e, 0x3b22, 0xba14, 0x33cb, 0x3f8d, 0x3508, 0x18e0, 0x3b2d, 0xa89e, 0x3c83, 0x3c7f,
|
||||
0x3cd9, 0xb82a, 0x39b5, 0x3912, 0x39d4, 0xbb1c, 0xb8ed, 0xb1de, 0x3b0b, 0xbb92, 0x3be0, 0x4178, 0x3716, 0x31e8, 0xb3ff, 0xbc80,
|
||||
0xba07, 0x393e, 0x39a9, 0xba87, 0xbb2d, 0x4185, 0xb616, 0x32fd, 0xb9d6, 0xbbe7, 0x3645, 0x3cee, 0xb4c6, 0xbcba, 0x3e24, 0xac74,
|
||||
0x2b37, 0xb9ba, 0x3c42, 0x3142, 0x3505, 0x33e9, 0xbe07, 0xb53e, 0xb609, 0x3b1d, 0xbd2b, 0x36e4, 0x3c8a, 0x36fb, 0x39e9, 0xb8c3,
|
||||
0x3fba, 0x4295, 0x3766, 0xbf1a, 0x39e3, 0x3ca3, 0x3fc7, 0xb434, 0xb899, 0xbb95, 0x398e, 0xb2e3, 0xbcd6, 0xb5c8, 0x38c5, 0xb442,
|
||||
0x3cf2, 0x407d, 0xb6e2, 0xb847, 0x3a6a, 0xbdcd, 0x34b0, 0xb342, 0x3a83, 0x2d94, 0x3e96, 0xb644, 0xbead, 0x3e5d, 0xb0bb, 0x39cd,
|
||||
0xa92f, 0xba58, 0x3c0b, 0xbdf9, 0x39ad, 0xa459, 0x3e21, 0xbd5c, 0x3d83, 0x41c8, 0x3299, 0xbeb7, 0xb260, 0xbc3a, 0xb6c7, 0xb98c,
|
||||
0x321a, 0x3d96, 0x3834, 0x3a6f, 0x3920, 0x3d35, 0x28a0, 0xbe28, 0xbe36, 0xb9db, 0xb7d3, 0xbbba, 0xbbd1, 0x357f, 0xbd91, 0xc114,
|
||||
0xb5fd, 0xae9b, 0xc078, 0xb85b, 0xc123, 0xb4c3, 0x38b3, 0xb796, 0xbb1b, 0x3ab8, 0x33b3, 0x37e5, 0x1a62, 0x3a31, 0xb4f1, 0x3a67,
|
||||
0xbbce, 0x3e7b, 0xb73c, 0xbc7c, 0x408e, 0x4098, 0xbe64, 0x342b, 0x3da6, 0x39c7, 0x4077, 0x1dea, 0xaf4e, 0x3c46, 0x3ebd, 0xbbe8,
|
||||
0x3936, 0x3cd8, 0x402f, 0x3e99, 0x3c05, 0xb2d2, 0xbc89, 0xb1eb, 0x2dfa, 0x3d84, 0xbed9, 0xbb80, 0x38a5, 0xbb72, 0xbc2c, 0xb173,
|
||||
0xb84d, 0xb35d, 0xb0ff, 0x3e9f, 0xbc79, 0x3b57, 0xbb5b, 0x307d, 0xb498, 0x3703, 0xbe4a, 0x38be, 0xb878, 0xab2e, 0x3b46, 0xbacc,
|
||||
0x3ab4, 0x32d8, 0xc20b, 0x365b, 0x35ac, 0x36ed, 0x40e5, 0x2d1b, 0xb594, 0xb0f7, 0xba7a, 0xbe4c, 0xa99c, 0xb070, 0xb21f, 0x2dca,
|
||||
0xbf8a, 0x3fd8, 0xb83e, 0x391b, 0xbc35, 0x330f, 0x34e7, 0xb698, 0xb482, 0x34c1, 0x36cd, 0xb818, 0x3e69, 0xb449, 0x3646, 0x31ab,
|
||||
0x38c2, 0x341e, 0x3925, 0xb987, 0x38e5, 0x41b9, 0xb79d, 0xb1ac, 0x36c6, 0x38f9, 0xc103, 0xa977, 0xbead, 0xbce0, 0xbc63, 0xb897,
|
||||
0x3f5d, 0xb842, 0x3d63, 0x3875, 0xab3a, 0xad0b, 0x25c0, 0xbcd6, 0x38d6, 0xb851, 0xb9a9, 0xc077, 0x3be3, 0xb4a1, 0xc293, 0x39c4,
|
||||
0x32dc, 0x414b, 0x3ada, 0x38cc, 0xbad6, 0x3b60, 0x3a85, 0xb52e, 0x3d6c, 0x3d6d, 0xb5a4, 0xb855, 0x2ccf, 0x27f6, 0x35b1, 0xbcf6,
|
||||
0x34df, 0xb4a0, 0xbe85, 0xb62a, 0x39d4, 0xad0d, 0xb542, 0xab88, 0x35dd, 0x345a, 0x353b, 0x3951, 0xb8f8, 0x2f10, 0xbaae, 0x363f,
|
||||
0x3878, 0x3ca2, 0x35df, 0x38da, 0xb443, 0xbcfd, 0xb87e, 0x2fdb, 0xbc75, 0x36ab, 0x389a, 0x3243, 0x29dc, 0xba70, 0x2ee6, 0x3250,
|
||||
0xb748, 0x3d29, 0x40a9, 0xbe21, 0xbba6, 0xb60d, 0xbbbc, 0x3c40, 0xb5dd, 0xbb7b, 0x2631, 0x3bf3, 0xbfbb, 0x2ad5, 0x35b7, 0xb417,
|
||||
0xafde, 0x3831, 0xb651, 0x3145, 0x3cfa, 0xb23f, 0x39ff, 0xb56f, 0xbd12, 0x3f03, 0x33d8, 0x3623, 0x3401, 0x3e04, 0xbe9f, 0x3f6b,
|
||||
0x30db, 0xa9d7, 0x31d9, 0xb34d, 0x9f5e, 0x3252, 0xc0f6, 0x3c75, 0x348d, 0xb8ec, 0x38d0, 0x3841, 0x3abf, 0x20a8, 0xc090, 0x2b97,
|
||||
0xbf35, 0xac01, 0xb854, 0x3722, 0xc074, 0x344d, 0x3a91, 0x3972, 0xbe82, 0x39b9, 0xb62c, 0xc02a, 0xbb3a, 0xba61, 0x2fcb, 0x3a29,
|
||||
0xba51, 0xbb4e, 0xb604, 0x3d17, 0x363e, 0x3b16, 0x3c14, 0x3ab9, 0xb80d, 0x3a9c, 0xb0df, 0x3936, 0xb50c, 0xb8ca, 0xbd85, 0x35f3,
|
||||
0x2ffc, 0xb02b, 0xc0b9, 0x38fe, 0x390d, 0xba48, 0x408f, 0xbc03, 0xb937, 0x3646, 0xc22b, 0xc0c1, 0xbab4, 0xbad0, 0xb3f6, 0x99a8,
|
||||
0xbc8c, 0xbf40, 0x2074, 0xbc80, 0xb927, 0xb89b, 0x33be, 0xa9e5, 0x417f, 0x3229, 0xb346, 0x353c, 0x395d, 0xb883, 0x3d69, 0xbadd,
|
||||
0x3c6c, 0xa743, 0xbd97, 0x3466, 0xbf85, 0x3977, 0x3618, 0x3976, 0x3e77, 0xb9f8, 0xbe06, 0xc024, 0xbc84, 0x325a, 0xbb6c, 0x3d18,
|
||||
0xb930, 0xbca2, 0xb806, 0xbfb2, 0x3578, 0xb253, 0xb48c, 0x33f1, 0xb9ac, 0xbb21, 0xb012, 0x374a, 0xb0cc, 0x3c0b, 0xaca9, 0x3dc8,
|
||||
0xb4d9, 0x322c, 0xab2c, 0xb993, 0x3aa6, 0x3a91, 0x42a1, 0x3da6, 0x3151, 0x3e59, 0x3751, 0x2d8e, 0x3365, 0x2d9a, 0xbaaa, 0xb77f,
|
||||
0xb7f0, 0x32ee, 0x3dd2, 0xbb78, 0x3d0e, 0xbe1c, 0xbe19, 0xbd05, 0xbcfe, 0xbebd, 0xbba1, 0x36b0, 0x3962, 0x4006, 0x380e, 0x370d,
|
||||
0x3e08, 0x3b9c, 0x2bfe, 0xb2a8, 0x3dd4, 0xc038, 0xc00f, 0xb32c, 0x33b5, 0x39f3, 0x3691, 0xb893, 0xbb79, 0xac1f, 0x3d09, 0xbd82,
|
||||
0xafcd, 0xb867, 0xc01c, 0xbbb5, 0xbbca, 0xb323, 0xb8d8, 0x3d5d, 0xbbda, 0x2db4, 0xb8ca, 0x38f9, 0xb615, 0x3a87, 0x321c, 0xc099,
|
||||
0x3a26, 0x3f8c, 0x30a7, 0x36f1, 0x386f, 0xc2a5, 0xb485, 0xb157, 0xb4d2, 0x3f94, 0x2056, 0xb1bb, 0xbb33, 0x35db, 0x35b5, 0xba51,
|
||||
0xbe3f, 0x845e, 0xb7cd, 0xbd67, 0x2dae, 0xb670, 0x399d, 0xc11f, 0x2c99, 0x378e, 0xb735, 0xbe92, 0x4021, 0x3c61, 0xba18, 0x34c2,
|
||||
0xb993, 0xb927, 0xb98a, 0xb82a, 0xba9d, 0xbf68, 0xb507, 0xb7f9, 0x40e7, 0xb718, 0x1e42, 0x3cd3, 0x2b48, 0x3a82, 0x3ef1, 0xbf98,
|
||||
0xb0ad, 0x3a56, 0x34a6, 0xbc12, 0x3fe4, 0x31d6, 0x3d63, 0xa315, 0x22f5, 0xb81a, 0x3b45, 0x32d7, 0x3e26, 0x3689, 0x3d81, 0xbc0c,
|
||||
0x3d04, 0xbcd3, 0x36b2, 0xb5c8, 0x37bb, 0xb86b, 0xb658, 0x3c81, 0xb81b, 0xba20, 0x356a, 0xadad, 0xbe5d, 0x3048, 0xb9d4, 0x301d,
|
||||
0xadb0, 0x3d2d, 0xaa8b, 0xb415, 0xb4b2, 0x413f, 0x3c3c, 0xb516, 0xaff4, 0x3572, 0xb682, 0xbbf6, 0xbbce, 0x3bd3, 0x3a19, 0x3d0a,
|
||||
0x3729, 0x3592, 0xbc5f, 0x3a21, 0x3c5b, 0xb667, 0x3c4b, 0x38c7, 0x3180, 0xaecd, 0xbd82, 0xb9d9, 0xac5a, 0x36d1, 0xc22c, 0x2c34,
|
||||
0xbcae, 0xb450, 0x3f37, 0x388f, 0xb698, 0xb5fd, 0x23d2, 0x3b4a, 0xb721, 0xae67, 0x3cbc, 0xab02, 0x39d8, 0xbd73, 0x98eb, 0xbaf1,
|
||||
0x3ad1, 0x381e, 0xb864, 0xbc12, 0xc0e9, 0xc084, 0x3831, 0x3971, 0x3ca9, 0xb2fa, 0xa167, 0x3708, 0x405f, 0xb9ca, 0x3ca1, 0x31ad,
|
||||
0x383f, 0x339d, 0x389a, 0x364f, 0xb77d, 0x3db4, 0xb56a, 0xb2bc, 0xba8f, 0xb4dd, 0xbf46, 0x32b6, 0x381e, 0xb90a, 0x3db5, 0xbf8a,
|
||||
0xbc4e, 0x37b4, 0xbc0e, 0xad30, 0x3c84, 0x3d83, 0x3a52, 0x3a04, 0xbc64, 0x4027, 0x3c18, 0x3e6d, 0xbcce, 0xaf48, 0xb052, 0x325c,
|
||||
0xb876, 0xbf1d, 0xbafa, 0xaf28, 0x3a5b, 0x3498, 0xaab7, 0xbc54, 0x3fdb, 0x3d7e, 0x39e0, 0xbf20, 0xbfc8, 0xaddc, 0xb815, 0xb83b,
|
||||
0xb793, 0x3798, 0x3915, 0xb6c5, 0xbc75, 0x395b, 0x358f, 0xb960, 0xbc4a, 0xbced, 0xbb4c, 0x34c2, 0x3cfd, 0x2022, 0x2cce, 0x30cf,
|
||||
0xb632, 0xbc4d, 0x3a35, 0x3308, 0x2f07, 0x38d2, 0xbc58, 0x3c45, 0xbae1, 0xb9ad, 0xbb37, 0x3910, 0xbf4b, 0xb91e, 0x374d, 0xb27e,
|
||||
0xb59a, 0x367b, 0x3af6, 0x39fb, 0xbb7c, 0x3a2a, 0xbf2d, 0x2d37, 0xb489, 0x3803, 0x3fc6, 0xbdc6, 0x381d, 0x3fe4, 0x33f7, 0xb508,
|
||||
0x4023, 0xbeb9, 0x3d4c, 0xb0c6, 0xb9aa, 0x38c5, 0xb65d, 0x360a, 0xbd31, 0x3ad7, 0x3f3e, 0x39bf, 0xbc24, 0xb920, 0x3774, 0xb7a3,
|
||||
0xafd2, 0xbcb9, 0xb627, 0x387a, 0xb7cc, 0x38cb, 0xaf26, 0xb37e, 0xb2c5, 0xbad1, 0xb881, 0xb982, 0xbe79, 0xbf5f, 0xb58c, 0x3cb6,
|
||||
0xb76a, 0xc084, 0x3888, 0x305f, 0x4386, 0xbb1c, 0x318f, 0x2990, 0xbc45, 0xb415, 0xbd45, 0x3b9a, 0x400b, 0xb6c7, 0x40d8, 0x3f49,
|
||||
0x3b3e, 0x3953, 0x4121, 0x41a5, 0x3e15, 0x3a86, 0xb745, 0xb50c, 0x394d, 0xbc62, 0x3ce8, 0x36fd, 0xb3fe, 0xb7d3, 0x320d, 0x3663,
|
||||
0x38fd, 0x39e8, 0xb2dd, 0x38c0, 0x3992, 0xb516, 0xb019, 0xbc1f, 0x35e3, 0xa8c6, 0x3fda, 0x3975, 0x3dba, 0xc0dd, 0x166a, 0x3863,
|
||||
0xa3cd, 0x3ab2, 0x332f, 0xbcb9, 0xbce3, 0xb88e, 0xbd5e, 0x41f6, 0xba72, 0xbd0a, 0xbac9, 0xc170, 0xbc26, 0xb615, 0xbab0, 0xbca7,
|
||||
0xc082, 0xbb6c, 0x3f5b, 0x415e, 0x3be8, 0xbe9b, 0x3c55, 0x3f32, 0xa521, 0x410a, 0xbf27, 0xbe1e, 0xbca8, 0x39df, 0xb924, 0xbbf5,
|
||||
0xb2aa, 0x39c7, 0x3af7, 0x424b, 0xb4c6, 0xaed0, 0x358e, 0x3532, 0x3116, 0x3924, 0xbee5, 0xc199, 0xba6e, 0x3849, 0x3c77, 0xb920,
|
||||
0x3c82, 0xb481, 0x33de, 0x3c4e, 0xba98, 0x3775, 0xb594, 0x96a7, 0xbd85, 0x4000, 0x2fd0, 0x3fd8, 0x3d71, 0x3bb7, 0x3dc5, 0x3808,
|
||||
0xbc1c, 0x34a8, 0x3d3d, 0xb86c, 0x3bf1, 0x3841, 0x399c, 0xb9d3, 0xbcee, 0xb752, 0x3ab9, 0xb00a, 0xb744, 0x3198, 0x2fcd, 0x398f,
|
||||
0x9a32, 0x3d75, 0x360a, 0x3bbc, 0x37e9, 0xbb59, 0xb969, 0xb330, 0xc0a5, 0x3ae6, 0x3e0c, 0x40b0, 0xbcda, 0x343c, 0x34bc, 0xb86c,
|
||||
0x3cb0, 0x35be, 0xbd82, 0xac1b, 0xbb08, 0xa5a7, 0x34bf, 0xb0f5, 0x3087, 0xb485, 0xa123, 0xbb9c, 0x3df9, 0xb45d, 0x3c17, 0x404c,
|
||||
0x347a, 0x39a3, 0xb6e8, 0xb913, 0xbd20, 0x38ce, 0xc006, 0x40b0, 0x402a, 0xbb4d, 0x3e7d, 0x3e49, 0x3b8b, 0xb6c8, 0x2d82, 0x3b90,
|
||||
0x388d, 0xae29, 0x327b, 0x3ad7, 0x3d10, 0xb984, 0x3933, 0x34cc, 0x3002, 0xbbda, 0xbcf3, 0x3819, 0x2c89, 0xbc31, 0x3dbd, 0x38e8,
|
||||
0xb4e4, 0xbb87, 0xb172, 0x3886, 0x39b9, 0xb829, 0xbd54, 0xb345, 0xb951, 0xba7f, 0x3d9f, 0x36c1, 0xb259, 0x3dd3, 0x3a49, 0x36a4,
|
||||
0x3b65, 0x3cf2, 0xacae, 0xbe2c, 0xbdae, 0x3ba3, 0x356a, 0x3603, 0x3d0e, 0x3370, 0xb96b, 0x2d88, 0xb8d3, 0x36e3, 0xb804, 0x3b24,
|
||||
0xc000, 0xbdd0, 0xc006, 0xb8c7, 0x3dc9, 0x3367, 0xb663, 0x344b, 0x3406, 0x341f, 0xac64, 0xc0cf, 0x34c6, 0x3d02, 0x3676, 0x39f8,
|
||||
0xa4b0, 0x2e04, 0xb4ee, 0x3b5f, 0xbb6d, 0x37d4, 0xb0cc, 0xb491, 0xb1aa, 0xacc8, 0xbea5, 0x3c6c, 0xb99e, 0xbc46, 0xbe17, 0x3b6c,
|
||||
0xbd5d, 0xbf93, 0xb462, 0x38fa, 0xc0e4, 0x331f, 0x3419, 0x3164, 0xbb25, 0x4066, 0xbd61, 0xbe28, 0x3891, 0xbc66, 0x32be, 0xbc0c,
|
||||
0x3055, 0x3dee, 0x20f7, 0xb3ab, 0x31ff, 0x3a50, 0xbe6a, 0xbad6, 0xbb8f, 0x3cb5, 0xbe0a, 0x3e97, 0x3110, 0xbc8b, 0x36cb, 0x3c1b,
|
||||
0xbb83, 0xbe5f, 0xaecd, 0x310b, 0xb4b8, 0x2985, 0x3c4a, 0xb9d9, 0x39c5, 0xbc1d, 0x390b, 0x3d9e, 0x3675, 0xbca4, 0x3ce1, 0xb49c,
|
||||
0xbb08, 0x3fff, 0x3927, 0x35e3, 0xbd50, 0xbc60, 0x39b6, 0xbd13, 0x4123, 0xc2a2, 0xbeab, 0x37d9, 0xb8ed, 0x3425, 0xbace, 0x3a36,
|
||||
0xb0c7, 0x4057, 0x3c69, 0x3e0c, 0xb5b0, 0x3a03, 0xba05, 0xbaa0, 0x19c4, 0x9c4c, 0xb72f, 0x3c37, 0x3467, 0xbd02, 0xb522, 0xb537,
|
||||
0x3673, 0x2c4d, 0xb17b, 0xbdef, 0xb95a, 0x3daa, 0xbbe8, 0xb4e3, 0x3034, 0xbb3a, 0xc116, 0xbd9c, 0x3891, 0xc1d5, 0xbd9f, 0xb874,
|
||||
0xbc4b, 0x357f, 0xb09a, 0x3f79, 0x3f0c, 0xc07e, 0xbbfe, 0xbca2, 0xbb50, 0x2af5, 0xb02f, 0xbaf7, 0xb629, 0xb509, 0x39c8, 0x36fc,
|
||||
0xa825, 0x395c, 0xb901, 0x3553, 0xbd9d, 0xbbeb, 0x39f2, 0xb451, 0x37bc, 0x3f3c, 0x35a3, 0x3866, 0x3046, 0x35fb, 0x3999, 0xbcb3,
|
||||
0xa417, 0x3d1d, 0xbc37, 0x3bec, 0x3c7c, 0x3bfa, 0xbcb8, 0xc1d5, 0x3c1a, 0x3c40, 0xb23c, 0xb73b, 0x3546, 0x3a09, 0xbbf5, 0xbb7f,
|
||||
0x30e8, 0xbe3f, 0x39fe, 0x3a8b, 0x341a, 0x9b02, 0xbc35, 0x2b91, 0x4256, 0x3a51, 0x3fd1, 0xba43, 0xb55c, 0x393a, 0x3c6f, 0xae6a,
|
||||
0x3da8, 0xb266, 0xbd17, 0xba78, 0x35cf, 0x3e3a, 0xb5dd, 0x3e4d, 0x345d, 0x32ff, 0xbca2, 0x35a2, 0xb9f1, 0x3c82, 0xbbc5, 0x38f1,
|
||||
0x3f36, 0xbe7b, 0xbe77, 0xb44a, 0xbd3b, 0x3501, 0x344c, 0xbe42, 0xbc81, 0x3dc3, 0x2613, 0xbf15, 0xbb1c, 0x3c71, 0x345f, 0xba6a,
|
||||
0xb944, 0x3c03, 0xb5ea, 0xbae1, 0xab67, 0x3e77, 0xc04f, 0xb9db, 0xbe0c, 0xb86e, 0xbc4f, 0xb9cd, 0x3ca8, 0xb07a, 0x36be, 0xb41f,
|
||||
0xac27, 0x3256, 0x3870, 0xb327, 0xb5f6, 0x3b9d, 0x30ba, 0xb8de, 0x3c1b, 0xb06a, 0x3ae1, 0x3d54, 0xba28, 0x3d08, 0x38a3, 0xb938,
|
||||
0x3472, 0xb96b, 0x3945, 0x3b80, 0xadbe, 0x3ab1, 0x3ccf, 0x39b5, 0x34a8, 0x3836, 0xb49e, 0x308c, 0x3916, 0xb5ba, 0xbb8a, 0x3b1b,
|
||||
0xbc56, 0xbe6f, 0xbd9e, 0xb4d5, 0x3e83, 0xa343, 0x3adc, 0xb2fc, 0xba2f, 0x3b55, 0x3cec, 0xb624, 0x261f, 0x37d7, 0xbf76, 0x3eb1,
|
||||
0x38b1, 0xb9c8, 0xa60d, 0x361c, 0xbca6, 0xc00c, 0xbb55, 0xbc6b, 0x34c5, 0x38ba, 0xb802, 0x383c, 0xbd59, 0x3e68, 0x3a2e, 0xbbad,
|
||||
0x3c74, 0x3b24, 0x3010, 0x3ebf, 0xb953, 0xbfa8, 0xb16b, 0x3b7c, 0x3952, 0x2c82, 0xb8ef, 0x412c, 0xb7ec, 0x3cdb, 0x3bc9, 0x38e0,
|
||||
0xbbfb, 0xbaa3, 0x3f28, 0xb1df, 0x3a77, 0xbccf, 0xb1a5, 0xb933, 0x3018, 0x37cb, 0xbec0, 0x31bc, 0xbd2e, 0x3997, 0x3930, 0x3906,
|
||||
0xb86f, 0x37fd, 0x323d, 0x33e5, 0xa60a, 0x38d7, 0xb30a, 0xb451, 0x3597, 0x3123, 0xc063, 0xbe8a, 0xbe42, 0x37af, 0xaff0, 0x3b21,
|
||||
0x365f, 0xb277, 0xb5b8, 0x2ad2, 0xc11d, 0x3a45, 0x31fd, 0xb500, 0xbf3f, 0xbc72, 0x3038, 0x24a3, 0x2890, 0xb595, 0xc08f, 0xc1c7,
|
||||
0xb86e, 0xbcaa, 0x3189, 0x38a6, 0xb408, 0x325d, 0x2ca7, 0x3b05, 0x3c55, 0xbf35, 0x387c, 0x3b7e, 0x3c20, 0x3a0b, 0x3741, 0x3db8,
|
||||
0x3a12, 0x3c4d, 0xb87c, 0x3d11, 0xbdc9, 0xbed7, 0x2444, 0xbdbb, 0xb9c6, 0x3cc9, 0xae72, 0xba10, 0x38b7, 0x3953, 0xb1e6, 0xbbe2,
|
||||
0xa918, 0x30b1, 0xbc8f, 0x283d, 0xaeb3, 0xb160, 0x3794, 0x3336, 0x3327, 0x401d, 0xbf99, 0x3d15, 0xad02, 0x3a32, 0x3df6, 0x3c57,
|
||||
0xbef4, 0x34ed, 0xbc1f, 0x368c, 0x3aed, 0xb95b, 0x38dd, 0x3bf3, 0x4185, 0x3c2f, 0xbbfc, 0x37b5, 0x37f3, 0x355e, 0x3559, 0x3c46,
|
||||
0xc003, 0x38bc, 0x3b53, 0xbda0, 0xac8d, 0x2acb, 0xb8ac, 0x396c, 0x2be0, 0xbb1f, 0x3ce8, 0x3b90, 0xae9f, 0x3ef8, 0xb33e, 0x3cf4,
|
||||
0x2c97, 0xb898, 0xbaa5, 0x3f56, 0x3e58, 0xbb16, 0xb33c, 0xc004, 0x400e, 0xbc68, 0x38bd, 0xa939, 0x3a55, 0x3b35, 0x40d6, 0x3db5,
|
||||
0x4176, 0xb869, 0x30ba, 0xbd7f, 0xba99, 0xb379, 0x3ecf, 0xb915, 0xb19f, 0x30f2, 0x3e11, 0xb632, 0xbe94, 0x3be5, 0x3d28, 0xac5d,
|
||||
0xb6e7, 0xbb64, 0xb282, 0x4380, 0xbde1, 0x36b5, 0x36c2, 0x3867, 0x3cca, 0x2e1c, 0x31cc, 0x2e2f, 0xb0d4, 0xbcff, 0xbb1c, 0xbd67,
|
||||
0x309a, 0x3d2c, 0xab7d, 0xbd03, 0xbbe1, 0xbefc, 0xbfbe, 0x3b98, 0xb53c, 0xbc72, 0x2f15, 0x3cca, 0xc106, 0xbc36, 0xb702, 0x3b57,
|
||||
0x391a, 0xb4da, 0x3861, 0x3afe, 0x3ea8, 0x335b, 0x34e4, 0xbd62, 0x3f1f, 0xbc86, 0xbcf4, 0x35bc, 0xb34a, 0xbf53, 0x3834, 0xbd10,
|
||||
0x273d, 0x39a1, 0xb839, 0xb4e4, 0x39b8, 0x34da, 0xbed6, 0x3a76, 0x3c50, 0xc0fa, 0xbd35, 0xb061, 0xb1b6, 0x34f0, 0x3ab1, 0xbc18,
|
||||
0xb91d, 0xb62c, 0xbb36, 0xb829, 0xb940, 0xafab, 0x3d46, 0x3e81, 0xb20b, 0xb822, 0xbe39, 0x35fd, 0x32f1, 0x3966, 0x2e17, 0xb543,
|
||||
0xbbed, 0x3a89, 0xb2a3, 0xbcc5, 0x3369, 0xb42b, 0xbbd4, 0x1f58, 0xbc48, 0x3ef4, 0x3bbe, 0xac2b, 0xbdf5, 0xb2e4, 0xbcae, 0x3f94,
|
||||
0xa11a, 0xc068, 0x35bb, 0xb82e, 0x3f77, 0xbbb9, 0xb386, 0x3b46, 0xb675, 0x22f3, 0x3e8b, 0xbcb2, 0xb8ba, 0xba29, 0x4235, 0xbd08,
|
||||
0x1038, 0x3f9f, 0xade8, 0x399f, 0x3363, 0xb9da, 0x3909, 0x37c8, 0x3c82, 0xbc4c, 0xbc3a, 0xb788, 0xa897, 0x39da, 0xb6d2, 0x3bee,
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
// ggml-common.h - the old name of Strata's quant format header, kept as a forwarder so every `#include "ggml-common.h"` keeps working.
|
||||
//
|
||||
// The header is include/strata/quant/strata-quant-common.h, generated by tools/gen_quant_header.py from Strata's own type and codebook tables
|
||||
// (tools/strata_quants.py, tools/strata_quant_tables.py). New code includes that file. The Metal runtime reads the header's TEXT (it cannot
|
||||
// follow an #include), and the Mac package ships it as metal/strata-quant-common.h plus a full-text copy under this old name.
|
||||
#include "../../include/strata/quant/strata-quant-common.h"
|
||||
Reference in New Issue
Block a user