STRA-338 size: the engine crates are rustfmt-clean at 120 columns (per-crate rustfmt.toml: max_width 120, Max heuristics); width violations 6869 -> 2862 prod, 1273 -> 717 test; files that grew are re-split. Reasons for the raised census numbers: fn_lines +119 and complexity +14 are functions that cross 30 lines / 10 branches only because rustfmt put their one-line bodies on several lines (nothing was added); test lists identical (1793), 800 tests pass, the same 5 known failures; bring-up print gate lookback 20 -> 30 lines for the same reason

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 13:03:51 +01:00
parent a9d80333b4
commit cdfec56460
1637 changed files with 80340 additions and 74407 deletions
+28 -28
View File
@@ -20,20 +20,21 @@
"crates/cpu-sys/src/lib.rs": 1007,
"crates/cpu-sys/src/simd.rs": 1503,
"crates/cpu-worker/tests/serve_loop.rs": 477,
"crates/cuda-driver/src/experimental.rs": 407,
"crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs": 618,
"crates/cuda-driver/src/lib.rs": 938,
"crates/cuda-driver/src/mmq_resident_gpu.rs": 517,
"crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs": 621,
"crates/cuda-driver/src/mtp_original_full_symbols.rs": 445,
"crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs": 676,
"crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs": 622,
"crates/cuda-driver/src/native_head.rs": 467,
"crates/cuda-driver/src/prefill_stage_gdn_gpu.rs": 420,
"crates/cuda-driver/src/qwen_ffi.rs": 876,
"crates/cuda-driver/src/sm86_table.rs": 933,
"crates/cuda-driver/tests/mock_driver.rs": 453,
"crates/cuda-driver/tests/projection_family_mock/common_protocol_matrix.rs": 411,
"crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs": 541,
"crates/cuda-driver/src/lib.rs": 801,
"crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs": 520,
"crates/cuda-driver/src/mtp_original_full_symbols.rs": 404,
"crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs": 557,
"crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs": 487,
"crates/cuda-driver/src/native_head.rs": 483,
"crates/cuda-driver/src/original_verify_window_proj.rs": 439,
"crates/cuda-driver/src/prefill_stage_gdn_gpu.rs": 616,
"crates/cuda-driver/src/prefill_stage_gr_gpu.rs": 445,
"crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace.rs": 415,
"crates/cuda-driver/src/qwen_ffi.rs": 826,
"crates/cuda-driver/src/sm86_table.rs": 1719,
"crates/cuda-driver/tests/mock_driver.rs": 435,
"crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs": 455,
"crates/deploy/src/app.rs": 1490,
"crates/deploy/src/bin/fake_runtime.rs": 426,
"crates/deploy/src/cli/tests.rs": 407,
@@ -49,20 +50,17 @@
"crates/deploy/src/sealed.rs": 592,
"crates/deploy/src/supervisor.rs": 1863,
"crates/deploy/tests/e2e.rs": 2118,
"crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs": 474,
"crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs": 851,
"crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs": 447,
"crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs": 979,
"crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs": 1648,
"crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs": 540,
"crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs": 651,
"crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs": 980,
"crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs": 466,
"crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs": 493,
"crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs": 454,
"crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs": 472,
"crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs": 993,
"crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs": 484,
"crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs": 1247,
"crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs": 1528,
"crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs": 465,
"crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs": 465,
"crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs": 492,
"crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs": 857,
"crates/experimental-ref/tests/emulated_kernels.rs": 467,
"crates/gateway-domain/src/responses/render.rs": 405,
"crates/gateway-text/src/prompt/tests.rs": 492,
"crates/gateway-text/src/tool_output/tests.rs": 654,
"crates/gguf/src/lib.rs": 560,
"crates/gguf/tests/synthetic.rs": 460,
@@ -72,7 +70,9 @@
"crates/gptoss/tests/synthetic_model.rs": 922,
"crates/igpu/src/lib.rs": 1386,
"crates/igpu/src/shaders.rs": 440,
"crates/native-cpu-expert/examples/kernel_ab.rs": 3347,
"crates/native-cpu-expert/examples/kernel_ab.rs": 3992,
"crates/native-cpu-expert/src/rust_codebooks.rs": 1905,
"crates/native-cpu-expert/src/rust_iq1_grid.rs": 2051,
"crates/openvino/src/lib.rs": 676,
"crates/quant-core/src/iq2s_grid.rs": 1032,
"crates/runtime-client/tests/grpc_backend.rs": 689,
@@ -109,7 +109,7 @@
"dyn-trait:strata-desktop-core": 2,
"env-read:leleka-cpu-kernels": 1,
"env-read:leleka-cpu-worker": 2,
"env-read:leleka-cuda-driver": 76,
"env-read:leleka-cuda-driver": 73,
"env-read:leleka-deploy": 41,
"env-read:leleka-engine-qwen35-cuda": 1,
"env-read:leleka-gateway-text": 2,
+3
View File
@@ -0,0 +1,3 @@
# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line.
max_width = 120
use_small_heuristics = "Max"
+20 -51
View File
@@ -23,12 +23,12 @@
//! the fp32 indexer store and the rope table. Nothing here is a performance or quality claim.
use crate::memory_plan::{
Costs, EngineResidentEstimate, Geometry, KvFormat, Plan, PlanError, cli_pool,
engine_resident_estimate, kv_bytes_per_token, make_plan_with_format, state_bytes,
Costs, EngineResidentEstimate, Geometry, KvFormat, Plan, PlanError, cli_pool, engine_resident_estimate,
kv_bytes_per_token, make_plan_with_format, state_bytes,
};
use crate::rope_scaling::{
MAX_CHARTER_CONTEXT, ModelRopeKeys, RopeKnobError, RopeKnobs, RopeScaling, RopeScalingType,
SetupRopeError, TRAINED_CONTEXT, resolve_rope_scaling, rope_table_bytes, setup_resolve_rope,
MAX_CHARTER_CONTEXT, ModelRopeKeys, RopeKnobError, RopeKnobs, RopeScaling, RopeScalingType, SetupRopeError,
TRAINED_CONTEXT, resolve_rope_scaling, rope_table_bytes, setup_resolve_rope,
};
use std::fmt;
@@ -79,11 +79,7 @@ impl ContextRequest {
rope_knobs: RopeKnobs::default(),
model_rope: ModelRopeKeys::default(),
geometry: Geometry::default(),
vram: VramBudget {
free_vram_bytes,
costs: Costs::default(),
state_bytes_per_slot: None,
},
vram: VramBudget { free_vram_bytes, costs: Costs::default(), state_bytes_per_slot: None },
}
}
}
@@ -112,16 +108,11 @@ impl fmt::Display for PolicyError {
Self::ZeroSlots => f.write_str("at least one slot is required"),
Self::ZeroContext => f.write_str("the per-slot context must be positive"),
Self::ContextTooLarge { requested, max } => {
write!(
f,
"per-slot context {requested} exceeds the supported {max}"
)
write!(f, "per-slot context {requested} exceeds the supported {max}")
}
Self::ExperimentalKvFormat(k) => {
write!(f, "KV format {} is experimental and was not explicitly enabled", k.name())
}
Self::ExperimentalKvFormat(k) => write!(
f,
"KV format {} is experimental and was not explicitly enabled",
k.name()
),
Self::Setup(e) => write!(f, "{e}"),
Self::Rope(e) => write!(f, "{e}"),
Self::Plan(e) => write!(f, "{e}"),
@@ -173,10 +164,7 @@ pub fn resolve_context(req: &ContextRequest) -> Result<EffectiveContext, PolicyE
return Err(PolicyError::ZeroContext);
}
if req.ctx_per_slot > MAX_CHARTER_CONTEXT {
return Err(PolicyError::ContextTooLarge {
requested: req.ctx_per_slot,
max: MAX_CHARTER_CONTEXT,
});
return Err(PolicyError::ContextTooLarge { requested: req.ctx_per_slot, max: MAX_CHARTER_CONTEXT });
}
if req.kv_format.is_experimental() && !req.allow_experimental {
return Err(PolicyError::ExperimentalKvFormat(req.kv_format));
@@ -184,13 +172,9 @@ pub fn resolve_context(req: &ContextRequest) -> Result<EffectiveContext, PolicyE
let mut notes = Vec::new();
// ---- rope: setup.py chooses (method, factor) for the context actually served, generate.cpp resolves
let trained = if req.model_rope.orig_ctx >= 1.0 {
req.model_rope.orig_ctx as u64
} else {
TRAINED_CONTEXT
};
let setup = setup_resolve_rope(req.ctx_per_slot, req.rope_scaling, req.rope_scale, trained)
.map_err(PolicyError::Setup)?;
let trained = if req.model_rope.orig_ctx >= 1.0 { req.model_rope.orig_ctx as u64 } else { TRAINED_CONTEXT };
let setup =
setup_resolve_rope(req.ctx_per_slot, req.rope_scaling, req.rope_scale, trained).map_err(PolicyError::Setup)?;
let mut knobs = req.rope_knobs;
match setup {
Some((kind, scale)) => {
@@ -219,8 +203,7 @@ pub fn resolve_context(req: &ContextRequest) -> Result<EffectiveContext, PolicyE
notes.push("rope scaling is none: the scaling knobs have no effect".into());
}
let rope_rows = req.ctx_per_slot;
let rope_bytes = rope_table_bytes(ROPE_N_ROT, rope_rows as usize)
.ok_or(PolicyError::Plan(PlanError::Overflow))?;
let rope_bytes = rope_table_bytes(ROPE_N_ROT, rope_rows as usize).ok_or(PolicyError::Plan(PlanError::Overflow))?;
// ---- admission: strata-plan arithmetic over slots * ctx
let g = &req.geometry;
@@ -228,25 +211,13 @@ pub fn resolve_context(req: &ContextRequest) -> Result<EffectiveContext, PolicyE
Some(s) => s,
None => state_bytes(g).map_err(PolicyError::Plan)?,
};
let total_cells = req
.slots
.checked_mul(req.ctx_per_slot)
.ok_or(PolicyError::Plan(PlanError::Overflow))?;
let state_total = req
.slots
.checked_mul(state_per_slot)
.ok_or(PolicyError::Plan(PlanError::Overflow))?;
let costs = Costs {
state_bytes: state_total,
..req.vram.costs
};
let total_cells = req.slots.checked_mul(req.ctx_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?;
let state_total = req.slots.checked_mul(state_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?;
let costs = Costs { state_bytes: state_total, ..req.vram.costs };
let pool = cli_pool(req.vram.free_vram_bytes, &costs).map_err(PolicyError::Plan)?;
let plan = make_plan_with_format(total_cells, g, req.kv_format, &costs, pool)
.map_err(PolicyError::Plan)?;
let plan = make_plan_with_format(total_cells, g, req.kv_format, &costs, pool).map_err(PolicyError::Plan)?;
let per_token = kv_bytes_per_token(g, req.kv_format).map_err(PolicyError::Plan)?;
let per_slot = per_token
.checked_mul(req.ctx_per_slot)
.ok_or(PolicyError::Plan(PlanError::Overflow))?;
let per_slot = per_token.checked_mul(req.ctx_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?;
let engine_estimate = engine_resident_estimate(
g,
req.kv_format,
@@ -265,9 +236,7 @@ pub fn resolve_context(req: &ContextRequest) -> Result<EffectiveContext, PolicyE
);
}
if req.kv_format.is_experimental() {
notes.push(
"experimental KV format enabled explicitly; no default and no quality claim".into(),
);
notes.push("experimental KV format enabled explicitly; no default and no quality claim".into());
}
Ok(EffectiveContext {
slots: req.slots,
+9 -37
View File
@@ -30,11 +30,7 @@ fn two_by_256k_needs_no_scaling_one_by_512k_needs_yarn_2() {
fn int8_does_not_close_on_the_default_pool_but_does_on_32_gib() {
let small = resolve_context(&req(1, 524_288, KvFormat::Int8, 5_943_000_000)).unwrap_err();
assert!(small.is_planner_rejection());
assert!(
small
.to_string()
.starts_with("max-context 524288 needs 6962774016 B of the 5943000000 B VRAM pool")
);
assert!(small.to_string().starts_with("max-context 524288 needs 6962774016 B of the 5943000000 B VRAM pool"));
assert!(resolve_context(&req(1, 524_288, KvFormat::Int8, 32 * GIB)).is_ok());
}
@@ -42,10 +38,7 @@ fn int8_does_not_close_on_the_default_pool_but_does_on_32_gib() {
fn explicit_none_past_trained_is_refused() {
let mut r = req(1, 524_288, KvFormat::Q4_0, 32 * GIB);
r.rope_scaling = Some(RopeScalingType::None);
assert_eq!(
resolve_context(&r),
Err(PolicyError::Setup(SetupRopeError::NoneBeyondTrained))
);
assert_eq!(resolve_context(&r), Err(PolicyError::Setup(SetupRopeError::NoneBeyondTrained)));
// per-slot, not total: 2 x 256K with explicit none is fine
let mut r = req(2, 262_144, KvFormat::Q4_0, 32 * GIB);
r.rope_scaling = Some(RopeScalingType::None);
@@ -56,10 +49,7 @@ fn explicit_none_past_trained_is_refused() {
fn stray_scale_inside_trained_range_is_refused() {
let mut r = req(2, 262_144, KvFormat::Q4_0, 32 * GIB);
r.rope_scale = Some(2.0);
assert_eq!(
resolve_context(&r),
Err(PolicyError::Setup(SetupRopeError::ScaleWithoutMethod))
);
assert_eq!(resolve_context(&r), Err(PolicyError::Setup(SetupRopeError::ScaleWithoutMethod)));
}
#[test]
@@ -75,40 +65,25 @@ fn explicit_method_and_factor_are_kept_verbatim() {
#[test]
fn request_errors() {
assert_eq!(
resolve_context(&req(0, 1, KvFormat::Int8, GIB)),
Err(PolicyError::ZeroSlots)
);
assert_eq!(
resolve_context(&req(1, 0, KvFormat::Int8, GIB)),
Err(PolicyError::ZeroContext)
);
assert_eq!(resolve_context(&req(0, 1, KvFormat::Int8, GIB)), Err(PolicyError::ZeroSlots));
assert_eq!(resolve_context(&req(1, 0, KvFormat::Int8, GIB)), Err(PolicyError::ZeroContext));
assert!(matches!(
resolve_context(&req(1, 524_289, KvFormat::Int8, 64 * GIB)),
Err(PolicyError::ContextTooLarge { .. })
));
let mut r = req(1, 262_144, KvFormat::Int8Keyless, 32 * GIB);
assert_eq!(
resolve_context(&r),
Err(PolicyError::ExperimentalKvFormat(KvFormat::Int8Keyless))
);
assert_eq!(resolve_context(&r), Err(PolicyError::ExperimentalKvFormat(KvFormat::Int8Keyless)));
r.allow_experimental = true;
assert!(resolve_context(&r).is_ok());
// slot multiplication overflow is reported, not wrapped
assert_eq!(
resolve_context(&req(u64::MAX, 2, KvFormat::Int8, GIB)),
Err(PolicyError::Plan(PlanError::Overflow))
);
assert_eq!(resolve_context(&req(u64::MAX, 2, KvFormat::Int8, GIB)), Err(PolicyError::Plan(PlanError::Overflow)));
}
#[test]
fn bad_rope_knobs_are_refused() {
let mut r = req(1, 524_288, KvFormat::Q4_0, 32 * GIB);
r.rope_knobs.yarn_beta_fast = f64::NAN;
assert_eq!(
resolve_context(&r),
Err(PolicyError::Rope(RopeKnobError::NotFinite))
);
assert_eq!(resolve_context(&r), Err(PolicyError::Rope(RopeKnobError::NotFinite)));
}
#[test]
@@ -126,9 +101,6 @@ fn advisory_flags_the_indexer_term_gap() {
// Q4_0 1 x 512K on 8 GB: planner is the judge; the advisory only annotates
let e = resolve_context(&req(1, 524_288, KvFormat::Q4_0, 6_100_000_000));
if let Ok(e) = e {
assert_eq!(
e.engine_estimate_exceeds_pool,
e.engine_estimate.total > e.plan.vram_budget
);
assert_eq!(e.engine_estimate_exceeds_pool, e.engine_estimate.total > e.plan.vram_budget);
}
}
+9 -30
View File
@@ -39,10 +39,9 @@ pub enum GeometryError {
impl fmt::Display for GeometryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Cells(n) => write!(
f,
"context of {n} cells must be a positive multiple of {PAGE_CELLS} and at most {MAX_CELLS}"
),
Self::Cells(n) => {
write!(f, "context of {n} cells must be a positive multiple of {PAGE_CELLS} and at most {MAX_CELLS}")
}
Self::Resident(n) => write!(
f,
"a resident KV window of {n} cells is not servable: it must give at least {RESOLVE_BLOCK} pages and at most {MAX_CELLS} cells (0 keeps the whole context resident)"
@@ -71,9 +70,7 @@ pub struct QsaGeometry {
impl QsaGeometry {
/// The frozen default (`262144` cells).
pub const TRAINED: Self = Self {
cells: TRAINED_CELLS,
};
pub const TRAINED: Self = Self { cells: TRAINED_CELLS };
pub fn new(cells: usize) -> R<Self> {
if cells == 0 || !cells.is_multiple_of(PAGE_CELLS) || cells > MAX_CELLS {
@@ -126,21 +123,12 @@ impl QsaGeometry {
/// Device staging pool: four runs, identity table and a 4 byte status word (`277_086_212`).
pub fn stage_bytes(self) -> R<usize> {
let r = self.stage_runs()?;
add(
add(
add(add(r[0], r[1])?, add(r[2], r[3])?)?,
self.page_table_bytes(),
)?,
4,
)
add(add(add(add(r[0], r[1])?, add(r[2], r[3])?)?, self.page_table_bytes())?, 4)
}
/// Device bytes of one layer's resident pool: the fixed 8192-page resident runs, the page table and
/// `map_bytes` of resolver state. `34_865_152 + map_bytes` at the trained size.
pub fn resident_bytes(self, map_bytes: usize) -> R<usize> {
add(
add(RESIDENT_RUNS_BYTES, self.page_table_bytes())?,
map_bytes,
)
add(add(RESIDENT_RUNS_BYTES, self.page_table_bytes())?, map_bytes)
}
/// Resident pages (VRAM slots) of one streamed QSA layer for `--kv-resident resident_cells`
/// (`layer.cpp::kv_plan`, `mode == 1`): `ceil(max(resident_cells, 20480) / 4)`. `0` keeps every page of
@@ -154,9 +142,7 @@ impl QsaGeometry {
let pages = if resident_cells == 0 {
self.pages()
} else {
resident_cells
.max(KV_RESIDENT_MIN_CELLS)
.div_ceil(PAGE_CELLS)
resident_cells.max(KV_RESIDENT_MIN_CELLS).div_ceil(PAGE_CELLS)
};
if pages < RESOLVE_BLOCK {
return Err(GeometryError::Resident(resident_cells));
@@ -167,13 +153,7 @@ impl QsaGeometry {
/// context page table and `map_bytes` of resolver state.
pub fn resident_bytes_with(self, slots: usize, map_bytes: usize) -> R<usize> {
let runs = resident_runs(slots)?;
add(
add(
add(add(runs[0], runs[1])?, add(runs[2], runs[3])?)?,
self.page_table_bytes(),
)?,
map_bytes,
)
add(add(add(add(runs[0], runs[1])?, add(runs[2], runs[3])?)?, self.page_table_bytes())?, map_bytes)
}
/// Canonical host metadata bound of one layer (`NativeQsaResources::CANONICAL_METADATA`).
pub fn canonical_metadata_bytes(self) -> R<usize> {
@@ -220,8 +200,7 @@ impl QsaGeometry {
/// [`KvStreamFootprint`] of this context with `--kv-resident resident_cells`.
pub fn kv_stream_footprint(self, resident_cells: usize) -> R<KvStreamFootprint> {
let resident_pages = self.resident_pages_for(resident_cells)?;
let layer_vram_bytes =
self.resident_bytes_with(resident_pages, stream_map_bytes(resident_pages)?)?;
let layer_vram_bytes = self.resident_bytes_with(resident_pages, stream_map_bytes(resident_pages)?)?;
Ok(KvStreamFootprint {
cells: self.cells,
resident_cells,
+12 -48
View File
@@ -12,14 +12,8 @@ fn trained_geometry_reproduces_every_frozen_literal() {
assert_eq!(g.max_blocks(), 65_538); // qsa_prompt_index MAX_BLOCKS
assert_eq!(g.host_payload_bytes(), Ok(276_824_064)); // QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES
assert_eq!(g.mapped_host_bytes(), Ok(276_825_088)); // QSA_PROMPT_MAPPED_HOST_BYTES, host BYTES
assert_eq!(
g.stage_runs(),
Ok([134_217_728, 134_217_728, 4_194_304, 4_194_304])
);
assert_eq!(
g.stage_offsets(),
Ok([0, 134_217_728, 268_435_456, 272_629_760])
);
assert_eq!(g.stage_runs(), Ok([134_217_728, 134_217_728, 4_194_304, 4_194_304]));
assert_eq!(g.stage_offsets(), Ok([0, 134_217_728, 268_435_456, 272_629_760]));
assert_eq!(g.stage_bytes(), Ok(277_086_212)); // QSA_PROMPT_STAGE_BYTES
assert_eq!(g.resident_bytes(0), Ok(34_865_152)); // QSA_PROMPT_RESIDENT_BYTES - MAP_BYTES
assert_eq!(g.canonical_metadata_bytes(), Ok(65_536 * 160 + 4096));
@@ -33,40 +27,22 @@ fn trained_geometry_reproduces_every_frozen_literal() {
#[test]
fn resident_window_follows_kv_plan_and_reproduces_the_frozen_pool_at_the_default() {
let g = QsaGeometry::TRAINED;
assert_eq!(
g.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS),
Ok(RESIDENT_PAGES)
);
assert_eq!(g.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS), Ok(RESIDENT_PAGES));
assert_eq!(resident_runs(RESIDENT_PAGES), Ok(RESIDENT_RUNS));
assert_eq!(stream_map_bytes(RESIDENT_PAGES), Ok(163_904));
assert_eq!(
g.resident_bytes_with(RESIDENT_PAGES, 163_904),
g.resident_bytes(163_904)
);
assert_eq!(g.resident_bytes_with(RESIDENT_PAGES, 163_904), g.resident_bytes(163_904));
// max(resident, qsa_kv_resident_min()) rounded up to whole pages
assert_eq!(g.resident_pages_for(1), Ok(5120));
assert_eq!(g.resident_pages_for(20_480), Ok(5120));
assert_eq!(g.resident_pages_for(20_481), Ok(5121));
// 0: the whole context resident
assert_eq!(g.resident_pages_for(0), Ok(65_536));
assert_eq!(
QsaGeometry::new(MAX_CELLS).unwrap().resident_pages_for(0),
Ok(131_072)
);
assert_eq!(QsaGeometry::new(MAX_CELLS).unwrap().resident_pages_for(0), Ok(131_072));
// a tiny context cannot be fully resident with fewer slots than the resolve block
assert_eq!(
QsaGeometry::new(1024).unwrap().resident_pages_for(0),
Err(GeometryError::Resident(0))
);
assert_eq!(
g.resident_pages_for(MAX_CELLS + 4),
Err(GeometryError::Resident(MAX_CELLS + 4))
);
assert_eq!(QsaGeometry::new(1024).unwrap().resident_pages_for(0), Err(GeometryError::Resident(0)));
assert_eq!(g.resident_pages_for(MAX_CELLS + 4), Err(GeometryError::Resident(MAX_CELLS + 4)));
// production profile: 12 layers x (32768 cells x 1056 B) of VRAM KV
assert_eq!(
resident_runs(RESIDENT_PAGES).unwrap().iter().sum::<usize>(),
32_768 * KV_CELL_BYTES
);
assert_eq!(resident_runs(RESIDENT_PAGES).unwrap().iter().sum::<usize>(), 32_768 * KV_CELL_BYTES);
}
#[test]
@@ -81,10 +57,7 @@ fn production_profile_footprint() {
// the smallest window frees 12 x 3072 pages x 4224 B of VRAM for expert slots
let small = QsaGeometry::TRAINED.kv_stream_footprint(20_480).unwrap();
assert_eq!(f.vram_bytes - small.vram_bytes, 12 * 3072 * (4224 + 20));
assert!(
f.to_string()
.starts_with("kv int8 context=262144 resident=32768 cells (8192 pages/layer)")
);
assert!(f.to_string().starts_with("kv int8 context=262144 resident=32768 cells (8192 pages/layer)"));
}
#[test]
@@ -100,19 +73,10 @@ fn charter_512k_scales_every_cell_linear_size_by_exactly_two() {
let b = QsaGeometry::new(MAX_CELLS).unwrap();
assert_eq!(b.pages(), 131_072);
assert_eq!(b.page_table_bytes(), 524_288);
assert_eq!(
b.host_payload_bytes().unwrap(),
2 * a.host_payload_bytes().unwrap()
);
assert_eq!(b.host_payload_bytes().unwrap(), 2 * a.host_payload_bytes().unwrap());
assert_eq!(b.mapped_host_bytes(), Ok(553_649_152));
assert_eq!(
b.stage_runs(),
Ok([268_435_456, 268_435_456, 8_388_608, 8_388_608])
);
assert_eq!(
b.stage_offsets(),
Ok([0, 268_435_456, 536_870_912, 545_259_520])
);
assert_eq!(b.stage_runs(), Ok([268_435_456, 268_435_456, 8_388_608, 8_388_608]));
assert_eq!(b.stage_offsets(), Ok([0, 268_435_456, 536_870_912, 545_259_520]));
// staging pool: runs + table + status
assert_eq!(b.stage_bytes(), Ok(2 * 276_824_064 + 524_288 + 4));
// the resident runs do not grow, only the table does
@@ -25,18 +25,14 @@ impl Default for Geometry {
impl Geometry {
pub fn n_gdn_layers(&self) -> Result<u64, PlanError> {
self.n_layers
.checked_sub(self.n_qsa_layers)
.ok_or(PlanError::Geometry("n_qsa_layers exceeds n_layers"))
self.n_layers.checked_sub(self.n_qsa_layers).ok_or(PlanError::Geometry("n_qsa_layers exceeds n_layers"))
}
/// Rejects values that would divide by zero or underflow in the Original's integer arithmetic.
pub fn validate(&self) -> Result<(), PlanError> {
self.n_gdn_layers()?;
if self.kv_group == 0 || self.qsa_block == 0 || self.ssm_d_conv == 0 {
return Err(PlanError::Geometry(
"kv_group, qsa_block and ssm_d_conv must be non-zero",
));
return Err(PlanError::Geometry("kv_group, qsa_block and ssm_d_conv must be non-zero"));
}
Ok(())
}
@@ -44,14 +40,7 @@ impl Geometry {
impl Default for Costs {
fn default() -> Self {
Self {
expert_blob: 1_382_400,
dense_bytes: 0,
embd_bytes: 0,
mtp_bytes: 0,
workspace_bytes: 0,
state_bytes: 0,
}
Self { expert_blob: 1_382_400, dense_bytes: 0, embd_bytes: 0, mtp_bytes: 0, workspace_bytes: 0, state_bytes: 0 }
}
}
@@ -77,10 +66,7 @@ pub(super) fn add(a: u64, b: u64) -> R<u64> {
/// GDN recurrence + conv history, bytes per sequence (plan.hpp `state_bytes`).
pub fn state_bytes(g: &Geometry) -> R<u64> {
g.validate()?;
let recurrence = mul(
mul(mul(g.ssm_state_size, g.ssm_v_heads)?, g.ssm_state_size)?,
4,
)?;
let recurrence = mul(mul(mul(g.ssm_state_size, g.ssm_v_heads)?, g.ssm_state_size)?, 4)?;
let conv = mul(mul(g.ssm_d_conv - 1, g.ssm_conv_channels)?, 4)?;
mul(g.n_gdn_layers()?, add(recurrence, conv)?)
}
@@ -127,37 +113,24 @@ impl KvFormat {
impl KvShapes {
pub fn real() -> Self {
Self {
n_head_kv: 2,
head_dim: 256,
page_size: 4,
}
Self { n_head_kv: 2, head_dim: 256, page_size: 4 }
}
pub fn from_geometry(g: &Geometry) -> Self {
Self {
n_head_kv: g.n_kv_heads,
head_dim: g.head_dim,
page_size: 4,
}
Self { n_head_kv: g.n_kv_heads, head_dim: g.head_dim, page_size: 4 }
}
pub(super) fn validate(&self, fmt: KvFormat) -> R<()> {
if self.page_size == 0 {
return Err(PlanError::Geometry("page_size must be non-zero"));
}
if fmt != KvFormat::Fp16 && !self.head_dim.is_multiple_of(KV_Q8_GROUP) {
return Err(PlanError::Geometry(
"quantised KV needs head_dim to be a multiple of 64",
));
return Err(PlanError::Geometry("quantised KV needs head_dim to be a multiple of 64"));
}
Ok(())
}
}
pub(super) fn q8_bytes_per_cell(s: &KvShapes) -> R<u64> {
add(
mul(mul(s.n_head_kv, s.head_dim)?, 2)?,
mul(mul(s.n_head_kv, s.head_dim / KV_Q8_GROUP)?, 4)?,
)
add(mul(mul(s.n_head_kv, s.head_dim)?, 2)?, mul(mul(s.n_head_kv, s.head_dim / KV_Q8_GROUP)?, 4)?)
}
pub(super) fn q4_bytes_per_head(head_dim: u64) -> R<u64> {
mul(head_dim / QK4_0, BLOCK_Q4_0_BYTES)
@@ -175,10 +148,7 @@ pub fn kv_cell_bytes(s: &KvShapes, fmt: KvFormat) -> R<u64> {
KvFormat::K8V4 => {
let rows = s.n_head_kv;
add(
add(
mul(rows, s.head_dim)?,
mul(mul(rows, s.head_dim / KV_Q8_GROUP)?, 2)?,
)?,
add(mul(rows, s.head_dim)?, mul(mul(rows, s.head_dim / KV_Q8_GROUP)?, 2)?)?,
mul(rows, q4_bytes_per_head(s.head_dim)?)?,
)
}
@@ -216,12 +186,6 @@ pub fn make_plan(max_context: u64, g: &Geometry, c: &Costs, pool: u64) -> R<Plan
}
/// EXTENSION: `make_plan` with another KV format's bytes per token. `Int8` reproduces [`make_plan`].
pub fn make_plan_with_format(
max_context: u64,
g: &Geometry,
fmt: KvFormat,
c: &Costs,
pool: u64,
) -> R<Plan> {
pub fn make_plan_with_format(max_context: u64, g: &Geometry, fmt: KvFormat, c: &Costs, pool: u64) -> R<Plan> {
plan_with_per_token(max_context, kv_bytes_per_token(g, fmt)?, c, pool)
}
@@ -3,21 +3,13 @@
#[allow(unused_imports)]
use super::*;
pub(super) fn plan_with_per_token(
max_context: u64,
per_token: u64,
c: &Costs,
pool: u64,
) -> R<Plan> {
pub(super) fn plan_with_per_token(max_context: u64, per_token: u64, c: &Costs, pool: u64) -> R<Plan> {
if c.expert_blob == 0 {
return Err(PlanError::Geometry("expert_blob must be non-zero"));
}
let kv_bytes = mul(per_token, max_context)?;
let dram_experts = add(c.dense_bytes, c.embd_bytes)?;
let fixed = add(
add(add(dram_experts, c.mtp_bytes)?, c.workspace_bytes)?,
c.state_bytes,
)?;
let fixed = add(add(add(dram_experts, c.mtp_bytes)?, c.workspace_bytes)?, c.state_bytes)?;
let need = add(kv_bytes, fixed)?;
if need > pool {
return does_not_close(format!(
@@ -28,9 +20,7 @@ pub(super) fn plan_with_per_token(
let cache_slots = cache_bytes / c.expert_blob;
let vram_used = pool - cache_bytes % c.expert_blob;
if cache_slots == 0 {
return does_not_close(format!(
"no room for even one expert cache slot at max-context {max_context}"
));
return does_not_close(format!("no room for even one expert cache slot at max-context {max_context}"));
}
Ok(Plan {
max_context,
@@ -95,10 +85,7 @@ pub fn engine_resident_estimate(
let kv_layer = kv_pool_bytes(&s, pages, fmt)?;
let pooled_rows = ctx_per_slot / g.qsa_block + 2;
let idx_layer = add(
add(
mul(mul(g.qsa_block - 1, g.indexer_key_dim)?, 4)?,
mul(g.indexer_key_dim, 4)?,
)?,
add(mul(mul(g.qsa_block - 1, g.indexer_key_dim)?, 4)?, mul(g.indexer_key_dim, 4)?)?,
mul(mul(pooled_rows, g.indexer_key_dim)?, 4)?,
)?;
let per_slot_kv = mul(layers, kv_layer)?;
@@ -112,15 +99,6 @@ pub fn engine_resident_estimate(
let page_tables = mul(slots, per_slot_pt)?;
let indexer_stores = mul(slots, per_slot_idx)?;
let rope_tables = mul(slots, per_slot_rope)?;
let total = add(
add(add(kv_pools, page_tables)?, indexer_stores)?,
rope_tables,
)?;
Ok(EngineResidentEstimate {
kv_pools,
page_tables,
indexer_stores,
rope_tables,
total,
})
let total = add(add(add(kv_pools, page_tables)?, indexer_stores)?, rope_tables)?;
Ok(EngineResidentEstimate { kv_pools, page_tables, indexer_stores, rope_tables, total })
}
+7 -33
View File
@@ -5,10 +5,7 @@ use super::*;
#[test]
fn real_geometry_constants() {
let g = Geometry::default();
assert_eq!(
state_bytes(&g).unwrap(),
36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4)
);
assert_eq!(state_bytes(&g).unwrap(), 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4));
assert_eq!(state_bytes(&g).unwrap(), 117_669_888);
// 12 layers x (1056 + 32)
assert_eq!(kv_bytes_per_token_int8(&g).unwrap(), 13_056);
@@ -26,19 +23,8 @@ fn per_cell_bytes_on_real_shapes() {
#[test]
fn int8_generic_equals_literal() {
for g in [
Geometry::default(),
Geometry {
n_kv_heads: 4,
head_dim: 128,
n_qsa_layers: 9,
..Geometry::default()
},
] {
assert_eq!(
kv_bytes_per_token(&g, KvFormat::Int8).unwrap(),
kv_bytes_per_token_int8(&g).unwrap()
);
for g in [Geometry::default(), Geometry { n_kv_heads: 4, head_dim: 128, n_qsa_layers: 9, ..Geometry::default() }] {
assert_eq!(kv_bytes_per_token(&g, KvFormat::Int8).unwrap(), kv_bytes_per_token_int8(&g).unwrap());
}
}
@@ -47,10 +33,7 @@ fn pool_derivation_quirks() {
let c = Costs::default();
assert_eq!(cli_pool(12_000_000_000, &c).unwrap(), 12_000_000_000);
// derived 0 becomes the default pool
let heavy = Costs {
dense_bytes: 13_000_000_000,
..c
};
let heavy = Costs { dense_bytes: 13_000_000_000, ..c };
assert_eq!(cli_pool(12_000_000_000, &heavy).unwrap(), vram_pool_bytes());
assert_eq!(cli_pool(0, &c).unwrap(), vram_pool_bytes());
}
@@ -67,28 +50,19 @@ fn does_not_close_messages() {
// exactly full pool: zero cache slots
let exact = 13_056 * 1000;
let e = make_plan(1000, &g, &c, exact).unwrap_err();
assert_eq!(
e.to_string(),
"no room for even one expert cache slot at max-context 1000"
);
assert_eq!(e.to_string(), "no room for even one expert cache slot at max-context 1000");
}
#[test]
fn overflow_is_reported_not_wrapped() {
let g = Geometry::default();
assert_eq!(
make_plan(u64::MAX, &g, &Costs::default(), 1),
Err(PlanError::Overflow)
);
assert_eq!(make_plan(u64::MAX, &g, &Costs::default(), 1), Err(PlanError::Overflow));
}
#[test]
fn q4_makes_both_charter_profiles_close_where_int8_does_not() {
let g = Geometry::default();
let c = Costs {
state_bytes: state_bytes(&g).unwrap(),
..Costs::default()
};
let c = Costs { state_bytes: state_bytes(&g).unwrap(), ..Costs::default() };
let pool = 5_943_000_000;
assert!(make_plan_with_format(524_288, &g, KvFormat::Int8, &c, pool).is_err());
assert!(make_plan_with_format(524_288, &g, KvFormat::Q4_0, &c, pool).is_ok());
+3 -4
View File
@@ -64,7 +64,8 @@ pub fn classify_set(entries: &[(&str, &str, usize)], extra: usize) -> Option<Set
mod tests {
use super::*;
const SAMPLE: &str = ".visible .entry k(\n\t.param .u64 k_param_0,\n\t.param .u32 k_param_1\n)\n.maxntid 1, 1, 1\n{\n}\n";
const SAMPLE: &str =
".visible .entry k(\n\t.param .u64 k_param_0,\n\t.param .u32 k_param_1\n)\n.maxntid 1, 1, 1\n{\n}\n";
#[test]
fn counts_params_of_the_named_entry_only() {
@@ -88,9 +89,7 @@ mod tests {
}
fn committed(name: &str) -> String {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../cuda-driver/src")
.join(name);
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../cuda-driver/src").join(name);
std::fs::read_to_string(path).unwrap()
}
@@ -22,17 +22,13 @@ pub fn fill_rope_table(
return Err(RopeTableError::BufferLength);
}
let rows = cos_out.len() / half;
let end = first_pos
.checked_add(rows)
.ok_or(RopeTableError::TooManyPositions(rows))?;
let end = first_pos.checked_add(rows).ok_or(RopeTableError::TooManyPositions(rows))?;
if i32::try_from(end).is_err() {
return Err(RopeTableError::TooManyPositions(end));
}
// inv[i] depends only on i: hoisting the pow out of the position loop yields the same value per entry.
let n_rot_f = n_rot as f64;
let inv: Vec<f64> = (0..half)
.map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f))
.collect();
let inv: Vec<f64> = (0..half).map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f)).collect();
if sc.kind == RopeScalingType::None {
for r in 0..rows {
let p = (first_pos + r) as f64;
@@ -50,9 +46,7 @@ pub fn fill_rope_table(
let correct = sc.ext_factor != 0.0;
let (low, high) = (cd[0] as f32, cd[1] as f32);
// the ramp depends on the pair only
let ramp: Vec<f64> = (0..half)
.map(|i| f64::from(rope_yarn_ramp(low, high, i as i32)) * sc.ext_factor)
.collect();
let ramp: Vec<f64> = (0..half).map(|i| f64::from(rope_yarn_ramp(low, high, i as i32)) * sc.ext_factor).collect();
for r in 0..rows {
let p = (first_pos + r) as f64;
for i in 0..half {
@@ -82,24 +76,13 @@ impl RopeTable {
}
/// `build_rope_table(n_rot, scaling, n_pos, ...)`; `n_pos` up to 524288 (128 MiB for `n_rot` 64) and beyond.
pub fn build_rope_table(
n_rot: usize,
sc: &RopeScaling,
n_pos: usize,
) -> Result<RopeTable, RopeTableError> {
pub fn build_rope_table(n_rot: usize, sc: &RopeScaling, n_pos: usize) -> Result<RopeTable, RopeTableError> {
check_n_rot(n_rot)?;
let len = n_pos
.checked_mul(n_rot / 2)
.ok_or(RopeTableError::TooManyPositions(n_pos))?;
let len = n_pos.checked_mul(n_rot / 2).ok_or(RopeTableError::TooManyPositions(n_pos))?;
let mut cos = vec![0.0f32; len];
let mut sin = vec![0.0f32; len];
fill_rope_table(n_rot, sc, 0, &mut cos, &mut sin)?;
Ok(RopeTable {
n_rot,
n_pos,
cos,
sin,
})
Ok(RopeTable { n_rot, n_pos, cos, sin })
}
impl Default for RopeKnobs {
@@ -144,10 +127,7 @@ impl std::error::Error for RopeKnobError {}
/// Port of the `generate.cpp` rope resolution: range checks, then precedence flag > model file > defaults,
/// the `none` reset, and the whole-config validity rule.
pub fn resolve_rope_scaling(
knobs: &RopeKnobs,
model: &ModelRopeKeys,
) -> Result<ResolvedRope, RopeKnobError> {
pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result<ResolvedRope, RopeKnobError> {
let all = [
knobs.rope_scale,
knobs.rope_freq_base,
@@ -220,16 +200,10 @@ pub fn resolve_rope_scaling(
|| knobs.yarn_ext_factor > 0.0
|| knobs.yarn_attn_factor != 1.0;
let base = cfg.freq_base;
cfg = RopeScaling {
freq_base: base,
..RopeScaling::default()
};
cfg = RopeScaling { freq_base: base, ..RopeScaling::default() };
}
cfg.validate().map_err(RopeKnobError::Invalid)?;
Ok(ResolvedRope {
scaling: cfg,
inert_knobs_ignored: inert,
})
Ok(ResolvedRope { scaling: cfg, inert_knobs_ignored: inert })
}
/// `setup.py::derived_factor`: final context over the trained one, at least 1.
@@ -35,16 +35,10 @@ pub fn setup_resolve_rope(
return Ok(None);
}
let kind = scaling.unwrap_or(RopeScalingType::YaRN);
return Ok(Some((
kind,
scale.unwrap_or_else(|| derived_factor(ctx, trained)),
)));
return Ok(Some((kind, scale.unwrap_or_else(|| derived_factor(ctx, trained)))));
}
if scaling == Some(RopeScalingType::None) {
return Err(SetupRopeError::NoneBeyondTrained);
}
Ok(Some((
scaling.unwrap_or(RopeScalingType::YaRN),
scale.unwrap_or_else(|| derived_factor(ctx, trained)),
)))
Ok(Some((scaling.unwrap_or(RopeScalingType::YaRN), scale.unwrap_or_else(|| derived_factor(ctx, trained)))))
}
@@ -23,13 +23,7 @@ impl RopeScalingType {
impl Default for RopeKernelArgs {
fn default() -> Self {
Self {
freq_scale: 1.0,
corr_low: 0.0,
corr_high: 0.0,
ext_factor: 0.0,
attn_factor: 1.0,
}
Self { freq_scale: 1.0, corr_low: 0.0, corr_high: 0.0, ext_factor: 0.0, attn_factor: 1.0 }
}
}
@@ -39,9 +33,7 @@ impl RopeScalingError {
Self::FreqBase => "the frequency base must be a finite value above 1",
Self::Factor => "the scaling factor must be a finite value >= 1",
Self::FreqScaleIn => "the frequency scale must be finite and positive (0 = 1/factor)",
Self::ResolvedFreqScale => {
"the resolved frequency scale must be a finite positive value"
}
Self::ResolvedFreqScale => "the resolved frequency scale must be a finite positive value",
Self::OrigCtx => "the original (trained) context must be finite and > 0",
Self::ExtFactor => "the YaRN ext factor must be finite and >= 0",
Self::AttnFactor => "the attention factor must be finite and > 0",
@@ -86,11 +78,7 @@ impl RopeScaling {
if self.kind == RopeScalingType::None {
return 1.0;
}
if self.freq_scale_in > 0.0 {
self.freq_scale_in
} else {
1.0 / self.factor
}
if self.freq_scale_in > 0.0 { self.freq_scale_in } else { 1.0 / self.factor }
}
/// The magnitude correction; the log term rides on `ext_factor != 0`, not on the type.
@@ -103,14 +91,10 @@ impl RopeScaling {
/// The correction window in PAIR indices, clamped to `[0, n_rot - 1]`.
pub fn corr_dims(&self, n_rot: i32) -> [f64; 2] {
let start =
rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_fast, self.freq_base).floor();
let start = rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_fast, self.freq_base).floor();
let end = rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_slow, self.freq_base).ceil();
let hi = f64::from(n_rot - 1);
[
if start < 0.0 { 0.0 } else { start },
if end > hi { hi } else { end },
]
[if start < 0.0 { 0.0 } else { start }, if end > hi { hi } else { end }]
}
/// The analytic kernels' constants; `none` returns the identity whatever the other knobs hold.
@@ -156,10 +140,7 @@ impl RopeScaling {
if !self.attn_factor.is_finite() || self.attn_factor <= 0.0 {
return Err(RopeScalingError::AttnFactor);
}
if !self.beta_fast.is_finite()
|| self.beta_fast <= 0.0
|| !self.beta_slow.is_finite()
|| self.beta_slow <= 0.0
if !self.beta_fast.is_finite() || self.beta_fast <= 0.0 || !self.beta_slow.is_finite() || self.beta_slow <= 0.0
{
return Err(RopeScalingError::Betas);
}
+26 -115
View File
@@ -3,12 +3,7 @@
use super::*;
fn yarn(factor: f64) -> RopeScaling {
RopeScaling {
kind: RopeScalingType::YaRN,
factor,
ext_factor: 1.0,
..RopeScaling::default()
}
RopeScaling { kind: RopeScalingType::YaRN, factor, ext_factor: 1.0, ..RopeScaling::default() }
}
#[test]
@@ -49,11 +44,7 @@ fn non_finite_values_are_rejected_before_range_checks() {
s.attn_factor = f64::NAN;
assert_eq!(s.validate(), Err(RopeScalingError::AttnFactor));
// none ignores every knob except the base
let n = RopeScaling {
factor: f64::NAN,
beta_fast: -1.0,
..RopeScaling::default()
};
let n = RopeScaling { factor: f64::NAN, beta_fast: -1.0, ..RopeScaling::default() };
assert_eq!(n.validate(), Ok(()));
}
@@ -81,25 +72,13 @@ fn position_zero_exposes_mscale() {
#[test]
fn bad_shapes_and_configs_are_refused() {
assert_eq!(
build_rope_table(63, &RopeScaling::default(), 1),
Err(RopeTableError::NRot(63))
);
assert_eq!(
build_rope_table(0, &RopeScaling::default(), 1),
Err(RopeTableError::NRot(0))
);
assert_eq!(build_rope_table(63, &RopeScaling::default(), 1), Err(RopeTableError::NRot(63)));
assert_eq!(build_rope_table(0, &RopeScaling::default(), 1), Err(RopeTableError::NRot(0)));
let bad = yarn(0.5);
assert!(matches!(
build_rope_table(64, &bad, 1),
Err(RopeTableError::Config(RopeScalingError::Factor))
));
assert!(matches!(build_rope_table(64, &bad, 1), Err(RopeTableError::Config(RopeScalingError::Factor))));
let mut c = vec![0.0; 33];
let mut s = vec![0.0; 33];
assert_eq!(
fill_rope_table(64, &RopeScaling::default(), 0, &mut c, &mut s),
Err(RopeTableError::BufferLength)
);
assert_eq!(fill_rope_table(64, &RopeScaling::default(), 0, &mut c, &mut s), Err(RopeTableError::BufferLength));
}
#[test]
@@ -115,30 +94,12 @@ fn setup_resolution_matches_setup_py() {
let t = TRAINED_CONTEXT;
assert_eq!(setup_resolve_rope(t, None, None, t), Ok(None));
assert_eq!(setup_resolve_rope(t, nn, None, t), Ok(None));
assert_eq!(
setup_resolve_rope(t, None, Some(2.0), t),
Err(SetupRopeError::ScaleWithoutMethod)
);
assert_eq!(
setup_resolve_rope(t, Some(Linear), None, t),
Ok(Some((Linear, 1.0)))
);
assert_eq!(
setup_resolve_rope(524_288, None, None, t),
Ok(Some((YaRN, 2.0)))
);
assert_eq!(
setup_resolve_rope(393_216, None, None, t),
Ok(Some((YaRN, 1.5)))
);
assert_eq!(
setup_resolve_rope(524_288, Some(Linear), Some(3.0), t),
Ok(Some((Linear, 3.0)))
);
assert_eq!(
setup_resolve_rope(524_288, nn, None, t),
Err(SetupRopeError::NoneBeyondTrained)
);
assert_eq!(setup_resolve_rope(t, None, Some(2.0), t), Err(SetupRopeError::ScaleWithoutMethod));
assert_eq!(setup_resolve_rope(t, Some(Linear), None, t), Ok(Some((Linear, 1.0))));
assert_eq!(setup_resolve_rope(524_288, None, None, t), Ok(Some((YaRN, 2.0))));
assert_eq!(setup_resolve_rope(393_216, None, None, t), Ok(Some((YaRN, 1.5))));
assert_eq!(setup_resolve_rope(524_288, Some(Linear), Some(3.0), t), Ok(Some((Linear, 3.0))));
assert_eq!(setup_resolve_rope(524_288, nn, None, t), Err(SetupRopeError::NoneBeyondTrained));
}
#[test]
@@ -149,47 +110,24 @@ fn knob_resolution_follows_generate_cpp() {
assert!(!r.inert_knobs_ignored);
// yarn factor 2: ext auto = 1
let k = RopeKnobs {
scaling: Some(RopeScalingType::YaRN),
rope_scale: 2.0,
..RopeKnobs::default()
};
let k = RopeKnobs { scaling: Some(RopeScalingType::YaRN), rope_scale: 2.0, ..RopeKnobs::default() };
let r = resolve_rope_scaling(&k, &ModelRopeKeys::default()).unwrap();
assert_eq!(r.scaling.kind, RopeScalingType::YaRN);
assert_eq!(r.scaling.factor, 2.0);
assert_eq!(r.scaling.ext_factor, 1.0);
// linear: ext auto = 0
let k = RopeKnobs {
scaling: Some(RopeScalingType::Linear),
rope_scale: 2.0,
..RopeKnobs::default()
};
assert_eq!(
resolve_rope_scaling(&k, &ModelRopeKeys::default())
.unwrap()
.scaling
.ext_factor,
0.0
);
let k = RopeKnobs { scaling: Some(RopeScalingType::Linear), rope_scale: 2.0, ..RopeKnobs::default() };
assert_eq!(resolve_rope_scaling(&k, &ModelRopeKeys::default()).unwrap().scaling.ext_factor, 0.0);
// model file supplies defaults; an explicit none opts out and notes the dropped knobs
let model = ModelRopeKeys {
scaling_type: Some("yarn".into()),
factor: 2.0,
freq_base: 5e6,
orig_ctx: 131_072.0,
};
let model = ModelRopeKeys { scaling_type: Some("yarn".into()), factor: 2.0, freq_base: 5e6, orig_ctx: 131_072.0 };
let r = resolve_rope_scaling(&RopeKnobs::default(), &model).unwrap();
assert_eq!(r.scaling.kind, RopeScalingType::YaRN);
assert_eq!(r.scaling.factor, 2.0);
assert_eq!(r.scaling.freq_base, 5e6);
assert_eq!(r.scaling.orig_ctx, 131_072.0);
let k = RopeKnobs {
scaling: Some(RopeScalingType::None),
rope_scale: 2.0,
..RopeKnobs::default()
};
let k = RopeKnobs { scaling: Some(RopeScalingType::None), rope_scale: 2.0, ..RopeKnobs::default() };
let r = resolve_rope_scaling(&k, &model).unwrap();
assert_eq!(r.scaling.kind, RopeScalingType::None);
assert_eq!(r.scaling.freq_base, 5e6);
@@ -197,43 +135,16 @@ fn knob_resolution_follows_generate_cpp() {
assert!(r.inert_knobs_ignored);
// refusals
let bad_scale = RopeKnobs {
rope_scale: 0.5,
..RopeKnobs::default()
};
assert_eq!(
resolve_rope_scaling(&bad_scale, &model),
Err(RopeKnobError::ScaleBelowOne)
);
let nan = RopeKnobs {
yarn_beta_fast: f64::NAN,
..RopeKnobs::default()
};
assert_eq!(
resolve_rope_scaling(&nan, &model),
Err(RopeKnobError::NotFinite)
);
let base1 = RopeKnobs {
rope_freq_base: 1.0,
..RopeKnobs::default()
};
assert_eq!(
resolve_rope_scaling(&base1, &model),
Err(RopeKnobError::FreqBase)
);
let neg = RopeKnobs {
yarn_attn_factor: 0.0,
..RopeKnobs::default()
};
let bad_scale = RopeKnobs { rope_scale: 0.5, ..RopeKnobs::default() };
assert_eq!(resolve_rope_scaling(&bad_scale, &model), Err(RopeKnobError::ScaleBelowOne));
let nan = RopeKnobs { yarn_beta_fast: f64::NAN, ..RopeKnobs::default() };
assert_eq!(resolve_rope_scaling(&nan, &model), Err(RopeKnobError::NotFinite));
let base1 = RopeKnobs { rope_freq_base: 1.0, ..RopeKnobs::default() };
assert_eq!(resolve_rope_scaling(&base1, &model), Err(RopeKnobError::FreqBase));
let neg = RopeKnobs { yarn_attn_factor: 0.0, ..RopeKnobs::default() };
assert_eq!(resolve_rope_scaling(&neg, &model), Err(RopeKnobError::Knob));
let weird = ModelRopeKeys {
scaling_type: Some("longrope".into()),
..ModelRopeKeys::default()
};
assert_eq!(
resolve_rope_scaling(&RopeKnobs::default(), &weird),
Err(RopeKnobError::ModelType("longrope".into()))
);
let weird = ModelRopeKeys { scaling_type: Some("longrope".into()), ..ModelRopeKeys::default() };
assert_eq!(resolve_rope_scaling(&RopeKnobs::default(), &weird), Err(RopeKnobError::ModelType("longrope".into())));
// a resolved factor that is fine per-flag but invalid as a whole
let k = RopeKnobs {
scaling: Some(RopeScalingType::YaRN),
+7 -35
View File
@@ -28,36 +28,12 @@ pub struct Model {
/// `setup.py` `MODELS`, in file order.
pub const MODELS: [Model; 6] = [
Model {
name: "Q2_0",
ram_gb: 48,
arena_gb: 34.0,
},
Model {
name: "IQ2_XS",
ram_gb: 48,
arena_gb: 35.5,
},
Model {
name: "IQ3_XXS",
ram_gb: 60,
arena_gb: 42.9,
},
Model {
name: "IQ3_S",
ram_gb: 62,
arena_gb: 50.3,
},
Model {
name: "IQ1_M",
ram_gb: 32,
arena_gb: 23.4,
},
Model {
name: "UD-Q4_K_XL",
ram_gb: 48,
arena_gb: 77.0,
},
Model { name: "Q2_0", ram_gb: 48, arena_gb: 34.0 },
Model { name: "IQ2_XS", ram_gb: 48, arena_gb: 35.5 },
Model { name: "IQ3_XXS", ram_gb: 60, arena_gb: 42.9 },
Model { name: "IQ3_S", ram_gb: 62, arena_gb: 50.3 },
Model { name: "IQ1_M", ram_gb: 32, arena_gb: 23.4 },
Model { name: "UD-Q4_K_XL", ram_gb: 48, arena_gb: 77.0 },
];
pub fn model(name: &str) -> Option<&'static Model> {
@@ -73,11 +49,7 @@ pub enum Kv {
impl Kv {
pub fn parse(name: &str) -> Self {
if name == "q4_0" {
Self::Q4_0
} else {
Self::Int8
}
if name == "q4_0" { Self::Q4_0 } else { Self::Int8 }
}
}
+9 -45
View File
@@ -2,23 +2,14 @@
//! geometry the driver and runtime allocate from. The driver and runtime consume `QsaGeometry` through their
//! serving context (linux-only crates); everything they size is a function of the values asserted here.
use leleka_context::context_policy::{
CHARTER_PROFILES, ContextRequest, PolicyError, ROPE_N_ROT, resolve_context,
};
use leleka_context::context_policy::{CHARTER_PROFILES, ContextRequest, PolicyError, ROPE_N_ROT, resolve_context};
use leleka_context::geometry::{MAX_CELLS, QsaGeometry, TRAINED_CELLS};
use leleka_context::memory_plan::KvFormat;
use leleka_context::rope_scaling::{RopeScalingType, build_rope_table};
const GIB: u64 = 1 << 30;
fn geometry_of(
slots: u64,
ctx: u64,
vram: u64,
) -> (
leleka_context::context_policy::EffectiveContext,
QsaGeometry,
) {
fn geometry_of(slots: u64, ctx: u64, vram: u64) -> (leleka_context::context_policy::EffectiveContext, QsaGeometry) {
let e = resolve_context(&ContextRequest::new(slots, ctx, KvFormat::Int8, vram)).unwrap();
let g = QsaGeometry::new(e.ctx_per_slot as usize).unwrap();
(e, g)
@@ -45,10 +36,7 @@ fn two_slots_of_256k_size_each_slot_like_the_default_without_scaling() {
assert_eq!(e.total_cells, 524_288);
assert_eq!(g, QsaGeometry::TRAINED, "per-slot buffers do not grow");
assert_eq!(e.rope_table_rows, TRAINED_CELLS as u64);
assert_eq!(
e.rope_table_bytes,
g.rope_table_bytes(ROPE_N_ROT).unwrap() as u64
);
assert_eq!(e.rope_table_bytes, g.rope_table_bytes(ROPE_N_ROT).unwrap() as u64);
}
#[test]
@@ -63,22 +51,13 @@ fn one_slot_of_512k_with_yarn_2_scales_every_buffer_formula() {
assert_eq!(g.page_table_bytes(), 2 * t.page_table_bytes());
assert_eq!(g.pooled_rows(), 2 * t.pages() + 1);
assert_eq!(g.max_blocks(), 2 * t.pages() + 2);
assert_eq!(
g.host_payload_bytes().unwrap(),
2 * t.host_payload_bytes().unwrap()
);
assert_eq!(
g.mapped_host_bytes().unwrap(),
2 * t.host_payload_bytes().unwrap() + 1024
);
assert_eq!(g.host_payload_bytes().unwrap(), 2 * t.host_payload_bytes().unwrap());
assert_eq!(g.mapped_host_bytes().unwrap(), 2 * t.host_payload_bytes().unwrap() + 1024);
for (a, b) in g.stage_runs().unwrap().iter().zip(t.stage_runs().unwrap()) {
assert_eq!(*a, 2 * b);
}
assert_eq!(g.canonical_metadata_bytes().unwrap(), 131_072 * 160 + 4096);
assert_eq!(
e.rope_table_bytes,
g.rope_table_bytes(ROPE_N_ROT).unwrap() as u64
);
assert_eq!(e.rope_table_bytes, g.rope_table_bytes(ROPE_N_ROT).unwrap() as u64);
assert_eq!(e.rope_table_rows as usize, g.cells());
// the planner and the geometry agree on the total cell count
assert_eq!(e.total_cells as usize, g.cells());
@@ -97,13 +76,7 @@ fn charter_profiles_all_resolve_and_total_at_most_512k_cells() {
#[test]
fn planner_refusals() {
// KV does not close on the default 5.943 GB pool
let small = resolve_context(&ContextRequest::new(
1,
524_288,
KvFormat::Int8,
5_943_000_000,
))
.unwrap_err();
let small = resolve_context(&ContextRequest::new(1, 524_288, KvFormat::Int8, 5_943_000_000)).unwrap_err();
assert!(small.is_planner_rejection());
// two slots of 512K are past the charter and past the supported bound
assert!(matches!(
@@ -126,10 +99,7 @@ fn boundary_positions_262143_262144_524287_524288() {
// `admits_end(n)` is "n tokens fit": the last valid position is n - 1
assert!(t.admits_end(262_143 + 1));
assert!(!t.admits_end(262_144 + 1));
assert!(
m.admits_end(262_144 + 1),
"262144 is a valid position at 512K"
);
assert!(m.admits_end(262_144 + 1), "262144 is a valid position at 512K");
assert!(m.admits_end(524_287 + 1));
assert!(!m.admits_end(524_288 + 1));
@@ -138,13 +108,7 @@ fn boundary_positions_262143_262144_524287_524288() {
let scaled = build_rope_table(ROPE_N_ROT, &e.rope, MAX_CELLS).unwrap();
assert_eq!(scaled.n_pos, MAX_CELLS);
for pos in [262_143usize, 262_144, 524_287] {
assert!(
scaled
.row_cos(pos)
.iter()
.chain(scaled.row_sin(pos))
.all(|v| v.is_finite())
);
assert!(scaled.row_cos(pos).iter().chain(scaled.row_sin(pos)).all(|v| v.is_finite()));
}
let (d, _) = geometry_of(1, 262_144, 32 * GIB);
let plain = build_rope_table(ROPE_N_ROT, &d.rope, TRAINED_CELLS).unwrap();
+14 -58
View File
@@ -12,12 +12,10 @@
#![allow(clippy::too_many_lines)]
use leleka_context::memory_plan::{
Costs, Geometry, KvFormat, KvShapes, PlanError, cli_pool, kv_pool_bytes, make_plan,
make_plan_with_format, state_bytes,
};
use leleka_context::rope_scaling::{
RopeScaling, RopeScalingType, fill_rope_table, rope_scaled_angle,
Costs, Geometry, KvFormat, KvShapes, PlanError, cli_pool, kv_pool_bytes, make_plan, make_plan_with_format,
state_bytes,
};
use leleka_context::rope_scaling::{RopeScaling, RopeScalingType, fill_rope_table, rope_scaled_angle};
use serde_json::Value;
const ROPE_JSON: &str = include_str!("rope_plan_golden/rope_golden.json");
@@ -41,11 +39,7 @@ fn ulp_diff(a: f32, b: f32) -> u32 {
}
let map = |x: f32| {
let u = x.to_bits() as i64;
if u >= 0x8000_0000 {
0x8000_0000 - (u & 0x7fff_ffff)
} else {
u + 0x8000_0000
}
if u >= 0x8000_0000 { 0x8000_0000 - (u & 0x7fff_ffff) } else { u + 0x8000_0000 }
};
(map(a) - map(b)).unsigned_abs() as u32
}
@@ -107,18 +101,11 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) {
let name = c["name"].as_str().unwrap();
// validity message, exactly
let want = c["invalid"].as_str();
assert_eq!(
sc.validate().err().map(|e| e.reason()),
want,
"{name}: validity"
);
assert_eq!(sc.validate().err().map(|e| e.reason()), want, "{name}: validity");
// scalar resolutions: libm log is the only dependency
let tol = if EXACT { 0.0 } else { 4.0 * f64::EPSILON };
let near = |a: f64, b: f64| (a - b).abs() <= tol * b.abs().max(1.0);
assert!(
near(sc.freq_scale(), bits64(&c["freq_scale"])),
"{name}: freq_scale"
);
assert!(near(sc.freq_scale(), bits64(&c["freq_scale"])), "{name}: freq_scale");
if want.is_none() || sc.freq_scale().is_finite() {
assert!(near(sc.mscale(), bits64(&c["mscale"])), "{name}: mscale");
}
@@ -126,18 +113,11 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) {
for k in 0..2 {
let want = bits64(&c["corr_dims"][k]);
// a NaN from log(<0) of an invalid config: any NaN matches (payload/sign are libm detail)
assert!(
cd[k].to_bits() == want.to_bits() || (cd[k].is_nan() && want.is_nan()),
"{name}: corr_dims[{k}]"
);
assert!(cd[k].to_bits() == want.to_bits() || (cd[k].is_nan() && want.is_nan()), "{name}: corr_dims[{k}]");
}
let a = sc.kernel_args(n_rot);
let w = &c["kernel_args"];
assert_eq!(
a.freq_scale.to_bits(),
bits32(&w["freq_scale"]).to_bits(),
"{name}: args.freq_scale"
);
assert_eq!(a.freq_scale.to_bits(), bits32(&w["freq_scale"]).to_bits(), "{name}: args.freq_scale");
assert!(
same_f32(a.corr_low, bits32(&w["corr_low"])),
"{name}: args.corr_low: {:#010x} vs {:#010x}",
@@ -150,16 +130,8 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) {
a.corr_high.to_bits(),
bits32(&w["corr_high"]).to_bits()
);
assert_eq!(
a.ext_factor.to_bits(),
bits32(&w["ext_factor"]).to_bits(),
"{name}: args.ext_factor"
);
assert_eq!(
a.attn_factor.to_bits(),
bits32(&w["attn_factor"]).to_bits(),
"{name}: args.attn_factor"
);
assert_eq!(a.ext_factor.to_bits(), bits32(&w["ext_factor"]).to_bits(), "{name}: args.ext_factor");
assert_eq!(a.attn_factor.to_bits(), bits32(&w["attn_factor"]).to_bits(), "{name}: args.attn_factor");
// analytic float32 path
for s in c["analytic"].as_array().unwrap() {
let (co, si) = rope_scaled_angle(
@@ -198,18 +170,8 @@ fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) {
if p >= first && p < first + CHUNK {
let r = p - first;
for i in 0..half {
assert_close(
&format!("{name}: row {p} cos[{i}]"),
cbuf[r * half + i],
bits32(&s["cos"][i]),
1,
);
assert_close(
&format!("{name}: row {p} sin[{i}]"),
sbuf[r * half + i],
bits32(&s["sin"][i]),
1,
);
assert_close(&format!("{name}: row {p} cos[{i}]"), cbuf[r * half + i], bits32(&s["cos"][i]), 1);
assert_close(&format!("{name}: row {p} sin[{i}]"), sbuf[r * half + i], bits32(&s["sin"][i]), 1);
}
}
}
@@ -234,10 +196,7 @@ fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) {
}
fn run_case(name: &str) {
let c = cases()
.into_iter()
.find(|c| c["name"] == name)
.expect("case in fixture");
let c = cases().into_iter().find(|c| c["name"] == name).expect("case in fixture");
let sc = config_of(&c);
let n_rot = c["n_rot"].as_u64().unwrap() as usize;
check_scalars(&c, &sc, n_rot as i32);
@@ -314,10 +273,7 @@ fn interpret_cli(args: &[String]) -> Option<(i32, String, String)> {
Some(match make_plan(ctx, &g, &costs, pool) {
Ok(p) => {
// the format-generic path with INT8 must be the same plan
assert_eq!(
make_plan_with_format(ctx, &g, KvFormat::Int8, &costs, pool).unwrap(),
p
);
assert_eq!(make_plan_with_format(ctx, &g, KvFormat::Int8, &costs, pool).unwrap(), p);
(0, p.to_text(), String::new())
}
Err(e @ PlanError::DoesNotClose(_)) => (1, String::new(), format!("strata-plan: {e}\n")),
@@ -3,13 +3,9 @@
#[allow(unused_imports)]
use super::*;
#[test]
fn every_fixture_case_has_a_test() {
let names: Vec<String> = cases()
.iter()
.map(|c| c["name"].as_str().unwrap().to_owned())
.collect();
let names: Vec<String> = cases().iter().map(|c| c["name"].as_str().unwrap().to_owned()).collect();
assert_eq!(names.len(), 25);
}
@@ -20,10 +16,7 @@ fn yarn_is_observably_different_from_none() {
let find = |n: &str| cs.iter().find(|c| c["name"] == n).unwrap().clone();
let (a, b) = (find("none_default"), find("yarn_2"));
assert_ne!(a["tables"][1]["cos_fnv1a64"], b["tables"][1]["cos_fnv1a64"]);
assert_ne!(
find("linear_2")["tables"][1]["cos_fnv1a64"],
b["tables"][1]["cos_fnv1a64"]
);
assert_ne!(find("linear_2")["tables"][1]["cos_fnv1a64"], b["tables"][1]["cos_fnv1a64"]);
// yarn with ext_factor 0 and a non-unit mscale path differs from linear only by the log term being off
assert_eq!(find("yarn_ext0")["mscale"], find("linear_2")["mscale"]);
}
@@ -31,39 +24,25 @@ fn yarn_is_observably_different_from_none() {
#[test]
fn strata_plan_cli_output_is_reproduced_exactly() {
let root: Value = serde_json::from_str(PLAN_JSON).unwrap();
assert_eq!(
root["state_bytes_default"].as_u64().unwrap(),
state_bytes(&Geometry::default()).unwrap()
);
assert_eq!(root["state_bytes_default"].as_u64().unwrap(), state_bytes(&Geometry::default()).unwrap());
let mut compared = 0;
let mut closed = 0;
let mut refused = 0;
for run in root["cli"].as_array().unwrap() {
let args: Vec<String> = run["args"]
.as_array()
.unwrap()
.iter()
.map(|a| a.as_str().unwrap().to_owned())
.collect();
let args: Vec<String> =
run["args"].as_array().unwrap().iter().map(|a| a.as_str().unwrap().to_owned()).collect();
let Some((exit, out, err)) = interpret_cli(&args) else {
assert!(matches!(run["exit"].as_i64().unwrap(), 0 | 2), "{args:?}");
continue;
};
assert_eq!(
exit as i64,
run["exit"].as_i64().unwrap(),
"{args:?}: exit code"
);
assert_eq!(exit as i64, run["exit"].as_i64().unwrap(), "{args:?}: exit code");
assert_eq!(out, run["stdout"].as_str().unwrap(), "{args:?}: stdout");
assert_eq!(err, run["stderr"].as_str().unwrap(), "{args:?}: stderr");
compared += 1;
if exit == 0 { closed += 1 } else { refused += 1 }
}
// the table must exercise both outcomes, or the comparison is vacuous
assert!(
compared >= 60 && closed >= 30 && refused >= 8,
"{compared} {closed} {refused}"
);
assert!(compared >= 60 && closed >= 30 && refused >= 8, "{compared} {closed} {refused}");
}
#[test]
+15 -56
View File
@@ -16,11 +16,7 @@ fn model(name: &Value) -> &'static policy::Model {
}
fn same(got: f64, want: &Value, what: &str) {
assert_eq!(
got.to_bits(),
want.as_f64().unwrap().to_bits(),
"{what}: {got} vs {want}"
);
assert_eq!(got.to_bits(), want.as_f64().unwrap().to_bits(), "{what}: {got} vs {want}");
}
#[test]
@@ -28,20 +24,11 @@ fn model_table_and_contexts_are_setup_pys() {
let g = golden();
for (name, row) in g["models"].as_object().unwrap() {
let m = policy::model(name).unwrap_or_else(|| panic!("{name} missing"));
assert_eq!(
u64::from(m.ram_gb),
row["ram_gb"].as_u64().unwrap(),
"{name}"
);
assert_eq!(u64::from(m.ram_gb), row["ram_gb"].as_u64().unwrap(), "{name}");
same(m.arena_gb, &row["arena_gb"], name);
}
assert_eq!(g["models"].as_object().unwrap().len(), policy::MODELS.len());
let contexts: Vec<u64> = g["contexts"]
.as_array()
.unwrap()
.iter()
.map(|c| c.as_u64().unwrap())
.collect();
let contexts: Vec<u64> = g["contexts"].as_array().unwrap().iter().map(|c| c.as_u64().unwrap()).collect();
assert_eq!(contexts, policy::CONTEXTS);
}
@@ -50,10 +37,7 @@ fn derived_factor_and_resolve_rope_match() {
let g = golden();
for row in g["derived_factor"].as_array().unwrap() {
same(
derived_factor(
row["ctx"].as_u64().unwrap(),
row["trained"].as_u64().unwrap(),
),
derived_factor(row["ctx"].as_u64().unwrap(), row["trained"].as_u64().unwrap()),
&row["result"],
"derived_factor",
);
@@ -68,12 +52,8 @@ fn derived_factor_and_resolve_rope_match() {
let rows = g["resolve_rope"].as_array().unwrap();
assert!(rows.len() > 300);
for row in rows {
let got = setup_resolve_rope(
row["ctx"].as_u64().unwrap(),
kind(&row["scaling"]),
row["scale"].as_f64(),
262144,
);
let got =
setup_resolve_rope(row["ctx"].as_u64().unwrap(), kind(&row["scaling"]), row["scale"].as_f64(), 262144);
if row.get("error").is_some() {
assert!(got.is_err(), "{row}");
continue;
@@ -94,21 +74,14 @@ fn ram_rules_match() {
let g = golden();
for row in g["ram_ctx"].as_array().unwrap() {
assert_eq!(
policy::ram_ctx(
model(&row["model"]),
row["ram"].as_f64().unwrap(),
row["low_ram"].as_bool().unwrap()
),
policy::ram_ctx(model(&row["model"]), row["ram"].as_f64().unwrap(), row["low_ram"].as_bool().unwrap()),
row["result"].as_u64().unwrap(),
"{row}"
);
}
for row in g["ctx_ram_need"].as_array().unwrap() {
let got = policy::ctx_ram_need(
model(&row["model"]),
row["ctx"].as_u64().unwrap(),
row["low_ram"].as_bool().unwrap(),
);
let got =
policy::ctx_ram_need(model(&row["model"]), row["ctx"].as_u64().unwrap(), row["low_ram"].as_bool().unwrap());
match (got, &row["result"]) {
(None, Value::Null) => {}
(Some(got), want) => same(got, want, &row.to_string()),
@@ -139,27 +112,13 @@ fn low_ram_rules_match() {
let kv = || Kv::parse(row["kv"].as_str().unwrap());
let ctx = || row["ctx"].as_u64().unwrap();
match row["fn"].as_str().unwrap() {
"needed" => assert_eq!(
policy::low_ram_needed(m, f("ram")),
row["result"].as_bool().unwrap(),
"{row}"
),
"fits" => assert_eq!(
policy::low_ram_fits(m, f("ram"), f("vram")),
row["result"].as_bool().unwrap(),
"{row}"
),
"needed" => assert_eq!(policy::low_ram_needed(m, f("ram")), row["result"].as_bool().unwrap(), "{row}"),
"fits" => {
assert_eq!(policy::low_ram_fits(m, f("ram"), f("vram")), row["result"].as_bool().unwrap(), "{row}")
}
"gpu_gb" => {
same(
policy::low_ram_gpu_gb(m, f("vram"), ctx(), kv()),
&row["result"],
&row.to_string(),
);
same(
policy::low_ram_gpu_share(m, f("vram"), ctx(), kv()),
&row["share"],
&row.to_string(),
);
same(policy::low_ram_gpu_gb(m, f("vram"), ctx(), kv()), &row["result"], &row.to_string());
same(policy::low_ram_gpu_share(m, f("vram"), ctx(), kv()), &row["share"], &row.to_string());
}
"resident" => assert_eq!(
policy::low_ram_resident(m, f("ram"), f("vram"), ctx(), kv()),
+3
View File
@@ -0,0 +1,3 @@
# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line.
max_width = 120
use_small_heuristics = "Max"
+3 -15
View File
@@ -16,17 +16,9 @@ pub(crate) struct MappedCopyArguments {
pub(crate) words: i64,
}
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod enabled;
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub(crate) use enabled::AsyncApi;
#[cfg(not(all(
@@ -36,11 +28,7 @@ pub(crate) use enabled::AsyncApi;
)))]
pub(crate) struct AsyncApi;
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub(crate) use enabled::{MappedApi, page_size};
#[cfg(not(all(
feature = "cuda-driver",
+26 -89
View File
@@ -35,20 +35,14 @@ pub(crate) struct AsyncApi {
zero: Zero,
}
fn check(operation: &'static str, code: c_int) -> Result<()> {
if code == 0 {
Ok(())
} else {
Err(Error::Driver { operation, code })
}
if code == 0 { Ok(()) } else { Err(Error::Driver { operation, code }) }
}
macro_rules! symbol {
($library:ident, $name:literal, $ty:ty) => {{
// SAFETY: fixed C name and live dlopen owner, never caller-selected.
let address = unsafe { libc::dlsym($library.0, $name.as_ptr()) };
if address.is_null() {
return Err(Error::MissingSymbol(
$name.to_str().expect("ASCII ABI name"),
));
return Err(Error::MissingSymbol($name.to_str().expect("ASCII ABI name")));
}
// SAFETY: exact Linux64 fixed function signature for this symbol.
unsafe { std::mem::transmute::<*mut c_void, $ty>(address) }
@@ -58,9 +52,7 @@ impl AsyncApi {
pub(crate) fn load() -> Result<Self> {
// SAFETY: fixed library name/flags; a second owned reference leaves
// the original synchronous loader and its symbol set untouched.
let handle = unsafe {
libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL)
};
let handle = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
if handle.is_null() {
return Err(Error::LibraryUnavailable);
}
@@ -84,9 +76,7 @@ impl AsyncApi {
pub(crate) fn create_stream(&self) -> Result<Stream> {
let mut handle = std::ptr::null_mut();
// SAFETY: valid out pointer, NON_BLOCKING=1, current owning Context.
check("cuStreamCreate", unsafe {
(self.stream_create)(&mut handle, 1)
})?;
check("cuStreamCreate", unsafe { (self.stream_create)(&mut handle, 1) })?;
if handle.is_null() {
return Err(Error::InvalidDriverValue("cuStreamCreate"));
}
@@ -96,9 +86,7 @@ impl AsyncApi {
pub(crate) fn create_event(&self) -> Result<Event> {
let mut handle = std::ptr::null_mut();
// SAFETY: valid out pointer, DISABLE_TIMING=2, current Context.
check("cuEventCreate", unsafe {
(self.event_create)(&mut handle, 2)
})?;
check("cuEventCreate", unsafe { (self.event_create)(&mut handle, 2) })?;
if handle.is_null() {
return Err(Error::InvalidDriverValue("cuEventCreate"));
}
@@ -107,82 +95,57 @@ impl AsyncApi {
pub(crate) fn register(&self, bytes: &mut [u8]) -> Result<()> {
// SAFETY: nonempty whole uniquely owned initialized allocation,
// no resize/mutation/free until unregister after completion.
check("cuMemHostRegister_v2", unsafe {
(self.register)(bytes.as_mut_ptr().cast(), bytes.len(), 0)
})
check("cuMemHostRegister_v2", unsafe { (self.register)(bytes.as_mut_ptr().cast(), bytes.len(), 0) })
}
pub(crate) fn unregister(&self, bytes: &mut [u8]) -> Result<()> {
// SAFETY: identical registered base retained by private owner.
check("cuMemHostUnregister", unsafe {
(self.unregister)(bytes.as_mut_ptr().cast())
})
check("cuMemHostUnregister", unsafe { (self.unregister)(bytes.as_mut_ptr().cast()) })
}
pub(crate) fn copy(&self, destination: u64, bytes: &[u8], stream: Stream) -> Result<()> {
// SAFETY: whole actual admitted allocation, registered source and
// stream retained until genuine recorded event completion.
check("cuMemcpyHtoDAsync_v2", unsafe {
(self.copy)(
destination,
bytes.as_ptr().cast(),
bytes.len(),
stream.0 as *mut c_void,
)
(self.copy)(destination, bytes.as_ptr().cast(), bytes.len(), stream.0 as *mut c_void)
})
}
pub(crate) fn synchronize_stream(&self, stream: Stream) -> Result<()> {
// SAFETY: the cache owns every source/destination until this fence;
// Stream(0) is CUDA's actual legacy default stream, not a fake owner.
check("cuStreamSynchronize", unsafe {
(self.stream_wait)(stream.0 as *mut c_void)
})
check("cuStreamSynchronize", unsafe { (self.stream_wait)(stream.0 as *mut c_void) })
}
pub(crate) fn zero(&self, destination: u64, bytes: usize) -> Result<()> {
// SAFETY: the caller validates the genuine whole cache allocation.
check("cuMemsetD8_v2", unsafe {
(self.zero)(destination, 0, bytes)
})
check("cuMemsetD8_v2", unsafe { (self.zero)(destination, 0, bytes) })
}
pub(crate) fn record(&self, event: Event, stream: Stream) -> Result<()> {
// SAFETY: live owned handles in their actual current Context.
check("cuEventRecord", unsafe {
(self.event_record)(event.0 as *mut c_void, stream.0 as *mut c_void)
})
check("cuEventRecord", unsafe { (self.event_record)(event.0 as *mut c_void, stream.0 as *mut c_void) })
}
pub(crate) fn query(&self, event: Event) -> Result<bool> {
// SAFETY: event was genuinely recorded after the complete batch.
match unsafe { (self.event_query)(event.0 as *mut c_void) } {
0 => Ok(true),
600 => Ok(false), // CUDA_ERROR_NOT_READY, never publication.
code => Err(Error::Driver {
operation: "cuEventQuery",
code,
}),
code => Err(Error::Driver { operation: "cuEventQuery", code }),
}
}
pub(crate) fn wait(&self, event: Event) -> Result<()> {
// SAFETY: event and registered sources remain live for this wait.
check("cuEventSynchronize", unsafe {
(self.event_wait)(event.0 as *mut c_void)
})
check("cuEventSynchronize", unsafe { (self.event_wait)(event.0 as *mut c_void) })
}
pub(crate) fn destroy_event(&self, event: Event) -> Result<()> {
// SAFETY: only called before enqueue or after proven completion.
check("cuEventDestroy_v2", unsafe {
(self.event_destroy)(event.0 as *mut c_void)
})
check("cuEventDestroy_v2", unsafe { (self.event_destroy)(event.0 as *mut c_void) })
}
pub(crate) fn destroy_stream(&self, stream: Stream) -> Result<()> {
crate::compute_drain::unregister(stream.0);
// SAFETY: only called before enqueue or after proven completion.
check("cuStreamDestroy_v2", unsafe {
(self.stream_destroy)(stream.0 as *mut c_void)
})
check("cuStreamDestroy_v2", unsafe { (self.stream_destroy)(stream.0 as *mut c_void) })
}
}
type Alias = unsafe extern "C" fn(*mut u64, *mut c_void, c_uint) -> c_int;
type LoadModule = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> c_int;
type GetFunction =
unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> c_int;
type GetFunction = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> c_int;
type Launch = unsafe extern "C" fn(
*mut c_void,
c_uint,
@@ -208,9 +171,7 @@ impl MappedApi {
pub(crate) fn load() -> Result<Self> {
let image = include_bytes!("../../kernels/mapped_expert_copy.ptx");
if image.starts_with(b"UNSEALED") || image.last() != Some(&0) {
return Err(Error::InvalidDriverValue(
"mapped expert copy asset unsealed",
));
return Err(Error::InvalidDriverValue("mapped expert copy asset unsealed"));
}
let inner = AsyncApi::load()?;
let library = &inner._library;
@@ -221,33 +182,20 @@ impl MappedApi {
let launch = symbol!(library, c"cuLaunchKernel", Launch);
let mut module = std::ptr::null_mut();
// SAFETY: fixed sealed terminated image; current actual Context.
check("cuModuleLoadData", unsafe {
load(&mut module, crate::arch_ptx::image(image).as_ptr().cast())
})?;
check("cuModuleLoadData", unsafe { load(&mut module, crate::arch_ptx::image(image).as_ptr().cast()) })?;
if module.is_null() {
return Err(Error::InvalidDriverValue("mapped module"));
}
let mut function = std::ptr::null_mut();
// SAFETY: real owned module and fixed original byte-only symbol.
let result = check("cuModuleGetFunction", unsafe {
get(&mut function, module, c"fetch_blobs_kernel".as_ptr())
});
let result =
check("cuModuleGetFunction", unsafe { get(&mut function, module, c"fetch_blobs_kernel".as_ptr()) });
if result.is_err() || function.is_null() {
// SAFETY: no launch occurred; release actual partial module.
let cleanup = check("cuModuleUnload", unsafe { unload(module) });
return crate::combine(
result.and_then(|()| Err(Error::InvalidDriverValue("mapped function"))),
cleanup,
);
return crate::combine(result.and_then(|()| Err(Error::InvalidDriverValue("mapped function"))), cleanup);
}
Ok(Self {
inner,
alias,
module,
function,
unload,
launch,
})
Ok(Self { inner, alias, module, function, unload, launch })
}
pub(crate) fn register_bank(&self, bytes: &[u8]) -> Result<()> {
// SAFETY: immutable retained actual initialized Box; DEVICEMAP=2.
@@ -261,28 +209,21 @@ impl MappedApi {
check("cuMemHostGetDevicePointer_v2", unsafe {
(self.alias)(&mut address, bytes.as_ptr().cast_mut().cast(), 0)
})?;
if address == 0
|| !address.is_multiple_of(16)
|| address.checked_add(bytes.len() as u64).is_none()
{
if address == 0 || !address.is_multiple_of(16) || address.checked_add(bytes.len() as u64).is_none() {
return Err(Error::InvalidDriverValue("mapped alias"));
}
Ok(address)
}
pub(crate) fn unregister_bank(&self, bytes: &[u8]) -> Result<()> {
// SAFETY: identical live registered base; all consumers drained.
check("cuMemHostUnregister", unsafe {
(self.inner.unregister)(bytes.as_ptr().cast_mut().cast())
})
check("cuMemHostUnregister", unsafe { (self.inner.unregister)(bytes.as_ptr().cast_mut().cast()) })
}
/// Page-lock `len` bytes at page-aligned `start`, inside a read-only file mapping a bank retains
/// (CU_MEMHOSTREGISTER_READ_ONLY = 8; no device mapping): the pages are read in and stay resident, and
/// copies from them are DMA instead of staged.
pub(crate) fn register_read_only(&self, start: usize, len: usize) -> Result<()> {
// SAFETY: the caller passes a page range inside a live mapping it retains until `unregister_at`.
check("cuMemHostRegister_v2", unsafe {
(self.inner.register)(start as *mut c_void, len, 8)
})
check("cuMemHostRegister_v2", unsafe { (self.inner.register)(start as *mut c_void, len, 8) })
}
pub(crate) fn unregister_at(&self, start: usize) -> Result<()> {
// SAFETY: identical live registered base from `register_read_only`; all consumers drained.
@@ -294,11 +235,7 @@ impl MappedApi {
// SAFETY: the caller passes a live page-aligned allocation it retains until `unregister_at`.
check("cuMemHostRegister_v2", unsafe { (self.inner.register)(start as *mut c_void, len, 0) })
}
pub(crate) fn copy_kernel(
&self,
actual: &mut MappedCopyArguments,
stream: Stream,
) -> Result<()> {
pub(crate) fn copy_kernel(&self, actual: &mut MappedCopyArguments, stream: Stream) -> Result<()> {
let mut args = [
(&mut actual.source as *mut u64).cast(),
(&mut actual.count as *mut u64).cast(),
+30 -82
View File
@@ -24,8 +24,7 @@ mod imp {
pub(super) fn current_cc() -> Option<(i32, i32)> {
// SAFETY: fixed library name; RTLD_NOLOAD only returns a handle if the caller's own Api already loaded it, and
// the extra reference is dropped below.
let handle =
unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_NOLOAD) };
let handle = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_NOLOAD) };
if handle.is_null() {
return None;
}
@@ -37,10 +36,7 @@ mod imp {
let (mut major, mut minor) = (0, 0);
// SAFETY: valid writable outputs; a current context is the caller's precondition for a module load.
unsafe {
if get(&mut device) != 0
|| attr(&mut major, 75, device) != 0
|| attr(&mut minor, 76, device) != 0
{
if get(&mut device) != 0 || attr(&mut major, 75, device) != 0 || attr(&mut minor, 76, device) != 0 {
return None;
}
}
@@ -68,10 +64,7 @@ mod imp {
}
}
#[cfg(all(
feature = "sm86",
not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))
))]
#[cfg(all(feature = "sm86", not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))))]
mod imp {
pub(super) fn current_cc() -> Option<(i32, i32)> {
None
@@ -96,10 +89,7 @@ mod tests {
let path = entry.unwrap().path();
if path.extension().and_then(|e| e.to_str()) == Some("ptx") {
let bytes = std::fs::read(&path).unwrap();
out.push((
path.file_name().unwrap().to_string_lossy().into_owned(),
bytes,
));
out.push((path.file_name().unwrap().to_string_lossy().into_owned(), bytes));
}
}
}
@@ -121,10 +111,7 @@ mod tests {
let tail = &text[at + ".entry ".len()..];
let open = tail.find('(').unwrap();
let close = tail.find(')').unwrap();
out.insert(
tail[..open].to_string(),
tail[open..close].matches(".param").count(),
);
out.insert(tail[..open].to_string(), tail[open..close].matches(".param").count());
}
out
}
@@ -132,12 +119,7 @@ mod tests {
#[test]
fn table_is_sorted_unique_and_every_companion_passes_its_pin() {
for pair in COMPANIONS.windows(2) {
assert!(
pair[0].key < pair[1].key,
"{} / {}",
pair[0].name,
pair[1].name
);
assert!(pair[0].key < pair[1].key, "{} / {}", pair[0].name, pair[1].name);
}
for c in COMPANIONS {
let pinned = crate::sealed_ptx::pinned(c.ptx, Some((c.len, c.sha)));
@@ -153,23 +135,14 @@ mod tests {
.collect();
for c in COMPANIONS {
let originals: Vec<_> = sealed.iter().filter(|(_, key, _)| *key == c.key).collect();
assert!(
!originals.is_empty(),
"{}: no sealed sm_120 file has the table key",
c.name
);
assert!(!originals.is_empty(), "{}: no sealed sm_120 file has the table key", c.name);
let text = std::str::from_utf8(body(c.ptx)).unwrap();
let targets: Vec<_> = text.lines().filter(|l| l.starts_with(".target")).collect();
assert_eq!(targets, [".target sm_86"], "{}", c.name);
assert!(text.lines().any(|l| l == ".address_size 64"), "{}", c.name);
assert!(!text.contains("UNSEALED"), "{}", c.name);
for (name, _, original) in originals {
assert_eq!(
entries(body(original)),
entries(body(c.ptx)),
"{} vs {name}",
c.name
);
assert_eq!(entries(body(original)), entries(body(c.ptx)), "{} vs {name}", c.name);
}
}
}
@@ -177,14 +150,9 @@ mod tests {
#[test]
fn every_sealed_sm120_file_has_a_companion_or_a_documented_reason() {
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(src().join("ptx-sm86/MANIFEST.json")).unwrap())
.unwrap();
let not_built: Vec<&str> = manifest["not_built"]
.as_array()
.unwrap()
.iter()
.map(|v| v["name"].as_str().unwrap())
.collect();
serde_json::from_slice(&std::fs::read(src().join("ptx-sm86/MANIFEST.json")).unwrap()).unwrap();
let not_built: Vec<&str> =
manifest["not_built"].as_array().unwrap().iter().map(|v| v["name"].as_str().unwrap()).collect();
let portable: Vec<&str> = manifest["portable_no_companion_needed"]
.as_array()
.unwrap()
@@ -211,19 +179,13 @@ mod tests {
);
}
// the placeholders have no companion by design: they cannot be loaded on any device until sealed
assert!(
placeholders
.iter()
.all(|p| !COMPANIONS.iter().any(|c| c.name == *p))
);
assert!(placeholders.iter().all(|p| !COMPANIONS.iter().any(|c| c.name == *p)));
}
#[test]
fn lookup_swaps_only_sealed_images_and_only_to_a_pinned_companion() {
let (name, bytes) = sealed_files()
.into_iter()
.find(|(n, _)| n == "device_poison.ptx")
.expect("device_poison.ptx");
let (name, bytes) =
sealed_files().into_iter().find(|(n, _)| n == "device_poison.ptx").expect("device_poison.ptx");
let mut stored = body(&bytes).to_vec();
stored.push(0);
let swapped = companion_for(&stored).unwrap_or_else(|| panic!("{name}: no companion"));
@@ -243,53 +205,39 @@ mod tests {
#[test]
fn capability_gates() {
assert!(
cc_major_ok(12)
&& cc_major_ok(8)
&& cc_major_ok(9)
&& !cc_major_ok(7)
&& !cc_major_ok(13)
);
assert!(
mmq_cc_ok(12, 0)
&& mmq_cc_ok(8, 6)
&& mmq_cc_ok(8, 9)
&& !mmq_cc_ok(8, 0)
&& !mmq_cc_ok(12, 1)
);
assert!(
companion_cc(8, 6) && companion_cc(9, 0) && !companion_cc(8, 0) && !companion_cc(12, 0)
);
assert!(cc_major_ok(12) && cc_major_ok(8) && cc_major_ok(9) && !cc_major_ok(7) && !cc_major_ok(13));
assert!(mmq_cc_ok(12, 0) && mmq_cc_ok(8, 6) && mmq_cc_ok(8, 9) && !mmq_cc_ok(8, 0) && !mmq_cc_ok(12, 1));
assert!(companion_cc(8, 6) && companion_cc(9, 0) && !companion_cc(8, 0) && !companion_cc(12, 0));
}
}
mod stream_k_off_fn;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::stream_k_off;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::forced_sms;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::chunk_drain;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::latch_stream_k_policy;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::cc_major_ok;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::mmq_cc_ok;
pub(crate) use stream_k_off_fn::chunk_drain;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::companion_cc;
#[cfg(feature = "sm86")]
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::loadable;
#[cfg(feature = "sm86")]
pub(crate) use stream_k_off_fn::companion_for;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::native_sm120;
pub(crate) use stream_k_off_fn::forced_sms;
#[cfg(not(feature = "sm86"))]
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::image;
#[cfg(feature = "sm86")]
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::image;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::latch_stream_k_policy;
#[cfg(feature = "sm86")]
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::companion_for;
pub(crate) use stream_k_off_fn::loadable;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::mmq_cc_ok;
#[cfg(feature = "sm86")]
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::native_sm120;
#[allow(unused_imports)]
pub(crate) use stream_k_off_fn::stream_k_off;
@@ -18,7 +18,8 @@ pub(crate) fn stream_k_off() -> bool {
static PRESENT: [AtomicBool; 2] = [const { AtomicBool::new(false) }; 2];
let fixed = *FIXED.get_or_init(|| std::env::var_os("LELEKA_MMQ_NO_STREAMK").is_some_and(|v| v != "0"));
let paths = PATHS.get_or_init(|| {
["LELEKA_MMQ_NO_STREAMK_FILE", "LELEKA_MMQ_STREAMK_FILE"].map(|name| std::env::var_os(name).map(std::path::PathBuf::from))
["LELEKA_MMQ_NO_STREAMK_FILE", "LELEKA_MMQ_STREAMK_FILE"]
.map(|name| std::env::var_os(name).map(std::path::PathBuf::from))
});
if paths.iter().any(Option::is_some) {
let now = CHECKED.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64;
@@ -43,7 +44,11 @@ pub(crate) fn stream_k_off() -> bool {
/// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_FORCE_SMS=N` makes the MMQ and MTP-prefill owners plan their stream-K grids (and size
/// their fixup workspaces) for N SMs instead of the device's count, e.g. 48 on a 5090 to run the laptop's decomposition there.
pub(crate) fn forced_sms(real: u32) -> u32 {
std::env::var("LELEKA_FORCE_SMS").ok().and_then(|v| v.parse::<u32>().ok()).filter(|n| (1..=4096).contains(n)).unwrap_or(real)
std::env::var("LELEKA_FORCE_SMS")
.ok()
.and_then(|v| v.parse::<u32>().ok())
.filter(|n| (1..=4096).contains(n))
.unwrap_or(real)
}
/// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_CHUNK_DRAIN=1`, or the existence of the file named by `LELEKA_CHUNK_DRAIN_FILE`
@@ -59,7 +64,9 @@ pub(crate) fn chunk_drain() -> bool {
if *FIXED.get_or_init(|| std::env::var_os("LELEKA_CHUNK_DRAIN").is_some_and(|v| v != "0")) {
return true;
}
let Some(path) = PATH.get_or_init(|| std::env::var_os("LELEKA_CHUNK_DRAIN_FILE").map(std::path::PathBuf::from)).as_ref() else {
let Some(path) =
PATH.get_or_init(|| std::env::var_os("LELEKA_CHUNK_DRAIN_FILE").map(std::path::PathBuf::from)).as_ref()
else {
return false;
};
let now = START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64;
@@ -152,11 +159,7 @@ pub(crate) fn companion_for(ptx: &[u8]) -> Option<&'static [u8]> {
let c = &table[at];
let pinned = crate::sealed_ptx::pinned(c.ptx, Some((c.len, c.sha)));
if pinned.is_some() && std::env::var_os("LELEKA_SM86_TRACE").is_some() {
eprintln!(
"sm86: companion {} ({} bytes) replaces the sealed sm_120 image",
c.name,
c.len - 1
);
eprintln!("sm86: companion {} ({} bytes) replaces the sealed sm_120 image", c.name, c.len - 1);
}
pinned
}
@@ -2,12 +2,7 @@
use super::*;
use std::cell::Cell;
fn checked(
asset: &Asset,
operation: Operation,
memo: &OnceLock<PtxProof>,
calls: &Cell<usize>,
) -> Result<()> {
fn checked(asset: &Asset, operation: Operation, memo: &OnceLock<PtxProof>, calls: &Cell<usize>) -> Result<()> {
asset.validate_with_memo(operation, memo, |ptx| {
calls.set(calls.get() + 1);
inspect_ptx(ptx) // The real ASCII/NUL/length/SHA validator, not a stub.
@@ -34,12 +29,7 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() {
let other: &'static [u8] = Box::leak(base.ptx.to_vec().into_boxed_slice());
assert!(!std::ptr::eq(other, base.ptx));
assert_eq!(other, base.ptx);
let distinct = Asset {
operation,
ptx: other,
receipt: base.receipt,
pin: base.pin,
};
let distinct = Asset { operation, ptx: other, receipt: base.receipt, pin: base.pin };
assert_eq!(checked(&distinct, operation, &memo, &calls), Ok(()));
assert_eq!(calls.get(), 2);
// A one-slot memo still holds the original allocation. The distinct one
@@ -97,16 +87,8 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() {
}
_ => unreachable!(),
}
assert_eq!(
checked(&asset, request, &memo, &calls),
Err(Error::UnsupportedQwenOperation),
"warm case {case}"
);
assert_eq!(
calls.get(),
3,
"metadata and memo hash refusal must not rescan"
);
assert_eq!(checked(&asset, request, &memo, &calls), Err(Error::UnsupportedQwenOperation), "warm case {case}");
assert_eq!(calls.get(), 3, "metadata and memo hash refusal must not rescan");
assert!(std::ptr::eq(memo.get().unwrap().ptx, base.ptx));
assert_eq!(memo.get().unwrap().digest, base.receipt.ptx_sha256);
}
@@ -118,10 +100,7 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() {
asset.pin = asset.receipt;
let fresh = OnceLock::new();
let count = Cell::new(0);
assert_eq!(
checked(&asset, operation, &fresh, &count),
Err(Error::UnsupportedQwenOperation)
);
assert_eq!(checked(&asset, operation, &fresh, &count), Err(Error::UnsupportedQwenOperation));
assert_eq!(count.get(), 1);
assert!(fresh.get().is_none());
}
@@ -130,10 +109,7 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() {
wrong_hash.pin = wrong_hash.receipt;
let fresh = OnceLock::new();
let count = Cell::new(0);
assert_eq!(
checked(&wrong_hash, operation, &fresh, &count),
Err(Error::UnsupportedQwenOperation)
);
assert_eq!(checked(&wrong_hash, operation, &fresh, &count), Err(Error::UnsupportedQwenOperation));
assert_eq!(count.get(), 1);
assert!(fresh.get().is_none());
// Failure did not reserve/poison the content proof: the first valid asset
+4 -21
View File
@@ -87,10 +87,7 @@ impl Context<'_> {
return Err(Error::ContextMismatch);
}
if destination.bytes != source.len() {
return Err(Error::ShapeMismatch {
expected: destination.bytes,
actual: source.len(),
});
return Err(Error::ShapeMismatch { expected: destination.bytes, actual: source.len() });
}
let handle = destination.handle.ok_or(Error::ContextPoisoned)?;
handle.validate_extent(destination.bytes)?;
@@ -171,14 +168,7 @@ impl<'ctx> PendingOwnedCopy<'ctx> {
for i in 0..self.count {
let (destination, source) = self.pairs[i].as_ref().expect("admitted whole pair");
self.attempted = true;
api.copy(
destination
.handle
.expect("admitted live allocation")
.qwen_address(),
source,
stream,
)?;
api.copy(destination.handle.expect("admitted live allocation").qwen_address(), source, stream)?;
}
api.record(self.event.expect("actual created event"), stream)?;
self.recorded = true;
@@ -209,11 +199,7 @@ impl<'ctx> PendingOwnedCopy<'ctx> {
};
let api = self.api.as_ref().expect("private live ABI");
let event = self.event.expect("actual recorded event");
let observed = if wait {
api.wait(event).map(|()| true)
} else {
api.query(event)
};
let observed = if wait { api.wait(event).map(|()| true) } else { api.query(event) };
let observed = combine(observed, guard.finish());
match observed {
Ok(true) => {
@@ -247,10 +233,7 @@ impl<'ctx> PendingOwnedCopy<'ctx> {
}
self.cleanup_transport()?;
let pairs = std::mem::replace(&mut self.pairs, std::array::from_fn(|_| None));
Ok(CompletedOwnedCopy {
pairs,
count: self.count,
})
Ok(CompletedOwnedCopy { pairs, count: self.count })
}
/// Cancellation/draining discards the unpublished destinations only after
/// genuine completion; first failure is preserved with all cleanup attempts.
+23 -79
View File
@@ -3,45 +3,20 @@ use super::*;
#[test]
fn bounded_host_capacity_admission_has_no_completion_shortcut() {
assert!(matches!(
admit_count_and_capacities(&[], 100),
Err(Error::InvalidSize)
));
assert!(matches!(
admit_count_and_capacities(&[(1, 1); 7], 100),
Err(Error::InvalidSize)
));
assert!(matches!(
admit_count_and_capacities(&[(1, 0)], 100),
Err(Error::InvalidSize)
));
assert!(matches!(
admit_count_and_capacities(&[(0, 0)], 100),
Err(Error::InvalidSize)
));
assert!(matches!(
admit_count_and_capacities(&[(1, usize::MAX), (1, 1)], usize::MAX),
Err(Error::BudgetExceeded)
));
assert!(matches!(
admit_count_and_capacities(&[(10, 16), (10, 16), (10, 16)], 47),
Err(Error::BudgetExceeded)
));
assert!(matches!(admit_count_and_capacities(&[], 100), Err(Error::InvalidSize)));
assert!(matches!(admit_count_and_capacities(&[(1, 1); 7], 100), Err(Error::InvalidSize)));
assert!(matches!(admit_count_and_capacities(&[(1, 0)], 100), Err(Error::InvalidSize)));
assert!(matches!(admit_count_and_capacities(&[(0, 0)], 100), Err(Error::InvalidSize)));
assert!(matches!(admit_count_and_capacities(&[(1, usize::MAX), (1, 1)], usize::MAX), Err(Error::BudgetExceeded)));
assert!(matches!(admit_count_and_capacities(&[(10, 16), (10, 16), (10, 16)], 47), Err(Error::BudgetExceeded)));
assert!(admit_count_and_capacities(&[(10, 16), (10, 16), (10, 16)], 48).is_ok());
}
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
#[test]
#[ignore = "Root-only genuine registered triplet event transport proof"]
fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(),
Ok("yes")
);
assert_eq!(std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(), Ok("yes"));
let driver = crate::Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(16 * 1024 * 1024).unwrap();
@@ -53,26 +28,18 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() {
let sizes = [262_144usize, 524_288, 786_432];
for round in 0..3u32 {
let mut pairs = Vec::new();
pairs
.try_reserve_exact(3)
.map_err(|_| Error::HostAllocation)?;
pairs.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?;
let mut expected = Vec::new();
expected
.try_reserve_exact(3)
.map_err(|_| Error::HostAllocation)?;
expected.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?;
let mut pointers = [0usize; 3];
for (role, bytes) in sizes.into_iter().enumerate() {
let mut source = Vec::new();
source
.try_reserve_exact(bytes)
.map_err(|_| Error::HostAllocation)?;
source.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?;
for i in 0..bytes / 4 {
let word = if round == 2 {
[0, 0x8000_0000, 1, 0x7f80_0000, 0xff80_0000, 0x7fc0_0042][i % 6]
} else {
(i as u32)
.wrapping_mul(0x9e37_79b9)
.wrapping_add(round + role as u32)
(i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round + role as u32)
};
source.extend_from_slice(&word.to_le_bytes());
}
@@ -107,20 +74,14 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() {
if let Some((destination, source)) = pair {
let observed = destination.copy_to_owned(sizes[i]);
if source.as_ptr() as usize != pointers[i] {
completion_error = combine(
completion_error,
Err(Error::InvalidDriverValue("staging ownership")),
);
completion_error =
combine(completion_error, Err(Error::InvalidDriverValue("staging ownership")));
}
match observed {
Ok(bytes) if bytes == expected[i] && source == expected[i] => {
compared += bytes.len()
}
Ok(bytes) if bytes == expected[i] && source == expected[i] => compared += bytes.len(),
Ok(_) => {
completion_error = combine(
completion_error,
Err(Error::InvalidDriverValue("async byte equality")),
)
completion_error =
combine(completion_error, Err(Error::InvalidDriverValue("async byte equality")))
}
Err(error) => completion_error = combine(completion_error, Err(error)),
}
@@ -130,30 +91,20 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() {
completion_error?;
}
// Genuine foreign allocation and exact whole-byte shape admission.
let invalid =
context.copy_owned_batch_async(vec![(foreign.allocate(4096)?, vec![0; 4096])]);
let invalid = context.copy_owned_batch_async(vec![(foreign.allocate(4096)?, vec![0; 4096])]);
if !matches!(invalid, Err(Error::ContextMismatch)) {
return Err(Error::InvalidDriverValue("foreign refusal"));
}
drop(invalid);
refusals += 1;
let invalid =
context.copy_owned_batch_async(vec![(context.allocate(4096)?, vec![0; 4095])]);
if !matches!(
invalid,
Err(Error::ShapeMismatch {
expected: 4096,
actual: 4095
})
) {
let invalid = context.copy_owned_batch_async(vec![(context.allocate(4096)?, vec![0; 4095])]);
if !matches!(invalid, Err(Error::ShapeMismatch { expected: 4096, actual: 4095 })) {
return Err(Error::InvalidDriverValue("extent refusal"));
}
drop(invalid);
refusals += 1;
// Real abandoned pending owner explicitly drains without publication.
context
.copy_owned_batch_async(vec![(context.allocate(262_144)?, vec![7; 262_144])])?
.close()?;
context.copy_owned_batch_async(vec![(context.allocate(262_144)?, vec![7; 262_144])])?.close()?;
Ok(())
})();
let sync = context.synchronize();
@@ -172,18 +123,11 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() {
);
}
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
#[test]
#[ignore = "Root-only: poison while a registered copy is pending must retain, not free"]
fn poison_while_pending_retains_registered_owners_and_preserves_the_primary_error() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(),
Ok("yes")
);
assert_eq!(std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(), Ok("yes"));
let driver = crate::Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(16 * 1024 * 1024).unwrap();
+22 -57
View File
@@ -5,10 +5,7 @@ fn batch_layout(operation: Operation, tokens: usize) -> Result<qwen_ffi::Layout>
if !(1..=64).contains(&tokens)
|| !matches!(
operation,
Operation::Norm
| Operation::LayerGate
| Operation::FinalGate
| Operation::InjectResidual
Operation::Norm | Operation::LayerGate | Operation::FinalGate | Operation::InjectResidual
)
{
return Err(Error::InvalidQwenShape);
@@ -18,15 +15,10 @@ fn batch_layout(operation: Operation, tokens: usize) -> Result<qwen_ffi::Layout>
if operation == Operation::Norm && i == 1 {
continue;
}
layout.bytes[i] = layout.bytes[i]
.checked_mul(tokens)
.ok_or(Error::InvalidQwenShape)?;
layout.bytes[i] = layout.bytes[i].checked_mul(tokens).ok_or(Error::InvalidQwenShape)?;
}
if operation != Operation::Norm {
layout.columns = layout
.columns
.checked_mul(tokens as u32)
.ok_or(Error::InvalidQwenShape)?;
layout.columns = layout.columns.checked_mul(tokens as u32).ok_or(Error::InvalidQwenShape)?;
}
layout.grid_y = tokens as u32;
Ok(layout)
@@ -61,18 +53,9 @@ mod installed {
};
let result = (|| {
Ok([
context
.driver
.api
.qwen_function(module, Operation::LayerGate)?,
context
.driver
.api
.qwen_function(module, Operation::FinalGate)?,
context
.driver
.api
.qwen_function(module, Operation::InjectResidual)?,
context.driver.api.qwen_function(module, Operation::LayerGate)?,
context.driver.api.qwen_function(module, Operation::FinalGate)?,
context.driver.api.qwen_function(module, Operation::InjectResidual)?,
context.driver.api.qwen_function(module, Operation::Norm)?,
])
})();
@@ -92,12 +75,7 @@ mod installed {
context.retain_driver();
return Err(e);
}
Ok(Self {
context,
module: Some(module),
functions,
launch_attempts: std::cell::Cell::new(0),
})
Ok(Self { context, module: Some(module), functions, launch_attempts: std::cell::Cell::new(0) })
}
pub fn inject(
&self,
@@ -107,18 +85,9 @@ mod installed {
inject: &DeviceBuffer<'_>,
candidate: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.run(
Operation::InjectResidual,
tokens,
&[residual, output, inject, candidate],
)
self.run(Operation::InjectResidual, tokens, &[residual, output, inject, candidate])
}
pub(super) fn run(
&self,
operation: Operation,
tokens: usize,
buffers: &[&DeviceBuffer<'_>],
) -> Result<()> {
pub(super) fn run(&self, operation: Operation, tokens: usize, buffers: &[&DeviceBuffer<'_>]) -> Result<()> {
self.run_with_epsilon(operation, tokens, buffers, 0.)
}
pub(super) fn run_with_epsilon(
@@ -156,10 +125,7 @@ mod installed {
let kernel = self.functions[slot(operation)?];
let mut arguments = Arguments::with_layout(operation, layout, handles, epsilon);
let guard = context.enter()?;
let launch = context
.driver
.api
.launch_qwen(kernel, operation, &mut arguments);
let launch = context.driver.api.launch_qwen(kernel, operation, &mut arguments);
self.launch_attempts.set(self.launch_attempts.get() + 1);
let sync = context.driver.api.synchronize();
if sync.is_err() {
@@ -218,15 +184,15 @@ impl Context<'_> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
{
let dispatcher = installed::GrBatchPreview::new(self)?;
let result = dispatcher.run(
Operation::InjectResidual,
tokens,
&[residual, output, inject, candidate],
);
let result = dispatcher.run(Operation::InjectResidual, tokens, &[residual, output, inject, candidate]);
let cleanup = dispatcher.close();
combine(result, cleanup)
}
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))]
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64",
feature = "cuda-driver"
)))]
{
let _ = (tokens, residual, output, inject, candidate);
Err(Error::UnsupportedPlatform)
@@ -247,15 +213,14 @@ impl Context<'_> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
{
let dispatcher = installed::GrBatchPreview::new(self)?;
let result = dispatcher.run_with_epsilon(
Operation::Norm,
tokens,
&[residual, gamma, output],
epsilon,
);
let result = dispatcher.run_with_epsilon(Operation::Norm, tokens, &[residual, gamma, output], epsilon);
combine(result, dispatcher.close())
}
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))]
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64",
feature = "cuda-driver"
)))]
{
let _ = (tokens, residual, gamma, epsilon, output);
Err(Error::UnsupportedPlatform)
@@ -3,8 +3,6 @@
#[allow(unused_imports)]
use super::*;
/// Bring-up tracing: `LELEKA_BRINGUP_TRACE` set (any value) enables the `DBG`/`PROBE` diagnostics on stderr.
/// Off by default so production serving prints nothing extra.
pub(crate) fn bringup_trace_enabled() -> bool {
@@ -33,9 +31,7 @@ impl Error {
Self::LibraryUnavailable => "cannot load libcuda.so.1",
Self::InvalidOrdinal => "device ordinal must be nonnegative",
Self::HostAllocation => "cannot allocate owned host staging memory",
Self::ContextPoisoned => {
"context is poisoned after uncertain completion or restoration"
}
Self::ContextPoisoned => "context is poisoned after uncertain completion or restoration",
Self::UnexpectedContext => "CUDA pop returned a different context",
_ => return None,
})
@@ -43,29 +39,15 @@ impl Error {
pub(super) fn validation_message(&self) -> Option<&'static str> {
Some(match self {
Self::ContextMismatch => "buffers must belong to this exact context",
Self::InvalidVectorShape => {
"vector shape must be nonempty f32 bytes with a bounded u32 count/grid"
}
Self::InvalidMatvecShape => {
"matvec requires exact nonempty bounded row-major f32 shapes"
}
Self::InvalidQ5KProjectionShape => {
"Q5_K projection requires exact bounded row-major single-column shapes"
}
Self::InvalidQ6KProjectionShape => {
"Q6_K projection requires exact bounded row-major single-column shapes"
}
Self::InvalidVectorShape => "vector shape must be nonempty f32 bytes with a bounded u32 count/grid",
Self::InvalidMatvecShape => "matvec requires exact nonempty bounded row-major f32 shapes",
Self::InvalidQ5KProjectionShape => "Q5_K projection requires exact bounded row-major single-column shapes",
Self::InvalidQ6KProjectionShape => "Q6_K projection requires exact bounded row-major single-column shapes",
Self::UnsupportedProjection => "projection format is not integrated",
Self::UnsupportedQwenOperation => "Qwen operation has no qualified fixed asset",
Self::InvalidQwenShape => {
"Qwen operation requires its exact pinned topology and byte layout"
}
Self::InvalidBf16ProjectionShape => {
"BF16 projection requires exact bounded rows and positive even columns"
}
Self::InvalidProjectionShape => {
"projection requires exact bounded packed single-column shapes"
}
Self::InvalidQwenShape => "Qwen operation requires its exact pinned topology and byte layout",
Self::InvalidBf16ProjectionShape => "BF16 projection requires exact bounded rows and positive even columns",
Self::InvalidProjectionShape => "projection requires exact bounded packed single-column shapes",
Self::InvalidQ8Activation => "activation cannot be represented by native Q8_1",
Self::NonFiniteMmqOutput(_) => "MMQ produced a nonfinite stage output",
Self::OutputAliasesInput => "output must not alias an input",
@@ -77,10 +59,7 @@ impl Error {
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(message) = self
.environment_message()
.or_else(|| self.validation_message())
{
if let Some(message) = self.environment_message().or_else(|| self.validation_message()) {
return f.write_str(message);
}
match self {
@@ -95,10 +74,16 @@ impl fmt::Display for Error {
write!(f, "byte shape mismatch: expected {expected}, got {actual}")
}
Self::GraphOutOfMemory { window: 0 } => {
write!(f, "the verifier commit graph did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)")
write!(
f,
"the verifier commit graph did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)"
)
}
Self::GraphOutOfMemory { window } => {
write!(f, "the verifier window graph T={window} did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)")
write!(
f,
"the verifier window graph T={window} did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)"
)
}
Self::Multiple { primary, secondary } => {
write!(f, "{primary}; subsequent error: {secondary}")
@@ -113,18 +98,13 @@ pub(super) fn combine<T>(primary: Result<T>, secondary: Result<()>) -> Result<T>
match (primary, secondary) {
(Ok(value), Ok(())) => Ok(value),
(Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error),
(Err(primary), Err(secondary)) => Err(Error::Multiple {
primary: Box::new(primary),
secondary: Box::new(secondary),
}),
(Err(primary), Err(secondary)) => {
Err(Error::Multiple { primary: Box::new(primary), secondary: Box::new(secondary) })
}
}
}
pub(super) fn valid_size(bytes: usize) -> Result<()> {
if bytes == 0 || bytes > isize::MAX as usize {
Err(Error::InvalidSize)
} else {
Ok(())
}
if bytes == 0 || bytes > isize::MAX as usize { Err(Error::InvalidSize) } else { Ok(()) }
}
impl Driver {
/// Resolve the entire fixed ABI before initializing CUDA.
@@ -141,11 +121,7 @@ impl Driver {
if ordinal < 0 {
return Err(Error::InvalidOrdinal);
}
Ok(Device {
driver: self,
handle: self.api.device(ordinal)?,
ordinal,
})
Ok(Device { driver: self, handle: self.api.device(ordinal)?, ordinal })
}
}
impl<'driver> Device<'driver> {
@@ -153,13 +129,8 @@ impl<'driver> Device<'driver> {
valid_size(byte_budget)?;
let api = &self.driver.api;
let handle = api.create(self.handle)?;
let restore = api.pop().and_then(|popped| {
if popped == handle {
Ok(())
} else {
Err(Error::UnexpectedContext)
}
});
let restore =
api.pop().and_then(|popped| if popped == handle { Ok(()) } else { Err(Error::UnexpectedContext) });
if let Err(error) = restore {
let cleanup = api.destroy(handle);
if cleanup.is_err() {
@@ -200,12 +171,19 @@ impl<'driver> Device<'driver> {
}
}
impl PoisonCell {
pub(crate) fn new(v: bool) -> Self { Self(Cell::new(v)) }
pub(crate) fn get(&self) -> bool { self.0.get() }
pub(crate) fn new(v: bool) -> Self {
Self(Cell::new(v))
}
pub(crate) fn get(&self) -> bool {
self.0.get()
}
pub(crate) fn set(&self, v: bool) {
if v && !self.0.get() && std::env::var_os("LELEKA_TRACE_POISON").is_some() {
crate::bringup_trace!("DBG context poisoned here:
{}", std::backtrace::Backtrace::force_capture());
crate::bringup_trace!(
"DBG context poisoned here:
{}",
std::backtrace::Backtrace::force_capture()
);
}
self.0.set(v);
}
+34 -85
View File
@@ -43,32 +43,32 @@ ptx_asset!(DEVICE_POISON_PTX, "device_poison.ptx");
pub const PINS: [PtxPin; 3] = [
PtxPin {
source_sha256: [
92, 183, 59, 88, 146, 201, 66, 56, 174, 58, 68, 112, 170, 113, 88, 85, 80, 193, 82, 105,
131, 234, 11, 86, 85, 40, 31, 41, 79, 53, 71, 52,
92, 183, 59, 88, 146, 201, 66, 56, 174, 58, 68, 112, 170, 113, 88, 85, 80, 193, 82, 105, 131, 234, 11, 86,
85, 40, 31, 41, 79, 53, 71, 52,
],
ptx_sha256: [
190, 53, 62, 97, 154, 21, 165, 102, 229, 123, 174, 18, 160, 191, 48, 204, 23, 18, 162,
129, 188, 230, 146, 143, 59, 183, 108, 20, 229, 17, 75, 186,
190, 53, 62, 97, 154, 21, 165, 102, 229, 123, 174, 18, 160, 191, 48, 204, 23, 18, 162, 129, 188, 230, 146,
143, 59, 183, 108, 20, 229, 17, 75, 186,
],
},
PtxPin {
source_sha256: [
9, 34, 187, 150, 202, 59, 47, 17, 16, 80, 154, 218, 178, 66, 207, 118, 250, 31, 145, 12,
222, 133, 157, 30, 78, 65, 80, 198, 7, 181, 25, 82,
9, 34, 187, 150, 202, 59, 47, 17, 16, 80, 154, 218, 178, 66, 207, 118, 250, 31, 145, 12, 222, 133, 157, 30,
78, 65, 80, 198, 7, 181, 25, 82,
],
ptx_sha256: [
58, 180, 209, 42, 94, 151, 196, 226, 244, 96, 44, 108, 135, 35, 114, 197, 192, 104, 93,
140, 241, 162, 2, 96, 175, 110, 15, 82, 5, 172, 118, 213,
58, 180, 209, 42, 94, 151, 196, 226, 244, 96, 44, 108, 135, 35, 114, 197, 192, 104, 93, 140, 241, 162, 2,
96, 175, 110, 15, 82, 5, 172, 118, 213,
],
},
PtxPin {
source_sha256: [
107, 44, 169, 146, 172, 57, 213, 182, 177, 130, 10, 116, 74, 216, 188, 160, 63, 100, 38,
48, 43, 193, 120, 192, 211, 8, 158, 79, 118, 123, 97, 14,
107, 44, 169, 146, 172, 57, 213, 182, 177, 130, 10, 116, 74, 216, 188, 160, 63, 100, 38, 48, 43, 193, 120,
192, 211, 8, 158, 79, 118, 123, 97, 14,
],
ptx_sha256: [
88, 123, 9, 122, 32, 26, 103, 48, 232, 254, 85, 67, 41, 25, 135, 187, 248, 7, 218, 114,
218, 18, 184, 224, 161, 105, 249, 229, 232, 246, 166, 88,
88, 123, 9, 122, 32, 26, 103, 48, 232, 254, 85, 67, 41, 25, 135, 187, 248, 7, 218, 114, 218, 18, 184, 224,
161, 105, 249, 229, 232, 246, 166, 88,
],
},
];
@@ -103,74 +103,23 @@ const S2_TPR: &[Arg] = &[P, P, P, P, L, L, I];
/// Order is `Kernel::ALL_ENTRIES`.
pub static S_GEMV_ENTRIES: [Entry; 17] = [
Entry {
name: c"leleka_s_gemv_2",
args: S_FP16,
},
Entry {
name: c"leleka_s_gemv_4",
args: S_FP16,
},
Entry {
name: c"leleka_s_gemv_8",
args: S_FP16,
},
Entry {
name: c"leleka_s_gemv_split_2",
args: S_SPLIT,
},
Entry {
name: c"leleka_s_gemv_split_4",
args: S_SPLIT,
},
Entry {
name: c"leleka_s_gemv_split_8",
args: S_SPLIT,
},
Entry {
name: c"leleka_s_gemv_q8k_4",
args: S_FP16,
},
Entry {
name: c"leleka_s_gemv_q8k_8",
args: S_FP16,
},
Entry {
name: c"leleka_s_gemv_q8k_split_4",
args: S_Q8,
},
Entry {
name: c"leleka_s_gemv_q8k_split_8",
args: S_Q8,
},
Entry {
name: c"leleka_s_gemv_q8_0_split_4",
args: S_Q8,
},
Entry {
name: c"leleka_s_gemv_q8_0_split_8",
args: S_Q8,
},
Entry {
name: c"leleka_s2_gemv",
args: S2_PLAIN,
},
Entry {
name: c"leleka_s2_gemv_quads",
args: S2_TPR,
},
Entry {
name: c"leleka_s2_gemv_q8",
args: S2_TPR,
},
Entry {
name: c"leleka_s2_gemv_fast_staged",
args: S2_TPR,
},
Entry {
name: c"leleka_s2_gemv_fast_unstaged",
args: S2_TPR,
},
Entry { name: c"leleka_s_gemv_2", args: S_FP16 },
Entry { name: c"leleka_s_gemv_4", args: S_FP16 },
Entry { name: c"leleka_s_gemv_8", args: S_FP16 },
Entry { name: c"leleka_s_gemv_split_2", args: S_SPLIT },
Entry { name: c"leleka_s_gemv_split_4", args: S_SPLIT },
Entry { name: c"leleka_s_gemv_split_8", args: S_SPLIT },
Entry { name: c"leleka_s_gemv_q8k_4", args: S_FP16 },
Entry { name: c"leleka_s_gemv_q8k_8", args: S_FP16 },
Entry { name: c"leleka_s_gemv_q8k_split_4", args: S_Q8 },
Entry { name: c"leleka_s_gemv_q8k_split_8", args: S_Q8 },
Entry { name: c"leleka_s_gemv_q8_0_split_4", args: S_Q8 },
Entry { name: c"leleka_s_gemv_q8_0_split_8", args: S_Q8 },
Entry { name: c"leleka_s2_gemv", args: S2_PLAIN },
Entry { name: c"leleka_s2_gemv_quads", args: S2_TPR },
Entry { name: c"leleka_s2_gemv_q8", args: S2_TPR },
Entry { name: c"leleka_s2_gemv_fast_staged", args: S2_TPR },
Entry { name: c"leleka_s2_gemv_fast_unstaged", args: S2_TPR },
];
pub const POISON_F32: usize = 0;
@@ -235,22 +184,22 @@ mod tests;
mod impl_program;
#[allow(unused_imports)]
pub use impl_program::admit_ptx;
#[allow(unused_imports)]
pub use impl_program::admit;
#[allow(unused_imports)]
pub use impl_program::s_gemv_entry_index;
pub use impl_program::admit_ptx;
#[allow(unused_imports)]
pub use impl_program::conforms;
#[allow(unused_imports)]
pub use impl_program::flash_slots;
#[allow(unused_imports)]
pub use impl_program::flash_bytes;
#[allow(unused_imports)]
pub use impl_program::flash_slots;
#[allow(unused_imports)]
pub use impl_program::poison_slots;
#[allow(unused_imports)]
use impl_program::s_activation_bytes;
#[allow(unused_imports)]
pub use impl_program::s_gemv_entry_index;
#[allow(unused_imports)]
pub use impl_program::s_operand_bytes;
mod s_gemv_slots_fn;
#[allow(unused_imports)]
@@ -3,13 +3,8 @@
#[allow(unused_imports)]
use super::*;
impl Program {
pub const ALL: [Program; 3] = [
Program::NativeFlashAttn,
Program::SGemvLegacy,
Program::DevicePoison,
];
pub const ALL: [Program; 3] = [Program::NativeFlashAttn, Program::SGemvLegacy, Program::DevicePoison];
pub const fn name(self) -> &'static str {
match self {
Self::NativeFlashAttn => "native_flash_attn",
@@ -50,11 +45,7 @@ pub fn admit_ptx(program: Program, ptx: &'static [u8], pin: &PtxPin) -> Result<(
if pin.source_sha256 == [0; 32] || pin.ptx_sha256 == [0; 32] {
return Err(refuse);
}
if ptx.len() < 2
|| ptx.last() != Some(&0)
|| ptx[..ptx.len() - 1].contains(&0)
|| !ptx.is_ascii()
{
if ptx.len() < 2 || ptx.last() != Some(&0) || ptx[..ptx.len() - 1].contains(&0) || !ptx.is_ascii() {
return Err(refuse);
}
if qwen_ffi::sha256(&ptx[..ptx.len() - 1]) != pin.ptx_sha256 {
@@ -92,14 +83,10 @@ impl Slot {
pub fn conforms(entry: &Entry, slots: &[Slot]) -> bool {
slots.len() <= MAX_ENTRY_ARGUMENTS
&& entry.args.len() == slots.len()
&& entry
.args
.iter()
.zip(slots)
.all(|(want, slot)| match (want, slot.kind()) {
(Arg::PtrOpt, Arg::Ptr | Arg::PtrOpt) => true,
(a, b) => *a == b,
})
&& entry.args.iter().zip(slots).all(|(want, slot)| match (want, slot.kind()) {
(Arg::PtrOpt, Arg::Ptr | Arg::PtrOpt) => true,
(a, b) => *a == b,
})
}
/// `leleka_native_flash_attn_short(q, k, v, step, max_context, padded_length, scale, out, status, mask)`.
@@ -114,11 +101,7 @@ pub fn flash_slots(max_context: i32, with_mask: bool) -> Vec<Slot> {
Slot::F32(flash::SCALE),
Slot::Ptr(Role::Out),
Slot::Ptr(Role::Status),
if with_mask {
Slot::Ptr(Role::Mask)
} else {
Slot::Null
},
if with_mask { Slot::Ptr(Role::Mask) } else { Slot::Null },
]
}
pub fn flash_bytes(capacity: i64) -> Result<FlashBytes> {
@@ -144,16 +127,10 @@ pub fn poison_slots(n_floats: u64) -> Result<Vec<Slot>> {
}
pub(super) fn s_activation_bytes(kernel: Kernel, n_in: u64) -> u64 {
use crate::s_gemv_legacy::{
Q8_0_BLOCK_BYTES, Q8_0_BLOCK_ELEMS, Q8K_BLOCK_BYTES, Q8K_BLOCK_ELEMS,
};
use crate::s_gemv_legacy::{Q8_0_BLOCK_BYTES, Q8_0_BLOCK_ELEMS, Q8K_BLOCK_BYTES, Q8K_BLOCK_ELEMS};
match kernel {
Kernel::SGemvQ8k(_) | Kernel::SGemvQ8kSplit(_) => {
n_in / Q8K_BLOCK_ELEMS as u64 * Q8K_BLOCK_BYTES as u64
}
Kernel::SGemvQ80Split(_) | Kernel::S2GemvQ8 => {
n_in / Q8_0_BLOCK_ELEMS as u64 * Q8_0_BLOCK_BYTES as u64
}
Kernel::SGemvQ8k(_) | Kernel::SGemvQ8kSplit(_) => n_in / Q8K_BLOCK_ELEMS as u64 * Q8K_BLOCK_BYTES as u64,
Kernel::SGemvQ80Split(_) | Kernel::S2GemvQ8 => n_in / Q8_0_BLOCK_ELEMS as u64 * Q8_0_BLOCK_BYTES as u64,
_ => n_in * 2,
}
}
@@ -168,20 +145,12 @@ pub fn s_operand_bytes(kernel: Kernel, form: &SForm, n_in: i64, n_out: i64) -> R
let (n_in, n_out) = (n_in as u64, n_out as u64);
let s2 = matches!(
kernel,
Kernel::S2Gemv
| Kernel::S2GemvQuads
| Kernel::S2GemvQ8
| Kernel::S2GemvFastStaged
| Kernel::S2GemvFastUnstaged
Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8 | Kernel::S2GemvFastStaged | Kernel::S2GemvFastUnstaged
);
let (bits, group, offset) = if s2 {
(2u64, crate::s_gemv_legacy::S2_QK as u64, false)
} else {
(
form.code_bits as u64,
form.group_elems as u64,
form.has_offset,
)
(form.code_bits as u64, form.group_elems as u64, form.has_offset)
};
if bits == 0 || group == 0 || n_in % group != 0 || n_in * bits % 8 != 0 {
return invalid("S-form GEMV rows must hold whole groups and whole code bytes");
@@ -3,27 +3,12 @@
#[allow(unused_imports)]
use super::*;
/// The kernel arguments of a planned S-form GEMV, in the entry's order. `offset_present` is `offset != nullptr`.
pub fn s_gemv_slots(
plan: &Plan,
form: &SForm,
n_in: i64,
n_out: i64,
offset_present: bool,
) -> Vec<Slot> {
let offset = if offset_present {
Slot::Ptr(Role::Offset)
} else {
Slot::Null
};
pub fn s_gemv_slots(plan: &Plan, form: &SForm, n_in: i64, n_out: i64, offset_present: bool) -> Vec<Slot> {
let offset = if offset_present { Slot::Ptr(Role::Offset) } else { Slot::Null };
let tpr = Slot::I32(plan.launch.block[0] as i32);
let head = |with_offset: bool| -> Vec<Slot> {
let mut v = vec![
Slot::Ptr(Role::X),
Slot::Ptr(Role::Codes),
Slot::Ptr(Role::Scales),
];
let mut v = vec![Slot::Ptr(Role::X), Slot::Ptr(Role::Codes), Slot::Ptr(Role::Scales)];
if with_offset {
v.push(offset);
}
@@ -31,11 +16,8 @@ pub fn s_gemv_slots(
v.extend([Slot::I64(n_in), Slot::I64(n_out)]);
v
};
let (bias, codebook, has_offset) = (
Slot::I32(form.code_bias),
Slot::I32(form.codebook as i32),
Slot::I32(i32::from(form.has_offset)),
);
let (bias, codebook, has_offset) =
(Slot::I32(form.code_bias), Slot::I32(form.codebook as i32), Slot::I32(i32::from(form.has_offset)));
match plan.kernel {
Kernel::SGemv(_) | Kernel::SGemvQ8k(_) => {
let mut v = head(true);
@@ -44,14 +26,7 @@ pub fn s_gemv_slots(
}
Kernel::SGemvSplit(_) => {
let mut v = head(true);
v.extend([
bias,
codebook,
Slot::I32(form.group_elems),
Slot::I32(plan.group_shift),
has_offset,
tpr,
]);
v.extend([bias, codebook, Slot::I32(form.group_elems), Slot::I32(plan.group_shift), has_offset, tpr]);
v
}
Kernel::SGemvQ8kSplit(_) | Kernel::SGemvQ80Split(_) => {
@@ -60,10 +35,7 @@ pub fn s_gemv_slots(
v
}
Kernel::S2Gemv => head(false),
Kernel::S2GemvQuads
| Kernel::S2GemvQ8
| Kernel::S2GemvFastStaged
| Kernel::S2GemvFastUnstaged => {
Kernel::S2GemvQuads | Kernel::S2GemvQ8 | Kernel::S2GemvFastStaged | Kernel::S2GemvFastUnstaged => {
let mut v = head(false);
v.push(tpr);
v
+3 -12
View File
@@ -5,9 +5,7 @@ use crate::s_gemv_legacy as sg;
/// `count_params`: parameter kinds of `extern "C" __global__ ... name(...)` in a `.cu` text.
fn kinds_in(source: &str, name: &str) -> Vec<&'static str> {
let at = source
.find(&format!(" {name}("))
.unwrap_or_else(|| panic!("{name} not in source"));
let at = source.find(&format!(" {name}(")).unwrap_or_else(|| panic!("{name} not in source"));
let rest = &source[at + name.len() + 2..];
let close = rest.find(") {").expect("parameter list end");
rest[..close]
@@ -31,15 +29,8 @@ fn kinds_in(source: &str, name: &str) -> Vec<&'static str> {
/// The S-form entries are generated by macros: expand the two argument macros to find their parameter kinds.
fn macro_kinds(source: &str, macro_name: &str) -> Vec<&'static str> {
let at = source
.find(&format!("#define {macro_name} "))
.expect("macro");
let body = source[at..]
.lines()
.take(3)
.collect::<Vec<_>>()
.join(" ")
.replace('\\', " ");
let at = source.find(&format!("#define {macro_name} ")).expect("macro");
let body = source[at..].lines().take(3).collect::<Vec<_>>().join(" ").replace('\\', " ");
let params = body.split_once(macro_name).unwrap().1.trim_start();
// the macro text ends at its last parameter ("int has_offset"); stop before the next `#define`
let params = params.split("#define").next().unwrap();
@@ -3,7 +3,6 @@
#[allow(unused_imports)]
use super::*;
#[test]
fn flash_and_poison_signatures_match_their_cuda_source() {
for program in [Program::NativeFlashAttn, Program::DevicePoison] {
@@ -13,11 +12,7 @@ fn flash_and_poison_signatures_match_their_cuda_source() {
assert!(entry.args.len() <= MAX_ENTRY_ARGUMENTS);
}
}
assert!(
Program::NativeFlashAttn
.source()
.contains("__launch_bounds__(128, 1)")
);
assert!(Program::NativeFlashAttn.source().contains("__launch_bounds__(128, 1)"));
assert_eq!(flash::LAUNCH.block[0] * flash::LAUNCH.block[1], 128);
}
@@ -26,12 +21,7 @@ fn s_gemv_signatures_match_their_cuda_source() {
let source = Program::SGemvLegacy.source();
let fp16 = macro_kinds(source, "LELEKA_S_FP16_ARGS");
let q8 = macro_kinds(source, "LELEKA_S_Q8_ARGS");
assert_eq!(
fp16,
[
"ptr", "ptr", "ptr", "ptr", "ptr", "i64", "i64", "i32", "i32", "i32", "i32"
]
);
assert_eq!(fp16, ["ptr", "ptr", "ptr", "ptr", "ptr", "i64", "i64", "i32", "i32", "i32", "i32"]);
assert_eq!(q8, fp16);
for (index, entry) in S_GEMV_ENTRIES.iter().enumerate() {
let name = entry.name.to_str().unwrap();
@@ -58,23 +48,10 @@ fn s_gemv_signatures_match_their_cuda_source() {
fn index_constants_and_planners_point_at_the_named_entries() {
let name = |p: Program, i: usize| p.entries()[i].name.to_str().unwrap();
assert_eq!(name(Program::NativeFlashAttn, FLASH_SHORT), flash::ENTRY);
assert_eq!(
name(Program::DevicePoison, POISON_F32),
crate::device_arena::ENTRY_POISON
);
let form = SForm {
code_bits: 4,
code_bias: -8,
group_elems: 32,
..SForm::default()
};
let plan = sg::plan_s_gemv_split(512, 8, &form, 64, false)
.unwrap()
.unwrap();
assert_eq!(
name(Program::SGemvLegacy, s_gemv_entry_index(plan.kernel)),
"leleka_s_gemv_split_4"
);
assert_eq!(name(Program::DevicePoison, POISON_F32), crate::device_arena::ENTRY_POISON);
let form = SForm { code_bits: 4, code_bias: -8, group_elems: 32, ..SForm::default() };
let plan = sg::plan_s_gemv_split(512, 8, &form, 64, false).unwrap().unwrap();
assert_eq!(name(Program::SGemvLegacy, s_gemv_entry_index(plan.kernel)), "leleka_s_gemv_split_4");
for (i, e) in Kernel::ALL_ENTRIES.iter().enumerate() {
assert_eq!(S_GEMV_ENTRIES[i].name.to_str().unwrap(), *e);
}
@@ -83,26 +60,9 @@ fn index_constants_and_planners_point_at_the_named_entries() {
#[test]
fn every_planned_launch_conforms_to_its_entry() {
let forms = [
SForm {
code_bits: 2,
code_bias: -1,
group_elems: 64,
..SForm::default()
},
SForm {
code_bits: 4,
code_bias: -8,
group_elems: 32,
has_offset: true,
..SForm::default()
},
SForm {
code_bits: 8,
code_bias: -128,
group_elems: 64,
codebook: sg::Codebook::Iq4Nl,
..SForm::default()
},
SForm { code_bits: 2, code_bias: -1, group_elems: 64, ..SForm::default() },
SForm { code_bits: 4, code_bias: -8, group_elems: 32, has_offset: true, ..SForm::default() },
SForm { code_bits: 8, code_bias: -128, group_elems: 64, codebook: sg::Codebook::Iq4Nl, ..SForm::default() },
];
let mut planned = 0;
for form in forms {
@@ -113,18 +73,10 @@ fn every_planned_launch_conforms_to_its_entry() {
let (n_in, n_out) = (1024, 6);
let mut plans: Vec<Plan> = Vec::new();
plans.extend(sg::plan_s_gemv(n_in, n_out, &form, offset).ok().flatten());
plans.extend(
sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset)
.ok()
.flatten(),
);
plans.extend(sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset).ok().flatten());
plans.extend(sg::plan_s_gemv_q8k(n_in, n_out, &form).ok().flatten());
plans.extend(sg::plan_s_gemv_q8k_split(n_in, n_out, &form).ok().flatten());
plans.extend(
sg::plan_s_gemv_q8_0_split(n_in, n_out, &form)
.ok()
.flatten(),
);
plans.extend(sg::plan_s_gemv_q8_0_split(n_in, n_out, &form).ok().flatten());
for plan in plans {
let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)];
let slots = s_gemv_slots(&plan, &form, n_in, n_out, offset);
@@ -162,9 +114,7 @@ fn slot_values_follow_the_oracle_driver() {
has_offset: true,
..SForm::default()
};
let plan = sg::plan_s_gemv_split(512, 8, &form, 64, true)
.unwrap()
.unwrap();
let plan = sg::plan_s_gemv_split(512, 8, &form, 64, true).unwrap().unwrap();
let slots = s_gemv_slots(&plan, &form, 512, 8, true);
assert_eq!(
slots,
@@ -184,92 +134,47 @@ fn slot_values_follow_the_oracle_driver() {
Slot::I32(64),
]
);
assert_eq!(
(
plan.launch.grid,
plan.launch.block,
plan.launch.dynamic_shared
),
([8, 1, 1], [64, 1, 1], 256)
);
assert_eq!((plan.launch.grid, plan.launch.block, plan.launch.dynamic_shared), ([8, 1, 1], [64, 1, 1], 256));
// the Q8 split kernels take the shift in place of the group
let plan = sg::plan_s_gemv_q8k_split(512, 8, &form).unwrap().unwrap();
let slots = s_gemv_slots(&plan, &form, 512, 8, true);
assert_eq!(
&slots[7..],
&[Slot::I32(-8), Slot::I32(1), Slot::I32(5), Slot::I32(1)]
);
assert_eq!(&slots[7..], &[Slot::I32(-8), Slot::I32(1), Slot::I32(5), Slot::I32(1)]);
// a form without an offset passes a null offset pointer
let none = SForm {
has_offset: false,
..form
};
let none = SForm { has_offset: false, ..form };
let plan = sg::plan_s_gemv(512, 8, &none, false).unwrap().unwrap();
assert_eq!(s_gemv_slots(&plan, &none, 512, 8, false)[3], Slot::Null);
}
#[test]
fn operand_sizes_follow_the_pack_format() {
let form = SForm {
code_bits: 4,
code_bias: -8,
group_elems: 32,
has_offset: true,
..SForm::default()
};
let form = SForm { code_bits: 4, code_bias: -8, group_elems: 32, has_offset: true, ..SForm::default() };
let b = s_operand_bytes(Kernel::SGemvSplit(4), &form, 512, 8).unwrap();
assert_eq!(
(b.x, b.codes, b.scales, b.offset, b.y),
(1024, 8 * 256, 8 * 16 * 4, Some(8 * 16 * 4), 32)
);
assert_eq!((b.x, b.codes, b.scales, b.offset, b.y), (1024, 8 * 256, 8 * 16 * 4, Some(8 * 16 * 4), 32));
let b = s_operand_bytes(Kernel::SGemvQ8k(4), &form, 512, 8).unwrap();
assert_eq!(b.x, 2 * 292);
let b = s_operand_bytes(Kernel::SGemvQ80Split(4), &form, 512, 8).unwrap();
assert_eq!(b.x, 16 * 34);
let b = s_operand_bytes(Kernel::S2GemvQ8, &SForm::default(), 512, 8).unwrap();
assert_eq!(
(b.x, b.codes, b.scales, b.offset),
(16 * 34, 8 * 128, 8 * 8 * 4, None)
);
assert_eq!((b.x, b.codes, b.scales, b.offset), (16 * 34, 8 * 128, 8 * 8 * 4, None));
assert!(s_operand_bytes(Kernel::SGemv(2), &SForm::default(), 0, 8).is_err());
assert!(
s_operand_bytes(
Kernel::SGemv(2),
&SForm {
group_elems: 64,
..SForm::default()
},
100,
8
)
.is_err()
);
assert!(s_operand_bytes(Kernel::SGemv(2), &SForm { group_elems: 64, ..SForm::default() }, 100, 8).is_err());
}
#[test]
fn flash_and_poison_slots_and_sizes() {
let slots = flash_slots(256, true);
assert!(conforms(&FLASH_ENTRIES[0], &slots));
assert_eq!(
slots[4..7],
[Slot::I32(256), Slot::I32(256), Slot::F32(0.0625)]
);
assert_eq!(slots[4..7], [Slot::I32(256), Slot::I32(256), Slot::F32(0.0625)]);
assert_eq!(flash_slots(256, false)[9], Slot::Null);
assert!(conforms(&FLASH_ENTRIES[0], &flash_slots(7, false)));
let b = flash_bytes(4096).unwrap();
assert_eq!(
(b.q, b.kv, b.step, b.out, b.status, b.mask),
(24576, 4096 * 1024, 16, 24576, 4, 512)
);
assert_eq!((b.q, b.kv, b.step, b.out, b.status, b.mask), (24576, 4096 * 1024, 16, 24576, 4, 512));
assert!(flash_bytes(255).is_err());
let slots = poison_slots(1000).unwrap();
assert_eq!(slots, vec![Slot::Ptr(Role::Poison), Slot::I64(1000)]);
assert!(conforms(&POISON_ENTRIES[0], &slots));
assert!(poison_slots(u64::MAX).is_err());
// a mismatching scalar kind never conforms
assert!(!conforms(
&POISON_ENTRIES[0],
&[Slot::Ptr(Role::Poison), Slot::I32(1)]
));
assert!(!conforms(&POISON_ENTRIES[0], &[Slot::Ptr(Role::Poison), Slot::I32(1)]));
assert!(!conforms(&POISON_ENTRIES[0], &[Slot::Ptr(Role::Poison)]));
}
@@ -3,12 +3,11 @@
#[allow(unused_imports)]
use super::*;
#[test]
fn sealed_assets_match_their_pins_and_export_every_entry() {
use crate::sealed_ptx::test_support::{
assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul,
without_terminator,
assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter,
with_embedded_nul, without_terminator,
};
for program in Program::ALL {
// Sealed with nvcc 13.2.86 on 2026-10-15; this checks structure and the pin only (no numerical claim,
@@ -33,34 +32,15 @@ fn sealed_assets_match_their_pins_and_export_every_entry() {
let mut wrong_digest = *pin;
wrong_digest.ptx_sha256[0] ^= 1;
assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse);
for zeroed in [
PtxPin { source_sha256: [0; 32], ..*pin },
PtxPin { ptx_sha256: [0; 32], ..*pin },
] {
for zeroed in [PtxPin { source_sha256: [0; 32], ..*pin }, PtxPin { ptx_sha256: [0; 32], ..*pin }] {
assert_eq!(admit_ptx(program, ptx, &zeroed), refuse);
}
}
// a matching pin admits; any difference refuses
static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0";
let pin = PtxPin {
source_sha256: [1; 32],
ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]),
};
let pin = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]) };
assert_eq!(admit_ptx(Program::DevicePoison, GOOD, &pin), Ok(()));
let wrong = PtxPin {
ptx_sha256: [2; 32],
..pin
};
let wrong = PtxPin { ptx_sha256: [2; 32], ..pin };
assert!(admit_ptx(Program::DevicePoison, GOOD, &wrong).is_err());
assert!(
admit_ptx(
Program::DevicePoison,
GOOD,
&PtxPin {
source_sha256: [0; 32],
..pin
}
)
.is_err()
);
assert!(admit_ptx(Program::DevicePoison, GOOD, &PtxPin { source_sha256: [0; 32], ..pin }).is_err());
}
+2 -2
View File
@@ -22,8 +22,8 @@
use crate::{
Context, DeviceBuffer, Error,
closed_kernels::{
FLASH_SHORT, POISON_F32, Program, Role, Slot, admit, conforms, flash_bytes, flash_slots,
poison_slots, s_gemv_entry_index, s_gemv_slots, s_operand_bytes,
FLASH_SHORT, POISON_F32, Program, Role, Slot, admit, conforms, flash_bytes, flash_slots, poison_slots,
s_gemv_entry_index, s_gemv_slots, s_operand_bytes,
},
combine, device_arena,
experimental::{ExperimentalError, Result, invalid},
@@ -3,10 +3,7 @@
#[allow(unused_imports)]
use super::*;
/// A primary driver failure plus the outcome of the mandatory context restore.
pub(super) fn failure(primary: Error, restore: DriverResult<()>) -> ExperimentalError {
combine::<()>(Err(primary), restore)
.expect_err("a primary failure always stays an error")
.into()
combine::<()>(Err(primary), restore).expect_err("a primary failure always stays an error").into()
}
@@ -3,8 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl<'c> ClosedKernels<'c> {
/// Pin gate, then load the module and resolve every entry; nothing is kept unless all of them resolve.
pub fn open(context: &'c Context<'c>, program: Program) -> Result<Self> {
@@ -32,12 +30,7 @@ impl<'c> ClosedKernels<'c> {
match resolved {
Ok(()) => {
guard.finish()?;
Ok(Self {
context,
program,
module,
functions,
})
Ok(Self { context, program, module, functions })
}
Err(error) => {
let cleanup = api.unload(module);
@@ -45,8 +38,7 @@ impl<'c> ClosedKernels<'c> {
context.poisoned.set(true);
std::mem::forget(Rc::clone(api));
}
let primary =
combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary");
let primary = combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary");
Err(failure(primary, guard.finish()))
}
}
@@ -88,10 +80,7 @@ impl<'c> ClosedKernels<'c> {
if !conforms(spec, slots) {
return invalid("closed launch arguments differ from the entry's fixed signature");
}
if block.contains(&0)
|| grid.contains(&0)
|| block.iter().map(|b| u64::from(*b)).product::<u64>() > 1024
{
if block.contains(&0) || grid.contains(&0) || block.iter().map(|b| u64::from(*b)).product::<u64>() > 1024 {
return invalid("closed launch geometry is empty or exceeds 1024 threads per block");
}
let context = self.context;
@@ -111,17 +100,12 @@ impl<'c> ClosedKernels<'c> {
return Err(Error::ContextMismatch.into());
}
let handle = operand.buffer.handle.ok_or(Error::ContextPoisoned)?;
let min = usize::try_from(operand.min)
.or_else(|_| invalid("closed buffer size exceeds usize"))?;
let min = usize::try_from(operand.min).or_else(|_| invalid("closed buffer size exceeds usize"))?;
if min == 0 || operand.buffer.bytes < min {
return invalid("closed buffer is smaller than the geometry requires");
}
handle.validate_projection_extent(operand.buffer.bytes, 16)?;
admitted.push(Admitted {
handle,
bytes: operand.buffer.bytes,
writes: operand.writes,
});
admitted.push(Admitted { handle, bytes: operand.buffer.bytes, writes: operand.writes });
let at = handle.experimental_offset(operand.offset)?;
args.push(ffi::KarArgument::Scalar64(at.qwen_address()));
}
@@ -138,13 +122,7 @@ impl<'c> ClosedKernels<'c> {
}
}
}
Ok(Launch {
function: self.functions[entry],
grid,
block,
shared,
args: ffi::KarLevelsArgs::new(&args)?,
})
Ok(Launch { function: self.functions[entry], grid, block, shared, args: ffi::KarLevelsArgs::new(&args)? })
}
/// Launch in order and drain with exactly one synchronize.
@@ -156,19 +134,11 @@ impl<'c> ClosedKernels<'c> {
let guard = context.enter()?;
let mut launch = Ok(());
for l in &mut launches {
launch = context.driver.api.launch_closed(
l.function,
l.grid,
l.block,
l.shared,
&mut l.args,
);
launch = context.driver.api.launch_closed(l.function, l.grid, l.block, l.shared, &mut l.args);
if launch.is_err() {
break;
}
}
context
.complete_launch(launch, launches, guard)
.map_err(Into::into)
context.complete_launch(launch, launches, guard).map_err(Into::into)
}
}
@@ -3,10 +3,7 @@
#[allow(unused_imports)]
use super::*;
impl<'c> ClosedKernels<'c> {
// --------------------------------------------------------------------------- short FlashAttention
/// `native_flash_attn_short_step`: one query, Q 24x256 f32, K/V 2x256 f16 cells (`capacity` of them each), device
@@ -32,8 +29,7 @@ impl<'c> ClosedKernels<'c> {
let bytes = flash_bytes(capacity)?;
let address = |b: &DeviceBuffer<'_>| -> Result<usize> {
let handle = b.handle.ok_or(Error::ContextPoisoned)?;
usize::try_from(handle.qwen_address())
.or_else(|_| invalid("device address exceeds usize"))
usize::try_from(handle.qwen_address()).or_else(|_| invalid("device address exceeds usize"))
};
let launch = flash::admit(&flash::Arguments {
n_head: flash::HEADS as i64,
@@ -54,67 +50,18 @@ impl<'c> ClosedKernels<'c> {
})
.map_err(|e| ExperimentalError::Invalid(e.message()))?;
let mut operands = vec![
Operand {
role: Role::Q,
buffer: q,
min: bytes.q,
offset: 0,
writes: false,
},
Operand {
role: Role::K,
buffer: k,
min: bytes.kv,
offset: 0,
writes: false,
},
Operand {
role: Role::V,
buffer: v,
min: bytes.kv,
offset: 0,
writes: false,
},
Operand {
role: Role::Step,
buffer: step,
min: bytes.step,
offset: 0,
writes: false,
},
Operand {
role: Role::Out,
buffer: out,
min: bytes.out,
offset: 0,
writes: true,
},
Operand {
role: Role::Status,
buffer: status,
min: bytes.status,
offset: 0,
writes: true,
},
Operand { role: Role::Q, buffer: q, min: bytes.q, offset: 0, writes: false },
Operand { role: Role::K, buffer: k, min: bytes.kv, offset: 0, writes: false },
Operand { role: Role::V, buffer: v, min: bytes.kv, offset: 0, writes: false },
Operand { role: Role::Step, buffer: step, min: bytes.step, offset: 0, writes: false },
Operand { role: Role::Out, buffer: out, min: bytes.out, offset: 0, writes: true },
Operand { role: Role::Status, buffer: status, min: bytes.status, offset: 0, writes: true },
];
if let Some(mask) = mask {
operands.push(Operand {
role: Role::Mask,
buffer: mask,
min: bytes.mask,
offset: 0,
writes: false,
});
operands.push(Operand { role: Role::Mask, buffer: mask, min: bytes.mask, offset: 0, writes: false });
}
let slots = flash_slots(max_context, mask.is_some());
let launch = self.build(
FLASH_SHORT,
launch.grid,
launch.block,
launch.dynamic_shared,
&slots,
&operands,
)?;
let launch = self.build(FLASH_SHORT, launch.grid, launch.block, launch.dynamic_shared, &slots, &operands)?;
self.run(vec![launch])
}
@@ -124,8 +71,7 @@ impl<'c> ClosedKernels<'c> {
/// `0x7fc00000`, in slices of at most `0x7FFFFFFF` blocks of 256 threads, under one drain.
pub fn poison_f32(&self, buffer: &mut DeviceBuffer<'_>) -> Result<()> {
self.expect(Program::DevicePoison)?;
let plan =
device_arena::poison_launches(buffer.bytes as u64, device_arena::POISON_MAX_BLOCKS);
let plan = device_arena::poison_launches(buffer.bytes as u64, device_arena::POISON_MAX_BLOCKS);
if plan.is_empty() {
return invalid("poison needs at least one float");
}
@@ -138,12 +84,7 @@ impl<'c> ClosedKernels<'c> {
offset: slice.float_offset * 4,
writes: true,
}];
let grid = [
u32::try_from(slice.blocks)
.or_else(|_| invalid("poison slice exceeds the grid"))?,
1,
1,
];
let grid = [u32::try_from(slice.blocks).or_else(|_| invalid("poison slice exceeds the grid"))?, 1, 1];
launches.push(self.build(
POISON_F32,
grid,
@@ -180,43 +121,13 @@ impl<'c> ClosedKernels<'c> {
return invalid("the S-form has an offset exactly when an offset buffer is passed");
}
let mut operands = vec![
Operand {
role: Role::X,
buffer: x,
min: bytes.x,
offset: 0,
writes: false,
},
Operand {
role: Role::Codes,
buffer: codes,
min: bytes.codes,
offset: 0,
writes: false,
},
Operand {
role: Role::Scales,
buffer: scales,
min: bytes.scales,
offset: 0,
writes: false,
},
Operand {
role: Role::Y,
buffer: y,
min: bytes.y,
offset: 0,
writes: true,
},
Operand { role: Role::X, buffer: x, min: bytes.x, offset: 0, writes: false },
Operand { role: Role::Codes, buffer: codes, min: bytes.codes, offset: 0, writes: false },
Operand { role: Role::Scales, buffer: scales, min: bytes.scales, offset: 0, writes: false },
Operand { role: Role::Y, buffer: y, min: bytes.y, offset: 0, writes: true },
];
if let (Some(buffer), Some(min)) = (offset, bytes.offset) {
operands.push(Operand {
role: Role::Offset,
buffer,
min,
offset: 0,
writes: false,
});
operands.push(Operand { role: Role::Offset, buffer, min, offset: 0, writes: false });
}
let slots = s_gemv_slots(plan, form, n_in, n_out, offset.is_some());
let launch = self.build(
@@ -242,16 +153,6 @@ impl<'c> ClosedKernels<'c> {
scales: &DeviceBuffer<'_>,
y: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.s_gemv(
plan,
&SForm::default(),
n_in,
n_out,
x,
codes,
scales,
None,
y,
)
self.s_gemv(plan, &SForm::default(), n_in, n_out, x, codes, scales, None, y)
}
}
@@ -31,17 +31,10 @@ fn closed_gpu_poison_fills_the_nan_pattern_and_nothing_else() {
let mut want = vec![0u32; floats];
device_arena::poison_model(
&mut want,
&device_arena::poison_launches(
(floats * 4) as u64,
device_arena::POISON_MAX_BLOCKS,
)[0],
&device_arena::poison_launches((floats * 4) as u64, device_arena::POISON_MAX_BLOCKS)[0],
);
for (i, word) in got.chunks_exact(4).enumerate() {
assert_eq!(
u32::from_le_bytes(word.try_into().unwrap()),
want[i],
"float {i} of {floats}"
);
assert_eq!(u32::from_le_bytes(word.try_into().unwrap()), want[i], "float {i} of {floats}");
}
}
gpu.close().unwrap();
@@ -62,43 +55,18 @@ fn closed_gpu_native_flash_attn_matches_the_fp64_specification() {
for with_mask in [false, true] {
let mut rng = Rng(0xf1a5_0000 + width as u64 * 2 + u64::from(with_mask));
let q: Vec<f32> = (0..24 * 256).map(|_| 0.8 * rng.normal()).collect();
let k: Vec<u16> = (0..capacity * 512)
.map(|_| f16_bits(rng.normal()))
.collect();
let v: Vec<u16> = (0..capacity * 512)
.map(|_| f16_bits(rng.normal()))
.collect();
let mask: Vec<u16> = (0..256)
.map(|c| {
f16_bits(if with_mask {
((c * 7) % 5) as f32 * -0.5
} else {
0.0
})
})
.collect();
let step = [
width as i32 - 1,
width as i32,
width as i32 / 4,
width as i32,
];
let k: Vec<u16> = (0..capacity * 512).map(|_| f16_bits(rng.normal())).collect();
let v: Vec<u16> = (0..capacity * 512).map(|_| f16_bits(rng.normal())).collect();
let mask: Vec<u16> =
(0..256).map(|c| f16_bits(if with_mask { ((c * 7) % 5) as f32 * -0.5 } else { 0.0 })).collect();
let step = [width as i32 - 1, width as i32, width as i32 / 4, width as i32];
let bytes = |h: &[u16]| h.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
let (q_b, k_b, v_b) = (
upload(
&ctx,
&q.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>(),
),
upload(&ctx, &q.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>()),
upload(&ctx, &bytes(&k)),
upload(&ctx, &bytes(&v)),
);
let step_b = upload(
&ctx,
&step
.iter()
.flat_map(|x| x.to_le_bytes())
.collect::<Vec<u8>>(),
);
let step_b = upload(&ctx, &step.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>());
let mask_b = upload(&ctx, &bytes(&mask));
let mut out_b = upload(&ctx, &vec![0xffu8; 24 * 256 * 4]);
let mut status_b = upload(&ctx, &(-1i32).to_le_bytes());
@@ -124,23 +92,16 @@ fn closed_gpu_native_flash_attn_matches_the_fp64_specification() {
let h2f = |b: u16| sg::f16_to_f32(b);
for head in 0..24 {
let kv = head / 12;
let kk: Vec<Vec<f32>> = (0..width)
.map(|c| (0..256).map(|d| h2f(k[(c * 2 + kv) * 256 + d])).collect())
.collect();
let vv: Vec<Vec<f32>> = (0..width)
.map(|c| (0..256).map(|d| h2f(v[(c * 2 + kv) * 256 + d])).collect())
.collect();
let kk: Vec<Vec<f32>> =
(0..width).map(|c| (0..256).map(|d| h2f(k[(c * 2 + kv) * 256 + d])).collect()).collect();
let vv: Vec<Vec<f32>> =
(0..width).map(|c| (0..256).map(|d| h2f(v[(c * 2 + kv) * 256 + d])).collect()).collect();
let m: Vec<f32> = (0..width).map(|c| h2f(mask[c])).collect();
let want = flash::reference_head(
&q[head * 256..(head + 1) * 256],
&kk,
&vv,
with_mask.then_some(&m[..]),
);
let want =
flash::reference_head(&q[head * 256..(head + 1) * 256], &kk, &vv, with_mask.then_some(&m[..]));
let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs())));
for d in 0..256 {
worst =
worst.max(f64::from((out[head * 256 + d] - want[d]).abs()) / magnitude);
worst = worst.max(f64::from((out[head * 256 + d] - want[d]).abs()) / magnitude);
}
}
}
@@ -165,15 +126,8 @@ fn closed_gpu_native_flash_attn_matches_the_fp64_specification() {
&mut status_b,
)
.unwrap();
assert_eq!(
i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()),
flash::STATUS_UNSUPPORTED_STEP
);
assert!(
f32s(&download(&out_b, 24 * 256 * 4))
.iter()
.all(|x| x.is_nan())
);
assert_eq!(i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()), flash::STATUS_UNSUPPORTED_STEP);
assert!(f32s(&download(&out_b, 24 * 256 * 4)).iter().all(|x| x.is_nan()));
gpu.close().unwrap();
}
ctx.close().unwrap();
@@ -199,70 +153,28 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() {
code_bits: case["bits"].as_i64().unwrap() as i32,
code_bias: case["bias"].as_i64().unwrap() as i32,
group_elems: case["group"].as_i64().unwrap() as i32,
codebook: if case["codebook"].as_i64().unwrap() == 1 {
Codebook::Iq4Nl
} else {
Codebook::Affine
},
codebook: if case["codebook"].as_i64().unwrap() == 1 { Codebook::Iq4Nl } else { Codebook::Affine },
has_offset: case["has_offset"].as_i64().unwrap() == 1,
act_kind: 0,
};
let (n_in, n_out) = (
case["n_in"].as_i64().unwrap(),
case["n_out"].as_i64().unwrap(),
);
let (n_in, n_out) = (case["n_in"].as_i64().unwrap(), case["n_out"].as_i64().unwrap());
let exact = case["exact"].as_i64().unwrap() == 1;
let codes = upload(&ctx, &json_bytes(&case["codes"]));
let scales = upload(
&ctx,
&json_f32(&case["scales"])
.iter()
.flat_map(|x| x.to_le_bytes())
.collect::<Vec<u8>>(),
);
let scales =
upload(&ctx, &json_f32(&case["scales"]).iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>());
let offset = form.has_offset.then(|| {
upload(
&ctx,
&json_f32(&case["offset"])
.iter()
.flat_map(|x| x.to_le_bytes())
.collect::<Vec<u8>>(),
)
upload(&ctx, &json_f32(&case["offset"]).iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>())
});
let x16: Vec<u8> = case["x"]
.as_array()
.unwrap()
.iter()
.flat_map(|v| (v.as_u64().unwrap() as u16).to_le_bytes())
.collect();
let (x16_b, q8k, q80) = (
upload(&ctx, &x16),
json_bytes(&case["q8k"]),
json_bytes(&case["q80"]),
);
let x16: Vec<u8> =
case["x"].as_array().unwrap().iter().flat_map(|v| (v.as_u64().unwrap() as u16).to_le_bytes()).collect();
let (x16_b, q8k, q80) = (upload(&ctx, &x16), json_bytes(&case["q8k"]), json_bytes(&case["q80"]));
let mut check = |what: &str, plan: sg::Plan, x: &DeviceBuffer<'_>, want: &[f32]| {
let mut y = upload(&ctx, &vec![0xffu8; n_out as usize * 4]);
if form.code_bits == 2
&& matches!(
plan.kernel,
Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8
)
if form.code_bits == 2 && matches!(plan.kernel, Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8)
{
gpu.s2_gemv(&plan, n_in, n_out, x, &codes, &scales, &mut y)
.unwrap();
gpu.s2_gemv(&plan, n_in, n_out, x, &codes, &scales, &mut y).unwrap();
} else {
gpu.s_gemv(
&plan,
&form,
n_in,
n_out,
x,
&codes,
&scales,
offset.as_ref(),
&mut y,
)
.unwrap();
gpu.s_gemv(&plan, &form, n_in, n_out, x, &codes, &scales, offset.as_ref(), &mut y).unwrap();
}
let got = f32s(&download(&y, n_out as usize * 4));
let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs())));
@@ -277,20 +189,11 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() {
let y_fp16 = json_f32(&case["y_fp16"]);
let offset_present = form.has_offset;
if exact {
check(
"s_gemv",
sg::plan_s_gemv(n_in, n_out, &form, offset_present)
.unwrap()
.unwrap(),
&x16_b,
&y_fp16,
);
check("s_gemv", sg::plan_s_gemv(n_in, n_out, &form, offset_present).unwrap().unwrap(), &x16_b, &y_fp16);
}
check(
"s_gemv_split64",
sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset_present)
.unwrap()
.unwrap(),
sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset_present).unwrap().unwrap(),
&x16_b,
&y_fp16,
);
@@ -298,9 +201,7 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() {
let b = upload(&ctx, &q8k);
check(
"q8k_split",
sg::plan_s_gemv_q8k_split(n_in, n_out, &form)
.unwrap()
.unwrap(),
sg::plan_s_gemv_q8k_split(n_in, n_out, &form).unwrap().unwrap(),
&b,
&json_f32(&case["y_q8k"]),
);
@@ -309,9 +210,7 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() {
let b = upload(&ctx, &q80);
check(
"q8_0_split",
sg::plan_s_gemv_q8_0_split(n_in, n_out, &form)
.unwrap()
.unwrap(),
sg::plan_s_gemv_q8_0_split(n_in, n_out, &form).unwrap().unwrap(),
&b,
&json_f32(&case["y_q80"]),
);
@@ -327,18 +226,18 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() {
#[path = "closed_kernels_gpu_smoke/impl_rng.rs"]
mod impl_rng;
#[allow(unused_imports)]
use impl_rng::f16_bits;
#[allow(unused_imports)]
use impl_rng::upload;
#[allow(unused_imports)]
use impl_rng::download;
#[allow(unused_imports)]
use impl_rng::f16_bits;
#[allow(unused_imports)]
use impl_rng::f32s;
#[allow(unused_imports)]
use impl_rng::open;
#[allow(unused_imports)]
use impl_rng::zero_kv;
#[allow(unused_imports)]
use impl_rng::json_bytes;
#[allow(unused_imports)]
use impl_rng::json_f32;
#[allow(unused_imports)]
use impl_rng::open;
#[allow(unused_imports)]
use impl_rng::upload;
#[allow(unused_imports)]
use impl_rng::zero_kv;
@@ -5,18 +5,12 @@ use super::*;
impl Rng {
pub(super) fn next(&mut self) -> u32 {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 32) as u32
}
/// A standard-normal-ish value (sum of twelve uniforms).
pub(super) fn normal(&mut self) -> f32 {
(0..12)
.map(|_| (self.next() >> 8) as f32 / 16_777_216.0)
.sum::<f32>()
- 6.0
(0..12).map(|_| (self.next() >> 8) as f32 / 16_777_216.0).sum::<f32>() - 6.0
}
}
@@ -54,18 +48,11 @@ pub(super) fn download(b: &DeviceBuffer<'_>, len: usize) -> Vec<u8> {
all
}
pub(super) fn f32s(bytes: &[u8]) -> Vec<f32> {
bytes
.chunks_exact(4)
.map(|c| f32::from_le_bytes(c.try_into().unwrap()))
.collect()
bytes.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect()
}
pub(super) fn open<'c>(ctx: &'c Context<'c>, program: Program) -> ClosedKernels<'c> {
ClosedKernels::open(ctx, program).unwrap_or_else(|e| {
panic!(
"{} open failed ({e}); TODO-ROOT: build PTX and freeze the pin",
program.name()
)
})
ClosedKernels::open(ctx, program)
.unwrap_or_else(|e| panic!("{} open failed ({e}); TODO-ROOT: build PTX and freeze the pin", program.name()))
}
pub(super) fn zero_kv<'c>(ctx: &'c Context<'c>) -> DeviceBuffer<'c> {
@@ -73,16 +60,8 @@ pub(super) fn zero_kv<'c>(ctx: &'c Context<'c>) -> DeviceBuffer<'c> {
}
pub(super) fn json_bytes(v: &serde_json::Value) -> Vec<u8> {
v.as_array()
.unwrap()
.iter()
.map(|x| x.as_u64().unwrap() as u8)
.collect()
v.as_array().unwrap().iter().map(|x| x.as_u64().unwrap() as u8).collect()
}
pub(super) fn json_f32(v: &serde_json::Value) -> Vec<f32> {
v.as_array()
.unwrap()
.iter()
.map(|x| x.as_f64().unwrap() as f32)
.collect()
v.as_array().unwrap().iter().map(|x| x.as_f64().unwrap() as f32).collect()
}
+1 -3
View File
@@ -9,9 +9,7 @@ static TOTALS: Mutex<Vec<(&'static str, usize, &'static str, Duration, u32)>> =
/// Whether per-command timing is on (both switches set).
pub fn enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| {
crate::bringup_trace_enabled() && std::env::var_os("LELEKA_PREFILL_PROFILE_SYNC").is_some()
})
*ON.get_or_init(|| crate::bringup_trace_enabled() && std::env::var_os("LELEKA_PREFILL_PROFILE_SYNC").is_some())
}
pub(crate) fn add(producer: &'static str, index: usize, label: &'static str, elapsed: Duration) {
if let Ok(mut totals) = TOTALS.lock() {
-1
View File
@@ -13,7 +13,6 @@ use std::sync::atomic::{AtomicUsize, Ordering};
static STREAMS: Mutex<Vec<usize>> = Mutex::new(Vec::new());
static BACKGROUND: AtomicUsize = AtomicUsize::new(0);
pub(crate) fn register(stream: usize) {
if stream == 0 {
return;
+47 -8
View File
@@ -56,7 +56,10 @@ pub(crate) fn enabled() -> bool {
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod device {
use super::evaluate;
use crate::ffi::{BufferHandle, deferred_status::{Api, HostBuffer}};
use crate::ffi::{
BufferHandle,
deferred_status::{Api, HostBuffer},
};
use crate::{Context, Error, Result};
use std::cell::RefCell;
use std::collections::VecDeque;
@@ -111,10 +114,19 @@ mod device {
}
/// Step 1 of a deferred run: zero the status words, stream ordered.
pub(crate) fn begin(context: &Context<'_>, status: BufferHandle, bytes: usize, stream: usize, slot_bytes: usize) -> Result<()> {
pub(crate) fn begin(
context: &Context<'_>,
status: BufferHandle,
bytes: usize,
stream: usize,
slot_bytes: usize,
) -> Result<()> {
STATE.with(|cell| {
let mut guard = cell.borrow_mut();
if guard.as_ref().is_some_and(|s| s.context != std::ptr::from_ref(context) as usize || s.slots[0].host.bytes() < bytes) {
if guard
.as_ref()
.is_some_and(|s| s.context != std::ptr::from_ref(context) as usize || s.slots[0].host.bytes() < bytes)
{
if guard.as_ref().is_some_and(|s| !s.live.is_empty()) {
return Err(Error::ContextMismatch);
}
@@ -152,7 +164,13 @@ mod device {
for other in crate::compute_drain::streams_except(stream) {
st.api.wait_stream(other, slot.event)?;
}
st.live.push_back(Check { slot: slot_index, bytes, stride, order: order.to_vec(), labels: labels.to_vec() });
st.live.push_back(Check {
slot: slot_index,
bytes,
stride,
order: order.to_vec(),
labels: labels.to_vec(),
});
Ok(())
})
}
@@ -189,14 +207,26 @@ mod device {
#[allow(unused_imports)]
pub(crate) use device::{begin, finish, pending, resolve};
#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))]
#[cfg(not(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
)))]
mod unsupported {
use crate::ffi::BufferHandle;
use crate::{Context, Error, Result};
pub(crate) fn begin(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn finish(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize, _: &[usize], _: &[&'static str]) -> Result<()> {
pub(crate) fn finish(
_: &Context<'_>,
_: BufferHandle,
_: usize,
_: usize,
_: usize,
_: &[usize],
_: &[&'static str],
) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn resolve(_: &Context<'_>) -> Result<()> {
@@ -206,10 +236,19 @@ mod unsupported {
0
}
}
#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))]
#[cfg(not(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
)))]
pub(crate) use unsupported::{begin, finish, pending, resolve};
#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
#[cfg(all(
test,
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[path = "deferred_status_gpu.rs"]
mod gpu_tests;
+10 -2
View File
@@ -148,13 +148,21 @@ impl Api {
// SAFETY: validated extent of a live allocation of the current context; stream handle of the same context.
check("cuMemsetD8Async", unsafe { (self.memset)(buffer.0, 0, bytes, stream as Handle) })
}
pub(crate) fn read_async(&self, host: &HostBuffer, source: BufferHandle, bytes: usize, stream: usize) -> Result<()> {
pub(crate) fn read_async(
&self,
host: &HostBuffer,
source: BufferHandle,
bytes: usize,
stream: usize,
) -> Result<()> {
if bytes == 0 || bytes > host.bytes {
return Err(Error::InvalidSize);
}
source.validate_extent(bytes)?;
// SAFETY: pinned destination of at least `bytes`, validated device extent, same-context stream; the caller keeps both
// alive and does not read or reuse the host buffer before the event recorded after this copy has completed.
check("cuMemcpyDtoHAsync_v2", unsafe { (self.dtoh)(host.address as *mut c_void, source.0, bytes, stream as Handle) })
check("cuMemcpyDtoHAsync_v2", unsafe {
(self.dtoh)(host.address as *mut c_void, source.0, bytes, stream as Handle)
})
}
}
+20 -9
View File
@@ -96,7 +96,9 @@ pub fn min_compute_capability(experimental_sm60: bool) -> (u32, &'static str) {
pub fn check_compute_capability(name: &str, major: u32, minor: u32, experimental_sm60: bool) -> Result<(), String> {
let (min, need) = min_compute_capability(experimental_sm60);
if major * 10 + minor < min {
return Err(format!("device {name} reports compute capability {major}.{minor}; Strata needs compute capability {need}"));
return Err(format!(
"device {name} reports compute capability {major}.{minor}; Strata needs compute capability {need}"
));
}
Ok(())
}
@@ -117,10 +119,13 @@ mod tests {
assert_eq!(big[0], PoisonLaunch { float_offset: 0, blocks: (3u64 << 30).div_ceil(256), n_floats: 3u64 << 30 });
// the slicing with a small max: 1000 floats -> 4 blocks, max 3 -> two launches
let l = poison_launches(4000, 3);
assert_eq!(l, vec![
PoisonLaunch { float_offset: 0, blocks: 3, n_floats: 1000 },
PoisonLaunch { float_offset: 768, blocks: 1, n_floats: 232 },
]);
assert_eq!(
l,
vec![
PoisonLaunch { float_offset: 0, blocks: 3, n_floats: 1000 },
PoisonLaunch { float_offset: 768, blocks: 1, n_floats: 232 },
]
);
assert!(poison_launches(0, 3).is_empty());
assert!(poison_launches(3, 3).is_empty(), "less than one float is nothing to poison");
}
@@ -138,15 +143,18 @@ mod tests {
#[test]
fn golden_poison_executed_on_the_host_shim_matches_the_model() {
let g: serde_json::Value = serde_json::from_str(include_str!("../oracle/fixtures/misc_kernels_golden.json")).unwrap();
let g: serde_json::Value =
serde_json::from_str(include_str!("../oracle/fixtures/misc_kernels_golden.json")).unwrap();
let p = &g["poison"];
let (bytes, words, max_blocks) = (p["bytes"].as_u64().unwrap(), p["words"].as_u64().unwrap() as usize, p["max_blocks"].as_u64().unwrap());
let (bytes, words, max_blocks) =
(p["bytes"].as_u64().unwrap(), p["words"].as_u64().unwrap() as usize, p["max_blocks"].as_u64().unwrap());
let mut mem = vec![0xdead_beefu32; words];
for launch in poison_launches(bytes, max_blocks) {
poison_model(&mut mem, &launch);
}
let raw: Vec<u8> = mem.iter().flat_map(|w| w.to_le_bytes()).collect();
let fnv = raw.iter().fold(1_469_598_103_934_665_603u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(1_099_511_628_211));
let fnv =
raw.iter().fold(1_469_598_103_934_665_603u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(1_099_511_628_211));
assert_eq!(format!("{fnv:x}"), p["hash"].as_str().unwrap());
}
@@ -161,7 +169,10 @@ mod tests {
assert!(a.alloc(8, 3).unwrap_err().contains("power of two"));
assert!(a.alloc(8, 0).unwrap_err().contains("power of two"));
let err = a.alloc(700, 8).unwrap_err();
assert_eq!(err, "DeviceArena out of memory: asked for 700 B at offset 376 (align 8) in a 1000 B region - the plan from P1.S9 did not close");
assert_eq!(
err,
"DeviceArena out of memory: asked for 700 B at offset 376 (align 8) in a 1000 B region - the plan from P1.S9 did not close"
);
assert_eq!(a.used(), 369, "a refused allocation leaves the arena untouched");
assert!(a.alloc(u64::MAX, 8).is_err());
assert_eq!(DeviceArenaPlan::new(0).unwrap_err(), "DeviceArena of 0 bytes");
+11 -2
View File
@@ -121,7 +121,10 @@ pub struct DeviceSlice<'ctx> {
enum SliceBacking<'ctx> {
Own(DeviceBuffer<'ctx>),
/// `view` is a borrowed alias of a range of `slab` (dropping it frees nothing); `slab` keeps the memory alive.
Carved { slab: Rc<DeviceBuffer<'ctx>>, view: DeviceBuffer<'ctx> },
Carved {
slab: Rc<DeviceBuffer<'ctx>>,
view: DeviceBuffer<'ctx>,
},
}
impl<'ctx> DeviceSlice<'ctx> {
@@ -237,7 +240,13 @@ impl<'ctx> DeviceBuffer<'ctx> {
/// alive for as long as the alias is used: [`DeviceSlice`] holds the slab for it.
pub(crate) fn view(&self, offset: usize, len: usize) -> Result<DeviceBuffer<'ctx>> {
let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, len)?;
Ok(DeviceBuffer { context: self.context, handle: Some(handle), bytes: len, _thread: std::marker::PhantomData, borrowed: true })
Ok(DeviceBuffer {
context: self.context,
handle: Some(handle),
bytes: len,
_thread: std::marker::PhantomData,
borrowed: true,
})
}
}
+12 -1
View File
@@ -110,7 +110,18 @@ fn packing_the_dense_weights_takes_much_less_device_memory_than_one_allocation_e
sizes.extend([6_600_000, 3_300_000, 3_300_000, 10_240, 10_240, 4096, 4096, 4096, 4096]);
}
for _ in 0..12 {
sizes.extend([4_900_000, 1_400_000, 1_400_000, 2_600_000, 650_000, 4_900_000, 2560 * 4, 2560 * 4, 2560 * 4, 2560 * 4]);
sizes.extend([
4_900_000,
1_400_000,
1_400_000,
2_600_000,
650_000,
4_900_000,
2560 * 4,
2560 * 4,
2560 * 4,
2560 * 4,
]);
}
sizes.extend(std::iter::repeat_n(5 * MIB / 2, 48));
sizes.extend(std::iter::repeat_n(330_000, 97 * 3));
+71 -126
View File
@@ -106,62 +106,62 @@ pub struct PtxPin {
pub const PINS: [PtxPin; 6] = [
PtxPin {
source_sha256: [
75, 46, 214, 128, 8, 243, 170, 135, 173, 241, 68, 92, 96, 139, 174, 228, 67, 154, 12,
164, 18, 19, 172, 46, 40, 10, 112, 232, 132, 72, 180, 32,
75, 46, 214, 128, 8, 243, 170, 135, 173, 241, 68, 92, 96, 139, 174, 228, 67, 154, 12, 164, 18, 19, 172, 46,
40, 10, 112, 232, 132, 72, 180, 32,
],
ptx_sha256: [
116, 102, 91, 1, 111, 222, 157, 196, 245, 10, 54, 230, 44, 191, 46, 87, 140, 115, 94,
72, 227, 190, 81, 183, 7, 52, 233, 229, 57, 66, 205, 231,
116, 102, 91, 1, 111, 222, 157, 196, 245, 10, 54, 230, 44, 191, 46, 87, 140, 115, 94, 72, 227, 190, 81,
183, 7, 52, 233, 229, 57, 66, 205, 231,
],
},
PtxPin {
source_sha256: [
147, 164, 86, 148, 37, 12, 28, 154, 190, 203, 55, 41, 64, 186, 82, 225, 88, 136, 123,
203, 234, 88, 19, 50, 21, 145, 14, 38, 169, 106, 113, 116,
147, 164, 86, 148, 37, 12, 28, 154, 190, 203, 55, 41, 64, 186, 82, 225, 88, 136, 123, 203, 234, 88, 19, 50,
21, 145, 14, 38, 169, 106, 113, 116,
],
ptx_sha256: [
67, 195, 8, 150, 8, 48, 131, 62, 41, 50, 153, 7, 226, 123, 229, 32, 62, 243, 188, 137,
204, 125, 10, 145, 118, 39, 13, 193, 135, 50, 214, 0,
67, 195, 8, 150, 8, 48, 131, 62, 41, 50, 153, 7, 226, 123, 229, 32, 62, 243, 188, 137, 204, 125, 10, 145,
118, 39, 13, 193, 135, 50, 214, 0,
],
},
PtxPin {
source_sha256: [
171, 135, 59, 249, 57, 245, 35, 80, 35, 221, 146, 215, 6, 200, 129, 74, 183, 143, 149,
90, 177, 94, 18, 147, 184, 224, 185, 108, 170, 92, 193, 83,
171, 135, 59, 249, 57, 245, 35, 80, 35, 221, 146, 215, 6, 200, 129, 74, 183, 143, 149, 90, 177, 94, 18,
147, 184, 224, 185, 108, 170, 92, 193, 83,
],
ptx_sha256: [
79, 113, 231, 32, 224, 202, 149, 13, 50, 27, 163, 203, 178, 0, 130, 202, 71, 62, 152,
57, 183, 109, 8, 137, 142, 149, 182, 98, 59, 255, 254, 80,
79, 113, 231, 32, 224, 202, 149, 13, 50, 27, 163, 203, 178, 0, 130, 202, 71, 62, 152, 57, 183, 109, 8, 137,
142, 149, 182, 98, 59, 255, 254, 80,
],
},
PtxPin {
source_sha256: [
119, 197, 14, 91, 175, 248, 66, 227, 31, 13, 113, 98, 74, 87, 6, 244, 110, 215, 74, 86,
205, 252, 94, 66, 17, 8, 109, 46, 240, 134, 113, 197,
119, 197, 14, 91, 175, 248, 66, 227, 31, 13, 113, 98, 74, 87, 6, 244, 110, 215, 74, 86, 205, 252, 94, 66,
17, 8, 109, 46, 240, 134, 113, 197,
],
ptx_sha256: [
26, 184, 184, 21, 110, 140, 130, 65, 49, 192, 12, 236, 218, 23, 127, 229, 125, 116, 178,
134, 160, 43, 126, 90, 253, 250, 57, 172, 173, 170, 51, 230,
26, 184, 184, 21, 110, 140, 130, 65, 49, 192, 12, 236, 218, 23, 127, 229, 125, 116, 178, 134, 160, 43, 126,
90, 253, 250, 57, 172, 173, 170, 51, 230,
],
},
PtxPin {
source_sha256: [
198, 93, 153, 26, 217, 254, 112, 1, 1, 206, 1, 42, 128, 201, 79, 199, 222, 88, 33, 23,
250, 227, 87, 197, 238, 168, 149, 67, 112, 25, 93, 143,
198, 93, 153, 26, 217, 254, 112, 1, 1, 206, 1, 42, 128, 201, 79, 199, 222, 88, 33, 23, 250, 227, 87, 197,
238, 168, 149, 67, 112, 25, 93, 143,
],
ptx_sha256: [
86, 35, 165, 174, 155, 46, 189, 47, 160, 16, 195, 52, 54, 127, 252, 84, 135, 154, 198,
223, 118, 174, 240, 131, 129, 219, 211, 43, 15, 126, 243, 17,
86, 35, 165, 174, 155, 46, 189, 47, 160, 16, 195, 52, 54, 127, 252, 84, 135, 154, 198, 223, 118, 174, 240,
131, 129, 219, 211, 43, 15, 126, 243, 17,
],
},
PtxPin {
source_sha256: [
212, 254, 34, 27, 17, 86, 157, 183, 50, 71, 100, 75, 183, 145, 24, 179, 77, 4, 11, 73,
193, 72, 151, 224, 186, 193, 88, 220, 212, 202, 53, 110,
212, 254, 34, 27, 17, 86, 157, 183, 50, 71, 100, 75, 183, 145, 24, 179, 77, 4, 11, 73, 193, 72, 151, 224,
186, 193, 88, 220, 212, 202, 53, 110,
],
ptx_sha256: [
25, 58, 221, 92, 180, 72, 245, 225, 147, 242, 15, 242, 72, 202, 68, 89, 171, 185, 98,
180, 114, 102, 60, 0, 209, 137, 65, 49, 59, 250, 62, 188,
25, 58, 221, 92, 180, 72, 245, 225, 147, 242, 15, 242, 72, 202, 68, 89, 171, 185, 98, 180, 114, 102, 60, 0,
209, 137, 65, 49, 59, 250, 62, 188,
],
},
];
@@ -171,12 +171,7 @@ pub const PINS: [PtxPin; 6] = [
/// previous source, so [`admit`] refuses them. The server-side reseal (nvcc 13.2.86, group `experimental`,
/// `scripts/gpu-bringup/reseal_own.py --plan docs/cuda-seal-plan-additions-experimental.json`) refreshes both pin
/// fields and empties this list; the unit test `pending_reseal_lists_exactly_the_unsealed_sources` forces that.
pub const PENDING_RESEAL: &[Program] = &[
Program::KvQ4,
Program::KvQ8,
Program::KvStream,
Program::QsaAttn,
];
pub const PENDING_RESEAL: &[Program] = &[Program::KvQ4, Program::KvQ8, Program::KvStream, Program::QsaAttn];
// ------------------------------------------------------------------------------------- entry signatures
@@ -208,26 +203,10 @@ pub const Q4_APPEND_STEP: usize = 1;
pub const Q4_APPEND_BATCH: usize = 2;
pub const Q4_GATHER_STEP: usize = 3;
pub static KV_Q4_ENTRIES: [Entry; 4] = [
Entry {
name: c"leleka_fwht256_f32",
block: [32, 4, 1],
args: &[P, P, L],
},
Entry {
name: c"leleka_kv_append_q4_step",
block: [32, 1, 1],
args: &[P, P, P, P, P, P, I, I, I, N, N],
},
Entry {
name: c"leleka_kv_append_q4_batch",
block: [32, 1, 1],
args: &[P, P, P, L, P, P, I, I, I, I, N, N, N, N],
},
Entry {
name: c"leleka_kv_gather_q4_step",
block: [32, 4, 1],
args: &[P, P, P, P, P, I, I, I, P, P],
},
Entry { name: c"leleka_fwht256_f32", block: [32, 4, 1], args: &[P, P, L] },
Entry { name: c"leleka_kv_append_q4_step", block: [32, 1, 1], args: &[P, P, P, P, P, P, I, I, I, N, N] },
Entry { name: c"leleka_kv_append_q4_batch", block: [32, 1, 1], args: &[P, P, P, L, P, P, I, I, I, I, N, N, N, N] },
Entry { name: c"leleka_kv_gather_q4_step", block: [32, 4, 1], args: &[P, P, P, P, P, I, I, I, P, P] },
];
pub const Q8_APPEND_STEP: usize = 0;
@@ -238,11 +217,7 @@ pub static KV_Q8_ENTRIES: [Entry; 2] = [
block: [64, 1, 1],
args: &[N, P, N, P, P, P, N, P, I, I, I, N, N, N, N],
},
Entry {
name: c"leleka_kv_gather_q8_step",
block: [256, 1, 1],
args: &[P, P, P, P, P, P, P, I, I, I, P, P],
},
Entry { name: c"leleka_kv_gather_q8_step", block: [256, 1, 1], args: &[P, P, P, P, P, P, P, I, I, I, P, P] },
];
pub const STREAM_RESET: usize = 0;
@@ -251,50 +226,27 @@ pub const STREAM_COPY: usize = 2;
pub const RING_TABLE: usize = 3;
pub const COPY_U4: usize = 4;
pub static KV_STREAM_ENTRIES: [Entry; 5] = [
Entry {
name: c"leleka_kv_stream_reset",
block: [256, 1, 1],
args: &[P, P, P, P, P, L, L],
},
Entry {
name: c"leleka_kv_stream_resolve",
block: [1024, 1, 1],
args: &[P, P, P, P, P, P, P, L, P, P, I, I, I],
},
Entry { name: c"leleka_kv_stream_reset", block: [256, 1, 1], args: &[P, P, P, P, P, L, L] },
Entry { name: c"leleka_kv_stream_resolve", block: [1024, 1, 1], args: &[P, P, P, P, P, P, P, L, P, P, I, I, I] },
Entry {
name: c"leleka_kv_stream_copy",
block: [128, 1, 1],
args: &[P, P, P, P, N, N, N, P, N, N, N, I, I, I, I, I],
},
Entry {
name: c"leleka_kv_ring_table",
block: [256, 1, 1],
args: &[P, L, L],
},
Entry {
name: c"leleka_kv_copy_u4",
block: [128, 1, 1],
args: &[P, P, L],
},
Entry { name: c"leleka_kv_ring_table", block: [256, 1, 1], args: &[P, L, L] },
Entry { name: c"leleka_kv_copy_u4", block: [128, 1, 1], args: &[P, P, L] },
];
pub const KEYLESS_ROUTE: usize = 0;
pub static KEYLESS_ENTRIES: [Entry; 1] = [Entry {
name: c"leleka_keyless_route_query",
block: [256, 1, 1],
args: &[P, P, I],
}];
pub static KEYLESS_ENTRIES: [Entry; 1] =
[Entry { name: c"leleka_keyless_route_query", block: [256, 1, 1], args: &[P, P, I] }];
pub const ATTN_CHUNK_M2: usize = 0;
pub const ATTN_CHUNK_M3: usize = 1;
pub const ATTN_CHUNK_M4: usize = 2;
pub const ATTN_MERGE: usize = 3;
pub static QSA_ATTN_ENTRIES: [Entry; 4] = [
Entry {
name: c"leleka_qsa_attn_chunk_m2",
block: [256, 1, 1],
args: &[P, P, P, P, P, P, I, I, P, P, P, I, I, L],
},
Entry { name: c"leleka_qsa_attn_chunk_m2", block: [256, 1, 1], args: &[P, P, P, P, P, P, I, I, P, P, P, I, I, L] },
Entry {
name: c"leleka_qsa_attn_chunk_m3",
block: [256, 1, 1],
@@ -305,19 +257,12 @@ pub static QSA_ATTN_ENTRIES: [Entry; 4] = [
block: [256, 1, 1],
args: &[P, P, P, P, P, P, N, I, P, P, I, I, P, P, P, I, I, L],
},
Entry {
name: c"leleka_qsa_attn_merge",
block: [256, 1, 1],
args: &[P, P, P, I, P, L],
},
Entry { name: c"leleka_qsa_attn_merge", block: [256, 1, 1], args: &[P, P, P, I, P, L] },
];
pub const CVEC_APPLY: usize = 0;
pub static CVEC_ENTRIES: [Entry; 1] = [Entry {
name: c"leleka_cvec_apply",
block: [256, 1, 1],
args: &[P, P, P, P, I, L, I, I, L, N, L, N, L, I],
}];
pub static CVEC_ENTRIES: [Entry; 1] =
[Entry { name: c"leleka_cvec_apply", block: [256, 1, 1], args: &[P, P, P, P, I, L, I, I, L, N, L, N, L, I] }];
#[allow(dead_code)]
const _: Arg = F; // `F32` arguments exist in the ABI (the attention scale is a compile-time constant here)
@@ -361,47 +306,47 @@ mod tests;
mod impl_mode;
#[allow(unused_imports)]
pub(crate) use impl_mode::invalid;
pub use impl_mode::admit;
#[allow(unused_imports)]
pub use impl_mode::admit_ptx;
#[allow(unused_imports)]
pub use impl_mode::source_is_sealed;
#[allow(unused_imports)]
pub use impl_mode::admit;
#[allow(unused_imports)]
use impl_mode::grid_x;
#[allow(unused_imports)]
use impl_mode::grid_yz;
#[allow(unused_imports)]
pub(crate) use impl_mode::invalid;
#[allow(unused_imports)]
pub use impl_mode::source_is_sealed;
mod impl_kvshape;
#[allow(unused_imports)]
pub use impl_kvshape::fwht_grid;
#[allow(unused_imports)]
pub use impl_kvshape::fwht_bytes;
#[allow(unused_imports)]
pub use impl_kvshape::q4_step_grid;
#[allow(unused_imports)]
pub use impl_kvshape::q4_batch_grid;
#[allow(unused_imports)]
pub use impl_kvshape::q4_gather_grid;
#[allow(unused_imports)]
pub use impl_kvshape::q8_step_grid;
#[allow(unused_imports)]
pub use impl_kvshape::q8_gather_grid;
#[allow(unused_imports)]
pub use impl_kvshape::copy_u4_grid;
#[allow(unused_imports)]
pub use impl_kvshape::check_stream_resolve;
#[allow(unused_imports)]
use impl_kvshape::stream_error_text;
#[allow(unused_imports)]
pub use impl_kvshape::keyless_grid;
#[allow(unused_imports)]
pub use impl_kvshape::keyless_matrices_bytes;
#[allow(unused_imports)]
pub use impl_kvshape::cvec_grid;
#[allow(unused_imports)]
pub use impl_kvshape::attn_chunk_grid;
#[allow(unused_imports)]
pub use impl_kvshape::attn_merge_grid;
#[allow(unused_imports)]
pub use impl_kvshape::attn_scratch_floats;
#[allow(unused_imports)]
pub use impl_kvshape::check_stream_resolve;
#[allow(unused_imports)]
pub use impl_kvshape::copy_u4_grid;
#[allow(unused_imports)]
pub use impl_kvshape::cvec_grid;
#[allow(unused_imports)]
pub use impl_kvshape::fwht_bytes;
#[allow(unused_imports)]
pub use impl_kvshape::fwht_grid;
#[allow(unused_imports)]
pub use impl_kvshape::keyless_grid;
#[allow(unused_imports)]
pub use impl_kvshape::keyless_matrices_bytes;
#[allow(unused_imports)]
pub use impl_kvshape::q4_batch_grid;
#[allow(unused_imports)]
pub use impl_kvshape::q4_gather_grid;
#[allow(unused_imports)]
pub use impl_kvshape::q4_step_grid;
#[allow(unused_imports)]
pub use impl_kvshape::q8_gather_grid;
#[allow(unused_imports)]
pub use impl_kvshape::q8_step_grid;
#[allow(unused_imports)]
use impl_kvshape::stream_error_text;
@@ -3,14 +3,9 @@
#[allow(unused_imports)]
use super::*;
impl KvShape {
pub const fn real() -> Self {
Self {
kv_heads: 2,
head_dim: 256,
page_size: 4,
}
Self { kv_heads: 2, head_dim: 256, page_size: 4 }
}
pub fn as_qsa(&self) -> QsaShapes {
let mut s = QsaShapes::real();
@@ -24,8 +19,7 @@ impl KvShape {
if self.kv_heads == 0 || self.page_size == 0 || self.head_dim == 0 {
return invalid("KV shape needs positive heads, head_dim and page_size");
}
if u64::from(self.kv_heads) > MAX_GRID_YZ || self.page_size > 1 << 20 || self.kv_heads > 64
{
if u64::from(self.kv_heads) > MAX_GRID_YZ || self.page_size > 1 << 20 || self.kv_heads > 64 {
return invalid("KV shape is beyond the closed programs' limits");
}
Ok(())
@@ -85,25 +79,16 @@ pub fn q4_step_grid(shape: &KvShape) -> Result<Grid> {
}
pub fn q4_batch_grid(tokens: u64, shape: &KvShape) -> Result<Grid> {
shape.check_q4()?;
Ok([
grid_x(tokens)?,
shape.kv_heads,
shape.head_dim / q4_0::QK4_0 as u32,
])
Ok([grid_x(tokens)?, shape.kv_heads, shape.head_dim / q4_0::QK4_0 as u32])
}
pub fn q4_gather_grid(max_ids: u64, shape: &KvShape) -> Result<Grid> {
shape.check_q4()?;
let blocks =
max_ids * u64::from(shape.kv_heads) * u64::from(shape.head_dim / q4_0::QK4_0 as u32);
let blocks = max_ids * u64::from(shape.kv_heads) * u64::from(shape.head_dim / q4_0::QK4_0 as u32);
Ok([grid_x(blocks.div_ceil(4))?, 1, 1])
}
pub fn q8_step_grid(shape: &KvShape, with_keys: bool) -> Result<Grid> {
shape.check_q8()?;
Ok([
shape.kv_heads,
shape.head_dim / kv_q8::KV_Q8_GROUP as u32,
if with_keys { 2 } else { 1 },
])
Ok([shape.kv_heads, shape.head_dim / kv_q8::KV_Q8_GROUP as u32, if with_keys { 2 } else { 1 }])
}
pub fn q8_gather_grid(max_ids: u64, shape: &KvShape) -> Result<Grid> {
shape.check_q8()?;
@@ -125,13 +110,8 @@ pub fn check_stream_resolve(shape: &KvShape, n_slots: u64, n_q: u64, cap: u64) -
if n_slots > i32::MAX as u64 {
return invalid("streaming resolve has too many slots");
}
leleka_experimental_ref::kv_stream::check_resolve(
&shape.as_qsa(),
n_slots as i64,
n_q as i64,
cap as i64,
)
.map_err(|e| ExperimentalError::Invalid(stream_error_text(e)))
leleka_experimental_ref::kv_stream::check_resolve(&shape.as_qsa(), n_slots as i64, n_q as i64, cap as i64)
.map_err(|e| ExperimentalError::Invalid(stream_error_text(e)))
}
pub(super) fn stream_error_text(e: leleka_experimental_ref::kv_stream::StreamError) -> &'static str {
use leleka_experimental_ref::kv_stream::StreamError as E;
@@ -171,11 +151,7 @@ pub fn attn_chunk_grid(cap: u64, shape: &KvShape, n_q: u64) -> Result<Grid> {
if cap == 0 || cap > i32::MAX as u64 || n_q == 0 || n_q > MAX_GRID_YZ {
return invalid("attention needs a positive cap and 1..=65535 queries");
}
Ok([
grid_x(cap.div_ceil(leleka_experimental_ref::attn::CHUNK as u64))?,
shape.kv_heads,
n_q as u32,
])
Ok([grid_x(cap.div_ceil(leleka_experimental_ref::attn::CHUNK as u64))?, shape.kv_heads, n_q as u32])
}
pub fn attn_merge_grid(shape: &KvShape, n_q: u64) -> Result<Grid> {
shape.check_attn()?;
@@ -3,16 +3,9 @@
#[allow(unused_imports)]
use super::*;
impl Mode {
pub const ALL: [Mode; 6] = [
Mode::KvQ40,
Mode::KvK8V4,
Mode::KvRotatedInt8,
Mode::KeylessVOnly,
Mode::KvStreamed,
Mode::ControlVectors,
];
pub const ALL: [Mode; 6] =
[Mode::KvQ40, Mode::KvK8V4, Mode::KvRotatedInt8, Mode::KeylessVOnly, Mode::KvStreamed, Mode::ControlVectors];
pub const fn name(self) -> &'static str {
match self {
Self::KvQ40 => "kv-q4_0",
@@ -54,14 +47,8 @@ impl OptIn {
}
impl Program {
pub const ALL: [Program; 6] = [
Program::KvQ4,
Program::KvQ8,
Program::KvStream,
Program::Keyless,
Program::QsaAttn,
Program::Cvec,
];
pub const ALL: [Program; 6] =
[Program::KvQ4, Program::KvQ8, Program::KvStream, Program::Keyless, Program::QsaAttn, Program::Cvec];
pub const fn name(self) -> &'static str {
match self {
Self::KvQ4 => "kv_q4",
@@ -122,10 +109,9 @@ impl fmt::Display for ExperimentalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Invalid(message) => f.write_str(message),
Self::NotEnabled(program) => write!(
f,
"experimental program {program} is off: enable one of its modes explicitly"
),
Self::NotEnabled(program) => {
write!(f, "experimental program {program} is off: enable one of its modes explicitly")
}
Self::Unpinned(program) => write!(
f,
"experimental program {program} PTX is not pinned for its checked-in source (TODO-ROOT: pin zero, PTX bytes or source digest differ)"
@@ -150,11 +136,7 @@ pub fn admit_ptx(program: Program, ptx: &'static [u8], pin: &PtxPin) -> Result<(
if pin.source_sha256 == [0; 32] || pin.ptx_sha256 == [0; 32] {
return Err(refuse);
}
if ptx.len() < 2
|| ptx.last() != Some(&0)
|| ptx[..ptx.len() - 1].contains(&0)
|| !ptx.is_ascii()
{
if ptx.len() < 2 || ptx.last() != Some(&0) || ptx[..ptx.len() - 1].contains(&0) || !ptx.is_ascii() {
return Err(refuse);
}
if qwen_ffi::sha256(&ptx[..ptx.len() - 1]) != pin.ptx_sha256 {
+34 -133
View File
@@ -3,17 +3,10 @@
use super::*;
fn count_params(source: &str, name: &str) -> (Vec<&'static str>, u32) {
let at = source
.find(&format!(" {name}("))
.unwrap_or_else(|| panic!("{name} not in source"));
let at = source.find(&format!(" {name}(")).unwrap_or_else(|| panic!("{name} not in source"));
let head = &source[..at];
let decl = head
.rfind("extern \"C\" __global__")
.expect("extern C entry");
let bounds = head[decl..]
.split("__launch_bounds__(")
.nth(1)
.expect("launch bounds");
let decl = head.rfind("extern \"C\" __global__").expect("extern C entry");
let bounds = head[decl..].split("__launch_bounds__(").nth(1).expect("launch bounds");
let threads: u32 = bounds.split(')').next().unwrap().trim().parse().unwrap();
let rest = &source[at + name.len() + 2..];
let close = rest.find(") {").expect("parameter list end");
@@ -55,11 +48,7 @@ fn every_entry_signature_matches_its_cuda_source() {
})
.collect();
assert_eq!(kinds, want, "{name}");
assert_eq!(
threads,
entry.block.iter().product::<u32>(),
"{name} launch bounds"
);
assert_eq!(threads, entry.block.iter().product::<u32>(), "{name} launch bounds");
assert!(entry.args.len() <= MAX_ENTRY_ARGUMENTS, "{name}");
checked += 1;
}
@@ -72,37 +61,19 @@ fn index_constants_point_at_the_named_entries() {
let n = |p: Program, i: usize| p.entries()[i].name.to_str().unwrap();
assert_eq!(n(Program::KvQ4, FWHT256), "leleka_fwht256_f32");
assert_eq!(n(Program::KvQ4, Q4_APPEND_STEP), "leleka_kv_append_q4_step");
assert_eq!(
n(Program::KvQ4, Q4_APPEND_BATCH),
"leleka_kv_append_q4_batch"
);
assert_eq!(n(Program::KvQ4, Q4_APPEND_BATCH), "leleka_kv_append_q4_batch");
assert_eq!(n(Program::KvQ4, Q4_GATHER_STEP), "leleka_kv_gather_q4_step");
assert_eq!(n(Program::KvQ8, Q8_APPEND_STEP), "leleka_kv_append_q8_step");
assert_eq!(n(Program::KvQ8, Q8_GATHER_STEP), "leleka_kv_gather_q8_step");
assert_eq!(n(Program::KvStream, STREAM_RESET), "leleka_kv_stream_reset");
assert_eq!(
n(Program::KvStream, STREAM_RESOLVE),
"leleka_kv_stream_resolve"
);
assert_eq!(n(Program::KvStream, STREAM_RESOLVE), "leleka_kv_stream_resolve");
assert_eq!(n(Program::KvStream, STREAM_COPY), "leleka_kv_stream_copy");
assert_eq!(n(Program::KvStream, RING_TABLE), "leleka_kv_ring_table");
assert_eq!(n(Program::KvStream, COPY_U4), "leleka_kv_copy_u4");
assert_eq!(
n(Program::Keyless, KEYLESS_ROUTE),
"leleka_keyless_route_query"
);
assert_eq!(
n(Program::QsaAttn, ATTN_CHUNK_M2),
"leleka_qsa_attn_chunk_m2"
);
assert_eq!(
n(Program::QsaAttn, ATTN_CHUNK_M3),
"leleka_qsa_attn_chunk_m3"
);
assert_eq!(
n(Program::QsaAttn, ATTN_CHUNK_M4),
"leleka_qsa_attn_chunk_m4"
);
assert_eq!(n(Program::Keyless, KEYLESS_ROUTE), "leleka_keyless_route_query");
assert_eq!(n(Program::QsaAttn, ATTN_CHUNK_M2), "leleka_qsa_attn_chunk_m2");
assert_eq!(n(Program::QsaAttn, ATTN_CHUNK_M3), "leleka_qsa_attn_chunk_m3");
assert_eq!(n(Program::QsaAttn, ATTN_CHUNK_M4), "leleka_qsa_attn_chunk_m4");
assert_eq!(n(Program::QsaAttn, ATTN_MERGE), "leleka_qsa_attn_merge");
assert_eq!(n(Program::Cvec, CVEC_APPLY), "leleka_cvec_apply");
}
@@ -114,36 +85,18 @@ fn every_mode_is_off_by_default_and_programs_need_an_explicit_one() {
assert_eq!(none.digest_text(), "");
for program in Program::ALL {
assert!(!none.enables(program));
assert_eq!(
admit(program, &none),
Err(ExperimentalError::NotEnabled(program.name()))
);
assert_eq!(admit(program, &none), Err(ExperimentalError::NotEnabled(program.name())));
assert!(!program.needed_by().is_empty());
}
let q4 = OptIn::default().with(Mode::KvQ40);
assert!(q4.enables(Program::KvQ4) && q4.enables(Program::QsaAttn));
assert!(
!q4.enables(Program::KvStream)
&& !q4.enables(Program::Cvec)
&& !q4.enables(Program::KvQ8)
);
assert!(!q4.enables(Program::KvStream) && !q4.enables(Program::Cvec) && !q4.enables(Program::KvQ8));
let k = OptIn::default().with(Mode::KeylessVOnly);
assert!(
k.enables(Program::Keyless) && k.enables(Program::KvQ8) && !k.enables(Program::KvQ4)
);
assert_eq!(
OptIn::default()
.with(Mode::KvStreamed)
.with(Mode::KvQ40)
.digest_text(),
"kv-q4_0,kv-streamed"
);
assert!(k.enables(Program::Keyless) && k.enables(Program::KvQ8) && !k.enables(Program::KvQ4));
assert_eq!(OptIn::default().with(Mode::KvStreamed).with(Mode::KvQ40).digest_text(), "kv-q4_0,kv-streamed");
// every mode reaches at least one program, and the names are unique
for mode in Mode::ALL {
assert!(
Program::ALL.iter().any(|p| p.needed_by().contains(&mode)),
"{mode:?}"
);
assert!(Program::ALL.iter().any(|p| p.needed_by().contains(&mode)), "{mode:?}");
}
let names: std::collections::BTreeSet<_> = Mode::ALL.iter().map(|m| m.name()).collect();
assert_eq!(names.len(), Mode::ALL.len());
@@ -152,8 +105,8 @@ fn every_mode_is_off_by_default_and_programs_need_an_explicit_one() {
#[test]
fn sealed_assets_match_their_pins_and_export_every_entry() {
use crate::sealed_ptx::test_support::{
assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul,
without_terminator,
assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter,
with_embedded_nul, without_terminator,
};
let all = OptIn::NONE
.with(Mode::KvQ40)
@@ -173,17 +126,11 @@ fn sealed_assets_match_their_pins_and_export_every_entry() {
assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name());
assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name());
// a program re-synced after the seal (PENDING_RESEAL) keeps its old PTX and refuses to open
let expected = if PENDING_RESEAL.contains(&program) {
Err(ExperimentalError::Unpinned(program.name()))
} else {
Ok(())
};
let expected =
if PENDING_RESEAL.contains(&program) { Err(ExperimentalError::Unpinned(program.name())) } else { Ok(()) };
assert_eq!(admit(program, &all), expected, "{}", program.name());
// the opt-in gate still comes first
assert_eq!(
admit(program, &OptIn::NONE),
Err(ExperimentalError::NotEnabled(program.name()))
);
assert_eq!(admit(program, &OptIn::NONE), Err(ExperimentalError::NotEnabled(program.name())));
// the pin guard still refuses every deviation, on synthetic copies of the real PTX
let refuse = Err(ExperimentalError::Unpinned(program.name()));
assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse);
@@ -194,10 +141,7 @@ fn sealed_assets_match_their_pins_and_export_every_entry() {
let mut wrong_digest = *pin;
wrong_digest.ptx_sha256[0] ^= 1;
assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse);
for zeroed in [
PtxPin { source_sha256: [0; 32], ..*pin },
PtxPin { ptx_sha256: [0; 32], ..*pin },
] {
for zeroed in [PtxPin { source_sha256: [0; 32], ..*pin }, PtxPin { ptx_sha256: [0; 32], ..*pin }] {
assert_eq!(admit_ptx(program, ptx, &zeroed), refuse);
}
}
@@ -214,11 +158,7 @@ fn pending_reseal_lists_exactly_the_unsealed_sources() {
);
}
for (i, program) in PENDING_RESEAL.iter().enumerate() {
assert!(
!PENDING_RESEAL[i + 1..].contains(program),
"{} listed twice",
program.name()
);
assert!(!PENDING_RESEAL[i + 1..].contains(program), "{} listed twice", program.name());
}
}
@@ -235,48 +175,24 @@ fn a_program_whose_source_is_newer_than_its_ptx_refuses_even_with_a_matching_ptx
assert_eq!(admit_ptx(program, program.ptx(), program.pin()), Ok(()));
// ... but they were not built from the checked-in source: admit fails closed
assert!(!source_is_sealed(program));
assert_eq!(
admit(program, &all),
Err(ExperimentalError::Unpinned(program.name()))
);
assert_eq!(admit(program, &all), Err(ExperimentalError::Unpinned(program.name())));
}
}
#[test]
fn a_matching_pin_admits_and_any_difference_refuses() {
static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0";
let pin = PtxPin {
source_sha256: [1; 32],
ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]),
};
let pin = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]) };
assert_eq!(admit_ptx(Program::Cvec, GOOD, &pin), Ok(()));
let wrong = PtxPin {
ptx_sha256: [2; 32],
..pin
};
assert_eq!(
admit_ptx(Program::Cvec, GOOD, &wrong),
Err(ExperimentalError::Unpinned("cvec"))
);
let half = PtxPin {
source_sha256: [0; 32],
..pin
};
assert_eq!(
admit_ptx(Program::Cvec, GOOD, &half),
Err(ExperimentalError::Unpinned("cvec"))
);
let wrong = PtxPin { ptx_sha256: [2; 32], ..pin };
assert_eq!(admit_ptx(Program::Cvec, GOOD, &wrong), Err(ExperimentalError::Unpinned("cvec")));
let half = PtxPin { source_sha256: [0; 32], ..pin };
assert_eq!(admit_ptx(Program::Cvec, GOOD, &half), Err(ExperimentalError::Unpinned("cvec")));
static NO_NUL: &[u8] = b".version 8.7\n";
let p2 = PtxPin {
source_sha256: [1; 32],
ptx_sha256: qwen_ffi::sha256(NO_NUL),
};
let p2 = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(NO_NUL) };
assert!(admit_ptx(Program::Cvec, NO_NUL, &p2).is_err());
static EMBEDDED: &[u8] = b"a\0b\0";
let p3 = PtxPin {
source_sha256: [1; 32],
ptx_sha256: qwen_ffi::sha256(b"a\0b"),
};
let p3 = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(b"a\0b") };
assert!(admit_ptx(Program::Cvec, EMBEDDED, &p3).is_err());
}
@@ -313,11 +229,7 @@ fn kv_geometry_matches_the_originals_host_wrappers() {
assert!(keyless_grid(0, 24).is_err());
assert_eq!(keyless_matrices_bytes(24), 24 * 65_536 * 4);
assert_eq!(cvec_grid(4, 3, 2560), Ok([4, 3, 1]));
assert!(
cvec_grid(4, 3, 4097).is_err()
&& cvec_grid(4, 3, 0).is_err()
&& cvec_grid(0, 3, 2560).is_err()
);
assert!(cvec_grid(4, 3, 4097).is_err() && cvec_grid(4, 3, 0).is_err() && cvec_grid(0, 3, 2560).is_err());
}
#[test]
@@ -335,17 +247,10 @@ fn byte_sizes_agree_with_the_reference_layouts() {
let k8v4 = pool_arrays(KvFormat::K8V4, &q, pages);
assert_eq!(
(k8v4[0].bytes, k8v4[1].bytes, k8v4[2].bytes),
(
s.q8_code_bytes(pages),
s.q8_scale_bytes(pages),
s.q4_bytes(pages)
)
(s.q8_code_bytes(pages), s.q8_scale_bytes(pages), s.q4_bytes(pages))
);
// 576 B per cell and layer for Q4_0, one page = 4 cells
assert_eq!(
kv_pool_bytes(KvFormat::Q4_0, &q, pages),
pages * 4 * 576 + 64
);
assert_eq!(kv_pool_bytes(KvFormat::Q4_0, &q, pages), pages * 4 * 576 + 64);
assert_eq!(s.q4_bytes(pages) * 2, pages * 4 * 576);
assert_eq!(s.gather_scratch_bytes(2048), 2048 * 2 * 256 * 2);
assert_eq!(attn_scratch_floats(2048, &s), 32 * 24 * 258 + 64);
@@ -364,11 +269,7 @@ fn stream_resolve_guards_are_the_originals() {
matches!(check_stream_resolve(&s, 1024, 8, 4096), Err(ExperimentalError::Invalid(m)) if m.contains("distinct blocks"))
);
assert!(check_stream_resolve(&s, 5120, 0, 8).is_err());
let misaligned = KvShape {
kv_heads: 1,
page_size: 1,
..s
};
let misaligned = KvShape { kv_heads: 1, page_size: 1, ..s };
assert!(
matches!(check_stream_resolve(&misaligned, 5120, 1, 8), Err(ExperimentalError::Invalid(m)) if m.contains("16 bytes"))
);
+6 -13
View File
@@ -21,10 +21,10 @@
use crate::{
Context, DeviceBuffer, Error, combine,
experimental::{
self, ATTN_CHUNK_M2, ATTN_CHUNK_M3, ATTN_CHUNK_M4, ATTN_MERGE, Arg, COPY_U4, CVEC_APPLY,
Entry, ExperimentalError, FWHT256, KEYLESS_ROUTE, KvShape, LoadedProgram, OptIn, Program,
Q4_APPEND_BATCH, Q4_APPEND_STEP, Q4_GATHER_STEP, Q8_APPEND_STEP, Q8_GATHER_STEP,
RING_TABLE, Result, STEP_BYTES, STREAM_COPY, STREAM_RESET, STREAM_RESOLVE, admit, invalid,
self, ATTN_CHUNK_M2, ATTN_CHUNK_M3, ATTN_CHUNK_M4, ATTN_MERGE, Arg, COPY_U4, CVEC_APPLY, Entry,
ExperimentalError, FWHT256, KEYLESS_ROUTE, KvShape, LoadedProgram, OptIn, Program, Q4_APPEND_BATCH,
Q4_APPEND_STEP, Q4_GATHER_STEP, Q8_APPEND_STEP, Q8_GATHER_STEP, RING_TABLE, Result, STEP_BYTES, STREAM_COPY,
STREAM_RESET, STREAM_RESOLVE, admit, invalid,
},
ffi,
};
@@ -82,16 +82,9 @@ pub struct StreamMap<'b, 'c> {
/// The pool arrays an experimental attention mode reads.
pub enum AttnPools<'b, 'c> {
/// Mode 2: Q4_0 keys and values.
Q4 {
k_q4: &'b DeviceBuffer<'c>,
v_q4: &'b DeviceBuffer<'c>,
},
Q4 { k_q4: &'b DeviceBuffer<'c>, v_q4: &'b DeviceBuffer<'c> },
/// Mode 3: INT8 keys, Q4_0 values.
K8V4 {
k_q: &'b DeviceBuffer<'c>,
k_scale: &'b DeviceBuffer<'c>,
v_q4: &'b DeviceBuffer<'c>,
},
K8V4 { k_q: &'b DeviceBuffer<'c>, k_scale: &'b DeviceBuffer<'c>, v_q4: &'b DeviceBuffer<'c> },
/// Mode 4: V-only INT8; keys rebuilt by RoPE from the value rows (cos/sin `[cell][32]`, optional M-RoPE
/// positions `[cell][3]`).
Keyless {
@@ -3,15 +3,10 @@
#[allow(unused_imports)]
use super::*;
impl Context<'_> {
/// Opt-in and pin gates, then load and cache the module once. Refuses without touching the driver while the
/// pin is zero or the mode is off.
pub(crate) fn experimental_program(
&self,
program: Program,
opt_in: &OptIn,
) -> Result<LoadedProgram> {
pub(crate) fn experimental_program(&self, program: Program, opt_in: &OptIn) -> Result<LoadedProgram> {
admit(program, opt_in)?;
if let Some(loaded) = self.experimental[program as usize].get() {
return Ok(loaded);
@@ -50,8 +45,7 @@ impl Context<'_> {
self.poisoned.set(true);
std::mem::forget(Rc::clone(api));
}
let primary =
combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary");
let primary = combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary");
Err(failure(primary, guard.finish()))
}
}
@@ -3,17 +3,11 @@
#[allow(unused_imports)]
use super::*;
impl<'c> Experimental<'c> {
/// Load (once) and return the cached program. Fails closed with `NotEnabled` / `Unpinned`.
pub fn open(context: &'c Context<'c>, program: Program, opt_in: &OptIn) -> Result<Self> {
let loaded = context.experimental_program(program, opt_in)?;
Ok(Self {
context,
program,
loaded,
})
Ok(Self { context, program, loaded })
}
/// The module is owned by the context and unloaded by `Context::close`.
@@ -29,13 +23,7 @@ impl<'c> Experimental<'c> {
}
pub(in super::super) fn call(&self, entry: usize) -> Call<'_, 'c> {
Call {
gpu: self,
entry,
args: Vec::new(),
kinds: Vec::new(),
admitted: Vec::new(),
}
Call { gpu: self, entry, args: Vec::new(), kinds: Vec::new(), admitted: Vec::new() }
}
/// Launch every entry in order and drain with exactly one synchronize.
@@ -47,38 +35,23 @@ impl<'c> Experimental<'c> {
let guard = context.enter()?;
let mut launch = Ok(());
for l in &mut launches {
launch = context
.driver
.api
.launch_kar_levels(l.function, l.grid, l.block, &mut l.args);
launch = context.driver.api.launch_kar_levels(l.function, l.grid, l.block, &mut l.args);
if launch.is_err() {
break;
}
}
context
.complete_launch(launch, launches, guard)
.map_err(Into::into)
context.complete_launch(launch, launches, guard).map_err(Into::into)
}
// ------------------------------------------------------------------------------------- FWHT-256
/// `fwht256_cuda`: orthonormal Walsh-Hadamard transform of `rows` rows of 256 floats (scale 1/16; the
/// transform is its own inverse). `src` and `dst` must not overlap.
pub fn fwht256(
&self,
src: &DeviceBuffer<'_>,
dst: &mut DeviceBuffer<'_>,
rows: u64,
) -> Result<()> {
pub fn fwht256(&self, src: &DeviceBuffer<'_>, dst: &mut DeviceBuffer<'_>, rows: u64) -> Result<()> {
self.expect(Program::KvQ4)?;
let grid = experimental::fwht_grid(rows)?;
let bytes = experimental::fwht_bytes(rows);
let launch = self
.call(FWHT256)
.ro(src, bytes)?
.rw(dst, bytes)?
.i64(i64_of(rows)?)
.finish(grid)?;
let launch = self.call(FWHT256).ro(src, bytes)?.rw(dst, bytes)?.i64(i64_of(rows)?).finish(grid)?;
self.run(vec![launch])
}
@@ -201,11 +174,7 @@ impl<'c> Experimental<'c> {
pub fn q8_append_step(
&self,
p: &Paged,
keys: Option<(
&mut DeviceBuffer<'_>,
&mut DeviceBuffer<'_>,
&DeviceBuffer<'_>,
)>,
keys: Option<(&mut DeviceBuffer<'_>, &mut DeviceBuffer<'_>, &DeviceBuffer<'_>)>,
v_q: &mut DeviceBuffer<'_>,
v_scale: &mut DeviceBuffer<'_>,
table: &DeviceBuffer<'_>,
@@ -221,18 +190,12 @@ impl<'c> Experimental<'c> {
match keys {
Some((k_q, k_scale, kcur)) => {
c = c.rw(k_q, codes)?.rw(v_q, codes)?.rw(k_scale, scales)?;
c = c
.rw(v_scale, scales)?
.ro(table, p.table_entries * 4)?
.ro(step, STEP_BYTES)?;
c = c.rw(v_scale, scales)?.ro(table, p.table_entries * 4)?.ro(step, STEP_BYTES)?;
c = c.ro(kcur, cell)?;
}
None => {
c = c.null().rw(v_q, codes)?.null().rw(v_scale, scales)?;
c = c
.ro(table, p.table_entries * 4)?
.ro(step, STEP_BYTES)?
.null();
c = c.ro(table, p.table_entries * 4)?.ro(step, STEP_BYTES)?.null();
}
}
let launch = c
@@ -3,10 +3,7 @@
#[allow(unused_imports)]
use super::*;
impl<'c> Experimental<'c> {
/// `kv_gather_q8_step`: dequantize the selected cells into fp16 scratch (K and V of the same pool).
#[allow(clippy::too_many_arguments)] // closed ABI operands
pub fn q8_gather_step(
@@ -49,12 +46,7 @@ impl<'c> Experimental<'c> {
// --------------------------------------------------------------------------------- KV streaming
/// `kv_stream_reset`: every block non-resident, every slot free, clock state zero.
pub fn stream_reset(
&self,
map: &mut StreamMap<'_, '_>,
n_blocks: u64,
n_slots: u64,
) -> Result<()> {
pub fn stream_reset(&self, map: &mut StreamMap<'_, '_>, n_blocks: u64, n_slots: u64) -> Result<()> {
self.expect(Program::KvStream)?;
let launch = map
.bind(self.call(STREAM_RESET), n_blocks, n_slots, false)?
@@ -117,19 +109,12 @@ impl<'c> Experimental<'c> {
for i in 0..4 {
copy = copy.i32(runs.get(i).map_or(0, |r| r.1 as i32));
}
let copy = copy
.i32(runs.len() as i32)
.finish(experimental::STREAM_COPY_GRID)?;
let copy = copy.i32(runs.len() as i32).finish(experimental::STREAM_COPY_GRID)?;
self.run(vec![resolve, copy])
}
/// `kv_ring_table`: the ring layout's fixed block -> slot table (`block % n_slots`).
pub fn ring_table(
&self,
table: &mut DeviceBuffer<'_>,
n_blocks: u64,
n_slots: u64,
) -> Result<()> {
pub fn ring_table(&self, table: &mut DeviceBuffer<'_>, n_blocks: u64, n_slots: u64) -> Result<()> {
self.expect(Program::KvStream)?;
if n_blocks == 0 || n_slots == 0 {
return invalid("kv ring: empty table");
@@ -145,20 +130,10 @@ impl<'c> Experimental<'c> {
/// `leleka_kv_copy_u4`: grid-stride copy of `n_u4` 16-byte units (stands in for `cudaMemcpyAsync` in
/// `kv_ring_restore` / `kv_stage_from_host`; `src` and `dst` must not overlap).
pub fn copy_u4(
&self,
src: &DeviceBuffer<'_>,
dst: &mut DeviceBuffer<'_>,
n_u4: u64,
) -> Result<()> {
pub fn copy_u4(&self, src: &DeviceBuffer<'_>, dst: &mut DeviceBuffer<'_>, n_u4: u64) -> Result<()> {
self.expect(Program::KvStream)?;
let grid = experimental::copy_u4_grid(n_u4)?;
let launch = self
.call(COPY_U4)
.ro(src, n_u4 * 16)?
.rw(dst, n_u4 * 16)?
.i64(i64_of(n_u4)?)
.finish(grid)?;
let launch = self.call(COPY_U4).ro(src, n_u4 * 16)?.rw(dst, n_u4 * 16)?.i64(i64_of(n_u4)?).finish(grid)?;
self.run(vec![launch])
}
@@ -3,10 +3,7 @@
#[allow(unused_imports)]
use super::*;
impl<'c> Experimental<'c> {
// ------------------------------------------------------------------------------------ attention
/// `qsa_decode_attn_batch` for the experimental KV modes: the chunk kernel of `pools`' mode, then the merge,
@@ -59,13 +56,7 @@ impl<'c> Experimental<'c> {
.ro(steps, n_q * STEP_BYTES)?
.i32(kv)
.i32(ps),
AttnPools::Keyless {
v_q,
v_scale,
cos,
sin,
mrope,
} => {
AttnPools::Keyless { v_q, v_scale, cos, sin, mrope } => {
let n_rot = leleka_experimental_ref::keyless::N_ROT as u64;
let c = self
.call(ATTN_CHUNK_M4)
@@ -79,11 +70,7 @@ impl<'c> Experimental<'c> {
Some(m) => c.ro(m, 4)?,
None => c.null(),
};
c.i32(n_rot as i32)
.ro(ids, n_q * cap * 4)?
.ro(steps, n_q * STEP_BYTES)?
.i32(kv)
.i32(ps)
c.i32(n_rot as i32).ro(ids, n_q * cap * 4)?.ro(steps, n_q * STEP_BYTES)?.i32(kv).i32(ps)
}
};
let scratch_bytes = n_q * stride * 4;
@@ -3,7 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl StreamMap<'_, '_> {
/// The first five (or seven, for resolve) pointer arguments of `reset` / `resolve`.
pub(super) fn bind<'g, 'c>(
@@ -20,22 +19,14 @@ impl StreamMap<'_, '_> {
.rw(&*self.slot_ref, n_slots * 4)?
.rw(&*self.ctl, CTL_INTS as u64 * 4)?;
if with_miss {
c = c
.rw(&*self.miss_block, n_slots * 4)?
.rw(&*self.miss_slot, n_slots * 4)?;
c = c.rw(&*self.miss_block, n_slots * 4)?.rw(&*self.miss_slot, n_slots * 4)?;
}
Ok(c)
}
}
impl Call<'_, '_> {
pub(super) fn pointer(
mut self,
buffer: &DeviceBuffer<'_>,
min: u64,
offset: u64,
writes: bool,
) -> Result<Self> {
pub(super) fn pointer(mut self, buffer: &DeviceBuffer<'_>, min: u64, offset: u64, writes: bool) -> Result<Self> {
let context = self.gpu.context;
if context.poisoned.get() {
return Err(Error::ContextPoisoned.into());
@@ -44,20 +35,14 @@ impl Call<'_, '_> {
return Err(Error::ContextMismatch.into());
}
let handle = buffer.handle.ok_or(Error::ContextPoisoned)?;
let min =
usize::try_from(min).or_else(|_| invalid("experimental buffer size exceeds usize"))?;
let min = usize::try_from(min).or_else(|_| invalid("experimental buffer size exceeds usize"))?;
if min == 0 || buffer.bytes < min {
return invalid("experimental buffer is smaller than the geometry requires");
}
handle.validate_projection_extent(buffer.bytes, 16)?;
self.admitted.push(Admitted {
handle,
bytes: buffer.bytes,
writes,
});
self.admitted.push(Admitted { handle, bytes: buffer.bytes, writes });
let at = handle.experimental_offset(offset)?;
self.args
.push(ffi::KarArgument::Scalar64(at.qwen_address()));
self.args.push(ffi::KarArgument::Scalar64(at.qwen_address()));
self.kinds.push(Arg::Ptr);
Ok(self)
}
@@ -93,18 +78,12 @@ impl Call<'_, '_> {
pub(super) fn finish(self, grid: [u32; 3]) -> Result<Launch> {
let entry: &Entry = &self.gpu.program.entries()[self.entry];
let matches = entry.args.len() == self.kinds.len()
&& entry
.args
.iter()
.zip(&self.kinds)
.all(|(want, got)| match (want, got) {
(Arg::PtrOpt, Arg::Ptr | Arg::PtrOpt) => true,
(a, b) => a == b,
});
&& entry.args.iter().zip(&self.kinds).all(|(want, got)| match (want, got) {
(Arg::PtrOpt, Arg::Ptr | Arg::PtrOpt) => true,
(a, b) => a == b,
});
if !matches {
return invalid(
"experimental launch arguments differ from the entry's fixed signature",
);
return invalid("experimental launch arguments differ from the entry's fixed signature");
}
for (i, a) in self.admitted.iter().enumerate() {
for b in &self.admitted[i + 1..] {
@@ -117,21 +96,13 @@ impl Call<'_, '_> {
}
}
}
let function = self.gpu.loaded.functions[self.entry].ok_or(ExperimentalError::Invalid(
"experimental entry is not loaded",
))?;
Ok(Launch {
function,
grid,
block: entry.block,
args: ffi::KarLevelsArgs::new(&self.args)?,
})
let function = self.gpu.loaded.functions[self.entry]
.ok_or(ExperimentalError::Invalid("experimental entry is not loaded"))?;
Ok(Launch { function, grid, block: entry.block, args: ffi::KarLevelsArgs::new(&self.args)? })
}
}
/// A primary driver failure plus the outcome of the mandatory context restore.
pub(super) fn failure(primary: Error, restore: DriverResult<()>) -> ExperimentalError {
combine::<()>(Err(primary), restore)
.expect_err("a primary failure always stays an error")
.into()
combine::<()>(Err(primary), restore).expect_err("a primary failure always stays an error").into()
}
@@ -20,10 +20,7 @@ use leleka_experimental_ref::{
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u32 {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 32) as u32
}
fn unit(&mut self) -> f32 {
@@ -60,10 +57,7 @@ fn download(b: &DeviceBuffer<'_>, len: usize) -> Vec<u8> {
fn open<'c>(ctx: &'c Context<'c>, program: Program, mode: Mode) -> Experimental<'c> {
Experimental::open(ctx, program, &OptIn::default().with(mode)).unwrap_or_else(|error| {
panic!(
"{} open failed ({error}); TODO-ROOT: build PTX and freeze the pin",
program.name()
)
panic!("{} open failed ({error}); TODO-ROOT: build PTX and freeze the pin", program.name())
})
}
@@ -104,55 +98,31 @@ fn experimental_gpu_q4_append_and_gather_match_cpu() {
{
let gpu = open(&ctx, Program::KvQ4, Mode::KvQ40);
let q = QsaShapes::real();
let p = Paged {
shape: KvShape::real(),
pages: 4,
table_entries: 4,
};
let p = Paged { shape: KvShape::real(), pages: 4, table_entries: 4 };
let table: Vec<i32> = vec![0, 1, 2, 3];
let mut rng = Rng(0x57a7_0002);
let n = 2 * 256;
let mut cpu = PoolSet::new(KvFormat::Q4_0, &q, p.shape.rows(p.pages)).unwrap();
let mut cells = Vec::new();
let (mut k_b, mut v_b) = (
zeroed(&ctx, p.shape.q4_bytes(4) as usize),
zeroed(&ctx, p.shape.q4_bytes(4) as usize),
);
let (table_b, ids_b) = (
upload(&ctx, &i32_bytes(&table)),
upload(&ctx, &i32_bytes(&[0, 3, 5, 7, 9, 12])),
);
let (mut k_b, mut v_b) =
(zeroed(&ctx, p.shape.q4_bytes(4) as usize), zeroed(&ctx, p.shape.q4_bytes(4) as usize));
let (table_b, ids_b) = (upload(&ctx, &i32_bytes(&table)), upload(&ctx, &i32_bytes(&[0, 3, 5, 7, 9, 12])));
for pos in 0..13i32 {
let kc: Vec<f32> = (0..n).map(|_| rng.unit()).collect();
let vc: Vec<f32> = (0..n).map(|_| rng.unit()).collect();
let step = upload(&ctx, &i32_bytes(&[pos, 0, 0, 0]));
let (kb, vb) = (upload(&ctx, &f32_bytes(&kc)), upload(&ctx, &f32_bytes(&vc)));
gpu.q4_append_step(&p, &mut k_b, &mut v_b, &table_b, &step, &kb, &vb)
.unwrap();
gpu.q4_append_step(&p, &mut k_b, &mut v_b, &table_b, &step, &kb, &vb).unwrap();
cells.push((pos, kc, vc));
}
let got_k = download(&k_b, p.shape.q4_bytes(4) as usize);
let got_v = download(&v_b, p.shape.q4_bytes(4) as usize);
// nvcc contracts a*b+c; the Fused model is the expectation, Separate the fallback we report.
let mut which = "none";
for (name, c) in [
("fused", Contraction::Fused),
("separate", Contraction::Separate),
] {
for (name, c) in [("fused", Contraction::Fused), ("separate", Contraction::Separate)] {
let mut m = PoolSet::new(KvFormat::Q4_0, &q, p.shape.rows(p.pages)).unwrap();
for (pos, kc, vc) in &cells {
append_cell(
KvFormat::Q4_0,
&mut m,
None,
&table,
i64::from(*pos),
kc,
vc,
&q,
c,
)
.unwrap();
append_cell(KvFormat::Q4_0, &mut m, None, &table, i64::from(*pos), kc, vc, &q, c).unwrap();
}
if m.k_q4 == got_k && m.v_q4 == got_v {
which = name;
@@ -160,23 +130,16 @@ fn experimental_gpu_q4_append_and_gather_match_cpu() {
break;
}
}
assert_ne!(
which, "none",
"device Q4_0 pools differ from both contraction models"
);
assert_ne!(which, "none", "device Q4_0 pools differ from both contraction models");
println!("EXPERIMENTAL q4_append cells=13 matches={which}");
// gather
let ids = [0, 3, 5, 7, 9, 12];
let step = upload(&ctx, &i32_bytes(&[0, 13, 0, 6]));
let scratch = p.shape.gather_scratch_bytes(6) as usize;
let (mut ks, mut vs) = (zeroed(&ctx, scratch), zeroed(&ctx, scratch));
gpu.q4_gather_step(&p, &k_b, &v_b, &table_b, &ids_b, &step, 6, &mut ks, &mut vs)
.unwrap();
gpu.q4_gather_step(&p, &k_b, &v_b, &table_b, &ids_b, &step, 6, &mut ks, &mut vs).unwrap();
let want_k = gather_q4(&cpu.k_q4, &table, &ids, &q).unwrap();
let got: Vec<u16> = download(&ks, scratch)
.chunks(2)
.map(|b| u16::from_le_bytes([b[0], b[1]]))
.collect();
let got: Vec<u16> = download(&ks, scratch).chunks(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect();
assert_eq!(got, want_k, "gathered fp16 K bits");
gpu.close().unwrap();
}
@@ -195,16 +158,11 @@ fn experimental_gpu_keyless_route_matches_cpu() {
let q0: Vec<f32> = (0..tokens * heads * 256).map(|_| rng.unit()).collect();
let m: Vec<f32> = (0..heads * 256 * 256).map(|_| rng.unit() * 0.1).collect();
let (mut q_b, m_b) = (upload(&ctx, &f32_bytes(&q0)), upload(&ctx, &f32_bytes(&m)));
gpu.keyless_route_query(&mut q_b, &m_b, tokens as u64, heads as u64)
.unwrap();
gpu.keyless_route_query(&mut q_b, &m_b, tokens as u64, heads as u64).unwrap();
let mut want = q0.clone();
keyless::route_query(&mut want, &m, tokens, heads).unwrap();
let got = download(&q_b, want.len() * 4);
let mismatches = want
.iter()
.enumerate()
.filter(|(i, w)| got[i * 4..i * 4 + 4] != w.to_le_bytes())
.count();
let mismatches = want.iter().enumerate().filter(|(i, w)| got[i * 4..i * 4 + 4] != w.to_le_bytes()).count();
assert_eq!(mismatches, 0, "fmaf-ordered routing is bit-exact");
println!("EXPERIMENTAL keyless_route tokens={tokens} heads={heads} mismatches=0");
gpu.close().unwrap();
@@ -224,15 +182,11 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() {
let (n_blocks, n_slots, n_q, cap) = (4096u64, 1024u64, 2u64, 64u64);
let runs = stream_runs(&q, StreamFormat::F16);
let mut rng = Rng(0x57a7_0004);
let host_bytes: Vec<Vec<u8>> = runs
.iter()
.map(|(_, len)| (0..n_blocks * len).map(|_| rng.next() as u8).collect())
.collect();
let host_bytes: Vec<Vec<u8>> =
runs.iter().map(|(_, len)| (0..n_blocks * len).map(|_| rng.next() as u8).collect()).collect();
let host: Vec<DeviceBuffer<'_>> = host_bytes.iter().map(|b| upload(&ctx, b)).collect();
let mut slots: Vec<DeviceBuffer<'_>> = runs
.iter()
.map(|(_, len)| zeroed(&ctx, (n_slots * len) as usize))
.collect();
let mut slots: Vec<DeviceBuffer<'_>> =
runs.iter().map(|(_, len)| zeroed(&ctx, (n_slots * len) as usize)).collect();
let mut page_table = upload(&ctx, &i32_bytes(&vec![-1; n_blocks as usize]));
let mut slot_block = zeroed(&ctx, n_slots as usize * 4);
let mut slot_stamp = zeroed(&ctx, n_slots as usize * 4);
@@ -258,10 +212,7 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() {
ids.extend((0..cap as i32).map(|i| i * 4 + qi * 8));
steps.extend([cap as i32 * 4, 0, 0, width]);
}
let (ids_b, steps_b) = (
upload(&ctx, &i32_bytes(&ids)),
upload(&ctx, &i32_bytes(&steps)),
);
let (ids_b, steps_b) = (upload(&ctx, &i32_bytes(&ids)), upload(&ctx, &i32_bytes(&steps)));
let host_refs: Vec<&DeviceBuffer<'_>> = host.iter().collect();
let mut slot_refs: Vec<&mut DeviceBuffer<'_>> = slots.iter_mut().collect();
gpu.stream_resolve(
@@ -292,16 +243,9 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() {
.expect("cpu resolve");
let _ = report;
let table = download(&*map.page_table, n_blocks as usize * 4);
let table: Vec<i32> = table
.chunks(4)
.map(|b| i32::from_le_bytes(b.try_into().unwrap()))
.collect();
let table: Vec<i32> = table.chunks(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect();
let resident: Vec<usize> = (0..n_blocks as usize).filter(|b| table[*b] >= 0).collect();
assert_eq!(
resident.len(),
cpu.resident_blocks(),
"same set of distinct blocks resident"
);
assert_eq!(resident.len(), cpu.resident_blocks(), "same set of distinct blocks resident");
for b in resident {
let slot = table[b] as usize;
for (i, (_, len)) in runs.iter().enumerate() {
@@ -314,10 +258,7 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() {
);
}
}
println!(
"EXPERIMENTAL kv_stream resolve+copy resident={}",
cpu.resident_blocks()
);
println!("EXPERIMENTAL kv_stream resolve+copy resident={}", cpu.resident_blocks());
gpu.close().unwrap();
}
ctx.close().unwrap();
+36 -134
View File
@@ -16,99 +16,43 @@ const KINDS: [ProjectionKind; 10] = [
#[test]
fn common_checked_geometry_matches_frozen_native_layouts() {
for (kind, index) in KINDS.into_iter().zip([0, 1, 2, 3, 4, 5, 5, 6, 6, 7]) {
let shape = projection_shape(ProjectionSpec {
kind,
rows: 5,
columns: 256,
})
.unwrap();
let shape = projection_shape(ProjectionSpec { kind, rows: 5, columns: 256 }).unwrap();
assert_eq!(
shape.weight_bytes,
5 * (256 / family_expectations::LAYOUTS[index].0)
* family_expectations::LAYOUTS[index].1
5 * (256 / family_expectations::LAYOUTS[index].0) * family_expectations::LAYOUTS[index].1
);
assert_eq!(
(
shape.activation_bytes,
shape.output_bytes,
shape.scratch_bytes,
shape.temporary_bytes
),
(shape.activation_bytes, shape.output_bytes, shape.scratch_bytes, shape.temporary_bytes),
(1024, 20, 288, 292)
);
}
for (n, bytes, grid) in family_expectations::TAILS {
let shape = projection_shape(ProjectionSpec {
kind: KINDS[0],
rows: 5,
columns: n,
})
.unwrap();
assert_eq!(
(shape.scratch_bytes, shape.quant_grid, shape.projection_grid),
(bytes, grid as u32, 2)
);
let shape = projection_shape(ProjectionSpec { kind: KINDS[0], rows: 5, columns: n }).unwrap();
assert_eq!((shape.scratch_bytes, shape.quant_grid, shape.projection_grid), (bytes, grid as u32, 2));
}
for (kind, limit) in [
(KINDS[0], 1024),
(KINDS[1], 2048),
(KINDS[5], 2048),
(KINDS[7], 4096),
] {
for (kind, limit) in [(KINDS[0], 1024), (KINDS[1], 2048), (KINDS[5], 2048), (KINDS[7], 4096)] {
for (n, grid) in [(limit - 256, 2), (limit, 5), (limit + 256, 5)] {
assert_eq!(
projection_shape(ProjectionSpec {
kind,
rows: 5,
columns: n
})
.unwrap()
.projection_grid,
grid
);
assert_eq!(projection_shape(ProjectionSpec { kind, rows: 5, columns: n }).unwrap().projection_grid, grid);
}
}
for kind in [KINDS[2], KINDS[3], KINDS[4], KINDS[6], KINDS[8], KINDS[9]] {
assert_eq!(
projection_shape(ProjectionSpec {
kind,
rows: 5,
columns: 6144
})
.unwrap()
.projection_grid,
2
);
assert_eq!(projection_shape(ProjectionSpec { kind, rows: 5, columns: 6144 }).unwrap().projection_grid, 2);
}
}
#[test]
fn common_invalid_shapes_have_fixed_errors() {
for kind in KINDS {
for (m, n) in [
(0, 256),
(1, 0),
(1, 31),
(1, 33),
(usize::MAX, 256),
(1, usize::MAX),
(i32::MAX as usize + 1, 256),
] {
for (m, n) in
[(0, 256), (1, 0), (1, 31), (1, 33), (usize::MAX, 256), (1, usize::MAX), (i32::MAX as usize + 1, 256)]
{
assert_eq!(
projection_shape(ProjectionSpec {
kind,
rows: m,
columns: n
}),
projection_shape(ProjectionSpec { kind, rows: m, columns: n }),
Err(Error::InvalidProjectionShape)
);
}
}
assert_eq!(
projection_shape(ProjectionSpec {
kind: KINDS[1],
rows: 1,
columns: 32
}),
projection_shape(ProjectionSpec { kind: KINDS[1], rows: 1, columns: 32 }),
Err(Error::InvalidProjectionShape)
);
}
@@ -124,8 +68,7 @@ fn q4_k_admission_bounds_every_padded_cta_byte_offset() {
let max_block_index = i32::MAX as usize / BLOCK_BYTES;
// Include the common final +8-block PTX increment after the last
// iteration, then round the small-N four-row CTA down to its boundary.
let max_padded_rows =
((max_block_index.saturating_sub(7) / ROWS_PER_CTA) * ROWS_PER_CTA).max(ROWS_PER_CTA);
let max_padded_rows = ((max_block_index.saturating_sub(7) / ROWS_PER_CTA) * ROWS_PER_CTA).max(ROWS_PER_CTA);
let at_limit_offset = (max_padded_rows + 7) * BLOCK_BYTES;
assert!(at_limit_offset <= i32::MAX as usize);
assert!(q4_k_native_indices_fit(max_padded_rows - ROWS_PER_CTA, 256));
@@ -187,11 +130,7 @@ fn q4_k_admission_bounds_every_padded_cta_byte_offset() {
for rows in [14_913_081, 14_913_082] {
assert!(!q4_k_native_indices_fit(rows, 256));
assert_eq!(
projection_shape(ProjectionSpec {
kind: ProjectionKind::Dense(DenseFormat::Q4_K),
rows,
columns: 256,
}),
projection_shape(ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q4_K), rows, columns: 256 }),
Err(Error::InvalidProjectionShape)
);
}
@@ -202,12 +141,8 @@ fn q4_k_admission_bounds_every_padded_cta_byte_offset() {
let large_n = 256 * 3_000_000;
assert!(q4_k_native_indices_fit(1, large_n));
assert!(
projection_shape(ProjectionSpec {
kind: ProjectionKind::Dense(DenseFormat::Q4_K),
rows: 1,
columns: large_n,
})
.is_ok()
projection_shape(ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q4_K), rows: 1, columns: large_n })
.is_ok()
);
// Positive individually-valid M and N still refuse when their Q4_K
@@ -224,52 +159,28 @@ fn q4_k_admission_bounds_every_padded_cta_byte_offset() {
);
}
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
#[test]
#[ignore = "private quantizer transport only; isolated CPU mock, not GPU math"]
fn family_quantizer_transport_child() {
assert_eq!(
std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(),
Ok("1")
);
assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), Ok("1"));
let n: usize = std::env::var("LELEKA_FAMILY_N").unwrap().parse().unwrap();
let driver = Driver::load().unwrap();
let context = driver.device(0).unwrap().create_context(8192).unwrap();
let trace_path = std::env::var("MOCK_CUDA_TRACE").unwrap();
let before = std::fs::read(&trace_path).unwrap();
for (kind, alignment) in KINDS.into_iter().zip([2, 4, 2, 2, 2, 2, 2, 4, 4, 2]) {
let shape = projection_shape(ProjectionSpec {
kind,
rows: 1,
columns: 256,
})
.unwrap();
let addresses = [
ffi::BufferHandle::synthetic(2),
ffi::BufferHandle::synthetic(4096),
ffi::BufferHandle::synthetic(8192),
];
let shape = projection_shape(ProjectionSpec { kind, rows: 1, columns: 256 }).unwrap();
let addresses =
[ffi::BufferHandle::synthetic(2), ffi::BufferHandle::synthetic(4096), ffi::BufferHandle::synthetic(8192)];
assert_eq!(
projection_ranges(kind, &shape, addresses),
if alignment == 4 {
Err(Error::InvalidProjectionShape)
} else {
Ok(())
}
if alignment == 4 { Err(Error::InvalidProjectionShape) } else { Ok(()) }
);
assert_eq!(std::fs::read(&trace_path).unwrap(), before);
assert_eq!(context.allocated_bytes(), 0);
assert!(context.common_quantizer.get().is_none());
assert!(
context
.projection_kernels
.iter()
.all(|slot| slot.get().is_none())
);
assert!(context.projection_kernels.iter().all(|slot| slot.get().is_none()));
}
let mut input = context.allocate(4 * n).unwrap();
input.copy_from(&vec![0; 4 * n]).unwrap();
@@ -290,18 +201,11 @@ fn family_quantizer_transport_child() {
n as u32,
);
let guard = context.enter()?;
let launch = context.driver.api.launch_q8_quantize(
kernel.function,
n.div_ceil(256) as u32,
&mut args,
);
let launch = context.driver.api.launch_q8_quantize(kernel.function, n.div_ceil(256) as u32, &mut args);
context.complete_launch(launch, args, guard)?;
let mut bytes = [0; 4];
status.copy_to(&mut bytes)?;
let expected = std::env::var("MOCK_FAMILY_STATUS")
.unwrap_or_else(|_| "0".into())
.parse::<u32>()
.unwrap();
let expected = std::env::var("MOCK_FAMILY_STATUS").unwrap_or_else(|_| "0".into()).parse::<u32>().unwrap();
assert_eq!(u32::from_le_bytes(bytes), expected);
Ok(())
})();
@@ -310,18 +214,16 @@ fn family_quantizer_transport_child() {
assert_eq!(result.is_err(), failure, "result={result:?}");
let base = std::env::var("MOCK_CUDA_FAIL").unwrap_or_default();
let family = std::env::var("MOCK_CUDA_FAMILY_FAIL").unwrap_or_default();
let expected_charge = if family.contains("quant_sync")
|| family.contains("quant_restore")
|| base == "lookup:1,unload:1"
{
4 * n + n / 32 * 36 + 4
} else if base == "free:1" {
4 * n + 4
} else if base == "free:2" {
4 * n + n / 32 * 36
} else {
4 * n
};
let expected_charge =
if family.contains("quant_sync") || family.contains("quant_restore") || base == "lookup:1,unload:1" {
4 * n + n / 32 * 36 + 4
} else if base == "free:1" {
4 * n + 4
} else if base == "free:2" {
4 * n + n / 32 * 36
} else {
4 * n
};
assert_eq!(context.allocated_bytes(), expected_charge);
if family == "quant_launch,quant_sync,quant_restore" {
let error = format!("{result:?}");
+17 -41
View File
@@ -97,8 +97,8 @@ pub(crate) struct Q5ProjectionArguments {
#[path = "mmq_ffi.rs"]
mod mmq_abi;
pub(crate) use mmq_abi::{
Iq3NativeIntegerArguments, MmqArguments, MmqFixupArguments, MmqOriginalGatherArguments,
MmqOriginalSwigluArguments, MmqQuantArguments, MmqResidentArguments,
Iq3NativeIntegerArguments, MmqArguments, MmqFixupArguments, MmqOriginalGatherArguments, MmqOriginalSwigluArguments,
MmqQuantArguments, MmqResidentArguments,
};
// Closed kernel-parameter storage of the Strata-prefill GDN / native dequant modules.
@@ -108,17 +108,9 @@ mod gdn_native_abi;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
pub(crate) use gdn_native_abi::{GdnPrefillArguments, KernelArg};
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod enabled;
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub(crate) use enabled::{Api, KarArgument, KarLevelsArgs};
#[cfg(not(all(
@@ -150,48 +142,32 @@ struct HeadGreedyStorage {
}
pub(crate) struct HeadGreedyArguments(std::ptr::NonNull<HeadGreedyStorage>);
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
#[path = "original_expert_stager_ffi.rs"]
pub(crate) mod original_stager;
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
#[path = "original_file_expert_source_ffi.rs"]
pub(crate) mod original_file_source;
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
#[path = "deferred_status_ffi.rs"]
pub(crate) mod deferred_status;
mod impl_contexthandle;
#[allow(unused_imports)]
use impl_contexthandle::projection_ptx;
#[cfg(any(
test,
all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
)
))]
#[allow(unused_imports)]
use impl_contexthandle::validate_projection_ptx;
#[allow(unused_imports)]
pub(crate) use impl_contexthandle::projection_available;
#[allow(unused_imports)]
use impl_contexthandle::projection_entry;
mod impl_functionhandle;
mod impl_drop_for_q5projectionarguments;
#[allow(unused_imports)]
use impl_contexthandle::projection_ptx;
#[cfg(any(
test,
all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")
))]
#[allow(unused_imports)]
use impl_contexthandle::validate_projection_ptx;
mod impl_api;
mod impl_drop_for_q5projectionarguments;
mod impl_functionhandle;
mod impl_qsaselectedarguments;
+3 -7
View File
@@ -21,8 +21,7 @@ type MemFreeV2 = unsafe extern "C" fn(CuDevicePtr) -> CuResult;
type MemGetInfoV2 = unsafe extern "C" fn(*mut usize, *mut usize) -> CuResult;
type MemcpyHtoDV2 = unsafe extern "C" fn(CuDevicePtr, *const c_void, usize) -> CuResult;
type ModuleLoadData = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> CuResult;
type ModuleGetFunction =
unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> CuResult;
type ModuleGetFunction = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> CuResult;
type ModuleUnload = unsafe extern "C" fn(*mut c_void) -> CuResult;
type LaunchKernel = unsafe extern "C" fn(
*mut c_void,
@@ -40,8 +39,7 @@ type LaunchKernel = unsafe extern "C" fn(
static FIXED_PTX: &[u8] = concat!(include_str!("../vector_add.ptx"), "\0").as_bytes();
static MATVEC_PTX: &[u8] = concat!(include_str!("../matvec.ptx"), "\0").as_bytes();
static Q5_K_PTX: &[u8] = concat!(include_str!("../q5_k_q8_1.ptx"), "\0").as_bytes();
static COMMON_QUANTIZER_PTX: &[u8] =
concat!(include_str!("../q8_1_quantize.ptx"), "\0").as_bytes();
static COMMON_QUANTIZER_PTX: &[u8] = concat!(include_str!("../q8_1_quantize.ptx"), "\0").as_bytes();
static Q6_K_PTX: &[u8] = concat!(include_str!("../q6_k_q8_1.ptx"), "\0").as_bytes();
type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult;
type MemcpyDtoDV2 = unsafe extern "C" fn(CuDevicePtr, CuDevicePtr, usize) -> CuResult;
@@ -87,9 +85,7 @@ macro_rules! symbol {
// SAFETY: valid owned library handle and static C name.
let address = unsafe { libc::dlsym($library.0, $name.as_ptr()) };
if address.is_null() {
return Err(Error::MissingSymbol(
$name.to_str().expect("static ASCII symbol"),
));
return Err(Error::MissingSymbol($name.to_str().expect("static ASCII symbol")));
}
// SAFETY: the fixed ABI name is paired with its exact
// documented signature. Linux64 supports dlsym function
+16 -65
View File
@@ -21,16 +21,9 @@ impl Api {
}
pub(crate) fn mmq_capabilities(&self) -> Result<u32> {
let library = &self._library;
let get = symbol!(
library,
c"cuCtxGetDevice",
unsafe extern "C" fn(*mut c_int) -> CuResult
);
let attr = symbol!(
library,
c"cuDeviceGetAttribute",
unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult
);
let get = symbol!(library, c"cuCtxGetDevice", unsafe extern "C" fn(*mut c_int) -> CuResult);
let attr =
symbol!(library, c"cuDeviceGetAttribute", unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult);
let mut device = 0;
// SAFETY: fixed optional Driver ABI, owner context current, valid output.
check("cuCtxGetDevice", unsafe { get(&mut device) })?;
@@ -39,10 +32,7 @@ impl Api {
// SAFETY: fixed capability selectors and live device returned above.
check("cuDeviceGetAttribute", unsafe { attr(slot, key, device) })?;
}
if !crate::arch_ptx::mmq_cc_ok(values[0], values[1])
|| values[2] < 52480
|| !(1..=4096).contains(&values[3])
{
if !crate::arch_ptx::mmq_cc_ok(values[0], values[1]) || values[2] < 52480 || !(1..=4096).contains(&values[3]) {
return Err(Error::InvalidDriverValue("MMQ SM120 capabilities"));
}
Ok(crate::arch_ptx::forced_sms(values[3] as u32))
@@ -103,40 +93,22 @@ impl Api {
return Err(Error::InvalidProjectionShape);
}
let library = &self._library;
let set = symbol!(
library,
c"cuFuncSetAttribute",
unsafe extern "C" fn(*mut c_void, c_int, c_int) -> CuResult
);
let set = symbol!(library, c"cuFuncSetAttribute", unsafe extern "C" fn(*mut c_void, c_int, c_int) -> CuResult);
// SAFETY: fixed attribute8, admitted shared bytes and live owned function.
check("cuFuncSetAttribute", unsafe {
set(function.0 as *mut c_void, 8, bytes as c_int)
})
check("cuFuncSetAttribute", unsafe { set(function.0 as *mut c_void, 8, bytes as c_int) })
}
pub(crate) fn load_iq3_native_integer(&self) -> Result<ModuleHandle> {
let ptx = crate::mmq::resident::native_integer::asset()?;
let mut m = std::ptr::null_mut();
// SAFETY: ROOT-sealed fixed NUL PTX, actual owning current Context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast())
})?;
check("cuModuleLoadData", unsafe { (self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
ModuleHandle::qwen_success(m as usize)
}
pub(crate) fn iq3_native_integer_function(
&self,
m: ModuleHandle,
reduce: bool,
) -> Result<FunctionHandle> {
let name = if reduce {
c"leleka_iq3_native_order_reduce"
} else {
c"leleka_iq3_native_integer_dot"
};
pub(crate) fn iq3_native_integer_function(&self, m: ModuleHandle, reduce: bool) -> Result<FunctionHandle> {
let name = if reduce { c"leleka_iq3_native_order_reduce" } else { c"leleka_iq3_native_integer_dot" };
let mut f = std::ptr::null_mut();
// SAFETY: closed fixed two-entry map in actual owned module.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut f, m.0 as *mut c_void, name.as_ptr())
})?;
check("cuModuleGetFunction", unsafe { (self.get_function)(&mut f, m.0 as *mut c_void, name.as_ptr()) })?;
FunctionHandle::qwen_success(f as usize)
}
pub(crate) fn launch_iq3_native_integer(
@@ -149,11 +121,7 @@ impl Api {
if !(1..=64).contains(&tokens) {
return Err(Error::InvalidProjectionShape);
}
let (x, y, z, by) = if reduce {
(160, tokens, 1, 4)
} else {
(40, tokens.div_ceil(8), 80, 1)
};
let (x, y, z, by) = if reduce { (160, tokens, 1, 4) } else { (40, tokens.div_ceil(8), 80, 1) };
// SAFETY: fixed complete M640/K2560/T1..64 grid, exact privately boxed ABI;
// queue retains every owner through one same-default-stream synchronize/pop.
check("cuLaunchKernel", unsafe {
@@ -176,23 +144,14 @@ impl Api {
let ptx = crate::mmq::resident::native_activation::asset()?;
let mut m = std::ptr::null_mut();
// SAFETY: pinned immutable NUL PTX in current owned Context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast())
})?;
check("cuModuleLoadData", unsafe { (self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
ModuleHandle::qwen_success(m as usize)
}
pub(crate) fn native_resident_d4_function(
&self,
m: ModuleHandle,
) -> Result<FunctionHandle> {
pub(crate) fn native_resident_d4_function(&self, m: ModuleHandle) -> Result<FunctionHandle> {
let mut f = std::ptr::null_mut();
// SAFETY: fixed entry in actual owned module.
check("cuModuleGetFunction", unsafe {
(self.get_function)(
&mut f,
m.0 as *mut c_void,
c"leleka_native_resident_d4".as_ptr(),
)
(self.get_function)(&mut f, m.0 as *mut c_void, c"leleka_native_resident_d4".as_ptr())
})?;
FunctionHandle::qwen_success(f as usize)
}
@@ -205,16 +164,8 @@ impl Api {
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn head_greedy_function(
&self,
module: ModuleHandle,
last: bool,
) -> Result<FunctionHandle> {
let name = if last {
c"leleka_head_final"
} else {
c"leleka_head_groups"
};
pub(crate) fn head_greedy_function(&self, module: ModuleHandle, last: bool) -> Result<FunctionHandle> {
let name = if last { c"leleka_head_final" } else { c"leleka_head_groups" };
let mut function = std::ptr::null_mut();
// SAFETY: closed two-entry map, actual retained module.
check("cuModuleGetFunction", unsafe {
+298 -153
View File
@@ -6,23 +6,14 @@ use super::*;
impl Api {
pub(crate) fn mmq_original_group_shared_limit(&self) -> Result<u32> {
let library = &self._library;
let get = symbol!(
library,
c"cuCtxGetDevice",
unsafe extern "C" fn(*mut c_int) -> CuResult
);
let attr = symbol!(
library,
c"cuDeviceGetAttribute",
unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult
);
let get = symbol!(library, c"cuCtxGetDevice", unsafe extern "C" fn(*mut c_int) -> CuResult);
let attr =
symbol!(library, c"cuDeviceGetAttribute", unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult);
let mut device = 0;
let mut limit = 0;
// SAFETY: current real Context, fixed attribute97 and live output slots.
check("cuCtxGetDevice", unsafe { get(&mut device) })?;
check("cuDeviceGetAttribute", unsafe {
attr(&mut limit, 97, device)
})?;
check("cuDeviceGetAttribute", unsafe { attr(&mut limit, 97, device) })?;
u32::try_from(limit).map_err(|_| Error::InvalidDriverValue("MMQ shared capacity"))
}
pub(crate) fn load_mmq_original_group(&self, kind: u32) -> Result<ModuleHandle> {
@@ -41,149 +32,303 @@ impl Api {
width: u32,
fixup: bool,
) -> Result<FunctionHandle> {
let name=match(kind,width,fixup){
(0,0,false)=>c"leleka_original_mmq_swiglu",
(1,0,false)=>c"leleka_original_mmq_gather",
(2,0,false)=>c"leleka_original_mmq_gu_finite",
(18,8,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,16,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,24,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,32,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,40,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,48,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,64,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,80,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,96,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,112,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,128,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,8,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,16,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,24,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,32,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,40,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,48,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,64,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,80,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,96,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,112,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,128,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,8,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,16,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,24,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,32,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,40,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,48,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,64,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,80,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,96,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,112,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,128,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,8,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,16,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,24,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,32,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,40,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,48,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,64,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,80,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,96,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,112,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,128,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,8,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,16,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,24,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,32,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,40,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,48,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,64,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,80,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,96,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,112,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,128,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,8,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,16,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,24,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,32,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,40,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,48,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,64,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,80,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,96,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,112,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,128,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
_=>return Err(Error::InvalidProjectionShape),
let name = match (kind, width, fixup) {
(0, 0, false) => c"leleka_original_mmq_swiglu",
(1, 0, false) => c"leleka_original_mmq_gather",
(2, 0, false) => c"leleka_original_mmq_gu_finite",
(18, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(18, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(22, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(22, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(21, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(21, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(23, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(23, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(20, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(20, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(42, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(42, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
_ => return Err(Error::InvalidProjectionShape),
};
let mut f = std::ptr::null_mut();
// SAFETY: closed literal Original template symbols only.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr())
})?;
check("cuModuleGetFunction", unsafe { (self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr()) })?;
FunctionHandle::qwen_success(f as usize)
}
pub(crate) fn launch_mmq_original_gather(
@@ -39,11 +39,7 @@ impl Api {
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn mmq_resident_function(
&self,
module: ModuleHandle,
kind: u8,
) -> Result<FunctionHandle> {
pub(crate) fn mmq_resident_function(&self, module: ModuleHandle, kind: u8) -> Result<FunctionHandle> {
let name = match kind {
0 => c"leleka_mmq_zero",
1 => c"leleka_mmq_finite",
@@ -52,9 +48,7 @@ impl Api {
};
let mut f = std::ptr::null_mut();
// SAFETY: closed three-entry name map, actual retained helper module.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr())
})?;
check("cuModuleGetFunction", unsafe { (self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr()) })?;
FunctionHandle::qwen_success(f as usize)
}
pub(crate) fn launch_mmq_resident(
@@ -130,12 +124,7 @@ impl Api {
)
})
}
pub(crate) fn fixup_mmq(
&self,
function: FunctionHandle,
grid: u32,
args: &mut MmqFixupArguments,
) -> Result<()> {
pub(crate) fn fixup_mmq(&self, function: FunctionHandle, grid: u32, args: &mut MmqFixupArguments) -> Result<()> {
// SAFETY: closed fixed 13-param ABI, actual same scratch/result after completed mul; args retained through sync.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
@@ -175,16 +164,8 @@ impl Api {
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn qsa_selected_function(
&self,
module: ModuleHandle,
gather: bool,
) -> Result<FunctionHandle> {
let name = if gather {
c"leleka_qsa_selected_gather"
} else {
c"leleka_qsa_selected_scatter"
};
pub(crate) fn qsa_selected_function(&self, module: ModuleHandle, gather: bool) -> Result<FunctionHandle> {
let name = if gather { c"leleka_qsa_selected_gather" } else { c"leleka_qsa_selected_scatter" };
let mut function = std::ptr::null_mut();
// SAFETY: two fixed entry names, live retained module and writable out pointer.
check("cuModuleGetFunction", unsafe {
@@ -219,10 +200,7 @@ impl Api {
)
})
}
pub(crate) fn load_qwen_module(
&self,
asset: &crate::qwen_ffi::Asset,
) -> Result<ModuleHandle> {
pub(crate) fn load_qwen_module(&self, asset: &crate::qwen_ffi::Asset) -> Result<ModuleHandle> {
asset.validate(asset.operation)?;
let mut module = std::ptr::null_mut();
// SAFETY: validated immutable closed-map NUL-terminated PTX and
@@ -241,11 +219,7 @@ impl Api {
// SAFETY: live private module, fixed operation-to-entry map and
// writable output. No external symbol resolver is exposed.
check("cuModuleGetFunction", unsafe {
(self.get_function)(
&mut function,
module.0 as *mut c_void,
operation.entry().as_ptr(),
)
(self.get_function)(&mut function, module.0 as *mut c_void, operation.entry().as_ptr())
})?;
FunctionHandle::qwen_success(function as usize)
}
@@ -33,9 +33,7 @@ impl Api {
}
pub(crate) fn load() -> Result<Self> {
// SAFETY: fixed NUL-terminated soname and immediate local lookup.
let handle = unsafe {
libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL)
};
let handle = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
if handle.is_null() {
return Err(Error::LibraryUnavailable);
}
@@ -133,47 +131,21 @@ impl Api {
pub(crate) fn load_fixed_module(&self, operation: FixedOperation) -> Result<ModuleHandle> {
let bytes = match operation {
FixedOperation::CommonQuantize => COMMON_QUANTIZER_PTX,
FixedOperation::GroupedSwiglu => {
concat!(include_str!("../../moe_group_swiglu.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedDownIq4 => {
concat!(include_str!("../../moe_group_down_iq4_nl.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedDownQ2 => {
concat!(include_str!("../../moe_group_down_q2_0.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq3 => {
concat!(include_str!("../../moe_group_iq3_xxs.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq2 => {
concat!(include_str!("../../moe_group_iq2_s.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq3S => {
concat!(include_str!("../../moe_group_iq3_s.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq4Xs => {
concat!(include_str!("../../moe_group_iq4_xs.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq3SNc4 => {
concat!(include_str!("../../moe_group_iq3_s_nc4.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq4XsNc4 => {
concat!(include_str!("../../moe_group_iq4_xs_nc4.ptx"), "\0").as_bytes()
}
FixedOperation::Projection(kind) => {
projection_ptx(kind).ok_or(Error::UnsupportedProjection)?
}
FixedOperation::GroupedSwiglu => concat!(include_str!("../../moe_group_swiglu.ptx"), "\0").as_bytes(),
FixedOperation::GroupedDownIq4 => concat!(include_str!("../../moe_group_down_iq4_nl.ptx"), "\0").as_bytes(),
FixedOperation::GroupedDownQ2 => concat!(include_str!("../../moe_group_down_q2_0.ptx"), "\0").as_bytes(),
FixedOperation::GroupedIq3 => concat!(include_str!("../../moe_group_iq3_xxs.ptx"), "\0").as_bytes(),
FixedOperation::GroupedIq2 => concat!(include_str!("../../moe_group_iq2_s.ptx"), "\0").as_bytes(),
FixedOperation::GroupedIq3S => concat!(include_str!("../../moe_group_iq3_s.ptx"), "\0").as_bytes(),
FixedOperation::GroupedIq4Xs => concat!(include_str!("../../moe_group_iq4_xs.ptx"), "\0").as_bytes(),
FixedOperation::GroupedIq3SNc4 => concat!(include_str!("../../moe_group_iq3_s_nc4.ptx"), "\0").as_bytes(),
FixedOperation::GroupedIq4XsNc4 => concat!(include_str!("../../moe_group_iq4_xs_nc4.ptx"), "\0").as_bytes(),
FixedOperation::Projection(kind) => projection_ptx(kind).ok_or(Error::UnsupportedProjection)?,
FixedOperation::VectorAdd => FIXED_PTX,
FixedOperation::GrReadFinite => {
concat!(include_str!("../../gr_read_guard.ptx"), "\0").as_bytes()
}
FixedOperation::GrReadFinite => concat!(include_str!("../../gr_read_guard.ptx"), "\0").as_bytes(),
FixedOperation::Matvec => MATVEC_PTX,
FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => {
Q5_K_PTX
}
FixedOperation::Q6K | FixedOperation::Q6KQuantize | FixedOperation::Q6KProject => {
Q6_K_PTX
}
FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => Q5_K_PTX,
FixedOperation::Q6K | FixedOperation::Q6KQuantize | FixedOperation::Q6KProject => Q6_K_PTX,
};
if matches!(
operation,
@@ -205,11 +177,7 @@ impl Api {
}
Ok(ModuleHandle(module as usize))
}
pub(crate) fn fixed_function(
&self,
module: ModuleHandle,
operation: FixedOperation,
) -> Result<FunctionHandle> {
pub(crate) fn fixed_function(&self, module: ModuleHandle, operation: FixedOperation) -> Result<FunctionHandle> {
let mut function = std::ptr::null_mut();
// SAFETY: live private module in current owner context; fixed C
// entry name; valid writable opaque function output.
@@ -8,16 +8,9 @@ impl Api {
// SAFETY: usable handle was consumed before this single attempt,
// current context owns it, and all prior work completed. It is
// never retried or reused even when unload reports failure.
check("cuModuleUnload", unsafe {
(self.unload_module)(module.0 as *mut c_void)
})
check("cuModuleUnload", unsafe { (self.unload_module)(module.0 as *mut c_void) })
}
pub(crate) fn launch(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut LaunchArguments,
) -> Result<()> {
pub(crate) fn launch(&self, function: FunctionHandle, grid: u32, arguments: &mut LaunchArguments) -> Result<()> {
// SAFETY: fixed live function/owner context; checked exact shapes,
// nonaliasing output and grid; six fixed dimensions + sharedBytes;
// null stream/extra. Four pointer entries address initialized typed
@@ -14,9 +14,7 @@ impl Api {
let mut context = std::ptr::null_mut();
// SAFETY: exact legacy v2 THREE-argument ABI, zero flags, a device
// returned by cuDeviceGet, and a valid writable context pointer.
check("cuCtxCreate_v2", unsafe {
(self.create)(&mut context, 0, device)
})?;
check("cuCtxCreate_v2", unsafe { (self.create)(&mut context, 0, device) })?;
if context.is_null() {
return Err(Error::InvalidDriverValue("cuCtxCreate_v2"));
}
@@ -26,15 +24,11 @@ impl Api {
// SAFETY: this handle was created by this Api and remains owned by
// the caller context. No buffer can outlive the borrow owner. This
// API explicitly supports destroying a non-current owned context.
check("cuCtxDestroy_v2", unsafe {
(self.destroy)(context.0 as CuContext)
})
check("cuCtxDestroy_v2", unsafe { (self.destroy)(context.0 as CuContext) })
}
pub(crate) fn push(&self, context: ContextHandle) -> Result<()> {
// SAFETY: live private context, same creating thread (Rc owners).
check("cuCtxPushCurrent_v2", unsafe {
(self.push)(context.0 as CuContext)
})
check("cuCtxPushCurrent_v2", unsafe { (self.push)(context.0 as CuContext) })
}
pub(crate) fn pop(&self) -> Result<ContextHandle> {
let mut context = std::ptr::null_mut();
@@ -49,9 +43,11 @@ impl Api {
// drained, then wait for the compute streams only (never for the copy stream)
crate::prefetch_point();
// SAFETY: caller guard makes its live owned context current; registered live streams.
return crate::compute_drain::timed(5, || crate::compute_drain::drain(|s| {
check("cuStreamSynchronize", unsafe { (self.stream_synchronize)(s as *mut c_void) })
}));
return crate::compute_drain::timed(5, || {
crate::compute_drain::drain(|s| {
check("cuStreamSynchronize", unsafe { (self.stream_synchronize)(s as *mut c_void) })
})
});
}
// SAFETY: caller guard makes its live owned context current.
check("cuCtxSynchronize", unsafe { (self.synchronize)() })
@@ -81,21 +77,21 @@ impl Api {
if crate::compute_drain::zero_memset() && owned.len() <= 1 << 20 && owned.iter().all(|b| *b == 0) {
// EXPERIMENT (chunk stream in flight): an all-zero upload is a device memset, which does not queue
// behind the expert copies on the host-to-device copy engine
return crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe {
(self.zero)(buffer.0, 0, owned.len())
}));
return crate::compute_drain::timed(4, || {
check("cuMemsetD8_v2", unsafe { (self.zero)(buffer.0, 0, owned.len()) })
});
}
crate::compute_drain::timed(2, || check("cuMemcpyHtoD_v2", unsafe {
(self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len())
}))
crate::compute_drain::timed(2, || {
check("cuMemcpyHtoD_v2", unsafe { (self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len()) })
})
}
pub(crate) fn copy_to(&self, buffer: BufferHandle, owned: &mut [u8]) -> Result<()> {
// SAFETY: valid owned writable staging of exactly the allocation
// size; current owner context; caller synchronizes or leaks as
// above. No borrowed output is passed directly to the driver.
crate::compute_drain::timed(3, || check("cuMemcpyDtoH_v2", unsafe {
(self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len())
}))
crate::compute_drain::timed(3, || {
check("cuMemcpyDtoH_v2", unsafe { (self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len()) })
})
}
pub(crate) fn zero(&self, destination: u64, bytes: usize) -> Result<()> {
if destination == 0 || bytes == 0 {
@@ -103,38 +99,27 @@ impl Api {
}
// SAFETY: caller owns the current-context allocation and has
// validated this exact nonzero extent before dispatch.
crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe {
(self.zero)(destination, 0, bytes)
}))
crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe { (self.zero)(destination, 0, bytes) }))
}
pub(crate) fn copy_mmq_weight(
&self,
destination: BufferHandle,
source: BufferHandle,
bytes: usize,
) -> Result<()> {
pub(crate) fn copy_mmq_weight(&self, destination: BufferHandle, source: BufferHandle, bytes: usize) -> Result<()> {
if !matches!(bytes, 627200 | 524800 | 704000 | 870400 | 921600 | 460800) {
return Err(Error::InvalidProjectionShape);
}
// SAFETY: the closed MMQ facade validates actual same-context,
// disjoint whole raw source and padded destination allocations.
// Owners stay borrowed until synchronize/pop, with poison on uncertainty.
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
(self.copy_moe_down)(destination.0, source.0, bytes)
}))
crate::compute_drain::timed(6, || {
check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, bytes) })
})
}
pub(crate) fn copy_moe_down(
&self,
destination: BufferHandle,
source: BufferHandle,
) -> Result<()> {
pub(crate) fn copy_moe_down(&self, destination: BufferHandle, source: BufferHandle) -> Result<()> {
// SAFETY: facade admits exact same-context disjoint owned extents,
// a checked ten-slot destination address and exactly10240 bytes.
// Both allocations remain borrowed until sync and context restore;
// ambiguous completion poisons their context before any later free.
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
(self.copy_moe_down)(destination.0, source.0, 10_240)
}))
crate::compute_drain::timed(6, || {
check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, 10_240) })
})
}
pub(crate) fn copy_original_down_group(
&self,
@@ -147,21 +132,17 @@ impl Api {
}
// SAFETY: actual affine grouped Down producer and prompt arena
// supply disjoint checked extents; both survive sync and pop.
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
(self.copy_moe_down)(destination.0, source.0, bytes)
}))
crate::compute_drain::timed(6, || {
check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, bytes) })
})
}
pub(crate) fn copy_moe_group_column(
&self,
destination: BufferHandle,
source: BufferHandle,
) -> Result<()> {
pub(crate) fn copy_moe_group_column(&self, destination: BufferHandle, source: BufferHandle) -> Result<()> {
// SAFETY: facade admits exact same-context disjoint owned extents,
// a checked 64-column destination address and exactly2560 bytes.
// Both allocations remain borrowed until sync and context restore;
// ambiguous completion poisons their context before any later free.
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
(self.copy_moe_down)(destination.0, source.0, 2560)
}))
crate::compute_drain::timed(6, || {
check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, 2560) })
})
}
}
@@ -14,9 +14,5 @@ impl Drop for Library {
}
}
pub(super) fn check(operation: &'static str, code: CuResult) -> Result<()> {
if code == 0 {
Ok(())
} else {
Err(Error::Driver { operation, code })
}
if code == 0 { Ok(()) } else { Err(Error::Driver { operation, code }) }
}
+10 -53
View File
@@ -25,10 +25,7 @@ impl Api {
format: Option<(crate::mmq::MmqFormat, crate::mmq::Tile)>,
fixup: bool,
) -> Result<FunctionHandle> {
let _ = (
module.0,
format.map(|(f, j)| if fixup { f.fixup_entry(j) } else { f.entry(j) }),
);
let _ = (module.0, format.map(|(f, j)| if fixup { f.fixup_entry(j) } else { f.entry(j) }));
Err(Error::UnsupportedPlatform)
}
pub(crate) fn mmq_shared(&self, function: FunctionHandle, bytes: u32) -> Result<()> {
@@ -38,11 +35,7 @@ impl Api {
pub(crate) fn load_iq3_native_integer(&self) -> Result<ModuleHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn iq3_native_integer_function(
&self,
m: ModuleHandle,
reduce: bool,
) -> Result<FunctionHandle> {
pub(crate) fn iq3_native_integer_function(&self, m: ModuleHandle, reduce: bool) -> Result<FunctionHandle> {
let _ = (m.0, reduce);
Err(Error::UnsupportedPlatform)
}
@@ -68,11 +61,7 @@ impl Api {
let _ = crate::head_greedy::asset();
Err(Error::UnsupportedPlatform)
}
pub(crate) fn head_greedy_function(
&self,
module: ModuleHandle,
last: bool,
) -> Result<FunctionHandle> {
pub(crate) fn head_greedy_function(&self, module: ModuleHandle, last: bool) -> Result<FunctionHandle> {
let _ = (module.0, last);
Err(Error::UnsupportedPlatform)
}
@@ -139,12 +128,7 @@ impl Api {
let _ = (m.0, k);
Err(Error::UnsupportedPlatform)
}
pub(crate) fn launch_mmq_resident(
&self,
f: FunctionHandle,
w: u32,
a: &mut MmqResidentArguments,
) -> Result<()> {
pub(crate) fn launch_mmq_resident(&self, f: FunctionHandle, w: u32, a: &mut MmqResidentArguments) -> Result<()> {
let _ = (f.0, w, a.parameters());
Err(Error::UnsupportedPlatform)
}
@@ -167,12 +151,7 @@ impl Api {
let _ = (function.0, l, grid, args.parameters());
Err(Error::UnsupportedPlatform)
}
pub(crate) fn fixup_mmq(
&self,
function: FunctionHandle,
grid: u32,
args: &mut MmqFixupArguments,
) -> Result<()> {
pub(crate) fn fixup_mmq(&self, function: FunctionHandle, grid: u32, args: &mut MmqFixupArguments) -> Result<()> {
let _ = (function.0, grid, args.parameters());
Err(Error::UnsupportedPlatform)
}
@@ -180,11 +159,7 @@ impl Api {
pub(crate) fn load_qsa_selected(&self) -> Result<ModuleHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn qsa_selected_function(
&self,
module: ModuleHandle,
gather: bool,
) -> Result<FunctionHandle> {
pub(crate) fn qsa_selected_function(&self, module: ModuleHandle, gather: bool) -> Result<FunctionHandle> {
let _ = (module.0, gather);
Err(Error::UnsupportedPlatform)
}
@@ -218,20 +193,12 @@ impl Api {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn load() -> Result<Self> {
if cfg!(feature = "cuda-driver") {
Err(Error::UnsupportedPlatform)
} else {
Err(Error::Disabled)
}
if cfg!(feature = "cuda-driver") { Err(Error::UnsupportedPlatform) } else { Err(Error::Disabled) }
}
pub(crate) fn load_fixed_module(&self, _: FixedOperation) -> Result<ModuleHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn fixed_function(
&self,
module: ModuleHandle,
operation: FixedOperation,
) -> Result<FunctionHandle> {
pub(crate) fn fixed_function(&self, module: ModuleHandle, operation: FixedOperation) -> Result<FunctionHandle> {
if let FixedOperation::Projection(kind) = operation {
let _ = projection_entry(kind);
}
@@ -242,12 +209,7 @@ impl Api {
let _ = module.0;
Err(Error::UnsupportedPlatform)
}
pub(crate) fn launch(
&self,
function: FunctionHandle,
_: u32,
arguments: &mut LaunchArguments,
) -> Result<()> {
pub(crate) fn launch(&self, function: FunctionHandle, _: u32, arguments: &mut LaunchArguments) -> Result<()> {
let _ = (function.0, arguments.storage);
Err(Error::UnsupportedPlatform)
}
@@ -367,12 +329,7 @@ impl Api {
pub(crate) fn copy_moe_down(&self, _: BufferHandle, _: BufferHandle) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_original_down_group(
&self,
_: BufferHandle,
_: BufferHandle,
_: usize,
) -> Result<()> {
pub(crate) fn copy_original_down_group(&self, _: BufferHandle, _: BufferHandle, _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
}
@@ -5,11 +5,7 @@ use super::*;
#[cfg(all(
test,
not(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))
not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))
))]
impl ContextHandle {
pub(in super::super) fn synthetic(address: usize) -> Self {
@@ -25,20 +21,13 @@ impl BufferHandle {
handle.validate_projection_extent(bytes, 16)?;
Ok(handle)
}
pub(crate) fn checked_subspan(
self,
allocation: usize,
offset: usize,
bytes: usize,
) -> Result<Self> {
pub(crate) fn checked_subspan(self, allocation: usize, offset: usize, bytes: usize) -> Result<Self> {
self.validate_extent(allocation)?;
if bytes == 0 || offset.checked_add(bytes).is_none_or(|end| end > allocation) {
return Err(Error::InvalidSize);
}
let address = self
.0
.checked_add(u64::try_from(offset).map_err(|_| Error::InvalidSize)?)
.ok_or(Error::InvalidSize)?;
let address =
self.0.checked_add(u64::try_from(offset).map_err(|_| Error::InvalidSize)?).ok_or(Error::InvalidSize)?;
let result = Self(address);
result.validate_extent(bytes)?;
Ok(result)
@@ -55,28 +44,19 @@ impl BufferHandle {
}
pub(crate) fn validate_projection_extent(self, bytes: usize, alignment: u64) -> Result<()> {
let bytes = u64::try_from(bytes).map_err(|_| Error::InvalidProjectionShape)?;
if self.0 == 0
|| bytes == 0
|| !self.0.is_multiple_of(alignment)
|| self.0.checked_add(bytes).is_none()
{
if self.0 == 0 || bytes == 0 || !self.0.is_multiple_of(alignment) || self.0.checked_add(bytes).is_none() {
return Err(Error::InvalidProjectionShape);
}
Ok(())
}
// Admission validates both extents before this half-open range comparison.
pub(crate) fn overlaps(self, bytes: usize, other: Self, other_bytes: usize) -> bool {
self.0 < other.0.saturating_add(other_bytes as u64)
&& other.0 < self.0.saturating_add(bytes as u64)
self.0 < other.0.saturating_add(other_bytes as u64) && other.0 < self.0.saturating_add(bytes as u64)
}
// A pointer `offset` bytes into an allocation the facade already admitted whole (experimental attention
// scratch: three partial buffers share one allocation). Overflow refuses.
pub(in super::super) fn experimental_offset(self, offset: u64) -> Result<Self> {
Ok(Self(
self.0
.checked_add(offset)
.ok_or(Error::InvalidProjectionShape)?,
))
Ok(Self(self.0.checked_add(offset).ok_or(Error::InvalidProjectionShape)?))
}
pub(in super::super) fn moe_group_column(self, total: usize, index: usize) -> Result<Self> {
if !(1..=64).contains(&total) || index >= total {
@@ -84,22 +64,14 @@ impl BufferHandle {
}
self.validate_projection_extent(total * 2560, 4)?;
let offset = u64::try_from(index * 2560).map_err(|_| Error::InvalidProjectionShape)?;
Ok(Self(
self.0
.checked_add(offset)
.ok_or(Error::InvalidProjectionShape)?,
))
Ok(Self(self.0.checked_add(offset).ok_or(Error::InvalidProjectionShape)?))
}
pub(in super::super) fn moe_group_down_column(self, total: usize, index: usize) -> Result<Self> {
if !(1..=64).contains(&total) || index >= total {
return Err(Error::InvalidProjectionShape);
}
self.validate_projection_extent(total * 10240, 4)?;
Ok(Self(
self.0
.checked_add((index * 10240) as u64)
.ok_or(Error::InvalidProjectionShape)?,
))
Ok(Self(self.0.checked_add((index * 10240) as u64).ok_or(Error::InvalidProjectionShape)?))
}
// The only admitted interior address is one of ten fixed MoE Down slots.
pub(crate) fn moe_down_slot(self, slot: u32) -> Result<Self> {
@@ -107,9 +79,7 @@ impl BufferHandle {
return Err(Error::InvalidQwenShape);
}
self.validate_projection_extent(102_400, 4)?;
let offset = u64::from(slot)
.checked_mul(10_240)
.ok_or(Error::InvalidQwenShape)?;
let offset = u64::from(slot).checked_mul(10_240).ok_or(Error::InvalidQwenShape)?;
let address = self.0.checked_add(offset).ok_or(Error::InvalidQwenShape)?;
let end = address.checked_add(10_240).ok_or(Error::InvalidQwenShape)?;
if end > self.0.checked_add(102_400).ok_or(Error::InvalidQwenShape)? {
@@ -129,14 +99,10 @@ pub(super) fn projection_ptx(kind: ProjectionKind) -> Option<&'static [u8]> {
match kind {
// Root-delivered STRA-146 frozen artifact341abbd0; independent
// installed-Driver proof precedes this bounded public composition.
ProjectionKind::Dense(DenseFormat::Q8_0) => {
Some(concat!(include_str!("../q8_0_q8_1.ptx"), "\0").as_bytes())
}
ProjectionKind::Dense(DenseFormat::Q8_0) => Some(concat!(include_str!("../q8_0_q8_1.ptx"), "\0").as_bytes()),
// Source-qualified STRA-154 Q4_K dense artifact; its independent
// qualification receipt is 017f1d90. Keep the original dense entry.
ProjectionKind::Dense(DenseFormat::Q4_K) => {
Some(concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes())
}
ProjectionKind::Dense(DenseFormat::Q4_K) => Some(concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes()),
// Root-delivered STRA-148 frozen routed artifact f9c10814; its
// standalone installed-Driver proof is distinct from composition.
ProjectionKind::Routed(RoutedFormat::IQ3_XXS) => {
@@ -153,32 +119,24 @@ pub(super) fn projection_ptx(kind: ProjectionKind) -> Option<&'static [u8]> {
}
// Root-delivered STRA-151 frozen paired IQ4_NL artifact 189b02ce.
// One module contains the separately named dense and routed entries.
ProjectionKind::Dense(DenseFormat::IQ4_NL)
| ProjectionKind::Routed(RoutedFormat::IQ4_NL) => {
ProjectionKind::Dense(DenseFormat::IQ4_NL) | ProjectionKind::Routed(RoutedFormat::IQ4_NL) => {
Some(concat!(include_str!("../iq4_nl_q8_1.ptx"), "\0").as_bytes())
}
// Root-delivered STRA-152 frozen paired IQ4_XS artifact 2c853bad.
// Its dense and routed entries share one isolated cache module.
ProjectionKind::Dense(DenseFormat::IQ4_XS)
| ProjectionKind::Routed(RoutedFormat::IQ4_XS) => {
ProjectionKind::Dense(DenseFormat::IQ4_XS) | ProjectionKind::Routed(RoutedFormat::IQ4_XS) => {
Some(concat!(include_str!("../iq4_xs_q8_1.ptx"), "\0").as_bytes())
}
// STRA-153 qualified the routed Q2_0 artifact independently (exact
// producer source SHA-256: 8e81dbbaa76d8516476339c168f1d9c172341a78ccecda08714a13a5687e3b6e).
// This fixed arm only composes that frozen asset; public GPU parity is
// still a separate STRA-154 acceptance gate.
ProjectionKind::Routed(RoutedFormat::Q2_0) => {
Some(concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes())
}
ProjectionKind::Routed(RoutedFormat::Q2_0) => Some(concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes()),
}
}
#[cfg(any(
test,
all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
)
all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")
))]
pub(super) fn validate_projection_ptx(bytes: &[u8]) -> Result<()> {
// Installed Driver JIT rejects non-ASCII comment bytes even when ptxas
@@ -207,19 +165,11 @@ pub(super) fn projection_entry(kind: ProjectionKind) -> &'static std::ffi::CStr
}
#[cfg(any(
test,
all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
)
all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")
))]
impl ModuleHandle {
pub(in super::super) fn qwen_success(address: usize) -> Result<Self> {
if address == 0 {
Err(Error::InvalidDriverValue("cuModuleLoadData"))
} else {
Ok(Self(address))
}
if address == 0 { Err(Error::InvalidDriverValue("cuModuleLoadData")) } else { Ok(Self(address)) }
}
}
#[cfg(test)]
@@ -5,19 +5,11 @@ use super::*;
#[cfg(any(
test,
all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
)
all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")
))]
impl FunctionHandle {
pub(in super::super) fn qwen_success(address: usize) -> Result<Self> {
if address == 0 {
Err(Error::InvalidDriverValue("cuModuleGetFunction"))
} else {
Ok(Self(address))
}
if address == 0 { Err(Error::InvalidDriverValue("cuModuleGetFunction")) } else { Ok(Self(address)) }
}
}
#[cfg(test)]
@@ -42,9 +34,7 @@ impl LaunchArguments {
}
(*storage).parameters[3] = (&raw mut (*storage).count).cast();
}
Self {
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
}
Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") }
}
}
impl Drop for LaunchArguments {
@@ -71,9 +61,7 @@ impl GrReadGuardArguments {
(*raw).parameters[i] = (&raw mut (*raw).addresses[i]).cast();
}
}
Self {
storage: std::ptr::NonNull::new(raw).expect("Box non-null"),
}
Self { storage: std::ptr::NonNull::new(raw).expect("Box non-null") }
}
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
@@ -108,18 +96,11 @@ impl MatvecArguments {
(*storage).parameters[3] = (&raw mut (*storage).rows).cast();
(*storage).parameters[4] = (&raw mut (*storage).columns).cast();
}
Self {
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
}
Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") }
}
}
impl Q8QuantizeArguments {
pub(crate) fn new(
input: BufferHandle,
scratch: BufferHandle,
status: BufferHandle,
elements: u32,
) -> Self {
pub(crate) fn new(input: BufferHandle, scratch: BufferHandle, status: BufferHandle, elements: u32) -> Self {
let storage = Box::into_raw(Box::new(Q8QuantizeStorage {
addresses: [input.0, scratch.0, status.0],
elements,
@@ -132,9 +113,7 @@ impl Q8QuantizeArguments {
}
(*storage).parameters[3] = (&raw mut (*storage).elements).cast();
}
Self {
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
}
Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") }
}
}
impl Drop for Q8QuantizeArguments {
@@ -165,9 +144,7 @@ impl Q6ProjectionArguments {
(*storage).parameters[3] = (&raw mut (*storage).rows).cast();
(*storage).parameters[4] = (&raw mut (*storage).columns).cast();
}
Self {
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
}
Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") }
}
}
impl Drop for Q6ProjectionArguments {
@@ -198,9 +175,7 @@ impl ProjectionArguments {
(*storage).parameters[3] = (&raw mut (*storage).rows).cast();
(*storage).parameters[4] = (&raw mut (*storage).columns).cast();
}
Self {
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
}
Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") }
}
}
impl Drop for ProjectionArguments {
@@ -231,8 +206,6 @@ impl Q5ProjectionArguments {
(*storage).parameters[3] = (&raw mut (*storage).rows).cast();
(*storage).parameters[4] = (&raw mut (*storage).columns).cast();
}
Self {
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
}
Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") }
}
}
+16 -67
View File
@@ -3,14 +3,8 @@
use super::*;
#[test]
fn new_fixed_asset_encoding_refuses_unicode_before_driver_call() {
assert_eq!(
validate_projection_ptx(include_bytes!("../q6_k_q8_1.ptx")),
Ok(())
);
assert_eq!(
validate_projection_ptx(include_bytes!("../q8_1_quantize.ptx")),
Ok(())
);
assert_eq!(validate_projection_ptx(include_bytes!("../q6_k_q8_1.ptx")), Ok(()));
assert_eq!(validate_projection_ptx(include_bytes!("../q8_1_quantize.ptx")), Ok(()));
assert_eq!(validate_projection_ptx(b"// plain ASCII\n\0"), Ok(()));
assert_eq!(
validate_projection_ptx("// \u{d7}\n\0".as_bytes()),
@@ -21,10 +15,7 @@ fn new_fixed_asset_encoding_refuses_unicode_before_driver_call() {
fn q4_k_dense_selector_resolves_only_its_qualified_asset() {
let kind = ProjectionKind::Dense(DenseFormat::Q4_K);
let bytes = projection_ptx(kind).expect("fixed Q4_K asset is integrated");
assert_eq!(
bytes,
concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes()
);
assert_eq!(bytes, concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes());
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(projection_entry(kind).to_bytes(), b"leleka_q4_k_q8_1_dense");
}
@@ -32,43 +23,25 @@ fn q4_k_dense_selector_resolves_only_its_qualified_asset() {
fn iq3_s_routed_selector_resolves_only_its_qualified_asset() {
let kind = ProjectionKind::Routed(RoutedFormat::IQ3_S);
let bytes = projection_ptx(kind).expect("fixed IQ3_S asset is integrated");
assert_eq!(
bytes,
concat!(include_str!("../iq3_s_q8_1.ptx"), "\0").as_bytes()
);
assert_eq!(bytes, concat!(include_str!("../iq3_s_q8_1.ptx"), "\0").as_bytes());
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(kind).to_bytes(),
b"leleka_iq3_s_q8_1_routed"
);
assert_eq!(projection_entry(kind).to_bytes(), b"leleka_iq3_s_q8_1_routed");
}
#[test]
fn iq2_s_routed_selector_resolves_only_its_qualified_asset() {
let kind = ProjectionKind::Routed(RoutedFormat::IQ2_S);
let bytes = projection_ptx(kind).expect("fixed IQ2_S asset is integrated");
assert_eq!(
bytes,
concat!(include_str!("../iq2_s_q8_1.ptx"), "\0").as_bytes()
);
assert_eq!(bytes, concat!(include_str!("../iq2_s_q8_1.ptx"), "\0").as_bytes());
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(kind).to_bytes(),
b"leleka_iq2_s_q8_1_routed"
);
assert_eq!(projection_entry(kind).to_bytes(), b"leleka_iq2_s_q8_1_routed");
}
#[test]
fn q2_0_routed_selector_resolves_only_its_qualified_asset() {
let kind = ProjectionKind::Routed(RoutedFormat::Q2_0);
let bytes = projection_ptx(kind).expect("fixed Q2_0 asset is integrated");
assert_eq!(
bytes,
concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes()
);
assert_eq!(bytes, concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes());
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(kind).to_bytes(),
b"leleka_q2_0_q8_1_routed"
);
assert_eq!(projection_entry(kind).to_bytes(), b"leleka_q2_0_q8_1_routed");
}
#[test]
fn iq4_nl_dense_and_routed_select_distinct_entries_from_one_asset() {
@@ -78,14 +51,8 @@ fn iq4_nl_dense_and_routed_select_distinct_entries_from_one_asset() {
assert_eq!(projection_ptx(dense), Some(bytes));
assert_eq!(projection_ptx(routed), Some(bytes));
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(dense).to_bytes(),
b"leleka_iq4_nl_q8_1_dense"
);
assert_eq!(
projection_entry(routed).to_bytes(),
b"leleka_iq4_nl_q8_1_routed"
);
assert_eq!(projection_entry(dense).to_bytes(), b"leleka_iq4_nl_q8_1_dense");
assert_eq!(projection_entry(routed).to_bytes(), b"leleka_iq4_nl_q8_1_routed");
}
#[test]
fn iq4_xs_dense_and_routed_select_distinct_entries_from_one_asset() {
@@ -95,38 +62,20 @@ fn iq4_xs_dense_and_routed_select_distinct_entries_from_one_asset() {
assert_eq!(projection_ptx(dense), Some(bytes));
assert_eq!(projection_ptx(routed), Some(bytes));
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(dense).to_bytes(),
b"leleka_iq4_xs_q8_1_dense"
);
assert_eq!(
projection_entry(routed).to_bytes(),
b"leleka_iq4_xs_q8_1_routed"
);
assert_eq!(projection_entry(dense).to_bytes(), b"leleka_iq4_xs_q8_1_dense");
assert_eq!(projection_entry(routed).to_bytes(), b"leleka_iq4_xs_q8_1_routed");
}
#[test]
fn packed_alignment_extents_and_overlap() {
assert_eq!(BufferHandle(2).validate_projection_extent(34, 2), Ok(()));
assert_eq!(
BufferHandle(2).validate_projection_extent(4, 4),
Err(Error::InvalidProjectionShape)
);
assert_eq!(
BufferHandle(u64::MAX - 1).validate_projection_extent(4, 2),
Err(Error::InvalidProjectionShape)
);
assert_eq!(BufferHandle(2).validate_projection_extent(4, 4), Err(Error::InvalidProjectionShape));
assert_eq!(BufferHandle(u64::MAX - 1).validate_projection_extent(4, 2), Err(Error::InvalidProjectionShape));
assert!(BufferHandle(16).overlaps(8, BufferHandle(12), 8));
assert!(!BufferHandle(16).overlaps(8, BufferHandle(8), 8));
}
#[test]
fn common_projection_raw_owner_keeps_exact_parameter_widths() {
let args = ProjectionArguments::new(
BufferHandle(11),
BufferHandle(22),
BufferHandle(33),
129,
u32::MAX,
);
let args = ProjectionArguments::new(BufferHandle(11), BufferHandle(22), BufferHandle(33), 129, u32::MAX);
let pointer = args.storage.as_ptr();
let moved = vec![args].pop().unwrap();
let churn: Vec<_> = (0..1024).map(|_| Box::new([7u64; 8])).collect();
+7 -33
View File
@@ -7,49 +7,23 @@ fn checked_subspan_refuses_empty_wrap_and_outside_allocation() {
assert!(h.checked_subspan(1024, 0, 1024).is_ok());
assert!(h.checked_subspan(1024, 1023, 1).is_ok());
for (offset, bytes) in [(0, 0), (1024, 1), (1023, 2), (usize::MAX, 1)] {
assert!(matches!(
h.checked_subspan(1024, offset, bytes),
Err(Error::InvalidSize)
));
assert!(matches!(h.checked_subspan(1024, offset, bytes), Err(Error::InvalidSize)));
}
assert!(
super::BufferHandle::synthetic(u64::MAX - 2)
.checked_subspan(4, 0, 1)
.is_err()
);
assert!(
super::BufferHandle::synthetic(0)
.checked_subspan(4, 0, 1)
.is_err()
);
assert!(super::BufferHandle::synthetic(u64::MAX - 2).checked_subspan(4, 0, 1).is_err());
assert!(super::BufferHandle::synthetic(0).checked_subspan(4, 0, 1).is_err());
}
use super::*;
#[test]
fn matvec_address_extents() {
assert_eq!(
BufferHandle(0).validate_extent(4),
Err(Error::InvalidMatvecShape)
);
assert_eq!(
BufferHandle(1).validate_extent(0),
Err(Error::InvalidMatvecShape)
);
assert_eq!(
BufferHandle(u64::MAX - 3).validate_extent(4),
Err(Error::InvalidMatvecShape)
);
assert_eq!(BufferHandle(0).validate_extent(4), Err(Error::InvalidMatvecShape));
assert_eq!(BufferHandle(1).validate_extent(0), Err(Error::InvalidMatvecShape));
assert_eq!(BufferHandle(u64::MAX - 3).validate_extent(4), Err(Error::InvalidMatvecShape));
assert_eq!(BufferHandle(u64::MAX - 4).validate_extent(4), Ok(()));
}
#[test]
fn matvec_raw_storage_survives_owner_moves() {
let arguments = MatvecArguments::new(
BufferHandle(11),
BufferHandle(22),
BufferHandle(33),
129,
u32::MAX,
);
let arguments = MatvecArguments::new(BufferHandle(11), BufferHandle(22), BufferHandle(33), 129, u32::MAX);
let pointer = arguments.storage.as_ptr();
let moved = vec![arguments].pop().unwrap();
let churn: Vec<_> = (0..1024).map(|_| Box::new([0xdeadbeefu64; 8])).collect();
+7 -26
View File
@@ -17,10 +17,7 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> {
if stream == 0 {
return Err(Error::InvalidDriverValue("native GDN shared stream"));
}
Ok(Self {
workspace,
stream: GdnStream::from_raw(stream),
})
Ok(Self { workspace, stream: GdnStream::from_raw(stream) })
}
fn enqueue(
@@ -41,8 +38,8 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> {
(10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640)
);
if bf16 {
let interleaved = (shape.rows, shape.depth, shape.ldy) == (48, 2560, 96)
&& matches!(shape.y_offset, 0 | 48);
let interleaved =
(shape.rows, shape.depth, shape.ldy) == (48, 2560, 96) && matches!(shape.y_offset, 0 | 48);
let moe = matches!((shape.rows, shape.depth), (512, 2560) | (1, 2560))
&& shape.ldy == shape.rows
&& shape.y_offset == 0;
@@ -61,8 +58,7 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> {
|| (!bf16
&& w.bytes != matrix_bytes
&& w.bytes != DEQUANT_BYTES
&& !(matches!((shape.rows, shape.depth), (640, 2560) | (2560, 640))
&& w.bytes == 3_276_800))
&& !(matches!((shape.rows, shape.depth), (640, 2560) | (2560, 640)) && w.bytes == 3_276_800))
{
return Err(Error::InvalidQwenShape);
}
@@ -79,10 +75,7 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> {
let xh = x.handle.ok_or(Error::ContextPoisoned)?;
let wh = w.handle.ok_or(Error::ContextPoisoned)?;
let yh = y.handle.ok_or(Error::ContextPoisoned)?;
if xh.overlaps(x.bytes, wh, w.bytes)
|| xh.overlaps(x.bytes, yh, y.bytes)
|| wh.overlaps(w.bytes, yh, y.bytes)
{
if xh.overlaps(x.bytes, wh, w.bytes) || xh.overlaps(x.bytes, yh, y.bytes) || wh.overlaps(w.bytes, yh, y.bytes) {
return Err(Error::OutputAliasesInput);
}
self.workspace.blas()?.gemm_gdn(
@@ -104,22 +97,10 @@ impl GdnGemm for NativeGdnGemm<'_, '_> {
fn stream(&self) -> GdnStream {
self.stream
}
fn f16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
fn f16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> {
self.enqueue(false, x, w, y, shape)
}
fn bf16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
fn bf16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> {
self.enqueue(true, x, w, y, shape)
}
}
+11 -40
View File
@@ -154,10 +154,7 @@ mod tests {
fn column_rows_are_only_whole_batch_multiples_of_one_qkv_row() {
assert_eq!(column_row_offset(QKV_BYTES, 0).unwrap(), 0);
assert_eq!(column_row_offset(3 * QKV_BYTES, 2).unwrap(), 2 * QKV_BYTES);
assert_eq!(
column_row_offset(64 * QKV_BYTES, 63).unwrap(),
63 * QKV_BYTES
);
assert_eq!(column_row_offset(64 * QKV_BYTES, 63).unwrap(), 63 * QKV_BYTES);
for (total, row) in [
(0, 0),
(QKV_BYTES - 4, 0),
@@ -166,10 +163,7 @@ mod tests {
(65 * QKV_BYTES, 0),
(QKV_BYTES, usize::MAX),
] {
assert!(matches!(
column_row_offset(total, row),
Err(Error::InvalidQwenShape)
));
assert!(matches!(column_row_offset(total, row), Err(Error::InvalidQwenShape)));
}
}
@@ -204,15 +198,9 @@ mod tests {
assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap().1, None);
words[GdnQueueStage::Gate.slot()] = 1;
words[GdnQueueStage::NextState.slot()] = 1;
assert_eq!(
decode_statuses(&bytes(&words), SLOTS).unwrap().1,
Some(GdnQueueStage::Gate)
);
assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap().1, Some(GdnQueueStage::Gate));
words[GdnQueueStage::Alpha.slot()] = 1;
assert_eq!(
decode_statuses(&bytes(&words), SLOTS).unwrap().1,
Some(GdnQueueStage::Alpha)
);
assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap().1, Some(GdnQueueStage::Alpha));
}
#[test]
@@ -220,41 +208,24 @@ mod tests {
let mut words = [0u32; SLOTS];
words[GdnQueueStage::Z.slot()] = 1;
// Only the first Z-1 stages were admitted: a set unused slot is invalid.
assert!(matches!(
decode_statuses(&bytes(&words), GdnQueueStage::Z.slot()),
Err(Error::InvalidDriverValue(_))
));
assert!(matches!(decode_statuses(&bytes(&words), GdnQueueStage::Z.slot()), Err(Error::InvalidDriverValue(_))));
words[GdnQueueStage::Z.slot()] = 2;
assert!(matches!(
decode_statuses(&bytes(&words), SLOTS),
Err(Error::InvalidDriverValue(_))
));
assert!(matches!(
decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS),
Err(Error::InvalidQwenShape)
));
assert!(matches!(
decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1),
Err(Error::InvalidQwenShape)
));
assert!(matches!(decode_statuses(&bytes(&words), SLOTS), Err(Error::InvalidDriverValue(_))));
assert!(matches!(decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), Err(Error::InvalidQwenShape)));
assert!(matches!(decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), Err(Error::InvalidQwenShape)));
}
}
#[cfg(all(
test,
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gdn_closed_queue_gpu.rs"]
mod gpu;
#[path = "gdn_closed_queue/impl_gdnqueuestage.rs"]
mod impl_gdnqueuestage;
#[allow(unused_imports)]
use impl_gdnqueuestage::decode_statuses;
#[allow(unused_imports)]
use impl_gdnqueuestage::column_row_offset;
#[allow(unused_imports)]
use impl_gdnqueuestage::decode_statuses;
#[path = "gdn_closed_queue/impl_gdnrowprefix.rs"]
mod impl_gdnrowprefix;
#[path = "gdn_closed_queue/impl_gdnrowqueue.rs"]
@@ -48,11 +48,7 @@ pub(super) fn decode_statuses(bytes: &[u8], checks: usize) -> Result<([u32; SLOT
return Err(Error::InvalidDriverValue("GDN row numeric witness"));
}
}
let refusal = decoded
.iter()
.take(checks)
.position(|status| *status != 0)
.map(|slot| STAGES[slot]);
let refusal = decoded.iter().take(checks).position(|status| *status != 0).map(|slot| STAGES[slot]);
Ok((decoded, refusal))
}
@@ -95,32 +91,19 @@ impl<'ctx> GdnRowQueue<'ctx> {
return Err(Error::ContextPoisoned);
}
for operation in OPS {
qwen_ffi::asset(operation)
.ok_or(Error::UnsupportedQwenOperation)?
.validate(operation)?;
qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?;
}
if context
.allocated_bytes()
.checked_add(STATUS_BYTES)
.is_none_or(|n| n > context.budget)
{
if context.allocated_bytes().checked_add(STATUS_BYTES).is_none_or(|n| n > context.budget) {
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
context,
status: None,
module: None,
kernels: None,
failed: false,
};
let mut owner = Self { context, status: None, module: None, kernels: None, failed: false };
let result = (|| {
owner.status = Some(context.allocate(STATUS_BYTES)?);
let guard = context.enter()?;
let load = (|| {
let mut qwen = [None; 6];
for (i, operation) in OPS.into_iter().enumerate() {
let asset =
qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?;
let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?;
qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function);
}
let module = context.driver.api.load_mmq_resident()?;
@@ -172,12 +155,9 @@ impl<'ctx> GdnRowQueue<'ctx> {
pub fn begin<'lease>(&'lease mut self) -> Result<GdnRowPrefix<'lease, 'ctx>> {
self.status_handle()?;
let mut held = Vec::new();
held.try_reserve_exact(24)
.map_err(|_| Error::HostAllocation)?;
held.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?;
let mut commands = Vec::new();
commands
.try_reserve_exact(24)
.map_err(|_| Error::HostAllocation)?;
commands.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?;
Ok(GdnRowPrefix {
queue: self,
held,
@@ -3,8 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
pub(in super::super) fn ready(&self, step: Step) -> Result<()> {
if let Some(error) = &self.refusal {
@@ -93,9 +91,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
}
let words = stage.words();
let queue = &*self.queue;
let status = queue
.status_handle()?
.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?;
let status = queue.status_handle()?.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?;
let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.finite;
self.commands.push(Command::Guard(
function,
@@ -112,11 +108,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
/// `tokens x 10,240` F32 owner of one batched projection; the fixed
/// 40,960 B row range is derived here (never caller supplied) exactly as the
/// recurrence derives its Q/K/V ranges from completed whole producers.
pub fn scan_qkv_columns(
&mut self,
columns: &'lease DeviceBuffer<'lease>,
row: usize,
) -> Result<()> {
pub fn scan_qkv_columns(&mut self, columns: &'lease DeviceBuffer<'lease>, row: usize) -> Result<()> {
let result = (|| {
self.ready(Step::Alpha)?;
if self.checks != 0 || self.columns.is_some() {
@@ -228,15 +220,9 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
self.commands.push(Command::Qwen(
function,
Operation::GdnConv,
Box::new(Arguments::with_layout(
Operation::GdnConv,
original,
handles,
0.0,
)),
Box::new(Arguments::with_layout(Operation::GdnConv, original, handles, 0.0)),
));
self.held
.extend_from_slice(&[history, columns, weights, next_history, raw, h]);
self.held.extend_from_slice(&[history, columns, weights, next_history, raw, h]);
self.push_scan(GdnQueueStage::ConvRaw, raw)?;
self.push_scan(GdnQueueStage::NextHistory, next_history)?;
self.push_scan(GdnQueueStage::ConvH, h)?;
@@ -3,8 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
/// Original Q/K L2 kernel into the whole 10,240-word slot; the scan covers
/// the initialized tail too, as the scalar chain's full readback did.
@@ -84,17 +82,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
// Admit the WHOLE real allocations, including aliases outside the
// consumed ranges, before deriving any private pointer operands.
let mut whole = original;
whole.bytes = [
STATE_BYTES,
QK_BYTES,
QK_BYTES,
192,
192,
STATE_BYTES,
24_576,
0,
0,
];
whole.bytes = [STATE_BYTES, QK_BYTES, QK_BYTES, 192, 192, STATE_BYTES, 24_576, 0, 0];
whole.align = [4; 9];
whole.count = 7;
whole.outputs = 0b110_0000;
@@ -119,23 +107,15 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
let q = owners[1].checked_subspan(QK_BYTES, 0, 8192)?;
let k = owners[1].checked_subspan(QK_BYTES, 8192, 8192)?;
let v = owners[2].checked_subspan(QK_BYTES, 16_384, 24_576)?;
let handles = [
owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0],
];
let handles = [owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0]];
ranges_layout(Operation::GdnStep, original, handles, original.bytes, false)?;
let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[STEP];
self.commands.push(Command::Qwen(
function,
Operation::GdnStep,
Box::new(Arguments::with_layout(
Operation::GdnStep,
original,
handles,
0.0,
)),
Box::new(Arguments::with_layout(Operation::GdnStep, original, handles, 0.0)),
));
self.held
.extend_from_slice(&[state, qk, h, gate, beta, next_state, readout]);
self.held.extend_from_slice(&[state, qk, h, gate, beta, next_state, readout]);
// Earliest full-state refusal precedes the readout, as before.
self.push_scan(GdnQueueStage::NextState, next_state)?;
self.push_scan(GdnQueueStage::Readout, readout)?;
@@ -207,11 +187,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
}
Ok(GdnRowCompletion {
refusal: drained.refusal,
next_history: if drained.refusal.is_none() {
drained.next_history
} else {
None
},
next_history: if drained.refusal.is_none() { drained.next_history } else { None },
})
}
}
@@ -3,33 +3,21 @@
#[allow(unused_imports)]
use super::*;
impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
pub(in super::super) fn drain(mut self, fetch: bool) -> Result<Drained> {
let status = self.queue.status_handle()?;
let mut statuses = staging(STATUS_BYTES)?;
let write_fetch = fetch && self.refusal.is_none();
let mut fetched = staging(if write_fetch { HISTORY_BYTES } else { 0 })?;
if !self.commands.is_empty() {
let zero = self
.queue
.kernels
.as_ref()
.ok_or(Error::ContextPoisoned)?
.zero;
let zero = self.queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.zero;
let mut reset = ffi::MmqResidentArguments::zero(status, SLOTS as u32);
let context = self.queue.context;
let guard = context.enter().inspect_err(|_| {
self.queue.failed = true;
context.poisoned.set(true);
})?;
let mut operation =
context
.driver
.api
.launch_mmq_resident(zero, SLOTS as u32, &mut reset);
let mut operation = context.driver.api.launch_mmq_resident(zero, SLOTS as u32, &mut reset);
for command in &mut self.commands {
if operation.is_err() {
break;
@@ -53,8 +41,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
// Completion is uncertain: retain every actual argument/staging
// owner and every borrowed buffer; Context poison forbids reuse.
std::mem::forget((reset, self.commands, self.held, statuses, fetched));
return combine(combine(operation, sync), pop)
.map(|()| unreachable!("uncertain GDN row drain"));
return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain GDN row drain"));
}
combine(combine(operation, sync), pop)?;
}
@@ -68,24 +55,12 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> {
};
let next_history = if write_fetch && refusal.is_none() {
let mut values = Vec::new();
values
.try_reserve_exact(HISTORY_BYTES / 4)
.map_err(|_| Error::HostAllocation)?;
values.extend(
fetched
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word)),
);
values.try_reserve_exact(HISTORY_BYTES / 4).map_err(|_| Error::HostAllocation)?;
values.extend(fetched.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word)));
Some(values.into_boxed_slice())
} else {
None
};
Ok(Drained {
refusal,
deferred: self.refusal,
next_history,
})
Ok(Drained { refusal, deferred: self.refusal, next_history })
}
}
@@ -3,7 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl GdnRowQueue<'_> {
pub(super) fn close_inner(&mut self) -> Result<()> {
self.failed = true;
@@ -51,9 +50,7 @@ impl Drop for GdnRowQueue<'_> {
}
pub(super) fn staging(bytes: usize) -> Result<Vec<u8>> {
let mut result = Vec::new();
result
.try_reserve_exact(bytes)
.map_err(|_| Error::HostAllocation)?;
result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?;
result.resize(bytes, 0);
Ok(result)
}
+30 -155
View File
@@ -70,42 +70,11 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() {
}
// Earliest refusal in program order, then the queue stays usable.
let cases = [
(
Poison {
alpha: true,
..Poison::default()
},
GdnQueueStage::Alpha,
),
(
Poison {
conv_weights: true,
..Poison::default()
},
GdnQueueStage::ConvRaw,
),
(
Poison {
state: true,
..Poison::default()
},
GdnQueueStage::NextState,
),
(
Poison {
z: true,
..Poison::default()
},
GdnQueueStage::Z,
),
(
Poison {
alpha: true,
z: true,
..Poison::default()
},
GdnQueueStage::Alpha,
),
(Poison { alpha: true, ..Poison::default() }, GdnQueueStage::Alpha),
(Poison { conv_weights: true, ..Poison::default() }, GdnQueueStage::ConvRaw),
(Poison { state: true, ..Poison::default() }, GdnQueueStage::NextState),
(Poison { z: true, ..Poison::default() }, GdnQueueStage::Z),
(Poison { alpha: true, z: true, ..Poison::default() }, GdnQueueStage::Alpha),
];
for (poison, stage) in cases {
refusal_case(&context, &mut queue, poison, stage, &mut report)?;
@@ -114,36 +83,9 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() {
// Retained batched QKV rows: first, middle and last of a 3-row and a
// 64-row batch; a poisoned OTHER row is irrelevant, the USED row refuses.
for (tokens, used) in [(3usize, 0usize), (3, 1), (3, 2), (64, 63)] {
columns_pair(
&context,
&mut queue,
8,
tokens,
used,
false,
false,
&mut report,
)?;
columns_pair(
&context,
&mut queue,
8,
tokens,
used,
false,
true,
&mut report,
)?;
columns_pair(
&context,
&mut queue,
8,
tokens,
used,
true,
false,
&mut report,
)?;
columns_pair(&context, &mut queue, 8, tokens, used, false, false, &mut report)?;
columns_pair(&context, &mut queue, 8, tokens, used, false, true, &mut report)?;
columns_pair(&context, &mut queue, 8, tokens, used, true, false, &mut report)?;
clean_pair(&context, &mut queue, 3, &mut report)?;
}
// Program order, data flow, aliasing, context and shape admission.
@@ -153,14 +95,7 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() {
// Convolution before the two input scans.
let mut prefix = queue.begin()?;
refuse(
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
),
prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h),
Error::InvalidQwenShape,
&mut report,
)?;
@@ -169,57 +104,27 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() {
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
refuse(
prefix.qk_l2(&row.raw, &row.qk, EPSILON),
Error::InvalidQwenShape,
&mut report,
)?;
prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?;
refuse(prefix.qk_l2(&row.raw, &row.qk, EPSILON), Error::InvalidQwenShape, &mut report)?;
// A latched admission error still drains the admitted prefix first.
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
// Recurrence whose current state and next state are one owner.
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?;
prefix.qk_l2(&row.h, &row.qk, EPSILON)?;
prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?;
prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?;
refuse(
prefix.recurrence(
&row.state,
&row.qk,
&row.h,
&row.gate,
&row.sigmoid,
&row.state,
&row.readout,
),
prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.state, &row.readout),
Error::OutputAliasesInput,
&mut report,
)?;
refuse(prefix.finish(), Error::OutputAliasesInput, &mut report)?;
// A buffer from another Context.
let mut prefix = queue.begin()?;
refuse(
prefix.scan_alpha(&other.alpha),
Error::ContextMismatch,
&mut report,
)?;
refuse(prefix.scan_alpha(&other.alpha), Error::ContextMismatch, &mut report)?;
refuse(prefix.finish(), Error::ContextMismatch, &mut report)?;
// A whole buffer of the wrong size.
let short = blank(&context, 47)?;
@@ -233,19 +138,8 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() {
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
refuse(
prefix.fetch_next_history(&row.history),
Error::InvalidQwenShape,
&mut report,
)?;
prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?;
refuse(prefix.fetch_next_history(&row.history), Error::InvalidQwenShape, &mut report)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
@@ -258,32 +152,17 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() {
let image = upload(&context, &column_image(1, 3, 1))?;
let admission = (|| -> Result<()> {
let mut prefix = queue.begin()?;
refuse(
prefix.scan_qkv_columns(&ragged, 0),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.scan_qkv_columns(&ragged, 0), Error::InvalidQwenShape, &mut report)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
let mut prefix = queue.begin()?;
refuse(
prefix.scan_qkv_columns(&image, 3),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.scan_qkv_columns(&image, 3), Error::InvalidQwenShape, &mut report)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
let mut prefix = queue.begin()?;
prefix.scan_qkv_columns(&image, 1)?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
refuse(
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
),
prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h),
Error::InvalidQwenShape,
&mut report,
)?;
@@ -308,11 +187,7 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() {
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
refuse(
prefix.scan_qkv_columns(&image, 1),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.scan_qkv_columns(&image, 1), Error::InvalidQwenShape, &mut report)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
// The retained-row conv over another owner than the scanned one.
let mut prefix = queue.begin()?;
@@ -359,32 +234,32 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() {
#[path = "gdn_closed_queue_gpu/bytes_fn.rs"]
mod bytes_fn;
#[allow(unused_imports)]
use bytes_fn::bytes;
#[allow(unused_imports)]
use bytes_fn::upload;
#[allow(unused_imports)]
use bytes_fn::blank;
#[allow(unused_imports)]
use bytes_fn::read;
use bytes_fn::bytes;
#[allow(unused_imports)]
use bytes_fn::column_image;
#[allow(unused_imports)]
use bytes_fn::pattern;
#[allow(unused_imports)]
use bytes_fn::scalar;
#[allow(unused_imports)]
use bytes_fn::queued;
#[allow(unused_imports)]
use bytes_fn::queued_columns;
#[allow(unused_imports)]
use bytes_fn::column_image;
use bytes_fn::read;
#[allow(unused_imports)]
use bytes_fn::scalar;
#[allow(unused_imports)]
use bytes_fn::upload;
#[path = "gdn_closed_queue_gpu/columns_pair_fn.rs"]
mod columns_pair_fn;
#[allow(unused_imports)]
use columns_pair_fn::clean_pair;
#[allow(unused_imports)]
use columns_pair_fn::columns_pair;
#[allow(unused_imports)]
use columns_pair_fn::compare;
#[allow(unused_imports)]
use columns_pair_fn::clean_pair;
#[allow(unused_imports)]
use columns_pair_fn::refusal_case;
#[allow(unused_imports)]
use columns_pair_fn::refuse;
@@ -3,7 +3,6 @@
#[allow(unused_imports)]
use super::*;
pub(super) fn bytes(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
@@ -23,9 +22,7 @@ pub(super) fn read(buffer: &DeviceBuffer<'_>) -> Result<Vec<u8>> {
Ok(out)
}
pub(super) fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, offset: f32) -> Vec<f32> {
(0..count)
.map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset)
.collect()
(0..count).map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset).collect()
}
impl<'a> Row<'a> {
pub(super) fn new(context: &'a Context<'_>, salt: usize, poison: Poison) -> Result<Self> {
@@ -34,9 +31,7 @@ impl<'a> Row<'a> {
if poison.alpha {
alpha[47] = nan;
}
let mut weights = (0..4 * CHANNELS)
.map(|i| [0.25, 0.5, -0.25, 0.125][(i + salt) % 4])
.collect::<Vec<f32>>();
let mut weights = (0..4 * CHANNELS).map(|i| [0.25, 0.5, -0.25, 0.125][(i + salt) % 4]).collect::<Vec<f32>>();
if poison.conv_weights {
weights[4 * CHANNELS - 1] = nan;
}
@@ -119,14 +114,7 @@ impl<'a> Row<'a> {
/// Independent original sequence: every launch separately completed.
pub(super) fn scalar(context: &Context<'_>, row: &mut Row<'_>) -> Result<()> {
context.gdn_conv_silu_f32(
&row.history,
&row.qkv,
&row.weights,
&mut row.next_history,
&mut row.raw,
&mut row.h,
)?;
context.gdn_conv_silu_f32(&row.history, &row.qkv, &row.weights, &mut row.next_history, &mut row.raw, &mut row.h)?;
context.gdn_qk_l2_f32(&row.h, &mut row.qk, EPSILON)?;
context.gdn_beta_sigmoid_f32(&row.beta_raw, &mut row.sigmoid)?;
context.gdn_gate_softplus_f32(&row.alpha, &row.dt, &row.a, &mut row.gate)?;
@@ -139,39 +127,18 @@ pub(super) fn scalar(context: &Context<'_>, row: &mut Row<'_>) -> Result<()> {
&mut row.next_state,
&mut row.readout,
)?;
context.gdn_out_norm_f32(
&row.readout,
&row.z,
&row.gamma,
&mut row.normalized,
EPSILON,
)
context.gdn_out_norm_f32(&row.readout, &row.z, &row.gamma, &mut row.normalized, EPSILON)
}
pub(super) fn queued<'q>(queue: &'q mut GdnRowQueue<'_>, row: &'q Row<'_>) -> Result<GdnRowCompletion> {
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?;
prefix.qk_l2(&row.h, &row.qk, EPSILON)?;
prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?;
prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?;
prefix.recurrence(
&row.state,
&row.qk,
&row.h,
&row.gate,
&row.sigmoid,
&row.next_state,
&row.readout,
)?;
prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.next_state, &row.readout)?;
prefix.scan_z(&row.z)?;
prefix.out_norm(&row.readout, &row.z, &row.gamma, &row.normalized, EPSILON)?;
prefix.fetch_next_history(&row.next_history)?;
@@ -190,27 +157,11 @@ pub(super) fn queued_columns<'q>(
prefix.scan_qkv_columns(columns, index)?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu_columns(
&row.history,
columns,
index,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
prefix.conv_silu_columns(&row.history, columns, index, &row.weights, &row.next_history, &row.raw, &row.h)?;
prefix.qk_l2(&row.h, &row.qk, EPSILON)?;
prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?;
prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?;
prefix.recurrence(
&row.state,
&row.qk,
&row.h,
&row.gate,
&row.sigmoid,
&row.next_state,
&row.readout,
)?;
prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.next_state, &row.readout)?;
prefix.scan_z(&row.z)?;
prefix.out_norm(&row.readout, &row.z, &row.gamma, &row.normalized, EPSILON)?;
prefix.fetch_next_history(&row.next_history)?;
@@ -221,11 +172,7 @@ pub(super) fn queued_columns<'q>(
pub(super) fn column_image(salt: usize, tokens: usize, used: usize) -> Vec<f32> {
let mut image = Vec::with_capacity(tokens * CHANNELS);
for row in 0..tokens {
let source = if row == used {
salt + 1
} else {
salt + 40 + row
};
let source = if row == used { salt + 1 } else { salt + 40 + row };
image.extend(pattern(CHANNELS, source, 29, 1.0 / 64.0, 0.21));
}
image
@@ -3,7 +3,6 @@
#[allow(unused_imports)]
use super::*;
/// Retained-row QKV must match the original sequence over the same row bit for
/// bit; non-finite words in OTHER rows must not matter, in the used row they
/// must refuse at the first stage.
@@ -43,9 +42,8 @@ pub(super) fn columns_pair(
}
return Ok(());
}
let history = completion
.into_next_history()
.map_err(|_| Error::InvalidDriverValue("unexpected GDN column refusal"))?;
let history =
completion.into_next_history().map_err(|_| Error::InvalidDriverValue("unexpected GDN column refusal"))?;
let found = actual.products()?;
compare(&expected, &found, report);
if bytes(&history) != found[0] {
@@ -54,10 +52,7 @@ pub(super) fn columns_pair(
report.rows += 1;
Ok(())
})();
combine(
combine(combine(operation, old.release()), actual.release()),
columns.release(),
)
combine(combine(combine(operation, old.release()), actual.release()), columns.release())
}
pub(super) fn compare(old: &[Vec<u8>], actual: &[Vec<u8>], report: &mut Report) {
@@ -87,9 +82,8 @@ pub(super) fn clean_pair(
if completion.numerical_refusal().is_some() {
return Err(Error::InvalidDriverValue("unexpected GDN row refusal"));
}
let history = completion
.into_next_history()
.map_err(|_| Error::InvalidDriverValue("missing GDN next history"))?;
let history =
completion.into_next_history().map_err(|_| Error::InvalidDriverValue("missing GDN next history"))?;
let found = actual.products()?;
compare(&expected, &found, report);
// The fetched canonical history is exactly the next-history owner.
@@ -113,9 +107,7 @@ pub(super) fn refusal_case(
let operation = (|| {
let completion = queued(queue, &row)?;
report.guards += 1;
if completion.numerical_refusal() != Some(expected)
|| completion.into_next_history().err() != Some(expected)
{
if completion.numerical_refusal() != Some(expected) || completion.into_next_history().err() != Some(expected) {
report.differences += 1;
} else {
report.refusals += 1;
+14 -44
View File
@@ -50,8 +50,8 @@ pub const GDN_FUSED_T1_PERSISTENT_BYTES: usize = STATUS_BYTES;
const FUSED_PTX_LEN: usize = 51663;
// TODO-ROOT: sha256 of offline_gdn_fused_t1.ptx (without the trailing NUL).
const FUSED_PTX_SHA256: [u8; 32] = [
123, 208, 9, 9, 39, 60, 65, 6, 85, 195, 225, 120, 30, 88, 210, 26, 225, 84, 24, 31, 189, 116,
198, 178, 17, 85, 116, 140, 151, 3, 93, 211,
123, 208, 9, 9, 39, 60, 65, 6, 85, 195, 225, 120, 30, 88, 210, 26, 225, 84, 24, 31, 189, 116, 198, 178, 17, 85,
116, 140, 151, 3, 93, 211,
];
// ------------------------------------------------------------------ kernel table
@@ -228,17 +228,7 @@ mod tests {
seen.push(step);
step = step.next();
}
assert_eq!(
seen,
[
Step::Inputs,
Step::Seed,
Step::Conv,
Step::Ab,
Step::Norm,
Step::Fetch
]
);
assert_eq!(seen, [Step::Inputs, Step::Seed, Step::Conv, Step::Ab, Step::Norm, Step::Fetch]);
assert_eq!(Step::Done.next(), Step::Done);
}
@@ -248,15 +238,9 @@ mod tests {
assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), None);
statuses[GdnFusedStage::Gate.slot()] = 1;
statuses[GdnFusedStage::State.slot()] = 1;
assert_eq!(
decode_statuses(&bytes(&statuses), SLOTS).unwrap(),
Some(GdnFusedStage::Gate)
);
assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), Some(GdnFusedStage::Gate));
statuses[GdnFusedStage::Qkv.slot()] = 1;
assert_eq!(
decode_statuses(&bytes(&statuses), SLOTS).unwrap(),
Some(GdnFusedStage::Qkv)
);
assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), Some(GdnFusedStage::Qkv));
}
#[test]
@@ -275,13 +259,7 @@ mod tests {
fn kernel_table_is_closed_and_geometry_matches_the_original_launches() {
for (index, kernel) in FUSED_KERNELS.into_iter().enumerate() {
assert_eq!(kernel.index(), index);
assert!(
kernel
.entry()
.to_str()
.unwrap()
.starts_with("leleka_gdn_fused_")
);
assert!(kernel.entry().to_str().unwrap().starts_with("leleka_gdn_fused_"));
}
// fused_gdn_conv_l2: channels / S blocks of S; fused_gdn_ab: (2 h_v + 7) / 8 blocks of 256;
// fused_gdn_step_norm: h_v blocks of (S, RG).
@@ -295,10 +273,7 @@ mod tests {
#[test]
fn unpinned_artifact_fails_closed_and_pins_check_length_and_digest() {
static GOOD: &[u8] = b".version 8.0\n\0";
assert!(matches!(
pinned(GOOD, 0, [0; 32]),
Err(Error::InvalidDriverValue(_))
));
assert!(matches!(pinned(GOOD, 0, [0; 32]), Err(Error::InvalidDriverValue(_))));
let digest = crate::qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]);
assert!(pinned(GOOD, GOOD.len() - 1, digest).is_ok());
assert!(pinned(GOOD, GOOD.len() - 2, digest).is_err());
@@ -309,32 +284,27 @@ mod tests {
}
}
#[cfg(all(
test,
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gdn_fused_t1_gpu.rs"]
mod gpu;
#[path = "gdn_fused_t1/pinned_fn.rs"]
mod pinned_fn;
#[allow(unused_imports)]
use pinned_fn::pinned;
use pinned_fn::decode_statuses;
#[allow(unused_imports)]
pub(crate) use pinned_fn::fused_asset;
#[allow(unused_imports)]
use pinned_fn::linear;
#[allow(unused_imports)]
use pinned_fn::decode_statuses;
#[path = "gdn_fused_t1/impl_gdnfusedt1.rs"]
mod impl_gdnfusedt1;
use pinned_fn::pinned;
#[path = "gdn_fused_t1/impl_gdnfusedprefix.rs"]
mod impl_gdnfusedprefix;
#[path = "gdn_fused_t1/impl_gdnfusedt1.rs"]
mod impl_gdnfusedt1;
#[path = "gdn_fused_t1/words_fn.rs"]
mod words_fn;
#[allow(unused_imports)]
use words_fn::words;
#[allow(unused_imports)]
use words_fn::staging;
#[allow(unused_imports)]
use words_fn::words;
@@ -3,8 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
pub(in super::super) fn ready(&self, step: Step) -> Result<()> {
if let Some(error) = &self.refusal {
@@ -53,11 +51,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
geometry: ([u32; 3], [u32; 3]),
args: &[ffi::KernelArg],
) -> Result<()> {
let function = self
.batch
.functions
.as_ref()
.ok_or(Error::ContextPoisoned)?[kernel.index()];
let function = self.batch.functions.as_ref().ok_or(Error::ContextPoisoned)?[kernel.index()];
self.commands.push(Command {
function,
grid: geometry.0,
@@ -67,9 +61,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
Ok(())
}
pub(in super::super) fn status_word(&self, stage: GdnFusedStage) -> Result<ffi::BufferHandle> {
self.batch
.status_handle()?
.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)
self.batch.status_handle()?.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)
}
/// Complete finite scan of the whole buffer bound to `role`, into the stage's own status word. Stages are
/// scanned strictly in program order.
@@ -101,11 +93,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
/// Admit the program inputs and scan them first: the projected QKV `[10240]` and Z `[6144]` (device-resident,
/// not yet finite-checked by their producer).
pub fn scan_inputs(
&mut self,
qkv: &'lease DeviceBuffer<'lease>,
z: &'lease DeviceBuffer<'lease>,
) -> Result<()> {
pub fn scan_inputs(&mut self, qkv: &'lease DeviceBuffer<'lease>, z: &'lease DeviceBuffer<'lease>) -> Result<()> {
let result = (|| {
self.ready(Step::Inputs)?;
self.bind(Role::Qkv, qkv, GdnFusedStage::Qkv.bytes())?;
@@ -135,9 +123,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
&[
ffi::KernelArg::Pointer(source),
ffi::KernelArg::Pointer(next),
ffi::KernelArg::U32(
u32::try_from(STATE_WORDS).map_err(|_| Error::InvalidQwenShape)?,
),
ffi::KernelArg::U32(u32::try_from(STATE_WORDS).map_err(|_| Error::InvalidQwenShape)?),
],
)?;
}
@@ -158,11 +144,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
let result = (|| {
self.ready(Step::Conv)?;
let qkv = self.handle(Role::Qkv)?;
let hist = self.bind(
Role::NextHistory,
next_history,
GdnFusedStage::NextHistory.bytes(),
)?;
let hist = self.bind(Role::NextHistory, next_history, GdnFusedStage::NextHistory.bytes())?;
let w = self.bind(Role::ConvW, conv_weights, 4 * C * F32)?;
let h_handle = self.bind(Role::H, h, GdnFusedStage::H.bytes())?;
self.push(
@@ -3,8 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
/// `fused_gdn_step_norm`: the in-place state update, readout and per-head norm / ssm_norm / sigmoid(z) gate.
/// `gamma` is the f32 `[128]` ssm_norm weight; `y` receives the f32 `[6144]` normalized readout. Scans `y` then
@@ -73,11 +71,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
}
Ok(GdnFusedCompletion {
refusal: drained.refusal,
fetched: if drained.refusal.is_none() {
drained.fetched
} else {
None
},
fetched: if drained.refusal.is_none() { drained.fetched } else { None },
})
}
@@ -85,11 +79,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
let status = self.batch.status_handle()?;
let mut statuses = staging(STATUS_BYTES)?;
let write_fetch = fetch && self.refusal.is_none();
let mut fetched_state = staging(if write_fetch {
GDN_FUSED_T1_STATE_BYTES
} else {
0
})?;
let mut fetched_state = staging(if write_fetch { GDN_FUSED_T1_STATE_BYTES } else { 0 })?;
let mut fetched_history = staging(if write_fetch { HISTORY_WORDS * F32 } else { 0 })?;
if self.commands.len() > 1 {
let context = self.batch.context;
@@ -135,15 +125,8 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
if sync.is_err() || pop.is_err() {
// Completion is uncertain: retain every actual argument/staging owner. The borrowed buffers are kept alive
// by the poisoned context (it refuses to enter, so their frees leak instead of racing the device).
std::mem::forget((
self.commands,
self.held,
statuses,
fetched_state,
fetched_history,
));
return combine(combine(operation, sync), pop)
.map(|()| unreachable!("uncertain fused GDN T1 drain"));
std::mem::forget((self.commands, self.held, statuses, fetched_state, fetched_history));
return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain fused GDN T1 drain"));
}
combine(combine(operation, sync), pop)?;
}
@@ -163,10 +146,6 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> {
} else {
None
};
Ok(Drained {
refusal,
deferred: self.refusal,
fetched,
})
Ok(Drained { refusal, deferred: self.refusal, fetched })
}
}
@@ -3,28 +3,18 @@
#[allow(unused_imports)]
use super::*;
impl<'ctx> GdnFusedT1<'ctx> {
pub(super) fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
let required = STATUS_BYTES + RESERVE;
if context
.allocated_bytes()
.checked_add(required)
.is_none_or(|n| n > context.budget)
if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget)
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
context,
status: None,
module: None,
functions: None,
failed: false,
};
let mut owner = Self { context, status: None, module: None, functions: None, failed: false };
let result = (|| {
owner.status = Some(context.allocate(STATUS_BYTES)?);
let guard = context.enter().inspect_err(|_| {
@@ -92,22 +82,15 @@ impl<'ctx> GdnFusedT1<'ctx> {
pub fn begin<'lease>(&'lease mut self) -> Result<GdnFusedPrefix<'lease, 'ctx>> {
let status = self.status_handle()?;
let mut held = Vec::new();
held.try_reserve_exact(24)
.map_err(|_| Error::HostAllocation)?;
held.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?;
let mut commands = Vec::new();
commands
.try_reserve_exact(24)
.map_err(|_| Error::HostAllocation)?;
commands.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?;
let (grid, block) = linear(SLOTS)?;
commands.push(Command {
function: self.functions.as_ref().ok_or(Error::ContextPoisoned)?
[FusedKernel::Zero.index()],
function: self.functions.as_ref().ok_or(Error::ContextPoisoned)?[FusedKernel::Zero.index()],
grid,
block,
args: ffi::GdnPrefillArguments::new(&[
ffi::KernelArg::Pointer(status),
ffi::KernelArg::U32(SLOTS as u32),
])?,
args: ffi::GdnPrefillArguments::new(&[ffi::KernelArg::Pointer(status), ffi::KernelArg::U32(SLOTS as u32)])?,
});
Ok(GdnFusedPrefix {
batch: self,
@@ -3,19 +3,13 @@
#[allow(unused_imports)]
use super::*;
pub(super) fn pinned(ptx: &'static [u8], len: usize, digest: [u8; 32]) -> Result<&'static [u8]> {
if ptx.last() != Some(&0)
|| !ptx[..ptx.len() - 1].is_ascii()
|| ptx[..ptx.len() - 1].contains(&0)
{
if ptx.last() != Some(&0) || !ptx[..ptx.len() - 1].is_ascii() || ptx[..ptx.len() - 1].contains(&0) {
return Err(Error::InvalidDriverValue("GDN fused T1 artifact encoding"));
}
let body = &ptx[..ptx.len() - 1];
if len == 0 || digest == [0; 32] {
return Err(Error::InvalidDriverValue(
"GDN fused T1 artifact pin is unset (TODO-ROOT)",
));
return Err(Error::InvalidDriverValue("GDN fused T1 artifact pin is unset (TODO-ROOT)"));
}
if body.len() != len || crate::qwen_ffi::sha256(body) != digest {
return Err(Error::InvalidDriverValue("GDN fused T1 artifact digest"));
@@ -23,11 +17,7 @@ pub(super) fn pinned(ptx: &'static [u8], len: usize, digest: [u8; 32]) -> Result
Ok(ptx)
}
pub(crate) fn fused_asset() -> Result<&'static [u8]> {
pinned(
concat!(include_str!("../offline_gdn_fused_t1.ptx"), "\0").as_bytes(),
FUSED_PTX_LEN,
FUSED_PTX_SHA256,
)
pinned(concat!(include_str!("../offline_gdn_fused_t1.ptx"), "\0").as_bytes(), FUSED_PTX_LEN, FUSED_PTX_SHA256)
}
impl FusedKernel {
pub(crate) fn entry(self) -> &'static std::ffi::CStr {
@@ -94,11 +84,8 @@ pub(super) fn decode_statuses(bytes: &[u8], checks: usize) -> Result<Option<GdnF
GdnFusedStage::State,
];
Ok(priority.into_iter().find(|stage| {
u32::from_le_bytes(
bytes[stage.slot() * 4..stage.slot() * 4 + 4]
.try_into()
.expect("admitted status extent"),
) != 0
u32::from_le_bytes(bytes[stage.slot() * 4..stage.slot() * 4 + 4].try_into().expect("admitted status extent"))
!= 0
}))
}
impl Step {
@@ -115,17 +102,11 @@ impl Step {
}
impl Bindings {
pub(super) fn new() -> Self {
Self {
slots: [None; ROLES],
}
Self { slots: [None; ROLES] }
}
pub(super) fn bind(&mut self, role: Role, handle: ffi::BufferHandle, bytes: usize) -> Result<()> {
if let Some((bound, size)) = self.slots[role as usize] {
return if bound == handle && size == bytes {
Ok(())
} else {
Err(Error::InvalidQwenShape)
};
return if bound == handle && size == bytes { Ok(()) } else { Err(Error::InvalidQwenShape) };
}
for (other, size) in self.slots.iter().flatten() {
if handle.overlaps(bytes, *other, *size) {
@@ -5,17 +5,13 @@ use super::*;
pub(super) fn words<T>(bytes: &[u8], decode: fn([u8; 4]) -> T) -> Result<Box<[T]>> {
let mut values = Vec::new();
values
.try_reserve_exact(bytes.len() / 4)
.map_err(|_| Error::HostAllocation)?;
values.try_reserve_exact(bytes.len() / 4).map_err(|_| Error::HostAllocation)?;
values.extend(bytes.as_chunks::<4>().0.iter().map(|word| decode(*word)));
Ok(values.into_boxed_slice())
}
pub(super) fn staging(bytes: usize) -> Result<Vec<u8>> {
let mut result = Vec::new();
result
.try_reserve_exact(bytes)
.map_err(|_| Error::HostAllocation)?;
result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?;
result.resize(bytes, 0);
Ok(result)
}
+13 -55
View File
@@ -27,9 +27,7 @@ fn mismatch<T>(what: &'static str) -> Result<T> {
fn synth(count: usize, salt: u32) -> Vec<f32> {
(0..count)
.map(|i| {
let x = (i as u32)
.wrapping_mul(2_654_435_761)
.wrapping_add(salt.wrapping_mul(40_503));
let x = (i as u32).wrapping_mul(2_654_435_761).wrapping_add(salt.wrapping_mul(40_503));
((x >> 8) % 1000) as f32 / 1000.0 - 0.5
})
.collect()
@@ -48,14 +46,8 @@ struct Case {
gamma: Vec<f32>,
}
fn case() -> Case {
let wa: Vec<u16> = synth(HV * N_EMBD, 7)
.iter()
.map(|v| bf_bits(v * 0.05))
.collect();
let wb: Vec<u16> = synth(HV * N_EMBD, 8)
.iter()
.map(|v| bf_bits(v * 0.05))
.collect();
let wa: Vec<u16> = synth(HV * N_EMBD, 7).iter().map(|v| bf_bits(v * 0.05)).collect();
let wb: Vec<u16> = synth(HV * N_EMBD, 8).iter().map(|v| bf_bits(v * 0.05)).collect();
Case {
qkv: synth(C, 1),
z: synth(VALUES, 2),
@@ -82,16 +74,8 @@ fn reference(c: &Case) -> Reference {
let mut history = c.history.clone();
let mut h = vec![0f32; C];
for ch in 0..C {
let (v0, v1, v2, x) = (
history[ch * 3],
history[ch * 3 + 1],
history[ch * 3 + 2],
c.qkv[ch],
);
let sum = v0 * c.conv[ch * 4]
+ v1 * c.conv[ch * 4 + 1]
+ v2 * c.conv[ch * 4 + 2]
+ x * c.conv[ch * 4 + 3];
let (v0, v1, v2, x) = (history[ch * 3], history[ch * 3 + 1], history[ch * 3 + 2], c.qkv[ch]);
let sum = v0 * c.conv[ch * 4] + v1 * c.conv[ch * 4 + 1] + v2 * c.conv[ch * 4 + 2] + x * c.conv[ch * 4 + 3];
history[ch * 3] = v1;
history[ch * 3 + 1] = v2;
history[ch * 3 + 2] = x;
@@ -145,14 +129,7 @@ fn reference(c: &Case) -> Reference {
y[head * S + col] = oc[col] * scale * c.gamma[col] / (1.0 + (-zz).exp());
}
}
Reference {
history,
h,
gate,
beta,
y,
state,
}
Reference { history, h, gate, beta, y, state }
}
const QK: usize = 2048;
const HK: usize = 16;
@@ -175,22 +152,12 @@ fn upload<'c>(context: &'c Context<'c>, values: &[f32]) -> Result<DeviceBuffer<'
}
fn upload_bf<'c>(context: &'c Context<'c>, bits: &[u16]) -> Result<DeviceBuffer<'c>> {
let mut buffer = context.allocate(bits.len() * 2)?;
buffer.copy_from(
&bits
.iter()
.flat_map(|v| v.to_le_bytes())
.collect::<Vec<_>>(),
)?;
buffer.copy_from(&bits.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>())?;
Ok(buffer)
}
fn download<'c>(buffer: &DeviceBuffer<'c>, count: usize) -> Result<Vec<f32>> {
let bytes = buffer.copy_to_owned(count * 4)?;
Ok(bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| f32::from_le_bytes(*w))
.collect())
Ok(bytes.as_chunks::<4>().0.iter().map(|w| f32::from_le_bytes(*w)).collect())
}
/// One program run. `from_resident`: seed the candidate state by the device copy of a resident mirror instead of a
@@ -221,18 +188,11 @@ fn run(
let gamma_b = upload(context, &c.gamma)?;
let y_b = context.allocate(VALUES * 4)?;
let resident = upload(context, &c.state)?;
let next_state = if from_resident {
context.allocate(STATE_WORDS * 4)?
} else {
upload(context, &c.state)?
};
let next_state = if from_resident { context.allocate(STATE_WORDS * 4)? } else { upload(context, &c.state)? };
let refusal = (|| -> Result<Option<GdnFusedStage>> {
let mut prefix = owner.begin()?;
prefix.scan_inputs(&qkv_b, &z_b)?;
prefix.seed_state(
if from_resident { Some(&resident) } else { None },
&next_state,
)?;
prefix.seed_state(if from_resident { Some(&resident) } else { None }, &next_state)?;
prefix.conv_l2(&hist_b, &conv_b, &h_b, EPS)?;
prefix.ab(&mixed_b, &wa_b, &wb_b, &dt_b, &a_b, &gate_b, &beta_b)?;
prefix.step_norm(&gamma_b, &y_b, EPS)?;
@@ -241,9 +201,7 @@ fn run(
if let Some(stage) = completion.numerical_refusal() {
return Ok(Some(stage));
}
let (state, history) = completion
.into_fetched()
.map_err(|_| Error::InvalidQwenShape)?;
let (state, history) = completion.into_fetched().map_err(|_| Error::InvalidQwenShape)?;
let want = reference(c);
close("history", &history, &want.history)?;
close("state", &state, &want.state)?;
@@ -259,8 +217,8 @@ fn run(
})();
let mut cleanup = Ok(());
for buffer in [
qkv_b, z_b, hist_b, conv_b, h_b, mixed_b, wa_b, wb_b, dt_b, a_b, gate_b, beta_b, gamma_b,
y_b, resident, next_state,
qkv_b, z_b, hist_b, conv_b, h_b, mixed_b, wa_b, wb_b, dt_b, a_b, gate_b, beta_b, gamma_b, y_b, resident,
next_state,
] {
cleanup = combine(cleanup, buffer.release());
}
+11 -28
View File
@@ -51,15 +51,15 @@ const F16: usize = 2;
const PREFILL_PTX_LEN: usize = 52304;
// TODO-ROOT: sha256 of offline_gdn_prefill.ptx (without the trailing NUL).
const PREFILL_PTX_SHA256: [u8; 32] = [
92, 195, 160, 40, 93, 185, 131, 206, 190, 158, 53, 250, 194, 213, 62, 87, 50, 104, 175, 129,
127, 19, 27, 35, 64, 189, 0, 58, 227, 225, 100, 206,
92, 195, 160, 40, 93, 185, 131, 206, 190, 158, 53, 250, 194, 213, 62, 87, 50, 104, 175, 129, 127, 19, 27, 35, 64,
189, 0, 58, 227, 225, 100, 206,
];
// TODO-ROOT: exact byte length (without the trailing NUL) of offline_native_dequant_f16.ptx.
const DEQUANT_PTX_LEN: usize = 58080;
// TODO-ROOT: sha256 of offline_native_dequant_f16.ptx (without the trailing NUL).
const DEQUANT_PTX_SHA256: [u8; 32] = [
2, 11, 199, 151, 252, 90, 143, 54, 35, 7, 84, 54, 180, 78, 2, 26, 46, 151, 255, 186, 170, 191,
84, 210, 115, 234, 206, 193, 49, 50, 235, 42,
2, 11, 199, 151, 252, 90, 143, 54, 35, 7, 84, 54, 180, 78, 2, 26, 46, 151, 255, 186, 170, 191, 84, 210, 115, 234,
206, 193, 49, 50, 235, 42,
];
// ------------------------------------------------------------------ kernel table
@@ -152,21 +152,9 @@ pub trait GdnGemm {
fn stream(&self) -> GdnStream;
/// cublasGemmEx(OP_T, OP_N, rows, tokens, depth, 1, W:CUDA_R_16F, X:CUDA_R_16F,
/// beta, Y:CUDA_R_32F, ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT).
fn f16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()>;
fn f16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()>;
/// The same with `CUDA_R_16BF` for `x` and `w`.
fn bf16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()>;
fn bf16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()>;
}
// ------------------------------------------------------------------ stages
@@ -340,12 +328,7 @@ struct Drained {
#[path = "gdn_native_batch/tests.rs"]
mod tests;
#[cfg(all(
test,
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gdn_native_batch_gpu.rs"]
mod gpu;
@@ -357,15 +340,15 @@ pub use prompt_device::{OriginalGdnPromptDevice, OriginalGdnPromptWeights};
#[path = "gdn_native_batch/pinned_fn.rs"]
mod pinned_fn;
#[allow(unused_imports)]
use pinned_fn::pinned;
#[allow(unused_imports)]
pub(crate) use pinned_fn::prefill_asset;
use pinned_fn::decode_statuses;
#[allow(unused_imports)]
pub(crate) use pinned_fn::dequant_asset;
#[allow(unused_imports)]
use pinned_fn::linear;
#[allow(unused_imports)]
use pinned_fn::decode_statuses;
use pinned_fn::pinned;
#[allow(unused_imports)]
pub(crate) use pinned_fn::prefill_asset;
#[path = "gdn_native_batch/impl_context.rs"]
mod impl_context;
#[path = "gdn_native_batch/impl_gdnbatchprefix.rs"]
@@ -3,7 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl Context<'_> {
pub fn gdn_prefill_batch(&self) -> Result<GdnPrefillBatch<'_>> {
GdnPrefillBatch::new(self)
@@ -24,21 +23,10 @@ impl<'ctx> GdnPrefillBatch<'ctx> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if context
.allocated_bytes()
.checked_add(STATUS_BYTES)
.is_none_or(|n| n > context.budget)
{
if context.allocated_bytes().checked_add(STATUS_BYTES).is_none_or(|n| n > context.budget) {
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
capacity,
context,
status: None,
modules: [None, None],
functions: None,
failed: false,
};
let mut owner = Self { capacity, context, status: None, modules: [None, None], functions: None, failed: false };
let result = (|| {
owner.status = Some(context.allocate(STATUS_BYTES)?);
let guard = context.enter()?;
@@ -50,16 +38,10 @@ impl<'ctx> GdnPrefillBatch<'ctx> {
owner.modules[1] = Some(dequant);
let mut all = [None; KERNELS.len()];
for kernel in KERNELS {
let module = if kernel.is_dequant() {
dequant
} else {
prefill
};
let module = if kernel.is_dequant() { dequant } else { prefill };
all[kernel.index()] = Some(api.gdn_native_function(module, kernel)?);
}
Ok(Functions {
all: all.map(|function| function.expect("every GDN batch kernel resolved")),
})
Ok(Functions { all: all.map(|function| function.expect("every GDN batch kernel resolved")) })
})();
let pop = guard.finish();
if pop.is_err() {
@@ -111,27 +93,17 @@ impl<'ctx> GdnPrefillBatch<'ctx> {
}
let status = self.status_handle()?;
let mut held = Vec::new();
held.try_reserve_exact(48)
.map_err(|_| Error::HostAllocation)?;
held.try_reserve_exact(48).map_err(|_| Error::HostAllocation)?;
let mut commands = Vec::new();
commands
.try_reserve_exact(64)
.map_err(|_| Error::HostAllocation)?;
commands.try_reserve_exact(64).map_err(|_| Error::HostAllocation)?;
// The zeroing of the status words is the first command of every drain.
let (grid, block) = linear(SLOTS)?;
commands.push(Command::Kernel {
function: self
.functions
.as_ref()
.ok_or(Error::ContextPoisoned)?
.get(Kernel::Zero),
function: self.functions.as_ref().ok_or(Error::ContextPoisoned)?.get(Kernel::Zero),
stream: gemm.stream(),
grid,
block,
args: ffi::GdnPrefillArguments::new(&[
ffi::KernelArg::Pointer(status),
ffi::KernelArg::U32(SLOTS as u32),
])?,
args: ffi::GdnPrefillArguments::new(&[ffi::KernelArg::Pointer(status), ffi::KernelArg::U32(SLOTS as u32)])?,
});
Ok(GdnBatchPrefix {
batch: self,
@@ -154,24 +126,10 @@ impl<'ctx> GdnPrefillBatch<'ctx> {
impl Command<'_> {
pub(super) fn launch(&mut self, context: &Context<'_>) -> Result<()> {
match self {
Self::Kernel {
function,
stream,
grid,
block,
args,
} => context
.driver
.api
.launch_gdn_native(*function, *stream, *grid, *block, args),
Self::Gemm {
gemm,
bf16,
x,
w,
y,
shape,
} => {
Self::Kernel { function, stream, grid, block, args } => {
context.driver.api.launch_gdn_native(*function, *stream, *grid, *block, args)
}
Self::Gemm { gemm, bf16, x, w, y, shape } => {
if *bf16 {
gemm.bf16(x, w, y, *shape)
} else {
@@ -3,8 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
pub fn tokens(&self) -> usize {
self.tokens
@@ -26,12 +24,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
result
}
pub(in super::super) fn function(&self, kernel: Kernel) -> Result<ffi::FunctionHandle> {
Ok(self
.batch
.functions
.as_ref()
.ok_or(Error::ContextPoisoned)?
.get(kernel))
Ok(self.batch.functions.as_ref().ok_or(Error::ContextPoisoned)?.get(kernel))
}
/// Admit one caller buffer under `role`. `bytes` is the exact size unless
/// `at_least`, in which case the whole allocation is bound.
@@ -45,8 +38,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
if !std::ptr::eq(self.batch.context, buffer.context) {
return Err(Error::ContextMismatch);
}
if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes)
{
if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes) {
return Err(Error::InvalidQwenShape);
}
let handle = buffer.handle.ok_or(Error::ContextPoisoned)?;
@@ -88,15 +80,8 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
if bytes != stage.bytes(self.tokens) {
return Err(Error::InvalidQwenShape);
}
let status =
self.batch
.status_handle()?
.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?;
let kernel = if stage.is_half() {
Kernel::FiniteF16
} else {
Kernel::FiniteF32
};
let status = self.batch.status_handle()?.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?;
let kernel = if stage.is_half() { Kernel::FiniteF16 } else { Kernel::FiniteF32 };
self.push_kernel(
kernel,
linear(elements)?,
@@ -114,10 +99,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
if self.checks != stage.slot() || stage != GdnBatchStage::StateSteps {
return Err(Error::InvalidQwenShape);
}
let word =
self.batch
.status_handle()?
.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?;
let word = self.batch.status_handle()?.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?;
self.checks = stage.slot() + 1;
Ok(word)
}
@@ -126,11 +108,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
}
pub(in super::super) fn buffer_ref(&self, role: Role) -> Result<&'lease DeviceBuffer<'lease>> {
let handle = self.handle(role)?;
self.held
.iter()
.copied()
.find(|buffer| buffer.handle == Some(handle))
.ok_or(Error::InvalidQwenShape)
self.held.iter().copied().find(|buffer| buffer.handle == Some(handle)).ok_or(Error::InvalidQwenShape)
}
// ---------------------------------------------------------------- images
@@ -152,12 +130,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
let h = self.bind(Role::MixedH, mixed_h, t * N * F16, false)?;
let bf = self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?;
let lo = match mixed_bf_lo {
Some(buffer) => ffi::KernelArg::Pointer(self.bind(
Role::MixedBfLo,
buffer,
t * N * F16,
false,
)?),
Some(buffer) => ffi::KernelArg::Pointer(self.bind(Role::MixedBfLo, buffer, t * N * F16, false)?),
None => ffi::KernelArg::NullPointer,
};
self.push_kernel(
@@ -240,14 +213,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
x,
w: scratch,
y: output.1,
shape: GemmShape {
tokens: t,
rows,
depth,
ldy: rows,
y_offset: 0,
beta: 0.0,
},
shape: GemmShape { tokens: t, rows, depth, ldy: rows, y_offset: 0, beta: 0.0 },
});
Ok(())
}
@@ -3,8 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
/// Native `attn_qkv` projection: dequantize to FP16, `Y[T,10240] = X . W^T`
/// with `X` = the FP16 image of `mixed`; then the QKV scan.
@@ -18,16 +16,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
let result = (|| {
self.ready(Step::Qkv)?;
let bytes = self.tokens * C * F32;
self.project_native(
format,
(Role::QkvW, weights),
scratch,
Role::MixedH,
(Role::Qkv, qkv),
C,
N,
bytes,
)?;
self.project_native(format, (Role::QkvW, weights), scratch, Role::MixedH, (Role::Qkv, qkv), C, N, bytes)?;
self.scan(GdnBatchStage::Qkv, Role::Qkv)?;
self.step = self.step.next();
Ok(())
@@ -45,16 +34,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
let result = (|| {
self.ready(Step::Z)?;
let bytes = self.tokens * ZV * F32;
self.project_native(
format,
(Role::ZW, weights),
scratch,
Role::MixedH,
(Role::Z, z),
ZV,
N,
bytes,
)?;
self.project_native(format, (Role::ZW, weights), scratch, Role::MixedH, (Role::Z, z), ZV, N, bytes)?;
self.scan(GdnBatchStage::Z, Role::Z)?;
self.step = self.step.next();
Ok(())
@@ -80,14 +60,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
let x = self.buffer_ref(Role::MixedBf)?;
let lo = self.buffer_ref(Role::MixedBfLo).ok();
for (weights, y_offset) in [(alpha_weights, 0), (beta_weights, HV)] {
let shape = |beta| GemmShape {
tokens: t,
rows: HV,
depth: N,
ldy: 2 * HV,
y_offset,
beta,
};
let shape = |beta| GemmShape { tokens: t, rows: HV, depth: N, ldy: 2 * HV, y_offset, beta };
self.commands.push(Command::Gemm {
gemm: self.gemm,
bf16: true,
@@ -187,10 +160,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
} else {
self.push_kernel(
Kernel::ConvTiled,
(
[(C / 128) as u32, t.div_ceil(CONV_TILE) as u32, 1],
[128, 1, 1],
),
([(C / 128) as u32, t.div_ceil(CONV_TILE) as u32, 1], [128, 1, 1]),
&[
ffi::KernelArg::Pointer(hist),
ffi::KernelArg::Pointer(qkv),
@@ -227,10 +197,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
self.push_kernel(
Kernel::L2,
([32, self.tokens as u32, 1], [128, 1, 1]),
&[
ffi::KernelArg::Pointer(h),
ffi::KernelArg::F32(GDN_BATCH_EPSILON),
],
&[ffi::KernelArg::Pointer(h), ffi::KernelArg::F32(GDN_BATCH_EPSILON)],
)?;
self.scan(GdnBatchStage::Qk, Role::H)?;
self.step = self.step.next();
@@ -3,8 +3,6 @@
#[allow(unused_imports)]
use super::*;
impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
/// `gdn_rec_cols_pipe`: the whole-chunk recurrence. `state_in` is the
/// immutable prior state `[128][48][128]`, `state_out` the separate final
@@ -50,11 +48,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
}
/// `gdn_out_norm`: in place on `y` (f32) plus the half image `y16`
/// (`hf(v)`), gated by `z`; then the Y and Y16 scans.
pub fn out_norm(
&mut self,
gamma: &'lease DeviceBuffer<'lease>,
y16: &'lease DeviceBuffer<'lease>,
) -> Result<()> {
pub fn out_norm(&mut self, gamma: &'lease DeviceBuffer<'lease>, y16: &'lease DeviceBuffer<'lease>) -> Result<()> {
let result = (|| {
self.ready(Step::OutNorm)?;
let t = self.tokens;
@@ -92,16 +86,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
let result = (|| {
self.ready(Step::Out)?;
let bytes = self.tokens * N * F32;
self.project_native(
format,
(Role::OutW, weights),
scratch,
Role::Y16,
(Role::Bo, bo),
N,
ZV,
bytes,
)?;
self.project_native(format, (Role::OutW, weights), scratch, Role::Y16, (Role::Bo, bo), N, ZV, bytes)?;
self.scan(GdnBatchStage::Bo, Role::Bo)?;
self.step = self.step.next();
Ok(())
@@ -125,11 +110,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
}
Ok(GdnBatchCompletion {
refusal: drained.refusal,
next_history: if drained.refusal.is_none() {
drained.next_history
} else {
None
},
next_history: if drained.refusal.is_none() { drained.next_history } else { None },
})
}
@@ -176,8 +157,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
// Completion is uncertain: retain every actual argument/staging
// owner and every borrowed buffer; Context poison forbids reuse.
std::mem::forget((self.commands, self.held, statuses, fetched));
return combine(combine(operation, sync), pop)
.map(|()| unreachable!("uncertain GDN batch drain"));
return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain GDN batch drain"));
}
combine(combine(operation, sync), pop)?;
}
@@ -191,24 +171,12 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> {
};
let next_history = if write_fetch && refusal.is_none() {
let mut values = Vec::new();
values
.try_reserve_exact(HISTORY_WORDS)
.map_err(|_| Error::HostAllocation)?;
values.extend(
fetched
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word)),
);
values.try_reserve_exact(HISTORY_WORDS).map_err(|_| Error::HostAllocation)?;
values.extend(fetched.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word)));
Some(values.into_boxed_slice())
} else {
None
};
Ok(Drained {
refusal,
deferred: self.refusal,
next_history,
})
Ok(Drained { refusal, deferred: self.refusal, next_history })
}
}
@@ -3,24 +3,13 @@
#[allow(unused_imports)]
use super::*;
pub(super) fn pinned(
ptx: &'static [u8],
len: usize,
digest: [u8; 32],
what: &'static str,
) -> Result<&'static [u8]> {
if ptx.last() != Some(&0)
|| !ptx[..ptx.len() - 1].is_ascii()
|| ptx[..ptx.len() - 1].contains(&0)
{
pub(super) fn pinned(ptx: &'static [u8], len: usize, digest: [u8; 32], what: &'static str) -> Result<&'static [u8]> {
if ptx.last() != Some(&0) || !ptx[..ptx.len() - 1].is_ascii() || ptx[..ptx.len() - 1].contains(&0) {
return Err(Error::InvalidDriverValue(what));
}
let body = &ptx[..ptx.len() - 1];
if len == 0 || digest == [0; 32] {
return Err(Error::InvalidDriverValue(
"GDN prefill artifact pin is unset (TODO-ROOT)",
));
return Err(Error::InvalidDriverValue("GDN prefill artifact pin is unset (TODO-ROOT)"));
}
if body.len() != len || crate::qwen_ffi::sha256(body) != digest {
return Err(Error::InvalidDriverValue(what));
@@ -125,10 +114,7 @@ impl GdnNativeFormat {
if rows == 0 || cols == 0 || !cols.is_multiple_of(elements) {
return Err(Error::InvalidQwenShape);
}
(cols / elements)
.checked_mul(bytes)
.and_then(|row| row.checked_mul(rows))
.ok_or(Error::InvalidQwenShape)
(cols / elements).checked_mul(bytes).and_then(|row| row.checked_mul(rows)).ok_or(Error::InvalidQwenShape)
}
}
impl GdnStream {
@@ -209,17 +195,11 @@ impl Step {
}
impl Bindings {
pub(super) fn new() -> Self {
Self {
slots: [None; ROLES],
}
Self { slots: [None; ROLES] }
}
pub(super) fn bind(&mut self, role: Role, handle: ffi::BufferHandle, bytes: usize) -> Result<()> {
if let Some((bound, size)) = self.slots[role as usize] {
return if bound == handle && size == bytes {
Ok(())
} else {
Err(Error::InvalidQwenShape)
};
return if bound == handle && size == bytes { Ok(()) } else { Err(Error::InvalidQwenShape) };
}
for (other, size) in self.slots.iter().flatten() {
if handle.overlaps(bytes, *other, *size) {
@@ -5,9 +5,7 @@ use super::*;
pub(super) fn staging(bytes: usize) -> Result<Vec<u8>> {
let mut result = Vec::new();
result
.try_reserve_exact(bytes)
.map_err(|_| Error::HostAllocation)?;
result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?;
result.resize(bytes, 0);
Ok(result)
}
@@ -54,50 +54,26 @@ fn earliest_status_in_program_order_is_the_refusal() {
assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), None);
words[GdnBatchStage::Beta.slot()] = 1;
words[GdnBatchStage::NextState.slot()] = 1;
assert_eq!(
decode_statuses(&bytes(&words), SLOTS).unwrap(),
Some(GdnBatchStage::Beta)
);
assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), Some(GdnBatchStage::Beta));
words[GdnBatchStage::Qkv.slot()] = 1;
assert_eq!(
decode_statuses(&bytes(&words), SLOTS).unwrap(),
Some(GdnBatchStage::Qkv)
);
assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), Some(GdnBatchStage::Qkv));
}
#[test]
fn unused_slots_and_non_boolean_words_are_driver_witness_errors() {
let mut words = [0u32; SLOTS];
words[GdnBatchStage::Y.slot()] = 1;
assert!(matches!(
decode_statuses(&bytes(&words), GdnBatchStage::Y.slot()),
Err(Error::InvalidDriverValue(_))
));
assert!(matches!(decode_statuses(&bytes(&words), GdnBatchStage::Y.slot()), Err(Error::InvalidDriverValue(_))));
words[GdnBatchStage::Y.slot()] = 2;
assert!(matches!(
decode_statuses(&bytes(&words), SLOTS),
Err(Error::InvalidDriverValue(_))
));
assert!(matches!(
decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS),
Err(Error::InvalidQwenShape)
));
assert!(matches!(
decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1),
Err(Error::InvalidQwenShape)
));
assert!(matches!(decode_statuses(&bytes(&words), SLOTS), Err(Error::InvalidDriverValue(_))));
assert!(matches!(decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), Err(Error::InvalidQwenShape)));
assert!(matches!(decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), Err(Error::InvalidQwenShape)));
}
#[test]
fn native_formats_have_the_original_block_geometry() {
assert_eq!(
GdnNativeFormat::Q6K.matrix_bytes(10_240, 2_560).unwrap(),
21_504_000
);
assert_eq!(
GdnNativeFormat::Q8_0.matrix_bytes(2, 64).unwrap(),
2 * 2 * 34
);
assert_eq!(GdnNativeFormat::Q6K.matrix_bytes(10_240, 2_560).unwrap(), 21_504_000);
assert_eq!(GdnNativeFormat::Q8_0.matrix_bytes(2, 64).unwrap(), 2 * 2 * 34);
assert_eq!(GdnNativeFormat::Iq4Nl.matrix_bytes(1, 32).unwrap(), 18);
assert_eq!(GdnNativeFormat::Iq4Xs.matrix_bytes(1, 256).unwrap(), 136);
assert_eq!(GdnNativeFormat::Q4K.matrix_bytes(1, 256).unwrap(), 144);
@@ -149,18 +125,9 @@ fn bindings_refuse_overlap_and_rebinding_to_a_different_range() {
bindings.bind(Role::Qkv, a, 0x1000).unwrap();
bindings.bind(Role::Z, b, 0x1000).unwrap();
bindings.bind(Role::Qkv, a, 0x1000).unwrap();
assert!(matches!(
bindings.bind(Role::Qkv, b, 0x1000),
Err(Error::InvalidQwenShape)
));
assert!(matches!(
bindings.bind(Role::Qkv, a, 0x800),
Err(Error::InvalidQwenShape)
));
assert!(matches!(
bindings.bind(Role::Gate, overlapping, 0x100),
Err(Error::OutputAliasesInput)
));
assert!(matches!(bindings.bind(Role::Qkv, b, 0x1000), Err(Error::InvalidQwenShape)));
assert!(matches!(bindings.bind(Role::Qkv, a, 0x800), Err(Error::InvalidQwenShape)));
assert!(matches!(bindings.bind(Role::Gate, overlapping, 0x100), Err(Error::OutputAliasesInput)));
assert!(bindings.get(Role::Gate).is_err());
assert!(bindings.get(Role::Z).unwrap() == (b, 0x1000));
}
@@ -168,10 +135,7 @@ fn bindings_refuse_overlap_and_rebinding_to_a_different_range() {
#[test]
fn unpinned_artifacts_fail_closed_and_pins_check_length_and_digest() {
static GOOD: &[u8] = b".version 8.0\n\0";
assert!(matches!(
pinned(GOOD, 0, [0; 32], "x"),
Err(Error::InvalidDriverValue(_))
));
assert!(matches!(pinned(GOOD, 0, [0; 32], "x"), Err(Error::InvalidDriverValue(_))));
let digest = crate::qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]);
assert!(pinned(GOOD, GOOD.len() - 1, digest, "x").is_ok());
assert!(pinned(GOOD, GOOD.len() - 2, digest, "x").is_err());
@@ -34,10 +34,8 @@ impl GdnPrefillArguments {
if args.is_empty() || args.len() > MAX_ARGS {
return Err(Error::InvalidQwenShape);
}
let owner = Box::into_raw(Box::new(Storage {
slots: [0; MAX_ARGS],
parameters: [std::ptr::null_mut(); MAX_ARGS],
}));
let owner =
Box::into_raw(Box::new(Storage { slots: [0; MAX_ARGS], parameters: [std::ptr::null_mut(); MAX_ARGS] }));
let owner = std::ptr::NonNull::new(owner).expect("Box is non-null");
// SAFETY: freshly allocated, uniquely owned, stable storage; the
// parameter pointers target this same Box and live until `Drop`.

Some files were not shown because too many files have changed in this diff Show More