STRA-338: native-cpu-expert = size4-n1 + size4-n2 per module group, nce slices kept for groups they alone touched
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
5b77c18213
commit
2f15b09501
@@ -1,265 +0,0 @@
|
||||
//! The stages of the alternation runner (`kernel_ab alternate`) after the command line is parsed: the preparation
|
||||
//! (paths, schedule file, host facts), the equality phase and the rounds.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The rounds of a schedule: the round number and the processes in the order they run.
|
||||
type Schedule = Vec<(u32, Vec<Proc>)>;
|
||||
|
||||
/// The paths the runner reads and writes.
|
||||
pub(super) struct AltPaths {
|
||||
pub(super) out: PathBuf,
|
||||
pub(super) own_exe: PathBuf,
|
||||
pub(super) kab: PathBuf,
|
||||
}
|
||||
|
||||
impl AltPaths {
|
||||
pub(super) fn records_dir(&self) -> PathBuf {
|
||||
self.out.join("records")
|
||||
}
|
||||
pub(super) fn proc_dir(&self) -> PathBuf {
|
||||
self.out.join("processes")
|
||||
}
|
||||
}
|
||||
|
||||
/// Facts about the host and the parent process, read once at the start.
|
||||
pub(super) struct HostFacts {
|
||||
pub(super) parent_env: Vec<(OsString, OsString)>,
|
||||
pub(super) sibling_at_start: bool,
|
||||
pub(super) machine_role: String,
|
||||
pub(super) rustc_version: String,
|
||||
pub(super) triple: String,
|
||||
}
|
||||
|
||||
/// What every stage of `alternate` reads.
|
||||
pub(super) struct AltRun<'a> {
|
||||
pub(super) a: &'a AltArgs,
|
||||
pub(super) verified: &'a Verified,
|
||||
pub(super) case: &'a CaseEntry,
|
||||
pub(super) trees: Vec<&'static str>,
|
||||
pub(super) procs: Vec<Proc>,
|
||||
pub(super) paths: AltPaths,
|
||||
pub(super) schedule_text: String,
|
||||
pub(super) first_round: u32,
|
||||
pub(super) host: HostFacts,
|
||||
pub(super) started: String,
|
||||
}
|
||||
|
||||
/// Chooses and checks the paths, writes the schedule file (before the first run) and reads the host facts.
|
||||
/// Returns the run and the schedule read back from its file.
|
||||
pub(super) fn prepare_alt_run<'a>(
|
||||
a: &'a AltArgs,
|
||||
verified: &'a Verified,
|
||||
case: &'a CaseEntry,
|
||||
started: String,
|
||||
) -> Result<(AltRun<'a>, Schedule), String> {
|
||||
let paths = resolve_alt_paths(a)?;
|
||||
// a host without AVX-512 has no avx512 cells (the C++ reference trees are identical by construction there)
|
||||
let trees: Vec<&'static str> =
|
||||
TREES.iter().copied().filter(|t| *t != "avx512" || verified.provenance.avx512_ok != Some(false)).collect();
|
||||
let procs = procs_for(&trees);
|
||||
let first_round = (a.batch - 1) * a.rounds + 1;
|
||||
let (schedule, schedule_text) = write_schedule(a, &paths.out, &procs, first_round)?;
|
||||
create_run_dirs(&paths)?;
|
||||
let host = read_host_facts(a);
|
||||
let run = AltRun { a, verified, case, trees, procs, paths, schedule_text, first_round, host, started };
|
||||
Ok((run, schedule))
|
||||
}
|
||||
|
||||
fn resolve_alt_paths(a: &AltArgs) -> Result<AltPaths, String> {
|
||||
let out = a.out.clone().unwrap_or_else(|| sibling_dir(&a.dir, &format!(".alt-{}", a.case)));
|
||||
require_alt_paths(a, &out)?;
|
||||
let own_exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
|
||||
let kab = a.kab.clone().or_else(|| std::env::var_os("KAB").map(PathBuf::from)).unwrap_or_else(default_kab);
|
||||
if !kab.is_file() {
|
||||
return Err(format!(
|
||||
"the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)",
|
||||
kab.display()
|
||||
));
|
||||
}
|
||||
Ok(AltPaths { out, own_exe, kab })
|
||||
}
|
||||
|
||||
/// The output lies outside the run directory and, with the schedule file, outside every Git checkout.
|
||||
fn require_alt_paths(a: &AltArgs, out: &Path) -> Result<(), String> {
|
||||
let abs = |p: &Path| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
if abs(out).starts_with(abs(&a.dir)) || abs(&a.dir).starts_with(abs(out)) {
|
||||
return Err("--out must not contain or lie inside the KAB1 directory".to_owned());
|
||||
}
|
||||
if inside_git_checkout(out) || inside_git_checkout(&a.schedule) {
|
||||
return Err(
|
||||
"--out and --schedule must lie outside every Git checkout (generated artifacts stay out of Git)".to_owned()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `$E2E_ROOT/build/kernel-ab/kab` (the root defaults to `$HOME/work/leleka-e2e`).
|
||||
fn default_kab() -> PathBuf {
|
||||
let root = std::env::var("E2E_ROOT")
|
||||
.unwrap_or_else(|_| format!("{}/work/leleka-e2e", std::env::var("HOME").unwrap_or_default()));
|
||||
PathBuf::from(root).join("build/kernel-ab/kab")
|
||||
}
|
||||
|
||||
/// The schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch.
|
||||
fn write_schedule(a: &AltArgs, out: &Path, procs: &[Proc], first_round: u32) -> Result<(Schedule, String), String> {
|
||||
let planned = make_schedule(a.seed, a.batch, a.rounds, procs);
|
||||
let text = schedule_text(a.seed, a.batch, a.rounds, &a.case, a.pin, first_round, &planned);
|
||||
fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
||||
}
|
||||
create_new_file(&a.schedule, text.as_bytes())?;
|
||||
let schedule =
|
||||
parse_schedule(&fs::read_to_string(&a.schedule).map_err(|e| format!("{}: {e}", a.schedule.display()))?)?;
|
||||
println!(
|
||||
"schedule written to {} (sha256 {}) before the first run: {} rounds x {} processes",
|
||||
a.schedule.display(),
|
||||
sha_hex(text.as_bytes()),
|
||||
schedule.len(),
|
||||
procs.len()
|
||||
);
|
||||
Ok((schedule, text))
|
||||
}
|
||||
|
||||
fn create_run_dirs(paths: &AltPaths) -> Result<(), String> {
|
||||
for d in [paths.records_dir(), paths.proc_dir()] {
|
||||
fs::create_dir_all(&d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_host_facts(a: &AltArgs) -> HostFacts {
|
||||
let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect();
|
||||
let sibling_at_start = sibling_idle(a.pin);
|
||||
let machine_role = machine_role_of(a.machine_role.as_deref());
|
||||
let (rustc_version, triple) = rustc_info();
|
||||
HostFacts { parent_env, sibling_at_start, machine_role, rustc_version, triple }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ equality phase
|
||||
|
||||
/// Our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by timing).
|
||||
pub(super) fn run_equality_phase(run: &AltRun) -> Result<BTreeMap<&'static str, Outcome>, String> {
|
||||
let eq_dir = run.paths.out.join(format!("equality-b{:04}", run.a.batch));
|
||||
let mut equality = BTreeMap::new();
|
||||
for &tree in &run.trees {
|
||||
let outcome = run_equality_tree(run, tree, &eq_dir)?;
|
||||
println!(
|
||||
"EQUALITY {} [{tree}] {}{}",
|
||||
run.a.case,
|
||||
if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
||||
mismatch_detail(&outcome)
|
||||
);
|
||||
equality.insert(tree, outcome);
|
||||
}
|
||||
Ok(equality)
|
||||
}
|
||||
|
||||
fn run_equality_tree(run: &AltRun, tree: &'static str, eq_dir: &Path) -> Result<Outcome, String> {
|
||||
let a = run.a;
|
||||
let p = Proc { imp: Impl::Rust, tree, rep: 'a' };
|
||||
let mut cmd = scrubbed_command(&run.paths.own_exe, &run.host.parent_env, &cell_env(&p));
|
||||
cmd.arg("run-tree")
|
||||
.arg(&a.dir)
|
||||
.args(["--tree", tree, "--case", &a.case, "--out"])
|
||||
.arg(eq_dir)
|
||||
.args(["--pin", &a.pin.to_string()]);
|
||||
run_cell(&mut cmd, &format!("{}/equality", p.name()))?;
|
||||
let (ours, reference) = read_ours_and_reference(eq_dir, &a.dir, run.case, tree, tree)?;
|
||||
Ok(compare_bits(&ours, &reference, run.case.tolerance.as_ref()))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ rounds
|
||||
|
||||
/// Runs every round of the schedule; returns the names of the round records written.
|
||||
pub(super) fn run_rounds(
|
||||
run: &AltRun,
|
||||
schedule: &[(u32, Vec<Proc>)],
|
||||
equality: &BTreeMap<&'static str, Outcome>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let mut ctx = batch_ctx(run, equality);
|
||||
let expect = Expect {
|
||||
manifest_sha: &run.verified.manifest_sha256,
|
||||
input_sha: &run.case.in_sha256,
|
||||
case: &run.a.case,
|
||||
pin: run.a.pin,
|
||||
};
|
||||
let mut written = Vec::new();
|
||||
for (round_no, order) in schedule {
|
||||
let done: Vec<ProcOut> =
|
||||
order.iter().map(|p| run_timed_cell(run, &expect, *round_no, p)).collect::<Result<_, _>>()?;
|
||||
if ctx.cpu_model.is_empty() {
|
||||
ctx.cpu_model = done.iter().find_map(|d| d.cpu_model.clone()).unwrap_or_else(|| "unknown model".to_owned());
|
||||
let batch_file = run.paths.out.join(format!("batch-{:04}.json", run.a.batch));
|
||||
create_new_file(&batch_file, batch_json(run, &ctx.cpu_model, equality)?.as_bytes())?;
|
||||
}
|
||||
written.extend(write_round_records(run, &ctx, *round_no, &done)?);
|
||||
println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::<Vec<_>>().join(" "));
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// What a round record needs that does not change within a batch (the CPU model is filled in after the first round).
|
||||
fn batch_ctx<'a>(run: &'a AltRun, equality: &'a BTreeMap<&'static str, Outcome>) -> BatchCtx<'a> {
|
||||
BatchCtx {
|
||||
verified: run.verified,
|
||||
case: run.case,
|
||||
pin: run.a.pin,
|
||||
machine_role: run.host.machine_role.clone(),
|
||||
os: host_os(),
|
||||
cpu_model: String::new(),
|
||||
started_utc: run.started.clone(),
|
||||
rust_tool: Tool {
|
||||
compiler: "rustc".to_owned(),
|
||||
version: run.host.rustc_version.clone(),
|
||||
triple: run.host.triple.clone(),
|
||||
flags: ours_flags(),
|
||||
},
|
||||
batch: run.a.batch,
|
||||
equality,
|
||||
}
|
||||
}
|
||||
|
||||
/// One fresh process of the round (`time` on the cell's implementation); its JSON is read back and checked.
|
||||
fn run_timed_cell(run: &AltRun, expect: &Expect, round_no: u32, p: &Proc) -> Result<ProcOut, String> {
|
||||
let name = p.name();
|
||||
let file = run.paths.proc_dir().join(format!("r{round_no:05}-{name}.json"));
|
||||
let mut cmd = time_command(run, p, &file);
|
||||
let res = run_cell(&mut cmd, &name)?;
|
||||
fs::write(file.with_extension("log"), [&res.stdout[..], &res.stderr[..]].concat())
|
||||
.map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let bytes =
|
||||
fs::read(&file).map_err(|e| format!("cell {name}: its output {} was not written: {e}", file.display()))?;
|
||||
parse_proc_json(p, &bytes, expect)
|
||||
}
|
||||
|
||||
fn time_command(run: &AltRun, p: &Proc, file: &Path) -> Command {
|
||||
let a = run.a;
|
||||
let program = if p.imp == Impl::Cpp { &run.paths.kab } else { &run.paths.own_exe };
|
||||
let mut cmd = scrubbed_command(program, &run.host.parent_env, &cell_env(p));
|
||||
cmd.arg("time")
|
||||
.args(["--run-dir"])
|
||||
.arg(&a.dir)
|
||||
.args(["--case", &a.case, "--slices", &a.slices.to_string(), "--pin", &a.pin.to_string(), "--out"])
|
||||
.arg(file);
|
||||
if let Some(ms) = a.slice_ms {
|
||||
cmd.args(["--slice-ms", &ms.to_string()]);
|
||||
}
|
||||
if let Some(b) = a.llc_bytes {
|
||||
cmd.args(["--llc-bytes", &b.to_string()]);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Writes the records of one round (never over an existing file); returns their names.
|
||||
fn write_round_records(run: &AltRun, ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result<Vec<String>, String> {
|
||||
let records_dir = run.paths.records_dir();
|
||||
let mut names = Vec::new();
|
||||
for (name, json) in round_records(ctx, round_no, done)? {
|
||||
create_new_file(&records_dir.join(&name), json.as_bytes())?;
|
||||
names.push(name);
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
//! The `batch-NNNN.json` file of the alternation runner: what a batch ran and on which host (it computes no
|
||||
//! statistics).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The batch file, written once after the first round (the CPU model comes from that round's processes).
|
||||
pub(super) fn batch_json(
|
||||
run: &AltRun,
|
||||
cpu_model: &str,
|
||||
equality: &BTreeMap<&'static str, Outcome>,
|
||||
) -> Result<String, String> {
|
||||
let kab_sha = file_sha(&run.paths.kab)?;
|
||||
let exe_sha = file_sha(&run.paths.own_exe)?;
|
||||
let mut j = batch_json_run(run);
|
||||
j += &batch_json_host(run, cpu_model);
|
||||
j += &batch_json_files(run, &kab_sha, &exe_sha);
|
||||
j += &batch_json_tail(run, equality);
|
||||
Ok(j)
|
||||
}
|
||||
|
||||
/// The batch file from its opening brace through the input hash.
|
||||
fn batch_json_run(run: &AltRun) -> String {
|
||||
let (a, first_round) = (run.a, run.first_round);
|
||||
format!(
|
||||
"{{\n \"format\": \"KAB1-alt\",\n \"version\": 1,\n \"batch\": {},\n \"rounds\": {},\n \
|
||||
\"first_round\": {first_round},\n \"run_started_utc\": {},\n \"case\": {},\n \"run_dir\": {},\n \
|
||||
\"manifest_sha256\": {},\n \"input_sha256\": {},\n",
|
||||
a.batch,
|
||||
a.rounds,
|
||||
jstr(&run.started),
|
||||
jstr(&a.case),
|
||||
jstr(&a.dir.display().to_string()),
|
||||
jstr(&run.verified.manifest_sha256),
|
||||
jstr(&run.case.in_sha256)
|
||||
)
|
||||
}
|
||||
|
||||
/// The pin, the pool and the machine, and the seed.
|
||||
fn batch_json_host(run: &AltRun, cpu_model: &str) -> String {
|
||||
let sibling_at_start = run.host.sibling_at_start;
|
||||
format!(
|
||||
" \"pin\": {{\"logical_cpu\": {}, \"sibling_idle_at_start\": {sibling_at_start}}},\n \
|
||||
\"pool\": {{\"workers\": 1}},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": {}, \"os\": {}}},\n \
|
||||
\"seed\": {},\n",
|
||||
run.a.pin,
|
||||
jstr(&run.host.machine_role),
|
||||
jstr(cpu_model),
|
||||
jstr(&host_os()),
|
||||
run.a.seed
|
||||
)
|
||||
}
|
||||
|
||||
/// The schedule file, the C++ driver and this example with their hashes, and the slice settings.
|
||||
fn batch_json_files(run: &AltRun, kab_sha: &str, exe_sha: &str) -> String {
|
||||
let a = run.a;
|
||||
format!(
|
||||
" \"schedule\": {{\"file\": {}, \"sha256\": {}}},\n \"kab\": {{\"path\": {}, \"sha256\": {}}},\n \
|
||||
\"rust_example\": {{\"path\": {}, \"sha256\": {}}},\n \"slices_per_regime\": {},\n \"slice_ms\": {},\n",
|
||||
jstr(&a.schedule.display().to_string()),
|
||||
jstr(&sha_hex(run.schedule_text.as_bytes())),
|
||||
jstr(&run.paths.kab.display().to_string()),
|
||||
jstr(kab_sha),
|
||||
jstr(&run.paths.own_exe.display().to_string()),
|
||||
jstr(exe_sha),
|
||||
a.slices,
|
||||
a.slice_ms.map_or("null".to_owned(), |m| jnum(m, 1))
|
||||
)
|
||||
}
|
||||
|
||||
/// The equality verdicts, the cells and the closing note.
|
||||
fn batch_json_tail(run: &AltRun, equality: &BTreeMap<&'static str, Outcome>) -> String {
|
||||
format!(
|
||||
" \"equality\": [{}],\n \"cells\": [{}],\n \"no_statistics\": \"this file computes no class, no interval \
|
||||
and \
|
||||
no A/A verdict (S0.10b, STRA-313)\"\n}}\n",
|
||||
equality_json(run.case, equality),
|
||||
cells_json(&run.procs)
|
||||
)
|
||||
}
|
||||
|
||||
fn equality_json(case: &CaseEntry, equality: &BTreeMap<&'static str, Outcome>) -> String {
|
||||
equality
|
||||
.iter()
|
||||
.map(|(t, o)| {
|
||||
format!(
|
||||
"{{\"tree\": {}, \"verdict\": \"{}\", \"mode\": \"{}\", \"compared_values\": {}, \"mismatches\": {}}}",
|
||||
jstr(t),
|
||||
if o.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
||||
if case.tolerance.is_some() { "tolerance" } else { "bitwise" },
|
||||
o.compared,
|
||||
o.mismatches
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
fn cells_json(procs: &[Proc]) -> String {
|
||||
procs
|
||||
.iter()
|
||||
.map(|p| {
|
||||
format!(
|
||||
"{{\"process\": {}, \"impl\": {}, \"tree\": {}, \"env_set\": {}, \
|
||||
\"env_scrubbed\": \"every STRATA_* and LELEKA_* variable of the parent\"}}",
|
||||
jstr(&p.name()),
|
||||
jstr(p.imp.name()),
|
||||
jstr(p.tree),
|
||||
json_env(&cell_env(p).into_iter().collect())
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
@@ -6,20 +6,218 @@ use super::*;
|
||||
pub(super) fn cmd_alternate(args: &[String]) -> Result<ExitCode, String> {
|
||||
let a = parse_alt_args(args)?;
|
||||
let started = now_utc();
|
||||
let verified = match verify_or_exit(&a.dir) {
|
||||
let verified = match verify_dir(&a.dir) {
|
||||
Ok(v) => v,
|
||||
Err(code) => return Ok(code),
|
||||
Err(e) => {
|
||||
println!("{e}");
|
||||
return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 }));
|
||||
}
|
||||
};
|
||||
let case = find_case(&verified, &a.case)?.clone();
|
||||
let (run, schedule) = prepare_alt_run(&a, &verified, &case, started)?;
|
||||
let equality = run_equality_phase(&run)?;
|
||||
let written = run_rounds(&run, &schedule, &equality)?;
|
||||
let case = verified
|
||||
.cases
|
||||
.iter()
|
||||
.find(|c| c.id == a.case)
|
||||
.ok_or_else(|| format!("case {} is not in the manifest", a.case))?
|
||||
.clone();
|
||||
let out = a.out.clone().unwrap_or_else(|| {
|
||||
let name = a.dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned());
|
||||
a.dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.alt-{}", a.case))
|
||||
});
|
||||
let abs = |p: &Path| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
if abs(&out).starts_with(abs(&a.dir)) || abs(&a.dir).starts_with(abs(&out)) {
|
||||
return Err("--out must not contain or lie inside the KAB1 directory".to_owned());
|
||||
}
|
||||
if inside_git_checkout(&out) || inside_git_checkout(&a.schedule) {
|
||||
return Err(
|
||||
"--out and --schedule must lie outside every Git checkout (generated artifacts stay out of Git)".to_owned()
|
||||
);
|
||||
}
|
||||
let own_exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
|
||||
let kab = a.kab.clone().or_else(|| std::env::var_os("KAB").map(PathBuf::from)).unwrap_or_else(|| {
|
||||
PathBuf::from(
|
||||
std::env::var("E2E_ROOT")
|
||||
.unwrap_or_else(|_| format!("{}/work/leleka-e2e", std::env::var("HOME").unwrap_or_default())),
|
||||
)
|
||||
.join("build/kernel-ab/kab")
|
||||
});
|
||||
if !kab.is_file() {
|
||||
return Err(format!(
|
||||
"the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)",
|
||||
kab.display()
|
||||
));
|
||||
}
|
||||
// a host without AVX-512 has no avx512 cells (the C++ reference trees are identical by construction there)
|
||||
let trees: Vec<&'static str> =
|
||||
TREES.iter().copied().filter(|t| *t != "avx512" || verified.provenance.avx512_ok != Some(false)).collect();
|
||||
let procs = procs_for(&trees);
|
||||
|
||||
// the schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch
|
||||
let first_round = (a.batch - 1) * a.rounds + 1;
|
||||
let planned = make_schedule(a.seed, a.batch, a.rounds, &procs);
|
||||
let text = schedule_text(a.seed, a.batch, a.rounds, &a.case, a.pin, first_round, &planned);
|
||||
fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
||||
}
|
||||
create_new_file(&a.schedule, text.as_bytes())?;
|
||||
let schedule =
|
||||
parse_schedule(&fs::read_to_string(&a.schedule).map_err(|e| format!("{}: {e}", a.schedule.display()))?)?;
|
||||
println!(
|
||||
"schedule written to {} (sha256 {}) before the first run: {} rounds x {} processes",
|
||||
a.schedule.display(),
|
||||
sha_hex(text.as_bytes()),
|
||||
schedule.len(),
|
||||
procs.len()
|
||||
);
|
||||
let (records_dir, proc_dir) = (out.join("records"), out.join("processes"));
|
||||
for d in [&records_dir, &proc_dir] {
|
||||
fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
}
|
||||
let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect();
|
||||
let sibling_at_start = sibling_idle(a.pin);
|
||||
let machine_role = a
|
||||
.machine_role
|
||||
.clone()
|
||||
.or_else(|| std::env::var("HOSTNAME").ok())
|
||||
.or_else(|| std::env::var("COMPUTERNAME").ok())
|
||||
.unwrap_or_else(|| "unknown".to_owned());
|
||||
let (rustc_version, triple) = rustc_info();
|
||||
|
||||
// equality phase: our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by timing)
|
||||
let eq_dir = out.join(format!("equality-b{:04}", a.batch));
|
||||
let mut equality: BTreeMap<&'static str, Outcome> = BTreeMap::new();
|
||||
for tree in &trees {
|
||||
let p = Proc { imp: Impl::Rust, tree, rep: 'a' };
|
||||
let mut cmd = scrubbed_command(&own_exe, &parent_env, &cell_env(&p));
|
||||
cmd.arg("run-tree")
|
||||
.arg(&a.dir)
|
||||
.args(["--tree", tree, "--case", &a.case, "--out"])
|
||||
.arg(&eq_dir)
|
||||
.args(["--pin", &a.pin.to_string()]);
|
||||
run_cell(&mut cmd, &format!("{}/equality", p.name()))?;
|
||||
let ours_name = format!("case-{}.rust-{tree}.out", a.case);
|
||||
let ours = read_out(&eq_dir.join(&ours_name), &ours_name, case.rows, tree, None).map_err(|e| e.to_string())?;
|
||||
let o = case.outs.iter().find(|o| o.tree == *tree).ok_or("missing reference out")?;
|
||||
let reference = read_out(&a.dir.join(&o.name), &o.name, case.rows, tree, Some((&o.sha256, o.bytes)))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let outcome = compare_bits(&ours, &reference, case.tolerance.as_ref());
|
||||
println!(
|
||||
"EQUALITY {} [{tree}] {}{}",
|
||||
a.case,
|
||||
if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
||||
outcome.first_mismatch.map_or(format!("; {} values", outcome.compared), |(i, x, y)| format!(
|
||||
"; {} of {} values differ, first at {i}: ours {x:#010x} reference {y:#010x}, max abs error {:e}",
|
||||
outcome.mismatches, outcome.compared, outcome.max_abs_error
|
||||
))
|
||||
);
|
||||
equality.insert(tree, outcome);
|
||||
}
|
||||
|
||||
let mut cpu_model = String::new();
|
||||
let batch_json = |cpu_model: String, equality: &BTreeMap<&'static str, Outcome>| -> Result<String, String> {
|
||||
let eq = equality
|
||||
.iter()
|
||||
.map(|(t, o)| {
|
||||
format!(
|
||||
"{{\"tree\": {}, \"verdict\": \"{}\", \"mode\": \"{}\", \"compared_values\": {}, \"mismatches\": {}}}",
|
||||
jstr(t),
|
||||
if o.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
||||
if case.tolerance.is_some() { "tolerance" } else { "bitwise" },
|
||||
o.compared,
|
||||
o.mismatches
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let cells = procs
|
||||
.iter()
|
||||
.map(|p| format!("{{\"process\": {}, \"impl\": {}, \"tree\": {}, \"env_set\": {}, \"env_scrubbed\": \"every STRATA_* and LELEKA_* variable of the parent\"}}", jstr(&p.name()), jstr(p.imp.name()), jstr(p.tree), json_env(&cell_env(p).into_iter().collect())))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
Ok(format!(
|
||||
"{{\n \"format\": \"KAB1-alt\",\n \"version\": 1,\n \"batch\": {},\n \"rounds\": {},\n \"first_round\": {first_round},\n \"run_started_utc\": {},\n \"case\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n \"input_sha256\": {},\n \"pin\": {{\"logical_cpu\": {}, \"sibling_idle_at_start\": {sibling_at_start}}},\n \"pool\": {{\"workers\": 1}},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": {}, \"os\": {}}},\n \"seed\": {},\n \"schedule\": {{\"file\": {}, \"sha256\": {}}},\n \"kab\": {{\"path\": {}, \"sha256\": {}}},\n \"rust_example\": {{\"path\": {}, \"sha256\": {}}},\n \"slices_per_regime\": {},\n \"slice_ms\": {},\n \"equality\": [{eq}],\n \"cells\": [{cells}],\n \"no_statistics\": \"this file computes no class, no interval and no A/A verdict (S0.10b, STRA-313)\"\n}}\n",
|
||||
a.batch,
|
||||
a.rounds,
|
||||
jstr(&started),
|
||||
jstr(&a.case),
|
||||
jstr(&a.dir.display().to_string()),
|
||||
jstr(&verified.manifest_sha256),
|
||||
jstr(&case.in_sha256),
|
||||
a.pin,
|
||||
jstr(&machine_role),
|
||||
jstr(&cpu_model),
|
||||
jstr(&host_os()),
|
||||
a.seed,
|
||||
jstr(&a.schedule.display().to_string()),
|
||||
jstr(&sha_hex(text.as_bytes())),
|
||||
jstr(&kab.display().to_string()),
|
||||
jstr(&file_sha(&kab)?),
|
||||
jstr(&own_exe.display().to_string()),
|
||||
jstr(&file_sha(&own_exe)?),
|
||||
a.slices,
|
||||
a.slice_ms.map_or("null".to_owned(), |m| jnum(m, 1))
|
||||
))
|
||||
};
|
||||
|
||||
let expect =
|
||||
Expect { manifest_sha: &verified.manifest_sha256, input_sha: &case.in_sha256, case: &a.case, pin: a.pin };
|
||||
let mut ctx = BatchCtx {
|
||||
verified: &verified,
|
||||
case: &case,
|
||||
pin: a.pin,
|
||||
machine_role: machine_role.clone(),
|
||||
os: host_os(),
|
||||
cpu_model: String::new(),
|
||||
started_utc: started.clone(),
|
||||
rust_tool: Tool { compiler: "rustc".to_owned(), version: rustc_version, triple, flags: ours_flags() },
|
||||
batch: a.batch,
|
||||
equality: &equality,
|
||||
};
|
||||
let mut written = Vec::new();
|
||||
for (round_no, order) in &schedule {
|
||||
let mut done: Vec<ProcOut> = Vec::new();
|
||||
for p in order {
|
||||
let name = p.name();
|
||||
let file = proc_dir.join(format!("r{round_no:05}-{name}.json"));
|
||||
let mut cmd = scrubbed_command(if p.imp == Impl::Cpp { &kab } else { &own_exe }, &parent_env, &cell_env(p));
|
||||
cmd.arg("time")
|
||||
.args(["--run-dir"])
|
||||
.arg(&a.dir)
|
||||
.args(["--case", &a.case, "--slices", &a.slices.to_string(), "--pin", &a.pin.to_string(), "--out"])
|
||||
.arg(&file);
|
||||
if let Some(ms) = a.slice_ms {
|
||||
cmd.args(["--slice-ms", &ms.to_string()]);
|
||||
}
|
||||
if let Some(b) = a.llc_bytes {
|
||||
cmd.args(["--llc-bytes", &b.to_string()]);
|
||||
}
|
||||
let res = run_cell(&mut cmd, &name)?;
|
||||
fs::write(file.with_extension("log"), [&res.stdout[..], &res.stderr[..]].concat())
|
||||
.map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let bytes = fs::read(&file)
|
||||
.map_err(|e| format!("cell {name}: its output {} was not written: {e}", file.display()))?;
|
||||
done.push(parse_proc_json(p, &bytes, &expect)?);
|
||||
}
|
||||
if cpu_model.is_empty() {
|
||||
cpu_model = done.iter().find_map(|d| d.cpu_model.clone()).unwrap_or_else(|| "unknown model".to_owned());
|
||||
ctx.cpu_model = cpu_model.clone();
|
||||
create_new_file(
|
||||
&out.join(format!("batch-{:04}.json", a.batch)),
|
||||
batch_json(cpu_model.clone(), &equality)?.as_bytes(),
|
||||
)?;
|
||||
}
|
||||
for (name, json) in round_records(&ctx, *round_no, &done)? {
|
||||
create_new_file(&records_dir.join(&name), json.as_bytes())?;
|
||||
written.push(name);
|
||||
}
|
||||
println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::<Vec<_>>().join(" "));
|
||||
}
|
||||
println!(
|
||||
"ALTERNATE OK batch={} rounds={} records={} dir={}",
|
||||
a.batch,
|
||||
a.rounds,
|
||||
written.len(),
|
||||
run.paths.records_dir().display()
|
||||
records_dir.display()
|
||||
);
|
||||
for (t, o) in &equality {
|
||||
println!("EQUALITY-SUMMARY {} {t} {}", a.case, if o.equal() { "EQUAL" } else { "NOT_EQUAL" });
|
||||
@@ -27,25 +225,17 @@ pub(super) fn cmd_alternate(args: &[String]) -> Result<ExitCode, String> {
|
||||
Ok(ExitCode::SUCCESS)
|
||||
}
|
||||
|
||||
/// The manifest entry of the case, or the error that names it.
|
||||
fn find_case<'a>(verified: &'a Verified, id: &str) -> Result<&'a CaseEntry, String> {
|
||||
verified.cases.iter().find(|c| c.id == id).ok_or_else(|| format!("case {id} is not in the manifest"))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ main
|
||||
|
||||
pub(super) fn usage() -> ExitCode {
|
||||
eprintln!(
|
||||
"usage: kernel_ab verify D | compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] | \
|
||||
run-tree D --tree T --out R [--pin CPU] [--case ID]"
|
||||
"usage: kernel_ab verify D | compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] | run-tree D --tree T --out R [--pin CPU] [--case ID]"
|
||||
);
|
||||
eprintln!(
|
||||
" kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] \
|
||||
[--regime both|resident|streamed] [--llc-bytes B]"
|
||||
" kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed] [--llc-bytes B]"
|
||||
);
|
||||
eprintln!(
|
||||
" kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] \
|
||||
[--out R] [--slices N] [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]"
|
||||
" kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N] [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]"
|
||||
);
|
||||
ExitCode::from(64)
|
||||
}
|
||||
|
||||
@@ -1,37 +1,16 @@
|
||||
//! Moved out of the parent module by STRA-338: fn cmd_compare, impl Flags, fn mono_ns, fn core_ghz, fn median_of, fn
|
||||
//! percentile_of ....
|
||||
//! Moved out of the parent module by STRA-338: fn cmd_compare, impl Flags, fn mono_ns, fn core_ghz, fn median_of, fn percentile_of ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// What `compare` knows once the directory is verified and the output directory is chosen.
|
||||
struct ComparePlan<'a> {
|
||||
opts: &'a Options,
|
||||
verified: Verified,
|
||||
out: PathBuf,
|
||||
records: PathBuf,
|
||||
exe: PathBuf,
|
||||
parent_env: Vec<(OsString, OsString)>,
|
||||
started: String,
|
||||
machine_role: String,
|
||||
rustc_version: String,
|
||||
triple: String,
|
||||
}
|
||||
|
||||
/// How the process of one tree ended.
|
||||
enum TreeRun {
|
||||
/// It ran; these are the `REPORT` lines it printed.
|
||||
Ran(Vec<String>),
|
||||
/// This host has no AVX-512 and the manifest says so: the tree is not run.
|
||||
Skipped,
|
||||
Failed,
|
||||
}
|
||||
|
||||
pub(super) fn cmd_compare(dir: &Path, opts: &Options) -> Result<ExitCode, String> {
|
||||
let started = now_utc();
|
||||
let verified = match verify_or_exit(dir) {
|
||||
let verified = match verify_dir(dir) {
|
||||
Ok(v) => v,
|
||||
Err(code) => return Ok(code),
|
||||
Err(e) => {
|
||||
println!("{e}");
|
||||
return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 }));
|
||||
}
|
||||
};
|
||||
println!(
|
||||
"KAB1 directory verified: {} files, {} cases, manifest sha256 {}",
|
||||
@@ -39,189 +18,127 @@ pub(super) fn cmd_compare(dir: &Path, opts: &Options) -> Result<ExitCode, String
|
||||
verified.cases.len(),
|
||||
verified.manifest_sha256
|
||||
);
|
||||
let out = opts.out.clone().unwrap_or_else(|| sibling_dir(dir, ".rust"));
|
||||
require_fresh_out_dir(dir, &out)?;
|
||||
let out = opts.out.clone().unwrap_or_else(|| {
|
||||
let name = dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned());
|
||||
dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.rust"))
|
||||
});
|
||||
if out.starts_with(dir) || dir.starts_with(&out) {
|
||||
return Err("--out must not contain or lie inside the KAB1 directory".to_owned());
|
||||
}
|
||||
if out.exists() && fs::read_dir(&out).map_err(|e| format!("{}: {e}", out.display()))?.next().is_some() {
|
||||
return Err(format!("{} exists and is not empty (nothing is overwritten or deleted)", out.display()));
|
||||
}
|
||||
let records = out.join("records");
|
||||
fs::create_dir_all(&records).map_err(|e| format!("{}: {e}", records.display()))?;
|
||||
let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
|
||||
let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect();
|
||||
let machine_role = machine_role_of(opts.machine_role.as_deref());
|
||||
let (rustc_version, triple) = rustc_info();
|
||||
let plan =
|
||||
ComparePlan { opts, verified, out, records, exe, parent_env, started, machine_role, rustc_version, triple };
|
||||
run_compare_trees(&plan)
|
||||
}
|
||||
|
||||
/// `<dir's parent>/<dir's name><suffix>`: the default output directory next to the run directory.
|
||||
pub(super) fn sibling_dir(dir: &Path, suffix: &str) -> PathBuf {
|
||||
let name = dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned());
|
||||
dir.parent().unwrap_or(Path::new(".")).join(format!("{name}{suffix}"))
|
||||
}
|
||||
|
||||
/// The output directory neither contains nor lies inside the run directory and is absent or empty.
|
||||
fn require_fresh_out_dir(dir: &Path, out: &Path) -> Result<(), String> {
|
||||
if out.starts_with(dir) || dir.starts_with(out) {
|
||||
return Err("--out must not contain or lie inside the KAB1 directory".to_owned());
|
||||
}
|
||||
if out.exists() && fs::read_dir(out).map_err(|e| format!("{}: {e}", out.display()))?.next().is_some() {
|
||||
return Err(format!("{} exists and is not empty (nothing is overwritten or deleted)", out.display()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The machine role: the given name, else the host name from the environment, else `unknown`.
|
||||
pub(super) fn machine_role_of(given: Option<&str>) -> String {
|
||||
given
|
||||
.map(str::to_owned)
|
||||
let machine_role = opts
|
||||
.machine_role
|
||||
.clone()
|
||||
.or_else(|| std::env::var("HOSTNAME").ok())
|
||||
.or_else(|| std::env::var("COMPUTERNAME").ok())
|
||||
.unwrap_or_else(|| "unknown".to_owned())
|
||||
}
|
||||
|
||||
/// The tree with this name from `TREES` (`avx2` for a name that is not one).
|
||||
fn static_tree(tree: &str) -> &'static str {
|
||||
TREES.iter().find(|t| **t == tree).copied().unwrap_or("avx2")
|
||||
}
|
||||
|
||||
fn run_compare_trees(plan: &ComparePlan) -> Result<ExitCode, String> {
|
||||
let (mut all_equal, mut cells) = (true, 0usize);
|
||||
for tree in &plan.opts.trees {
|
||||
let sibling = sibling_idle(plan.opts.pin);
|
||||
let report = match run_tree_process(plan, tree)? {
|
||||
TreeRun::Ran(report) => report,
|
||||
TreeRun::Skipped => continue,
|
||||
TreeRun::Failed => return Ok(ExitCode::from(1)),
|
||||
.unwrap_or_else(|| "unknown".to_owned());
|
||||
let (rustc_version, triple) = rustc_info();
|
||||
let flags = format!(
|
||||
"cargo profile {}; RUSTFLAGS={:?}; target-cpu default",
|
||||
if cfg!(debug_assertions) { "dev" } else { "release" },
|
||||
std::env::var("RUSTFLAGS").unwrap_or_default()
|
||||
);
|
||||
let mut all_equal = true;
|
||||
let mut cells = 0usize;
|
||||
for tree in &opts.trees {
|
||||
let sibling = sibling_idle(opts.pin);
|
||||
let probe = Proc {
|
||||
imp: Impl::Rust,
|
||||
tree: TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2"),
|
||||
rep: 'a',
|
||||
};
|
||||
let mut cmd = scrubbed_command(&exe, &parent_env, &cell_env(&probe));
|
||||
cmd.arg("run-tree").arg(dir).args(["--tree", tree, "--out"]).arg(&out).args(["--pin", &opts.pin.to_string()]);
|
||||
let res = cmd.output().map_err(|e| format!("cannot start the {tree} process: {e}"))?;
|
||||
let stdout = String::from_utf8_lossy(&res.stdout).into_owned();
|
||||
let report: Vec<String> = stdout.lines().filter_map(|l| l.strip_prefix("REPORT ")).map(str::to_owned).collect();
|
||||
match res.status.code() {
|
||||
Some(0) => {}
|
||||
Some(3) if tree == "avx512" && verified.provenance.avx512_ok == Some(false) => {
|
||||
println!(
|
||||
"tree avx512: SKIPPED, this host has no AVX-512 (manifest avx512_ok=false; the reference trees are identical by construction)"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
code => {
|
||||
eprint!("{}", String::from_utf8_lossy(&res.stderr));
|
||||
println!("tree {tree}: the Rust process failed (exit {code:?})");
|
||||
return Ok(ExitCode::from(1));
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"tree {tree}: {}",
|
||||
report.iter().find(|l| l.starts_with("cpu: process kernel family")).map_or("", String::as_str)
|
||||
);
|
||||
for c in &plan.verified.cases {
|
||||
all_equal &= compare_case(plan, tree, c, &report, sibling)?;
|
||||
let tree_name: &str = TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2");
|
||||
for c in &verified.cases {
|
||||
let ours_name = format!("case-{}.rust-{tree}.out", c.id);
|
||||
let ours = read_out(&out.join(&ours_name), &ours_name, c.rows, tree, None).map_err(|e| e.to_string())?;
|
||||
let o = c.outs.iter().find(|o| o.tree == tree_name).ok_or("missing reference out")?;
|
||||
let reference = read_out(&verified.dir.join(&o.name), &o.name, c.rows, tree, Some((&o.sha256, o.bytes)))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let outcome = compare_bits(&ours, &reference, c.tolerance.as_ref());
|
||||
let label = match (&c.tolerance, outcome.equal()) {
|
||||
(None, true) => "bitwise EQUAL".to_owned(),
|
||||
(None, false) => "bitwise NOT EQUAL".to_owned(),
|
||||
(Some(t), eq) => format!(
|
||||
"{} within tolerance {:e} (metric {TOLERANCE_METRIC}; basis: {})",
|
||||
if eq { "EQUAL" } else { "NOT EQUAL" },
|
||||
t.value,
|
||||
t.basis
|
||||
),
|
||||
};
|
||||
let detail = match outcome.first_mismatch {
|
||||
Some((i, a, b)) => format!(
|
||||
"; {} of {} values differ, first at {i}: ours {a:#010x} reference {b:#010x}, max abs error {:e}",
|
||||
outcome.mismatches, outcome.compared, outcome.max_abs_error
|
||||
),
|
||||
None => format!("; {} values", outcome.compared),
|
||||
};
|
||||
println!("case {} [{tree}] {label}{detail}", c.id);
|
||||
all_equal &= outcome.equal();
|
||||
cells += 1;
|
||||
let record = record_json(&RecordInput {
|
||||
record_id: format!(
|
||||
"kab1-{}-{}-{tree}-{}",
|
||||
verified.provenance.run_id,
|
||||
c.id,
|
||||
started.replace([':', '-'], "")
|
||||
),
|
||||
created_utc: now_utc(),
|
||||
run_started_utc: started.clone(),
|
||||
machine_role: machine_role.clone(),
|
||||
cpu_model: cpu_model_of(&report),
|
||||
os: host_os(),
|
||||
ours_compiler: "rustc".to_owned(),
|
||||
ours_version: rustc_version.clone(),
|
||||
ours_triple: triple.clone(),
|
||||
ours_flags: flags.clone(),
|
||||
tree: tree_name,
|
||||
verified: &verified,
|
||||
case: c,
|
||||
pin_cpu: opts.pin,
|
||||
sibling_idle: sibling,
|
||||
outcome: &outcome,
|
||||
});
|
||||
let path = records.join(format!("case-{}.{tree}.record.json", c.id));
|
||||
fs::write(&path, record).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"compared {cells} cells; records in {}; {}",
|
||||
plan.records.display(),
|
||||
records.display(),
|
||||
if all_equal { "ALL EQUAL" } else { "NOT ALL EQUAL" }
|
||||
);
|
||||
Ok(if all_equal && cells > 0 { ExitCode::SUCCESS } else { ExitCode::from(1) })
|
||||
}
|
||||
|
||||
/// Runs `run-tree` for one tree in a fresh process and says how it ended; a skip or a failure is reported here.
|
||||
fn run_tree_process(plan: &ComparePlan, tree: &str) -> Result<TreeRun, String> {
|
||||
let probe = Proc { imp: Impl::Rust, tree: static_tree(tree), rep: 'a' };
|
||||
let mut cmd = scrubbed_command(&plan.exe, &plan.parent_env, &cell_env(&probe));
|
||||
cmd.arg("run-tree").arg(&plan.verified.dir).args(["--tree", tree, "--out"]).arg(&plan.out);
|
||||
cmd.args(["--pin", &plan.opts.pin.to_string()]);
|
||||
let res = cmd.output().map_err(|e| format!("cannot start the {tree} process: {e}"))?;
|
||||
let stdout = String::from_utf8_lossy(&res.stdout).into_owned();
|
||||
let report: Vec<String> = stdout.lines().filter_map(|l| l.strip_prefix("REPORT ")).map(str::to_owned).collect();
|
||||
match res.status.code() {
|
||||
Some(0) => Ok(TreeRun::Ran(report)),
|
||||
Some(3) if tree == "avx512" && plan.verified.provenance.avx512_ok == Some(false) => {
|
||||
println!(
|
||||
"tree avx512: SKIPPED, this host has no AVX-512 (manifest avx512_ok=false; the reference trees are \
|
||||
identical by construction)"
|
||||
);
|
||||
Ok(TreeRun::Skipped)
|
||||
}
|
||||
code => {
|
||||
eprint!("{}", String::from_utf8_lossy(&res.stderr));
|
||||
println!("tree {tree}: the Rust process failed (exit {code:?})");
|
||||
Ok(TreeRun::Failed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Our output against the reference for one case: prints the verdict line, writes the record; true when equal.
|
||||
fn compare_case(
|
||||
plan: &ComparePlan,
|
||||
tree: &str,
|
||||
c: &CaseEntry,
|
||||
report: &[String],
|
||||
sibling: bool,
|
||||
) -> Result<bool, String> {
|
||||
let (ours, reference) = read_ours_and_reference(&plan.out, &plan.verified.dir, c, tree, static_tree(tree))?;
|
||||
let outcome = compare_bits(&ours, &reference, c.tolerance.as_ref());
|
||||
println!("case {} [{tree}] {}{}", c.id, compare_label(c, &outcome), mismatch_detail(&outcome));
|
||||
let record = record_json(&compare_record_input(plan, tree, c, report, sibling, &outcome));
|
||||
let path = plan.records.join(format!("case-{}.{tree}.record.json", c.id));
|
||||
fs::write(&path, record).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
Ok(outcome.equal())
|
||||
}
|
||||
|
||||
/// Reads our `.out` file of the case from `ours_dir` and the C++ reference from `ref_dir` (checked against the
|
||||
/// manifest). `lookup` names the tree whose reference file is taken.
|
||||
pub(super) fn read_ours_and_reference(
|
||||
ours_dir: &Path,
|
||||
ref_dir: &Path,
|
||||
c: &CaseEntry,
|
||||
tree: &str,
|
||||
lookup: &str,
|
||||
) -> Result<(Vec<u32>, Vec<u32>), String> {
|
||||
let ours_name = format!("case-{}.rust-{tree}.out", c.id);
|
||||
let ours = read_out(&ours_dir.join(&ours_name), &ours_name, c.rows, tree, None).map_err(|e| e.to_string())?;
|
||||
let o = c.outs.iter().find(|o| o.tree == lookup).ok_or("missing reference out")?;
|
||||
let reference = read_out(&ref_dir.join(&o.name), &o.name, c.rows, tree, Some((&o.sha256, o.bytes)))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok((ours, reference))
|
||||
}
|
||||
|
||||
fn compare_label(c: &CaseEntry, outcome: &Outcome) -> String {
|
||||
match (&c.tolerance, outcome.equal()) {
|
||||
(None, true) => "bitwise EQUAL".to_owned(),
|
||||
(None, false) => "bitwise NOT EQUAL".to_owned(),
|
||||
(Some(t), eq) => format!(
|
||||
"{} within tolerance {:e} (metric {TOLERANCE_METRIC}; basis: {})",
|
||||
if eq { "EQUAL" } else { "NOT EQUAL" },
|
||||
t.value,
|
||||
t.basis
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// What differs, or how many values were compared when nothing does.
|
||||
pub(super) fn mismatch_detail(o: &Outcome) -> String {
|
||||
match o.first_mismatch {
|
||||
Some((i, a, b)) => format!(
|
||||
"; {} of {} values differ, first at {i}: ours {a:#010x} reference {b:#010x}, max abs error {:e}",
|
||||
o.mismatches, o.compared, o.max_abs_error
|
||||
),
|
||||
None => format!("; {} values", o.compared),
|
||||
}
|
||||
}
|
||||
|
||||
fn compare_record_input<'a>(
|
||||
plan: &'a ComparePlan,
|
||||
tree: &str,
|
||||
c: &'a CaseEntry,
|
||||
report: &[String],
|
||||
sibling: bool,
|
||||
outcome: &'a Outcome,
|
||||
) -> RecordInput<'a> {
|
||||
let run_id = &plan.verified.provenance.run_id;
|
||||
RecordInput {
|
||||
record_id: format!("kab1-{run_id}-{}-{tree}-{}", c.id, plan.started.replace([':', '-'], "")),
|
||||
created_utc: now_utc(),
|
||||
run_started_utc: plan.started.clone(),
|
||||
machine_role: plan.machine_role.clone(),
|
||||
cpu_model: cpu_model_of(report),
|
||||
os: host_os(),
|
||||
ours_compiler: "rustc".to_owned(),
|
||||
ours_version: plan.rustc_version.clone(),
|
||||
ours_triple: plan.triple.clone(),
|
||||
ours_flags: ours_flags(),
|
||||
tree: static_tree(tree),
|
||||
verified: &plan.verified,
|
||||
case: c,
|
||||
pin_cpu: plan.opts.pin,
|
||||
sibling_idle: sibling,
|
||||
outcome,
|
||||
}
|
||||
}
|
||||
|
||||
impl Flags {
|
||||
pub(super) fn parse(args: &[String], known: &[&str]) -> Result<Self, String> {
|
||||
let mut items: Vec<(String, String)> = Vec::new();
|
||||
@@ -248,18 +165,6 @@ impl Flags {
|
||||
pub(super) fn number<T: std::str::FromStr>(&self, k: &str) -> Result<Option<T>, String> {
|
||||
self.get(k).map(|v| v.parse::<T>().map_err(|_| format!("--{k} {v:?} is not a valid number"))).transpose()
|
||||
}
|
||||
/// A number that must be given: `--k` missing is an error.
|
||||
pub(super) fn need_number<T: std::str::FromStr>(&self, k: &str) -> Result<T, String> {
|
||||
self.number::<T>(k)?.ok_or_else(|| format!("--{k} is required"))
|
||||
}
|
||||
/// The `--case` value, which must be a plain identifier.
|
||||
pub(super) fn case_id(&self) -> Result<String, String> {
|
||||
let case = self.req("case")?.to_owned();
|
||||
if !valid_id(&case) {
|
||||
return Err(format!("--case {case:?} is not a plain identifier"));
|
||||
}
|
||||
Ok(case)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn mono_ns() -> u64 {
|
||||
@@ -267,9 +172,9 @@ pub(super) fn mono_ns() -> u64 {
|
||||
ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() as u64
|
||||
}
|
||||
|
||||
/// The core clock in GHz from a chain of dependent steps (safe code: the C++ chain of dependent adds needs inline
|
||||
/// assembly). A plain chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every step
|
||||
/// also xors in a shifted copy of the running value, which no reassociation can remove.
|
||||
/// The core clock in GHz from a chain of dependent steps (safe code: the C++ chain of dependent adds needs inline assembly). A plain
|
||||
/// chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every step also xors in a shifted copy of the
|
||||
/// running value, which no reassociation can remove.
|
||||
pub(super) fn core_ghz() -> f64 {
|
||||
let k = std::hint::black_box(0x9E37_79B9_7F4A_7C15u64 | 1);
|
||||
let mut x = std::hint::black_box(1u64);
|
||||
|
||||
@@ -3,55 +3,245 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// `kernel_ab time ...`: one fresh process, one case, the resident and the streamed regime, JSON written by tmp +
|
||||
/// rename. Exit codes as `kab time`: 0 ok; 1 usage / refused input; 3 a regime kept no slice or a slice migrated off
|
||||
/// the pin; 4 the final output differs.
|
||||
/// `kernel_ab time ...`: one fresh process, one case, the resident and the streamed regime, JSON written by tmp + rename. Exit codes as
|
||||
/// `kab time`: 0 ok; 1 usage / refused input; 3 a regime kept no slice or a slice migrated off the pin; 4 the final output differs.
|
||||
pub(super) fn cmd_time(args: &[String]) -> Result<ExitCode, String> {
|
||||
let p = prepare_time_run(args)?;
|
||||
let (pool, want) = first_call(&p.tc.case)?;
|
||||
let t = parse_time_args(args)?;
|
||||
let wall0 = mono_ns();
|
||||
// pin first (before any buffer or pool exists, so the pool's threads inherit the mask), then the facts about the pin
|
||||
if rust_topology::pin_current_thread(t.pin as i32) < 0 {
|
||||
return Err(format!("the pin to CPU {} was refused", t.pin));
|
||||
}
|
||||
if cfg!(target_os = "linux") && current_cpu() != Some(t.pin) {
|
||||
return Err(format!("the process is not running on CPU {} after the pin", t.pin));
|
||||
}
|
||||
let cpu_dir = format!("/sys/devices/system/cpu/cpu{}", t.pin);
|
||||
let sib_text = read_text(&format!("{cpu_dir}/topology/thread_siblings_list"));
|
||||
let sibling = parse_cpu_list(&sib_text).into_iter().rfind(|c| *c != t.pin);
|
||||
let sib0 = sibling.and_then(proc_stat_cpu);
|
||||
let pin0 = proc_stat_cpu(t.pin);
|
||||
let load0 = read_text("/proc/loadavg");
|
||||
|
||||
// the case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes
|
||||
let (manifest_bytes, _provenance, cases, _files) = read_manifest(&t.dir).map_err(|e| e.to_string())?;
|
||||
let manifest_sha = sha_hex(&manifest_bytes);
|
||||
let entry =
|
||||
cases.iter().find(|c| c.id == t.case).ok_or_else(|| format!("case {} is not in the manifest", t.case))?;
|
||||
let case = read_case_in(&t.dir, entry).map_err(|e| e.to_string())?;
|
||||
let header = case.header;
|
||||
let weights = &case.blob[IN_HEADER..header.input_at()];
|
||||
let expert_bytes = weights.len();
|
||||
|
||||
// environment and tree
|
||||
let env = managed_env_now();
|
||||
let report = cpu_kernel_report();
|
||||
let tree = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?;
|
||||
|
||||
// the streamed set: K copies, K x stride at least 2 x the last-level cache of the pinned CPU (the design choice of kab_time.cpp)
|
||||
let llc = match (t.llc_bytes, llc_of_cpu(t.pin)) {
|
||||
(Some(bytes), found) => {
|
||||
Llc { level: found.map_or(0, |l| l.level), bytes, source: "--llc-bytes (override)".to_owned() }
|
||||
}
|
||||
(None, Some(l)) => l,
|
||||
(None, None) => {
|
||||
return Err(format!("cannot read the last-level cache size of CPU {} from sysfs; pass --llc-bytes", t.pin));
|
||||
}
|
||||
};
|
||||
if llc.bytes == 0 {
|
||||
return Err("--llc-bytes must be positive".to_owned());
|
||||
}
|
||||
let stride = expert_bytes.div_ceil(ALIGN) * ALIGN;
|
||||
let copies_k = ((2 * llc.bytes) / stride as u64) as usize + 1;
|
||||
if copies_k * stride > (4usize << 30) {
|
||||
return Err("the streamed working set would exceed 4 GiB; check --llc-bytes".to_owned());
|
||||
}
|
||||
|
||||
// the pool is created AFTER the pin: its worker inherits the one-CPU mask (rust_platform::cores sees a one-CPU affinity)
|
||||
let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?;
|
||||
let want = compute_case(&mut pool, &case)?;
|
||||
let want_bits: Vec<u32> = want.iter().map(|v| v.to_bits()).collect();
|
||||
let output_sha = f32_bits_sha(&want);
|
||||
let buffers = fill_buffers(&p.tc.case, &p.plan);
|
||||
let copies = buffers.copies(&p.plan);
|
||||
let mut timed = buffers.timed(pool, p.tc.case.header)?;
|
||||
let m = measure(&p.t, &p.plan, &mut timed, &copies, &want_bits)?;
|
||||
let end = read_pin_end(&p.start, p.t.pin);
|
||||
let report = TimeReport { p: &p, end: &end, m: &m, output_sha: &output_sha };
|
||||
write_time_json(&p.t.out, &render_time_json(&report))?;
|
||||
print_time_summary(&p, &m);
|
||||
Ok(time_exit_code(&p.t, &m))
|
||||
}
|
||||
|
||||
fn print_time_summary(p: &Prepared, m: &Measured) {
|
||||
println!(
|
||||
"kernel_ab time: case={} tree={} pin={} slices={} resident_kept={} streamed_kept={} K={} out={}",
|
||||
p.t.case,
|
||||
p.tree,
|
||||
p.t.pin,
|
||||
p.t.slices,
|
||||
m.regimes.kept_res,
|
||||
m.regimes.kept_stm,
|
||||
p.plan.copies_k,
|
||||
p.t.out.display()
|
||||
let mut tokens = Arena::<f32>::new(header.rows * H);
|
||||
tokens.slice_mut(header.rows * H).copy_from_slice(&case.input());
|
||||
let mut resident = Arena::<u8>::new(stride);
|
||||
resident.slice_mut(expert_bytes).copy_from_slice(weights);
|
||||
let mut streamed = Arena::<u8>::new(stride * copies_k);
|
||||
for k in 0..copies_k {
|
||||
streamed.slice_mut(stride * copies_k)[k * stride..k * stride + expert_bytes].copy_from_slice(weights);
|
||||
}
|
||||
let res_copies: Vec<&[u8]> = vec![resident.slice(expert_bytes)];
|
||||
let stm_all = streamed.slice(stride * copies_k);
|
||||
let stm_copies: Vec<&[u8]> = (0..copies_k).map(|k| &stm_all[k * stride..k * stride + expert_bytes]).collect();
|
||||
|
||||
let mut timed = Timed {
|
||||
pool,
|
||||
gu: gate_up_row(header.gu).ok_or("gate/up type")?.1,
|
||||
down: down_row(header.down).ok_or("down type")?.1,
|
||||
header,
|
||||
pairs: (0..header.rows).map(|r| (r, 0)).collect(),
|
||||
tokens: tokens.slice(header.rows * H),
|
||||
out: vec![0.0f32; header.rows * H],
|
||||
};
|
||||
// selfcheck: the timed call's output on every aligned copy is bit-identical to the first (unaligned) call's
|
||||
let mut selfcheck = true;
|
||||
for w in [res_copies[0], stm_copies[0], stm_copies[copies_k - 1]] {
|
||||
timed.call(w)?;
|
||||
selfcheck &= timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied());
|
||||
}
|
||||
if !selfcheck {
|
||||
return Err("selfcheck failed: the timed call differs from the first call".to_owned());
|
||||
}
|
||||
|
||||
let ghz0 = core_ghz();
|
||||
let mut regimes = Vec::new();
|
||||
let mut all_ok = true;
|
||||
let (mut kept_res, mut kept_stm) = (0, 0);
|
||||
for (label, copies, sel) in
|
||||
[("RESIDENT", &res_copies, RegimeSel::Resident), ("STREAMED", &stm_copies, RegimeSel::Streamed)]
|
||||
{
|
||||
if t.regime != RegimeSel::Both && t.regime != sel {
|
||||
continue;
|
||||
}
|
||||
let spec = RegimeSpec {
|
||||
label,
|
||||
copies: copies.clone(),
|
||||
expert_bytes,
|
||||
stride,
|
||||
llc: &llc,
|
||||
slices: t.slices,
|
||||
slice_ms: t.slice_ms,
|
||||
pin: t.pin,
|
||||
selfcheck,
|
||||
};
|
||||
let r = run_regime(&mut timed, &spec)?;
|
||||
all_ok &= r.ok;
|
||||
if sel == RegimeSel::Resident {
|
||||
kept_res = r.kept
|
||||
} else {
|
||||
kept_stm = r.kept
|
||||
}
|
||||
regimes.push(r.json);
|
||||
}
|
||||
let ghz1 = core_ghz();
|
||||
timed.call(res_copies[0])?;
|
||||
let final_same = timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied());
|
||||
|
||||
let threads = observed_threads();
|
||||
let sib1 = sibling.and_then(proc_stat_cpu);
|
||||
let pin1 = proc_stat_cpu(t.pin);
|
||||
let frac = |f: Option<f64>| f.map_or("null".to_owned(), |v| jnum(v, 4));
|
||||
let rust_fmt = |l: &str| jstr(l);
|
||||
let (gu_name, down_name) =
|
||||
(gate_up_row(header.gu).map_or("?", |x| x.4), down_row(header.down).map_or("?", |x| x.4));
|
||||
let in_name = format!("case-{}.in", t.case);
|
||||
let command_line = format!(
|
||||
"time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}",
|
||||
t.dir.display(),
|
||||
t.case,
|
||||
t.slices,
|
||||
t.pin,
|
||||
t.out.display(),
|
||||
if args.iter().any(|a| a == "--slice-ms") { format!(" --slice-ms {}", t.slice_ms) } else { String::new() },
|
||||
match t.regime {
|
||||
RegimeSel::Both => String::new(),
|
||||
RegimeSel::Resident => " --regime resident".to_owned(),
|
||||
RegimeSel::Streamed => " --regime streamed".to_owned(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// Writes the JSON to `<out>.tmp` and renames it over `out`.
|
||||
fn write_time_json(out: &Path, json: &str) -> Result<(), String> {
|
||||
let tmp = PathBuf::from(format!("{}.tmp", out.display()));
|
||||
fs::write(&tmp, json.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
fs::rename(&tmp, out).map_err(|e| format!("rename to {}: {e}", out.display()))
|
||||
}
|
||||
|
||||
/// 3 when a regime kept no slice or a slice migrated off the pin; 4 when the final output differs; else 0.
|
||||
fn time_exit_code(t: &TimeArgs, m: &Measured) -> ExitCode {
|
||||
if !m.regimes.all_ok {
|
||||
let mut j = String::from(
|
||||
"{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n",
|
||||
);
|
||||
j += &format!(
|
||||
" \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n",
|
||||
jstr(&command_line),
|
||||
jstr(&t.dir.display().to_string()),
|
||||
jstr(&manifest_sha)
|
||||
);
|
||||
j += &format!(
|
||||
" \"case\": {{\"id\": {}, \"gu_type\": {}, \"down_type\": {}, \"gu_name\": {}, \"down_name\": {}, \"rows\": {}, \"input_file\": {}, \"input_sha256\": {}, \"input_sha256_matches_manifest\": true, \"expert_bytes\": {}}},\n",
|
||||
jstr(&t.case),
|
||||
header.gu,
|
||||
header.down,
|
||||
jstr(gu_name),
|
||||
jstr(down_name),
|
||||
header.rows,
|
||||
jstr(&in_name),
|
||||
jstr(&entry.in_sha256),
|
||||
expert_bytes
|
||||
);
|
||||
j += &format!(
|
||||
" \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \"effective_env\": {},\n",
|
||||
jstr(tree),
|
||||
jstr(tree),
|
||||
report.iter().map(|l| rust_fmt(l)).collect::<Vec<_>>().join(", "),
|
||||
json_env(&env),
|
||||
json_env(&env)
|
||||
);
|
||||
j += &format!(
|
||||
" \"pool\": {{\"workers\": 1, \"host_drains\": true, \"threads_observed\": [{}], \"note\": \"DirectCpuPool::new(1): one worker thread plus the calling thread that drains beside it (pool.cpp host_works_); both inherit the one-CPU mask of the pin\"}},\n",
|
||||
threads
|
||||
.iter()
|
||||
.map(|(n, c)| format!(
|
||||
"{{\"name\": {}, \"cpu\": {}}}",
|
||||
jstr(n),
|
||||
c.map_or("null".to_owned(), |c| c.to_string())
|
||||
))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
);
|
||||
j += &format!(
|
||||
" \"pin\": {{\"cpu\": {}, \"thread_siblings_list\": {}, \"sibling_cpu\": {}, \"physical_core_id\": {}, \"pin_busy_fraction_during_run\": {}, \"sibling_busy_fraction_during_run\": {}, \"sibling_busy_note\": \"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is recorded, no threshold is applied here\", \"scaling_governor\": {}, \"cpufreq_boost\": {}, \"loadavg_start\": {}, \"loadavg_end\": {}, \"final_cpu\": {}}},\n",
|
||||
t.pin,
|
||||
jstr(&sib_text),
|
||||
sibling.map_or("null".to_owned(), |s| s.to_string()),
|
||||
jstr(&read_text(&format!("{cpu_dir}/topology/core_id"))),
|
||||
frac(busy_fraction(pin0, pin1)),
|
||||
if sibling.is_some() { frac(busy_fraction(sib0, sib1)) } else { "null".to_owned() },
|
||||
jstr(&read_text(&format!("{cpu_dir}/cpufreq/scaling_governor"))),
|
||||
jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")),
|
||||
jstr(&load0),
|
||||
jstr(&read_text("/proc/loadavg")),
|
||||
current_cpu().map_or("null".to_owned(), |c| c.to_string())
|
||||
);
|
||||
j += &format!(
|
||||
" \"buffers\": {{\"alignment_bytes\": {ALIGN}, \"expert_copy_stride_bytes\": {stride}, \"activations_aligned\": true, \"scratch_aligned\": false, \"scratch_note\": \"the pool's own scratch is allocated inside the crate\"}},\n"
|
||||
);
|
||||
j += &format!(
|
||||
" \"clock_calibration\": {{\"method\": {}, \"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp --bench: core_ghz() lines 273-284, time_slice() lines 290-304; the dependent-add chain needs inline assembly, so the safe Rust twin chains multiplies\", \"drop_rule\": {{\"source_file\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": 303, \"source_text\": \"std::fabs(g1 - g0) > 0.05 * g0\", \"fraction\": {}, \"meaning\": \"a slice whose calibrated clock moved by more than 5 percent between its before and after calibration is dropped\"}}, \"slice_ms_source\": \"tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60\", \"ghz_at_start\": {}, \"ghz_at_end\": {}, \"tsc_invariant\": null, \"clocks\": \"monotonic ns (std::time::Instant); no TSC read: rdtsc and lfence are unsafe intrinsics and the crate keeps unsafe_code = deny\"}},\n",
|
||||
jstr(CLOCK_METHOD),
|
||||
jnum(CLOCK_MOVED_FRACTION, 2),
|
||||
jnum(ghz0, 6),
|
||||
jnum(ghz1, 6)
|
||||
);
|
||||
j += &format!(
|
||||
" \"build\": {{\"profile\": {}, \"rustflags\": {}, \"example\": \"crates/native-cpu-expert/examples/kernel_ab.rs\"}},\n",
|
||||
jstr(if cfg!(debug_assertions) { "dev" } else { "release" }),
|
||||
jstr(&std::env::var("RUSTFLAGS").unwrap_or_default())
|
||||
);
|
||||
j += &format!(
|
||||
" \"selfcheck_bitwise_equal_first_call\": {selfcheck},\n \"final_output_unchanged\": {final_same},\n \"output_sha256\": {},\n \"duration_ns\": {},\n \"timing_caveat\": \"numbers from a shared host are not evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n \"regimes\": [\n {}\n ]\n}}\n",
|
||||
jstr(&output_sha),
|
||||
mono_ns() - wall0,
|
||||
regimes.join(",\n ")
|
||||
);
|
||||
let tmp = PathBuf::from(format!("{}.tmp", t.out.display()));
|
||||
fs::write(&tmp, j.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
fs::rename(&tmp, &t.out).map_err(|e| format!("rename to {}: {e}", t.out.display()))?;
|
||||
println!(
|
||||
"kernel_ab time: case={} tree={tree} pin={} slices={} resident_kept={kept_res} streamed_kept={kept_stm} K={copies_k} out={}",
|
||||
t.case,
|
||||
t.pin,
|
||||
t.slices,
|
||||
t.out.display()
|
||||
);
|
||||
if !all_ok {
|
||||
eprintln!("kernel_ab time: a regime has no kept slice or a slice migrated off CPU {}", t.pin);
|
||||
return ExitCode::from(3);
|
||||
return Ok(ExitCode::from(3));
|
||||
}
|
||||
if !m.final_same {
|
||||
if !final_same {
|
||||
eprintln!("kernel_ab time: the final output differs from the first call's");
|
||||
return ExitCode::from(4);
|
||||
return Ok(ExitCode::from(4));
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
Ok(ExitCode::SUCCESS)
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
//! The command table of `kernel_ab`: which command line runs which command, and how a refusal of the directory ends
|
||||
//! one.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// `time` and `alternate`: flags only (the command line of `kab time`); a failure is printed with the command's name.
|
||||
pub(super) fn run_flag_command(cmd: &str, args: &[String]) -> ExitCode {
|
||||
let result = if cmd == "time" { cmd_time(args) } else { cmd_alternate(args) };
|
||||
result.unwrap_or_else(|e| {
|
||||
eprintln!("kernel_ab {cmd}: {e}");
|
||||
ExitCode::from(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// `verify`, `compare` and `run-tree`, which take the directory first; None when the command line is not one of them.
|
||||
pub(super) fn run_dir_command(cmd: &str, dir: &Path, opts: &Options) -> Option<ExitCode> {
|
||||
let result = match cmd {
|
||||
"verify" => cmd_verify(dir),
|
||||
"compare" => cmd_compare(dir, opts),
|
||||
"run-tree" => match (&opts.tree, &opts.out) {
|
||||
(Some(t), Some(o)) => cmd_run_tree(dir, t, o, opts.pin, opts.case.as_deref()),
|
||||
_ => return None,
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
Some(result.unwrap_or_else(|e| {
|
||||
eprintln!("kernel_ab: {e}");
|
||||
ExitCode::from(1)
|
||||
}))
|
||||
}
|
||||
|
||||
/// The directory verified, or the exit code of its refusal (2: incomplete, 1: refused) after the refusal is printed.
|
||||
pub(super) fn verify_or_exit(dir: &Path) -> Result<Verified, ExitCode> {
|
||||
verify_dir(dir).map_err(|e| {
|
||||
println!("{e}");
|
||||
ExitCode::from(if e.incomplete { 2 } else { 1 })
|
||||
})
|
||||
}
|
||||
|
||||
fn cmd_verify(dir: &Path) -> Result<ExitCode, String> {
|
||||
Ok(match verify_or_exit(dir) {
|
||||
Ok(v) => {
|
||||
println!("OK {} files (manifest sha256 {})", v.file_count, v.manifest_sha256);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(code) => code,
|
||||
})
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Moved out of the parent module by STRA-338: fn describe_cpp_tree, fn parse_proc_json, impl Kind, fn side_stat, fn
|
||||
//! stat_json, fn tool_json ....
|
||||
//! Moved out of the parent module by STRA-338: fn describe_cpp_tree, fn parse_proc_json, impl Kind, fn side_stat, fn stat_json, fn tool_json ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -29,156 +28,102 @@ pub(super) fn describe_cpp_tree(d: &Json) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Parses a process's KAB1-time JSON and checks it against the cell that was started: writer, tree, manifest and input
|
||||
/// hashes, case, pin, and that the effective STRATA_* / LELEKA_* environment is exactly the cell's.
|
||||
/// Parses a process's KAB1-time JSON and checks it against the cell that was started: writer, tree, manifest and input hashes, case,
|
||||
/// pin, and that the effective STRATA_* / LELEKA_* environment is exactly the cell's.
|
||||
pub(super) fn parse_proc_json(p: &Proc, bytes: &[u8], expect: &Expect) -> Result<ProcOut, String> {
|
||||
let j = parse_json(bytes)?;
|
||||
let name = p.name();
|
||||
read_proc_cell(p, &j, expect).map_err(|what| format!("cell {name}: {what}"))
|
||||
}
|
||||
|
||||
/// The checks and the reading of a parsed process JSON; a failure carries no cell name yet.
|
||||
fn read_proc_cell(p: &Proc, j: &Json, expect: &Expect) -> Result<ProcOut, String> {
|
||||
require_cell_run(j, p, expect)?;
|
||||
let regimes = parse_regimes(j, p.imp)?;
|
||||
let clock = j.req("clock_calibration")?;
|
||||
let sibling_idle = read_sibling_idle(j)?;
|
||||
let (tree_text, cpu_report) = read_tree_text(j, p)?;
|
||||
let fail = |what: String| format!("cell {name}: {what}");
|
||||
if j.str("format").map_err(fail)? != "KAB1-time" || j.uint("version").map_err(fail)? != 1 {
|
||||
return Err(fail("the output is not KAB1-time version 1".to_owned()));
|
||||
}
|
||||
if j.str("writer").map_err(fail)? != p.imp.name() {
|
||||
return Err(fail(format!(
|
||||
"the output's writer is {:?}, expected {}",
|
||||
j.str("writer").unwrap_or("?"),
|
||||
p.imp.name()
|
||||
)));
|
||||
}
|
||||
if j.str("tree").map_err(fail)? != p.tree {
|
||||
return Err(fail(format!(
|
||||
"the process ran the {} tree, the cell asks for {}",
|
||||
j.str("tree").unwrap_or("?"),
|
||||
p.tree
|
||||
)));
|
||||
}
|
||||
if j.str("manifest_sha256").map_err(fail)? != expect.manifest_sha {
|
||||
return Err(fail("manifest_sha256 differs from the run directory's".to_owned()));
|
||||
}
|
||||
let c = j.req("case").map_err(fail)?;
|
||||
if c.str("id").map_err(fail)? != expect.case || c.str("input_sha256").map_err(fail)? != expect.input_sha {
|
||||
return Err(fail("the case id or its input hash differs from the manifest's".to_owned()));
|
||||
}
|
||||
let pin = j.req("pin").map_err(fail)?;
|
||||
if pin.uint("cpu").map_err(fail)? as usize != expect.pin {
|
||||
return Err(fail(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin)));
|
||||
}
|
||||
let want_env: BTreeMap<String, String> = cell_env(p).into_iter().collect();
|
||||
let mut seen_env = BTreeMap::new();
|
||||
if let Json::Obj(items) = j.req("effective_env").map_err(fail)? {
|
||||
for (k, v) in items {
|
||||
seen_env.insert(
|
||||
k.clone(),
|
||||
match v {
|
||||
Json::Str(s) => s.clone(),
|
||||
Json::Num(n) => n.clone(),
|
||||
_ => "?".to_owned(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
if seen_env != want_env {
|
||||
return Err(fail(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}")));
|
||||
}
|
||||
let mut regimes = BTreeMap::new();
|
||||
for r in j.array("regimes").map_err(fail)? {
|
||||
let label = r.str("regime").map_err(fail)?.to_owned();
|
||||
regimes.insert(label, parse_regime(r, p.imp).map_err(fail)?);
|
||||
}
|
||||
for want in ["RESIDENT", "STREAMED"] {
|
||||
if !regimes.contains_key(want) {
|
||||
return Err(fail(format!("regime {want} is missing")));
|
||||
}
|
||||
}
|
||||
let clock = j.req("clock_calibration").map_err(fail)?;
|
||||
let sibling_idle = match pin.req("sibling_cpu").map_err(fail)? {
|
||||
Json::Null => Some(true),
|
||||
_ => pin.float_or_null("sibling_busy_fraction_during_run").map_err(fail)?.map(|f| f < SIBLING_BUSY_LIMIT),
|
||||
};
|
||||
let detail = j.req("tree_detail").map_err(fail)?;
|
||||
let (tree_text, cpu_report) = if p.imp == Impl::Rust {
|
||||
let report: Vec<String> = detail
|
||||
.array("cpu_report")
|
||||
.map_err(fail)?
|
||||
.iter()
|
||||
.filter_map(|l| if let Json::Str(s) = l { Some(s.clone()) } else { None })
|
||||
.collect();
|
||||
let line = report
|
||||
.iter()
|
||||
.find(|l| l.starts_with("cpu: process kernel family"))
|
||||
.cloned()
|
||||
.ok_or_else(|| fail("no process kernel family line".to_owned()))?;
|
||||
(format!("leleka-serve {line}"), report)
|
||||
} else {
|
||||
(describe_cpp_tree(detail), Vec::new())
|
||||
};
|
||||
let cpu_model = (!cpu_report.is_empty()).then(|| cpu_model_of(&cpu_report));
|
||||
Ok(ProcOut {
|
||||
proc: *p,
|
||||
regimes,
|
||||
ghz_start: clock.float("ghz_at_start")?,
|
||||
ghz_end: clock.float("ghz_at_end")?,
|
||||
ghz_start: clock.float("ghz_at_start").map_err(fail)?,
|
||||
ghz_end: clock.float("ghz_at_end").map_err(fail)?,
|
||||
sibling_idle,
|
||||
final_unchanged: j.flag("final_output_unchanged")?,
|
||||
final_unchanged: j.flag("final_output_unchanged").map_err(fail)?,
|
||||
output_sha: j.get("output_sha256").and_then(|v| if let Json::Str(s) = v { Some(s.clone()) } else { None }),
|
||||
tree_text,
|
||||
cpu_model,
|
||||
})
|
||||
}
|
||||
|
||||
/// The process says it is the run that was asked for: format, writer, tree, manifest, case, pin and environment.
|
||||
fn require_cell_run(j: &Json, p: &Proc, expect: &Expect) -> Result<(), String> {
|
||||
require_time_format(j)?;
|
||||
require_writer(j, p)?;
|
||||
require_tree(j, p)?;
|
||||
require_manifest_sha(j, expect)?;
|
||||
require_case(j, expect)?;
|
||||
require_pin(j, expect)?;
|
||||
require_cell_env(j, p)
|
||||
}
|
||||
|
||||
fn require_time_format(j: &Json) -> Result<(), String> {
|
||||
if j.str("format")? != "KAB1-time" || j.uint("version")? != 1 {
|
||||
return Err("the output is not KAB1-time version 1".to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_writer(j: &Json, p: &Proc) -> Result<(), String> {
|
||||
if j.str("writer")? != p.imp.name() {
|
||||
return Err(format!("the output's writer is {:?}, expected {}", j.str("writer").unwrap_or("?"), p.imp.name()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_tree(j: &Json, p: &Proc) -> Result<(), String> {
|
||||
if j.str("tree")? != p.tree {
|
||||
return Err(format!("the process ran the {} tree, the cell asks for {}", j.str("tree").unwrap_or("?"), p.tree));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_manifest_sha(j: &Json, expect: &Expect) -> Result<(), String> {
|
||||
if j.str("manifest_sha256")? != expect.manifest_sha {
|
||||
return Err("manifest_sha256 differs from the run directory's".to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_case(j: &Json, expect: &Expect) -> Result<(), String> {
|
||||
let c = j.req("case")?;
|
||||
if c.str("id")? != expect.case || c.str("input_sha256")? != expect.input_sha {
|
||||
return Err("the case id or its input hash differs from the manifest's".to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_pin(j: &Json, expect: &Expect) -> Result<(), String> {
|
||||
let pin = j.req("pin")?;
|
||||
if pin.uint("cpu")? as usize != expect.pin {
|
||||
return Err(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The environment the process reports is exactly the cell's.
|
||||
fn require_cell_env(j: &Json, p: &Proc) -> Result<(), String> {
|
||||
let want_env: BTreeMap<String, String> = cell_env(p).into_iter().collect();
|
||||
let mut seen_env = BTreeMap::new();
|
||||
if let Json::Obj(items) = j.req("effective_env")? {
|
||||
for (k, v) in items {
|
||||
seen_env.insert(k.clone(), env_value_text(v));
|
||||
}
|
||||
}
|
||||
if seen_env != want_env {
|
||||
return Err(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn env_value_text(v: &Json) -> String {
|
||||
match v {
|
||||
Json::Str(s) => s.clone(),
|
||||
Json::Num(n) => n.clone(),
|
||||
_ => "?".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Both regimes of the process by label; a missing RESIDENT or STREAMED is an error.
|
||||
fn parse_regimes(j: &Json, imp: Impl) -> Result<BTreeMap<String, RegimeStat>, String> {
|
||||
let mut regimes = BTreeMap::new();
|
||||
for r in j.array("regimes")? {
|
||||
let label = r.str("regime")?.to_owned();
|
||||
regimes.insert(label, parse_regime(r, imp)?);
|
||||
}
|
||||
for want in ["RESIDENT", "STREAMED"] {
|
||||
if !regimes.contains_key(want) {
|
||||
return Err(format!("regime {want} is missing"));
|
||||
}
|
||||
}
|
||||
Ok(regimes)
|
||||
}
|
||||
|
||||
/// Whether the SMT sibling stayed idle; unknown (None) when the sibling's busy fraction is null.
|
||||
fn read_sibling_idle(j: &Json) -> Result<Option<bool>, String> {
|
||||
let pin = j.req("pin")?;
|
||||
Ok(match pin.req("sibling_cpu")? {
|
||||
Json::Null => Some(true),
|
||||
_ => pin.float_or_null("sibling_busy_fraction_during_run")?.map(|f| f < SIBLING_BUSY_LIMIT),
|
||||
})
|
||||
}
|
||||
|
||||
/// The text that describes the tree of the process, and (Rust only) the report lines it printed.
|
||||
fn read_tree_text(j: &Json, p: &Proc) -> Result<(String, Vec<String>), String> {
|
||||
let detail = j.req("tree_detail")?;
|
||||
if p.imp != Impl::Rust {
|
||||
return Ok((describe_cpp_tree(detail), Vec::new()));
|
||||
}
|
||||
let report: Vec<String> = detail
|
||||
.array("cpu_report")?
|
||||
.iter()
|
||||
.filter_map(|l| if let Json::Str(s) = l { Some(s.clone()) } else { None })
|
||||
.collect();
|
||||
let line = report
|
||||
.iter()
|
||||
.find(|l| l.starts_with("cpu: process kernel family"))
|
||||
.cloned()
|
||||
.ok_or_else(|| "no process kernel family line".to_owned())?;
|
||||
Ok((format!("leleka-serve {line}"), report))
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub(super) fn slug(self) -> &'static str {
|
||||
match self {
|
||||
@@ -222,8 +167,7 @@ pub(super) fn equality_block(c: &CaseEntry, o: &Outcome) -> String {
|
||||
)
|
||||
});
|
||||
format!(
|
||||
"{{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": \
|
||||
{}{tolerance}\n }}",
|
||||
"{{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}{tolerance}\n }}",
|
||||
if c.tolerance.is_some() { "tolerance" } else { "bitwise" },
|
||||
if o.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
||||
o.compared,
|
||||
@@ -231,9 +175,8 @@ pub(super) fn equality_block(c: &CaseEntry, o: &Outcome) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The A/A equality: the same implementation in two fresh processes. Rust: the output hashes of the two processes (and
|
||||
/// each one's selfcheck); C++: each process's timed composition equals `compose_expert()` bit for bit (selfcheck),
|
||||
/// which is the same function.
|
||||
/// The A/A equality: the same implementation in two fresh processes. Rust: the output hashes of the two processes (and each one's
|
||||
/// selfcheck); C++: each process's timed composition equals `compose_expert()` bit for bit (selfcheck), which is the same function.
|
||||
pub(super) fn aa_outcome(a: &ProcOut, b: &ProcOut, rows: usize) -> (Outcome, String) {
|
||||
let compared = rows * H;
|
||||
let selfchecks =
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Moved out of the parent module by STRA-338: fn gate_up_row, fn down_row, impl Refusal, impl std_fmt_Display, fn
|
||||
//! sha_hex, fn take_buffer ....
|
||||
//! Moved out of the parent module by STRA-338: fn gate_up_row, fn down_row, impl Refusal, impl std_fmt_Display, fn sha_hex, fn take_buffer ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Impl, impl Proc, fn procs_for, fn cell_env, fn scrubbed_command, fn
|
||||
//! run_cell ....
|
||||
//! Moved out of the parent module by STRA-338: impl Impl, impl Proc, fn procs_for, fn cell_env, fn scrubbed_command, fn run_cell ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -47,11 +46,10 @@ pub(super) fn procs_for(trees: &[&'static str]) -> Vec<Proc> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations
|
||||
/// honour. The Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining caller, both confined to the
|
||||
/// one pinned CPU: the pool must not re-pin its caller (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested
|
||||
/// one) and its worker must not spin after a batch (`STRATA_POOL_SPIN_US=0`; with the 20 ms default the worker spins on
|
||||
/// the caller's only CPU and costs it half its time).
|
||||
/// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. The
|
||||
/// Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining caller, both confined to the one pinned CPU: the pool must
|
||||
/// not re-pin its caller (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested one) and its worker must not spin after a batch
|
||||
/// (`STRATA_POOL_SPIN_US=0`; with the 20 ms default the worker spins on the caller's only CPU and costs it half its time).
|
||||
pub(super) fn cell_env(p: &Proc) -> Vec<(String, String)> {
|
||||
let mut v = Vec::new();
|
||||
if p.tree == "avx2" {
|
||||
@@ -65,8 +63,7 @@ pub(super) fn cell_env(p: &Proc) -> Vec<(String, String)> {
|
||||
v
|
||||
}
|
||||
|
||||
/// A command whose environment is exactly: the parent's variables minus every STRATA_* / LELEKA_* one, plus the cell's
|
||||
/// variables.
|
||||
/// A command whose environment is exactly: the parent's variables minus every STRATA_* / LELEKA_* one, plus the cell's variables.
|
||||
pub(super) fn scrubbed_command(
|
||||
program: &Path,
|
||||
parent_env: &[(OsString, OsString)],
|
||||
@@ -118,9 +115,8 @@ pub(super) fn splitmix(state: &mut u64) -> u64 {
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
/// The schedule of one batch: round `i` (0-based) rotates a seeded permutation by `i mod n`; every block of `n` rounds
|
||||
/// draws a fresh permutation, so each process takes each position equally often within a block. A pure function of
|
||||
/// (seed, batch, rounds, procs).
|
||||
/// The schedule of one batch: round `i` (0-based) rotates a seeded permutation by `i mod n`; every block of `n` rounds draws a fresh
|
||||
/// permutation, so each process takes each position equally often within a block. A pure function of (seed, batch, rounds, procs).
|
||||
pub(super) fn make_schedule(seed: u64, batch: u32, rounds: u32, procs: &[Proc]) -> Vec<Vec<Proc>> {
|
||||
let n = procs.len();
|
||||
let mut out = Vec::new();
|
||||
@@ -155,8 +151,7 @@ pub(super) fn schedule_text(
|
||||
order: &[Vec<Proc>],
|
||||
) -> String {
|
||||
let mut t = format!(
|
||||
"{SCHEDULE_MAGIC} (written before the first run; the runner reads this file back)\n# seed={seed} batch={batch} \
|
||||
rounds={rounds} case={case} pin={pin}\n"
|
||||
"{SCHEDULE_MAGIC} (written before the first run; the runner reads this file back)\n# seed={seed} batch={batch} rounds={rounds} case={case} pin={pin}\n"
|
||||
);
|
||||
for (i, o) in order.iter().enumerate() {
|
||||
t += &format!("{}\t{}\n", first_round + i as u32, o.iter().map(Proc::name).collect::<Vec<_>>().join(","));
|
||||
@@ -164,8 +159,7 @@ pub(super) fn schedule_text(
|
||||
t
|
||||
}
|
||||
|
||||
/// Reads a schedule back: (round number, processes in order) per round. Every round must name each process of the first
|
||||
/// round once.
|
||||
/// Reads a schedule back: (round number, processes in order) per round. Every round must name each process of the first round once.
|
||||
pub(super) fn parse_schedule(text: &str) -> Result<Vec<(u32, Vec<Proc>)>, String> {
|
||||
let mut lines = text.lines();
|
||||
if !lines.next().is_some_and(|l| l.starts_with(SCHEDULE_MAGIC)) {
|
||||
@@ -173,9 +167,16 @@ pub(super) fn parse_schedule(text: &str) -> Result<Vec<(u32, Vec<Proc>)>, String
|
||||
}
|
||||
let mut rounds: Vec<(u32, Vec<Proc>)> = Vec::new();
|
||||
for l in lines.filter(|l| !l.starts_with('#') && !l.is_empty()) {
|
||||
let (no, order) = parse_schedule_line(l)?;
|
||||
let (no, list) = l.split_once('\t').ok_or_else(|| format!("bad schedule line {l:?}"))?;
|
||||
let no = no.parse::<u32>().map_err(|_| format!("bad round number in {l:?}"))?;
|
||||
let order: Vec<Proc> = list
|
||||
.split(',')
|
||||
.map(|n| Proc::parse(n).ok_or_else(|| format!("unknown process {n:?} in the schedule")))
|
||||
.collect::<Result<_, _>>()?;
|
||||
if let Some(prev) = rounds.last()
|
||||
&& !follows_round(prev, no, &order)
|
||||
&& (no != prev.0 + 1
|
||||
|| BTreeSet::from_iter(order.iter()) != BTreeSet::from_iter(prev.1.iter())
|
||||
|| order.len() != prev.1.len())
|
||||
{
|
||||
return Err(format!("round {no} does not follow round {} with the same processes", prev.0));
|
||||
}
|
||||
@@ -187,123 +188,45 @@ pub(super) fn parse_schedule(text: &str) -> Result<Vec<(u32, Vec<Proc>)>, String
|
||||
Ok(rounds)
|
||||
}
|
||||
|
||||
/// One schedule line: the round number, a tab, the process names separated by commas.
|
||||
fn parse_schedule_line(l: &str) -> Result<(u32, Vec<Proc>), String> {
|
||||
let (no, list) = l.split_once('\t').ok_or_else(|| format!("bad schedule line {l:?}"))?;
|
||||
let no = no.parse::<u32>().map_err(|_| format!("bad round number in {l:?}"))?;
|
||||
let order: Vec<Proc> = list
|
||||
.split(',')
|
||||
.map(|n| Proc::parse(n).ok_or_else(|| format!("unknown process {n:?} in the schedule")))
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok((no, order))
|
||||
}
|
||||
|
||||
/// Whether round `no` with `order` is the round after `prev` and names the same processes.
|
||||
fn follows_round(prev: &(u32, Vec<Proc>), no: u32, order: &[Proc]) -> bool {
|
||||
no == prev.0 + 1
|
||||
&& BTreeSet::from_iter(order.iter()) == BTreeSet::from_iter(prev.1.iter())
|
||||
&& order.len() == prev.1.len()
|
||||
}
|
||||
|
||||
/// Refuses a path that is, or lies inside, a Git checkout (generated artifacts stay out of Git).
|
||||
pub(super) fn inside_git_checkout(path: &Path) -> bool {
|
||||
let abs = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
abs.ancestors().any(|a| a.join(".git").exists())
|
||||
}
|
||||
|
||||
/// The kept slices of one regime and the largest clock drift over the kept and the dropped slices.
|
||||
struct Samples {
|
||||
ns: Vec<f64>,
|
||||
cycles: Vec<f64>,
|
||||
max_drift: f64,
|
||||
}
|
||||
|
||||
/// One slice of the process JSON: its clock before and after and, for a kept slice, its time per call.
|
||||
struct SliceSample {
|
||||
ghz_before: f64,
|
||||
ghz_after: f64,
|
||||
kept: Option<(f64, f64)>,
|
||||
}
|
||||
|
||||
fn parse_slice(s: &Json, keep: bool) -> Result<SliceSample, String> {
|
||||
let (ghz_before, ghz_after) = (s.float("ghz_before")?, s.float("ghz_after")?);
|
||||
let kept = if keep { Some((s.float("ns_per_call")?, s.float("cycles_per_call")?)) } else { None };
|
||||
Ok(SliceSample { ghz_before, ghz_after, kept })
|
||||
}
|
||||
|
||||
fn read_samples(r: &Json) -> Result<Samples, String> {
|
||||
let mut samples = Samples { ns: Vec::new(), cycles: Vec::new(), max_drift: 0.0f64 };
|
||||
pub(super) fn parse_regime(r: &Json, imp: Impl) -> Result<RegimeStat, String> {
|
||||
let mut ns = Vec::new();
|
||||
let mut cycles = Vec::new();
|
||||
let mut max_drift = 0.0f64;
|
||||
for (key, keep) in [("slices", true), ("dropped", false)] {
|
||||
for s in r.array(key)? {
|
||||
let slice = parse_slice(s, keep)?;
|
||||
samples.add_slice(&slice);
|
||||
let (g0, g1) = (s.float("ghz_before")?, s.float("ghz_after")?);
|
||||
if g0 > 0.0 {
|
||||
max_drift = max_drift.max(((g1 - g0).abs() / g0).min(1.0));
|
||||
}
|
||||
if keep {
|
||||
ns.push(s.float("ns_per_call")?);
|
||||
cycles.push(s.float("cycles_per_call")?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(samples)
|
||||
}
|
||||
|
||||
impl Samples {
|
||||
fn add_slice(&mut self, s: &SliceSample) {
|
||||
let (g0, g1) = (s.ghz_before, s.ghz_after);
|
||||
if g0 > 0.0 {
|
||||
self.max_drift = self.max_drift.max(((g1 - g0).abs() / g0).min(1.0));
|
||||
}
|
||||
if let Some((ns, cycles)) = s.kept {
|
||||
self.ns.push(ns);
|
||||
self.cycles.push(cycles);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn parse_regime(r: &Json, imp: Impl) -> Result<RegimeStat, String> {
|
||||
let Samples { ns, cycles, max_drift } = read_samples(r)?;
|
||||
require_kept_count(r, ns.len())?;
|
||||
let sets = read_set_counts(r)?;
|
||||
Ok(RegimeStat {
|
||||
copies_k: sets.copies_k,
|
||||
expert_bytes: sets.expert_bytes,
|
||||
llc_bytes: sets.llc_bytes,
|
||||
requested: sets.requested,
|
||||
dropped: sets.dropped,
|
||||
median_ns: r.float("median_ns_per_call")?,
|
||||
median_cycles: r.float("median_cycles_per_call")?,
|
||||
ns,
|
||||
cycles,
|
||||
max_drift,
|
||||
selfcheck: r.flag(selfcheck_key(imp))?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The JSON key of the regime's selfcheck verdict: the C++ driver compares with `compose_expert()`, ours with the first
|
||||
/// call.
|
||||
fn selfcheck_key(imp: Impl) -> &'static str {
|
||||
if imp == Impl::Cpp { "selfcheck_bitwise_equal_compose_expert" } else { "selfcheck_bitwise_equal_first_call" }
|
||||
}
|
||||
|
||||
/// `slices_kept` agrees with the kept slices that were read, and at least one was kept.
|
||||
fn require_kept_count(r: &Json, read: usize) -> Result<(), String> {
|
||||
let selfcheck_key =
|
||||
if imp == Impl::Cpp { "selfcheck_bitwise_equal_compose_expert" } else { "selfcheck_bitwise_equal_first_call" };
|
||||
let kept = r.uint("slices_kept")? as usize;
|
||||
if kept != read || kept == 0 {
|
||||
return Err(format!("slices_kept {kept} disagrees with the {read} kept slices (or none was kept)"));
|
||||
if kept != ns.len() || kept == 0 {
|
||||
return Err(format!("slices_kept {kept} disagrees with the {} kept slices (or none was kept)", ns.len()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The counts a regime reports about its set of copies and its slices.
|
||||
struct SetCounts {
|
||||
copies_k: usize,
|
||||
expert_bytes: usize,
|
||||
llc_bytes: u64,
|
||||
requested: usize,
|
||||
dropped: usize,
|
||||
}
|
||||
|
||||
fn read_set_counts(r: &Json) -> Result<SetCounts, String> {
|
||||
Ok(SetCounts {
|
||||
Ok(RegimeStat {
|
||||
copies_k: r.uint("copies_k")? as usize,
|
||||
expert_bytes: r.uint("expert_bytes")? as usize,
|
||||
llc_bytes: r.uint("llc_bytes")?,
|
||||
requested: r.uint("slices_requested")? as usize,
|
||||
dropped: r.uint("dropped_count")? as usize,
|
||||
median_ns: r.float("median_ns_per_call")?,
|
||||
median_cycles: r.float("median_cycles_per_call")?,
|
||||
ns,
|
||||
cycles,
|
||||
max_drift,
|
||||
selfcheck: r.flag(selfcheck_key)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -38,7 +38,39 @@ impl Parser<'_> {
|
||||
match c {
|
||||
b'"' => return String::from_utf8(out).map_err(|_| "string is not UTF-8".to_owned()),
|
||||
b'\\' => {
|
||||
let ch = self.escape()?;
|
||||
let Some(&e) = self.b.get(self.at) else { return self.err("unterminated escape") };
|
||||
self.at += 1;
|
||||
let ch = match e {
|
||||
b'"' => '"',
|
||||
b'\\' => '\\',
|
||||
b'/' => '/',
|
||||
b'b' => '\u{8}',
|
||||
b'f' => '\u{c}',
|
||||
b'n' => '\n',
|
||||
b'r' => '\r',
|
||||
b't' => '\t',
|
||||
b'u' => {
|
||||
let hi = self.hex4()?;
|
||||
let cp = if (0xD800..0xDC00).contains(&hi) {
|
||||
if !self.b[self.at..].starts_with(b"\\u") {
|
||||
return self.err("lone surrogate");
|
||||
}
|
||||
self.at += 2;
|
||||
let lo = self.hex4()?;
|
||||
if !(0xDC00..0xE000).contains(&lo) {
|
||||
return self.err("lone surrogate");
|
||||
}
|
||||
0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00)
|
||||
} else {
|
||||
hi
|
||||
};
|
||||
match char::from_u32(cp) {
|
||||
Some(c) => c,
|
||||
None => return self.err("lone surrogate"),
|
||||
}
|
||||
}
|
||||
_ => return self.err("unknown escape"),
|
||||
};
|
||||
let mut buf = [0u8; 4];
|
||||
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
|
||||
}
|
||||
@@ -47,39 +79,6 @@ impl Parser<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The character an escape sequence stands for; the backslash is already consumed.
|
||||
fn escape(&mut self) -> Result<char, String> {
|
||||
let Some(&e) = self.b.get(self.at) else { return self.err("unterminated escape") };
|
||||
self.at += 1;
|
||||
if e == b'u' {
|
||||
return self.unicode_escape();
|
||||
}
|
||||
match simple_escape(e) {
|
||||
Some(ch) => Ok(ch),
|
||||
None => self.err("unknown escape"),
|
||||
}
|
||||
}
|
||||
/// `\uXXXX`, with the low half of a surrogate pair when the first half asks for one; the `u` is already consumed.
|
||||
fn unicode_escape(&mut self) -> Result<char, String> {
|
||||
let hi = self.hex4()?;
|
||||
let cp = if (0xD800..0xDC00).contains(&hi) { self.low_surrogate(hi)? } else { hi };
|
||||
match char::from_u32(cp) {
|
||||
Some(c) => Ok(c),
|
||||
None => self.err("lone surrogate"),
|
||||
}
|
||||
}
|
||||
/// The code point of the pair whose high half is `hi`; the low half must follow as `\uXXXX`.
|
||||
fn low_surrogate(&mut self, hi: u32) -> Result<u32, String> {
|
||||
if !self.b[self.at..].starts_with(b"\\u") {
|
||||
return self.err("lone surrogate");
|
||||
}
|
||||
self.at += 2;
|
||||
let lo = self.hex4()?;
|
||||
if !(0xDC00..0xE000).contains(&lo) {
|
||||
return self.err("lone surrogate");
|
||||
}
|
||||
Ok(0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00))
|
||||
}
|
||||
pub(super) fn number(&mut self) -> Result<Json, String> {
|
||||
let start = self.at;
|
||||
while self.at < self.b.len() && matches!(self.b[self.at], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') {
|
||||
@@ -98,102 +97,70 @@ impl Parser<'_> {
|
||||
self.ws();
|
||||
match self.b.get(self.at) {
|
||||
None => self.err("unexpected end"),
|
||||
Some(b'{') => self.object(depth),
|
||||
Some(b'[') => self.array(depth),
|
||||
Some(b'"') => self.string().map(Json::Str),
|
||||
Some(b't' | b'f' | b'n') => self.keyword(),
|
||||
Some(b'{') => {
|
||||
self.at += 1;
|
||||
let mut items: Vec<(String, Json)> = Vec::new();
|
||||
self.ws();
|
||||
if self.b.get(self.at) == Some(&b'}') {
|
||||
self.at += 1;
|
||||
return Ok(Json::Obj(items));
|
||||
}
|
||||
loop {
|
||||
self.ws();
|
||||
if self.b.get(self.at) != Some(&b'"') {
|
||||
return self.err("object key expected");
|
||||
}
|
||||
let key = self.string()?;
|
||||
if items.iter().any(|(k, _)| *k == key) {
|
||||
return self.err(&format!("duplicate key {key:?}"));
|
||||
}
|
||||
self.ws();
|
||||
if self.b.get(self.at) != Some(&b':') {
|
||||
return self.err("':' expected");
|
||||
}
|
||||
self.at += 1;
|
||||
let v = self.value(depth + 1)?;
|
||||
items.push((key, v));
|
||||
self.ws();
|
||||
match self.b.get(self.at) {
|
||||
Some(b',') => self.at += 1,
|
||||
Some(b'}') => {
|
||||
self.at += 1;
|
||||
return Ok(Json::Obj(items));
|
||||
}
|
||||
_ => return self.err("',' or '}' expected"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(b'[') => {
|
||||
self.at += 1;
|
||||
let mut items = Vec::new();
|
||||
self.ws();
|
||||
if self.b.get(self.at) == Some(&b']') {
|
||||
self.at += 1;
|
||||
return Ok(Json::Arr(items));
|
||||
}
|
||||
loop {
|
||||
items.push(self.value(depth + 1)?);
|
||||
self.ws();
|
||||
match self.b.get(self.at) {
|
||||
Some(b',') => self.at += 1,
|
||||
Some(b']') => {
|
||||
self.at += 1;
|
||||
return Ok(Json::Arr(items));
|
||||
}
|
||||
_ => return self.err("',' or ']' expected"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(b'"') => Ok(Json::Str(self.string()?)),
|
||||
Some(b't') => self.lit("true", Json::Bool(true)),
|
||||
Some(b'f') => self.lit("false", Json::Bool(false)),
|
||||
Some(b'n') => self.lit("null", Json::Null),
|
||||
Some(b'-' | b'0'..=b'9') => self.number(),
|
||||
Some(_) => self.err("unexpected character"),
|
||||
}
|
||||
}
|
||||
/// `true`, `false` or `null`; the current byte is the first letter of one of them.
|
||||
fn keyword(&mut self) -> Result<Json, String> {
|
||||
match self.b[self.at] {
|
||||
b't' => self.lit("true", Json::Bool(true)),
|
||||
b'f' => self.lit("false", Json::Bool(false)),
|
||||
_ => self.lit("null", Json::Null),
|
||||
}
|
||||
}
|
||||
fn object(&mut self, depth: usize) -> Result<Json, String> {
|
||||
self.at += 1;
|
||||
let mut items: Vec<(String, Json)> = Vec::new();
|
||||
self.ws();
|
||||
if self.b.get(self.at) == Some(&b'}') {
|
||||
self.at += 1;
|
||||
return Ok(Json::Obj(items));
|
||||
}
|
||||
loop {
|
||||
let member = self.member(depth, &items)?;
|
||||
items.push(member);
|
||||
self.ws();
|
||||
if self.end_of_item(b'}')? {
|
||||
return Ok(Json::Obj(items));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// One `"key": value` of an object whose earlier members are `items`.
|
||||
fn member(&mut self, depth: usize, items: &[(String, Json)]) -> Result<(String, Json), String> {
|
||||
self.ws();
|
||||
if self.b.get(self.at) != Some(&b'"') {
|
||||
return self.err("object key expected");
|
||||
}
|
||||
let key = self.string()?;
|
||||
if items.iter().any(|(k, _)| *k == key) {
|
||||
return self.err(&format!("duplicate key {key:?}"));
|
||||
}
|
||||
self.ws();
|
||||
if self.b.get(self.at) != Some(&b':') {
|
||||
return self.err("':' expected");
|
||||
}
|
||||
self.at += 1;
|
||||
let v = self.value(depth + 1)?;
|
||||
Ok((key, v))
|
||||
}
|
||||
fn array(&mut self, depth: usize) -> Result<Json, String> {
|
||||
self.at += 1;
|
||||
let mut items = Vec::new();
|
||||
self.ws();
|
||||
if self.b.get(self.at) == Some(&b']') {
|
||||
self.at += 1;
|
||||
return Ok(Json::Arr(items));
|
||||
}
|
||||
loop {
|
||||
items.push(self.value(depth + 1)?);
|
||||
self.ws();
|
||||
if self.end_of_item(b']')? {
|
||||
return Ok(Json::Arr(items));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// After an item: a comma (false: more follow) or the closing byte (true); anything else is an error.
|
||||
fn end_of_item(&mut self, close: u8) -> Result<bool, String> {
|
||||
match self.b.get(self.at) {
|
||||
Some(b',') => {
|
||||
self.at += 1;
|
||||
Ok(false)
|
||||
}
|
||||
Some(c) if *c == close => {
|
||||
self.at += 1;
|
||||
Ok(true)
|
||||
}
|
||||
_ => self.err(&format!("',' or '{}' expected", close as char)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The character of a single-letter escape (`\n`, `\"`, ...); `u` is handled by the caller.
|
||||
fn simple_escape(e: u8) -> Option<char> {
|
||||
Some(match e {
|
||||
b'"' => '"',
|
||||
b'\\' => '\\',
|
||||
b'/' => '/',
|
||||
b'b' => '\u{8}',
|
||||
b'f' => '\u{c}',
|
||||
b'n' => '\n',
|
||||
b'r' => '\r',
|
||||
b't' => '\t',
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn parse_json(bytes: &[u8]) -> Result<Json, String> {
|
||||
|
||||
@@ -15,9 +15,8 @@ pub(super) const MAX_FILE_BYTES: u64 = 16 << 20;
|
||||
pub(super) const MAX_MANIFEST_BYTES: u64 = 8 << 20;
|
||||
pub(super) const MAX_CASES: usize = 1024;
|
||||
pub(super) const TOLERANCE_METRIC: &str = "max_abs_error_over_max_abs_reference";
|
||||
/// Marker of every schema-required timing field this part does not measure (STRA-318 fills them): a text marker where
|
||||
/// the schema takes text, the smallest positive double (`5e-324`) where it takes a positive number, 1 where it takes a
|
||||
/// positive count.
|
||||
/// Marker of every schema-required timing field this part does not measure (STRA-318 fills them): a text marker where the schema takes
|
||||
/// text, the smallest positive double (`5e-324`) where it takes a positive number, 1 where it takes a positive count.
|
||||
pub(super) const NOT_MEASURED: &str = "NOT_MEASURED (filled by STRA-318, the alternation runner)";
|
||||
pub(super) const TREES: [&str; 2] = ["avx512", "avx2"];
|
||||
|
||||
@@ -174,25 +173,23 @@ pub(super) struct Options {
|
||||
pub(super) case: Option<String>,
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- flags (time, alternate)
|
||||
// ------------------------------------------------------------------------------------------------ flags (time, alternate)
|
||||
|
||||
pub(super) struct Flags(pub(super) Vec<(String, String)>);
|
||||
|
||||
// ----------------------------------------------------------------------------------------------- clocks and host facts
|
||||
// ------------------------------------------------------------------------------------------------ clocks and host facts
|
||||
|
||||
/// The 60 ms slice of `tq_cpu_parity.cpp:461` (`slice_ms = quick ? 40 : 60`), the same value `kab time` uses.
|
||||
pub(super) const DEFAULT_SLICE_MS: f64 = 60.0;
|
||||
/// `tq_cpu_parity.cpp:303`: a slice whose calibrated clock moved by more than this fraction is dropped. Copied, not
|
||||
/// chosen here.
|
||||
/// `tq_cpu_parity.cpp:303`: a slice whose calibrated clock moved by more than this fraction is dropped. Copied, not chosen here.
|
||||
pub(super) const CLOCK_MOVED_FRACTION: f64 = 0.05;
|
||||
/// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`).
|
||||
pub(super) const SIBLING_BUSY_LIMIT: f64 = 0.05;
|
||||
pub(super) const ALIGN: usize = 4096;
|
||||
/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel Skylake
|
||||
/// to Golden Cove and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply.
|
||||
/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel Skylake to Golden Cove
|
||||
/// and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply.
|
||||
pub(super) const CHAIN_STEP_CYCLES: f64 = 4.0;
|
||||
pub(super) const CLOCK_METHOD: &str = "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step \
|
||||
(3 multiply + 1 xor), 1000000 iterations of 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice";
|
||||
pub(super) const CLOCK_METHOD: &str = "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step (3 multiply + 1 xor), 1000000 iterations of 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice";
|
||||
|
||||
pub(super) struct Llc {
|
||||
pub(super) level: u32,
|
||||
@@ -200,7 +197,7 @@ pub(super) struct Llc {
|
||||
pub(super) source: String,
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------- time (one fresh process)
|
||||
// ------------------------------------------------------------------------------------------------ time (one fresh process)
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(super) enum RegimeSel {
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
//! Moved out of the parent module by STRA-338: fn llc_of_cpu, fn proc_stat_cpu, fn busy_fraction, fn current_cpu, fn
|
||||
//! observed_threads, fn is_managed_name ....
|
||||
//! Moved out of the parent module by STRA-338: fn llc_of_cpu, fn proc_stat_cpu, fn busy_fraction, fn current_cpu, fn observed_threads, fn is_managed_name ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Linux: the highest-level data or unified cache of `cpu` from sysfs. Elsewhere: None (the caller passes
|
||||
/// `--llc-bytes`).
|
||||
/// Linux: the highest-level data or unified cache of `cpu` from sysfs. Elsewhere: None (the caller passes `--llc-bytes`).
|
||||
pub(super) fn llc_of_cpu(cpu: usize) -> Option<Llc> {
|
||||
let mut best: Option<Llc> = None;
|
||||
for i in 0..16 {
|
||||
@@ -84,41 +82,25 @@ pub(super) fn json_env(env: &BTreeMap<String, String>) -> String {
|
||||
/// The command line of `kab time` (STRA-317), checked the same way.
|
||||
pub(super) fn parse_time_args(args: &[String]) -> Result<TimeArgs, String> {
|
||||
let f = Flags::parse(args, &TIME_FLAGS)?;
|
||||
let slices = f.need_number::<usize>("slices")?;
|
||||
let pin = f.need_number::<usize>("pin")?;
|
||||
let slices = f.number::<usize>("slices")?.ok_or("--slices is required")?;
|
||||
let pin = f.number::<usize>("pin")?.ok_or("--pin is required")?;
|
||||
let slice_ms = f.number::<f64>("slice-ms")?.unwrap_or(DEFAULT_SLICE_MS);
|
||||
require_time_ranges(slices, slice_ms)?;
|
||||
let regime = parse_regime_sel(f.get("regime").unwrap_or("both"))?;
|
||||
let case = f.case_id()?;
|
||||
build_time_args(&f, (slices, pin, slice_ms), regime, case)
|
||||
}
|
||||
|
||||
fn require_time_ranges(slices: usize, slice_ms: f64) -> Result<(), String> {
|
||||
if !(1..=100_000).contains(&slices) {
|
||||
return Err("--slices must be 1..100000".to_owned());
|
||||
}
|
||||
if !(1.0..=10_000.0).contains(&slice_ms) {
|
||||
return Err("--slice-ms must be 1..10000".to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_regime_sel(text: &str) -> Result<RegimeSel, String> {
|
||||
match text {
|
||||
"both" => Ok(RegimeSel::Both),
|
||||
"resident" => Ok(RegimeSel::Resident),
|
||||
"streamed" => Ok(RegimeSel::Streamed),
|
||||
_ => Err("--regime must be both, resident or streamed".to_owned()),
|
||||
let regime = match f.get("regime").unwrap_or("both") {
|
||||
"both" => RegimeSel::Both,
|
||||
"resident" => RegimeSel::Resident,
|
||||
"streamed" => RegimeSel::Streamed,
|
||||
_ => return Err("--regime must be both, resident or streamed".to_owned()),
|
||||
};
|
||||
let case = f.req("case")?.to_owned();
|
||||
if !valid_id(&case) {
|
||||
return Err(format!("--case {case:?} is not a plain identifier"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The parsed command line from the values read so far and the paths and the cache override still to be read.
|
||||
fn build_time_args(
|
||||
f: &Flags,
|
||||
(slices, pin, slice_ms): (usize, usize, f64),
|
||||
regime: RegimeSel,
|
||||
case: String,
|
||||
) -> Result<TimeArgs, String> {
|
||||
Ok(TimeArgs {
|
||||
dir: PathBuf::from(f.req("run-dir")?),
|
||||
case,
|
||||
@@ -130,7 +112,6 @@ fn build_time_args(
|
||||
llc_bytes: f.number::<u64>("llc-bytes")?,
|
||||
})
|
||||
}
|
||||
|
||||
impl<T: Copy + Default> Arena<T> {
|
||||
pub(super) fn new(len: usize) -> Self {
|
||||
let size = std::mem::size_of::<T>();
|
||||
@@ -164,8 +145,7 @@ impl Timed<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// One slice of `ms` milliseconds cycling over the copies; the shape of `time_slice()` in tq_cpu_parity.cpp (lines
|
||||
/// 290-304).
|
||||
/// One slice of `ms` milliseconds cycling over the copies; the shape of `time_slice()` in tq_cpu_parity.cpp (lines 290-304).
|
||||
pub(super) fn time_slice(t: &mut Timed, copies: &[&[u8]], ms: f64, next: &mut usize) -> Result<Slice, String> {
|
||||
let ghz_before = core_ghz();
|
||||
let mut calls = 0u64;
|
||||
@@ -197,8 +177,7 @@ pub(super) fn time_slice(t: &mut Timed, copies: &[&[u8]], ms: f64, next: &mut us
|
||||
|
||||
pub(super) fn slice_json(s: &Slice, idx: usize) -> String {
|
||||
format!(
|
||||
"{{\"i\": {idx}, \"calls\": {}, \"wall_ns\": {}, \"ns_per_call\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \
|
||||
\"cycles_per_call\": {}}}",
|
||||
"{{\"i\": {idx}, \"calls\": {}, \"wall_ns\": {}, \"ns_per_call\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \"cycles_per_call\": {}}}",
|
||||
s.calls,
|
||||
s.wall_ns,
|
||||
jnum(s.ns_per_call, 3),
|
||||
|
||||
@@ -1,43 +1,35 @@
|
||||
#![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
// This file is its own lint gate: `cargo clippy -- -D warnings` also lints the other workspace crates, which carry
|
||||
// warnings of their own.
|
||||
// This file is its own lint gate: `cargo clippy -- -D warnings` also lints the other workspace crates, which carry warnings of their own.
|
||||
#![deny(warnings, clippy::all)]
|
||||
//! Rust half of the CPU kernel A/B, part 1 (STRA-289, S0.8b): the KAB1 reader, the comparison against the C++
|
||||
//! reference outputs and the COMPONENT_KERNEL record writer. The C++ driver (`tools/kernel-ab`, STRA-248) writes a run
|
||||
//! directory `D`; this example only reads it. C++ and Rust meet through files: no FFI, no unsafe, public API of the
|
||||
//! crate only, no module in the production library.
|
||||
//! Rust half of the CPU kernel A/B, part 1 (STRA-289, S0.8b): the KAB1 reader, the comparison against the C++ reference outputs and
|
||||
//! the COMPONENT_KERNEL record writer. The C++ driver (`tools/kernel-ab`, STRA-248) writes a run directory `D`; this example only
|
||||
//! reads it. C++ and Rust meet through files: no FFI, no unsafe, public API of the crate only, no module in the production library.
|
||||
//!
|
||||
//! kernel_ab verify D the reader rule: manifest, every sha256 and length, header-derived
|
||||
//! sizes, finite FP16 block headers and activations; any mismatch
|
||||
//! refuses the WHOLE directory
|
||||
//! kernel_ab verify D the reader rule: manifest, every sha256 and length, header-derived sizes, finite
|
||||
//! FP16 block headers and activations; any mismatch refuses the WHOLE directory
|
||||
//! kernel_ab compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2]
|
||||
//! verify D, run our trees in fresh processes (`run-tree`), compare
|
||||
//! with the C++ `.out` files (bitwise on the f32 bit patterns, or the
|
||||
//! tolerance the manifest case declares with its basis), write
|
||||
//! `R/case-<id>.rust-<tree>.out` and one COMPONENT_KERNEL record per case
|
||||
//! and tree to `R/records/`
|
||||
//! verify D, run our trees in fresh processes (`run-tree`), compare with the C++
|
||||
//! `.out` files (bitwise on the f32 bit patterns, or the tolerance the manifest case
|
||||
//! declares with its basis), write `R/case-<id>.rust-<tree>.out` and one
|
||||
//! COMPONENT_KERNEL record per case and tree to `R/records/`
|
||||
//! kernel_ab run-tree D --tree T --out R [--pin CPU] [--case ID]
|
||||
//! internal: one fresh process, one tree (T = avx512 | avx2), all cases or
|
||||
//! only ID
|
||||
//! internal: one fresh process, one tree (T = avx512 | avx2), all cases or only ID
|
||||
//!
|
||||
//! Timing is not in `verify` / `compare`. The records written by `compare` carry the fields the schema requires for
|
||||
//! timing with the explicit NOT_MEASURED marker (see `NOT_MEASURED`), never a measurement. Timing is the second
|
||||
//! half (STRA-318, S0.8b2):
|
||||
//! Timing is not in `verify` / `compare`. The records written by `compare` carry the fields the schema requires for timing with the
|
||||
//! explicit NOT_MEASURED marker (see `NOT_MEASURED`), never a measurement. Timing is the second half (STRA-318, S0.8b2):
|
||||
//!
|
||||
//! kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60]
|
||||
//! [--regime both|resident|streamed] [--llc-bytes B]
|
||||
//! the Rust twin of `kab time` (tools/kernel-ab, STRA-317): ONE fresh
|
||||
//! process times ONE case in the resident and the streamed regime on the
|
||||
//! pinned CPU and writes the KAB1-time JSON (writer "rust"); no statistics
|
||||
//! kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R]
|
||||
//! [--slices N] [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]
|
||||
//! the alternation runner (ARCHITECT 395f0394 sec 1.3):
|
||||
//! std::process::Command only. Per round it starts FRESH processes for the
|
||||
//! cells {cpp, rust} x {avx512, avx2} (each twice, a and b, for the A/A
|
||||
//! pairs) in the order of a seeded schedule file written before the first
|
||||
//! run, and writes COMPONENT_KERNEL round records. It computes NO
|
||||
//! statistics: no class, no interval, no A/A verdict (those are S0.10b,
|
||||
//! STRA-313).
|
||||
//! kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed]
|
||||
//! [--llc-bytes B]
|
||||
//! the Rust twin of `kab time` (tools/kernel-ab, STRA-317): ONE fresh process times ONE
|
||||
//! case in the resident and the streamed regime on the pinned CPU and writes the KAB1-time
|
||||
//! JSON (writer "rust"); no statistics
|
||||
//! kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N]
|
||||
//! [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]
|
||||
//! the alternation runner (ARCHITECT 395f0394 sec 1.3): std::process::Command only. Per
|
||||
//! round it starts FRESH processes for the cells {cpp, rust} x {avx512, avx2} (each twice,
|
||||
//! a and b, for the A/A pairs) in the order of a seeded schedule file written before the
|
||||
//! first run, and writes COMPONENT_KERNEL round records. It computes NO statistics: no
|
||||
//! class, no interval, no A/A verdict (those are S0.10b, STRA-313).
|
||||
//!
|
||||
//! cargo run --release -p leleka-native-cpu-expert --example kernel_ab -- compare D
|
||||
//! cargo test -p leleka-native-cpu-expert --example kernel_ab
|
||||
@@ -61,12 +53,16 @@ thread_local! { static BUFFERS: Cell<usize> = const { Cell::new(0) }; }
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
// `time` and `alternate` take flags only (the command line of `kab time`); the older commands take the directory
|
||||
// first
|
||||
// `time` and `alternate` take flags only (the command line of `kab time`); the older commands take the directory first
|
||||
if let Some(cmd @ ("time" | "alternate")) = args.first().map(String::as_str) {
|
||||
return run_flag_command(cmd, &args[1..]);
|
||||
let result = if cmd == "time" { cmd_time(&args[1..]) } else { cmd_alternate(&args[1..]) };
|
||||
return result.unwrap_or_else(|e| {
|
||||
eprintln!("kernel_ab {cmd}: {e}");
|
||||
ExitCode::from(1)
|
||||
});
|
||||
}
|
||||
let (Some(cmd), Some(dir)) = (args.first(), args.get(1)) else { return usage() };
|
||||
let dir = Path::new(dir);
|
||||
let opts = match parse_options(&args[2..]) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
@@ -74,7 +70,28 @@ fn main() -> ExitCode {
|
||||
return usage();
|
||||
}
|
||||
};
|
||||
run_dir_command(cmd, Path::new(dir), &opts).unwrap_or_else(usage)
|
||||
let result = match cmd.as_str() {
|
||||
"verify" => match verify_dir(dir) {
|
||||
Ok(v) => {
|
||||
println!("OK {} files (manifest sha256 {})", v.file_count, v.manifest_sha256);
|
||||
Ok(ExitCode::SUCCESS)
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{e}");
|
||||
Ok(ExitCode::from(if e.incomplete { 2 } else { 1 }))
|
||||
}
|
||||
},
|
||||
"compare" => cmd_compare(dir, &opts),
|
||||
"run-tree" => match (&opts.tree, &opts.out) {
|
||||
(Some(t), Some(o)) => cmd_run_tree(dir, t, o, opts.pin, opts.case.as_deref()),
|
||||
_ => return usage(),
|
||||
},
|
||||
_ => return usage(),
|
||||
};
|
||||
result.unwrap_or_else(|e| {
|
||||
eprintln!("kernel_ab: {e}");
|
||||
ExitCode::from(1)
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ tests
|
||||
@@ -174,8 +191,6 @@ use cmd_compare_fn::parse_size;
|
||||
use cmd_compare_fn::percentile_of;
|
||||
#[allow(unused_imports)]
|
||||
use cmd_compare_fn::read_text;
|
||||
#[allow(unused_imports)]
|
||||
use cmd_compare_fn::{machine_role_of, mismatch_detail, read_ours_and_reference, sibling_dir};
|
||||
mod llc_of_cpu_fn;
|
||||
#[allow(unused_imports)]
|
||||
use llc_of_cpu_fn::busy_fraction;
|
||||
@@ -262,22 +277,6 @@ use cmd_alternate_fn::cmd_alternate;
|
||||
#[allow(unused_imports)]
|
||||
use cmd_alternate_fn::usage;
|
||||
|
||||
mod command_dispatch;
|
||||
#[allow(unused_imports)]
|
||||
use command_dispatch::{run_dir_command, run_flag_command, verify_or_exit};
|
||||
mod alternate_run;
|
||||
#[allow(unused_imports)]
|
||||
use alternate_run::{AltRun, prepare_alt_run, run_equality_phase, run_rounds};
|
||||
mod batch_json;
|
||||
#[allow(unused_imports)]
|
||||
use batch_json::batch_json;
|
||||
mod time_session;
|
||||
#[allow(unused_imports)]
|
||||
use time_session::{Measured, PinEnd, Prepared, fill_buffers, first_call, measure, prepare_time_run, read_pin_end};
|
||||
mod time_report;
|
||||
#[allow(unused_imports)]
|
||||
use time_report::{TimeReport, render_time_json};
|
||||
|
||||
mod in_magic_types;
|
||||
#[allow(unused_imports)]
|
||||
use in_magic_types::ALIGN;
|
||||
|
||||
@@ -1,105 +1,44 @@
|
||||
//! Moved out of the parent module by STRA-338: fn read_case_in, fn read_out, fn read_manifest, fn verify_dir, impl
|
||||
//! Outcome, fn compare_bits ....
|
||||
//! Moved out of the parent module by STRA-338: fn read_case_in, fn read_out, fn read_manifest, fn verify_dir, impl Outcome, fn compare_bits ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Opens `path` and returns the file with its length; `name` is what a refusal calls the file.
|
||||
fn open_measured(path: &Path, name: &str) -> Result<(File, u64), Refusal> {
|
||||
let f = File::open(path).map_err(|e| Refusal::new(name, format!("cannot open: {e}")))?;
|
||||
let len = f.metadata().map_err(|e| Refusal::new(name, format!("cannot stat: {e}")))?.len();
|
||||
Ok((f, len))
|
||||
}
|
||||
|
||||
/// The length is at most the limit and holds at least the header.
|
||||
fn require_length_in_range(name: &str, len: u64, header: usize) -> Result<(), Refusal> {
|
||||
if len > MAX_FILE_BYTES || len < header as u64 {
|
||||
return Err(Refusal::new(name, format!("length {len} outside {header}..={MAX_FILE_BYTES}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_header<const N: usize>(f: &mut File, name: &str) -> Result<[u8; N], Refusal> {
|
||||
let mut hdr = [0u8; N];
|
||||
f.read_exact(&mut hdr).map_err(|e| Refusal::new(name, format!("cannot read the header: {e}")))?;
|
||||
Ok(hdr)
|
||||
}
|
||||
|
||||
/// The whole file in one buffer whose first bytes are the header that was already read.
|
||||
fn read_whole(f: &mut File, name: &str, len: u64, hdr: &[u8]) -> Result<Vec<u8>, Refusal> {
|
||||
let mut blob = take_buffer(len as usize).map_err(|reason| Refusal::new(name, reason))?;
|
||||
blob[..hdr.len()].copy_from_slice(hdr);
|
||||
f.read_exact(&mut blob[hdr.len()..]).map_err(|e| Refusal::new(name, format!("cannot read the body: {e}")))?;
|
||||
Ok(blob)
|
||||
}
|
||||
|
||||
/// Reads one case input: length against the manifest and the limit, header decision, THEN the buffer, then sha256, FP16
|
||||
/// headers and finite activations. Any failure names the file.
|
||||
/// Reads one case input: length against the manifest and the limit, header decision, THEN the buffer, then sha256, FP16 headers and
|
||||
/// finite activations. Any failure names the file.
|
||||
pub(super) fn read_case_in(dir: &Path, c: &CaseEntry) -> Result<CaseIn, Refusal> {
|
||||
let name = c.in_name.as_str();
|
||||
let (mut f, len) = open_measured(&dir.join(name), name)?;
|
||||
require_manifest_length(name, len, c.in_bytes)?;
|
||||
require_length_in_range(name, len, IN_HEADER)?;
|
||||
let hdr = read_header::<IN_HEADER>(&mut f, name)?;
|
||||
let header = validate_in_header(&hdr, len).map_err(|reason| Refusal::new(name, reason))?;
|
||||
require_header_matches(name, &header, c)?;
|
||||
let blob = read_whole(&mut f, name, len, &hdr)?;
|
||||
require_sha(name, &blob, &c.in_sha256)?;
|
||||
let case = CaseIn { header, blob };
|
||||
require_finite_input(name, &case)?;
|
||||
Ok(case)
|
||||
}
|
||||
|
||||
fn require_manifest_length(name: &str, len: u64, manifest_bytes: u64) -> Result<(), Refusal> {
|
||||
if len != manifest_bytes {
|
||||
return Err(Refusal::new(name, format!("length {len} differs from the manifest's {manifest_bytes}")));
|
||||
let r = |reason: String| Refusal::new(name, reason);
|
||||
let mut f = File::open(dir.join(name)).map_err(|e| r(format!("cannot open: {e}")))?;
|
||||
let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len();
|
||||
if len != c.in_bytes {
|
||||
return Err(r(format!("length {len} differs from the manifest's {}", c.in_bytes)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The length is the manifest's, when the manifest has an entry for the file.
|
||||
fn require_expected_length(name: &str, len: u64, expect: Option<(&str, u64)>) -> Result<(), Refusal> {
|
||||
match expect {
|
||||
Some((_, bytes)) => require_manifest_length(name, len, bytes),
|
||||
None => Ok(()),
|
||||
if len > MAX_FILE_BYTES || len < IN_HEADER as u64 {
|
||||
return Err(r(format!("length {len} outside {IN_HEADER}..={MAX_FILE_BYTES}")));
|
||||
}
|
||||
}
|
||||
|
||||
/// The hash is the manifest's, when the manifest has an entry for the file.
|
||||
fn require_expected_sha(name: &str, blob: &[u8], expect: Option<(&str, u64)>) -> Result<(), Refusal> {
|
||||
match expect {
|
||||
Some((sha, _)) => require_sha(name, blob, sha),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn require_header_matches(name: &str, header: &InHeader, c: &CaseEntry) -> Result<(), Refusal> {
|
||||
let mut hdr = [0u8; IN_HEADER];
|
||||
f.read_exact(&mut hdr).map_err(|e| r(format!("cannot read the header: {e}")))?;
|
||||
let header = validate_in_header(&hdr, len).map_err(r)?;
|
||||
if header.gu != c.gu || header.down != c.down || header.rows != c.rows {
|
||||
return Err(Refusal::new(name, "the header's types / rows differ from the manifest case"));
|
||||
return Err(r("the header's types / rows differ from the manifest case".to_owned()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_sha(name: &str, blob: &[u8], want: &str) -> Result<(), Refusal> {
|
||||
if sha_hex(blob) != want {
|
||||
return Err(Refusal::new(name, "sha256 differs from the manifest"));
|
||||
let mut blob = take_buffer(len as usize).map_err(r)?;
|
||||
blob[..IN_HEADER].copy_from_slice(&hdr);
|
||||
f.read_exact(&mut blob[IN_HEADER..]).map_err(|e| r(format!("cannot read the body: {e}")))?;
|
||||
if sha_hex(&blob) != c.in_sha256 {
|
||||
return Err(r("sha256 differs from the manifest".to_owned()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every FP16 block header of the weights and every activation of the case is finite.
|
||||
fn require_finite_input(name: &str, case: &CaseIn) -> Result<(), Refusal> {
|
||||
let header = case.header;
|
||||
let case = CaseIn { header, blob };
|
||||
let (gb, db) = (gate_up_row(header.gu).map_or(1, |x| x.3), down_row(header.down).map_or(1, |x| x.3));
|
||||
for (role, bytes, block) in [("gate", case.gate(), gb), ("up", case.up(), gb), ("down", case.down(), db)] {
|
||||
if let Some(at) = fp16_finite(bytes, block) {
|
||||
return Err(Refusal::new(name, format!("non-finite FP16 block header in {role} at byte {at}")));
|
||||
return Err(r(format!("non-finite FP16 block header in {role} at byte {at}")));
|
||||
}
|
||||
}
|
||||
if words_le(&case.blob[header.input_at()..]).into_iter().any(|w| !f32::from_bits(w).is_finite()) {
|
||||
return Err(Refusal::new(name, "non-finite activation"));
|
||||
return Err(r("non-finite activation".to_owned()));
|
||||
}
|
||||
Ok(())
|
||||
Ok(case)
|
||||
}
|
||||
|
||||
/// Reads an `.out` file as f32 bit patterns. `expect` is the manifest's (sha256, bytes) for a C++ file; ours has none.
|
||||
@@ -110,27 +49,40 @@ pub(super) fn read_out(
|
||||
tree: &str,
|
||||
expect: Option<(&str, u64)>,
|
||||
) -> Result<Vec<u32>, Refusal> {
|
||||
let (mut f, len) = open_measured(path, name)?;
|
||||
require_expected_length(name, len, expect)?;
|
||||
require_length_in_range(name, len, OUT_HEADER)?;
|
||||
let hdr = read_header::<OUT_HEADER>(&mut f, name)?;
|
||||
validate_out_header(&hdr, len, rows, tree).map_err(|reason| Refusal::new(name, reason))?;
|
||||
let blob = read_whole(&mut f, name, len, &hdr)?;
|
||||
require_expected_sha(name, &blob, expect)?;
|
||||
let r = |reason: String| Refusal::new(name, reason);
|
||||
let mut f = File::open(path).map_err(|e| r(format!("cannot open: {e}")))?;
|
||||
let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len();
|
||||
if let Some((_, bytes)) = expect
|
||||
&& len != bytes
|
||||
{
|
||||
return Err(r(format!("length {len} differs from the manifest's {bytes}")));
|
||||
}
|
||||
if len > MAX_FILE_BYTES || len < OUT_HEADER as u64 {
|
||||
return Err(r(format!("length {len} outside {OUT_HEADER}..={MAX_FILE_BYTES}")));
|
||||
}
|
||||
let mut hdr = [0u8; OUT_HEADER];
|
||||
f.read_exact(&mut hdr).map_err(|e| r(format!("cannot read the header: {e}")))?;
|
||||
validate_out_header(&hdr, len, rows, tree).map_err(r)?;
|
||||
let mut blob = take_buffer(len as usize).map_err(r)?;
|
||||
blob[..OUT_HEADER].copy_from_slice(&hdr);
|
||||
f.read_exact(&mut blob[OUT_HEADER..]).map_err(|e| r(format!("cannot read the body: {e}")))?;
|
||||
if let Some((sha, _)) = expect
|
||||
&& sha_hex(&blob) != sha
|
||||
{
|
||||
return Err(r("sha256 differs from the manifest".to_owned()));
|
||||
}
|
||||
let bits = words_le(&blob[OUT_HEADER..]);
|
||||
if bits.iter().any(|b| !f32::from_bits(*b).is_finite()) {
|
||||
return Err(Refusal::new(name, "non-finite value"));
|
||||
return Err(r("non-finite value".to_owned()));
|
||||
}
|
||||
Ok(bits)
|
||||
}
|
||||
|
||||
const MANIFEST_NAME: &str = "manifest.json";
|
||||
|
||||
/// Reads and parses `manifest.json` (size cap first). Returns its bytes (the caller hashes them), the provenance, the
|
||||
/// cases and the flat files table. A missing manifest is the `incomplete` refusal.
|
||||
/// Reads and parses `manifest.json` (size cap first). Returns its bytes (the caller hashes them), the provenance, the cases and the flat
|
||||
/// files table. A missing manifest is the `incomplete` refusal.
|
||||
pub(super) fn read_manifest(dir: &Path) -> Result<(Vec<u8>, Provenance, Vec<CaseEntry>, FileTable), Refusal> {
|
||||
let mpath = dir.join("manifest.json");
|
||||
let mname = MANIFEST_NAME;
|
||||
let mname = "manifest.json";
|
||||
if !mpath.is_file() {
|
||||
let mut r = Refusal::new(mname, "no manifest.json (the writer publishes it last)");
|
||||
r.incomplete = true;
|
||||
@@ -149,12 +101,28 @@ pub(super) fn read_manifest(dir: &Path) -> Result<(Vec<u8>, Provenance, Vec<Case
|
||||
Ok((mbytes, provenance, cases, files))
|
||||
}
|
||||
|
||||
/// The reader rule. Everything in the directory is checked before anything is used; any problem refuses the whole
|
||||
/// directory.
|
||||
/// The reader rule. Everything in the directory is checked before anything is used; any problem refuses the whole directory.
|
||||
pub(super) fn verify_dir(dir: &Path) -> Result<Verified, Refusal> {
|
||||
let mname = "manifest.json";
|
||||
let r = |reason: String| Refusal::new(mname, reason);
|
||||
let (mbytes, provenance, cases, files) = read_manifest(dir)?;
|
||||
let names = require_files_agree(&cases, &files)?;
|
||||
require_listing_known(dir, &names)?;
|
||||
// the flat files table and the case entries must describe exactly the same files
|
||||
let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect();
|
||||
expected.sort_unstable();
|
||||
let mut table: Vec<(&str, &str, u64)> = files.iter().map(|(n, s, b)| (n.as_str(), s.as_str(), *b)).collect();
|
||||
table.sort_unstable();
|
||||
if expected != table {
|
||||
return Err(r("the flat files table and the case entries disagree".to_owned()));
|
||||
}
|
||||
let names: BTreeSet<&str> = expected.iter().map(|e| e.0).collect();
|
||||
let listing = fs::read_dir(dir).map_err(|e| r(format!("cannot list the directory: {e}")))?;
|
||||
for entry in listing {
|
||||
let entry = entry.map_err(|e| r(format!("cannot list the directory: {e}")))?;
|
||||
let n = entry.file_name().to_string_lossy().into_owned();
|
||||
if n != mname && !names.contains(n.as_str()) {
|
||||
return Err(Refusal::new(&n, "file is not in the manifest"));
|
||||
}
|
||||
}
|
||||
let file_count = names.len() + 1;
|
||||
for c in &cases {
|
||||
read_case_in(dir, c)?;
|
||||
@@ -164,40 +132,14 @@ pub(super) fn verify_dir(dir: &Path) -> Result<Verified, Refusal> {
|
||||
}
|
||||
Ok(Verified { dir: dir.to_owned(), manifest_sha256: sha_hex(&mbytes), provenance, cases, file_count })
|
||||
}
|
||||
|
||||
/// The flat files table and the case entries must describe exactly the same files; returns their names.
|
||||
fn require_files_agree<'a>(cases: &'a [CaseEntry], files: &FileTable) -> Result<BTreeSet<&'a str>, Refusal> {
|
||||
let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect();
|
||||
expected.sort_unstable();
|
||||
let mut table: Vec<(&str, &str, u64)> = files.iter().map(|(n, s, b)| (n.as_str(), s.as_str(), *b)).collect();
|
||||
table.sort_unstable();
|
||||
if expected != table {
|
||||
return Err(Refusal::new(MANIFEST_NAME, "the flat files table and the case entries disagree"));
|
||||
}
|
||||
Ok(expected.iter().map(|e| e.0).collect())
|
||||
}
|
||||
|
||||
/// Every file of the directory is the manifest or listed in it.
|
||||
fn require_listing_known(dir: &Path, names: &BTreeSet<&str>) -> Result<(), Refusal> {
|
||||
let listing =
|
||||
fs::read_dir(dir).map_err(|e| Refusal::new(MANIFEST_NAME, format!("cannot list the directory: {e}")))?;
|
||||
for entry in listing {
|
||||
let entry = entry.map_err(|e| Refusal::new(MANIFEST_NAME, format!("cannot list the directory: {e}")))?;
|
||||
let n = entry.file_name().to_string_lossy().into_owned();
|
||||
if n != MANIFEST_NAME && !names.contains(n.as_str()) {
|
||||
return Err(Refusal::new(&n, "file is not in the manifest"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
impl Outcome {
|
||||
pub(super) fn equal(&self) -> bool {
|
||||
self.mismatches == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Bitwise on the f32 bit patterns (so -0 and +0 differ) when `tol` is None; otherwise `|ours - ref| <= value *
|
||||
/// max|ref|` per value (the one metric the reader knows, `TOLERANCE_METRIC`).
|
||||
/// Bitwise on the f32 bit patterns (so -0 and +0 differ) when `tol` is None; otherwise `|ours - ref| <= value * max|ref|` per value
|
||||
/// (the one metric the reader knows, `TOLERANCE_METRIC`).
|
||||
pub(super) fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Tolerance>) -> Outcome {
|
||||
let scale = reference.iter().map(|b| f64::from(f32::from_bits(*b)).abs()).fold(0.0, f64::max);
|
||||
let mut o = Outcome {
|
||||
@@ -215,7 +157,11 @@ pub(super) fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Toleran
|
||||
if err.is_finite() {
|
||||
o.max_abs_error = o.max_abs_error.max(err);
|
||||
}
|
||||
if is_mismatch(tol, (*a, *b), err, scale) {
|
||||
let bad = match tol {
|
||||
None => a != b,
|
||||
Some(t) => err.partial_cmp(&(t.value * scale)).is_none_or(|o| o == std::cmp::Ordering::Greater),
|
||||
};
|
||||
if bad {
|
||||
o.mismatches += 1;
|
||||
o.first_mismatch.get_or_insert((i, *a, *b));
|
||||
}
|
||||
@@ -226,16 +172,7 @@ pub(super) fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Toleran
|
||||
o
|
||||
}
|
||||
|
||||
/// Whether one value pair `(ours, reference)` is a mismatch: differing bits when `tol` is None, otherwise an error
|
||||
/// above `value * scale` (or an error that cannot be ordered).
|
||||
fn is_mismatch(tol: Option<&Tolerance>, (a, b): (u32, u32), err: f64, scale: f64) -> bool {
|
||||
match tol {
|
||||
None => a != b,
|
||||
Some(t) => err.partial_cmp(&(t.value * scale)).is_none_or(|o| o == std::cmp::Ordering::Greater),
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ record (hand-written JSON)
|
||||
// ------------------------------------------------------------------------------------------------ record (hand-written JSON)
|
||||
|
||||
pub(super) fn jstr(s: &str) -> String {
|
||||
let mut o = String::with_capacity(s.len() + 2);
|
||||
@@ -256,103 +193,50 @@ pub(super) fn jstr(s: &str) -> String {
|
||||
}
|
||||
|
||||
pub(super) fn record_json(r: &RecordInput) -> String {
|
||||
let p = &r.verified.provenance;
|
||||
let c = r.case;
|
||||
let tolerance = c.tolerance.as_ref().map_or(String::new(), tolerance_json);
|
||||
let mode = if c.tolerance.is_some() { "tolerance" } else { "bitwise" };
|
||||
let tolerance = c.tolerance.as_ref().map_or(String::new(), |t| {
|
||||
format!(
|
||||
",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}",
|
||||
t.value,
|
||||
jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)),
|
||||
jstr(&t.basis_written_utc)
|
||||
)
|
||||
});
|
||||
let tiny = format!("{:e}", f64::from_bits(1));
|
||||
let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4));
|
||||
let mut j = record_head(r, gu, down);
|
||||
j += &record_toolchain(r);
|
||||
j += &record_case(r);
|
||||
j += &record_placeholders(r, gu, down, &tiny);
|
||||
j += &format!(
|
||||
" \"equality\": {{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \
|
||||
\"mismatches\": {}{tolerance}\n }}\n}}\n",
|
||||
if c.tolerance.is_some() { "tolerance" } else { "bitwise" },
|
||||
if r.outcome.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
||||
r.outcome.compared,
|
||||
r.outcome.mismatches
|
||||
);
|
||||
j
|
||||
}
|
||||
|
||||
/// The `tolerance` member of an equality block (with its leading comma) for a case that declares one.
|
||||
fn tolerance_json(t: &Tolerance) -> String {
|
||||
format!(
|
||||
",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}",
|
||||
t.value,
|
||||
jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)),
|
||||
jstr(&t.basis_written_utc)
|
||||
)
|
||||
}
|
||||
|
||||
/// The record from its opening brace to the `kernel` member.
|
||||
fn record_head(r: &RecordInput, gu: &str, down: &str) -> String {
|
||||
format!(
|
||||
"{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {},\n \
|
||||
\"created_utc\": {},\n \
|
||||
\"run_started_utc\": {},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": {}, \"gpu_name\": \"none\", \
|
||||
\"os\": {}}},\n \"kernel\": {},\n",
|
||||
jstr(&r.record_id),
|
||||
jstr(&r.created_utc),
|
||||
jstr(&r.run_started_utc),
|
||||
jstr(&r.machine_role),
|
||||
jstr(&r.cpu_model),
|
||||
jstr(&r.os),
|
||||
jstr(&format!(
|
||||
"{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {rid},\n \"created_utc\": {created},\n \"run_started_utc\": {started},\n \"machine\": {{\"machine_role\": {role}, \"cpu_model\": {cpu}, \"gpu_name\": \"none\", \"os\": {os}}},\n \"kernel\": {kernel},\n \"toolchain\": {{\n \"ours\": {{\"compiler\": {oc}, \"version\": {ov}, \"target_triple\": {ot}, \"flags\": {of}}},\n \"reference\": {{\"compiler\": {rc}, \"version\": {rv}, \"target_triple\": {rt}, \"flags\": {rf}}}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree}, \"reference\": {tree}}},\n \"regime\": \"resident\",\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {nm}, \"ghz_before\": {tiny}, \"ghz_after\": {tiny}, \"max_drift_fraction\": 0, \"slices_total\": 1, \"slices_dropped\": 0}},\n \"rows\": [\n {{\"row_type\": {rowtype}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {{\"median\": {tiny}, \"p05\": {tiny}, \"p95\": {tiny}}}, \"reference\": {{\"median\": {tiny}, \"p05\": {tiny}, \"p95\": {tiny}}}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \"equality\": {{\n \"mode\": \"{mode}\",\n \"verdict\": \"{verdict}\",\n \"compared_values\": {compared},\n \"mismatches\": {mism}{tolerance}\n }}\n}}\n",
|
||||
rid = jstr(&r.record_id),
|
||||
created = jstr(&r.created_utc),
|
||||
started = jstr(&r.run_started_utc),
|
||||
role = jstr(&r.machine_role),
|
||||
cpu = jstr(&r.cpu_model),
|
||||
os = jstr(&r.os),
|
||||
kernel = jstr(&format!(
|
||||
"routed-expert-gate-up-down {gu}+{down} rows={} (equality only; timing {NOT_MEASURED})",
|
||||
r.case.rows
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
/// The `toolchain` member: our compiler and the reference's from the provenance.
|
||||
fn record_toolchain(r: &RecordInput) -> String {
|
||||
let p = &r.verified.provenance;
|
||||
format!(
|
||||
" \"toolchain\": {{\n \"ours\": {{\"compiler\": {}, \"version\": {}, \"target_triple\": {}, \"flags\": \
|
||||
{}}},\n \
|
||||
\"reference\": {{\"compiler\": {}, \"version\": {}, \"target_triple\": {}, \"flags\": {}}}\n }},\n",
|
||||
jstr(&r.ours_compiler),
|
||||
jstr(&r.ours_version),
|
||||
jstr(&r.ours_triple),
|
||||
jstr(&r.ours_flags),
|
||||
jstr(&p.compiler_id),
|
||||
jstr(&p.compiler_version),
|
||||
jstr(&p.target_triple),
|
||||
jstr(&p.reference_flags)
|
||||
)
|
||||
}
|
||||
|
||||
/// The members that name the case, the hashes, the tree, the regime, the pin and the upstream commit.
|
||||
fn record_case(r: &RecordInput) -> String {
|
||||
format!(
|
||||
" \"case_id\": {},\n \"input_sha256\": {},\n \"kab1_manifest_sha256\": {},\n \"tree\": {{\"ours\": {tree}, \
|
||||
\"reference\": {tree}}},\n \"regime\": \"resident\",\n \"pin\": {{\"logical_cpu\": {}, \"sibling_idle\": \
|
||||
{}}},\n \
|
||||
\"strata_upstream_commit\": {},\n",
|
||||
jstr(&r.case.id),
|
||||
jstr(&r.case.in_sha256),
|
||||
jstr(&r.verified.manifest_sha256),
|
||||
r.pin_cpu,
|
||||
r.sibling_idle,
|
||||
jstr(&r.verified.provenance.engine_strata_pin),
|
||||
tree = jstr(r.tree)
|
||||
)
|
||||
}
|
||||
|
||||
/// The members that carry no timing: the NOT_MEASURED markers and the A/A noise floor placeholder.
|
||||
fn record_placeholders(r: &RecordInput, gu: &str, down: &str, tiny: &str) -> String {
|
||||
format!(
|
||||
" \"clock_calibration\": {{\"method\": {}, \"ghz_before\": {tiny}, \"ghz_after\": {tiny}, \
|
||||
\"max_drift_fraction\": 0, \
|
||||
\"slices_total\": 1, \"slices_dropped\": 0}},\n \"rows\": [\n {{\"row_type\": {}, \"unit\": \"ns\", \
|
||||
\"rounds\": 1, \
|
||||
\"ours\": {{\"median\": {tiny}, \"p05\": {tiny}, \"p95\": {tiny}}}, \"reference\": {{\"median\": {tiny}, \
|
||||
\"p05\": {tiny}, \"p95\": {tiny}}}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \
|
||||
\"ci95_low\": 0, \
|
||||
\"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \
|
||||
\"floor_fraction\": 0}},\n",
|
||||
jstr(NOT_MEASURED),
|
||||
jstr(&format!("{gu}+{down} r{} {NOT_MEASURED}", r.case.rows))
|
||||
c.rows
|
||||
)),
|
||||
oc = jstr(&r.ours_compiler),
|
||||
ov = jstr(&r.ours_version),
|
||||
ot = jstr(&r.ours_triple),
|
||||
of = jstr(&r.ours_flags),
|
||||
rc = jstr(&p.compiler_id),
|
||||
rv = jstr(&p.compiler_version),
|
||||
rt = jstr(&p.target_triple),
|
||||
rf = jstr(&p.reference_flags),
|
||||
cid = jstr(&c.id),
|
||||
insha = jstr(&c.in_sha256),
|
||||
msha = jstr(&r.verified.manifest_sha256),
|
||||
tree = jstr(r.tree),
|
||||
pin = r.pin_cpu,
|
||||
sib = r.sibling_idle,
|
||||
commit = jstr(&p.engine_strata_pin),
|
||||
nm = jstr(NOT_MEASURED),
|
||||
rowtype = jstr(&format!("{gu}+{down} r{} {NOT_MEASURED}", c.rows)),
|
||||
verdict = if r.outcome.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
||||
compared = r.outcome.compared,
|
||||
mism = r.outcome.mismatches,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,285 +1,148 @@
|
||||
//! Moved out of the parent module by STRA-338: fn round_records, fn aa_equality_block, fn parse_alt_args, fn
|
||||
//! create_new_file, fn file_sha, fn ours_flags.
|
||||
//! Moved out of the parent module by STRA-338: fn round_records, fn aa_equality_block, fn parse_alt_args, fn create_new_file, fn file_sha, fn ours_flags.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The records of one round: per tree and regime the A/B record (ours = Rust `a`, reference = C++ `a`) and the two A/A
|
||||
/// records.
|
||||
/// The records of one round: per tree and regime the A/B record (ours = Rust `a`, reference = C++ `a`) and the two A/A records.
|
||||
pub(super) fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result<Vec<(String, String)>, String> {
|
||||
let round = Round::new(ctx, round_no, done);
|
||||
let find = |imp: Impl, tree: &str, rep: char| {
|
||||
done.iter()
|
||||
.find(|p| p.proc.imp == imp && p.proc.tree == tree && p.proc.rep == rep)
|
||||
.ok_or_else(|| format!("round {round_no}: process {}-{tree}-{rep} did not run", imp.name()))
|
||||
};
|
||||
let p = &ctx.verified.provenance;
|
||||
let c = ctx.case;
|
||||
let cpp_tool = Tool {
|
||||
compiler: p.compiler_id.clone(),
|
||||
version: p.compiler_version.clone(),
|
||||
triple: p.target_triple.clone(),
|
||||
flags: p.reference_flags.clone(),
|
||||
};
|
||||
let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4));
|
||||
if done.is_empty() {
|
||||
return Err("empty round".to_owned());
|
||||
}
|
||||
let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect();
|
||||
let position = |p: &ProcOut| done.iter().position(|d| d.proc == p.proc).unwrap_or(0);
|
||||
let mut files = Vec::new();
|
||||
let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect();
|
||||
for tree in trees {
|
||||
let procs = TreeProcs::find(done, round_no, tree)?;
|
||||
let (cpp_a, cpp_b, rust_a, rust_b) = (
|
||||
find(Impl::Cpp, tree, 'a')?,
|
||||
find(Impl::Cpp, tree, 'b')?,
|
||||
find(Impl::Rust, tree, 'a')?,
|
||||
find(Impl::Rust, tree, 'b')?,
|
||||
);
|
||||
for regime in ["RESIDENT", "STREAMED"] {
|
||||
for kind in [Kind::Ab, Kind::AaCpp, Kind::AaRust] {
|
||||
files.push(round.record(&round.slot(&procs, tree, regime, kind))?);
|
||||
let (ours, reference, ours_tool, ref_tool) = match kind {
|
||||
Kind::Ab => (rust_a, cpp_a, &ctx.rust_tool, &cpp_tool),
|
||||
Kind::AaCpp => (cpp_a, cpp_b, &cpp_tool, &cpp_tool),
|
||||
Kind::AaRust => (rust_a, rust_b, &ctx.rust_tool, &ctx.rust_tool),
|
||||
};
|
||||
let (o, r) = (&ours.regimes[regime], &reference.regimes[regime]);
|
||||
if (o.copies_k, o.expert_bytes, o.llc_bytes) != (r.copies_k, r.expert_bytes, r.llc_bytes) {
|
||||
return Err(format!(
|
||||
"round {round_no} {tree} {regime}: the streamed set differs between {} and {} (K {} vs {}, LLC {} vs {})",
|
||||
ours.proc.name(),
|
||||
reference.proc.name(),
|
||||
o.copies_k,
|
||||
r.copies_k,
|
||||
o.llc_bytes,
|
||||
r.llc_bytes
|
||||
));
|
||||
}
|
||||
let (equality, equality_note) = match kind {
|
||||
Kind::Ab => (equality_block(c, &ctx.equality[tree]), "Rust output against the C++ reference .out file of the run directory, from the equality phase of this batch".to_owned()),
|
||||
_ => {
|
||||
let (outcome, note) = aa_outcome(ours, reference, c.rows);
|
||||
(aa_equality_block(&outcome), format!("{note}, the same implementation in two fresh processes"))
|
||||
}
|
||||
};
|
||||
let kernel = format!(
|
||||
"routed-expert-gate-up-down {gu}+{down} rows={} regime {regime} ROUND RECORD {} (batch {}, round {round_no}); ours-slot process {}, reference-slot process {}; tree ours: {}; tree reference: {}; equality: {equality_note}; aa_noise_floor is a PLACEHOLDER (n=1, CI 0): the A/A evaluation is S0.10b, this record carries one round's medians only",
|
||||
c.rows,
|
||||
match kind {
|
||||
Kind::Ab => "A/B (ours = Rust, reference = C++)",
|
||||
Kind::AaCpp => "A/A (C++ process a in the ours slot, C++ process b in the reference slot)",
|
||||
Kind::AaRust => "A/A (Rust process a in the ours slot, Rust process b in the reference slot)",
|
||||
},
|
||||
ctx.batch,
|
||||
ours.proc.name(),
|
||||
reference.proc.name(),
|
||||
ours.tree_text,
|
||||
reference.tree_text
|
||||
);
|
||||
let drift = o.max_drift.max(r.max_drift);
|
||||
// the two processes of this record, earliest first: the clock before the earlier one, after the later one
|
||||
let (earlier, later) =
|
||||
if position(ours) <= position(reference) { (ours, reference) } else { (reference, ours) };
|
||||
let sibling_idle = ours.sibling_idle == Some(true) && reference.sibling_idle == Some(true);
|
||||
let streamed = if regime == "STREAMED" {
|
||||
format!(
|
||||
",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}",
|
||||
o.copies_k, o.expert_bytes, o.llc_bytes
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let rowtype =
|
||||
|unit: &str| format!("{gu}+{down} rows={} {} [{unit}]", c.rows, regime.to_ascii_lowercase());
|
||||
let json = format!(
|
||||
"{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {rid},\n \"created_utc\": {created},\n \"run_started_utc\": {started},\n \"machine\": {{\"machine_role\": {role}, \"cpu_model\": {cpu}, \"gpu_name\": \"none\", \"os\": {os}}},\n \"kernel\": {kernel},\n \"toolchain\": {{\n \"ours\": {ot},\n \"reference\": {rt}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree_q}, \"reference\": {tree_q}}},\n \"regime\": {regime_q}{streamed},\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {method}, \"ghz_before\": {g0}, \"ghz_after\": {g1}, \"max_drift_fraction\": {drift}, \"slices_total\": {total}, \"slices_dropped\": {dropped}}},\n \"rows\": [\n {{\"row_type\": {rt_ns}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {on}, \"reference\": {rn}}},\n {{\"row_type\": {rt_cy}, \"unit\": \"cycles\", \"rounds\": 1, \"ours\": {oc}, \"reference\": {rc}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \"equality\": {equality}\n}}\n",
|
||||
rid = jstr(&format!(
|
||||
"kab1alt-{}-{}-b{}-r{round_no:05}-{}-{tree}-{}",
|
||||
ctx.verified.provenance.run_id,
|
||||
c.id,
|
||||
ctx.batch,
|
||||
kind.slug(),
|
||||
regime.to_ascii_lowercase()
|
||||
)),
|
||||
created = jstr(&now_utc()),
|
||||
started = jstr(&ctx.started_utc),
|
||||
role = jstr(&ctx.machine_role),
|
||||
cpu = jstr(&ctx.cpu_model),
|
||||
os = jstr(&ctx.os),
|
||||
kernel = jstr(&kernel),
|
||||
ot = tool_json(ours_tool),
|
||||
rt = tool_json(ref_tool),
|
||||
cid = jstr(&c.id),
|
||||
insha = jstr(&c.in_sha256),
|
||||
msha = jstr(&ctx.verified.manifest_sha256),
|
||||
tree_q = jstr(tree),
|
||||
regime_q = jstr(®ime.to_ascii_lowercase()),
|
||||
pin = ctx.pin,
|
||||
sib = sibling_idle,
|
||||
commit = jstr(&p.engine_strata_pin),
|
||||
method = jstr(&format!(
|
||||
"{CLOCK_METHOD}; ghz_before is the ghz_at_start of the earlier process of this record ({}), ghz_after the ghz_at_end of the later one ({}); sibling_idle: the SMT sibling stayed under 5 percent busy during both processes; max_drift_fraction is the largest |g1 - g0| / g0 over every slice of the two processes of this record, slices_total and slices_dropped count their requested and dropped slices",
|
||||
earlier.proc.name(),
|
||||
later.proc.name()
|
||||
)),
|
||||
g0 = jnum(earlier.ghz_start, 6),
|
||||
g1 = jnum(later.ghz_end, 6),
|
||||
drift = jnum(drift, 6),
|
||||
total = o.requested + r.requested,
|
||||
dropped = o.dropped + r.dropped,
|
||||
rt_ns = jstr(&rowtype("ns")),
|
||||
rt_cy = jstr(&rowtype("cycles")),
|
||||
on = stat_json(&side_stat(o, false)),
|
||||
rn = stat_json(&side_stat(r, false)),
|
||||
oc = stat_json(&side_stat(o, true)),
|
||||
rc = stat_json(&side_stat(r, true)),
|
||||
);
|
||||
files.push((
|
||||
format!("r{round_no:05}.{}.{tree}.{}.json", kind.slug(), regime.to_ascii_lowercase()),
|
||||
json,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn find_proc<'a>(done: &'a [ProcOut], round_no: u32, imp: Impl, tree: &str, rep: char) -> Result<&'a ProcOut, String> {
|
||||
done.iter()
|
||||
.find(|p| p.proc.imp == imp && p.proc.tree == tree && p.proc.rep == rep)
|
||||
.ok_or_else(|| format!("round {round_no}: process {}-{tree}-{rep} did not run", imp.name()))
|
||||
}
|
||||
|
||||
/// The four processes of one tree in a round: C++ and Rust, replicates `a` and `b`.
|
||||
struct TreeProcs<'a> {
|
||||
cpp_a: &'a ProcOut,
|
||||
cpp_b: &'a ProcOut,
|
||||
rust_a: &'a ProcOut,
|
||||
rust_b: &'a ProcOut,
|
||||
}
|
||||
|
||||
impl<'a> TreeProcs<'a> {
|
||||
fn find(done: &'a [ProcOut], round_no: u32, tree: &str) -> Result<Self, String> {
|
||||
Ok(Self {
|
||||
cpp_a: find_proc(done, round_no, Impl::Cpp, tree, 'a')?,
|
||||
cpp_b: find_proc(done, round_no, Impl::Cpp, tree, 'b')?,
|
||||
rust_a: find_proc(done, round_no, Impl::Rust, tree, 'a')?,
|
||||
rust_b: find_proc(done, round_no, Impl::Rust, tree, 'b')?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What one round shares between its records.
|
||||
struct Round<'a> {
|
||||
ctx: &'a BatchCtx<'a>,
|
||||
round_no: u32,
|
||||
done: &'a [ProcOut],
|
||||
cpp_tool: Tool,
|
||||
gu: &'static str,
|
||||
down: &'static str,
|
||||
}
|
||||
|
||||
/// One record of a round: the pair of processes that fill its ours and reference slots, and the tools that built them.
|
||||
struct Slot<'a> {
|
||||
tree: &'static str,
|
||||
regime: &'static str,
|
||||
kind: Kind,
|
||||
ours: &'a ProcOut,
|
||||
reference: &'a ProcOut,
|
||||
ours_tool: &'a Tool,
|
||||
ref_tool: &'a Tool,
|
||||
}
|
||||
|
||||
impl Slot<'_> {
|
||||
fn regime_lower(&self) -> String {
|
||||
self.regime.to_ascii_lowercase()
|
||||
}
|
||||
/// The regime stats of the ours and the reference process.
|
||||
fn stats(&self) -> (&RegimeStat, &RegimeStat) {
|
||||
(&self.ours.regimes[self.regime], &self.reference.regimes[self.regime])
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Round<'a> {
|
||||
fn new(ctx: &'a BatchCtx<'a>, round_no: u32, done: &'a [ProcOut]) -> Self {
|
||||
let p = &ctx.verified.provenance;
|
||||
let cpp_tool = Tool {
|
||||
compiler: p.compiler_id.clone(),
|
||||
version: p.compiler_version.clone(),
|
||||
triple: p.target_triple.clone(),
|
||||
flags: p.reference_flags.clone(),
|
||||
};
|
||||
let c = ctx.case;
|
||||
let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4));
|
||||
Self { ctx, round_no, done, cpp_tool, gu, down }
|
||||
}
|
||||
|
||||
fn slot<'s>(&'s self, procs: &TreeProcs<'s>, tree: &'static str, regime: &'static str, kind: Kind) -> Slot<'s> {
|
||||
let (ours, reference, ours_tool, ref_tool) = match kind {
|
||||
Kind::Ab => (procs.rust_a, procs.cpp_a, &self.ctx.rust_tool, &self.cpp_tool),
|
||||
Kind::AaCpp => (procs.cpp_a, procs.cpp_b, &self.cpp_tool, &self.cpp_tool),
|
||||
Kind::AaRust => (procs.rust_a, procs.rust_b, &self.ctx.rust_tool, &self.ctx.rust_tool),
|
||||
};
|
||||
Slot { tree, regime, kind, ours, reference, ours_tool, ref_tool }
|
||||
}
|
||||
|
||||
/// The file name and the text of one record.
|
||||
fn record(&self, s: &Slot) -> Result<(String, String), String> {
|
||||
self.require_same_streamed_set(s)?;
|
||||
let (equality, equality_note) = self.equality_of(s);
|
||||
let kernel = self.kernel_text(s, &equality_note);
|
||||
let mut json = self.record_head(s, &kernel);
|
||||
json += &self.record_ids(s);
|
||||
json += &self.record_clock(s);
|
||||
json += &self.record_rows(s, &equality);
|
||||
let name = format!("r{:05}.{}.{}.{}.json", self.round_no, s.kind.slug(), s.tree, s.regime_lower());
|
||||
Ok((name, json))
|
||||
}
|
||||
|
||||
/// Both processes of a record timed the same streamed set.
|
||||
fn require_same_streamed_set(&self, s: &Slot) -> Result<(), String> {
|
||||
let (o, r) = s.stats();
|
||||
if (o.copies_k, o.expert_bytes, o.llc_bytes) != (r.copies_k, r.expert_bytes, r.llc_bytes) {
|
||||
return Err(format!(
|
||||
"round {} {} {}: the streamed set differs between {} and {} (K {} vs {}, LLC {} vs {})",
|
||||
self.round_no,
|
||||
s.tree,
|
||||
s.regime,
|
||||
s.ours.proc.name(),
|
||||
s.reference.proc.name(),
|
||||
o.copies_k,
|
||||
r.copies_k,
|
||||
o.llc_bytes,
|
||||
r.llc_bytes
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `equality` block of the record and the note that says where it comes from.
|
||||
fn equality_of(&self, s: &Slot) -> (String, String) {
|
||||
if s.kind == Kind::Ab {
|
||||
let note = "Rust output against the C++ reference .out file of the run directory, from the equality phase \
|
||||
of this batch";
|
||||
return (equality_block(self.ctx.case, &self.ctx.equality[s.tree]), note.to_owned());
|
||||
}
|
||||
let (outcome, note) = aa_outcome(s.ours, s.reference, self.ctx.case.rows);
|
||||
(aa_equality_block(&outcome), format!("{note}, the same implementation in two fresh processes"))
|
||||
}
|
||||
|
||||
fn kernel_text(&self, s: &Slot, equality_note: &str) -> String {
|
||||
let (gu, down, regime, round_no) = (self.gu, self.down, s.regime, self.round_no);
|
||||
let label = match s.kind {
|
||||
Kind::Ab => "A/B (ours = Rust, reference = C++)",
|
||||
Kind::AaCpp => "A/A (C++ process a in the ours slot, C++ process b in the reference slot)",
|
||||
Kind::AaRust => "A/A (Rust process a in the ours slot, Rust process b in the reference slot)",
|
||||
};
|
||||
format!(
|
||||
"routed-expert-gate-up-down {gu}+{down} rows={} regime {regime} ROUND RECORD {label} (batch {}, \
|
||||
round {round_no}); ours-slot process {}, reference-slot process {}; tree ours: {}; tree reference: {}; \
|
||||
equality: {equality_note}; aa_noise_floor is a PLACEHOLDER (n=1, CI 0): the A/A evaluation is S0.10b, \
|
||||
this record carries one round's medians only",
|
||||
self.ctx.case.rows,
|
||||
self.ctx.batch,
|
||||
s.ours.proc.name(),
|
||||
s.reference.proc.name(),
|
||||
s.ours.tree_text,
|
||||
s.reference.tree_text
|
||||
)
|
||||
}
|
||||
|
||||
/// The record from its opening brace through the `toolchain` member.
|
||||
fn record_head(&self, s: &Slot, kernel: &str) -> String {
|
||||
let ctx = self.ctx;
|
||||
format!(
|
||||
"{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {},\n \
|
||||
\"created_utc\": {},\n \"run_started_utc\": {},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": \
|
||||
{}, \
|
||||
\"gpu_name\": \"none\", \"os\": {}}},\n \"kernel\": {},\n \"toolchain\": {{\n \"ours\": {},\n \
|
||||
\"reference\": {}\n }},\n",
|
||||
jstr(&format!(
|
||||
"kab1alt-{}-{}-b{}-r{:05}-{}-{}-{}",
|
||||
ctx.verified.provenance.run_id,
|
||||
ctx.case.id,
|
||||
ctx.batch,
|
||||
self.round_no,
|
||||
s.kind.slug(),
|
||||
s.tree,
|
||||
s.regime_lower()
|
||||
)),
|
||||
jstr(&now_utc()),
|
||||
jstr(&ctx.started_utc),
|
||||
jstr(&ctx.machine_role),
|
||||
jstr(&ctx.cpu_model),
|
||||
jstr(&ctx.os),
|
||||
jstr(kernel),
|
||||
tool_json(s.ours_tool),
|
||||
tool_json(s.ref_tool)
|
||||
)
|
||||
}
|
||||
|
||||
/// The members that name the case, the hashes, the tree, the regime, the pin and the upstream commit.
|
||||
fn record_ids(&self, s: &Slot) -> String {
|
||||
let ctx = self.ctx;
|
||||
let (o, _) = s.stats();
|
||||
let streamed = if s.regime == "STREAMED" {
|
||||
format!(
|
||||
",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}",
|
||||
o.copies_k, o.expert_bytes, o.llc_bytes
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let sibling_idle = s.ours.sibling_idle == Some(true) && s.reference.sibling_idle == Some(true);
|
||||
format!(
|
||||
" \"case_id\": {},\n \"input_sha256\": {},\n \"kab1_manifest_sha256\": {},\n \"tree\": {{\"ours\": \
|
||||
{tree_q}, \
|
||||
\"reference\": {tree_q}}},\n \"regime\": {}{streamed},\n \"pin\": {{\"logical_cpu\": {}, \
|
||||
\"sibling_idle\": {sibling_idle}}},\n \"strata_upstream_commit\": {},\n",
|
||||
jstr(&ctx.case.id),
|
||||
jstr(&ctx.case.in_sha256),
|
||||
jstr(&ctx.verified.manifest_sha256),
|
||||
jstr(&s.regime_lower()),
|
||||
ctx.pin,
|
||||
jstr(&ctx.verified.provenance.engine_strata_pin),
|
||||
tree_q = jstr(s.tree)
|
||||
)
|
||||
}
|
||||
|
||||
/// The `clock_calibration` member: the clock before the earlier process of the record and after the later one.
|
||||
fn record_clock(&self, s: &Slot) -> String {
|
||||
let (o, r) = s.stats();
|
||||
let drift = o.max_drift.max(r.max_drift);
|
||||
let position = |p: &ProcOut| self.done.iter().position(|d| d.proc == p.proc).unwrap_or(0);
|
||||
let (earlier, later) =
|
||||
if position(s.ours) <= position(s.reference) { (s.ours, s.reference) } else { (s.reference, s.ours) };
|
||||
let method = format!(
|
||||
"{CLOCK_METHOD}; ghz_before is the ghz_at_start of the earlier process of this record ({}), ghz_after the \
|
||||
ghz_at_end of the later one ({}); sibling_idle: the SMT sibling stayed under 5 percent busy during both \
|
||||
processes; max_drift_fraction is the largest |g1 - g0| / g0 over every slice of the two processes of this \
|
||||
record, slices_total and slices_dropped count their requested and dropped slices",
|
||||
earlier.proc.name(),
|
||||
later.proc.name()
|
||||
);
|
||||
format!(
|
||||
" \"clock_calibration\": {{\"method\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \"max_drift_fraction\": \
|
||||
{}, \
|
||||
\"slices_total\": {}, \"slices_dropped\": {}}},\n",
|
||||
jstr(&method),
|
||||
jnum(earlier.ghz_start, 6),
|
||||
jnum(later.ghz_end, 6),
|
||||
jnum(drift, 6),
|
||||
o.requested + r.requested,
|
||||
o.dropped + r.dropped
|
||||
)
|
||||
}
|
||||
|
||||
/// The `rows` member (ns and cycles), the A/A noise floor placeholder and the `equality` block.
|
||||
fn record_rows(&self, s: &Slot, equality: &str) -> String {
|
||||
let (o, r) = s.stats();
|
||||
let rowtype =
|
||||
|unit: &str| format!("{}+{} rows={} {} [{unit}]", self.gu, self.down, self.ctx.case.rows, s.regime_lower());
|
||||
format!(
|
||||
" \"rows\": [\n {{\"row_type\": {}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {}, \"reference\": \
|
||||
{}}},\n \
|
||||
{{\"row_type\": {}, \"unit\": \"cycles\", \"rounds\": 1, \"ours\": {}, \"reference\": {}}}\n ],\n \
|
||||
\"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \
|
||||
\"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \
|
||||
\"equality\": {equality}\n}}\n",
|
||||
jstr(&rowtype("ns")),
|
||||
stat_json(&side_stat(o, false)),
|
||||
stat_json(&side_stat(r, false)),
|
||||
jstr(&rowtype("cycles")),
|
||||
stat_json(&side_stat(o, true)),
|
||||
stat_json(&side_stat(r, true))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn aa_equality_block(o: &Outcome) -> String {
|
||||
format!(
|
||||
"{{\n \"mode\": \"bitwise\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \
|
||||
\"mismatches\": {}\n }}",
|
||||
"{{\n \"mode\": \"bitwise\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}\n }}",
|
||||
if o.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
||||
o.compared,
|
||||
o.mismatches
|
||||
@@ -288,43 +151,29 @@ pub(super) fn aa_equality_block(o: &Outcome) -> String {
|
||||
|
||||
pub(super) fn parse_alt_args(args: &[String]) -> Result<AltArgs, String> {
|
||||
let f = Flags::parse(args, &ALT_FLAGS)?;
|
||||
let core = read_alt_core(&f)?;
|
||||
build_alt_args(&f, core)
|
||||
}
|
||||
|
||||
/// The counts and the case of the alternation command line, checked in the order of the command line's own rules.
|
||||
struct AltCore {
|
||||
rounds: u32,
|
||||
batch: u32,
|
||||
case: String,
|
||||
slices: usize,
|
||||
}
|
||||
|
||||
fn read_alt_core(f: &Flags) -> Result<AltCore, String> {
|
||||
let rounds = f.need_number::<u32>("rounds")?;
|
||||
let batch = f.need_number::<u32>("batch")?;
|
||||
let rounds = f.number::<u32>("rounds")?.ok_or("--rounds is required")?;
|
||||
let batch = f.number::<u32>("batch")?.ok_or("--batch is required")?;
|
||||
if !(1..=10_000).contains(&rounds) || !(1..=1000).contains(&batch) {
|
||||
return Err("--rounds must be 1..10000 and --batch 1..1000 (the batch number, counted from 1)".to_owned());
|
||||
}
|
||||
let case = f.case_id()?;
|
||||
let case = f.req("case")?.to_owned();
|
||||
if !valid_id(&case) {
|
||||
return Err(format!("--case {case:?} is not a plain identifier"));
|
||||
}
|
||||
let slices = f.number::<usize>("slices")?.unwrap_or(20);
|
||||
if !(1..=100_000).contains(&slices) {
|
||||
return Err("--slices must be 1..100000".to_owned());
|
||||
}
|
||||
Ok(AltCore { rounds, batch, case, slices })
|
||||
}
|
||||
|
||||
fn build_alt_args(f: &Flags, core: AltCore) -> Result<AltArgs, String> {
|
||||
Ok(AltArgs {
|
||||
dir: PathBuf::from(f.req("run-dir")?),
|
||||
case: core.case,
|
||||
rounds: core.rounds,
|
||||
batch: core.batch,
|
||||
pin: f.need_number::<usize>("pin")?,
|
||||
case,
|
||||
rounds,
|
||||
batch,
|
||||
pin: f.number::<usize>("pin")?.ok_or("--pin is required")?,
|
||||
schedule: PathBuf::from(f.req("schedule")?),
|
||||
seed: f.number::<u64>("seed")?.unwrap_or(1),
|
||||
out: f.get("out").map(PathBuf::from),
|
||||
slices: core.slices,
|
||||
slices,
|
||||
slice_ms: f.number::<f64>("slice-ms")?,
|
||||
llc_bytes: f.number::<u64>("llc-bytes")?,
|
||||
machine_role: f.get("machine-role").map(str::to_owned),
|
||||
|
||||
@@ -4,27 +4,8 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result<RegimeRun, String> {
|
||||
let next = warm_up(t, spec)?;
|
||||
let sampled = sample_slices(t, spec, next)?;
|
||||
let json = regime_json(spec, &sampled);
|
||||
Ok(RegimeRun {
|
||||
json,
|
||||
kept: sampled.kept.len(),
|
||||
ok: !sampled.kept.is_empty() && sampled.migrated.is_none_or(|m| m == 0),
|
||||
})
|
||||
}
|
||||
|
||||
/// The slices of one regime: kept and dropped with their index, and (Linux) how many left the pinned CPU.
|
||||
struct Sampled {
|
||||
kept: Numbered,
|
||||
dropped: Numbered,
|
||||
migrated: Option<usize>,
|
||||
}
|
||||
|
||||
/// Warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is
|
||||
/// resident. Returns the index of the next copy to call.
|
||||
fn warm_up(t: &mut Timed, spec: &RegimeSpec) -> Result<usize, String> {
|
||||
let mut next = 0usize;
|
||||
// warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is resident
|
||||
for _ in 0..3 {
|
||||
t.call(spec.copies[next % spec.copies.len()])?;
|
||||
next += 1;
|
||||
@@ -35,58 +16,24 @@ fn warm_up(t: &mut Timed, spec: &RegimeSpec) -> Result<usize, String> {
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
fn sample_slices(t: &mut Timed, spec: &RegimeSpec, mut next: usize) -> Result<Sampled, String> {
|
||||
let (mut kept, mut dropped): (Numbered, Numbered) = (Vec::new(), Vec::new());
|
||||
let mut migrated: Option<usize> = cfg!(target_os = "linux").then_some(0);
|
||||
for i in 0..spec.slices {
|
||||
let before = current_cpu();
|
||||
let s = time_slice(t, &spec.copies, spec.slice_ms, &mut next)?;
|
||||
if let Some(m) = migrated.as_mut()
|
||||
&& left_pin(before, spec.pin)
|
||||
&& (before != Some(spec.pin) || current_cpu() != Some(spec.pin))
|
||||
{
|
||||
*m += 1;
|
||||
}
|
||||
if s.moved { dropped.push((i, s)) } else { kept.push((i, s)) }
|
||||
}
|
||||
Ok(Sampled { kept, dropped, migrated })
|
||||
}
|
||||
|
||||
/// The slice started off the pinned CPU or ended off it.
|
||||
fn left_pin(before: Option<usize>, pin: usize) -> bool {
|
||||
before != Some(pin) || current_cpu() != Some(pin)
|
||||
}
|
||||
|
||||
fn regime_json(spec: &RegimeSpec, s: &Sampled) -> String {
|
||||
let ns: Vec<f64> = s.kept.iter().map(|k| k.1.ns_per_call).collect();
|
||||
let cyc: Vec<f64> = s.kept.iter().map(|k| k.1.cycles_per_call).collect();
|
||||
let mut json = regime_json_set(spec);
|
||||
json += &format!(
|
||||
"\"slice_ms\": {}, \"slices_requested\": {}, \"slices_kept\": {}, \"dropped_count\": {}, \
|
||||
\"selfcheck_bitwise_equal_first_call\": {}, \"migrated_slices\": {}, \"median_ns_per_call\": {}, \
|
||||
\"median_cycles_per_call\": {},\n \"slices\": [\n {}],\n \"dropped\": [\n {}]}}",
|
||||
jnum(spec.slice_ms, 1),
|
||||
spec.slices,
|
||||
s.kept.len(),
|
||||
s.dropped.len(),
|
||||
spec.selfcheck,
|
||||
s.migrated.map_or("null".to_owned(), |m| m.to_string()),
|
||||
median_json(&ns, 3),
|
||||
median_json(&cyc, 1),
|
||||
slice_list_json(&s.kept),
|
||||
slice_list_json(&s.dropped)
|
||||
);
|
||||
json
|
||||
}
|
||||
|
||||
/// The members of the regime JSON that describe the set of copies and the last-level cache.
|
||||
fn regime_json_set(spec: &RegimeSpec) -> String {
|
||||
format!(
|
||||
"{{\"regime\": {}, \"copies_k\": {}, \"expert_bytes\": {}, \"copy_stride_bytes\": {}, \"working_set_bytes\": \
|
||||
{}, \
|
||||
\"llc_level\": {}, \"llc_bytes\": {}, \"llc_source\": {}, \"working_set_over_llc\": {}, ",
|
||||
let ns: Vec<f64> = kept.iter().map(|k| k.1.ns_per_call).collect();
|
||||
let cyc: Vec<f64> = kept.iter().map(|k| k.1.cycles_per_call).collect();
|
||||
let med = |v: &[f64], d: usize| if v.is_empty() { "null".to_owned() } else { jnum(median_of(v), d) };
|
||||
let list = |v: &[(usize, Slice)]| v.iter().map(|(i, s)| slice_json(s, *i)).collect::<Vec<_>>().join(",\n ");
|
||||
let json = format!(
|
||||
"{{\"regime\": {}, \"copies_k\": {}, \"expert_bytes\": {}, \"copy_stride_bytes\": {}, \"working_set_bytes\": {}, \"llc_level\": {}, \"llc_bytes\": {}, \"llc_source\": {}, \"working_set_over_llc\": {}, \"slice_ms\": {}, \"slices_requested\": {}, \"slices_kept\": {}, \"dropped_count\": {}, \"selfcheck_bitwise_equal_first_call\": {}, \"migrated_slices\": {}, \"median_ns_per_call\": {}, \"median_cycles_per_call\": {},\n \"slices\": [\n {}],\n \"dropped\": [\n {}]}}",
|
||||
jstr(spec.label),
|
||||
spec.copies.len(),
|
||||
spec.expert_bytes,
|
||||
@@ -95,16 +42,19 @@ fn regime_json_set(spec: &RegimeSpec) -> String {
|
||||
spec.llc.level,
|
||||
spec.llc.bytes,
|
||||
jstr(&spec.llc.source),
|
||||
spec.copies.len() > 1
|
||||
)
|
||||
}
|
||||
|
||||
fn median_json(v: &[f64], decimals: usize) -> String {
|
||||
if v.is_empty() { "null".to_owned() } else { jnum(median_of(v), decimals) }
|
||||
}
|
||||
|
||||
fn slice_list_json(v: &[(usize, Slice)]) -> String {
|
||||
v.iter().map(|(i, s)| slice_json(s, *i)).collect::<Vec<_>>().join(",\n ")
|
||||
spec.copies.len() > 1,
|
||||
jnum(spec.slice_ms, 1),
|
||||
spec.slices,
|
||||
kept.len(),
|
||||
dropped.len(),
|
||||
spec.selfcheck,
|
||||
migrated.map_or("null".to_owned(), |m| m.to_string()),
|
||||
med(&ns, 3),
|
||||
med(&cyc, 1),
|
||||
list(&kept),
|
||||
list(&dropped)
|
||||
);
|
||||
Ok(RegimeRun { json, kept: kept.len(), ok: !kept.is_empty() && migrated.is_none_or(|m| m == 0) })
|
||||
}
|
||||
|
||||
pub(super) fn f32_bits_sha(values: &[f32]) -> String {
|
||||
|
||||
@@ -65,7 +65,7 @@ pub(super) struct RegimeSpec<'a> {
|
||||
pub(super) selfcheck: bool,
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------- alternate: cells, environment, schedule
|
||||
// ------------------------------------------------------------------------------------------------ alternate: cells, environment, schedule
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
|
||||
pub(super) enum Impl {
|
||||
@@ -83,7 +83,7 @@ pub(super) struct Proc {
|
||||
|
||||
pub(super) const SCHEDULE_MAGIC: &str = "# KAB1-alt schedule v1";
|
||||
|
||||
// --------------------------------------------------------------------------------- alternate: reading a process's JSON
|
||||
// ------------------------------------------------------------------------------------------------ alternate: reading a process's JSON
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct RegimeStat {
|
||||
@@ -122,7 +122,7 @@ pub(super) struct Expect<'a> {
|
||||
pub(super) pin: usize,
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------- alternate: round records
|
||||
// ------------------------------------------------------------------------------------------------ alternate: round records
|
||||
|
||||
pub(super) struct Tool {
|
||||
pub(super) compiler: String,
|
||||
@@ -159,7 +159,7 @@ pub(super) struct BatchCtx<'a> {
|
||||
pub(super) equality: &'a BTreeMap<&'static str, Outcome>,
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------------- alternate: the runner
|
||||
// ------------------------------------------------------------------------------------------------ alternate: the runner
|
||||
|
||||
pub(super) const ALT_FLAGS: [&str; 13] = [
|
||||
"run-dir",
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
//! The KAB1-time JSON that `kernel_ab time` writes (writer "rust"), one section after the other.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Everything the JSON says: what was prepared, what was measured, the pin at the end and the hash of the output.
|
||||
pub(super) struct TimeReport<'a> {
|
||||
pub(super) p: &'a Prepared,
|
||||
pub(super) end: &'a PinEnd,
|
||||
pub(super) m: &'a Measured,
|
||||
pub(super) output_sha: &'a str,
|
||||
}
|
||||
|
||||
/// The whole JSON text. The sections read the host (load average, current CPU, the clock) as they are built, in this
|
||||
/// order.
|
||||
pub(super) fn render_time_json(r: &TimeReport) -> String {
|
||||
let mut j = String::from(
|
||||
"{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n",
|
||||
);
|
||||
j += §ion_command(r);
|
||||
j += §ion_case(r);
|
||||
j += §ion_tree(r);
|
||||
j += §ion_pool(r);
|
||||
j += §ion_pin(r);
|
||||
j += §ion_buffers(r);
|
||||
j += §ion_clock(r);
|
||||
j += §ion_build();
|
||||
j += §ion_result(r);
|
||||
j
|
||||
}
|
||||
|
||||
/// The command line of the run, as `kab time` would print it.
|
||||
fn time_command_line(r: &TimeReport) -> String {
|
||||
let t = &r.p.t;
|
||||
format!(
|
||||
"time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}",
|
||||
t.dir.display(),
|
||||
t.case,
|
||||
t.slices,
|
||||
t.pin,
|
||||
t.out.display(),
|
||||
if r.p.has_slice_ms { format!(" --slice-ms {}", t.slice_ms) } else { String::new() },
|
||||
match t.regime {
|
||||
RegimeSel::Both => String::new(),
|
||||
RegimeSel::Resident => " --regime resident".to_owned(),
|
||||
RegimeSel::Streamed => " --regime streamed".to_owned(),
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn section_command(r: &TimeReport) -> String {
|
||||
format!(
|
||||
" \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n",
|
||||
jstr(&time_command_line(r)),
|
||||
jstr(&r.p.t.dir.display().to_string()),
|
||||
jstr(&r.p.tc.manifest_sha)
|
||||
)
|
||||
}
|
||||
|
||||
fn section_case(r: &TimeReport) -> String {
|
||||
let header = r.p.tc.case.header;
|
||||
let (gu_name, down_name) =
|
||||
(gate_up_row(header.gu).map_or("?", |x| x.4), down_row(header.down).map_or("?", |x| x.4));
|
||||
format!(
|
||||
" \"case\": {{\"id\": {}, \"gu_type\": {}, \"down_type\": {}, \"gu_name\": {}, \"down_name\": {}, \"rows\": \
|
||||
{}, \
|
||||
\"input_file\": {}, \"input_sha256\": {}, \"input_sha256_matches_manifest\": true, \"expert_bytes\": {}}},\n",
|
||||
jstr(&r.p.t.case),
|
||||
header.gu,
|
||||
header.down,
|
||||
jstr(gu_name),
|
||||
jstr(down_name),
|
||||
header.rows,
|
||||
jstr(&format!("case-{}.in", r.p.t.case)),
|
||||
jstr(&r.p.tc.in_sha256),
|
||||
r.p.plan.expert_bytes
|
||||
)
|
||||
}
|
||||
|
||||
fn section_tree(r: &TimeReport) -> String {
|
||||
format!(
|
||||
" \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \
|
||||
\"effective_env\": {},\n",
|
||||
jstr(r.p.tree),
|
||||
jstr(r.p.tree),
|
||||
r.p.report.iter().map(|l| jstr(l)).collect::<Vec<_>>().join(", "),
|
||||
json_env(&r.p.env),
|
||||
json_env(&r.p.env)
|
||||
)
|
||||
}
|
||||
|
||||
fn section_pool(r: &TimeReport) -> String {
|
||||
format!(
|
||||
" \"pool\": {{\"workers\": 1, \"host_drains\": true, \"threads_observed\": [{}], \"note\": \
|
||||
\"DirectCpuPool::new(1): \
|
||||
one worker thread plus the calling thread that drains beside it (pool.cpp host_works_); both inherit the \
|
||||
one-CPU mask of the pin\"}},\n",
|
||||
r.end
|
||||
.threads
|
||||
.iter()
|
||||
.map(|(n, c)| format!(
|
||||
"{{\"name\": {}, \"cpu\": {}}}",
|
||||
jstr(n),
|
||||
c.map_or("null".to_owned(), |c| c.to_string())
|
||||
))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
)
|
||||
}
|
||||
|
||||
/// A busy fraction with four decimals, or `null` when it is unknown.
|
||||
fn busy_json(f: Option<f64>) -> String {
|
||||
f.map_or("null".to_owned(), |v| jnum(v, 4))
|
||||
}
|
||||
|
||||
fn section_pin(r: &TimeReport) -> String {
|
||||
let (s, e) = (&r.p.start, r.end);
|
||||
let sibling_busy = if s.sibling.is_some() { busy_json(busy_fraction(s.sib0, e.sib1)) } else { "null".to_owned() };
|
||||
format!(
|
||||
" \"pin\": {{\"cpu\": {}, \"thread_siblings_list\": {}, \"sibling_cpu\": {}, \"physical_core_id\": {}, \
|
||||
\"pin_busy_fraction_during_run\": {}, \"sibling_busy_fraction_during_run\": {}, \"sibling_busy_note\": \
|
||||
\"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is \
|
||||
recorded, \
|
||||
no threshold is applied here\", \"scaling_governor\": {}, \"cpufreq_boost\": {}, \"loadavg_start\": {}, \
|
||||
\"loadavg_end\": {}, \"final_cpu\": {}}},\n",
|
||||
r.p.t.pin,
|
||||
jstr(&s.sib_text),
|
||||
s.sibling.map_or("null".to_owned(), |s| s.to_string()),
|
||||
jstr(&read_text(&format!("{}/topology/core_id", s.cpu_dir))),
|
||||
busy_json(busy_fraction(s.pin0, e.pin1)),
|
||||
sibling_busy,
|
||||
jstr(&read_text(&format!("{}/cpufreq/scaling_governor", s.cpu_dir))),
|
||||
jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")),
|
||||
jstr(&s.load0),
|
||||
jstr(&read_text("/proc/loadavg")),
|
||||
current_cpu().map_or("null".to_owned(), |c| c.to_string())
|
||||
)
|
||||
}
|
||||
|
||||
fn section_buffers(r: &TimeReport) -> String {
|
||||
let stride = r.p.plan.stride;
|
||||
format!(
|
||||
" \"buffers\": {{\"alignment_bytes\": {ALIGN}, \"expert_copy_stride_bytes\": {stride}, \
|
||||
\"activations_aligned\": true, \"scratch_aligned\": false, \"scratch_note\": \"the pool's own scratch is \
|
||||
allocated inside the crate\"}},\n"
|
||||
)
|
||||
}
|
||||
|
||||
fn section_clock(r: &TimeReport) -> String {
|
||||
format!(
|
||||
" \"clock_calibration\": {{\"method\": {}, \"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp \
|
||||
--bench: \
|
||||
core_ghz() lines 273-284, time_slice() lines 290-304; the dependent-add chain needs inline assembly, so the \
|
||||
safe Rust twin chains multiplies\", \"drop_rule\": {{\"source_file\": \
|
||||
\"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": 303, \"source_text\": \
|
||||
\"std::fabs(g1 - g0) > 0.05 * g0\", \"fraction\": {}, \"meaning\": \"a slice whose calibrated clock moved by \
|
||||
more than 5 percent between its before and after calibration is dropped\"}}, \"slice_ms_source\": \
|
||||
\"tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60\", \"ghz_at_start\": {}, \"ghz_at_end\": {}, \
|
||||
\"tsc_invariant\": null, \"clocks\": \"monotonic ns (std::time::Instant); no TSC read: rdtsc and lfence are \
|
||||
unsafe intrinsics and the crate keeps unsafe_code = deny\"}},\n",
|
||||
jstr(CLOCK_METHOD),
|
||||
jnum(CLOCK_MOVED_FRACTION, 2),
|
||||
jnum(r.m.ghz0, 6),
|
||||
jnum(r.m.ghz1, 6)
|
||||
)
|
||||
}
|
||||
|
||||
fn section_build() -> String {
|
||||
format!(
|
||||
" \"build\": {{\"profile\": {}, \"rustflags\": {}, \"example\": \
|
||||
\"crates/native-cpu-expert/examples/kernel_ab.rs\"}},\n",
|
||||
jstr(if cfg!(debug_assertions) { "dev" } else { "release" }),
|
||||
jstr(&std::env::var("RUSTFLAGS").unwrap_or_default())
|
||||
)
|
||||
}
|
||||
|
||||
/// The selfcheck, the final check, the output hash, the duration and the regimes.
|
||||
fn section_result(r: &TimeReport) -> String {
|
||||
let (selfcheck, final_same) = (r.m.selfcheck, r.m.final_same);
|
||||
format!(
|
||||
" \"selfcheck_bitwise_equal_first_call\": {selfcheck},\n \"final_output_unchanged\": {final_same},\n \
|
||||
\"output_sha256\": {},\n \"duration_ns\": {},\n \"timing_caveat\": \"numbers from a shared host are not \
|
||||
evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n \"regimes\": [\n \
|
||||
{}\n ]\n}}\n",
|
||||
jstr(r.output_sha),
|
||||
mono_ns() - r.p.wall0,
|
||||
r.m.regimes.jsons.join(",\n ")
|
||||
)
|
||||
}
|
||||
@@ -1,283 +0,0 @@
|
||||
//! The stages of `kernel_ab time` before the JSON is written: the pin and what is known about it, the case, the
|
||||
//! streamed set, the buffers and the measurement of the two regimes.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// What is known about the pinned CPU before the run: its SMT sibling, the jiffies of both and the load average.
|
||||
pub(super) struct PinStart {
|
||||
pub(super) cpu_dir: String,
|
||||
pub(super) sib_text: String,
|
||||
pub(super) sibling: Option<usize>,
|
||||
pub(super) sib0: Option<(u64, u64)>,
|
||||
pub(super) pin0: Option<(u64, u64)>,
|
||||
pub(super) load0: String,
|
||||
}
|
||||
|
||||
/// Pins the process first (before any buffer or pool exists, so the pool's threads inherit the mask); then the facts
|
||||
/// about the pin.
|
||||
pub(super) fn pin_and_probe(t: &TimeArgs) -> Result<PinStart, String> {
|
||||
if rust_topology::pin_current_thread(t.pin as i32) < 0 {
|
||||
return Err(format!("the pin to CPU {} was refused", t.pin));
|
||||
}
|
||||
if cfg!(target_os = "linux") && current_cpu() != Some(t.pin) {
|
||||
return Err(format!("the process is not running on CPU {} after the pin", t.pin));
|
||||
}
|
||||
let cpu_dir = format!("/sys/devices/system/cpu/cpu{}", t.pin);
|
||||
let sib_text = read_text(&format!("{cpu_dir}/topology/thread_siblings_list"));
|
||||
let sibling = parse_cpu_list(&sib_text).into_iter().rfind(|c| *c != t.pin);
|
||||
let sib0 = sibling.and_then(proc_stat_cpu);
|
||||
let pin0 = proc_stat_cpu(t.pin);
|
||||
let load0 = read_text("/proc/loadavg");
|
||||
Ok(PinStart { cpu_dir, sib_text, sibling, sib0, pin0, load0 })
|
||||
}
|
||||
|
||||
/// What `cmd_time` knows before the first kernel call: the command line, the pin, the case, the host report and the
|
||||
/// streamed set.
|
||||
pub(super) struct Prepared {
|
||||
pub(super) t: TimeArgs,
|
||||
pub(super) has_slice_ms: bool,
|
||||
pub(super) wall0: u64,
|
||||
pub(super) start: PinStart,
|
||||
pub(super) tc: TimeCase,
|
||||
pub(super) env: BTreeMap<String, String>,
|
||||
pub(super) report: Vec<String>,
|
||||
pub(super) tree: &'static str,
|
||||
pub(super) plan: StreamPlan,
|
||||
}
|
||||
|
||||
pub(super) fn prepare_time_run(args: &[String]) -> Result<Prepared, String> {
|
||||
let t = parse_time_args(args)?;
|
||||
let wall0 = mono_ns();
|
||||
let start = pin_and_probe(&t)?;
|
||||
let tc = load_time_case(&t)?;
|
||||
let env = managed_env_now();
|
||||
let report = cpu_kernel_report();
|
||||
let tree = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?;
|
||||
let plan = plan_streamed_set(&t, &tc.case)?;
|
||||
Ok(Prepared { has_slice_ms: args.iter().any(|a| a == "--slice-ms"), t, wall0, start, tc, env, report, tree, plan })
|
||||
}
|
||||
|
||||
/// The pool is created AFTER the pin (its worker inherits the one-CPU mask: rust_platform::cores sees a one-CPU
|
||||
/// affinity) and computes the case once, unaligned: the output every later call must reproduce bit for bit.
|
||||
pub(super) fn first_call(case: &CaseIn) -> Result<(DirectCpuPool, Vec<f32>), String> {
|
||||
let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?;
|
||||
let want = compute_case(&mut pool, case)?;
|
||||
Ok((pool, want))
|
||||
}
|
||||
|
||||
/// What is known about the pinned CPU after the run.
|
||||
pub(super) struct PinEnd {
|
||||
pub(super) threads: Vec<(String, Option<usize>)>,
|
||||
pub(super) sib1: Option<(u64, u64)>,
|
||||
pub(super) pin1: Option<(u64, u64)>,
|
||||
}
|
||||
|
||||
pub(super) fn read_pin_end(start: &PinStart, pin: usize) -> PinEnd {
|
||||
let threads = observed_threads();
|
||||
let sib1 = start.sibling.and_then(proc_stat_cpu);
|
||||
let pin1 = proc_stat_cpu(pin);
|
||||
PinEnd { threads, sib1, pin1 }
|
||||
}
|
||||
|
||||
/// The case under test: the KAB1 reader rule (validate, then use) and the manifest and case input hashes.
|
||||
pub(super) struct TimeCase {
|
||||
pub(super) manifest_sha: String,
|
||||
pub(super) in_sha256: String,
|
||||
pub(super) case: CaseIn,
|
||||
}
|
||||
|
||||
pub(super) fn load_time_case(t: &TimeArgs) -> Result<TimeCase, String> {
|
||||
let (manifest_bytes, _provenance, cases, _files) = read_manifest(&t.dir).map_err(|e| e.to_string())?;
|
||||
let manifest_sha = sha_hex(&manifest_bytes);
|
||||
let entry =
|
||||
cases.iter().find(|c| c.id == t.case).ok_or_else(|| format!("case {} is not in the manifest", t.case))?;
|
||||
let case = read_case_in(&t.dir, entry).map_err(|e| e.to_string())?;
|
||||
Ok(TimeCase { manifest_sha, in_sha256: entry.in_sha256.clone(), case })
|
||||
}
|
||||
|
||||
/// The streamed set: K copies of the expert, K x stride at least 2 x the last-level cache of the pinned CPU (the design
|
||||
/// choice of kab_time.cpp).
|
||||
pub(super) struct StreamPlan {
|
||||
pub(super) llc: Llc,
|
||||
pub(super) stride: usize,
|
||||
pub(super) copies_k: usize,
|
||||
pub(super) expert_bytes: usize,
|
||||
}
|
||||
|
||||
pub(super) fn plan_streamed_set(t: &TimeArgs, case: &CaseIn) -> Result<StreamPlan, String> {
|
||||
let expert_bytes = case.weights().len();
|
||||
let llc = resolve_llc(t)?;
|
||||
let stride = expert_bytes.div_ceil(ALIGN) * ALIGN;
|
||||
let copies_k = ((2 * llc.bytes) / stride as u64) as usize + 1;
|
||||
if copies_k * stride > (4usize << 30) {
|
||||
return Err("the streamed working set would exceed 4 GiB; check --llc-bytes".to_owned());
|
||||
}
|
||||
Ok(StreamPlan { llc, stride, copies_k, expert_bytes })
|
||||
}
|
||||
|
||||
/// The last-level cache: the `--llc-bytes` override, else sysfs.
|
||||
fn resolve_llc(t: &TimeArgs) -> Result<Llc, String> {
|
||||
let llc = match (t.llc_bytes, llc_of_cpu(t.pin)) {
|
||||
(Some(bytes), found) => {
|
||||
Llc { level: found.map_or(0, |l| l.level), bytes, source: "--llc-bytes (override)".to_owned() }
|
||||
}
|
||||
(None, Some(l)) => l,
|
||||
(None, None) => {
|
||||
return Err(format!("cannot read the last-level cache size of CPU {} from sysfs; pass --llc-bytes", t.pin));
|
||||
}
|
||||
};
|
||||
if llc.bytes == 0 {
|
||||
return Err("--llc-bytes must be positive".to_owned());
|
||||
}
|
||||
Ok(llc)
|
||||
}
|
||||
|
||||
/// The aligned buffers the timed calls read: the activations, one resident copy of the expert and the streamed copies.
|
||||
pub(super) struct TimeBuffers {
|
||||
tokens: Arena<f32>,
|
||||
resident: Arena<u8>,
|
||||
streamed: Arena<u8>,
|
||||
}
|
||||
|
||||
pub(super) fn fill_buffers(case: &CaseIn, plan: &StreamPlan) -> TimeBuffers {
|
||||
let rows = case.header.rows;
|
||||
let weights = case.weights();
|
||||
let mut tokens = Arena::<f32>::new(rows * H);
|
||||
tokens.slice_mut(rows * H).copy_from_slice(&case.input());
|
||||
let mut resident = Arena::<u8>::new(plan.stride);
|
||||
resident.slice_mut(plan.expert_bytes).copy_from_slice(weights);
|
||||
let mut streamed = Arena::<u8>::new(plan.stride * plan.copies_k);
|
||||
for k in 0..plan.copies_k {
|
||||
let all = streamed.slice_mut(plan.stride * plan.copies_k);
|
||||
all[k * plan.stride..k * plan.stride + plan.expert_bytes].copy_from_slice(weights);
|
||||
}
|
||||
TimeBuffers { tokens, resident, streamed }
|
||||
}
|
||||
|
||||
impl TimeBuffers {
|
||||
/// The call under time: one group of one expert through the crate's public pool.
|
||||
pub(super) fn timed<'a>(&'a self, pool: DirectCpuPool, header: InHeader) -> Result<Timed<'a>, String> {
|
||||
Ok(Timed {
|
||||
pool,
|
||||
gu: gate_up_row(header.gu).ok_or("gate/up type")?.1,
|
||||
down: down_row(header.down).ok_or("down type")?.1,
|
||||
header,
|
||||
pairs: (0..header.rows).map(|r| (r, 0)).collect(),
|
||||
tokens: self.tokens.slice(header.rows * H),
|
||||
out: vec![0.0f32; header.rows * H],
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn copies(&self, plan: &StreamPlan) -> Copies<'_> {
|
||||
let all = self.streamed.slice(plan.stride * plan.copies_k);
|
||||
Copies {
|
||||
resident: vec![self.resident.slice(plan.expert_bytes)],
|
||||
streamed: (0..plan.copies_k).map(|k| &all[k * plan.stride..k * plan.stride + plan.expert_bytes]).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The copies of the expert one regime cycles over.
|
||||
pub(super) struct Copies<'a> {
|
||||
resident: Vec<&'a [u8]>,
|
||||
streamed: Vec<&'a [u8]>,
|
||||
}
|
||||
|
||||
/// What the measurement found: the selfcheck, the clock at both ends, the regime JSON texts and the final output check.
|
||||
pub(super) struct Measured {
|
||||
pub(super) selfcheck: bool,
|
||||
pub(super) ghz0: f64,
|
||||
pub(super) ghz1: f64,
|
||||
pub(super) regimes: RegimeResults,
|
||||
pub(super) final_same: bool,
|
||||
}
|
||||
|
||||
/// The JSON texts of the regimes that ran, whether all were fine and how many slices each kept.
|
||||
pub(super) struct RegimeResults {
|
||||
pub(super) jsons: Vec<String>,
|
||||
pub(super) all_ok: bool,
|
||||
pub(super) kept_res: usize,
|
||||
pub(super) kept_stm: usize,
|
||||
}
|
||||
|
||||
/// Selfcheck, clock, the two regimes, clock, and the final call against the first call's output.
|
||||
pub(super) fn measure(
|
||||
t: &TimeArgs,
|
||||
plan: &StreamPlan,
|
||||
timed: &mut Timed,
|
||||
copies: &Copies,
|
||||
want_bits: &[u32],
|
||||
) -> Result<Measured, String> {
|
||||
let last = plan.copies_k - 1;
|
||||
let selfcheck = run_selfcheck(timed, [copies.resident[0], copies.streamed[0], copies.streamed[last]], want_bits)?;
|
||||
let ghz0 = core_ghz();
|
||||
let regimes = run_regimes(t, plan, timed, copies, selfcheck)?;
|
||||
let ghz1 = core_ghz();
|
||||
timed.call(copies.resident[0])?;
|
||||
let final_same = same_bits(&timed.out, want_bits);
|
||||
Ok(Measured { selfcheck, ghz0, ghz1, regimes, final_same })
|
||||
}
|
||||
|
||||
fn same_bits(out: &[f32], want_bits: &[u32]) -> bool {
|
||||
out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied())
|
||||
}
|
||||
|
||||
/// The timed call's output on every aligned copy is bit-identical to the first (unaligned) call's; true, or an error.
|
||||
fn run_selfcheck(timed: &mut Timed, weights: [&[u8]; 3], want_bits: &[u32]) -> Result<bool, String> {
|
||||
let mut selfcheck = true;
|
||||
for w in weights {
|
||||
timed.call(w)?;
|
||||
selfcheck &= same_bits(&timed.out, want_bits);
|
||||
}
|
||||
if !selfcheck {
|
||||
return Err("selfcheck failed: the timed call differs from the first call".to_owned());
|
||||
}
|
||||
Ok(selfcheck)
|
||||
}
|
||||
|
||||
fn regime_spec<'a>(
|
||||
t: &TimeArgs,
|
||||
plan: &'a StreamPlan,
|
||||
label: &'a str,
|
||||
copies: Vec<&'a [u8]>,
|
||||
selfcheck: bool,
|
||||
) -> RegimeSpec<'a> {
|
||||
RegimeSpec {
|
||||
label,
|
||||
copies,
|
||||
expert_bytes: plan.expert_bytes,
|
||||
stride: plan.stride,
|
||||
llc: &plan.llc,
|
||||
slices: t.slices,
|
||||
slice_ms: t.slice_ms,
|
||||
pin: t.pin,
|
||||
selfcheck,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_regimes(
|
||||
t: &TimeArgs,
|
||||
plan: &StreamPlan,
|
||||
timed: &mut Timed,
|
||||
copies: &Copies,
|
||||
selfcheck: bool,
|
||||
) -> Result<RegimeResults, String> {
|
||||
let mut results = RegimeResults { jsons: Vec::new(), all_ok: true, kept_res: 0, kept_stm: 0 };
|
||||
for (label, set, sel) in
|
||||
[("RESIDENT", &copies.resident, RegimeSel::Resident), ("STREAMED", &copies.streamed, RegimeSel::Streamed)]
|
||||
{
|
||||
if t.regime != RegimeSel::Both && t.regime != sel {
|
||||
continue;
|
||||
}
|
||||
let r = run_regime(timed, ®ime_spec(t, plan, label, set.clone(), selfcheck))?;
|
||||
results.all_ok &= r.ok;
|
||||
if sel == RegimeSel::Resident {
|
||||
results.kept_res = r.kept
|
||||
} else {
|
||||
results.kept_stm = r.kept
|
||||
}
|
||||
results.jsons.push(r.json);
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
@@ -1,12 +1,16 @@
|
||||
//! Moved out of the parent module by STRA-338: fn validate_in_header, fn validate_out_header, fn fp16_finite, fn
|
||||
//! parse_manifest, fn case_files, impl CaseIn.
|
||||
//! Moved out of the parent module by STRA-338: fn validate_in_header, fn validate_out_header, fn fp16_finite, fn parse_manifest, fn case_files, impl CaseIn.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Pure: decides from 64 header bytes and the file length, allocates nothing.
|
||||
pub(super) fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result<InHeader, String> {
|
||||
require_magic_and_version(h)?;
|
||||
if le32(h, 0) != IN_MAGIC {
|
||||
return Err(format!("wrong magic 0x{:08x}, expected 0x{IN_MAGIC:08x}", le32(h, 0)));
|
||||
}
|
||||
if le32(h, 4) != 1 {
|
||||
return Err(format!("unsupported version {}, expected 1", le32(h, 4)));
|
||||
}
|
||||
let (gu, down) = (le32(h, 8) as i32, le32(h, 12) as i32);
|
||||
let Some(&(_, _, gq, gb, _)) = gate_up_row(gu) else {
|
||||
return Err(format!("gate/up type {gu} is not in the KAB1 list"));
|
||||
@@ -15,8 +19,14 @@ pub(super) fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result<I
|
||||
return Err(format!("down type {down} is not in the KAB1 list"));
|
||||
};
|
||||
let rows = le32(h, 16) as usize;
|
||||
require_rows_and_dims(h, rows)?;
|
||||
let (gsize, dsize) = ((H / gq * gb * FF) as u64, (FF / dq * db * H) as u64);
|
||||
if !(1..=MAX_ROWS).contains(&rows) {
|
||||
return Err(format!("rows {rows} outside 1..={MAX_ROWS}"));
|
||||
}
|
||||
if le32(h, 20) as usize != H || le32(h, 24) as usize != FF {
|
||||
return Err(format!("n_embd {} / n_ff {} differ from {H} / {FF}", le32(h, 20), le32(h, 24)));
|
||||
}
|
||||
let gsize = (H / gq * gb * FF) as u64;
|
||||
let dsize = (FF / dq * db * H) as u64;
|
||||
let (g, u, d) = (le32(h, 28) as u64, le32(h, 32) as u64, le32(h, 36) as u64);
|
||||
if g != gsize || u != gsize || d != dsize {
|
||||
return Err(format!(
|
||||
@@ -33,27 +43,6 @@ pub(super) fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result<I
|
||||
Ok(InHeader { gu, down, rows, gate: g as usize, up: u as usize, down_bytes: d as usize })
|
||||
}
|
||||
|
||||
fn require_magic_and_version(h: &[u8; IN_HEADER]) -> Result<(), String> {
|
||||
if le32(h, 0) != IN_MAGIC {
|
||||
return Err(format!("wrong magic 0x{:08x}, expected 0x{IN_MAGIC:08x}", le32(h, 0)));
|
||||
}
|
||||
if le32(h, 4) != 1 {
|
||||
return Err(format!("unsupported version {}, expected 1", le32(h, 4)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The row count is in range and the embedding and feed-forward widths are the ones this reader knows.
|
||||
fn require_rows_and_dims(h: &[u8; IN_HEADER], rows: usize) -> Result<(), String> {
|
||||
if !(1..=MAX_ROWS).contains(&rows) {
|
||||
return Err(format!("rows {rows} outside 1..={MAX_ROWS}"));
|
||||
}
|
||||
if le32(h, 20) as usize != H || le32(h, 24) as usize != FF {
|
||||
return Err(format!("n_embd {} / n_ff {} differ from {H} / {FF}", le32(h, 20), le32(h, 24)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pure: 20 bytes and the file length.
|
||||
pub(super) fn validate_out_header(h: &[u8; OUT_HEADER], file_len: u64, rows: usize, tree: &str) -> Result<(), String> {
|
||||
if le32(h, 0) != OUT_MAGIC {
|
||||
@@ -84,167 +73,109 @@ pub(super) fn parse_manifest(m: &Json) -> Result<(Provenance, Vec<CaseEntry>, Fi
|
||||
if m.str("format")? != "KAB1" || m.uint("version")? != 1 {
|
||||
return Err("format is not KAB1 version 1".to_owned());
|
||||
}
|
||||
let (provenance, built) = parse_provenance(m)?;
|
||||
let cases = parse_cases(m, built)?;
|
||||
let files = parse_file_table(m)?;
|
||||
require_unique_cases(&cases)?;
|
||||
Ok((provenance, cases, files))
|
||||
}
|
||||
|
||||
/// The provenance block and the time the reference run was built (a tolerance basis may not be written after it).
|
||||
fn parse_provenance(m: &Json) -> Result<(Provenance, &str), String> {
|
||||
let p = m.req("provenance")?;
|
||||
let flags = p.req("flags")?;
|
||||
let commit = read_commit(p)?;
|
||||
let built = read_built(p)?;
|
||||
let commit = p.str("engine_strata_pin")?;
|
||||
if !is_hex(commit, 7, 40) {
|
||||
return Err("provenance.engine_strata_pin is not a commit hash".to_owned());
|
||||
}
|
||||
let built = p.str("built_at_utc")?;
|
||||
if !is_utc(built) {
|
||||
return Err("provenance.built_at_utc is not a UTC timestamp".to_owned());
|
||||
}
|
||||
let avx512_ok = match p.get("avx512_ok") {
|
||||
Some(Json::Bool(b)) => Some(*b),
|
||||
_ => None,
|
||||
};
|
||||
let provenance = Provenance {
|
||||
run_id: m.str("run_id")?.to_owned(),
|
||||
engine_strata_pin: commit.to_owned(),
|
||||
compiler_id: p.str("compiler_id")?.to_owned(),
|
||||
compiler_version: p.str("compiler_version")?.to_owned(),
|
||||
target_triple: p.str("target_triple")?.to_owned(),
|
||||
reference_flags: reference_flags(flags)?,
|
||||
avx512_ok: read_avx512_ok(p),
|
||||
reference_flags: format!(
|
||||
"strata_cxx_flags: {}; ggml_cpu_arch_flags: {}",
|
||||
flags.str("strata_cxx_flags")?,
|
||||
flags.str("ggml_cpu_arch_flags")?
|
||||
),
|
||||
avx512_ok,
|
||||
};
|
||||
Ok((provenance, built))
|
||||
}
|
||||
|
||||
/// Whether the reference build had AVX-512; None when the manifest does not say.
|
||||
fn read_avx512_ok(p: &Json) -> Option<bool> {
|
||||
match p.get("avx512_ok") {
|
||||
Some(Json::Bool(b)) => Some(*b),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_commit(p: &Json) -> Result<&str, String> {
|
||||
let commit = p.str("engine_strata_pin")?;
|
||||
if !is_hex(commit, 7, 40) {
|
||||
return Err("provenance.engine_strata_pin is not a commit hash".to_owned());
|
||||
}
|
||||
Ok(commit)
|
||||
}
|
||||
|
||||
fn read_built(p: &Json) -> Result<&str, String> {
|
||||
let built = p.str("built_at_utc")?;
|
||||
if !is_utc(built) {
|
||||
return Err("provenance.built_at_utc is not a UTC timestamp".to_owned());
|
||||
}
|
||||
Ok(built)
|
||||
}
|
||||
|
||||
/// The compile flags of the reference build, as one line.
|
||||
fn reference_flags(flags: &Json) -> Result<String, String> {
|
||||
Ok(format!(
|
||||
"strata_cxx_flags: {}; ggml_cpu_arch_flags: {}",
|
||||
flags.str("strata_cxx_flags")?,
|
||||
flags.str("ggml_cpu_arch_flags")?
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_cases(m: &Json, built: &str) -> Result<Vec<CaseEntry>, String> {
|
||||
let Json::Arr(cases_json) = m.req("cases")? else { return Err("cases is not an array".to_owned()) };
|
||||
if cases_json.is_empty() || cases_json.len() > MAX_CASES {
|
||||
return Err(format!("{} cases (1..={MAX_CASES} allowed)", cases_json.len()));
|
||||
}
|
||||
let mut cases = Vec::new();
|
||||
for c in cases_json {
|
||||
cases.push(parse_case(c, built)?);
|
||||
}
|
||||
Ok(cases)
|
||||
}
|
||||
|
||||
/// The id, the row count and the input file name of a case.
|
||||
struct CaseHead {
|
||||
id: String,
|
||||
rows: usize,
|
||||
in_name: String,
|
||||
}
|
||||
|
||||
fn read_case_head(c: &Json) -> Result<CaseHead, String> {
|
||||
let id = c.str("id")?.to_owned();
|
||||
if !valid_id(&id) {
|
||||
return Err(format!("case id {id:?} is not a plain identifier"));
|
||||
}
|
||||
let rows = c.uint("rows")? as usize;
|
||||
let in_name = format!("case-{id}.in");
|
||||
if c.str("in")? != in_name {
|
||||
return Err(format!("case {id}: file name {:?} is not {in_name}", c.str("in")?));
|
||||
}
|
||||
Ok(CaseHead { id, rows, in_name })
|
||||
}
|
||||
|
||||
fn parse_case(c: &Json, built: &str) -> Result<CaseEntry, String> {
|
||||
let CaseHead { id, rows, in_name } = read_case_head(c)?;
|
||||
let outs = parse_outs(c, &id)?;
|
||||
let tolerance = parse_tolerance(c, &id, built)?;
|
||||
let in_sha256 = c.str("in_sha256")?.to_owned();
|
||||
let gu = c.uint("gu_type")? as i32;
|
||||
let down = c.uint("down_type")? as i32;
|
||||
Ok(CaseEntry { id, gu, down, rows, in_name, in_sha256, in_bytes: c.uint("in_bytes")?, outs, tolerance })
|
||||
}
|
||||
|
||||
/// The C++ output file of every tree of the case.
|
||||
fn parse_outs(c: &Json, id: &str) -> Result<Vec<OutRef>, String> {
|
||||
let mut outs = Vec::new();
|
||||
for tree in TREES {
|
||||
let key = format!("out_cpp_{tree}");
|
||||
let name = format!("case-{id}.cpp-{tree}.out");
|
||||
if c.str(&key)? != name {
|
||||
return Err(format!("case {id}: file name {:?} is not {name}", c.str(&key)?));
|
||||
let id = c.str("id")?.to_owned();
|
||||
if !valid_id(&id) {
|
||||
return Err(format!("case id {id:?} is not a plain identifier"));
|
||||
}
|
||||
outs.push(OutRef {
|
||||
tree,
|
||||
name,
|
||||
sha256: c.str(&format!("{key}_sha256"))?.to_owned(),
|
||||
bytes: c.uint(&format!("{key}_bytes"))?,
|
||||
let rows = c.uint("rows")? as usize;
|
||||
let in_name = format!("case-{id}.in");
|
||||
if c.str("in")? != in_name {
|
||||
return Err(format!("case {id}: file name {:?} is not {in_name}", c.str("in")?));
|
||||
}
|
||||
let mut outs = Vec::new();
|
||||
for tree in TREES {
|
||||
let key = format!("out_cpp_{tree}");
|
||||
let name = format!("case-{id}.cpp-{tree}.out");
|
||||
if c.str(&key)? != name {
|
||||
return Err(format!("case {id}: file name {:?} is not {name}", c.str(&key)?));
|
||||
}
|
||||
outs.push(OutRef {
|
||||
tree,
|
||||
name,
|
||||
sha256: c.str(&format!("{key}_sha256"))?.to_owned(),
|
||||
bytes: c.uint(&format!("{key}_bytes"))?,
|
||||
});
|
||||
}
|
||||
let tolerance = match (c.str("equality")?, c.req("tolerance")?) {
|
||||
("bitwise", Json::Null) => None,
|
||||
("tolerance", t @ Json::Obj(_)) => {
|
||||
if t.str("metric")? != TOLERANCE_METRIC {
|
||||
return Err(format!(
|
||||
"case {id}: tolerance metric {:?} is not {TOLERANCE_METRIC}",
|
||||
t.str("metric")?
|
||||
));
|
||||
}
|
||||
let value = match t.req("value")? {
|
||||
Json::Num(n) => n.parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| format!("case {id}: tolerance.value is not a positive number"))?;
|
||||
let basis = t.str("basis")?.to_owned();
|
||||
let written = t.str("basis_written_utc")?.to_owned();
|
||||
if basis.trim().is_empty() || !is_utc(&written) {
|
||||
return Err(format!("case {id}: tolerance needs a non-empty basis and a UTC basis_written_utc"));
|
||||
}
|
||||
if written.as_str() > built {
|
||||
return Err(format!(
|
||||
"case {id}: the tolerance basis was written {written}, after the reference run {built}"
|
||||
));
|
||||
}
|
||||
Some(Tolerance { value, basis, basis_written_utc: written })
|
||||
}
|
||||
(other, _) => {
|
||||
return Err(format!(
|
||||
"case {id}: equality {other:?} and tolerance disagree (bitwise needs null, tolerance an object)"
|
||||
));
|
||||
}
|
||||
};
|
||||
let in_sha256 = c.str("in_sha256")?.to_owned();
|
||||
let gu = c.uint("gu_type")? as i32;
|
||||
let down = c.uint("down_type")? as i32;
|
||||
cases.push(CaseEntry {
|
||||
id,
|
||||
gu,
|
||||
down,
|
||||
rows,
|
||||
in_name,
|
||||
in_sha256,
|
||||
in_bytes: c.uint("in_bytes")?,
|
||||
outs,
|
||||
tolerance,
|
||||
});
|
||||
}
|
||||
Ok(outs)
|
||||
}
|
||||
|
||||
/// None for a bitwise case; the declared tolerance for a tolerance case; the two must agree with `equality`.
|
||||
fn parse_tolerance(c: &Json, id: &str, built: &str) -> Result<Option<Tolerance>, String> {
|
||||
match (c.str("equality")?, c.req("tolerance")?) {
|
||||
("bitwise", Json::Null) => Ok(None),
|
||||
("tolerance", t @ Json::Obj(_)) => read_tolerance(t, id, built).map(Some),
|
||||
(other, _) => Err(format!(
|
||||
"case {id}: equality {other:?} and tolerance disagree (bitwise needs null, tolerance an object)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_tolerance(t: &Json, id: &str, built: &str) -> Result<Tolerance, String> {
|
||||
if t.str("metric")? != TOLERANCE_METRIC {
|
||||
return Err(format!("case {id}: tolerance metric {:?} is not {TOLERANCE_METRIC}", t.str("metric")?));
|
||||
}
|
||||
let value = read_tolerance_value(t, id)?;
|
||||
let basis = t.str("basis")?.to_owned();
|
||||
let written = t.str("basis_written_utc")?.to_owned();
|
||||
require_basis(id, &basis, &written, built)?;
|
||||
Ok(Tolerance { value, basis, basis_written_utc: written })
|
||||
}
|
||||
|
||||
fn read_tolerance_value(t: &Json, id: &str) -> Result<f64, String> {
|
||||
match t.req("value")? {
|
||||
Json::Num(n) => n.parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| format!("case {id}: tolerance.value is not a positive number"))
|
||||
}
|
||||
|
||||
/// The basis is stated, dated in UTC, and written no later than the reference run.
|
||||
fn require_basis(id: &str, basis: &str, written: &str, built: &str) -> Result<(), String> {
|
||||
if basis.trim().is_empty() || !is_utc(written) {
|
||||
return Err(format!("case {id}: tolerance needs a non-empty basis and a UTC basis_written_utc"));
|
||||
}
|
||||
if written > built {
|
||||
return Err(format!("case {id}: the tolerance basis was written {written}, after the reference run {built}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_file_table(m: &Json) -> Result<FileTable, String> {
|
||||
let Json::Obj(files_json) = m.req("files")? else { return Err("files is not an object".to_owned()) };
|
||||
let mut files = Vec::new();
|
||||
for (name, v) in files_json {
|
||||
@@ -254,13 +185,8 @@ fn parse_file_table(m: &Json) -> Result<FileTable, String> {
|
||||
}
|
||||
files.push((name.clone(), sha.to_owned(), v.uint("bytes")?));
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
/// Case ids are unique and every sha256 of a case is 64 lowercase hex digits.
|
||||
fn require_unique_cases(cases: &[CaseEntry]) -> Result<(), String> {
|
||||
let mut seen = BTreeSet::new();
|
||||
for c in cases {
|
||||
for c in &cases {
|
||||
if !seen.insert(c.id.clone()) {
|
||||
return Err(format!("case id {} appears twice", c.id));
|
||||
}
|
||||
@@ -270,7 +196,7 @@ fn require_unique_cases(cases: &[CaseEntry]) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok((provenance, cases, files))
|
||||
}
|
||||
|
||||
pub(super) fn case_files(c: &CaseEntry) -> Vec<(&str, &str, u64)> {
|
||||
@@ -290,10 +216,6 @@ impl CaseIn {
|
||||
let s = IN_HEADER + self.header.gate + self.header.up;
|
||||
&self.blob[s..s + self.header.down_bytes]
|
||||
}
|
||||
/// The expert's weights: gate, up and down, which sit between the header and the activations.
|
||||
pub(super) fn weights(&self) -> &[u8] {
|
||||
&self.blob[IN_HEADER..self.header.input_at()]
|
||||
}
|
||||
pub(super) fn input(&self) -> Vec<f32> {
|
||||
words_le(&self.blob[self.header.input_at()..]).into_iter().map(f32::from_bits).collect()
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
//! Moved out of the parent module by STRA-338: fn write_out, fn compute_case, fn family_of, fn cmd_run_tree, fn
|
||||
//! sibling_idle, fn rustc_info ....
|
||||
//! Moved out of the parent module by STRA-338: fn write_out, fn compute_case, fn family_of, fn cmd_run_tree, fn sibling_idle, fn rustc_info ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
// ---------------------------------------------------------------------------------------- run-tree (one fresh process)
|
||||
// ------------------------------------------------------------------------------------------------ run-tree (one fresh process)
|
||||
|
||||
pub(super) fn write_out(path: &Path, rows: usize, tree: &str, values: &[f32]) -> Result<(), String> {
|
||||
let tree_id = TREES.iter().position(|t| *t == tree).ok_or("unknown tree")? as u32;
|
||||
@@ -18,8 +17,8 @@ pub(super) fn write_out(path: &Path, rows: usize, tree: &str, values: &[f32]) ->
|
||||
File::create(path).and_then(|mut f| f.write_all(&b)).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Our kernels on one verified case through the public API: PreparedJob only for the input validation it performs, then
|
||||
/// one `compute_group` over borrowed bytes (one expert, `rows` tokens, pairs `(t, 0)`, stride 1).
|
||||
/// Our kernels on one verified case through the public API: PreparedJob only for the input validation it performs, then one
|
||||
/// `compute_group` over borrowed bytes (one expert, `rows` tokens, pairs `(t, 0)`, stride 1).
|
||||
pub(super) fn compute_case(pool: &mut DirectCpuPool, case: &CaseIn) -> Result<Vec<f32>, String> {
|
||||
let (gu, down) =
|
||||
(gate_up_row(case.header.gu).ok_or("gate/up type")?.1, down_row(case.header.down).ok_or("down type")?.1);
|
||||
@@ -58,39 +57,20 @@ pub(super) fn cmd_run_tree(
|
||||
only_case: Option<&str>,
|
||||
) -> Result<ExitCode, String> {
|
||||
let verified = verify_dir(dir).map_err(|e| e.to_string())?;
|
||||
pin_process(pin);
|
||||
let previous = rust_topology::pin_current_thread(pin as i32);
|
||||
if previous < 0 {
|
||||
eprintln!("kernel_ab: the pin to CPU {pin} was refused; running unpinned");
|
||||
}
|
||||
let report = cpu_kernel_report();
|
||||
print_report(&report);
|
||||
for line in &report {
|
||||
println!("REPORT {line}");
|
||||
}
|
||||
let family = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?;
|
||||
if family != tree {
|
||||
eprintln!("kernel_ab: this process runs the {family} family, not {tree}");
|
||||
return Ok(ExitCode::from(3));
|
||||
}
|
||||
fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let done = write_tree_outputs(&verified, tree, out, only_case)?;
|
||||
if done == 0 {
|
||||
return Err(format!("case {} is not in the manifest", only_case.unwrap_or("?")));
|
||||
}
|
||||
println!("RUN-TREE {tree} cases={done}");
|
||||
Ok(ExitCode::SUCCESS)
|
||||
}
|
||||
|
||||
/// Pins the calling thread; a refused pin is reported and the run goes on unpinned.
|
||||
fn pin_process(pin: usize) {
|
||||
if rust_topology::pin_current_thread(pin as i32) < 0 {
|
||||
eprintln!("kernel_ab: the pin to CPU {pin} was refused; running unpinned");
|
||||
}
|
||||
}
|
||||
|
||||
fn print_report(report: &[String]) {
|
||||
for line in report {
|
||||
println!("REPORT {line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the cases (all, or only `only_case`) with a one-worker pool and writes one `.out` file per case; returns
|
||||
/// how many.
|
||||
fn write_tree_outputs(verified: &Verified, tree: &str, out: &Path, only_case: Option<&str>) -> Result<usize, String> {
|
||||
let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?;
|
||||
let mut done = 0usize;
|
||||
for c in verified.cases.iter().filter(|c| only_case.is_none_or(|id| c.id == id)) {
|
||||
@@ -99,61 +79,53 @@ fn write_tree_outputs(verified: &Verified, tree: &str, out: &Path, only_case: Op
|
||||
write_out(&out.join(format!("case-{}.rust-{tree}.out", c.id)), c.rows, tree, &values)?;
|
||||
done += 1;
|
||||
}
|
||||
Ok(done)
|
||||
if done == 0 {
|
||||
return Err(format!("case {} is not in the manifest", only_case.unwrap_or("?")));
|
||||
}
|
||||
println!("RUN-TREE {tree} cases={done}");
|
||||
Ok(ExitCode::SUCCESS)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ compare driver
|
||||
|
||||
/// Linux: is the SMT sibling of `cpu` idle (below 5 percent busy over 200 ms)? No sibling counts as idle. Elsewhere:
|
||||
/// false (unknown).
|
||||
/// Linux: is the SMT sibling of `cpu` idle (below 5 percent busy over 200 ms)? No sibling counts as idle. Elsewhere: false (unknown).
|
||||
pub(super) fn sibling_idle(cpu: usize) -> bool {
|
||||
if !cfg!(target_os = "linux") {
|
||||
return false;
|
||||
}
|
||||
let Some(siblings) = sibling_cpus(cpu) else { return false };
|
||||
if siblings.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let before: Vec<_> = siblings.iter().map(|s| jiffies_total_idle(*s)).collect();
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
siblings.iter().zip(before).all(|(s, b)| stayed_idle(b, jiffies_total_idle(*s)))
|
||||
}
|
||||
|
||||
/// The other logical CPUs of the core of `cpu` from sysfs; None when the list cannot be read or parsed.
|
||||
fn sibling_cpus(cpu: usize) -> Option<Vec<usize>> {
|
||||
let list = fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")).ok()?;
|
||||
let Ok(list) = fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")) else {
|
||||
return false;
|
||||
};
|
||||
let mut siblings = Vec::new();
|
||||
for part in list.trim().split(',') {
|
||||
let (a, b) = part.split_once('-').unwrap_or((part, part));
|
||||
let (Ok(a), Ok(b)) = (a.trim().parse::<usize>(), b.trim().parse::<usize>()) else { return None };
|
||||
let (Ok(a), Ok(b)) = (a.trim().parse::<usize>(), b.trim().parse::<usize>()) else { return false };
|
||||
siblings.extend((a..=b).filter(|s| *s != cpu));
|
||||
}
|
||||
Some(siblings)
|
||||
}
|
||||
|
||||
/// (total, idle) jiffies of one logical CPU from /proc/stat (Linux).
|
||||
fn jiffies_total_idle(cpu: usize) -> Option<(u64, u64)> {
|
||||
let stat = fs::read_to_string("/proc/stat").ok()?;
|
||||
let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?;
|
||||
let f: Vec<u64> = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect();
|
||||
let idle = f.get(3)? + f.get(4).copied().unwrap_or(0);
|
||||
Some((f.iter().sum(), idle))
|
||||
}
|
||||
|
||||
/// The CPU was below 5 percent busy between the two samples; a missing sample or no elapsed time is not idle.
|
||||
fn stayed_idle(before: Option<(u64, u64)>, after: Option<(u64, u64)>) -> bool {
|
||||
match (before, after) {
|
||||
if siblings.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let sample = |cpu: usize| -> Option<(u64, u64)> {
|
||||
let stat = fs::read_to_string("/proc/stat").ok()?;
|
||||
let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?;
|
||||
let f: Vec<u64> = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect();
|
||||
let idle = f.get(3)? + f.get(4).copied().unwrap_or(0);
|
||||
Some((f.iter().sum(), idle))
|
||||
};
|
||||
let before: Vec<_> = siblings.iter().map(|s| sample(*s)).collect();
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
siblings.iter().zip(before).all(|(s, b)| match (b, sample(*s)) {
|
||||
(Some(b), Some(a)) => {
|
||||
let total = a.0.saturating_sub(b.0);
|
||||
let idle = a.1.saturating_sub(b.1);
|
||||
total > 0 && (total - idle.min(total)) * 20 < total
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn rustc_info() -> (String, String) {
|
||||
// $RUSTC, then `rustc` on the PATH, then the rustup shim of the user (a non-login shell has no cargo bin directory
|
||||
// on its PATH)
|
||||
// $RUSTC, then `rustc` on the PATH, then the rustup shim of the user (a non-login shell has no cargo bin directory on its PATH)
|
||||
let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default();
|
||||
let shim = format!("{home}/.cargo/bin/{}", if cfg!(windows) { "rustc.exe" } else { "rustc" });
|
||||
let candidates = [std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()), "rustc".to_owned(), shim];
|
||||
@@ -202,33 +174,19 @@ pub(super) fn parse_options(args: &[String]) -> Result<Options, String> {
|
||||
};
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
if !takes_value(a) {
|
||||
return Err(format!("unknown option {a}"));
|
||||
let mut value = |what: &str| it.next().cloned().ok_or_else(|| format!("{what} needs a value"));
|
||||
match a.as_str() {
|
||||
"--out" => o.out = Some(PathBuf::from(value("--out")?)),
|
||||
"--pin" => o.pin = value("--pin")?.parse().map_err(|_| "--pin takes a logical CPU number".to_owned())?,
|
||||
"--machine-role" => o.machine_role = Some(value("--machine-role")?),
|
||||
"--trees" => o.trees = value("--trees")?.split(',').map(str::to_owned).collect(),
|
||||
"--tree" => o.tree = Some(value("--tree")?),
|
||||
"--case" => o.case = Some(value("--case")?),
|
||||
other => return Err(format!("unknown option {other}")),
|
||||
}
|
||||
let value = it.next().cloned().ok_or_else(|| format!("{a} needs a value"))?;
|
||||
set_option(&mut o, a, value)?;
|
||||
}
|
||||
if let Some(bad) = o.trees.iter().find(|t| !TREES.contains(&t.as_str())) {
|
||||
return Err(format!("unknown tree {bad} (avx512 | avx2)"));
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// The options of `compare` / `run-tree` that carry a value.
|
||||
fn takes_value(flag: &str) -> bool {
|
||||
matches!(flag, "--out" | "--pin" | "--machine-role" | "--trees" | "--tree" | "--case")
|
||||
}
|
||||
|
||||
/// Stores the value of one option that takes a value (see `takes_value`).
|
||||
fn set_option(o: &mut Options, flag: &str, value: String) -> Result<(), String> {
|
||||
match flag {
|
||||
"--out" => o.out = Some(PathBuf::from(value)),
|
||||
"--pin" => o.pin = value.parse().map_err(|_| "--pin takes a logical CPU number".to_owned())?,
|
||||
"--machine-role" => o.machine_role = Some(value),
|
||||
"--trees" => o.trees = value.split(',').map(str::to_owned).collect(),
|
||||
"--tree" => o.tree = Some(value),
|
||||
"--case" => o.case = Some(value),
|
||||
other => return Err(format!("unknown option {other}")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
//! Start-up report of the CPUs the expert kernels run on and of the kernel family chosen for them (operator log only,
|
||||
//! no behaviour).
|
||||
//! Start-up report of the CPUs the expert kernels run on and of the kernel family chosen for them (operator log only, no behaviour).
|
||||
//!
|
||||
//! The kernel family (AVX-512 or AVX2) is decided once per process by `rust_simd::dispatch()`. This report probes every
|
||||
//! logical CPU the process may run on (a thread pinned to it, `cpuid`, `xgetbv`) and groups the identical ones, so a
|
||||
//! machine with several packages or with unlike cores shows each kind on its own line, and a core that cannot run the
|
||||
//! chosen family is named.
|
||||
//! The kernel family (AVX-512 or AVX2) is decided once per process by `rust_simd::dispatch()`. This report probes every logical CPU the
|
||||
//! process may run on (a thread pinned to it, `cpuid`, `xgetbv`) and groups the identical ones, so a machine with several packages or
|
||||
//! with unlike cores shows each kind on its own line, and a core that cannot run the chosen family is named.
|
||||
use core::arch::x86_64::{__cpuid, __cpuid_count, _xgetbv};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
@@ -16,13 +14,8 @@ struct Core {
|
||||
|
||||
const AVX512_NAMES: [&str; 6] = ["F", "BW", "VL", "DQ", "VBMI", "VNNI"];
|
||||
|
||||
/// The text of the 48 brand bytes of CPUID leaves 0x80000002..=0x80000004: NULs and blanks trimmed at both ends.
|
||||
fn brand_text(raw: &[u8]) -> String {
|
||||
String::from_utf8_lossy(raw).trim_matches(|c: char| c == '\0' || c.is_whitespace()).to_owned()
|
||||
}
|
||||
|
||||
/// The brand string of the CPU the calling thread runs on; empty when the CPU has no brand leaves.
|
||||
fn read_brand() -> String {
|
||||
/// The CPU brand string from the extended leaves (empty when the CPU has none).
|
||||
fn brand_string() -> String {
|
||||
if __cpuid(0x8000_0000).eax < 0x8000_0004 {
|
||||
return String::new();
|
||||
}
|
||||
@@ -33,41 +26,45 @@ fn read_brand() -> String {
|
||||
raw.extend_from_slice(&w.to_le_bytes());
|
||||
}
|
||||
}
|
||||
brand_text(&raw)
|
||||
String::from_utf8_lossy(&raw).trim_matches(|c: char| c == '\0' || c.is_whitespace()).to_owned()
|
||||
}
|
||||
|
||||
/// AVX2, FMA and F16C usable: the CPUID.1 ECX bits, the YMM state enabled in XCR0, the AVX2 bit of leaf 7.
|
||||
fn has_avx2(c1: u32, xcr0: u64, l7_ebx: u32) -> bool {
|
||||
[12, 27, 28, 29].iter().all(|b| c1 & (1 << b) != 0) && xcr0 & 6 == 6 && l7_ebx & (1 << 5) != 0
|
||||
}
|
||||
|
||||
/// F, BW, VL, DQ, VBMI, VNNI (in `AVX512_NAMES` order) present and the ZMM state enabled by the OS.
|
||||
fn avx512_flags(osxsave: bool, xcr0: u64, l7_ebx: u32, l7_ecx: u32) -> [bool; 6] {
|
||||
let os512 = osxsave && xcr0 & 0xe6 == 0xe6;
|
||||
let bits = [
|
||||
l7_ebx & (1 << 16) != 0,
|
||||
l7_ebx & (1 << 30) != 0,
|
||||
l7_ebx & (1 << 31) != 0,
|
||||
l7_ebx & (1 << 17) != 0,
|
||||
l7_ecx & (1 << 1) != 0,
|
||||
l7_ecx & (1 << 11) != 0,
|
||||
];
|
||||
bits.map(|b| b && os512)
|
||||
/// AVX2/FMA/F16C and the six AVX-512 subsets of the calling core (leaf 7 must exist).
|
||||
///
|
||||
/// # Safety
|
||||
/// CPUID is always available on x86_64; XGETBV only after the OSXSAVE bit is seen.
|
||||
unsafe fn feature_bits() -> (bool, [bool; 6]) {
|
||||
unsafe {
|
||||
let c1 = __cpuid(1).ecx;
|
||||
let osxsave = c1 & (1 << 27) != 0;
|
||||
let xcr0 = if osxsave { _xgetbv(0) } else { 0 };
|
||||
let l7 = __cpuid_count(7, 0);
|
||||
let avx2 = [12, 27, 28, 29].iter().all(|b| c1 & (1 << b) != 0) && xcr0 & 6 == 6 && l7.ebx & (1 << 5) != 0;
|
||||
let os512 = osxsave && xcr0 & 0xe6 == 0xe6;
|
||||
let bits = [
|
||||
l7.ebx & (1 << 16) != 0,
|
||||
l7.ebx & (1 << 30) != 0,
|
||||
l7.ebx & (1 << 31) != 0,
|
||||
l7.ebx & (1 << 17) != 0,
|
||||
l7.ecx & (1 << 1) != 0,
|
||||
l7.ecx & (1 << 11) != 0,
|
||||
];
|
||||
(avx2, bits.map(|b| b && os512))
|
||||
}
|
||||
}
|
||||
|
||||
/// The features of the core the calling thread runs on. The gates mirror `rust_simd::probe_avx2` / `probe_avx512`.
|
||||
fn probe() -> Core {
|
||||
let max = __cpuid(0).eax;
|
||||
let brand = read_brand();
|
||||
if max < 7 {
|
||||
return Core { brand, avx2: false, avx512: [false; 6] };
|
||||
// SAFETY: CPUID is always available on x86_64; XGETBV only after the OSXSAVE bit is seen.
|
||||
unsafe {
|
||||
let max = __cpuid(0).eax;
|
||||
let brand = brand_string();
|
||||
if max < 7 {
|
||||
return Core { brand, avx2: false, avx512: [false; 6] };
|
||||
}
|
||||
let (avx2, avx512) = feature_bits();
|
||||
Core { brand, avx2, avx512 }
|
||||
}
|
||||
let c1 = __cpuid(1).ecx;
|
||||
let osxsave = c1 & (1 << 27) != 0;
|
||||
// SAFETY: XGETBV only after the OSXSAVE bit is seen.
|
||||
let xcr0 = if osxsave { unsafe { _xgetbv(0) } } else { 0 };
|
||||
let l7 = __cpuid_count(7, 0);
|
||||
Core { brand, avx2: has_avx2(c1, xcr0, l7.ebx), avx512: avx512_flags(osxsave, xcr0, l7.ebx, l7.ecx) }
|
||||
}
|
||||
|
||||
fn avx512_complete(c: &Core) -> bool {
|
||||
@@ -92,39 +89,30 @@ fn ranges(cpus: &[usize]) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// A pinned probe thread for logical CPU `cpu`; a refused pin probes wherever the thread runs (the line then shows
|
||||
/// that CPU kind). `None` when the probe thread panicked.
|
||||
fn probe_pinned(cpu: usize) -> Option<Core> {
|
||||
std::thread::spawn(move || {
|
||||
let previous = crate::rust_topology::pin_current_thread(cpu as i32);
|
||||
let core = probe();
|
||||
crate::rust_topology::restore_thread_affinity(previous);
|
||||
core
|
||||
})
|
||||
.join()
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Adds `cpu` to the group of identical cores `core` belongs to, or starts a new group.
|
||||
fn push_group(groups: &mut Vec<(Core, Vec<usize>)>, core: Core, cpu: usize) {
|
||||
match groups.iter_mut().find(|(g, _)| *g == core) {
|
||||
Some((_, cpus)) => cpus.push(cpu),
|
||||
None => groups.push((core, vec![cpu])),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every logical CPU the process may run on (at most 256), probed on its own thread and grouped by identical features.
|
||||
/// The logical CPUs the process may run on, grouped by identical probe result (first-seen order).
|
||||
fn probe_groups() -> Vec<(Core, Vec<usize>)> {
|
||||
let n = std::thread::available_parallelism().map_or(1, |n| n.get()).min(256);
|
||||
let mut groups: Vec<(Core, Vec<usize>)> = Vec::new();
|
||||
for cpu in 0..n {
|
||||
let Some(core) = probe_pinned(cpu) else { continue };
|
||||
push_group(&mut groups, core, cpu);
|
||||
// a pinned probe thread per logical CPU; a refused pin probes wherever the thread runs (the line then shows
|
||||
// that CPU's kind)
|
||||
let core = std::thread::spawn(move || {
|
||||
let previous = crate::rust_topology::pin_current_thread(cpu as i32);
|
||||
let core = probe();
|
||||
crate::rust_topology::restore_thread_affinity(previous);
|
||||
core
|
||||
})
|
||||
.join();
|
||||
let Ok(core) = core else { continue };
|
||||
match groups.iter_mut().find(|(g, _)| *g == core) {
|
||||
Some((_, cpus)) => cpus.push(cpu),
|
||||
None => groups.push((core, vec![cpu])),
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// The AVX-512 part of a core line: all of the six extensions, none, or which ones the core has and lacks.
|
||||
/// The AVX-512 part of a core line: all, none, or which subsets it has and lacks.
|
||||
fn avx512_summary(core: &Core) -> String {
|
||||
let have: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| *b).map(|(n, _)| *n).collect();
|
||||
let lacks: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| !*b).map(|(n, _)| *n).collect();
|
||||
@@ -137,18 +125,7 @@ fn avx512_summary(core: &Core) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The kernel family the core itself can run.
|
||||
fn core_family(core: &Core) -> &'static str {
|
||||
if avx512_complete(core) {
|
||||
"AVX-512"
|
||||
} else if core.avx2 {
|
||||
"AVX2"
|
||||
} else {
|
||||
"none (unsupported)"
|
||||
}
|
||||
}
|
||||
|
||||
/// The line of one group of identical logical CPUs.
|
||||
/// The report line of one group of identical logical CPUs.
|
||||
fn core_line(core: &Core, cpus: &[usize]) -> String {
|
||||
format!(
|
||||
"cpu: logical {} ({}): {}; AVX2/FMA/F16C: {}; {}; kernel family on this core: {}",
|
||||
@@ -157,23 +134,24 @@ fn core_line(core: &Core, cpus: &[usize]) -> String {
|
||||
if core.brand.is_empty() { "unknown model" } else { &core.brand },
|
||||
if core.avx2 { "yes" } else { "no" },
|
||||
avx512_summary(core),
|
||||
core_family(core)
|
||||
if avx512_complete(core) {
|
||||
"AVX-512"
|
||||
} else if core.avx2 {
|
||||
"AVX2"
|
||||
} else {
|
||||
"none (unsupported)"
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// The environment switches that change the kernel family, in the order they are reported.
|
||||
fn family_switches() -> Vec<&'static str> {
|
||||
/// The line with the kernel family the process chose and the environment switches that changed it.
|
||||
fn process_line(dispatch: &crate::rust_simd::Dispatch) -> String {
|
||||
let mut switches = Vec::new();
|
||||
for name in ["STRATA_FORCE_AVX2", "STRATA_NO_IQ512", "STRATA_NO_IQ256", "STRATA_NO_IQ4NL"] {
|
||||
if std::env::var_os(name).is_some() {
|
||||
switches.push(name);
|
||||
}
|
||||
}
|
||||
switches
|
||||
}
|
||||
|
||||
/// The line with the kernel family the process chose and the switches that changed it.
|
||||
fn process_line(dispatch: &crate::rust_simd::Dispatch, switches: &[&str]) -> String {
|
||||
format!(
|
||||
"cpu: process kernel family {} (IQ rows: 512-bit {}, 256-bit {}; IQ4_NL {}){}",
|
||||
if dispatch.avx512 { "AVX-512" } else { "AVX2" },
|
||||
@@ -184,27 +162,22 @@ fn process_line(dispatch: &crate::rust_simd::Dispatch, switches: &[&str]) -> Str
|
||||
)
|
||||
}
|
||||
|
||||
/// True when some group disagrees with the process family in a way that matters: the process uses AVX-512 and the
|
||||
/// group lacks it, or the group has all of it and the process does not use it.
|
||||
fn differs_in_avx512(groups: &[(Core, Vec<usize>)], dispatch: &crate::rust_simd::Dispatch) -> bool {
|
||||
groups.len() > 1
|
||||
&& groups.iter().any(|(c, _)| avx512_complete(c) != dispatch.avx512 && (dispatch.avx512 || avx512_complete(c)))
|
||||
}
|
||||
|
||||
const MIXED_AVX512_WARNING: &str = concat!(
|
||||
"cpu: WARNING: the logical CPUs differ in AVX-512 support but the kernel family is chosen once per process; ",
|
||||
"a worker pinned to a core without it would fault or be refused"
|
||||
);
|
||||
|
||||
/// One line per kind of logical CPU, then one line with the kernel family the process chose and the switches that
|
||||
/// changed it.
|
||||
/// One line per kind of logical CPU, then one line with the kernel family the process chose and the switches that changed it.
|
||||
pub fn cpu_kernel_report() -> Vec<String> {
|
||||
let groups = probe_groups();
|
||||
let mut lines: Vec<String> = groups.iter().map(|(core, cpus)| core_line(core, cpus)).collect();
|
||||
let dispatch = crate::rust_simd::dispatch();
|
||||
lines.push(process_line(dispatch, &family_switches()));
|
||||
if differs_in_avx512(&groups, dispatch) {
|
||||
lines.push(MIXED_AVX512_WARNING.to_owned());
|
||||
lines.push(process_line(dispatch));
|
||||
if groups.len() > 1
|
||||
&& groups.iter().any(|(c, _)| avx512_complete(c) != dispatch.avx512 && (dispatch.avx512 || avx512_complete(c)))
|
||||
{
|
||||
lines.push(
|
||||
concat!(
|
||||
"cpu: WARNING: the logical CPUs differ in AVX-512 support but the kernel family is chosen once per ",
|
||||
"process; a worker pinned to a core without it would fault or be refused"
|
||||
)
|
||||
.to_owned(),
|
||||
);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Moved out of the parent module by STRA-338: CpuPool, PendingBatch and their Drop impls.
|
||||
//! Moved out of the parent module by STRA-338: impl CpuPool, impl PendingBatch, impl Drop_for_PendingBatch, impl Drop_for_CpuPool.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The coordinator thread: creates the native pool, reports its worker count (or the error) to `startup`, then serves
|
||||
/// batches until the command channel closes.
|
||||
fn run_coordinator(
|
||||
/// The actor thread: build the native pool, report its worker count (or the failure), then serve batches until the
|
||||
/// command channel closes or a native failure closes the coordinator.
|
||||
fn actor_main(
|
||||
workers: i32,
|
||||
receive: mpsc::Receiver<Vec<PreparedJob>>,
|
||||
send_result: mpsc::SyncSender<Result<Vec<PreparedJob>>>,
|
||||
@@ -22,15 +22,14 @@ fn run_coordinator(
|
||||
if startup.send(native.workers()).is_err() {
|
||||
return;
|
||||
}
|
||||
serve_batches(native, &receive, &send_result);
|
||||
serve(native, receive, send_result);
|
||||
}
|
||||
|
||||
/// Computes every received batch and sends it back, until the actor closes the channel, drops the result channel, or a
|
||||
/// native failure closes the coordinator for good.
|
||||
fn serve_batches(
|
||||
/// Compute received batches until the command channel closes, the result channel closes or a native failure closes the
|
||||
/// coordinator forever.
|
||||
fn serve(
|
||||
mut native: ffi::NativePool,
|
||||
receive: &mpsc::Receiver<Vec<PreparedJob>>,
|
||||
send_result: &mpsc::SyncSender<Result<Vec<PreparedJob>>>,
|
||||
receive: mpsc::Receiver<Vec<PreparedJob>>,
|
||||
send_result: mpsc::SyncSender<Result<Vec<PreparedJob>>>,
|
||||
) {
|
||||
while let Ok(mut jobs) = receive.recv() {
|
||||
let result = native.compute_batch(&mut jobs);
|
||||
@@ -50,35 +49,6 @@ fn serve_batches(
|
||||
}
|
||||
// NativePool is destroyed here; original destructor joins all workers.
|
||||
}
|
||||
|
||||
/// The result vector of a batch of `jobs` once the jobs are admitted: 1..=MAX_JOBS jobs in a vector of at most that
|
||||
/// capacity, within `allowance` and the batch ceiling. `Shape`, `BudgetExceeded` or `Allocation` otherwise.
|
||||
fn admit_batch(jobs: &Vec<PreparedJob>, allowance: usize) -> Result<Vec<CompletedJob>> {
|
||||
if !(1..=MAX_JOBS).contains(&jobs.len()) || jobs.capacity() > MAX_JOBS {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
if allowance > MAX_BATCH_BYTES {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
let mut results = Vec::new();
|
||||
results.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?;
|
||||
if batch_charge(jobs, &results)? > allowance {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// The bytes a batch is charged: the metadata of the job and result vectors plus the bytes every job owns.
|
||||
fn batch_charge(jobs: &Vec<PreparedJob>, results: &Vec<CompletedJob>) -> Result<usize> {
|
||||
let results_bytes = results.capacity().checked_mul(std::mem::size_of::<CompletedJob>());
|
||||
let metadata = jobs
|
||||
.capacity()
|
||||
.checked_mul(std::mem::size_of::<PreparedJob>())
|
||||
.and_then(|n| results_bytes.and_then(|m| n.checked_add(m)))
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
jobs.iter().try_fold(metadata, |bytes, job| bytes.checked_add(job.owned_bytes()?).ok_or(Error::BudgetExceeded))
|
||||
}
|
||||
|
||||
impl CpuPool {
|
||||
pub fn new(workers: i32) -> Result<Self> {
|
||||
let (command, receive) = mpsc::sync_channel::<Vec<PreparedJob>>(1);
|
||||
@@ -87,7 +57,7 @@ impl CpuPool {
|
||||
let worker = thread::Builder::new()
|
||||
.name("leleka-cpu-miss".into())
|
||||
.stack_size(2 * 1024 * 1024)
|
||||
.spawn(move || run_coordinator(workers, receive, send_result, startup))
|
||||
.spawn(move || actor_main(workers, receive, send_result, startup))
|
||||
.map_err(|_| Error::Allocation)?;
|
||||
match initialized.recv().unwrap_or(Err(Error::NativeFailure)) {
|
||||
Ok(workers) => Ok(Self {
|
||||
@@ -109,11 +79,34 @@ impl CpuPool {
|
||||
pub fn workers(&self) -> usize {
|
||||
self.workers
|
||||
}
|
||||
pub fn start(&mut self, jobs: Vec<PreparedJob>, allowance: usize) -> Result<PendingBatch<'_>> {
|
||||
/// Bytes a batch is charged: the job and result vectors' capacity plus every job's owned bytes.
|
||||
fn charged_bytes(jobs: &[PreparedJob], (jobs_cap, results_cap): (usize, usize)) -> Result<usize> {
|
||||
let metadata = jobs_cap
|
||||
.checked_mul(std::mem::size_of::<PreparedJob>())
|
||||
.and_then(|n| results_cap.checked_mul(std::mem::size_of::<CompletedJob>()).and_then(|m| n.checked_add(m)))
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
jobs.iter().try_fold(metadata, |bytes, job| bytes.checked_add(job.owned_bytes()?).ok_or(Error::BudgetExceeded))
|
||||
}
|
||||
/// The pool is open and idle, and the batch has an admissible size and byte allowance.
|
||||
fn admit(&self, jobs: &Vec<PreparedJob>, allowance: usize) -> Result<()> {
|
||||
if self.failed || self.in_flight {
|
||||
return Err(Error::Closed);
|
||||
}
|
||||
let results = admit_batch(&jobs, allowance)?;
|
||||
if !(1..=MAX_JOBS).contains(&jobs.len()) || jobs.capacity() > MAX_JOBS {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
if allowance > MAX_BATCH_BYTES {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn start(&mut self, jobs: Vec<PreparedJob>, allowance: usize) -> Result<PendingBatch<'_>> {
|
||||
self.admit(&jobs, allowance)?;
|
||||
let mut results = Vec::new();
|
||||
results.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?;
|
||||
if Self::charged_bytes(&jobs, (jobs.capacity(), results.capacity()))? > allowance {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
if self.command.as_ref().ok_or(Error::Closed)?.send(jobs).is_err() {
|
||||
self.failed = true;
|
||||
return Err(Error::Closed);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Moved out of the parent module by STRA-338: the format tables, PreparedJob, DirectCpuPool and CompletedJob.
|
||||
//! Moved out of the parent module by STRA-338: impl GateUpFormat, impl DownFormat, impl PreparedJob, impl DirectCpuPool, impl Drop_for_DirectCpuPool, impl CompletedJob.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -15,6 +15,11 @@ impl GateUpFormat {
|
||||
Self::Iq2Xs => 17,
|
||||
}
|
||||
}
|
||||
/// Bytes of one gate or up matrix (`FF` rows of `H` weights) and the bytes per block.
|
||||
pub(super) fn matrix_bytes(self) -> (usize, usize) {
|
||||
let (q, b) = self.block();
|
||||
(H / q * b * FF, b)
|
||||
}
|
||||
pub(super) fn block(self) -> (usize, usize) {
|
||||
match self {
|
||||
Self::Iq3Xxs => (256, 98),
|
||||
@@ -34,6 +39,11 @@ impl DownFormat {
|
||||
Self::Q2_0 => 42,
|
||||
}
|
||||
}
|
||||
/// Bytes of the down matrix (`H` rows of `FF` weights) and the bytes per block.
|
||||
pub(super) fn matrix_bytes(self) -> (usize, usize) {
|
||||
let (q, b) = self.block();
|
||||
(FF / q * b * H, b)
|
||||
}
|
||||
pub(super) fn block(self) -> (usize, usize) {
|
||||
match self {
|
||||
Self::Iq4Nl => (32, 18),
|
||||
@@ -41,42 +51,8 @@ impl DownFormat {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `NonFinite` when any block of the three role matrices starts with an FP16 header that is Inf or NaN.
|
||||
///
|
||||
/// Every admitted family has one FP16 header at each original block start. Integer multipliers are bounded; this is a
|
||||
/// guard, never a source proof.
|
||||
fn validate_headers(roles: [(&[u8], usize); 3]) -> Result<()> {
|
||||
for (bytes, block) in roles {
|
||||
for at in (0..bytes.len()).step_by(block) {
|
||||
if u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00 {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The complete native G|U|D owner: the three role matrices copied one after the other into one fallible allocation.
|
||||
fn join_blob(gate: &[u8], up: &[u8], down: &[u8], gsize: usize, dsize: usize) -> Result<Box<[u8]>> {
|
||||
let size = gsize.checked_mul(2).and_then(|n| n.checked_add(dsize)).ok_or(Error::Shape)?;
|
||||
let mut blob = Vec::new();
|
||||
blob.try_reserve_exact(size).map_err(|_| Error::Allocation)?;
|
||||
blob.extend_from_slice(gate);
|
||||
blob.extend_from_slice(up);
|
||||
blob.extend_from_slice(down);
|
||||
Ok(blob.into_boxed_slice())
|
||||
}
|
||||
|
||||
/// `rows * H` zeroed output floats in one fallible allocation.
|
||||
fn zeroed_output(rows: usize) -> Result<Box<[f32]>> {
|
||||
let mut output = Vec::new();
|
||||
output.try_reserve_exact(rows * H).map_err(|_| Error::Allocation)?;
|
||||
output.resize(rows * H, 0.0);
|
||||
Ok(output.into_boxed_slice())
|
||||
}
|
||||
|
||||
/// The rows and the input of a job: 1..=MAX_ROWS rows of `H` finite floats.
|
||||
fn validate_input(input: &[f32], rows: usize) -> Result<()> {
|
||||
/// Row count in range, one `H`-float input row per job row, every input finite.
|
||||
fn check_job_input(rows: usize, input: &[f32]) -> Result<()> {
|
||||
if !(1..=MAX_ROWS).contains(&rows) || input.len() != rows * H {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
@@ -85,14 +61,41 @@ fn validate_input(input: &[f32], rows: usize) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The block (values, bytes) of the gate/up and down formats and the byte sizes of one gate/up and the down matrix.
|
||||
fn matrix_sizes(gu: GateUpFormat, down: DownFormat) -> ((usize, usize), (usize, usize), usize, usize) {
|
||||
let (gq, gb) = gu.block();
|
||||
let (dq, db) = down.block();
|
||||
((gq, gb), (dq, db), H / gq * gb * FF, FF / dq * db * H)
|
||||
// Every admitted family has one FP16 header at each original block start.
|
||||
// Integer multipliers are bounded; this is a guard, never a source proof.
|
||||
fn check_fp16_headers(parts: [(&[u8], usize); 3]) -> Result<()> {
|
||||
for (bytes, block) in parts {
|
||||
for at in (0..bytes.len()).step_by(block) {
|
||||
if u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00 {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The gate/up and down matrices concatenated into one immutable G|U|D owner; the role owners are dropped before
|
||||
/// the caller allocates its output.
|
||||
fn concat_blob(gate: Box<[u8]>, up: Box<[u8]>, down: Box<[u8]>, (gsize, dsize): (usize, usize)) -> Result<Box<[u8]>> {
|
||||
let size = gsize.checked_mul(2).and_then(|n| n.checked_add(dsize)).ok_or(Error::Shape)?;
|
||||
let mut blob = Vec::new();
|
||||
blob.try_reserve_exact(size).map_err(|_| Error::Allocation)?;
|
||||
blob.extend_from_slice(&gate);
|
||||
blob.extend_from_slice(&up);
|
||||
blob.extend_from_slice(&down);
|
||||
// Drop original role owners before output allocation; all numerical
|
||||
// consumers will use this immutable complete native G|U|D owner.
|
||||
drop(gate);
|
||||
drop(up);
|
||||
drop(down);
|
||||
Ok(blob.into_boxed_slice())
|
||||
}
|
||||
/// `len` zeroed output floats.
|
||||
fn zeroed_output(len: usize) -> Result<Box<[f32]>> {
|
||||
let mut output = Vec::new();
|
||||
output.try_reserve_exact(len).map_err(|_| Error::Allocation)?;
|
||||
output.resize(len, 0.0);
|
||||
Ok(output.into_boxed_slice())
|
||||
}
|
||||
|
||||
impl PreparedJob {
|
||||
pub fn new(
|
||||
gu: GateUpFormat,
|
||||
@@ -103,19 +106,15 @@ impl PreparedJob {
|
||||
input: Box<[f32]>,
|
||||
rows: usize,
|
||||
) -> Result<Self> {
|
||||
validate_input(&input, rows)?;
|
||||
let ((_, gb), (_, db), gsize, dsize) = matrix_sizes(gu, down);
|
||||
check_job_input(rows, &input)?;
|
||||
let (gsize, gb) = gu.matrix_bytes();
|
||||
let (dsize, db) = down.matrix_bytes();
|
||||
if gate.len() != gsize || up.len() != gsize || down_bytes.len() != dsize {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
validate_headers([(&gate[..], gb), (&up[..], gb), (&down_bytes[..], db)])?;
|
||||
let blob = join_blob(&gate, &up, &down_bytes, gsize, dsize)?;
|
||||
// Drop original role owners before output allocation; all numerical
|
||||
// consumers will use this immutable complete native G|U|D owner.
|
||||
drop(gate);
|
||||
drop(up);
|
||||
drop(down_bytes);
|
||||
let output = zeroed_output(rows)?;
|
||||
check_fp16_headers([(&gate, gb), (&up, gb), (&down_bytes, db)])?;
|
||||
let blob = concat_blob(gate, up, down_bytes, (gsize, dsize))?;
|
||||
let output = zeroed_output(rows * H)?;
|
||||
Ok(Self { gu, down, gate_bytes: gsize, up_bytes: gsize, down_bytes: dsize, rows, blob, input, output })
|
||||
}
|
||||
pub fn owned_bytes(&self) -> Result<usize> {
|
||||
@@ -147,8 +146,7 @@ impl DirectCpuPool {
|
||||
pub fn workers(&self) -> usize {
|
||||
self.workers
|
||||
}
|
||||
/// `LELEKA_POOL_TIMING=1`: the host stage times of `compute_group` summed since the last call, in ms (see
|
||||
/// `POOL_TIMING_STAGES`).
|
||||
/// `LELEKA_POOL_TIMING=1`: the host's stage times of `compute_group` summed since the last call, in ms (see `POOL_TIMING_STAGES`).
|
||||
pub fn take_timing(&mut self) -> Option<[f64; POOL_TIMING_STAGES]> {
|
||||
self.native.take_timing()
|
||||
}
|
||||
|
||||
@@ -1,21 +1,16 @@
|
||||
//! How many CPU expert workers to start by default (docs/upstream-port-plan.md row 2.3; upstream `pool_plan.hpp`,
|
||||
//! commit `5ece068f`).
|
||||
//! How many CPU expert workers to start by default (docs/upstream-port-plan.md row 2.3; upstream `pool_plan.hpp`, commit `5ece068f`).
|
||||
//!
|
||||
//! Pure arithmetic on a CPU description, unit tested on mock CPUs. The plan is opt-in (`LELEKA_CPU_POOL_PLAN=on`): the
|
||||
//! default of the stack stays the Original's 15 until the plan has a paired A/B on the machine it changes. On the
|
||||
//! 16-core 9950X3D of the server the plan gives 15 as well.
|
||||
//! Pure arithmetic on a CPU description, unit tested on mock CPUs. The plan is opt-in (`LELEKA_CPU_POOL_PLAN=on`): the stack's default stays the
|
||||
//! Original's 15 until the plan has a paired A/B on the machine it changes. On the 16-core 9950X3D of the server the plan gives 15 as well.
|
||||
//!
|
||||
//! Why a plan and not "every physical core but the host's": the workers of the pool spin while they wait, so a worker
|
||||
//! without a core of its own takes cycles from one that has one (a bigger count is slower, not just useless); the
|
||||
//! kernel is DRAM-bound, past the width of the memory system more cores add nothing and the barrier at the end of
|
||||
//! every layer waits for more threads; a container limited by a CFS quota still shows every core of the machine. The
|
||||
//! pool refuses more than 15 workers (`NativePool::new`), so the count handed to the pool is also capped at
|
||||
//! [`POOL_MAX_WORKERS`].
|
||||
//! Why a plan and not "every physical core but the host's": the pool's workers spin while they wait, so a worker without a core of its own takes
|
||||
//! cycles from one that has one (a bigger count is slower, not just useless); the kernel is DRAM-bound, past the memory system's width more cores
|
||||
//! add nothing and the barrier at the end of every layer waits for more threads; a container limited by a CFS quota still shows every core of the
|
||||
//! machine. The pool refuses more than 15 workers (`NativePool::new`), so the count handed to the pool is also capped at [`POOL_MAX_WORKERS`].
|
||||
|
||||
/// The pool's own ceiling (`NativePool::new` refuses more).
|
||||
pub const POOL_MAX_WORKERS: usize = 15;
|
||||
/// Upstream measured cap of a default count (`kPoolWorkersCap`); above the ceiling of the pool here, kept so the
|
||||
/// mock-CPU tests match upstream.
|
||||
/// Upstream's measured cap of a default count (`kPoolWorkersCap`); above the pool's ceiling here, kept so the mock-CPU tests match upstream's.
|
||||
pub const WORKERS_CAP: usize = 32;
|
||||
/// A CPU with at least this many workers keeps [`RESERVE`] cores free for the engine's other threads.
|
||||
pub const RESERVE_FROM: usize = 16;
|
||||
@@ -26,8 +21,7 @@ pub const RESERVE: usize = 1;
|
||||
pub struct PoolPlanInput {
|
||||
/// Logical processors this process may run on.
|
||||
pub logical: usize,
|
||||
/// Physical cores this process may use per CPU package, the package of the host thread first (its own core is
|
||||
/// counted); empty = unknown.
|
||||
/// Physical cores this process may use per CPU package, the host thread's package first (its own core is counted); empty = unknown.
|
||||
pub cores_per_package: Vec<usize>,
|
||||
/// CPUs a container quota allows (cgroup `cpu.max`); 0 = no quota.
|
||||
pub cpu_quota: f64,
|
||||
@@ -49,90 +43,75 @@ pub struct PoolPlan {
|
||||
pub limit: &'static str,
|
||||
}
|
||||
|
||||
/// The core layout the plan counts: physical cores (all packages and the host package), packages, and whether the OS
|
||||
/// said which logical processors share a core.
|
||||
struct Layout {
|
||||
cores: usize,
|
||||
local: usize,
|
||||
packages: usize,
|
||||
known: bool,
|
||||
}
|
||||
|
||||
/// The worker count so far and what bounded it (for the start-up line).
|
||||
/// A worker count and what bounded it.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Bound {
|
||||
n: usize,
|
||||
limit: &'static str,
|
||||
}
|
||||
|
||||
impl Bound {
|
||||
/// The bound lowered to `candidate` (named `limit`) when that is below the count so far, else unchanged.
|
||||
fn lowered_to(self, candidate: usize, limit: &'static str) -> Self {
|
||||
if candidate < self.n { Self { n: candidate, limit } } else { self }
|
||||
}
|
||||
}
|
||||
|
||||
fn read_layout(input: &PoolPlanInput) -> Layout {
|
||||
let cores: usize = input.cores_per_package.iter().sum();
|
||||
let local = input.cores_per_package.first().copied().unwrap_or(0);
|
||||
/// Physical cores counted, those of the host's package, the package count and whether the layout was known.
|
||||
fn core_layout(input: &PoolPlanInput) -> (usize, usize, usize, bool) {
|
||||
let mut cores: usize = input.cores_per_package.iter().sum();
|
||||
let mut local = input.cores_per_package.first().copied().unwrap_or(0);
|
||||
let packages = input.cores_per_package.len().max(1);
|
||||
let known = !input.cores_per_package.is_empty() && cores > 0;
|
||||
if known {
|
||||
return Layout { cores, local, packages, known };
|
||||
if !known {
|
||||
// The OS did not say which logical processors share a core: counting every one as a core is what put a
|
||||
// 256-thread machine at 255 workers.
|
||||
cores = if input.logical >= 16 { input.logical / 2 } else { input.logical };
|
||||
local = cores;
|
||||
}
|
||||
// The OS did not say which logical processors share a core: counting every one as a core is what put a 256-thread
|
||||
// machine at 255 workers.
|
||||
let cores = if input.logical >= 16 { input.logical / 2 } else { input.logical };
|
||||
Layout { cores, local: cores, packages, known }
|
||||
(cores, local, packages, known)
|
||||
}
|
||||
|
||||
/// Every physical core but the host first (the host thread has the first core), bounded by the socket of the host.
|
||||
fn host_bound(layout: &Layout) -> Bound {
|
||||
let n = layout.local.saturating_sub(1).max(1);
|
||||
let limit = if !layout.known {
|
||||
"half the logical processors (the OS gave no core layout)"
|
||||
} else if layout.packages > 1 {
|
||||
"the host's CPU socket"
|
||||
} else {
|
||||
"every physical core but the host's"
|
||||
};
|
||||
/// Every physical core of the host's package but the host's, minus the reserve on a big CPU.
|
||||
fn base_bound(local: usize, packages: usize, known: bool) -> Bound {
|
||||
let mut limit = "every physical core but the host's";
|
||||
let mut n = local.saturating_sub(1).max(1); // the host thread has the first core
|
||||
if !known {
|
||||
limit = "half the logical processors (the OS gave no core layout)";
|
||||
} else if packages > 1 {
|
||||
limit = "the host's CPU socket";
|
||||
}
|
||||
if n >= RESERVE_FROM {
|
||||
n -= RESERVE;
|
||||
if known && packages == 1 {
|
||||
limit = "physical cores, one kept free";
|
||||
}
|
||||
}
|
||||
Bound { n, limit }
|
||||
}
|
||||
|
||||
/// A CPU with at least `RESERVE_FROM` workers keeps `RESERVE` cores free for the other threads of the engine.
|
||||
fn keep_cores_free(bound: Bound, layout: &Layout) -> Bound {
|
||||
if bound.n < RESERVE_FROM {
|
||||
return bound;
|
||||
}
|
||||
let limit = if layout.known && layout.packages == 1 { "physical cores, one kept free" } else { bound.limit };
|
||||
Bound { n: bound.n - RESERVE, limit }
|
||||
}
|
||||
|
||||
/// A hybrid CPU with more E-cores than P-cores: the P-cores but the host's plus half of the E-cores.
|
||||
fn hybrid_workers(input: &PoolPlanInput) -> Option<usize> {
|
||||
(input.p_cores > 0 && input.e_cores > input.p_cores).then(|| (input.p_cores - 1 + input.e_cores / 2).max(1))
|
||||
fn cap_hybrid(input: &PoolPlanInput, b: Bound) -> Bound {
|
||||
if input.p_cores > 0 && input.e_cores > input.p_cores {
|
||||
let h = (input.p_cores - 1 + input.e_cores / 2).max(1);
|
||||
if h < b.n {
|
||||
return Bound { n: h, limit: "the performance cores and half of the efficiency cores" };
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The CPUs a container quota allows, less the host, at least one.
|
||||
fn quota_workers(input: &PoolPlanInput) -> Option<usize> {
|
||||
(input.cpu_quota > 0.0).then(|| ((input.cpu_quota as usize).saturating_sub(1)).max(1))
|
||||
/// A container CPU quota below the count.
|
||||
fn cap_quota(input: &PoolPlanInput, b: Bound) -> Bound {
|
||||
if input.cpu_quota > 0.0 {
|
||||
let q = ((input.cpu_quota as usize).saturating_sub(1)).max(1);
|
||||
if q < b.n {
|
||||
return Bound { n: q, limit: "the container's CPU quota" };
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
pub fn plan_pool_workers(input: &PoolPlanInput) -> PoolPlan {
|
||||
let layout = read_layout(input);
|
||||
let bound = keep_cores_free(host_bound(&layout), &layout);
|
||||
let bound = hybrid_workers(input)
|
||||
.map_or(bound, |h| bound.lowered_to(h, "the performance cores and half of the efficiency cores"));
|
||||
let bound = quota_workers(input).map_or(bound, |q| bound.lowered_to(q, "the container's CPU quota"));
|
||||
let bound = bound.lowered_to(WORKERS_CAP, "the measured cap");
|
||||
PoolPlan {
|
||||
workers: bound.n.max(1),
|
||||
cores: layout.cores,
|
||||
cores_local: layout.local,
|
||||
packages: layout.packages,
|
||||
topology_known: layout.known,
|
||||
limit: bound.limit,
|
||||
let (cores, local, packages, known) = core_layout(input);
|
||||
let mut b = cap_quota(input, cap_hybrid(input, base_bound(local, packages, known)));
|
||||
if b.n > WORKERS_CAP {
|
||||
b = Bound { n: WORKERS_CAP, limit: "the measured cap" };
|
||||
}
|
||||
PoolPlan { workers: b.n.max(1), cores, cores_local: local, packages, topology_known: known, limit: b.limit }
|
||||
}
|
||||
|
||||
/// The CPU this process runs on, as far as this build can read it.
|
||||
|
||||
@@ -107,20 +107,6 @@ pub struct DequantizedExpert {
|
||||
pub up: Vec<f32>,
|
||||
pub down: Vec<f32>,
|
||||
}
|
||||
/// Dequantizes `rows` rows of `width` values of one role; its blob rows start at `offset`, `stride` bytes apart.
|
||||
fn dequantize_role(
|
||||
kind: Kind,
|
||||
blob: &[u8],
|
||||
(offset, stride): (usize, usize),
|
||||
(rows, width): (usize, usize),
|
||||
out: &mut [f32],
|
||||
) -> Result<()> {
|
||||
for r in 0..rows {
|
||||
let raw = &blob[offset + r * stride..offset + (r + 1) * stride];
|
||||
super::rust_dequant::dequantize(kind, raw, &mut out[r * width..(r + 1) * width])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn dequantize_expert(f: &NativeFormat, blob: &[u8]) -> Result<DequantizedExpert> {
|
||||
f.validate()?;
|
||||
if blob.len() != f.bytes {
|
||||
@@ -130,29 +116,27 @@ pub fn dequantize_expert(f: &NativeFormat, blob: &[u8]) -> Result<DequantizedExp
|
||||
let mut gate = zeros(n)?;
|
||||
let mut up = zeros(n)?;
|
||||
let mut down = zeros(n)?;
|
||||
let gu_shape = (f.n_ff, f.n_embd);
|
||||
dequantize_role(f.gu, blob, (0, f.gu_row), gu_shape, &mut gate)?;
|
||||
dequantize_role(f.gu, blob, (f.up_offset, f.gu_row), gu_shape, &mut up)?;
|
||||
dequantize_role(f.down, blob, (f.down_offset, f.down_row), (f.n_embd, f.n_ff), &mut down)?;
|
||||
for r in 0..f.n_ff {
|
||||
super::rust_dequant::dequantize(
|
||||
f.gu,
|
||||
&blob[r * f.gu_row..(r + 1) * f.gu_row],
|
||||
&mut gate[r * f.n_embd..(r + 1) * f.n_embd],
|
||||
)?;
|
||||
super::rust_dequant::dequantize(
|
||||
f.gu,
|
||||
&blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row],
|
||||
&mut up[r * f.n_embd..(r + 1) * f.n_embd],
|
||||
)?;
|
||||
}
|
||||
for r in 0..f.n_embd {
|
||||
super::rust_dequant::dequantize(
|
||||
f.down,
|
||||
&blob[f.down_offset + r * f.down_row..f.down_offset + (r + 1) * f.down_row],
|
||||
&mut down[r * f.n_ff..(r + 1) * f.n_ff],
|
||||
)?;
|
||||
}
|
||||
Ok(DequantizedExpert { gate, up, down })
|
||||
}
|
||||
/// SiLU(gate row `r` . x) * (up row `r` . x), accumulated in f64.
|
||||
fn hidden_unit(w: &DequantizedExpert, n_embd: usize, r: usize, x: &[f32]) -> f32 {
|
||||
let (mut g, mut u) = (0.0f64, 0.0f64);
|
||||
for (i, &x) in x.iter().enumerate() {
|
||||
g += w.gate[r * n_embd + i] as f64 * x as f64;
|
||||
u += w.up[r * n_embd + i] as f64 * x as f64;
|
||||
}
|
||||
(g / (1.0 + (-g).exp()) * u) as f32
|
||||
}
|
||||
/// Down row `r` . hidden, accumulated in f64.
|
||||
fn down_unit(w: &DequantizedExpert, n_ff: usize, r: usize, hidden: &[f32]) -> f32 {
|
||||
let mut value = 0.0f64;
|
||||
for (i, &h) in hidden.iter().enumerate() {
|
||||
value += w.down[r * n_ff + i] as f64 * h as f64;
|
||||
}
|
||||
value as f32
|
||||
}
|
||||
pub fn float_oracle(f: &NativeFormat, blob: &[u8], input: &[f32]) -> Result<Vec<f32>> {
|
||||
f.validate()?;
|
||||
if input.is_empty() || input.len() % f.n_embd != 0 {
|
||||
@@ -163,35 +147,23 @@ pub fn float_oracle(f: &NativeFormat, blob: &[u8], input: &[f32]) -> Result<Vec<
|
||||
let mut hidden = zeros(f.n_ff)?;
|
||||
for (x, o) in input.chunks_exact(f.n_embd).zip(out.chunks_exact_mut(f.n_embd)) {
|
||||
for (r, h) in hidden.iter_mut().enumerate() {
|
||||
*h = hidden_unit(&w, f.n_embd, r, x);
|
||||
let (mut g, mut u) = (0.0f64, 0.0f64);
|
||||
for (i, &x) in x.iter().enumerate() {
|
||||
g += w.gate[r * f.n_embd + i] as f64 * x as f64;
|
||||
u += w.up[r * f.n_embd + i] as f64 * x as f64;
|
||||
}
|
||||
*h = (g / (1.0 + (-g).exp()) * u) as f32;
|
||||
}
|
||||
for (r, o) in o.iter_mut().enumerate() {
|
||||
*o = down_unit(&w, f.n_ff, r, &hidden);
|
||||
let mut value = 0.0f64;
|
||||
for (i, &h) in hidden.iter().enumerate() {
|
||||
value += w.down[r * f.n_ff + i] as f64 * h as f64;
|
||||
}
|
||||
*o = value as f32;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
/// `rows * cols` normal weights, each row scaled by a row-dependent factor.
|
||||
fn synthetic_weights(rows: usize, cols: usize, rng: &mut Mt19937, nd: &mut NormalFloat) -> Result<Vec<f32>> {
|
||||
let n = rows.checked_mul(cols).ok_or(Error::Shape)?;
|
||||
let mut w = zeros(n)?;
|
||||
for r in 0..rows {
|
||||
let scale = 0.02f32 * (0.5f32 + (r % 7) as f32 / 7.0f32);
|
||||
for c in 0..cols {
|
||||
w[r * cols + c] = scale * nd.next(rng);
|
||||
}
|
||||
}
|
||||
Ok(w)
|
||||
}
|
||||
/// The all-ones importance vector of the formats that need one.
|
||||
fn unit_imatrix(kind: Kind, cols: usize) -> Result<Option<Vec<f32>>> {
|
||||
if !super::rust_model_quant::requires_imatrix(kind) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut v = zeros(cols)?;
|
||||
v.fill(1.0);
|
||||
Ok(Some(v))
|
||||
}
|
||||
pub fn synthetic_blob(f: &NativeFormat, seed: u32) -> Result<Vec<u8>> {
|
||||
f.validate()?;
|
||||
let mut out = zeros(f.bytes)?;
|
||||
@@ -200,11 +172,31 @@ pub fn synthetic_blob(f: &NativeFormat, seed: u32) -> Result<Vec<u8>> {
|
||||
for (kind, rows, cols, offset) in
|
||||
[(f.gu, f.n_ff, f.n_embd, 0), (f.gu, f.n_ff, f.n_embd, f.up_offset), (f.down, f.n_embd, f.n_ff, f.down_offset)]
|
||||
{
|
||||
let w = synthetic_weights(rows, cols, &mut rng, &mut nd)?;
|
||||
let imatrix = unit_imatrix(kind, cols)?;
|
||||
let n = rows.checked_mul(cols).ok_or(Error::Shape)?;
|
||||
let mut w = zeros(n)?;
|
||||
for r in 0..rows {
|
||||
let scale = 0.02f32 * (0.5f32 + (r % 7) as f32 / 7.0f32);
|
||||
for c in 0..cols {
|
||||
w[r * cols + c] = scale * nd.next(&mut rng);
|
||||
}
|
||||
}
|
||||
let imatrix = if super::rust_model_quant::requires_imatrix(kind) {
|
||||
let mut v = zeros(cols)?;
|
||||
v.fill(1.0);
|
||||
Some(v)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let bytes = kind.row_bytes(cols)?.checked_mul(rows).ok_or(Error::Shape)?;
|
||||
let dst = &mut out[offset..offset + bytes];
|
||||
super::rust_model_quant::quantize_chunk(kind, &w, dst, 0, rows, cols, imatrix.as_deref())?;
|
||||
super::rust_model_quant::quantize_chunk(
|
||||
kind,
|
||||
&w,
|
||||
&mut out[offset..offset + bytes],
|
||||
0,
|
||||
rows,
|
||||
cols,
|
||||
imatrix.as_deref(),
|
||||
)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -77,12 +77,7 @@ const NAMES: [&str; 43] = [
|
||||
|
||||
#[repr(C, align(64))]
|
||||
struct Q81Owner([u8; 720]);
|
||||
const USAGE: &str = concat!(
|
||||
"usage: native_expert_parity <shard.gguf> [layer ...]\n",
|
||||
" native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n",
|
||||
" native_expert_parity --q5_1-min\n",
|
||||
" native_expert_parity --bf16-embd\n",
|
||||
);
|
||||
const USAGE: &str = "usage: native_expert_parity <shard.gguf> [layer ...]\n native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n native_expert_parity --q5_1-min\n native_expert_parity --bf16-embd\n";
|
||||
|
||||
mod numerical_fn;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -27,14 +27,13 @@ struct Mapping {
|
||||
impl Mapping {
|
||||
fn open(path: &str) -> Result<Self, String> {
|
||||
let file = File::open(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let len = file.metadata().map_err(|e| e.to_string())?.len();
|
||||
let bytes = usize::try_from(len).map_err(|_| "GGUF file too large")?;
|
||||
let bytes =
|
||||
usize::try_from(file.metadata().map_err(|e| e.to_string())?.len()).map_err(|_| "GGUF file too large")?;
|
||||
if bytes == 0 {
|
||||
return Err("empty GGUF file".into());
|
||||
}
|
||||
// Actual retained FD, PROT_READ | MAP_PRIVATE. No detached data handle.
|
||||
// SAFETY: a null hint, non-zero length and a live fd; the result is checked against MAP_FAILED before use and
|
||||
// unmapped in Drop.
|
||||
// SAFETY: a null hint, non-zero length and a live fd; the result is checked against MAP_FAILED before use and unmapped in Drop.
|
||||
#[cfg(unix)]
|
||||
let address = unsafe { mmap(std::ptr::null_mut(), bytes, 1, 2, file.as_raw_fd(), 0) };
|
||||
#[cfg(unix)]
|
||||
@@ -54,9 +53,9 @@ impl Mapping {
|
||||
};
|
||||
Ok(Self { file, address, bytes })
|
||||
}
|
||||
// SAFETY: `address`/`bytes` are the live PROT_READ mapping owned by `self` (unmapped only in Drop); the slice
|
||||
// borrows &self. Residual (benchmark-only offline loader): truncating the file underneath raises SIGBUS and a
|
||||
// concurrent writer is visible through the shared pages; stable_length() brackets the copies in Model::expert.
|
||||
// SAFETY: `address`/`bytes` are the live PROT_READ mapping owned by `self` (unmapped only in Drop); the slice borrows &self.
|
||||
// Residual (benchmark-only offline loader): truncating the file underneath raises SIGBUS and a concurrent writer is visible
|
||||
// through the shared pages; stable_length() brackets the copies in Model::expert.
|
||||
fn bytes(&self) -> &[u8] {
|
||||
unsafe { std::slice::from_raw_parts(self.address.cast(), self.bytes) }
|
||||
}
|
||||
@@ -111,49 +110,48 @@ impl<'a> Cursor<'a> {
|
||||
let n = usize::try_from(self.u64()?).map_err(|_| "GGUF string too large")?;
|
||||
copy(self.take(n)?)
|
||||
}
|
||||
/// Even kinds 0, 2, 4 are the unsigned 8/16/32-bit integers.
|
||||
fn unsigned_scalar(&mut self, kind: u32) -> Result<u64, String> {
|
||||
Ok(match kind {
|
||||
0 => self.u8()? as u64,
|
||||
2 => self.u16()? as u64,
|
||||
_ => self.u32()? as u64,
|
||||
})
|
||||
}
|
||||
/// Odd kinds 1, 3, 5 are the signed 8/16/32-bit integers, sign-extended.
|
||||
fn signed_scalar(&mut self, kind: u32) -> Result<u64, String> {
|
||||
Ok(match kind {
|
||||
1 => (self.u8()? as i8 as i64) as u64,
|
||||
3 => (self.u16()? as i16 as i64) as u64,
|
||||
_ => (self.u32()? as i32 as i64) as u64,
|
||||
})
|
||||
}
|
||||
/// Skips an array of `count` values of one element type; the value is 0.
|
||||
fn skip_array(&mut self, depth: u32) -> Result<u64, String> {
|
||||
let ty = self.u32()?;
|
||||
let count = self.u64()?;
|
||||
if count > 1 << 24 {
|
||||
return Err("GGUF array too large".into());
|
||||
}
|
||||
for _ in 0..count {
|
||||
self.value(ty, depth + 1)?;
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
fn value(&mut self, kind: u32, depth: u32) -> Result<u64, String> {
|
||||
if depth > 2 {
|
||||
return Err("GGUF nested array too deep".into());
|
||||
}
|
||||
match kind {
|
||||
0 | 2 | 4 => self.unsigned_scalar(kind),
|
||||
1 | 3 | 5 => self.signed_scalar(kind),
|
||||
6 => self.take(4).map(|_| 0),
|
||||
7 => self.u8().map(|v| u64::from(v != 0)),
|
||||
8 => self.string().map(|_| 0),
|
||||
9 => self.skip_array(depth),
|
||||
10 | 11 => self.u64(),
|
||||
12 => self.take(8).map(|_| 0),
|
||||
_ => Err("unknown GGUF metadata type".into()),
|
||||
}
|
||||
Ok(match kind {
|
||||
0 => self.u8()? as u64,
|
||||
1 => (self.u8()? as i8 as i64) as u64,
|
||||
2 => self.u16()? as u64,
|
||||
3 => (self.u16()? as i16 as i64) as u64,
|
||||
4 => self.u32()? as u64,
|
||||
5 => (self.u32()? as i32 as i64) as u64,
|
||||
6 => {
|
||||
self.take(4)?;
|
||||
0
|
||||
}
|
||||
7 => u64::from(self.u8()? != 0),
|
||||
8 => {
|
||||
self.string()?;
|
||||
0
|
||||
}
|
||||
9 => {
|
||||
if depth > 2 {
|
||||
return Err("GGUF nested array too deep".into());
|
||||
}
|
||||
let ty = self.u32()?;
|
||||
let count = self.u64()?;
|
||||
if count > 1 << 24 {
|
||||
return Err("GGUF array too large".into());
|
||||
}
|
||||
for _ in 0..count {
|
||||
self.value(ty, depth + 1)?;
|
||||
}
|
||||
0
|
||||
}
|
||||
10 => self.u64()?,
|
||||
11 => self.u64()?,
|
||||
12 => {
|
||||
self.take(8)?;
|
||||
0
|
||||
}
|
||||
_ => return Err("unknown GGUF metadata type".into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
fn copy(b: &[u8]) -> Result<Vec<u8>, String> {
|
||||
@@ -162,68 +160,6 @@ fn copy(b: &[u8]) -> Result<Vec<u8>, String> {
|
||||
v.extend_from_slice(b);
|
||||
Ok(v)
|
||||
}
|
||||
/// Checks the magic and version; returns the tensor count and the metadata entry count.
|
||||
fn read_header(c: &mut Cursor) -> Result<(usize, u64), String> {
|
||||
if c.u32()? != 0x46554747 || c.u32()? != 3 {
|
||||
return Err("GGUF magic/version mismatch".into());
|
||||
}
|
||||
let nt = usize::try_from(c.u64()?).map_err(|_| "GGUF tensor count")?;
|
||||
let nk = c.u64()?;
|
||||
Ok((nt, nk))
|
||||
}
|
||||
/// Reads the `nk` key/value entries; only the first value of a repeated key is kept.
|
||||
fn read_metadata(c: &mut Cursor, nk: u64) -> Result<HashMap<Vec<u8>, u64>, String> {
|
||||
let mut metadata = HashMap::new();
|
||||
for _ in 0..nk {
|
||||
let key = c.string()?;
|
||||
let ty = c.u32()?;
|
||||
let value = c.value(ty, 0)?;
|
||||
metadata.try_reserve(1).map_err(|_| "GGUF allocation")?;
|
||||
metadata.entry(key).or_insert(value);
|
||||
}
|
||||
Ok(metadata)
|
||||
}
|
||||
/// Reads one tensor header; its name must not be in `names` yet.
|
||||
fn read_tensor(c: &mut Cursor, names: &mut HashSet<Vec<u8>>) -> Result<Tensor, String> {
|
||||
let name = c.string()?;
|
||||
if !names.insert(copy(&name)?) {
|
||||
return Err("duplicate GGUF tensor".into());
|
||||
}
|
||||
let nd = c.u32()?;
|
||||
if !(1..=4).contains(&nd) {
|
||||
return Err("GGUF tensor dimension".into());
|
||||
}
|
||||
for _ in 0..nd {
|
||||
c.u64()?;
|
||||
}
|
||||
let kind = c.u32()?;
|
||||
let offset = c.u64()?;
|
||||
Ok(Tensor { name, kind, offset })
|
||||
}
|
||||
fn read_tensors(c: &mut Cursor, nt: usize) -> Result<Vec<Tensor>, String> {
|
||||
let mut tensors = Vec::new();
|
||||
let mut names = HashSet::new();
|
||||
tensors.try_reserve_exact(nt).map_err(|_| "GGUF allocation")?;
|
||||
names.try_reserve(nt).map_err(|_| "GGUF allocation")?;
|
||||
for _ in 0..nt {
|
||||
tensors.push(read_tensor(c, &mut names)?);
|
||||
}
|
||||
Ok(tensors)
|
||||
}
|
||||
/// The tensor data starts at the end of the tensor table rounded up to the declared alignment (default 32).
|
||||
fn data_start(table_end: usize, metadata: &HashMap<Vec<u8>, u64>, file_len: usize) -> Result<usize, String> {
|
||||
let alignment = metadata.get(b"general.alignment".as_slice()).copied().filter(|n| *n != 0).unwrap_or(32);
|
||||
let a = usize::try_from(alignment).map_err(|_| "GGUF alignment overflow")?;
|
||||
let start = table_end
|
||||
.checked_add(a - 1)
|
||||
.and_then(|n| n.checked_div(a))
|
||||
.and_then(|n| n.checked_mul(a))
|
||||
.ok_or("GGUF alignment overflow")?;
|
||||
if start > file_len {
|
||||
return Err("GGUF data start beyond file".into());
|
||||
}
|
||||
Ok(start)
|
||||
}
|
||||
struct Tensor {
|
||||
name: Vec<u8>,
|
||||
kind: u32,
|
||||
@@ -239,14 +175,53 @@ impl Shard {
|
||||
fn open(path: &str) -> Result<Self, String> {
|
||||
let map = Mapping::open(path)?;
|
||||
let mut c = Cursor { bytes: map.bytes(), at: 0 };
|
||||
let (nt, nk) = read_header(&mut c)?;
|
||||
let metadata = read_metadata(&mut c, nk)?;
|
||||
if c.u32()? != 0x46554747 || c.u32()? != 3 {
|
||||
return Err("GGUF magic/version mismatch".into());
|
||||
}
|
||||
let nt = usize::try_from(c.u64()?).map_err(|_| "GGUF tensor count")?;
|
||||
let nk = c.u64()?;
|
||||
let mut metadata = HashMap::new();
|
||||
for _ in 0..nk {
|
||||
let key = c.string()?;
|
||||
let ty = c.u32()?;
|
||||
let value = c.value(ty, 0)?;
|
||||
metadata.try_reserve(1).map_err(|_| "GGUF allocation")?;
|
||||
metadata.entry(key).or_insert(value);
|
||||
}
|
||||
let mut tensors = Vec::new();
|
||||
let mut names = HashSet::new();
|
||||
// A valid tensor header cannot be shorter than name length+nd+one dim+type+offset.
|
||||
if nt > (map.bytes.saturating_sub(c.at)) / 32 {
|
||||
return Err("truncated GGUF tensor table".into());
|
||||
}
|
||||
let tensors = read_tensors(&mut c, nt)?;
|
||||
let data_start = data_start(c.at, &metadata, map.bytes)?;
|
||||
tensors.try_reserve_exact(nt).map_err(|_| "GGUF allocation")?;
|
||||
names.try_reserve(nt).map_err(|_| "GGUF allocation")?;
|
||||
for _ in 0..nt {
|
||||
let name = c.string()?;
|
||||
if !names.insert(copy(&name)?) {
|
||||
return Err("duplicate GGUF tensor".into());
|
||||
}
|
||||
let nd = c.u32()?;
|
||||
if !(1..=4).contains(&nd) {
|
||||
return Err("GGUF tensor dimension".into());
|
||||
}
|
||||
for _ in 0..nd {
|
||||
c.u64()?;
|
||||
}
|
||||
let kind = c.u32()?;
|
||||
let offset = c.u64()?;
|
||||
tensors.push(Tensor { name, kind, offset });
|
||||
}
|
||||
let alignment = metadata.get(b"general.alignment".as_slice()).copied().filter(|n| *n != 0).unwrap_or(32);
|
||||
let a = usize::try_from(alignment).map_err(|_| "GGUF alignment overflow")?;
|
||||
let data_start =
|
||||
c.at.checked_add(a - 1)
|
||||
.and_then(|n| n.checked_div(a))
|
||||
.and_then(|n| n.checked_mul(a))
|
||||
.ok_or("GGUF alignment overflow")?;
|
||||
if data_start > map.bytes {
|
||||
return Err("GGUF data start beyond file".into());
|
||||
}
|
||||
Ok(Self { map, metadata, tensors, data_start })
|
||||
}
|
||||
fn meta(&self, key: &[u8]) -> Option<u64> {
|
||||
@@ -265,8 +240,41 @@ impl Model {
|
||||
for path in paths {
|
||||
shards.push(Shard::open(&path)?);
|
||||
}
|
||||
validate_split(&shards)?;
|
||||
let index = index_tensors(&shards)?;
|
||||
let n = shards.len();
|
||||
let first = &shards[0];
|
||||
if n == 1 && first.meta(b"split.count").unwrap_or(0) > 1 {
|
||||
return Err("split GGUF requires all shards".into());
|
||||
}
|
||||
if n > 1 {
|
||||
if !first.metadata.contains_key(b"general.architecture".as_slice()) {
|
||||
return Err("first split shard lacks architecture".into());
|
||||
}
|
||||
let declared = first.meta(b"split.tensors.count");
|
||||
let mut total = 0usize;
|
||||
for (i, s) in shards.iter().enumerate() {
|
||||
if s.meta(b"split.count") != Some(n as u64) || s.meta(b"split.no") != Some(i as u64) {
|
||||
return Err("split GGUF count/order mismatch".into());
|
||||
}
|
||||
if let Some(v) = declared {
|
||||
if s.meta(b"split.tensors.count") != Some(v) {
|
||||
return Err("split GGUF tensor count metadata mismatch".into());
|
||||
}
|
||||
}
|
||||
total = total.checked_add(s.tensors.len()).ok_or("tensor count overflow")?;
|
||||
}
|
||||
if declared.is_some_and(|v| v != total as u64) {
|
||||
return Err("split GGUF tensor count mismatch".into());
|
||||
}
|
||||
}
|
||||
let mut index = HashMap::new();
|
||||
for (s, shard) in shards.iter().enumerate() {
|
||||
index.try_reserve(shard.tensors.len()).map_err(|_| "GGUF allocation")?;
|
||||
for (t, tensor) in shard.tensors.iter().enumerate() {
|
||||
if index.insert(copy(&tensor.name)?, (s, t)).is_some() {
|
||||
return Err("duplicate tensor across GGUF shards".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Self { shards, index })
|
||||
}
|
||||
pub(super) fn kinds(&self, layer: i32) -> Option<(i32, i32)> {
|
||||
@@ -299,80 +307,24 @@ impl Model {
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
/// A single shard must not declare a split; several shards must declare the same split in order.
|
||||
fn validate_split(shards: &[Shard]) -> Result<(), String> {
|
||||
let n = shards.len();
|
||||
let first = &shards[0];
|
||||
if n == 1 && first.meta(b"split.count").unwrap_or(0) > 1 {
|
||||
return Err("split GGUF requires all shards".into());
|
||||
}
|
||||
if n > 1 {
|
||||
if !first.metadata.contains_key(b"general.architecture".as_slice()) {
|
||||
return Err("first split shard lacks architecture".into());
|
||||
}
|
||||
let declared = first.meta(b"split.tensors.count");
|
||||
let total = validate_split_shards(shards, declared)?;
|
||||
if declared.is_some_and(|v| v != total as u64) {
|
||||
return Err("split GGUF tensor count mismatch".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Checks every shard's split number and tensor-count metadata; returns the tensors across all shards.
|
||||
fn validate_split_shards(shards: &[Shard], declared: Option<u64>) -> Result<usize, String> {
|
||||
let mut total = 0usize;
|
||||
for (i, s) in shards.iter().enumerate() {
|
||||
if s.meta(b"split.count") != Some(shards.len() as u64) || s.meta(b"split.no") != Some(i as u64) {
|
||||
return Err("split GGUF count/order mismatch".into());
|
||||
}
|
||||
if declared.is_some_and(|v| s.meta(b"split.tensors.count") != Some(v)) {
|
||||
return Err("split GGUF tensor count metadata mismatch".into());
|
||||
}
|
||||
total = total.checked_add(s.tensors.len()).ok_or("tensor count overflow")?;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
/// Maps every tensor name to its shard and position; a name may occur once across the shards.
|
||||
fn index_tensors(shards: &[Shard]) -> Result<HashMap<Vec<u8>, (usize, usize)>, String> {
|
||||
let mut index = HashMap::new();
|
||||
for (s, shard) in shards.iter().enumerate() {
|
||||
index.try_reserve(shard.tensors.len()).map_err(|_| "GGUF allocation")?;
|
||||
for (t, tensor) in shard.tensors.iter().enumerate() {
|
||||
if index.insert(copy(&tensor.name)?, (s, t)).is_some() {
|
||||
return Err("duplicate tensor across GGUF shards".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(index)
|
||||
}
|
||||
/// Whether `b` has the `-NNNNN-of-NNNNN.gguf` shape with `-of-` at `at`.
|
||||
fn has_split_shape(b: &[u8], at: usize) -> bool {
|
||||
at >= 6
|
||||
&& b[at - 6] == b'-'
|
||||
&& b.len() == at + 14
|
||||
&& &b[at + 9..] == b".gguf"
|
||||
&& b[at - 5..at].iter().chain(&b[at + 4..at + 9]).all(u8::is_ascii_digit)
|
||||
}
|
||||
/// The position of `-of-` and the shard count `n` of a name ending `-NNNNN-of-NNNNN.gguf` whose shard number is within
|
||||
/// 1..=n; `None` for any other name.
|
||||
fn split_pattern(any: &str) -> Result<Option<(usize, usize)>, String> {
|
||||
fn split_paths(any: &str) -> Result<Vec<String>, String> {
|
||||
let Some(at) = any.rfind("-of-") else {
|
||||
return Ok(None);
|
||||
return Ok(vec![any.into()]);
|
||||
};
|
||||
if !has_split_shape(any.as_bytes(), at) {
|
||||
return Ok(None);
|
||||
let b = any.as_bytes();
|
||||
if at < 6
|
||||
|| b[at - 6] != b'-'
|
||||
|| b.len() != at + 14
|
||||
|| &b[at + 9..] != b".gguf"
|
||||
|| !b[at - 5..at].iter().chain(&b[at + 4..at + 9]).all(u8::is_ascii_digit)
|
||||
{
|
||||
return Ok(vec![any.into()]);
|
||||
}
|
||||
let no = any[at - 5..at].parse::<usize>().map_err(|e| e.to_string())?;
|
||||
let n = any[at + 4..at + 9].parse::<usize>().map_err(|e| e.to_string())?;
|
||||
if n < 1 || no < 1 || no > n {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some((at, n)))
|
||||
}
|
||||
fn split_paths(any: &str) -> Result<Vec<String>, String> {
|
||||
let Some((at, n)) = split_pattern(any)? else {
|
||||
return Ok(vec![any.into()]);
|
||||
};
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(n).map_err(|_| "shard allocation")?;
|
||||
for i in 1..=n {
|
||||
|
||||
@@ -20,8 +20,241 @@ pub(super) const KSIGNS_IQ2XS: [u8; 128] = [
|
||||
120, 249, 250, 123, 252, 125, 126, 255,
|
||||
];
|
||||
|
||||
mod iq2_grids;
|
||||
pub(super) use iq2_grids::{IQ2S_GRID, IQ2XS_GRID, IQ2XXS_GRID};
|
||||
#[rustfmt::skip]
|
||||
pub(super) const IQ2XXS_GRID: [u64; 256] = [
|
||||
0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808,
|
||||
0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819, 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819,
|
||||
0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b, 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808,
|
||||
0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b,
|
||||
0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819, 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08,
|
||||
0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08,
|
||||
0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808, 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808,
|
||||
0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819,
|
||||
0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08, 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908,
|
||||
0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819, 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808,
|
||||
0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808, 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908,
|
||||
0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808, 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08,
|
||||
0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819,
|
||||
0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819, 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908,
|
||||
0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19, 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819,
|
||||
0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b, 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808,
|
||||
0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908, 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08,
|
||||
0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08, 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908,
|
||||
0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819, 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808,
|
||||
0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808, 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19,
|
||||
0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919,
|
||||
0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b, 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08,
|
||||
0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808, 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908,
|
||||
0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b, 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819,
|
||||
0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08,
|
||||
0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808, 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b,
|
||||
0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908,
|
||||
0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808,
|
||||
0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908, 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b,
|
||||
0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808, 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b,
|
||||
0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b, 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808,
|
||||
0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19, 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908,
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub(super) const IQ2XS_GRID: [u64; 512] = [
|
||||
0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b,
|
||||
0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b,
|
||||
0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808,
|
||||
0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b192b19, 0x080808082b2b0808, 0x0808081908080819,
|
||||
0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b,
|
||||
0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908,
|
||||
0x08080819192b0808, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908, 0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919,
|
||||
0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, 0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919,
|
||||
0x0808082b2b080808, 0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b,
|
||||
0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08,
|
||||
0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x0808191908080808,
|
||||
0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908190819, 0x0808191908191908, 0x08081919082b0808, 0x0808191919080819, 0x0808191919081908,
|
||||
0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819, 0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808,
|
||||
0x0808192b1908082b, 0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b, 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808082b2b, 0x08082b0808190819,
|
||||
0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b0819080819, 0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808,
|
||||
0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908, 0x08082b1908190808, 0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19,
|
||||
0x08082b2b08080808, 0x08082b2b082b0808, 0x08082b2b082b2b08, 0x08082b2b2b19192b, 0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b,
|
||||
0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808,
|
||||
0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x08190808192b0808, 0x08190808192b2b2b, 0x081908082b080819,
|
||||
0x081908082b081908, 0x081908082b190808, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908,
|
||||
0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808, 0x081908192b080808, 0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819,
|
||||
0x0819082b08081908, 0x0819082b0808192b, 0x0819082b08190808, 0x0819082b19080808, 0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919,
|
||||
0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808, 0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808,
|
||||
0x08191908192b1908, 0x081919082b080808, 0x0819191908080819, 0x0819191908081908, 0x0819191908190808, 0x0819191919080808, 0x0819192b08080808, 0x0819192b08191908,
|
||||
0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, 0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b,
|
||||
0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819, 0x08192b2b2b2b2b19, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919,
|
||||
0x082b080808082b08, 0x082b080808082b2b, 0x082b080808190819, 0x082b080808191908, 0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808,
|
||||
0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919,
|
||||
0x082b082b08080808, 0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b1908082b2b19,
|
||||
0x082b190819080808, 0x082b191908080808, 0x082b191919080819, 0x082b19191919082b, 0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b,
|
||||
0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808, 0x082b2b0819191919, 0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08,
|
||||
0x082b2b192b190808, 0x082b2b2b08082b08, 0x082b2b2b082b0808, 0x082b2b2b2b08082b, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908,
|
||||
0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908,
|
||||
0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x19080808192b0808,
|
||||
0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808, 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08,
|
||||
0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819, 0x1908081919081908, 0x1908081919190808, 0x190808192b080808, 0x190808192b081919,
|
||||
0x190808192b2b082b, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808, 0x1908190808080808,
|
||||
0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819, 0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819,
|
||||
0x1908190819081908, 0x1908190819190808, 0x190819082b080808, 0x190819082b191908, 0x1908191908080819, 0x1908191908081908, 0x1908191908190808, 0x19081919082b1908,
|
||||
0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808, 0x1908192b08082b2b, 0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908,
|
||||
0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908, 0x19082b08192b082b, 0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908,
|
||||
0x19082b1919190808, 0x19082b19192b2b19, 0x19082b2b08081908, 0x1919080808080808, 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819,
|
||||
0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819,
|
||||
0x1919081908081908, 0x1919081908190808, 0x1919081908191919, 0x1919081919080808, 0x191908191908082b, 0x1919082b08080808, 0x1919082b19081908, 0x1919082b2b2b2b2b,
|
||||
0x1919190808080819, 0x1919190808081908, 0x1919190808190808, 0x19191908082b0819, 0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819,
|
||||
0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08, 0x1919192b082b0819, 0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808,
|
||||
0x19192b0808191908, 0x19192b0819080819, 0x19192b0819190808, 0x19192b082b192b19, 0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b, 0x19192b2b2b081919,
|
||||
0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19,
|
||||
0x192b081908080808, 0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b, 0x192b190808080808, 0x192b19080819192b, 0x192b191908190808, 0x192b191919080808,
|
||||
0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819, 0x192b2b08192b2b2b, 0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b,
|
||||
0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, 0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b,
|
||||
0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808082b080808, 0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b, 0x2b08081908080819,
|
||||
0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808, 0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808,
|
||||
0x2b08082b2b080808, 0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08, 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b0819080819082b,
|
||||
0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b0819082b082b19, 0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08,
|
||||
0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919, 0x2b082b0819192b2b, 0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08,
|
||||
0x2b082b190808192b, 0x2b082b2b082b082b, 0x2b082b2b2b080808, 0x2b082b2b2b082b08, 0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819, 0x2b19080808081908,
|
||||
0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908, 0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b,
|
||||
0x2b19082b2b082b19, 0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908, 0x2b19190819190808, 0x2b19190819192b08, 0x2b191919082b2b19, 0x2b1919192b190808,
|
||||
0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819, 0x2b192b082b2b192b, 0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808,
|
||||
0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808, 0x2b2b0808082b2b2b, 0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19,
|
||||
0x2b2b08192b2b192b, 0x2b2b082b08080808, 0x2b2b082b0808082b, 0x2b2b082b08082b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808, 0x2b2b190819080808,
|
||||
0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b, 0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808,
|
||||
0x2b2b2b082b2b2b08, 0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b, 0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b,
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub(super) const IQ2S_GRID: [u64; 1024] = [
|
||||
0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b,
|
||||
0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b,
|
||||
0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b,
|
||||
0x08080808192b2b19, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b2b0808,
|
||||
0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819, 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b,
|
||||
0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08,
|
||||
0x0808081919190819, 0x0808081919191908, 0x080808191919192b, 0x0808081919192b19, 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08, 0x080808192b080819,
|
||||
0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919, 0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b,
|
||||
0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, 0x0808082b082b2b2b, 0x0808082b19080819, 0x0808082b19081908,
|
||||
0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808, 0x0808082b19191919, 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908,
|
||||
0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919,
|
||||
0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x08081908082b192b, 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919,
|
||||
0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b,
|
||||
0x08081908192b1919, 0x080819082b080819, 0x080819082b081908, 0x080819082b08192b, 0x080819082b082b19, 0x080819082b190808, 0x080819082b191919, 0x080819082b192b08,
|
||||
0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819,
|
||||
0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808, 0x08081919082b1919, 0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908,
|
||||
0x080819191908192b, 0x0808191919082b19, 0x0808191919190808, 0x080819191919082b, 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819, 0x08081919192b1908,
|
||||
0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08, 0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819,
|
||||
0x0808192b08081908, 0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b08191919, 0x0808192b19080808, 0x0808192b19081919, 0x0808192b19082b08,
|
||||
0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808, 0x0808192b2b080819, 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b,
|
||||
0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908, 0x08082b080819192b, 0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919,
|
||||
0x08082b08082b2b2b, 0x08082b0819080819, 0x08082b0819081908, 0x08082b081908192b, 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b, 0x08082b0819191919,
|
||||
0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808, 0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819,
|
||||
0x08082b1908081908, 0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919, 0x08082b1908192b08, 0x08082b19082b0819, 0x08082b1919080808, 0x08082b1919081919,
|
||||
0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908, 0x08082b19192b0808, 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819,
|
||||
0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b, 0x08082b2b19190808, 0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908,
|
||||
0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908,
|
||||
0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b,
|
||||
0x0819080819192b19, 0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919, 0x08190808192b2b08, 0x081908082b080819, 0x081908082b081908, 0x081908082b08192b,
|
||||
0x081908082b190808, 0x081908082b191919, 0x081908082b192b08, 0x081908082b2b0819, 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919,
|
||||
0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908, 0x081908190819192b, 0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b,
|
||||
0x08190819082b1919, 0x08190819082b2b08, 0x0819081919080819, 0x0819081919081908, 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808, 0x081908191919082b,
|
||||
0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908, 0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08,
|
||||
0x081908192b190819, 0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908, 0x0819082b08082b19, 0x0819082b08190808, 0x0819082b08191919, 0x0819082b082b0819,
|
||||
0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919, 0x0819082b19190819, 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808,
|
||||
0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x081919080819192b, 0x0819190808192b19,
|
||||
0x08191908082b0808, 0x08191908082b1919, 0x08191908082b2b08, 0x0819190819080819, 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19, 0x0819190819190808,
|
||||
0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819, 0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919,
|
||||
0x081919082b082b08, 0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808, 0x0819191908080819, 0x0819191908081908, 0x081919190808192b, 0x0819191908082b19,
|
||||
0x0819191908190808, 0x081919190819082b, 0x0819191908191919, 0x0819191908192b08, 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b,
|
||||
0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908, 0x08191919192b0808, 0x081919192b080819, 0x081919192b081908, 0x081919192b190808,
|
||||
0x0819192b08080808, 0x0819192b08081919, 0x0819192b08082b08, 0x0819192b08190819, 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819, 0x0819192b19081908,
|
||||
0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819, 0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808,
|
||||
0x08192b0808191919, 0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808, 0x08192b081908082b, 0x08192b0819081919, 0x08192b0819082b08, 0x08192b0819190819,
|
||||
0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819, 0x08192b082b081908, 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08,
|
||||
0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819, 0x08192b1919081908, 0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b,
|
||||
0x08192b2b08081908, 0x08192b2b08190808, 0x08192b2b19080808, 0x08192b2b1919192b, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08,
|
||||
0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19, 0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819,
|
||||
0x082b080819081908, 0x082b080819190808, 0x082b08081919082b, 0x082b080819191919, 0x082b0808192b1908, 0x082b08082b080808, 0x082b08082b082b2b, 0x082b08082b191908,
|
||||
0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808,
|
||||
0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908, 0x082b0819192b0808, 0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808,
|
||||
0x082b082b08080808, 0x082b082b08082b2b, 0x082b082b082b082b, 0x082b082b082b2b08, 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808, 0x082b082b2b082b08,
|
||||
0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, 0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919,
|
||||
0x082b190808192b08, 0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808, 0x082b19081908082b, 0x082b190819081919, 0x082b190819082b08, 0x082b190819190819,
|
||||
0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819, 0x082b19082b081908, 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08,
|
||||
0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819, 0x082b191919081908, 0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808,
|
||||
0x082b192b08080819, 0x082b192b08081908, 0x082b192b08190808, 0x082b192b19080808, 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919, 0x082b2b0808190819,
|
||||
0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808, 0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908,
|
||||
0x082b2b1908190808, 0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b, 0x082b2b2b192b1908, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819,
|
||||
0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b,
|
||||
0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b,
|
||||
0x1908080819190819, 0x1908080819191908, 0x190808081919192b, 0x1908080819192b19, 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919, 0x190808082b080819,
|
||||
0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08, 0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b,
|
||||
0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, 0x190808190819192b, 0x1908081908192b19, 0x19080819082b0808, 0x19080819082b082b,
|
||||
0x19080819082b1919, 0x1908081919080819, 0x1908081919081908, 0x190808191908192b, 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919,
|
||||
0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808, 0x190808192b08082b, 0x190808192b081919, 0x190808192b082b08, 0x190808192b190819,
|
||||
0x190808192b191908, 0x190808192b2b0808, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919, 0x1908082b08192b08,
|
||||
0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08, 0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819,
|
||||
0x1908082b2b081908, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808082b2b, 0x1908190808190819, 0x1908190808191908,
|
||||
0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808, 0x19081908082b082b, 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908,
|
||||
0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b, 0x1908190819191919, 0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908,
|
||||
0x190819082b080808, 0x190819082b08082b, 0x190819082b081919, 0x190819082b082b08, 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808, 0x1908191908080819,
|
||||
0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808, 0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819,
|
||||
0x19081919082b1908, 0x1908191919080808, 0x190819191908082b, 0x1908191919081919, 0x1908191919082b08, 0x1908191919190819, 0x1908191919191908, 0x19081919192b0808,
|
||||
0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908, 0x190819192b190808, 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08,
|
||||
0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819, 0x1908192b19081908, 0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919,
|
||||
0x19082b0808080819, 0x19082b0808081908, 0x19082b0808082b19, 0x19082b0808190808, 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08, 0x19082b08082b0819,
|
||||
0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919, 0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808,
|
||||
0x19082b082b081908, 0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b, 0x19082b1908081919, 0x19082b1908082b08, 0x19082b1908190819, 0x19082b1908191908,
|
||||
0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908, 0x19082b1919190808, 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908,
|
||||
0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908,
|
||||
0x191908080819192b, 0x1919080808192b19, 0x19190808082b0808, 0x19190808082b082b, 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908,
|
||||
0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b, 0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908,
|
||||
0x191908082b080808, 0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08, 0x191908082b190819, 0x191908082b191908, 0x1919081908080819, 0x1919081908081908,
|
||||
0x191908190808192b, 0x1919081908082b19, 0x1919081908190808, 0x191908190819082b, 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908,
|
||||
0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08, 0x1919081919190819, 0x1919081919191908, 0x19190819192b0808, 0x191908192b080819,
|
||||
0x191908192b081908, 0x191908192b190808, 0x1919082b08080808, 0x1919082b08081919, 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908, 0x1919082b082b0808,
|
||||
0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19, 0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b,
|
||||
0x1919190808082b19, 0x1919190808190808, 0x191919080819082b, 0x1919190808191919, 0x1919190808192b08, 0x19191908082b0819, 0x19191908082b1908, 0x1919190819080808,
|
||||
0x191919081908082b, 0x1919190819081919, 0x1919190819082b08, 0x1919190819190819, 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908,
|
||||
0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919, 0x1919191908082b08, 0x1919191908190819, 0x1919191908191908, 0x19191919082b0808,
|
||||
0x1919191919080819, 0x1919191919081908, 0x1919191919190808, 0x191919192b080808, 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808, 0x1919192b082b192b,
|
||||
0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919, 0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808,
|
||||
0x19192b0819080819, 0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b, 0x19192b082b080808, 0x19192b1908080819, 0x19192b1908081908, 0x19192b1908190808,
|
||||
0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19, 0x19192b2b2b081919, 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b,
|
||||
0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08, 0x192b0808082b0819, 0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919,
|
||||
0x192b080819082b08, 0x192b080819190819, 0x192b080819191908, 0x192b0808192b0808, 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808, 0x192b08190808082b,
|
||||
0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908, 0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808,
|
||||
0x192b08192b080808, 0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808, 0x192b082b19080808, 0x192b082b1919192b, 0x192b082b2b2b0819, 0x192b190808080808,
|
||||
0x192b190808081919, 0x192b190808082b08, 0x192b190808190819, 0x192b190808191908, 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808,
|
||||
0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808, 0x192b191919080808, 0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b,
|
||||
0x192b192b08080808, 0x192b192b2b191908, 0x192b2b0808080819, 0x192b2b0808081908, 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08, 0x192b2b1908080808,
|
||||
0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819,
|
||||
0x2b08080808191908, 0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919, 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808081919082b,
|
||||
0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819, 0x2b0808082b080808, 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819,
|
||||
0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b, 0x2b08081908191919, 0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908,
|
||||
0x2b08081919080808, 0x2b0808191908082b, 0x2b08081919081919, 0x2b08081919082b08, 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819, 0x2b0808192b081908,
|
||||
0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919, 0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819,
|
||||
0x2b08082b19081908, 0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908, 0x2b0819080808192b, 0x2b08190808082b19, 0x2b08190808190808, 0x2b0819080819082b,
|
||||
0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819, 0x2b08190819080808, 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819,
|
||||
0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908, 0x2b0819082b190808, 0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919,
|
||||
0x2b08191908082b08, 0x2b08191908190819, 0x2b08191908191908, 0x2b081919082b0808, 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808, 0x2b0819192b080808,
|
||||
0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808, 0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919,
|
||||
0x2b082b0808190819, 0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908, 0x2b082b0819190808, 0x2b082b082b2b082b, 0x2b082b1908080819, 0x2b082b1908081908,
|
||||
0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b, 0x2b082b2b19192b08, 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819,
|
||||
0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b, 0x2b19080808191919, 0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808,
|
||||
0x2b1908081908082b, 0x2b19080819081919, 0x2b19080819082b08, 0x2b19080819190819, 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819, 0x2b1908082b081908,
|
||||
0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819, 0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808,
|
||||
0x2b19081919192b2b, 0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808, 0x2b19082b19080808, 0x2b19082b2b2b192b, 0x2b19190808080808, 0x2b1919080808082b,
|
||||
0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819, 0x2b19190808191908, 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808,
|
||||
0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908, 0x2b19191908190808, 0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819,
|
||||
0x2b19192b08080808, 0x2b19192b1908192b, 0x2b19192b192b1908, 0x2b192b0808080819, 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b, 0x2b192b0819080808,
|
||||
0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b, 0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b,
|
||||
0x2b2b080808191908, 0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819, 0x2b2b080819081908, 0x2b2b080819190808, 0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b,
|
||||
0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b, 0x2b2b082b08082b2b, 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b,
|
||||
0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819, 0x2b2b190808081908, 0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19,
|
||||
0x2b2b19082b2b1908, 0x2b2b191908080808, 0x2b2b191908192b19, 0x2b2b192b19190819, 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b, 0x2b2b2b1919191908,
|
||||
0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808, 0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b,
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub(super) const IQ3XXS_GRID: [u32; 256] = [
|
||||
|
||||
@@ -1,373 +0,0 @@
|
||||
//! The 2-bit sign-modulated grids of the IQ2 formats, literal from pinned ggml-common.h. See LICENSE.ggml.
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub(crate) const IQ2XXS_GRID: [u64; 256] = [
|
||||
0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b,
|
||||
0x0808080808190819, 0x0808080808191908, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b2b08,
|
||||
0x08080808082b2b2b, 0x0808080819080819, 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08,
|
||||
0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b,
|
||||
0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808, 0x0808081908191919,
|
||||
0x0808081919080808, 0x080808192b081908, 0x080808192b192b08, 0x0808082b08080808, 0x0808082b0808082b,
|
||||
0x0808082b082b082b, 0x0808082b2b08082b, 0x0808190808080819, 0x0808190808081908, 0x0808190808190808,
|
||||
0x08081908082b0819, 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08,
|
||||
0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x080819082b2b1908,
|
||||
0x0808191908080808, 0x080819190808082b, 0x0808191908082b08, 0x08081919082b0808, 0x080819191908192b,
|
||||
0x08081919192b2b19, 0x080819192b080808, 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808,
|
||||
0x0808192b19080808, 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919,
|
||||
0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819, 0x08082b0819081908,
|
||||
0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08, 0x08082b1908081908, 0x08082b1919080808,
|
||||
0x08082b2b0808082b, 0x08082b2b08191908, 0x0819080808080819, 0x0819080808081908, 0x0819080808190808,
|
||||
0x08190808082b0819, 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808,
|
||||
0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808, 0x0819081919190808,
|
||||
0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908, 0x0819082b19081919, 0x0819190808080808,
|
||||
0x0819190808082b08, 0x08191908082b0808, 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808,
|
||||
0x0819191908192b08, 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819,
|
||||
0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819, 0x08192b1908080808,
|
||||
0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819, 0x082b080808080808, 0x082b08080808082b,
|
||||
0x082b080808082b2b, 0x082b080819081908, 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b,
|
||||
0x082b0819082b2b19, 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819,
|
||||
0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b, 0x082b191908080808,
|
||||
0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808, 0x082b2b0808082b08, 0x082b2b08082b0808,
|
||||
0x082b2b082b191908, 0x082b2b2b19081908, 0x1908080808080819, 0x1908080808081908, 0x1908080808190808,
|
||||
0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08,
|
||||
0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808,
|
||||
0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819, 0x190808192b080808, 0x190808192b081919,
|
||||
0x1908082b08080819, 0x1908082b08190808, 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08,
|
||||
0x1908190808080808, 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19,
|
||||
0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819, 0x19082b0808081908,
|
||||
0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b1908080808, 0x19082b1919192b08,
|
||||
0x19082b19192b0819, 0x19082b192b08082b, 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808,
|
||||
0x1919080808082b08, 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808,
|
||||
0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908, 0x1919082b2b190819,
|
||||
0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b, 0x1919192b08080819, 0x1919192b19191908,
|
||||
0x19192b0808080808, 0x19192b0808190819, 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808,
|
||||
0x19192b2b08082b08, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08,
|
||||
0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808, 0x192b190808080808,
|
||||
0x192b190808081919, 0x192b191908190808, 0x192b19190819082b, 0x192b19192b081908, 0x192b2b081908082b,
|
||||
0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b,
|
||||
0x2b08081908081908, 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819,
|
||||
0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808,
|
||||
0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908, 0x2b08192b08082b19, 0x2b08192b19080808,
|
||||
0x2b08192b192b0808, 0x2b082b080808082b, 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908,
|
||||
0x2b19080808190808, 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b,
|
||||
0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b, 0x2b19190819081908,
|
||||
0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808, 0x2b2b08080808082b, 0x2b2b080819190808,
|
||||
0x2b2b08082b081919, 0x2b2b081908082b19, 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808,
|
||||
0x2b2b2b1908081908,
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub(crate) const IQ2XS_GRID: [u64; 512] = [
|
||||
0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b,
|
||||
0x0808080808190819, 0x0808080808191908, 0x080808080819192b, 0x0808080808192b19, 0x08080808082b0808,
|
||||
0x08080808082b082b, 0x08080808082b1919, 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908,
|
||||
0x080808081908192b, 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919,
|
||||
0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b,
|
||||
0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b192b19,
|
||||
0x080808082b2b0808, 0x0808081908080819, 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19,
|
||||
0x0808081908190808, 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b,
|
||||
0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, 0x0808081919081919,
|
||||
0x0808081919082b08, 0x0808081919190819, 0x0808081919191908, 0x08080819192b0808, 0x08080819192b2b08,
|
||||
0x080808192b080819, 0x080808192b081908, 0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b,
|
||||
0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808,
|
||||
0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919, 0x0808082b2b080808,
|
||||
0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, 0x0808190808082b19,
|
||||
0x0808190808190808, 0x080819080819082b, 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819,
|
||||
0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08,
|
||||
0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808, 0x080819082b080819,
|
||||
0x080819082b081908, 0x080819082b190808, 0x0808191908080808, 0x080819190808082b, 0x0808191908081919,
|
||||
0x0808191908082b08, 0x0808191908190819, 0x0808191908191908, 0x08081919082b0808, 0x0808191919080819,
|
||||
0x0808191919081908, 0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819,
|
||||
0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808, 0x0808192b1908082b,
|
||||
0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b, 0x08082b0808081919, 0x08082b0808082b08,
|
||||
0x08082b0808082b2b, 0x08082b0808190819, 0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919,
|
||||
0x08082b0819080819, 0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808,
|
||||
0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908, 0x08082b1908190808,
|
||||
0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19, 0x08082b2b08080808, 0x08082b2b082b0808,
|
||||
0x08082b2b082b2b08, 0x08082b2b2b19192b, 0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908,
|
||||
0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919,
|
||||
0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808, 0x081908081908082b,
|
||||
0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x08190808192b0808,
|
||||
0x08190808192b2b2b, 0x081908082b080819, 0x081908082b081908, 0x081908082b190808, 0x0819081908080808,
|
||||
0x081908190808082b, 0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908,
|
||||
0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808, 0x081908192b080808,
|
||||
0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819, 0x0819082b08081908, 0x0819082b0808192b,
|
||||
0x0819082b08190808, 0x0819082b19080808, 0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b,
|
||||
0x0819190808081919, 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808,
|
||||
0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808, 0x08191908192b1908,
|
||||
0x081919082b080808, 0x0819191908080819, 0x0819191908081908, 0x0819191908190808, 0x0819191919080808,
|
||||
0x0819192b08080808, 0x0819192b08191908, 0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908,
|
||||
0x08192b0808190808, 0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b,
|
||||
0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819, 0x08192b2b2b2b2b19,
|
||||
0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08, 0x082b080808082b2b,
|
||||
0x082b080808190819, 0x082b080808191908, 0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908,
|
||||
0x082b080819190808, 0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908,
|
||||
0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919, 0x082b082b08080808,
|
||||
0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908,
|
||||
0x082b190808190808, 0x082b1908082b2b19, 0x082b190819080808, 0x082b191908080808, 0x082b191919080819,
|
||||
0x082b19191919082b, 0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b,
|
||||
0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808, 0x082b2b0819191919,
|
||||
0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08, 0x082b2b192b190808, 0x082b2b2b08082b08,
|
||||
0x082b2b2b082b0808, 0x082b2b2b2b08082b, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819,
|
||||
0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b,
|
||||
0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808,
|
||||
0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, 0x1908080819190819,
|
||||
0x1908080819191908, 0x19080808192b0808, 0x19080808192b1919, 0x190808082b080819, 0x190808082b081908,
|
||||
0x190808082b190808, 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08,
|
||||
0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819, 0x1908081919081908,
|
||||
0x1908081919190808, 0x190808192b080808, 0x190808192b081919, 0x190808192b2b082b, 0x1908082b08080819,
|
||||
0x1908082b08081908, 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808,
|
||||
0x1908190808080808, 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819,
|
||||
0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819, 0x1908190819081908,
|
||||
0x1908190819190808, 0x190819082b080808, 0x190819082b191908, 0x1908191908080819, 0x1908191908081908,
|
||||
0x1908191908190808, 0x19081919082b1908, 0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808,
|
||||
0x1908192b08082b2b, 0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908,
|
||||
0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908, 0x19082b08192b082b,
|
||||
0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908, 0x19082b1919190808, 0x19082b19192b2b19,
|
||||
0x19082b2b08081908, 0x1919080808080808, 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08,
|
||||
0x1919080808190819, 0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819,
|
||||
0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819, 0x1919081908081908,
|
||||
0x1919081908190808, 0x1919081908191919, 0x1919081919080808, 0x191908191908082b, 0x1919082b08080808,
|
||||
0x1919082b19081908, 0x1919082b2b2b2b2b, 0x1919190808080819, 0x1919190808081908, 0x1919190808190808,
|
||||
0x19191908082b0819, 0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819,
|
||||
0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08, 0x1919192b082b0819,
|
||||
0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808, 0x19192b0808191908, 0x19192b0819080819,
|
||||
0x19192b0819190808, 0x19192b082b192b19, 0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b,
|
||||
0x19192b2b2b081919, 0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808,
|
||||
0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19, 0x192b081908080808,
|
||||
0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b, 0x192b190808080808, 0x192b19080819192b,
|
||||
0x192b191908190808, 0x192b191919080808, 0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819,
|
||||
0x192b2b08192b2b2b, 0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b,
|
||||
0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819,
|
||||
0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b, 0x2b08080819080819, 0x2b08080819081908,
|
||||
0x2b08080819190808, 0x2b0808082b080808, 0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b,
|
||||
0x2b08081908080819, 0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808,
|
||||
0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808, 0x2b08082b2b080808,
|
||||
0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08, 0x2b08190808080819, 0x2b08190808081908,
|
||||
0x2b08190808190808, 0x2b0819080819082b, 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808,
|
||||
0x2b0819082b082b19, 0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08,
|
||||
0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919, 0x2b082b0819192b2b,
|
||||
0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08, 0x2b082b190808192b, 0x2b082b2b082b082b,
|
||||
0x2b082b2b2b080808, 0x2b082b2b2b082b08, 0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819,
|
||||
0x2b19080808081908, 0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908,
|
||||
0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b, 0x2b19082b2b082b19,
|
||||
0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908, 0x2b19190819190808, 0x2b19190819192b08,
|
||||
0x2b191919082b2b19, 0x2b1919192b190808, 0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819,
|
||||
0x2b192b082b2b192b, 0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808,
|
||||
0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808, 0x2b2b0808082b2b2b,
|
||||
0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19, 0x2b2b08192b2b192b, 0x2b2b082b08080808,
|
||||
0x2b2b082b0808082b, 0x2b2b082b08082b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808,
|
||||
0x2b2b190819080808, 0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b,
|
||||
0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808, 0x2b2b2b082b2b2b08,
|
||||
0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b,
|
||||
0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b,
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub(crate) const IQ2S_GRID: [u64; 1024] = [
|
||||
0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b,
|
||||
0x0808080808190819, 0x0808080808191908, 0x080808080819192b, 0x0808080808192b19, 0x08080808082b0808,
|
||||
0x08080808082b082b, 0x08080808082b1919, 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908,
|
||||
0x080808081908192b, 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919,
|
||||
0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b, 0x08080808192b2b19,
|
||||
0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819,
|
||||
0x080808082b191908, 0x080808082b2b0808, 0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819,
|
||||
0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b,
|
||||
0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808,
|
||||
0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908,
|
||||
0x080808191919192b, 0x0808081919192b19, 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08,
|
||||
0x080808192b080819, 0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919,
|
||||
0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919,
|
||||
0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, 0x0808082b082b2b2b,
|
||||
0x0808082b19080819, 0x0808082b19081908, 0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808,
|
||||
0x0808082b19191919, 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908,
|
||||
0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, 0x0808190808082b19,
|
||||
0x0808190808190808, 0x080819080819082b, 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819,
|
||||
0x08081908082b1908, 0x08081908082b192b, 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b,
|
||||
0x0808190819081919, 0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908,
|
||||
0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b, 0x08081908192b1919,
|
||||
0x080819082b080819, 0x080819082b081908, 0x080819082b08192b, 0x080819082b082b19, 0x080819082b190808,
|
||||
0x080819082b191919, 0x080819082b192b08, 0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808,
|
||||
0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819,
|
||||
0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808, 0x08081919082b1919,
|
||||
0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908, 0x080819191908192b, 0x0808191919082b19,
|
||||
0x0808191919190808, 0x080819191919082b, 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819,
|
||||
0x08081919192b1908, 0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08,
|
||||
0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819, 0x0808192b08081908,
|
||||
0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b08191919, 0x0808192b19080808,
|
||||
0x0808192b19081919, 0x0808192b19082b08, 0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808,
|
||||
0x0808192b2b080819, 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b,
|
||||
0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908, 0x08082b080819192b,
|
||||
0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b08082b2b2b, 0x08082b0819080819,
|
||||
0x08082b0819081908, 0x08082b081908192b, 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b,
|
||||
0x08082b0819191919, 0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808,
|
||||
0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908,
|
||||
0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919, 0x08082b1908192b08, 0x08082b19082b0819,
|
||||
0x08082b1919080808, 0x08082b1919081919, 0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908,
|
||||
0x08082b19192b0808, 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819,
|
||||
0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b, 0x08082b2b19190808,
|
||||
0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b, 0x0819080808082b19,
|
||||
0x0819080808190808, 0x081908080819082b, 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819,
|
||||
0x08190808082b1908, 0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919,
|
||||
0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b, 0x0819080819192b19,
|
||||
0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919, 0x08190808192b2b08, 0x081908082b080819,
|
||||
0x081908082b081908, 0x081908082b08192b, 0x081908082b190808, 0x081908082b191919, 0x081908082b192b08,
|
||||
0x081908082b2b0819, 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919,
|
||||
0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908, 0x081908190819192b,
|
||||
0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b, 0x08190819082b1919, 0x08190819082b2b08,
|
||||
0x0819081919080819, 0x0819081919081908, 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808,
|
||||
0x081908191919082b, 0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908,
|
||||
0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08, 0x081908192b190819,
|
||||
0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908, 0x0819082b08082b19, 0x0819082b08190808,
|
||||
0x0819082b08191919, 0x0819082b082b0819, 0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919,
|
||||
0x0819082b19190819, 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808,
|
||||
0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, 0x0819190808190819,
|
||||
0x0819190808191908, 0x081919080819192b, 0x0819190808192b19, 0x08191908082b0808, 0x08191908082b1919,
|
||||
0x08191908082b2b08, 0x0819190819080819, 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19,
|
||||
0x0819190819190808, 0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819,
|
||||
0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919, 0x081919082b082b08,
|
||||
0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808, 0x0819191908080819, 0x0819191908081908,
|
||||
0x081919190808192b, 0x0819191908082b19, 0x0819191908190808, 0x081919190819082b, 0x0819191908191919,
|
||||
0x0819191908192b08, 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b,
|
||||
0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908, 0x08191919192b0808,
|
||||
0x081919192b080819, 0x081919192b081908, 0x081919192b190808, 0x0819192b08080808, 0x0819192b08081919,
|
||||
0x0819192b08082b08, 0x0819192b08190819, 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819,
|
||||
0x0819192b19081908, 0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819,
|
||||
0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808, 0x08192b0808191919,
|
||||
0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808, 0x08192b081908082b, 0x08192b0819081919,
|
||||
0x08192b0819082b08, 0x08192b0819190819, 0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819,
|
||||
0x08192b082b081908, 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08,
|
||||
0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819, 0x08192b1919081908,
|
||||
0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b, 0x08192b2b08081908, 0x08192b2b08190808,
|
||||
0x08192b2b19080808, 0x08192b2b1919192b, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919,
|
||||
0x082b080808082b08, 0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19,
|
||||
0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819, 0x082b080819081908,
|
||||
0x082b080819190808, 0x082b08081919082b, 0x082b080819191919, 0x082b0808192b1908, 0x082b08082b080808,
|
||||
0x082b08082b082b2b, 0x082b08082b191908, 0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908,
|
||||
0x082b081908190808, 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808,
|
||||
0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908, 0x082b0819192b0808,
|
||||
0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808, 0x082b082b08080808, 0x082b082b08082b2b,
|
||||
0x082b082b082b082b, 0x082b082b082b2b08, 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808,
|
||||
0x082b082b2b082b08, 0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908,
|
||||
0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919, 0x082b190808192b08,
|
||||
0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808, 0x082b19081908082b, 0x082b190819081919,
|
||||
0x082b190819082b08, 0x082b190819190819, 0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819,
|
||||
0x082b19082b081908, 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08,
|
||||
0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819, 0x082b191919081908,
|
||||
0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808, 0x082b192b08080819, 0x082b192b08081908,
|
||||
0x082b192b08190808, 0x082b192b19080808, 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919,
|
||||
0x082b2b0808190819, 0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808,
|
||||
0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908, 0x082b2b1908190808,
|
||||
0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b, 0x082b2b2b192b1908, 0x082b2b2b2b082b08,
|
||||
0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19,
|
||||
0x1908080808190808, 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b,
|
||||
0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808, 0x190808081908082b,
|
||||
0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908,
|
||||
0x190808081919192b, 0x1908080819192b19, 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919,
|
||||
0x190808082b080819, 0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08,
|
||||
0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b, 0x1908081908081919,
|
||||
0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, 0x190808190819192b, 0x1908081908192b19,
|
||||
0x19080819082b0808, 0x19080819082b082b, 0x19080819082b1919, 0x1908081919080819, 0x1908081919081908,
|
||||
0x190808191908192b, 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919,
|
||||
0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808, 0x190808192b08082b,
|
||||
0x190808192b081919, 0x190808192b082b08, 0x190808192b190819, 0x190808192b191908, 0x190808192b2b0808,
|
||||
0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919,
|
||||
0x1908082b08192b08, 0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08,
|
||||
0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819, 0x1908082b2b081908,
|
||||
0x1908190808080808, 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808082b2b,
|
||||
0x1908190808190819, 0x1908190808191908, 0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808,
|
||||
0x19081908082b082b, 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908,
|
||||
0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b, 0x1908190819191919,
|
||||
0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908, 0x190819082b080808, 0x190819082b08082b,
|
||||
0x190819082b081919, 0x190819082b082b08, 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808,
|
||||
0x1908191908080819, 0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808,
|
||||
0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819, 0x19081919082b1908,
|
||||
0x1908191919080808, 0x190819191908082b, 0x1908191919081919, 0x1908191919082b08, 0x1908191919190819,
|
||||
0x1908191919191908, 0x19081919192b0808, 0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908,
|
||||
0x190819192b190808, 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08,
|
||||
0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819, 0x1908192b19081908,
|
||||
0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919, 0x19082b0808080819, 0x19082b0808081908,
|
||||
0x19082b0808082b19, 0x19082b0808190808, 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08,
|
||||
0x19082b08082b0819, 0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919,
|
||||
0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808, 0x19082b082b081908,
|
||||
0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b, 0x19082b1908081919, 0x19082b1908082b08,
|
||||
0x19082b1908190819, 0x19082b1908191908, 0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908,
|
||||
0x19082b1919190808, 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908,
|
||||
0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b, 0x1919080808081919,
|
||||
0x1919080808082b08, 0x1919080808190819, 0x1919080808191908, 0x191908080819192b, 0x1919080808192b19,
|
||||
0x19190808082b0808, 0x19190808082b082b, 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819,
|
||||
0x1919080819081908, 0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b,
|
||||
0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908, 0x191908082b080808,
|
||||
0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08, 0x191908082b190819, 0x191908082b191908,
|
||||
0x1919081908080819, 0x1919081908081908, 0x191908190808192b, 0x1919081908082b19, 0x1919081908190808,
|
||||
0x191908190819082b, 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908,
|
||||
0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08, 0x1919081919190819,
|
||||
0x1919081919191908, 0x19190819192b0808, 0x191908192b080819, 0x191908192b081908, 0x191908192b190808,
|
||||
0x1919082b08080808, 0x1919082b08081919, 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908,
|
||||
0x1919082b082b0808, 0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19,
|
||||
0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b, 0x1919190808082b19,
|
||||
0x1919190808190808, 0x191919080819082b, 0x1919190808191919, 0x1919190808192b08, 0x19191908082b0819,
|
||||
0x19191908082b1908, 0x1919190819080808, 0x191919081908082b, 0x1919190819081919, 0x1919190819082b08,
|
||||
0x1919190819190819, 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908,
|
||||
0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919, 0x1919191908082b08,
|
||||
0x1919191908190819, 0x1919191908191908, 0x19191919082b0808, 0x1919191919080819, 0x1919191919081908,
|
||||
0x1919191919190808, 0x191919192b080808, 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808,
|
||||
0x1919192b082b192b, 0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919,
|
||||
0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808, 0x19192b0819080819,
|
||||
0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b, 0x19192b082b080808, 0x19192b1908080819,
|
||||
0x19192b1908081908, 0x19192b1908190808, 0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19,
|
||||
0x19192b2b2b081919, 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b,
|
||||
0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08, 0x192b0808082b0819,
|
||||
0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919, 0x192b080819082b08, 0x192b080819190819,
|
||||
0x192b080819191908, 0x192b0808192b0808, 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808,
|
||||
0x192b08190808082b, 0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908,
|
||||
0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808, 0x192b08192b080808,
|
||||
0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808, 0x192b082b19080808, 0x192b082b1919192b,
|
||||
0x192b082b2b2b0819, 0x192b190808080808, 0x192b190808081919, 0x192b190808082b08, 0x192b190808190819,
|
||||
0x192b190808191908, 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808,
|
||||
0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808, 0x192b191919080808,
|
||||
0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b, 0x192b192b08080808, 0x192b192b2b191908,
|
||||
0x192b2b0808080819, 0x192b2b0808081908, 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08,
|
||||
0x192b2b1908080808, 0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808,
|
||||
0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, 0x2b08080808191908,
|
||||
0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919, 0x2b08080819080819, 0x2b08080819081908,
|
||||
0x2b08080819190808, 0x2b0808081919082b, 0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819,
|
||||
0x2b0808082b080808, 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819,
|
||||
0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b, 0x2b08081908191919,
|
||||
0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908, 0x2b08081919080808, 0x2b0808191908082b,
|
||||
0x2b08081919081919, 0x2b08081919082b08, 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819,
|
||||
0x2b0808192b081908, 0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919,
|
||||
0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819, 0x2b08082b19081908,
|
||||
0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908, 0x2b0819080808192b, 0x2b08190808082b19,
|
||||
0x2b08190808190808, 0x2b0819080819082b, 0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819,
|
||||
0x2b08190819080808, 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819,
|
||||
0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908, 0x2b0819082b190808,
|
||||
0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919, 0x2b08191908082b08, 0x2b08191908190819,
|
||||
0x2b08191908191908, 0x2b081919082b0808, 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808,
|
||||
0x2b0819192b080808, 0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808,
|
||||
0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919, 0x2b082b0808190819,
|
||||
0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908, 0x2b082b0819190808, 0x2b082b082b2b082b,
|
||||
0x2b082b1908080819, 0x2b082b1908081908, 0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b,
|
||||
0x2b082b2b19192b08, 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819,
|
||||
0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b, 0x2b19080808191919,
|
||||
0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908081908082b, 0x2b19080819081919,
|
||||
0x2b19080819082b08, 0x2b19080819190819, 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819,
|
||||
0x2b1908082b081908, 0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819,
|
||||
0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808, 0x2b19081919192b2b,
|
||||
0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808, 0x2b19082b19080808, 0x2b19082b2b2b192b,
|
||||
0x2b19190808080808, 0x2b1919080808082b, 0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819,
|
||||
0x2b19190808191908, 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808,
|
||||
0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908, 0x2b19191908190808,
|
||||
0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819, 0x2b19192b08080808, 0x2b19192b1908192b,
|
||||
0x2b19192b192b1908, 0x2b192b0808080819, 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b,
|
||||
0x2b192b0819080808, 0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b,
|
||||
0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b, 0x2b2b080808191908,
|
||||
0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819, 0x2b2b080819081908, 0x2b2b080819190808,
|
||||
0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b, 0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b,
|
||||
0x2b2b082b08082b2b, 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b,
|
||||
0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819, 0x2b2b190808081908,
|
||||
0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19, 0x2b2b19082b2b1908, 0x2b2b191908080808,
|
||||
0x2b2b191908192b19, 0x2b2b192b19190819, 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b,
|
||||
0x2b2b2b1919191908, 0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808,
|
||||
0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b,
|
||||
];
|
||||
@@ -66,31 +66,274 @@ fn k4(x: &[u8], j: usize) -> (i32, i32) {
|
||||
(((x[j + 4] & 15) | ((x[j - 4] >> 6) << 4)) as i32, ((x[j + 4] >> 4) | ((x[j] >> 6) << 4)) as i32)
|
||||
}
|
||||
}
|
||||
mod iq_blocks;
|
||||
mod k_blocks;
|
||||
mod legacy_blocks;
|
||||
fn dequantize_block(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::F32 | Kind::F16 | Kind::Bf16 => legacy_blocks::dequant_float(kind, x, y),
|
||||
Kind::Q1Zero | Kind::Q2Zero | Kind::Q4Zero | Kind::Q4One | Kind::Q5Zero | Kind::Q5One | Kind::Q8Zero => {
|
||||
legacy_blocks::dequant_legacy(kind, x, y)
|
||||
}
|
||||
Kind::MxFp4 | Kind::NvFp4 => legacy_blocks::dequant_fp4(kind, x, y),
|
||||
Kind::Q2K | Kind::Q3K | Kind::Q4K | Kind::Q5K | Kind::Q6K => k_blocks::dequant_k(kind, x, y),
|
||||
Kind::Iq2Xxs | Kind::Iq2Xs | Kind::Iq2S => iq_blocks::dequant_iq2(kind, x, y),
|
||||
Kind::Iq3Xxs | Kind::Iq3S => iq_blocks::dequant_iq3(kind, x, y),
|
||||
Kind::Iq1S | Kind::Iq1M => iq_blocks::dequant_iq1(kind, x, y),
|
||||
Kind::Iq4Nl | Kind::Iq4Xs => iq_blocks::dequant_iq4(kind, x, y),
|
||||
Kind::Tq1 | Kind::Tq2 => legacy_blocks::dequant_ternary(kind, x, y),
|
||||
}
|
||||
}
|
||||
pub fn dequantize(kind: Kind, raw: &[u8], output: &mut [f32]) -> Result<()> {
|
||||
if kind.row_bytes(output.len())? != raw.len() {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let (q, b) = kind.block();
|
||||
for (x, y) in raw.chunks_exact(b).zip(output.chunks_exact_mut(q)) {
|
||||
dequantize_block(kind, x, y);
|
||||
match kind {
|
||||
Kind::F32 => y[0] = f32::from_le_bytes(x.try_into().unwrap()),
|
||||
Kind::F16 => y[0] = h(x, 0),
|
||||
Kind::Bf16 => y[0] = f32::from_bits((u16at(x, 0) as u32) << 16),
|
||||
Kind::Q1Zero => {
|
||||
let d = h(x, 0);
|
||||
let negative = -d;
|
||||
for j in 0..128 {
|
||||
y[j] = if x[2 + j / 8] & (1 << (j % 8)) != 0 { d } else { negative };
|
||||
}
|
||||
}
|
||||
Kind::Q2Zero => {
|
||||
let d = h(x, 0);
|
||||
for j in 0..64 {
|
||||
y[j] = (((x[2 + j / 4] >> (2 * (j % 4))) & 3) as i32 - 1) as f32 * d;
|
||||
}
|
||||
}
|
||||
Kind::Q4Zero | Kind::Q4One | Kind::Q5Zero | Kind::Q5One | Kind::Q8Zero => {
|
||||
let d = h(x, 0);
|
||||
if kind == Kind::Q8Zero {
|
||||
for j in 0..32 {
|
||||
y[j] = x[j + 2] as i8 as f32 * d;
|
||||
}
|
||||
} else {
|
||||
let min = if matches!(kind, Kind::Q4One | Kind::Q5One) { h(x, 2) } else { 0.0 };
|
||||
let head = match kind {
|
||||
Kind::Q4Zero => 2,
|
||||
Kind::Q4One => 4,
|
||||
Kind::Q5Zero => 6,
|
||||
_ => 8,
|
||||
};
|
||||
let high = if matches!(kind, Kind::Q5Zero | Kind::Q5One) { u32at(x, head - 4) } else { 0 };
|
||||
for j in 0..16 {
|
||||
let low = x[head + j];
|
||||
let a = (low & 15) as i32 | ((((high >> j) & 1) as i32) << 4);
|
||||
let c = (low >> 4) as i32 | ((((high >> (j + 16)) & 1) as i32) << 4);
|
||||
if matches!(kind, Kind::Q4One | Kind::Q5One) {
|
||||
y[j] = a as f32 * d + min;
|
||||
y[j + 16] = c as f32 * d + min;
|
||||
} else {
|
||||
let center = if kind == Kind::Q4Zero { 8 } else { 16 };
|
||||
y[j] = (a - center) as f32 * d;
|
||||
y[j + 16] = (c - center) as f32 * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::MxFp4 => {
|
||||
let d = e8_half(x[0]);
|
||||
for j in 0..16 {
|
||||
y[j] = FP4[(x[1 + j] & 15) as usize] as f32 * d;
|
||||
y[j + 16] = FP4[(x[1 + j] >> 4) as usize] as f32 * d;
|
||||
}
|
||||
}
|
||||
Kind::NvFp4 => {
|
||||
for k in 0..4 {
|
||||
let d = ue4(x[k]);
|
||||
for j in 0..8 {
|
||||
let v = x[4 + k / 2 * 16 + j + k % 2 * 8];
|
||||
y[k * 16 + j] = FP4[(v & 15) as usize] as f32 * d;
|
||||
y[k * 16 + j + 8] = FP4[(v >> 4) as usize] as f32 * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Q2K => {
|
||||
let d = h(x, 80);
|
||||
let m = h(x, 82);
|
||||
for j in 0..256 {
|
||||
let sc = x[j / 16];
|
||||
let q = (x[16 + j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3;
|
||||
y[j] = (d * (sc & 15) as f32) * q as f32 - m * (sc >> 4) as f32;
|
||||
}
|
||||
}
|
||||
Kind::Q3K => {
|
||||
let d = h(x, 108);
|
||||
let sc = six(&x[96..108]);
|
||||
for j in 0..256 {
|
||||
let q = ((x[32 + j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3) as i32
|
||||
- if x[j % 32] & (1 << (j / 32)) != 0 { 0 } else { 4 };
|
||||
y[j] = (d * sc[j / 16] as f32) * q as f32;
|
||||
}
|
||||
}
|
||||
Kind::Q4K | Kind::Q5K => {
|
||||
let d = h(x, 0);
|
||||
let m = h(x, 2);
|
||||
let qstart = if kind == Kind::Q4K { 16 } else { 48 };
|
||||
for j in 0..256 {
|
||||
let k = j / 32;
|
||||
let (s, min) = k4(&x[4..16], k);
|
||||
let mut v = ((x[qstart + k / 2 * 32 + j % 32] >> (4 * (k % 2))) & 15) as i32;
|
||||
if kind == Kind::Q5K {
|
||||
v += (((x[16 + j % 32] >> k) & 1) as i32) << 4;
|
||||
}
|
||||
y[j] = (d * s as f32) * v as f32 - m * min as f32;
|
||||
}
|
||||
}
|
||||
Kind::Q6K => {
|
||||
let d = h(x, 208);
|
||||
for j in 0..256 {
|
||||
let k = j % 128 / 32;
|
||||
let v = ((x[j / 128 * 64 + if k % 2 == 1 { 32 } else { 0 } + j % 32]
|
||||
>> (if k >= 2 { 4 } else { 0 }))
|
||||
& 15)
|
||||
| (((x[128 + j / 128 * 32 + j % 32] >> (k * 2)) & 3) << 4);
|
||||
y[j] = d * x[192 + j / 16] as i8 as f32 * (v as i32 - 32) as f32;
|
||||
}
|
||||
}
|
||||
Kind::Iq2Xxs | Kind::Iq2Xs | Kind::Iq2S => {
|
||||
let d = h(x, 0);
|
||||
for group in 0..8 {
|
||||
let packed = if kind == Kind::Iq2Xxs { u32at(x, 2 + group * 8 + 4) } else { 0 };
|
||||
for l in 0..4 {
|
||||
let (db, grid, sign) = match kind {
|
||||
Kind::Iq2Xxs => (
|
||||
d * (0.5 + (packed >> 28) as f32) * 0.25,
|
||||
IQ2XXS_GRID[x[2 + group * 8 + l] as usize],
|
||||
KSIGNS_IQ2XS[((packed >> (7 * l)) & 127) as usize],
|
||||
),
|
||||
Kind::Iq2Xs => {
|
||||
let q = u16at(x, 2 + (group * 4 + l) * 2);
|
||||
(
|
||||
d * (0.5 + ((x[66 + group] >> (4 * (l / 2))) & 15) as f32) * 0.25,
|
||||
IQ2XS_GRID[(q & 511) as usize],
|
||||
KSIGNS_IQ2XS[(q >> 9) as usize],
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let index =
|
||||
x[2 + group * 4 + l] as usize | (((x[66 + group] as usize) << (8 - 2 * l)) & 0x300);
|
||||
(
|
||||
d * (0.5 + ((x[74 + group] >> (4 * (l / 2))) & 15) as f32) * 0.25,
|
||||
IQ2S_GRID[index],
|
||||
x[34 + group * 4 + l],
|
||||
)
|
||||
}
|
||||
};
|
||||
let grid = grid.to_le_bytes();
|
||||
for j in 0..8 {
|
||||
y[group * 32 + l * 8 + j] =
|
||||
db * grid[j] as f32 * if sign & (1 << j) != 0 { -1.0 } else { 1.0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Iq3Xxs | Kind::Iq3S => {
|
||||
let d = h(x, 0);
|
||||
for group in 0..8 {
|
||||
let packed = if kind == Kind::Iq3Xxs { u32at(x, 66 + group * 4) } else { 0 };
|
||||
let db = if kind == Kind::Iq3Xxs {
|
||||
d * (0.5 + (packed >> 28) as f32) * 0.5
|
||||
} else {
|
||||
d * (1 + 2 * ((x[106 + group / 2] >> (4 * (group % 2))) & 15)) as f32
|
||||
};
|
||||
for l in 0..4 {
|
||||
let sign = if kind == Kind::Iq3Xxs {
|
||||
KSIGNS_IQ2XS[((packed >> (7 * l)) & 127) as usize]
|
||||
} else {
|
||||
x[74 + group * 4 + l]
|
||||
};
|
||||
let g0 = if kind == Kind::Iq3Xxs {
|
||||
IQ3XXS_GRID[x[2 + group * 8 + l * 2] as usize]
|
||||
} else {
|
||||
IQ3S_GRID
|
||||
[x[2 + group * 8 + l * 2] as usize | (((x[66 + group] as usize) << (8 - 2 * l)) & 256)]
|
||||
};
|
||||
let g1 = if kind == Kind::Iq3Xxs {
|
||||
IQ3XXS_GRID[x[3 + group * 8 + l * 2] as usize]
|
||||
} else {
|
||||
IQ3S_GRID
|
||||
[x[3 + group * 8 + l * 2] as usize | (((x[66 + group] as usize) << (7 - 2 * l)) & 256)]
|
||||
};
|
||||
for (half, grid) in [g0, g1].into_iter().enumerate() {
|
||||
let grid = grid.to_le_bytes();
|
||||
for j in 0..4 {
|
||||
let at = half * 4 + j;
|
||||
y[group * 32 + l * 8 + at] =
|
||||
db * grid[j] as f32 * if sign & (1 << at) != 0 { -1.0 } else { 1.0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Iq1S | Kind::Iq1M => {
|
||||
let sc: [u16; 4] =
|
||||
if kind == Kind::Iq1M { std::array::from_fn(|j| u16at(x, 48 + j * 2)) } else { [0; 4] };
|
||||
let d = if kind == Kind::Iq1S {
|
||||
h(x, 0)
|
||||
} else {
|
||||
half((sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000))
|
||||
};
|
||||
for group in 0..8 {
|
||||
for l in 0..4 {
|
||||
let (index, delta, scale) = if kind == Kind::Iq1S {
|
||||
let hi = u16at(x, 34 + group * 2);
|
||||
(
|
||||
x[2 + group * 4 + l] as usize | ((((hi >> (3 * l)) & 7) as usize) << 8),
|
||||
if hi & 0x8000 != 0 { -0.125 } else { 0.125 },
|
||||
2 * ((hi >> 12) & 7) + 1,
|
||||
)
|
||||
} else {
|
||||
let hi = x[32 + group * 2 + l / 2];
|
||||
(
|
||||
x[group * 4 + l] as usize
|
||||
| (((hi as usize) << (if l % 2 == 0 { 8 } else { 4 })) & 0x700),
|
||||
if hi & (if l % 2 == 0 { 8 } else { 128 }) != 0 { -0.125 } else { 0.125 },
|
||||
2 * ((sc[group / 2] >> (6 * (group % 2) + 3 * (l / 2))) & 7) + 1,
|
||||
)
|
||||
};
|
||||
let grid = super::rust_iq1_grid::GRID[index].to_le_bytes();
|
||||
let dl = d * scale as f32;
|
||||
for j in 0..8 {
|
||||
y[group * 32 + l * 8 + j] = dl * (grid[j] as i8 as f32 + delta);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Iq4Nl => {
|
||||
let d = h(x, 0);
|
||||
for j in 0..16 {
|
||||
y[j] = d * KVALUES_IQ4NL[(x[2 + j] & 15) as usize] as f32;
|
||||
y[j + 16] = d * KVALUES_IQ4NL[(x[2 + j] >> 4) as usize] as f32;
|
||||
}
|
||||
}
|
||||
Kind::Iq4Xs => {
|
||||
let d = h(x, 0);
|
||||
let hi = u16at(x, 2);
|
||||
for k in 0..8 {
|
||||
let s = (((x[4 + k / 2] >> (4 * (k % 2))) & 15) as i32) | ((((hi >> (2 * k)) & 3) as i32) << 4);
|
||||
let dl = d * (s - 32) as f32;
|
||||
for j in 0..16 {
|
||||
y[k * 32 + j] = dl * KVALUES_IQ4NL[(x[8 + k * 16 + j] & 15) as usize] as f32;
|
||||
y[k * 32 + j + 16] = dl * KVALUES_IQ4NL[(x[8 + k * 16 + j] >> 4) as usize] as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Tq1 => {
|
||||
let d = h(x, 52);
|
||||
let powers = [1u8, 3, 9, 27, 81];
|
||||
for k in 0..5 {
|
||||
for j in 0..32 {
|
||||
y[k * 32 + j] = (((x[j].wrapping_mul(powers[k]) as u16 * 3) >> 8) as i16 - 1) as f32 * d;
|
||||
}
|
||||
for j in 0..16 {
|
||||
y[160 + k * 16 + j] =
|
||||
(((x[32 + j].wrapping_mul(powers[k]) as u16 * 3) >> 8) as i16 - 1) as f32 * d;
|
||||
}
|
||||
}
|
||||
for k in 0..4 {
|
||||
for j in 0..4 {
|
||||
y[240 + k * 4 + j] =
|
||||
(((x[48 + j].wrapping_mul(powers[k]) as u16 * 3) >> 8) as i16 - 1) as f32 * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Tq2 => {
|
||||
let d = h(x, 64);
|
||||
for j in 0..256 {
|
||||
let q = ((x[j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3) as i8;
|
||||
y[j] = (q - 1) as f32 * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
//! Block dequantizers of the IQ formats (grid-lookup 2/3/1-bit and the 4-bit non-linear ones).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Eight values of a sign-modulated 2-bit grid word: `db * grid byte`, negated for set sign bits.
|
||||
fn put_signed_grid(y: &mut [f32], at: usize, db: f32, (grid, sign): (u64, u8)) {
|
||||
let grid = grid.to_le_bytes();
|
||||
for j in 0..8 {
|
||||
y[at + j] = db * grid[j] as f32 * if sign & (1 << j) != 0 { -1.0 } else { 1.0 };
|
||||
}
|
||||
}
|
||||
fn dequant_iq2_xxs(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
for group in 0..8 {
|
||||
let packed = u32at(x, 2 + group * 8 + 4);
|
||||
for l in 0..4 {
|
||||
let db = d * (0.5 + (packed >> 28) as f32) * 0.25;
|
||||
let grid = IQ2XXS_GRID[x[2 + group * 8 + l] as usize];
|
||||
let sign = KSIGNS_IQ2XS[((packed >> (7 * l)) & 127) as usize];
|
||||
put_signed_grid(y, group * 32 + l * 8, db, (grid, sign));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn dequant_iq2_xs(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
for group in 0..8 {
|
||||
for l in 0..4 {
|
||||
let q = u16at(x, 2 + (group * 4 + l) * 2);
|
||||
let db = d * (0.5 + ((x[66 + group] >> (4 * (l / 2))) & 15) as f32) * 0.25;
|
||||
let grid = IQ2XS_GRID[(q & 511) as usize];
|
||||
let sign = KSIGNS_IQ2XS[(q >> 9) as usize];
|
||||
put_signed_grid(y, group * 32 + l * 8, db, (grid, sign));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn dequant_iq2_s(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
for group in 0..8 {
|
||||
for l in 0..4 {
|
||||
let index = x[2 + group * 4 + l] as usize | (((x[66 + group] as usize) << (8 - 2 * l)) & 0x300);
|
||||
let db = d * (0.5 + ((x[74 + group] >> (4 * (l / 2))) & 15) as f32) * 0.25;
|
||||
put_signed_grid(y, group * 32 + l * 8, db, (IQ2S_GRID[index], x[34 + group * 4 + l]));
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn dequant_iq2(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::Iq2Xxs => dequant_iq2_xxs(x, y),
|
||||
Kind::Iq2Xs => dequant_iq2_xs(x, y),
|
||||
_ => dequant_iq2_s(x, y),
|
||||
}
|
||||
}
|
||||
/// Eight values of two sign-modulated 3-bit grid words (four bytes each).
|
||||
fn put_signed_halves(y: &mut [f32], at: usize, db: f32, (g0, g1): (u32, u32), sign: u8) {
|
||||
for (half, grid) in [g0, g1].into_iter().enumerate() {
|
||||
let grid = grid.to_le_bytes();
|
||||
for (j, &byte) in grid.iter().enumerate() {
|
||||
let bit = half * 4 + j;
|
||||
y[at + bit] = db * byte as f32 * if sign & (1 << bit) != 0 { -1.0 } else { 1.0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
fn dequant_iq3_xxs(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
for group in 0..8 {
|
||||
let packed = u32at(x, 66 + group * 4);
|
||||
let db = d * (0.5 + (packed >> 28) as f32) * 0.5;
|
||||
for l in 0..4 {
|
||||
let sign = KSIGNS_IQ2XS[((packed >> (7 * l)) & 127) as usize];
|
||||
let g0 = IQ3XXS_GRID[x[2 + group * 8 + l * 2] as usize];
|
||||
let g1 = IQ3XXS_GRID[x[3 + group * 8 + l * 2] as usize];
|
||||
put_signed_halves(y, group * 32 + l * 8, db, (g0, g1), sign);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn dequant_iq3_s(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
for group in 0..8 {
|
||||
let db = d * (1 + 2 * ((x[106 + group / 2] >> (4 * (group % 2))) & 15)) as f32;
|
||||
for l in 0..4 {
|
||||
let sign = x[74 + group * 4 + l];
|
||||
let high = x[66 + group] as usize;
|
||||
let g0 = IQ3S_GRID[x[2 + group * 8 + l * 2] as usize | ((high << (8 - 2 * l)) & 256)];
|
||||
let g1 = IQ3S_GRID[x[3 + group * 8 + l * 2] as usize | ((high << (7 - 2 * l)) & 256)];
|
||||
put_signed_halves(y, group * 32 + l * 8, db, (g0, g1), sign);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn dequant_iq3(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::Iq3Xxs => dequant_iq3_xxs(x, y),
|
||||
_ => dequant_iq3_s(x, y),
|
||||
}
|
||||
}
|
||||
/// Eight values of an IQ1 grid word: `scale * d * (grid byte + delta)`.
|
||||
fn put_iq1_group(y: &mut [f32], at: usize, dl: f32, (index, delta): (usize, f32)) {
|
||||
let grid = super::super::rust_iq1_grid::GRID[index].to_le_bytes();
|
||||
for j in 0..8 {
|
||||
y[at + j] = dl * (grid[j] as i8 as f32 + delta);
|
||||
}
|
||||
}
|
||||
fn dequant_iq1_s(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
for group in 0..8 {
|
||||
for l in 0..4 {
|
||||
let hi = u16at(x, 34 + group * 2);
|
||||
let index = x[2 + group * 4 + l] as usize | ((((hi >> (3 * l)) & 7) as usize) << 8);
|
||||
let delta = if hi & 0x8000 != 0 { -0.125 } else { 0.125 };
|
||||
let scale = 2 * ((hi >> 12) & 7) + 1;
|
||||
put_iq1_group(y, group * 32 + l * 8, d * scale as f32, (index, delta));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn dequant_iq1_m(x: &[u8], y: &mut [f32]) {
|
||||
let sc: [u16; 4] = std::array::from_fn(|j| u16at(x, 48 + j * 2));
|
||||
let d = half((sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000));
|
||||
for group in 0..8 {
|
||||
for l in 0..4 {
|
||||
let hi = x[32 + group * 2 + l / 2];
|
||||
let index = x[group * 4 + l] as usize | (((hi as usize) << (if l % 2 == 0 { 8 } else { 4 })) & 0x700);
|
||||
let delta = if hi & (if l % 2 == 0 { 8 } else { 128 }) != 0 { -0.125 } else { 0.125 };
|
||||
let scale = 2 * ((sc[group / 2] >> (6 * (group % 2) + 3 * (l / 2))) & 7) + 1;
|
||||
put_iq1_group(y, group * 32 + l * 8, d * scale as f32, (index, delta));
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn dequant_iq1(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::Iq1S => dequant_iq1_s(x, y),
|
||||
_ => dequant_iq1_m(x, y),
|
||||
}
|
||||
}
|
||||
fn dequant_iq4_nl(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
for j in 0..16 {
|
||||
y[j] = d * KVALUES_IQ4NL[(x[2 + j] & 15) as usize] as f32;
|
||||
y[j + 16] = d * KVALUES_IQ4NL[(x[2 + j] >> 4) as usize] as f32;
|
||||
}
|
||||
}
|
||||
fn dequant_iq4_xs(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
let hi = u16at(x, 2);
|
||||
for k in 0..8 {
|
||||
let s = (((x[4 + k / 2] >> (4 * (k % 2))) & 15) as i32) | ((((hi >> (2 * k)) & 3) as i32) << 4);
|
||||
let dl = d * (s - 32) as f32;
|
||||
for j in 0..16 {
|
||||
y[k * 32 + j] = dl * KVALUES_IQ4NL[(x[8 + k * 16 + j] & 15) as usize] as f32;
|
||||
y[k * 32 + j + 16] = dl * KVALUES_IQ4NL[(x[8 + k * 16 + j] >> 4) as usize] as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn dequant_iq4(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::Iq4Nl => dequant_iq4_nl(x, y),
|
||||
_ => dequant_iq4_xs(x, y),
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
//! Block dequantizers of the 256-element K formats (Q2_K to Q6_K).
|
||||
|
||||
use super::*;
|
||||
|
||||
fn dequant_q2k(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 80);
|
||||
let m = h(x, 82);
|
||||
for j in 0..256 {
|
||||
let sc = x[j / 16];
|
||||
let q = (x[16 + j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3;
|
||||
y[j] = (d * (sc & 15) as f32) * q as f32 - m * (sc >> 4) as f32;
|
||||
}
|
||||
}
|
||||
fn dequant_q3k(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 108);
|
||||
let sc = six(&x[96..108]);
|
||||
for j in 0..256 {
|
||||
let q = ((x[32 + j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3) as i32
|
||||
- if x[j % 32] & (1 << (j / 32)) != 0 { 0 } else { 4 };
|
||||
y[j] = (d * sc[j / 16] as f32) * q as f32;
|
||||
}
|
||||
}
|
||||
fn dequant_q45k(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
let m = h(x, 2);
|
||||
let qstart = if kind == Kind::Q4K { 16 } else { 48 };
|
||||
for j in 0..256 {
|
||||
let k = j / 32;
|
||||
let (s, min) = k4(&x[4..16], k);
|
||||
let mut v = ((x[qstart + k / 2 * 32 + j % 32] >> (4 * (k % 2))) & 15) as i32;
|
||||
if kind == Kind::Q5K {
|
||||
v += (((x[16 + j % 32] >> k) & 1) as i32) << 4;
|
||||
}
|
||||
y[j] = (d * s as f32) * v as f32 - m * min as f32;
|
||||
}
|
||||
}
|
||||
fn dequant_q6k(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 208);
|
||||
for j in 0..256 {
|
||||
let k = j % 128 / 32;
|
||||
let low = (x[j / 128 * 64 + if k % 2 == 1 { 32 } else { 0 } + j % 32] >> (if k >= 2 { 4 } else { 0 })) & 15;
|
||||
let v = low | (((x[128 + j / 128 * 32 + j % 32] >> (k * 2)) & 3) << 4);
|
||||
y[j] = d * x[192 + j / 16] as i8 as f32 * (v as i32 - 32) as f32;
|
||||
}
|
||||
}
|
||||
pub(super) fn dequant_k(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::Q2K => dequant_q2k(x, y),
|
||||
Kind::Q3K => dequant_q3k(x, y),
|
||||
Kind::Q4K | Kind::Q5K => dequant_q45k(kind, x, y),
|
||||
_ => dequant_q6k(x, y),
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
//! Block dequantizers of the float, legacy 32-element, FP4 and ternary formats.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn dequant_float(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::F32 => y[0] = f32::from_le_bytes(x.try_into().unwrap()),
|
||||
Kind::F16 => y[0] = h(x, 0),
|
||||
_ => y[0] = f32::from_bits((u16at(x, 0) as u32) << 16),
|
||||
}
|
||||
}
|
||||
fn dequant_q1(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
let negative = -d;
|
||||
for j in 0..128 {
|
||||
y[j] = if x[2 + j / 8] & (1 << (j % 8)) != 0 { d } else { negative };
|
||||
}
|
||||
}
|
||||
fn dequant_q2(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
for j in 0..64 {
|
||||
y[j] = (((x[2 + j / 4] >> (2 * (j % 4))) & 3) as i32 - 1) as f32 * d;
|
||||
}
|
||||
}
|
||||
fn dequant_q8(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
for j in 0..32 {
|
||||
y[j] = x[j + 2] as i8 as f32 * d;
|
||||
}
|
||||
}
|
||||
/// Q4_0, Q4_1, Q5_0 and Q5_1: 16 packed bytes of low nibbles, plus a 32-bit word of high bits for the 5-bit formats.
|
||||
fn dequant_q45(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 0);
|
||||
let min = if matches!(kind, Kind::Q4One | Kind::Q5One) { h(x, 2) } else { 0.0 };
|
||||
let head = match kind {
|
||||
Kind::Q4Zero => 2,
|
||||
Kind::Q4One => 4,
|
||||
Kind::Q5Zero => 6,
|
||||
_ => 8,
|
||||
};
|
||||
let high = if matches!(kind, Kind::Q5Zero | Kind::Q5One) { u32at(x, head - 4) } else { 0 };
|
||||
for j in 0..16 {
|
||||
let low = x[head + j];
|
||||
let a = (low & 15) as i32 | ((((high >> j) & 1) as i32) << 4);
|
||||
let c = (low >> 4) as i32 | ((((high >> (j + 16)) & 1) as i32) << 4);
|
||||
if matches!(kind, Kind::Q4One | Kind::Q5One) {
|
||||
y[j] = a as f32 * d + min;
|
||||
y[j + 16] = c as f32 * d + min;
|
||||
} else {
|
||||
let center = if kind == Kind::Q4Zero { 8 } else { 16 };
|
||||
y[j] = (a - center) as f32 * d;
|
||||
y[j + 16] = (c - center) as f32 * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn dequant_legacy(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::Q1Zero => dequant_q1(x, y),
|
||||
Kind::Q2Zero => dequant_q2(x, y),
|
||||
Kind::Q8Zero => dequant_q8(x, y),
|
||||
_ => dequant_q45(kind, x, y),
|
||||
}
|
||||
}
|
||||
fn dequant_mxfp4(x: &[u8], y: &mut [f32]) {
|
||||
let d = e8_half(x[0]);
|
||||
for j in 0..16 {
|
||||
y[j] = FP4[(x[1 + j] & 15) as usize] as f32 * d;
|
||||
y[j + 16] = FP4[(x[1 + j] >> 4) as usize] as f32 * d;
|
||||
}
|
||||
}
|
||||
fn dequant_nvfp4(x: &[u8], y: &mut [f32]) {
|
||||
for k in 0..4 {
|
||||
let d = ue4(x[k]);
|
||||
for j in 0..8 {
|
||||
let v = x[4 + k / 2 * 16 + j + k % 2 * 8];
|
||||
y[k * 16 + j] = FP4[(v & 15) as usize] as f32 * d;
|
||||
y[k * 16 + j + 8] = FP4[(v >> 4) as usize] as f32 * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn dequant_fp4(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::MxFp4 => dequant_mxfp4(x, y),
|
||||
_ => dequant_nvfp4(x, y),
|
||||
}
|
||||
}
|
||||
/// One ternary value of TQ1_0: the base-3 digit selected by `power` of byte `byte`.
|
||||
fn trit(byte: u8, power: u8) -> i16 {
|
||||
((byte.wrapping_mul(power) as u16 * 3) >> 8) as i16 - 1
|
||||
}
|
||||
fn dequant_tq1(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 52);
|
||||
let powers = [1u8, 3, 9, 27, 81];
|
||||
for k in 0..5 {
|
||||
for j in 0..32 {
|
||||
y[k * 32 + j] = trit(x[j], powers[k]) as f32 * d;
|
||||
}
|
||||
for j in 0..16 {
|
||||
y[160 + k * 16 + j] = trit(x[32 + j], powers[k]) as f32 * d;
|
||||
}
|
||||
}
|
||||
for k in 0..4 {
|
||||
for j in 0..4 {
|
||||
y[240 + k * 4 + j] = trit(x[48 + j], powers[k]) as f32 * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn dequant_tq2(x: &[u8], y: &mut [f32]) {
|
||||
let d = h(x, 64);
|
||||
for j in 0..256 {
|
||||
let q = ((x[j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3) as i8;
|
||||
y[j] = (q - 1) as f32 * d;
|
||||
}
|
||||
}
|
||||
pub(super) fn dequant_ternary(kind: Kind, x: &[u8], y: &mut [f32]) {
|
||||
match kind {
|
||||
Kind::Tq1 => dequant_tq1(x, y),
|
||||
_ => dequant_tq2(x, y),
|
||||
}
|
||||
}
|
||||
@@ -64,41 +64,23 @@ impl ExpertLayout {
|
||||
Self::parse(data, n_layers, n_expert)
|
||||
}
|
||||
pub fn parse(data: &str, n_layers: usize, n_expert: i64) -> Result<Self> {
|
||||
let (mut l, mut fmt) = Self::blank_native(n_layers, n_expert)?;
|
||||
l.record_lines(data, n_layers, &mut fmt)?;
|
||||
l.finish(n_layers, fmt)
|
||||
}
|
||||
/// A native layout with no layer read yet, and the (still empty) per-layer formats.
|
||||
fn blank_native(n_layers: usize, n_expert: i64) -> Result<(Self, Vec<Option<NativeFormat>>)> {
|
||||
let mut l = Self::canonical(n_layers, n_expert);
|
||||
l.native = true;
|
||||
l.max_blob = 0;
|
||||
let fmt = filled(n_layers, None)?;
|
||||
let mut fmt: Vec<Option<NativeFormat>> = filled(n_layers, None)?;
|
||||
l.offset = filled(n_layers, u64::MAX)?;
|
||||
l.bytes = filled(n_layers, 0)?;
|
||||
Ok((l, fmt))
|
||||
}
|
||||
fn record_lines(&mut self, data: &str, n_layers: usize, fmt: &mut [Option<NativeFormat>]) -> Result<()> {
|
||||
for line in data.split('\n') {
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
self.record_comment(line)?;
|
||||
l.comment_line(line)?;
|
||||
continue;
|
||||
}
|
||||
self.record_line(line, n_layers, fmt)?;
|
||||
l.record_line(line, n_layers, &mut fmt)?;
|
||||
}
|
||||
Ok(())
|
||||
l.finish(n_layers, fmt)
|
||||
}
|
||||
/// Checks the layers are contiguous, sets the total and moves the per-layer formats in.
|
||||
fn finish(mut self, n_layers: usize, fmt: Vec<Option<NativeFormat>>) -> Result<Self> {
|
||||
self.total = self.verify_offsets(n_layers)?;
|
||||
self.format.try_reserve_exact(n_layers).map_err(|_| Error::Allocation)?;
|
||||
for f in fmt {
|
||||
self.format.push(f.ok_or(Error::Shape)?);
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
/// Reads the version and expert-count headers of a comment (or empty) line.
|
||||
fn record_comment(&mut self, line: &str) -> Result<()> {
|
||||
/// A `#` comment line: the version header (`# strata native experts vN`) and the `(n_expert N)` count.
|
||||
fn comment_line(&mut self, line: &str) -> Result<()> {
|
||||
if let Some(v) = line.strip_prefix("# strata native experts v") {
|
||||
self.version = super::rust_simd::atoi(v);
|
||||
if self.version > 4 {
|
||||
@@ -110,19 +92,41 @@ impl ExpertLayout {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Reads one layer line: the fixed fields, the optional GGUF extras, then stores the layer.
|
||||
/// The five leading fields of a layer record: `layer gu down offset bytes`.
|
||||
fn record_head(fields: &mut DecimalStream<'_>) -> Result<(i64, i64, i64, u64, u64)> {
|
||||
let layer = fields.signed().ok_or(Error::Shape)?;
|
||||
let gu = fields.signed().ok_or(Error::Shape)?;
|
||||
let down = fields.signed().ok_or(Error::Shape)?;
|
||||
let offset = fields.unsigned().ok_or(Error::Shape)?;
|
||||
let bytes = fields.unsigned().ok_or(Error::Shape)?;
|
||||
Ok((layer, gu, down, offset, bytes))
|
||||
}
|
||||
/// The native format named by a record's kinds; its size must equal the record's `bytes`.
|
||||
fn record_format(gu: i64, down: i64, bytes: u64) -> Result<NativeFormat> {
|
||||
let f = NativeFormat::new(Kind::from_original(gu as i32)?, Kind::from_original(down as i32)?, H, FF)?;
|
||||
if f.bytes as u64 != bytes {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
/// One layer record: `layer gu down offset bytes [gguf offsets [file]]`.
|
||||
fn record_line(&mut self, line: &str, n_layers: usize, fmt: &mut [Option<NativeFormat>]) -> Result<()> {
|
||||
let mut fields = DecimalStream::new(line);
|
||||
let row = read_layer_fields(&mut fields, n_layers)?;
|
||||
self.record_gguf_extras(&mut fields, row.layer, n_layers)?;
|
||||
fmt[row.layer] = Some(row.format);
|
||||
self.offset[row.layer] = row.offset;
|
||||
self.bytes[row.layer] = row.bytes;
|
||||
self.max_blob = self.max_blob.max(row.bytes);
|
||||
let (layer, gu, down, offset, bytes) = Self::record_head(&mut fields)?;
|
||||
if layer < 0 || layer as usize >= n_layers {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let f = Self::record_format(gu, down, bytes)?;
|
||||
let layer = layer as usize;
|
||||
self.gguf_fields(&mut fields, layer, n_layers)?;
|
||||
fmt[layer] = Some(f);
|
||||
self.offset[layer] = offset;
|
||||
self.bytes[layer] = bytes;
|
||||
self.max_blob = self.max_blob.max(bytes);
|
||||
Ok(())
|
||||
}
|
||||
/// Reads the three GGUF offsets and the optional file name(s) that may follow the fixed fields.
|
||||
fn record_gguf_extras(&mut self, fields: &mut DecimalStream, layer: usize, n_layers: usize) -> Result<()> {
|
||||
/// The optional trailing three GGUF offsets (and file name or three names) of a layer record.
|
||||
fn gguf_fields(&mut self, fields: &mut DecimalStream<'_>, layer: usize, n_layers: usize) -> Result<()> {
|
||||
let a = fields.unsigned();
|
||||
let b = fields.unsigned();
|
||||
let c = fields.unsigned();
|
||||
@@ -132,18 +136,12 @@ impl ExpertLayout {
|
||||
}
|
||||
self.gguf_offset[layer * 3..layer * 3 + 3].copy_from_slice(&[a, b, c]);
|
||||
match fields.word() {
|
||||
Some(file) => self.record_gguf_files(file, fields, layer, n_layers),
|
||||
Some(file) => self.gguf_names(fields, file, layer, n_layers),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
/// Stores the one (shared) or three (gate, up, down) GGUF file names of a layer.
|
||||
fn record_gguf_files(
|
||||
&mut self,
|
||||
file: &str,
|
||||
fields: &mut DecimalStream,
|
||||
layer: usize,
|
||||
n_layers: usize,
|
||||
) -> Result<()> {
|
||||
/// The GGUF file name of a layer record: one name for all three matrices or three comma-separated names.
|
||||
fn gguf_names(&mut self, fields: &mut DecimalStream<'_>, file: &str, layer: usize, n_layers: usize) -> Result<()> {
|
||||
let parts: Vec<&str> = file.split(',').collect();
|
||||
if (parts.len() != 1 && parts.len() != 3) || fields.word().is_some() {
|
||||
return Err(Error::Shape);
|
||||
@@ -156,8 +154,8 @@ impl ExpertLayout {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The layers must follow each other without gaps; returns the end of the last one.
|
||||
fn verify_offsets(&self, n_layers: usize) -> Result<u64> {
|
||||
/// Check the layer offsets are contiguous, total them and move the per-layer formats in.
|
||||
fn finish(mut self, n_layers: usize, fmt: Vec<Option<NativeFormat>>) -> Result<Self> {
|
||||
let mut at = 0u64;
|
||||
for i in 0..n_layers {
|
||||
if self.offset[i] != at {
|
||||
@@ -165,44 +163,14 @@ impl ExpertLayout {
|
||||
}
|
||||
at = at.wrapping_add(self.bytes[i].wrapping_mul(self.n_expert as u64));
|
||||
}
|
||||
Ok(at)
|
||||
self.total = at;
|
||||
self.format.try_reserve_exact(n_layers).map_err(|_| Error::Allocation)?;
|
||||
for f in fmt {
|
||||
self.format.push(f.ok_or(Error::Shape)?);
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
/// The fixed fields of one layer line.
|
||||
struct LayerFields {
|
||||
layer: usize,
|
||||
offset: u64,
|
||||
bytes: u64,
|
||||
format: NativeFormat,
|
||||
}
|
||||
/// The five numbers that start a layer line.
|
||||
struct RawFields {
|
||||
layer: i64,
|
||||
gu: i64,
|
||||
down: i64,
|
||||
offset: u64,
|
||||
bytes: u64,
|
||||
}
|
||||
fn read_raw_fields(fields: &mut DecimalStream) -> Result<RawFields> {
|
||||
let layer = fields.signed().ok_or(Error::Shape)?;
|
||||
let gu = fields.signed().ok_or(Error::Shape)?;
|
||||
let down = fields.signed().ok_or(Error::Shape)?;
|
||||
let offset = fields.unsigned().ok_or(Error::Shape)?;
|
||||
let bytes = fields.unsigned().ok_or(Error::Shape)?;
|
||||
Ok(RawFields { layer, gu, down, offset, bytes })
|
||||
}
|
||||
fn read_layer_fields(fields: &mut DecimalStream, n_layers: usize) -> Result<LayerFields> {
|
||||
let raw = read_raw_fields(fields)?;
|
||||
if raw.layer < 0 || raw.layer as usize >= n_layers {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let (gu, down) = (Kind::from_original(raw.gu as i32)?, Kind::from_original(raw.down as i32)?);
|
||||
let format = NativeFormat::new(gu, down, H, FF)?;
|
||||
if format.bytes as u64 != raw.bytes {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok(LayerFields { layer: raw.layer as usize, offset: raw.offset, bytes: raw.bytes, format })
|
||||
}
|
||||
fn filled<T: Clone>(n: usize, value: T) -> Result<Vec<T>> {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(n).map_err(|_| Error::Allocation)?;
|
||||
@@ -243,35 +211,29 @@ pub fn expert_layout() -> ExpertLayout {
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.clone()
|
||||
}
|
||||
/// The 48 brand-string bytes of CPUID leaves 0x80000002..=4, or `None` when the CPU does not report them.
|
||||
fn cpuid_brand() -> Option<[u8; 48]> {
|
||||
// SAFETY: CPUID is architectural on x86_64; leaves 0x80000002..=4 are queried only after leaf 0x80000000
|
||||
// reported them.
|
||||
pub fn cpu_name() -> String {
|
||||
// SAFETY: CPUID is architectural on x86_64; leaves 0x80000002..=4 are queried only after leaf 0x80000000 reported
|
||||
// them.
|
||||
unsafe {
|
||||
use std::arch::x86_64::__cpuid;
|
||||
if __cpuid(0x80000000).eax < 0x80000004 {
|
||||
return None;
|
||||
return "unknown".into();
|
||||
}
|
||||
let mut bytes = [0u8; 48];
|
||||
for i in 0..3 {
|
||||
let q = __cpuid(0x80000002 + i);
|
||||
for (j, v) in [q.eax, q.ebx, q.ecx, q.edx].into_iter().enumerate() {
|
||||
let at = (i as usize) * 16 + j * 4;
|
||||
bytes[at..at + 4].copy_from_slice(&v.to_le_bytes());
|
||||
bytes[(i as usize) * 16 + j * 4..(i as usize) * 16 + j * 4 + 4].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
Some(bytes)
|
||||
let end = bytes.iter().position(|&x| x == 0).unwrap_or(48);
|
||||
{
|
||||
let name = String::from_utf8_lossy(&bytes[..end]);
|
||||
let trimmed = name.trim_matches(' ');
|
||||
if trimmed.is_empty() { "unknown".to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn cpu_name() -> String {
|
||||
let Some(bytes) = cpuid_brand() else {
|
||||
return "unknown".into();
|
||||
};
|
||||
let end = bytes.iter().position(|&x| x == 0).unwrap_or(48);
|
||||
let name = String::from_utf8_lossy(&bytes[..end]);
|
||||
let trimmed = name.trim_matches(' ');
|
||||
if trimmed.is_empty() { "unknown".to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
// Decimal istringstream extraction: consume prefixes, preserve optional failure,
|
||||
// and allow the standard unsigned negation rather than parsing whole tokens.
|
||||
@@ -284,43 +246,40 @@ impl<'a> DecimalStream<'a> {
|
||||
fn new(text: &'a str) -> Self {
|
||||
Self { text, at: 0, failed: false }
|
||||
}
|
||||
fn skip_whitespace(&mut self) {
|
||||
fn skip_space(&mut self) {
|
||||
let b = self.text.as_bytes();
|
||||
while self.at < b.len() && b[self.at].is_ascii_whitespace() {
|
||||
self.at += 1;
|
||||
}
|
||||
}
|
||||
/// Consumes an optional `+` or `-`; true for `-`.
|
||||
fn take_sign(&mut self) -> bool {
|
||||
/// Consume decimal digits; `None` once the value overflows `u64` (the digits are still consumed).
|
||||
fn digits(&mut self) -> Option<u64> {
|
||||
let b = self.text.as_bytes();
|
||||
if self.at < b.len() && matches!(b[self.at], b'+' | b'-') {
|
||||
self.at += 1;
|
||||
return b[self.at - 1] == b'-';
|
||||
}
|
||||
false
|
||||
}
|
||||
/// Consumes a run of digits; `None` when there is none or the value overflows (the run is consumed either way).
|
||||
fn take_digits(&mut self) -> Option<u64> {
|
||||
let b = self.text.as_bytes();
|
||||
let start = self.at;
|
||||
let mut n = Some(0u64);
|
||||
while self.at < b.len() && b[self.at].is_ascii_digit() {
|
||||
n = n.and_then(|n| n.checked_mul(10)?.checked_add((b[self.at] - b'0') as u64));
|
||||
self.at += 1;
|
||||
}
|
||||
if self.at == start { None } else { n }
|
||||
n
|
||||
}
|
||||
fn number(&mut self) -> Option<(bool, u64)> {
|
||||
if self.failed {
|
||||
return None;
|
||||
}
|
||||
self.skip_whitespace();
|
||||
let neg = self.take_sign();
|
||||
let Some(n) = self.take_digits() else {
|
||||
self.skip_space();
|
||||
let b = self.text.as_bytes();
|
||||
let mut neg = false;
|
||||
if self.at < b.len() && matches!(b[self.at], b'+' | b'-') {
|
||||
neg = b[self.at] == b'-';
|
||||
self.at += 1;
|
||||
}
|
||||
let start = self.at;
|
||||
let n = self.digits();
|
||||
if self.at == start || n.is_none() {
|
||||
self.failed = true;
|
||||
return None;
|
||||
};
|
||||
Some((neg, n))
|
||||
}
|
||||
Some((neg, n.unwrap()))
|
||||
}
|
||||
fn signed(&mut self) -> Option<i64> {
|
||||
let (neg, n) = self.number()?;
|
||||
@@ -339,7 +298,7 @@ impl<'a> DecimalStream<'a> {
|
||||
if self.failed {
|
||||
return None;
|
||||
}
|
||||
self.skip_whitespace();
|
||||
self.skip_space();
|
||||
let b = self.text.as_bytes();
|
||||
let start = self.at;
|
||||
while self.at < b.len() && !b[self.at].is_ascii_whitespace() {
|
||||
|
||||
@@ -109,7 +109,7 @@ pub struct ExpertPool {
|
||||
phase: [f64; 3],
|
||||
}
|
||||
|
||||
mod execute_rows;
|
||||
mod exec;
|
||||
mod impl_default_for_job;
|
||||
#[allow(unused_imports)]
|
||||
use impl_default_for_job::alloc_with;
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
//! STRA-338 size4: the body of `Shared::execute`, split by mode (whole expert, legacy planar spans, native rows).
|
||||
|
||||
use super::super::rust_ggml::Kind;
|
||||
use super::super::rust_types::ActQ;
|
||||
use super::super::{rust_legacy, rust_native_general, rust_q2, rust_simd};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// One claimed row interval of one expert of the published batch.
|
||||
struct Span<'a> {
|
||||
b: &'a Batch,
|
||||
j: Job,
|
||||
s: *mut Split,
|
||||
ff_ptr: *mut f32,
|
||||
a2_ptr: *const PlanarActivation,
|
||||
blob: &'a [u8],
|
||||
n: usize,
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
}
|
||||
|
||||
/// First and one-past-last row (or whole-expert unit) of task `i`.
|
||||
fn task_range(b: &Batch, i: usize, per: usize) -> (usize, usize) {
|
||||
if b.mode <= 2 {
|
||||
let e = i / b.parts;
|
||||
let p = i % b.parts;
|
||||
(e * per + per * p / b.parts, e * per + per * (p + 1) / b.parts)
|
||||
} else {
|
||||
(b.rows * i / b.tasks, b.rows * (i + 1) / b.tasks)
|
||||
}
|
||||
}
|
||||
|
||||
/// Q2 dot of one weight row against `a.len()` activations (AVX-512 or AVX2 path).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `rust_q2::dot256/dot512`: `row.len() <= 720`, `a.len() <= 8`, `r.len() == a.len()`.
|
||||
unsafe fn q2_dot(row: &[u8], a: &[&ActQ], r: &mut [f32]) {
|
||||
unsafe {
|
||||
if rust_simd::dispatch().avx512 {
|
||||
rust_q2::dot512(row, a, r);
|
||||
} else {
|
||||
rust_q2::dot256(row, a, r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// # Safety
|
||||
/// The caller holds a successful epoch-tagged claim of task `i` (or is the host running the single-worker path
|
||||
/// with all workers parked) and `id` is its exclusive scratch index. `batch.jobs[..]` pointers are live until
|
||||
/// the done+parked barriers. Modes 1/2 are only reached with `nt == 1` jobs; modes 0/3..6 bound `nt <= 8` and
|
||||
/// rows by FF/H.
|
||||
pub(super) unsafe fn execute(&self, i: usize, id: usize) {
|
||||
unsafe {
|
||||
let b = &*self.batch.get();
|
||||
if b.mode == 0 {
|
||||
self.execute_whole(b, i, id);
|
||||
return;
|
||||
}
|
||||
let per = if b.mode == 1 || b.mode == 3 || b.mode == 5 { FF } else { H };
|
||||
let (mut at, end) = task_range(b, i, per);
|
||||
while at < end {
|
||||
let e = at / per;
|
||||
let r0 = at % per;
|
||||
let r1 = per.min(r0 + end - at);
|
||||
let sp = self.span(b, e, r0, r1);
|
||||
if b.mode <= 4 {
|
||||
legacy_span(&sp);
|
||||
} else {
|
||||
native_span(&sp);
|
||||
}
|
||||
at += r1 - r0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// As `execute` for mode 0 (one whole expert per task, `id` an exclusive scratch index).
|
||||
unsafe fn execute_whole(&self, b: &Batch, i: usize, id: usize) {
|
||||
unsafe {
|
||||
let j = b.jobs[i];
|
||||
let a = &*j.a[0];
|
||||
let out = std::slice::from_raw_parts_mut(j.out[0], H);
|
||||
rust_legacy::whole_single(std::slice::from_raw_parts(j.blob, j.len), a, out, &mut *self.scratch[id].get());
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// As `execute`: `e` indexes a live job of the published batch and the claim covers rows `r0..r1` of it.
|
||||
unsafe fn span<'a>(&'a self, b: &'a Batch, e: usize, r0: usize, r1: usize) -> Span<'a> {
|
||||
unsafe {
|
||||
let j = b.jobs[e];
|
||||
let s = self.split[e].get();
|
||||
let (ff_ptr, a2_ptr) = if b.mode <= 2 {
|
||||
let z = self.single[e].get();
|
||||
(std::ptr::addr_of_mut!((*z).ff).cast::<f32>(), std::ptr::addr_of!((*z).a2))
|
||||
} else {
|
||||
(std::ptr::addr_of_mut!((*s).ff).cast::<f32>(), std::ptr::addr_of!((*s).a2).cast::<PlanarActivation>())
|
||||
};
|
||||
let blob = std::slice::from_raw_parts(j.blob, j.len);
|
||||
Span { b, j, s, ff_ptr, a2_ptr, blob, n: j.nt, r0, r1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Modes 1..4: planar gate/up (1, 3) or down (2, 4) rows of the legacy layout.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute` for the claimed span.
|
||||
unsafe fn legacy_span(sp: &Span) {
|
||||
unsafe {
|
||||
let n = sp.n;
|
||||
let gate = sp.b.mode == 1 || sp.b.mode == 3;
|
||||
let a0 = if gate { sp.j.a[0] } else { sp.a2_ptr };
|
||||
let mut a = [&*a0; 8];
|
||||
for t in 0..n {
|
||||
a[t] = if gate { &*sp.j.a[t] } else { &*sp.a2_ptr.add(t) };
|
||||
}
|
||||
if gate {
|
||||
rust_legacy::gate_each(sp.blob, &a[..n], sp.r0, sp.r1, |t, r, v| sp.ff_ptr.add(t * FF + r).write(v));
|
||||
} else {
|
||||
rust_legacy::down_each(sp.blob, &a[..n], sp.r0, sp.r1, |t, r, v| sp.j.out[t].add(r).write(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Modes 5 and 6: native-format gate/up (5) or down (6) rows.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute` for the claimed span; `sp.b.format` is set for these modes.
|
||||
unsafe fn native_span(sp: &Span) {
|
||||
unsafe {
|
||||
let f = sp.b.format.as_ref().unwrap();
|
||||
for r in sp.r0..sp.r1 {
|
||||
native_row(sp, f, r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// As `native_span`, for one row `r` of the span.
|
||||
unsafe fn native_row(sp: &Span, f: &NativeFormat, r: usize) {
|
||||
unsafe {
|
||||
let gate = sp.b.mode == 5;
|
||||
let (kind, offset, stride, width) =
|
||||
if gate { (f.gu, 0, f.gu_row, H) } else { (f.down, f.down_offset, f.down_row, FF) };
|
||||
let row = &sp.blob[offset + r * stride..offset + (r + 1) * stride];
|
||||
let up = f.up_offset + r * stride..f.up_offset + (r + 1) * stride;
|
||||
let mut g = [0.0; 8];
|
||||
let mut u = g;
|
||||
if kind.original_id() == 42 {
|
||||
q2_row(sp, row, &up, &mut g, &mut u);
|
||||
} else if gate {
|
||||
gate_up_row(sp, kind, row, &sp.blob[up], &mut g, &mut u);
|
||||
} else {
|
||||
down_row(sp, kind, row, &mut g);
|
||||
}
|
||||
debug_assert_eq!(width, if gate { H } else { FF });
|
||||
for t in 0..sp.n {
|
||||
if gate {
|
||||
sp.ff_ptr.add(t * FF + r).write(rust_simd::silu(g[t], u[t]));
|
||||
} else {
|
||||
sp.j.out[t].add(r).write(g[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Q2 rows: `g` gets `row` (gate or down); in gate mode `u` also gets the matching `up` row (byte range `up`).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `native_row`.
|
||||
unsafe fn q2_row(sp: &Span, row: &[u8], up: &std::ops::Range<usize>, g: &mut [f32; 8], u: &mut [f32; 8]) {
|
||||
unsafe {
|
||||
let n = sp.n;
|
||||
let gate = sp.b.mode == 5;
|
||||
let a0 = if gate { &(*sp.j.a[0]).0 } else { &(*sp.a2_ptr).0 };
|
||||
let mut a = [a0; 8];
|
||||
for t in 0..n {
|
||||
a[t] = if gate { &(*sp.j.a[t]).0 } else { &(*sp.a2_ptr.add(t)).0 };
|
||||
}
|
||||
q2_dot(row, &a[..n], &mut g[..n]);
|
||||
if gate {
|
||||
q2_dot(&sp.blob[up.clone()], &a[..n], &mut u[..n]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-Q2 gate/up row pair against the per-token native activations.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `native_row`.
|
||||
unsafe fn gate_up_row(sp: &Span, kind: Kind, row: &[u8], up: &[u8], g: &mut [f32; 8], u: &mut [f32; 8]) {
|
||||
unsafe {
|
||||
let n = sp.n;
|
||||
let mut a = [&*sp.j.na[0]; 8];
|
||||
for t in 0..n {
|
||||
a[t] = &*sp.j.na[t];
|
||||
}
|
||||
rust_native_general::group_dot(kind, row, &a[..n], &mut g[..n], rust_simd::dispatch(), true);
|
||||
rust_native_general::group_dot(kind, up, &a[..n], &mut u[..n], rust_simd::dispatch(), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-Q2 down row against the quantized `hq` activations of the expert.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `native_row`.
|
||||
unsafe fn down_row(sp: &Span, kind: Kind, row: &[u8], g: &mut [f32; 8]) {
|
||||
unsafe {
|
||||
let n = sp.n;
|
||||
let base = std::ptr::addr_of!((*sp.s).hq).cast::<[u8; 1024]>();
|
||||
let mut a: [&[u8]; 8] = [&[]; 8];
|
||||
for t in 0..n {
|
||||
a[t] = &*base.add(t);
|
||||
}
|
||||
rust_native_general::group_dot_bytes(kind, row, FF, &a[..n], &mut g[..n], rust_simd::dispatch(), false);
|
||||
}
|
||||
}
|
||||
@@ -1,274 +0,0 @@
|
||||
//! The row work of `Shared::execute`, split by stage: which interval a task owns, which scratch cells a claimed segment
|
||||
//! uses, then the legacy planar kernels (modes 1-4) or the native-format kernels (modes 5 and 6) over its rows.
|
||||
//! Moved out of `impl_shared.rs` by STRA-338 (size); the arithmetic and its order are those of the original.
|
||||
|
||||
use super::super::rust_simd::{dispatch, silu};
|
||||
use super::super::rust_types::ActQ;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Rows per expert in one phase: the gate/up rows (`FF`) in modes 1, 3 and 5, the down rows (`H`) otherwise.
|
||||
fn rows_per_expert(mode: u32) -> usize {
|
||||
if mode == 1 || mode == 3 || mode == 5 { FF } else { H }
|
||||
}
|
||||
|
||||
/// The half-open interval of the batch global row index that task `i` owns.
|
||||
fn task_interval(b: &Batch, i: usize, per: usize) -> (usize, usize) {
|
||||
if b.mode <= 2 {
|
||||
let e = i / b.parts;
|
||||
let p = i % b.parts;
|
||||
(e * per + per * p / b.parts, e * per + per * (p + 1) / b.parts)
|
||||
} else {
|
||||
(b.rows * i / b.tasks, b.rows * (i + 1) / b.tasks)
|
||||
}
|
||||
}
|
||||
|
||||
/// `dot512` or `dot256` of the Q2_0 rows, by the process kernel family.
|
||||
///
|
||||
/// # Safety
|
||||
/// The AVX2 (and, when `dispatch().avx512`, AVX-512) capability that `ExpertPool::new` admitted;
|
||||
/// `a.len() == out.len()`.
|
||||
unsafe fn dot_q2(row: &[u8], a: &[&ActQ], out: &mut [f32]) {
|
||||
unsafe {
|
||||
if dispatch().avx512 {
|
||||
super::super::rust_q2::dot512(row, a, out);
|
||||
} else {
|
||||
super::super::rust_q2::dot256(row, a, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What one claimed segment (rows `r0..r1` of expert `e`) works on: the job and encoded blob of the expert, its scratch
|
||||
/// cells and the batch.
|
||||
struct Segment<'a> {
|
||||
b: &'a Batch,
|
||||
j: Job,
|
||||
blob: &'a [u8],
|
||||
ff: *mut f32,
|
||||
a2: *const PlanarActivation,
|
||||
hq: *const [u8; 1024],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// # Safety
|
||||
/// The caller holds a successful epoch-tagged claim of task `i` (or is the host running the single-worker path with
|
||||
/// all workers parked) and `id` is its exclusive scratch index. `batch.jobs[..]` pointers are live until the
|
||||
/// done+parked barriers. Modes 1/2 are only reached with `nt == 1` jobs; modes 0/3..6 bound `nt <= 8` and rows by
|
||||
/// FF/H.
|
||||
pub(super) unsafe fn execute(&self, i: usize, id: usize) {
|
||||
// SAFETY: the claim of task `i` makes `batch` published and immutable until the done+parked barriers.
|
||||
unsafe {
|
||||
let b = &*self.batch.get();
|
||||
if b.mode == 0 {
|
||||
self.execute_whole(b, i, id);
|
||||
return;
|
||||
}
|
||||
let per = rows_per_expert(b.mode);
|
||||
let (mut at, end) = task_interval(b, i, per);
|
||||
while at < end {
|
||||
let e = at / per;
|
||||
let r0 = at % per;
|
||||
let r1 = per.min(r0 + end - at);
|
||||
self.execute_segment(b, e, r0, r1);
|
||||
at += r1 - r0;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Mode 0: task `i` is one whole expert, computed with the host or worker scratch `id`.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `execute`.
|
||||
unsafe fn execute_whole(&self, b: &Batch, i: usize, id: usize) {
|
||||
unsafe {
|
||||
let j = b.jobs[i];
|
||||
let a = &*j.a[0];
|
||||
let out = std::slice::from_raw_parts_mut(j.out[0], H);
|
||||
super::super::rust_legacy::whole_single(
|
||||
std::slice::from_raw_parts(j.blob, j.len),
|
||||
a,
|
||||
out,
|
||||
&mut *self.scratch[id].get(),
|
||||
);
|
||||
}
|
||||
}
|
||||
/// Rows `r0..r1` of expert `e` in a mode other than 0.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `execute`; `e` is below the job count of the batch and the split/single cells of `e` exist.
|
||||
unsafe fn execute_segment(&self, b: &Batch, e: usize, r0: usize, r1: usize) {
|
||||
unsafe {
|
||||
let seg = self.segment(b, e, r0, r1);
|
||||
if b.mode <= 4 {
|
||||
seg.planar_rows();
|
||||
} else {
|
||||
seg.native_rows();
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The job of expert `e` and its scratch cells: the single-split cells in modes 1/2, the split cells otherwise.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `execute_segment`.
|
||||
unsafe fn segment<'a>(&self, b: &'a Batch, e: usize, r0: usize, r1: usize) -> Segment<'a> {
|
||||
unsafe {
|
||||
let j = b.jobs[e];
|
||||
let s = self.split[e].get();
|
||||
let (ff, a2) = if b.mode <= 2 {
|
||||
let z = self.single[e].get();
|
||||
(std::ptr::addr_of_mut!((*z).ff).cast::<f32>(), std::ptr::addr_of!((*z).a2))
|
||||
} else {
|
||||
(std::ptr::addr_of_mut!((*s).ff).cast::<f32>(), std::ptr::addr_of!((*s).a2).cast::<PlanarActivation>())
|
||||
};
|
||||
let blob = std::slice::from_raw_parts(j.blob, j.len);
|
||||
let hq = std::ptr::addr_of!((*s).hq).cast::<[u8; 1024]>();
|
||||
Segment { b, j, blob, ff, a2, hq, r0, r1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Segment<'_> {
|
||||
/// Modes 1-4: the legacy planar Q2 kernels. Gate rows (modes 1, 3) read the activations of the jobs and write `ff`;
|
||||
/// down rows (modes 2, 4) read the quantized hidden rows of `a2` and write the outputs of the jobs.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`.
|
||||
unsafe fn planar_rows(&self) {
|
||||
unsafe {
|
||||
let j = self.j;
|
||||
let ff_ptr = self.ff;
|
||||
let n = j.nt;
|
||||
let gate = self.b.mode == 1 || self.b.mode == 3;
|
||||
let a0 = if gate { j.a[0] } else { self.a2 };
|
||||
let mut a = [&*a0; 8];
|
||||
for (t, slot) in a.iter_mut().enumerate().take(n) {
|
||||
*slot = if gate { &*j.a[t] } else { &*self.a2.add(t) };
|
||||
}
|
||||
if gate {
|
||||
super::super::rust_legacy::gate_each(self.blob, &a[..n], self.r0, self.r1, |t, r, v| {
|
||||
ff_ptr.add(t * FF + r).write(v)
|
||||
});
|
||||
} else {
|
||||
super::super::rust_legacy::down_each(self.blob, &a[..n], self.r0, self.r1, |t, r, v| {
|
||||
j.out[t].add(r).write(v)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Modes 5 and 6: the native-format kernels, one row at a time for all `nt` tokens.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`; the batch holds a format.
|
||||
unsafe fn native_rows(&self) {
|
||||
unsafe {
|
||||
let f = self.b.format.as_ref().unwrap();
|
||||
let mut g = [0.0; 8];
|
||||
let mut u = g;
|
||||
for r in self.r0..self.r1 {
|
||||
self.native_row(f, r, &mut g, &mut u);
|
||||
self.write_row(r, &g, &u);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The dot products of row `r` for every token: `g` (and `u` in mode 5, the up row).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `native_rows`.
|
||||
unsafe fn native_row(&self, f: &NativeFormat, r: usize, g: &mut [f32; 8], u: &mut [f32; 8]) {
|
||||
unsafe {
|
||||
let gate_up = self.b.mode == 5;
|
||||
let (kind, offset, stride, width) =
|
||||
if gate_up { (f.gu, 0, f.gu_row, H) } else { (f.down, f.down_offset, f.down_row, FF) };
|
||||
let row = &self.blob[offset + r * stride..offset + (r + 1) * stride];
|
||||
if kind.original_id() == 42 {
|
||||
self.q2_row(f, r, row, g, u);
|
||||
} else if gate_up {
|
||||
self.native_gate_up_row(f, r, row, g, u);
|
||||
} else {
|
||||
self.native_down_row(f, row, g);
|
||||
}
|
||||
debug_assert_eq!(width, if gate_up { H } else { FF });
|
||||
}
|
||||
}
|
||||
/// The up row `r` of the encoded blob (mode 5).
|
||||
fn up_row(&self, f: &NativeFormat, r: usize) -> &[u8] {
|
||||
let stride = f.gu_row;
|
||||
&self.blob[f.up_offset + r * stride..f.up_offset + (r + 1) * stride]
|
||||
}
|
||||
/// Q2_0 rows (planar activations): the gate row, then in mode 5 the up row.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `native_rows`.
|
||||
unsafe fn q2_row(&self, f: &NativeFormat, r: usize, row: &[u8], g: &mut [f32; 8], u: &mut [f32; 8]) {
|
||||
unsafe {
|
||||
let j = self.j;
|
||||
let n = j.nt;
|
||||
let gate_up = self.b.mode == 5;
|
||||
let a0 = if gate_up { &(*j.a[0]).0 } else { &(*self.a2).0 };
|
||||
let mut a = [a0; 8];
|
||||
for (t, slot) in a.iter_mut().enumerate().take(n) {
|
||||
*slot = if gate_up { &(*j.a[t]).0 } else { &(*self.a2.add(t)).0 };
|
||||
}
|
||||
dot_q2(row, &a[..n], &mut g[..n]);
|
||||
if gate_up {
|
||||
dot_q2(self.up_row(f, r), &a[..n], &mut u[..n]);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Other gate/up formats: the gate row, then the up row, over the native activations.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `native_rows`.
|
||||
unsafe fn native_gate_up_row(&self, f: &NativeFormat, r: usize, row: &[u8], g: &mut [f32; 8], u: &mut [f32; 8]) {
|
||||
unsafe {
|
||||
let j = self.j;
|
||||
let n = j.nt;
|
||||
let mut a = [&*j.na[0]; 8];
|
||||
for (t, slot) in a.iter_mut().enumerate().take(n) {
|
||||
*slot = &*j.na[t];
|
||||
}
|
||||
let d = dispatch();
|
||||
super::super::rust_native_general::group_dot(f.gu, row, &a[..n], &mut g[..n], d, true);
|
||||
super::super::rust_native_general::group_dot(f.gu, self.up_row(f, r), &a[..n], &mut u[..n], d, true);
|
||||
}
|
||||
}
|
||||
/// Other down formats: the down row over the hidden rows of the split cell (`hq`).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `native_rows`.
|
||||
unsafe fn native_down_row(&self, f: &NativeFormat, row: &[u8], g: &mut [f32; 8]) {
|
||||
unsafe {
|
||||
let n = self.j.nt;
|
||||
let mut a: [&[u8]; 8] = [&[]; 8];
|
||||
for (t, slot) in a.iter_mut().enumerate().take(n) {
|
||||
*slot = &*self.hq.add(t);
|
||||
}
|
||||
super::super::rust_native_general::group_dot_bytes(
|
||||
f.down,
|
||||
row,
|
||||
FF,
|
||||
&a[..n],
|
||||
&mut g[..n],
|
||||
dispatch(),
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
/// Row `r` of every token: `silu(g, u)` into the hidden rows (mode 5) or `g` into the output of the job (mode 6).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `native_rows`.
|
||||
unsafe fn write_row(&self, r: usize, g: &[f32; 8], u: &[f32; 8]) {
|
||||
unsafe {
|
||||
let j = self.j;
|
||||
for t in 0..j.nt {
|
||||
if self.b.mode == 5 {
|
||||
self.ff.add(t * FF + r).write(silu(g[t], u[t]));
|
||||
} else {
|
||||
j.out[t].add(r).write(g[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Moved out of the parent module by STRA-338: the Default impls of the pool cells, Sync/Send of Shared, helpers.
|
||||
//! Moved out of the parent module by STRA-338: impl Default_for_Job, impl Default_for_Split, impl Default_for_SingleSplit, impl Sync_for_Shared, impl Send_for_Shared, fn alloc_with ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -3,68 +3,29 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The CPU capability the pool needs: AVX2, and the AVX-512 DQ extension when AVX-512 is on.
|
||||
fn require_cpu_features() -> Result<()> {
|
||||
if !super::super::rust_simd::avx2_ok() || super::super::rust_simd::avx512_ok() && !super::super::rust_simd::dq_ok()
|
||||
{
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The worker count: `workers` when positive, else the cores the topology leaves for workers.
|
||||
fn worker_count(workers: i32, topology: &CpuTopology, affinity: PoolAffinity) -> usize {
|
||||
if workers > 0 {
|
||||
workers as usize
|
||||
} else if topology.is_hybrid && affinity != PoolAffinity::All {
|
||||
topology.p_cores.saturating_sub(1).max(1)
|
||||
} else {
|
||||
topology.worker_cores.len().max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// How long an idle worker spins before it sleeps: `STRATA_POOL_SPIN_US` microseconds, else 20 ms.
|
||||
fn spin_from_env() -> Duration {
|
||||
std::env::var("STRATA_POOL_SPIN_US")
|
||||
.map(|s| Duration::from_micros(super::super::rust_simd::atoi(&s).max(0) as u64))
|
||||
.unwrap_or(Duration::from_millis(20))
|
||||
}
|
||||
|
||||
/// The shared state of a pool of `n` workers: the claim/park words and all scratch cells, allocated fallibly.
|
||||
fn new_shared(n: usize, spin: Duration) -> Result<Arc<Shared>> {
|
||||
let mut jobs = Vec::new();
|
||||
jobs.try_reserve_exact(96).map_err(|_| Error::Allocation)?;
|
||||
Ok(Arc::new(Shared {
|
||||
head: Line(AtomicU64::new(0)),
|
||||
done: Line(AtomicU32::new(0)),
|
||||
parked: Line(AtomicU32::new(0)),
|
||||
epoch: Line(AtomicU32::new(0)),
|
||||
stop: Line(AtomicBool::new(false)),
|
||||
sleepers: Line(AtomicU32::new(0)),
|
||||
sleep_mu: Mutex::new(()),
|
||||
sleep_cv: Condvar::new(),
|
||||
spin,
|
||||
n,
|
||||
batch: UnsafeCell::new(Batch { jobs, format: None, mode: 0, rows: 0, tasks: 1, parts: 1 }),
|
||||
split: cells::<Split>(96)?,
|
||||
scratch: cells::<SingleScratch>(n + 1)?,
|
||||
single: cells::<SingleSplit>(16)?,
|
||||
states: alloc_with(n, || AtomicI32::new(-1))?,
|
||||
host: AtomicI32::new(-10),
|
||||
host_ms: AtomicI64::new(now_ms()),
|
||||
}))
|
||||
}
|
||||
|
||||
impl ExpertPool {
|
||||
pub fn new(workers: i32, pin: bool, host_works: bool, affinity: PoolAffinity) -> Result<Self> {
|
||||
require_cpu_features()?;
|
||||
if !super::super::rust_simd::avx2_ok()
|
||||
|| super::super::rust_simd::avx512_ok() && !super::super::rust_simd::dq_ok()
|
||||
{
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
let topology = super::super::rust_topology::detect_cpu_topology(true, affinity);
|
||||
let n = worker_count(workers, &topology, affinity);
|
||||
let n = Self::worker_count(workers, &topology, affinity);
|
||||
if n.checked_add(1).and_then(|v| v.checked_mul(3)).is_none_or(|v| v > 65535) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let shared = new_shared(n, spin_from_env())?;
|
||||
let mut pool = Self {
|
||||
let mut pool = Self::assemble(Self::new_shared(n)?, topology, affinity, host_works);
|
||||
pool.threads.try_reserve_exact(n).map_err(|_| Error::Allocation)?;
|
||||
for i in 0..n {
|
||||
let core = if pin { pool.topology.worker_cores.get(i).copied().unwrap_or(-1) } else { -1 };
|
||||
let handle = Self::spawn_worker(Arc::clone(&pool.shared), i, core)?;
|
||||
pool.threads.push(handle);
|
||||
}
|
||||
Ok(pool)
|
||||
}
|
||||
fn assemble(shared: Arc<Shared>, topology: CpuTopology, affinity: PoolAffinity, host_works: bool) -> Self {
|
||||
Self {
|
||||
shared,
|
||||
threads: Vec::new(),
|
||||
topology,
|
||||
@@ -75,22 +36,44 @@ impl ExpertPool {
|
||||
ms_multi_down: 0.0,
|
||||
multi_bytes: 0,
|
||||
phase: [0.0; 3],
|
||||
};
|
||||
pool.spawn_workers(n, pin)?;
|
||||
Ok(pool)
|
||||
}
|
||||
/// Starts the `n` worker threads; a failure returns with the pool dropped by the caller (stop + join).
|
||||
fn spawn_workers(&mut self, n: usize, pin: bool) -> Result<()> {
|
||||
self.threads.try_reserve_exact(n).map_err(|_| Error::Allocation)?;
|
||||
for i in 0..n {
|
||||
let core = if pin { self.topology.worker_cores.get(i).copied().unwrap_or(-1) } else { -1 };
|
||||
let handle = self.spawn_worker(i, core)?;
|
||||
self.threads.push(handle);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn spawn_worker(&self, i: usize, core: i32) -> Result<thread::JoinHandle<()>> {
|
||||
let s = Arc::clone(&self.shared);
|
||||
fn worker_count(workers: i32, topology: &CpuTopology, affinity: PoolAffinity) -> usize {
|
||||
if workers > 0 {
|
||||
workers as usize
|
||||
} else if topology.is_hybrid && affinity != PoolAffinity::All {
|
||||
topology.p_cores.saturating_sub(1).max(1)
|
||||
} else {
|
||||
topology.worker_cores.len().max(1)
|
||||
}
|
||||
}
|
||||
fn new_shared(n: usize) -> Result<Arc<Shared>> {
|
||||
let spin = std::env::var("STRATA_POOL_SPIN_US")
|
||||
.map(|s| Duration::from_micros(super::super::rust_simd::atoi(&s).max(0) as u64))
|
||||
.unwrap_or(Duration::from_millis(20));
|
||||
let mut jobs = Vec::new();
|
||||
jobs.try_reserve_exact(96).map_err(|_| Error::Allocation)?;
|
||||
Ok(Arc::new(Shared {
|
||||
head: Line(AtomicU64::new(0)),
|
||||
done: Line(AtomicU32::new(0)),
|
||||
parked: Line(AtomicU32::new(0)),
|
||||
epoch: Line(AtomicU32::new(0)),
|
||||
stop: Line(AtomicBool::new(false)),
|
||||
sleepers: Line(AtomicU32::new(0)),
|
||||
sleep_mu: Mutex::new(()),
|
||||
sleep_cv: Condvar::new(),
|
||||
spin,
|
||||
n,
|
||||
batch: UnsafeCell::new(Batch { jobs, format: None, mode: 0, rows: 0, tasks: 1, parts: 1 }),
|
||||
split: cells::<Split>(96)?,
|
||||
scratch: cells::<SingleScratch>(n + 1)?,
|
||||
single: cells::<SingleSplit>(16)?,
|
||||
states: alloc_with(n, || AtomicI32::new(-1))?,
|
||||
host: AtomicI32::new(-10),
|
||||
host_ms: AtomicI64::new(now_ms()),
|
||||
}))
|
||||
}
|
||||
fn spawn_worker(s: Arc<Shared>, i: usize, core: i32) -> Result<thread::JoinHandle<()>> {
|
||||
thread::Builder::new()
|
||||
.name(format!("strata-general-expert-{i}"))
|
||||
.spawn(move || {
|
||||
@@ -131,6 +114,8 @@ impl ExpertPool {
|
||||
pub fn diagnostic(&self) -> Diagnostic {
|
||||
let s = &self.shared;
|
||||
let h = s.head.0.load(Ordering::SeqCst);
|
||||
// SAFETY: as owned_bytes: a plain read of `mode` while the host cannot hold &mut self; workers never write it.
|
||||
let mode = unsafe { (*s.batch.get()).mode };
|
||||
Diagnostic {
|
||||
epoch: s.epoch.0.load(Ordering::SeqCst),
|
||||
batch_epoch: (h >> 32) as u32,
|
||||
@@ -139,9 +124,7 @@ impl ExpertPool {
|
||||
done: s.done.0.load(Ordering::SeqCst),
|
||||
parked: s.parked.0.load(Ordering::SeqCst),
|
||||
sleeping: s.sleepers.0.load(Ordering::SeqCst),
|
||||
// SAFETY: as owned_bytes: a plain read of `mode` while the host cannot hold &mut self; workers never
|
||||
// write it.
|
||||
mode: unsafe { (*s.batch.get()).mode },
|
||||
mode,
|
||||
workers: s.states.iter().map(|s| s.load(Ordering::SeqCst)).collect(),
|
||||
host: s.host.load(Ordering::SeqCst),
|
||||
host_for_ms: now_ms() - s.host_ms.load(Ordering::SeqCst),
|
||||
@@ -157,7 +140,10 @@ impl ExpertPool {
|
||||
b.rows = rows;
|
||||
b.parts = parts;
|
||||
}
|
||||
let e = self.shared.open_epoch(tasks);
|
||||
self.shared.done.0.store(0, Ordering::Relaxed);
|
||||
let e = self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1);
|
||||
self.shared.head.0.store(((e as u64) << 32) | ((tasks as u64) << 16), Ordering::Release);
|
||||
self.shared.publish();
|
||||
if self.host_works {
|
||||
self.shared.drain(e, self.shared.n);
|
||||
}
|
||||
@@ -178,7 +164,7 @@ impl ExpertPool {
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn clear(&mut self) {
|
||||
// SAFETY: only called after the phase barriers (workers parked) or before any publication.
|
||||
/* SAFETY: only called after the phase barriers (workers parked) or before any publication. */
|
||||
unsafe {
|
||||
let b = &mut *self.shared.batch.get();
|
||||
b.jobs.clear();
|
||||
@@ -196,33 +182,32 @@ impl ExpertPool {
|
||||
let a = Instant::now();
|
||||
self.load(jobs, None)?;
|
||||
if self.shared.n == 1 {
|
||||
self.execute_inline(jobs.len());
|
||||
for i in 0..jobs.len() {
|
||||
// SAFETY: n==1 and load() saw the lone worker parked; nothing is published here, so it stays parked and
|
||||
// scratch[0] is host-only. mode is 0 (clear() after every operation).
|
||||
unsafe {
|
||||
self.shared.execute(i, 0);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.whole_published(jobs.len(), a);
|
||||
}
|
||||
self.clear();
|
||||
Ok(())
|
||||
}
|
||||
/// The single-worker path: the host computes every whole expert itself with the scratch of worker 0.
|
||||
fn execute_inline(&self, count: usize) {
|
||||
for i in 0..count {
|
||||
// SAFETY: n==1 and load() saw the lone worker parked; nothing is published here, so it stays parked and
|
||||
// scratch[0] is host-only. mode is 0 (clear() after every operation).
|
||||
unsafe {
|
||||
self.shared.execute(i, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Mode 0 over `count` loaded jobs through the workers; `a` is the instant `whole` started, for the phase timing.
|
||||
/// Publish `count` whole-expert tasks (mode 0), drain with the host if it works, and time the phases from `a`.
|
||||
fn whole_published(&mut self, count: usize, a: Instant) {
|
||||
let b = Instant::now();
|
||||
// SAFETY: load() above waited for all workers to park.
|
||||
// SAFETY: load() in the caller waited for all workers to park.
|
||||
unsafe {
|
||||
let batch = &mut *self.shared.batch.get();
|
||||
batch.mode = 0;
|
||||
batch.tasks = count;
|
||||
}
|
||||
let epoch = self.shared.open_epoch(count);
|
||||
self.shared.done.0.store(0, Ordering::Relaxed);
|
||||
let epoch = self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1);
|
||||
self.shared.head.0.store(((epoch as u64) << 32) | ((count as u64) << 16), Ordering::Release);
|
||||
self.shared.publish();
|
||||
if self.host_works {
|
||||
self.shared.drain(epoch, self.shared.n);
|
||||
}
|
||||
@@ -235,11 +220,25 @@ impl ExpertPool {
|
||||
self.phase[1] += (c - b).as_secs_f64() * 1000.0;
|
||||
self.phase[2] += (d - c).as_secs_f64() * 1000.0;
|
||||
}
|
||||
/// The job header of one validated planar expert.
|
||||
fn planar_header(j: &mut PlanarJob<'_>) -> Result<Job> {
|
||||
if j.blob.len() != super::super::rust_legacy::BLOB
|
||||
|| j.output.len() != H
|
||||
|| j.activation.0.nchunks != 80
|
||||
|| !super::super::rust_legacy::legacy_supported()
|
||||
{
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let mut h = Job { blob: j.blob.as_ptr(), len: j.blob.len(), nt: 1, ..Job::default() };
|
||||
h.a[0] = j.activation;
|
||||
h.out[0] = j.output.as_mut_ptr();
|
||||
Ok(h)
|
||||
}
|
||||
pub fn run(&mut self, jobs: &mut [PlanarJob<'_>]) -> Result<()> {
|
||||
let mut headers = Vec::new();
|
||||
headers.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?;
|
||||
for j in jobs {
|
||||
headers.push(planar_header(j)?);
|
||||
headers.push(Self::planar_header(j)?);
|
||||
}
|
||||
self.whole(&headers)
|
||||
}
|
||||
@@ -253,58 +252,8 @@ impl ExpertPool {
|
||||
let t = Instant::now();
|
||||
let mut headers = [Job::default(); 16];
|
||||
for (i, j) in jobs.iter_mut().enumerate() {
|
||||
headers[i] = planar_header(j)?;
|
||||
headers[i] = Self::planar_header(j)?;
|
||||
}
|
||||
self.split_loaded(&headers[..jobs.len()], t)
|
||||
}
|
||||
/// The two-phase split of at most 16 single-token jobs: gate/up rows, requantization of the hidden rows, down rows.
|
||||
/// `t` is the instant the caller started, for the `phase[1]` timing.
|
||||
pub(super) fn split_loaded(&mut self, jobs: &[Job], t: Instant) -> Result<()> {
|
||||
let n = jobs.len();
|
||||
self.load(jobs, None)?;
|
||||
let parts = (3 * (self.shared.n + usize::from(self.host_works))).div_ceil(n).max(1);
|
||||
if n.checked_mul(parts).is_none_or(|v| v > 65535) {
|
||||
self.clear();
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
self.phase(1, n * parts, n * FF, parts);
|
||||
self.requantize_singles(n)?;
|
||||
self.phase(2, n * parts, n * H, parts);
|
||||
self.clear();
|
||||
self.phase[1] += t.elapsed().as_secs_f64() * 1000.0;
|
||||
Ok(())
|
||||
}
|
||||
/// Quantizes the hidden rows of the first `n` single-split cells; the first failure clears the batch and returns.
|
||||
fn requantize_singles(&mut self, n: usize) -> Result<()> {
|
||||
// SAFETY: phase() returned => done AND parked; e < n <= 16 = single.len().
|
||||
unsafe {
|
||||
for e in 0..n {
|
||||
let z = &mut *self.shared.single[e].get();
|
||||
if let Err(error) = z.a2.quantize(&z.ff) {
|
||||
self.clear();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
self.split_run(&headers[..jobs.len()], t)
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the job has the shape and the CPU support of the legacy planar Q2 path.
|
||||
fn check_planar_shape(j: &PlanarJob<'_>) -> bool {
|
||||
j.blob.len() == super::super::rust_legacy::BLOB
|
||||
&& j.output.len() == H
|
||||
&& j.activation.0.nchunks == 80
|
||||
&& super::super::rust_legacy::legacy_supported()
|
||||
}
|
||||
|
||||
/// The job header of one planar job, or `Shape` when it is not admitted by the legacy Q2 path.
|
||||
fn planar_header(j: &mut PlanarJob<'_>) -> Result<Job> {
|
||||
if !check_planar_shape(j) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let mut h = Job { blob: j.blob.as_ptr(), len: j.blob.len(), nt: 1, ..Job::default() };
|
||||
h.a[0] = j.activation;
|
||||
h.out[0] = j.output.as_mut_ptr();
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
@@ -3,114 +3,6 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// True when a multi-token planar job has the shape and the CPU support of the legacy planar Q2 path.
|
||||
fn check_planar_multi(j: &PlanarJobMulti<'_>) -> bool {
|
||||
j.blob.len() == super::super::rust_legacy::BLOB
|
||||
&& !j.activation.is_empty()
|
||||
&& j.activation.len() <= 8
|
||||
&& j.activation.len() == j.output.len()
|
||||
&& j.output.iter().all(|o| o.len() == H)
|
||||
&& j.activation.iter().all(|a| a.0.nchunks == 80)
|
||||
&& super::super::rust_legacy::legacy_supported()
|
||||
}
|
||||
|
||||
/// The job header of one multi-token planar job, or `Shape` when it is not admitted by the legacy Q2 path.
|
||||
fn planar_multi_header(j: &mut PlanarJobMulti<'_>) -> Result<Job> {
|
||||
if !check_planar_multi(j) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let mut h = Job { blob: j.blob.as_ptr(), len: j.blob.len(), nt: j.activation.len(), ..Job::default() };
|
||||
for t in 0..h.nt {
|
||||
h.a[t] = j.activation[t];
|
||||
h.out[t] = j.output[t].as_mut_ptr();
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
/// One single-token job per token of every job, in job order (the fallback for more than 96 jobs or the oracle).
|
||||
fn single_token_headers(all: Vec<Job>) -> Result<Vec<Job>> {
|
||||
let mut singles = Vec::new();
|
||||
singles.try_reserve_exact(all.len().checked_mul(8).ok_or(Error::Shape)?).map_err(|_| Error::Allocation)?;
|
||||
for j in all {
|
||||
for t in 0..j.nt {
|
||||
let mut h = j;
|
||||
h.nt = 1;
|
||||
h.a[0] = j.a[t];
|
||||
h.out[0] = j.out[t];
|
||||
singles.push(h);
|
||||
}
|
||||
}
|
||||
Ok(singles)
|
||||
}
|
||||
|
||||
/// True when the output and activations of a native job fit the format (`n` tokens of `H` floats, `n` in 1..=8).
|
||||
fn check_native_shape(f: &NativeFormat, j: &NativeJobMulti<'_>) -> bool {
|
||||
let n = j.output.len();
|
||||
j.blob.len() == f.bytes && n != 0 && n <= 8 && j.output.iter().all(|v| v.len() == H)
|
||||
}
|
||||
|
||||
/// The job header of one native job: the planar activations of a Q2_0 gate/up format, the native ones otherwise.
|
||||
fn native_multi_header(f: &NativeFormat, j: &mut NativeJobMulti<'_>) -> Result<Job> {
|
||||
if !check_native_shape(f, j) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let n = j.output.len();
|
||||
let q2 = f.gu.original_id() == 42;
|
||||
if (q2 && j.planar.len() != n) || (!q2 && j.activation.len() != n) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let mut h = Job { blob: j.blob.as_ptr(), len: j.blob.len(), nt: n, ..Job::default() };
|
||||
for t in 0..n {
|
||||
if q2 {
|
||||
if j.planar[t].0.nchunks != 80 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
h.a[t] = j.planar[t];
|
||||
} else {
|
||||
j.activation[t].check(f.gu, H)?;
|
||||
h.na[t] = j.activation[t];
|
||||
}
|
||||
h.out[t] = j.output[t].as_mut_ptr();
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
/// Requantizes the gate/up result `ff[t]` of token `t` into the input of the down matrix.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2 (and AVX-512 when `dispatch().avx512`) admitted by `ExpertPool::new`; `hq[t]` is a 1024-byte row.
|
||||
unsafe fn quantize_down_input(f: &NativeFormat, s: &mut Split, t: usize) {
|
||||
unsafe {
|
||||
if f.down.original_id() == 42 {
|
||||
let a = &mut s.a2[t].0;
|
||||
if super::super::rust_simd::dispatch().avx512 {
|
||||
super::super::rust_quant::q8_one_avx512(&s.ff[t], a);
|
||||
} else {
|
||||
super::super::rust_quant::q8_one_avx2(&s.ff[t], a);
|
||||
}
|
||||
} else {
|
||||
super::super::rust_ggml::quantize_raw(f.down, &s.ff[t], &mut s.hq[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Token `t` of a split cell: the native requantization for a given format, the planar one otherwise (the only
|
||||
/// fallible one).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `quantize_down_input`.
|
||||
unsafe fn quantize_hidden_row(s: &mut Split, t: usize, fmt: Option<&NativeFormat>) -> Result<()> {
|
||||
unsafe {
|
||||
match fmt {
|
||||
Some(f) => {
|
||||
quantize_down_input(f, s, t);
|
||||
Ok(())
|
||||
}
|
||||
None => s.a2[t].quantize(&s.ff[t]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExpertPool {
|
||||
pub(super) fn split_headers(&mut self, jobs: &[Job]) -> Result<()> {
|
||||
if jobs.is_empty() {
|
||||
@@ -119,8 +11,68 @@ impl ExpertPool {
|
||||
if jobs.len() > 16 || self.shared.n == 1 || super::super::rust_legacy::oracle_q8_zero_enabled() {
|
||||
return self.whole(jobs);
|
||||
}
|
||||
let t = Instant::now();
|
||||
self.split_loaded(jobs, t)
|
||||
self.split_run(jobs, Instant::now())
|
||||
}
|
||||
/// The two-phase (gate/up, requantize, down) single-activation split path; `t` is when the caller started timing.
|
||||
pub(super) fn split_run(&mut self, jobs: &[Job], t: Instant) -> Result<()> {
|
||||
self.load(jobs, None)?;
|
||||
let parts = (3 * (self.shared.n + usize::from(self.host_works))).div_ceil(jobs.len()).max(1);
|
||||
if jobs.len().checked_mul(parts).is_none_or(|v| v > 65535) {
|
||||
self.clear();
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
self.phase(1, jobs.len() * parts, jobs.len() * FF, parts);
|
||||
self.quantize_single(jobs.len())?;
|
||||
self.phase(2, jobs.len() * parts, jobs.len() * H, parts);
|
||||
self.clear();
|
||||
self.phase[1] += t.elapsed().as_secs_f64() * 1000.0;
|
||||
Ok(())
|
||||
}
|
||||
/// Requantize the `n` gate/up outputs of phase 1 into the per-expert Q8 activations; clears the batch on failure.
|
||||
fn quantize_single(&mut self, n: usize) -> Result<()> {
|
||||
let outcome = (0..n).try_for_each(|e| {
|
||||
// SAFETY: phase() returned => done AND parked; n <= 16 = single.len().
|
||||
let z = unsafe { &mut *self.shared.single[e].get() };
|
||||
z.a2.quantize(&z.ff)
|
||||
});
|
||||
if outcome.is_err() {
|
||||
self.clear();
|
||||
}
|
||||
outcome
|
||||
}
|
||||
/// The job header of one validated multi-token planar expert.
|
||||
fn planar_multi_header(j: &mut PlanarJobMulti<'_>) -> Result<Job> {
|
||||
if j.blob.len() != super::super::rust_legacy::BLOB
|
||||
|| j.activation.is_empty()
|
||||
|| j.activation.len() > 8
|
||||
|| j.activation.len() != j.output.len()
|
||||
|| j.output.iter().any(|o| o.len() != H)
|
||||
|| j.activation.iter().any(|a| a.0.nchunks != 80)
|
||||
|| !super::super::rust_legacy::legacy_supported()
|
||||
{
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let mut h = Job { blob: j.blob.as_ptr(), len: j.blob.len(), nt: j.activation.len(), ..Job::default() };
|
||||
for t in 0..h.nt {
|
||||
h.a[t] = j.activation[t];
|
||||
h.out[t] = j.output[t].as_mut_ptr();
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
/// One single-token header per token of every multi-token header, in order.
|
||||
fn single_token_headers(all: Vec<Job>) -> Result<Vec<Job>> {
|
||||
let mut singles = Vec::new();
|
||||
singles.try_reserve_exact(all.len().checked_mul(8).ok_or(Error::Shape)?).map_err(|_| Error::Allocation)?;
|
||||
for j in all {
|
||||
for t in 0..j.nt {
|
||||
let mut h = j;
|
||||
h.nt = 1;
|
||||
h.a[0] = j.a[t];
|
||||
h.out[0] = j.out[t];
|
||||
singles.push(h);
|
||||
}
|
||||
}
|
||||
Ok(singles)
|
||||
}
|
||||
pub fn run_split_multi(&mut self, jobs: &mut [PlanarJobMulti<'_>]) -> Result<()> {
|
||||
if jobs.is_empty() {
|
||||
@@ -129,17 +81,52 @@ impl ExpertPool {
|
||||
let mut all = Vec::new();
|
||||
all.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?;
|
||||
for j in jobs {
|
||||
all.push(planar_multi_header(j)?);
|
||||
all.push(Self::planar_multi_header(j)?);
|
||||
}
|
||||
if all.len() > 96 || super::super::rust_legacy::oracle_q8_zero_enabled() {
|
||||
let singles = single_token_headers(all)?;
|
||||
for c in singles.chunks(16) {
|
||||
for c in Self::single_token_headers(all)?.chunks(16) {
|
||||
self.split_headers(c)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.multi(&all, None)
|
||||
}
|
||||
/// Shape checks of one multi-token native-format expert; true when its gate/up kind is Q2 (planar activations).
|
||||
fn check_native_multi(f: &NativeFormat, j: &NativeJobMulti<'_>) -> Result<bool> {
|
||||
let n = j.output.len();
|
||||
if j.blob.len() != f.bytes || n == 0 || n > 8 || j.output.iter().any(|v| v.len() != H) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let q2 = f.gu.original_id() == 42;
|
||||
if (q2 && j.planar.len() != n) || (!q2 && j.activation.len() != n) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok(q2)
|
||||
}
|
||||
/// The job header of one validated multi-token native-format expert.
|
||||
fn native_multi_header(f: &NativeFormat, j: &mut NativeJobMulti<'_>) -> Result<Job> {
|
||||
let n = j.output.len();
|
||||
let q2 = Self::check_native_multi(f, j)?;
|
||||
let mut h = Job { blob: j.blob.as_ptr(), len: j.blob.len(), nt: n, ..Job::default() };
|
||||
for t in 0..n {
|
||||
Self::native_lane(f, j, &mut h, t, q2)?;
|
||||
h.out[t] = j.output[t].as_mut_ptr();
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
/// Validate lane `t` of a native-format expert and record its activation pointer in `h`.
|
||||
fn native_lane(f: &NativeFormat, j: &NativeJobMulti<'_>, h: &mut Job, t: usize, q2: bool) -> Result<()> {
|
||||
if q2 {
|
||||
if j.planar[t].0.nchunks != 80 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
h.a[t] = j.planar[t];
|
||||
} else {
|
||||
j.activation[t].check(f.gu, H)?;
|
||||
h.na[t] = j.activation[t];
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn run_split_multi_native(&mut self, f: &NativeFormat, jobs: &mut [NativeJobMulti<'_>]) -> Result<()> {
|
||||
f.validate()?;
|
||||
if f.n_embd != H || f.n_ff != FF {
|
||||
@@ -148,7 +135,7 @@ impl ExpertPool {
|
||||
let mut all = Vec::new();
|
||||
all.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?;
|
||||
for j in jobs {
|
||||
all.push(native_multi_header(f, j)?);
|
||||
all.push(Self::native_multi_header(f, j)?);
|
||||
}
|
||||
let elapsed = Instant::now();
|
||||
let before = self.phase[1];
|
||||
@@ -158,6 +145,11 @@ impl ExpertPool {
|
||||
self.phase[1] = before + elapsed.elapsed().as_secs_f64() * 1000.0;
|
||||
Ok(())
|
||||
}
|
||||
fn add_multi_times(&mut self, [t0, t1, t2, t3]: [Instant; 4]) {
|
||||
self.ms_multi_gu += (t1 - t0).as_secs_f64() * 1000.0;
|
||||
self.ms_multi_q += (t2 - t1).as_secs_f64() * 1000.0;
|
||||
self.ms_multi_down += (t3 - t2).as_secs_f64() * 1000.0;
|
||||
}
|
||||
pub(super) fn multi(&mut self, jobs: &[Job], fmt: Option<NativeFormat>) -> Result<()> {
|
||||
let outer = Instant::now();
|
||||
let n = jobs.len();
|
||||
@@ -169,39 +161,19 @@ impl ExpertPool {
|
||||
let tasks = 3 * (self.shared.n + usize::from(self.host_works));
|
||||
self.phase(if fmt.is_some() { 5 } else { 3 }, tasks, n * FF, 1);
|
||||
let t1 = Instant::now();
|
||||
if let Err(error) = self.requantize_hidden(jobs, fmt.as_ref()) {
|
||||
// SAFETY: phase() returned => done AND parked; n <= 96 = split.len(); nt <= 8 (validated by the
|
||||
// run_split_multi* callers).
|
||||
if let Err(error) = unsafe { self.shared.quantize_lanes(jobs, fmt.as_ref()) } {
|
||||
self.clear();
|
||||
return Err(error);
|
||||
}
|
||||
let t2 = Instant::now();
|
||||
self.phase(if fmt.is_some() { 6 } else { 4 }, tasks, n * H, 1);
|
||||
let t3 = Instant::now();
|
||||
self.finish_multi(n, fmt.as_ref(), [t0, t1, t2, t3])
|
||||
}
|
||||
/// Quantizes the gate/up results of every token of every job into the input of the down phase; the first failure
|
||||
/// is returned (the caller clears the batch).
|
||||
fn requantize_hidden(&mut self, jobs: &[Job], fmt: Option<&NativeFormat>) -> Result<()> {
|
||||
// SAFETY: phase() returned => done AND parked; n <= 96 = split.len(); nt <= 8 (validated by the
|
||||
// run_split_multi* callers).
|
||||
unsafe {
|
||||
for (e, job) in jobs.iter().enumerate() {
|
||||
let s = &mut *self.shared.split[e].get();
|
||||
for t in 0..job.nt {
|
||||
quantize_hidden_row(s, t, fmt)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Adds the stage times of one `multi` call (`t` are the four stage instants) and its bytes, then clears the batch.
|
||||
fn finish_multi(&mut self, n: usize, fmt: Option<&NativeFormat>, t: [Instant; 4]) -> Result<()> {
|
||||
let [t0, t1, t2, t3] = t;
|
||||
self.ms_multi_gu += (t1 - t0).as_secs_f64() * 1000.0;
|
||||
self.ms_multi_q += (t2 - t1).as_secs_f64() * 1000.0;
|
||||
self.ms_multi_down += (t3 - t2).as_secs_f64() * 1000.0;
|
||||
self.add_multi_times([t0, t1, t2, t3]);
|
||||
let next_bytes = self
|
||||
.multi_bytes
|
||||
.checked_add((n as u64) * (fmt.map_or(super::super::rust_legacy::BLOB, |f| f.bytes) as u64));
|
||||
.checked_add((n as u64) * (fmt.as_ref().map_or(super::super::rust_legacy::BLOB, |f| f.bytes) as u64));
|
||||
self.clear();
|
||||
self.multi_bytes = next_bytes.ok_or(Error::Shape)?;
|
||||
self.phase[1] += (t3 - t0).as_secs_f64() * 1000.0;
|
||||
|
||||
@@ -11,15 +11,6 @@ impl Shared {
|
||||
self.sleep_cv.notify_all();
|
||||
}
|
||||
}
|
||||
/// Opens a phase of `tasks` tasks: resets `done`, tags `head` with the next epoch, wakes the workers; returns the
|
||||
/// epoch.
|
||||
pub(super) fn open_epoch(&self, tasks: usize) -> u32 {
|
||||
self.done.0.store(0, Ordering::Relaxed);
|
||||
let e = self.epoch.0.load(Ordering::Relaxed).wrapping_add(1);
|
||||
self.head.0.store(((e as u64) << 32) | ((tasks as u64) << 16), Ordering::Release);
|
||||
self.publish();
|
||||
e
|
||||
}
|
||||
pub(super) fn claim(&self, e: u32) -> Option<usize> {
|
||||
let mut h = self.head.0.load(Ordering::Acquire);
|
||||
loop {
|
||||
@@ -58,8 +49,8 @@ impl Shared {
|
||||
super::super::rust_platform::pin(core);
|
||||
let mut seen = 0;
|
||||
self.parked.0.fetch_add(1, Ordering::AcqRel);
|
||||
while self.await_epoch(id, seen) {
|
||||
if self.stop.0.load(Ordering::Acquire) {
|
||||
loop {
|
||||
if !self.await_epoch(id, seen) || self.stop.0.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
seen = self.epoch.0.load(Ordering::Acquire);
|
||||
@@ -70,7 +61,7 @@ impl Shared {
|
||||
self.parked.0.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
/// Spins, then sleeps on the condvar, until the epoch moves past `seen`; `false` when the pool was told to stop.
|
||||
/// Spin (then sleep) until the epoch moves past `seen`; false when the pool is stopping.
|
||||
fn await_epoch(&self, id: usize, seen: u32) -> bool {
|
||||
let at = Instant::now();
|
||||
let mut spins = 0u32;
|
||||
@@ -87,7 +78,6 @@ impl Shared {
|
||||
}
|
||||
true
|
||||
}
|
||||
/// The slow wait of a worker that spun past `spin`: counted as a sleeper, woken by `publish` or by `stop`.
|
||||
fn sleep_until_epoch(&self, id: usize, seen: u32) {
|
||||
let mut lk = self.sleep_mu.lock().unwrap_or_else(|p| p.into_inner());
|
||||
self.state(id, -2);
|
||||
|
||||
@@ -27,4 +27,39 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Requantize the phase-1 gate/up outputs of every lane of `jobs` for the down phase.
|
||||
///
|
||||
/// # Safety
|
||||
/// Done AND parked (no worker touches `split`); `jobs.len() <= split.len()` and each `nt <= 8`.
|
||||
pub(super) unsafe fn quantize_lanes(&self, jobs: &[Job], fmt: Option<&NativeFormat>) -> Result<()> {
|
||||
for (e, job) in jobs.iter().enumerate() {
|
||||
let s = unsafe { &mut *self.split[e].get() };
|
||||
for t in 0..job.nt {
|
||||
match fmt {
|
||||
Some(f) => unsafe { quantize_native_lane(s, t, f) },
|
||||
None => s.a2[t].quantize(&s.ff[t])?,
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Native-format lane `t`: Q2 down rows use the Q8 one-block quantizer, other kinds the raw GGML quantizer.
|
||||
///
|
||||
/// # Safety
|
||||
/// `t < 8`; the Q8 and raw quantizers need their destination sized for one lane (guaranteed by `Split`).
|
||||
unsafe fn quantize_native_lane(s: &mut Split, t: usize, f: &NativeFormat) {
|
||||
unsafe {
|
||||
if f.down.original_id() == 42 {
|
||||
let a = &mut s.a2[t].0;
|
||||
if super::super::rust_simd::dispatch().avx512 {
|
||||
super::super::rust_quant::q8_one_avx512(&s.ff[t], a);
|
||||
} else {
|
||||
super::super::rust_quant::q8_one_avx2(&s.ff[t], a);
|
||||
}
|
||||
} else {
|
||||
super::super::rust_ggml::quantize_raw(f.down, &s.ff[t], &mut s.hq[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,30 +78,33 @@ mod tests {
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
#[repr(C, align(8))]
|
||||
struct Aligned([u8; 512]);
|
||||
// quantize_raw reinterprets `dst` as Q8Zero / Q8K / u16: a short or misaligned destination must be refused, not
|
||||
// written through.
|
||||
// quantize_raw reinterprets `dst` as Q8Zero / Q8K / u16: a short or misaligned destination must be refused, not written through.
|
||||
#[test]
|
||||
fn quantize_raw_refuses_a_short_or_misaligned_destination() {
|
||||
let x = [0.5f32; 64];
|
||||
let k = [0.5f32; 256];
|
||||
let mut a = Aligned([0; 512]);
|
||||
assert!(quantize_is_refused(Kind::Q8Zero, &x, &mut a.0[..67]), "67 < 68 bytes");
|
||||
assert!(quantize_is_refused(Kind::Q8Zero, &x, &mut a.0[1..69]), "odd address");
|
||||
assert!(quantize_is_refused(Kind::Q4K, &k, &mut a.0[2..2 + 292]), "Q8K needs 4-byte alignment");
|
||||
// SAFETY (all calls): the destination checks are the asserts under test; no CPU leaf runs unless they pass (last block, avx2_ok()).
|
||||
assert!(
|
||||
catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(Kind::Q8Zero, &x, &mut a.0[..67]) })).is_err(),
|
||||
"67 < 68 bytes"
|
||||
);
|
||||
assert!(
|
||||
catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(Kind::Q8Zero, &x, &mut a.0[1..69]) })).is_err(),
|
||||
"odd address"
|
||||
);
|
||||
assert!(
|
||||
catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(Kind::Q4K, &k, &mut a.0[2..2 + 292]) })).is_err(),
|
||||
"Q8K needs 4-byte alignment"
|
||||
);
|
||||
if super::super::rust_simd::avx2_ok() {
|
||||
// SAFETY: avx2_ok() above; the destination holds the 68 bytes of two Q8Zero blocks and is 8-byte aligned.
|
||||
unsafe {
|
||||
quantize_raw(Kind::Q8Zero, &x, &mut a.0[..68]);
|
||||
}
|
||||
assert_ne!(&a.0[..2], &[0, 0], "FP16 block scale written");
|
||||
}
|
||||
}
|
||||
fn quantize_is_refused(kind: Kind, x: &[f32], dst: &mut [u8]) -> bool {
|
||||
// SAFETY: the destination checks are the asserts under test; no CPU leaf runs unless they pass.
|
||||
catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(kind, x, dst) })).is_err()
|
||||
}
|
||||
// The generic float dot reads `row` through raw 256-bit loads sized by the activation: a row shorter than 4 bytes
|
||||
// per f32 is refused.
|
||||
// The generic float dot reads `row` through raw 256-bit loads sized by the activation: a row shorter than 4 bytes per f32 is refused.
|
||||
#[test]
|
||||
fn float_dot_refuses_a_row_shorter_than_the_activation() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
@@ -119,21 +122,18 @@ mod tests {
|
||||
}
|
||||
|
||||
mod impl_kind;
|
||||
mod kind_table;
|
||||
#[allow(unused_imports)]
|
||||
use impl_kind::alloc;
|
||||
#[allow(unused_imports)]
|
||||
use impl_kind::round_bf16_scalar;
|
||||
use impl_kind::bf16_bits;
|
||||
mod impl_nativeformat;
|
||||
#[allow(unused_imports)]
|
||||
pub use impl_nativeformat::dot;
|
||||
#[allow(unused_imports)]
|
||||
use impl_nativeformat::dot_k_blocks;
|
||||
#[allow(unused_imports)]
|
||||
use impl_nativeformat::dot_zero_blocks;
|
||||
#[allow(unused_imports)]
|
||||
use impl_nativeformat::float_dot;
|
||||
#[allow(unused_imports)]
|
||||
use impl_nativeformat::iq4nl_dot;
|
||||
#[allow(unused_imports)]
|
||||
use impl_nativeformat::q1_dot;
|
||||
#[allow(unused_imports)]
|
||||
use impl_nativeformat::q2_generic;
|
||||
|
||||
@@ -1,19 +1,90 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Kind, impl ActKind, fn alloc, impl Activation.
|
||||
|
||||
use super::kind_table::KIND_TABLE;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Every `Kind` in declaration order; `KIND_IDS` and `KIND_BLOCKS` are indexed by `kind as usize`.
|
||||
const KINDS: [Kind; 28] = [
|
||||
Kind::F32,
|
||||
Kind::F16,
|
||||
Kind::Q4Zero,
|
||||
Kind::Q4One,
|
||||
Kind::Q5Zero,
|
||||
Kind::Q5One,
|
||||
Kind::Q8Zero,
|
||||
Kind::Q2K,
|
||||
Kind::Q3K,
|
||||
Kind::Q4K,
|
||||
Kind::Q5K,
|
||||
Kind::Q6K,
|
||||
Kind::Iq2Xxs,
|
||||
Kind::Iq2Xs,
|
||||
Kind::Iq3Xxs,
|
||||
Kind::Iq1S,
|
||||
Kind::Iq4Nl,
|
||||
Kind::Iq3S,
|
||||
Kind::Iq2S,
|
||||
Kind::Iq4Xs,
|
||||
Kind::Iq1M,
|
||||
Kind::Bf16,
|
||||
Kind::Tq1,
|
||||
Kind::Tq2,
|
||||
Kind::MxFp4,
|
||||
Kind::NvFp4,
|
||||
Kind::Q1Zero,
|
||||
Kind::Q2Zero,
|
||||
];
|
||||
/// The Original (ggml) type id of each `Kind`.
|
||||
const KIND_IDS: [i32; 28] =
|
||||
[0, 1, 2, 3, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 29, 30, 34, 35, 39, 40, 41, 42];
|
||||
/// Weights per block and bytes per block of each `Kind`.
|
||||
const KIND_BLOCKS: [(usize, usize); 28] = [
|
||||
(1, 4), // F32
|
||||
(1, 2), // F16
|
||||
(32, 18), // Q4Zero
|
||||
(32, 20), // Q4One
|
||||
(32, 22), // Q5Zero
|
||||
(32, 24), // Q5One
|
||||
(32, 34), // Q8Zero
|
||||
(256, 84), // Q2K
|
||||
(256, 110), // Q3K
|
||||
(256, 144), // Q4K
|
||||
(256, 176), // Q5K
|
||||
(256, 210), // Q6K
|
||||
(256, 66), // Iq2Xxs
|
||||
(256, 74), // Iq2Xs
|
||||
(256, 98), // Iq3Xxs
|
||||
(256, 50), // Iq1S
|
||||
(32, 18), // Iq4Nl
|
||||
(256, 110), // Iq3S
|
||||
(256, 82), // Iq2S
|
||||
(256, 136), // Iq4Xs
|
||||
(256, 56), // Iq1M
|
||||
(1, 2), // Bf16
|
||||
(256, 54), // Tq1
|
||||
(256, 66), // Tq2
|
||||
(32, 17), // MxFp4
|
||||
(64, 36), // NvFp4
|
||||
(128, 18), // Q1Zero
|
||||
(64, 18), // Q2Zero
|
||||
];
|
||||
// `KINDS` lists the variants in declaration order, so a kind indexes the tables above.
|
||||
const _: () = {
|
||||
let mut i = 0;
|
||||
while i < KINDS.len() {
|
||||
assert!(KINDS[i] as usize == i);
|
||||
i += 1;
|
||||
}
|
||||
};
|
||||
impl Kind {
|
||||
pub fn from_original(type_id: i32) -> Result<Self> {
|
||||
KIND_TABLE.iter().find(|row| row.id == type_id).map(|row| row.kind).ok_or(Error::Unsupported)
|
||||
KIND_IDS.iter().position(|&id| id == type_id).map(|at| KINDS[at]).ok_or(Error::Unsupported)
|
||||
}
|
||||
pub fn original_id(self) -> i32 {
|
||||
self.info().id
|
||||
KIND_IDS[self as usize]
|
||||
}
|
||||
pub fn block(self) -> (usize, usize) {
|
||||
let row = self.info();
|
||||
(row.block_elems, row.block_bytes)
|
||||
KIND_BLOCKS[self as usize]
|
||||
}
|
||||
pub fn row_bytes(self, n: usize) -> Result<usize> {
|
||||
let (q, b) = self.block();
|
||||
@@ -74,78 +145,17 @@ pub(super) fn alloc<T: Default>(n: usize) -> Result<Vec<T>> {
|
||||
v.resize_with(n, T::default);
|
||||
Ok(v)
|
||||
}
|
||||
impl Activation {
|
||||
pub fn quantize(weight_kind: Kind, input: &[f32]) -> Result<Self> {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
let kind = weight_kind.act();
|
||||
kind.bytes(input.len())?;
|
||||
let n = input.len();
|
||||
let data = Self::encode(kind, input)?;
|
||||
Ok(Self { kind, n, data })
|
||||
}
|
||||
// Only called from quantize() after avx2_ok() proved AVX2+FMA+F16C and `kind.bytes(input.len())` proved the block
|
||||
// geometry (n % block == 0); the encoders below rely on both.
|
||||
fn encode(kind: ActKind, input: &[f32]) -> Result<Storage> {
|
||||
match kind {
|
||||
ActKind::F32 => Self::encode_f32(input),
|
||||
ActKind::F16 => Self::encode_f16(input),
|
||||
ActKind::Bf16 => Self::encode_bf16(input),
|
||||
ActKind::Zero => Self::encode_zero(input),
|
||||
ActKind::One => Self::encode_one(input),
|
||||
ActKind::K => Self::encode_k(input),
|
||||
}
|
||||
}
|
||||
fn encode_f32(input: &[f32]) -> Result<Storage> {
|
||||
let mut v = alloc(input.len())?;
|
||||
v.copy_from_slice(input);
|
||||
Ok(Storage::F32(v))
|
||||
}
|
||||
fn encode_f16(input: &[f32]) -> Result<Storage> {
|
||||
let mut v = alloc(input.len())?;
|
||||
for (&x, v) in input.iter().zip(&mut v) {
|
||||
// SAFETY: encode() runs after quantize() proved F16C with avx2_ok().
|
||||
*v = unsafe { to_half(x) };
|
||||
}
|
||||
Ok(Storage::Half(v))
|
||||
}
|
||||
fn encode_bf16(input: &[f32]) -> Result<Storage> {
|
||||
let mut v = alloc(input.len())?;
|
||||
// SAFETY: encode() runs after quantize() proved AVX2 with avx2_ok(); `v` has `input.len()` elements.
|
||||
if !unsafe { super::super::rust_ggml_native::convert_bf16(input, &mut v) } {
|
||||
round_bf16_scalar(input, &mut v);
|
||||
}
|
||||
Ok(Storage::Half(v))
|
||||
}
|
||||
fn encode_zero(input: &[f32]) -> Result<Storage> {
|
||||
let mut v = alloc(input.len() / 32)?;
|
||||
// SAFETY: encode() runs after quantize() proved AVX2+FMA+F16C (avx2_ok()); `v` holds one Q8Zero per 32 inputs.
|
||||
unsafe {
|
||||
super::super::rust_quant::q8_zero(input, &mut v);
|
||||
}
|
||||
Ok(Storage::Zero(v))
|
||||
}
|
||||
fn encode_one(input: &[f32]) -> Result<Storage> {
|
||||
let mut v = alloc(input.len() / 32)?;
|
||||
// SAFETY: encode() runs after quantize() proved AVX2+FMA+F16C (avx2_ok()); `v` holds one Q8One per 32 inputs.
|
||||
unsafe {
|
||||
super::super::rust_kq::quant_one(input, &mut v);
|
||||
}
|
||||
Ok(Storage::One(v))
|
||||
}
|
||||
fn encode_k(input: &[f32]) -> Result<Storage> {
|
||||
let mut v = alloc(input.len() / 256)?;
|
||||
super::super::rust_quant::q8_k(input, &mut v);
|
||||
Ok(Storage::K(v))
|
||||
}
|
||||
pub fn encoded_bytes(&self) -> Result<usize> {
|
||||
self.kind.bytes(self.n)
|
||||
/// F16 activation: every element converted to half precision.
|
||||
fn store_f16(input: &[f32]) -> Result<Storage> {
|
||||
let mut v = alloc(input.len())?;
|
||||
for (&x, v) in input.iter().zip(&mut v) {
|
||||
// SAFETY: the caller proved avx2_ok() (AVX2+FMA+F16C).
|
||||
*v = unsafe { to_half(x) };
|
||||
}
|
||||
Ok(Storage::Half(v))
|
||||
}
|
||||
/// Round one f32 to its BF16 bits (round to nearest even; a NaN keeps a quiet payload bit).
|
||||
#[inline]
|
||||
fn bf16_bits(x: f32) -> u16 {
|
||||
/// Round-to-nearest-even bf16 of `x`; NaNs keep a set quiet bit.
|
||||
pub(super) fn bf16_bits(x: f32) -> u16 {
|
||||
let b = x.to_bits();
|
||||
if b & 0x7fffffff > 0x7f800000 {
|
||||
((b >> 16) | 64) as u16
|
||||
@@ -153,9 +163,60 @@ fn bf16_bits(x: f32) -> u16 {
|
||||
(b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16) as u16
|
||||
}
|
||||
}
|
||||
/// Round `src` into `dst` element by element (`zip` stops at the shorter slice).
|
||||
pub(super) fn round_bf16_scalar(src: &[f32], dst: &mut [u16]) {
|
||||
for (&x, v) in src.iter().zip(dst) {
|
||||
*v = bf16_bits(x);
|
||||
/// BF16 activation: the native converter when available, else the scalar rounding.
|
||||
fn store_bf16(input: &[f32]) -> Result<Storage> {
|
||||
let mut v = alloc(input.len())?;
|
||||
// SAFETY: the caller proved avx2_ok() (AVX2+FMA+F16C); `v` has one slot per input element.
|
||||
if !unsafe { super::super::rust_ggml_native::convert_bf16(input, &mut v) } {
|
||||
for (&x, v) in input.iter().zip(&mut v) {
|
||||
*v = bf16_bits(x);
|
||||
}
|
||||
}
|
||||
Ok(Storage::Half(v))
|
||||
}
|
||||
/// The owned activation storage of `input` in the encoding `kind` (n % block == 0 was checked).
|
||||
fn storage(kind: ActKind, input: &[f32]) -> Result<Storage> {
|
||||
let n = input.len();
|
||||
match kind {
|
||||
ActKind::F32 => {
|
||||
let mut v = alloc(n)?;
|
||||
v.copy_from_slice(input);
|
||||
Ok(Storage::F32(v))
|
||||
}
|
||||
ActKind::F16 => store_f16(input),
|
||||
ActKind::Bf16 => store_bf16(input),
|
||||
ActKind::Zero => {
|
||||
let mut v = alloc(n / 32)?;
|
||||
// SAFETY: the caller proved avx2_ok(); `v` holds one block per 32 inputs.
|
||||
unsafe { super::super::rust_quant::q8_zero(input, &mut v) };
|
||||
Ok(Storage::Zero(v))
|
||||
}
|
||||
ActKind::One => {
|
||||
let mut v = alloc(n / 32)?;
|
||||
// SAFETY: the caller proved avx2_ok(); `v` holds one block per 32 inputs.
|
||||
unsafe { super::super::rust_kq::quant_one(input, &mut v) };
|
||||
Ok(Storage::One(v))
|
||||
}
|
||||
ActKind::K => {
|
||||
let mut v = alloc(n / 256)?;
|
||||
super::super::rust_quant::q8_k(input, &mut v);
|
||||
Ok(Storage::K(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Activation {
|
||||
pub fn quantize(weight_kind: Kind, input: &[f32]) -> Result<Self> {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
// SAFETY (every unsafe block in `storage`): avx2_ok() above proved AVX2+FMA+F16C; all vector lengths derive
|
||||
// from kind.bytes(n) (n % block == 0) and each callee asserts its own slice lengths.
|
||||
let kind = weight_kind.act();
|
||||
kind.bytes(input.len())?;
|
||||
let data = storage(kind, input)?;
|
||||
Ok(Self { kind, n: input.len(), data })
|
||||
}
|
||||
pub fn encoded_bytes(&self) -> Result<usize> {
|
||||
self.kind.bytes(self.n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,14 +4,25 @@
|
||||
use super::*;
|
||||
|
||||
impl NativeFormat {
|
||||
/// Byte offsets of the up matrix, the down matrix and the whole blob for the given row sizes.
|
||||
fn offsets(gu_row: usize, down_row: usize, n_embd: usize, n_ff: usize) -> Result<(usize, usize, usize)> {
|
||||
let up_offset = gu_row.checked_mul(n_ff).ok_or(Error::Shape)?;
|
||||
let down_offset = up_offset.checked_mul(2).ok_or(Error::Shape)?;
|
||||
let bytes = down_row.checked_mul(n_embd).and_then(|b| b.checked_add(down_offset)).ok_or(Error::Shape)?;
|
||||
Ok((up_offset, down_offset, bytes))
|
||||
}
|
||||
pub fn new(gu: Kind, down: Kind, n_embd: usize, n_ff: usize) -> Result<Self> {
|
||||
if n_embd == 0 || n_ff == 0 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let gu_row = gu.row_bytes(n_embd)?;
|
||||
let down_row = down.row_bytes(n_ff)?;
|
||||
let (activation_bytes, hidden_bytes) = Self::activation_sizes(gu, down, n_embd, n_ff)?;
|
||||
let (up_offset, down_offset, bytes) = Self::bank_layout(gu_row, down_row, n_embd, n_ff)?;
|
||||
let activation_bytes = gu.act().bytes(n_embd)?;
|
||||
let hidden_bytes = down.act().bytes(n_ff)?;
|
||||
if activation_bytes > 4096 || hidden_bytes > 1024 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let (up_offset, down_offset, bytes) = Self::offsets(gu_row, down_row, n_embd, n_ff)?;
|
||||
Ok(Self {
|
||||
gu,
|
||||
down,
|
||||
@@ -26,22 +37,6 @@ impl NativeFormat {
|
||||
hidden_bytes,
|
||||
})
|
||||
}
|
||||
// The encoded input (`gu` side) and hidden (`down` side) sizes, refused when they exceed the pool's fixed buffers.
|
||||
fn activation_sizes(gu: Kind, down: Kind, n_embd: usize, n_ff: usize) -> Result<(usize, usize)> {
|
||||
let activation_bytes = gu.act().bytes(n_embd)?;
|
||||
let hidden_bytes = down.act().bytes(n_ff)?;
|
||||
if activation_bytes > 4096 || hidden_bytes > 1024 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok((activation_bytes, hidden_bytes))
|
||||
}
|
||||
// The (up_offset, down_offset, total bytes) of one expert bank: gate rows, up rows, then down rows.
|
||||
fn bank_layout(gu_row: usize, down_row: usize, n_embd: usize, n_ff: usize) -> Result<(usize, usize, usize)> {
|
||||
let up_offset = gu_row.checked_mul(n_ff).ok_or(Error::Shape)?;
|
||||
let down_offset = up_offset.checked_mul(2).ok_or(Error::Shape)?;
|
||||
let bytes = down_row.checked_mul(n_embd).and_then(|b| b.checked_add(down_offset)).ok_or(Error::Shape)?;
|
||||
Ok((up_offset, down_offset, bytes))
|
||||
}
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
let f = Self::new(self.gu, self.down, self.n_embd, self.n_ff)?;
|
||||
if self.gu_row != f.gu_row
|
||||
@@ -57,6 +52,73 @@ impl NativeFormat {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// IQ4_NL row against a Q8_0 activation: the paired blocks through the SIMD kernel, an odd last block scalar.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok(); `row.len() == row_bytes(n)` for `v.len()` blocks.
|
||||
pub(super) unsafe fn iq4nl_dot(row: &[u8], v: &[Q8Zero]) -> f32 {
|
||||
unsafe {
|
||||
let paired = v.len() / 2 * 2;
|
||||
let mut out = [0.0];
|
||||
super::super::rust_iq::iq4nl(&row[..paired * 18], &[&v[..paired]], &mut out, true);
|
||||
if paired < v.len() {
|
||||
let b = &row[paired * 18..];
|
||||
let y = v[paired];
|
||||
let values = &super::super::rust_codebooks::KVALUES_IQ4NL;
|
||||
let mut a = 0i32;
|
||||
let mut c = 0i32;
|
||||
for j in 0..16 {
|
||||
a += y.qs[j] as i32 * values[(b[2 + j] & 15) as usize] as i32;
|
||||
c += y.qs[j + 16] as i32 * values[(b[2 + j] >> 4) as usize] as i32;
|
||||
}
|
||||
out[0] += (half(y.d) * half(u16::from_le_bytes([b[0], b[1]]))) * (a + c) as f32;
|
||||
}
|
||||
out[0]
|
||||
}
|
||||
}
|
||||
/// Row product against a Q8_0-style (`Zero`) activation.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `dot`.
|
||||
unsafe fn dot_zero(kind: Kind, row: &[u8], v: &[Q8Zero]) -> Result<f32> {
|
||||
unsafe {
|
||||
match kind {
|
||||
Kind::Iq4Nl => Ok(iq4nl_dot(row, v)),
|
||||
Kind::Q2Zero => Ok(q2_generic(row, v)),
|
||||
Kind::Q1Zero => Ok(q1_dot(row, v)),
|
||||
Kind::MxFp4 => Ok(super::super::rust_ggml_extra::mxfp4(row, v)),
|
||||
Kind::NvFp4 => Ok(super::super::rust_ggml_extra::nvfp4(row, v)),
|
||||
Kind::Q4Zero | Kind::Q5Zero | Kind::Q8Zero => {
|
||||
Ok(super::super::rust_kq::small_dot(kind.original_id(), row, Some(v), None))
|
||||
}
|
||||
_ => Err(Error::Unsupported),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Row product against a Q8_K (`K`) activation.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `dot`.
|
||||
unsafe fn dot_k(kind: Kind, row: &[u8], v: &[Q8K]) -> Result<f32> {
|
||||
unsafe {
|
||||
match kind {
|
||||
Kind::Iq1S | Kind::Iq1M => Ok(super::super::rust_ggml_extra::iq1(kind.original_id(), row, v)),
|
||||
Kind::Tq1 | Kind::Tq2 => Ok(super::super::rust_ggml_extra::ternary(kind.original_id(), row, v)),
|
||||
Kind::Q4K => {
|
||||
let mut out = [0.0];
|
||||
super::super::rust_kq::q4_k_dot(row, &[v], &mut out);
|
||||
Ok(out[0])
|
||||
}
|
||||
Kind::Q2K | Kind::Q3K | Kind::Q5K | Kind::Q6K => {
|
||||
Ok(super::super::rust_k_blocks::dot(kind.original_id(), row, v))
|
||||
}
|
||||
Kind::Iq2Xxs | Kind::Iq2Xs | Kind::Iq3Xxs | Kind::Iq3S | Kind::Iq2S | Kind::Iq4Xs => {
|
||||
Ok(super::super::rust_iq::dot_single(kind.original_id(), row, v))
|
||||
}
|
||||
_ => Err(Error::Unsupported),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn dot(kind: Kind, row: &[u8], activation: &Activation) -> Result<f32> {
|
||||
if row.len() != kind.row_bytes(activation.n)? || activation.kind != kind.act() {
|
||||
return Err(Error::Shape);
|
||||
@@ -65,98 +127,70 @@ pub fn dot(kind: Kind, row: &[u8], activation: &Activation) -> Result<f32> {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
// SAFETY: avx2_ok() above; `row.len() == row_bytes(n)` and `activation.kind == kind.act()` were checked, and
|
||||
// `activation.data` was built by quantize() for exactly n elements of that encoding, so every kernel gets whole,
|
||||
// equal-count blocks.
|
||||
unsafe { dot_storage(kind, row, &activation.data) }
|
||||
}
|
||||
/// # Safety
|
||||
/// The CPU gate (avx2_ok()); `row` is a whole weight row of `kind` and `data` its activation encoded with `kind.act()`
|
||||
/// for the same element count.
|
||||
unsafe fn dot_storage(kind: Kind, row: &[u8], data: &Storage) -> Result<f32> {
|
||||
// `activation.data` was built by quantize() for exactly n elements of that encoding, so every kernel below gets
|
||||
// whole, equal-count blocks.
|
||||
unsafe {
|
||||
match data {
|
||||
match &activation.data {
|
||||
Storage::F32(v) => Ok(float_dot(kind, row, v, &[])),
|
||||
Storage::Half(v) => Ok(float_dot(kind, row, &[], v)),
|
||||
Storage::Zero(v) => dot_zero_blocks(kind, row, v).ok_or(Error::Unsupported),
|
||||
Storage::Zero(v) => dot_zero(kind, row, v),
|
||||
Storage::One(v) => Ok(super::super::rust_kq::small_dot(kind.original_id(), row, None, Some(v))),
|
||||
Storage::K(v) => dot_k_blocks(kind, row, v).ok_or(Error::Unsupported),
|
||||
Storage::K(v) => dot_k(kind, row, v),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The row product of a `Zero`-encoded activation; `None` for a kind that is not stored with it.
|
||||
///
|
||||
/// # Safety
|
||||
/// The CPU gate (avx2_ok()); `row` is a whole weight row of `kind` and `y` its activation, one block per 32 elements.
|
||||
pub(super) unsafe fn dot_zero_blocks(kind: Kind, row: &[u8], y: &[Q8Zero]) -> Option<f32> {
|
||||
/// One 8-lane pair of operands of `float_dot`: the row's and the activation's elements `i..i + 8`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn float_lanes(kind: Kind, row: &[u8], f: &[f32], h: &[u16], i: usize) -> (__m256, __m256) {
|
||||
unsafe {
|
||||
Some(match kind {
|
||||
Kind::Iq4Nl => iq4nl_dot(row, y),
|
||||
Kind::Q2Zero => q2_generic(row, y),
|
||||
Kind::Q1Zero => q1_dot(row, y),
|
||||
Kind::MxFp4 => super::super::rust_ggml_extra::mxfp4(row, y),
|
||||
Kind::NvFp4 => super::super::rust_ggml_extra::nvfp4(row, y),
|
||||
Kind::Q4Zero | Kind::Q5Zero | Kind::Q8Zero => {
|
||||
super::super::rust_kq::small_dot(kind.original_id(), row, Some(y), None)
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
/// The row product of a `K`-encoded activation; `None` for a kind that is not stored with it.
|
||||
///
|
||||
/// # Safety
|
||||
/// The CPU gate (avx2_ok()); `row` is a whole weight row of `kind` and `y` its activation, one block per 256 elements.
|
||||
pub(super) unsafe fn dot_k_blocks(kind: Kind, row: &[u8], y: &[Q8K]) -> Option<f32> {
|
||||
unsafe {
|
||||
Some(match kind {
|
||||
Kind::Iq1S | Kind::Iq1M => super::super::rust_ggml_extra::iq1(kind.original_id(), row, y),
|
||||
Kind::Tq1 | Kind::Tq2 => super::super::rust_ggml_extra::ternary(kind.original_id(), row, y),
|
||||
Kind::Q4K => {
|
||||
let mut out = [0.0];
|
||||
super::super::rust_kq::q4_k_dot(row, &[y], &mut out);
|
||||
out[0]
|
||||
}
|
||||
Kind::Q2K | Kind::Q3K | Kind::Q5K | Kind::Q6K => {
|
||||
super::super::rust_k_blocks::dot(kind.original_id(), row, y)
|
||||
}
|
||||
Kind::Iq2Xxs | Kind::Iq2Xs | Kind::Iq3Xxs | Kind::Iq3S | Kind::Iq2S | Kind::Iq4Xs => {
|
||||
super::super::rust_iq::dot_single(kind.original_id(), row, y)
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
/// IQ4_NL row product: whole block pairs through the vector kernel, an odd last block through the scalar tail.
|
||||
///
|
||||
/// # Safety
|
||||
/// The CPU gate (avx2_ok()); `row` holds `y.len()` IQ4_NL blocks of 18 bytes.
|
||||
#[inline(always)]
|
||||
unsafe fn iq4nl_dot(row: &[u8], y: &[Q8Zero]) -> f32 {
|
||||
unsafe {
|
||||
let paired = y.len() / 2 * 2;
|
||||
let mut out = [0.0];
|
||||
super::super::rust_iq::iq4nl(&row[..paired * 18], &[&y[..paired]], &mut out, true);
|
||||
if paired < y.len() {
|
||||
out[0] += iq4nl_tail(&row[paired * 18..], y[paired]);
|
||||
match kind {
|
||||
Kind::F32 => (_mm256_loadu_ps(row.as_ptr().add(i * 4).cast()), _mm256_loadu_ps(f.as_ptr().add(i))),
|
||||
Kind::F16 => (
|
||||
_mm256_cvtph_ps(_mm_loadu_si128(row.as_ptr().add(i * 2).cast())),
|
||||
_mm256_cvtph_ps(_mm_loadu_si128(h.as_ptr().add(i).cast())),
|
||||
),
|
||||
Kind::Bf16 => (
|
||||
_mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128(
|
||||
row.as_ptr().add(i * 2).cast(),
|
||||
)))),
|
||||
_mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128(
|
||||
h.as_ptr().add(i).cast(),
|
||||
)))),
|
||||
),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
out[0]
|
||||
}
|
||||
}
|
||||
/// The product of one IQ4_NL block `b` (2 scale bytes, 16 nibble bytes) with the activation block `y`.
|
||||
///
|
||||
/// # Safety
|
||||
/// The CPU gate (avx2_ok(), F16C for `half`); `b` holds at least 18 bytes.
|
||||
#[inline(always)]
|
||||
unsafe fn iq4nl_tail(b: &[u8], y: Q8Zero) -> f32 {
|
||||
/// The scalar tail `np..n` of a half/bf16 `float_dot`, added to `s` in double precision.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn float_tail_half(kind: Kind, row: &[u8], h: &[u16], (np, n): (usize, usize), mut s: f64) -> f32 {
|
||||
unsafe {
|
||||
let values = &super::super::rust_codebooks::KVALUES_IQ4NL;
|
||||
let mut a = 0i32;
|
||||
let mut c = 0i32;
|
||||
for j in 0..16 {
|
||||
a += y.qs[j] as i32 * values[(b[2 + j] & 15) as usize] as i32;
|
||||
c += y.qs[j + 16] as i32 * values[(b[2 + j] >> 4) as usize] as i32;
|
||||
for i in np..n {
|
||||
let a = u16::from_le_bytes([row[i * 2], row[i * 2 + 1]]);
|
||||
let (a, b) = if kind == Kind::Bf16 {
|
||||
(f32::from_bits((a as u32) << 16), f32::from_bits((h[i] as u32) << 16))
|
||||
} else {
|
||||
(half(a), half(h[i]))
|
||||
};
|
||||
s += (a * b) as f64;
|
||||
}
|
||||
s as f32
|
||||
}
|
||||
}
|
||||
/// Reduce the lane sums and add the scalar tail `np..n` of `float_dot`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn float_finish(kind: Kind, row: &[u8], (f, h): (&[f32], &[u16]), sum: __m256, (np, n): (usize, usize)) -> f32 {
|
||||
unsafe {
|
||||
if kind == Kind::F32 {
|
||||
let mut s = hsum_original(sum);
|
||||
for i in np..n {
|
||||
s += f32::from_le_bytes(row[i * 4..i * 4 + 4].try_into().unwrap()) * f[i];
|
||||
}
|
||||
s
|
||||
} else {
|
||||
let s = if kind == Kind::Bf16 { hsum_ggml(sum) } else { hsum_original(sum) } as f64;
|
||||
float_tail_half(kind, row, h, (np, n), s)
|
||||
}
|
||||
(half(y.d) * half(u16::from_le_bytes([b[0], b[1]]))) * (a + c) as f32
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
@@ -168,99 +202,19 @@ pub(super) unsafe fn float_dot(kind: Kind, row: &[u8], f: &[f32], h: &[u16]) ->
|
||||
return value;
|
||||
}
|
||||
let np = n & !31;
|
||||
let sum = float_vector_sum(kind, row, f, h, np);
|
||||
if kind == Kind::F32 { float_tail_f32(row, f, sum, np, n) } else { float_tail_half(kind, row, h, sum, np, n) }
|
||||
}
|
||||
}
|
||||
/// The eight-lane partial sums of the first `np` elements (a multiple of 32): four accumulators, combined (0+2)+(1+3).
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2+FMA+F16C; `row` holds `np` elements of `kind` and the matching activation slice (`f` for F32, else `h`) too.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn float_vector_sum(kind: Kind, row: &[u8], f: &[f32], h: &[u16], np: usize) -> __m256 {
|
||||
unsafe {
|
||||
let mut acc = [_mm256_setzero_ps(); 4];
|
||||
for at in (0..np).step_by(32) {
|
||||
for j in 0..4 {
|
||||
let (x, y) = float_load_pair(kind, row, f, h, at + j * 8);
|
||||
acc[j] = float_accumulate(kind, x, y, acc[j]);
|
||||
let (x, y) = float_lanes(kind, row, f, h, at + j * 8);
|
||||
acc[j] = if kind == Kind::Bf16 {
|
||||
_mm256_add_ps(_mm256_mul_ps(x, y), acc[j])
|
||||
} else {
|
||||
_mm256_fmadd_ps(x, y, acc[j])
|
||||
};
|
||||
}
|
||||
}
|
||||
_mm256_add_ps(_mm256_add_ps(acc[0], acc[2]), _mm256_add_ps(acc[1], acc[3]))
|
||||
}
|
||||
}
|
||||
/// Eight weights and the eight matching activations starting at element `i`.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2+FMA+F16C; elements `i..i + 8` exist in `row` and in `f` (F32) or `h` (F16/BF16); `kind` is F32, F16 or BF16.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn float_load_pair(kind: Kind, row: &[u8], f: &[f32], h: &[u16], i: usize) -> (__m256, __m256) {
|
||||
unsafe {
|
||||
match kind {
|
||||
Kind::F32 => (_mm256_loadu_ps(row.as_ptr().add(i * 4).cast()), _mm256_loadu_ps(f.as_ptr().add(i))),
|
||||
Kind::F16 => (
|
||||
_mm256_cvtph_ps(_mm_loadu_si128(row.as_ptr().add(i * 2).cast())),
|
||||
_mm256_cvtph_ps(_mm_loadu_si128(h.as_ptr().add(i).cast())),
|
||||
),
|
||||
Kind::Bf16 => (bf16_widen(row.as_ptr().add(i * 2).cast()), bf16_widen(h.as_ptr().add(i).cast())),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Eight BF16 values widened to f32 lanes (a BF16 is the high half of its f32).
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2; `p` points at 16 readable bytes.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn bf16_widen(p: *const __m128i) -> __m256 {
|
||||
unsafe { _mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128(p)))) }
|
||||
}
|
||||
/// `acc + x * y`: a separate multiply and add for BF16, a fused multiply-add otherwise.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2+FMA.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn float_accumulate(kind: Kind, x: __m256, y: __m256, acc: __m256) -> __m256 {
|
||||
if kind == Kind::Bf16 { _mm256_add_ps(_mm256_mul_ps(x, y), acc) } else { _mm256_fmadd_ps(x, y, acc) }
|
||||
}
|
||||
/// The F32 dot of the vector sum plus the scalar elements `np..n`, accumulated in f32.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2; `row` holds `n` f32 values and `f` has `n` elements.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn float_tail_f32(row: &[u8], f: &[f32], sum: __m256, np: usize, n: usize) -> f32 {
|
||||
unsafe {
|
||||
let mut s = hsum_original(sum);
|
||||
for i in np..n {
|
||||
s += f32::from_le_bytes(row[i * 4..i * 4 + 4].try_into().unwrap()) * f[i];
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
/// The F16 / BF16 dot of the vector sum plus the scalar elements `np..n`, accumulated in f64.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2+F16C; `row` holds `n` 16-bit values of `kind` and `h` has `n` elements.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn float_tail_half(kind: Kind, row: &[u8], h: &[u16], sum: __m256, np: usize, n: usize) -> f32 {
|
||||
unsafe {
|
||||
let mut s = if kind == Kind::Bf16 { hsum_ggml(sum) } else { hsum_original(sum) } as f64;
|
||||
for i in np..n {
|
||||
let a = u16::from_le_bytes([row[i * 2], row[i * 2 + 1]]);
|
||||
let (a, b) = if kind == Kind::Bf16 {
|
||||
(f32::from_bits((a as u32) << 16), f32::from_bits((h[i] as u32) << 16))
|
||||
} else {
|
||||
(half(a), half(h[i]))
|
||||
};
|
||||
s += (a * b) as f64;
|
||||
}
|
||||
s as f32
|
||||
let sum = _mm256_add_ps(_mm256_add_ps(acc[0], acc[2]), _mm256_add_ps(acc[1], acc[3]));
|
||||
float_finish(kind, row, (f, h), sum, (np, n))
|
||||
}
|
||||
}
|
||||
// SAFETY (the two `unsafe{half(..)}` below): private; reached only from dot()/dot_raw() after avx2_ok() proved F16C.
|
||||
@@ -283,60 +237,38 @@ pub(super) fn q2_generic(row: &[u8], y: &[Q8Zero]) -> f32 {
|
||||
}
|
||||
total
|
||||
}
|
||||
/// The 32 per-lane sign masks (-1 for a clear bit, 0 for a set one) of Q1 sub-block `k` of a block `x`.
|
||||
fn q1_signs(x: &[u8], k: usize) -> [i8; 32] {
|
||||
let mut signs = [0i8; 32];
|
||||
for j in 0..32 {
|
||||
signs[j] = if x[2 + k * 4 + j / 8] & (1 << (j % 8)) == 0 { -1 } else { 0 };
|
||||
}
|
||||
signs
|
||||
}
|
||||
/// `d * sum(sign * q)` of Q1 sub-block `k` of block `ib`, as 8 float lanes.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn q1_lane(x: &[u8], y: &Q8Zero, k: usize) -> (__m256, __m256) {
|
||||
unsafe {
|
||||
let signs = q1_signs(x, k);
|
||||
let mask = _mm256_loadu_si256(signs.as_ptr().cast());
|
||||
let q = _mm256_loadu_si256(y.qs.as_ptr().cast());
|
||||
let sy = _mm256_sub_epi8(_mm256_xor_si256(q, mask), mask);
|
||||
let p = _mm256_madd_epi16(_mm256_maddubs_epi16(_mm256_set1_epi8(1), sy), _mm256_set1_epi16(1));
|
||||
(_mm256_set1_ps(half(y.d)), _mm256_cvtepi32_ps(p))
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn q1_dot(row: &[u8], y: &[Q8Zero]) -> f32 {
|
||||
unsafe {
|
||||
let mut acc = _mm256_setzero_ps();
|
||||
for (ib, x) in row.chunks_exact(18).enumerate() {
|
||||
let block = q1_block_sum(x, y, ib);
|
||||
let mut block = _mm256_setzero_ps();
|
||||
for k in 0..4 {
|
||||
let (d, p) = q1_lane(x, &y[ib * 4 + k], k);
|
||||
block = if k == 0 { _mm256_mul_ps(d, p) } else { _mm256_fmadd_ps(d, p, block) };
|
||||
}
|
||||
acc = _mm256_fmadd_ps(_mm256_set1_ps(half(u16::from_le_bytes([x[0], x[1]]))), block, acc);
|
||||
}
|
||||
hsum_ggml(acc)
|
||||
}
|
||||
}
|
||||
/// The scaled integer products of one 128-element block `x` with its four activation blocks `y[ib * 4..ib * 4 + 4]`.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2+FMA+F16C; `x` holds 18 bytes and `y` has the four blocks of block `ib`.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn q1_block_sum(x: &[u8], y: &[Q8Zero], ib: usize) -> __m256 {
|
||||
unsafe {
|
||||
let mut block = _mm256_setzero_ps();
|
||||
for k in 0..4 {
|
||||
block = q1_accumulate(block, x, &y[ib * 4 + k], k);
|
||||
}
|
||||
block
|
||||
}
|
||||
}
|
||||
/// Adds sub-block `k` of `x` times the activation block `yk` to `block`: a plain product for `k == 0`, else fused.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2+FMA+F16C; `x` holds 18 bytes and `k < 4`.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn q1_accumulate(block: __m256, x: &[u8], yk: &Q8Zero, k: usize) -> __m256 {
|
||||
unsafe {
|
||||
let mask = q1_sign_mask(x, k);
|
||||
let q = _mm256_loadu_si256(yk.qs.as_ptr().cast());
|
||||
let sy = _mm256_sub_epi8(_mm256_xor_si256(q, mask), mask);
|
||||
let p = _mm256_madd_epi16(_mm256_maddubs_epi16(_mm256_set1_epi8(1), sy), _mm256_set1_epi16(1));
|
||||
let d = _mm256_set1_ps(half(yk.d));
|
||||
if k == 0 { _mm256_mul_ps(d, _mm256_cvtepi32_ps(p)) } else { _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(p), block) }
|
||||
}
|
||||
}
|
||||
/// The 32 sign bytes of sub-block `k` (-1 for a clear bit, 0 for a set one) as one vector.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2; `x` holds 18 bytes and `k < 4`.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn q1_sign_mask(x: &[u8], k: usize) -> __m256i {
|
||||
unsafe {
|
||||
let mut signs = [0i8; 32];
|
||||
for j in 0..32 {
|
||||
signs[j] = if x[2 + k * 4 + j / 8] & (1 << (j % 8)) == 0 { -1 } else { 0 };
|
||||
}
|
||||
_mm256_loadu_si256(signs.as_ptr().cast())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
//! The GGML type table of `Kind`: Original type id and `(elements, bytes)` per block, one row per variant.
|
||||
use super::Kind;
|
||||
|
||||
/// One row per `Kind` variant, in declaration order.
|
||||
pub(super) struct KindInfo {
|
||||
pub(super) kind: Kind,
|
||||
/// The Original (ggml) type id.
|
||||
pub(super) id: i32,
|
||||
/// Elements per block.
|
||||
pub(super) block_elems: usize,
|
||||
/// Bytes per block.
|
||||
pub(super) block_bytes: usize,
|
||||
}
|
||||
|
||||
const fn row(kind: Kind, id: i32, block_elems: usize, block_bytes: usize) -> KindInfo {
|
||||
KindInfo { kind, id, block_elems, block_bytes }
|
||||
}
|
||||
|
||||
pub(super) const KIND_COUNT: usize = 28;
|
||||
|
||||
pub(super) static KIND_TABLE: [KindInfo; KIND_COUNT] = [
|
||||
row(Kind::F32, 0, 1, 4),
|
||||
row(Kind::F16, 1, 1, 2),
|
||||
row(Kind::Q4Zero, 2, 32, 18),
|
||||
row(Kind::Q4One, 3, 32, 20),
|
||||
row(Kind::Q5Zero, 6, 32, 22),
|
||||
row(Kind::Q5One, 7, 32, 24),
|
||||
row(Kind::Q8Zero, 8, 32, 34),
|
||||
row(Kind::Q2K, 10, 256, 84),
|
||||
row(Kind::Q3K, 11, 256, 110),
|
||||
row(Kind::Q4K, 12, 256, 144),
|
||||
row(Kind::Q5K, 13, 256, 176),
|
||||
row(Kind::Q6K, 14, 256, 210),
|
||||
row(Kind::Iq2Xxs, 16, 256, 66),
|
||||
row(Kind::Iq2Xs, 17, 256, 74),
|
||||
row(Kind::Iq3Xxs, 18, 256, 98),
|
||||
row(Kind::Iq1S, 19, 256, 50),
|
||||
row(Kind::Iq4Nl, 20, 32, 18),
|
||||
row(Kind::Iq3S, 21, 256, 110),
|
||||
row(Kind::Iq2S, 22, 256, 82),
|
||||
row(Kind::Iq4Xs, 23, 256, 136),
|
||||
row(Kind::Iq1M, 29, 256, 56),
|
||||
row(Kind::Bf16, 30, 1, 2),
|
||||
row(Kind::Tq1, 34, 256, 54),
|
||||
row(Kind::Tq2, 35, 256, 66),
|
||||
row(Kind::MxFp4, 39, 32, 17),
|
||||
row(Kind::NvFp4, 40, 64, 36),
|
||||
row(Kind::Q1Zero, 41, 128, 18),
|
||||
row(Kind::Q2Zero, 42, 64, 18),
|
||||
];
|
||||
|
||||
// `Kind::info` indexes the table by discriminant: every row must sit at its variant's discriminant.
|
||||
const _: () = {
|
||||
let mut i = 0;
|
||||
while i < KIND_COUNT {
|
||||
assert!(KIND_TABLE[i].kind as usize == i);
|
||||
i += 1;
|
||||
}
|
||||
};
|
||||
|
||||
impl Kind {
|
||||
/// The table row of this variant.
|
||||
pub(super) fn info(self) -> &'static KindInfo {
|
||||
&KIND_TABLE[self as usize]
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,41 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Alignment the encoded activation of `kind` is reinterpreted with (F32: bytes, K: `Q8K`, others: `u16`/`Q8*`).
|
||||
fn raw_align(kind: Kind) -> usize {
|
||||
match kind.act() {
|
||||
ActKind::F32 => 1,
|
||||
ActKind::K => std::mem::align_of::<Q8K>(),
|
||||
_ => std::mem::align_of::<u16>(),
|
||||
}
|
||||
}
|
||||
/// F16 / BF16 activation written into `dst` as `x.len()` half words.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `quantize_raw` (avx2_ok(); `dst` holds `2 * x.len()` bytes aligned for `u16`).
|
||||
unsafe fn quantize_half_raw(kind: Kind, x: &[f32], dst: &mut [u8]) {
|
||||
unsafe {
|
||||
let v = std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::<u16>(), x.len());
|
||||
if kind.act() == ActKind::Bf16 && super::super::rust_ggml_native::convert_bf16(x, v) {
|
||||
return;
|
||||
}
|
||||
for (&x, v) in x.iter().zip(v) {
|
||||
*v = if kind.act() == ActKind::F16 { to_half(x) } else { bf16_bits(x) };
|
||||
}
|
||||
}
|
||||
}
|
||||
// Callers own initialized aligned banks and admit geometry before this private leaf.
|
||||
/// # Safety
|
||||
/// The CPU gate (avx2_ok()). `dst` extent and alignment are asserted here: it must hold `activation_bytes(x.len())`
|
||||
/// bytes and be aligned for the element it is reinterpreted as (2 for u16/Q8Zero/Q8One, 4 for Q8K). Callers:
|
||||
/// NativeActivation (bytes at offset 0 of a repr(C, align(64)) struct) and Split.hq rows (offset pinned by the const
|
||||
/// assert in rust_general_pool).
|
||||
/// The CPU gate (avx2_ok()). `dst` extent and alignment are asserted here: it must hold `activation_bytes(x.len())` bytes and be
|
||||
/// aligned for the element it is reinterpreted as (2 for u16/Q8Zero/Q8One, 4 for Q8K). Callers: NativeActivation (bytes at
|
||||
/// offset 0 of a repr(C, align(64)) struct) and Split.hq rows (offset pinned by the const assert in rust_general_pool).
|
||||
pub(in super::super) unsafe fn quantize_raw(kind: Kind, x: &[f32], dst: &mut [u8]) {
|
||||
unsafe {
|
||||
assert_destination(kind, x.len(), dst);
|
||||
let need = kind.activation_bytes(x.len()).expect("admitted activation geometry");
|
||||
assert!(dst.len() >= need && dst.as_ptr().align_offset(raw_align(kind)) == 0);
|
||||
match kind.act() {
|
||||
ActKind::F32 => std::ptr::copy_nonoverlapping(x.as_ptr().cast::<u8>(), dst.as_mut_ptr(), x.len() * 4),
|
||||
ActKind::F16 | ActKind::Bf16 => write_half(kind.act(), x, dst),
|
||||
ActKind::F16 | ActKind::Bf16 => quantize_half_raw(kind, x, dst),
|
||||
ActKind::Zero => super::super::rust_quant::q8_zero(
|
||||
x,
|
||||
std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::<Q8Zero>(), x.len() / 32),
|
||||
@@ -30,40 +53,48 @@ pub(in super::super) unsafe fn quantize_raw(kind: Kind, x: &[f32], dst: &mut [u8
|
||||
}
|
||||
}
|
||||
}
|
||||
// Refuses (panics) a destination shorter than the encoded activation of `n` inputs or misaligned for its element type.
|
||||
fn assert_destination(kind: Kind, n: usize, dst: &[u8]) {
|
||||
let need = kind.activation_bytes(n).expect("admitted activation geometry");
|
||||
let align = match kind.act() {
|
||||
ActKind::F32 => 1,
|
||||
ActKind::K => std::mem::align_of::<Q8K>(),
|
||||
_ => std::mem::align_of::<u16>(),
|
||||
};
|
||||
assert!(dst.len() >= need && dst.as_ptr().align_offset(align) == 0);
|
||||
}
|
||||
/// Writes `x` into `dst` as 16-bit values: F16 (`act` is `F16`) or BF16 (`act` is `Bf16`).
|
||||
/// Row product against a Q8_0-style (`Zero`) activation `y` (kinds not listed take the small-kind kernel).
|
||||
///
|
||||
/// # Safety
|
||||
/// The CPU gate (avx2_ok()); `dst` holds `x.len()` 16-bit elements and is 2-byte aligned (assert_destination()).
|
||||
unsafe fn write_half(act: ActKind, x: &[f32], dst: &mut [u8]) {
|
||||
/// As `dot_raw`.
|
||||
unsafe fn dot_raw_zero(kind: Kind, row: &[u8], y: &[Q8Zero]) -> f32 {
|
||||
unsafe {
|
||||
let v = std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::<u16>(), x.len());
|
||||
if act == ActKind::Bf16 {
|
||||
if !super::super::rust_ggml_native::convert_bf16(x, v) {
|
||||
round_bf16_scalar(x, v);
|
||||
match kind {
|
||||
Kind::Q2Zero => q2_generic(row, y),
|
||||
Kind::Q1Zero => q1_dot(row, y),
|
||||
Kind::MxFp4 => super::super::rust_ggml_extra::mxfp4(row, y),
|
||||
Kind::NvFp4 => super::super::rust_ggml_extra::nvfp4(row, y),
|
||||
Kind::Iq4Nl => iq4nl_dot(row, y),
|
||||
_ => super::super::rust_kq::small_dot(kind.original_id(), row, Some(y), None),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Row product against a Q8_K (`K`) activation `y`.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `dot_raw`.
|
||||
unsafe fn dot_raw_k(kind: Kind, row: &[u8], y: &[Q8K]) -> f32 {
|
||||
unsafe {
|
||||
match kind {
|
||||
Kind::Iq1S | Kind::Iq1M => super::super::rust_ggml_extra::iq1(kind.original_id(), row, y),
|
||||
Kind::Tq1 | Kind::Tq2 => super::super::rust_ggml_extra::ternary(kind.original_id(), row, y),
|
||||
Kind::Q4K => {
|
||||
let mut out = [0.0];
|
||||
super::super::rust_kq::q4_k_dot(row, &[y], &mut out);
|
||||
out[0]
|
||||
}
|
||||
} else {
|
||||
for (&x, v) in x.iter().zip(v) {
|
||||
*v = to_half(x);
|
||||
Kind::Q2K | Kind::Q3K | Kind::Q5K | Kind::Q6K => {
|
||||
super::super::rust_k_blocks::dot(kind.original_id(), row, y)
|
||||
}
|
||||
_ => super::super::rust_iq::dot_single(kind.original_id(), row, y),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// # Safety
|
||||
/// The CPU gate (avx2_ok()). `raw` must hold the encoded activation of `n` elements of `kind.act()` (>=
|
||||
/// activation_bytes(n)), aligned for its element type, and `row` must be a whole weight row (>= row_bytes(n)). Every
|
||||
/// caller derives both from a NativeActivation (quantize() enforces bytes <= BYTES; check() pins n) and a
|
||||
/// NativeFormat::validate()d row slice; the 4096/1024-byte caps of NativeFormat::new keep the pool's `hq` rows
|
||||
/// (1024 B) large enough for Zero/One encodings.
|
||||
/// The CPU gate (avx2_ok()). `raw` must hold the encoded activation of `n` elements of `kind.act()` (>= activation_bytes(n)),
|
||||
/// aligned for its element type, and `row` must be a whole weight row (>= row_bytes(n)). Every caller derives both from a
|
||||
/// NativeActivation (quantize() enforces bytes <= BYTES; check() pins n) and a NativeFormat::validate()d row slice; the
|
||||
/// 4096/1024-byte caps of NativeFormat::new keep the pool's `hq` rows (1024 B) large enough for Zero/One encodings.
|
||||
pub(in super::super) unsafe fn dot_raw(kind: Kind, row: &[u8], n: usize, raw: &[u8]) -> f32 {
|
||||
unsafe {
|
||||
debug_assert!(
|
||||
@@ -80,14 +111,8 @@ pub(in super::super) unsafe fn dot_raw(kind: Kind, row: &[u8], n: usize, raw: &[
|
||||
None,
|
||||
Some(std::slice::from_raw_parts(raw.as_ptr().cast::<Q8One>(), n / 32)),
|
||||
),
|
||||
ActKind::Zero => {
|
||||
let y = std::slice::from_raw_parts(raw.as_ptr().cast::<Q8Zero>(), n / 32);
|
||||
dot_zero_blocks(kind, row, y).expect("a Zero-encoded kind")
|
||||
}
|
||||
ActKind::K => {
|
||||
let y = std::slice::from_raw_parts(raw.as_ptr().cast::<Q8K>(), n / 256);
|
||||
dot_k_blocks(kind, row, y).expect("a K-encoded kind")
|
||||
}
|
||||
ActKind::Zero => dot_raw_zero(kind, row, std::slice::from_raw_parts(raw.as_ptr().cast::<Q8Zero>(), n / 32)),
|
||||
ActKind::K => dot_raw_k(kind, row, std::slice::from_raw_parts(raw.as_ptr().cast::<Q8K>(), n / 256)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ use super::rust_iq1_grid::GRID;
|
||||
use super::rust_simd::{half, hsum_ggml};
|
||||
use super::rust_types::{Q8K, Q8Zero};
|
||||
use std::arch::x86_64::*;
|
||||
// Bounds: row blocks come from chunks_exact(size)/checked slicing (`row[j*17..(j+1)*17]`), activation blocks are
|
||||
// safe-indexed; raw loads are 16 bytes at block offsets <= size-16 (fp4), 32 bytes of Q8Zero.qs / Q8K.qs[..256] /
|
||||
// Q8K.bsums, and GRID[..] indices are (u8 | 11 bits) < 2048 = GRID.len(). Gate: avx2_ok().
|
||||
// Bounds: row blocks come from chunks_exact(size)/checked slicing (`row[j*17..(j+1)*17]`), activation blocks are safe-indexed;
|
||||
// raw loads are 16 bytes at block offsets <= size-16 (fp4), 32 bytes of Q8Zero.qs / Q8K.qs[..256] / Q8K.bsums, and
|
||||
// GRID[..] indices are (u8 | 11 bits) < 2048 = GRID.len(). Gate: avx2_ok().
|
||||
const FP4: [i8; 16] = [0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12];
|
||||
#[target_feature(enable = "avx2")]
|
||||
unsafe fn signed_pairs(a: __m256i, b: __m256i) -> __m256i {
|
||||
@@ -103,105 +103,82 @@ fn trit(q: u8) -> u8 {
|
||||
let avg = (a + 1) / 2;
|
||||
(((a + avg + 1) / 2) >> 6) as u8 & 3
|
||||
}
|
||||
const TQ1_POWERS: [u8; 5] = [1, 3, 9, 27, 81];
|
||||
/// TQ2_0: the two 16-bit partial sums of the 128 values at byte offset `j` of the block (quant pairs 0+1 and 2+3).
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn tq2_half(x: &[u8], y: &Q8K, j: usize) -> (__m256i, __m256i) {
|
||||
let mut q = [[0u8; 32]; 4];
|
||||
for k in 0..4 {
|
||||
for b in 0..32 {
|
||||
q[k][b] = (x[j + b] >> (2 * k)) & 3;
|
||||
}
|
||||
}
|
||||
let mut p = [_mm256_setzero_si256(); 4];
|
||||
for k in 0..4 {
|
||||
// SAFETY: `q[k]` is 32 bytes and `y.qs` holds 256 bytes; the offset j * 4 + k * 32 is at most 224.
|
||||
p[k] = unsafe {
|
||||
_mm256_maddubs_epi16(
|
||||
_mm256_loadu_si256(q[k].as_ptr().cast()),
|
||||
_mm256_loadu_si256(y.qs.as_ptr().add(j * 4 + k * 32).cast()),
|
||||
)
|
||||
};
|
||||
}
|
||||
(_mm256_add_epi16(p[0], p[1]), _mm256_add_epi16(p[2], p[3]))
|
||||
}
|
||||
/// TQ2_0: the 16-bit lane sums of a whole block with the `-1` offset of the unsigned 2-bit quants removed.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
/// TQ2_0 block: 2-bit trits of both 32-byte halves against the activation bytes, minus the bsums bias.
|
||||
#[target_feature(enable = "avx2,f16c")]
|
||||
unsafe fn tq2_sums(x: &[u8], y: &Q8K) -> __m256i {
|
||||
// SAFETY: this fn's target features cover the helpers and intrinsics called below.
|
||||
unsafe {
|
||||
let mut sums = [_mm256_setzero_si256(); 2];
|
||||
for j in [0, 32] {
|
||||
let (lo, hi) = tq2_half(x, y, j);
|
||||
sums[0] = _mm256_add_epi16(sums[0], lo);
|
||||
sums[1] = _mm256_add_epi16(sums[1], hi);
|
||||
let mut q = [[0u8; 32]; 4];
|
||||
for k in 0..4 {
|
||||
for b in 0..32 {
|
||||
q[k][b] = (x[j + b] >> (2 * k)) & 3;
|
||||
}
|
||||
}
|
||||
let mut p = [_mm256_setzero_si256(); 4];
|
||||
for k in 0..4 {
|
||||
p[k] = _mm256_maddubs_epi16(
|
||||
_mm256_loadu_si256(q[k].as_ptr().cast()),
|
||||
_mm256_loadu_si256(y.qs.as_ptr().add(j * 4 + k * 32).cast()),
|
||||
);
|
||||
}
|
||||
sums[0] = _mm256_add_epi16(sums[0], _mm256_add_epi16(p[0], p[1]));
|
||||
sums[1] = _mm256_add_epi16(sums[1], _mm256_add_epi16(p[2], p[3]));
|
||||
}
|
||||
// `y.bsums` is [i16; 16] (32 bytes), fully read by the load.
|
||||
let bsums = _mm256_loadu_si256(y.bsums.as_ptr().cast());
|
||||
_mm256_sub_epi16(_mm256_add_epi16(sums[0], sums[1]), bsums)
|
||||
_mm256_sub_epi16(_mm256_add_epi16(sums[0], sums[1]), _mm256_loadu_si256(y.bsums.as_ptr().cast()))
|
||||
}
|
||||
}
|
||||
/// TQ1_0: the five products of the 160 base-3 digits stored five per byte in the first 32 bytes.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn tq1_main_products(x: &[u8], y: &Q8K) -> [__m256i; 5] {
|
||||
let mut p = [_mm256_setzero_si256(); 5];
|
||||
for k in 0..5 {
|
||||
let mut q = [0u8; 32];
|
||||
for b in 0..32 {
|
||||
q[b] = trit(x[b].wrapping_mul(TQ1_POWERS[k]));
|
||||
}
|
||||
// SAFETY: `q` is 32 bytes and `y.qs` holds 256 bytes; the offset k * 32 is at most 128.
|
||||
p[k] = unsafe {
|
||||
_mm256_maddubs_epi16(
|
||||
/// The five 32-trit planes of the TQ1_0 main bytes (`x[..32]` times 3^k) against `y.qs[..160]`.
|
||||
#[target_feature(enable = "avx2,f16c")]
|
||||
unsafe fn tq1_main_products(x: &[u8], y: &Q8K, powers: &[u8; 5]) -> [__m256i; 5] {
|
||||
unsafe {
|
||||
let mut p = [_mm256_setzero_si256(); 5];
|
||||
for k in 0..5 {
|
||||
let mut q = [0u8; 32];
|
||||
for b in 0..32 {
|
||||
q[b] = trit(x[b].wrapping_mul(powers[k]));
|
||||
}
|
||||
p[k] = _mm256_maddubs_epi16(
|
||||
_mm256_loadu_si256(q.as_ptr().cast()),
|
||||
_mm256_loadu_si256(y.qs.as_ptr().add(k * 32).cast()),
|
||||
)
|
||||
};
|
||||
);
|
||||
}
|
||||
p
|
||||
}
|
||||
p
|
||||
}
|
||||
/// TQ1_0: the product of the 96 digits stored in the last 16 + 4 bytes, for the 32 activations at `160 + k * 32`.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn tq1_tail_product(x: &[u8], y: &Q8K, k: usize) -> __m256i {
|
||||
/// Trits of tail plane `k` of a TQ1_0 block (`x[32..64]`): 16 bytes x 5 powers, then 4 bytes x 4 powers.
|
||||
fn tq1_tail_trits(x: &[u8], k: usize, powers: &[u8; 5]) -> [u8; 32] {
|
||||
let mut q = [0u8; 32];
|
||||
for b in 0..32 {
|
||||
let group = k * 2 + b / 16;
|
||||
let v = if group < 5 {
|
||||
x[32 + b % 16].wrapping_mul(TQ1_POWERS[group])
|
||||
x[32 + b % 16].wrapping_mul(powers[group])
|
||||
} else {
|
||||
x[48 + b % 4].wrapping_mul(TQ1_POWERS[(b % 16) / 4])
|
||||
x[48 + b % 4].wrapping_mul(powers[(b % 16) / 4])
|
||||
};
|
||||
q[b] = trit(v);
|
||||
}
|
||||
// SAFETY: `q` is 32 bytes and `y.qs` holds 256 bytes; the offset 160 + k * 32 is at most 224.
|
||||
unsafe {
|
||||
_mm256_maddubs_epi16(
|
||||
_mm256_loadu_si256(q.as_ptr().cast()),
|
||||
_mm256_loadu_si256(y.qs.as_ptr().add(160 + k * 32).cast()),
|
||||
)
|
||||
}
|
||||
q
|
||||
}
|
||||
/// TQ1_0: the 16-bit lane sums of a whole block with the `-1` offset of the unsigned digits removed.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
/// TQ1_0 block: main and tail trit planes against the activation bytes, minus the bsums bias.
|
||||
#[target_feature(enable = "avx2,f16c")]
|
||||
unsafe fn tq1_sums(x: &[u8], y: &Q8K) -> __m256i {
|
||||
// SAFETY: this fn's target features cover the helpers and intrinsics called below.
|
||||
unsafe {
|
||||
let powers = [1u8, 3, 9, 27, 81];
|
||||
let mut sums = [_mm256_setzero_si256(); 3];
|
||||
let p = tq1_main_products(x, y);
|
||||
let p = tq1_main_products(x, y, &powers);
|
||||
sums[0] = _mm256_add_epi16(sums[0], _mm256_add_epi16(p[0], p[1]));
|
||||
sums[1] = _mm256_add_epi16(sums[1], _mm256_add_epi16(p[2], p[3]));
|
||||
sums[2] = _mm256_add_epi16(sums[2], p[4]);
|
||||
for k in 0..3 {
|
||||
sums[k] = _mm256_add_epi16(sums[k], tq1_tail_product(x, y, k));
|
||||
let q = tq1_tail_trits(x, k, &powers);
|
||||
let p = _mm256_maddubs_epi16(
|
||||
_mm256_loadu_si256(q.as_ptr().cast()),
|
||||
_mm256_loadu_si256(y.qs.as_ptr().add(160 + k * 32).cast()),
|
||||
);
|
||||
sums[k] = _mm256_add_epi16(sums[k], p);
|
||||
}
|
||||
// `y.bsums` is [i16; 16] (32 bytes), fully read by the load.
|
||||
let bsums = _mm256_loadu_si256(y.bsums.as_ptr().cast());
|
||||
sums[0] = _mm256_sub_epi16(sums[0], bsums);
|
||||
sums[0] = _mm256_sub_epi16(sums[0], _mm256_loadu_si256(y.bsums.as_ptr().cast()));
|
||||
_mm256_add_epi16(sums[0], _mm256_add_epi16(sums[1], sums[2]))
|
||||
}
|
||||
}
|
||||
@@ -219,19 +196,9 @@ pub(super) unsafe fn ternary(kind: i32, row: &[u8], ys: &[Q8K]) -> f32 {
|
||||
hsum_ggml(acc)
|
||||
}
|
||||
}
|
||||
/// The operands of one 32-value IQ1 group: the grid bytes, the +-1 delta signs (IQ1_M), the 16-bit scale lanes and
|
||||
/// the IQ1_S scalar correction term.
|
||||
struct Iq1Group {
|
||||
grid: [u64; 4],
|
||||
signs: [i8; 32],
|
||||
ls: __m256i,
|
||||
corr: i32,
|
||||
}
|
||||
/// The block scale `d` and, for IQ1_M, the 3-bit sub-block scales as odd 16-bit lanes (zero for IQ1_S).
|
||||
#[target_feature(enable = "avx2,f16c")]
|
||||
#[inline]
|
||||
/// IQ1 block scale `d` (times the activation scale) and, for IQ1_M, the per-group 3-bit scales as 16-bit lanes.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn iq1_block_scale(kind: i32, x: &[u8], y: &Q8K) -> (f32, __m256i) {
|
||||
// SAFETY: this fn's target features cover the helpers and intrinsics called below.
|
||||
unsafe {
|
||||
if kind == 19 {
|
||||
return (y.d * half(u16::from_le_bytes([x[0], x[1]])), _mm256_setzero_si256());
|
||||
@@ -247,112 +214,89 @@ unsafe fn iq1_block_scale(kind: i32, x: &[u8], y: &Q8K) -> (f32, __m256i) {
|
||||
(y.d * half(h), scales)
|
||||
}
|
||||
}
|
||||
/// IQ1_S group `group`: grid from the 8-bit index plus 3 high bits, one scale for all lanes, and the sign/scale term
|
||||
/// of the group's activation sums.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn iq1_group_s(x: &[u8], y: &Q8K, group: usize) -> Iq1Group {
|
||||
let h = u16::from_le_bytes([x[34 + group * 2], x[35 + group * 2]]);
|
||||
let mut grid = [0u64; 4];
|
||||
for j in 0..4 {
|
||||
let high = match j {
|
||||
0 => (h << 8) & 0x700,
|
||||
1 => (h << 5) & 0x700,
|
||||
2 => (h << 2) & 0x700,
|
||||
_ => (h >> 1) & 0x700,
|
||||
};
|
||||
grid[j] = GRID[x[2 + group * 4 + j] as usize | high as usize];
|
||||
}
|
||||
let corr = (y.bsums[group * 2] as i32 + y.bsums[group * 2 + 1] as i32)
|
||||
* if h & 0x8000 != 0 { -1 } else { 1 }
|
||||
* (2 * ((h >> 12) & 7) + 1) as i32;
|
||||
let ls = _mm256_set1_epi16((2 * ((h >> 12) & 7) + 1) as i16);
|
||||
Iq1Group { grid, signs: [1i8; 32], ls, corr }
|
||||
}
|
||||
/// The delta sign (+1 or -1) of quarter `j` of an IQ1_M group whose two quarters share the byte `h`.
|
||||
fn iq1m_sign(h: u8, j: usize) -> i8 {
|
||||
if h & (if j.is_multiple_of(2) { 8 } else { 128 }) != 0 { -1 } else { 1 }
|
||||
}
|
||||
/// IQ1_M group `group`: grid from the 8-bit index plus 3 high bits, per-quarter delta signs, and the scale lanes
|
||||
/// picked from `scales` by `idx`.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn iq1_group_m(x: &[u8], group: usize, scales: __m256i, idx: __m256i) -> Iq1Group {
|
||||
let mut grid = [0u64; 4];
|
||||
let mut signs = [1i8; 32];
|
||||
for j in 0..4 {
|
||||
let h = x[32 + group * 2 + j / 2];
|
||||
let hi = if j % 2 == 0 { ((h as u16) << 8) & 0x700 } else { ((h as u16) << 4) & 0x700 };
|
||||
grid[j] = GRID[x[group * 4 + j] as usize | hi as usize];
|
||||
for v in &mut signs[j * 8..j * 8 + 8] {
|
||||
*v = iq1m_sign(h, j);
|
||||
}
|
||||
}
|
||||
Iq1Group { grid, signs, ls: _mm256_shuffle_epi8(scales, idx), corr: 0 }
|
||||
}
|
||||
/// The grid product of group `group` (and, for IQ1_M, its delta correction) against the activation block `y`.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn iq1_group_terms(kind: i32, y: &Q8K, group: usize, g: &Iq1Group) -> (__m256i, __m256i) {
|
||||
// SAFETY: `y.qs` holds 256 bytes and group * 32 is at most 224; `g.grid` and `g.signs` are 32 bytes each.
|
||||
/// IQ1_S group: grid product against the activation bytes; adds the delta correction term to `corr`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn iq1s_group(x: &[u8], y: &Q8K, group: usize, corr: &mut i32) -> __m256i {
|
||||
unsafe {
|
||||
let mut grid = [0u64; 4];
|
||||
let h = u16::from_le_bytes([x[34 + group * 2], x[35 + group * 2]]);
|
||||
for j in 0..4 {
|
||||
let high = match j {
|
||||
0 => (h << 8) & 0x700,
|
||||
1 => (h << 5) & 0x700,
|
||||
2 => (h << 2) & 0x700,
|
||||
_ => (h >> 1) & 0x700,
|
||||
};
|
||||
grid[j] = GRID[x[2 + group * 4 + j] as usize | high as usize];
|
||||
}
|
||||
let ls = _mm256_set1_epi16((2 * ((h >> 12) & 7) + 1) as i16);
|
||||
*corr += (y.bsums[group * 2] as i32 + y.bsums[group * 2 + 1] as i32)
|
||||
* if h & 0x8000 != 0 { -1 } else { 1 }
|
||||
* (2 * ((h >> 12) & 7) + 1) as i32;
|
||||
let q = _mm256_loadu_si256(y.qs.as_ptr().add(group * 32).cast());
|
||||
let grid = _mm256_loadu_si256(g.grid.as_ptr().cast());
|
||||
let product = _mm256_madd_epi16(signed_pairs(grid, q), g.ls);
|
||||
if kind != 29 {
|
||||
return (product, _mm256_setzero_si256());
|
||||
}
|
||||
let delta = _mm256_loadu_si256(g.signs.as_ptr().cast());
|
||||
let c = _mm256_maddubs_epi16(_mm256_set1_epi8(1), _mm256_sign_epi8(q, delta));
|
||||
(product, _mm256_madd_epi16(c, g.ls))
|
||||
_mm256_madd_epi16(signed_pairs(_mm256_loadu_si256(grid.as_ptr().cast()), q), ls)
|
||||
}
|
||||
}
|
||||
/// The sums of two consecutive groups `ib`, `ib + 1`: products, delta corrections and the IQ1_S scalar term.
|
||||
struct Iq1Pair {
|
||||
products: __m256i,
|
||||
corrections: __m256i,
|
||||
corr: i32,
|
||||
}
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn iq1_pair(kind: i32, x: &[u8], y: &Q8K, ib: usize, scales: __m256i, idx: [__m256i; 2]) -> Iq1Pair {
|
||||
// SAFETY: this fn's target features cover the helpers and intrinsics called below.
|
||||
/// IQ1_M group with scale lanes `ls`: the grid product and the delta correction.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn iq1m_group(x: &[u8], y: &Q8K, group: usize, ls: __m256i) -> (__m256i, __m256i) {
|
||||
unsafe {
|
||||
let mut products = [_mm256_setzero_si256(); 2];
|
||||
let mut corrections = products;
|
||||
let mut corr = 0i32;
|
||||
for k in 0..2 {
|
||||
let group = ib + k;
|
||||
let g = if kind == 19 { iq1_group_s(x, y, group) } else { iq1_group_m(x, group, scales, idx[k]) };
|
||||
corr += g.corr;
|
||||
(products[k], corrections[k]) = iq1_group_terms(kind, y, group, &g);
|
||||
}
|
||||
Iq1Pair {
|
||||
products: _mm256_add_epi32(products[0], products[1]),
|
||||
corrections: _mm256_add_epi32(corrections[0], corrections[1]),
|
||||
corr,
|
||||
let mut grid = [0u64; 4];
|
||||
let mut signs = [1i8; 32];
|
||||
for j in 0..4 {
|
||||
let h = x[32 + group * 2 + j / 2];
|
||||
let hi = if j % 2 == 0 { ((h as u16) << 8) & 0x700 } else { ((h as u16) << 4) & 0x700 };
|
||||
grid[j] = GRID[x[group * 4 + j] as usize | hi as usize];
|
||||
for v in &mut signs[j * 8..j * 8 + 8] {
|
||||
*v = if h & (if j % 2 == 0 { 8 } else { 128 }) != 0 { -1 } else { 1 };
|
||||
}
|
||||
}
|
||||
let q = _mm256_loadu_si256(y.qs.as_ptr().add(group * 32).cast());
|
||||
let g = _mm256_loadu_si256(grid.as_ptr().cast());
|
||||
let delta = _mm256_loadu_si256(signs.as_ptr().cast());
|
||||
let c = _mm256_maddubs_epi16(_mm256_set1_epi8(1), _mm256_sign_epi8(q, delta));
|
||||
(_mm256_madd_epi16(signed_pairs(g, q), ls), _mm256_madd_epi16(c, ls))
|
||||
}
|
||||
}
|
||||
/// The exact integer sums of one block (`[0]` grid products, `[1]` IQ1_M delta corrections) and the IQ1_S scalar term.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn iq1_block_sums(kind: i32, x: &[u8], y: &Q8K, scales: __m256i) -> ([__m256i; 2], i32) {
|
||||
// SAFETY: this fn's target features cover the helpers and intrinsics called below.
|
||||
/// One IQ1 group: its product against the activations and (IQ1_M with delta) the correction, both zero otherwise.
|
||||
/// `ls_index` selects the group's scale lanes of `scales` (IQ1_M).
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn iq1_group(
|
||||
kind: i32,
|
||||
(x, y): (&[u8], &Q8K),
|
||||
group: usize,
|
||||
(scales, ls_index): (__m256i, __m256i),
|
||||
corr: &mut i32,
|
||||
) -> (__m256i, __m256i) {
|
||||
unsafe {
|
||||
let zero = _mm256_setzero_si256();
|
||||
if kind == 19 {
|
||||
return (iq1s_group(x, y, group, corr), zero);
|
||||
}
|
||||
let (product, correction) = iq1m_group(x, y, group, _mm256_shuffle_epi8(scales, ls_index));
|
||||
(product, if kind == 29 { correction } else { zero })
|
||||
}
|
||||
}
|
||||
/// The grid-product and correction sums of one IQ1 block (`corr` accumulates the IQ1_S scalar correction).
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn iq1_block_sums(kind: i32, x: &[u8], y: &Q8K, scales: __m256i, corr: &mut i32) -> [__m256i; 2] {
|
||||
unsafe {
|
||||
let mut sums = [_mm256_setzero_si256(); 2];
|
||||
let mut corr = 0i32;
|
||||
let mut idx1 = _mm256_set1_epi16(0x0100);
|
||||
let mut idx2 = _mm256_add_epi8(idx1, _mm256_set1_epi8(8));
|
||||
for ib in (0..8).step_by(2) {
|
||||
let pair = iq1_pair(kind, x, y, ib, scales, [idx1, idx2]);
|
||||
corr += pair.corr;
|
||||
sums[0] = _mm256_add_epi32(sums[0], pair.products);
|
||||
sums[1] = _mm256_add_epi32(sums[1], pair.corrections);
|
||||
let mut products = [_mm256_setzero_si256(); 2];
|
||||
let mut corrections = products;
|
||||
for k in 0..2 {
|
||||
let ls_index = if k == 0 { idx1 } else { idx2 };
|
||||
(products[k], corrections[k]) = iq1_group(kind, (x, y), ib + k, (scales, ls_index), corr);
|
||||
}
|
||||
sums[0] = _mm256_add_epi32(sums[0], _mm256_add_epi32(products[0], products[1]));
|
||||
sums[1] = _mm256_add_epi32(sums[1], _mm256_add_epi32(corrections[0], corrections[1]));
|
||||
idx1 = _mm256_add_epi8(idx1, _mm256_set1_epi8(2));
|
||||
idx2 = _mm256_add_epi8(idx2, _mm256_set1_epi8(2));
|
||||
}
|
||||
(sums, corr)
|
||||
sums
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
@@ -363,8 +307,9 @@ pub(super) unsafe fn iq1(kind: i32, row: &[u8], ys: &[Q8K]) -> f32 {
|
||||
let mut scalar = 0.0;
|
||||
let size = if kind == 19 { 50 } else { 56 };
|
||||
for (x, y) in row.chunks_exact(size).zip(ys) {
|
||||
let mut corr = 0i32;
|
||||
let (d, scales) = iq1_block_scale(kind, x, y);
|
||||
let (sums, corr) = iq1_block_sums(kind, x, y, scales);
|
||||
let sums = iq1_block_sums(kind, x, y, scales, &mut corr);
|
||||
let dv = _mm256_set1_ps(d);
|
||||
accum1 = _mm256_fmadd_ps(dv, _mm256_cvtepi32_ps(sums[0]), accum1);
|
||||
if kind == 19 {
|
||||
|
||||
@@ -17,60 +17,62 @@ pub(super) fn compiled_admitted() -> bool {
|
||||
static ADMITTED: OnceLock<bool> = OnceLock::new();
|
||||
*ADMITTED.get_or_init(probe)
|
||||
}
|
||||
/// The baseline AVX2 gate: CPUID leaf 7 present, AVX/OSXSAVE/FMA/F16C bits, XCR0 enabling XMM+YMM, AVX2 bit.
|
||||
/// Returns XCR0 and the leaf-7 registers when it holds.
|
||||
///
|
||||
/// # Safety
|
||||
/// CPUID is available on x86_64; XGETBV is executed only after the OSXSAVE bit was seen.
|
||||
unsafe fn baseline() -> Option<(u64, CpuidResult)> {
|
||||
unsafe {
|
||||
if __cpuid(0).eax < 7 {
|
||||
return None;
|
||||
}
|
||||
let c = __cpuid(1).ecx;
|
||||
if [12, 27, 28, 29].iter().any(|b| c & (1 << b) == 0) {
|
||||
return None;
|
||||
}
|
||||
let xcr = _xgetbv(0);
|
||||
if xcr & 6 != 6 {
|
||||
return None;
|
||||
}
|
||||
let p = __cpuid_count(7, 0);
|
||||
if p.ebx & (1 << 5) == 0 { None } else { Some((xcr, p)) }
|
||||
}
|
||||
}
|
||||
/// The AVX-512 / AVX-512-VNNI / FP16 bits the compiled branches above need.
|
||||
fn wide_ok(xcr: u64, p: &CpuidResult) -> bool {
|
||||
let wide = F || BF || PH || V512;
|
||||
if wide && (xcr & 0xe6 != 0xe6 || p.ebx & (1 << 16) == 0) {
|
||||
return false;
|
||||
}
|
||||
fp16_ok(p) && vnni512_ok(p)
|
||||
}
|
||||
/// The AVX512-FP16 bit, when the FP16 branch is compiled.
|
||||
fn fp16_ok(p: &CpuidResult) -> bool {
|
||||
!(PH && p.edx & (1 << 23) == 0)
|
||||
}
|
||||
/// The AVX512-VL and AVX512-VNNI bits, when the 512-bit VNNI branches are compiled.
|
||||
fn vnni512_ok(p: &CpuidResult) -> bool {
|
||||
!(V512 && (p.ebx & (1 << 31) == 0 || p.ecx & (1 << 11) == 0))
|
||||
}
|
||||
/// The leaf 7 sub-leaf 1 bits for the BF16 / AVX-VNNI / AVX-VNNI-INT8 branches.
|
||||
fn leaf1_ok(p: &CpuidResult) -> bool {
|
||||
if !(BF || V256 || SIGNED) {
|
||||
return true;
|
||||
}
|
||||
if p.eax < 1 {
|
||||
return false;
|
||||
}
|
||||
let p1 = __cpuid_count(7, 1);
|
||||
!(BF && p1.eax & (1 << 5) == 0 || V256 && p1.eax & (1 << 4) == 0 || SIGNED && p1.edx & (1 << 4) == 0)
|
||||
}
|
||||
fn probe() -> bool {
|
||||
// SAFETY: CPUID is available on x86_64; XGETBV follows OSXSAVE.
|
||||
// No STRATA_FORCE_AVX2 read here: that flag only controls Original explicit
|
||||
// IQ/Q2 dispatch and does not change compiled GGML type-trait arithmetic.
|
||||
unsafe { probe_cpu() }
|
||||
}
|
||||
/// CPUID leaf 1 ECX bits 12 (FMA), 27 (OSXSAVE), 28 (AVX) and 29 (F16C) are all set.
|
||||
fn leaf1_ok(ecx: u32) -> bool {
|
||||
!([12, 27, 28, 29].iter().any(|b| ecx & (1 << b) == 0))
|
||||
}
|
||||
/// The compiled-in AVX-512 branches need the OS-enabled ZMM state and AVX512BW (leaf 7 EBX bit 16).
|
||||
fn wide_state_ok(xcr: u64, leaf7: &CpuidResult) -> bool {
|
||||
let wide = F || BF || PH || V512;
|
||||
!(wide && (xcr & 0xe6 != 0xe6 || leaf7.ebx & (1 << 16) == 0))
|
||||
}
|
||||
/// The compiled-in FP16 branch needs AVX512-FP16 (leaf 7 EDX bit 23).
|
||||
fn fp16_ok(leaf7: &CpuidResult) -> bool {
|
||||
!(PH && leaf7.edx & (1 << 23) == 0)
|
||||
}
|
||||
/// The compiled-in AVX512-VNNI branch needs AVX512VL (EBX bit 31) and AVX512-VNNI (ECX bit 11).
|
||||
fn vnni512_ok(leaf7: &CpuidResult) -> bool {
|
||||
!(V512 && (leaf7.ebx & (1 << 31) == 0 || leaf7.ecx & (1 << 11) == 0))
|
||||
}
|
||||
/// The compiled-in BF16 / AVX-VNNI / AVX-VNNI-INT8 branches need the matching bits of leaf 7 sub-leaf 1.
|
||||
fn subleaf1_ok(leaf7: &CpuidResult) -> bool {
|
||||
if !(BF || V256 || SIGNED) {
|
||||
return true;
|
||||
}
|
||||
if leaf7.eax < 1 {
|
||||
return false;
|
||||
}
|
||||
let p1 = __cpuid_count(7, 1);
|
||||
!(BF && p1.eax & (1 << 5) == 0) && !(V256 && p1.eax & (1 << 4) == 0) && !(SIGNED && p1.edx & (1 << 4) == 0)
|
||||
}
|
||||
/// Every CPU capability the compiled branches rely on is present and OS-enabled.
|
||||
unsafe fn probe_cpu() -> bool {
|
||||
// SAFETY: CPUID is available on x86_64; XGETBV follows OSXSAVE (leaf 1 ECX bit 27, checked before it is read).
|
||||
unsafe {
|
||||
if __cpuid(0).eax < 7 {
|
||||
return false;
|
||||
}
|
||||
if !leaf1_ok(__cpuid(1).ecx) {
|
||||
return false;
|
||||
}
|
||||
let xcr = _xgetbv(0);
|
||||
if xcr & 6 != 6 {
|
||||
return false;
|
||||
}
|
||||
let leaf7 = __cpuid_count(7, 0);
|
||||
leaf7.ebx & (1 << 5) != 0
|
||||
&& wide_state_ok(xcr, &leaf7)
|
||||
&& fp16_ok(&leaf7)
|
||||
&& vnni512_ok(&leaf7)
|
||||
&& subleaf1_ok(&leaf7)
|
||||
let Some((xcr, p)) = baseline() else { return false };
|
||||
wide_ok(xcr, &p) && leaf1_ok(&p)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,21 +81,15 @@ unsafe fn probe_cpu() -> bool {
|
||||
pub(super) unsafe fn float_dot(kind: Kind, row: &[u8], f: &[f32], h: &[u16]) -> Option<f32> {
|
||||
unsafe {
|
||||
match kind {
|
||||
Kind::F32 => f32_dot_native(row, f),
|
||||
Kind::F16 => f16_dot_native(row, h),
|
||||
Kind::Bf16 => bf16_dot_native(row, h),
|
||||
Kind::F32 if F => Some(f32_dot(row, f)),
|
||||
Kind::F16 => f16_native(row, h),
|
||||
Kind::Bf16 => bf16_native(row, h),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// F32 rows: the AVX-512F branch when it is compiled in.
|
||||
unsafe fn f32_dot_native(row: &[u8], f: &[f32]) -> Option<f32> {
|
||||
// SAFETY: the contract of `float_dot` (admitted CPU, whole row, initialized activation) holds for this call too.
|
||||
unsafe { if F { Some(f32_dot(row, f)) } else { None } }
|
||||
}
|
||||
/// F16 rows: the AVX512-FP16 branch, else the AVX-512F one, whichever is compiled in.
|
||||
unsafe fn f16_dot_native(row: &[u8], h: &[u16]) -> Option<f32> {
|
||||
// SAFETY: the contract of `float_dot` (admitted CPU, whole row, initialized activation) holds for this call too.
|
||||
/// The compiled F16 branch (AVX512-FP16, else AVX-512F), if any.
|
||||
unsafe fn f16_native(row: &[u8], h: &[u16]) -> Option<f32> {
|
||||
unsafe {
|
||||
if F && PH {
|
||||
Some(f16_ph_dot(row, h))
|
||||
@@ -104,9 +100,8 @@ unsafe fn f16_dot_native(row: &[u8], h: &[u16]) -> Option<f32> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// BF16 rows: the AVX512-BF16 branch, else the AVX-512F one, whichever is compiled in.
|
||||
unsafe fn bf16_dot_native(row: &[u8], h: &[u16]) -> Option<f32> {
|
||||
// SAFETY: the contract of `float_dot` (admitted CPU, whole row, initialized activation) holds for this call too.
|
||||
/// The compiled BF16 branch (AVX512-BF16, else AVX-512F), if any.
|
||||
unsafe fn bf16_native(row: &[u8], h: &[u16]) -> Option<f32> {
|
||||
unsafe {
|
||||
if BF {
|
||||
Some(bf16_dot(row, h))
|
||||
@@ -368,8 +363,8 @@ unsafe fn signed_native(x: __m256i, y: __m256i) -> __m256 {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
// bf16_convert stores 32 u16 per step through a raw pointer: a destination shorter than the source must be refused
|
||||
// first (independent of whether this build compiles the AVX512-BF16 branch).
|
||||
// bf16_convert stores 32 u16 per step through a raw pointer: a destination shorter than the source must be refused first
|
||||
// (independent of whether this build compiles the AVX512-BF16 branch).
|
||||
#[test]
|
||||
fn convert_bf16_refuses_a_destination_shorter_than_the_source() {
|
||||
let x = [1.0f32; 40];
|
||||
|
||||
@@ -47,6 +47,4 @@ pub(super) use dot_multi512_impl_fn::iq4nl;
|
||||
use dot_multi512_impl_fn::iq4xs;
|
||||
mod iq4nl_n_fn;
|
||||
#[allow(unused_imports)]
|
||||
use iq4nl_n_fn::iq4nl_codes;
|
||||
#[allow(unused_imports)]
|
||||
use iq4nl_n_fn::iq4nl_n;
|
||||
|
||||
@@ -1,10 +1,76 @@
|
||||
//! Moved out of the parent module by STRA-338: fn dot_multi512_impl, fn iq3_single_fast, fn dot_single, ....
|
||||
//! Moved out of the parent module by STRA-338: fn dot_multi512_impl, fn iq3_single_fast, fn dot_single, fn dot_single_generic, fn dot_single_iq3, fn iq4xs ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// `fast`: the register-built IQ3 halves (bitwise the stack-array decode, `iq3_multi_trees_are_bitwise_equal`; slower
|
||||
/// on Zen 5, opt-in).
|
||||
/// IQ3 formats (`iq3_multi_fast`): both halves' grid words straight into the 512-bit register, lane order = `decode`'s
|
||||
/// byte order. Returns the grid bytes, the 16-bit scales and the sign mask of sub-block `j`.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn iq3_regs512<const T: i32>(b: &[u8], j: usize) -> (__m512i, __m512i, u64) {
|
||||
unsafe {
|
||||
let (g0, s0, c0) = iq3_half::<T>(b, j, 0);
|
||||
let (g1, s1, c1) = iq3_half::<T>(b, j, 1);
|
||||
(
|
||||
_mm512_inserti64x4::<1>(_mm512_castsi256_si512(g0), g1),
|
||||
_mm512_inserti64x4::<1>(_mm512_castsi256_si512(_mm256_set1_epi16(c0)), _mm256_set1_epi16(c1)),
|
||||
s0 as u64 | ((s1 as u64) << 32),
|
||||
)
|
||||
}
|
||||
}
|
||||
/// The 16 IQ3 grid words of sub-block `j` gathered straight from the codebook (IQ3_XXS: `t == 18`, IQ3_S: `t == 21`).
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn gather_grid512(t: i32, b: &[u8], j: usize) -> __m512i {
|
||||
unsafe {
|
||||
let q = &b[2 + 16 * j..];
|
||||
let mut idx = _mm512_cvtepu8_epi32(_mm_loadu_si128(q.as_ptr().cast()));
|
||||
if t == 21 {
|
||||
let m = b[66 + 2 * j] as u16 | ((b[67 + 2 * j] as u16) << 8);
|
||||
idx = _mm512_mask_add_epi32(idx, m, idx, _mm512_set1_epi32(256));
|
||||
}
|
||||
_mm512_i32gather_epi32::<4>(idx, if t == 18 { IQ3XXS_GRID.as_ptr().cast() } else { IQ3S_GRID.as_ptr().cast() })
|
||||
}
|
||||
}
|
||||
/// The stack-array decode of sub-block `j` (both halves) into 512-bit registers: grid bytes, scales, sign mask.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn stack_regs512(t: i32, b: &[u8], j: usize) -> (__m512i, __m512i, u64) {
|
||||
unsafe {
|
||||
let (g0, s0, sc0) = decode(t, b, j, 0);
|
||||
let (g1, s1, sc1) = decode(t, b, j, 1);
|
||||
let mut g = [0u8; 64];
|
||||
g[..32].copy_from_slice(&g0);
|
||||
g[32..].copy_from_slice(&g1);
|
||||
let mut sc = [0i16; 32];
|
||||
sc[..16].copy_from_slice(&sc0);
|
||||
sc[16..].copy_from_slice(&sc1);
|
||||
let gv = if super::super::rust_simd::dispatch().gather && (t == 18 || t == 21) {
|
||||
gather_grid512(t, b, j)
|
||||
} else {
|
||||
_mm512_loadu_si512(g.as_ptr().cast())
|
||||
};
|
||||
let sv = _mm512_loadu_si512(sc.as_ptr().cast());
|
||||
(gv, sv, s0 as u64 | ((s1 as u64) << 32))
|
||||
}
|
||||
}
|
||||
/// Integer accumulators of block `i` of the `N` tokens against one weight block `b`.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn block_acc512<const T: i32, const N: usize>(b: &[u8], ys: &[&[Q8K]], i: usize, fast: bool) -> [__m512i; 8] {
|
||||
unsafe {
|
||||
let zero = _mm512_setzero_si512();
|
||||
let mut ai = [zero; 8];
|
||||
for j in 0..4 {
|
||||
let reg = (T == 21 || T == 18) && fast && !super::super::rust_simd::dispatch().gather;
|
||||
let (gv, sv, m) = if reg { iq3_regs512::<T>(b, j) } else { stack_regs512(T, b, j) };
|
||||
for k in 0..N {
|
||||
let y = ys[k];
|
||||
let v = _mm512_loadu_si512(y[i].qs.as_ptr().add(64 * j).cast());
|
||||
let sy = _mm512_mask_sub_epi8(v, m, zero, v);
|
||||
ai[k] = _mm512_add_epi32(ai[k], _mm512_madd_epi16(_mm512_maddubs_epi16(gv, sy), sv));
|
||||
}
|
||||
}
|
||||
ai
|
||||
}
|
||||
}
|
||||
/// `fast`: the register-built IQ3 halves (bitwise the stack-array decode, `iq3_multi_trees_are_bitwise_equal`; slower on Zen 5, opt-in).
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
pub(super) unsafe fn dot_multi512_impl<const T: i32, const N: usize>(
|
||||
row: &[u8],
|
||||
@@ -21,7 +87,7 @@ pub(super) unsafe fn dot_multi512_impl<const T: i32, const N: usize>(
|
||||
for i in 0..nb {
|
||||
let b = &row[i * format_bytes(t)..][..format_bytes(t)];
|
||||
prefetch(b.as_ptr());
|
||||
let ai = sum_block512::<T, N>(b, ys, i, fast);
|
||||
let ai = block_acc512::<T, N>(b, ys, i, fast);
|
||||
let dx = half(u16(b, 0)) * factor(t);
|
||||
for k in 0..N {
|
||||
let y = ys[k];
|
||||
@@ -33,85 +99,6 @@ pub(super) unsafe fn dot_multi512_impl<const T: i32, const N: usize>(
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The exact i32 accumulators of one weight block `b` against block `i` of each of the `N` tokens' activation rows.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn sum_block512<const T: i32, const N: usize>(b: &[u8], ys: &[&[Q8K]], i: usize, fast: bool) -> [__m512i; 8] {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe {
|
||||
let zero = _mm512_setzero_si512();
|
||||
let mut ai = [_mm512_setzero_si512(); 8];
|
||||
for j in 0..4 {
|
||||
let (gv, sv, m) = operands512::<T>(b, j, fast);
|
||||
for k in 0..N {
|
||||
let y = ys[k];
|
||||
let v = _mm512_loadu_si512(y[i].qs.as_ptr().add(64 * j).cast());
|
||||
let sy = _mm512_mask_sub_epi8(v, m, zero, v);
|
||||
ai[k] = _mm512_add_epi32(ai[k], _mm512_madd_epi16(_mm512_maddubs_epi16(gv, sy), sv));
|
||||
}
|
||||
}
|
||||
ai
|
||||
}
|
||||
}
|
||||
/// The 64 magnitude bytes, 32 16-bit scales and 64 sign bits of group `j` of block `b`.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn operands512<const T: i32>(b: &[u8], j: usize, fast: bool) -> (__m512i, __m512i, u64) {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe {
|
||||
// IQ3 formats (`iq3_multi_fast`): both halves' grid words straight into the 512-bit register, lane order =
|
||||
// `decode`'s byte order
|
||||
let reg = (T == 21 || T == 18) && fast && !super::super::rust_simd::dispatch().gather;
|
||||
if reg { register_operands512::<T>(b, j) } else { stack_operands512(T, b, j) }
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn register_operands512<const T: i32>(b: &[u8], j: usize) -> (__m512i, __m512i, u64) {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe {
|
||||
let (g0, s0, c0) = iq3_half::<T>(b, j, 0);
|
||||
let (g1, s1, c1) = iq3_half::<T>(b, j, 1);
|
||||
(
|
||||
_mm512_inserti64x4::<1>(_mm512_castsi256_si512(g0), g1),
|
||||
_mm512_inserti64x4::<1>(_mm512_castsi256_si512(_mm256_set1_epi16(c0)), _mm256_set1_epi16(c1)),
|
||||
s0 as u64 | ((s1 as u64) << 32),
|
||||
)
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn stack_operands512(t: i32, b: &[u8], j: usize) -> (__m512i, __m512i, u64) {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe {
|
||||
let (g0, s0, sc0) = decode(t, b, j, 0);
|
||||
let (g1, s1, sc1) = decode(t, b, j, 1);
|
||||
let mut g = [0u8; 64];
|
||||
g[..32].copy_from_slice(&g0);
|
||||
g[32..].copy_from_slice(&g1);
|
||||
let mut sc = [0i16; 32];
|
||||
sc[..16].copy_from_slice(&sc0);
|
||||
sc[16..].copy_from_slice(&sc1);
|
||||
let gv = if super::super::rust_simd::dispatch().gather && (t == 18 || t == 21) {
|
||||
gather_grid512(t, b, j)
|
||||
} else {
|
||||
_mm512_loadu_si512(g.as_ptr().cast())
|
||||
};
|
||||
let sv = _mm512_loadu_si512(sc.as_ptr().cast());
|
||||
let m = s0 as u64 | ((s1 as u64) << 32);
|
||||
(gv, sv, m)
|
||||
}
|
||||
}
|
||||
/// The 64 grid bytes of an IQ3_XXS (18) / IQ3_S (21) group straight from the grid table (`idx` <= 255 / <= 511).
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn gather_grid512(t: i32, b: &[u8], j: usize) -> __m512i {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe {
|
||||
let q = &b[2 + 16 * j..];
|
||||
let mut idx = _mm512_cvtepu8_epi32(_mm_loadu_si128(q.as_ptr().cast()));
|
||||
if t == 21 {
|
||||
let m = b[66 + 2 * j] as u16 | ((b[67 + 2 * j] as u16) << 8);
|
||||
idx = _mm512_mask_add_epi32(idx, m, idx, _mm512_set1_epi32(256));
|
||||
}
|
||||
_mm512_i32gather_epi32::<4>(idx, if t == 18 { IQ3XXS_GRID.as_ptr().cast() } else { IQ3S_GRID.as_ptr().cast() })
|
||||
}
|
||||
}
|
||||
/// `LELEKA_IQ_SINGLE=legacy` keeps the generic single-token tree for IQ3_S / IQ3_XXS (A/B arm); the default is the
|
||||
/// register-built tree below (`dot_single_iq3`), the same integer lanes and float operations, so the same bits.
|
||||
pub(super) fn iq3_single_fast() -> bool {
|
||||
@@ -153,37 +140,35 @@ pub(super) unsafe fn dot_single_generic(t: i32, row: &[u8], y: &[Q8K]) -> f32 {
|
||||
}
|
||||
}
|
||||
/// IQ3_S (21) / IQ3_XXS (18), one token: `dot_single_generic`'s tree with the 32 magnitude bytes of a half built in a
|
||||
/// register (`iq3_half`: `_mm256_setr_epi32` of the eight grid words, lane l = grid word l, the bytes `decode` writes
|
||||
/// at 4l..4l+4), the same sign mask (`signs32`), the same per-half 16-bit scale broadcast, the same two exact i32
|
||||
/// accumulators and the same per-block FMA and final reduction. Only where the bytes live between decode and use
|
||||
/// changes (no stack round trip, no per-half `match`), so every lane, and the result, is bit for bit the generic
|
||||
/// one's (`iq3_single_trees_are_bitwise_equal`). Bounds: `row` is walked by `chunks_exact(format_bytes(T))`, every
|
||||
/// offset below is inside a 110/98-byte block, `y[i]` is checked.
|
||||
/// register (`_mm256_setr_epi32` of the eight grid words: lane l = grid word l, the bytes `decode` writes at 4l..4l+4),
|
||||
/// the same sign mask (`signs32`), the same per-half 16-bit scale broadcast, the same two exact i32 accumulators and the
|
||||
/// same per-block FMA and final reduction. Only where the bytes live between decode and use changes (no stack round trip,
|
||||
/// no per-half `match`), so every lane, and the result, is bit for bit the generic one's (`iq3_single_trees_are_bitwise_equal`).
|
||||
/// Bounds: `row` is walked by `chunks_exact(format_bytes(T))`, every offset below is inside a 110/98-byte block, `y[i]` is checked.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn dot_single_iq3<const T: i32>(row: &[u8], y: &[Q8K]) -> f32 {
|
||||
unsafe {
|
||||
let mut af = _mm256_setzero_ps();
|
||||
for (i, b) in row.chunks_exact(format_bytes(T)).enumerate() {
|
||||
let yi = &y[i];
|
||||
let a = sum_block_iq3::<T>(b, yi);
|
||||
let a = block_acc_single3::<T>(b, yi);
|
||||
let d = half(u16(b, 0)) * yi.d;
|
||||
af = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(_mm256_add_epi32(a[0], a[1])), af);
|
||||
}
|
||||
factor(T) * hsum_ggml(af)
|
||||
}
|
||||
}
|
||||
/// The two exact i32 accumulators (one per half) of one IQ3 weight block `b` against the activation block `yi`.
|
||||
/// The two exact i32 accumulators (one per half) of one IQ3 block against one activation block.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn sum_block_iq3<const T: i32>(b: &[u8], yi: &Q8K) -> [__m256i; 2] {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe fn block_acc_single3<const T: i32>(b: &[u8], yi: &Q8K) -> [__m256i; 2] {
|
||||
unsafe {
|
||||
let mut a = [_mm256_setzero_si256(); 2];
|
||||
for j in 0..4 {
|
||||
for (h, ah) in a.iter_mut().enumerate() {
|
||||
for h in 0..2 {
|
||||
let (g, s, sc) = iq3_half::<T>(b, j, h);
|
||||
let v = _mm256_loadu_si256(yi.qs.as_ptr().add(64 * j + 32 * h).cast());
|
||||
*ah = _mm256_add_epi32(
|
||||
*ah,
|
||||
a[h] = _mm256_add_epi32(
|
||||
a[h],
|
||||
_mm256_madd_epi16(_mm256_maddubs_epi16(g, _mm256_sign_epi8(v, signs32(s))), _mm256_set1_epi16(sc)),
|
||||
);
|
||||
}
|
||||
@@ -191,6 +176,27 @@ unsafe fn sum_block_iq3<const T: i32>(b: &[u8], yi: &Q8K) -> [__m256i; 2] {
|
||||
a
|
||||
}
|
||||
}
|
||||
/// IQ4_XS sub-block scale (signed 6-bit) of half `h` of pair `ib / 2`; `sh` carries the high scale bits.
|
||||
fn iq4xs_scale(b: &[u8], ib: usize, h: usize, sh: u16) -> i16 {
|
||||
if h == 0 {
|
||||
((b[4 + ib / 2] & 15) as u16 | ((sh << 4) & 48)) as i16 - 32
|
||||
} else {
|
||||
((b[4 + ib / 2] >> 4) as u16 | ((sh << 2) & 48)) as i16 - 32
|
||||
}
|
||||
}
|
||||
/// The 16-bit products of the |IQ4_NL values| of sub-block `ib + h` against the sign-adjusted activation bytes.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn iq4xs_products(values: __m128i, m4: __m128i, b: &[u8], yi: &Q8K, sub: usize) -> __m256i {
|
||||
unsafe {
|
||||
let bits = _mm_loadu_si128(b.as_ptr().add(8 + 16 * sub).cast());
|
||||
let q = _mm256_inserti128_si256::<1>(
|
||||
_mm256_castsi128_si256(_mm_shuffle_epi8(values, _mm_and_si128(bits, m4))),
|
||||
_mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16::<4>(bits), m4)),
|
||||
);
|
||||
let v = _mm256_loadu_si256(yi.qs.as_ptr().add(32 * sub).cast());
|
||||
_mm256_maddubs_epi16(_mm256_sign_epi8(q, q), _mm256_sign_epi8(v, q))
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn iq4xs(row: &[u8], y: &[Q8K]) -> f32 {
|
||||
unsafe {
|
||||
@@ -198,7 +204,16 @@ pub(super) unsafe fn iq4xs(row: &[u8], y: &[Q8K]) -> f32 {
|
||||
let m4 = _mm_set1_epi8(15);
|
||||
let mut af = _mm256_setzero_ps();
|
||||
for (i, b) in row.chunks_exact(136).enumerate() {
|
||||
let sums = sum_block_iq4xs(values, m4, b, &y[i]);
|
||||
let mut sh = u16(b, 2);
|
||||
let mut sums = [_mm256_setzero_si256(); 2];
|
||||
for ib in (0..8).step_by(2) {
|
||||
for h in 0..2 {
|
||||
let p = iq4xs_products(values, m4, b, &y[i], ib + h);
|
||||
let ls = iq4xs_scale(b, ib, h, sh);
|
||||
sums[h] = _mm256_add_epi32(_mm256_madd_epi16(p, _mm256_set1_epi16(ls)), sums[h]);
|
||||
}
|
||||
sh >>= 4;
|
||||
}
|
||||
af = _mm256_fmadd_ps(
|
||||
_mm256_set1_ps(half(u16(b, 0)) * y[i].d),
|
||||
_mm256_cvtepi32_ps(_mm256_add_epi32(sums[0], sums[1])),
|
||||
@@ -208,35 +223,6 @@ pub(super) unsafe fn iq4xs(row: &[u8], y: &[Q8K]) -> f32 {
|
||||
hsum_ggml(af)
|
||||
}
|
||||
}
|
||||
/// The two exact i32 accumulators (one per half) of one IQ4_XS weight block `b` against the activation block `yi`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn sum_block_iq4xs(values: __m128i, m4: __m128i, b: &[u8], yi: &Q8K) -> [__m256i; 2] {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe {
|
||||
let mut sh = u16(b, 2);
|
||||
let mut sums = [_mm256_setzero_si256(); 2];
|
||||
for ib in (0..8).step_by(2) {
|
||||
for h in 0..2 {
|
||||
let bits = _mm_loadu_si128(b.as_ptr().add(8 + 16 * (ib + h)).cast());
|
||||
let q = iq4nl_codes(values, m4, bits);
|
||||
let v = _mm256_loadu_si256(yi.qs.as_ptr().add(32 * (ib + h)).cast());
|
||||
let p = _mm256_maddubs_epi16(_mm256_sign_epi8(q, q), _mm256_sign_epi8(v, q));
|
||||
let ls = iq4xs_scale(b, sh, ib, h);
|
||||
sums[h] = _mm256_add_epi32(_mm256_madd_epi16(p, _mm256_set1_epi16(ls)), sums[h]);
|
||||
}
|
||||
sh >>= 4;
|
||||
}
|
||||
sums
|
||||
}
|
||||
}
|
||||
/// The signed 6-bit scale (ls - 32) of sub-block `ib + h`; `sh` is the high-bit word shifted by 4 per `ib` pair.
|
||||
fn iq4xs_scale(b: &[u8], sh: u16, ib: usize, h: usize) -> i16 {
|
||||
if h == 0 {
|
||||
((b[4 + ib / 2] & 15) as u16 | ((sh << 4) & 48)) as i16 - 32
|
||||
} else {
|
||||
((b[4 + ib / 2] >> 4) as u16 | ((sh << 2) & 48)) as i16 - 32
|
||||
}
|
||||
}
|
||||
/// IQ4_NL rows specialised on the token count; the same operations in the same order per token.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(in super::super) unsafe fn iq4nl(row: &[u8], ys: &[&[Q8Zero]], out: &mut [f32], single: bool) {
|
||||
|
||||
@@ -3,15 +3,16 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The 32 signed IQ4_NL codebook values of 32 nibbles: the low nibbles of `bits` in the low 128-bit lane, the high
|
||||
/// nibbles in the high one.
|
||||
/// The 32 IQ4_NL values (signed bytes) of one 18-byte block.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn iq4nl_codes(values: __m128i, m4: __m128i, bits: __m128i) -> __m256i {
|
||||
// Register-only intrinsics under the same target features: no unsafe operation inside.
|
||||
_mm256_inserti128_si256::<1>(
|
||||
_mm256_castsi128_si256(_mm_shuffle_epi8(values, _mm_and_si128(bits, m4))),
|
||||
_mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16::<4>(bits), m4)),
|
||||
)
|
||||
unsafe fn iq4nl_values(values: __m128i, m4: __m128i, b: &[u8]) -> __m256i {
|
||||
unsafe {
|
||||
let bits = _mm_loadu_si128(b.as_ptr().add(2).cast());
|
||||
_mm256_inserti128_si256::<1>(
|
||||
_mm256_castsi128_si256(_mm_shuffle_epi8(values, _mm_and_si128(bits, m4))),
|
||||
_mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16::<4>(bits), m4)),
|
||||
)
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn iq4nl_n<const N: usize>(row: &[u8], ys: &[&[Q8Zero]], out: &mut [f32], single: bool) {
|
||||
@@ -23,8 +24,7 @@ pub(super) unsafe fn iq4nl_n<const N: usize>(row: &[u8], ys: &[&[Q8Zero]], out:
|
||||
let mut af = [[_mm256_setzero_ps(); 2]; 8];
|
||||
for (ib, b) in row.chunks_exact(18).enumerate() {
|
||||
prefetch(b.as_ptr());
|
||||
let bits = _mm_loadu_si128(b.as_ptr().add(2).cast());
|
||||
let q = iq4nl_codes(values, m4, bits);
|
||||
let q = iq4nl_values(values, m4, b);
|
||||
let aq = _mm256_sign_epi8(q, q);
|
||||
let dx = half(u16(b, 0));
|
||||
for t in 0..N {
|
||||
|
||||
@@ -13,9 +13,8 @@ fn h2f(h: u16) -> f32 {
|
||||
assert!(e > 0 && e < 31, "finite normal FP16 only");
|
||||
f32::from_bits(((h as u32 & 0x8000) << 16) | ((e + 112) << 23) | ((h as u32 & 0x3ff) << 13))
|
||||
}
|
||||
// Scalar model of iq_avx2.cpp row_dot<23,NT> (non-EX): per block one int32 accumulator per lane, sum over the 8
|
||||
// sub-blocks of (ls-32) * (4 consecutive signed-codebook x activation products), then ONE fma per block and lane,
|
||||
// then the original hsum.
|
||||
// Scalar model of iq_avx2.cpp row_dot<23,NT> (non-EX): per block one int32 accumulator per lane, sum over the 8 sub-blocks of
|
||||
// (ls-32) * (4 consecutive signed-codebook x activation products), then ONE fma per block and lane, then the original hsum.
|
||||
fn model_iq4xs(row: &[u8], y: &[Q8K]) -> f32 {
|
||||
let mut acc = [0.0f32; 8];
|
||||
for (i, b) in row.chunks_exact(136).enumerate() {
|
||||
@@ -64,22 +63,6 @@ fn random_act(nb: usize, scale: f32, seed: &mut u64) -> Vec<Q8K> {
|
||||
q8_k(&x, &mut y);
|
||||
y
|
||||
}
|
||||
// One round of the single-token comparison: every row of `rows` random blocks (all grid indices, high bits, sign
|
||||
// words and scales) of format `t` against activations of one magnitude, bit for bit.
|
||||
fn assert_iq3_single_round_equal(t: i32, nb: usize, rows: usize, round: usize, seed: &mut u64) {
|
||||
let w = random_rows(t, nb, rows, seed);
|
||||
let y = random_act(nb, 0.0001 + round as f32 * 0.37, seed);
|
||||
for r in w.chunks_exact(nb * format_bytes(t)) {
|
||||
// SAFETY: the caller checked avx2_ok(); every row is nb whole blocks and y has nb blocks.
|
||||
let (a, b) = unsafe {
|
||||
(
|
||||
dot_single_generic(t, r, &y),
|
||||
if t == 21 { dot_single_iq3::<21>(r, &y) } else { dot_single_iq3::<18>(r, &y) },
|
||||
)
|
||||
};
|
||||
assert_eq!(a.to_bits(), b.to_bits(), "type {t} round {round}");
|
||||
}
|
||||
}
|
||||
// The register-built IQ3 single-token tree against the generic one: every row of random blocks (all grid indices, high
|
||||
// bits, sign words and scales) and activations of several magnitudes, compared bit for bit.
|
||||
#[test]
|
||||
@@ -92,83 +75,24 @@ fn iq3_single_trees_are_bitwise_equal() {
|
||||
let nb = 10usize;
|
||||
for t in [21, 18] {
|
||||
for round in 0..8 {
|
||||
assert_iq3_single_round_equal(t, nb, 64, round, &mut seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The weights and activation of the throughput benchmark: 48 distinct IQ3_S experts of gate+up rows, one token.
|
||||
struct Bench {
|
||||
t: i32,
|
||||
nb: usize,
|
||||
experts: usize,
|
||||
w: Vec<u8>,
|
||||
y: Vec<Q8K>,
|
||||
}
|
||||
impl Bench {
|
||||
fn row_bytes(&self) -> usize {
|
||||
self.nb * format_bytes(self.t)
|
||||
}
|
||||
}
|
||||
// Generic against register-built single-token trees.
|
||||
fn bench_single_trees(b: &Bench, pass: usize) {
|
||||
for (name, fast) in [("generic", false), ("iq3", true)] {
|
||||
let start = std::time::Instant::now();
|
||||
let mut s = 0.0f32;
|
||||
for r in b.w.chunks_exact(b.row_bytes()) {
|
||||
// SAFETY: the caller checked avx2_ok(); rows are whole blocks and y has nb blocks.
|
||||
s += unsafe { if fast { dot_single_iq3::<21>(r, &b.y) } else { dot_single_generic(b.t, r, &b.y) } };
|
||||
}
|
||||
let el = start.elapsed().as_secs_f64();
|
||||
eprintln!(
|
||||
"pass {pass} {name}: {:.1} us per expert gate+up, {:.2} GB/s (sum {s})",
|
||||
el * 1e6 / b.experts as f64,
|
||||
b.w.len() as f64 / el / 1e9
|
||||
);
|
||||
}
|
||||
}
|
||||
// Two-token AVX-512 kernel with the stack-array and the register-built halves.
|
||||
fn bench_multi512(b: &Bench, pass: usize, seed: &mut u64) {
|
||||
let y2 = random_act(b.nb, 0.01, seed);
|
||||
let ys = [b.y.as_slice(), y2.as_slice()];
|
||||
for (name, fast) in [("stack", false), ("register", true)] {
|
||||
let start = std::time::Instant::now();
|
||||
let mut s = 0.0f32;
|
||||
for r in b.w.chunks_exact(b.row_bytes()) {
|
||||
let mut o = [0.0f32; 2];
|
||||
// SAFETY: the caller checked avx512_ok() and dq_ok(); rows are whole blocks and both y have nb blocks.
|
||||
unsafe {
|
||||
dot_multi512_impl::<21, 2>(r, &ys, &mut o, fast);
|
||||
let rows = 64;
|
||||
let w = random_rows(t, nb, rows, &mut seed);
|
||||
let y = random_act(nb, 0.0001 + round as f32 * 0.37, &mut seed);
|
||||
for r in w.chunks_exact(nb * format_bytes(t)) {
|
||||
// SAFETY: avx2_ok() above; every row is nb whole blocks and y has nb blocks.
|
||||
let (a, b) = unsafe {
|
||||
(
|
||||
dot_single_generic(t, r, &y),
|
||||
if t == 21 { dot_single_iq3::<21>(r, &y) } else { dot_single_iq3::<18>(r, &y) },
|
||||
)
|
||||
};
|
||||
assert_eq!(a.to_bits(), b.to_bits(), "type {t} round {round}");
|
||||
}
|
||||
s += o[0];
|
||||
}
|
||||
let el = start.elapsed().as_secs_f64();
|
||||
eprintln!("pass {pass} multi512 x2 {name}: {:.1} us per expert gate+up (sum {s})", el * 1e6 / b.experts as f64);
|
||||
}
|
||||
}
|
||||
// The down rows of the same experts: H=2560 rows of IQ4_NL over FF=640 (20 blocks of 18 bytes), one token.
|
||||
fn bench_iq4nl_down(experts: usize, pass: usize, seed: &mut u64) {
|
||||
let dn = random_iq4nl(2560 * experts, 20, seed);
|
||||
let hq = random_q8zero(20, seed);
|
||||
let start = std::time::Instant::now();
|
||||
let mut s = 0.0f32;
|
||||
for r in dn.chunks_exact(20 * 18) {
|
||||
let mut o = [0.0f32];
|
||||
// SAFETY: the caller checked avx2_ok(); rows are 20 whole blocks and hq has 20 blocks.
|
||||
unsafe {
|
||||
iq4nl(r, &[hq.as_slice()], &mut o, true);
|
||||
}
|
||||
s += o[0];
|
||||
}
|
||||
let el = start.elapsed().as_secs_f64();
|
||||
eprintln!(
|
||||
"pass {pass} iq4nl down x1: {:.1} us per expert down, {:.2} GB/s (sum {s})",
|
||||
el * 1e6 / experts as f64,
|
||||
dn.len() as f64 / el / 1e9
|
||||
);
|
||||
}
|
||||
// Throughput of one token's gate+up rows (FF=640 rows x 2 matrices of H=2560) over 48 distinct experts (past the L3),
|
||||
// generic against register-built, one thread.
|
||||
// `cargo test --release -p leleka-native-cpu-expert iq3_single_bench -- --ignored --nocapture`
|
||||
// generic against register-built, one thread. `cargo test --release -p leleka-native-cpu-expert iq3_single_bench -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore = "benchmark"]
|
||||
fn iq3_single_bench() {
|
||||
@@ -177,16 +101,77 @@ fn iq3_single_bench() {
|
||||
return;
|
||||
}
|
||||
let mut seed = 42u64;
|
||||
let (nb, t, experts, rows) = (10usize, 21, 48usize, 1280usize);
|
||||
let nb = 10usize;
|
||||
let t = 21;
|
||||
let experts = 48usize;
|
||||
let rows = 1280usize;
|
||||
let w = random_rows(t, nb, rows * experts, &mut seed);
|
||||
let y = random_act(nb, 0.01, &mut seed);
|
||||
let bench = Bench { t, nb, experts, w, y };
|
||||
let rb = nb * format_bytes(t);
|
||||
for pass in 0..3 {
|
||||
bench_single_trees(&bench, pass);
|
||||
if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() {
|
||||
bench_multi512(&bench, pass, &mut seed);
|
||||
for (name, fast) in [("generic", false), ("iq3", true)] {
|
||||
let start = std::time::Instant::now();
|
||||
let mut s = 0.0f32;
|
||||
for r in w.chunks_exact(rb) {
|
||||
s += unsafe { if fast { dot_single_iq3::<21>(r, &y) } else { dot_single_generic(t, r, &y) } };
|
||||
}
|
||||
let el = start.elapsed().as_secs_f64();
|
||||
eprintln!(
|
||||
"pass {pass} {name}: {:.1} us per expert gate+up, {:.2} GB/s (sum {s})",
|
||||
el * 1e6 / experts as f64,
|
||||
w.len() as f64 / el / 1e9
|
||||
);
|
||||
}
|
||||
bench_iq4nl_down(experts, pass, &mut seed);
|
||||
if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() {
|
||||
let y2 = random_act(nb, 0.01, &mut seed);
|
||||
let ys = [y.as_slice(), y2.as_slice()];
|
||||
let start = std::time::Instant::now();
|
||||
let mut s = 0.0f32;
|
||||
for r in w.chunks_exact(rb) {
|
||||
let mut o = [0.0f32; 2];
|
||||
unsafe {
|
||||
dot_multi512_impl::<21, 2>(r, &ys, &mut o, false);
|
||||
}
|
||||
s += o[0];
|
||||
}
|
||||
let el = start.elapsed().as_secs_f64();
|
||||
eprintln!(
|
||||
"pass {pass} multi512 x2 stack: {:.1} us per expert gate+up (sum {s})",
|
||||
el * 1e6 / experts as f64
|
||||
);
|
||||
let start = std::time::Instant::now();
|
||||
let mut s = 0.0f32;
|
||||
for r in w.chunks_exact(rb) {
|
||||
let mut o = [0.0f32; 2];
|
||||
unsafe {
|
||||
dot_multi512_impl::<21, 2>(r, &ys, &mut o, true);
|
||||
}
|
||||
s += o[0];
|
||||
}
|
||||
let el = start.elapsed().as_secs_f64();
|
||||
eprintln!(
|
||||
"pass {pass} multi512 x2 register: {:.1} us per expert gate+up (sum {s})",
|
||||
el * 1e6 / experts as f64
|
||||
);
|
||||
}
|
||||
// the down rows of the same experts: H=2560 rows of IQ4_NL over FF=640 (20 blocks of 18 bytes), one token
|
||||
let dn = random_iq4nl(2560 * experts, 20, &mut seed);
|
||||
let hq = random_q8zero(20, &mut seed);
|
||||
let start = std::time::Instant::now();
|
||||
let mut s = 0.0f32;
|
||||
for r in dn.chunks_exact(20 * 18) {
|
||||
let mut o = [0.0f32];
|
||||
unsafe {
|
||||
iq4nl(r, &[hq.as_slice()], &mut o, true);
|
||||
}
|
||||
s += o[0];
|
||||
}
|
||||
let el = start.elapsed().as_secs_f64();
|
||||
eprintln!(
|
||||
"pass {pass} iq4nl down x1: {:.1} us per expert down, {:.2} GB/s (sum {s})",
|
||||
el * 1e6 / experts as f64,
|
||||
dn.len() as f64 / el / 1e9
|
||||
);
|
||||
}
|
||||
}
|
||||
fn random_iq4nl(rows: usize, nb: usize, seed: &mut u64) -> Vec<u8> {
|
||||
@@ -211,28 +196,6 @@ fn random_q8zero(nb: usize, seed: &mut u64) -> Vec<Q8Zero> {
|
||||
}
|
||||
v
|
||||
}
|
||||
// The stack-array and the register-built multi-token trees on every row of `w`, for `N` tokens, bit for bit.
|
||||
fn assert_multi512_trees_equal<const T: i32, const N: usize>(w: &[u8], ys: &[&[Q8K]], nb: usize) {
|
||||
let mut a = [0.0f32; N];
|
||||
let mut b = [0.0f32; N];
|
||||
for r in w.chunks_exact(nb * format_bytes(T)) {
|
||||
// SAFETY: the caller checked avx512_ok() and dq_ok(); rows are nb whole blocks and every y has nb blocks.
|
||||
unsafe {
|
||||
dot_multi512_impl::<T, N>(r, &ys[..N], &mut a, false);
|
||||
dot_multi512_impl::<T, N>(r, &ys[..N], &mut b, true);
|
||||
}
|
||||
for k in 0..N {
|
||||
assert_eq!(a[k].to_bits(), b[k].to_bits(), "type {} tokens {} token {k}", T, N);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The same comparison for one to four tokens.
|
||||
fn assert_multi512_trees_equal_up_to_four_tokens<const T: i32>(w: &[u8], ys: &[&[Q8K]], nb: usize) {
|
||||
assert_multi512_trees_equal::<T, 1>(w, ys, nb);
|
||||
assert_multi512_trees_equal::<T, 2>(w, ys, nb);
|
||||
assert_multi512_trees_equal::<T, 3>(w, ys, nb);
|
||||
assert_multi512_trees_equal::<T, 4>(w, ys, nb);
|
||||
}
|
||||
#[test]
|
||||
fn iq3_multi_trees_are_bitwise_equal() {
|
||||
if !(super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok()) {
|
||||
@@ -241,56 +204,40 @@ fn iq3_multi_trees_are_bitwise_equal() {
|
||||
}
|
||||
let mut seed = 0x3e3e_5eed_7777_0001u64;
|
||||
let nb = 10usize;
|
||||
macro_rules! cmp {
|
||||
($T:literal,$N:literal,$w:expr,$ys:expr) => {{
|
||||
let mut a = [0.0f32; $N];
|
||||
let mut b = [0.0f32; $N];
|
||||
for r in $w.chunks_exact(nb * format_bytes($T)) {
|
||||
unsafe {
|
||||
dot_multi512_impl::<$T, $N>(r, &$ys[..$N], &mut a, false);
|
||||
dot_multi512_impl::<$T, $N>(r, &$ys[..$N], &mut b, true);
|
||||
}
|
||||
for k in 0..$N {
|
||||
assert_eq!(a[k].to_bits(), b[k].to_bits(), "type {} tokens {} token {k}", $T, $N);
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
for round in 0..6 {
|
||||
let acts: Vec<Vec<Q8K>> =
|
||||
(0..4).map(|k| random_act(nb, 0.0003 + (round * 4 + k) as f32 * 0.21, &mut seed)).collect();
|
||||
let ys: Vec<&[Q8K]> = acts.iter().map(|y| y.as_slice()).collect();
|
||||
let w21 = random_rows(21, nb, 32, &mut seed);
|
||||
let w18 = random_rows(18, nb, 32, &mut seed);
|
||||
assert_multi512_trees_equal_up_to_four_tokens::<21>(&w21, &ys, nb);
|
||||
assert_multi512_trees_equal_up_to_four_tokens::<18>(&w18, &ys, nb);
|
||||
cmp!(21, 1, w21, ys);
|
||||
cmp!(21, 2, w21, ys);
|
||||
cmp!(21, 3, w21, ys);
|
||||
cmp!(21, 4, w21, ys);
|
||||
cmp!(18, 1, w18, ys);
|
||||
cmp!(18, 2, w18, ys);
|
||||
cmp!(18, 3, w18, ys);
|
||||
cmp!(18, 4, w18, ys);
|
||||
}
|
||||
}
|
||||
// A row of `nb` random IQ4_XS blocks with a finite normal FP16 block scale.
|
||||
fn random_iq4xs_row(nb: usize, seed: &mut u64) -> Vec<u8> {
|
||||
let mut row = vec![0u8; nb * 136];
|
||||
for v in row.iter_mut() {
|
||||
*v = xorshift(seed) as u8;
|
||||
}
|
||||
for b in row.chunks_exact_mut(136) {
|
||||
let e = 8 + (xorshift(seed) % 8) as u16;
|
||||
let m = (xorshift(seed) & 0x3ff) as u16;
|
||||
b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes());
|
||||
}
|
||||
row
|
||||
}
|
||||
// Eight activation rows of `nb` Q8K blocks, the magnitude growing with `round`.
|
||||
fn random_iq4xs_acts(round: usize, nb: usize, seed: &mut u64) -> Vec<Vec<Q8K>> {
|
||||
let mut ys: Vec<Vec<Q8K>> = Vec::new();
|
||||
for _ in 0..8 {
|
||||
let x: Vec<f32> =
|
||||
(0..nb * 256).map(|_| ((xorshift(seed) % 20001) as f32 - 10000.0) * (0.001 + (round as f32))).collect();
|
||||
let mut y = vec![Q8K::default(); nb];
|
||||
q8_k(&x, &mut y);
|
||||
ys.push(y);
|
||||
}
|
||||
ys
|
||||
}
|
||||
// The AVX2 multi-token kernel of `nt` tokens against the scalar model, bit for bit.
|
||||
fn assert_iq4xs_kernel_matches_model(round: usize, row: &[u8], ys: &[Vec<Q8K>], nt: usize) {
|
||||
let refs: Vec<&[Q8K]> = ys[..nt].iter().map(|y| y.as_slice()).collect();
|
||||
let mut out = vec![0.0f32; nt];
|
||||
// SAFETY: the caller checked avx2_ok(); row is whole 136-byte blocks and every Q8K row has as many blocks.
|
||||
unsafe {
|
||||
dot_multi256(23, row, &refs, &mut out);
|
||||
}
|
||||
for t in 0..nt {
|
||||
assert_eq!(out[t].to_bits(), model_iq4xs(row, &ys[t]).to_bits(), "round {round} nt {nt} token {t}");
|
||||
}
|
||||
}
|
||||
// IQ4_XS gate/up rows at two or more tokens on the AVX2 tree take the multi-token kernel (iq_avx2.cpp iq256_gu_rows,
|
||||
// native_expert.cpp `!cpu512 && iq256_supported(23)`), not ggml's single-token dot: its last bits differ, and a Q2_0
|
||||
// down projection (not requantized to int8 as IQ4_NL's is) exposed it in KAB1 (STRA-324: cases 23-42-r2/r3/r8).
|
||||
// IQ4_XS gate/up rows at two or more tokens on the AVX2 tree take the multi-token kernel (iq_avx2.cpp iq256_gu_rows, native_expert.cpp
|
||||
// `!cpu512 && iq256_supported(23)`), not ggml's single-token dot: its last bits differ, and a Q2_0 down projection (not requantized
|
||||
// to int8 as IQ4_NL's is) exposed it in KAB1 (STRA-324: cases 23-42-r2/r3/r8).
|
||||
#[test]
|
||||
fn iq4xs_multi_token_avx2_kernel_matches_the_scalar_model_bitwise() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
@@ -300,10 +247,34 @@ fn iq4xs_multi_token_avx2_kernel_matches_the_scalar_model_bitwise() {
|
||||
let mut seed = 0x5eed_1234_abcd_ef01u64;
|
||||
let nb = 10usize;
|
||||
for round in 0..6 {
|
||||
let row = random_iq4xs_row(nb, &mut seed);
|
||||
let ys = random_iq4xs_acts(round, nb, &mut seed);
|
||||
let mut row = vec![0u8; nb * 136];
|
||||
for v in row.iter_mut() {
|
||||
*v = xorshift(&mut seed) as u8;
|
||||
}
|
||||
for b in row.chunks_exact_mut(136) {
|
||||
let e = 8 + (xorshift(&mut seed) % 8) as u16;
|
||||
let m = (xorshift(&mut seed) & 0x3ff) as u16;
|
||||
b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes());
|
||||
}
|
||||
let mut ys: Vec<Vec<Q8K>> = Vec::new();
|
||||
for _ in 0..8 {
|
||||
let x: Vec<f32> = (0..nb * 256)
|
||||
.map(|_| ((xorshift(&mut seed) % 20001) as f32 - 10000.0) * (0.001 + (round as f32)))
|
||||
.collect();
|
||||
let mut y = vec![Q8K::default(); nb];
|
||||
q8_k(&x, &mut y);
|
||||
ys.push(y);
|
||||
}
|
||||
for nt in [1usize, 2, 3, 5, 8] {
|
||||
assert_iq4xs_kernel_matches_model(round, &row, &ys, nt);
|
||||
let refs: Vec<&[Q8K]> = ys[..nt].iter().map(|y| y.as_slice()).collect();
|
||||
let mut out = vec![0.0f32; nt];
|
||||
// SAFETY: avx2_ok() above; row is exactly nb blocks of 136 bytes and every Q8K row has nb blocks.
|
||||
unsafe {
|
||||
dot_multi256(23, &row, &refs, &mut out);
|
||||
}
|
||||
for t in 0..nt {
|
||||
assert_eq!(out[t].to_bits(), model_iq4xs(&row, &ys[t]).to_bits(), "round {round} nt {nt} token {t}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
// Bounds: `row` is walked with chunks_exact/checked slicing and every activation block is safe-indexed (`y[i]`), so a
|
||||
// short operand panics instead of reading past it. The raw loads are 32/64 bytes at 64*j+32*h (j<4,h<2) of a 256-byte
|
||||
// Q8K.qs, 16 bytes inside a block (<= block size), and the only data-dependent address is the optional gather:
|
||||
// idx <= 255 into IQ3XXS_GRID[u32;256] and idx <= 511 into IQ3S_GRID[u32;512]. Gate: avx2_ok() / avx512_ok()+dq_ok().
|
||||
// Bounds: `row` is walked with chunks_exact/checked slicing and every activation block is safe-indexed (`y[i]`), so a short
|
||||
// operand panics instead of reading past it. The raw loads are 32/64 bytes at 64*j+32*h (j<4,h<2) of a 256-byte Q8K.qs, 16
|
||||
// bytes inside a block (<= block size), and the only data-dependent address is the optional gather: idx <= 255 into
|
||||
// IQ3XXS_GRID[u32;256] and idx <= 511 into IQ3S_GRID[u32;512]. Gate: avx2_ok() / avx512_ok()+dq_ok().
|
||||
pub(super) fn u16(b: &[u8], o: usize) -> u16 {
|
||||
u16::from_le_bytes(b[o..o + 2].try_into().unwrap())
|
||||
}
|
||||
@@ -32,40 +32,28 @@ pub(super) fn factor(t: i32) -> f32 {
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
/// One decoded 32-value half: magnitude bytes, literal sign word, and the integer scale of each 16-value quarter.
|
||||
type HalfParts = ([u8; 32], u32, i16, i16);
|
||||
// Whole 32-value half: magnitude bytes, literal signs and 16-value integer scales.
|
||||
/// The four literal sign bytes of an IQ2_XXS / IQ3_XXS 28-bit sign word `w` (7 bits each, through `KSIGNS_IQ2XS`).
|
||||
#[inline(always)]
|
||||
pub(super) fn decode(t: i32, b: &[u8], j: usize, h: usize) -> ([u8; 32], u32, [i16; 16]) {
|
||||
let (g, signs, s0, s1) = match t {
|
||||
16 => decode_iq2xxs(b, j, h),
|
||||
17 => decode_iq2xs(b, j, h),
|
||||
22 => decode_iq2s(b, j, h),
|
||||
18 => decode_iq3xxs(b, j, h),
|
||||
21 => decode_iq3s(b, j, h),
|
||||
23 => decode_iq4xs(b, j, h),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let mut sc = [s0; 16];
|
||||
sc[8..].fill(s1);
|
||||
(g, signs, sc)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn decode_iq2xxs(b: &[u8], j: usize, h: usize) -> HalfParts {
|
||||
let mut g = [0u8; 32];
|
||||
fn ksigns7(w: u32) -> u32 {
|
||||
let mut signs = 0u32;
|
||||
for l in 0..4 {
|
||||
signs |= (KSIGNS_IQ2XS[((w >> (7 * l)) & 127) as usize] as u32) << (8 * l);
|
||||
}
|
||||
signs
|
||||
}
|
||||
// The `decode_*` helpers fill `g` with the magnitude bytes of half `h` of sub-block `j` and return (signs, s0, s1).
|
||||
#[inline(always)]
|
||||
fn decode_16(b: &[u8], j: usize, h: usize, g: &mut [u8; 32]) -> (u32, i16, i16) {
|
||||
let a = u32(b, 2 + 16 * j + 8 * h);
|
||||
let w = u32(b, 6 + 16 * j + 8 * h);
|
||||
for l in 0..4 {
|
||||
g[l * 8..l * 8 + 8].copy_from_slice(&IQ2XXS_GRID[((a >> (8 * l)) & 255) as usize].to_le_bytes());
|
||||
signs |= (KSIGNS_IQ2XS[((w >> (7 * l)) & 127) as usize] as u32) << (8 * l);
|
||||
}
|
||||
let s = 2 * (w >> 28) as i16 + 1;
|
||||
(g, signs, s, s)
|
||||
(ksigns7(w), s, s)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn decode_iq2xs(b: &[u8], j: usize, h: usize) -> HalfParts {
|
||||
let mut g = [0u8; 32];
|
||||
fn decode_17(b: &[u8], j: usize, h: usize, g: &mut [u8; 32]) -> (u32, i16, i16) {
|
||||
let mut signs = 0u32;
|
||||
for l in 0..4 {
|
||||
let v = u16(b, 2 + 16 * j + 8 * h + 2 * l);
|
||||
@@ -73,11 +61,10 @@ fn decode_iq2xs(b: &[u8], j: usize, h: usize) -> HalfParts {
|
||||
signs |= (KSIGNS_IQ2XS[(v >> 9) as usize] as u32) << (8 * l);
|
||||
}
|
||||
let s = b[66 + 2 * j + h];
|
||||
(g, signs, 2 * (s & 15) as i16 + 1, 2 * (s >> 4) as i16 + 1)
|
||||
(signs, 2 * (s & 15) as i16 + 1, 2 * (s >> 4) as i16 + 1)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn decode_iq2s(b: &[u8], j: usize, h: usize) -> HalfParts {
|
||||
let mut g = [0u8; 32];
|
||||
fn decode_22(b: &[u8], j: usize, h: usize, g: &mut [u8; 32]) -> (u32, i16, i16) {
|
||||
let q = &b[2 + 8 * j + 4 * h..];
|
||||
let high = b[66 + 2 * j + h] as usize;
|
||||
for l in 0..4 {
|
||||
@@ -86,42 +73,34 @@ fn decode_iq2s(b: &[u8], j: usize, h: usize) -> HalfParts {
|
||||
}
|
||||
let signs = u32(b, 34 + 8 * j + 4 * h);
|
||||
let s = b[74 + 2 * j + h];
|
||||
(g, signs, 2 * (s & 15) as i16 + 1, 2 * (s >> 4) as i16 + 1)
|
||||
(signs, 2 * (s & 15) as i16 + 1, 2 * (s >> 4) as i16 + 1)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn decode_iq3xxs(b: &[u8], j: usize, h: usize) -> HalfParts {
|
||||
let mut g = [0u8; 32];
|
||||
let mut signs = 0u32;
|
||||
fn decode_18(b: &[u8], j: usize, h: usize, g: &mut [u8; 32]) -> (u32, i16, i16) {
|
||||
let q = &b[2 + 16 * j + 8 * h..];
|
||||
for l in 0..8 {
|
||||
g[l * 4..l * 4 + 4].copy_from_slice(&IQ3XXS_GRID[q[l] as usize].to_le_bytes());
|
||||
}
|
||||
let w = u32(b, 66 + 8 * j + 4 * h);
|
||||
for l in 0..4 {
|
||||
signs |= (KSIGNS_IQ2XS[((w >> (7 * l)) & 127) as usize] as u32) << (8 * l);
|
||||
}
|
||||
let s0 = 2 * (w >> 28) as i16 + 1;
|
||||
(g, signs, s0, s0)
|
||||
(ksigns7(w), s0, s0)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn decode_iq3s(b: &[u8], j: usize, h: usize) -> HalfParts {
|
||||
let mut g = [0u8; 32];
|
||||
fn decode_21(b: &[u8], j: usize, h: usize, g: &mut [u8; 32]) -> (u32, i16, i16) {
|
||||
let q = &b[2 + 16 * j + 8 * h..];
|
||||
let high = b[66 + 2 * j + h] as usize;
|
||||
for l in 0..8 {
|
||||
let idx = q[l] as usize | (((high >> l) & 1) << 8);
|
||||
g[l * 4..l * 4 + 4].copy_from_slice(&IQ3S_GRID[idx].to_le_bytes());
|
||||
g[l * 4..l * 4 + 4].copy_from_slice(&IQ3S_GRID[q[l] as usize | (((high >> l) & 1) << 8)].to_le_bytes());
|
||||
}
|
||||
let signs = u32(b, 74 + 8 * j + 4 * h);
|
||||
let s = b[106 + j];
|
||||
let s0 = 2 * (if h == 0 { s & 15 } else { s >> 4 }) as i16 + 1;
|
||||
(g, signs, s0, s0)
|
||||
(signs, s0, s0)
|
||||
}
|
||||
// IQ4_XS (AVX2 multi-token tree only, STRA-324): iq_avx2.cpp Fmt32<23>::decode. `g` = |kvalues|, the sign bit =
|
||||
// (kvalue<0) (no kvalue is 0), scale = the signed 6-bit sub-block scale ls-32 of sub-block 2j+h.
|
||||
#[inline(always)]
|
||||
fn decode_iq4xs(b: &[u8], j: usize, h: usize) -> HalfParts {
|
||||
let mut g = [0u8; 32];
|
||||
fn decode_23(b: &[u8], j: usize, h: usize, g: &mut [u8; 32]) -> (u32, i16, i16) {
|
||||
let mut signs = 0u32;
|
||||
let hh = 2 * j + h;
|
||||
let bits = &b[8 + 16 * hh..8 + 16 * hh + 16];
|
||||
@@ -138,8 +117,24 @@ fn decode_iq4xs(b: &[u8], j: usize, h: usize) -> HalfParts {
|
||||
}
|
||||
}
|
||||
let ls = ((b[4 + (hh >> 1)] >> (4 * (hh & 1))) & 15) as i16 | ((((u16(b, 2) >> (2 * hh)) & 3) as i16) << 4);
|
||||
let s0 = ls - 32;
|
||||
(g, signs, s0, s0)
|
||||
(signs, ls - 32, ls - 32)
|
||||
}
|
||||
// Whole 32-value half: magnitude bytes, literal signs and 16-value integer scales.
|
||||
#[inline(always)]
|
||||
pub(super) fn decode(t: i32, b: &[u8], j: usize, h: usize) -> ([u8; 32], u32, [i16; 16]) {
|
||||
let mut g = [0u8; 32];
|
||||
let (signs, s0, s1) = match t {
|
||||
16 => decode_16(b, j, h, &mut g),
|
||||
17 => decode_17(b, j, h, &mut g),
|
||||
22 => decode_22(b, j, h, &mut g),
|
||||
18 => decode_18(b, j, h, &mut g),
|
||||
21 => decode_21(b, j, h, &mut g),
|
||||
23 => decode_23(b, j, h, &mut g),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let mut sc = [s0; 16];
|
||||
sc[8..].fill(s1);
|
||||
(g, signs, sc)
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn decoded(t: i32, b: &[u8], j: usize, h: usize) -> (__m256i, __m256i, __m256i) {
|
||||
@@ -148,31 +143,9 @@ pub(super) unsafe fn decoded(t: i32, b: &[u8], j: usize, h: usize) -> (__m256i,
|
||||
(_mm256_loadu_si256(g.as_ptr().cast()), signs32(s), _mm256_loadu_si256(sc.as_ptr().cast()))
|
||||
}
|
||||
}
|
||||
/// Integer accumulators of block `i` of every token against one weight block `b`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(in super::super) unsafe fn dot_multi256(t: i32, row: &[u8], ys: &[&[Q8K]], out: &mut [f32]) {
|
||||
unsafe {
|
||||
assert!(ys.len() <= 8 && ys.len() == out.len());
|
||||
let nb = ys[0].len();
|
||||
assert_eq!(row.len(), nb * format_bytes(t));
|
||||
let mut accf = [_mm256_setzero_ps(); 8];
|
||||
for i in 0..nb {
|
||||
let b = &row[i * format_bytes(t)..][..format_bytes(t)];
|
||||
prefetch(b.as_ptr());
|
||||
let ai = sum_block256(t, b, ys, i);
|
||||
let dx = half(u16(b, 0)) * factor(t);
|
||||
for (k, y) in ys.iter().enumerate() {
|
||||
accf[k] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[i].d), _mm256_cvtepi32_ps(ai[k]), accf[k]);
|
||||
}
|
||||
}
|
||||
for (k, r) in out.iter_mut().enumerate() {
|
||||
*r = hsum_original(accf[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The exact i32 accumulators of one weight block `b` against block `i` of every token's activation row.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn sum_block256(t: i32, b: &[u8], ys: &[&[Q8K]], i: usize) -> [__m256i; 8] {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe fn block_acc256(t: i32, b: &[u8], ys: &[&[Q8K]], i: usize) -> [__m256i; 8] {
|
||||
unsafe {
|
||||
let mut ai = [_mm256_setzero_si256(); 8];
|
||||
for j in 0..4 {
|
||||
@@ -188,25 +161,29 @@ unsafe fn sum_block256(t: i32, b: &[u8], ys: &[&[Q8K]], i: usize) -> [__m256i; 8
|
||||
ai
|
||||
}
|
||||
}
|
||||
/// The multi-token IQ kernel, specialised on the format and the token count (iq_avx512.cpp templates its
|
||||
/// `row_dot<TY, NT>` the same way): the same operations in the same order per token, so the same bits.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
pub(in super::super) unsafe fn dot_multi512(t: i32, row: &[u8], ys: &[&[Q8K]], out: &mut [f32]) {
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(in super::super) unsafe fn dot_multi256(t: i32, row: &[u8], ys: &[&[Q8K]], out: &mut [f32]) {
|
||||
unsafe {
|
||||
match t {
|
||||
16 => dot_multi512_by_tokens::<16>(row, ys, out),
|
||||
17 => dot_multi512_by_tokens::<17>(row, ys, out),
|
||||
18 => dot_multi512_by_tokens::<18>(row, ys, out),
|
||||
21 => dot_multi512_by_tokens::<21>(row, ys, out),
|
||||
22 => dot_multi512_by_tokens::<22>(row, ys, out),
|
||||
_ => unreachable!(),
|
||||
assert!(ys.len() <= 8 && ys.len() == out.len());
|
||||
let nb = ys[0].len();
|
||||
assert_eq!(row.len(), nb * format_bytes(t));
|
||||
let mut accf = [_mm256_setzero_ps(); 8];
|
||||
for i in 0..nb {
|
||||
let b = &row[i * format_bytes(t)..][..format_bytes(t)];
|
||||
prefetch(b.as_ptr());
|
||||
let ai = block_acc256(t, b, ys, i);
|
||||
let dx = half(u16(b, 0)) * factor(t);
|
||||
for (k, y) in ys.iter().enumerate() {
|
||||
accf[k] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[i].d), _mm256_cvtepi32_ps(ai[k]), accf[k]);
|
||||
}
|
||||
}
|
||||
for (k, r) in out.iter_mut().enumerate() {
|
||||
*r = hsum_original(accf[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `dot_multi512` of one format: the token count (1..=8) picks the monomorphised kernel.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn dot_multi512_by_tokens<const T: i32>(row: &[u8], ys: &[&[Q8K]], out: &mut [f32]) {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe fn dot_multi512_by_n<const T: i32>(row: &[u8], ys: &[&[Q8K]], out: &mut [f32]) {
|
||||
unsafe {
|
||||
match ys.len() {
|
||||
1 => dot_multi512_tn::<T, 1>(row, ys, out),
|
||||
@@ -221,15 +198,29 @@ unsafe fn dot_multi512_by_tokens<const T: i32>(row: &[u8], ys: &[&[Q8K]], out: &
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `LELEKA_IQ_MULTI=register` (opt-in, measured SLOWER on the 9950X3D: 2 tokens 36.2 against 29.4 us of gate/up drain
|
||||
/// per expert in `cpu_service_bench`, runs/cpu-service2 bench out-b) builds the multi-token AVX-512 IQ3 halves in
|
||||
/// registers; the default keeps the stack arrays.
|
||||
/// The multi-token IQ kernel, specialised on the format and the token count (iq_avx512.cpp templates its
|
||||
/// `row_dot<TY, NT>` the same way): the same operations in the same order per token, so the same bits.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
pub(in super::super) unsafe fn dot_multi512(t: i32, row: &[u8], ys: &[&[Q8K]], out: &mut [f32]) {
|
||||
unsafe {
|
||||
match t {
|
||||
16 => dot_multi512_by_n::<16>(row, ys, out),
|
||||
17 => dot_multi512_by_n::<17>(row, ys, out),
|
||||
18 => dot_multi512_by_n::<18>(row, ys, out),
|
||||
21 => dot_multi512_by_n::<21>(row, ys, out),
|
||||
22 => dot_multi512_by_n::<22>(row, ys, out),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `LELEKA_IQ_MULTI=register` (opt-in, measured SLOWER on the 9950X3D: 2 tokens 36.2 against 29.4 us of gate/up drain per expert in
|
||||
/// `cpu_service_bench`, runs/cpu-service2 bench out-b) builds the multi-token AVX-512 IQ3 halves in registers; the default keeps the stack arrays.
|
||||
pub(super) fn iq3_multi_fast() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var("LELEKA_IQ_MULTI").as_deref() == Ok("register"))
|
||||
}
|
||||
/// One 32-weight half of an IQ3_S (21) / IQ3_XXS (18) block in a register: the eight grid words (lane l = word l,
|
||||
/// `decode`'s bytes 4l..4l+4), the sign word `decode` returns and its (uniform) 16-bit scale.
|
||||
/// One 32-weight half of an IQ3_S (21) / IQ3_XXS (18) block in a register: the eight grid words (lane l = word l, `decode`'s bytes 4l..4l+4),
|
||||
/// the sign word `decode` returns and its (uniform) 16-bit scale.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn iq3_half<const T: i32>(b: &[u8], j: usize, h: usize) -> (__m256i, u32, i16) {
|
||||
let q = &b[2 + 16 * j + 8 * h..2 + 16 * j + 8 * h + 8];
|
||||
|
||||
@@ -1,346 +1,260 @@
|
||||
//! Literal pinned GGML IQ1 grid; see LICENSE.ggml.
|
||||
#[rustfmt::skip]
|
||||
pub(super) const GRID:[u64;2048]=[
|
||||
0xffffffffffffffff,0xffffffffffffff01,0xffffffffffff0000,0xffffffffffff01ff,0xffffffffffff0101,0xffffffffff00ff00,
|
||||
0xffffffffff000000,0xffffffffff01ffff,0xffffffffff01ff01,0xffffffffff0101ff,0xffffffffff010101,0xffffffff00ff0000,
|
||||
0xffffffff0000ff00,0xffffffff000000ff,0xffffffff00000001,0xffffffff00010000,0xffffffff01ffffff,0xffffffff01ffff01,
|
||||
0xffffffff01ff01ff,0xffffffff01ff0101,0xffffffff01000000,0xffffffff0101ffff,0xffffffff0101ff01,0xffffffff010101ff,
|
||||
0xffffffff01010101,0xffffff00ffff00ff,0xffffff00ffff0000,0xffffff00ff00ff00,0xffffff00ff0000ff,0xffffff00ff000001,
|
||||
0xffffff00ff000100,0xffffff00ff000101,0xffffff00ff010000,0xffffff0000ffff00,0xffffff0000ff0001,0xffffff0000ff0100,
|
||||
0xffffff000000ff01,0xffffff0000000000,0xffffff0000000101,0xffffff000001ff00,0xffffff00000100ff,0xffffff0000010001,
|
||||
0xffffff00000101ff,0xffffff0001ff0000,0xffffff000100ff00,0xffffff00010000ff,0xffffff0001000001,0xffffff0001010000,
|
||||
0xffffff01ffffffff,0xffffff01ffffff01,0xffffff01ffff01ff,0xffffff01ffff0101,0xffffff01ff000000,0xffffff01ff01ffff,
|
||||
0xffffff01ff01ff01,0xffffff01ff0101ff,0xffffff01ff010101,0xffffff0100ff0000,0xffffff010000ff00,0xffffff0100000100,
|
||||
0xffffff01000100ff,0xffffff0100010100,0xffffff0101ffffff,0xffffff0101ffff01,0xffffff0101ff01ff,0xffffff0101ff0101,
|
||||
0xffffff010100ff00,0xffffff0101000000,0xffffff0101000100,0xffffff010101ffff,0xffffff010101ff01,0xffffff01010101ff,
|
||||
0xffffff0101010101,0xffff00ffff00ff00,0xffff00ffff0000ff,0xffff00ffff000001,0xffff00ffff010000,0xffff00ff00ffff00,
|
||||
0xffff00ff00ff0100,0xffff00ff00000000,0xffff00ff00000101,0xffff00ff000100ff,0xffff00ff00010000,0xffff00ff0100ff00,
|
||||
0xffff00ff01000100,0xffff00ff01010000,0xffff0000ffffff00,0xffff0000ffff00ff,0xffff0000ffff0000,0xffff0000ffff0001,
|
||||
0xffff0000ff000000,0xffff0000ff0001ff,0xffff0000ff000101,0xffff0000ff010100,0xffff000000ffffff,0xffff000000ff0000,
|
||||
0xffff000000ff0101,0xffff00000000ffff,0xffff00000000ff00,0xffff0000000000ff,0xffff000000000000,0xffff000000000001,
|
||||
0xffff000000000100,0xffff00000001ffff,0xffff00000001ff01,0xffff000000010000,0xffff0000000101ff,0xffff000000010101,
|
||||
0xffff000001ffff00,0xffff00000100ff00,0xffff000001000000,0xffff0000010001ff,0xffff000001000101,0xffff00000101ff00,
|
||||
0xffff0000010100ff,0xffff000001010000,0xffff000001010001,0xffff000001010100,0xffff0001ff0000ff,0xffff0001ff000100,
|
||||
0xffff000100ffff00,0xffff000100ff00ff,0xffff00010000ffff,0xffff00010000ff01,0xffff000100000000,0xffff0001000001ff,
|
||||
0xffff00010001ffff,0xffff00010001ff00,0xffff000100010001,0xffff000100010100,0xffff000101ff0000,0xffff00010100ff00,
|
||||
0xffff0001010000ff,0xffff000101000100,0xffff01ffffffffff,0xffff01ffffffff01,0xffff01ffffff01ff,0xffff01ffffff0101,
|
||||
0xffff01ffff000000,0xffff01ffff01ffff,0xffff01ffff01ff01,0xffff01ffff0101ff,0xffff01ffff010101,0xffff01ff00ff0000,
|
||||
0xffff01ff0000ff00,0xffff01ff00000001,0xffff01ff00010000,0xffff01ff01ffffff,0xffff01ff01ffff01,0xffff01ff01ff01ff,
|
||||
0xffff01ff01ff0101,0xffff01ff01000000,0xffff01ff0101ffff,0xffff01ff0101ff01,0xffff01ff010101ff,0xffff01ff01010101,
|
||||
0xffff0100ffff0000,0xffff0100ff00ff00,0xffff0100ff0000ff,0xffff0100ff000100,0xffff0100ff0100ff,0xffff0100ff010000,
|
||||
0xffff010000ffff00,0xffff01000000ffff,0xffff01000000ff00,0xffff010000000000,0xffff01000001ff00,0xffff0100000100ff,
|
||||
0xffff010000010100,0xffff01000100ff00,0xffff0100010000ff,0xffff010001000001,0xffff010001000100,0xffff010001010000,
|
||||
0xffff0101ffffffff,0xffff0101ffffff01,0xffff0101ffff01ff,0xffff0101ffff0101,0xffff0101ff000000,0xffff0101ff01ffff,
|
||||
0xffff0101ff01ff01,0xffff0101ff0101ff,0xffff0101ff010101,0xffff010100ff0000,0xffff01010000ff00,0xffff010100000100,
|
||||
0xffff01010001ff00,0xffff010100010000,0xffff010101ffffff,0xffff010101ffff01,0xffff010101ff0000,0xffff010101ff01ff,
|
||||
0xffff010101ff0101,0xffff010101000000,0xffff01010101ffff,0xffff01010101ff01,0xffff0101010101ff,0xffff010101010101,
|
||||
0xff00ffffff00ffff,0xff00ffffff00ff00,0xff00ffffff0000ff,0xff00ffffff000100,0xff00ffffff0100ff,0xff00ffffff010000,
|
||||
0xff00ffff00ffff00,0xff00ffff00ff00ff,0xff00ffff0000ffff,0xff00ffff00000000,0xff00ffff000001ff,0xff00ffff0001ff00,
|
||||
0xff00ffff000100ff,0xff00ffff00010000,0xff00ffff00010100,0xff00ffff0100ff00,0xff00ffff010000ff,0xff00ffff01000001,
|
||||
0xff00ffff0101ff00,0xff00ffff01010000,0xff00ff00ffffff00,0xff00ff00ffff00ff,0xff00ff00ffff0001,0xff00ff00ffff0100,
|
||||
0xff00ff00ff00ffff,0xff00ff00ff00ff01,0xff00ff00ff000000,0xff00ff00ff0001ff,0xff00ff00ff01ff00,0xff00ff00ff0100ff,
|
||||
0xff00ff00ff010100,0xff00ff0000ff0000,0xff00ff0000ff0101,0xff00ff000000ffff,0xff00ff000000ff00,0xff00ff000000ff01,
|
||||
0xff00ff00000000ff,0xff00ff0000000000,0xff00ff0000000001,0xff00ff0000000100,0xff00ff000001ffff,0xff00ff0000010000,
|
||||
0xff00ff0001ff00ff,0xff00ff000100ff01,0xff00ff0001000000,0xff00ff000101ff00,0xff00ff00010100ff,0xff00ff01ff00ff00,
|
||||
0xff00ff01ff0000ff,0xff00ff01ff000001,0xff00ff01ff010000,0xff00ff0100ffffff,0xff00ff0100ff0001,0xff00ff0100ff0100,
|
||||
0xff00ff010000ff01,0xff00ff0100000000,0xff00ff01000001ff,0xff00ff0100000101,0xff00ff01000100ff,0xff00ff0100010001,
|
||||
0xff00ff0101ff0000,0xff00ff010100ff00,0xff00ff01010000ff,0xff00ff0101000001,0xff00ff0101010000,0xff0000ffffffff00,
|
||||
0xff0000ffffff0001,0xff0000ffffff0100,0xff0000ffff0000ff,0xff0000ffff000000,0xff0000ffff0001ff,0xff0000ffff000100,
|
||||
0xff0000ffff01ff00,0xff0000ffff010001,0xff0000ff00ffff00,0xff0000ff00ff0000,0xff0000ff00ff0001,0xff0000ff00ff01ff,
|
||||
0xff0000ff00ff0101,0xff0000ff0000ff00,0xff0000ff000000ff,0xff0000ff00000000,0xff0000ff00000001,0xff0000ff00000100,
|
||||
0xff0000ff0001ff01,0xff0000ff00010000,0xff0000ff000101ff,0xff0000ff01ff00ff,0xff0000ff01ff0100,0xff0000ff0100ffff,
|
||||
0xff0000ff010000ff,0xff0000ff01000000,0xff0000ff010001ff,0xff0000ff01000100,0xff0000ff01000101,0xff0000ff0101ff00,
|
||||
0xff0000ff010100ff,0xff0000ff01010000,0xff0000ff01010100,0xff000000ffffff01,0xff000000ffff0000,0xff000000ffff0101,
|
||||
0xff000000ff00ff00,0xff000000ff0000ff,0xff000000ff000000,0xff000000ff000001,0xff000000ff000100,0xff000000ff01ffff,
|
||||
0xff000000ff01ff01,0xff000000ff010000,0xff000000ff0101ff,0xff000000ff010101,0xff00000000ffff00,0xff00000000ff00ff,
|
||||
0xff00000000ff0000,0xff00000000ff0001,0xff0000000000ff00,0xff0000000000ff01,0xff000000000000ff,0xff00000000000000,
|
||||
0xff00000000000001,0xff00000000000100,0xff00000000000101,0xff0000000001ff00,0xff000000000100ff,0xff00000000010000,
|
||||
0xff00000000010001,0xff00000000010100,0xff00000001ffffff,0xff00000001ffff01,0xff00000001ff00ff,0xff00000001ff0000,
|
||||
0xff00000001ff01ff,0xff00000001ff0101,0xff0000000100ffff,0xff0000000100ff00,0xff000000010000ff,0xff00000001000000,
|
||||
0xff00000001000001,0xff00000001000100,0xff00000001000101,0xff0000000101ffff,0xff0000000101ff01,0xff00000001010000,
|
||||
0xff000001ffffff00,0xff000001ffff00ff,0xff000001ffff0000,0xff000001ffff0001,0xff000001ff000000,0xff000001ff000001,
|
||||
0xff000001ff0001ff,0xff000001ff000101,0xff000001ff01ff00,0xff000001ff010001,0xff00000100ffffff,0xff00000100ffff01,
|
||||
0xff00000100ff00ff,0xff00000100ff0000,0xff00000100ff01ff,0xff00000100ff0101,0xff0000010000ff00,0xff00000100000000,
|
||||
0xff00000100000001,0xff000001000001ff,0xff00000100000100,0xff0000010001ff00,0xff000001000100ff,0xff00000100010000,
|
||||
0xff000001000101ff,0xff00000100010100,0xff00000100010101,0xff00000101ff0001,0xff00000101ff0101,0xff0000010100ff01,
|
||||
0xff00000101000000,0xff000001010100ff,0xff00000101010100,0xff0001ffff00ff00,0xff0001ffff000001,0xff0001ffff010000,
|
||||
0xff0001ff00ffff00,0xff0001ff00ff00ff,0xff0001ff00ff0001,0xff0001ff00ff0100,0xff0001ff0000ffff,0xff0001ff00000000,
|
||||
0xff0001ff000001ff,0xff0001ff00000101,0xff0001ff0001ffff,0xff0001ff0001ff00,0xff0001ff000100ff,0xff0001ff00010001,
|
||||
0xff0001ff00010100,0xff0001ff01ff0000,0xff0001ff0100ff00,0xff0001ff010000ff,0xff0001ff01010000,0xff000100ff00ffff,
|
||||
0xff000100ff00ff01,0xff000100ff000000,0xff000100ff000101,0xff000100ff01ff00,0xff000100ff010000,0xff00010000ffff01,
|
||||
0xff00010000ff00ff,0xff00010000ff0000,0xff00010000ff01ff,0xff0001000000ff00,0xff000100000000ff,0xff00010000000000,
|
||||
0xff00010000000001,0xff00010000000100,0xff00010000000101,0xff0001000001ffff,0xff00010000010000,0xff00010000010101,
|
||||
0xff00010001ff0100,0xff0001000100ff00,0xff0001000100ff01,0xff00010001000000,0xff000100010001ff,0xff0001000101ff00,
|
||||
0xff00010001010001,0xff00010001010100,0xff000101ffff0100,0xff000101ff000001,0xff000101ff0100ff,0xff000101ff010001,
|
||||
0xff00010100ff00ff,0xff00010100ff0001,0xff00010100ff0100,0xff0001010000ffff,0xff0001010000ff01,0xff00010100000000,
|
||||
0xff000101000001ff,0xff0001010001ff00,0xff00010100010001,0xff00010100010100,0xff00010101ff0000,0xff0001010100ff00,
|
||||
0xff00010101000001,0xff00010101000101,0xff01ffffffffffff,0xff01ffffffffff01,0xff01ffffffff01ff,0xff01ffffffff0101,
|
||||
0xff01ffffff000000,0xff01ffffff01ffff,0xff01ffffff01ff01,0xff01ffffff010000,0xff01ffffff0101ff,0xff01ffffff010101,
|
||||
0xff01ffff00ff0000,0xff01ffff0000ff00,0xff01ffff00000100,0xff01ffff0001ff00,0xff01ffff00010000,0xff01ffff01ffffff,
|
||||
0xff01ffff01ffff01,0xff01ffff01ff01ff,0xff01ffff01ff0101,0xff01ffff01000000,0xff01ffff0101ffff,0xff01ffff0101ff01,
|
||||
0xff01ffff01010000,0xff01ffff010101ff,0xff01ffff01010101,0xff01ff00ffff0000,0xff01ff00ff00ff00,0xff01ff00ff0000ff,
|
||||
0xff01ff00ff000100,0xff01ff00ff010000,0xff01ff0000ffff01,0xff01ff0000ff00ff,0xff01ff0000ff0100,0xff01ff0000000000,
|
||||
0xff01ff00000001ff,0xff01ff0000000101,0xff01ff000001ff00,0xff01ff00000100ff,0xff01ff0000010000,0xff01ff0000010001,
|
||||
0xff01ff0001ff0000,0xff01ff000100ffff,0xff01ff0001000001,0xff01ff0001000100,0xff01ff0001010000,0xff01ff01ffffff00,
|
||||
0xff01ff01ffff01ff,0xff01ff01ffff0101,0xff01ff01ff00ff00,0xff01ff01ff000000,0xff01ff01ff01ffff,0xff01ff01ff01ff01,
|
||||
0xff01ff01ff0101ff,0xff01ff01ff010101,0xff01ff0100ff0000,0xff01ff010000ff00,0xff01ff0100000001,0xff01ff0100000100,
|
||||
0xff01ff0100010000,0xff01ff0101ffff00,0xff01ff0101ff01ff,0xff01ff0101ff0101,0xff01ff010100ff00,0xff01ff0101000000,
|
||||
0xff01ff010101ffff,0xff01ff010101ff01,0xff01ff01010101ff,0xff01ff0101010101,0xff0100ffffff0000,0xff0100ffff0000ff,
|
||||
0xff0100ffff000001,0xff0100ffff000100,0xff0100ffff010000,0xff0100ff00ff00ff,0xff0100ff00ff0000,0xff0100ff00ff0001,
|
||||
0xff0100ff00ff0100,0xff0100ff0000ff01,0xff0100ff00000000,0xff0100ff000001ff,0xff0100ff00000101,0xff0100ff00010001,
|
||||
0xff0100ff01ff0000,0xff0100ff0100ff00,0xff0100ff010000ff,0xff0100ff01000100,0xff0100ff0101ff00,0xff0100ff01010000,
|
||||
0xff010000ffff0100,0xff010000ff000000,0xff010000ff01ff00,0xff010000ff010100,0xff01000000ffffff,0xff01000000ff0000,
|
||||
0xff01000000ff01ff,0xff0100000000ff00,0xff010000000000ff,0xff01000000000000,0xff01000000000100,0xff0100000001ff01,
|
||||
0xff01000000010000,0xff010000000101ff,0xff01000001ff0100,0xff0100000100ffff,0xff010000010000ff,0xff01000001000000,
|
||||
0xff010000010001ff,0xff01000001000101,0xff0100000101ff00,0xff010000010100ff,0xff01000001010001,0xff01000001010100,
|
||||
0xff010001ffff0000,0xff010001ff00ffff,0xff010001ff00ff01,0xff010001ff000100,0xff010001ff010000,0xff01000100ffff00,
|
||||
0xff01000100ff0100,0xff01000100000000,0xff0100010001ffff,0xff0100010001ff00,0xff01000100010100,0xff01000101ff00ff,
|
||||
0xff01000101ff0001,0xff0100010100ffff,0xff01000101000101,0xff0101ffffffffff,0xff0101ffffffff01,0xff0101ffffff01ff,
|
||||
0xff0101ffffff0101,0xff0101ffff000000,0xff0101ffff01ffff,0xff0101ffff01ff01,0xff0101ffff0101ff,0xff0101ffff010101,
|
||||
0xff0101ff00ff0000,0xff0101ff0000ff00,0xff0101ff000000ff,0xff0101ff00010000,0xff0101ff01ffffff,0xff0101ff01ffff01,
|
||||
0xff0101ff01ff01ff,0xff0101ff01ff0101,0xff0101ff0101ffff,0xff0101ff0101ff01,0xff0101ff010101ff,0xff0101ff01010101,
|
||||
0xff010100ffff0100,0xff010100ff00ff00,0xff010100ff0000ff,0xff010100ff000100,0xff010100ff010000,0xff01010000ff0001,
|
||||
0xff01010000ff0100,0xff0101000000ff01,0xff01010000000000,0xff0101000001ff00,0xff010100000100ff,0xff01010000010001,
|
||||
0xff01010000010100,0xff01010001ff0000,0xff0101000100ffff,0xff01010001000001,0xff01010001000100,0xff010100010100ff,
|
||||
0xff01010001010000,0xff010101ffffffff,0xff010101ffffff01,0xff010101ffff01ff,0xff010101ffff0101,0xff010101ff01ffff,
|
||||
0xff010101ff01ff01,0xff010101ff0101ff,0xff010101ff010101,0xff01010100ff0000,0xff0101010000ff00,0xff01010100000001,
|
||||
0xff01010100000100,0xff01010100010000,0xff01010101ffffff,0xff01010101ffff01,0xff01010101ff01ff,0xff01010101ff0101,
|
||||
0xff01010101000000,0xff0101010101ffff,0xff0101010101ff01,0xff010101010101ff,0xff01010101010101,0x00ffffffffff0000,
|
||||
0x00ffffffff00ff00,0x00ffffffff000001,0x00ffffffff010000,0x00ffffff00ff0100,0x00ffffff0000ff01,0x00ffffff00000000,
|
||||
0x00ffffff000001ff,0x00ffffff00000101,0x00ffffff0001ff00,0x00ffffff000100ff,0x00ffffff00010001,0x00ffffff010000ff,
|
||||
0x00ffffff01000100,0x00ffffff0101ff00,0x00ffffff01010001,0x00ffff00ffffffff,0x00ffff00ffffff00,0x00ffff00ffff00ff,
|
||||
0x00ffff00ffff0001,0x00ffff00ffff0100,0x00ffff00ff00ff01,0x00ffff00ff000000,0x00ffff00ff000001,0x00ffff00ff0001ff,
|
||||
0x00ffff00ff000101,0x00ffff00ff01ff00,0x00ffff00ff010001,0x00ffff00ff010100,0x00ffff0000ff0000,0x00ffff0000ff01ff,
|
||||
0x00ffff0000ff0101,0x00ffff000000ff00,0x00ffff00000000ff,0x00ffff0000000000,0x00ffff0000000001,0x00ffff0000000100,
|
||||
0x00ffff0000000101,0x00ffff0000010000,0x00ffff00000101ff,0x00ffff0000010101,0x00ffff0001ffff00,0x00ffff0001ff00ff,
|
||||
0x00ffff0001ff0001,0x00ffff000100ffff,0x00ffff000100ff01,0x00ffff0001000000,0x00ffff000101ffff,0x00ffff000101ff00,
|
||||
0x00ffff000101ff01,0x00ffff01ffff0000,0x00ffff01ff00ff00,0x00ffff01ff0000ff,0x00ffff01ff000001,0x00ffff01ff010000,
|
||||
0x00ffff0100ffff00,0x00ffff010000ff01,0x00ffff0100000000,0x00ffff0100000101,0x00ffff01000100ff,0x00ffff0100010100,
|
||||
0x00ffff0101ff0100,0x00ffff01010000ff,0x00ffff0101010000,0x00ff00ffffffff00,0x00ff00ffff000000,0x00ff00ffff000100,
|
||||
0x00ff00ffff010100,0x00ff00ff00ff0000,0x00ff00ff00ff01ff,0x00ff00ff00ff0101,0x00ff00ff0000ff00,0x00ff00ff000000ff,
|
||||
0x00ff00ff00000000,0x00ff00ff00000001,0x00ff00ff0001ff00,0x00ff00ff0001ff01,0x00ff00ff00010000,0x00ff00ff000101ff,
|
||||
0x00ff00ff00010101,0x00ff00ff01ffff00,0x00ff00ff01ff0001,0x00ff00ff01ff0100,0x00ff00ff0100ffff,0x00ff00ff0100ff01,
|
||||
0x00ff00ff01000000,0x00ff00ff0101ffff,0x00ff00ff0101ff00,0x00ff00ff01010100,0x00ff0000ffffff00,0x00ff0000ffffff01,
|
||||
0x00ff0000ffff0000,0x00ff0000ffff0101,0x00ff0000ff00ff00,0x00ff0000ff0000ff,0x00ff0000ff000000,0x00ff0000ff000001,
|
||||
0x00ff0000ff000100,0x00ff0000ff01ffff,0x00ff0000ff010000,0x00ff0000ff010101,0x00ff000000ffff00,0x00ff000000ff00ff,
|
||||
0x00ff000000ff0000,0x00ff000000ff0001,0x00ff000000ff0100,0x00ff00000000ffff,0x00ff00000000ff00,0x00ff0000000000ff,
|
||||
0x00ff000000000000,0x00ff000000000001,0x00ff0000000001ff,0x00ff000000000100,0x00ff00000001ff00,0x00ff0000000100ff,
|
||||
0x00ff000000010000,0x00ff000000010001,0x00ff000000010100,0x00ff000001ffff01,0x00ff000001ff00ff,0x00ff000001ff0000,
|
||||
0x00ff000001ff01ff,0x00ff00000100ff00,0x00ff0000010000ff,0x00ff000001000000,0x00ff000001000001,0x00ff000001000100,
|
||||
0x00ff000001000101,0x00ff000001010000,0x00ff0000010101ff,0x00ff000001010101,0x00ff0001ffffff00,0x00ff0001ffff0000,
|
||||
0x00ff0001ffff0100,0x00ff0001ff0000ff,0x00ff0001ff000000,0x00ff0001ff0001ff,0x00ff0001ff000101,0x00ff0001ff01ff00,
|
||||
0x00ff0001ff0100ff,0x00ff0001ff010100,0x00ff000100ffffff,0x00ff000100ffff01,0x00ff000100ff0000,0x00ff000100ff01ff,
|
||||
0x00ff00010000ffff,0x00ff00010000ff00,0x00ff00010000ff01,0x00ff000100000000,0x00ff000100000001,0x00ff000100000100,
|
||||
0x00ff00010001ff01,0x00ff000100010000,0x00ff0001000101ff,0x00ff000101ffff00,0x00ff000101ff0000,0x00ff000101ff0101,
|
||||
0x00ff0001010000ff,0x00ff000101000000,0x00ff00010101ff00,0x00ff0001010100ff,0x00ff000101010001,0x00ff01ffffff0000,
|
||||
0x00ff01ffff00ff00,0x00ff01ffff000000,0x00ff01ffff000101,0x00ff01ffff010000,0x00ff01ff00ffff01,0x00ff01ff00ff0100,
|
||||
0x00ff01ff0000ffff,0x00ff01ff00000000,0x00ff01ff000001ff,0x00ff01ff0001ff00,0x00ff01ff000100ff,0x00ff01ff00010001,
|
||||
0x00ff01ff00010100,0x00ff01ff01ff0000,0x00ff01ff0100ff00,0x00ff01ff010000ff,0x00ff01ff01000001,0x00ff01ff01000100,
|
||||
0x00ff01ff01010000,0x00ff0100ffffff00,0x00ff0100ffff0000,0x00ff0100ffff0001,0x00ff0100ffff0101,0x00ff0100ff00ffff,
|
||||
0x00ff0100ff0000ff,0x00ff0100ff000000,0x00ff0100ff0001ff,0x00ff0100ff01ff00,0x00ff0100ff0100ff,0x00ff0100ff010001,
|
||||
0x00ff010000ffffff,0x00ff010000ff0000,0x00ff010000ff0101,0x00ff01000000ff00,0x00ff01000000ff01,0x00ff0100000000ff,
|
||||
0x00ff010000000000,0x00ff010000000001,0x00ff010000000100,0x00ff01000001ffff,0x00ff01000001ff01,0x00ff010000010000,
|
||||
0x00ff010000010001,0x00ff010000010101,0x00ff010001ff0001,0x00ff010001ff0100,0x00ff01000100ff01,0x00ff010001000000,
|
||||
0x00ff010001000001,0x00ff0100010001ff,0x00ff01000101ff00,0x00ff0100010100ff,0x00ff010001010001,0x00ff010001010100,
|
||||
0x00ff0101ff000001,0x00ff010100ff00ff,0x00ff010100ff0001,0x00ff010100ff0100,0x00ff010100000000,0x00ff0101000001ff,
|
||||
0x00ff010100000101,0x00ff0101000100ff,0x00ff010100010100,0x00ff0101010000ff,0x00ff010101010000,0x0000ffffffffff00,
|
||||
0x0000ffffffff00ff,0x0000ffffffff0000,0x0000ffffffff0001,0x0000ffffffff0100,0x0000ffffff00ff01,0x0000ffffff000000,
|
||||
0x0000ffffff000101,0x0000ffffff01ff00,0x0000ffffff0100ff,0x0000ffffff010100,0x0000ffff00ffffff,0x0000ffff00ff0000,
|
||||
0x0000ffff00ff01ff,0x0000ffff0000ff00,0x0000ffff000000ff,0x0000ffff00000000,0x0000ffff00000001,0x0000ffff00000100,
|
||||
0x0000ffff00010000,0x0000ffff000101ff,0x0000ffff01ff0001,0x0000ffff01ff0100,0x0000ffff01000000,0x0000ffff010001ff,
|
||||
0x0000ffff0101ffff,0x0000ffff0101ff00,0x0000ffff01010001,0x0000ffff01010100,0x0000ff00ffff0000,0x0000ff00ffff01ff,
|
||||
0x0000ff00ffff0100,0x0000ff00ffff0101,0x0000ff00ff00ff00,0x0000ff00ff0000ff,0x0000ff00ff000000,0x0000ff00ff000001,
|
||||
0x0000ff00ff0001ff,0x0000ff00ff000100,0x0000ff00ff01ffff,0x0000ff00ff010000,0x0000ff00ff010001,0x0000ff00ff0101ff,
|
||||
0x0000ff00ff010101,0x0000ff0000ffff00,0x0000ff0000ff00ff,0x0000ff0000ff0000,0x0000ff0000ff0001,0x0000ff0000ff0100,
|
||||
0x0000ff000000ffff,0x0000ff000000ff00,0x0000ff000000ff01,0x0000ff00000000ff,0x0000ff0000000000,0x0000ff0000000001,
|
||||
0x0000ff00000001ff,0x0000ff0000000100,0x0000ff0000000101,0x0000ff000001ff00,0x0000ff00000100ff,0x0000ff0000010000,
|
||||
0x0000ff0000010001,0x0000ff0000010100,0x0000ff0001ffff01,0x0000ff0001ff0000,0x0000ff000100ff00,0x0000ff00010000ff,
|
||||
0x0000ff0001000000,0x0000ff0001000001,0x0000ff0001000100,0x0000ff000101ffff,0x0000ff0001010000,0x0000ff0001010101,
|
||||
0x0000ff01ffffff00,0x0000ff01ffff0001,0x0000ff01ff00ff01,0x0000ff01ff000000,0x0000ff01ff000101,0x0000ff01ff01ff00,
|
||||
0x0000ff01ff0100ff,0x0000ff0100ffff01,0x0000ff0100ff0000,0x0000ff0100ff0101,0x0000ff010000ff00,0x0000ff01000000ff,
|
||||
0x0000ff0100000000,0x0000ff0100000001,0x0000ff0100000100,0x0000ff010001ff01,0x0000ff0100010000,0x0000ff0101ff0000,
|
||||
0x0000ff010100ffff,0x0000ff010100ff01,0x0000ff0101000000,0x0000ff0101000100,0x0000ff0101000101,0x0000ff01010100ff,
|
||||
0x000000ffffff00ff,0x000000ffffff0000,0x000000ffff00ff00,0x000000ffff0000ff,0x000000ffff000000,0x000000ffff000001,
|
||||
0x000000ffff0001ff,0x000000ffff000100,0x000000ffff01ff00,0x000000ffff010000,0x000000ffff0101ff,0x000000ffff010101,
|
||||
0x000000ff00ffff00,0x000000ff00ff00ff,0x000000ff00ff0000,0x000000ff00ff0001,0x000000ff00ff0100,0x000000ff00ff0101,
|
||||
0x000000ff0000ffff,0x000000ff0000ff00,0x000000ff000000ff,0x000000ff00000000,0x000000ff00000001,0x000000ff000001ff,
|
||||
0x000000ff00000100,0x000000ff00000101,0x000000ff0001ff00,0x000000ff0001ff01,0x000000ff000100ff,0x000000ff00010000,
|
||||
0x000000ff00010001,0x000000ff00010100,0x000000ff01ffffff,0x000000ff01ff01ff,0x000000ff01ff0101,0x000000ff0100ff00,
|
||||
0x000000ff010000ff,0x000000ff01000000,0x000000ff01000001,0x000000ff01000100,0x000000ff0101ff00,0x000000ff010100ff,
|
||||
0x000000ff01010000,0x000000ff01010101,0x00000000ffffff00,0x00000000ffffff01,0x00000000ffff00ff,0x00000000ffff0000,
|
||||
0x00000000ffff0001,0x00000000ffff0100,0x00000000ff00ffff,0x00000000ff00ff00,0x00000000ff00ff01,0x00000000ff0000ff,
|
||||
0x00000000ff000000,0x00000000ff000001,0x00000000ff000100,0x00000000ff000101,0x00000000ff01ff00,0x00000000ff0100ff,
|
||||
0x00000000ff010000,0x00000000ff010001,0x00000000ff010100,0x0000000000ffffff,0x0000000000ffff00,0x0000000000ffff01,
|
||||
0x0000000000ff00ff,0x0000000000ff0000,0x0000000000ff0001,0x0000000000ff01ff,0x0000000000ff0100,0x000000000000ffff,
|
||||
0x000000000000ff00,0x000000000000ff01,0x00000000000000ff,0x0000000000000000,0x0000000000000001,0x00000000000001ff,
|
||||
0x0000000000000100,0x0000000000000101,0x000000000001ffff,0x000000000001ff00,0x00000000000100ff,0x0000000000010000,
|
||||
0x0000000000010001,0x00000000000101ff,0x0000000000010100,0x0000000000010101,0x0000000001ffff00,0x0000000001ff00ff,
|
||||
0x0000000001ff0000,0x0000000001ff0100,0x0000000001ff0101,0x000000000100ffff,0x000000000100ff00,0x00000000010000ff,
|
||||
0x0000000001000000,0x0000000001000001,0x00000000010001ff,0x0000000001000100,0x000000000101ff00,0x00000000010100ff,
|
||||
0x0000000001010000,0x0000000001010001,0x0000000001010100,0x00000001ffffffff,0x00000001ffffff00,0x00000001ffffff01,
|
||||
0x00000001ffff00ff,0x00000001ffff0001,0x00000001ffff01ff,0x00000001ffff0100,0x00000001ff00ff00,0x00000001ff0000ff,
|
||||
0x00000001ff000000,0x00000001ff0001ff,0x00000001ff000100,0x00000001ff01ffff,0x00000001ff01ff00,0x00000001ff01ff01,
|
||||
0x00000001ff0100ff,0x00000001ff010000,0x00000001ff010001,0x00000001ff0101ff,0x00000001ff010100,0x0000000100ffff00,
|
||||
0x0000000100ff0000,0x0000000100ff0001,0x0000000100ff01ff,0x0000000100ff0100,0x0000000100ff0101,0x000000010000ffff,
|
||||
0x000000010000ff00,0x000000010000ff01,0x00000001000000ff,0x0000000100000000,0x0000000100000001,0x00000001000001ff,
|
||||
0x0000000100000100,0x0000000100000101,0x000000010001ff00,0x00000001000100ff,0x0000000100010000,0x0000000100010100,
|
||||
0x0000000101ffff01,0x0000000101ff0000,0x0000000101ff0001,0x0000000101ff01ff,0x0000000101ff0100,0x0000000101ff0101,
|
||||
0x000000010100ff00,0x0000000101000000,0x0000000101000101,0x000000010101ff01,0x0000000101010000,0x0000000101010001,
|
||||
0x00000001010101ff,0x0000000101010100,0x000001ffffff00ff,0x000001ffffff0000,0x000001ffffff0001,0x000001ffffff0100,
|
||||
0x000001ffff00ffff,0x000001ffff000000,0x000001ffff0001ff,0x000001ffff01ff00,0x000001ffff010101,0x000001ff00ff0000,
|
||||
0x000001ff00ff01ff,0x000001ff00ff0101,0x000001ff0000ff00,0x000001ff000000ff,0x000001ff00000000,0x000001ff00000001,
|
||||
0x000001ff000001ff,0x000001ff00000100,0x000001ff0001ffff,0x000001ff0001ff01,0x000001ff000100ff,0x000001ff00010000,
|
||||
0x000001ff01ffff01,0x000001ff01ff0100,0x000001ff0100ffff,0x000001ff0100ff01,0x000001ff01000000,0x000001ff010001ff,
|
||||
0x000001ff0101ff00,0x000001ff01010100,0x00000100ffffff00,0x00000100ffffff01,0x00000100ffff0000,0x00000100ffff0101,
|
||||
0x00000100ff00ff00,0x00000100ff0000ff,0x00000100ff000000,0x00000100ff000001,0x00000100ff000100,0x00000100ff010000,
|
||||
0x0000010000ffff00,0x0000010000ff00ff,0x0000010000ff0000,0x0000010000ff0001,0x0000010000ff0100,0x000001000000ffff,
|
||||
0x000001000000ff00,0x000001000000ff01,0x00000100000000ff,0x0000010000000000,0x0000010000000001,0x00000100000001ff,
|
||||
0x0000010000000100,0x0000010000000101,0x000001000001ff00,0x00000100000100ff,0x0000010000010000,0x0000010000010001,
|
||||
0x0000010000010100,0x0000010001ffff00,0x0000010001ff0000,0x0000010001ff0100,0x000001000100ff00,0x00000100010000ff,
|
||||
0x0000010001000000,0x0000010001000001,0x00000100010001ff,0x0000010001000100,0x0000010001010000,0x00000101ffff00ff,
|
||||
0x00000101ffff01ff,0x00000101ff000000,0x00000101ff000101,0x00000101ff01ffff,0x00000101ff010000,0x00000101ff010001,
|
||||
0x00000101ff010100,0x0000010100ff0000,0x0000010100ff01ff,0x0000010100ff0100,0x000001010000ff00,0x0000010100000000,
|
||||
0x0000010100000001,0x00000101000001ff,0x0000010100000100,0x000001010001ff01,0x0000010100010000,0x00000101000101ff,
|
||||
0x0000010100010101,0x0000010101ffff00,0x0000010101ff0101,0x000001010100ff01,0x0000010101000000,0x0000010101000001,
|
||||
0x00000101010001ff,0x0000010101000101,0x000001010101ff00,0x0001ffffffff0000,0x0001ffffff0000ff,0x0001ffffff000001,
|
||||
0x0001ffffff000100,0x0001ffffff010000,0x0001ffff00ff00ff,0x0001ffff0000ffff,0x0001ffff00000000,0x0001ffff00000001,
|
||||
0x0001ffff000001ff,0x0001ffff00000101,0x0001ffff0001ff00,0x0001ffff000100ff,0x0001ffff00010001,0x0001ffff00010100,
|
||||
0x0001ffff01ffff00,0x0001ffff01000001,0x0001ffff01010000,0x0001ff00ffffff00,0x0001ff00ffff00ff,0x0001ff00ffff0001,
|
||||
0x0001ff00ffff0100,0x0001ff00ff00ff01,0x0001ff00ff000000,0x0001ff00ff01ff00,0x0001ff00ff01ff01,0x0001ff00ff010001,
|
||||
0x0001ff00ff010100,0x0001ff0000ff0000,0x0001ff0000ff0100,0x0001ff000000ff00,0x0001ff0000000000,0x0001ff0000000001,
|
||||
0x0001ff0000000100,0x0001ff0000010000,0x0001ff0000010001,0x0001ff0000010101,0x0001ff0001ff00ff,0x0001ff0001ff0101,
|
||||
0x0001ff000100ff01,0x0001ff0001000000,0x0001ff000101ff00,0x0001ff0001010001,0x0001ff0001010100,0x0001ff01ff00ff00,
|
||||
0x0001ff01ff000001,0x0001ff01ff000100,0x0001ff0100ffffff,0x0001ff0100ffff00,0x0001ff0100ff0001,0x0001ff0100000000,
|
||||
0x0001ff0100000001,0x0001ff01000001ff,0x0001ff010001ffff,0x0001ff0101ff0000,0x0001ff010100ff00,0x0001ff0101000001,
|
||||
0x0001ff0101010000,0x000100ffff00ff00,0x000100ffff00ff01,0x000100ffff000000,0x000100ffff000001,0x000100ffff000101,
|
||||
0x000100ffff01ff00,0x000100ffff010001,0x000100ffff010100,0x000100ff00ffffff,0x000100ff00ffff01,0x000100ff00ff0000,
|
||||
0x000100ff00ff01ff,0x000100ff00ff0101,0x000100ff0000ff00,0x000100ff000000ff,0x000100ff00000000,0x000100ff00000001,
|
||||
0x000100ff00000100,0x000100ff00000101,0x000100ff0001ffff,0x000100ff0001ff01,0x000100ff00010000,0x000100ff01ff00ff,
|
||||
0x000100ff01ff0000,0x000100ff01ff0100,0x000100ff0100ffff,0x000100ff0100ff01,0x000100ff010000ff,0x000100ff01000000,
|
||||
0x000100ff01000001,0x000100ff010001ff,0x000100ff01000101,0x000100ff0101ff00,0x000100ff010100ff,0x000100ff01010100,
|
||||
0x00010000ffff0000,0x00010000ffff01ff,0x00010000ffff0101,0x00010000ff00ff00,0x00010000ff000000,0x00010000ff000001,
|
||||
0x00010000ff000100,0x0001000000ff00ff,0x0001000000ff0000,0x0001000000ff0001,0x0001000000ff0100,0x000100000000ffff,
|
||||
0x000100000000ff00,0x00010000000000ff,0x0001000000000000,0x0001000000000001,0x0001000000000100,0x000100000001ff00,
|
||||
0x00010000000100ff,0x0001000000010000,0x0001000000010001,0x0001000000010100,0x0001000001ff0001,0x0001000001ff0100,
|
||||
0x0001000001ff0101,0x000100000100ff00,0x0001000001000000,0x0001000001000001,0x0001000001000100,0x0001000001000101,
|
||||
0x000100000101ff01,0x0001000001010000,0x0001000001010001,0x00010000010101ff,0x00010001ffffff01,0x00010001ffff0100,
|
||||
0x00010001ff000000,0x00010001ff01ffff,0x00010001ff010001,0x00010001ff0101ff,0x00010001ff010100,0x0001000100ffffff,
|
||||
0x0001000100ff0000,0x0001000100ff01ff,0x0001000100ff0101,0x000100010000ff00,0x00010001000000ff,0x0001000100000000,
|
||||
0x0001000100000001,0x00010001000001ff,0x0001000100000101,0x000100010001ffff,0x0001000100010000,0x00010001000101ff,
|
||||
0x0001000101ffffff,0x0001000101ffff01,0x0001000101ff0000,0x0001000101ff0101,0x00010001010000ff,0x0001000101000001,
|
||||
0x00010001010001ff,0x0001000101000100,0x000100010101ffff,0x00010001010100ff,0x0001000101010001,0x0001000101010101,
|
||||
0x000101ffff000001,0x000101ffff000100,0x000101ffff010000,0x000101ff00ffff00,0x000101ff0000ff01,0x000101ff00000000,
|
||||
0x000101ff00000101,0x000101ff0001ff00,0x000101ff00010100,0x000101ff01ff0000,0x000101ff0100ff00,0x000101ff010001ff,
|
||||
0x000101ff01010001,0x00010100ffffff00,0x00010100ffff00ff,0x00010100ff00ffff,0x00010100ff000000,0x00010100ff01ff00,
|
||||
0x00010100ff0100ff,0x00010100ff010001,0x00010100ff010100,0x0001010000ffffff,0x0001010000ffff00,0x0001010000ff0000,
|
||||
0x0001010000ff0001,0x0001010000ff01ff,0x000101000000ff00,0x00010100000000ff,0x0001010000000000,0x0001010000000001,
|
||||
0x0001010000000100,0x000101000001ffff,0x0001010000010000,0x0001010000010101,0x0001010001ffff01,0x0001010001ff00ff,
|
||||
0x0001010001ff0101,0x0001010001000000,0x000101000101ff00,0x00010100010100ff,0x0001010001010000,0x0001010001010100,
|
||||
0x00010101ff00ff00,0x00010101ff000001,0x00010101ff0001ff,0x0001010100ffff00,0x0001010100ff00ff,0x0001010100ff0100,
|
||||
0x000101010000ffff,0x0001010100000000,0x00010101000001ff,0x0001010100000101,0x00010101000100ff,0x0001010100010000,
|
||||
0x0001010100010100,0x0001010101ff0001,0x00010101010000ff,0x00010101010001ff,0x0001010101000101,0x0001010101010001,
|
||||
0x01ffffffffffffff,0x01ffffffffffff01,0x01ffffffffff01ff,0x01ffffffffff0101,0x01ffffffff01ffff,0x01ffffffff01ff01,
|
||||
0x01ffffffff0101ff,0x01ffffffff010101,0x01ffffff00ff0000,0x01ffffff0000ffff,0x01ffffff0000ff00,0x01ffffff000000ff,
|
||||
0x01ffffff00000001,0x01ffffff00000100,0x01ffffff00010000,0x01ffffff01ffffff,0x01ffffff01ffff01,0x01ffffff01ff01ff,
|
||||
0x01ffffff01ff0101,0x01ffffff01000000,0x01ffffff0101ffff,0x01ffffff0101ff01,0x01ffffff010101ff,0x01ffffff01010101,
|
||||
0x01ffff00ffff0000,0x01ffff00ff00ff00,0x01ffff00ff0000ff,0x01ffff00ff000001,0x01ffff00ff000100,0x01ffff00ff010000,
|
||||
0x01ffff0000ffff00,0x01ffff0000ff00ff,0x01ffff0000ff0100,0x01ffff000000ffff,0x01ffff000000ff01,0x01ffff0000000000,
|
||||
0x01ffff0000000001,0x01ffff00000001ff,0x01ffff0000000100,0x01ffff00000100ff,0x01ffff0000010001,0x01ffff0000010100,
|
||||
0x01ffff0001ff0000,0x01ffff0001ff0100,0x01ffff00010000ff,0x01ffff0001000001,0x01ffff0001000100,0x01ffff0001010000,
|
||||
0x01ffff01ffffffff,0x01ffff01ffffff01,0x01ffff01ffff01ff,0x01ffff01ffff0101,0x01ffff01ff000000,0x01ffff01ff01ffff,
|
||||
0x01ffff01ff01ff01,0x01ffff01ff0101ff,0x01ffff01ff010101,0x01ffff010000ff00,0x01ffff01000000ff,0x01ffff0100000100,
|
||||
0x01ffff0100010000,0x01ffff0101ffffff,0x01ffff0101ffff01,0x01ffff0101ff01ff,0x01ffff0101ff0101,0x01ffff0101000000,
|
||||
0x01ffff010101ffff,0x01ffff010101ff01,0x01ffff01010101ff,0x01ffff0101010101,0x01ff00ffff0000ff,0x01ff00ffff000100,
|
||||
0x01ff00ff00ffff00,0x01ff00ff00ff00ff,0x01ff00ff0000ff00,0x01ff00ff00000000,0x01ff00ff00000101,0x01ff00ff0001ff00,
|
||||
0x01ff00ff000100ff,0x01ff00ff00010100,0x01ff00ff010000ff,0x01ff00ff01000100,0x01ff0000ffffff00,0x01ff0000ffff0100,
|
||||
0x01ff0000ff00ff01,0x01ff0000ff000000,0x01ff0000ff000101,0x01ff0000ff010001,0x01ff0000ff010100,0x01ff000000ffffff,
|
||||
0x01ff000000ffff00,0x01ff000000ff0000,0x01ff000000ff01ff,0x01ff00000000ff00,0x01ff0000000000ff,0x01ff000000000000,
|
||||
0x01ff000000000001,0x01ff000000000100,0x01ff000000000101,0x01ff000000010000,0x01ff000000010001,0x01ff0000000101ff,
|
||||
0x01ff000000010101,0x01ff000001ffff00,0x01ff000001ff00ff,0x01ff000001ff0001,0x01ff000001ff0100,0x01ff00000100ffff,
|
||||
0x01ff00000100ff01,0x01ff000001000000,0x01ff0000010001ff,0x01ff000001010001,0x01ff0001ff00ff00,0x01ff0001ff000001,
|
||||
0x01ff0001ff000100,0x01ff0001ff010000,0x01ff000100ffff00,0x01ff000100ff00ff,0x01ff000100ff0100,0x01ff000100ff0101,
|
||||
0x01ff00010000ffff,0x01ff000100000000,0x01ff000100000100,0x01ff000100000101,0x01ff00010001ff00,0x01ff000100010001,
|
||||
0x01ff000100010101,0x01ff000101ff0000,0x01ff00010100ff00,0x01ff000101000101,0x01ff0001010100ff,0x01ff01ffffffffff,
|
||||
0x01ff01ffffffff01,0x01ff01ffffff01ff,0x01ff01ffffff0101,0x01ff01ffff000000,0x01ff01ffff01ffff,0x01ff01ffff01ff01,
|
||||
0x01ff01ffff0101ff,0x01ff01ffff010101,0x01ff01ff00ffff00,0x01ff01ff00ff0000,0x01ff01ff0000ff00,0x01ff01ff000000ff,
|
||||
0x01ff01ff00000100,0x01ff01ff00010000,0x01ff01ff00010100,0x01ff01ff01ffffff,0x01ff01ff01ffff01,0x01ff01ff01ff01ff,
|
||||
0x01ff01ff01ff0101,0x01ff01ff01000000,0x01ff01ff0101ffff,0x01ff01ff0101ff01,0x01ff01ff010101ff,0x01ff01ff01010101,
|
||||
0x01ff0100ffff0000,0x01ff0100ffff0001,0x01ff0100ff00ff00,0x01ff0100ff0000ff,0x01ff0100ff000001,0x01ff0100ff010000,
|
||||
0x01ff010000ffff00,0x01ff010000ff00ff,0x01ff010000ff0001,0x01ff010000ff0100,0x01ff01000000ffff,0x01ff01000000ff01,
|
||||
0x01ff010000000000,0x01ff010000000101,0x01ff01000001ff00,0x01ff0100000100ff,0x01ff010001ff0000,0x01ff010001000001,
|
||||
0x01ff010001000100,0x01ff010001010000,0x01ff0101ffffffff,0x01ff0101ffffff01,0x01ff0101ffff01ff,0x01ff0101ffff0101,
|
||||
0x01ff0101ff000000,0x01ff0101ff01ffff,0x01ff0101ff01ff01,0x01ff0101ff0101ff,0x01ff0101ff010101,0x01ff010100ff0000,
|
||||
0x01ff01010000ff00,0x01ff0101000000ff,0x01ff010100000001,0x01ff010101ffffff,0x01ff010101ffff01,0x01ff010101ff01ff,
|
||||
0x01ff010101ff0101,0x01ff010101000000,0x01ff01010101ffff,0x01ff01010101ff01,0x01ff0101010101ff,0x01ff010101010101,
|
||||
0x0100ffffffff0000,0x0100ffffff00ff00,0x0100ffffff000001,0x0100ffffff0001ff,0x0100ffffff000100,0x0100ffffff010000,
|
||||
0x0100ffff00ffff00,0x0100ffff00ff0001,0x0100ffff00ff0100,0x0100ffff00000000,0x0100ffff000001ff,0x0100ffff00000101,
|
||||
0x0100ffff00010100,0x0100ffff00010101,0x0100ffff01ff0000,0x0100ffff0100ff00,0x0100ffff010000ff,0x0100ffff01000001,
|
||||
0x0100ffff01000100,0x0100ffff01010000,0x0100ff00ffffff00,0x0100ff00ffff00ff,0x0100ff00ffff0001,0x0100ff00ffff0100,
|
||||
0x0100ff00ff00ffff,0x0100ff00ff000000,0x0100ff00ff0001ff,0x0100ff00ff000101,0x0100ff00ff01ff00,0x0100ff00ff0100ff,
|
||||
0x0100ff00ff010001,0x0100ff00ff010100,0x0100ff0000ffffff,0x0100ff0000ff0000,0x0100ff000000ffff,0x0100ff000000ff00,
|
||||
0x0100ff00000000ff,0x0100ff0000000000,0x0100ff0000000001,0x0100ff0000000100,0x0100ff000001ff01,0x0100ff0000010000,
|
||||
0x0100ff0001ff00ff,0x0100ff0001ff0001,0x0100ff000100ff01,0x0100ff0001000000,0x0100ff00010001ff,0x0100ff000101ff00,
|
||||
0x0100ff00010100ff,0x0100ff0001010001,0x0100ff0001010100,0x0100ff01ffff0000,0x0100ff01ff00ff00,0x0100ff01ff0000ff,
|
||||
0x0100ff01ff000100,0x0100ff01ff010000,0x0100ff0100ff00ff,0x0100ff0100ff0001,0x0100ff0100ff0100,0x0100ff010000ffff,
|
||||
0x0100ff010000ff01,0x0100ff0100000000,0x0100ff01000001ff,0x0100ff0100010001,0x0100ff0100010100,0x0100ff0101ff0000,
|
||||
0x0100ff01010000ff,0x0100ff0101000001,0x0100ff0101010100,0x010000ffffffff00,0x010000ffffff00ff,0x010000ffffff0001,
|
||||
0x010000ffff00ffff,0x010000ffff000000,0x010000ffff0001ff,0x010000ffff010001,0x010000ff00ffffff,0x010000ff00ff0101,
|
||||
0x010000ff0000ff00,0x010000ff000000ff,0x010000ff00000000,0x010000ff00000001,0x010000ff000001ff,0x010000ff00000100,
|
||||
0x010000ff0001ffff,0x010000ff0001ff00,0x010000ff0001ff01,0x010000ff00010000,0x010000ff01ff00ff,0x010000ff01ff0001,
|
||||
0x010000ff0100ff01,0x010000ff010000ff,0x010000ff01000000,0x010000ff010001ff,0x010000ff0101ff00,0x010000ff01010100,
|
||||
0x01000000ffffffff,0x01000000ffff0000,0x01000000ffff01ff,0x01000000ffff0101,0x01000000ff00ffff,0x01000000ff00ff00,
|
||||
0x01000000ff0000ff,0x01000000ff000000,0x01000000ff000001,0x01000000ff000100,0x01000000ff01ff00,0x01000000ff010000,
|
||||
0x01000000ff010100,0x01000000ff010101,0x0100000000ffff00,0x0100000000ff00ff,0x0100000000ff0000,0x0100000000ff0001,
|
||||
0x0100000000ff0100,0x010000000000ffff,0x010000000000ff00,0x010000000000ff01,0x01000000000000ff,0x0100000000000000,
|
||||
0x0100000000000001,0x01000000000001ff,0x0100000000000100,0x0100000000000101,0x010000000001ff00,0x01000000000100ff,
|
||||
0x0100000000010000,0x0100000000010001,0x0100000000010100,0x0100000001ffff00,0x0100000001ff0000,0x0100000001ff01ff,
|
||||
0x010000000100ff00,0x010000000100ff01,0x01000000010000ff,0x0100000001000000,0x0100000001000001,0x0100000001000100,
|
||||
0x0100000001000101,0x010000000101ffff,0x010000000101ff01,0x0100000001010000,0x01000000010101ff,0x0100000001010101,
|
||||
0x01000001ffffff00,0x01000001ffff00ff,0x01000001ff00ffff,0x01000001ff000000,0x01000001ff000100,0x01000001ff01ffff,
|
||||
0x01000001ff010001,0x01000001ff010100,0x0100000100ff0000,0x0100000100ff01ff,0x0100000100ff0100,0x010000010000ff00,
|
||||
0x010000010000ff01,0x0100000100000000,0x0100000100000001,0x0100000100000100,0x0100000100010000,0x01000001000101ff,
|
||||
0x0100000101ffff01,0x0100000101ff00ff,0x0100000101ff0100,0x0100000101ff0101,0x010000010100ff01,0x01000001010000ff,
|
||||
0x0100000101000000,0x01000001010100ff,0x0100000101010001,0x0100000101010100,0x010001ffffff0000,0x010001ffff000001,
|
||||
0x010001ffff000100,0x010001ffff010000,0x010001ff00ffff00,0x010001ff00ff0001,0x010001ff0000ffff,0x010001ff0000ff01,
|
||||
0x010001ff00000000,0x010001ff00000001,0x010001ff00000101,0x010001ff000100ff,0x010001ff00010000,0x010001ff01ff0000,
|
||||
0x010001ff0100ff00,0x010001ff01000001,0x010001ff01000100,0x010001ff01010000,0x01000100ffff00ff,0x01000100ffff0001,
|
||||
0x01000100ffff0100,0x01000100ff00ffff,0x01000100ff00ff01,0x01000100ff000000,0x01000100ff0001ff,0x01000100ff000101,
|
||||
0x01000100ff01ffff,0x01000100ff01ff00,0x01000100ff0100ff,0x01000100ff010001,0x0100010000ffffff,0x0100010000ffff01,
|
||||
0x0100010000ff0000,0x0100010000ff01ff,0x0100010000ff0101,0x010001000000ff00,0x01000100000000ff,0x0100010000000000,
|
||||
0x0100010000000001,0x0100010000000100,0x010001000001ff01,0x0100010000010000,0x0100010000010001,0x0100010000010101,
|
||||
0x0100010001ffff00,0x0100010001ff00ff,0x010001000100ffff,0x010001000100ff01,0x0100010001000000,0x0100010001000101,
|
||||
0x010001000101ff00,0x0100010001010001,0x01000101ffff0000,0x01000101ff000000,0x01000101ff010000,0x0100010100ff00ff,
|
||||
0x0100010100ff0001,0x0100010100ff0100,0x010001010000ffff,0x0100010100000000,0x01000101000001ff,0x010001010001ff00,
|
||||
0x0100010101ff0000,0x010001010100ff00,0x01000101010000ff,0x0100010101000000,0x0100010101000001,0x0101ffffffffffff,
|
||||
0x0101ffffffffff01,0x0101ffffffff01ff,0x0101ffffffff0101,0x0101ffffff000000,0x0101ffffff01ffff,0x0101ffffff01ff01,
|
||||
0x0101ffffff0101ff,0x0101ffffff010101,0x0101ffff00ff0000,0x0101ffff0000ff00,0x0101ffff000000ff,0x0101ffff00000001,
|
||||
0x0101ffff00000100,0x0101ffff01ffffff,0x0101ffff01ffff01,0x0101ffff01ff01ff,0x0101ffff01ff0101,0x0101ffff01000000,
|
||||
0x0101ffff0101ffff,0x0101ffff0101ff01,0x0101ffff010101ff,0x0101ffff01010101,0x0101ff00ffff0000,0x0101ff00ffff0100,
|
||||
0x0101ff00ff00ff00,0x0101ff00ff0000ff,0x0101ff00ff000001,0x0101ff00ff000100,0x0101ff00ff000101,0x0101ff0000ff0001,
|
||||
0x0101ff0000ff0100,0x0101ff000000ff00,0x0101ff0000000000,0x0101ff00000001ff,0x0101ff0000000101,0x0101ff000001ff00,
|
||||
0x0101ff00000100ff,0x0101ff0001ff0000,0x0101ff000100ffff,0x0101ff000100ff01,0x0101ff0001000001,0x0101ff0001000100,
|
||||
0x0101ff01ffffff01,0x0101ff01ffff01ff,0x0101ff01ffff0101,0x0101ff01ff00ffff,0x0101ff01ff000100,0x0101ff01ff01ff01,
|
||||
0x0101ff01ff0101ff,0x0101ff01ff010101,0x0101ff0100ff0000,0x0101ff010000ff00,0x0101ff0100000001,0x0101ff0100000100,
|
||||
0x0101ff0100010000,0x0101ff0101ffffff,0x0101ff0101ffff01,0x0101ff0101ff01ff,0x0101ff0101ff0101,0x0101ff0101000000,
|
||||
0x0101ff010101ffff,0x0101ff010101ff01,0x0101ff01010101ff,0x0101ff0101010101,0x010100ffff000100,0x010100ffff010000,
|
||||
0x010100ff00ffff00,0x010100ff00ff00ff,0x010100ff0000ffff,0x010100ff000000ff,0x010100ff00000000,0x010100ff000001ff,
|
||||
0x010100ff00000101,0x010100ff0001ff00,0x010100ff00010000,0x010100ff00010001,0x010100ff000101ff,0x010100ff00010100,
|
||||
0x010100ff01ff0000,0x01010000ffff0001,0x01010000ffff0100,0x01010000ff00ffff,0x01010000ff00ff01,0x01010000ff000000,
|
||||
0x01010000ff0001ff,0x01010000ff010001,0x01010000ff010100,0x0101000000ffff01,0x0101000000ff0000,0x010100000000ff00,
|
||||
0x01010000000000ff,0x0101000000000000,0x0101000000000001,0x0101000000000100,0x0101000000010000,0x0101000000010101,
|
||||
0x0101000001ffff00,0x0101000001ff00ff,0x0101000001ff0000,0x0101000001ff0001,0x0101000001ff0100,0x010100000100ff01,
|
||||
0x0101000001000000,0x01010000010001ff,0x01010001ffff0000,0x01010001ff00ff00,0x01010001ff000001,0x01010001ff000101,
|
||||
0x01010001ff01ff00,0x01010001ff010000,0x0101000100ff00ff,0x0101000100ff0001,0x0101000100ff0101,0x010100010000ff01,
|
||||
0x0101000100000000,0x0101000100000001,0x01010001000001ff,0x010100010001ffff,0x010100010001ff01,0x0101000101ff0001,
|
||||
0x010100010100ffff,0x0101000101000000,0x0101000101000001,0x0101000101000100,0x010100010101ff00,0x01010001010100ff,
|
||||
0x0101000101010001,0x010101ffffffffff,0x010101ffffffff01,0x010101ffffff01ff,0x010101ffffff0101,0x010101ffff01ffff,
|
||||
0x010101ffff01ff01,0x010101ffff0101ff,0x010101ffff010101,0x010101ff0000ff00,0x010101ff000000ff,0x010101ff00000001,
|
||||
0x010101ff00000100,0x010101ff01ffffff,0x010101ff01ffff01,0x010101ff01ff01ff,0x010101ff01ff0101,0x010101ff01000000,
|
||||
0x010101ff0101ffff,0x010101ff0101ff01,0x010101ff010101ff,0x010101ff01010101,0x01010100ffff0000,0x01010100ff0000ff,
|
||||
0x01010100ff000100,0x01010100ff01ff00,0x01010100ff010000,0x0101010000ffff00,0x010101000000ffff,0x0101010000000000,
|
||||
0x0101010000000101,0x010101000001ff00,0x0101010000010001,0x0101010000010100,0x010101000100ffff,0x0101010001000001,
|
||||
0x01010101ffffffff,0x01010101ffffff01,0x01010101ffff01ff,0x01010101ffff0101,0x01010101ff01ffff,0x01010101ff01ff01,
|
||||
0x01010101ff0101ff,0x01010101ff010101,0x010101010000ff00,0x01010101000000ff,0x0101010100000001,0x0101010101ffffff,
|
||||
0x0101010101ffff01,0x0101010101ff01ff,0x0101010101ff0101,0x0101010101000000,0x010101010101ffff,0x010101010101ff01,
|
||||
0x01010101010101ff,0x0101010101010101,
|
||||
0xffffffffffffffff,0xffffffffffffff01,0xffffffffffff0000,0xffffffffffff01ff,0xffffffffffff0101,0xffffffffff00ff00,0xffffffffff000000,0xffffffffff01ffff,
|
||||
0xffffffffff01ff01,0xffffffffff0101ff,0xffffffffff010101,0xffffffff00ff0000,0xffffffff0000ff00,0xffffffff000000ff,0xffffffff00000001,0xffffffff00010000,
|
||||
0xffffffff01ffffff,0xffffffff01ffff01,0xffffffff01ff01ff,0xffffffff01ff0101,0xffffffff01000000,0xffffffff0101ffff,0xffffffff0101ff01,0xffffffff010101ff,
|
||||
0xffffffff01010101,0xffffff00ffff00ff,0xffffff00ffff0000,0xffffff00ff00ff00,0xffffff00ff0000ff,0xffffff00ff000001,0xffffff00ff000100,0xffffff00ff000101,
|
||||
0xffffff00ff010000,0xffffff0000ffff00,0xffffff0000ff0001,0xffffff0000ff0100,0xffffff000000ff01,0xffffff0000000000,0xffffff0000000101,0xffffff000001ff00,
|
||||
0xffffff00000100ff,0xffffff0000010001,0xffffff00000101ff,0xffffff0001ff0000,0xffffff000100ff00,0xffffff00010000ff,0xffffff0001000001,0xffffff0001010000,
|
||||
0xffffff01ffffffff,0xffffff01ffffff01,0xffffff01ffff01ff,0xffffff01ffff0101,0xffffff01ff000000,0xffffff01ff01ffff,0xffffff01ff01ff01,0xffffff01ff0101ff,
|
||||
0xffffff01ff010101,0xffffff0100ff0000,0xffffff010000ff00,0xffffff0100000100,0xffffff01000100ff,0xffffff0100010100,0xffffff0101ffffff,0xffffff0101ffff01,
|
||||
0xffffff0101ff01ff,0xffffff0101ff0101,0xffffff010100ff00,0xffffff0101000000,0xffffff0101000100,0xffffff010101ffff,0xffffff010101ff01,0xffffff01010101ff,
|
||||
0xffffff0101010101,0xffff00ffff00ff00,0xffff00ffff0000ff,0xffff00ffff000001,0xffff00ffff010000,0xffff00ff00ffff00,0xffff00ff00ff0100,0xffff00ff00000000,
|
||||
0xffff00ff00000101,0xffff00ff000100ff,0xffff00ff00010000,0xffff00ff0100ff00,0xffff00ff01000100,0xffff00ff01010000,0xffff0000ffffff00,0xffff0000ffff00ff,
|
||||
0xffff0000ffff0000,0xffff0000ffff0001,0xffff0000ff000000,0xffff0000ff0001ff,0xffff0000ff000101,0xffff0000ff010100,0xffff000000ffffff,0xffff000000ff0000,
|
||||
0xffff000000ff0101,0xffff00000000ffff,0xffff00000000ff00,0xffff0000000000ff,0xffff000000000000,0xffff000000000001,0xffff000000000100,0xffff00000001ffff,
|
||||
0xffff00000001ff01,0xffff000000010000,0xffff0000000101ff,0xffff000000010101,0xffff000001ffff00,0xffff00000100ff00,0xffff000001000000,0xffff0000010001ff,
|
||||
0xffff000001000101,0xffff00000101ff00,0xffff0000010100ff,0xffff000001010000,0xffff000001010001,0xffff000001010100,0xffff0001ff0000ff,0xffff0001ff000100,
|
||||
0xffff000100ffff00,0xffff000100ff00ff,0xffff00010000ffff,0xffff00010000ff01,0xffff000100000000,0xffff0001000001ff,0xffff00010001ffff,0xffff00010001ff00,
|
||||
0xffff000100010001,0xffff000100010100,0xffff000101ff0000,0xffff00010100ff00,0xffff0001010000ff,0xffff000101000100,0xffff01ffffffffff,0xffff01ffffffff01,
|
||||
0xffff01ffffff01ff,0xffff01ffffff0101,0xffff01ffff000000,0xffff01ffff01ffff,0xffff01ffff01ff01,0xffff01ffff0101ff,0xffff01ffff010101,0xffff01ff00ff0000,
|
||||
0xffff01ff0000ff00,0xffff01ff00000001,0xffff01ff00010000,0xffff01ff01ffffff,0xffff01ff01ffff01,0xffff01ff01ff01ff,0xffff01ff01ff0101,0xffff01ff01000000,
|
||||
0xffff01ff0101ffff,0xffff01ff0101ff01,0xffff01ff010101ff,0xffff01ff01010101,0xffff0100ffff0000,0xffff0100ff00ff00,0xffff0100ff0000ff,0xffff0100ff000100,
|
||||
0xffff0100ff0100ff,0xffff0100ff010000,0xffff010000ffff00,0xffff01000000ffff,0xffff01000000ff00,0xffff010000000000,0xffff01000001ff00,0xffff0100000100ff,
|
||||
0xffff010000010100,0xffff01000100ff00,0xffff0100010000ff,0xffff010001000001,0xffff010001000100,0xffff010001010000,0xffff0101ffffffff,0xffff0101ffffff01,
|
||||
0xffff0101ffff01ff,0xffff0101ffff0101,0xffff0101ff000000,0xffff0101ff01ffff,0xffff0101ff01ff01,0xffff0101ff0101ff,0xffff0101ff010101,0xffff010100ff0000,
|
||||
0xffff01010000ff00,0xffff010100000100,0xffff01010001ff00,0xffff010100010000,0xffff010101ffffff,0xffff010101ffff01,0xffff010101ff0000,0xffff010101ff01ff,
|
||||
0xffff010101ff0101,0xffff010101000000,0xffff01010101ffff,0xffff01010101ff01,0xffff0101010101ff,0xffff010101010101,0xff00ffffff00ffff,0xff00ffffff00ff00,
|
||||
0xff00ffffff0000ff,0xff00ffffff000100,0xff00ffffff0100ff,0xff00ffffff010000,0xff00ffff00ffff00,0xff00ffff00ff00ff,0xff00ffff0000ffff,0xff00ffff00000000,
|
||||
0xff00ffff000001ff,0xff00ffff0001ff00,0xff00ffff000100ff,0xff00ffff00010000,0xff00ffff00010100,0xff00ffff0100ff00,0xff00ffff010000ff,0xff00ffff01000001,
|
||||
0xff00ffff0101ff00,0xff00ffff01010000,0xff00ff00ffffff00,0xff00ff00ffff00ff,0xff00ff00ffff0001,0xff00ff00ffff0100,0xff00ff00ff00ffff,0xff00ff00ff00ff01,
|
||||
0xff00ff00ff000000,0xff00ff00ff0001ff,0xff00ff00ff01ff00,0xff00ff00ff0100ff,0xff00ff00ff010100,0xff00ff0000ff0000,0xff00ff0000ff0101,0xff00ff000000ffff,
|
||||
0xff00ff000000ff00,0xff00ff000000ff01,0xff00ff00000000ff,0xff00ff0000000000,0xff00ff0000000001,0xff00ff0000000100,0xff00ff000001ffff,0xff00ff0000010000,
|
||||
0xff00ff0001ff00ff,0xff00ff000100ff01,0xff00ff0001000000,0xff00ff000101ff00,0xff00ff00010100ff,0xff00ff01ff00ff00,0xff00ff01ff0000ff,0xff00ff01ff000001,
|
||||
0xff00ff01ff010000,0xff00ff0100ffffff,0xff00ff0100ff0001,0xff00ff0100ff0100,0xff00ff010000ff01,0xff00ff0100000000,0xff00ff01000001ff,0xff00ff0100000101,
|
||||
0xff00ff01000100ff,0xff00ff0100010001,0xff00ff0101ff0000,0xff00ff010100ff00,0xff00ff01010000ff,0xff00ff0101000001,0xff00ff0101010000,0xff0000ffffffff00,
|
||||
0xff0000ffffff0001,0xff0000ffffff0100,0xff0000ffff0000ff,0xff0000ffff000000,0xff0000ffff0001ff,0xff0000ffff000100,0xff0000ffff01ff00,0xff0000ffff010001,
|
||||
0xff0000ff00ffff00,0xff0000ff00ff0000,0xff0000ff00ff0001,0xff0000ff00ff01ff,0xff0000ff00ff0101,0xff0000ff0000ff00,0xff0000ff000000ff,0xff0000ff00000000,
|
||||
0xff0000ff00000001,0xff0000ff00000100,0xff0000ff0001ff01,0xff0000ff00010000,0xff0000ff000101ff,0xff0000ff01ff00ff,0xff0000ff01ff0100,0xff0000ff0100ffff,
|
||||
0xff0000ff010000ff,0xff0000ff01000000,0xff0000ff010001ff,0xff0000ff01000100,0xff0000ff01000101,0xff0000ff0101ff00,0xff0000ff010100ff,0xff0000ff01010000,
|
||||
0xff0000ff01010100,0xff000000ffffff01,0xff000000ffff0000,0xff000000ffff0101,0xff000000ff00ff00,0xff000000ff0000ff,0xff000000ff000000,0xff000000ff000001,
|
||||
0xff000000ff000100,0xff000000ff01ffff,0xff000000ff01ff01,0xff000000ff010000,0xff000000ff0101ff,0xff000000ff010101,0xff00000000ffff00,0xff00000000ff00ff,
|
||||
0xff00000000ff0000,0xff00000000ff0001,0xff0000000000ff00,0xff0000000000ff01,0xff000000000000ff,0xff00000000000000,0xff00000000000001,0xff00000000000100,
|
||||
0xff00000000000101,0xff0000000001ff00,0xff000000000100ff,0xff00000000010000,0xff00000000010001,0xff00000000010100,0xff00000001ffffff,0xff00000001ffff01,
|
||||
0xff00000001ff00ff,0xff00000001ff0000,0xff00000001ff01ff,0xff00000001ff0101,0xff0000000100ffff,0xff0000000100ff00,0xff000000010000ff,0xff00000001000000,
|
||||
0xff00000001000001,0xff00000001000100,0xff00000001000101,0xff0000000101ffff,0xff0000000101ff01,0xff00000001010000,0xff000001ffffff00,0xff000001ffff00ff,
|
||||
0xff000001ffff0000,0xff000001ffff0001,0xff000001ff000000,0xff000001ff000001,0xff000001ff0001ff,0xff000001ff000101,0xff000001ff01ff00,0xff000001ff010001,
|
||||
0xff00000100ffffff,0xff00000100ffff01,0xff00000100ff00ff,0xff00000100ff0000,0xff00000100ff01ff,0xff00000100ff0101,0xff0000010000ff00,0xff00000100000000,
|
||||
0xff00000100000001,0xff000001000001ff,0xff00000100000100,0xff0000010001ff00,0xff000001000100ff,0xff00000100010000,0xff000001000101ff,0xff00000100010100,
|
||||
0xff00000100010101,0xff00000101ff0001,0xff00000101ff0101,0xff0000010100ff01,0xff00000101000000,0xff000001010100ff,0xff00000101010100,0xff0001ffff00ff00,
|
||||
0xff0001ffff000001,0xff0001ffff010000,0xff0001ff00ffff00,0xff0001ff00ff00ff,0xff0001ff00ff0001,0xff0001ff00ff0100,0xff0001ff0000ffff,0xff0001ff00000000,
|
||||
0xff0001ff000001ff,0xff0001ff00000101,0xff0001ff0001ffff,0xff0001ff0001ff00,0xff0001ff000100ff,0xff0001ff00010001,0xff0001ff00010100,0xff0001ff01ff0000,
|
||||
0xff0001ff0100ff00,0xff0001ff010000ff,0xff0001ff01010000,0xff000100ff00ffff,0xff000100ff00ff01,0xff000100ff000000,0xff000100ff000101,0xff000100ff01ff00,
|
||||
0xff000100ff010000,0xff00010000ffff01,0xff00010000ff00ff,0xff00010000ff0000,0xff00010000ff01ff,0xff0001000000ff00,0xff000100000000ff,0xff00010000000000,
|
||||
0xff00010000000001,0xff00010000000100,0xff00010000000101,0xff0001000001ffff,0xff00010000010000,0xff00010000010101,0xff00010001ff0100,0xff0001000100ff00,
|
||||
0xff0001000100ff01,0xff00010001000000,0xff000100010001ff,0xff0001000101ff00,0xff00010001010001,0xff00010001010100,0xff000101ffff0100,0xff000101ff000001,
|
||||
0xff000101ff0100ff,0xff000101ff010001,0xff00010100ff00ff,0xff00010100ff0001,0xff00010100ff0100,0xff0001010000ffff,0xff0001010000ff01,0xff00010100000000,
|
||||
0xff000101000001ff,0xff0001010001ff00,0xff00010100010001,0xff00010100010100,0xff00010101ff0000,0xff0001010100ff00,0xff00010101000001,0xff00010101000101,
|
||||
0xff01ffffffffffff,0xff01ffffffffff01,0xff01ffffffff01ff,0xff01ffffffff0101,0xff01ffffff000000,0xff01ffffff01ffff,0xff01ffffff01ff01,0xff01ffffff010000,
|
||||
0xff01ffffff0101ff,0xff01ffffff010101,0xff01ffff00ff0000,0xff01ffff0000ff00,0xff01ffff00000100,0xff01ffff0001ff00,0xff01ffff00010000,0xff01ffff01ffffff,
|
||||
0xff01ffff01ffff01,0xff01ffff01ff01ff,0xff01ffff01ff0101,0xff01ffff01000000,0xff01ffff0101ffff,0xff01ffff0101ff01,0xff01ffff01010000,0xff01ffff010101ff,
|
||||
0xff01ffff01010101,0xff01ff00ffff0000,0xff01ff00ff00ff00,0xff01ff00ff0000ff,0xff01ff00ff000100,0xff01ff00ff010000,0xff01ff0000ffff01,0xff01ff0000ff00ff,
|
||||
0xff01ff0000ff0100,0xff01ff0000000000,0xff01ff00000001ff,0xff01ff0000000101,0xff01ff000001ff00,0xff01ff00000100ff,0xff01ff0000010000,0xff01ff0000010001,
|
||||
0xff01ff0001ff0000,0xff01ff000100ffff,0xff01ff0001000001,0xff01ff0001000100,0xff01ff0001010000,0xff01ff01ffffff00,0xff01ff01ffff01ff,0xff01ff01ffff0101,
|
||||
0xff01ff01ff00ff00,0xff01ff01ff000000,0xff01ff01ff01ffff,0xff01ff01ff01ff01,0xff01ff01ff0101ff,0xff01ff01ff010101,0xff01ff0100ff0000,0xff01ff010000ff00,
|
||||
0xff01ff0100000001,0xff01ff0100000100,0xff01ff0100010000,0xff01ff0101ffff00,0xff01ff0101ff01ff,0xff01ff0101ff0101,0xff01ff010100ff00,0xff01ff0101000000,
|
||||
0xff01ff010101ffff,0xff01ff010101ff01,0xff01ff01010101ff,0xff01ff0101010101,0xff0100ffffff0000,0xff0100ffff0000ff,0xff0100ffff000001,0xff0100ffff000100,
|
||||
0xff0100ffff010000,0xff0100ff00ff00ff,0xff0100ff00ff0000,0xff0100ff00ff0001,0xff0100ff00ff0100,0xff0100ff0000ff01,0xff0100ff00000000,0xff0100ff000001ff,
|
||||
0xff0100ff00000101,0xff0100ff00010001,0xff0100ff01ff0000,0xff0100ff0100ff00,0xff0100ff010000ff,0xff0100ff01000100,0xff0100ff0101ff00,0xff0100ff01010000,
|
||||
0xff010000ffff0100,0xff010000ff000000,0xff010000ff01ff00,0xff010000ff010100,0xff01000000ffffff,0xff01000000ff0000,0xff01000000ff01ff,0xff0100000000ff00,
|
||||
0xff010000000000ff,0xff01000000000000,0xff01000000000100,0xff0100000001ff01,0xff01000000010000,0xff010000000101ff,0xff01000001ff0100,0xff0100000100ffff,
|
||||
0xff010000010000ff,0xff01000001000000,0xff010000010001ff,0xff01000001000101,0xff0100000101ff00,0xff010000010100ff,0xff01000001010001,0xff01000001010100,
|
||||
0xff010001ffff0000,0xff010001ff00ffff,0xff010001ff00ff01,0xff010001ff000100,0xff010001ff010000,0xff01000100ffff00,0xff01000100ff0100,0xff01000100000000,
|
||||
0xff0100010001ffff,0xff0100010001ff00,0xff01000100010100,0xff01000101ff00ff,0xff01000101ff0001,0xff0100010100ffff,0xff01000101000101,0xff0101ffffffffff,
|
||||
0xff0101ffffffff01,0xff0101ffffff01ff,0xff0101ffffff0101,0xff0101ffff000000,0xff0101ffff01ffff,0xff0101ffff01ff01,0xff0101ffff0101ff,0xff0101ffff010101,
|
||||
0xff0101ff00ff0000,0xff0101ff0000ff00,0xff0101ff000000ff,0xff0101ff00010000,0xff0101ff01ffffff,0xff0101ff01ffff01,0xff0101ff01ff01ff,0xff0101ff01ff0101,
|
||||
0xff0101ff0101ffff,0xff0101ff0101ff01,0xff0101ff010101ff,0xff0101ff01010101,0xff010100ffff0100,0xff010100ff00ff00,0xff010100ff0000ff,0xff010100ff000100,
|
||||
0xff010100ff010000,0xff01010000ff0001,0xff01010000ff0100,0xff0101000000ff01,0xff01010000000000,0xff0101000001ff00,0xff010100000100ff,0xff01010000010001,
|
||||
0xff01010000010100,0xff01010001ff0000,0xff0101000100ffff,0xff01010001000001,0xff01010001000100,0xff010100010100ff,0xff01010001010000,0xff010101ffffffff,
|
||||
0xff010101ffffff01,0xff010101ffff01ff,0xff010101ffff0101,0xff010101ff01ffff,0xff010101ff01ff01,0xff010101ff0101ff,0xff010101ff010101,0xff01010100ff0000,
|
||||
0xff0101010000ff00,0xff01010100000001,0xff01010100000100,0xff01010100010000,0xff01010101ffffff,0xff01010101ffff01,0xff01010101ff01ff,0xff01010101ff0101,
|
||||
0xff01010101000000,0xff0101010101ffff,0xff0101010101ff01,0xff010101010101ff,0xff01010101010101,0x00ffffffffff0000,0x00ffffffff00ff00,0x00ffffffff000001,
|
||||
0x00ffffffff010000,0x00ffffff00ff0100,0x00ffffff0000ff01,0x00ffffff00000000,0x00ffffff000001ff,0x00ffffff00000101,0x00ffffff0001ff00,0x00ffffff000100ff,
|
||||
0x00ffffff00010001,0x00ffffff010000ff,0x00ffffff01000100,0x00ffffff0101ff00,0x00ffffff01010001,0x00ffff00ffffffff,0x00ffff00ffffff00,0x00ffff00ffff00ff,
|
||||
0x00ffff00ffff0001,0x00ffff00ffff0100,0x00ffff00ff00ff01,0x00ffff00ff000000,0x00ffff00ff000001,0x00ffff00ff0001ff,0x00ffff00ff000101,0x00ffff00ff01ff00,
|
||||
0x00ffff00ff010001,0x00ffff00ff010100,0x00ffff0000ff0000,0x00ffff0000ff01ff,0x00ffff0000ff0101,0x00ffff000000ff00,0x00ffff00000000ff,0x00ffff0000000000,
|
||||
0x00ffff0000000001,0x00ffff0000000100,0x00ffff0000000101,0x00ffff0000010000,0x00ffff00000101ff,0x00ffff0000010101,0x00ffff0001ffff00,0x00ffff0001ff00ff,
|
||||
0x00ffff0001ff0001,0x00ffff000100ffff,0x00ffff000100ff01,0x00ffff0001000000,0x00ffff000101ffff,0x00ffff000101ff00,0x00ffff000101ff01,0x00ffff01ffff0000,
|
||||
0x00ffff01ff00ff00,0x00ffff01ff0000ff,0x00ffff01ff000001,0x00ffff01ff010000,0x00ffff0100ffff00,0x00ffff010000ff01,0x00ffff0100000000,0x00ffff0100000101,
|
||||
0x00ffff01000100ff,0x00ffff0100010100,0x00ffff0101ff0100,0x00ffff01010000ff,0x00ffff0101010000,0x00ff00ffffffff00,0x00ff00ffff000000,0x00ff00ffff000100,
|
||||
0x00ff00ffff010100,0x00ff00ff00ff0000,0x00ff00ff00ff01ff,0x00ff00ff00ff0101,0x00ff00ff0000ff00,0x00ff00ff000000ff,0x00ff00ff00000000,0x00ff00ff00000001,
|
||||
0x00ff00ff0001ff00,0x00ff00ff0001ff01,0x00ff00ff00010000,0x00ff00ff000101ff,0x00ff00ff00010101,0x00ff00ff01ffff00,0x00ff00ff01ff0001,0x00ff00ff01ff0100,
|
||||
0x00ff00ff0100ffff,0x00ff00ff0100ff01,0x00ff00ff01000000,0x00ff00ff0101ffff,0x00ff00ff0101ff00,0x00ff00ff01010100,0x00ff0000ffffff00,0x00ff0000ffffff01,
|
||||
0x00ff0000ffff0000,0x00ff0000ffff0101,0x00ff0000ff00ff00,0x00ff0000ff0000ff,0x00ff0000ff000000,0x00ff0000ff000001,0x00ff0000ff000100,0x00ff0000ff01ffff,
|
||||
0x00ff0000ff010000,0x00ff0000ff010101,0x00ff000000ffff00,0x00ff000000ff00ff,0x00ff000000ff0000,0x00ff000000ff0001,0x00ff000000ff0100,0x00ff00000000ffff,
|
||||
0x00ff00000000ff00,0x00ff0000000000ff,0x00ff000000000000,0x00ff000000000001,0x00ff0000000001ff,0x00ff000000000100,0x00ff00000001ff00,0x00ff0000000100ff,
|
||||
0x00ff000000010000,0x00ff000000010001,0x00ff000000010100,0x00ff000001ffff01,0x00ff000001ff00ff,0x00ff000001ff0000,0x00ff000001ff01ff,0x00ff00000100ff00,
|
||||
0x00ff0000010000ff,0x00ff000001000000,0x00ff000001000001,0x00ff000001000100,0x00ff000001000101,0x00ff000001010000,0x00ff0000010101ff,0x00ff000001010101,
|
||||
0x00ff0001ffffff00,0x00ff0001ffff0000,0x00ff0001ffff0100,0x00ff0001ff0000ff,0x00ff0001ff000000,0x00ff0001ff0001ff,0x00ff0001ff000101,0x00ff0001ff01ff00,
|
||||
0x00ff0001ff0100ff,0x00ff0001ff010100,0x00ff000100ffffff,0x00ff000100ffff01,0x00ff000100ff0000,0x00ff000100ff01ff,0x00ff00010000ffff,0x00ff00010000ff00,
|
||||
0x00ff00010000ff01,0x00ff000100000000,0x00ff000100000001,0x00ff000100000100,0x00ff00010001ff01,0x00ff000100010000,0x00ff0001000101ff,0x00ff000101ffff00,
|
||||
0x00ff000101ff0000,0x00ff000101ff0101,0x00ff0001010000ff,0x00ff000101000000,0x00ff00010101ff00,0x00ff0001010100ff,0x00ff000101010001,0x00ff01ffffff0000,
|
||||
0x00ff01ffff00ff00,0x00ff01ffff000000,0x00ff01ffff000101,0x00ff01ffff010000,0x00ff01ff00ffff01,0x00ff01ff00ff0100,0x00ff01ff0000ffff,0x00ff01ff00000000,
|
||||
0x00ff01ff000001ff,0x00ff01ff0001ff00,0x00ff01ff000100ff,0x00ff01ff00010001,0x00ff01ff00010100,0x00ff01ff01ff0000,0x00ff01ff0100ff00,0x00ff01ff010000ff,
|
||||
0x00ff01ff01000001,0x00ff01ff01000100,0x00ff01ff01010000,0x00ff0100ffffff00,0x00ff0100ffff0000,0x00ff0100ffff0001,0x00ff0100ffff0101,0x00ff0100ff00ffff,
|
||||
0x00ff0100ff0000ff,0x00ff0100ff000000,0x00ff0100ff0001ff,0x00ff0100ff01ff00,0x00ff0100ff0100ff,0x00ff0100ff010001,0x00ff010000ffffff,0x00ff010000ff0000,
|
||||
0x00ff010000ff0101,0x00ff01000000ff00,0x00ff01000000ff01,0x00ff0100000000ff,0x00ff010000000000,0x00ff010000000001,0x00ff010000000100,0x00ff01000001ffff,
|
||||
0x00ff01000001ff01,0x00ff010000010000,0x00ff010000010001,0x00ff010000010101,0x00ff010001ff0001,0x00ff010001ff0100,0x00ff01000100ff01,0x00ff010001000000,
|
||||
0x00ff010001000001,0x00ff0100010001ff,0x00ff01000101ff00,0x00ff0100010100ff,0x00ff010001010001,0x00ff010001010100,0x00ff0101ff000001,0x00ff010100ff00ff,
|
||||
0x00ff010100ff0001,0x00ff010100ff0100,0x00ff010100000000,0x00ff0101000001ff,0x00ff010100000101,0x00ff0101000100ff,0x00ff010100010100,0x00ff0101010000ff,
|
||||
0x00ff010101010000,0x0000ffffffffff00,0x0000ffffffff00ff,0x0000ffffffff0000,0x0000ffffffff0001,0x0000ffffffff0100,0x0000ffffff00ff01,0x0000ffffff000000,
|
||||
0x0000ffffff000101,0x0000ffffff01ff00,0x0000ffffff0100ff,0x0000ffffff010100,0x0000ffff00ffffff,0x0000ffff00ff0000,0x0000ffff00ff01ff,0x0000ffff0000ff00,
|
||||
0x0000ffff000000ff,0x0000ffff00000000,0x0000ffff00000001,0x0000ffff00000100,0x0000ffff00010000,0x0000ffff000101ff,0x0000ffff01ff0001,0x0000ffff01ff0100,
|
||||
0x0000ffff01000000,0x0000ffff010001ff,0x0000ffff0101ffff,0x0000ffff0101ff00,0x0000ffff01010001,0x0000ffff01010100,0x0000ff00ffff0000,0x0000ff00ffff01ff,
|
||||
0x0000ff00ffff0100,0x0000ff00ffff0101,0x0000ff00ff00ff00,0x0000ff00ff0000ff,0x0000ff00ff000000,0x0000ff00ff000001,0x0000ff00ff0001ff,0x0000ff00ff000100,
|
||||
0x0000ff00ff01ffff,0x0000ff00ff010000,0x0000ff00ff010001,0x0000ff00ff0101ff,0x0000ff00ff010101,0x0000ff0000ffff00,0x0000ff0000ff00ff,0x0000ff0000ff0000,
|
||||
0x0000ff0000ff0001,0x0000ff0000ff0100,0x0000ff000000ffff,0x0000ff000000ff00,0x0000ff000000ff01,0x0000ff00000000ff,0x0000ff0000000000,0x0000ff0000000001,
|
||||
0x0000ff00000001ff,0x0000ff0000000100,0x0000ff0000000101,0x0000ff000001ff00,0x0000ff00000100ff,0x0000ff0000010000,0x0000ff0000010001,0x0000ff0000010100,
|
||||
0x0000ff0001ffff01,0x0000ff0001ff0000,0x0000ff000100ff00,0x0000ff00010000ff,0x0000ff0001000000,0x0000ff0001000001,0x0000ff0001000100,0x0000ff000101ffff,
|
||||
0x0000ff0001010000,0x0000ff0001010101,0x0000ff01ffffff00,0x0000ff01ffff0001,0x0000ff01ff00ff01,0x0000ff01ff000000,0x0000ff01ff000101,0x0000ff01ff01ff00,
|
||||
0x0000ff01ff0100ff,0x0000ff0100ffff01,0x0000ff0100ff0000,0x0000ff0100ff0101,0x0000ff010000ff00,0x0000ff01000000ff,0x0000ff0100000000,0x0000ff0100000001,
|
||||
0x0000ff0100000100,0x0000ff010001ff01,0x0000ff0100010000,0x0000ff0101ff0000,0x0000ff010100ffff,0x0000ff010100ff01,0x0000ff0101000000,0x0000ff0101000100,
|
||||
0x0000ff0101000101,0x0000ff01010100ff,0x000000ffffff00ff,0x000000ffffff0000,0x000000ffff00ff00,0x000000ffff0000ff,0x000000ffff000000,0x000000ffff000001,
|
||||
0x000000ffff0001ff,0x000000ffff000100,0x000000ffff01ff00,0x000000ffff010000,0x000000ffff0101ff,0x000000ffff010101,0x000000ff00ffff00,0x000000ff00ff00ff,
|
||||
0x000000ff00ff0000,0x000000ff00ff0001,0x000000ff00ff0100,0x000000ff00ff0101,0x000000ff0000ffff,0x000000ff0000ff00,0x000000ff000000ff,0x000000ff00000000,
|
||||
0x000000ff00000001,0x000000ff000001ff,0x000000ff00000100,0x000000ff00000101,0x000000ff0001ff00,0x000000ff0001ff01,0x000000ff000100ff,0x000000ff00010000,
|
||||
0x000000ff00010001,0x000000ff00010100,0x000000ff01ffffff,0x000000ff01ff01ff,0x000000ff01ff0101,0x000000ff0100ff00,0x000000ff010000ff,0x000000ff01000000,
|
||||
0x000000ff01000001,0x000000ff01000100,0x000000ff0101ff00,0x000000ff010100ff,0x000000ff01010000,0x000000ff01010101,0x00000000ffffff00,0x00000000ffffff01,
|
||||
0x00000000ffff00ff,0x00000000ffff0000,0x00000000ffff0001,0x00000000ffff0100,0x00000000ff00ffff,0x00000000ff00ff00,0x00000000ff00ff01,0x00000000ff0000ff,
|
||||
0x00000000ff000000,0x00000000ff000001,0x00000000ff000100,0x00000000ff000101,0x00000000ff01ff00,0x00000000ff0100ff,0x00000000ff010000,0x00000000ff010001,
|
||||
0x00000000ff010100,0x0000000000ffffff,0x0000000000ffff00,0x0000000000ffff01,0x0000000000ff00ff,0x0000000000ff0000,0x0000000000ff0001,0x0000000000ff01ff,
|
||||
0x0000000000ff0100,0x000000000000ffff,0x000000000000ff00,0x000000000000ff01,0x00000000000000ff,0x0000000000000000,0x0000000000000001,0x00000000000001ff,
|
||||
0x0000000000000100,0x0000000000000101,0x000000000001ffff,0x000000000001ff00,0x00000000000100ff,0x0000000000010000,0x0000000000010001,0x00000000000101ff,
|
||||
0x0000000000010100,0x0000000000010101,0x0000000001ffff00,0x0000000001ff00ff,0x0000000001ff0000,0x0000000001ff0100,0x0000000001ff0101,0x000000000100ffff,
|
||||
0x000000000100ff00,0x00000000010000ff,0x0000000001000000,0x0000000001000001,0x00000000010001ff,0x0000000001000100,0x000000000101ff00,0x00000000010100ff,
|
||||
0x0000000001010000,0x0000000001010001,0x0000000001010100,0x00000001ffffffff,0x00000001ffffff00,0x00000001ffffff01,0x00000001ffff00ff,0x00000001ffff0001,
|
||||
0x00000001ffff01ff,0x00000001ffff0100,0x00000001ff00ff00,0x00000001ff0000ff,0x00000001ff000000,0x00000001ff0001ff,0x00000001ff000100,0x00000001ff01ffff,
|
||||
0x00000001ff01ff00,0x00000001ff01ff01,0x00000001ff0100ff,0x00000001ff010000,0x00000001ff010001,0x00000001ff0101ff,0x00000001ff010100,0x0000000100ffff00,
|
||||
0x0000000100ff0000,0x0000000100ff0001,0x0000000100ff01ff,0x0000000100ff0100,0x0000000100ff0101,0x000000010000ffff,0x000000010000ff00,0x000000010000ff01,
|
||||
0x00000001000000ff,0x0000000100000000,0x0000000100000001,0x00000001000001ff,0x0000000100000100,0x0000000100000101,0x000000010001ff00,0x00000001000100ff,
|
||||
0x0000000100010000,0x0000000100010100,0x0000000101ffff01,0x0000000101ff0000,0x0000000101ff0001,0x0000000101ff01ff,0x0000000101ff0100,0x0000000101ff0101,
|
||||
0x000000010100ff00,0x0000000101000000,0x0000000101000101,0x000000010101ff01,0x0000000101010000,0x0000000101010001,0x00000001010101ff,0x0000000101010100,
|
||||
0x000001ffffff00ff,0x000001ffffff0000,0x000001ffffff0001,0x000001ffffff0100,0x000001ffff00ffff,0x000001ffff000000,0x000001ffff0001ff,0x000001ffff01ff00,
|
||||
0x000001ffff010101,0x000001ff00ff0000,0x000001ff00ff01ff,0x000001ff00ff0101,0x000001ff0000ff00,0x000001ff000000ff,0x000001ff00000000,0x000001ff00000001,
|
||||
0x000001ff000001ff,0x000001ff00000100,0x000001ff0001ffff,0x000001ff0001ff01,0x000001ff000100ff,0x000001ff00010000,0x000001ff01ffff01,0x000001ff01ff0100,
|
||||
0x000001ff0100ffff,0x000001ff0100ff01,0x000001ff01000000,0x000001ff010001ff,0x000001ff0101ff00,0x000001ff01010100,0x00000100ffffff00,0x00000100ffffff01,
|
||||
0x00000100ffff0000,0x00000100ffff0101,0x00000100ff00ff00,0x00000100ff0000ff,0x00000100ff000000,0x00000100ff000001,0x00000100ff000100,0x00000100ff010000,
|
||||
0x0000010000ffff00,0x0000010000ff00ff,0x0000010000ff0000,0x0000010000ff0001,0x0000010000ff0100,0x000001000000ffff,0x000001000000ff00,0x000001000000ff01,
|
||||
0x00000100000000ff,0x0000010000000000,0x0000010000000001,0x00000100000001ff,0x0000010000000100,0x0000010000000101,0x000001000001ff00,0x00000100000100ff,
|
||||
0x0000010000010000,0x0000010000010001,0x0000010000010100,0x0000010001ffff00,0x0000010001ff0000,0x0000010001ff0100,0x000001000100ff00,0x00000100010000ff,
|
||||
0x0000010001000000,0x0000010001000001,0x00000100010001ff,0x0000010001000100,0x0000010001010000,0x00000101ffff00ff,0x00000101ffff01ff,0x00000101ff000000,
|
||||
0x00000101ff000101,0x00000101ff01ffff,0x00000101ff010000,0x00000101ff010001,0x00000101ff010100,0x0000010100ff0000,0x0000010100ff01ff,0x0000010100ff0100,
|
||||
0x000001010000ff00,0x0000010100000000,0x0000010100000001,0x00000101000001ff,0x0000010100000100,0x000001010001ff01,0x0000010100010000,0x00000101000101ff,
|
||||
0x0000010100010101,0x0000010101ffff00,0x0000010101ff0101,0x000001010100ff01,0x0000010101000000,0x0000010101000001,0x00000101010001ff,0x0000010101000101,
|
||||
0x000001010101ff00,0x0001ffffffff0000,0x0001ffffff0000ff,0x0001ffffff000001,0x0001ffffff000100,0x0001ffffff010000,0x0001ffff00ff00ff,0x0001ffff0000ffff,
|
||||
0x0001ffff00000000,0x0001ffff00000001,0x0001ffff000001ff,0x0001ffff00000101,0x0001ffff0001ff00,0x0001ffff000100ff,0x0001ffff00010001,0x0001ffff00010100,
|
||||
0x0001ffff01ffff00,0x0001ffff01000001,0x0001ffff01010000,0x0001ff00ffffff00,0x0001ff00ffff00ff,0x0001ff00ffff0001,0x0001ff00ffff0100,0x0001ff00ff00ff01,
|
||||
0x0001ff00ff000000,0x0001ff00ff01ff00,0x0001ff00ff01ff01,0x0001ff00ff010001,0x0001ff00ff010100,0x0001ff0000ff0000,0x0001ff0000ff0100,0x0001ff000000ff00,
|
||||
0x0001ff0000000000,0x0001ff0000000001,0x0001ff0000000100,0x0001ff0000010000,0x0001ff0000010001,0x0001ff0000010101,0x0001ff0001ff00ff,0x0001ff0001ff0101,
|
||||
0x0001ff000100ff01,0x0001ff0001000000,0x0001ff000101ff00,0x0001ff0001010001,0x0001ff0001010100,0x0001ff01ff00ff00,0x0001ff01ff000001,0x0001ff01ff000100,
|
||||
0x0001ff0100ffffff,0x0001ff0100ffff00,0x0001ff0100ff0001,0x0001ff0100000000,0x0001ff0100000001,0x0001ff01000001ff,0x0001ff010001ffff,0x0001ff0101ff0000,
|
||||
0x0001ff010100ff00,0x0001ff0101000001,0x0001ff0101010000,0x000100ffff00ff00,0x000100ffff00ff01,0x000100ffff000000,0x000100ffff000001,0x000100ffff000101,
|
||||
0x000100ffff01ff00,0x000100ffff010001,0x000100ffff010100,0x000100ff00ffffff,0x000100ff00ffff01,0x000100ff00ff0000,0x000100ff00ff01ff,0x000100ff00ff0101,
|
||||
0x000100ff0000ff00,0x000100ff000000ff,0x000100ff00000000,0x000100ff00000001,0x000100ff00000100,0x000100ff00000101,0x000100ff0001ffff,0x000100ff0001ff01,
|
||||
0x000100ff00010000,0x000100ff01ff00ff,0x000100ff01ff0000,0x000100ff01ff0100,0x000100ff0100ffff,0x000100ff0100ff01,0x000100ff010000ff,0x000100ff01000000,
|
||||
0x000100ff01000001,0x000100ff010001ff,0x000100ff01000101,0x000100ff0101ff00,0x000100ff010100ff,0x000100ff01010100,0x00010000ffff0000,0x00010000ffff01ff,
|
||||
0x00010000ffff0101,0x00010000ff00ff00,0x00010000ff000000,0x00010000ff000001,0x00010000ff000100,0x0001000000ff00ff,0x0001000000ff0000,0x0001000000ff0001,
|
||||
0x0001000000ff0100,0x000100000000ffff,0x000100000000ff00,0x00010000000000ff,0x0001000000000000,0x0001000000000001,0x0001000000000100,0x000100000001ff00,
|
||||
0x00010000000100ff,0x0001000000010000,0x0001000000010001,0x0001000000010100,0x0001000001ff0001,0x0001000001ff0100,0x0001000001ff0101,0x000100000100ff00,
|
||||
0x0001000001000000,0x0001000001000001,0x0001000001000100,0x0001000001000101,0x000100000101ff01,0x0001000001010000,0x0001000001010001,0x00010000010101ff,
|
||||
0x00010001ffffff01,0x00010001ffff0100,0x00010001ff000000,0x00010001ff01ffff,0x00010001ff010001,0x00010001ff0101ff,0x00010001ff010100,0x0001000100ffffff,
|
||||
0x0001000100ff0000,0x0001000100ff01ff,0x0001000100ff0101,0x000100010000ff00,0x00010001000000ff,0x0001000100000000,0x0001000100000001,0x00010001000001ff,
|
||||
0x0001000100000101,0x000100010001ffff,0x0001000100010000,0x00010001000101ff,0x0001000101ffffff,0x0001000101ffff01,0x0001000101ff0000,0x0001000101ff0101,
|
||||
0x00010001010000ff,0x0001000101000001,0x00010001010001ff,0x0001000101000100,0x000100010101ffff,0x00010001010100ff,0x0001000101010001,0x0001000101010101,
|
||||
0x000101ffff000001,0x000101ffff000100,0x000101ffff010000,0x000101ff00ffff00,0x000101ff0000ff01,0x000101ff00000000,0x000101ff00000101,0x000101ff0001ff00,
|
||||
0x000101ff00010100,0x000101ff01ff0000,0x000101ff0100ff00,0x000101ff010001ff,0x000101ff01010001,0x00010100ffffff00,0x00010100ffff00ff,0x00010100ff00ffff,
|
||||
0x00010100ff000000,0x00010100ff01ff00,0x00010100ff0100ff,0x00010100ff010001,0x00010100ff010100,0x0001010000ffffff,0x0001010000ffff00,0x0001010000ff0000,
|
||||
0x0001010000ff0001,0x0001010000ff01ff,0x000101000000ff00,0x00010100000000ff,0x0001010000000000,0x0001010000000001,0x0001010000000100,0x000101000001ffff,
|
||||
0x0001010000010000,0x0001010000010101,0x0001010001ffff01,0x0001010001ff00ff,0x0001010001ff0101,0x0001010001000000,0x000101000101ff00,0x00010100010100ff,
|
||||
0x0001010001010000,0x0001010001010100,0x00010101ff00ff00,0x00010101ff000001,0x00010101ff0001ff,0x0001010100ffff00,0x0001010100ff00ff,0x0001010100ff0100,
|
||||
0x000101010000ffff,0x0001010100000000,0x00010101000001ff,0x0001010100000101,0x00010101000100ff,0x0001010100010000,0x0001010100010100,0x0001010101ff0001,
|
||||
0x00010101010000ff,0x00010101010001ff,0x0001010101000101,0x0001010101010001,0x01ffffffffffffff,0x01ffffffffffff01,0x01ffffffffff01ff,0x01ffffffffff0101,
|
||||
0x01ffffffff01ffff,0x01ffffffff01ff01,0x01ffffffff0101ff,0x01ffffffff010101,0x01ffffff00ff0000,0x01ffffff0000ffff,0x01ffffff0000ff00,0x01ffffff000000ff,
|
||||
0x01ffffff00000001,0x01ffffff00000100,0x01ffffff00010000,0x01ffffff01ffffff,0x01ffffff01ffff01,0x01ffffff01ff01ff,0x01ffffff01ff0101,0x01ffffff01000000,
|
||||
0x01ffffff0101ffff,0x01ffffff0101ff01,0x01ffffff010101ff,0x01ffffff01010101,0x01ffff00ffff0000,0x01ffff00ff00ff00,0x01ffff00ff0000ff,0x01ffff00ff000001,
|
||||
0x01ffff00ff000100,0x01ffff00ff010000,0x01ffff0000ffff00,0x01ffff0000ff00ff,0x01ffff0000ff0100,0x01ffff000000ffff,0x01ffff000000ff01,0x01ffff0000000000,
|
||||
0x01ffff0000000001,0x01ffff00000001ff,0x01ffff0000000100,0x01ffff00000100ff,0x01ffff0000010001,0x01ffff0000010100,0x01ffff0001ff0000,0x01ffff0001ff0100,
|
||||
0x01ffff00010000ff,0x01ffff0001000001,0x01ffff0001000100,0x01ffff0001010000,0x01ffff01ffffffff,0x01ffff01ffffff01,0x01ffff01ffff01ff,0x01ffff01ffff0101,
|
||||
0x01ffff01ff000000,0x01ffff01ff01ffff,0x01ffff01ff01ff01,0x01ffff01ff0101ff,0x01ffff01ff010101,0x01ffff010000ff00,0x01ffff01000000ff,0x01ffff0100000100,
|
||||
0x01ffff0100010000,0x01ffff0101ffffff,0x01ffff0101ffff01,0x01ffff0101ff01ff,0x01ffff0101ff0101,0x01ffff0101000000,0x01ffff010101ffff,0x01ffff010101ff01,
|
||||
0x01ffff01010101ff,0x01ffff0101010101,0x01ff00ffff0000ff,0x01ff00ffff000100,0x01ff00ff00ffff00,0x01ff00ff00ff00ff,0x01ff00ff0000ff00,0x01ff00ff00000000,
|
||||
0x01ff00ff00000101,0x01ff00ff0001ff00,0x01ff00ff000100ff,0x01ff00ff00010100,0x01ff00ff010000ff,0x01ff00ff01000100,0x01ff0000ffffff00,0x01ff0000ffff0100,
|
||||
0x01ff0000ff00ff01,0x01ff0000ff000000,0x01ff0000ff000101,0x01ff0000ff010001,0x01ff0000ff010100,0x01ff000000ffffff,0x01ff000000ffff00,0x01ff000000ff0000,
|
||||
0x01ff000000ff01ff,0x01ff00000000ff00,0x01ff0000000000ff,0x01ff000000000000,0x01ff000000000001,0x01ff000000000100,0x01ff000000000101,0x01ff000000010000,
|
||||
0x01ff000000010001,0x01ff0000000101ff,0x01ff000000010101,0x01ff000001ffff00,0x01ff000001ff00ff,0x01ff000001ff0001,0x01ff000001ff0100,0x01ff00000100ffff,
|
||||
0x01ff00000100ff01,0x01ff000001000000,0x01ff0000010001ff,0x01ff000001010001,0x01ff0001ff00ff00,0x01ff0001ff000001,0x01ff0001ff000100,0x01ff0001ff010000,
|
||||
0x01ff000100ffff00,0x01ff000100ff00ff,0x01ff000100ff0100,0x01ff000100ff0101,0x01ff00010000ffff,0x01ff000100000000,0x01ff000100000100,0x01ff000100000101,
|
||||
0x01ff00010001ff00,0x01ff000100010001,0x01ff000100010101,0x01ff000101ff0000,0x01ff00010100ff00,0x01ff000101000101,0x01ff0001010100ff,0x01ff01ffffffffff,
|
||||
0x01ff01ffffffff01,0x01ff01ffffff01ff,0x01ff01ffffff0101,0x01ff01ffff000000,0x01ff01ffff01ffff,0x01ff01ffff01ff01,0x01ff01ffff0101ff,0x01ff01ffff010101,
|
||||
0x01ff01ff00ffff00,0x01ff01ff00ff0000,0x01ff01ff0000ff00,0x01ff01ff000000ff,0x01ff01ff00000100,0x01ff01ff00010000,0x01ff01ff00010100,0x01ff01ff01ffffff,
|
||||
0x01ff01ff01ffff01,0x01ff01ff01ff01ff,0x01ff01ff01ff0101,0x01ff01ff01000000,0x01ff01ff0101ffff,0x01ff01ff0101ff01,0x01ff01ff010101ff,0x01ff01ff01010101,
|
||||
0x01ff0100ffff0000,0x01ff0100ffff0001,0x01ff0100ff00ff00,0x01ff0100ff0000ff,0x01ff0100ff000001,0x01ff0100ff010000,0x01ff010000ffff00,0x01ff010000ff00ff,
|
||||
0x01ff010000ff0001,0x01ff010000ff0100,0x01ff01000000ffff,0x01ff01000000ff01,0x01ff010000000000,0x01ff010000000101,0x01ff01000001ff00,0x01ff0100000100ff,
|
||||
0x01ff010001ff0000,0x01ff010001000001,0x01ff010001000100,0x01ff010001010000,0x01ff0101ffffffff,0x01ff0101ffffff01,0x01ff0101ffff01ff,0x01ff0101ffff0101,
|
||||
0x01ff0101ff000000,0x01ff0101ff01ffff,0x01ff0101ff01ff01,0x01ff0101ff0101ff,0x01ff0101ff010101,0x01ff010100ff0000,0x01ff01010000ff00,0x01ff0101000000ff,
|
||||
0x01ff010100000001,0x01ff010101ffffff,0x01ff010101ffff01,0x01ff010101ff01ff,0x01ff010101ff0101,0x01ff010101000000,0x01ff01010101ffff,0x01ff01010101ff01,
|
||||
0x01ff0101010101ff,0x01ff010101010101,0x0100ffffffff0000,0x0100ffffff00ff00,0x0100ffffff000001,0x0100ffffff0001ff,0x0100ffffff000100,0x0100ffffff010000,
|
||||
0x0100ffff00ffff00,0x0100ffff00ff0001,0x0100ffff00ff0100,0x0100ffff00000000,0x0100ffff000001ff,0x0100ffff00000101,0x0100ffff00010100,0x0100ffff00010101,
|
||||
0x0100ffff01ff0000,0x0100ffff0100ff00,0x0100ffff010000ff,0x0100ffff01000001,0x0100ffff01000100,0x0100ffff01010000,0x0100ff00ffffff00,0x0100ff00ffff00ff,
|
||||
0x0100ff00ffff0001,0x0100ff00ffff0100,0x0100ff00ff00ffff,0x0100ff00ff000000,0x0100ff00ff0001ff,0x0100ff00ff000101,0x0100ff00ff01ff00,0x0100ff00ff0100ff,
|
||||
0x0100ff00ff010001,0x0100ff00ff010100,0x0100ff0000ffffff,0x0100ff0000ff0000,0x0100ff000000ffff,0x0100ff000000ff00,0x0100ff00000000ff,0x0100ff0000000000,
|
||||
0x0100ff0000000001,0x0100ff0000000100,0x0100ff000001ff01,0x0100ff0000010000,0x0100ff0001ff00ff,0x0100ff0001ff0001,0x0100ff000100ff01,0x0100ff0001000000,
|
||||
0x0100ff00010001ff,0x0100ff000101ff00,0x0100ff00010100ff,0x0100ff0001010001,0x0100ff0001010100,0x0100ff01ffff0000,0x0100ff01ff00ff00,0x0100ff01ff0000ff,
|
||||
0x0100ff01ff000100,0x0100ff01ff010000,0x0100ff0100ff00ff,0x0100ff0100ff0001,0x0100ff0100ff0100,0x0100ff010000ffff,0x0100ff010000ff01,0x0100ff0100000000,
|
||||
0x0100ff01000001ff,0x0100ff0100010001,0x0100ff0100010100,0x0100ff0101ff0000,0x0100ff01010000ff,0x0100ff0101000001,0x0100ff0101010100,0x010000ffffffff00,
|
||||
0x010000ffffff00ff,0x010000ffffff0001,0x010000ffff00ffff,0x010000ffff000000,0x010000ffff0001ff,0x010000ffff010001,0x010000ff00ffffff,0x010000ff00ff0101,
|
||||
0x010000ff0000ff00,0x010000ff000000ff,0x010000ff00000000,0x010000ff00000001,0x010000ff000001ff,0x010000ff00000100,0x010000ff0001ffff,0x010000ff0001ff00,
|
||||
0x010000ff0001ff01,0x010000ff00010000,0x010000ff01ff00ff,0x010000ff01ff0001,0x010000ff0100ff01,0x010000ff010000ff,0x010000ff01000000,0x010000ff010001ff,
|
||||
0x010000ff0101ff00,0x010000ff01010100,0x01000000ffffffff,0x01000000ffff0000,0x01000000ffff01ff,0x01000000ffff0101,0x01000000ff00ffff,0x01000000ff00ff00,
|
||||
0x01000000ff0000ff,0x01000000ff000000,0x01000000ff000001,0x01000000ff000100,0x01000000ff01ff00,0x01000000ff010000,0x01000000ff010100,0x01000000ff010101,
|
||||
0x0100000000ffff00,0x0100000000ff00ff,0x0100000000ff0000,0x0100000000ff0001,0x0100000000ff0100,0x010000000000ffff,0x010000000000ff00,0x010000000000ff01,
|
||||
0x01000000000000ff,0x0100000000000000,0x0100000000000001,0x01000000000001ff,0x0100000000000100,0x0100000000000101,0x010000000001ff00,0x01000000000100ff,
|
||||
0x0100000000010000,0x0100000000010001,0x0100000000010100,0x0100000001ffff00,0x0100000001ff0000,0x0100000001ff01ff,0x010000000100ff00,0x010000000100ff01,
|
||||
0x01000000010000ff,0x0100000001000000,0x0100000001000001,0x0100000001000100,0x0100000001000101,0x010000000101ffff,0x010000000101ff01,0x0100000001010000,
|
||||
0x01000000010101ff,0x0100000001010101,0x01000001ffffff00,0x01000001ffff00ff,0x01000001ff00ffff,0x01000001ff000000,0x01000001ff000100,0x01000001ff01ffff,
|
||||
0x01000001ff010001,0x01000001ff010100,0x0100000100ff0000,0x0100000100ff01ff,0x0100000100ff0100,0x010000010000ff00,0x010000010000ff01,0x0100000100000000,
|
||||
0x0100000100000001,0x0100000100000100,0x0100000100010000,0x01000001000101ff,0x0100000101ffff01,0x0100000101ff00ff,0x0100000101ff0100,0x0100000101ff0101,
|
||||
0x010000010100ff01,0x01000001010000ff,0x0100000101000000,0x01000001010100ff,0x0100000101010001,0x0100000101010100,0x010001ffffff0000,0x010001ffff000001,
|
||||
0x010001ffff000100,0x010001ffff010000,0x010001ff00ffff00,0x010001ff00ff0001,0x010001ff0000ffff,0x010001ff0000ff01,0x010001ff00000000,0x010001ff00000001,
|
||||
0x010001ff00000101,0x010001ff000100ff,0x010001ff00010000,0x010001ff01ff0000,0x010001ff0100ff00,0x010001ff01000001,0x010001ff01000100,0x010001ff01010000,
|
||||
0x01000100ffff00ff,0x01000100ffff0001,0x01000100ffff0100,0x01000100ff00ffff,0x01000100ff00ff01,0x01000100ff000000,0x01000100ff0001ff,0x01000100ff000101,
|
||||
0x01000100ff01ffff,0x01000100ff01ff00,0x01000100ff0100ff,0x01000100ff010001,0x0100010000ffffff,0x0100010000ffff01,0x0100010000ff0000,0x0100010000ff01ff,
|
||||
0x0100010000ff0101,0x010001000000ff00,0x01000100000000ff,0x0100010000000000,0x0100010000000001,0x0100010000000100,0x010001000001ff01,0x0100010000010000,
|
||||
0x0100010000010001,0x0100010000010101,0x0100010001ffff00,0x0100010001ff00ff,0x010001000100ffff,0x010001000100ff01,0x0100010001000000,0x0100010001000101,
|
||||
0x010001000101ff00,0x0100010001010001,0x01000101ffff0000,0x01000101ff000000,0x01000101ff010000,0x0100010100ff00ff,0x0100010100ff0001,0x0100010100ff0100,
|
||||
0x010001010000ffff,0x0100010100000000,0x01000101000001ff,0x010001010001ff00,0x0100010101ff0000,0x010001010100ff00,0x01000101010000ff,0x0100010101000000,
|
||||
0x0100010101000001,0x0101ffffffffffff,0x0101ffffffffff01,0x0101ffffffff01ff,0x0101ffffffff0101,0x0101ffffff000000,0x0101ffffff01ffff,0x0101ffffff01ff01,
|
||||
0x0101ffffff0101ff,0x0101ffffff010101,0x0101ffff00ff0000,0x0101ffff0000ff00,0x0101ffff000000ff,0x0101ffff00000001,0x0101ffff00000100,0x0101ffff01ffffff,
|
||||
0x0101ffff01ffff01,0x0101ffff01ff01ff,0x0101ffff01ff0101,0x0101ffff01000000,0x0101ffff0101ffff,0x0101ffff0101ff01,0x0101ffff010101ff,0x0101ffff01010101,
|
||||
0x0101ff00ffff0000,0x0101ff00ffff0100,0x0101ff00ff00ff00,0x0101ff00ff0000ff,0x0101ff00ff000001,0x0101ff00ff000100,0x0101ff00ff000101,0x0101ff0000ff0001,
|
||||
0x0101ff0000ff0100,0x0101ff000000ff00,0x0101ff0000000000,0x0101ff00000001ff,0x0101ff0000000101,0x0101ff000001ff00,0x0101ff00000100ff,0x0101ff0001ff0000,
|
||||
0x0101ff000100ffff,0x0101ff000100ff01,0x0101ff0001000001,0x0101ff0001000100,0x0101ff01ffffff01,0x0101ff01ffff01ff,0x0101ff01ffff0101,0x0101ff01ff00ffff,
|
||||
0x0101ff01ff000100,0x0101ff01ff01ff01,0x0101ff01ff0101ff,0x0101ff01ff010101,0x0101ff0100ff0000,0x0101ff010000ff00,0x0101ff0100000001,0x0101ff0100000100,
|
||||
0x0101ff0100010000,0x0101ff0101ffffff,0x0101ff0101ffff01,0x0101ff0101ff01ff,0x0101ff0101ff0101,0x0101ff0101000000,0x0101ff010101ffff,0x0101ff010101ff01,
|
||||
0x0101ff01010101ff,0x0101ff0101010101,0x010100ffff000100,0x010100ffff010000,0x010100ff00ffff00,0x010100ff00ff00ff,0x010100ff0000ffff,0x010100ff000000ff,
|
||||
0x010100ff00000000,0x010100ff000001ff,0x010100ff00000101,0x010100ff0001ff00,0x010100ff00010000,0x010100ff00010001,0x010100ff000101ff,0x010100ff00010100,
|
||||
0x010100ff01ff0000,0x01010000ffff0001,0x01010000ffff0100,0x01010000ff00ffff,0x01010000ff00ff01,0x01010000ff000000,0x01010000ff0001ff,0x01010000ff010001,
|
||||
0x01010000ff010100,0x0101000000ffff01,0x0101000000ff0000,0x010100000000ff00,0x01010000000000ff,0x0101000000000000,0x0101000000000001,0x0101000000000100,
|
||||
0x0101000000010000,0x0101000000010101,0x0101000001ffff00,0x0101000001ff00ff,0x0101000001ff0000,0x0101000001ff0001,0x0101000001ff0100,0x010100000100ff01,
|
||||
0x0101000001000000,0x01010000010001ff,0x01010001ffff0000,0x01010001ff00ff00,0x01010001ff000001,0x01010001ff000101,0x01010001ff01ff00,0x01010001ff010000,
|
||||
0x0101000100ff00ff,0x0101000100ff0001,0x0101000100ff0101,0x010100010000ff01,0x0101000100000000,0x0101000100000001,0x01010001000001ff,0x010100010001ffff,
|
||||
0x010100010001ff01,0x0101000101ff0001,0x010100010100ffff,0x0101000101000000,0x0101000101000001,0x0101000101000100,0x010100010101ff00,0x01010001010100ff,
|
||||
0x0101000101010001,0x010101ffffffffff,0x010101ffffffff01,0x010101ffffff01ff,0x010101ffffff0101,0x010101ffff01ffff,0x010101ffff01ff01,0x010101ffff0101ff,
|
||||
0x010101ffff010101,0x010101ff0000ff00,0x010101ff000000ff,0x010101ff00000001,0x010101ff00000100,0x010101ff01ffffff,0x010101ff01ffff01,0x010101ff01ff01ff,
|
||||
0x010101ff01ff0101,0x010101ff01000000,0x010101ff0101ffff,0x010101ff0101ff01,0x010101ff010101ff,0x010101ff01010101,0x01010100ffff0000,0x01010100ff0000ff,
|
||||
0x01010100ff000100,0x01010100ff01ff00,0x01010100ff010000,0x0101010000ffff00,0x010101000000ffff,0x0101010000000000,0x0101010000000101,0x010101000001ff00,
|
||||
0x0101010000010001,0x0101010000010100,0x010101000100ffff,0x0101010001000001,0x01010101ffffffff,0x01010101ffffff01,0x01010101ffff01ff,0x01010101ffff0101,
|
||||
0x01010101ff01ffff,0x01010101ff01ff01,0x01010101ff0101ff,0x01010101ff010101,0x010101010000ff00,0x01010101000000ff,0x0101010100000001,0x0101010101ffffff,
|
||||
0x0101010101ffff01,0x0101010101ff01ff,0x0101010101ff0101,0x0101010101000000,0x010101010101ffff,0x010101010101ff01,0x01010101010101ff,0x0101010101010101,
|
||||
];
|
||||
|
||||
@@ -4,9 +4,8 @@
|
||||
use super::rust_simd::{half, hsum_ggml};
|
||||
use super::rust_types::Q8K;
|
||||
use std::arch::x86_64::*;
|
||||
// Bounds: `dot` asserts row.len()==ys.len()*block; all row bytes are read through safe indexing, and the only raw loads
|
||||
// are 32-byte reads of local [i16;16]/[u8;256]/[i8;256] arrays at offsets <= 224 and of y.bsums ([i16;16]).
|
||||
// Gate: avx2_ok().
|
||||
// Bounds: `dot` asserts row.len()==ys.len()*block; all row bytes are read through safe indexing, and the only raw loads are
|
||||
// 32-byte reads of local [i16;16]/[u8;256]/[i8;256] arrays at offsets <= 224 and of y.bsums ([i16;16]). Gate: avx2_ok().
|
||||
fn h(x: &[u8], p: usize) -> f32 {
|
||||
/* SAFETY: private; reached only from `dot`, whose entry gate proved F16C. */
|
||||
unsafe { half(u16::from_le_bytes([x[p], x[p + 1]])) }
|
||||
@@ -53,15 +52,8 @@ unsafe fn product(q: &[u8], high: Option<&[u8]>, y: &[i8], scales: __m256i) -> _
|
||||
_mm256_madd_epi16(scales, p)
|
||||
}
|
||||
}
|
||||
/// The scalar-unpacked operands of one block: 8-bit quants, the Q3_K high-bit correction, the 16 sub-block scales
|
||||
/// and the block scale already multiplied by the activation scale.
|
||||
struct Unpacked {
|
||||
q: [u8; 256],
|
||||
hi: [u8; 256],
|
||||
sc: [i16; 16],
|
||||
d: f32,
|
||||
}
|
||||
fn block_bytes(kind: i32) -> usize {
|
||||
/// Encoded bytes of one super-block of `kind` (10 Q2_K, 11 Q3_K, 13 Q5_K, 14 Q6_K).
|
||||
fn block_size(kind: i32) -> usize {
|
||||
match kind {
|
||||
10 => 84,
|
||||
11 => 110,
|
||||
@@ -70,38 +62,53 @@ fn block_bytes(kind: i32) -> usize {
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn unpack_q2k(x: &[u8], y: &Q8K) -> Unpacked {
|
||||
let mut q = [0u8; 256];
|
||||
for j in 0..256 {
|
||||
q[j] = (x[16 + (j / 128) * 32 + j % 32] >> ((j % 128 / 32) * 2)) & 3;
|
||||
/// Q2_K block: unpack the 2-bit quants into `q`, fold the mins into `acc`; returns the scales and the block scale.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn decode_q2(x: &[u8], y: &Q8K, q: &mut [u8; 256], acc: &mut __m256) -> ([i16; 16], f32) {
|
||||
unsafe {
|
||||
for j in 0..256 {
|
||||
q[j] = (x[16 + (j / 128) * 32 + j % 32] >> ((j % 128 / 32) * 2)) & 3;
|
||||
}
|
||||
let sc = std::array::from_fn(|j| (x[j] & 15) as i16);
|
||||
let min: [i16; 16] = std::array::from_fn(|j| (x[j] >> 4) as i16);
|
||||
let prod =
|
||||
_mm256_madd_epi16(_mm256_loadu_si256(min.as_ptr().cast()), _mm256_loadu_si256(y.bsums.as_ptr().cast()));
|
||||
let dm = -y.d * h(x, 82);
|
||||
*acc = _mm256_fmadd_ps(_mm256_set1_ps(dm), _mm256_cvtepi32_ps(prod), *acc);
|
||||
(sc, y.d * h(x, 80))
|
||||
}
|
||||
Unpacked { q, hi: [0u8; 256], sc: std::array::from_fn(|j| (x[j] & 15) as i16), d: y.d * h(x, 80) }
|
||||
}
|
||||
#[inline]
|
||||
fn unpack_q3k(x: &[u8], y: &Q8K) -> Unpacked {
|
||||
let mut q = [0u8; 256];
|
||||
let mut hi = [0u8; 256];
|
||||
/// Q3_K block: unpack the low 2 bits into `q` and the high-bit correction into `hi`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn decode_q3(x: &[u8], y: &Q8K, q: &mut [u8; 256], hi: &mut [u8; 256]) -> ([i16; 16], f32) {
|
||||
for j in 0..256 {
|
||||
q[j] = (x[32 + (j / 128) * 32 + j % 32] >> ((j % 128 / 32) * 2)) & 3;
|
||||
hi[j] = if x[j % 32] & (1 << (j / 32)) == 0 { 4 } else { 0 };
|
||||
}
|
||||
Unpacked { q, hi, sc: six_scales(&x[96..108]), d: y.d * h(x, 108) }
|
||||
(six_scales(&x[96..108]), y.d * h(x, 108))
|
||||
}
|
||||
#[inline]
|
||||
fn unpack_q5k(x: &[u8], y: &Q8K) -> Unpacked {
|
||||
let (s, _) = k4(&x[4..16]);
|
||||
let mut q = [0u8; 256];
|
||||
for j in 0..256 {
|
||||
let chunk = j / 32;
|
||||
q[j] = (x[48 + (chunk / 2) * 32 + j % 32] >> ((chunk % 2) * 4)) & 15;
|
||||
q[j] += ((x[16 + j % 32] >> chunk) & 1) << 4;
|
||||
/// Q5_K block: unpack the 5-bit quants into `q`, add the mins term to `mins_sum`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn decode_q5(x: &[u8], y: &Q8K, q: &mut [u8; 256], mins_sum: &mut f32) -> ([i16; 16], f32) {
|
||||
unsafe {
|
||||
let (s, m) = k4(&x[4..16]);
|
||||
for j in 0..256 {
|
||||
let chunk = j / 32;
|
||||
q[j] = (x[48 + (chunk / 2) * 32 + j % 32] >> ((chunk % 2) * 4)) & 15;
|
||||
q[j] += ((x[16 + j % 32] >> chunk) & 1) << 4;
|
||||
}
|
||||
let mins = _mm_setr_epi16(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7]);
|
||||
let b = _mm256_loadu_si256(y.bsums.as_ptr().cast());
|
||||
let b = _mm_hadd_epi16(_mm256_extracti128_si256::<0>(b), _mm256_extracti128_si256::<1>(b));
|
||||
let prod = _mm_madd_epi16(mins, b);
|
||||
let hs = _mm_hadd_epi32(_mm_hadd_epi32(prod, _mm_setzero_si128()), _mm_setzero_si128());
|
||||
*mins_sum += (-y.d * h(x, 2)) * _mm_extract_epi32::<0>(hs) as f32;
|
||||
(std::array::from_fn(|j| s[j / 2]), y.d * h(x, 0))
|
||||
}
|
||||
Unpacked { q, hi: [0u8; 256], sc: std::array::from_fn(|j| s[j / 2]), d: y.d * h(x, 0) }
|
||||
}
|
||||
#[inline]
|
||||
fn unpack_q6k(x: &[u8], y: &Q8K) -> Unpacked {
|
||||
let mut q = [0u8; 256];
|
||||
/// Q6_K block: unpack the 6-bit quants into `q`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn decode_q6(x: &[u8], y: &Q8K, q: &mut [u8; 256]) -> ([i16; 16], f32) {
|
||||
for j in 0..256 {
|
||||
let chunk = j % 128 / 32;
|
||||
q[j] = ((x[j / 128 * 64 + if chunk == 1 || chunk == 3 { 32 } else { 0 } + j % 32]
|
||||
@@ -109,98 +116,46 @@ fn unpack_q6k(x: &[u8], y: &Q8K) -> Unpacked {
|
||||
& 15)
|
||||
| (((x[128 + j / 128 * 32 + j % 32] >> (chunk * 2)) & 3) << 4);
|
||||
}
|
||||
Unpacked { q, hi: [0u8; 256], sc: std::array::from_fn(|j| x[192 + j] as i8 as i16), d: y.d * h(x, 208) }
|
||||
(std::array::from_fn(|j| x[192 + j] as i8 as i16), y.d * h(x, 208))
|
||||
}
|
||||
#[inline]
|
||||
fn unpack(kind: i32, x: &[u8], y: &Q8K) -> Unpacked {
|
||||
match kind {
|
||||
10 => unpack_q2k(x, y),
|
||||
11 => unpack_q3k(x, y),
|
||||
13 => unpack_q5k(x, y),
|
||||
14 => unpack_q6k(x, y),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
/// Q2_K: the accumulator with the block's min correction `-d_y * dmin * sum(min * bsums)` fused into it.
|
||||
/// The four 32-lane products of one 128-quant group starting at `at`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn add_q2k_mins(x: &[u8], y: &Q8K, acc: __m256) -> __m256 {
|
||||
let min: [i16; 16] = std::array::from_fn(|j| (x[j] >> 4) as i16);
|
||||
// SAFETY: `min` is 16 i16 (32 bytes) and `y.bsums` is [i16; 16], both fully read by the 32-byte loads.
|
||||
let prod = unsafe {
|
||||
_mm256_madd_epi16(_mm256_loadu_si256(min.as_ptr().cast()), _mm256_loadu_si256(y.bsums.as_ptr().cast()))
|
||||
};
|
||||
let dm = -y.d * h(x, 82);
|
||||
_mm256_fmadd_ps(_mm256_set1_ps(dm), _mm256_cvtepi32_ps(prod), acc)
|
||||
}
|
||||
/// Q5_K: the block's min correction `-d_y * dmin * sum(min * bsums)` as a float term (added to a separate sum).
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn q5k_mins_term(x: &[u8], y: &Q8K) -> f32 {
|
||||
let (_, m) = k4(&x[4..16]);
|
||||
let mins = _mm_setr_epi16(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7]);
|
||||
// SAFETY: `y.bsums` is [i16; 16], fully read by the 32-byte load.
|
||||
let b = unsafe { _mm256_loadu_si256(y.bsums.as_ptr().cast()) };
|
||||
let b = _mm_hadd_epi16(_mm256_extracti128_si256::<0>(b), _mm256_extracti128_si256::<1>(b));
|
||||
let prod = _mm_madd_epi16(mins, b);
|
||||
let hs = _mm_hadd_epi32(_mm_hadd_epi32(prod, _mm_setzero_si128()), _mm_setzero_si128());
|
||||
(-y.d * h(x, 2)) * _mm_extract_epi32::<0>(hs) as f32
|
||||
}
|
||||
/// The four 32-lane integer products of the 128 values starting at `at`.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn group_products(kind: i32, u: &Unpacked, y: &Q8K, at: usize) -> [__m256i; 4] {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
unsafe fn group_products(kind: i32, q: &[u8; 256], hi: &[u8; 256], y: &Q8K, sc: &[i16; 16], at: usize) -> [__m256i; 4] {
|
||||
unsafe {
|
||||
let mut p = [_mm256_setzero_si256(); 4];
|
||||
for j in 0..4 {
|
||||
let offset = at + j * 32;
|
||||
p[j] = product(
|
||||
&u.q[offset..],
|
||||
if kind == 11 { Some(&u.hi[offset..]) } else { None },
|
||||
&q[offset..],
|
||||
if kind == 11 { Some(&hi[offset..]) } else { None },
|
||||
&y.qs[offset..],
|
||||
pair_scale(u.sc[offset / 16], u.sc[offset / 16 + 1]),
|
||||
pair_scale(sc[offset / 16], sc[offset / 16 + 1]),
|
||||
);
|
||||
}
|
||||
p
|
||||
}
|
||||
}
|
||||
/// `sum` plus the four products of one group (Q6_K adds them as two pairs, the others as one balanced tree).
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn add_group(kind: i32, sum: __m256i, p: &[__m256i; 4]) -> __m256i {
|
||||
if kind == 14 {
|
||||
let sum = _mm256_add_epi32(sum, _mm256_add_epi32(p[0], p[1]));
|
||||
_mm256_add_epi32(sum, _mm256_add_epi32(p[2], p[3]))
|
||||
} else {
|
||||
_mm256_add_epi32(sum, _mm256_add_epi32(_mm256_add_epi32(p[0], p[1]), _mm256_add_epi32(p[2], p[3])))
|
||||
}
|
||||
}
|
||||
/// Q6_K: the `32 * sum(scale * bsums)` offset that the unsigned quants carry.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn q6k_offset(y: &Q8K, sc: &[i16; 16]) -> __m256i {
|
||||
// SAFETY: `y.bsums` and `sc` are [i16; 16], both fully read by the 32-byte loads.
|
||||
unsafe {
|
||||
_mm256_slli_epi32::<5>(_mm256_madd_epi16(
|
||||
_mm256_loadu_si256(y.bsums.as_ptr().cast()),
|
||||
_mm256_loadu_si256(sc.as_ptr().cast()),
|
||||
))
|
||||
}
|
||||
}
|
||||
/// The exact i32 sum of one block's scaled products.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn sum_block(kind: i32, u: &Unpacked, y: &Q8K) -> __m256i {
|
||||
// SAFETY: this fn's target features cover the intrinsics and helpers below; the loads follow the Bounds note above.
|
||||
/// Integer dot of one block: both groups folded into `sum` (Q6_K pairs the adds differently), minus the Q6_K bias.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn block_sum(kind: i32, q: &[u8; 256], hi: &[u8; 256], y: &Q8K, sc: &[i16; 16]) -> __m256i {
|
||||
unsafe {
|
||||
let mut sum = _mm256_setzero_si256();
|
||||
for group in 0..2 {
|
||||
let p = group_products(kind, u, y, group * 128);
|
||||
sum = add_group(kind, sum, &p);
|
||||
let p = group_products(kind, q, hi, y, sc, group * 128);
|
||||
if kind == 14 {
|
||||
sum = _mm256_add_epi32(sum, _mm256_add_epi32(p[0], p[1]));
|
||||
sum = _mm256_add_epi32(sum, _mm256_add_epi32(p[2], p[3]));
|
||||
} else {
|
||||
sum =
|
||||
_mm256_add_epi32(sum, _mm256_add_epi32(_mm256_add_epi32(p[0], p[1]), _mm256_add_epi32(p[2], p[3])));
|
||||
}
|
||||
}
|
||||
if kind == 14 {
|
||||
sum = _mm256_sub_epi32(sum, q6k_offset(y, &u.sc));
|
||||
let sub = _mm256_slli_epi32::<5>(_mm256_madd_epi16(
|
||||
_mm256_loadu_si256(y.bsums.as_ptr().cast()),
|
||||
_mm256_loadu_si256(sc.as_ptr().cast()),
|
||||
));
|
||||
sum = _mm256_sub_epi32(sum, sub);
|
||||
}
|
||||
sum
|
||||
}
|
||||
@@ -208,20 +163,22 @@ unsafe fn sum_block(kind: i32, u: &Unpacked, y: &Q8K) -> __m256i {
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn dot(kind: i32, row: &[u8], ys: &[Q8K]) -> f32 {
|
||||
unsafe {
|
||||
let size = block_bytes(kind);
|
||||
let size = block_size(kind);
|
||||
assert_eq!(row.len(), ys.len() * size);
|
||||
let mut acc = _mm256_setzero_ps();
|
||||
let mut mins_sum = 0.0f32;
|
||||
for (x, y) in row.chunks_exact(size).zip(ys) {
|
||||
let u = unpack(kind, x, y);
|
||||
if kind == 10 {
|
||||
acc = add_q2k_mins(x, y, acc);
|
||||
}
|
||||
if kind == 13 {
|
||||
mins_sum += q5k_mins_term(x, y);
|
||||
}
|
||||
let sum = sum_block(kind, &u, y);
|
||||
acc = _mm256_fmadd_ps(_mm256_set1_ps(u.d), _mm256_cvtepi32_ps(sum), acc);
|
||||
let mut q = [0u8; 256];
|
||||
let mut hi = [0u8; 256];
|
||||
let (sc, d) = match kind {
|
||||
10 => decode_q2(x, y, &mut q, &mut acc),
|
||||
11 => decode_q3(x, y, &mut q, &mut hi),
|
||||
13 => decode_q5(x, y, &mut q, &mut mins_sum),
|
||||
14 => decode_q6(x, y, &mut q),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let sum = block_sum(kind, &q, &hi, y, &sc);
|
||||
acc = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sum), acc);
|
||||
}
|
||||
let total = hsum_ggml(acc);
|
||||
if kind == 13 { total + mins_sum } else { total }
|
||||
|
||||
@@ -4,13 +4,9 @@ use super::rust_simd::{half, hsum_ggml};
|
||||
use super::rust_types::{Q8K, Q8Zero};
|
||||
use super::{Error, Result};
|
||||
use std::arch::x86_64::*;
|
||||
|
||||
mod q4_k_block;
|
||||
use q4_k_block::{q4k_add_mins, q4k_expand, q4k_reduce, q4k_scales_mins, q4k_sum};
|
||||
// Bounds: every row walk is chunks_exact(block)/safe slicing with a `y[ib]` safe index; raw loads read 16 bytes of a
|
||||
// block at offset (2|4|6|8) <= block-16, 32 bytes of Q8One/Q8Zero.qs ([i8;32]) or Q8K.qs/bsums ([i8;256]/[i16;16] = 32
|
||||
// bytes). bf16_* are `pub` safe wrappers: shape-checked with checked_mul, then avx2_ok() (AVX2+FMA) before the unsafe
|
||||
// leaf.
|
||||
// Bounds: every row walk is chunks_exact(block)/safe slicing with a `y[ib]` safe index; raw loads read 16 bytes of a block
|
||||
// at offset (2|4|6|8) <= block-16, 32 bytes of Q8One/Q8Zero.qs ([i8;32]) or Q8K.qs/bsums ([i8;256]/[i16;16] = 32 bytes).
|
||||
// bf16_* are `pub` safe wrappers: shape-checked with checked_mul, then avx2_ok() (AVX2+FMA) before the unsafe leaf.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(super) struct Q8One {
|
||||
@@ -114,9 +110,83 @@ pub(super) unsafe fn q5_one_dot(row: &[u8], ys: &[&[Q8One]], res: &mut [f32]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The per-block weight tables of a Q4_K block: min scales and the low/high nibble planes with their scale shuffles.
|
||||
struct Q4kBlock {
|
||||
mins: __m128i,
|
||||
ql: [__m256i; 4],
|
||||
qh: [__m256i; 4],
|
||||
sl: [__m256i; 4],
|
||||
sh: [__m256i; 4],
|
||||
}
|
||||
/// The 6-bit scales (as 16-bit lanes duplicated across both halves) and mins of a Q4_K block's packed scale bytes.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn q4k_scales(x: &[u8]) -> (__m128i, __m256i) {
|
||||
let mut u = [0u32; 4];
|
||||
for j in 0..3 {
|
||||
u[j] = u32::from_le_bytes(x[4 + j * 4..8 + j * 4].try_into().unwrap());
|
||||
}
|
||||
u[3] = ((u[2] >> 4) & 0x0f0f0f0f) | (((u[1] >> 6) & 0x03030303) << 4);
|
||||
let aux = u[1] & 0x3f3f3f3f;
|
||||
u[1] = (u[2] & 0x0f0f0f0f) | (((u[0] >> 6) & 0x03030303) << 4);
|
||||
u[2] = aux;
|
||||
u[0] &= 0x3f3f3f3f;
|
||||
let ms = _mm256_cvtepu8_epi16(_mm_set_epi32(u[3] as i32, u[2] as i32, u[1] as i32, u[0] as i32));
|
||||
let mins = _mm256_extracti128_si256::<1>(ms);
|
||||
let s128 = _mm256_castsi256_si128(ms);
|
||||
(mins, _mm256_inserti128_si256::<1>(_mm256_castsi128_si256(s128), s128))
|
||||
}
|
||||
/// Unpack one Q4_K weight block into its nibble planes and scale shuffles.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn q4k_unpack(x: &[u8]) -> Q4kBlock {
|
||||
unsafe {
|
||||
let (mins, scales) = q4k_scales(x);
|
||||
let mut ql = [_mm256_setzero_si256(); 4];
|
||||
let mut qh = ql;
|
||||
let mut sl = ql;
|
||||
let mut sh = ql;
|
||||
for j in 0..4 {
|
||||
let mut l = [0i8; 32];
|
||||
let mut h = [0i8; 32];
|
||||
for k in 0..32 {
|
||||
l[k] = (4 * j + k % 2) as i8;
|
||||
h[k] = (4 * j + 2 + k % 2) as i8;
|
||||
}
|
||||
sl[j] = _mm256_shuffle_epi8(scales, _mm256_loadu_si256(l.as_ptr().cast()));
|
||||
sh[j] = _mm256_shuffle_epi8(scales, _mm256_loadu_si256(h.as_ptr().cast()));
|
||||
let q = _mm256_loadu_si256(x.as_ptr().add(16 + j * 32).cast());
|
||||
ql[j] = _mm256_and_si256(q, _mm256_set1_epi8(15));
|
||||
qh[j] = _mm256_and_si256(_mm256_srli_epi16::<4>(q), _mm256_set1_epi8(15));
|
||||
}
|
||||
Q4kBlock { mins, ql, qh, sl, sh }
|
||||
}
|
||||
}
|
||||
/// One token's block: fold the mins correction into `acc_m` and the scaled integer dot into `acc`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn q4k_token(w: &Q4kBlock, y: &Q8K, (xd, xdmin): (f32, f32), acc: &mut __m256, acc_m: &mut __m128) {
|
||||
unsafe {
|
||||
let d = y.d * xd;
|
||||
let dm = -y.d * xdmin;
|
||||
let sums = _mm256_loadu_si256(y.bsums.as_ptr().cast());
|
||||
let sums = _mm_hadd_epi16(_mm256_extracti128_si256::<0>(sums), _mm256_extracti128_si256::<1>(sums));
|
||||
let prod = _mm_madd_epi16(w.mins, sums);
|
||||
*acc_m = _mm_fmadd_ps(_mm_set1_ps(dm), _mm_cvtepi32_ps(prod), *acc_m);
|
||||
let mut sumi = _mm256_setzero_si256();
|
||||
for j in 0..4 {
|
||||
let lo = _mm256_madd_epi16(
|
||||
w.sl[j],
|
||||
_mm256_maddubs_epi16(w.ql[j], _mm256_loadu_si256(y.qs.as_ptr().add(j * 64).cast())),
|
||||
);
|
||||
let hi = _mm256_madd_epi16(
|
||||
w.sh[j],
|
||||
_mm256_maddubs_epi16(w.qh[j], _mm256_loadu_si256(y.qs.as_ptr().add(j * 64 + 32).cast())),
|
||||
);
|
||||
sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(lo, hi));
|
||||
}
|
||||
*acc = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), *acc);
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn q4_k_dot(row: &[u8], ys: &[&[Q8K]], res: &mut [f32]) {
|
||||
// SAFETY: the target features of this fn cover the intrinsics and helpers below; loads stay inside whole arrays.
|
||||
unsafe {
|
||||
let mut acc = [_mm256_setzero_ps(); 8];
|
||||
let mut acc_m = [_mm_setzero_ps(); 8];
|
||||
@@ -124,23 +194,20 @@ pub(super) unsafe fn q4_k_dot(row: &[u8], ys: &[&[Q8K]], res: &mut [f32]) {
|
||||
for (ib, x) in row.chunks_exact(144).enumerate() {
|
||||
let xd = half(u16::from_le_bytes([x[0], x[1]]));
|
||||
let xdmin = half(u16::from_le_bytes([x[2], x[3]]));
|
||||
let (scales, mins) = q4k_scales_mins(x);
|
||||
let block = q4k_expand(x, scales);
|
||||
let w = q4k_unpack(x);
|
||||
for t in 0..ys.len() {
|
||||
let y = &ys[t][ib];
|
||||
let d = y.d * xd;
|
||||
let dm = -y.d * xdmin;
|
||||
acc_m[t] = q4k_add_mins(mins, y, dm, acc_m[t]);
|
||||
let sumi = q4k_sum(&block, y);
|
||||
acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc[t]);
|
||||
q4k_token(&w, &ys[t][ib], (xd, xdmin), &mut acc[t], &mut acc_m[t]);
|
||||
}
|
||||
}
|
||||
for t in 0..ys.len() {
|
||||
res[t] = q4k_reduce(acc[t], acc_m[t]);
|
||||
let m = _mm_add_ps(acc_m[t], _mm_movehl_ps(acc_m[t], acc_m[t]));
|
||||
let m = _mm_add_ss(m, _mm_movehdup_ps(m));
|
||||
res[t] = hsum_ggml(acc[t]) + _mm_cvtss_f32(m);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn small_block_bytes(kind: i32) -> usize {
|
||||
/// Bytes per block of the small kinds 2 (Q4_0), 3 (Q4_1), 6 (Q5_0), 7 (Q5_1), 8 (Q8_0).
|
||||
fn small_block(kind: i32) -> usize {
|
||||
match kind {
|
||||
2 => 18,
|
||||
3 => 20,
|
||||
@@ -150,31 +217,9 @@ fn small_block_bytes(kind: i32) -> usize {
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
/// Activation block `ib`: its scale, its 32 quants and, for Q8One only, the weight-min x activation-sum term.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn small_activation(
|
||||
x: &[u8],
|
||||
zero: Option<&[Q8Zero]>,
|
||||
one: Option<&[Q8One]>,
|
||||
ib: usize,
|
||||
) -> (f32, __m256i, Option<f32>) {
|
||||
// SAFETY: the 32-byte loads read the whole [i8; 32] `qs` of a safely indexed block.
|
||||
unsafe {
|
||||
if let Some(y) = zero {
|
||||
(half(y[ib].d), _mm256_loadu_si256(y[ib].qs.as_ptr().cast()), None)
|
||||
} else {
|
||||
let y = one.unwrap();
|
||||
let term = half(u16::from_le_bytes([x[2], x[3]])) * half(y[ib].s);
|
||||
(half(y[ib].d), _mm256_loadu_si256(y[ib].qs.as_ptr().cast()), Some(term))
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The 32 signed weight quants of one block `x` of format `kind`.
|
||||
/// The 32 unpacked weight bytes of one small-kind block `x`.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn small_weights(kind: i32, x: &[u8]) -> __m256i {
|
||||
// SAFETY: the target features of this fn cover the intrinsics and helpers below; loads stay inside whole arrays.
|
||||
unsafe {
|
||||
match kind {
|
||||
2 => _mm256_sub_epi8(nibbles(x.as_ptr().add(2)), _mm256_set1_epi8(8)),
|
||||
@@ -192,33 +237,40 @@ unsafe fn small_weights(kind: i32, x: &[u8]) -> __m256i {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The 32 products summed in pairs: unsigned weights for the formats with a min (3, 7), signed for the others.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn small_products(kind: i32, qx: __m256i, qy: __m256i) -> __m256 {
|
||||
// SAFETY: the target features of this fn cover the intrinsics and helpers below; loads stay inside whole arrays.
|
||||
/// The activation scale and bytes of block `ib` (Q8_0 `zero` or Q8_1-style `one`); the `one` form also adds its
|
||||
/// min term to `sums`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn small_acts(
|
||||
(zero, one): (Option<&[Q8Zero]>, Option<&[Q8One]>),
|
||||
ib: usize,
|
||||
x: &[u8],
|
||||
sums: &mut f32,
|
||||
) -> (f32, __m256i) {
|
||||
unsafe {
|
||||
if matches!(kind, 3 | 7) {
|
||||
super::rust_ggml_native::unsigned_pairs(qx, qy).unwrap_or_else(|| unsigned_dot(qx, qy))
|
||||
if let Some(y) = zero {
|
||||
(half(y[ib].d), _mm256_loadu_si256(y[ib].qs.as_ptr().cast()))
|
||||
} else {
|
||||
super::rust_ggml_native::signed_pairs(qx, qy).unwrap_or_else(|| signed_dot(qx, qy))
|
||||
let y = one.unwrap();
|
||||
*sums += half(u16::from_le_bytes([x[2], x[3]])) * half(y[ib].s);
|
||||
(half(y[ib].d), _mm256_loadu_si256(y[ib].qs.as_ptr().cast()))
|
||||
}
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn small_dot(kind: i32, row: &[u8], zero: Option<&[Q8Zero]>, one: Option<&[Q8One]>) -> f32 {
|
||||
// SAFETY: the target features of this fn cover the intrinsics and helpers below; loads stay inside whole arrays.
|
||||
unsafe {
|
||||
let block = small_block_bytes(kind);
|
||||
let block = small_block(kind);
|
||||
let mut acc = _mm256_setzero_ps();
|
||||
let mut sums = 0.0;
|
||||
for (ib, x) in row.chunks_exact(block).enumerate() {
|
||||
let xd = half(u16::from_le_bytes([x[0], x[1]]));
|
||||
let (yd, qy, term) = small_activation(x, zero, one, ib);
|
||||
if let Some(term) = term {
|
||||
sums += term;
|
||||
}
|
||||
let q = small_products(kind, small_weights(kind, x), qy);
|
||||
let (yd, qy) = small_acts((zero, one), ib, x, &mut sums);
|
||||
let qx = small_weights(kind, x);
|
||||
let q = if matches!(kind, 3 | 7) {
|
||||
super::rust_ggml_native::unsigned_pairs(qx, qy).unwrap_or_else(|| unsigned_dot(qx, qy))
|
||||
} else {
|
||||
super::rust_ggml_native::signed_pairs(qx, qy).unwrap_or_else(|| signed_dot(qx, qy))
|
||||
};
|
||||
acc = if kind == 7 {
|
||||
_mm256_fmadd_ps(q, _mm256_set1_ps(xd * yd), acc)
|
||||
} else {
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
//! Q4_K helpers of `rust_kq`: scale/min unpack, nibble expansion, min correction, block sum, final reduction.
|
||||
use super::*;
|
||||
|
||||
/// The expanded Q4_K weights of one block: the low and high nibbles of each 32 bytes (`ql`, `qh`) and the scales
|
||||
/// broadcast to match them (`sl`, `sh`).
|
||||
pub(super) struct Q4kBlock {
|
||||
ql: [__m256i; 4],
|
||||
qh: [__m256i; 4],
|
||||
sl: [__m256i; 4],
|
||||
sh: [__m256i; 4],
|
||||
}
|
||||
/// The 6-bit sub-block scales (both 128-bit lanes equal) and the eight 6-bit mins (as 16-bit lanes) of a Q4_K block.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
pub(super) unsafe fn q4k_scales_mins(x: &[u8]) -> (__m256i, __m128i) {
|
||||
let mut u = [0u32; 4];
|
||||
for j in 0..3 {
|
||||
u[j] = u32::from_le_bytes(x[4 + j * 4..8 + j * 4].try_into().unwrap());
|
||||
}
|
||||
u[3] = ((u[2] >> 4) & 0x0f0f0f0f) | (((u[1] >> 6) & 0x03030303) << 4);
|
||||
let aux = u[1] & 0x3f3f3f3f;
|
||||
u[1] = (u[2] & 0x0f0f0f0f) | (((u[0] >> 6) & 0x03030303) << 4);
|
||||
u[2] = aux;
|
||||
u[0] &= 0x3f3f3f3f;
|
||||
let ms = _mm256_cvtepu8_epi16(_mm_set_epi32(u[3] as i32, u[2] as i32, u[1] as i32, u[0] as i32));
|
||||
let mins = _mm256_extracti128_si256::<1>(ms);
|
||||
let s128 = _mm256_castsi256_si128(ms);
|
||||
(_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(s128), s128), mins)
|
||||
}
|
||||
/// The scales of byte pairs `4j + off`, `4j + off + 1` spread over the 32 lanes (`off` 0 for the low nibbles, 2 for
|
||||
/// the high ones).
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
unsafe fn q4k_spread_scales(scales: __m256i, j: usize, off: usize) -> __m256i {
|
||||
let mut idx = [0i8; 32];
|
||||
for (k, v) in idx.iter_mut().enumerate() {
|
||||
*v = (4 * j + off + k % 2) as i8;
|
||||
}
|
||||
// SAFETY: `idx` is 32 bytes, fully read by the 32-byte load.
|
||||
unsafe { _mm256_shuffle_epi8(scales, _mm256_loadu_si256(idx.as_ptr().cast())) }
|
||||
}
|
||||
/// Expands the 128 quant bytes at offset 16 of a 144-byte block `x` into nibble vectors and matching scales.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
pub(super) unsafe fn q4k_expand(x: &[u8], scales: __m256i) -> Q4kBlock {
|
||||
// SAFETY: the target features of this fn cover the intrinsics and helpers below; loads stay inside whole arrays.
|
||||
unsafe {
|
||||
let zero = [_mm256_setzero_si256(); 4];
|
||||
let mut b = Q4kBlock { ql: zero, qh: zero, sl: zero, sh: zero };
|
||||
for j in 0..4 {
|
||||
b.sl[j] = q4k_spread_scales(scales, j, 0);
|
||||
b.sh[j] = q4k_spread_scales(scales, j, 2);
|
||||
let q = _mm256_loadu_si256(x.as_ptr().add(16 + j * 32).cast());
|
||||
b.ql[j] = _mm256_and_si256(q, _mm256_set1_epi8(15));
|
||||
b.qh[j] = _mm256_and_si256(_mm256_srli_epi16::<4>(q), _mm256_set1_epi8(15));
|
||||
}
|
||||
b
|
||||
}
|
||||
}
|
||||
/// `acc_m` plus the min correction `dm * sum(min * bsums)` of one activation block.
|
||||
#[target_feature(enable = "avx2,fma")]
|
||||
#[inline]
|
||||
pub(super) unsafe fn q4k_add_mins(mins: __m128i, y: &Q8K, dm: f32, acc_m: __m128) -> __m128 {
|
||||
// SAFETY: `y.bsums` is [i16; 16] (32 bytes), fully read by the load.
|
||||
let sums = unsafe { _mm256_loadu_si256(y.bsums.as_ptr().cast()) };
|
||||
let sums = _mm_hadd_epi16(_mm256_extracti128_si256::<0>(sums), _mm256_extracti128_si256::<1>(sums));
|
||||
let prod = _mm_madd_epi16(mins, sums);
|
||||
_mm_fmadd_ps(_mm_set1_ps(dm), _mm_cvtepi32_ps(prod), acc_m)
|
||||
}
|
||||
/// The exact i32 sum of one block's scaled nibble products against the activation block `y`.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
pub(super) unsafe fn q4k_sum(b: &Q4kBlock, y: &Q8K) -> __m256i {
|
||||
// SAFETY: the target features of this fn cover the intrinsics and helpers below; loads stay inside whole arrays.
|
||||
unsafe {
|
||||
let mut sumi = _mm256_setzero_si256();
|
||||
for j in 0..4 {
|
||||
let lo = _mm256_madd_epi16(
|
||||
b.sl[j],
|
||||
_mm256_maddubs_epi16(b.ql[j], _mm256_loadu_si256(y.qs.as_ptr().add(j * 64).cast())),
|
||||
);
|
||||
let hi = _mm256_madd_epi16(
|
||||
b.sh[j],
|
||||
_mm256_maddubs_epi16(b.qh[j], _mm256_loadu_si256(y.qs.as_ptr().add(j * 64 + 32).cast())),
|
||||
);
|
||||
sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(lo, hi));
|
||||
}
|
||||
sumi
|
||||
}
|
||||
}
|
||||
/// One token's result: the reduced block accumulator plus the reduced min accumulator.
|
||||
#[target_feature(enable = "avx2")]
|
||||
#[inline]
|
||||
pub(super) unsafe fn q4k_reduce(acc: __m256, acc_m: __m128) -> f32 {
|
||||
let m = _mm_add_ps(acc_m, _mm_movehl_ps(acc_m, acc_m));
|
||||
let m = _mm_add_ss(m, _mm_movehdup_ps(m));
|
||||
// SAFETY: the target features of this fn include AVX2, which `hsum_ggml` requires; register-only otherwise.
|
||||
unsafe { hsum_ggml(acc) + _mm_cvtss_f32(m) }
|
||||
}
|
||||
@@ -54,6 +54,9 @@ use set_oracle_q8_zero_fn::row512;
|
||||
pub use set_oracle_q8_zero_fn::set_oracle_q8_zero;
|
||||
#[allow(unused_imports)]
|
||||
use set_oracle_q8_zero_fn::unpack32;
|
||||
mod pair_rows_fn;
|
||||
#[allow(unused_imports)]
|
||||
use pair_rows_fn::{act_refs, down_row, gate_up_pair};
|
||||
mod admit_fn;
|
||||
#[allow(unused_imports)]
|
||||
use admit_fn::admit;
|
||||
@@ -67,9 +70,6 @@ pub use admit_fn::expert_quantized;
|
||||
pub use admit_fn::expert_scalar;
|
||||
#[allow(unused_imports)]
|
||||
pub use admit_fn::gate_up_rows;
|
||||
mod row_slices;
|
||||
#[allow(unused_imports)]
|
||||
use row_slices::{activation_refs, down_row, gate_row, store_cells, store_silu_cells, up_row};
|
||||
mod gate_each_fn;
|
||||
#[allow(unused_imports)]
|
||||
pub(super) use gate_each_fn::down_each;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Planar Q2 entry points: the admission checks, the row-range gate/up and down, and the whole-expert entries.
|
||||
//! Moved out of the parent module by STRA-338: fn admit, fn gate_up_rows, fn down_rows, fn expert_quantized, fn expert, fn expert_scalar.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -31,30 +31,35 @@ pub(super) fn admit(
|
||||
pub fn gate_up_rows(blob: &[u8], a: &[&PlanarActivation], out: &mut [&mut [f32]], r0: usize, r1: usize) -> Result<()> {
|
||||
admit(blob, a, out, FF, 80, r0, r1)?;
|
||||
let empty = ActQ::default();
|
||||
let aa = activation_refs(a.iter().copied(), &empty);
|
||||
let aa = act_refs(a, &empty);
|
||||
let n = a.len();
|
||||
let mut g = [0.0; MAX_ROWS];
|
||||
let mut u = [0.0; MAX_ROWS];
|
||||
// Original row-range APIs always use row_dot, even in oracle activation mode.
|
||||
for r in r0..r1 {
|
||||
gate_row(blob, r, &aa[..a.len()], &mut g[..a.len()], false);
|
||||
up_row(blob, r, &aa[..a.len()], &mut u[..a.len()], false);
|
||||
store_silu_cells(out, r, &g[..a.len()], &u[..a.len()]);
|
||||
gate_up_pair(blob, r, &aa[..n], &mut g[..n], &mut u[..n], false);
|
||||
for t in 0..n {
|
||||
out[t][r] = silu(g[t], u[t]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn down_rows(blob: &[u8], a: &[&PlanarActivation], out: &mut [&mut [f32]], r0: usize, r1: usize) -> Result<()> {
|
||||
admit(blob, a, out, H, 20, r0, r1)?;
|
||||
let empty = ActQ::default();
|
||||
let aa = activation_refs(a.iter().copied(), &empty);
|
||||
let aa = act_refs(a, &empty);
|
||||
let n = a.len();
|
||||
let mut v = [0.0; MAX_ROWS];
|
||||
for r in r0..r1 {
|
||||
down_row(blob, r, &aa[..a.len()], &mut v[..a.len()], false);
|
||||
store_cells(out, r, &v[..a.len()]);
|
||||
down_row(blob, r, &aa[..n], &mut v[..n], false);
|
||||
for t in 0..n {
|
||||
out[t][r] = v[t];
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The checks of a whole-expert call: shapes (any token count), then the CPU gate.
|
||||
fn admit_whole(blob: &[u8], a: &[&PlanarActivation], out: &[&mut [f32]]) -> Result<()> {
|
||||
/// Shape and CPU admission of a whole multi-token expert call.
|
||||
fn admit_expert(blob: &[u8], a: &[&PlanarActivation], out: &[&mut [f32]]) -> Result<()> {
|
||||
if blob.len() != BLOB
|
||||
|| a.is_empty()
|
||||
|| a.len() > i32::MAX as usize
|
||||
@@ -69,24 +74,27 @@ fn admit_whole(blob: &[u8], a: &[&PlanarActivation], out: &[&mut [f32]]) -> Resu
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Gate/up of every row for `aa.len()` tokens: the hidden activation `silu(gate) * up` into `ff[token][row]`.
|
||||
fn fill_hidden(blob: &[u8], aa: &[&ActQ], oracle: bool, ff: &mut [[f32; FF]; MAX_ROWS]) {
|
||||
/// Gate/up pass of an eight-row-or-fewer multi call: the SiLU product of every hidden row into `scratch.ff`.
|
||||
fn hidden_rows(blob: &[u8], aa: &[&ActQ], scratch: &mut PlanarScratch, oracle: bool) {
|
||||
let n = aa.len();
|
||||
let mut g = [0.0; MAX_ROWS];
|
||||
let mut u = [0.0; MAX_ROWS];
|
||||
for r in 0..FF {
|
||||
gate_row(blob, r, aa, &mut g[..aa.len()], oracle);
|
||||
up_row(blob, r, aa, &mut u[..aa.len()], oracle);
|
||||
for ((cells, g), u) in ff.iter_mut().zip(&g[..aa.len()]).zip(&u[..aa.len()]) {
|
||||
cells[r] = silu(*g, *u);
|
||||
gate_up_pair(blob, r, aa, &mut g[..n], &mut u[..n], oracle);
|
||||
for t in 0..n {
|
||||
scratch.ff[t][r] = silu(g[t], u[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Down projection of every row for `aa.len()` tokens into `out[token][row]`.
|
||||
fn fill_output(blob: &[u8], aa: &[&ActQ], oracle: bool, out: &mut [&mut [f32]]) {
|
||||
let mut v = [0.0; MAX_ROWS];
|
||||
/// Down pass of a multi call against the requantized hidden rows `aa`, into the token outputs.
|
||||
fn output_rows(blob: &[u8], aa: &[&ActQ], out: &mut [&mut [f32]], oracle: bool) {
|
||||
let n = aa.len();
|
||||
let mut g = [0.0; MAX_ROWS];
|
||||
for r in 0..H {
|
||||
down_row(blob, r, aa, &mut v[..aa.len()], oracle);
|
||||
store_cells(out, r, &v[..aa.len()]);
|
||||
down_row(blob, r, aa, &mut g[..n], oracle);
|
||||
for t in 0..n {
|
||||
out[t][r] = g[t];
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn expert_quantized(
|
||||
@@ -97,7 +105,7 @@ pub fn expert_quantized(
|
||||
) -> Result<()> {
|
||||
// The Original multi entry falls back to complete per-token experts for
|
||||
// oracle mode or a call wider than its eight-row multi scratch.
|
||||
admit_whole(blob, a, out)?;
|
||||
admit_expert(blob, a, out)?;
|
||||
let oracle = oracle_q8_zero_enabled();
|
||||
if oracle || a.len() > MAX_ROWS {
|
||||
for t in 0..a.len() {
|
||||
@@ -105,12 +113,17 @@ pub fn expert_quantized(
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let n = a.len();
|
||||
let empty = ActQ::default();
|
||||
fill_hidden(blob, &activation_refs(a.iter().copied(), &empty)[..a.len()], oracle, &mut scratch.ff);
|
||||
for t in 0..a.len() {
|
||||
let mut aa = act_refs(a, &empty);
|
||||
hidden_rows(blob, &aa[..n], scratch, oracle);
|
||||
for t in 0..n {
|
||||
scratch.a2[t].quantize(&scratch.ff[t])?;
|
||||
}
|
||||
fill_output(blob, &activation_refs(scratch.a2[..a.len()].iter(), &empty)[..a.len()], oracle, out);
|
||||
for t in 0..n {
|
||||
aa[t] = &scratch.a2[t].0;
|
||||
}
|
||||
output_rows(blob, &aa[..n], out, oracle);
|
||||
Ok(())
|
||||
}
|
||||
pub fn expert(blob: &[u8], x: &[f32], out: &mut [f32], scratch: &mut PlanarScratch) -> Result<()> {
|
||||
@@ -121,41 +134,47 @@ pub fn expert(blob: &[u8], x: &[f32], out: &mut [f32], scratch: &mut PlanarScrat
|
||||
a.quantize(x)?;
|
||||
expert_quantized(blob, &[&a], &mut [out], scratch)
|
||||
}
|
||||
/// Replace `values` by their dequantized form `scale * code` under the quantization of `a`.
|
||||
/// Overwrite `values` with the dequantized activation `scale * q` (the scalar reference's quantized operand).
|
||||
fn dequantize(a: &PlanarActivation, values: &mut [f32]) {
|
||||
for (i, v) in values.iter_mut().enumerate() {
|
||||
*v = a.0.scale[i / 32] * a.0.q[i] as f32;
|
||||
}
|
||||
}
|
||||
/// The ternary weight `code - 1` of the two-bit code `j` of `byte` (four codes per byte, low bits first).
|
||||
fn ternary(byte: u8, j: usize) -> f32 {
|
||||
(((byte >> (2 * (j % 4))) & 3) as i32 - 1) as f32
|
||||
/// Ternary weight `{-1, 0, 1, 2}` (as a float) at position `j` of block `b` of the row starting at `row_at`.
|
||||
fn trit(blob: &[u8], row_at: usize, b: usize, j: usize) -> f32 {
|
||||
(((blob[row_at + b * 16 + j / 4] >> (2 * (j % 4))) & 3) as i32 - 1) as f32
|
||||
}
|
||||
/// Scalar gate and up dot of row `r` against `input`, combined as `silu(gate) * up`.
|
||||
fn scalar_hidden(blob: &[u8], r: usize, input: &[f32]) -> f32 {
|
||||
let mut sg = 0.0;
|
||||
let mut su = 0.0;
|
||||
for b in 0..40 {
|
||||
let dg = half(&blob[GU_SCALES + 2 * r * 80 + 2 * b..]);
|
||||
let du = half(&blob[GU_SCALES + (2 * r + 1) * 80 + 2 * b..]);
|
||||
for j in 0..64 {
|
||||
let o = b * 64 + j;
|
||||
sg += ternary(blob[2 * r * 640 + b * 16 + j / 4], j) * dg * input[o];
|
||||
su += ternary(blob[(2 * r + 1) * 640 + b * 16 + j / 4], j) * du * input[o];
|
||||
/// The scalar gate/up pass: `silu(gate . input, up . input)` of every hidden row.
|
||||
fn scalar_gate_up(blob: &[u8], input: &[f32]) -> [f32; FF] {
|
||||
let mut ff = [0.0; FF];
|
||||
for r in 0..FF {
|
||||
let mut sg = 0.0;
|
||||
let mut su = 0.0;
|
||||
for b in 0..40 {
|
||||
let dg = half(&blob[GU_SCALES + 2 * r * 80 + 2 * b..]);
|
||||
let du = half(&blob[GU_SCALES + (2 * r + 1) * 80 + 2 * b..]);
|
||||
for j in 0..64 {
|
||||
let o = b * 64 + j;
|
||||
sg += trit(blob, 2 * r * 640, b, j) * dg * input[o];
|
||||
su += trit(blob, (2 * r + 1) * 640, b, j) * du * input[o];
|
||||
}
|
||||
}
|
||||
ff[r] = silu(sg, su);
|
||||
}
|
||||
silu(sg, su)
|
||||
ff
|
||||
}
|
||||
/// Scalar down dot of row `r` against the hidden activation `ff`.
|
||||
fn scalar_output(blob: &[u8], r: usize, ff: &[f32; FF]) -> f32 {
|
||||
let mut sum = 0.0;
|
||||
for b in 0..10 {
|
||||
let d = half(&blob[D_SCALES + r * 20 + 2 * b..]);
|
||||
for j in 0..64 {
|
||||
sum += ternary(blob[D_CODES + r * 160 + b * 16 + j / 4], j) * d * ff[b * 64 + j];
|
||||
/// The scalar down pass over the hidden row `ff`.
|
||||
fn scalar_down(blob: &[u8], ff: &[f32; FF], out: &mut [f32]) {
|
||||
for (r, value) in out.iter_mut().enumerate() {
|
||||
let mut sum = 0.0;
|
||||
for b in 0..10 {
|
||||
let d = half(&blob[D_SCALES + r * 20 + 2 * b..]);
|
||||
for j in 0..64 {
|
||||
sum += trit(blob, D_CODES + r * 160, b, j) * d * ff[b * 64 + j];
|
||||
}
|
||||
}
|
||||
*value = sum;
|
||||
}
|
||||
sum
|
||||
}
|
||||
/// Original scalar benchmark, deliberately distinct from VNNI evaluation order.
|
||||
pub fn expert_scalar(blob: &[u8], x: &[f32], out: &mut [f32], quantized: bool) -> Result<()> {
|
||||
@@ -171,16 +190,11 @@ pub fn expert_scalar(blob: &[u8], x: &[f32], out: &mut [f32], quantized: bool) -
|
||||
} else {
|
||||
x
|
||||
};
|
||||
let mut ff = [0.0; FF];
|
||||
for (r, cell) in ff.iter_mut().enumerate() {
|
||||
*cell = scalar_hidden(blob, r, input);
|
||||
}
|
||||
let mut ff = scalar_gate_up(blob, input);
|
||||
if quantized {
|
||||
a.quantize(&ff)?;
|
||||
dequantize(&a, &mut ff);
|
||||
}
|
||||
for (r, value) in out.iter_mut().enumerate() {
|
||||
*value = scalar_output(blob, r, &ff);
|
||||
}
|
||||
scalar_down(blob, &ff, out);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Planar Q2 row walkers for the pool (gate/up and down, one callback per cell) and the single-token whole expert.
|
||||
//! Moved out of the parent module by STRA-338: fn gate_each, fn down_each, impl Default_for_SingleScratch, fn whole_single.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -13,13 +13,13 @@ pub(in super::super) fn gate_each(
|
||||
mut write: impl FnMut(usize, usize, f32),
|
||||
) {
|
||||
let empty = ActQ::default();
|
||||
let aa = activation_refs(a.iter().copied(), &empty);
|
||||
let aa = act_refs(a, &empty);
|
||||
let n = a.len();
|
||||
let mut g = [0.0; MAX_ROWS];
|
||||
let mut u = g;
|
||||
for r in r0..r1 {
|
||||
gate_row(blob, r, &aa[..a.len()], &mut g[..a.len()], false);
|
||||
up_row(blob, r, &aa[..a.len()], &mut u[..a.len()], false);
|
||||
for t in 0..a.len() {
|
||||
gate_up_pair(blob, r, &aa[..n], &mut g[..n], &mut u[..n], false);
|
||||
for t in 0..n {
|
||||
write(t, r, silu(g[t], u[t]));
|
||||
}
|
||||
}
|
||||
@@ -32,12 +32,13 @@ pub(in super::super) fn down_each(
|
||||
mut write: impl FnMut(usize, usize, f32),
|
||||
) {
|
||||
let empty = ActQ::default();
|
||||
let aa = activation_refs(a.iter().copied(), &empty);
|
||||
let aa = act_refs(a, &empty);
|
||||
let n = a.len();
|
||||
let mut v = [0.0; MAX_ROWS];
|
||||
for r in r0..r1 {
|
||||
down_row(blob, r, &aa[..a.len()], &mut v[..a.len()], false);
|
||||
for (t, cell) in v[..a.len()].iter().enumerate() {
|
||||
write(t, r, *cell);
|
||||
down_row(blob, r, &aa[..n], &mut v[..n], false);
|
||||
for t in 0..n {
|
||||
write(t, r, v[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,8 +52,7 @@ pub(in super::super) fn whole_single(blob: &[u8], a: &PlanarActivation, out: &mu
|
||||
let mut g = [0.0];
|
||||
let mut u = [0.0];
|
||||
for r in 0..FF {
|
||||
gate_row(blob, r, &[&a.0], &mut g, oracle);
|
||||
up_row(blob, r, &[&a.0], &mut u, oracle);
|
||||
gate_up_pair(blob, r, &[&a.0], &mut g, &mut u, oracle);
|
||||
s.ff[r] = silu(g[0], u[0]);
|
||||
}
|
||||
s.a2.quantize(&s.ff).expect("admitted legacy whole geometry");
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
//! STRA-338 size4: the row-pair helpers shared by the legacy planar entry points (`gate_each`, `down_each`,
|
||||
//! `whole_single`, `gate_up_rows`, `down_rows`, `expert_quantized`).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The per-token `ActQ` references of `a` (unused slots point at `empty`).
|
||||
pub(super) fn act_refs<'a>(a: &'a [&PlanarActivation], empty: &'a ActQ) -> [&'a ActQ; MAX_ROWS] {
|
||||
let mut aa = [empty; MAX_ROWS];
|
||||
for t in 0..a.len() {
|
||||
aa[t] = &a[t].0;
|
||||
}
|
||||
aa
|
||||
}
|
||||
/// Gate (`g`) and up (`u`) dot products of row pair `r` against the activations `aa`.
|
||||
pub(super) fn gate_up_pair(blob: &[u8], r: usize, aa: &[&ActQ], g: &mut [f32], u: &mut [f32], oracle: bool) {
|
||||
row(
|
||||
&blob[(2 * r) * 640..(2 * r + 1) * 640],
|
||||
&blob[GU_SCALES + 2 * r * 80..GU_SCALES + (2 * r + 1) * 80],
|
||||
aa,
|
||||
g,
|
||||
oracle,
|
||||
);
|
||||
row(
|
||||
&blob[(2 * r + 1) * 640..(2 * r + 2) * 640],
|
||||
&blob[GU_SCALES + (2 * r + 1) * 80..GU_SCALES + (2 * r + 2) * 80],
|
||||
aa,
|
||||
u,
|
||||
oracle,
|
||||
);
|
||||
}
|
||||
/// Down-projection dot products of row `r` against the activations `aa`.
|
||||
pub(super) fn down_row(blob: &[u8], r: usize, aa: &[&ActQ], out: &mut [f32], oracle: bool) {
|
||||
row(
|
||||
&blob[D_CODES + r * 160..D_CODES + (r + 1) * 160],
|
||||
&blob[D_SCALES + r * 20..D_SCALES + (r + 1) * 20],
|
||||
aa,
|
||||
out,
|
||||
oracle,
|
||||
);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
//! Row slicing of the planar Q2 blob: where the codes and scales of one gate, up or down row live.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The activation leaves of `acts` in the first slots of an eight-slot array whose other slots point at `empty`.
|
||||
pub(super) fn activation_refs<'a>(
|
||||
acts: impl Iterator<Item = &'a PlanarActivation>,
|
||||
empty: &'a ActQ,
|
||||
) -> [&'a ActQ; MAX_ROWS] {
|
||||
let mut refs = [empty; MAX_ROWS];
|
||||
for (t, act) in acts.enumerate() {
|
||||
refs[t] = &act.0;
|
||||
}
|
||||
refs
|
||||
}
|
||||
/// Write `v[t]` as cell `r` of output `t`, for the first `v.len()` outputs.
|
||||
pub(super) fn store_cells(out: &mut [&mut [f32]], r: usize, v: &[f32]) {
|
||||
for (cells, x) in out.iter_mut().zip(v) {
|
||||
cells[r] = *x;
|
||||
}
|
||||
}
|
||||
/// Write `silu(g[t]) * u[t]` as cell `r` of output `t`, for the first `g.len()` outputs.
|
||||
pub(super) fn store_silu_cells(out: &mut [&mut [f32]], r: usize, g: &[f32], u: &[f32]) {
|
||||
for ((cells, g), u) in out.iter_mut().zip(g).zip(u) {
|
||||
cells[r] = silu(*g, *u);
|
||||
}
|
||||
}
|
||||
/// Gate row `r` (the even row of the interleaved gate/up pair) against `a`, written to `out`.
|
||||
pub(super) fn gate_row(blob: &[u8], r: usize, a: &[&ActQ], out: &mut [f32], oracle: bool) {
|
||||
let codes = &blob[(2 * r) * 640..(2 * r + 1) * 640];
|
||||
let scales = &blob[GU_SCALES + 2 * r * 80..GU_SCALES + (2 * r + 1) * 80];
|
||||
row(codes, scales, a, out, oracle);
|
||||
}
|
||||
/// Up row `r` (the odd row of the interleaved gate/up pair) against `a`, written to `out`.
|
||||
pub(super) fn up_row(blob: &[u8], r: usize, a: &[&ActQ], out: &mut [f32], oracle: bool) {
|
||||
let codes = &blob[(2 * r + 1) * 640..(2 * r + 2) * 640];
|
||||
let scales = &blob[GU_SCALES + (2 * r + 1) * 80..GU_SCALES + (2 * r + 2) * 80];
|
||||
row(codes, scales, a, out, oracle);
|
||||
}
|
||||
/// Down row `r` against `a`, written to `out`.
|
||||
pub(super) fn down_row(blob: &[u8], r: usize, a: &[&ActQ], out: &mut [f32], oracle: bool) {
|
||||
let codes = &blob[D_CODES + r * 160..D_CODES + (r + 1) * 160];
|
||||
let scales = &blob[D_SCALES + r * 20..D_SCALES + (r + 1) * 20];
|
||||
row(codes, scales, a, out, oracle);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Planar Q2 leaves: oracle switch, half conversion, CPU gate, activation quantizers and the row kernels.
|
||||
//! Moved out of the parent module by STRA-338: fn set_oracle_q8_zero, fn oracle_q8_zero_enabled, fn half, fn legacy_supported, impl Default_for_PlanarActivation, impl PlanarActivation ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -52,43 +52,37 @@ impl Default for PlanarActivation {
|
||||
Self(ActQ::default())
|
||||
}
|
||||
}
|
||||
/// The input checks both quantizers make first: a whole number of 32-value chunks within H, then the AVX2 gate.
|
||||
fn admit_input(x: &[f32]) -> Result<()> {
|
||||
if x.is_empty() || x.len() > H || x.len() % 32 != 0 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
impl PlanarActivation {
|
||||
pub fn quantize(&mut self, x: &[f32]) -> Result<()> {
|
||||
admit_input(x)?;
|
||||
if oracle_q8_zero_enabled() {
|
||||
self.quantize_oracle(x);
|
||||
return Ok(());
|
||||
if x.is_empty() || x.len() > H || x.len() % 32 != 0 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
if !legacy_supported() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
// SAFETY: legacy_supported() above proved AVX-512 F/DQ/BW/VL (+VNNI/VBMI, XCR0); x.len() <= H, % 32 == 0
|
||||
// (asserted by the leaf).
|
||||
unsafe {
|
||||
super::super::rust_quant::q8_one_avx512(x, &mut self.0);
|
||||
if oracle_q8_zero_enabled() {
|
||||
self.quantize_oracle(x);
|
||||
} else {
|
||||
if !legacy_supported() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
// SAFETY: legacy_supported() above proved AVX-512 F/DQ/BW/VL (+VNNI/VBMI, XCR0); x.len() <= H, % 32 == 0
|
||||
// (asserted by the leaf).
|
||||
unsafe {
|
||||
super::super::rust_quant::q8_one_avx512(x, &mut self.0);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The oracle activation: the Q8_0 blocks of `q8_zero`, widened to the planar layout (scale, code sum, product).
|
||||
/// The oracle activation: Q8_0 blocks expanded into the planar layout.
|
||||
fn quantize_oracle(&mut self, x: &[f32]) {
|
||||
let n = x.len() / 32;
|
||||
let mut q = [super::super::rust_types::Q8Zero::default(); 80];
|
||||
// SAFETY: avx2_ok() by the caller (AVX2+FMA+F16C); x.len() <= H and % 32 == 0 so x.len()/32 <= 80 = q.len().
|
||||
// SAFETY: the caller checked avx2_ok() (AVX2+FMA+F16C); x.len() <= H and % 32 == 0 so x.len()/32 <= 80.
|
||||
unsafe {
|
||||
super::super::rust_quant::q8_zero(x, &mut q[..n]);
|
||||
super::super::rust_quant::q8_zero(x, &mut q[..x.len() / 32]);
|
||||
}
|
||||
self.0.nchunks = n as i32;
|
||||
for (k, q) in q[..n].iter().enumerate() {
|
||||
self.0.nchunks = (x.len() / 32) as i32;
|
||||
for (k, q) in q[..x.len() / 32].iter().enumerate() {
|
||||
self.0.q[k * 32..k * 32 + 32].copy_from_slice(&q.qs);
|
||||
let d = half(&q.d.to_le_bytes());
|
||||
let s = q.qs.iter().map(|&v| v as i32).sum::<i32>();
|
||||
@@ -98,8 +92,12 @@ impl PlanarActivation {
|
||||
}
|
||||
}
|
||||
pub fn quantize_native(&mut self, x: &[f32]) -> Result<()> {
|
||||
admit_input(x)?;
|
||||
// SAFETY: avx2_ok() above; the avx512 arm additionally checks dq_ok() before its leaf.
|
||||
if x.is_empty() || x.len() > H || x.len() % 32 != 0 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
} /* SAFETY: avx2_ok() above; the avx512 arm additionally checks dq_ok() before its leaf. */
|
||||
unsafe {
|
||||
if super::super::rust_simd::dispatch().avx512 {
|
||||
if !super::super::rust_simd::dq_ok() {
|
||||
@@ -133,9 +131,13 @@ pub(super) unsafe fn unpack32(p: *const u8) -> __m256i {
|
||||
pub(super) unsafe fn dot32(p: *const u8, q: *const i8) -> __m256i {
|
||||
unsafe { _mm256_dpbusd_epi32(_mm256_setzero_si256(), unpack32(p), _mm256_loadu_si256(q.cast())) }
|
||||
}
|
||||
// The correction `corr += d*(hx0+hx1)` is ONE fused multiply-add, as in the pinned C++ (expert.cpp row_dot line 242 and
|
||||
// row_dot_multi line 294, GCC contracts it under -mfma); a separate mul+add rounds twice (STRA-329; the same rule as
|
||||
// rust_q2.rs, STRA-324).
|
||||
/// `dpbusd(0, w, q[..32])` as floats: one 32-weight half-block against 32 activation bytes.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
unsafe fn dot32_ps(w: __m256i, q: *const i8) -> __m256 {
|
||||
unsafe { _mm256_cvtepi32_ps(_mm256_dpbusd_epi32(_mm256_setzero_si256(), w, _mm256_loadu_si256(q.cast()))) }
|
||||
}
|
||||
// The correction `corr += d*(hx0+hx1)` is ONE fused multiply-add, as in the pinned C++ (expert.cpp row_dot line 242 and row_dot_multi line 294,
|
||||
// GCC contracts it under -mfma); a separate mul+add rounds twice (STRA-329; the same rule as rust_q2.rs, STRA-324).
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
pub(super) unsafe fn row256(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut [f32]) {
|
||||
unsafe {
|
||||
@@ -144,9 +146,15 @@ pub(super) unsafe fn row256(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut
|
||||
assert!(scales.len() / 2 <= 40 && codes.len() >= scales.len() / 2 * 16 && a.len() <= MAX_ROWS);
|
||||
for b in 0..scales.len() / 2 {
|
||||
let d = half(&scales[b * 2..]);
|
||||
let weights = (unpack32(codes.as_ptr().add(b * 16)), unpack32(codes.as_ptr().add(b * 16 + 8)));
|
||||
let lo = unpack32(codes.as_ptr().add(b * 16));
|
||||
let hi = unpack32(codes.as_ptr().add(b * 16 + 8));
|
||||
for t in 0..a.len() {
|
||||
(acc[t], corr[t]) = accumulate_block256(acc[t], corr[t], d, weights, a[t], b);
|
||||
let x = a[t];
|
||||
let sl = dot32_ps(lo, x.q.as_ptr().add(b * 64));
|
||||
let sh = dot32_ps(hi, x.q.as_ptr().add(b * 64 + 32));
|
||||
acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * x.scale[b * 2]), sl, acc[t]);
|
||||
acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * x.scale[b * 2 + 1]), sh, acc[t]);
|
||||
corr[t] = d.mul_add(x.hx[b * 2] + x.hx[b * 2 + 1], corr[t]);
|
||||
}
|
||||
}
|
||||
for t in 0..a.len() {
|
||||
@@ -154,31 +162,35 @@ pub(super) unsafe fn row256(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut
|
||||
}
|
||||
}
|
||||
}
|
||||
/// One token advanced by weight block `b` (scale `d`, the two unpacked 32-code halves): the two integer dots scaled
|
||||
/// into `acc`, and the fused correction chain `corr`.
|
||||
/// The `n` blocks from `b0` of one row against every token: `acc[t] += scale_lane * dpbusd(codes, token bytes)`.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn accumulate_block256(
|
||||
acc: __m256,
|
||||
corr: f32,
|
||||
d: f32,
|
||||
weights: (__m256i, __m256i),
|
||||
x: &ActQ,
|
||||
b: usize,
|
||||
) -> (__m256, f32) {
|
||||
// SAFETY: row256 asserted nb <= 40, so b < 40 and both 32-byte loads stay inside the 2560 of `x.q`.
|
||||
unsafe fn row512_blocks(
|
||||
codes: &[u8],
|
||||
a: &[&ActQ],
|
||||
b0: usize,
|
||||
n: usize,
|
||||
p: &[__m512; MAX_ROWS],
|
||||
acc: &mut [__m512; MAX_ROWS],
|
||||
) {
|
||||
unsafe {
|
||||
let q = x.q.as_ptr().add(b * 64);
|
||||
let sl =
|
||||
_mm256_cvtepi32_ps(_mm256_dpbusd_epi32(_mm256_setzero_si256(), weights.0, _mm256_loadu_si256(q.cast())));
|
||||
let sh = _mm256_cvtepi32_ps(_mm256_dpbusd_epi32(
|
||||
_mm256_setzero_si256(),
|
||||
weights.1,
|
||||
_mm256_loadu_si256(q.add(32).cast()),
|
||||
));
|
||||
let acc = _mm256_fmadd_ps(_mm256_set1_ps(d * x.scale[b * 2]), sl, acc);
|
||||
let acc = _mm256_fmadd_ps(_mm256_set1_ps(d * x.scale[b * 2 + 1]), sh, acc);
|
||||
(acc, d.mul_add(x.hx[b * 2] + x.hx[b * 2 + 1], corr))
|
||||
let base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
|
||||
for i in 0..n {
|
||||
let b = b0 + i;
|
||||
let q = _mm512_cvtepu16_epi64(_mm_loadu_si128(codes.as_ptr().add(b * 16).cast()));
|
||||
let q = _mm512_and_si512(
|
||||
_mm512_multishift_epi64_epi8(_mm512_set1_epi64(0x0e0c0a0806040200), q),
|
||||
_mm512_set1_epi8(3),
|
||||
);
|
||||
for t in 0..a.len() {
|
||||
let dot = _mm512_dpbusd_epi32(
|
||||
_mm512_setzero_si512(),
|
||||
q,
|
||||
_mm512_loadu_si512(a[t].q.as_ptr().add(b * 64).cast()),
|
||||
);
|
||||
let s = _mm512_permutexvar_ps(_mm512_add_epi32(base, _mm512_set1_epi32((2 * i) as i32)), p[t]);
|
||||
acc[t] = _mm512_fmadd_ps(s, _mm512_cvtepi32_ps(dot), acc[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
@@ -188,76 +200,26 @@ pub(super) unsafe fn row512(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut
|
||||
let mut corr = [_mm512_setzero_ps(); MAX_ROWS];
|
||||
let nb = scales.len() / 2;
|
||||
assert!(nb <= 40 && codes.len() >= nb * 16 && a.len() <= MAX_ROWS);
|
||||
let dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7);
|
||||
for b0 in (0..nb).step_by(8) {
|
||||
let n = (nb - b0).min(8);
|
||||
let (mask, dd) = group_scales512(scales, b0, n);
|
||||
let m8 = if n == 8 { 255 } else { (1u16 << n) - 1 } as u8;
|
||||
let m16 = if n == 8 { 65535 } else { (1u32 << (2 * n)) - 1 } as u16;
|
||||
let hs = _mm_maskz_loadu_epi16(m8, scales.as_ptr().add(b0 * 2).cast());
|
||||
let ds = _mm512_castps256_ps512(_mm256_cvtph_ps(hs));
|
||||
let dd = _mm512_maskz_mov_ps(m16, _mm512_permutexvar_ps(dup, ds));
|
||||
let mut p = [_mm512_setzero_ps(); MAX_ROWS];
|
||||
for t in 0..a.len() {
|
||||
(p[t], corr[t]) = token_scales512(dd, mask, a[t], b0, corr[t]);
|
||||
}
|
||||
for i in 0..n {
|
||||
let (q, idx) = (weights512(codes, b0 + i), block_index512(i));
|
||||
for t in 0..a.len() {
|
||||
acc[t] = accumulate_block512(acc[t], idx, p[t], q, a[t], b0 + i);
|
||||
}
|
||||
p[t] = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(m16, a[t].scale.as_ptr().add(b0 * 2)));
|
||||
corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a[t].hx.as_ptr().add(b0 * 2)), corr[t]);
|
||||
}
|
||||
row512_blocks(codes, a, b0, n, &p, &mut acc);
|
||||
}
|
||||
for t in 0..a.len() {
|
||||
out[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The FP16 weight scales of the `n` blocks from `b0` (at most 8), each in its two lanes, and the 16-lane mask.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn group_scales512(scales: &[u8], b0: usize, n: usize) -> (u16, __m512) {
|
||||
// SAFETY: row512 asserted nb <= 40; the masked load reads only the n scales (2 bytes each) from block b0.
|
||||
unsafe {
|
||||
let m8 = if n == 8 { 255 } else { (1u16 << n) - 1 } as u8;
|
||||
let m16 = if n == 8 { 65535 } else { (1u32 << (2 * n)) - 1 } as u16;
|
||||
let dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7);
|
||||
let hs = _mm_maskz_loadu_epi16(m8, scales.as_ptr().add(b0 * 2).cast());
|
||||
let ds = _mm512_castps256_ps512(_mm256_cvtph_ps(hs));
|
||||
(m16, _mm512_maskz_mov_ps(m16, _mm512_permutexvar_ps(dup, ds)))
|
||||
}
|
||||
}
|
||||
/// The per-token weight-scale products of one group (`dd * x.scale`) and the updated correction (`dd * x.hx`).
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn token_scales512(dd: __m512, mask: u16, x: &ActQ, b0: usize, corr: __m512) -> (__m512, __m512) {
|
||||
// SAFETY: masked loads read only the 2 * n scale/hx entries from 2 * b0 named by the mask, inside the 80 entries.
|
||||
unsafe {
|
||||
let p = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(mask, x.scale.as_ptr().add(b0 * 2)));
|
||||
(p, _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(mask, x.hx.as_ptr().add(b0 * 2)), corr))
|
||||
}
|
||||
}
|
||||
/// The 64 two-bit codes of block `b` as bytes 0..=3.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn weights512(codes: &[u8], b: usize) -> __m512i {
|
||||
// SAFETY: row512 asserted codes.len() >= nb * 16, so the 16-byte load of block b < nb is inside `codes`.
|
||||
unsafe {
|
||||
let q = _mm512_cvtepu16_epi64(_mm_loadu_si128(codes.as_ptr().add(b * 16).cast()));
|
||||
_mm512_and_si512(_mm512_multishift_epi64_epi8(_mm512_set1_epi64(0x0e0c0a0806040200), q), _mm512_set1_epi8(3))
|
||||
}
|
||||
}
|
||||
/// The lane selector that picks the two scale lanes of the `i`-th block of a group.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn block_index512(i: usize) -> __m512i {
|
||||
let base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
|
||||
_mm512_add_epi32(base, _mm512_set1_epi32((2 * i) as i32))
|
||||
}
|
||||
/// One token's accumulator advanced by block `b`: `acc + p[idx] * float(dot(codes, x.q[b*64..]))`.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn accumulate_block512(acc: __m512, idx: __m512i, p: __m512, q: __m512i, x: &ActQ, b: usize) -> __m512 {
|
||||
// SAFETY: row512 asserted nb <= 40, so b < 40 and the 64-byte load stays inside the 2560 of `x.q`.
|
||||
unsafe {
|
||||
let dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), q, _mm512_loadu_si512(x.q.as_ptr().add(b * 64).cast()));
|
||||
_mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p), _mm512_cvtepi32_ps(dot), acc)
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")]
|
||||
pub(super) unsafe fn row_oracle(codes: &[u8], scales: &[u8], a: &ActQ) -> f32 {
|
||||
unsafe {
|
||||
@@ -279,10 +241,9 @@ pub(super) unsafe fn row_oracle(codes: &[u8], scales: &[u8], a: &ActQ) -> f32 {
|
||||
}
|
||||
}
|
||||
pub(super) fn row(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut [f32], oracle: bool) {
|
||||
// SAFETY: private; every caller (gate_row, up_row, down_row of gate_up_rows, down_rows, expert_quantized,
|
||||
// whole_single, gate_each, down_each) first passed legacy_supported() -- directly or via ExpertPool::run, run_split
|
||||
// and run_split_multi -- and hands 640 B/80 B (gate/up) or 160 B/20 B (down) code/scale slices, i.e. nb <= 40
|
||||
// (asserted in the leaves).
|
||||
// SAFETY: private; every caller (gate_up_rows, down_rows, expert_quantized, whole_single, gate_each, down_each)
|
||||
// first passed legacy_supported() -- directly or via ExpertPool::run, run_split and run_split_multi -- and hands
|
||||
// 640 B/80 B (gate/up) or 160 B/20 B (down) code/scale slices, i.e. nb <= 40 (asserted in the leaves).
|
||||
unsafe {
|
||||
if oracle {
|
||||
for t in 0..a.len() {
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
use super::*;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
// The AVX-512 row leaves load a.q / a.scale / a.hx for every 8-byte-code block pair of the row: more than 40 blocks
|
||||
// would read past the ActQ, so the leaves refuse it before the first load (the exact-fit 640 B / 80 B row still runs).
|
||||
// The AVX-512 row leaves load a.q / a.scale / a.hx for every 8-byte-code block pair of the row: more than 40 blocks would read
|
||||
// past the ActQ, so the leaves refuse it before the first load (the exact-fit 640 B / 80 B row still runs).
|
||||
#[test]
|
||||
fn leaf_rows_longer_than_the_activation_are_refused() {
|
||||
if !legacy_supported() {
|
||||
@@ -26,46 +26,8 @@ fn leaf_rows_longer_than_the_activation_are_refused() {
|
||||
}
|
||||
}
|
||||
|
||||
fn xorshift(s: &mut u64) -> u64 {
|
||||
*s ^= *s << 13;
|
||||
*s ^= *s >> 7;
|
||||
*s ^= *s << 17;
|
||||
*s
|
||||
}
|
||||
/// One round of the correction fixture: 40 random code blocks, finite FP16 scales, and an activation that carries only
|
||||
/// `hx` (scaled by the round), so the integer dots vanish.
|
||||
fn correction_case(round: usize, seed: &mut u64) -> (Vec<u8>, Vec<u8>, ActQ) {
|
||||
let nb = 40usize;
|
||||
let mut scales = vec![0u8; nb * 2];
|
||||
let mut a = ActQ::default();
|
||||
let mut codes = vec![0u8; nb * 16];
|
||||
for v in codes.iter_mut() {
|
||||
*v = xorshift(seed) as u8;
|
||||
}
|
||||
for b in 0..nb {
|
||||
let e = 10 + (xorshift(seed) % 6) as u16;
|
||||
let m = (xorshift(seed) & 0x3ff) as u16;
|
||||
scales[b * 2..b * 2 + 2].copy_from_slice(&((e << 10) | m).to_le_bytes());
|
||||
for h in 0..2 {
|
||||
a.hx[b * 2 + h] = ((xorshift(seed) % 2_000_001) as f32 - 1_000_000.0) * (0.001 + 0.37 * round as f32);
|
||||
}
|
||||
}
|
||||
(codes, scales, a)
|
||||
}
|
||||
/// The scalar model of the correction chain `corr += d * (hx0 + hx1)`: fused, and as a separate multiply and add.
|
||||
fn correction_chains(scales: &[u8], a: &ActQ) -> (f32, f32) {
|
||||
let (mut fused, mut unfused) = (0.0f32, 0.0f32);
|
||||
for b in 0..scales.len() / 2 {
|
||||
let d = half(&scales[b * 2..]);
|
||||
let s = a.hx[b * 2] + a.hx[b * 2 + 1];
|
||||
fused = d.mul_add(s, fused);
|
||||
unfused += d * s;
|
||||
}
|
||||
(fused, unfused)
|
||||
}
|
||||
// STRA-329: row256 (STRATA_CPU_YMM=1 on an AVX-512 CPU) fuses the weight-scale times activation-sum correction like
|
||||
// expert.cpp:242/:294. With an all-zero activation the integer dots vanish, so the result is exactly -corr and the
|
||||
// scalar model below is the whole kernel.
|
||||
// STRA-329: row256 (STRATA_CPU_YMM=1 on an AVX-512 CPU) fuses the weight-scale times activation-sum correction like expert.cpp:242/:294.
|
||||
// With an all-zero activation the integer dots vanish, so the result is exactly -corr and the scalar model below is the whole kernel.
|
||||
#[test]
|
||||
fn row256_correction_is_one_fused_multiply_add() {
|
||||
if !legacy_supported() {
|
||||
@@ -73,17 +35,44 @@ fn row256_correction_is_one_fused_multiply_add() {
|
||||
return;
|
||||
}
|
||||
let mut seed = 0x0329_5eed_1234_abcdu64;
|
||||
let mut next = || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
let mut differed = 0;
|
||||
for round in 0..8 {
|
||||
let (codes, scales, a) = correction_case(round, &mut seed);
|
||||
let (fused, unfused) = correction_chains(&scales, &a);
|
||||
let mut out = [0.0f32];
|
||||
// SAFETY: legacy_supported() above; 40 blocks of 16 code bytes / 2 scale bytes, the ActQ holds 80 chunks.
|
||||
let nb = 40usize;
|
||||
let mut scales = vec![0u8; nb * 2];
|
||||
let mut a = ActQ::default();
|
||||
let mut codes = vec![0u8; nb * 16];
|
||||
for v in codes.iter_mut() {
|
||||
*v = next() as u8;
|
||||
}
|
||||
for b in 0..nb {
|
||||
let e = 10 + (next() % 6) as u16;
|
||||
let m = (next() & 0x3ff) as u16;
|
||||
scales[b * 2..b * 2 + 2].copy_from_slice(&((e << 10) | m).to_le_bytes());
|
||||
for h in 0..2 {
|
||||
a.hx[b * 2 + h] = ((next() % 2_000_001) as f32 - 1_000_000.0) * (0.001 + 0.37 * round as f32);
|
||||
}
|
||||
}
|
||||
let (mut fused, mut unfused) = (0.0f32, 0.0f32);
|
||||
for b in 0..nb {
|
||||
let d = half(&scales[b * 2..]);
|
||||
let s = a.hx[b * 2] + a.hx[b * 2 + 1];
|
||||
fused = d.mul_add(s, fused);
|
||||
unfused += d * s;
|
||||
}
|
||||
let mut out = [0.0f32]; /* SAFETY: legacy_supported() above; 40 blocks of 16 code bytes / 2 scale bytes, the ActQ holds 80 chunks. */
|
||||
unsafe {
|
||||
row256(&codes, &scales, &[&a], &mut out);
|
||||
}
|
||||
assert_eq!(out[0].to_bits(), (-fused).to_bits(), "round {round}: -corr must be the fused chain");
|
||||
differed += (fused.to_bits() != unfused.to_bits()) as usize;
|
||||
if fused.to_bits() != unfused.to_bits() {
|
||||
differed += 1;
|
||||
}
|
||||
}
|
||||
assert!(differed > 0, "the fixture must separate the fused and the unfused chain, or the test proves nothing");
|
||||
}
|
||||
|
||||
@@ -37,47 +37,30 @@ pub fn quantize_row_ref(kind: Kind, x: &[f32], y: &mut [u8]) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Whether the chunk start, row width and imatrix of a `quantize_chunk` call are consistent with the format.
|
||||
fn chunk_arguments_ok(kind: Kind, start: usize, n_per_row: usize, imatrix: Option<&[f32]>) -> bool {
|
||||
!(n_per_row == 0
|
||||
/// Argument shapes of a chunk quantization: a row length, a row-aligned block-aligned start, a matching importance
|
||||
/// matrix where the kind needs one.
|
||||
fn check_chunk_args(kind: Kind, start: usize, n_per_row: usize, imatrix: Option<&[f32]>) -> Result<()> {
|
||||
if n_per_row == 0
|
||||
|| start % kind.block().0 != 0
|
||||
|| start % n_per_row != 0
|
||||
|| imatrix.is_some_and(|w| w.len() != n_per_row)
|
||||
|| requires_imatrix(kind) && imatrix.is_none())
|
||||
|| requires_imatrix(kind) && imatrix.is_none()
|
||||
{
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The element end, the output byte range and the row size of a chunk.
|
||||
struct ChunkSpan {
|
||||
end: usize,
|
||||
at: usize,
|
||||
outend: usize,
|
||||
/// Source end, destination start and end, and the byte count of `nrows` rows of `n_per_row` weights from `start`.
|
||||
fn chunk_extents(
|
||||
(start, nrows, n_per_row): (usize, usize, usize),
|
||||
rowbytes: usize,
|
||||
bytes: usize,
|
||||
}
|
||||
fn chunk_span(kind: Kind, start: usize, nrows: usize, n_per_row: usize) -> Result<ChunkSpan> {
|
||||
let rowbytes = kind.row_bytes(n_per_row)?;
|
||||
) -> Result<(usize, usize, usize, usize)> {
|
||||
let n = nrows.checked_mul(n_per_row).ok_or(Error::Shape)?;
|
||||
let end = start.checked_add(n).ok_or(Error::Shape)?;
|
||||
let at = (start / n_per_row).checked_mul(rowbytes).ok_or(Error::Shape)?;
|
||||
let bytes = nrows.checked_mul(rowbytes).ok_or(Error::Shape)?;
|
||||
let outend = at.checked_add(bytes).ok_or(Error::Shape)?;
|
||||
Ok(ChunkSpan { end, at, outend, rowbytes, bytes })
|
||||
}
|
||||
fn inputs_finite(x: &[f32], imatrix: Option<&[f32]>) -> bool {
|
||||
!(x.iter().any(|x| !x.is_finite()) || imatrix.is_some_and(|w| w.iter().any(|x| !x.is_finite() || *x < 0.0)))
|
||||
}
|
||||
fn quantize_rows(
|
||||
kind: Kind,
|
||||
src: &[f32],
|
||||
dst: &mut [u8],
|
||||
(n_per_row, rowbytes): (usize, usize),
|
||||
imatrix: Option<&[f32]>,
|
||||
) -> Result<()> {
|
||||
for (x, y) in src.chunks_exact(n_per_row).zip(dst.chunks_exact_mut(rowbytes)) {
|
||||
if !super::rust_weight_quant::row_without_iq(kind, x, y, imatrix, false)? {
|
||||
super::rust_weight_iq::row(kind, x, y, imatrix)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok((end, at, outend, bytes))
|
||||
}
|
||||
pub fn quantize_chunk(
|
||||
kind: Kind,
|
||||
@@ -88,18 +71,30 @@ pub fn quantize_chunk(
|
||||
n_per_row: usize,
|
||||
imatrix: Option<&[f32]>,
|
||||
) -> Result<usize> {
|
||||
if !chunk_arguments_ok(kind, start, n_per_row, imatrix) {
|
||||
check_chunk_args(kind, start, n_per_row, imatrix)?;
|
||||
let rowbytes = kind.row_bytes(n_per_row)?;
|
||||
let (end, at, outend, bytes) = chunk_extents((start, nrows, n_per_row), rowbytes)?;
|
||||
if end > src.len() || outend > dst.len() {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let span = chunk_span(kind, start, nrows, n_per_row)?;
|
||||
if span.end > src.len() || span.outend > dst.len() {
|
||||
return Err(Error::Shape);
|
||||
check_chunk_finite(&src[start..end], imatrix)?;
|
||||
quantize_init(kind)?;
|
||||
for (x, y) in src[start..end].chunks_exact(n_per_row).zip(dst[at..outend].chunks_exact_mut(rowbytes)) {
|
||||
quantize_row_chunk(kind, x, y, imatrix)?;
|
||||
}
|
||||
if !inputs_finite(&src[start..span.end], imatrix) {
|
||||
Ok(bytes)
|
||||
}
|
||||
/// Source weights finite; importance weights finite and non-negative.
|
||||
fn check_chunk_finite(src: &[f32], imatrix: Option<&[f32]>) -> Result<()> {
|
||||
if src.iter().any(|x| !x.is_finite()) || imatrix.is_some_and(|w| w.iter().any(|x| !x.is_finite() || *x < 0.0)) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
quantize_init(kind)?;
|
||||
let rows = (n_per_row, span.rowbytes);
|
||||
quantize_rows(kind, &src[start..span.end], &mut dst[span.at..span.outend], rows, imatrix)?;
|
||||
Ok(span.bytes)
|
||||
Ok(())
|
||||
}
|
||||
/// One row of a chunk: the non-IQ quantizers first, the IQ family when they decline the kind.
|
||||
fn quantize_row_chunk(kind: Kind, x: &[f32], y: &mut [u8], imatrix: Option<&[f32]>) -> Result<()> {
|
||||
if !super::rust_weight_quant::row_without_iq(kind, x, y, imatrix, false)? {
|
||||
super::rust_weight_iq::row(kind, x, y, imatrix)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -4,11 +4,10 @@ use super::rust_ggml::{Kind, NativeFormat};
|
||||
use super::rust_kq::Q8One;
|
||||
use super::rust_types::{Q8K, Q8Zero};
|
||||
use super::{Error, Result};
|
||||
// Bounds: NativeActivation is `repr(C, align(64))` with `bytes` at offset 0, so the Q8K/Q8Zero/Q8One/u16/f32 views of
|
||||
// `raw()` are aligned; quantize() guarantees activation_bytes(n) <= BYTES and check(kind, n) pins `self.n == n` and
|
||||
// the encoding class, so every `from_raw_parts(.., n/block)` stays inside the array. Weight extents come from
|
||||
// NativeFormat::validate() (recomputed geometry) plus `blob.len() == f.bytes`, `r1 <= rows`, and
|
||||
// `out[t].len() == rows`. Gate: avx2_ok().
|
||||
// Bounds: NativeActivation is `repr(C, align(64))` with `bytes` at offset 0, so the Q8K/Q8Zero/Q8One/u16/f32 views of `raw()`
|
||||
// are aligned; quantize() guarantees activation_bytes(n) <= BYTES and check(kind, n) pins `self.n == n` and the encoding
|
||||
// class, so every `from_raw_parts(.., n/block)` stays inside the array. Weight extents come from NativeFormat::validate()
|
||||
// (recomputed geometry) plus `blob.len() == f.bytes`, `r1 <= rows`, and `out[t].len() == rows`. Gate: avx2_ok().
|
||||
#[repr(C, align(64))]
|
||||
pub struct NativeActivation<const BYTES: usize = 4096> {
|
||||
bytes: [u8; BYTES],
|
||||
@@ -19,17 +18,6 @@ pub struct NativeActivation<const BYTES: usize = 4096> {
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
mod admission;
|
||||
#[allow(unused_imports)]
|
||||
use admission::{
|
||||
admit_activations, batch_shaped, down_shaped, gu_shaped, iq512_lacks_dq, q2_shaped, require_avx2, require_iq_cpu,
|
||||
require_q2_cpu, rows_fit,
|
||||
};
|
||||
mod typed_dots;
|
||||
#[allow(unused_imports)]
|
||||
use typed_dots::{
|
||||
dot_iq, dot_kq, gate_bytes, raw_views, store_column, store_silu_column, typed_blocks, typed_blocks_of, up_bytes,
|
||||
};
|
||||
mod impl_default_for_nativeactivation;
|
||||
#[allow(unused_imports)]
|
||||
pub(super) use impl_default_for_nativeactivation::group_dot;
|
||||
@@ -52,6 +40,8 @@ pub use group_dot_bytes_policy_fn::iq_gu_rows;
|
||||
pub use group_dot_bytes_policy_fn::iq_rows;
|
||||
#[allow(unused_imports)]
|
||||
pub use group_dot_bytes_policy_fn::kq_rows;
|
||||
#[allow(unused_imports)]
|
||||
use group_dot_bytes_policy_fn::{check_gu, check_rows, check_weights, kq_dot, store, typed};
|
||||
mod iq4nl_rows_fn;
|
||||
#[allow(unused_imports)]
|
||||
pub use iq4nl_rows_fn::cpu_avx2_ok;
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
//! Request admission of the native row entries: shape predicates and CPU capability gates.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// True when `n_act` activations (1..=i32::MAX) pair with `n_out` outputs and `r0..r1` is an ordered row range.
|
||||
pub(super) fn batch_shaped(n_act: usize, n_out: usize, r0: usize, r1: usize) -> bool {
|
||||
n_act != 0 && n_act <= i32::MAX as usize && n_act == n_out && r0 <= r1
|
||||
}
|
||||
/// True when the blob is whole rows of `stride` bytes, `r1` is inside them and every output holds one cell per row.
|
||||
pub(super) fn rows_fit(blob_len: usize, stride: usize, r1: usize, out: &[&mut [f32]]) -> bool {
|
||||
blob_len % stride == 0 && r1 <= blob_len / stride && out.iter().all(|o| o.len() == blob_len / stride)
|
||||
}
|
||||
/// True when a gate/up request matches the validated format `f`: blob size, batch, rows and `n_ff` cells per output.
|
||||
pub(super) fn gu_shaped(f: &NativeFormat, blob: &[u8], n_act: usize, out: &[&mut [f32]], r0: usize, r1: usize) -> bool {
|
||||
blob.len() == f.bytes
|
||||
&& batch_shaped(n_act, out.len(), r0, r1)
|
||||
&& r1 <= f.n_ff
|
||||
&& out.iter().all(|v| v.len() == f.n_ff)
|
||||
}
|
||||
/// True when a down request matches the validated format `f`: blob size, batch, rows and `n_embd` cells per output.
|
||||
pub(super) fn down_shaped(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
n_act: usize,
|
||||
out: &[&mut [f32]],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
) -> bool {
|
||||
blob.len() == f.bytes
|
||||
&& batch_shaped(n_act, out.len(), r0, r1)
|
||||
&& r1 <= f.n_embd
|
||||
&& out.iter().all(|v| v.len() == f.n_embd)
|
||||
}
|
||||
/// True when a Q2_0 request has a width within H, at most eight activations and an ordered row range.
|
||||
pub(super) fn q2_shaped(width: usize, n_act: usize, n_out: usize, r0: usize, r1: usize) -> bool {
|
||||
width != 0 && width <= super::super::H && n_act != 0 && n_act <= 8 && n_act == n_out && r0 <= r1
|
||||
}
|
||||
/// Every activation was quantized for `kind` at width `n`.
|
||||
pub(super) fn admit_activations<const BYTES: usize>(
|
||||
act: &[&NativeActivation<BYTES>],
|
||||
kind: Kind,
|
||||
n: usize,
|
||||
) -> Result<()> {
|
||||
for a in act {
|
||||
a.check(kind, n)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The AVX2 gate of every native row entry.
|
||||
pub(super) fn require_avx2() -> Result<()> {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The gate of the explicit IQ entries: AVX2, and for the 512-bit kernels AVX-512 with DQ.
|
||||
pub(super) fn require_iq_cpu(avx512: bool) -> Result<()> {
|
||||
let lacks_512 = || !super::super::rust_simd::avx512_ok() || !super::super::rust_simd::dq_ok();
|
||||
if !super::super::rust_simd::avx2_ok() || avx512 && lacks_512() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The gate of the Q2_0 entry: AVX2, and DQ when the CPU runs the AVX-512 tree.
|
||||
pub(super) fn require_q2_cpu() -> Result<()> {
|
||||
if !super::super::rust_simd::avx2_ok() || super::super::rust_simd::avx512_ok() && !super::super::rust_simd::dq_ok()
|
||||
{
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// True when the dispatch would pick the 512-bit IQ gate/up kernel for this batch on a CPU without DQ.
|
||||
pub(super) fn iq512_lacks_dq(kind: Kind, n_act: usize, d: &super::super::rust_simd::Dispatch) -> bool {
|
||||
d.iq512
|
||||
&& (n_act as i32) >= d.mt_min
|
||||
&& matches!(kind.original_id(), 16 | 17 | 18 | 21 | 22)
|
||||
&& !super::super::rust_simd::dq_ok()
|
||||
}
|
||||
@@ -1,32 +1,69 @@
|
||||
//! Env-selected grouped dot of one weight row, and the explicit KQ256 / IQ256 / IQ512 benchmark row entries.
|
||||
//! Moved out of the parent module by STRA-338: fn group_dot_bytes_policy, fn kq_rows, fn iq_rows, fn iq_gu_rows.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// `STRATA_KQ256`, read once.
|
||||
/// Reinterpret the raw bytes of up to eight activations as `blocks` blocks of `T` each.
|
||||
///
|
||||
/// # Safety
|
||||
/// Every activation holds at least `blocks` initialized, suitably aligned blocks of `T` (module header).
|
||||
pub(super) unsafe fn typed_bytes<'a, T>(act: &[&'a [u8]], blocks: usize) -> [&'a [T]; 8] {
|
||||
let mut a: [&[T]; 8] = [&[]; 8];
|
||||
for t in 0..act.len() {
|
||||
a[t] = unsafe { std::slice::from_raw_parts(act[t].as_ptr().cast(), blocks) };
|
||||
}
|
||||
a
|
||||
}
|
||||
/// `typed_bytes` over native activations.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `typed_bytes`; `check(kind, n)` pinned the activations' encoding class and length.
|
||||
pub(super) unsafe fn typed<'a, T, const BYTES: usize>(
|
||||
act: &[&'a NativeActivation<BYTES>],
|
||||
blocks: usize,
|
||||
) -> [&'a [T]; 8] {
|
||||
let mut a: [&[T]; 8] = [&[]; 8];
|
||||
for t in 0..act.len() {
|
||||
a[t] = unsafe { std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), blocks) };
|
||||
}
|
||||
a
|
||||
}
|
||||
/// One row of a Q4_K / Q5 one-block / Q8 zero-block kind against up to eight native activations.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok(); `check(kind, width)` pinned every activation; `row` is one whole encoded row of `width` weights.
|
||||
pub(super) unsafe fn kq_dot(kind: Kind, row: &[u8], act: &[&NativeActivation], width: usize, out: &mut [f32]) {
|
||||
unsafe {
|
||||
let n = act.len();
|
||||
match kind {
|
||||
Kind::Q4K => super::super::rust_kq::q4_k_dot(row, &typed::<Q8K, 4096>(act, width / 256)[..n], out),
|
||||
Kind::Q5One => super::super::rust_kq::q5_one_dot(row, &typed::<Q8One, 4096>(act, width / 32)[..n], out),
|
||||
Kind::Q8Zero => super::super::rust_kq::q8_zero_dot(row, &typed::<Q8Zero, 4096>(act, width / 32)[..n], out),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `STRATA_KQ256`: route multi-token Q4_K / Q5 / Q8 rows through the 256-bit kq kernels.
|
||||
fn kq256_enabled() -> bool {
|
||||
static KQ: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*KQ.get_or_init(|| std::env::var("STRATA_KQ256").ok().is_some_and(|s| super::super::rust_simd::atoi(&s) != 0))
|
||||
}
|
||||
/// True when the KQ256 kernel serves Original type `k` of a gate/up (`gu`) or down row at this policy batch size.
|
||||
fn kq256_serves(k: i32, gu: bool, policy_nt: usize) -> bool {
|
||||
policy_nt >= 2 && ((gu && k == 12) || (!gu && matches!(k, 7 | 8)))
|
||||
/// The kq kernel a multi-token row of original kind `k` takes under the env policy (gate/up Q4_K, down Q5/Q8).
|
||||
fn kq_route(k: i32, gu: bool, policy_nt: usize) -> bool {
|
||||
kq256_enabled() && policy_nt >= 2 && ((gu && k == 12) || (!gu && matches!(k, 7 | 8)))
|
||||
}
|
||||
/// The multi-token IQ kernel (256-bit, or 512-bit when `wide`) of type `k` on Q8K activations.
|
||||
unsafe fn dot_iq_multi(wide: bool, k: i32, row: &[u8], n: usize, act: &[&[u8]], out: &mut [f32]) {
|
||||
// SAFETY: the callers' contract: avx2_ok() (and avx512_ok()+dq_ok() when `wide`), Q8K activations of n / 256
|
||||
// blocks.
|
||||
/// The kq dot of one row against `act` byte activations of `n` weights (kinds 12, 7, 8).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `group_dot_bytes_policy`.
|
||||
unsafe fn kq_bytes_dot(k: i32, row: &[u8], n: usize, act: &[&[u8]], out: &mut [f32]) {
|
||||
unsafe {
|
||||
let a = typed_blocks::<Q8K>(act, n / 256);
|
||||
dot_iq(wide, k, row, &a[..act.len()], out);
|
||||
}
|
||||
}
|
||||
/// The multi-token IQ4_NL kernel on Q8_0 activations of `n / 32` blocks.
|
||||
unsafe fn dot_iq4nl_multi(row: &[u8], n: usize, act: &[&[u8]], out: &mut [f32]) {
|
||||
// SAFETY: the callers' contract: avx2_ok(), Q8_0 activations of n / 32 blocks.
|
||||
unsafe {
|
||||
let a = typed_blocks::<Q8Zero>(act, n / 32);
|
||||
super::super::rust_iq::iq4nl(row, &a[..act.len()], out, false);
|
||||
let nt = act.len();
|
||||
match k {
|
||||
12 => super::super::rust_kq::q4_k_dot(row, &typed_bytes::<Q8K>(act, n / 256)[..nt], out),
|
||||
7 => super::super::rust_kq::q5_one_dot(row, &typed_bytes::<Q8One>(act, n / 32)[..nt], out),
|
||||
_ => super::super::rust_kq::q8_zero_dot(row, &typed_bytes::<Q8Zero>(act, n / 32)[..nt], out),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) unsafe fn group_dot_bytes_policy(
|
||||
@@ -40,21 +77,72 @@ pub(super) unsafe fn group_dot_bytes_policy(
|
||||
policy_nt: usize,
|
||||
) {
|
||||
unsafe {
|
||||
let nt = act.len();
|
||||
let k = kind.original_id();
|
||||
if kq256_enabled() && kq256_serves(k, gu, policy_nt) {
|
||||
return dot_kq(kind, row, n, act, out);
|
||||
if kq_route(k, gu, policy_nt) {
|
||||
kq_bytes_dot(k, row, n, act, out);
|
||||
return;
|
||||
}
|
||||
if gu && let Some(wide) = gu_multi_route(k, policy_nt as i32, d) {
|
||||
return dot_iq_multi(wide, k, row, n, act, out);
|
||||
iq_multi(wide, k, row, &typed_bytes::<Q8K>(act, n / 256)[..nt], out);
|
||||
return;
|
||||
}
|
||||
if !gu && (policy_nt as i32) >= d.mt_min && k == 20 && d.iq4nl {
|
||||
return dot_iq4nl_multi(row, n, act, out);
|
||||
super::super::rust_iq::iq4nl(row, &typed_bytes::<Q8Zero>(act, n / 32)[..nt], out, false);
|
||||
return;
|
||||
}
|
||||
for t in 0..act.len() {
|
||||
for t in 0..nt {
|
||||
out[t] = super::super::rust_ggml::dot_raw(kind, row, n, act[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Shape checks shared by the explicit row APIs: positive count within `i32`, one output per activation, `r0 <= r1`.
|
||||
pub(super) fn check_rows(act: usize, out: usize, r0: usize, r1: usize) -> Result<()> {
|
||||
if act == 0 || act > i32::MAX as usize || act != out || r0 > r1 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Row stride of `kind` at `width`, and the extent checks of a weights buffer holding whole rows with outputs per row.
|
||||
pub(super) fn check_weights(kind: Kind, width: usize, weights: &[u8], out: &[&mut [f32]], r1: usize) -> Result<usize> {
|
||||
let stride = kind.row_bytes(width)?;
|
||||
if stride == 0
|
||||
|| weights.len() % stride != 0
|
||||
|| r1 > weights.len() / stride
|
||||
|| out.iter().any(|o| o.len() != weights.len() / stride)
|
||||
{
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok(stride)
|
||||
}
|
||||
/// Store the `v.len()` row results of the chunk starting at token `base` into `out[token][r]`.
|
||||
pub(super) fn store(out: &mut [&mut [f32]], base: usize, r: usize, v: &[f32]) {
|
||||
for (t, x) in v.iter().enumerate() {
|
||||
out[base + t][r] = *x;
|
||||
}
|
||||
}
|
||||
/// Admission of the explicit kq256 row API (shapes, activations, CPU); returns the row stride.
|
||||
fn admit_kq(
|
||||
kind: Kind,
|
||||
weights: &[u8],
|
||||
width: usize,
|
||||
act: &[&NativeActivation],
|
||||
out: &[&mut [f32]],
|
||||
(r0, r1): (usize, usize),
|
||||
) -> Result<usize> {
|
||||
if !matches!(kind, Kind::Q4K | Kind::Q5One | Kind::Q8Zero) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
check_rows(act.len(), out.len(), r0, r1)?;
|
||||
let stride = check_weights(kind, width, weights, out, r1)?;
|
||||
for a in act {
|
||||
a.check(kind, width)?;
|
||||
}
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(stride)
|
||||
}
|
||||
/// The explicit Original kq256 benchmark API is independent of its env policy.
|
||||
pub fn kq_rows(
|
||||
kind: Kind,
|
||||
@@ -65,55 +153,62 @@ pub fn kq_rows(
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
) -> Result<()> {
|
||||
if !kq_supported(kind) || !batch_shaped(act.len(), out.len(), r0, r1) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let stride = kind.row_bytes(width)?;
|
||||
if stride == 0 || !rows_fit(weights.len(), stride, r1, out) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
admit_activations(act, kind, width)?;
|
||||
require_avx2()?;
|
||||
// SAFETY: module header; avx2_ok() checked above, check(kind,width) pinned every activation, row extents are
|
||||
// r*stride slices.
|
||||
unsafe {
|
||||
let job = RowsJob { kind, weights, width, stride, r0, r1, avx512: false };
|
||||
fill_kq_rows(&job, act, out);
|
||||
let stride = admit_kq(kind, weights, width, act, out, (r0, r1))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
for r in r0..r1 {
|
||||
let mut v = [0.0; 8];
|
||||
// SAFETY: module header; avx2_ok() checked in admit_kq, check(kind,width) pinned every activation, row
|
||||
// extents are r*stride slices.
|
||||
unsafe { kq_dot(kind, &weights[r * stride..(r + 1) * stride], act, width, &mut v[..act.len()]) };
|
||||
store(out, base, r, &v[..act.len()]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The weight rows and range of an explicit single-format row entry.
|
||||
struct RowsJob<'a> {
|
||||
kind: Kind,
|
||||
weights: &'a [u8],
|
||||
width: usize,
|
||||
stride: usize,
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
avx512: bool,
|
||||
}
|
||||
impl RowsJob<'_> {
|
||||
fn row(&self, r: usize) -> &[u8] {
|
||||
&self.weights[r * self.stride..(r + 1) * self.stride]
|
||||
|
||||
/// The CPU gates of the explicit IQ256/IQ512 entries: AVX2, and AVX-512 F/DQ when `avx512` is requested.
|
||||
pub(super) fn check_iq_cpu(avx512: bool) -> Result<()> {
|
||||
if !super::super::rust_simd::avx2_ok()
|
||||
|| avx512 && (!super::super::rust_simd::avx512_ok() || !super::super::rust_simd::dq_ok())
|
||||
{
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Rows `r0..r1` of the KQ256 format against every activation, eight activations at a time, into `out`.
|
||||
/// One IQ row against up to eight Q8K activations with the 512-bit or the 256-bit multi-token kernel.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok() holds, every activation was checked for (`kind`, `width`), `weights` holds whole rows of `stride` bytes.
|
||||
unsafe fn fill_kq_rows(job: &RowsJob, act: &[&NativeActivation], out: &mut [&mut [f32]]) {
|
||||
/// The matching CPU gate (`check_iq_cpu`) passed; `row` is one whole encoded row of kind `id`.
|
||||
pub(super) unsafe fn iq_multi(avx512: bool, id: i32, row: &[u8], a: &[&[Q8K]], out: &mut [f32]) {
|
||||
unsafe {
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
let raw = raw_views(act);
|
||||
for r in job.r0..job.r1 {
|
||||
let mut v = [0.0; 8];
|
||||
dot_kq(job.kind, job.row(r), job.width, &raw[..act.len()], &mut v[..act.len()]);
|
||||
store_column(out, base, r, &v[..act.len()]);
|
||||
}
|
||||
if avx512 {
|
||||
super::super::rust_iq::dot_multi512(id, row, a, out);
|
||||
} else {
|
||||
super::super::rust_iq::dot_multi256(id, row, a, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Admission of the explicit IQ256/IQ512 row API (shapes, activations, CPU); returns the row stride.
|
||||
fn admit_iq(
|
||||
kind: Kind,
|
||||
weights: &[u8],
|
||||
width: usize,
|
||||
act: &[&NativeActivation],
|
||||
out: &[&mut [f32]],
|
||||
(r0, r1, avx512): (usize, usize, bool),
|
||||
) -> Result<usize> {
|
||||
if !matches!(kind.original_id(), 16 | 17 | 18 | 21 | 22) || width == 0 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
check_rows(act.len(), out.len(), r0, r1)?;
|
||||
let stride = check_weights(kind, width, weights, out, r1)?;
|
||||
for a in act {
|
||||
a.check(kind, width)?;
|
||||
}
|
||||
check_iq_cpu(avx512)?;
|
||||
Ok(stride)
|
||||
}
|
||||
/// Explicit Original IQ256/IQ512 benchmark entry, independent of MT/env policy.
|
||||
pub fn iq_rows(
|
||||
kind: Kind,
|
||||
@@ -125,39 +220,74 @@ pub fn iq_rows(
|
||||
r1: usize,
|
||||
avx512: bool,
|
||||
) -> Result<()> {
|
||||
if !iq_supported(kind) || width == 0 || !batch_shaped(act.len(), out.len(), r0, r1) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let stride = kind.row_bytes(width)?;
|
||||
if !rows_fit(weights.len(), stride, r1, out) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
admit_activations(act, kind, width)?;
|
||||
require_iq_cpu(avx512)?;
|
||||
// SAFETY: module header; avx2_ok() (and avx512_ok()+dq_ok() when `avx512`) checked above; width % 256 == 0 via
|
||||
// row_bytes().
|
||||
unsafe {
|
||||
let job = RowsJob { kind, weights, width, stride, r0, r1, avx512 };
|
||||
fill_iq_rows(&job, act, out);
|
||||
let stride = admit_iq(kind, weights, width, act, out, (r0, r1, avx512))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
// SAFETY: module header; avx2_ok() (and avx512_ok()+dq_ok() when `avx512`) checked in admit_iq; width % 256
|
||||
// == 0 via row_bytes().
|
||||
let a = unsafe { typed::<Q8K, 4096>(act, width / 256) };
|
||||
for r in r0..r1 {
|
||||
let mut v = [0.0; 8];
|
||||
let row = &weights[r * stride..(r + 1) * stride];
|
||||
// SAFETY: as above; `row` is one whole encoded row.
|
||||
unsafe { iq_multi(avx512, kind.original_id(), row, &a[..act.len()], &mut v[..act.len()]) };
|
||||
store(out, base, r, &v[..act.len()]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Rows `r0..r1` of the IQ format against every activation, eight activations at a time, into `out`.
|
||||
/// Shape checks of a gate/up blob with `ff` outputs of `n_ff` floats each.
|
||||
pub(super) fn check_gu(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
act: usize,
|
||||
out: &[&mut [f32]],
|
||||
(r0, r1): (usize, usize),
|
||||
) -> Result<()> {
|
||||
check_rows(act, out.len(), r0, r1)?;
|
||||
if blob.len() != f.bytes || r1 > f.n_ff || out.iter().any(|v| v.len() != f.n_ff) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Admission of the explicit IQ gate/up row API (shapes, activations, CPU).
|
||||
fn admit_iq_gu(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
act: &[&NativeActivation],
|
||||
out: &[&mut [f32]],
|
||||
(r0, r1, avx512): (usize, usize, bool),
|
||||
) -> Result<()> {
|
||||
f.validate()?;
|
||||
if !matches!(f.gu.original_id(), 16 | 17 | 18 | 21 | 22) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
check_gu(f, blob, act.len(), out, (r0, r1))?;
|
||||
for a in act {
|
||||
a.check(f.gu, f.n_embd)?;
|
||||
}
|
||||
check_iq_cpu(avx512)
|
||||
}
|
||||
/// SiLU(gate, up) of gate/up row `r` for the chunk's tokens, stored to `out[base + t][r]`.
|
||||
///
|
||||
/// # Safety
|
||||
/// The CPU gates of `dot_iq` hold for `job.avx512`, every activation was checked for (`kind`, `width`), and
|
||||
/// `width % 256 == 0`.
|
||||
unsafe fn fill_iq_rows(job: &RowsJob, act: &[&NativeActivation], out: &mut [&mut [f32]]) {
|
||||
/// The IQ CPU gates passed; `a` holds the chunk's Q8K activations of `n_embd` weights.
|
||||
unsafe fn iq_gu_row(
|
||||
(avx512, f, blob): (bool, &NativeFormat, &[u8]),
|
||||
a: &[&[Q8K]],
|
||||
(base, r): (usize, usize),
|
||||
out: &mut [&mut [f32]],
|
||||
) {
|
||||
unsafe {
|
||||
let id = job.kind.original_id();
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
let a = typed_blocks_of::<Q8K, 4096>(act, job.width / 256);
|
||||
for r in job.r0..job.r1 {
|
||||
let mut v = [0.0; 8];
|
||||
dot_iq(job.avx512, id, job.row(r), &a[..act.len()], &mut v[..act.len()]);
|
||||
store_column(out, base, r, &v[..act.len()]);
|
||||
}
|
||||
let id = f.gu.original_id();
|
||||
let g = &blob[r * f.gu_row..(r + 1) * f.gu_row];
|
||||
let u = &blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row];
|
||||
let mut gv = [0.0; 8];
|
||||
let mut uv = gv;
|
||||
iq_multi(avx512, id, g, a, &mut gv[..a.len()]);
|
||||
iq_multi(avx512, id, u, a, &mut uv[..a.len()]);
|
||||
for t in 0..a.len() {
|
||||
out[base + t][r] = super::super::rust_simd::silu(gv[t], uv[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,42 +300,16 @@ pub fn iq_gu_rows(
|
||||
r1: usize,
|
||||
avx512: bool,
|
||||
) -> Result<()> {
|
||||
f.validate()?;
|
||||
if !iq_supported(f.gu) || !gu_shaped(f, blob, act.len(), out, r0, r1) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
admit_activations(act, f.gu, f.n_embd)?;
|
||||
require_iq_cpu(avx512)?;
|
||||
// SAFETY: module header; gates checked above; f.validate() pinned n_embd % 256 == 0 for these kinds.
|
||||
unsafe {
|
||||
fill_iq_gu_rows(f, blob, act, out, (r0, r1), avx512);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Rows `r0..r1` of the IQ gate/up pair, `silu(gate) * up`, against every activation, eight at a time, into `out`.
|
||||
///
|
||||
/// # Safety
|
||||
/// The CPU gates of `dot_iq` hold for `avx512`, every activation was checked for (`f.gu`, `f.n_embd`), `f` is
|
||||
/// validated and `blob` matches it.
|
||||
unsafe fn fill_iq_gu_rows(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
act: &[&NativeActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
rows: (usize, usize),
|
||||
avx512: bool,
|
||||
) {
|
||||
unsafe {
|
||||
let id = f.gu.original_id();
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
let a = typed_blocks_of::<Q8K, 4096>(act, f.n_embd / 256);
|
||||
for r in rows.0..rows.1 {
|
||||
let (mut gv, mut uv) = ([0.0; 8], [0.0; 8]);
|
||||
dot_iq(avx512, id, gate_bytes(f, blob, r), &a[..act.len()], &mut gv[..act.len()]);
|
||||
dot_iq(avx512, id, up_bytes(f, blob, r), &a[..act.len()], &mut uv[..act.len()]);
|
||||
store_silu_column(out, base, r, &gv[..act.len()], &uv[..act.len()]);
|
||||
admit_iq_gu(f, blob, act, out, (r0, r1, avx512))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
// SAFETY: module header; gates checked in admit_iq_gu; f.validate() pinned n_embd % 256 == 0 for these kinds.
|
||||
unsafe {
|
||||
let a = typed::<Q8K, 4096>(act, f.n_embd / 256);
|
||||
for r in r0..r1 {
|
||||
iq_gu_row((avx512, f, blob), &a[..act.len()], (base, r), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+92
-65
@@ -1,4 +1,4 @@
|
||||
//! NativeActivation (default, quantize, check), the native gate/up and down row entries and the grouped dot wrappers.
|
||||
//! Moved out of the parent module by STRA-338: impl Default_for_NativeActivation, impl NativeActivation, fn native_gu_rows, fn native_down_rows, fn gu_multi_route, fn group_dot ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -39,6 +39,43 @@ impl<const BYTES: usize> NativeActivation<BYTES> {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
/// The 512-bit IQ kernel needs AVX-512 DQ; a multi-token IQ gate/up call on a CPU without it is refused.
|
||||
fn check_iq512_dq(f: &NativeFormat, nt: usize, d: &super::super::rust_simd::Dispatch) -> Result<()> {
|
||||
if d.iq512
|
||||
&& (nt as i32) >= d.mt_min
|
||||
&& matches!(f.gu.original_id(), 16 | 17 | 18 | 21 | 22)
|
||||
&& !super::super::rust_simd::dq_ok()
|
||||
{
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Gate/up rows `gr`/`ur` against every activation, eight at a time, SiLU-combined into `ff[token][r]`.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok() and (iq512 && dq_ok) checked; `gr`/`ur` are whole rows of a validated blob.
|
||||
unsafe fn gate_up_row(
|
||||
f: &NativeFormat,
|
||||
(gr, ur): (&[u8], &[u8]),
|
||||
r: usize,
|
||||
act: &[&NativeActivation],
|
||||
ff: &mut [&mut [f32]],
|
||||
) {
|
||||
unsafe {
|
||||
let d = super::super::rust_simd::dispatch();
|
||||
for at in (0..act.len()).step_by(8) {
|
||||
let end = (at + 8).min(act.len());
|
||||
let chunk = &act[at..end];
|
||||
let mut g = [0.0; 8];
|
||||
let mut u = [0.0; 8];
|
||||
group_dot_policy(f.gu, gr, chunk, &mut g[..chunk.len()], d, true, act.len());
|
||||
group_dot_policy(f.gu, ur, chunk, &mut u[..chunk.len()], d, true, act.len());
|
||||
for t in 0..chunk.len() {
|
||||
ff[at + t][r] = super::super::rust_simd::silu(g[t], u[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn native_gu_rows(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
@@ -48,42 +85,45 @@ pub fn native_gu_rows(
|
||||
r1: usize,
|
||||
) -> Result<()> {
|
||||
f.validate()?;
|
||||
require_avx2()?;
|
||||
if !gu_shaped(f, blob, act.len(), ff, r0, r1) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
admit_activations(act, f.gu, f.n_embd)?;
|
||||
let d = super::super::rust_simd::dispatch();
|
||||
if iq512_lacks_dq(f.gu, act.len(), d) {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
// SAFETY: module header; avx2_ok() and (iq512 && dq_ok) checked above, gr/ur are whole rows of a validated blob.
|
||||
unsafe {
|
||||
fill_gu_rows(f, blob, act, ff, (r0, r1), d);
|
||||
check_gu(f, blob, act.len(), ff, (r0, r1))?;
|
||||
for a in act {
|
||||
a.check(f.gu, f.n_embd)?;
|
||||
}
|
||||
check_iq512_dq(f, act.len(), super::super::rust_simd::dispatch())?;
|
||||
for r in r0..r1 {
|
||||
let gr = &blob[r * f.gu_row..(r + 1) * f.gu_row];
|
||||
let ur = &blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row];
|
||||
// SAFETY: module header; avx2_ok() and (iq512 && dq_ok) checked above, gr/ur are whole rows of a validated
|
||||
// blob.
|
||||
unsafe {
|
||||
gate_up_row(f, (gr, ur), r, act, ff);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Rows `r0..r1` of the gate/up pair, `silu(gate) * up`, against every activation, eight at a time, into `ff`.
|
||||
/// Down row `row` against every hidden activation, eight at a time, into `out[token][r]`.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok() holds (and dq_ok() where the 512-bit IQ kernel is selected), `f` is validated and `blob` matches it.
|
||||
unsafe fn fill_gu_rows(
|
||||
/// avx2_ok() checked; `row` is a whole down row of a validated blob.
|
||||
unsafe fn down_row<const BYTES: usize>(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
act: &[&NativeActivation],
|
||||
ff: &mut [&mut [f32]],
|
||||
rows: (usize, usize),
|
||||
d: &super::super::rust_simd::Dispatch,
|
||||
row: &[u8],
|
||||
r: usize,
|
||||
hq: &[&NativeActivation<BYTES>],
|
||||
out: &mut [&mut [f32]],
|
||||
) {
|
||||
unsafe {
|
||||
for r in rows.0..rows.1 {
|
||||
let (gr, ur) = (gate_bytes(f, blob, r), up_bytes(f, blob, r));
|
||||
for at in (0..act.len()).step_by(8) {
|
||||
let chunk = &act[at..(at + 8).min(act.len())];
|
||||
let (mut g, mut u) = ([0.0; 8], [0.0; 8]);
|
||||
group_dot_policy(f.gu, gr, chunk, &mut g[..chunk.len()], d, true, act.len());
|
||||
group_dot_policy(f.gu, ur, chunk, &mut u[..chunk.len()], d, true, act.len());
|
||||
store_silu_column(ff, at, r, &g[..chunk.len()], &u[..chunk.len()]);
|
||||
let d = super::super::rust_simd::dispatch();
|
||||
for at in (0..hq.len()).step_by(8) {
|
||||
let end = (at + 8).min(hq.len());
|
||||
let chunk = &hq[at..end];
|
||||
let mut v = [0.0; 8];
|
||||
group_dot_policy(f.down, row, chunk, &mut v[..chunk.len()], d, false, hq.len());
|
||||
for t in 0..chunk.len() {
|
||||
out[at + t][r] = v[t];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,47 +137,28 @@ pub fn native_down_rows<const BYTES: usize>(
|
||||
r1: usize,
|
||||
) -> Result<()> {
|
||||
f.validate()?;
|
||||
require_avx2()?;
|
||||
if !down_shaped(f, blob, hq.len(), out, r0, r1) {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
check_rows(hq.len(), out.len(), r0, r1)?;
|
||||
if blob.len() != f.bytes || r1 > f.n_embd || out.iter().any(|v| v.len() != f.n_embd) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
admit_activations(hq, f.down, f.n_ff)?;
|
||||
let d = super::super::rust_simd::dispatch();
|
||||
// SAFETY: module header; avx2_ok() checked above, `row` is a whole down row of a validated blob.
|
||||
unsafe {
|
||||
fill_down_rows(f, blob, hq, out, (r0, r1), d);
|
||||
for a in hq {
|
||||
a.check(f.down, f.n_ff)?;
|
||||
}
|
||||
for r in r0..r1 {
|
||||
let row = &blob[f.down_offset + r * f.down_row..f.down_offset + (r + 1) * f.down_row];
|
||||
// SAFETY: module header; avx2_ok() checked above, `row` is a whole down row of a validated blob.
|
||||
unsafe {
|
||||
down_row(f, row, r, hq, out);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Rows `r0..r1` of the down projection against every activation, eight at a time, into `out`.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok() holds, `f` is validated and `blob` matches it.
|
||||
unsafe fn fill_down_rows<const BYTES: usize>(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
hq: &[&NativeActivation<BYTES>],
|
||||
out: &mut [&mut [f32]],
|
||||
rows: (usize, usize),
|
||||
d: &super::super::rust_simd::Dispatch,
|
||||
) {
|
||||
unsafe {
|
||||
for r in rows.0..rows.1 {
|
||||
let row = &blob[f.down_offset + r * f.down_row..f.down_offset + (r + 1) * f.down_row];
|
||||
for at in (0..hq.len()).step_by(8) {
|
||||
let chunk = &hq[at..(at + 8).min(hq.len())];
|
||||
let mut v = [0.0; 8];
|
||||
group_dot_policy(f.down, row, chunk, &mut v[..chunk.len()], d, false, hq.len());
|
||||
store_column(out, at, r, &v[..chunk.len()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Multi-token gate/up kernel choice of native_expert.cpp native_gu_rows
|
||||
/// (`nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`):
|
||||
/// Some(true) = the 512-bit kernel, Some(false) = the 256-bit one, None = ggml's per-token dot. IQ4_XS (23) has only
|
||||
/// the 256-bit kernel and takes it on an AVX2-only tree (STRA-329: this site omitted it, rust_pool.rs
|
||||
/// `f.gu==23&&!d.avx512` has it since STRA-324).
|
||||
/// Multi-token gate/up kernel choice of native_expert.cpp native_gu_rows (`nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`):
|
||||
/// Some(true) = the 512-bit kernel, Some(false) = the 256-bit one, None = ggml's per-token dot. IQ4_XS (23) has only the 256-bit kernel and
|
||||
/// takes it on an AVX2-only tree (STRA-329: this site omitted it, rust_pool.rs `f.gu==23&&!d.avx512` has it since STRA-324).
|
||||
pub(in super::super) fn gu_multi_route(k: i32, policy_nt: i32, d: &super::super::rust_simd::Dispatch) -> Option<bool> {
|
||||
if policy_nt < d.mt_min {
|
||||
return None;
|
||||
@@ -161,7 +182,10 @@ pub(in super::super) unsafe fn group_dot<const BYTES: usize>(
|
||||
gu: bool,
|
||||
) {
|
||||
unsafe {
|
||||
let raw = raw_views(act);
|
||||
let mut raw: [&[u8]; 8] = [&[]; 8];
|
||||
for t in 0..act.len() {
|
||||
raw[t] = act[t].raw();
|
||||
}
|
||||
group_dot_bytes(kind, row, act[0].n, &raw[..act.len()], out, d, gu)
|
||||
}
|
||||
}
|
||||
@@ -188,7 +212,10 @@ pub(super) unsafe fn group_dot_policy<const BYTES: usize>(
|
||||
policy_nt: usize,
|
||||
) {
|
||||
unsafe {
|
||||
let raw = raw_views(act);
|
||||
let mut raw: [&[u8]; 8] = [&[]; 8];
|
||||
for t in 0..act.len() {
|
||||
raw[t] = act[t].raw();
|
||||
}
|
||||
group_dot_bytes_policy(kind, row, act[0].n, &raw[..act.len()], out, d, gu, policy_nt)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,29 @@
|
||||
//! IQ4_NL, KQ gate/up and Q2_0 row entries, and the Original header capability predicates.
|
||||
//! Moved out of the parent module by STRA-338: fn iq4nl_rows, fn native_experts_available, fn kq_supported, fn iq_supported, fn cpu_avx2_ok, fn cpu_avx512_ok ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Admission of the IQ4_NL row API (shapes, activations, CPU); returns the row stride.
|
||||
fn admit_iq4nl(
|
||||
weights: &[u8],
|
||||
width: usize,
|
||||
act: &[&NativeActivation],
|
||||
out: &[&mut [f32]],
|
||||
(r0, r1): (usize, usize),
|
||||
) -> Result<usize> {
|
||||
if width == 0 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
check_rows(act.len(), out.len(), r0, r1)?;
|
||||
let stride = check_weights(Kind::Iq4Nl, width, weights, out, r1)?;
|
||||
for a in act {
|
||||
a.check(Kind::Iq4Nl, width)?;
|
||||
}
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(stride)
|
||||
}
|
||||
pub fn iq4nl_rows(
|
||||
weights: &[u8],
|
||||
width: usize,
|
||||
@@ -11,44 +32,20 @@ pub fn iq4nl_rows(
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
) -> Result<()> {
|
||||
if width == 0 || !batch_shaped(act.len(), out.len(), r0, r1) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let stride = Kind::Iq4Nl.row_bytes(width)?;
|
||||
if !rows_fit(weights.len(), stride, r1, out) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
admit_activations(act, Kind::Iq4Nl, width)?;
|
||||
require_avx2()?;
|
||||
// SAFETY: module header; avx2_ok() checked above; width % 32 == 0 via row_bytes().
|
||||
unsafe {
|
||||
fill_iq4nl_rows(weights, (width, stride), act, out, (r0, r1));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Rows `r0..r1` of IQ4_NL against every activation, eight activations at a time, into `out`.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok() holds, every activation was checked for (IQ4_NL, `width`), `weights` holds whole rows of `stride` bytes.
|
||||
unsafe fn fill_iq4nl_rows(
|
||||
weights: &[u8],
|
||||
(width, stride): (usize, usize),
|
||||
act: &[&NativeActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
(r0, r1): (usize, usize),
|
||||
) {
|
||||
unsafe {
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
let a = typed_blocks_of::<Q8Zero, 4096>(act, width / 32);
|
||||
for r in r0..r1 {
|
||||
let mut v = [0.0; 8];
|
||||
let row = &weights[r * stride..(r + 1) * stride];
|
||||
super::super::rust_iq::iq4nl(row, &a[..act.len()], &mut v[..act.len()], false);
|
||||
store_column(out, base, r, &v[..act.len()]);
|
||||
}
|
||||
let stride = admit_iq4nl(weights, width, act, out, (r0, r1))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
// SAFETY: module header; avx2_ok() checked in admit_iq4nl; width % 32 == 0 via row_bytes().
|
||||
let a = unsafe { typed::<Q8Zero, 4096>(act, width / 32) };
|
||||
for r in r0..r1 {
|
||||
let mut v = [0.0; 8];
|
||||
let row = &weights[r * stride..(r + 1) * stride];
|
||||
// SAFETY: as above; `row` is one whole encoded row.
|
||||
unsafe { super::super::rust_iq::iq4nl(row, &a[..act.len()], &mut v[..act.len()], false) };
|
||||
store(out, base, r, &v[..act.len()]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Original header capability predicates. Numerical owners still admit actual
|
||||
@@ -69,6 +66,50 @@ pub fn cpu_avx512_ok() -> bool {
|
||||
super::super::rust_simd::avx512_ok()
|
||||
}
|
||||
|
||||
/// Admission of the explicit KQ gate/up row API (shapes, activations, CPU).
|
||||
fn admit_kq_gu(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
act: &[&NativeActivation],
|
||||
out: &[&mut [f32]],
|
||||
(r0, r1): (usize, usize),
|
||||
) -> Result<()> {
|
||||
f.validate()?;
|
||||
if !kq_supported(f.gu) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
check_gu(f, blob, act.len(), out, (r0, r1))?;
|
||||
for a in act {
|
||||
a.check(f.gu, f.n_embd)?;
|
||||
}
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// SiLU(gate, up) of gate/up row `r` for the chunk's tokens, stored to `out[base + t][r]`.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok(); `f.validate()` pinned the geometry and `blob.len() == f.bytes`.
|
||||
unsafe fn kq_gu_row(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
act: &[&NativeActivation],
|
||||
(base, r): (usize, usize),
|
||||
out: &mut [&mut [f32]],
|
||||
) {
|
||||
unsafe {
|
||||
let mut g = [0.0; 8];
|
||||
let mut u = g;
|
||||
for (role, values) in [(0, &mut g), (f.up_offset, &mut u)] {
|
||||
let row = &blob[role + r * f.gu_row..role + (r + 1) * f.gu_row];
|
||||
kq_dot(f.gu, row, act, f.n_embd, &mut values[..act.len()]);
|
||||
}
|
||||
for t in 0..act.len() {
|
||||
out[base + t][r] = super::super::rust_simd::silu(g[t], u[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Original explicit KQ gate/up entry, independent of STRATA_KQ256.
|
||||
pub fn kq_gu_rows(
|
||||
f: &NativeFormat,
|
||||
@@ -78,43 +119,48 @@ pub fn kq_gu_rows(
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
) -> Result<()> {
|
||||
f.validate()?;
|
||||
if !kq_supported(f.gu) || !gu_shaped(f, blob, act.len(), out, r0, r1) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
admit_activations(act, f.gu, f.n_embd)?;
|
||||
require_avx2()?;
|
||||
// SAFETY: module header; avx2_ok() checked above; f.validate() pinned the geometry and blob.len()==f.bytes.
|
||||
unsafe {
|
||||
fill_kq_gu_rows(f, blob, act, out, (r0, r1));
|
||||
admit_kq_gu(f, blob, act, out, (r0, r1))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
for r in r0..r1 {
|
||||
// SAFETY: module header; avx2_ok() checked in admit_kq_gu; f.validate() pinned the geometry and
|
||||
// blob.len()==f.bytes.
|
||||
unsafe { kq_gu_row(f, blob, act, (base, r), out) };
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Rows `r0..r1` of the KQ gate/up pair, `silu(gate) * up`, against every activation, eight at a time, into `out`.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok() holds, every activation was checked for (`f.gu`, `f.n_embd`), `f` is validated and `blob` matches it.
|
||||
unsafe fn fill_kq_gu_rows(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
act: &[&NativeActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
(r0, r1): (usize, usize),
|
||||
) {
|
||||
unsafe {
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
let raw = raw_views(act);
|
||||
for r in r0..r1 {
|
||||
let (mut g, mut u) = ([0.0; 8], [0.0; 8]);
|
||||
dot_kq(f.gu, gate_bytes(f, blob, r), f.n_embd, &raw[..act.len()], &mut g[..act.len()]);
|
||||
dot_kq(f.gu, up_bytes(f, blob, r), f.n_embd, &raw[..act.len()], &mut u[..act.len()]);
|
||||
store_silu_column(out, base, r, &g[..act.len()], &u[..act.len()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Argument shapes of the Q2 row API: width within `H`, one to eight activations, one output each, `r0 <= r1`.
|
||||
fn check_q2_args(width: usize, act: usize, out: usize, (r0, r1): (usize, usize)) -> Result<()> {
|
||||
if width == 0 || width > super::super::H || act == 0 || act > 8 || act != out || r0 > r1 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Shape and CPU admission of the Q2 row API; returns the row stride.
|
||||
fn check_q2_rows(
|
||||
weights: &[u8],
|
||||
width: usize,
|
||||
act: &[&super::super::rust_legacy::PlanarActivation],
|
||||
out: &[&mut [f32]],
|
||||
(r0, r1): (usize, usize),
|
||||
) -> Result<usize> {
|
||||
check_q2_args(width, act.len(), out.len(), (r0, r1))?;
|
||||
let stride = Kind::Q2Zero.row_bytes(width)?;
|
||||
if weights.len() % stride != 0
|
||||
|| r1 > weights.len() / stride
|
||||
|| out.iter().any(|o| o.len() != weights.len() / stride)
|
||||
|| act.iter().any(|a| a.0.nchunks != (width / 32) as i32)
|
||||
{
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
if !super::super::rust_simd::avx2_ok() || super::super::rust_simd::avx512_ok() && !super::super::rust_simd::dq_ok()
|
||||
{
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(stride)
|
||||
}
|
||||
/// Original q2_rows_any dispatch on a genuine initialized Planar activation.
|
||||
pub fn q2_rows(
|
||||
weights: &[u8],
|
||||
@@ -124,48 +170,40 @@ pub fn q2_rows(
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
) -> Result<()> {
|
||||
if !q2_shaped(width, act.len(), out.len(), r0, r1) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let stride = Kind::Q2Zero.row_bytes(width)?;
|
||||
if !rows_fit(weights.len(), stride, r1, out) || act.iter().any(|a| a.0.nchunks != (width / 32) as i32) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
require_q2_cpu()?;
|
||||
// SAFETY: avx2_ok() (+dq_ok() if avx512_ok()) checked above; rows are `stride = width/64*18 <= 720` bytes
|
||||
// (width <= H) and act.len() <= 8 (see rust_q2 bounds).
|
||||
unsafe {
|
||||
fill_q2_rows(weights, stride, act, out, (r0, r1));
|
||||
let stride = check_q2_rows(weights, width, act, out, (r0, r1))?;
|
||||
let empty = super::super::rust_types::ActQ::default();
|
||||
let mut a = [∅ 8];
|
||||
for t in 0..act.len() {
|
||||
a[t] = &act[t].0;
|
||||
}
|
||||
// SAFETY: avx2_ok() (+dq_ok() if avx512_ok()) checked above; rows are `stride = width/64*18 <= 720` bytes (width
|
||||
// <= H) and act.len() <= 8 (see rust_q2 bounds).
|
||||
unsafe { q2_dot_rows(weights, stride, &a[..act.len()], (r0, r1), out) };
|
||||
Ok(())
|
||||
}
|
||||
/// Rows `r0..r1` of Q2_0 against up to eight Planar activations, into `out`.
|
||||
/// Q2 dot of rows `r0..r1` against the activations `a`, stored to `out[token][r]`.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok() (and dq_ok() when avx512_ok()) holds, `weights` holds whole rows of `stride` bytes (at most 720), and
|
||||
/// `act.len() <= 8`.
|
||||
unsafe fn fill_q2_rows(
|
||||
/// As `q2_rows`: the CPU gates passed, `stride <= 720`, `a.len() <= 8`.
|
||||
unsafe fn q2_dot_rows(
|
||||
weights: &[u8],
|
||||
stride: usize,
|
||||
act: &[&super::super::rust_legacy::PlanarActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
a: &[&super::super::rust_types::ActQ],
|
||||
(r0, r1): (usize, usize),
|
||||
out: &mut [&mut [f32]],
|
||||
) {
|
||||
unsafe {
|
||||
let empty = super::super::rust_types::ActQ::default();
|
||||
let mut a = [∅ 8];
|
||||
for t in 0..act.len() {
|
||||
a[t] = &act[t].0;
|
||||
}
|
||||
let mut values = [0.0; 8];
|
||||
for r in r0..r1 {
|
||||
let row = &weights[r * stride..(r + 1) * stride];
|
||||
if super::super::rust_simd::avx512_ok() {
|
||||
super::super::rust_q2::dot512(row, &a[..act.len()], &mut values[..act.len()]);
|
||||
super::super::rust_q2::dot512(row, a, &mut values[..a.len()]);
|
||||
} else {
|
||||
super::super::rust_q2::dot256(row, &a[..act.len()], &mut values[..act.len()]);
|
||||
super::super::rust_q2::dot256(row, a, &mut values[..a.len()]);
|
||||
}
|
||||
for t in 0..a.len() {
|
||||
out[t][r] = values[t];
|
||||
}
|
||||
store_column(out, 0, r, &values[..act.len()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,7 @@ fn xorshift(s: &mut u64) -> u64 {
|
||||
fn dispatch_of(iq512: bool, iq256: bool, avx512: bool) -> Dispatch {
|
||||
Dispatch { iq512, iq256, iq4nl: true, mt_min: 2, gather: false, prefetch: 0, avx512 }
|
||||
}
|
||||
// native_expert.cpp native_gu_rows: `nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`, then AVX-512
|
||||
// kernel first, else AVX2.
|
||||
// native_expert.cpp native_gu_rows: `nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`, then AVX-512 kernel first, else AVX2.
|
||||
#[test]
|
||||
fn gu_multi_route_follows_native_gu_rows() {
|
||||
let avx2_tree = dispatch_of(false, true, false);
|
||||
@@ -39,84 +38,8 @@ fn gu_multi_route_follows_native_gu_rows() {
|
||||
assert_eq!(gu_multi_route(k, 4, &avx2_tree), None, "k {k} has no multi-token IQ kernel");
|
||||
}
|
||||
}
|
||||
const IQ4XS_TEST: &str = "iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel";
|
||||
/// Re-run this test in a child process with STRATA_FORCE_AVX2=1, so the AVX2 tree is chosen on an AVX-512 CPU.
|
||||
fn rerun_on_avx2_tree() {
|
||||
assert!(std::env::var_os("LELEKA_TEST_AVX2_CHILD").is_none(), "STRATA_FORCE_AVX2=1 did not select the AVX2 tree");
|
||||
let path = module_path!();
|
||||
let path = &path[path.find("::").unwrap() + 2..];
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", &format!("{path}::{IQ4XS_TEST}"), "--nocapture"])
|
||||
.env("STRATA_FORCE_AVX2", "1")
|
||||
.env("LELEKA_TEST_AVX2_CHILD", "1")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "child run on the AVX2 tree failed");
|
||||
}
|
||||
/// A random IQ4_XS gate/up blob whose block scales are finite normal FP16 values.
|
||||
fn random_blob(f: &NativeFormat, seed: &mut u64) -> Vec<u8> {
|
||||
let mut blob = vec![0u8; f.bytes];
|
||||
for v in blob.iter_mut() {
|
||||
*v = xorshift(seed) as u8;
|
||||
}
|
||||
for b in blob[..f.down_offset].chunks_exact_mut(136) {
|
||||
let e = 8 + (xorshift(seed) % 8) as u16;
|
||||
let m = (xorshift(seed) & 0x3ff) as u16;
|
||||
b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes());
|
||||
}
|
||||
blob
|
||||
}
|
||||
/// `nt` activations of `n_embd` random values, scaled by the round, quantized for IQ4_XS.
|
||||
fn quantized_acts(nt: usize, n_embd: usize, round: usize, seed: &mut u64) -> Vec<NativeActivation> {
|
||||
let mut acts: Vec<NativeActivation> = (0..nt).map(|_| NativeActivation::default()).collect();
|
||||
for a in acts.iter_mut() {
|
||||
let x: Vec<f32> =
|
||||
(0..n_embd).map(|_| ((xorshift(seed) % 20001) as f32 - 10000.0) * (0.001 + round as f32)).collect();
|
||||
a.quantize(Kind::Iq4Xs, &x).unwrap();
|
||||
}
|
||||
acts
|
||||
}
|
||||
/// native_gu_rows over every row of `f`, one output vector per activation.
|
||||
fn native_ff(f: &NativeFormat, blob: &[u8], acts: &[NativeActivation]) -> Vec<Vec<f32>> {
|
||||
let refs: Vec<&NativeActivation> = acts.iter().collect();
|
||||
let mut ff = vec![vec![0.0f32; f.n_ff]; acts.len()];
|
||||
let mut outs: Vec<&mut [f32]> = ff.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
native_gu_rows(f, blob, &refs, &mut outs, 0, f.n_ff).unwrap();
|
||||
ff
|
||||
}
|
||||
/// The Q8K blocks `quantize(Iq4Xs, n_embd)` wrote at the start of each activation.
|
||||
fn q8k_blocks(acts: &[NativeActivation], n_embd: usize) -> Vec<&[Q8K]> {
|
||||
// SAFETY: quantize(Iq4Xs, n_embd) wrote n_embd/256 Q8K blocks at offset 0 of the 64-aligned activation.
|
||||
acts.iter().map(|a| unsafe { std::slice::from_raw_parts(a.raw().as_ptr().cast::<Q8K>(), n_embd / 256) }).collect()
|
||||
}
|
||||
/// Row `r` of the gate and up dots through the AVX2 multi-token kernel, combined as `silu(gate) * up`.
|
||||
fn reference_row(f: &NativeFormat, blob: &[u8], ys: &[&[Q8K]], r: usize) -> ([f32; 8], [f32; 8]) {
|
||||
let (mut g, mut u) = ([0.0f32; 8], [0.0f32; 8]);
|
||||
let nt = ys.len();
|
||||
// SAFETY: avx2_ok() by the caller; rows are whole IQ4_XS rows of the validated blob and every activation has
|
||||
// n_embd/256 blocks.
|
||||
unsafe {
|
||||
super::super::rust_iq::dot_multi256(23, &blob[r * f.gu_row..(r + 1) * f.gu_row], ys, &mut g[..nt]);
|
||||
let up = &blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row];
|
||||
super::super::rust_iq::dot_multi256(23, up, ys, &mut u[..nt]);
|
||||
}
|
||||
(g, u)
|
||||
}
|
||||
fn assert_rows_match(f: &NativeFormat, blob: &[u8], acts: &[NativeActivation], round: usize) {
|
||||
let nt = acts.len();
|
||||
let ff = native_ff(f, blob, acts);
|
||||
let ys = q8k_blocks(acts, f.n_embd);
|
||||
for r in 0..f.n_ff {
|
||||
let (g, u) = reference_row(f, blob, &ys, r);
|
||||
for (t, cells) in ff.iter().enumerate() {
|
||||
let expected = super::super::rust_simd::silu(g[t], u[t]);
|
||||
assert_eq!(cells[r].to_bits(), expected.to_bits(), "round {round} nt {nt} row {r} token {t}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Differential: native_gu_rows with an IQ4_XS gate/up at 2..8 tokens on the AVX2 tree == the multi-token kernel row by
|
||||
// row. The tree is chosen once per process (OnceLock), so on an AVX-512 CPU the test re-runs itself in a child with
|
||||
// STRATA_FORCE_AVX2=1.
|
||||
// Differential: native_gu_rows with an IQ4_XS gate/up at 2..8 tokens on the AVX2 tree == the multi-token kernel row by row.
|
||||
// The tree is chosen once per process (OnceLock), so on an AVX-512 CPU the test re-runs itself in a child with STRATA_FORCE_AVX2=1.
|
||||
#[test]
|
||||
fn iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel() {
|
||||
if !avx2_ok() {
|
||||
@@ -124,17 +47,73 @@ fn iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel() {
|
||||
return;
|
||||
}
|
||||
if avx512_ok() {
|
||||
rerun_on_avx2_tree();
|
||||
assert!(
|
||||
std::env::var_os("LELEKA_TEST_AVX2_CHILD").is_none(),
|
||||
"STRATA_FORCE_AVX2=1 did not select the AVX2 tree"
|
||||
);
|
||||
let path = module_path!();
|
||||
let path = &path[path.find("::").unwrap() + 2..];
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
&format!("{path}::iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel"),
|
||||
"--nocapture",
|
||||
])
|
||||
.env("STRATA_FORCE_AVX2", "1")
|
||||
.env("LELEKA_TEST_AVX2_CHILD", "1")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "child run on the AVX2 tree failed");
|
||||
return;
|
||||
}
|
||||
let (n_embd, n_ff) = (512usize, 32usize);
|
||||
let f = NativeFormat::new(Kind::Iq4Xs, Kind::Iq4Nl, n_embd, n_ff).unwrap();
|
||||
let mut seed = 0x5eed_0329_abcd_ef01u64;
|
||||
for round in 0..3 {
|
||||
let blob = random_blob(&f, &mut seed);
|
||||
let mut blob = vec![0u8; f.bytes];
|
||||
for v in blob.iter_mut() {
|
||||
*v = xorshift(&mut seed) as u8;
|
||||
}
|
||||
for b in blob[..f.down_offset].chunks_exact_mut(136) {
|
||||
let e = 8 + (xorshift(&mut seed) % 8) as u16;
|
||||
let m = (xorshift(&mut seed) & 0x3ff) as u16;
|
||||
b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes());
|
||||
}
|
||||
for nt in [2usize, 3, 5, 8] {
|
||||
let acts = quantized_acts(nt, n_embd, round, &mut seed);
|
||||
assert_rows_match(&f, &blob, &acts, round);
|
||||
let mut acts: Vec<NativeActivation> = (0..nt).map(|_| NativeActivation::default()).collect();
|
||||
for a in acts.iter_mut() {
|
||||
let x: Vec<f32> = (0..n_embd)
|
||||
.map(|_| ((xorshift(&mut seed) % 20001) as f32 - 10000.0) * (0.001 + round as f32))
|
||||
.collect();
|
||||
a.quantize(Kind::Iq4Xs, &x).unwrap();
|
||||
}
|
||||
let refs: Vec<&NativeActivation> = acts.iter().collect();
|
||||
let mut ff = vec![vec![0.0f32; n_ff]; nt];
|
||||
{
|
||||
let mut outs: Vec<&mut [f32]> = ff.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
native_gu_rows(&f, &blob, &refs, &mut outs, 0, n_ff).unwrap();
|
||||
}
|
||||
let ys:Vec<&[Q8K]>=acts.iter().map(|a|/* SAFETY: quantize(Iq4Xs, n_embd) wrote n_embd/256 Q8K blocks at offset 0 of the 64-aligned activation. */unsafe{std::slice::from_raw_parts(a.raw().as_ptr().cast::<Q8K>(),n_embd/256)}).collect();
|
||||
for r in 0..n_ff {
|
||||
let (mut g, mut u) = ([0.0f32; 8], [0.0f32; 8]);
|
||||
// SAFETY: avx2_ok() above; rows are whole IQ4_XS rows of the validated blob and every activation has n_embd/256 blocks.
|
||||
unsafe {
|
||||
super::super::rust_iq::dot_multi256(23, &blob[r * f.gu_row..(r + 1) * f.gu_row], &ys, &mut g[..nt]);
|
||||
super::super::rust_iq::dot_multi256(
|
||||
23,
|
||||
&blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row],
|
||||
&ys,
|
||||
&mut u[..nt],
|
||||
);
|
||||
}
|
||||
for t in 0..nt {
|
||||
assert_eq!(
|
||||
ff[t][r].to_bits(),
|
||||
super::super::rust_simd::silu(g[t], u[t]).to_bits(),
|
||||
"round {round} nt {nt} row {r} token {t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
//! Typed views over encoded activations, the dot dispatch of the native row drivers, and their output stores.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The encoded bytes of the activations in the first slots of an eight-slot array (the others are empty).
|
||||
pub(super) fn raw_views<'a, const BYTES: usize>(act: &[&'a NativeActivation<BYTES>]) -> [&'a [u8]; 8] {
|
||||
let mut raw: [&[u8]; 8] = [&[]; 8];
|
||||
for t in 0..act.len() {
|
||||
raw[t] = act[t].raw();
|
||||
}
|
||||
raw
|
||||
}
|
||||
/// Views of `count` blocks of `T` over each encoded activation, in the first slots of an eight-slot array.
|
||||
///
|
||||
/// # Safety
|
||||
/// Every `raw[t]` starts with at least `count` initialized blocks of `T` and is aligned for `T`: the bytes of a
|
||||
/// `NativeActivation` that `quantize()` filled for the block type (see the module header), or the same bytes of a pool
|
||||
/// bank.
|
||||
pub(super) unsafe fn typed_blocks<'a, T>(raw: &[&'a [u8]], count: usize) -> [&'a [T]; 8] {
|
||||
let mut a: [&[T]; 8] = [&[]; 8];
|
||||
for t in 0..raw.len() {
|
||||
// SAFETY: the contract of this function.
|
||||
a[t] = unsafe { std::slice::from_raw_parts(raw[t].as_ptr().cast(), count) };
|
||||
}
|
||||
a
|
||||
}
|
||||
/// `typed_blocks` over the bytes of `act`.
|
||||
///
|
||||
/// # Safety
|
||||
/// Every activation was quantized for the block type `T` with at least `count` blocks (checked by `check()`).
|
||||
pub(super) unsafe fn typed_blocks_of<'a, T, const BYTES: usize>(
|
||||
act: &[&'a NativeActivation<BYTES>],
|
||||
count: usize,
|
||||
) -> [&'a [T]; 8] {
|
||||
// SAFETY: the contract of this function.
|
||||
unsafe { typed_blocks(&raw_views(act)[..act.len()], count) }
|
||||
}
|
||||
/// One KQ256 weight row (Q4_K, Q5_1 or Q8_0) against `n` columns of each activation in `raw`.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok() holds, `kind` is one of the three, and `typed_blocks` holds for the block type of `kind` at `n` columns.
|
||||
pub(super) unsafe fn dot_kq(kind: Kind, row: &[u8], n: usize, raw: &[&[u8]], out: &mut [f32]) {
|
||||
// SAFETY: the contract of this function.
|
||||
unsafe {
|
||||
match kind {
|
||||
Kind::Q4K => super::super::rust_kq::q4_k_dot(row, &typed_blocks::<Q8K>(raw, n / 256)[..raw.len()], out),
|
||||
Kind::Q5One => {
|
||||
super::super::rust_kq::q5_one_dot(row, &typed_blocks::<Q8One>(raw, n / 32)[..raw.len()], out)
|
||||
}
|
||||
Kind::Q8Zero => {
|
||||
super::super::rust_kq::q8_zero_dot(row, &typed_blocks::<Q8Zero>(raw, n / 32)[..raw.len()], out)
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// One IQ weight row of Original type `id` against the Q8K activations `a`, in the 512-bit or the 256-bit kernel.
|
||||
///
|
||||
/// # Safety
|
||||
/// avx2_ok() holds, and avx512_ok() with dq_ok() when `avx512`; `row` is a whole row of type `id`.
|
||||
pub(super) unsafe fn dot_iq(avx512: bool, id: i32, row: &[u8], a: &[&[Q8K]], out: &mut [f32]) {
|
||||
// SAFETY: the contract of this function.
|
||||
unsafe {
|
||||
if avx512 {
|
||||
super::super::rust_iq::dot_multi512(id, row, a, out);
|
||||
} else {
|
||||
super::super::rust_iq::dot_multi256(id, row, a, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Store the dot results `v` of row `r` as cell `r` of outputs `base..base + v.len()`.
|
||||
pub(super) fn store_column(out: &mut [&mut [f32]], base: usize, r: usize, v: &[f32]) {
|
||||
for t in 0..v.len() {
|
||||
out[base + t][r] = v[t];
|
||||
}
|
||||
}
|
||||
/// Store `silu(g) * u` of row `r` as cell `r` of outputs `base..base + g.len()`.
|
||||
pub(super) fn store_silu_column(out: &mut [&mut [f32]], base: usize, r: usize, g: &[f32], u: &[f32]) {
|
||||
for t in 0..g.len() {
|
||||
out[base + t][r] = super::super::rust_simd::silu(g[t], u[t]);
|
||||
}
|
||||
}
|
||||
/// Gate row `r` of the interleaved gate/up blob of `f`.
|
||||
pub(super) fn gate_bytes<'a>(f: &NativeFormat, blob: &'a [u8], r: usize) -> &'a [u8] {
|
||||
&blob[r * f.gu_row..(r + 1) * f.gu_row]
|
||||
}
|
||||
/// Up row `r` of the gate/up blob of `f`.
|
||||
pub(super) fn up_bytes<'a>(f: &NativeFormat, blob: &'a [u8], r: usize) -> &'a [u8] {
|
||||
&blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row]
|
||||
}
|
||||
@@ -21,35 +21,33 @@ unsafe extern "C" {
|
||||
fn sysconf(name: i32) -> i64;
|
||||
fn madvise(addr: *mut u8, len: usize, advice: i32) -> i32;
|
||||
}
|
||||
/// True when the soft stack limit is a finite value of at most 8 MiB.
|
||||
fn check_stack_limit(current: u64) -> bool {
|
||||
current != 0 && current != u64::MAX && current <= 8 * 1024 * 1024
|
||||
}
|
||||
/// True when the default thread stack size is nonzero and at most 8 MiB.
|
||||
fn check_stack_size(size: usize) -> bool {
|
||||
size != 0 && size <= 8 * 1024 * 1024
|
||||
}
|
||||
/// True when `getrlimit(RLIMIT_STACK)` succeeds and the soft limit passes `check_stack_limit`.
|
||||
/// The soft stack limit is finite and within 8 MiB.
|
||||
#[cfg(target_env = "gnu")]
|
||||
fn stack_limit_admitted() -> bool {
|
||||
fn stack_limit_ok() -> bool {
|
||||
let mut limit = Limit { current: 0, max: 0 };
|
||||
// SAFETY: `limit` is a live, writable local of the exact glibc layout (struct rlimit = 2*u64).
|
||||
let failed = unsafe { getrlimit(3, &mut limit) } != 0;
|
||||
!failed && check_stack_limit(limit.current)
|
||||
let rc = unsafe { getrlimit(3, &mut limit) };
|
||||
rc == 0 && limit.current != 0 && limit.current != u64::MAX && limit.current <= 8 * 1024 * 1024
|
||||
}
|
||||
/// The default thread stack size of the process (glibc default attributes), when readable and admitted.
|
||||
/// The default pthread stack size, if it is within 8 MiB.
|
||||
#[cfg(target_env = "gnu")]
|
||||
fn default_stack_size() -> Option<usize> {
|
||||
fn default_stack() -> Result<usize> {
|
||||
let mut attr = Attr { words: [0; 7] };
|
||||
// SAFETY: `attr` is a live, writable local of the exact glibc layout (pthread_attr_t = 56 bytes, align 8).
|
||||
if unsafe { pthread_getattr_default_np(&mut attr) } != 0 {
|
||||
return None;
|
||||
// SAFETY: `attr`/`size` are live, writable locals of the exact glibc layouts (pthread_attr_t = 56 bytes, align
|
||||
// 8); the attr is destroyed exactly once, only after a successful getattr.
|
||||
unsafe {
|
||||
if pthread_getattr_default_np(&mut attr) != 0 {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
let mut size = 0;
|
||||
let query = pthread_attr_getstacksize(&attr, &mut size);
|
||||
let release = pthread_attr_destroy(&mut attr);
|
||||
if query != 0 || release != 0 || size == 0 || size > 8 * 1024 * 1024 {
|
||||
Err(Error::Unsupported)
|
||||
} else {
|
||||
Ok(size)
|
||||
}
|
||||
}
|
||||
let mut size = 0;
|
||||
// SAFETY: `attr` was filled by the successful getattr above and is destroyed exactly once, here; `size` is a live
|
||||
// writable word.
|
||||
let (query, release) = unsafe { (pthread_attr_getstacksize(&attr, &mut size), pthread_attr_destroy(&mut attr)) };
|
||||
(query == 0 && release == 0 && check_stack_size(size)).then_some(size)
|
||||
}
|
||||
pub(super) fn stack_size() -> Result<usize> {
|
||||
#[cfg(not(target_env = "gnu"))]
|
||||
@@ -58,42 +56,43 @@ pub(super) fn stack_size() -> Result<usize> {
|
||||
}
|
||||
#[cfg(target_env = "gnu")]
|
||||
{
|
||||
if !stack_limit_admitted() {
|
||||
if !stack_limit_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
default_stack_size().ok_or(Error::Unsupported)
|
||||
default_stack()
|
||||
}
|
||||
}
|
||||
/// The leading number of the text of a sysfs file (`topology/core_id`, `cpu_capacity`), -1 when there is none.
|
||||
pub(super) fn parse_leading_number(text: &str) -> i64 {
|
||||
text.split_whitespace().next().and_then(|word| word.parse().ok()).unwrap_or(-1)
|
||||
}
|
||||
fn read_cpu(cpu: i32, key: &str) -> i64 {
|
||||
std::fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/{key}"))
|
||||
.map_or(-1, |text| parse_leading_number(&text))
|
||||
.ok()
|
||||
.and_then(|s| s.split_whitespace().next()?.parse().ok())
|
||||
.unwrap_or(-1)
|
||||
}
|
||||
/// The logical CPUs set in a `cpu_set_t`-sized mask, ascending.
|
||||
pub(super) fn mask_cpus(set: &[usize; 16]) -> Vec<i32> {
|
||||
(0..1024).filter(|i| set[i / 64] & (1usize << (i % 64)) != 0).map(|i| i as i32).collect()
|
||||
}
|
||||
/// The logical CPUs this process may run on: its affinity mask, else every CPU `sysconf` counts.
|
||||
/// The CPUs this process may run on (affinity mask, else every configured processor).
|
||||
fn allowed_cpus() -> Vec<i32> {
|
||||
let mut set = [0usize; 16];
|
||||
let mut allowed = Vec::new();
|
||||
// SAFETY: initialized Linux cpu_set_t-sized mask, no pointer retention.
|
||||
if unsafe { sched_getaffinity(0, std::mem::size_of_val(&set), set.as_mut_ptr()) } == 0 {
|
||||
return mask_cpus(&set);
|
||||
for i in 0..1024 {
|
||||
if set[i / 64] & (1usize << (i % 64)) != 0 {
|
||||
allowed.push(i as i32);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// SAFETY: sysconf(_SC_NPROCESSORS_CONF) reads no caller memory.
|
||||
let n = unsafe { sysconf(84) };
|
||||
for i in 0..n.max(0) {
|
||||
allowed.push(i as i32);
|
||||
}
|
||||
}
|
||||
// SAFETY: `sysconf` takes an integer name and touches no memory of this process (84 = _SC_NPROCESSORS_CONF).
|
||||
let n = unsafe { sysconf(84) };
|
||||
(0..n.max(0)).map(|i| i as i32).collect()
|
||||
allowed
|
||||
}
|
||||
/// The first logical CPU of every (package, core) pair, in the order of `allowed`; a CPU whose ids are unreadable
|
||||
/// (negative) counts as a core of its own. `ids_of` gives the (package, core) ids of a CPU.
|
||||
pub(super) fn first_cpu_of_each_core(allowed: &[i32], ids_of: impl Fn(i32) -> (i64, i64)) -> Vec<i32> {
|
||||
pub(super) fn cores(skip_first: bool) -> Vec<i32> {
|
||||
let mut seen = Vec::new();
|
||||
let mut physical = Vec::new();
|
||||
for &cpu in allowed {
|
||||
let key = ids_of(cpu);
|
||||
for cpu in allowed_cpus() {
|
||||
let key = (read_cpu(cpu, "physical_package_id"), read_cpu(cpu, "core_id"));
|
||||
if key.0 >= 0 && key.1 >= 0 {
|
||||
if seen.contains(&key) {
|
||||
continue;
|
||||
@@ -102,12 +101,6 @@ pub(super) fn first_cpu_of_each_core(allowed: &[i32], ids_of: impl Fn(i32) -> (i
|
||||
}
|
||||
physical.push(cpu);
|
||||
}
|
||||
physical
|
||||
}
|
||||
pub(super) fn cores(skip_first: bool) -> Vec<i32> {
|
||||
let allowed = allowed_cpus();
|
||||
let mut physical =
|
||||
first_cpu_of_each_core(&allowed, |cpu| (read_cpu(cpu, "physical_package_id"), read_cpu(cpu, "core_id")));
|
||||
if skip_first && !physical.is_empty() {
|
||||
physical.remove(0);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! `#[cfg_attr(windows, path = "rust_platform_win.rs")]`.
|
||||
//!
|
||||
//! * Affinity is a 64-bit mask of the processor group the process starts in (this port targets machines with at most
|
||||
//! 64 logical processors; a larger machine simply uses its first group). `current_affinity` returns the mask in
|
||||
//! word 0 of the same 16-word array the Linux code uses.
|
||||
//! 64 logical processors; a larger machine simply uses its first group). `current_affinity` returns the mask in word 0
|
||||
//! of the same 16-word array the Linux code uses.
|
||||
//! * `will_need` is `PrefetchVirtualMemory`: the memory manager starts reading a file-mapped range in the background.
|
||||
//! Advice only; failure changes nothing.
|
||||
//! * `cores` lists the first logical processor of every physical core (SMT siblings are skipped), like the Linux
|
||||
@@ -30,8 +30,7 @@ fn process_mask() -> Option<usize> {
|
||||
.then_some(process)
|
||||
}
|
||||
|
||||
/// Pure: the first set bit of every group of sibling bits (`cores` are the per-physical-core masks), restricted to
|
||||
/// `allowed`.
|
||||
/// Pure: the first set bit of every group of sibling bits (`cores` are the per-physical-core masks), restricted to `allowed`.
|
||||
pub(super) fn first_of_each_core(core_masks: &[usize], allowed: usize) -> Vec<i32> {
|
||||
let mut out: Vec<i32> = core_masks
|
||||
.iter()
|
||||
@@ -78,8 +77,8 @@ pub(super) fn cores(skip_first: bool) -> Vec<i32> {
|
||||
physical
|
||||
}
|
||||
|
||||
/// `PrefetchVirtualMemory` over `[addr, addr+len)` rounded out to pages: advice only, it never reads or writes the
|
||||
/// range through a Rust reference, so any address is memory-safe (an unmapped range just fails).
|
||||
/// `PrefetchVirtualMemory` over `[addr, addr+len)` rounded out to pages: advice only, it never reads or writes the range
|
||||
/// through a Rust reference, so any address is memory-safe (an unmapped range just fails).
|
||||
pub fn advise_will_need(addr: usize, len: usize) {
|
||||
if len == 0 {
|
||||
return;
|
||||
|
||||
@@ -76,9 +76,8 @@ struct Shared {
|
||||
_single_split: Vec<SingleSplit>,
|
||||
}
|
||||
/// `LELEKA_POOL_TIMING=1`: wall time of the host's stages of `compute_borrowed`, summed over calls until taken (ms):
|
||||
/// 0 pre (validation, token quantization, job table), 1-5 gate/up phase (park wait before, publish, host drain, wait
|
||||
/// done, park wait after), 6 host requantization, 7-11 down phase (same five), 12 post (output check). Off: no clock is
|
||||
/// read.
|
||||
/// 0 pre (validation, token quantization, job table), 1-5 gate/up phase (park wait before, publish, host drain, wait done, park wait after),
|
||||
/// 6 host requantization, 7-11 down phase (same five), 12 post (output check). Off: no clock is read.
|
||||
pub const TIMING_STAGES: usize = 13;
|
||||
pub(super) struct NativePool {
|
||||
shared: Arc<Shared>,
|
||||
@@ -86,15 +85,15 @@ pub(super) struct NativePool {
|
||||
timing: Option<[f64; TIMING_STAGES]>,
|
||||
}
|
||||
|
||||
mod exec;
|
||||
mod impl_default_for_nativeact;
|
||||
#[allow(unused_imports)]
|
||||
use impl_default_for_nativeact::all_finite;
|
||||
#[allow(unused_imports)]
|
||||
use impl_default_for_nativeact::allocated;
|
||||
mod execute_rows;
|
||||
mod impl_shared;
|
||||
mod stage;
|
||||
#[allow(unused_imports)]
|
||||
use impl_shared::tasks_per_thread;
|
||||
mod borrowed_group;
|
||||
mod impl_nativepool;
|
||||
mod impl_nativepool_2;
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
//! The stages of `NativePool::compute_borrowed` that are not the dispatch itself: the admission of a borrowed group
|
||||
//! (shape, extents, pair bounds, disjoint destination rows), the quantization of its tokens, the job table, and the
|
||||
//! check of its output. Moved out of `impl_nativepool_2.rs` by STRA-338 (size); the checks run in the original order.
|
||||
|
||||
use super::super::{BorrowedExpert, BorrowedGroup, MAX_OUT_ROWS};
|
||||
use super::impl_nativepool::{check_extents, quantize_q2_act};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// True when the group and the output have admissible dimensions: 1..=MAX_JOBS experts, 1..=MAX_ROWS whole tokens,
|
||||
/// a stride, whole output rows.
|
||||
fn check_group_dims(group: &BorrowedGroup<'_>, out_len: usize) -> bool {
|
||||
(1..=MAX_JOBS).contains(&group.experts.len())
|
||||
&& group.tokens.len().is_multiple_of(H)
|
||||
&& (1..=MAX_ROWS).contains(&(group.tokens.len() / H))
|
||||
&& group.stride != 0
|
||||
&& out_len.is_multiple_of(H)
|
||||
}
|
||||
|
||||
/// The destination rows claimed so far by the pairs of a group, and the tokens some pair uses.
|
||||
struct Claims {
|
||||
written: [u64; MAX_OUT_ROWS / 64],
|
||||
used: [bool; MAX_ROWS],
|
||||
ntok: usize,
|
||||
stride: usize,
|
||||
out_rows: usize,
|
||||
}
|
||||
|
||||
impl Claims {
|
||||
fn new(ntok: usize, stride: usize, out_rows: usize) -> Self {
|
||||
Self { written: [0u64; MAX_OUT_ROWS / 64], used: [false; MAX_ROWS], ntok, stride, out_rows }
|
||||
}
|
||||
/// Claims output row `token * stride + slot`: in bounds and not claimed before, else `Shape`.
|
||||
fn claim(&mut self, token: usize, slot: usize) -> Result<()> {
|
||||
if token >= self.ntok || slot >= self.stride {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let row = token.checked_mul(self.stride).and_then(|r| r.checked_add(slot)).ok_or(Error::Shape)?;
|
||||
if row >= self.out_rows || self.written[row / 64] >> (row % 64) & 1 != 0 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
self.written[row / 64] |= 1 << (row % 64);
|
||||
self.used[token] = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One expert of a group: its extents, its 1..=MAX_ROWS pairs, and the claim of every pair destination row.
|
||||
fn validate_expert(f: &NativeFmt, x: &BorrowedExpert<'_>, claims: &mut Claims) -> Result<()> {
|
||||
if !check_extents(x, f) || !(1..=MAX_ROWS).contains(&x.pairs.len()) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
for &(token, slot) in x.pairs {
|
||||
claims.claim(token, slot)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates the ENTIRE group (dimensions, extents, pair bounds, disjoint destinations); returns the tokens in use.
|
||||
pub(super) fn admit_group(f: &NativeFmt, group: &BorrowedGroup<'_>, out_len: usize) -> Result<[bool; MAX_ROWS]> {
|
||||
if !check_group_dims(group, out_len) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let ntok = group.tokens.len() / H;
|
||||
let out_rows = out_len / H;
|
||||
if out_rows > MAX_OUT_ROWS {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let mut claims = Claims::new(ntok, group.stride, out_rows);
|
||||
for x in group.experts {
|
||||
validate_expert(f, x, &mut claims)?;
|
||||
}
|
||||
Ok(claims.used)
|
||||
}
|
||||
|
||||
/// `NonFinite` when any destination row of any pair of `out` holds a non-finite value.
|
||||
pub(super) fn validate_group_output(group: &BorrowedGroup<'_>, out: &[f32]) -> Result<()> {
|
||||
for x in group.experts {
|
||||
for &(token, slot) in x.pairs {
|
||||
let at = (token * group.stride + slot) * H;
|
||||
if !all_finite(&out[at..at + H]) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Quantizes every used token of the group once: Q8 (one) for Q2_0 gate/up matrices, Q8_K otherwise.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2 (and AVX-512 when `dispatch().avx512`) admitted by `NativePool::new`; `tokens.len() <= MAX_ROWS * H`.
|
||||
pub(super) unsafe fn quantize_tokens(
|
||||
f: &NativeFmt,
|
||||
tokens: &[f32],
|
||||
used: &[bool; MAX_ROWS],
|
||||
ta: &mut [ActQ; MAX_ROWS],
|
||||
tn: &mut [NativeAct; MAX_ROWS],
|
||||
) {
|
||||
unsafe {
|
||||
for t in (0..tokens.len() / H).filter(|&t| used[t]) {
|
||||
let x = &tokens[t * H..(t + 1) * H];
|
||||
if f.gu == 42 {
|
||||
quantize_q2_act(x, &mut ta[t]);
|
||||
} else if super::super::rust_quant::q8k_fast() {
|
||||
super::super::rust_quant::q8_k_avx2(x, &mut tn[t].q);
|
||||
} else {
|
||||
super::super::rust_quant::q8_k(x, &mut tn[t].q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The job of one expert of a group: its matrices in place, and per pair the activation of the token and the
|
||||
/// output row.
|
||||
///
|
||||
/// # Safety
|
||||
/// `base` points at the output of the group, which has a row `token * stride + slot` for every pair.
|
||||
pub(super) unsafe fn describe_expert(
|
||||
x: &BorrowedExpert<'_>,
|
||||
ta: &[ActQ; MAX_ROWS],
|
||||
tn: &[NativeAct; MAX_ROWS],
|
||||
base: *mut f32,
|
||||
stride: usize,
|
||||
) -> Job {
|
||||
unsafe {
|
||||
let mut job = Job {
|
||||
gate: x.gate.as_ptr(),
|
||||
up: x.up.as_ptr(),
|
||||
down: x.down.as_ptr(),
|
||||
rows: x.pairs.len() as i32,
|
||||
..Job::default()
|
||||
};
|
||||
for (t, &(token, slot)) in x.pairs.iter().enumerate() {
|
||||
job.act[t] = ta.as_ptr().add(token);
|
||||
job.nact[t] = tn.as_ptr().add(token).cast();
|
||||
job.output[t] = base.add((token * stride + slot) * H);
|
||||
}
|
||||
job
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
//! STRA-338 size4: the body of `Shared::execute`, split by phase (prefault, gate/up, down).
|
||||
|
||||
use super::super::rust_simd::Dispatch;
|
||||
use super::super::rust_types::{NativeHidden, Q8Zero};
|
||||
use super::super::{rust_iq, rust_q2};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// One claimed row interval `[r0, r1)` of expert `e` of the published batch.
|
||||
struct Span<'a> {
|
||||
j: Job,
|
||||
f: NativeFmt,
|
||||
gate: &'a [u8],
|
||||
up: &'a [u8],
|
||||
down: &'a [u8],
|
||||
slot: *mut SplitBuf,
|
||||
nr: usize,
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
}
|
||||
|
||||
/// The multi-token IQ kernel family for a gate/up kind (decided once per row, as the open-coded chain was).
|
||||
enum IqPath {
|
||||
Multi512,
|
||||
Multi256,
|
||||
Single,
|
||||
}
|
||||
|
||||
fn iq_path(gu: i32, nr: usize, d: &Dispatch) -> IqPath {
|
||||
let multi = (nr as i32) >= d.mt_min;
|
||||
let family = matches!(gu, 16 | 17 | 18 | 21 | 22);
|
||||
if multi && family && d.iq512 {
|
||||
IqPath::Multi512
|
||||
} else if multi && (family || gu == 23 && !d.avx512) && d.iq256 {
|
||||
IqPath::Multi256
|
||||
} else {
|
||||
IqPath::Single
|
||||
}
|
||||
}
|
||||
|
||||
/// Q2 dot of one weight row against the activations (AVX-512 or AVX2 path).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `rust_q2::dot256/dot512`: `row.len() <= 720`, `a.len() <= 8`, `r.len() == a.len()`.
|
||||
unsafe fn q2_dot(row: &[u8], a: &[&ActQ], r: &mut [f32]) {
|
||||
unsafe {
|
||||
if dispatch().avx512 {
|
||||
rust_q2::dot512(row, a, r);
|
||||
} else {
|
||||
rust_q2::dot256(row, a, r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// # Safety
|
||||
/// The caller holds a successful epoch-tagged claim of task `i` (so `batch` is published and immutable, and every
|
||||
/// gate/up/down/activation/output pointer in `batch.jobs[..count]` is live until the done+parked barriers). Task `i`
|
||||
/// owns the row interval `[rows*i/tasks, rows*(i+1)/tasks)`; `rows == count*per` so `at/per < count` for every row.
|
||||
pub(super) unsafe fn execute(&self, i: usize) {
|
||||
unsafe {
|
||||
let b = &*self.batch.get();
|
||||
let per = match b.mode {
|
||||
5 => FF,
|
||||
6 => H,
|
||||
_ => 2 * FF + H,
|
||||
};
|
||||
let mut at = b.rows * i / b.tasks;
|
||||
let end = b.rows * (i + 1) / b.tasks;
|
||||
while at < end {
|
||||
let e = at / per;
|
||||
debug_assert!(e < b.count);
|
||||
let r0 = at % per;
|
||||
let r1 = per.min(r0 + end - at);
|
||||
let sp = self.span(b, e, r0, r1);
|
||||
match b.mode {
|
||||
7 => prefault_span(&sp),
|
||||
5 => gate_up_span(&sp),
|
||||
_ => down_span(&sp),
|
||||
}
|
||||
at += r1 - r0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// As `execute`: `e < b.count` and the claim covers rows `r0..r1` of expert `e`.
|
||||
unsafe fn span<'a>(&self, b: &'a Batch, e: usize, r0: usize, r1: usize) -> Span<'a> {
|
||||
unsafe {
|
||||
let j = b.jobs[e];
|
||||
let f = b.format;
|
||||
Span {
|
||||
j,
|
||||
f,
|
||||
gate: std::slice::from_raw_parts(j.gate, f.up_off),
|
||||
up: std::slice::from_raw_parts(j.up, f.up_off),
|
||||
down: std::slice::from_raw_parts(j.down, f.bytes - f.down_off),
|
||||
slot: self.split[e].get(),
|
||||
nr: j.rows as usize,
|
||||
r0,
|
||||
r1,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Prefault: read the first and the last byte of every encoded row (rows are contiguous, so every page).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute` for the claimed span.
|
||||
unsafe fn prefault_span(sp: &Span) {
|
||||
unsafe {
|
||||
let f = &sp.f;
|
||||
for r in sp.r0..sp.r1 {
|
||||
let row = if r < FF {
|
||||
&sp.gate[r * f.gu_row..(r + 1) * f.gu_row]
|
||||
} else if r < 2 * FF {
|
||||
&sp.up[(r - FF) * f.gu_row..(r - FF + 1) * f.gu_row]
|
||||
} else {
|
||||
&sp.down[(r - 2 * FF) * f.down_row..(r - 2 * FF + 1) * f.down_row]
|
||||
};
|
||||
std::ptr::read_volatile(row.as_ptr());
|
||||
std::ptr::read_volatile(row.as_ptr().add(row.len() - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mode 5: gate and up rows, fused with the SiLU product into the split `ff` buffer.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute` for the claimed span.
|
||||
unsafe fn gate_up_span(sp: &Span) {
|
||||
unsafe {
|
||||
let f = &sp.f;
|
||||
let nr = sp.nr;
|
||||
let mut g = [0.0f32; MAX_ROWS];
|
||||
let mut u = [0.0f32; MAX_ROWS];
|
||||
for r in sp.r0..sp.r1 {
|
||||
let gr = &sp.gate[r * f.gu_row..(r + 1) * f.gu_row];
|
||||
let ur = &sp.up[r * f.gu_row..(r + 1) * f.gu_row];
|
||||
if f.gu == 42 {
|
||||
q2_gate_up(sp, gr, ur, &mut g, &mut u);
|
||||
} else {
|
||||
iq_gate_up(sp, gr, ur, &mut g, &mut u);
|
||||
}
|
||||
let dst = std::ptr::addr_of_mut!((*sp.slot).ff).cast::<f32>();
|
||||
for t in 0..nr {
|
||||
dst.add(t * FF + r).write(silu(g[t], u[t]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// As `gate_up_span`, for one gate/up row pair.
|
||||
unsafe fn q2_gate_up(sp: &Span, gr: &[u8], ur: &[u8], g: &mut [f32; MAX_ROWS], u: &mut [f32; MAX_ROWS]) {
|
||||
unsafe {
|
||||
let nr = sp.nr;
|
||||
let mut aa = [&*sp.j.act[0]; MAX_ROWS];
|
||||
for t in 0..nr {
|
||||
aa[t] = &*sp.j.act[t];
|
||||
}
|
||||
q2_dot(gr, &aa[..nr], &mut g[..nr]);
|
||||
q2_dot(ur, &aa[..nr], &mut u[..nr]);
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// As `gate_up_span`, for one gate/up row pair.
|
||||
unsafe fn iq_gate_up(sp: &Span, gr: &[u8], ur: &[u8], g: &mut [f32; MAX_ROWS], u: &mut [f32; MAX_ROWS]) {
|
||||
unsafe {
|
||||
let (nr, gu) = (sp.nr, sp.f.gu);
|
||||
let mut yy = [(&*sp.j.nact[0].cast::<NativeAct>()).q.as_slice(); MAX_ROWS];
|
||||
for t in 0..nr {
|
||||
yy[t] = (&*sp.j.nact[t].cast::<NativeAct>()).q.as_slice();
|
||||
}
|
||||
match iq_path(gu, nr, dispatch()) {
|
||||
IqPath::Multi512 => {
|
||||
rust_iq::dot_multi512(gu, gr, &yy[..nr], &mut g[..nr]);
|
||||
rust_iq::dot_multi512(gu, ur, &yy[..nr], &mut u[..nr]);
|
||||
}
|
||||
IqPath::Multi256 => {
|
||||
rust_iq::dot_multi256(gu, gr, &yy[..nr], &mut g[..nr]);
|
||||
rust_iq::dot_multi256(gu, ur, &yy[..nr], &mut u[..nr]);
|
||||
}
|
||||
IqPath::Single => {
|
||||
for t in 0..nr {
|
||||
g[t] = rust_iq::dot_single(gu, gr, yy[t]);
|
||||
u[t] = rust_iq::dot_single(gu, ur, yy[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mode 6: down rows against the requantized split activations, written straight to the job outputs.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute` for the claimed span.
|
||||
unsafe fn down_span(sp: &Span) {
|
||||
unsafe {
|
||||
let f = &sp.f;
|
||||
let nr = sp.nr;
|
||||
let mut g = [0.0f32; MAX_ROWS];
|
||||
for r in sp.r0..sp.r1 {
|
||||
let row = &sp.down[r * f.down_row..(r + 1) * f.down_row];
|
||||
if f.down == 42 {
|
||||
q2_down(sp, row, &mut g);
|
||||
} else {
|
||||
iq_down(sp, row, &mut g);
|
||||
}
|
||||
for t in 0..nr {
|
||||
sp.j.output[t].add(r).write(g[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// As `down_span`, for one down row.
|
||||
unsafe fn q2_down(sp: &Span, row: &[u8], g: &mut [f32; MAX_ROWS]) {
|
||||
unsafe {
|
||||
let nr = sp.nr;
|
||||
let base = std::ptr::addr_of!((*sp.slot).a2).cast::<ActQ>();
|
||||
let mut aa = [&*base; MAX_ROWS];
|
||||
for t in 0..nr {
|
||||
aa[t] = &*base.add(t);
|
||||
}
|
||||
q2_dot(row, &aa[..nr], &mut g[..nr]);
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// As `down_span`, for one down row.
|
||||
unsafe fn iq_down(sp: &Span, row: &[u8], g: &mut [f32; MAX_ROWS]) {
|
||||
unsafe {
|
||||
let nr = sp.nr;
|
||||
let base = std::ptr::addr_of!((*sp.slot).hq).cast::<NativeHidden>();
|
||||
let empty: &[Q8Zero] = &[];
|
||||
let mut yy = [empty; MAX_ROWS];
|
||||
for t in 0..nr {
|
||||
yy[t] = &(*base.add(t)).q;
|
||||
}
|
||||
let d = dispatch();
|
||||
let single = (nr as i32) < d.mt_min || !d.iq4nl;
|
||||
rust_iq::iq4nl(row, &yy[..nr], &mut g[..nr], single);
|
||||
}
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
//! The row work of `Shared::execute`, split by stage: which rows a task owns, which segment of which expert a claimed
|
||||
//! interval falls in, then the prefault, gate/up or down rows of that segment. Moved out of `impl_shared.rs` by
|
||||
//! STRA-338 (size); the arithmetic and its order are those of the original.
|
||||
|
||||
use super::super::rust_simd::Dispatch;
|
||||
use super::super::rust_types::{NativeHidden, Q8Zero};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// `dot512` or `dot256` of the Q2_0 rows, by the process kernel family.
|
||||
///
|
||||
/// # Safety
|
||||
/// The AVX2 (and, when `dispatch().avx512`, AVX-512) capability that `NativePool::new` admitted;
|
||||
/// `a.len() == out.len()`.
|
||||
unsafe fn dot_q2(row: &[u8], a: &[&ActQ], out: &mut [f32]) {
|
||||
unsafe {
|
||||
if dispatch().avx512 {
|
||||
super::super::rust_q2::dot512(row, a, out);
|
||||
} else {
|
||||
super::super::rust_q2::dot256(row, a, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the IQ gate/up rows of `nr` tokens use the 512-bit multi-token kernel.
|
||||
fn check_iq_multi512(gu: i32, nr: usize, d: &Dispatch) -> bool {
|
||||
(nr as i32) >= d.mt_min && matches!(gu, 16 | 17 | 18 | 21 | 22) && d.iq512
|
||||
}
|
||||
|
||||
/// True when the IQ gate/up rows of `nr` tokens use the 256-bit multi-token kernel.
|
||||
fn check_iq_multi256(gu: i32, nr: usize, d: &Dispatch) -> bool {
|
||||
(nr as i32) >= d.mt_min && (matches!(gu, 16 | 17 | 18 | 21 | 22) || gu == 23 && !d.avx512) && d.iq256
|
||||
}
|
||||
|
||||
/// What one claimed segment (rows `r0..r1` of expert `e`) works on: the three encoded matrices of the expert, its job,
|
||||
/// its split cell and the batch.
|
||||
struct Segment<'a> {
|
||||
b: &'a Batch,
|
||||
j: Job,
|
||||
gate: &'a [u8],
|
||||
up: &'a [u8],
|
||||
down: &'a [u8],
|
||||
slot: *mut SplitBuf,
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// # Safety
|
||||
/// The caller holds a successful epoch-tagged claim of task `i` (so `batch` is published and immutable, and every
|
||||
/// gate/up/down/activation/output pointer in `batch.jobs[..count]` is live until the done+parked barriers). Task
|
||||
/// `i` owns the row interval `[rows*i/tasks, rows*(i+1)/tasks)`; `rows == count*per` so `at/per < count` for every
|
||||
/// row.
|
||||
pub(super) unsafe fn execute(&self, i: usize) {
|
||||
unsafe {
|
||||
let b = &*self.batch.get();
|
||||
let per = match b.mode {
|
||||
5 => FF,
|
||||
6 => H,
|
||||
_ => 2 * FF + H,
|
||||
};
|
||||
let mut at = b.rows * i / b.tasks;
|
||||
let end = b.rows * (i + 1) / b.tasks;
|
||||
while at < end {
|
||||
let e = at / per;
|
||||
debug_assert!(e < b.count);
|
||||
let r0 = at % per;
|
||||
let r1 = per.min(r0 + end - at);
|
||||
self.segment(b, e, r0, r1).run();
|
||||
at += r1 - r0;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The matrices, job and split cell of expert `e` for rows `r0..r1`.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `execute`; `e < count`.
|
||||
unsafe fn segment<'a>(&self, b: &'a Batch, e: usize, r0: usize, r1: usize) -> Segment<'a> {
|
||||
unsafe {
|
||||
let j = b.jobs[e];
|
||||
let f = b.format;
|
||||
let gate = std::slice::from_raw_parts(j.gate, f.up_off);
|
||||
let up = std::slice::from_raw_parts(j.up, f.up_off);
|
||||
let down = std::slice::from_raw_parts(j.down, f.bytes - f.down_off);
|
||||
let slot = self.split[e].get();
|
||||
Segment { b, j, gate, up, down, slot, r0, r1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Segment<'_> {
|
||||
/// The rows of the segment in the mode of the batch: 7 prefault, 5 gate/up, otherwise down.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`.
|
||||
unsafe fn run(&self) {
|
||||
unsafe {
|
||||
match self.b.mode {
|
||||
7 => self.prefault_rows(),
|
||||
5 => self.gate_up_rows(),
|
||||
_ => self.down_rows(),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The encoded row `r` of the concatenation gate | up | down (mode 7 walks all three matrices).
|
||||
fn prefault_row(&self, r: usize) -> &[u8] {
|
||||
let f = self.b.format;
|
||||
if r < FF {
|
||||
&self.gate[r * f.gu_row..(r + 1) * f.gu_row]
|
||||
} else if r < 2 * FF {
|
||||
&self.up[(r - FF) * f.gu_row..(r - FF + 1) * f.gu_row]
|
||||
} else {
|
||||
&self.down[(r - 2 * FF) * f.down_row..(r - 2 * FF + 1) * f.down_row]
|
||||
}
|
||||
}
|
||||
/// Prefault: read the first and the last byte of every encoded row (rows are contiguous, so every page).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`.
|
||||
unsafe fn prefault_rows(&self) {
|
||||
unsafe {
|
||||
for r in self.r0..self.r1 {
|
||||
let row = self.prefault_row(r);
|
||||
std::ptr::read_volatile(row.as_ptr());
|
||||
std::ptr::read_volatile(row.as_ptr().add(row.len() - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Mode 5: the gate and up rows of every token, `silu(gate, up)` into the hidden rows of the split cell.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`.
|
||||
unsafe fn gate_up_rows(&self) {
|
||||
unsafe {
|
||||
let f = self.b.format;
|
||||
let nr = self.j.rows as usize;
|
||||
let mut g = [0.0f32; MAX_ROWS];
|
||||
let mut u = [0.0f32; MAX_ROWS];
|
||||
for r in self.r0..self.r1 {
|
||||
let gr = &self.gate[r * f.gu_row..(r + 1) * f.gu_row];
|
||||
let ur = &self.up[r * f.gu_row..(r + 1) * f.gu_row];
|
||||
if f.gu == 42 {
|
||||
self.q2_gate_up(gr, ur, &mut g[..nr], &mut u[..nr]);
|
||||
} else {
|
||||
self.iq_gate_up(gr, ur, &mut g[..nr], &mut u[..nr]);
|
||||
}
|
||||
let dst = std::ptr::addr_of_mut!((*self.slot).ff).cast::<f32>();
|
||||
for t in 0..nr {
|
||||
dst.add(t * FF + r).write(silu(g[t], u[t]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Q2_0 gate and up rows against the quantized tokens (`g`, `u` have one value per token).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`.
|
||||
unsafe fn q2_gate_up(&self, gr: &[u8], ur: &[u8], g: &mut [f32], u: &mut [f32]) {
|
||||
unsafe {
|
||||
let nr = g.len();
|
||||
let mut aa = [&*self.j.act[0]; MAX_ROWS];
|
||||
for (t, slot) in aa.iter_mut().enumerate().take(nr) {
|
||||
*slot = &*self.j.act[t];
|
||||
}
|
||||
dot_q2(gr, &aa[..nr], g);
|
||||
dot_q2(ur, &aa[..nr], u);
|
||||
}
|
||||
}
|
||||
/// IQ and K-quant gate and up rows: the multi-token kernels when the tokens and the CPU admit them, else per token.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`.
|
||||
unsafe fn iq_gate_up(&self, gr: &[u8], ur: &[u8], g: &mut [f32], u: &mut [f32]) {
|
||||
unsafe {
|
||||
let gu = self.b.format.gu;
|
||||
let nr = g.len();
|
||||
let mut yy = [(&*self.j.nact[0].cast::<NativeAct>()).q.as_slice(); MAX_ROWS];
|
||||
for (t, slot) in yy.iter_mut().enumerate().take(nr) {
|
||||
*slot = (&*self.j.nact[t].cast::<NativeAct>()).q.as_slice();
|
||||
}
|
||||
let d = dispatch();
|
||||
if check_iq_multi512(gu, nr, d) {
|
||||
super::super::rust_iq::dot_multi512(gu, gr, &yy[..nr], g);
|
||||
super::super::rust_iq::dot_multi512(gu, ur, &yy[..nr], u);
|
||||
} else if check_iq_multi256(gu, nr, d) {
|
||||
super::super::rust_iq::dot_multi256(gu, gr, &yy[..nr], g);
|
||||
super::super::rust_iq::dot_multi256(gu, ur, &yy[..nr], u);
|
||||
} else {
|
||||
for t in 0..nr {
|
||||
g[t] = super::super::rust_iq::dot_single(gu, gr, yy[t]);
|
||||
u[t] = super::super::rust_iq::dot_single(gu, ur, yy[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Mode 6: the down rows of every token, written to the output rows of the job.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`.
|
||||
unsafe fn down_rows(&self) {
|
||||
unsafe {
|
||||
let f = self.b.format;
|
||||
let j = self.j;
|
||||
let nr = j.rows as usize;
|
||||
let mut g = [0.0f32; MAX_ROWS];
|
||||
for r in self.r0..self.r1 {
|
||||
let row = &self.down[r * f.down_row..(r + 1) * f.down_row];
|
||||
if f.down == 42 {
|
||||
self.q2_down(row, &mut g[..nr]);
|
||||
} else {
|
||||
self.iq4nl_down(row, &mut g[..nr]);
|
||||
}
|
||||
for (t, &v) in g.iter().enumerate().take(nr) {
|
||||
j.output[t].add(r).write(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A Q2_0 down row against the requantized hidden rows (`g` has one value per token).
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`.
|
||||
unsafe fn q2_down(&self, row: &[u8], g: &mut [f32]) {
|
||||
unsafe {
|
||||
let nr = g.len();
|
||||
let base = std::ptr::addr_of!((*self.slot).a2).cast::<ActQ>();
|
||||
let mut aa = [&*base; MAX_ROWS];
|
||||
for (t, slot) in aa.iter_mut().enumerate().take(nr) {
|
||||
*slot = &*base.add(t);
|
||||
}
|
||||
dot_q2(row, &aa[..nr], g);
|
||||
}
|
||||
}
|
||||
/// An IQ4_NL down row against the requantized hidden rows.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `Shared::execute`.
|
||||
unsafe fn iq4nl_down(&self, row: &[u8], g: &mut [f32]) {
|
||||
unsafe {
|
||||
let nr = g.len();
|
||||
let base = std::ptr::addr_of!((*self.slot).hq).cast::<NativeHidden>();
|
||||
let empty: &[Q8Zero] = &[];
|
||||
let mut yy = [empty; MAX_ROWS];
|
||||
for (t, slot) in yy.iter_mut().enumerate().take(nr) {
|
||||
*slot = &(*base.add(t)).q;
|
||||
}
|
||||
let d = dispatch();
|
||||
let single = (nr as i32) < d.mt_min || !d.iq4nl;
|
||||
super::super::rust_iq::iq4nl(row, &yy[..nr], g, single);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Moved out of the parent module by STRA-338: the Default impls of the pool cells, Sync/Send of Shared, helpers.
|
||||
//! Moved out of the parent module by STRA-338: impl Default_for_NativeAct, impl Default_for_Scratch, impl Default_for_Job, impl Default_for_SingleSplit, impl Sync_for_Shared, impl Send_for_Shared ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -41,8 +41,7 @@ impl Default for SingleSplit {
|
||||
// panicking worker never reaches `done`, so the host aborts after 60 s instead of returning to the caller.
|
||||
unsafe impl Sync for Shared {}
|
||||
unsafe impl Send for Shared {}
|
||||
/// `!any(|v| !v.is_finite())` as a branch-free exponent fold that vectorizes (`LELEKA_Q8K=legacy` keeps the
|
||||
/// element-wise scan).
|
||||
/// `!any(|v| !v.is_finite())` as a branch-free exponent fold that vectorizes (`LELEKA_Q8K=legacy` keeps the element-wise scan).
|
||||
pub(super) fn all_finite(v: &[f32]) -> bool {
|
||||
if !super::super::rust_quant::q8k_fast() {
|
||||
return !v.iter().any(|x| !x.is_finite());
|
||||
|
||||
@@ -3,186 +3,78 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The CPU capability the pool needs: AVX2, and the AVX-512 DQ extension when AVX-512 is on.
|
||||
fn require_cpu_features() -> Result<()> {
|
||||
if !super::super::rust_simd::avx2_ok() || super::super::rust_simd::avx512_ok() && !super::super::rust_simd::dq_ok()
|
||||
{
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The worker count: `workers` when positive, else one per physical core (at most 15).
|
||||
fn pool_size(workers: i32, cores: &[i32]) -> Result<usize> {
|
||||
if workers == 0 && cores.len() > 15 {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
Ok(if workers > 0 { workers as usize } else { cores.len().max(1) })
|
||||
}
|
||||
|
||||
/// How long an idle worker spins before it sleeps: `STRATA_POOL_SPIN_US` microseconds, else 20 ms.
|
||||
fn spin_from_env() -> Duration {
|
||||
std::env::var("STRATA_POOL_SPIN_US")
|
||||
.map(|s| Duration::from_micros(super::super::rust_simd::atoi(&s).max(0) as u64))
|
||||
.unwrap_or(Duration::from_millis(20))
|
||||
}
|
||||
|
||||
/// `LELEKA_POOL_TIMING=1`: the stage accumulators of the host, zeroed.
|
||||
fn timing_from_env() -> Option<[f64; TIMING_STAGES]> {
|
||||
std::env::var("LELEKA_POOL_TIMING").is_ok_and(|v| v == "1").then_some([0.0; TIMING_STAGES])
|
||||
}
|
||||
|
||||
/// The shared state of a pool of `n` workers: the claim/park words and all scratch cells, allocated fallibly.
|
||||
fn new_shared(n: usize, spin: Duration) -> Result<Arc<Shared>> {
|
||||
Ok(Arc::new(Shared {
|
||||
head: Line(AtomicU64::new(0)),
|
||||
done: Line(AtomicU32::new(0)),
|
||||
parked: Line(AtomicU32::new(0)),
|
||||
epoch: Line(AtomicU32::new(0)),
|
||||
stop: Line(AtomicBool::new(false)),
|
||||
sleepers: Line(AtomicU32::new(0)),
|
||||
sleep_mu: Mutex::new(()),
|
||||
sleep_cv: Condvar::new(),
|
||||
spin,
|
||||
n,
|
||||
batch: UnsafeCell::new(Batch {
|
||||
jobs: [Job::default(); MAX_JOBS],
|
||||
format: NativeFmt::new(18, 42)?,
|
||||
count: 0,
|
||||
mode: 0,
|
||||
rows: 0,
|
||||
tasks: 1,
|
||||
}),
|
||||
act: allocated(MAX_JOBS)?,
|
||||
nact: allocated(MAX_JOBS)?,
|
||||
split: allocated(MAX_JOBS)?,
|
||||
tok_act: allocated(1)?,
|
||||
tok_nact: allocated(1)?,
|
||||
_scratch: allocated(n + 1)?,
|
||||
_single_split: allocated(16)?,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The instants at the six stage boundaries of one phase (`None` when timing is off: no clock is read).
|
||||
struct Laps {
|
||||
on: bool,
|
||||
t: [Option<Instant>; 6],
|
||||
}
|
||||
impl Laps {
|
||||
fn new(on: bool) -> Self {
|
||||
Self { on, t: [None; 6] }
|
||||
}
|
||||
fn lap(&mut self, i: usize) {
|
||||
if self.on {
|
||||
self.t[i] = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
/// Adds the five stage durations to `acc[at..at + 5]` (ms).
|
||||
fn add_to(&self, acc: &mut [f64; TIMING_STAGES], at: usize) {
|
||||
for i in 0..5 {
|
||||
if let (Some(a), Some(b)) = (self.t[i], self.t[i + 1]) {
|
||||
acc[at + i] += b.duration_since(a).as_secs_f64() * 1e3;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the shapes of one owned job fit the format `f`.
|
||||
fn check_job_shape(j: &PreparedJob, f: &NativeFmt) -> bool {
|
||||
(1..=MAX_ROWS).contains(&j.rows)
|
||||
&& j.input.len() == j.rows * H
|
||||
&& j.output.len() == j.rows * H
|
||||
&& j.gate_bytes == f.up_off
|
||||
&& j.up_bytes == f.up_off
|
||||
&& j.down_bytes == f.bytes - f.down_off
|
||||
}
|
||||
|
||||
/// The format shared by every job of a batch, or `Shape` when the batch is empty, too long or mixed.
|
||||
fn batch_format(jobs: &[PreparedJob]) -> Result<NativeFmt> {
|
||||
if !(1..=MAX_JOBS).contains(&jobs.len()) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let gu = jobs[0].gu;
|
||||
let down = jobs[0].down;
|
||||
if jobs.iter().any(|j| j.gu != gu || j.down != down) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
NativeFmt::new(gu.kind(), down.kind())
|
||||
}
|
||||
|
||||
/// The shape and the finite input of one owned job.
|
||||
fn validate_batch_job(j: &PreparedJob, f: &NativeFmt) -> Result<()> {
|
||||
if !check_job_shape(j, f) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
if j.input.iter().any(|x| !x.is_finite()) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// True when the three matrices of a borrowed expert have the extents of the format `f`.
|
||||
pub(super) fn check_extents(x: &super::super::BorrowedExpert<'_>, f: &NativeFmt) -> bool {
|
||||
x.gate.len() == f.up_off && x.up.len() == f.up_off && x.down.len() == f.bytes - f.down_off
|
||||
}
|
||||
|
||||
/// Q8 quantization of one token for a Q2_0 matrix, by the process kernel family.
|
||||
///
|
||||
/// # Safety
|
||||
/// AVX2 (and AVX-512 when `dispatch().avx512`) admitted by `NativePool::new`.
|
||||
pub(super) unsafe fn quantize_q2_act(x: &[f32], a: &mut ActQ) {
|
||||
unsafe {
|
||||
if dispatch().avx512 {
|
||||
super::super::rust_quant::q8_one_avx512(x, a);
|
||||
} else {
|
||||
super::super::rust_quant::q8_one_avx2(x, a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Row `t` of a split cell: the hidden row requantized as the input of the down matrix.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `quantize_q2_act`.
|
||||
unsafe fn requantize_hidden_row(f: NativeFmt, s: &mut SplitBuf, t: usize) {
|
||||
unsafe {
|
||||
if f.down == 42 {
|
||||
quantize_q2_act(&s.ff[t], &mut s.a2[t]);
|
||||
} else {
|
||||
super::super::rust_quant::q8_zero(&s.ff[t], &mut s.hq[t].q);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NativePool {
|
||||
pub fn new(workers: i32) -> Result<Self> {
|
||||
/// Validate the worker request and the CPU; returns the worker stack size, the core list and the worker count.
|
||||
fn plan(workers: i32) -> Result<(usize, Vec<i32>, usize)> {
|
||||
if !(0..=15).contains(&workers) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let stack = super::super::rust_platform::stack_size()?;
|
||||
require_cpu_features()?;
|
||||
if !super::super::rust_simd::avx2_ok()
|
||||
|| super::super::rust_simd::avx512_ok() && !super::super::rust_simd::dq_ok()
|
||||
{
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
let cores = super::super::rust_platform::cores(true);
|
||||
let n = pool_size(workers, &cores)?;
|
||||
let shared = new_shared(n, spin_from_env())?;
|
||||
let mut out = Self { shared, workers: Vec::new(), timing: timing_from_env() };
|
||||
out.spawn_workers(n, &cores, stack)?;
|
||||
if workers == 0 && cores.len() > 15 {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
let n = if workers > 0 { workers as usize } else { cores.len().max(1) };
|
||||
Ok((stack, cores, n))
|
||||
}
|
||||
pub fn new(workers: i32) -> Result<Self> {
|
||||
let (stack, cores, n) = Self::plan(workers)?;
|
||||
let shared = Self::new_shared(n)?;
|
||||
let timing = std::env::var("LELEKA_POOL_TIMING").is_ok_and(|v| v == "1").then_some([0.0; TIMING_STAGES]);
|
||||
let mut out = Self { shared, workers: Vec::new(), timing };
|
||||
out.workers.try_reserve_exact(n).map_err(|_| Error::Allocation)?;
|
||||
for i in 0..n {
|
||||
let core = cores.get(i).copied().unwrap_or(-1);
|
||||
out.workers.push(Self::spawn_worker(Arc::clone(&out.shared), i, core, stack)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
/// Starts the `n` worker threads, worker `i` pinned to `cores[i]` when there is one; a failure returns with the
|
||||
/// pool dropped by the caller (stop + join).
|
||||
fn spawn_workers(&mut self, n: usize, cores: &[i32], stack: usize) -> Result<()> {
|
||||
self.workers.try_reserve_exact(n).map_err(|_| Error::Allocation)?;
|
||||
for i in 0..n {
|
||||
let shared = Arc::clone(&self.shared);
|
||||
let core = cores.get(i).copied().unwrap_or(-1);
|
||||
let handle = thread::Builder::new()
|
||||
.name(format!("strata-expert-{i}"))
|
||||
.stack_size(stack)
|
||||
.spawn(move || shared.worker(core))
|
||||
.map_err(|_| Error::Allocation)?;
|
||||
self.workers.push(handle);
|
||||
fn new_shared(n: usize) -> Result<Arc<Shared>> {
|
||||
let spin = std::env::var("STRATA_POOL_SPIN_US")
|
||||
.map(|s| Duration::from_micros(super::super::rust_simd::atoi(&s).max(0) as u64))
|
||||
.unwrap_or(Duration::from_millis(20));
|
||||
Ok(Arc::new(Shared {
|
||||
head: Line(AtomicU64::new(0)),
|
||||
done: Line(AtomicU32::new(0)),
|
||||
parked: Line(AtomicU32::new(0)),
|
||||
epoch: Line(AtomicU32::new(0)),
|
||||
stop: Line(AtomicBool::new(false)),
|
||||
sleepers: Line(AtomicU32::new(0)),
|
||||
sleep_mu: Mutex::new(()),
|
||||
sleep_cv: Condvar::new(),
|
||||
spin,
|
||||
n,
|
||||
batch: UnsafeCell::new(Self::empty_batch()?),
|
||||
act: allocated(MAX_JOBS)?,
|
||||
nact: allocated(MAX_JOBS)?,
|
||||
split: allocated(MAX_JOBS)?,
|
||||
tok_act: allocated(1)?,
|
||||
tok_nact: allocated(1)?,
|
||||
_scratch: allocated(n + 1)?,
|
||||
_single_split: allocated(16)?,
|
||||
}))
|
||||
}
|
||||
fn empty_batch() -> Result<Batch> {
|
||||
let format = NativeFmt::new(18, 42)?;
|
||||
Ok(Batch { jobs: [Job::default(); MAX_JOBS], format, count: 0, mode: 0, rows: 0, tasks: 1 })
|
||||
}
|
||||
/// Add the time since `t` (when timing is on) to timing stage `stage`.
|
||||
pub(super) fn lap_since(&mut self, t: Option<Instant>, stage: usize) {
|
||||
if let (Some(t), Some(acc)) = (t, self.timing.as_mut()) {
|
||||
acc[stage] += t.elapsed().as_secs_f64() * 1e3;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn spawn_worker(shared: Arc<Shared>, i: usize, core: i32, stack: usize) -> Result<thread::JoinHandle<()>> {
|
||||
thread::Builder::new()
|
||||
.name(format!("strata-expert-{i}"))
|
||||
.stack_size(stack)
|
||||
.spawn(move || shared.worker(core))
|
||||
.map_err(|_| Error::Allocation)
|
||||
}
|
||||
pub fn workers(&self) -> Result<usize> {
|
||||
Ok(self.workers.len())
|
||||
@@ -192,124 +84,108 @@ impl NativePool {
|
||||
}
|
||||
/// `at`: first of the five timing stages of this phase (ignored when timing is off).
|
||||
pub(super) fn phase_timed(&mut self, mode: u32, rows: usize, at: usize) {
|
||||
let mut laps = Laps::new(self.timing.is_some());
|
||||
laps.lap(0);
|
||||
let on = self.timing.is_some();
|
||||
let mut t = [None; 6];
|
||||
let mut lap = |i: usize| {
|
||||
if on {
|
||||
t[i] = Some(Instant::now());
|
||||
}
|
||||
};
|
||||
lap(0);
|
||||
self.shared.wait_parked();
|
||||
laps.lap(1);
|
||||
let (e, tasks) = self.open_phase(mode, rows);
|
||||
laps.lap(2);
|
||||
lap(1);
|
||||
let (e, tasks) = self.publish_phase(mode, rows);
|
||||
lap(2);
|
||||
self.shared.drain(e);
|
||||
laps.lap(3);
|
||||
lap(3);
|
||||
self.shared.wait_done(tasks);
|
||||
laps.lap(4);
|
||||
lap(4);
|
||||
self.shared.wait_parked();
|
||||
laps.lap(5);
|
||||
lap(5);
|
||||
if let Some(acc) = self.timing.as_mut() {
|
||||
laps.add_to(acc, at);
|
||||
for i in 0..5 {
|
||||
if let (Some(a), Some(b)) = (t[i], t[i + 1]) {
|
||||
acc[at + i] += b.duration_since(a).as_secs_f64() * 1e3;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Publishes the phase `mode` over `rows` rows of the loaded batch (workers parked); returns its epoch and tasks.
|
||||
fn open_phase(&mut self, mode: u32, rows: usize) -> (u32, usize) {
|
||||
/// Describe the phase in `batch` and publish it (workers parked); returns the epoch and the task count.
|
||||
fn publish_phase(&mut self, mode: u32, rows: usize) -> (u32, usize) {
|
||||
let tasks = tasks_per_thread() * (self.shared.n + 1);
|
||||
// SAFETY: wait_parked() by the caller proves every worker finished its previous drain and holds no claim, so
|
||||
// the host is the only accessor of `batch` until the Release store of `head` publishes it.
|
||||
// the host is the only accessor of `batch` until the Release store of `head` below publishes it.
|
||||
unsafe {
|
||||
let b = &mut *self.shared.batch.get();
|
||||
b.mode = mode;
|
||||
b.rows = rows;
|
||||
b.tasks = tasks;
|
||||
}
|
||||
(self.shared.open_epoch(tasks), tasks)
|
||||
self.shared.done.0.store(0, Ordering::Relaxed);
|
||||
let e = self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1);
|
||||
self.shared.head.0.store(((e as u64) << 32) | ((tasks as u64) << 16), Ordering::Release);
|
||||
self.shared.publish();
|
||||
(e, tasks)
|
||||
}
|
||||
/// The summed stage times since the last call (see `TIMING_STAGES`), zeroed; `None` when timing is off.
|
||||
pub fn take_timing(&mut self) -> Option<[f64; TIMING_STAGES]> {
|
||||
self.timing.as_mut().map(|t| std::mem::replace(t, [0.0; TIMING_STAGES]))
|
||||
}
|
||||
pub fn compute_batch(&mut self, jobs: &mut [PreparedJob]) -> Result<()> {
|
||||
let f = batch_format(jobs)?;
|
||||
// Validate the ENTIRE batch before touching quantized operands or publication.
|
||||
for j in jobs.iter() {
|
||||
validate_batch_job(j, &f)?;
|
||||
/// Shape/format agreement of the whole owned batch (checked before any operand is quantized or published).
|
||||
fn check_batch(jobs: &[PreparedJob], f: &NativeFmt) -> Result<()> {
|
||||
for j in jobs {
|
||||
if !(1..=MAX_ROWS).contains(&j.rows)
|
||||
|| j.input.len() != j.rows * H
|
||||
|| j.output.len() != j.rows * H
|
||||
|| j.gate_bytes != f.up_off
|
||||
|| j.up_bytes != f.up_off
|
||||
|| j.down_bytes != f.bytes - f.down_off
|
||||
{
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
if j.input.iter().any(|x| !x.is_finite()) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn compute_batch(&mut self, jobs: &mut [PreparedJob]) -> Result<()> {
|
||||
if !(1..=MAX_JOBS).contains(&jobs.len()) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let gu = jobs[0].gu;
|
||||
let down = jobs[0].down;
|
||||
if jobs.iter().any(|j| j.gu != gu || j.down != down) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let f = NativeFmt::new(gu.kind(), down.kind())?;
|
||||
// Validate the ENTIRE batch before touching quantized operands or publication.
|
||||
Self::check_batch(jobs, &f)?;
|
||||
self.shared.wait_parked();
|
||||
// SAFETY: all workers parked; jobs remain exclusively borrowed until both
|
||||
// phases finish and workers park again. NativePool::Drop joins before owners.
|
||||
unsafe {
|
||||
self.load_batch(jobs, f);
|
||||
}
|
||||
self.run_published(f, jobs.len());
|
||||
if jobs.iter().any(|j| j.output.iter().any(|v| !v.is_finite())) { Err(Error::NonFinite) } else { Ok(()) }
|
||||
}
|
||||
/// Describes every owned job in the batch and quantizes its input rows.
|
||||
///
|
||||
/// # Safety
|
||||
/// All workers parked; `jobs` stay borrowed until both phases finished and the workers parked again.
|
||||
unsafe fn load_batch(&mut self, jobs: &mut [PreparedJob], f: NativeFmt) {
|
||||
unsafe {
|
||||
let b = &mut *self.shared.batch.get();
|
||||
b.format = f;
|
||||
b.count = jobs.len();
|
||||
for (e, j) in jobs.iter_mut().enumerate() {
|
||||
self.describe_job(b, e, j, f);
|
||||
self.shared.describe_owned(b, e, j, f);
|
||||
}
|
||||
}
|
||||
self.run_published(f, jobs.len());
|
||||
if jobs.iter().any(|j| j.output.iter().any(|v| !v.is_finite())) { Err(Error::NonFinite) } else { Ok(()) }
|
||||
}
|
||||
/// Job `e` of the batch: the three matrices of the blob, the output rows and the quantized input rows.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `load_batch`.
|
||||
unsafe fn describe_job(&self, b: &mut Batch, e: usize, j: &mut PreparedJob, f: NativeFmt) {
|
||||
unsafe {
|
||||
let p = j.blob.as_ptr();
|
||||
b.jobs[e] =
|
||||
Job { gate: p, up: p.add(f.up_off), down: p.add(f.down_off), rows: j.rows as i32, ..Job::default() };
|
||||
for t in 0..j.rows {
|
||||
let x = &j.input[t * H..(t + 1) * H];
|
||||
b.jobs[e].output[t] = j.output.as_mut_ptr().add(t * H);
|
||||
b.jobs[e].act[t] = (*self.shared.act[e].get()).as_ptr().add(t);
|
||||
b.jobs[e].nact[t] = (*self.shared.nact[e].get()).as_ptr().add(t).cast();
|
||||
self.quantize_input(e, t, x, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Quantizes input row `t` of job `e` into its activation cell: Q8 (one) for Q2_0, Q8_K otherwise.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `load_batch`.
|
||||
unsafe fn quantize_input(&self, e: usize, t: usize, x: &[f32], f: NativeFmt) {
|
||||
unsafe {
|
||||
if f.gu == 42 {
|
||||
let ptr = (*self.shared.act[e].get()).as_mut_ptr().add(t);
|
||||
quantize_q2_act(x, &mut *ptr);
|
||||
} else {
|
||||
let ptr = (*self.shared.nact[e].get()).as_mut_ptr().add(t);
|
||||
super::super::rust_quant::q8_k(x, &mut (*ptr).q);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Gate/up phase, the host requantization of the hidden rows of every job, then the down phase, over the
|
||||
/// Gate/up phase, the host requantization of every job's hidden rows, then the down phase, over the
|
||||
/// `count` jobs already described in the batch (workers parked).
|
||||
pub(super) fn run_published(&mut self, f: NativeFmt, count: usize) {
|
||||
self.phase_timed(5, count * FF, 1);
|
||||
let t = self.timing.is_some().then(Instant::now);
|
||||
self.requantize_hidden(f, count);
|
||||
if let (Some(t), Some(acc)) = (t, self.timing.as_mut()) {
|
||||
acc[6] += t.elapsed().as_secs_f64() * 1e3;
|
||||
}
|
||||
self.phase_timed(6, count * H, 7);
|
||||
}
|
||||
/// The host requantization of the hidden rows of the first `count` jobs, between the gate/up and the down phase.
|
||||
fn requantize_hidden(&self, f: NativeFmt, count: usize) {
|
||||
// SAFETY: all workers parked after phase 5; job rows were admitted before publication.
|
||||
unsafe {
|
||||
let b = &*self.shared.batch.get();
|
||||
for (e, job) in b.jobs[..count].iter().enumerate() {
|
||||
let s = &mut *self.shared.split[e].get();
|
||||
for t in 0..job.rows as usize {
|
||||
requantize_hidden_row(f, s, t);
|
||||
}
|
||||
}
|
||||
self.shared.requantize_split(f, count);
|
||||
}
|
||||
self.lap_since(t, 6);
|
||||
self.phase_timed(6, count * H, 7);
|
||||
}
|
||||
/// Fault the borrowed matrices in on every worker (and the caller) after `MADV_WILLNEED` on all of
|
||||
/// them: a file-mapped source's misses become many outstanding reads instead of one serial stream
|
||||
@@ -325,29 +201,22 @@ impl NativePool {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
for x in experts {
|
||||
if !check_extents(x, &f) {
|
||||
if x.gate.len() != f.up_off || x.up.len() != f.up_off || x.down.len() != f.bytes - f.down_off {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
}
|
||||
for x in experts {
|
||||
for m in [x.gate, x.up, x.down] {
|
||||
super::super::rust_platform::will_need(m);
|
||||
}
|
||||
for m in experts.iter().flat_map(|x| [x.gate, x.up, x.down]) {
|
||||
super::super::rust_platform::will_need(m);
|
||||
}
|
||||
self.shared.wait_parked();
|
||||
// SAFETY: all workers parked; the borrowed matrices outlive this call, which returns only after the
|
||||
// phase finished and the workers parked again. The phase only reads them.
|
||||
unsafe {
|
||||
self.load_prefetch(experts, f);
|
||||
}
|
||||
self.stage_prefetch(f, experts);
|
||||
self.phase(7, experts.len() * (2 * FF + H));
|
||||
Ok(())
|
||||
}
|
||||
/// Describes the borrowed matrices of every expert in the batch (no pairs, no activations).
|
||||
///
|
||||
/// # Safety
|
||||
/// As the `unsafe` block of `prefetch_borrowed`.
|
||||
unsafe fn load_prefetch(&mut self, experts: &[super::super::BorrowedExpert<'_>], f: NativeFmt) {
|
||||
/// Describe a read-only prefetch phase over the borrowed experts (workers parked).
|
||||
fn stage_prefetch(&mut self, f: NativeFmt, experts: &[super::super::BorrowedExpert<'_>]) {
|
||||
// SAFETY: all workers parked; the borrowed matrices outlive the caller, which returns only after the
|
||||
// phase finished and the workers parked again. The phase only reads them.
|
||||
unsafe {
|
||||
let b = &mut *self.shared.batch.get();
|
||||
b.format = f;
|
||||
|
||||
@@ -1,14 +1,85 @@
|
||||
//! Moved out of the parent module by STRA-338: impl NativePool (2), impl Drop_for_NativePool.
|
||||
|
||||
use super::borrowed_group::{admit_group, describe_expert, quantize_tokens, validate_group_output};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl NativePool {
|
||||
/// One whole group straight from borrowed encoded matrices into the caller output rows: a single
|
||||
/// Shape, extent, destination and bounds checks of a whole borrowed group before anything is quantized or
|
||||
/// published: every `(token, slot)` pair names a distinct output row. Returns which tokens are used.
|
||||
fn validate_group(
|
||||
f: &NativeFmt,
|
||||
group: &super::super::BorrowedGroup<'_>,
|
||||
out_len: usize,
|
||||
) -> Result<[bool; MAX_ROWS]> {
|
||||
let (ntok, out_rows) = Self::group_shape(group, out_len)?;
|
||||
let stride = group.stride;
|
||||
let mut written = [0u64; super::super::MAX_OUT_ROWS / 64];
|
||||
let mut used = [false; MAX_ROWS];
|
||||
for x in group.experts {
|
||||
Self::check_expert(f, x)?;
|
||||
for &(token, slot) in x.pairs {
|
||||
if token >= ntok || slot >= stride {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Self::claim_row(&mut written, token, slot, stride, out_rows)?;
|
||||
used[token] = true;
|
||||
}
|
||||
}
|
||||
Ok(used)
|
||||
}
|
||||
/// Token and output row counts of a borrowed group, or a shape error for an unusable layout.
|
||||
fn group_shape(group: &super::super::BorrowedGroup<'_>, out_len: usize) -> Result<(usize, usize)> {
|
||||
let (experts, tokens) = (group.experts, group.tokens);
|
||||
if !(1..=MAX_JOBS).contains(&experts.len())
|
||||
|| tokens.len() % H != 0
|
||||
|| !(1..=MAX_ROWS).contains(&(tokens.len() / H))
|
||||
|| group.stride == 0
|
||||
|| out_len % H != 0
|
||||
{
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
let out_rows = out_len / H;
|
||||
if out_rows > super::super::MAX_OUT_ROWS {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok((tokens.len() / H, out_rows))
|
||||
}
|
||||
/// Extents of one borrowed expert's matrices and pair count.
|
||||
fn check_expert(f: &NativeFmt, x: &super::super::BorrowedExpert<'_>) -> Result<()> {
|
||||
if x.gate.len() != f.up_off
|
||||
|| x.up.len() != f.up_off
|
||||
|| x.down.len() != f.bytes - f.down_off
|
||||
|| !(1..=MAX_ROWS).contains(&x.pairs.len())
|
||||
{
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Mark output row `token * stride + slot` as written; an overflow, out-of-range or repeated row is a shape error.
|
||||
fn claim_row(written: &mut [u64], token: usize, slot: usize, stride: usize, out_rows: usize) -> Result<()> {
|
||||
let row = token.checked_mul(stride).and_then(|r| r.checked_add(slot)).ok_or(Error::Shape)?;
|
||||
if row >= out_rows || written[row / 64] >> (row % 64) & 1 != 0 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
written[row / 64] |= 1 << (row % 64);
|
||||
Ok(())
|
||||
}
|
||||
/// Every output row the group's pairs wrote is finite.
|
||||
fn check_group_outputs(group: &super::super::BorrowedGroup<'_>, out: &[f32]) -> Result<()> {
|
||||
for x in group.experts {
|
||||
for &(token, slot) in x.pairs {
|
||||
let at = (token * group.stride + slot) * H;
|
||||
if !all_finite(&out[at..at + H]) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// One whole group straight from borrowed encoded matrices into the caller's output rows: a single
|
||||
/// two-phase dispatch, no copy of expert bytes or activations. Every borrow ends before this returns;
|
||||
/// the caller holds `group` and `out` exclusively for the call. `out` row `token * stride + slot` of
|
||||
/// each pair receives that expert row; the pairs of all experts must name distinct rows.
|
||||
/// each pair receives that expert's row; the pairs of all experts must name distinct rows.
|
||||
pub fn compute_borrowed(
|
||||
&mut self,
|
||||
gu: i32,
|
||||
@@ -18,7 +89,8 @@ impl NativePool {
|
||||
) -> Result<()> {
|
||||
let t_pre = self.timing.is_some().then(Instant::now);
|
||||
let f = NativeFmt::new(gu, down)?;
|
||||
let used = admit_group(&f, group, out.len())?;
|
||||
// Validate the ENTIRE group (extents, pair bounds, disjoint destinations, finite inputs) first.
|
||||
let used = Self::validate_group(&f, group, out.len())?;
|
||||
if !all_finite(group.tokens) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
@@ -26,43 +98,16 @@ impl NativePool {
|
||||
// SAFETY: all workers parked; the borrowed matrices, tokens and `out` outlive this call, which returns
|
||||
// only after both phases finished and the workers parked again. Destinations are pairwise disjoint rows.
|
||||
unsafe {
|
||||
self.load_group(f, group, &used, out);
|
||||
}
|
||||
if let (Some(t), Some(acc)) = (t_pre, self.timing.as_mut()) {
|
||||
acc[0] += t.elapsed().as_secs_f64() * 1e3;
|
||||
self.shared.quantize_tokens(f, group.tokens, &used);
|
||||
self.shared.describe_borrowed(f, group.experts, group.stride, out.as_mut_ptr());
|
||||
}
|
||||
self.lap_since(t_pre, 0);
|
||||
self.run_published(f, group.experts.len());
|
||||
let t_post = self.timing.is_some().then(Instant::now);
|
||||
validate_group_output(group, out)?;
|
||||
if let (Some(t), Some(acc)) = (t_post, self.timing.as_mut()) {
|
||||
acc[12] += t.elapsed().as_secs_f64() * 1e3;
|
||||
}
|
||||
Self::check_group_outputs(group, out)?;
|
||||
self.lap_since(t_post, 12);
|
||||
Ok(())
|
||||
}
|
||||
/// Quantizes the used tokens once and describes every expert of the group in the batch.
|
||||
///
|
||||
/// # Safety
|
||||
/// As the `unsafe` block of `compute_borrowed`.
|
||||
unsafe fn load_group(
|
||||
&mut self,
|
||||
f: NativeFmt,
|
||||
group: &super::super::BorrowedGroup<'_>,
|
||||
used: &[bool; MAX_ROWS],
|
||||
out: &mut [f32],
|
||||
) {
|
||||
unsafe {
|
||||
let ta = &mut *self.shared.tok_act[0].get();
|
||||
let tn = &mut *self.shared.tok_nact[0].get();
|
||||
quantize_tokens(&f, group.tokens, used, ta, tn);
|
||||
let b = &mut *self.shared.batch.get();
|
||||
b.format = f;
|
||||
b.count = group.experts.len();
|
||||
let base = out.as_mut_ptr();
|
||||
for (e, x) in group.experts.iter().enumerate() {
|
||||
b.jobs[e] = describe_expert(x, ta, tn, base, group.stride);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for NativePool {
|
||||
fn drop(&mut self) {
|
||||
|
||||
@@ -11,15 +11,6 @@ impl Shared {
|
||||
self.sleep_cv.notify_all();
|
||||
}
|
||||
}
|
||||
/// Opens a phase of `tasks` tasks: resets `done`, tags `head` with the next epoch, wakes the workers; returns the
|
||||
/// epoch.
|
||||
pub(super) fn open_epoch(&self, tasks: usize) -> u32 {
|
||||
self.done.0.store(0, Ordering::Relaxed);
|
||||
let e = self.epoch.0.load(Ordering::Relaxed).wrapping_add(1);
|
||||
self.head.0.store(((e as u64) << 32) | ((tasks as u64) << 16), Ordering::Release);
|
||||
self.publish();
|
||||
e
|
||||
}
|
||||
pub(super) fn claim(&self, epoch: u32) -> Option<usize> {
|
||||
let mut h = self.head.0.load(Ordering::Acquire);
|
||||
loop {
|
||||
@@ -51,8 +42,8 @@ impl Shared {
|
||||
super::super::rust_platform::pin(core);
|
||||
let mut seen = 0u32;
|
||||
self.parked.0.fetch_add(1, Ordering::AcqRel);
|
||||
while self.await_epoch(seen) {
|
||||
if self.stop.0.load(Ordering::Acquire) {
|
||||
loop {
|
||||
if !self.await_epoch(seen) || self.stop.0.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
seen = self.epoch.0.load(Ordering::Acquire);
|
||||
@@ -61,7 +52,7 @@ impl Shared {
|
||||
self.parked.0.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
/// Spins, then sleeps on the condvar, until the epoch moves past `seen`; `false` when the pool was told to stop.
|
||||
/// Spin (then sleep) until the epoch moves past `seen`; false when the pool is stopping.
|
||||
fn await_epoch(&self, seen: u32) -> bool {
|
||||
let parked_at = Instant::now();
|
||||
let mut spins = 0u32;
|
||||
@@ -78,7 +69,6 @@ impl Shared {
|
||||
}
|
||||
true
|
||||
}
|
||||
/// The slow wait of a worker that spun past `spin`: counted as a sleeper, woken by `publish` or by `stop`.
|
||||
fn sleep_until_epoch(&self, seen: u32) {
|
||||
let mut lock = self.sleep_mu.lock().unwrap_or_else(|p| p.into_inner());
|
||||
self.sleepers.0.fetch_add(1, Ordering::SeqCst);
|
||||
@@ -128,8 +118,8 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Tasks per participating thread in a phase (pool.cpp `phase_tasks`: 3). `LELEKA_POOL_TASKS_PER_THREAD` (1..=16) is
|
||||
/// an A/B knob: every row is computed by the same code whatever task holds it, so the output does not depend on it.
|
||||
/// Tasks per participating thread in a phase (pool.cpp `phase_tasks`: 3). `LELEKA_POOL_TASKS_PER_THREAD` (1..=16) is an A/B knob: every row is
|
||||
/// computed by the same code whatever task holds it, so the output does not depend on it.
|
||||
pub(super) fn tasks_per_thread() -> usize {
|
||||
static V: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
|
||||
*V.get_or_init(|| {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! STRA-338 size4: host-side staging of a published batch (job table, activation quantization), shared by the
|
||||
//! owned (`compute_batch`) and borrowed (`compute_borrowed`) paths. Every function runs only while all workers are
|
||||
//! parked, so the host is the sole accessor of `batch` and the activation cells.
|
||||
|
||||
use super::super::rust_quant;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Quantize one hidden row to the Q8 one-block activation (AVX-512 or AVX2 path).
|
||||
///
|
||||
/// # Safety
|
||||
/// `x` is one `H`-float row; the quantizers need the AVX2/AVX-512 features `dispatch()` reported.
|
||||
unsafe fn q8_one(x: &[f32], dst: &mut ActQ) {
|
||||
unsafe {
|
||||
if dispatch().avx512 {
|
||||
rust_quant::q8_one_avx512(x, dst);
|
||||
} else {
|
||||
rust_quant::q8_one_avx2(x, dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// Fill `b.jobs[e]` from owned job `j` and quantize its input rows into the per-job activation cells.
|
||||
///
|
||||
/// # Safety
|
||||
/// All workers parked (exclusive access to `b` and to the cells of job `e`); `e < MAX_JOBS`, `j.rows <= MAX_ROWS`.
|
||||
pub(super) unsafe fn describe_owned(&self, b: &mut Batch, e: usize, j: &mut PreparedJob, f: NativeFmt) {
|
||||
unsafe {
|
||||
let p = j.blob.as_ptr();
|
||||
b.jobs[e] =
|
||||
Job { gate: p, up: p.add(f.up_off), down: p.add(f.down_off), rows: j.rows as i32, ..Job::default() };
|
||||
for t in 0..j.rows {
|
||||
let x = &j.input[t * H..(t + 1) * H];
|
||||
b.jobs[e].output[t] = j.output.as_mut_ptr().add(t * H);
|
||||
b.jobs[e].act[t] = (*self.act[e].get()).as_ptr().add(t);
|
||||
b.jobs[e].nact[t] = (*self.nact[e].get()).as_ptr().add(t).cast();
|
||||
let ptr = (*self.act[e].get()).as_mut_ptr().add(t);
|
||||
if f.gu == 42 {
|
||||
q8_one(x, &mut *ptr);
|
||||
} else {
|
||||
let ptr = (*self.nact[e].get()).as_mut_ptr().add(t);
|
||||
rust_quant::q8_k(x, &mut (*ptr).q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Requantize the gate/up outputs of the first `count` jobs (phase 5) into the down-phase activations.
|
||||
///
|
||||
/// # Safety
|
||||
/// All workers parked after phase 5; job rows were admitted before publication.
|
||||
pub(super) unsafe fn requantize_split(&self, f: NativeFmt, count: usize) {
|
||||
unsafe {
|
||||
let b = &*self.batch.get();
|
||||
for e in 0..count {
|
||||
let rows = b.jobs[e].rows as usize;
|
||||
let s = &mut *self.split[e].get();
|
||||
for t in 0..rows {
|
||||
if f.down == 42 {
|
||||
q8_one(&s.ff[t], &mut s.a2[t]);
|
||||
} else {
|
||||
rust_quant::q8_zero(&s.ff[t], &mut s.hq[t].q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Quantize every token a borrowed group uses once (`used[t]`) into the shared token activation cells.
|
||||
///
|
||||
/// # Safety
|
||||
/// All workers parked; `tokens.len() == ntok * H`, `ntok <= MAX_ROWS`.
|
||||
pub(super) unsafe fn quantize_tokens(&self, f: NativeFmt, tokens: &[f32], used: &[bool; MAX_ROWS]) {
|
||||
unsafe {
|
||||
let ta = &mut *self.tok_act[0].get();
|
||||
let tn = &mut *self.tok_nact[0].get();
|
||||
for t in (0..tokens.len() / H).filter(|&t| used[t]) {
|
||||
let x = &tokens[t * H..(t + 1) * H];
|
||||
if f.gu == 42 {
|
||||
q8_one(x, &mut ta[t]);
|
||||
} else if rust_quant::q8k_fast() {
|
||||
rust_quant::q8_k_avx2(x, &mut tn[t].q);
|
||||
} else {
|
||||
rust_quant::q8_k(x, &mut tn[t].q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill the job table from the experts of a borrowed group; outputs point straight into `base` (the caller's rows).
|
||||
///
|
||||
/// # Safety
|
||||
/// All workers parked; the group's matrices and `base` outlive the phases; destinations are pairwise disjoint rows.
|
||||
pub(super) unsafe fn describe_borrowed(
|
||||
&self,
|
||||
f: NativeFmt,
|
||||
experts: &[super::super::BorrowedExpert<'_>],
|
||||
stride: usize,
|
||||
base: *mut f32,
|
||||
) {
|
||||
unsafe {
|
||||
let ta = &*self.tok_act[0].get();
|
||||
let tn = &*self.tok_nact[0].get();
|
||||
let b = &mut *self.batch.get();
|
||||
b.format = f;
|
||||
b.count = experts.len();
|
||||
for (e, x) in experts.iter().enumerate() {
|
||||
b.jobs[e] = Job {
|
||||
gate: x.gate.as_ptr(),
|
||||
up: x.up.as_ptr(),
|
||||
down: x.down.as_ptr(),
|
||||
rows: x.pairs.len() as i32,
|
||||
..Job::default()
|
||||
};
|
||||
for (t, &(token, slot)) in x.pairs.iter().enumerate() {
|
||||
b.jobs[e].act[t] = ta.as_ptr().add(token);
|
||||
b.jobs[e].nact[t] = tn.as_ptr().add(token).cast();
|
||||
b.jobs[e].output[t] = base.add((token * stride + slot) * H);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,9 @@
|
||||
use super::rust_simd::half;
|
||||
use super::rust_types::ActQ;
|
||||
use std::arch::x86_64::*;
|
||||
// Bounds: for each 18-byte block b of `row`, dot256/dot512 read a.q[b*64..b*64+64], a.scale/hx[2b..2b+2] and
|
||||
// row[b*18..(b+1)*18]. ActQ has 2560 q and 80 scale/hx entries, so `row.len() <= 40*18 = 720` and `a.len() <= 8` are
|
||||
// required and asserted below (callers pass 720-byte gate/up rows, 180-byte down rows, or q2_rows(width <= H)).
|
||||
// Gate: avx2_ok() / avx512_ok()+dq_ok(). The dot512_n helpers are called only by dot512_n after its asserts.
|
||||
// Bounds: for each 18-byte block b of `row`, dot256/dot512 read a.q[b*64..b*64+64], a.scale/hx[2b..2b+2] and row[b*18..(b+1)*18].
|
||||
// ActQ has 2560 q and 80 scale/hx entries, so `row.len() <= 40*18 = 720` and `a.len() <= 8` are required and asserted
|
||||
// below (callers pass 720-byte gate/up rows, 180-byte down rows, or q2_rows(width <= H)). Gate: avx2_ok() / avx512_ok()+dq_ok().
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn unpack(c: &[u8]) -> (__m256i, __m256i) {
|
||||
unsafe {
|
||||
@@ -31,11 +30,10 @@ unsafe fn unpack(c: &[u8]) -> (__m256i, __m256i) {
|
||||
)
|
||||
}
|
||||
}
|
||||
// The weight-scale times activation-sum correction `corr += d*(hx0+hx1)` is ONE fused multiply-add (vfmadd231ss), as in
|
||||
// the pinned C++ q2_avx2.cpp row_multi built by GCC with -mfma (default -ffp-contract=fast contracts it; objdump of
|
||||
// q2_avx2.o shows the scalar vfmadd) and as in the AVX-512 tree's explicit `_mm512_fmadd_ps(dd,hx,corr)`. A separate
|
||||
// mul+add rounds twice and differs in the last bits (STRA-324). Not contractible by rustc, hence the explicit
|
||||
// `mul_add`; this function enables `fma`, so it lowers to the instruction, never to a libm call.
|
||||
// The weight-scale times activation-sum correction `corr += d*(hx0+hx1)` is ONE fused multiply-add (vfmadd231ss), as in the pinned C++
|
||||
// q2_avx2.cpp row_multi built by GCC with -mfma (default -ffp-contract=fast contracts it; objdump of q2_avx2.o shows the scalar vfmadd) and as in the
|
||||
// AVX-512 tree's explicit `_mm512_fmadd_ps(dd,hx,corr)`. A separate mul+add rounds twice and differs in the last bits (STRA-324). Not contractible
|
||||
// by rustc, hence the explicit `mul_add`; this function enables `fma`, so it lowers to the instruction, never to a libm call.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn dot256(row: &[u8], a: &[&ActQ], r: &mut [f32]) {
|
||||
unsafe {
|
||||
@@ -79,6 +77,47 @@ pub(super) unsafe fn dot512(row: &[u8], a: &[&ActQ], r: &mut [f32]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The block scales of blocks `b0..b0 + n` duplicated per half-block lane, with the lane mask of the `n` blocks.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn block_scales512(row: &[u8], b0: usize, n: usize) -> (u16, __m512) {
|
||||
unsafe {
|
||||
let dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7);
|
||||
let mask = if n == 8 { 0xffff } else { ((1u32 << (2 * n)) - 1) as u16 };
|
||||
let mut sc = [0u16; 8];
|
||||
for i in 0..n {
|
||||
sc[i] = u16::from_le_bytes([row[(b0 + i) * 18], row[(b0 + i) * 18 + 1]]);
|
||||
}
|
||||
let d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(_mm_loadu_si128(sc.as_ptr().cast())));
|
||||
(mask, _mm512_maskz_mov_ps(mask, _mm512_permutexvar_ps(dup, d8)))
|
||||
}
|
||||
}
|
||||
/// The `n` blocks from `b0` of one row against `N` tokens: `acc[t] += scale lane * dpbusd(weights, token bytes)`.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn blocks512<const N: usize>(
|
||||
row: &[u8],
|
||||
a: &[&ActQ],
|
||||
(b0, n): (usize, usize),
|
||||
p: &[__m512; 8],
|
||||
acc: &mut [__m512; 8],
|
||||
) {
|
||||
unsafe {
|
||||
let base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
|
||||
for i in 0..n {
|
||||
let b = b0 + i;
|
||||
let packed = _mm_loadu_si128(row.as_ptr().add(b * 18 + 2).cast());
|
||||
let lanes = _mm512_cvtepu16_epi64(packed);
|
||||
let ctrl = _mm512_set1_epi64(0x0e0c0a0806040200);
|
||||
let w = _mm512_and_si512(_mm512_multishift_epi64_epi8(ctrl, lanes), _mm512_set1_epi8(3));
|
||||
let idx = _mm512_add_epi32(base, _mm512_set1_epi32(2 * i as i32));
|
||||
for t in 0..N {
|
||||
let a = a[t];
|
||||
let dot =
|
||||
_mm512_dpbusd_epi32(_mm512_setzero_si512(), w, _mm512_loadu_si512(a.q.as_ptr().add(b * 64).cast()));
|
||||
acc[t] = _mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p[t]), _mm512_cvtepi32_ps(dot), acc[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn dot512_n<const N: usize>(row: &[u8], a: &[&ActQ], r: &mut [f32]) {
|
||||
unsafe {
|
||||
@@ -88,78 +127,137 @@ unsafe fn dot512_n<const N: usize>(row: &[u8], a: &[&ActQ], r: &mut [f32]) {
|
||||
let nb = row.len() / 18;
|
||||
for b0 in (0..nb).step_by(8) {
|
||||
let n = (nb - b0).min(8);
|
||||
let (mask, dd) = group_scales(row, b0, n);
|
||||
let (mask, dd) = block_scales512(row, b0, n);
|
||||
let mut p = [_mm512_setzero_ps(); 8];
|
||||
for t in 0..N {
|
||||
(p[t], corr[t]) = token_scales(dd, mask, a[t], b0, corr[t]);
|
||||
}
|
||||
for i in 0..n {
|
||||
let (w, idx) = (block_weights(row, b0 + i), block_index(i));
|
||||
for t in 0..N {
|
||||
acc[t] = accumulate_token(acc[t], idx, p[t], w, a[t], b0 + i);
|
||||
}
|
||||
let a = a[t];
|
||||
p[t] = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(mask, a.scale.as_ptr().add(2 * b0)));
|
||||
corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(mask, a.hx.as_ptr().add(2 * b0)), corr[t]);
|
||||
}
|
||||
blocks512::<N>(row, a, (b0, n), &p, &mut acc);
|
||||
}
|
||||
for t in 0..N {
|
||||
r[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The FP16 weight scales of the `n` blocks from `b0` (at most 8), each in its two lanes, and the lane mask.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn group_scales(row: &[u8], b0: usize, n: usize) -> (u16, __m512) {
|
||||
// SAFETY: dot512_n asserted row.len() <= 40 * 18, so blocks b0..b0+n lie inside `row`; `sc` holds 8 u16 (16 bytes).
|
||||
unsafe {
|
||||
let mask = if n == 8 { 0xffff } else { ((1u32 << (2 * n)) - 1) as u16 };
|
||||
let mut sc = [0u16; 8];
|
||||
for i in 0..n {
|
||||
sc[i] = u16::from_le_bytes([row[(b0 + i) * 18], row[(b0 + i) * 18 + 1]]);
|
||||
}
|
||||
let d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(_mm_loadu_si128(sc.as_ptr().cast())));
|
||||
let dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7);
|
||||
(mask, _mm512_maskz_mov_ps(mask, _mm512_permutexvar_ps(dup, d8)))
|
||||
}
|
||||
}
|
||||
/// The per-token weight-scale products of one group (`dd * a.scale`) and the updated correction chain (`dd * a.hx`).
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn token_scales(dd: __m512, mask: u16, a: &ActQ, b0: usize, corr: __m512) -> (__m512, __m512) {
|
||||
// SAFETY: masked loads read only the 2 * n scale/hx entries from 2 * b0 named by the mask, inside the 80 entries.
|
||||
unsafe {
|
||||
let p = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(mask, a.scale.as_ptr().add(2 * b0)));
|
||||
(p, _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(mask, a.hx.as_ptr().add(2 * b0)), corr))
|
||||
}
|
||||
}
|
||||
/// The 64 two-bit weights of block `b` as bytes 0..=3.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn block_weights(row: &[u8], b: usize) -> __m512i {
|
||||
// SAFETY: block `b` lies inside `row` (dot512_n asserted row.len() <= 40 * 18); the 16-byte load is its codes.
|
||||
unsafe {
|
||||
let packed = _mm_loadu_si128(row.as_ptr().add(b * 18 + 2).cast());
|
||||
let lanes = _mm512_cvtepu16_epi64(packed);
|
||||
let ctrl = _mm512_set1_epi64(0x0e0c0a0806040200);
|
||||
_mm512_and_si512(_mm512_multishift_epi64_epi8(ctrl, lanes), _mm512_set1_epi8(3))
|
||||
}
|
||||
}
|
||||
/// The lane selector that picks the two scale lanes of the `i`-th block of a group.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn block_index(i: usize) -> __m512i {
|
||||
let base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
|
||||
_mm512_add_epi32(base, _mm512_set1_epi32(2 * i as i32))
|
||||
}
|
||||
/// One token's accumulator advanced by block `b`: `acc + p[idx] * float(dot(weights, a.q[b*64..]))`.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn accumulate_token(acc: __m512, idx: __m512i, p: __m512, w: __m512i, a: &ActQ, b: usize) -> __m512 {
|
||||
// SAFETY: b < 40 (dot512_n asserted row.len() <= 40 * 18), so the 64-byte load stays inside the 2560 of `a.q`.
|
||||
unsafe {
|
||||
let dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), w, _mm512_loadu_si512(a.q.as_ptr().add(b * 64).cast()));
|
||||
_mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p), _mm512_cvtepi32_ps(dot), acc)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
// A row longer than the 40 blocks an ActQ holds would make the kernels load past `a.q` / `a.scale`: it is refused before any load,
|
||||
// while the exact-fit row still runs.
|
||||
fn xorshift(s: &mut u64) -> u64 {
|
||||
*s ^= *s << 13;
|
||||
*s ^= *s >> 7;
|
||||
*s ^= *s << 17;
|
||||
*s
|
||||
}
|
||||
fn h2f(h: u16) -> f32 {
|
||||
let e = ((h >> 10) & 31) as u32;
|
||||
assert!(e > 0 && e < 31, "finite normal FP16 only");
|
||||
f32::from_bits(((h as u32 & 0x8000) << 16) | ((e + 112) << 23) | ((h as u32 & 0x3ff) << 13))
|
||||
}
|
||||
// Scalar model of q2_avx2.cpp row_multi (the AVX2 tree): per 32-value chunk and lane (4 consecutive code x activation products, exact in int32),
|
||||
// `acc = fma(d*scale, float(sum), acc)` twice per block, the correction chain `corr` fused (`fused`) or as a separate mul+add, the reduction
|
||||
// ((l0+l4)+(l2+l6)) + ((l1+l5)+(l3+l7)), result minus corr.
|
||||
fn model(row: &[u8], a: &ActQ, fused: bool) -> f32 {
|
||||
let mut acc = [0.0f32; 8];
|
||||
let mut corr = 0.0f32;
|
||||
for (b, blk) in row.chunks_exact(18).enumerate() {
|
||||
let d = h2f(u16::from_le_bytes([blk[0], blk[1]]));
|
||||
let code = |i: usize| -> i32 { ((blk[2 + i / 4] >> (2 * (i % 4))) & 3) as i32 };
|
||||
for c in 0..2 {
|
||||
for l in 0..8 {
|
||||
let mut s = 0i32;
|
||||
for k in 0..4 {
|
||||
let e = 32 * c + 4 * l + k;
|
||||
s += code(e) * a.q[b * 64 + e] as i32;
|
||||
}
|
||||
acc[l] = (d * a.scale[2 * b + c]).mul_add(s as f32, acc[l]);
|
||||
}
|
||||
}
|
||||
let t = a.hx[2 * b] + a.hx[2 * b + 1];
|
||||
corr = if fused { d.mul_add(t, corr) } else { corr + d * t };
|
||||
}
|
||||
let h = [acc[0] + acc[4], acc[1] + acc[5], acc[2] + acc[6], acc[3] + acc[7]];
|
||||
let s = [h[0] + h[2], h[1] + h[3]];
|
||||
(s[0] + s[1]) - corr
|
||||
}
|
||||
// The Q2_0 AVX2 tree (gate/up: 40 blocks, down: 10 blocks of the hidden), 1..8 tokens, against the scalar model of the pinned C++ AVX2 row kernel. The
|
||||
// correction `corr += d*(hx0+hx1)` is fused there (GCC contracts it under -mfma) and in the AVX-512 tree; a separate mul+add (the first Rust port) differed in the
|
||||
// last bits of 20 of 40 KAB1 cases (every Q2_0 down, STRA-324). The check that the unfused model differs keeps this test sensitive to that change.
|
||||
#[test]
|
||||
fn avx2_tree_matches_the_pinned_cpp_row_kernel_model_for_gate_up_and_down_rows() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
eprintln!("SKIP: Original AVX2/F16C/FMA capability required");
|
||||
return;
|
||||
}
|
||||
let mut seed = 0x0123_4567_89ab_cdefu64;
|
||||
let mut unfused_differs = 0usize;
|
||||
for (nb, n) in [(10usize, 640usize), (40, 2560)] {
|
||||
let mut acts: Vec<ActQ> = Vec::new();
|
||||
for tok in 0..8 {
|
||||
let x: Vec<f32> = (0..n)
|
||||
.map(|_| ((xorshift(&mut seed) % 20001) as f32 - 10000.0) * 0.01 * (1.0 + (tok as f32)))
|
||||
.collect();
|
||||
let mut a = ActQ::default();
|
||||
// SAFETY: avx2_ok() above; n <= 2560 and n % 32 == 0.
|
||||
unsafe {
|
||||
super::super::rust_quant::q8_one_avx2(&x, &mut a);
|
||||
}
|
||||
acts.push(a);
|
||||
}
|
||||
for _ in 0..8 {
|
||||
let mut row = vec![0u8; nb * 18];
|
||||
for v in row.iter_mut() {
|
||||
*v = xorshift(&mut seed) as u8;
|
||||
}
|
||||
for b in row.chunks_exact_mut(18) {
|
||||
let e = 8 + (xorshift(&mut seed) % 8) as u16;
|
||||
let m = (xorshift(&mut seed) & 0x3ff) as u16;
|
||||
b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes());
|
||||
}
|
||||
for nt in 1..=8usize {
|
||||
let refs: Vec<&ActQ> = acts[..nt].iter().collect();
|
||||
let mut out = vec![0.0f32; nt];
|
||||
// SAFETY: avx2_ok() above; rows have at most 40 blocks and at most 8 tokens.
|
||||
unsafe {
|
||||
dot256(&row, &refs, &mut out);
|
||||
}
|
||||
for t in 0..nt {
|
||||
assert_eq!(
|
||||
out[t].to_bits(),
|
||||
model(&row, &acts[t], true).to_bits(),
|
||||
"blocks {nb} nt {nt} token {t}"
|
||||
);
|
||||
if model(&row, &acts[t], false).to_bits() != out[t].to_bits() {
|
||||
unfused_differs += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(unfused_differs > 0, "the unfused correction must be distinguishable from the fused one on this data");
|
||||
}
|
||||
#[test]
|
||||
fn rows_longer_than_the_activation_are_refused_before_any_load() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
eprintln!("SKIP: Original AVX2/F16C/FMA capability required");
|
||||
return;
|
||||
}
|
||||
let a = ActQ::default();
|
||||
let row = vec![0u8; 41 * 18];
|
||||
let mut out = [0.0f32];
|
||||
// SAFETY: avx2_ok() above; the over-long row panics at the entry assert before any vector load.
|
||||
assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot256(&row, &[&a], &mut out) })).is_err());
|
||||
// SAFETY: avx2_ok() above; 720 bytes = 40 blocks, the largest row an ActQ covers.
|
||||
assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot256(&row[..40 * 18], &[&a], &mut out) })).is_ok());
|
||||
if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() {
|
||||
// SAFETY: avx512_ok()+dq_ok() above; same bounds as the AVX2 leaf.
|
||||
assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot512(&row, &[&a], &mut out) })).is_err());
|
||||
assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot512(&row[..40 * 18], &[&a], &mut out) })).is_ok());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
//! Moved out of rust_q2.rs by STRA-338 (same module path as before).
|
||||
|
||||
use super::*;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
// A row longer than the 40 blocks an ActQ holds would make the kernels load past `a.q` / `a.scale`: it is refused
|
||||
// before any load, while the exact-fit row still runs.
|
||||
fn xorshift(s: &mut u64) -> u64 {
|
||||
*s ^= *s << 13;
|
||||
*s ^= *s >> 7;
|
||||
*s ^= *s << 17;
|
||||
*s
|
||||
}
|
||||
fn h2f(h: u16) -> f32 {
|
||||
let e = ((h >> 10) & 31) as u32;
|
||||
assert!(e > 0 && e < 31, "finite normal FP16 only");
|
||||
f32::from_bits(((h as u32 & 0x8000) << 16) | ((e + 112) << 23) | ((h as u32 & 0x3ff) << 13))
|
||||
}
|
||||
// Scalar model of q2_avx2.cpp row_multi (the AVX2 tree): per 32-value chunk and lane (4 consecutive code x activation
|
||||
// products, exact in int32), `acc = fma(d*scale, float(sum), acc)` twice per block, the correction chain `corr` fused
|
||||
// (`fused`) or as a separate mul+add, the reduction ((l0+l4)+(l2+l6)) + ((l1+l5)+(l3+l7)), result minus corr.
|
||||
fn model(row: &[u8], a: &ActQ, fused: bool) -> f32 {
|
||||
let mut acc = [0.0f32; 8];
|
||||
let mut corr = 0.0f32;
|
||||
for (b, blk) in row.chunks_exact(18).enumerate() {
|
||||
let d = h2f(u16::from_le_bytes([blk[0], blk[1]]));
|
||||
let code = |i: usize| -> i32 { ((blk[2 + i / 4] >> (2 * (i % 4))) & 3) as i32 };
|
||||
for c in 0..2 {
|
||||
for l in 0..8 {
|
||||
let mut s = 0i32;
|
||||
for k in 0..4 {
|
||||
let e = 32 * c + 4 * l + k;
|
||||
s += code(e) * a.q[b * 64 + e] as i32;
|
||||
}
|
||||
acc[l] = (d * a.scale[2 * b + c]).mul_add(s as f32, acc[l]);
|
||||
}
|
||||
}
|
||||
let t = a.hx[2 * b] + a.hx[2 * b + 1];
|
||||
corr = if fused { d.mul_add(t, corr) } else { corr + d * t };
|
||||
}
|
||||
let h = [acc[0] + acc[4], acc[1] + acc[5], acc[2] + acc[6], acc[3] + acc[7]];
|
||||
let s = [h[0] + h[2], h[1] + h[3]];
|
||||
(s[0] + s[1]) - corr
|
||||
}
|
||||
/// Eight activations of `n` values each (token `tok` scaled by `1 + tok`), quantized by the AVX2 q8_one leaf.
|
||||
fn random_acts(n: usize, seed: &mut u64) -> Vec<ActQ> {
|
||||
let mut acts: Vec<ActQ> = Vec::new();
|
||||
for tok in 0..8 {
|
||||
let x: Vec<f32> =
|
||||
(0..n).map(|_| ((xorshift(seed) % 20001) as f32 - 10000.0) * 0.01 * (1.0 + (tok as f32))).collect();
|
||||
let mut a = ActQ::default();
|
||||
// SAFETY: avx2_ok() by the caller; n <= 2560 and n % 32 == 0.
|
||||
unsafe {
|
||||
super::super::rust_quant::q8_one_avx2(&x, &mut a);
|
||||
}
|
||||
acts.push(a);
|
||||
}
|
||||
acts
|
||||
}
|
||||
/// A row of `nb` Q2_0 blocks: random bytes, with a finite normal FP16 scale at the start of each block.
|
||||
fn random_row(nb: usize, seed: &mut u64) -> Vec<u8> {
|
||||
let mut row = vec![0u8; nb * 18];
|
||||
for v in row.iter_mut() {
|
||||
*v = xorshift(seed) as u8;
|
||||
}
|
||||
for b in row.chunks_exact_mut(18) {
|
||||
let e = 8 + (xorshift(seed) % 8) as u16;
|
||||
let m = (xorshift(seed) & 0x3ff) as u16;
|
||||
b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes());
|
||||
}
|
||||
row
|
||||
}
|
||||
/// Compare dot256 on `nt` tokens with the fused model; the count of tokens where the unfused model differs.
|
||||
fn check_tokens(row: &[u8], acts: &[ActQ], nb: usize, nt: usize) -> usize {
|
||||
let refs: Vec<&ActQ> = acts[..nt].iter().collect();
|
||||
let mut out = vec![0.0f32; nt];
|
||||
// SAFETY: avx2_ok() by the caller; rows have at most 40 blocks and at most 8 tokens.
|
||||
unsafe {
|
||||
dot256(row, &refs, &mut out);
|
||||
}
|
||||
let mut differs = 0;
|
||||
for t in 0..nt {
|
||||
assert_eq!(out[t].to_bits(), model(row, &acts[t], true).to_bits(), "blocks {nb} nt {nt} token {t}");
|
||||
differs += (model(row, &acts[t], false).to_bits() != out[t].to_bits()) as usize;
|
||||
}
|
||||
differs
|
||||
}
|
||||
// The Q2_0 AVX2 tree (gate/up: 40 blocks, down: 10 blocks of the hidden), 1..8 tokens, against the scalar model of the
|
||||
// pinned C++ AVX2 row kernel. The correction `corr += d*(hx0+hx1)` is fused there (GCC contracts it under -mfma) and in
|
||||
// the AVX-512 tree; a separate mul+add (the first Rust port) differed in the last bits of 20 of 40 KAB1 cases (every
|
||||
// Q2_0 down, STRA-324). The check that the unfused model differs keeps this test sensitive to that change.
|
||||
#[test]
|
||||
fn avx2_tree_matches_the_pinned_cpp_row_kernel_model_for_gate_up_and_down_rows() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
eprintln!("SKIP: Original AVX2/F16C/FMA capability required");
|
||||
return;
|
||||
}
|
||||
let mut seed = 0x0123_4567_89ab_cdefu64;
|
||||
let mut unfused_differs = 0usize;
|
||||
for (nb, n) in [(10usize, 640usize), (40, 2560)] {
|
||||
let acts = random_acts(n, &mut seed);
|
||||
for _ in 0..8 {
|
||||
let row = random_row(nb, &mut seed);
|
||||
for nt in 1..=8usize {
|
||||
unfused_differs += check_tokens(&row, &acts, nb, nt);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(unfused_differs > 0, "the unfused correction must be distinguishable from the fused one on this data");
|
||||
}
|
||||
#[test]
|
||||
fn rows_longer_than_the_activation_are_refused_before_any_load() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
eprintln!("SKIP: Original AVX2/F16C/FMA capability required");
|
||||
return;
|
||||
}
|
||||
let a = ActQ::default();
|
||||
let row = vec![0u8; 41 * 18];
|
||||
let mut out = [0.0f32];
|
||||
// SAFETY: avx2_ok() above; the over-long row panics at the entry assert before any vector load.
|
||||
assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot256(&row, &[&a], &mut out) })).is_err());
|
||||
// SAFETY: avx2_ok() above; 720 bytes = 40 blocks, the largest row an ActQ covers.
|
||||
assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot256(&row[..40 * 18], &[&a], &mut out) })).is_ok());
|
||||
if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() {
|
||||
// SAFETY: avx512_ok()+dq_ok() above; same bounds as the AVX2 leaf.
|
||||
assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot512(&row, &[&a], &mut out) })).is_err());
|
||||
assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot512(&row[..40 * 18], &[&a], &mut out) })).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -4,20 +4,13 @@ use super::rust_types::{ActQ, Q8K, Q8Zero};
|
||||
use std::arch::x86_64::*;
|
||||
// Bounds: q8_zero asserts x.len()==32*y.len() and stores 32 i8 per Q8Zero; q8_one_* assert x.len()<=2560 && %32==0, so
|
||||
// every store lands in a.q[..x.len()] (H = 2560 i8) and a.scale/sum/hx[..x.len()/32] (80 entries); all vector accesses
|
||||
// are unaligned (loadu/storeu). Gate: see rust_simd.rs SAFETY CONTRACT. The per-block helpers below are called only by
|
||||
// the quantizer of the same name with a block slice of exactly 256 (q8_k) or 32 (q8_zero, q8_one_*) floats.
|
||||
// are unaligned (loadu/storeu). Gate: see rust_simd.rs SAFETY CONTRACT.
|
||||
// ggml nearest_int: signed bit-bias rounding; inputs bounded by signed maximum.
|
||||
fn nearest_int(x: f32) -> i32 {
|
||||
debug_assert!(x.abs() <= 4_194_303.0);
|
||||
let y = x + 12_582_912.0;
|
||||
(y.to_bits() & 0x007f_ffff) as i32 - 0x0040_0000
|
||||
}
|
||||
/// The 16 partial sums of a quantized Q8K block, as the scalar quantizer and its AVX2 form both define them.
|
||||
fn fill_bsums(y: &mut Q8K) {
|
||||
for (sum, q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)) {
|
||||
*sum = q.iter().map(|&v| v as i32).sum::<i32>() as i16;
|
||||
}
|
||||
}
|
||||
pub(super) fn q8_k(x: &[f32], y: &mut [Q8K]) {
|
||||
assert_eq!(x.len(), 256 * y.len());
|
||||
for (xb, y) in x.chunks_exact(256).zip(y) {
|
||||
@@ -39,7 +32,9 @@ pub(super) fn q8_k(x: &[f32], y: &mut [Q8K]) {
|
||||
for (q, &x) in y.qs.iter_mut().zip(xb) {
|
||||
*q = nearest_int(iscale * x).min(127) as i8;
|
||||
}
|
||||
fill_bsums(y);
|
||||
for (sum, q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)) {
|
||||
*sum = q.iter().map(|&v| v as i32).sum::<i32>() as i16;
|
||||
}
|
||||
y.d = 1.0 / iscale;
|
||||
}
|
||||
}
|
||||
@@ -48,75 +43,29 @@ pub(super) fn q8k_fast() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var("LELEKA_Q8K").as_deref() != Ok("legacy"))
|
||||
}
|
||||
/// `q8_k` with the 256 products, roundings and the clamp in 256-bit lanes: the same IEEE multiply `iscale*x`, the same
|
||||
/// magic-number `nearest_int` (add 12582912, mantissa bits), `min(127)`; the signed maximum is the FIRST element of
|
||||
/// largest magnitude (the scalar loop's strict `>`), `d = 1/iscale`, `bsums` summed as before, and an all-zero block
|
||||
/// leaves `bsums` as the scalar one does. Inputs must be finite (the caller's check), so no NaN reaches the maximum.
|
||||
/// Bitwise `q8_k` (`q8_k_avx2_is_bitwise_q8_k`).
|
||||
/// Horizontal maximum of the 8 lanes of `m` (high half first, then the pairwise reductions).
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn q8_k_avx2(x: &[f32], y: &mut [Q8K]) {
|
||||
unsafe {
|
||||
assert_eq!(x.len(), 256 * y.len());
|
||||
for (xb, y) in x.chunks_exact(256).zip(y) {
|
||||
q8_k_avx2_block(xb, y);
|
||||
}
|
||||
}
|
||||
unsafe fn hmax_ps(m: __m256) -> f32 {
|
||||
let mut h = _mm_max_ps(_mm256_extractf128_ps::<1>(m), _mm256_castps256_ps128(m));
|
||||
h = _mm_max_ps(h, _mm_movehl_ps(h, h));
|
||||
h = _mm_max_ss(h, _mm_movehdup_ps(h));
|
||||
_mm_cvtss_f32(h)
|
||||
}
|
||||
/// One 256-float block of `q8_k_avx2`.
|
||||
/// Largest magnitude of the 256 floats of `xb`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn q8_k_avx2_block(xb: &[f32], y: &mut Q8K) {
|
||||
// SAFETY: the module header gate; `xb` is a whole 256-float block, so every 8-float load below is in range.
|
||||
unsafe {
|
||||
let amax = q8_k_amax(xb);
|
||||
if amax == 0.0 {
|
||||
y.d = 0.0;
|
||||
y.qs.fill(0);
|
||||
return;
|
||||
}
|
||||
let max = *xb.iter().find(|v| v.abs() == amax).unwrap_or(&amax);
|
||||
let iscale = -127.0 / max;
|
||||
store_q8_k_codes(xb, y, iscale);
|
||||
fill_bsums(y);
|
||||
y.d = 1.0 / iscale;
|
||||
}
|
||||
}
|
||||
/// Largest magnitude of a 256-float block: running 256-bit maximum, then the 8-lane reduction.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn q8_k_amax(xb: &[f32]) -> f32 {
|
||||
// SAFETY: the module header gate; `xb` holds 256 floats (32 loads of 8).
|
||||
unsafe fn absmax256(xb: &[f32]) -> f32 {
|
||||
unsafe {
|
||||
let sign = _mm256_set1_ps(-0.0);
|
||||
let mut m = _mm256_setzero_ps();
|
||||
for c in 0..32 {
|
||||
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, _mm256_loadu_ps(xb.as_ptr().add(8 * c))));
|
||||
}
|
||||
reduce_max_high_first(m)
|
||||
hmax_ps(m)
|
||||
}
|
||||
}
|
||||
/// The 8-lane maximum reduction of `q8_k_avx2` and `q8_zero`: the high half is the first operand of the first step.
|
||||
/// Quantize the 256 floats of `xb` with `iscale` into `y.qs` and rebuild `y.bsums`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
fn reduce_max_high_first(m: __m256) -> f32 {
|
||||
let mut h = _mm_max_ps(_mm256_extractf128_ps::<1>(m), _mm256_castps256_ps128(m));
|
||||
h = _mm_max_ps(h, _mm_movehl_ps(h, h));
|
||||
h = _mm_max_ss(h, _mm_movehdup_ps(h));
|
||||
_mm_cvtss_f32(h)
|
||||
}
|
||||
/// The 8-lane maximum reduction of `q8_one_avx2`: the low half is the first operand of the first step.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
fn reduce_max_low_first(m: __m256) -> f32 {
|
||||
let mut h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps::<1>(m));
|
||||
h = _mm_max_ps(h, _mm_movehl_ps(h, h));
|
||||
_mm_cvtss_f32(_mm_max_ss(h, _mm_movehdup_ps(h)))
|
||||
}
|
||||
/// Quantize a 256-float block to `y.qs` with the inverse scale `iscale` (multiply, magic-number rounding, clamp 127).
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn store_q8_k_codes(xb: &[f32], y: &mut Q8K, iscale: f32) {
|
||||
// SAFETY: the module header gate; `xb` holds 256 floats and `y.qs` 256 bytes (8 stores of 32).
|
||||
unsafe fn q8_k_store(xb: &[f32], iscale: f32, y: &mut Q8K) {
|
||||
unsafe {
|
||||
let vs = _mm256_set1_ps(iscale);
|
||||
let magic = _mm256_set1_ps(12_582_912.0);
|
||||
@@ -133,196 +82,124 @@ unsafe fn store_q8_k_codes(xb: &[f32], y: &mut Q8K, iscale: f32) {
|
||||
let p = _mm256_permutevar8x32_epi32(_mm256_packs_epi16(a, b), _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
|
||||
_mm256_storeu_si256(y.qs.as_mut_ptr().add(32 * g).cast(), p);
|
||||
}
|
||||
for (sum, q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)) {
|
||||
*sum = q.iter().map(|&v| v as i32).sum::<i32>() as i16;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Load a 32-float block as four 8-lane vectors.
|
||||
/// `q8_k` with the 256 products, roundings and the clamp in 256-bit lanes: the same IEEE multiply `iscale*x`, the same magic-number
|
||||
/// `nearest_int` (add 12582912, mantissa bits), `min(127)`; the signed maximum is the FIRST element of largest magnitude (the scalar loop's
|
||||
/// strict `>`), `d = 1/iscale`, `bsums` summed as before, and an all-zero block leaves `bsums` as the scalar one does. Inputs must be finite
|
||||
/// (the caller's check), so no NaN reaches the maximum. Bitwise `q8_k` (`q8_k_avx2_is_bitwise_q8_k`).
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn load_four(xb: &[f32]) -> [__m256; 4] {
|
||||
// SAFETY: the module header gate; `xb` holds 32 floats (4 loads of 8).
|
||||
unsafe { std::array::from_fn(|i| _mm256_loadu_ps(xb.as_ptr().add(8 * i))) }
|
||||
pub(super) unsafe fn q8_k_avx2(x: &[f32], y: &mut [Q8K]) {
|
||||
unsafe {
|
||||
assert_eq!(x.len(), 256 * y.len());
|
||||
for (xb, y) in x.chunks_exact(256).zip(y) {
|
||||
let amax = absmax256(xb);
|
||||
if amax == 0.0 {
|
||||
y.d = 0.0;
|
||||
y.qs.fill(0);
|
||||
continue;
|
||||
}
|
||||
let max = *xb.iter().find(|v| v.abs() == amax).unwrap_or(&amax);
|
||||
let iscale = -127.0 / max;
|
||||
q8_k_store(xb, iscale, y);
|
||||
y.d = 1.0 / iscale;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn q8_zero(x: &[f32], y: &mut [Q8Zero]) {
|
||||
unsafe {
|
||||
assert_eq!(x.len(), 32 * y.len());
|
||||
for (xb, y) in x.chunks_exact(32).zip(y) {
|
||||
q8_zero_block(xb, y);
|
||||
let mut v0 = _mm256_loadu_ps(xb.as_ptr());
|
||||
let mut v1 = _mm256_loadu_ps(xb.as_ptr().add(8));
|
||||
let mut v2 = _mm256_loadu_ps(xb.as_ptr().add(16));
|
||||
let mut v3 = _mm256_loadu_ps(xb.as_ptr().add(24));
|
||||
let sign = _mm256_set1_ps(-0.0);
|
||||
let mut m = _mm256_andnot_ps(sign, v0);
|
||||
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v1));
|
||||
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v2));
|
||||
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v3));
|
||||
let amax = hmax_ps(m);
|
||||
let d = amax / 127.0;
|
||||
y.d = to_half(d);
|
||||
let inv = _mm256_set1_ps(if amax != 0.0 { 127.0 / amax } else { 0.0 });
|
||||
v0 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v0, inv));
|
||||
v1 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v1, inv));
|
||||
v2 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v2, inv));
|
||||
v3 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v3, inv));
|
||||
let i0 = _mm256_packs_epi32(_mm256_cvtps_epi32(v0), _mm256_cvtps_epi32(v1));
|
||||
let i2 = _mm256_packs_epi32(_mm256_cvtps_epi32(v2), _mm256_cvtps_epi32(v3));
|
||||
let i0 = _mm256_packs_epi16(i0, i2);
|
||||
let i0 = _mm256_permutevar8x32_epi32(i0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
|
||||
_mm256_storeu_si256(y.qs.as_mut_ptr().cast(), i0);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// One 32-float block of `q8_zero`: half-precision scale `amax / 127`, codes `round(v * 127 / amax)`, saturated.
|
||||
/// Scale (`amax / 127`, 0 for an all-zero block) of the 32 floats `v` of a Q8 one-block.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn q8_zero_block(xb: &[f32], y: &mut Q8Zero) {
|
||||
// SAFETY: the module header gate; `xb` holds 32 floats and `y.qs` 32 bytes.
|
||||
unsafe fn q8_one_scale(v: &[__m256; 4]) -> f32 {
|
||||
let absmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff));
|
||||
let mut m = _mm256_setzero_ps();
|
||||
for x in v {
|
||||
m = _mm256_max_ps(m, _mm256_and_ps(*x, absmask));
|
||||
}
|
||||
let mut h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps::<1>(m));
|
||||
h = _mm_max_ps(h, _mm_movehl_ps(h, h));
|
||||
let amax = _mm_cvtss_f32(_mm_max_ss(h, _mm_movehdup_ps(h)));
|
||||
if amax > 0.0 { amax / 127.0 } else { 0.0 }
|
||||
}
|
||||
/// Round-half-away, clamp to +-127 and store the 32 quantized values of `v` into `qi`; returns their lane sums.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn q8_one_round(v: &[__m256; 4], inv: f32, qi: &mut [i32; 32]) -> __m256i {
|
||||
unsafe {
|
||||
let v = load_four(xb);
|
||||
let amax = q8_zero_amax(&v);
|
||||
let d = amax / 127.0;
|
||||
y.d = to_half(d);
|
||||
let inv = _mm256_set1_ps(if amax != 0.0 { 127.0 / amax } else { 0.0 });
|
||||
store_q8_zero_codes(&round_scaled(v, inv), y);
|
||||
let half = _mm256_set1_ps(0.5);
|
||||
let mhalf = _mm256_set1_ps(-0.5);
|
||||
let zero = _mm256_setzero_ps();
|
||||
let lo = _mm256_set1_epi32(-127);
|
||||
let hi = _mm256_set1_epi32(127);
|
||||
let vinv = _mm256_set1_ps(inv);
|
||||
let mut sum = _mm256_setzero_si256();
|
||||
for i in 0..4 {
|
||||
let t = _mm256_mul_ps(v[i], vinv);
|
||||
let r = _mm256_add_ps(t, _mm256_blendv_ps(mhalf, half, _mm256_cmp_ps::<_CMP_GE_OQ>(t, zero)));
|
||||
let q = _mm256_min_epi32(_mm256_max_epi32(_mm256_cvttps_epi32(r), lo), hi);
|
||||
sum = _mm256_add_epi32(sum, q);
|
||||
_mm256_storeu_si256(qi.as_mut_ptr().add(8 * i).cast(), q);
|
||||
}
|
||||
sum
|
||||
}
|
||||
}
|
||||
/// Largest magnitude of four vectors, folded in order from the first vector.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
fn q8_zero_amax(v: &[__m256; 4]) -> f32 {
|
||||
let sign = _mm256_set1_ps(-0.0);
|
||||
let mut m = _mm256_andnot_ps(sign, v[0]);
|
||||
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v[1]));
|
||||
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v[2]));
|
||||
m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v[3]));
|
||||
reduce_max_high_first(m)
|
||||
}
|
||||
/// `round_to_nearest_even(v * inv)` on four vectors.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
fn round_scaled(v: [__m256; 4], inv: __m256) -> [__m256; 4] {
|
||||
let mut r = v;
|
||||
for x in r.iter_mut() {
|
||||
*x = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(*x, inv));
|
||||
}
|
||||
r
|
||||
}
|
||||
/// Convert four rounded vectors to 32 saturated i8 codes and store them in lane order.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn store_q8_zero_codes(r: &[__m256; 4], y: &mut Q8Zero) {
|
||||
// SAFETY: the module header gate; `y.qs` holds 32 bytes, one 256-bit store.
|
||||
unsafe {
|
||||
let i0 = _mm256_packs_epi32(_mm256_cvtps_epi32(r[0]), _mm256_cvtps_epi32(r[1]));
|
||||
let i2 = _mm256_packs_epi32(_mm256_cvtps_epi32(r[2]), _mm256_cvtps_epi32(r[3]));
|
||||
let i0 = _mm256_packs_epi16(i0, i2);
|
||||
let i0 = _mm256_permutevar8x32_epi32(i0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
|
||||
_mm256_storeu_si256(y.qs.as_mut_ptr().cast(), i0);
|
||||
}
|
||||
}
|
||||
/// Scale of a q8_one chunk and its inverse (zero for an all-zero chunk).
|
||||
fn q8_one_scale(amax: f32) -> (f32, f32) {
|
||||
let s = if amax > 0.0 { amax / 127.0 } else { 0.0 };
|
||||
let inv = if s > 0.0 { 1.0 / s } else { 0.0 };
|
||||
(s, inv)
|
||||
}
|
||||
/// Record the scale, the integer sum of the codes and their product for chunk `k` of a q8_one activation.
|
||||
fn set_q8_one_chunk(a: &mut ActQ, k: usize, s: f32, total: i32) {
|
||||
a.scale[k] = s;
|
||||
a.sum[k] = total;
|
||||
a.hx[k] = s * total as f32;
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub(super) unsafe fn q8_one_avx2(x: &[f32], a: &mut ActQ) {
|
||||
unsafe {
|
||||
assert!(x.len() <= 2560 && x.len() % 32 == 0);
|
||||
a.nchunks = (x.len() / 32) as i32;
|
||||
for (k, xb) in x.chunks_exact(32).enumerate() {
|
||||
q8_one_avx2_chunk(xb, a, k);
|
||||
let v: [__m256; 4] = std::array::from_fn(|i| _mm256_loadu_ps(xb.as_ptr().add(8 * i)));
|
||||
let s = q8_one_scale(&v);
|
||||
let inv = if s > 0.0 { 1.0 / s } else { 0.0 };
|
||||
let mut qi = [0i32; 32];
|
||||
let sum = q8_one_round(&v, inv, &mut qi);
|
||||
for (j, &q) in qi.iter().enumerate() {
|
||||
a.q[k * 32 + j] = q as i8;
|
||||
}
|
||||
let mut s4 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256::<1>(sum));
|
||||
s4 = _mm_add_epi32(s4, _mm_shuffle_epi32::<0x4e>(s4));
|
||||
s4 = _mm_add_epi32(s4, _mm_shuffle_epi32::<0xb1>(s4));
|
||||
let total = _mm_cvtsi128_si32(s4);
|
||||
a.scale[k] = s;
|
||||
a.sum[k] = total;
|
||||
a.hx[k] = s * total as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Chunk `k` of `q8_one_avx2`: scale from the largest magnitude, codes rounded half away from zero and clamped at 127.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn q8_one_avx2_chunk(xb: &[f32], a: &mut ActQ, k: usize) {
|
||||
// SAFETY: the module header gate; `xb` holds 32 floats and `k * 32 + 32 <= a.q.len()` (x.len() <= 2560).
|
||||
unsafe {
|
||||
let v = load_four(xb);
|
||||
let (s, inv) = q8_one_scale(q8_one_amax(&v));
|
||||
let q = round_clamp_four(&v, _mm256_set1_ps(inv));
|
||||
store_q8_one_codes(&q, a, k);
|
||||
set_q8_one_chunk(a, k, s, sum_lanes(add_four(&q)));
|
||||
}
|
||||
}
|
||||
/// Largest magnitude of four vectors, folded from zero.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
fn q8_one_amax(v: &[__m256; 4]) -> f32 {
|
||||
let absmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff));
|
||||
let mut m = _mm256_setzero_ps();
|
||||
for x in v {
|
||||
m = _mm256_max_ps(m, _mm256_and_ps(*x, absmask));
|
||||
}
|
||||
reduce_max_low_first(m)
|
||||
}
|
||||
/// `clamp(trunc(t + copysign(0.5, t)), -127, 127)` with `t = v * vinv`, on four vectors.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
fn round_clamp_four(v: &[__m256; 4], vinv: __m256) -> [__m256i; 4] {
|
||||
let half = _mm256_set1_ps(0.5);
|
||||
let mhalf = _mm256_set1_ps(-0.5);
|
||||
let zero = _mm256_setzero_ps();
|
||||
let lo = _mm256_set1_epi32(-127);
|
||||
let hi = _mm256_set1_epi32(127);
|
||||
std::array::from_fn(|i| {
|
||||
let t = _mm256_mul_ps(v[i], vinv);
|
||||
let r = _mm256_add_ps(t, _mm256_blendv_ps(mhalf, half, _mm256_cmp_ps::<_CMP_GE_OQ>(t, zero)));
|
||||
_mm256_min_epi32(_mm256_max_epi32(_mm256_cvttps_epi32(r), lo), hi)
|
||||
})
|
||||
}
|
||||
/// The four code vectors added into one, in order from the first.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
fn add_four(q: &[__m256i; 4]) -> __m256i {
|
||||
q.iter().fold(_mm256_setzero_si256(), |sum, x| _mm256_add_epi32(sum, *x))
|
||||
}
|
||||
/// Store 32 i32 codes (each within -127..=127) as the i8 codes of chunk `k`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
unsafe fn store_q8_one_codes(q: &[__m256i; 4], a: &mut ActQ, k: usize) {
|
||||
// SAFETY: the module header gate; `qi` holds 32 i32, four 256-bit stores.
|
||||
unsafe {
|
||||
let mut qi = [0i32; 32];
|
||||
for (i, v) in q.iter().enumerate() {
|
||||
_mm256_storeu_si256(qi.as_mut_ptr().add(8 * i).cast(), *v);
|
||||
}
|
||||
for (j, &q) in qi.iter().enumerate() {
|
||||
a.q[k * 32 + j] = q as i8;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Sum of the eight i32 lanes.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
#[inline]
|
||||
fn sum_lanes(sum: __m256i) -> i32 {
|
||||
let mut s4 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256::<1>(sum));
|
||||
s4 = _mm_add_epi32(s4, _mm_shuffle_epi32::<0x4e>(s4));
|
||||
s4 = _mm_add_epi32(s4, _mm_shuffle_epi32::<0xb1>(s4));
|
||||
_mm_cvtsi128_si32(s4)
|
||||
}
|
||||
/// Round-half-away and clamp to +-127 of the 16 floats `x * vinv`.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,f16c,fma")]
|
||||
pub(super) unsafe fn q8_one_avx512(x: &[f32], a: &mut ActQ) {
|
||||
unsafe {
|
||||
assert!(x.len() <= 2560 && x.len() % 32 == 0);
|
||||
a.nchunks = (x.len() / 32) as i32;
|
||||
for (k, xb) in x.chunks_exact(32).enumerate() {
|
||||
q8_one_avx512_chunk(xb, a, k);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Chunk `k` of `q8_one_avx512`: the same rounding rule as `q8_one_avx2_chunk` on two 512-bit vectors.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,f16c,fma")]
|
||||
#[inline]
|
||||
unsafe fn q8_one_avx512_chunk(xb: &[f32], a: &mut ActQ, k: usize) {
|
||||
// SAFETY: the module header gate; `xb` holds 32 floats and `k * 32 + 32 <= a.q.len()` (x.len() <= 2560).
|
||||
unsafe {
|
||||
let absmask = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
|
||||
let x0 = _mm512_loadu_ps(xb.as_ptr());
|
||||
let x1 = _mm512_loadu_ps(xb.as_ptr().add(16));
|
||||
let amax = _mm512_reduce_max_ps(_mm512_max_ps(_mm512_and_ps(x0, absmask), _mm512_and_ps(x1, absmask)));
|
||||
let (s, inv) = q8_one_scale(amax);
|
||||
let vinv = _mm512_set1_ps(inv);
|
||||
let v0 = round_clamp_512(x0, vinv);
|
||||
let v1 = round_clamp_512(x1, vinv);
|
||||
_mm_storeu_si128(a.q.as_mut_ptr().add(k * 32).cast(), _mm512_cvtepi32_epi8(v0));
|
||||
_mm_storeu_si128(a.q.as_mut_ptr().add(k * 32 + 16).cast(), _mm512_cvtepi32_epi8(v1));
|
||||
set_q8_one_chunk(a, k, s, _mm512_reduce_add_epi32(_mm512_add_epi32(v0, v1)));
|
||||
}
|
||||
}
|
||||
/// `clamp(trunc(t + copysign(0.5, t)), -127, 127)` with `t = x * vinv`, on one 512-bit vector.
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,f16c,fma")]
|
||||
#[inline]
|
||||
fn round_clamp_512(x: __m512, vinv: __m512) -> __m512i {
|
||||
unsafe fn quant16(x: __m512, vinv: __m512) -> __m512i {
|
||||
let half = _mm512_set1_ps(0.5);
|
||||
let mhalf = _mm512_set1_ps(-0.5);
|
||||
let zero = _mm512_setzero_ps();
|
||||
@@ -332,9 +209,176 @@ fn round_clamp_512(x: __m512, vinv: __m512) -> __m512i {
|
||||
let r = _mm512_add_ps(t, _mm512_mask_blend_ps(_mm512_cmp_ps_mask::<_CMP_GE_OQ>(t, zero), mhalf, half));
|
||||
_mm512_min_epi32(_mm512_max_epi32(_mm512_cvttps_epi32(r), lo), hi)
|
||||
}
|
||||
#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,f16c,fma")]
|
||||
pub(super) unsafe fn q8_one_avx512(x: &[f32], a: &mut ActQ) {
|
||||
unsafe {
|
||||
assert!(x.len() <= 2560 && x.len() % 32 == 0);
|
||||
a.nchunks = (x.len() / 32) as i32;
|
||||
let absmask = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
|
||||
for (k, xb) in x.chunks_exact(32).enumerate() {
|
||||
let x0 = _mm512_loadu_ps(xb.as_ptr());
|
||||
let x1 = _mm512_loadu_ps(xb.as_ptr().add(16));
|
||||
let amax = _mm512_reduce_max_ps(_mm512_max_ps(_mm512_and_ps(x0, absmask), _mm512_and_ps(x1, absmask)));
|
||||
let s = if amax > 0.0 { amax / 127.0 } else { 0.0 };
|
||||
let inv = if s > 0.0 { 1.0 / s } else { 0.0 };
|
||||
let vinv = _mm512_set1_ps(inv);
|
||||
let v0 = quant16(x0, vinv);
|
||||
let v1 = quant16(x1, vinv);
|
||||
_mm_storeu_si128(a.q.as_mut_ptr().add(k * 32).cast(), _mm512_cvtepi32_epi8(v0));
|
||||
_mm_storeu_si128(a.q.as_mut_ptr().add(k * 32 + 16).cast(), _mm512_cvtepi32_epi8(v1));
|
||||
let sum = _mm512_reduce_add_epi32(_mm512_add_epi32(v0, v1));
|
||||
a.scale[k] = s;
|
||||
a.sum[k] = sum;
|
||||
a.hx[k] = s * sum as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod tests {
|
||||
use super::*;
|
||||
// Original expert.cpp scalar rule, evaluated FIRST without SIMD quantization.
|
||||
// This bounded transport-free oracle covers tie rounding and the whole public
|
||||
// activation extent. It does not qualify IQ dots or model output.
|
||||
fn original_scalar(x: &[f32]) -> ActQ {
|
||||
let mut a = ActQ::default();
|
||||
a.nchunks = (x.len() / 32) as i32;
|
||||
for (k, xb) in x.chunks_exact(32).enumerate() {
|
||||
let mut maximum = 0.0f32;
|
||||
for &value in xb {
|
||||
maximum = maximum.max(value.abs());
|
||||
}
|
||||
let scale = if maximum > 0.0 { maximum / 127.0 } else { 0.0 };
|
||||
let inv = if scale > 0.0 { 1.0 / scale } else { 0.0 };
|
||||
let mut sum = 0i32;
|
||||
for (j, &value) in xb.iter().enumerate() {
|
||||
let t = value * inv;
|
||||
let rounded = t + if t >= 0.0 { 0.5 } else { -0.5 };
|
||||
let q = (rounded as i32).clamp(-127, 127);
|
||||
a.q[k * 32 + j] = q as i8;
|
||||
sum += q;
|
||||
}
|
||||
a.scale[k] = scale;
|
||||
a.sum[k] = sum;
|
||||
a.hx[k] = scale * sum as f32;
|
||||
}
|
||||
a
|
||||
}
|
||||
fn exact(actual: &ActQ, expected: &ActQ, n: usize) {
|
||||
assert_eq!(actual.nchunks, expected.nchunks);
|
||||
assert_eq!(&actual.q[..n], &expected.q[..n]);
|
||||
assert_eq!(&actual.sum[..n / 32], &expected.sum[..n / 32]);
|
||||
for k in 0..n / 32 {
|
||||
assert_eq!(actual.scale[k].to_bits(), expected.scale[k].to_bits());
|
||||
assert_eq!(actual.hx[k].to_bits(), expected.hx[k].to_bits());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn original_scalar_first_q8_one_ties_zero_and_full_rows() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
eprintln!("SKIP: Original AVX2/F16C/FMA capability required");
|
||||
return;
|
||||
}
|
||||
for n in [640usize, 2560] {
|
||||
for changed in [false, true] {
|
||||
let mut x = vec![0.0f32; n];
|
||||
for (i, value) in x.iter_mut().enumerate() {
|
||||
*value = match i % 32 {
|
||||
0 => 127.0,
|
||||
1 => -127.0,
|
||||
2 => 0.5,
|
||||
3 => -0.5,
|
||||
4 => 1.5,
|
||||
5 => -1.5,
|
||||
6 => 0.0,
|
||||
7 => -0.0,
|
||||
_ => {
|
||||
if changed {
|
||||
(i % 61) as f32 - 30.0
|
||||
} else {
|
||||
(i % 47) as f32 - 23.0
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
let expected = original_scalar(&x);
|
||||
let mut actual = ActQ::default();
|
||||
// SAFETY: actual CPUID/XCR0 admission above; whole sanitized arrays.
|
||||
unsafe {
|
||||
q8_one_avx2(&x, &mut actual);
|
||||
}
|
||||
exact(&actual, &expected, n);
|
||||
if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() {
|
||||
unsafe {
|
||||
q8_one_avx512(&x, &mut actual);
|
||||
}
|
||||
exact(&actual, &expected, n);
|
||||
}
|
||||
x.fill(-0.0);
|
||||
let expected = original_scalar(&x);
|
||||
unsafe {
|
||||
q8_one_avx2(&x, &mut actual);
|
||||
}
|
||||
exact(&actual, &expected, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod q8k_tests;
|
||||
mod q8k_tests {
|
||||
use super::*;
|
||||
fn xorshift(s: &mut u64) -> u64 {
|
||||
*s ^= *s << 13;
|
||||
*s ^= *s >> 7;
|
||||
*s ^= *s << 17;
|
||||
*s
|
||||
}
|
||||
#[test]
|
||||
fn q8_k_avx2_is_bitwise_q8_k() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
eprintln!("SKIP");
|
||||
return;
|
||||
}
|
||||
let mut seed = 0x7a11_5eed_0102_0304u64;
|
||||
for round in 0..400 {
|
||||
let nb = 10;
|
||||
let scale = [1e-6f32, 1e-3, 0.5, 3.0, 1e3, 3e4][round % 6];
|
||||
let mut x: Vec<f32> =
|
||||
(0..nb * 256).map(|_| ((xorshift(&mut seed) % 200001) as f32 - 100000.0) * scale / 1e5).collect();
|
||||
// ties of magnitude with both signs, zero blocks, rounding-half cases
|
||||
if round % 5 == 1 {
|
||||
x[3] = 7.0 * scale;
|
||||
x[200] = -7.0 * scale;
|
||||
for v in x[256..512].iter_mut() {
|
||||
*v = 0.0;
|
||||
}
|
||||
}
|
||||
if round % 5 == 2 {
|
||||
let m = x[..256].iter().fold(0.0f32, |a, v| a.max(v.abs()));
|
||||
x[10] = -m;
|
||||
x[11] = m;
|
||||
}
|
||||
if round % 5 == 3 {
|
||||
for (i, v) in x.iter_mut().enumerate().take(256) {
|
||||
*v = (i as f32 - 128.0) * 0.5;
|
||||
}
|
||||
}
|
||||
let mut a = vec![Q8K::default(); nb];
|
||||
let mut b = vec![Q8K::default(); nb];
|
||||
for (i, (p, q)) in a.iter_mut().zip(b.iter_mut()).enumerate() {
|
||||
p.bsums = [i as i16; 16];
|
||||
q.bsums = [i as i16; 16];
|
||||
}
|
||||
q8_k(&x, &mut a);
|
||||
unsafe {
|
||||
q8_k_avx2(&x, &mut b);
|
||||
}
|
||||
for (i, (p, q)) in a.iter().zip(&b).enumerate() {
|
||||
assert_eq!(p.d.to_bits(), q.d.to_bits(), "d round {round} block {i}");
|
||||
assert_eq!(p.qs, q.qs, "qs round {round} block {i}");
|
||||
assert_eq!(p.bsums, q.bsums, "bsums round {round} block {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
//! Moved out of rust_quant.rs by STRA-338 (same module path as before).
|
||||
|
||||
use super::*;
|
||||
fn xorshift(s: &mut u64) -> u64 {
|
||||
*s ^= *s << 13;
|
||||
*s ^= *s >> 7;
|
||||
*s ^= *s << 17;
|
||||
*s
|
||||
}
|
||||
/// Special inputs in three of every five rounds: ties of magnitude with both signs, zero blocks, rounding-half cases.
|
||||
fn apply_special_case(round: usize, scale: f32, x: &mut [f32]) {
|
||||
if round % 5 == 1 {
|
||||
x[3] = 7.0 * scale;
|
||||
x[200] = -7.0 * scale;
|
||||
x[256..512].fill(0.0);
|
||||
}
|
||||
if round % 5 == 2 {
|
||||
let m = x[..256].iter().fold(0.0f32, |a, v| a.max(v.abs()));
|
||||
x[10] = -m;
|
||||
x[11] = m;
|
||||
}
|
||||
if round % 5 == 3 {
|
||||
for (i, v) in x.iter_mut().enumerate().take(256) {
|
||||
*v = (i as f32 - 128.0) * 0.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn round_input(round: usize, nb: usize, seed: &mut u64) -> Vec<f32> {
|
||||
let scale = [1e-6f32, 1e-3, 0.5, 3.0, 1e3, 3e4][round % 6];
|
||||
let mut x: Vec<f32> = (0..nb * 256).map(|_| ((xorshift(seed) % 200001) as f32 - 100000.0) * scale / 1e5).collect();
|
||||
apply_special_case(round, scale, &mut x);
|
||||
x
|
||||
}
|
||||
/// Output blocks whose `bsums` start as the block index, so a block left untouched is told apart from a zeroed one.
|
||||
fn marked_blocks(nb: usize) -> Vec<Q8K> {
|
||||
let mut blocks = vec![Q8K::default(); nb];
|
||||
for (i, p) in blocks.iter_mut().enumerate() {
|
||||
p.bsums = [i as i16; 16];
|
||||
}
|
||||
blocks
|
||||
}
|
||||
fn assert_blocks_equal(round: usize, a: &[Q8K], b: &[Q8K]) {
|
||||
for (i, (p, q)) in a.iter().zip(b).enumerate() {
|
||||
assert_eq!(p.d.to_bits(), q.d.to_bits(), "d round {round} block {i}");
|
||||
assert_eq!(p.qs, q.qs, "qs round {round} block {i}");
|
||||
assert_eq!(p.bsums, q.bsums, "bsums round {round} block {i}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn q8_k_avx2_is_bitwise_q8_k() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
eprintln!("SKIP");
|
||||
return;
|
||||
}
|
||||
let mut seed = 0x7a11_5eed_0102_0304u64;
|
||||
for round in 0..400 {
|
||||
let nb = 10;
|
||||
let x = round_input(round, nb, &mut seed);
|
||||
let (mut a, mut b) = (marked_blocks(nb), marked_blocks(nb));
|
||||
q8_k(&x, &mut a);
|
||||
// SAFETY: avx2_ok() above; x holds nb * 256 floats for nb blocks.
|
||||
unsafe {
|
||||
q8_k_avx2(&x, &mut b);
|
||||
}
|
||||
assert_blocks_equal(round, &a, &b);
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
//! Moved out of rust_quant.rs by STRA-338 (same module path as before).
|
||||
|
||||
use super::*;
|
||||
// Original expert.cpp scalar rule, evaluated FIRST without SIMD quantization.
|
||||
// This bounded transport-free oracle covers tie rounding and the whole public
|
||||
// activation extent. It does not qualify IQ dots or model output.
|
||||
fn original_scalar(x: &[f32]) -> ActQ {
|
||||
let mut a = ActQ::default();
|
||||
a.nchunks = (x.len() / 32) as i32;
|
||||
for (k, xb) in x.chunks_exact(32).enumerate() {
|
||||
let mut maximum = 0.0f32;
|
||||
for &value in xb {
|
||||
maximum = maximum.max(value.abs());
|
||||
}
|
||||
let scale = if maximum > 0.0 { maximum / 127.0 } else { 0.0 };
|
||||
let inv = if scale > 0.0 { 1.0 / scale } else { 0.0 };
|
||||
let mut sum = 0i32;
|
||||
for (j, &value) in xb.iter().enumerate() {
|
||||
let t = value * inv;
|
||||
let rounded = t + if t >= 0.0 { 0.5 } else { -0.5 };
|
||||
let q = (rounded as i32).clamp(-127, 127);
|
||||
a.q[k * 32 + j] = q as i8;
|
||||
sum += q;
|
||||
}
|
||||
a.scale[k] = scale;
|
||||
a.sum[k] = sum;
|
||||
a.hx[k] = scale * sum as f32;
|
||||
}
|
||||
a
|
||||
}
|
||||
fn exact(actual: &ActQ, expected: &ActQ, n: usize) {
|
||||
assert_eq!(actual.nchunks, expected.nchunks);
|
||||
assert_eq!(&actual.q[..n], &expected.q[..n]);
|
||||
assert_eq!(&actual.sum[..n / 32], &expected.sum[..n / 32]);
|
||||
for k in 0..n / 32 {
|
||||
assert_eq!(actual.scale[k].to_bits(), expected.scale[k].to_bits());
|
||||
assert_eq!(actual.hx[k].to_bits(), expected.hx[k].to_bits());
|
||||
}
|
||||
}
|
||||
/// The first eight lanes of every chunk of the tie fixture: the fixed tie and zero cases.
|
||||
const TIES: [f32; 8] = [127.0, -127.0, 0.5, -0.5, 1.5, -1.5, 0.0, -0.0];
|
||||
/// Value `i` of the tie fixture.
|
||||
fn tie_value(i: usize, changed: bool) -> f32 {
|
||||
match TIES.get(i % 32) {
|
||||
Some(&tie) => tie,
|
||||
None if changed => (i % 61) as f32 - 30.0,
|
||||
None => (i % 47) as f32 - 23.0,
|
||||
}
|
||||
}
|
||||
fn tie_fixture(n: usize, changed: bool) -> Vec<f32> {
|
||||
(0..n).map(|i| tie_value(i, changed)).collect()
|
||||
}
|
||||
fn check_avx2(x: &[f32], actual: &mut ActQ, expected: &ActQ, n: usize) {
|
||||
// SAFETY: actual CPUID/XCR0 admission by the caller; whole sanitized arrays.
|
||||
unsafe {
|
||||
q8_one_avx2(x, actual);
|
||||
}
|
||||
exact(actual, expected, n);
|
||||
}
|
||||
fn check_avx512(x: &[f32], actual: &mut ActQ, expected: &ActQ, n: usize) {
|
||||
// SAFETY: avx512_ok() and dq_ok() admitted by the caller; whole sanitized arrays.
|
||||
unsafe {
|
||||
q8_one_avx512(x, actual);
|
||||
}
|
||||
exact(actual, expected, n);
|
||||
}
|
||||
fn check_tie_case(n: usize, changed: bool) {
|
||||
let mut x = tie_fixture(n, changed);
|
||||
let expected = original_scalar(&x);
|
||||
let mut actual = ActQ::default();
|
||||
check_avx2(&x, &mut actual, &expected, n);
|
||||
if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() {
|
||||
check_avx512(&x, &mut actual, &expected, n);
|
||||
}
|
||||
x.fill(-0.0);
|
||||
let expected = original_scalar(&x);
|
||||
check_avx2(&x, &mut actual, &expected, n);
|
||||
}
|
||||
#[test]
|
||||
fn original_scalar_first_q8_one_ties_zero_and_full_rows() {
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
eprintln!("SKIP: Original AVX2/F16C/FMA capability required");
|
||||
return;
|
||||
}
|
||||
for n in [640usize, 2560] {
|
||||
for changed in [false, true] {
|
||||
check_tie_case(n, changed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,8 +142,7 @@ pub(super) unsafe fn signs32(m: u32) -> __m256i {
|
||||
}
|
||||
#[target_feature(enable = "avx2")]
|
||||
/// # Safety
|
||||
/// Only the target feature: PREFETCH never faults and reads nothing, so `p` may be any address (wrapping_add, no
|
||||
/// deref).
|
||||
/// Only the target feature: PREFETCH never faults and reads nothing, so `p` may be any address (wrapping_add, no deref).
|
||||
pub(super) unsafe fn prefetch(p: *const u8) {
|
||||
let n = dispatch().prefetch;
|
||||
if n > 0 {
|
||||
|
||||
@@ -25,51 +25,40 @@ unsafe extern "C" {
|
||||
}
|
||||
#[cfg(unix)]
|
||||
fn number(path: String) -> i64 {
|
||||
std::fs::read_to_string(path).map_or(-1, |text| super::rust_platform::parse_leading_number(&text))
|
||||
std::fs::read_to_string(path).ok().and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or(-1)
|
||||
}
|
||||
/// What sysfs says about one logical CPU (-1 where a file is missing or has no number).
|
||||
#[cfg(unix)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct CpuInfo {
|
||||
cpu: i32,
|
||||
package: i64,
|
||||
core: i64,
|
||||
capacity: i64,
|
||||
}
|
||||
#[cfg(unix)]
|
||||
fn read_cpu_info(cpu: i32) -> CpuInfo {
|
||||
let package = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/physical_package_id"));
|
||||
let core = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/core_id"));
|
||||
let capacity = number(format!("/sys/devices/system/cpu/cpu{cpu}/cpu_capacity"));
|
||||
CpuInfo { cpu, package, core, capacity }
|
||||
}
|
||||
/// The logical CPUs this process may run on: its affinity mask, else every CPU `available_parallelism` counts.
|
||||
#[cfg(unix)]
|
||||
fn allowed_cpus() -> Vec<i32> {
|
||||
let mut mask = [0usize; 16];
|
||||
if
|
||||
/* SAFETY: `mask` is a live, writable 128-byte cpu_set_t-sized buffer; no pointer is retained. */
|
||||
unsafe { sched_getaffinity(0, std::mem::size_of_val(&mask), mask.as_mut_ptr()) } == 0 {
|
||||
return super::rust_platform::mask_cpus(&mask);
|
||||
let mut allowed = Vec::new();
|
||||
// SAFETY: `mask` is a live, writable 128-byte cpu_set_t-sized buffer; no pointer is retained.
|
||||
let read = unsafe { sched_getaffinity(0, std::mem::size_of_val(&mask), mask.as_mut_ptr()) } == 0;
|
||||
if read {
|
||||
for i in 0..1024 {
|
||||
if mask[i / 64] & (1usize << (i % 64)) != 0 {
|
||||
allowed.push(i as i32);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
allowed.extend(0..std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0) as i32);
|
||||
}
|
||||
(0..std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0) as i32).collect()
|
||||
allowed
|
||||
}
|
||||
/// The CPUs in the order read, each with its capacity and whether an earlier CPU already has its (package, core) ids
|
||||
/// (an SMT sibling); the highest and lowest nonzero capacity; the number of distinct cores.
|
||||
/// Per-CPU (id, capacity, is-SMT-sibling) plus the distinct physical-core count and the capacity range.
|
||||
#[cfg(unix)]
|
||||
struct Scan {
|
||||
rows: Vec<(i32, i64, bool)>,
|
||||
struct CpuScan {
|
||||
all: Vec<(i32, i64, bool)>,
|
||||
cores: usize,
|
||||
max: i64,
|
||||
min: i64,
|
||||
}
|
||||
/// True when `info` has the (package, core) ids of an earlier CPU; else the pair is recorded in `seen`.
|
||||
/// True when `(package, core)` was already seen (an SMT sibling); records it otherwise. Unknown ids are never siblings.
|
||||
#[cfg(unix)]
|
||||
fn record_core(seen: &mut Vec<(i64, i64)>, info: &CpuInfo) -> bool {
|
||||
if info.package < 0 || info.core < 0 {
|
||||
fn is_sibling(seen: &mut Vec<(i64, i64)>, package: i64, core: i64) -> bool {
|
||||
if package < 0 || core < 0 {
|
||||
return false;
|
||||
}
|
||||
let key = (info.package, info.core);
|
||||
let key = (package, core);
|
||||
if seen.contains(&key) {
|
||||
return true;
|
||||
}
|
||||
@@ -77,88 +66,84 @@ fn record_core(seen: &mut Vec<(i64, i64)>, info: &CpuInfo) -> bool {
|
||||
false
|
||||
}
|
||||
#[cfg(unix)]
|
||||
fn scan_cpus(infos: &[CpuInfo]) -> Scan {
|
||||
fn scan_cpus(allowed: Vec<i32>) -> CpuScan {
|
||||
let mut seen = Vec::new();
|
||||
let mut rows = Vec::new();
|
||||
let mut all = Vec::new();
|
||||
let mut max = 0;
|
||||
let mut min = 1_000_000;
|
||||
for info in infos {
|
||||
if info.capacity > 0 {
|
||||
max = max.max(info.capacity);
|
||||
min = min.min(info.capacity);
|
||||
for cpu in allowed {
|
||||
let package = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/physical_package_id"));
|
||||
let core = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/core_id"));
|
||||
let cap = number(format!("/sys/devices/system/cpu/cpu{cpu}/cpu_capacity"));
|
||||
if cap > 0 {
|
||||
max = max.max(cap);
|
||||
min = min.min(cap);
|
||||
}
|
||||
let sibling = record_core(&mut seen, info);
|
||||
rows.push((info.cpu, info.capacity, sibling));
|
||||
let sibling = is_sibling(&mut seen, package, core);
|
||||
all.push((cpu, cap, sibling));
|
||||
}
|
||||
Scan { rows, cores: seen.len(), max, min }
|
||||
CpuScan { all, cores: seen.len(), max, min }
|
||||
}
|
||||
/// Performance cores, performance threads and efficiency cores: by capacity on a hybrid CPU, else the plain counts.
|
||||
/// Fill the core/thread counts of `t` from the scan (`t.is_hybrid` already set).
|
||||
#[cfg(unix)]
|
||||
fn count_cores(scan: &Scan, is_hybrid: bool) -> (usize, usize, usize) {
|
||||
if !is_hybrid {
|
||||
return (scan.cores, scan.rows.len(), 0);
|
||||
fn count_cores(t: &mut CpuTopology, scan: &CpuScan) {
|
||||
if !t.is_hybrid {
|
||||
t.p_cores = scan.cores;
|
||||
t.p_threads = scan.all.len();
|
||||
return;
|
||||
}
|
||||
let (mut p_cores, mut p_threads, mut e_cores) = (0, 0, 0);
|
||||
for &(_, cap, sibling) in &scan.rows {
|
||||
for &(_, cap, sibling) in &scan.all {
|
||||
if cap == scan.max {
|
||||
if !sibling {
|
||||
p_cores += 1;
|
||||
t.p_cores += 1;
|
||||
}
|
||||
p_threads += 1;
|
||||
t.p_threads += 1;
|
||||
} else if !sibling {
|
||||
e_cores += 1;
|
||||
t.e_cores += 1;
|
||||
}
|
||||
}
|
||||
(p_cores, p_threads, e_cores)
|
||||
}
|
||||
/// The host core (the first worker core when `skip_first`, else -1) and the worker cores: one thread per core.
|
||||
/// Hybrid worker order: primary P threads, then P siblings, then (unless P-cores only) the efficient cores.
|
||||
#[cfg(unix)]
|
||||
fn plain_cores(scan: &Scan, skip_first: bool) -> (i32, Vec<i32>) {
|
||||
let mut workers: Vec<i32> = scan.rows.iter().filter_map(|&(cpu, _, sib)| (!sib).then_some(cpu)).collect();
|
||||
let host = if skip_first && !workers.is_empty() { workers.remove(0) } else { -1 };
|
||||
(host, workers)
|
||||
}
|
||||
/// The host core and the worker cores of a hybrid CPU: the performance cores, then their siblings, then (unless
|
||||
/// `PCores`) the efficiency cores.
|
||||
#[cfg(unix)]
|
||||
fn hybrid_cores(scan: &Scan, skip_first: bool, affinity: PoolAffinity) -> (i32, Vec<i32>) {
|
||||
fn order_hybrid_workers(t: &mut CpuTopology, scan: CpuScan, skip_first: bool, affinity: PoolAffinity) {
|
||||
let mut primary = Vec::new();
|
||||
let mut siblings = Vec::new();
|
||||
let mut efficient = Vec::new();
|
||||
for &(cpu, cap, sib) in &scan.rows {
|
||||
if cap != scan.max {
|
||||
efficient.push(cpu);
|
||||
} else if sib {
|
||||
siblings.push(cpu);
|
||||
for (cpu, cap, sib) in scan.all {
|
||||
if cap == scan.max {
|
||||
if sib {
|
||||
siblings.push(cpu);
|
||||
} else {
|
||||
primary.push(cpu);
|
||||
}
|
||||
} else {
|
||||
primary.push(cpu);
|
||||
efficient.push(cpu);
|
||||
}
|
||||
}
|
||||
let host = if skip_first && !primary.is_empty() { primary.remove(0) } else { -1 };
|
||||
let mut workers = primary;
|
||||
workers.extend(siblings);
|
||||
if skip_first && !primary.is_empty() {
|
||||
t.host_core = primary.remove(0);
|
||||
}
|
||||
t.worker_cores = primary;
|
||||
t.worker_cores.extend(siblings);
|
||||
if affinity != PoolAffinity::PCores {
|
||||
workers.extend(efficient);
|
||||
t.worker_cores.extend(efficient);
|
||||
}
|
||||
(host, workers)
|
||||
}
|
||||
/// The topology the sysfs descriptions `infos` of the allowed CPUs give.
|
||||
#[cfg(unix)]
|
||||
fn topology_from(infos: &[CpuInfo], skip_first: bool, affinity: PoolAffinity) -> CpuTopology {
|
||||
let scan = scan_cpus(infos);
|
||||
let is_hybrid = scan.max > 0 && scan.max > scan.min;
|
||||
let (p_cores, p_threads, e_cores) = count_cores(&scan, is_hybrid);
|
||||
let (host_core, worker_cores) = if affinity == PoolAffinity::All || !is_hybrid {
|
||||
plain_cores(&scan, skip_first)
|
||||
} else {
|
||||
hybrid_cores(&scan, skip_first, affinity)
|
||||
};
|
||||
CpuTopology { is_hybrid, p_cores, p_threads, e_cores, worker_cores, host_core }
|
||||
}
|
||||
#[cfg(unix)]
|
||||
pub fn detect_cpu_topology(skip_first: bool, affinity: PoolAffinity) -> CpuTopology {
|
||||
let infos: Vec<CpuInfo> = allowed_cpus().into_iter().map(read_cpu_info).collect();
|
||||
topology_from(&infos, skip_first, affinity)
|
||||
let mut t = CpuTopology { host_core: -1, ..CpuTopology::default() };
|
||||
let scan = scan_cpus(allowed_cpus());
|
||||
t.is_hybrid = scan.max > 0 && scan.max > scan.min;
|
||||
count_cores(&mut t, &scan);
|
||||
if affinity == PoolAffinity::All || !t.is_hybrid {
|
||||
t.worker_cores = scan.all.iter().filter_map(|&(cpu, _, sib)| (!sib).then_some(cpu)).collect();
|
||||
if skip_first && !t.worker_cores.is_empty() {
|
||||
t.host_core = t.worker_cores.remove(0);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
order_hybrid_workers(&mut t, scan, skip_first, affinity);
|
||||
t
|
||||
}
|
||||
#[cfg(unix)]
|
||||
pub fn pin_current_thread(core: i32) -> i64 {
|
||||
@@ -166,9 +151,9 @@ pub fn pin_current_thread(core: i32) -> i64 {
|
||||
return -1;
|
||||
}
|
||||
let mut old = [0usize; 16];
|
||||
if
|
||||
/* SAFETY: `old` is a live 128-byte cpu_set_t-sized buffer for the calling thread. */
|
||||
unsafe { pthread_getaffinity_np(pthread_self(), std::mem::size_of_val(&old), old.as_mut_ptr()) } != 0 {
|
||||
// SAFETY: `old` is a live 128-byte cpu_set_t-sized buffer for the calling thread.
|
||||
let failed = unsafe { pthread_getaffinity_np(pthread_self(), std::mem::size_of_val(&old), old.as_mut_ptr()) } != 0;
|
||||
if failed {
|
||||
return -1;
|
||||
}
|
||||
let previous = old[0] as i64;
|
||||
@@ -181,7 +166,8 @@ pub fn restore_thread_affinity(previous: i64) {
|
||||
return;
|
||||
}
|
||||
let mut mask = [0usize; 16];
|
||||
mask[0] = previous as usize; /* SAFETY: `mask` is a live 128-byte mask; a refusal leaves the thread where it is. */
|
||||
mask[0] = previous as usize;
|
||||
// SAFETY: `mask` is a live 128-byte mask; a refusal leaves the thread where it is.
|
||||
unsafe {
|
||||
let _ = pthread_setaffinity_np(pthread_self(), std::mem::size_of_val(&mask), mask.as_ptr());
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
use super::rust_dequant::half_rn;
|
||||
use super::rust_ggml::Kind;
|
||||
use super::rust_quant_grids::*;
|
||||
use super::rust_weight_quant::{nearest, qp, sum_squares};
|
||||
use super::rust_weight_quant::{nearest, qp};
|
||||
use super::{Error, Result};
|
||||
use std::sync::{Arc, Mutex};
|
||||
struct Grid {
|
||||
@@ -30,15 +30,6 @@ unsafe extern "C" {
|
||||
);
|
||||
}
|
||||
|
||||
mod block_stats;
|
||||
#[allow(unused_imports)]
|
||||
use block_stats::{block_weights, max_abs, max_value, negate_signs, square_roots};
|
||||
mod candidates;
|
||||
#[allow(unused_imports)]
|
||||
use candidates::{Folded, Plan, refit_off_grid, search_scale};
|
||||
mod iq1_split;
|
||||
#[allow(unused_imports)]
|
||||
use iq1_split::{Split, accumulate_group, flip_levels, three_levels};
|
||||
mod alloc_fn;
|
||||
#[allow(unused_imports)]
|
||||
use alloc_fn::alloc;
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
//! Reductions and small helpers shared by the IQ block quantizers.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Largest magnitude of a block.
|
||||
pub(super) fn max_abs(xb: &[f32]) -> f32 {
|
||||
let mut max = xb[0].abs();
|
||||
for &v in &xb[1..] {
|
||||
if v.abs() > max {
|
||||
max = v.abs();
|
||||
}
|
||||
}
|
||||
max
|
||||
}
|
||||
/// Largest value of a block of magnitudes.
|
||||
pub(super) fn max_value(xv: &[f32]) -> f32 {
|
||||
let mut max = xv[0];
|
||||
for &v in &xv[1..] {
|
||||
if v > max {
|
||||
max = v;
|
||||
}
|
||||
}
|
||||
max
|
||||
}
|
||||
/// Importance weights of the block at `at`: the imatrix scaled by the block energy, or `plain(i)` without one.
|
||||
pub(super) fn block_weights<const N: usize>(
|
||||
xb: &[f32],
|
||||
at: usize,
|
||||
qw: Option<&[f32]>,
|
||||
sigma: f32,
|
||||
plain: impl Fn(usize) -> f32,
|
||||
) -> [f32; N] {
|
||||
std::array::from_fn(|i| qw.map_or(plain(i), |q| q[at + i] * (sigma + xb[i] * xb[i]).sqrt()))
|
||||
}
|
||||
pub(super) fn square_roots<const N: usize>(w: &[f32; N]) -> [f32; N] {
|
||||
std::array::from_fn(|i| w[i].sqrt())
|
||||
}
|
||||
/// Complements the sign bytes within `mask` (127 for seven-bit signs, 255 for whole bytes).
|
||||
pub(super) fn negate_signs(signs: &mut [u8], mask: u8) {
|
||||
for s in signs {
|
||||
*s = !*s & mask;
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
//! The scale search over grid-candidate level assignments shared by the IQ2_XS, IQ2_S and IQ3 blocks.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// One block as the search sees it: sign-folded magnitudes, weights and their square roots.
|
||||
pub(super) struct Folded<'a, const N: usize> {
|
||||
pub(super) xv: &'a [f32; N],
|
||||
pub(super) w: &'a [f32; N],
|
||||
pub(super) wa: &'a [f32; N],
|
||||
}
|
||||
/// The trial inverse scales `(center + is * step) / max` for `is` in `-tries..=tries`; `top` bounds the levels.
|
||||
pub(super) struct Plan {
|
||||
pub(super) center: f32,
|
||||
pub(super) step: f32,
|
||||
pub(super) tries: i32,
|
||||
pub(super) top: i32,
|
||||
}
|
||||
/// Levels, per-group on-grid flags and scale of the best trial.
|
||||
pub(super) struct Fit<const N: usize, const K: usize> {
|
||||
pub(super) l: [i8; N],
|
||||
pub(super) on: [bool; K],
|
||||
pub(super) scale: f32,
|
||||
}
|
||||
/// Tries every inverse scale of the plan and keeps the assignment with the best weighted fit.
|
||||
pub(super) fn search_scale<const N: usize, const K: usize>(
|
||||
g: &Grid,
|
||||
b: &Folded<N>,
|
||||
max: f32,
|
||||
plan: &Plan,
|
||||
on: [bool; K],
|
||||
) -> Fit<N, K> {
|
||||
let mut fit = Fit { l: [0; N], on, scale: max / plan.center };
|
||||
let mut best = 0.0;
|
||||
for is in -plan.tries..=plan.tries {
|
||||
let inv = (plan.center + is as f32 * plan.step) / max;
|
||||
let mut aux = [0i8; N];
|
||||
let mut ao = [true; K];
|
||||
quant_candidates(g, inv, b.xv, b.wa, 1.0 / inv, &mut aux, plan.top, &mut ao);
|
||||
let (sx, s2) = totals(b.xv, b.w, &aux);
|
||||
if s2 > 0.0 && sx * sx > best * s2 {
|
||||
fit.scale = sx / s2;
|
||||
best = fit.scale * sx;
|
||||
fit.l = aux;
|
||||
fit.on = ao;
|
||||
}
|
||||
}
|
||||
fit
|
||||
}
|
||||
/// Re-rounds the groups that missed the grid (all of them when `all_groups`) against the fitted scale and
|
||||
/// refits the scale to the result.
|
||||
pub(super) fn refit_off_grid<const N: usize, const K: usize>(
|
||||
g: &Grid,
|
||||
b: &Folded<N>,
|
||||
fit: &mut Fit<N, K>,
|
||||
top: i32,
|
||||
all_groups: bool,
|
||||
) {
|
||||
if !(fit.on.iter().any(|v| !*v) && fit.scale > 0.0) {
|
||||
return;
|
||||
}
|
||||
let inv = 1.0 / fit.scale;
|
||||
for k in 0..K {
|
||||
if !all_groups && fit.on[k] {
|
||||
continue;
|
||||
}
|
||||
let at = k * g.dim;
|
||||
for j in 0..g.dim {
|
||||
fit.l[at + j] = nearest(0.5 * (inv * b.xv[at + j] - 1.0)).clamp(0, top - 1) as i8;
|
||||
}
|
||||
g.resolve(&mut fit.l[at..at + g.dim], &b.xv[at..at + g.dim], &b.wa[at..at + g.dim], fit.scale);
|
||||
}
|
||||
let (sx, s2) = totals(b.xv, b.w, &fit.l);
|
||||
if s2 > 0.0 {
|
||||
fit.scale = sx / s2;
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
//! The three-level split of a sorted block and the grid resolution shared by the IQ1_S and IQ1_M blocks.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The best split of a sorted block into three level runs: both cut positions, the scale and a variant tag
|
||||
/// (the shift sign of IQ1_S, the delta pattern of IQ1_M).
|
||||
pub(super) struct Split {
|
||||
pub(super) scale: f32,
|
||||
pub(super) b1: usize,
|
||||
pub(super) b2: usize,
|
||||
pub(super) tag: i8,
|
||||
}
|
||||
/// Levels 0, 1, 2 for the sorted positions before `b1`, before `b2` and after; `p` maps positions to elements.
|
||||
pub(super) fn three_levels<const N: usize>(p: &[Pair; N], b1: usize, b2: usize) -> [i8; N] {
|
||||
let mut l = [0i8; N];
|
||||
for j in 0..N {
|
||||
l[p[j].index as usize] = if j < b1 {
|
||||
0
|
||||
} else if j < b2 {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
}
|
||||
l
|
||||
}
|
||||
/// Mirrors the three levels (0 <-> 2) after a negative scale was made positive.
|
||||
pub(super) fn flip_levels(l: &mut [i8]) {
|
||||
for q in l {
|
||||
*q = 2 - *q;
|
||||
}
|
||||
}
|
||||
/// Adds the weighted moments of the grid point `index` read through `values` (and scaled by `mult`) to `acc`.
|
||||
pub(super) fn accumulate_group(
|
||||
g: &Grid,
|
||||
index: usize,
|
||||
(x8, w8): (&[f32], &[f32]),
|
||||
(values, mult): (&[f32; 3], f32),
|
||||
acc: (f32, f32),
|
||||
) -> (f32, f32) {
|
||||
let (mut qx, mut q2) = acc;
|
||||
let p = &g.points[index];
|
||||
for j in 0..8 {
|
||||
let q = values[((p[j] - 1) / 2) as usize] * mult;
|
||||
qx += w8[j] * q * x8[j];
|
||||
q2 += w8[j] * q * q;
|
||||
}
|
||||
(qx, q2)
|
||||
}
|
||||
@@ -8,8 +8,6 @@ const FP4: [i8; 16] = [0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12];
|
||||
|
||||
mod nearest_fn;
|
||||
#[allow(unused_imports)]
|
||||
use nearest_fn::Sums;
|
||||
#[allow(unused_imports)]
|
||||
use nearest_fn::h;
|
||||
#[allow(unused_imports)]
|
||||
use nearest_fn::max_signed;
|
||||
@@ -24,8 +22,6 @@ use nearest_fn::qkx;
|
||||
#[allow(unused_imports)]
|
||||
pub(super) use nearest_fn::qx;
|
||||
#[allow(unused_imports)]
|
||||
pub(super) use nearest_fn::sum_squares;
|
||||
#[allow(unused_imports)]
|
||||
use nearest_fn::weight;
|
||||
mod qp_fn;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -15,10 +15,6 @@ const FF: usize = 640;
|
||||
const TOP_K: usize = 10;
|
||||
const OLD_BATCH: usize = 12;
|
||||
|
||||
#[path = "borrowed_group_parity/cost_bench.rs"]
|
||||
mod cost_bench;
|
||||
use cost_bench::{CostShape, cost_groups, env_usize, report_arm, time_arm};
|
||||
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
@@ -114,47 +110,6 @@ fn plan(ids: &[usize], include: &[bool]) -> Vec<(usize, Vec<(usize, usize)>)> {
|
||||
jobs
|
||||
}
|
||||
|
||||
/// The token rows an expert serves, concatenated in pair order.
|
||||
fn gather_input(tokens: &[f32], pairs: &[(usize, usize)]) -> Box<[f32]> {
|
||||
let mut input = Vec::with_capacity(pairs.len() * H);
|
||||
for &(row, _) in pairs {
|
||||
input.extend_from_slice(&tokens[row * H..(row + 1) * H]);
|
||||
}
|
||||
input.into_boxed_slice()
|
||||
}
|
||||
|
||||
/// One owned job of the previous serve path: every role copied into its own box.
|
||||
fn owned_job(gu: GateUpFormat, down: DownFormat, x: &Expert, tokens: &[f32], pairs: &[(usize, usize)]) -> PreparedJob {
|
||||
let input = gather_input(tokens, pairs);
|
||||
PreparedJob::new(
|
||||
gu,
|
||||
down,
|
||||
x.gate.clone().into_boxed_slice(),
|
||||
x.up.clone().into_boxed_slice(),
|
||||
x.down.clone().into_boxed_slice(),
|
||||
input,
|
||||
pairs.len(),
|
||||
)
|
||||
.expect("owned job")
|
||||
}
|
||||
|
||||
/// Runs one batch of owned jobs and scatters every expert's rows into the output.
|
||||
fn run_and_scatter(
|
||||
pool: &mut CpuPool,
|
||||
prepared: Vec<PreparedJob>,
|
||||
batch: &[(usize, Vec<(usize, usize)>)],
|
||||
out: &mut [f32],
|
||||
) {
|
||||
let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join");
|
||||
for (job, (_, pairs)) in done.into_iter().zip(batch) {
|
||||
let values = job.into_values();
|
||||
for (i, &(row, slot)) in pairs.iter().enumerate() {
|
||||
let at = (row * TOP_K + slot) * H;
|
||||
out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The previous serve path: copy every role into owned boxes, build owned inputs, run batches of 12 with
|
||||
/// a join between them, scatter every expert's rows into the output.
|
||||
fn owned_path(
|
||||
@@ -167,18 +122,37 @@ fn owned_path(
|
||||
out: &mut [f32],
|
||||
) {
|
||||
for batch in jobs.chunks(OLD_BATCH) {
|
||||
let prepared: Vec<PreparedJob> =
|
||||
batch.iter().map(|(e, pairs)| owned_job(gu, down, &bank[*e], tokens, pairs)).collect();
|
||||
run_and_scatter(pool, prepared, batch, out);
|
||||
let mut prepared = Vec::with_capacity(batch.len());
|
||||
for (e, pairs) in batch {
|
||||
let x = &bank[*e];
|
||||
let mut input = Vec::with_capacity(pairs.len() * H);
|
||||
for &(row, _) in pairs {
|
||||
input.extend_from_slice(&tokens[row * H..(row + 1) * H]);
|
||||
}
|
||||
prepared.push(
|
||||
PreparedJob::new(
|
||||
gu,
|
||||
down,
|
||||
x.gate.clone().into_boxed_slice(),
|
||||
x.up.clone().into_boxed_slice(),
|
||||
x.down.clone().into_boxed_slice(),
|
||||
input.into_boxed_slice(),
|
||||
pairs.len(),
|
||||
)
|
||||
.expect("owned job"),
|
||||
);
|
||||
}
|
||||
let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join");
|
||||
for (job, (_, pairs)) in done.into_iter().zip(batch) {
|
||||
let values = job.into_values();
|
||||
for (i, &(row, slot)) in pairs.iter().enumerate() {
|
||||
let at = (row * TOP_K + slot) * H;
|
||||
out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn borrowed_experts<'a>(bank: &'a [Expert], jobs: &'a [(usize, Vec<(usize, usize)>)]) -> Vec<BorrowedExpert<'a>> {
|
||||
jobs.iter()
|
||||
.map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs })
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn borrowed_path(
|
||||
pool: &mut DirectCpuPool,
|
||||
gu: GateUpFormat,
|
||||
@@ -188,7 +162,10 @@ fn borrowed_path(
|
||||
jobs: &[(usize, Vec<(usize, usize)>)],
|
||||
out: &mut [f32],
|
||||
) {
|
||||
let experts = borrowed_experts(bank, jobs);
|
||||
let experts: Vec<BorrowedExpert<'_>> = jobs
|
||||
.iter()
|
||||
.map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs })
|
||||
.collect();
|
||||
pool.compute_group(gu, down, &BorrowedGroup { tokens, experts: &experts, stride: TOP_K }, out)
|
||||
.expect("borrowed group");
|
||||
}
|
||||
@@ -206,149 +183,151 @@ const PAIRS: [(GateUpFormat, DownFormat); 10] = [
|
||||
(GateUpFormat::Q2_0, DownFormat::Q2_0),
|
||||
];
|
||||
|
||||
/// Both pools and the random source of one parity run.
|
||||
struct Rig {
|
||||
owned: CpuPool,
|
||||
direct: DirectCpuPool,
|
||||
rng: Rng,
|
||||
}
|
||||
|
||||
/// A digest of every output bit: compared across builds to prove a kernel change bit-exact.
|
||||
fn digest_of(values: &[f32]) -> u64 {
|
||||
values.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x100_0000_01b3))
|
||||
}
|
||||
|
||||
/// One group of `rows` rows with `share` percent of the entries on the CPU through both paths; false when the plan is
|
||||
/// empty.
|
||||
fn check_group(
|
||||
rig: &mut Rig,
|
||||
(gu, down): (GateUpFormat, DownFormat),
|
||||
bank: &[Expert],
|
||||
rows: usize,
|
||||
share: usize,
|
||||
) -> bool {
|
||||
let (ids, include) = route(&mut rig.rng, rows, bank.len(), share);
|
||||
let jobs = plan(&ids, &include);
|
||||
if jobs.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let tokens: Vec<f32> = (0..rows * H).map(|_| rig.rng.unit()).collect();
|
||||
// different sentinels: rows the plan leaves out must stay untouched by both paths
|
||||
let (mut a, mut b) = (sentinel_rows(rows), sentinel_rows(rows));
|
||||
owned_path(&mut rig.owned, gu, down, bank, &tokens, &jobs, &mut a);
|
||||
if share != 100 {
|
||||
// the file-mapped source's prefetch phase reads only: the group computes the same bits
|
||||
rig.direct.prefetch(gu, down, &borrowed_experts(bank, &jobs)).expect("prefetch");
|
||||
}
|
||||
borrowed_path(&mut rig.direct, gu, down, bank, &tokens, &jobs, &mut b);
|
||||
let differing = a.iter().zip(&b).filter(|(x, y)| x.to_bits() != y.to_bits()).count();
|
||||
assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ");
|
||||
eprintln!("DIGEST {gu:?} {down:?} rows={rows} share={share} {:016x}", digest_of(&b));
|
||||
let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum();
|
||||
assert_only_planned_rows(&b, computed, (gu, down));
|
||||
true
|
||||
}
|
||||
|
||||
/// An output buffer filled with a NaN sentinel: a row nobody writes stays visibly untouched.
|
||||
fn sentinel_rows(rows: usize) -> Vec<f32> {
|
||||
vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H]
|
||||
}
|
||||
|
||||
fn assert_only_planned_rows(out: &[f32], computed: usize, (gu, down): (GateUpFormat, DownFormat)) {
|
||||
assert!(
|
||||
out.iter().filter(|v| v.is_finite()).count() == computed * H,
|
||||
"{gu:?} x {down:?}: only planned rows written, all finite"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrowed_group_is_bit_identical_to_the_owned_batches() {
|
||||
let workers = std::env::var("PARITY_WORKERS").ok().and_then(|v| v.parse().ok()).unwrap_or(4);
|
||||
let owned = CpuPool::new(workers).expect("owned pool");
|
||||
let direct = DirectCpuPool::new(workers).expect("direct pool");
|
||||
let mut rig = Rig { owned, direct, rng: Rng(0x9e37_79b9_7f4a_7c15) };
|
||||
let mut owned = CpuPool::new(workers).expect("owned pool");
|
||||
let mut direct = DirectCpuPool::new(workers).expect("direct pool");
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
let mut groups = 0;
|
||||
for (gu, down) in PAIRS {
|
||||
// a small bank so rows share experts and batches of 12 are crossed
|
||||
let bank = bank(&mut rig.rng, gu, down, 40);
|
||||
let bank = bank(&mut rng, gu, down, 40);
|
||||
for rows in [1usize, 2, 3, 4, 6, 8] {
|
||||
for share in [100usize, 50] {
|
||||
groups += usize::from(check_group(&mut rig, (gu, down), &bank, rows, share));
|
||||
let (ids, include) = route(&mut rng, rows, bank.len(), share);
|
||||
let jobs = plan(&ids, &include);
|
||||
if jobs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let tokens: Vec<f32> = (0..rows * H).map(|_| rng.unit()).collect();
|
||||
// different sentinels: rows the plan leaves out must stay untouched by both paths
|
||||
let mut a = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H];
|
||||
let mut b = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H];
|
||||
owned_path(&mut owned, gu, down, &bank, &tokens, &jobs, &mut a);
|
||||
if share != 100 {
|
||||
// the file-mapped source's prefetch phase reads only: the group computes the same bits
|
||||
let refs: Vec<BorrowedExpert<'_>> = jobs
|
||||
.iter()
|
||||
.map(|(e, pairs)| BorrowedExpert {
|
||||
gate: &bank[*e].gate,
|
||||
up: &bank[*e].up,
|
||||
down: &bank[*e].down,
|
||||
pairs,
|
||||
})
|
||||
.collect();
|
||||
direct.prefetch(gu, down, &refs).expect("prefetch");
|
||||
}
|
||||
borrowed_path(&mut direct, gu, down, &bank, &tokens, &jobs, &mut b);
|
||||
let differing = a.iter().zip(&b).filter(|(x, y)| x.to_bits() != y.to_bits()).count();
|
||||
assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ");
|
||||
// A digest of every output bit: compared across builds to prove a kernel change bit-exact.
|
||||
let digest = b
|
||||
.iter()
|
||||
.fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x100_0000_01b3));
|
||||
eprintln!("DIGEST {gu:?} {down:?} rows={rows} share={share} {digest:016x}");
|
||||
let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum();
|
||||
assert!(
|
||||
b.iter().filter(|v| v.is_finite()).count() == computed * H,
|
||||
"{gu:?} x {down:?}: only planned rows written, all finite"
|
||||
);
|
||||
groups += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("bit-identical groups: {groups}");
|
||||
}
|
||||
|
||||
/// Compute the group of `experts` with the pool's call; the group is the one-expert-per-entry shape of these tests.
|
||||
fn compute(
|
||||
direct: &mut DirectCpuPool,
|
||||
(gu, down): (GateUpFormat, DownFormat),
|
||||
tokens: &[f32],
|
||||
experts: &[BorrowedExpert<'_>],
|
||||
out: &mut [f32],
|
||||
) -> Result<(), leleka_native_cpu_expert::Error> {
|
||||
direct.compute_group(gu, down, &BorrowedGroup { tokens, experts, stride: TOP_K }, out)
|
||||
}
|
||||
|
||||
/// One expert of the bank over the given pairs.
|
||||
fn expert_over<'a>(bank: &'a [Expert], at: usize, pairs: &'a [(usize, usize)]) -> BorrowedExpert<'a> {
|
||||
BorrowedExpert { gate: &bank[at].gate, up: &bank[at].up, down: &bank[at].down, pairs }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrowed_group_refuses_bad_shapes_without_touching_out() {
|
||||
let mut direct = DirectCpuPool::new(2).expect("direct pool");
|
||||
let mut rng = Rng(7);
|
||||
let formats = (GateUpFormat::Iq3S, DownFormat::Iq4Nl);
|
||||
let bank = bank(&mut rng, formats.0, formats.1, 2);
|
||||
let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl);
|
||||
let bank = bank(&mut rng, gu, down, 2);
|
||||
let tokens = vec![0.25f32; 2 * H];
|
||||
let mut out = vec![-3.0f32; 2 * TOP_K * H];
|
||||
let pairs_a = [(0usize, 1usize)];
|
||||
assert_bad_pairs_refused(&mut direct, formats, &bank, &tokens, &mut out);
|
||||
assert_bad_inputs_refused(&mut direct, formats, &bank, &tokens, &mut out);
|
||||
assert!(out.iter().all(|&v| v == -3.0), "a refused group writes nothing");
|
||||
// and the pool still serves a good group afterwards
|
||||
let good = [expert_over(&bank, 0, &pairs_a)];
|
||||
compute(&mut direct, formats, &tokens, &good, &mut out).expect("good group");
|
||||
assert!(out[H..2 * H].iter().all(|v| v.is_finite()));
|
||||
}
|
||||
|
||||
/// Duplicate (row, slot) pairs, a row beyond the tokens, a slot beyond the stride and no expert at all are refused.
|
||||
fn assert_bad_pairs_refused(
|
||||
direct: &mut DirectCpuPool,
|
||||
formats: (GateUpFormat, DownFormat),
|
||||
bank: &[Expert],
|
||||
tokens: &[f32],
|
||||
out: &mut [f32],
|
||||
) {
|
||||
let pairs_a = [(0usize, 1usize)];
|
||||
let duplicate = [(0usize, 1usize)];
|
||||
let out_of_rows = [(2usize, 0usize)];
|
||||
let wide_slot = [(0usize, TOP_K)];
|
||||
let x = |pairs| expert_over(bank, 0, pairs);
|
||||
let y = |pairs| expert_over(bank, 1, pairs);
|
||||
let x = |pairs| BorrowedExpert { gate: &bank[0].gate, up: &bank[0].up, down: &bank[0].down, pairs };
|
||||
let y = |pairs| BorrowedExpert { gate: &bank[1].gate, up: &bank[1].up, down: &bank[1].down, pairs };
|
||||
for experts in [vec![x(&pairs_a), y(&duplicate)], vec![x(&out_of_rows)], vec![x(&wide_slot)], vec![]] {
|
||||
assert!(compute(direct, formats, tokens, &experts, out).is_err());
|
||||
let group = BorrowedGroup { tokens: &tokens, experts: &experts, stride: TOP_K };
|
||||
assert!(direct.compute_group(gu, down, &group, &mut out).is_err());
|
||||
}
|
||||
let short = BorrowedExpert { gate: &bank[0].gate[1..], up: &bank[0].up, down: &bank[0].down, pairs: &pairs_a };
|
||||
assert!(
|
||||
direct
|
||||
.compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &[short], stride: TOP_K }, &mut out)
|
||||
.is_err()
|
||||
);
|
||||
let wrong_format = [x(&pairs_a)];
|
||||
assert!(
|
||||
direct
|
||||
.compute_group(
|
||||
GateUpFormat::Iq3Xxs,
|
||||
down,
|
||||
&BorrowedGroup { tokens: &tokens, experts: &wrong_format, stride: TOP_K },
|
||||
&mut out
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut nan = tokens.clone();
|
||||
nan[5] = f32::NAN;
|
||||
assert!(
|
||||
direct
|
||||
.compute_group(gu, down, &BorrowedGroup { tokens: &nan, experts: &wrong_format, stride: TOP_K }, &mut out)
|
||||
.is_err()
|
||||
);
|
||||
assert!(out.iter().all(|&v| v == -3.0), "a refused group writes nothing");
|
||||
// and the pool still serves a good group afterwards
|
||||
let good = [x(&pairs_a)];
|
||||
direct
|
||||
.compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &good, stride: TOP_K }, &mut out)
|
||||
.expect("good group");
|
||||
assert!(out[H..2 * H].iter().all(|v| v.is_finite()));
|
||||
}
|
||||
|
||||
/// A short blob, a format that does not match the blob and a non-finite activation are refused.
|
||||
fn assert_bad_inputs_refused(
|
||||
direct: &mut DirectCpuPool,
|
||||
(gu, down): (GateUpFormat, DownFormat),
|
||||
/// The previous runtime prepare step per expert also copied each role out of the source (`block`) and
|
||||
/// scanned every block header (`encoded_finite`) before `PreparedJob::new` copied them again.
|
||||
fn owned_path_with_source_copy(
|
||||
pool: &mut CpuPool,
|
||||
gu: GateUpFormat,
|
||||
down: DownFormat,
|
||||
bank: &[Expert],
|
||||
tokens: &[f32],
|
||||
jobs: &[(usize, Vec<(usize, usize)>)],
|
||||
out: &mut [f32],
|
||||
) {
|
||||
let pairs_a = [(0usize, 1usize)];
|
||||
let short = BorrowedExpert { gate: &bank[0].gate[1..], up: &bank[0].up, down: &bank[0].down, pairs: &pairs_a };
|
||||
assert!(compute(direct, (gu, down), tokens, &[short], out).is_err());
|
||||
let wrong_format = [expert_over(bank, 0, &pairs_a)];
|
||||
assert!(compute(direct, (GateUpFormat::Iq3Xxs, down), tokens, &wrong_format, out).is_err());
|
||||
let mut nan = tokens.to_vec();
|
||||
nan[5] = f32::NAN;
|
||||
assert!(compute(direct, (gu, down), &nan, &wrong_format, out).is_err());
|
||||
let (_, gb) = gate_up_block(gu);
|
||||
let (_, db) = down_block(down);
|
||||
let scan = |bytes: &[u8], block: usize| {
|
||||
bytes.chunks_exact(block).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00)
|
||||
};
|
||||
for batch in jobs.chunks(OLD_BATCH) {
|
||||
let mut prepared = Vec::with_capacity(batch.len());
|
||||
for (e, pairs) in batch {
|
||||
let x = &bank[*e];
|
||||
let (g, u, d) =
|
||||
(x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice());
|
||||
assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db));
|
||||
let mut input = Vec::with_capacity(pairs.len() * H);
|
||||
for &(row, _) in pairs {
|
||||
input.extend_from_slice(&tokens[row * H..(row + 1) * H]);
|
||||
}
|
||||
prepared
|
||||
.push(PreparedJob::new(gu, down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job"));
|
||||
}
|
||||
let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join");
|
||||
for (job, (_, pairs)) in done.into_iter().zip(batch) {
|
||||
let values = job.into_values();
|
||||
for (i, &(row, slot)) in pairs.iter().enumerate() {
|
||||
let at = (row * TOP_K + slot) * H;
|
||||
out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Model-free cost of one decode round's CPU share: 48 groups of `GROUP_ROWS` rows, `GROUP_SHARE`% of the
|
||||
@@ -356,22 +335,40 @@ fn assert_bad_inputs_refused(
|
||||
#[test]
|
||||
#[ignore = "benchmark; prints the cost of both group paths"]
|
||||
fn group_path_cost() {
|
||||
let shape = CostShape {
|
||||
workers: env_usize("BENCH_WORKERS", 15) as i32,
|
||||
rows: env_usize("GROUP_ROWS", 4),
|
||||
share: env_usize("GROUP_SHARE", 50),
|
||||
rounds: env_usize("ROUNDS", 5),
|
||||
};
|
||||
let formats = (GateUpFormat::Iq3S, DownFormat::Iq4Nl);
|
||||
let env = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default);
|
||||
let workers = env("BENCH_WORKERS", 15) as i32;
|
||||
let rows = env("GROUP_ROWS", 4);
|
||||
let share = env("GROUP_SHARE", 50);
|
||||
let rounds = env("ROUNDS", 5);
|
||||
let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl);
|
||||
let mut rng = Rng(42);
|
||||
let bank = bank(&mut rng, formats.0, formats.1, env_usize("BANK_EXPERTS", 256));
|
||||
let mut owned = CpuPool::new(shape.workers).expect("owned pool");
|
||||
let mut direct = DirectCpuPool::new(shape.workers).expect("direct pool");
|
||||
let groups = cost_groups(&mut rng, &bank, &shape);
|
||||
let bank = bank(&mut rng, gu, down, env("BANK_EXPERTS", 256));
|
||||
let mut owned = CpuPool::new(workers).expect("owned pool");
|
||||
let mut direct = DirectCpuPool::new(workers).expect("direct pool");
|
||||
let groups: Vec<(Vec<f32>, Vec<(usize, Vec<(usize, usize)>)>)> = (0..48 * rounds)
|
||||
.map(|_| {
|
||||
let (ids, include) = route(&mut rng, rows, bank.len(), share);
|
||||
((0..rows * H).map(|_| rng.unit()).collect(), plan(&ids, &include))
|
||||
})
|
||||
.collect();
|
||||
let experts: usize = groups.iter().map(|(_, j)| j.len()).sum();
|
||||
let mut out = vec![0.0f32; shape.rows * TOP_K * H];
|
||||
let mut out = vec![0.0f32; rows * TOP_K * H];
|
||||
for arm in ["owned+source-copy", "owned", "borrowed", "owned+source-copy", "owned", "borrowed"] {
|
||||
let ms = time_arm(arm, (&mut owned, &mut direct), formats, &bank, &groups, &mut out);
|
||||
report_arm(arm, &shape, (experts, groups.len()), ms, &bank[0]);
|
||||
let started = Instant::now();
|
||||
for (tokens, jobs) in &groups {
|
||||
match arm {
|
||||
"borrowed" => borrowed_path(&mut direct, gu, down, &bank, tokens, jobs, &mut out),
|
||||
"owned" => owned_path(&mut owned, gu, down, &bank, tokens, jobs, &mut out),
|
||||
_ => owned_path_with_source_copy(&mut owned, gu, down, &bank, tokens, jobs, &mut out),
|
||||
}
|
||||
}
|
||||
let ms = started.elapsed().as_secs_f64() * 1e3;
|
||||
let gb = experts as f64 * (bank[0].gate.len() * 2 + bank[0].down.len()) as f64 / 1e9;
|
||||
eprintln!(
|
||||
"BENCH {arm:>18}: workers={workers} rows={rows} share={share}% {:.2} experts/group, {:.2} ms/round (48 groups), {:.1} GB/s of expert bytes",
|
||||
experts as f64 / groups.len() as f64,
|
||||
ms / rounds as f64,
|
||||
gb / (ms / 1e3)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
//! The model-free cost bench of `borrowed_group_parity` (`group_path_cost`): its arms, its groups and its report line.
|
||||
use super::*;
|
||||
|
||||
/// The previous runtime prepare step per expert also copied each role out of the source (`block`) and
|
||||
/// scanned every block header (`encoded_finite`) before `PreparedJob::new` copied them again.
|
||||
pub(super) fn copied_job(
|
||||
gu: GateUpFormat,
|
||||
down: DownFormat,
|
||||
x: &Expert,
|
||||
tokens: &[f32],
|
||||
pairs: &[(usize, usize)],
|
||||
) -> PreparedJob {
|
||||
let (_, gb) = gate_up_block(gu);
|
||||
let (_, db) = down_block(down);
|
||||
let scan = |bytes: &[u8], block: usize| {
|
||||
bytes.chunks_exact(block).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00)
|
||||
};
|
||||
let (g, u, d) =
|
||||
(x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice());
|
||||
assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db));
|
||||
PreparedJob::new(gu, down, g, u, d, gather_input(tokens, pairs), pairs.len()).expect("owned job")
|
||||
}
|
||||
|
||||
pub(super) fn owned_path_with_source_copy(
|
||||
pool: &mut CpuPool,
|
||||
gu: GateUpFormat,
|
||||
down: DownFormat,
|
||||
bank: &[Expert],
|
||||
tokens: &[f32],
|
||||
jobs: &[(usize, Vec<(usize, usize)>)],
|
||||
out: &mut [f32],
|
||||
) {
|
||||
for batch in jobs.chunks(OLD_BATCH) {
|
||||
let prepared: Vec<PreparedJob> =
|
||||
batch.iter().map(|(e, pairs)| copied_job(gu, down, &bank[*e], tokens, pairs)).collect();
|
||||
run_and_scatter(pool, prepared, batch, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// One decode round's worth of work: the token rows and the planned experts of each group.
|
||||
pub(super) type Groups = Vec<(Vec<f32>, Vec<(usize, Vec<(usize, usize)>)>)>;
|
||||
|
||||
/// The knobs of the cost bench (environment variables, with the defaults of the serve shape).
|
||||
pub(super) struct CostShape {
|
||||
pub(super) workers: i32,
|
||||
pub(super) rows: usize,
|
||||
pub(super) share: usize,
|
||||
pub(super) rounds: usize,
|
||||
}
|
||||
|
||||
pub(super) fn env_usize(name: &str, default: usize) -> usize {
|
||||
std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// 48 groups per round of `rows` rows each, experts drawn from the bank.
|
||||
pub(super) fn cost_groups(rng: &mut Rng, bank: &[Expert], shape: &CostShape) -> Groups {
|
||||
(0..48 * shape.rounds)
|
||||
.map(|_| {
|
||||
let (ids, include) = route(rng, shape.rows, bank.len(), shape.share);
|
||||
((0..shape.rows * H).map(|_| rng.unit()).collect(), plan(&ids, &include))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Wall milliseconds of every group through one arm of the bench.
|
||||
pub(super) fn time_arm(
|
||||
arm: &str,
|
||||
pools: (&mut CpuPool, &mut DirectCpuPool),
|
||||
(gu, down): (GateUpFormat, DownFormat),
|
||||
bank: &[Expert],
|
||||
groups: &Groups,
|
||||
out: &mut [f32],
|
||||
) -> f64 {
|
||||
let (owned, direct) = pools;
|
||||
let started = Instant::now();
|
||||
for (tokens, jobs) in groups {
|
||||
match arm {
|
||||
"borrowed" => borrowed_path(direct, gu, down, bank, tokens, jobs, out),
|
||||
"owned" => owned_path(owned, gu, down, bank, tokens, jobs, out),
|
||||
_ => owned_path_with_source_copy(owned, gu, down, bank, tokens, jobs, out),
|
||||
}
|
||||
}
|
||||
started.elapsed().as_secs_f64() * 1e3
|
||||
}
|
||||
|
||||
pub(super) fn report_arm(arm: &str, shape: &CostShape, (experts, groups): (usize, usize), ms: f64, x: &Expert) {
|
||||
let gb = experts as f64 * (x.gate.len() * 2 + x.down.len()) as f64 / 1e9;
|
||||
eprintln!(
|
||||
"BENCH {arm:>18}: workers={} rows={} share={}% {:.2} experts/group, {:.2} ms/round (48 groups), \
|
||||
{:.1} GB/s of expert bytes",
|
||||
shape.workers,
|
||||
shape.rows,
|
||||
shape.share,
|
||||
experts as f64 / groups as f64,
|
||||
ms / shape.rounds as f64,
|
||||
gb / (ms / 1e3)
|
||||
);
|
||||
}
|
||||
@@ -47,52 +47,38 @@ fn cpu_pool_runs_every_expert_format_pair() {
|
||||
let downs = [DownFormat::Iq4Nl, DownFormat::Q2_0];
|
||||
for gu in gates {
|
||||
for down in downs {
|
||||
probe_pair(&mut pool, gu, down, rows);
|
||||
let (gq, gb) = gate_up_block(gu);
|
||||
let (dq, db) = down_block(down);
|
||||
let gsize = H / gq * gb * FF;
|
||||
let dsize = FF / dq * db * H;
|
||||
let input = vec![0.5f32; rows * H].into_boxed_slice();
|
||||
let job = match PreparedJob::new(
|
||||
gu,
|
||||
down,
|
||||
vec![0u8; gsize].into_boxed_slice(),
|
||||
vec![0u8; gsize].into_boxed_slice(),
|
||||
vec![0u8; dsize].into_boxed_slice(),
|
||||
input,
|
||||
rows,
|
||||
) {
|
||||
Ok(job) => job,
|
||||
Err(e) => {
|
||||
eprintln!("PREFLIGHT PreparedJob::new({gu:?}, {down:?}) ERR: {e:?}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let started = std::time::Instant::now();
|
||||
let result = pool.start(vec![job], 48 << 20).and_then(|pending| pending.join());
|
||||
match result {
|
||||
Ok(done) => {
|
||||
let finite = done.into_iter().all(|j| j.into_values().iter().all(|v| v.is_finite()));
|
||||
eprintln!(
|
||||
"PREFLIGHT cpu expert {gu:?} x {down:?} rows={rows} ok finite={finite} in {:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
}
|
||||
Err(e) => eprintln!("PREFLIGHT cpu expert {gu:?} x {down:?} ERR: {e:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero-filled job of the pair (valid FP16 headers, constant activation).
|
||||
fn zero_job(gu: GateUpFormat, down: DownFormat, rows: usize) -> Result<PreparedJob, leleka_native_cpu_expert::Error> {
|
||||
let (gq, gb) = gate_up_block(gu);
|
||||
let (dq, db) = down_block(down);
|
||||
let gsize = H / gq * gb * FF;
|
||||
let dsize = FF / dq * db * H;
|
||||
let input = vec![0.5f32; rows * H].into_boxed_slice();
|
||||
PreparedJob::new(
|
||||
gu,
|
||||
down,
|
||||
vec![0u8; gsize].into_boxed_slice(),
|
||||
vec![0u8; gsize].into_boxed_slice(),
|
||||
vec![0u8; dsize].into_boxed_slice(),
|
||||
input,
|
||||
rows,
|
||||
)
|
||||
}
|
||||
|
||||
/// Starts the job on the pool and joins it: whether every returned value is finite, and how long it took.
|
||||
fn run_timed(
|
||||
pool: &mut CpuPool,
|
||||
job: PreparedJob,
|
||||
) -> (Result<bool, leleka_native_cpu_expert::Error>, std::time::Duration) {
|
||||
let started = std::time::Instant::now();
|
||||
let result = pool.start(vec![job], 48 << 20).and_then(|pending| pending.join());
|
||||
let finite = result.map(|done| done.into_iter().all(|j| j.into_values().iter().all(|v| v.is_finite())));
|
||||
(finite, started.elapsed())
|
||||
}
|
||||
|
||||
fn probe_pair(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, rows: usize) {
|
||||
let job = match zero_job(gu, down, rows) {
|
||||
Ok(job) => job,
|
||||
Err(e) => {
|
||||
eprintln!("PREFLIGHT PreparedJob::new({gu:?}, {down:?}) ERR: {e:?}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
match run_timed(pool, job) {
|
||||
(Ok(finite), elapsed) => {
|
||||
eprintln!("PREFLIGHT cpu expert {gu:?} x {down:?} rows={rows} ok finite={finite} in {elapsed:?}");
|
||||
}
|
||||
(Err(e), _) => eprintln!("PREFLIGHT cpu expert {gu:?} x {down:?} ERR: {e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user