From 68b2947f330044cdac411be0d8ac80d8d972e08a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 7 Nov 2026 16:34:55 +0100 Subject: [PATCH] STRA-338 size4 s07: WIP of the slice (unverified, committed by the integrator after the workers died) --- .../qwen_ffi/tests/full_s2_expert_scalar.rs | 148 +++--- .../tests/moe_fixed_pointer_abi_extents.rs | 188 +++++--- .../tests/mtp_new_qualified_assets.rs | 75 +-- .../tests/qsa_new_literal_abi_scalar.rs | 267 ++++++++--- .../impl_drop_for_sharedexpertworkspace.rs | 3 +- .../src/qwen_shared_tail/impl_sharedgukind.rs | 3 +- .../src/qwen_shared_tail_gpu/original_fn.rs | 3 +- .../src/qwen_shared_tail_gpu/read_fn.rs | 3 +- .../routed_group_workspace/impl_context.rs | 3 +- .../impl_routedgroupworkspace.rs | 3 +- .../impl_drop_for_routedresidentqueue.rs | 3 +- crates/cuda-driver/src/s_gemv_legacy.rs | 40 +- .../s_gemv_legacy/impl_default_for_sform.rs | 10 +- .../s_gemv_legacy/plan_s2_gemv_quads_fn.rs | 19 +- crates/cuda-driver/src/s_gemv_legacy/tests.rs | 140 +++--- crates/cuda-driver/src/tests.rs | 90 ++-- crates/cuda-driver/src/vram_ledger.rs | 35 +- .../tests/full_matrix_transport_gpu.rs | 104 +++-- .../tests/mock_driver/bootstrap_copies_fn.rs | 3 +- .../mock_driver/check_matvec_lengths_fn.rs | 14 +- .../mock_driver/matvec_launch_count_fn.rs | 3 +- .../tests/mock_driver/row_types.rs | 3 +- .../cuda-driver/tests/mock_driver/trace_fn.rs | 3 +- .../tests/mock_driver/vector_bounds_fn.rs | 3 +- .../vector_module_context_trace_fn.rs | 3 +- .../tests/original_serve_preflight_probe.rs | 3 +- .../env_usize_fn.rs | 390 ++++++++++------ .../preflight_00_sealed_asset_report.rs | 112 +++-- .../src/rust_weight_iq/alloc_fn.rs | 163 ++++--- .../src/rust_weight_iq/impl_grid.rs | 277 +++++------ .../src/rust_weight_iq/iq1_m_fn.rs | 314 ++++++------- .../src/rust_weight_iq/iq2_xxs_fn.rs | 224 +++++---- .../src/rust_weight_iq/iq3_fn.rs | 219 ++++----- .../src/rust_weight_quant/best_fp4_fn.rs | 255 ++++++----- .../src/rust_weight_quant/iq4_fn.rs | 227 ++++----- .../src/rust_weight_quant/nearest_fn.rs | 431 ++++++++++-------- .../src/rust_weight_quant/q45k_fn.rs | 161 ++++--- .../src/rust_weight_quant/qp_fn.rs | 306 +++++++------ 38 files changed, 2437 insertions(+), 1814 deletions(-) diff --git a/crates/cuda-driver/src/qwen_ffi/tests/full_s2_expert_scalar.rs b/crates/cuda-driver/src/qwen_ffi/tests/full_s2_expert_scalar.rs index 5def0606..91da00f2 100644 --- a/crates/cuda-driver/src/qwen_ffi/tests/full_s2_expert_scalar.rs +++ b/crates/cuda-driver/src/qwen_ffi/tests/full_s2_expert_scalar.rs @@ -1,4 +1,7 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): full_s2_expert_scalar_and_fixed_bank_abi, mtp_new_nine_pointer_owner_and_scaled_packets, gr_saturation_asset_requires_exact_independent_qualification_and_bytes, kar_ple_qualified_receipt_matches_frozen_source_and_ptx .... +//! Tests of tests by topic (moved out of the test file by STRA-338): full_s2_expert_scalar_and_fixed_bank_abi, +//! mtp_new_nine_pointer_owner_and_scaled_packets, +//! gr_saturation_asset_requires_exact_independent_qualification_and_bytes, +//! kar_ple_qualified_receipt_matches_frozen_source_and_ptx .... #[allow(unused_imports)] use super::*; @@ -11,25 +14,10 @@ fn full_s2_expert_scalar_and_fixed_bank_abi() { ] { for expert in [0, 257, 511] { let layout = mtp_s2_full_layout(operation, expert).unwrap(); - assert_eq!(layout.bytes[..4], [707_788_800, q, scales, out]); - assert_eq!(layout.align[..4], [8, 4, 4, 4]); - assert_eq!((layout.count, layout.outputs, layout.grid, layout.block), (4, 8, 40, 256)); - assert_eq!((layout.grid_y, layout.grid_z, layout.shared_bytes), (1, 1, 0)); + assert_full_s2_layout(&layout, [q, scales, out]); assert_eq!(layout.integer, Some((expert, 1))); assert_eq!(operation.entry(), name); - let handles = [11, 22, 33, 44, 0, 0, 0, 0, 0].map(ffi::BufferHandle::synthetic); - let mut args = Arguments::with_layout(operation, layout, handles, 0.0); - let table = args.parameters(); - // SAFETY: these initialized raw-owned scalar fields are live; - // the pointer table is inspected only before driver execution. - unsafe { - assert_eq!(*(*table).cast::(), 11); - assert_eq!(*(*table.add(1)).cast::(), expert); - for (i, value) in [22u64, 33, 44].into_iter().enumerate() { - assert_eq!(*(*table.add(i + 2)).cast::(), value); - } - assert!((*table.add(5)).is_null()); - } + assert_full_s2_parameter_table(operation, layout, expert); } for expert in [512, u32::MAX] { assert!(matches!(mtp_s2_full_layout(operation, expert), Err(Error::InvalidQwenShape))); @@ -37,6 +25,29 @@ fn full_s2_expert_scalar_and_fixed_bank_abi() { } } +fn assert_full_s2_layout(layout: &Layout, [q, scales, out]: [usize; 3]) { + assert_eq!(layout.bytes[..4], [707_788_800, q, scales, out]); + assert_eq!(layout.align[..4], [8, 4, 4, 4]); + assert_eq!((layout.count, layout.outputs, layout.grid, layout.block), (4, 8, 40, 256)); + assert_eq!((layout.grid_y, layout.grid_z, layout.shared_bytes), (1, 1, 0)); +} + +fn assert_full_s2_parameter_table(operation: Operation, layout: Layout, expert: u32) { + let handles = [11, 22, 33, 44, 0, 0, 0, 0, 0].map(ffi::BufferHandle::synthetic); + let mut args = Arguments::with_layout(operation, layout, handles, 0.0); + let table = args.parameters(); + // SAFETY: these initialized raw-owned scalar fields are live; + // the pointer table is inspected only before driver execution. + unsafe { + assert_eq!(*(*table).cast::(), 11); + assert_eq!(*(*table.add(1)).cast::(), expert); + for (i, value) in [22u64, 33, 44].into_iter().enumerate() { + assert_eq!(*(*table.add(i + 2)).cast::(), value); + } + assert!((*table.add(5)).is_null()); + } +} + #[test] fn mtp_new_nine_pointer_owner_and_scaled_packets() { for (operation, count) in [ @@ -90,7 +101,8 @@ fn kar_ple_qualified_receipt_matches_frozen_source_and_ptx() { assert_eq!(sha256(include_bytes!("../../kar_ple_fixed.ptx")), KAR_PLE_RECEIPT.ptx_sha256); assert_eq!( KAR_PLE_RECEIPT.qualification_receipt, - "STRA161 SDET7ca247af-161d-4215-9128-f4ba19018b7b; GPUbb8d133b-2286-4b59-8ab0-876c2ca03321; DEV2df2eb3d-7d75-43a4-8019-7583921daf0d" + "STRA161 SDET7ca247af-161d-4215-9128-f4ba19018b7b; GPUbb8d133b-2286-4b59-8ab0-876c2ca03321; \ + DEV2df2eb3d-7d75-43a4-8019-7583921daf0d" ); for op in [Operation::KarPleScatter, Operation::KarPleDecode] { let admitted = asset(op).unwrap(); @@ -100,43 +112,71 @@ fn kar_ple_qualified_receipt_matches_frozen_source_and_ptx() { } } +/// One frozen KAR PLE entry: operation, scalar value, entry name, ABI sizes, alignments and geometry. +struct KarPleCase { + op: Operation, + value: u32, + entry: &'static std::ffi::CStr, + bytes: &'static [usize], + align: &'static [u64], + geometry: (u16, u32, u32), + scalar_index: usize, +} + +const KAR_PLE_CASES: [KarPleCase; 2] = [ + KarPleCase { + op: Operation::KarPleScatter, + value: 16, + entry: c"leleka_kar_ple_scatter", + bytes: &[67_108_864, 896], + align: &[1, 4], + geometry: (1, 16, 64), + scalar_index: 2, + }, + KarPleCase { + op: Operation::KarPleDecode, + value: 65_535, + entry: c"leleka_kar_ple_decode", + bytes: &[67_108_864, 64, 524_280, 10_240], + align: &[1, 4, 2, 4], + geometry: (8, 16, 256), + scalar_index: 4, + }, +]; + +fn assert_kar_ple_layout(case: &KarPleCase, layout: &Layout) { + assert_eq!(case.op.entry(), case.entry); + assert_eq!(&layout.bytes[..layout.count], case.bytes); + assert_eq!(&layout.align[..layout.count], case.align); + let (outputs, grid, block) = case.geometry; + assert_eq!((layout.outputs, layout.grid, layout.block), (outputs, grid, block)); + assert_eq!((layout.grid_y, layout.grid_z, layout.block_y, layout.shared_bytes), (1, 1, 1, 0)); + assert_eq!(layout.integer, Some((case.value, case.scalar_index))); + asset(case.op).expect("qualified fixed KAR entry").validate(case.op).unwrap(); +} + +fn assert_kar_ple_parameter_table(case: &KarPleCase, layout: Layout) { + let addresses = [101u64, 202, 303, 404, 505, 606, 707, 808, 0]; + let args = Arguments::with_layout(case.op, layout, addresses.map(ffi::BufferHandle::synthetic), 0.0); + let mut moved = std::hint::black_box(args); + let table = moved.parameters(); + // SAFETY: the private raw-owned table is live, and this frozen ABI + // contains exactly its buffer addresses followed by one u32. + unsafe { + for (i, address) in addresses.iter().enumerate().take(layout.count) { + assert_eq!(*(*table.add(i)).cast::(), *address); + } + assert_eq!(*(*table.add(case.scalar_index)).cast::(), case.value); + assert!((*table.add(case.scalar_index + 1)).is_null()); + } +} + #[test] fn kar_ple_fixed_abi_and_boundary_refusals() { - for (op, value, entry, bytes, align, outputs, grid, block, scalar_index) in [ - (Operation::KarPleScatter, 16, c"leleka_kar_ple_scatter", vec![67_108_864, 896], vec![1, 4], 1, 16, 64, 2), - ( - Operation::KarPleDecode, - 65_535, - c"leleka_kar_ple_decode", - vec![67_108_864, 64, 524_280, 10_240], - vec![1, 4, 2, 4], - 8, - 16, - 256, - 4, - ), - ] { - let layout = kar_ple_layout(op, value).unwrap(); - assert_eq!(op.entry(), entry); - assert_eq!(&layout.bytes[..layout.count], bytes); - assert_eq!(&layout.align[..layout.count], align); - assert_eq!((layout.outputs, layout.grid, layout.block), (outputs, grid, block)); - assert_eq!((layout.grid_y, layout.grid_z, layout.block_y, layout.shared_bytes), (1, 1, 1, 0)); - assert_eq!(layout.integer, Some((value, scalar_index))); - asset(op).expect("qualified fixed KAR entry").validate(op).unwrap(); - let addresses = [101u64, 202, 303, 404, 505, 606, 707, 808, 0]; - let args = Arguments::with_layout(op, layout, addresses.map(ffi::BufferHandle::synthetic), 0.0); - let mut moved = std::hint::black_box(args); - let table = moved.parameters(); - // SAFETY: the private raw-owned table is live, and this frozen ABI - // contains exactly its buffer addresses followed by one u32. - unsafe { - for (i, address) in addresses.iter().enumerate().take(layout.count) { - assert_eq!(*(*table.add(i)).cast::(), *address); - } - assert_eq!(*(*table.add(scalar_index)).cast::(), value); - assert!((*table.add(scalar_index + 1)).is_null()); - } + for case in &KAR_PLE_CASES { + let layout = kar_ple_layout(case.op, case.value).unwrap(); + assert_kar_ple_layout(case, &layout); + assert_kar_ple_parameter_table(case, layout); } for (op, maximum) in [(Operation::KarPleScatter, 16), (Operation::KarPleDecode, 65_535)] { assert!(kar_ple_layout(op, 1).is_ok()); diff --git a/crates/cuda-driver/src/qwen_ffi/tests/moe_fixed_pointer_abi_extents.rs b/crates/cuda-driver/src/qwen_ffi/tests/moe_fixed_pointer_abi_extents.rs index f0321532..e04f260a 100644 --- a/crates/cuda-driver/src/qwen_ffi/tests/moe_fixed_pointer_abi_extents.rs +++ b/crates/cuda-driver/src/qwen_ffi/tests/moe_fixed_pointer_abi_extents.rs @@ -1,8 +1,49 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): moe_fixed_pointer_abi_extents_and_qualified_receipts, qwen_hash_known_vectors_and_padding_boundaries, qwen_raw_abi_remains_stable_after_moves, qwen_router_has_exact_three_pointer_abi_and_32_by_8_geometry .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! moe_fixed_pointer_abi_extents_and_qualified_receipts, qwen_hash_known_vectors_and_padding_boundaries, +//! qwen_raw_abi_remains_stable_after_moves, qwen_router_has_exact_three_pointer_abi_and_32_by_8_geometry .... #[allow(unused_imports)] use super::*; +/// The frozen layout of one MoE entry: ABI sizes, alignments, parameter count, outputs and grid. +struct MoeExpect { + bytes: [usize; 4], + align: [u64; 4], + count: usize, + outputs: u16, + grid: u32, +} + +fn assert_moe_layout(operation: Operation, entry: &std::ffi::CStr, expect: &MoeExpect) { + let layout = operation.layout(); + assert_eq!(operation.entry(), entry); + assert_eq!(layout.bytes[..4], expect.bytes); + assert_eq!(layout.align[..4], expect.align); + assert_eq!((layout.count, layout.outputs), (expect.count, expect.outputs)); + assert_eq!((layout.grid, layout.grid_z, layout.block, layout.block_y), (expect.grid, 1, 256, 1)); + assert!(!layout.projection); + assert!(!operation.has_epsilon()); +} + +fn assert_moe_qualified_component(operation: Operation) { + let qualified = asset(operation).expect("frozen167 qualified component"); + qualified.validate(operation).unwrap(); + assert_eq!(qualified.receipt, MOE_RECEIPT); +} + +fn assert_moe_parameter_table(operation: Operation, count: usize) { + let handles = [101, 202, 303, 404, 505, 606, 707, 808, 0].map(ffi::BufferHandle::synthetic); + let mut arguments = Arguments::new(operation, handles, 0.0); + let parameters = arguments.parameters(); + // SAFETY: inspect only live initialized pointer-table fields. + unsafe { + for (index, expected) in [101u64, 202, 303, 404].iter().take(count).enumerate() { + assert_eq!(*(*parameters.add(index)).cast::(), *expected); + } + assert!((*parameters.add(count)).is_null()); + } +} + #[test] fn moe_fixed_pointer_abi_extents_and_qualified_receipts() { // Literal expectations come from STRA-167 AD v1 / STRA-172 AD v8. @@ -12,27 +53,9 @@ fn moe_fixed_pointer_abi_extents_and_qualified_receipts() { (Operation::MoeSharedScale, c"leleka_moe_scale_shared_f32", [10240, 4, 10240, 0], [4, 4, 4, 4], 3, 4, 10), (Operation::MoeCombine, c"leleka_moe_combine_f32", [102400, 40, 10240, 10240], [4, 4, 4, 4], 4, 8, 10), ] { - let layout = operation.layout(); - assert_eq!(operation.entry(), entry); - assert_eq!(layout.bytes[..4], bytes); - assert_eq!(layout.align[..4], align); - assert_eq!((layout.count, layout.outputs), (count, outputs)); - assert_eq!((layout.grid, layout.grid_z, layout.block, layout.block_y), (grid, 1, 256, 1)); - assert!(!layout.projection); - assert!(!operation.has_epsilon()); - let qualified = asset(operation).expect("frozen167 qualified component"); - qualified.validate(operation).unwrap(); - assert_eq!(qualified.receipt, MOE_RECEIPT); - let handles = [101, 202, 303, 404, 505, 606, 707, 808, 0].map(ffi::BufferHandle::synthetic); - let mut arguments = Arguments::new(operation, handles, 0.0); - let parameters = arguments.parameters(); - // SAFETY: inspect only live initialized pointer-table fields. - unsafe { - for (index, expected) in [101u64, 202, 303, 404].iter().take(count).enumerate() { - assert_eq!(*(*parameters.add(index)).cast::(), *expected); - } - assert!((*parameters.add(count)).is_null()); - } + assert_moe_layout(operation, entry, &MoeExpect { bytes, align, count, outputs, grid }); + assert_moe_qualified_component(operation); + assert_moe_parameter_table(operation, count); } assert_eq!(OPERATIONS.len(), 58); } @@ -47,6 +70,30 @@ fn qwen_hash_known_vectors_and_padding_boundaries() { "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" ); } + +fn assert_raw_table_matches_layout(op: Operation, layout: &Layout, table: *mut *mut std::ffi::c_void) { + // SAFETY: read exactly the live owner's initialized scalar fields; + // private ABI pointer table is valid across the owner moves above. + unsafe { + for (i, expected) in [11u64, 22, 33, 44, 55, 66, 77, 88, 0].iter().enumerate().take(layout.count) { + let slot = i + usize::from(layout.integer.is_some_and(|(_, index)| index <= i)); + assert_eq!(*(*table.add(slot)).cast::(), *expected); + } + if let Some((value, index)) = layout.integer { + assert_eq!(*(*table.add(index)).cast::(), value); + } + if op == Operation::MtpDenseChunk { + assert_eq!(*(*table.add(6)).cast::(), layout.rows); + assert_eq!(*(*table.add(7)).cast::(), layout.columns); + } else if layout.projection { + assert_eq!(*(*table.add(3)).cast::(), layout.rows); + assert_eq!(*(*table.add(4)).cast::(), layout.columns); + } else if op.has_epsilon() { + assert_eq!((*(*table.add(layout.count)).cast::()).to_bits(), 1e-6f32.to_bits()); + } + } +} + #[test] fn qwen_raw_abi_remains_stable_after_moves() { for op in OPERATIONS { @@ -59,26 +106,7 @@ fn qwen_raw_abi_remains_stable_after_moves() { assert_eq!(pointer, moved.storage.as_ptr()); let layout = op.layout(); let table = moved.parameters(); - // SAFETY: read exactly the live owner's initialized scalar fields; - // private ABI pointer table is valid across the owner moves above. - unsafe { - for (i, expected) in [11u64, 22, 33, 44, 55, 66, 77, 88, 0].iter().enumerate().take(layout.count) { - let slot = i + usize::from(layout.integer.is_some_and(|(_, index)| index <= i)); - assert_eq!(*(*table.add(slot)).cast::(), *expected); - } - if let Some((value, index)) = layout.integer { - assert_eq!(*(*table.add(index)).cast::(), value); - } - if op == Operation::MtpDenseChunk { - assert_eq!(*(*table.add(6)).cast::(), layout.rows); - assert_eq!(*(*table.add(7)).cast::(), layout.columns); - } else if layout.projection { - assert_eq!(*(*table.add(3)).cast::(), layout.rows); - assert_eq!(*(*table.add(4)).cast::(), layout.columns); - } else if op.has_epsilon() { - assert_eq!((*(*table.add(layout.count)).cast::()).to_bits(), 1e-6f32.to_bits()); - } - } + assert_raw_table_matches_layout(op, &layout, table); } } #[test] @@ -103,6 +131,49 @@ fn qwen_router_has_exact_three_pointer_abi_and_32_by_8_geometry() { assert_eq!(admitted.receipt.qualification_receipt, "STRA-166 b31a40ef-50b1-4ece-8d9d-1467c1feb388"); } +/// The frozen alignment of parameter `i`: the BF16 value matrix and the conv weights are 2-byte aligned. +fn ple_alignment(op: Operation, i: usize) -> u64 { + if (op == Operation::PleValue && i == 1) || (op == Operation::PleConv && i == 2) { 2 } else { 4 } +} + +fn assert_ple_layout(op: Operation, entry: &std::ffi::CStr, bytes: &[usize], (outputs, grid): (u16, u32)) { + let layout = op.layout(); + assert_eq!(op.entry(), entry); + assert_eq!(layout.count, bytes.len()); + assert_eq!(&layout.bytes[..layout.count], bytes); + assert!(layout.bytes[layout.count..].iter().all(|b| *b == 0)); + assert_eq!(layout.outputs, outputs); + assert_eq!((layout.grid, layout.grid_z, layout.block, layout.block_y), (grid, 1, 256, 1)); + assert!(!layout.projection && !op.has_epsilon()); + for i in 0..layout.count { + assert_eq!(layout.align[i], ple_alignment(op, i)); + } +} + +fn assert_ple_pointer_only_table(op: Operation) { + let layout = op.layout(); + let mut args = Arguments::new(op, [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic), 0.0); + let pointers = args.parameters(); + // SAFETY: table storage belongs to live args. These fixed entries + // have no scalar or hidden shape arguments after their pointers. + unsafe { + for i in layout.count..9 { + assert!((*pointers.add(i)).is_null()); + } + } +} + +fn assert_ple_component_receipt(op: Operation) { + let admitted = asset(op).expect("independently reviewed PLE component"); + assert_eq!(admitted.validate(op), Ok(())); + assert_eq!(admitted.receipt.qualification_receipt, "STRA-161 ada1a470-76ad-47af-a326-e388ae592d51"); + // A self-consistent forged pin still cannot admit different bytes. + let mut bad = admitted.receipt; + bad.ptx_sha256[0] ^= 1; + let corrupt = Asset { operation: op, ptx: admitted.ptx, receipt: bad, pin: bad }; + assert_eq!(corrupt.validate(op), Err(Error::UnsupportedQwenOperation)); +} + #[test] fn qwen_ple_fixed_geometry_has_pointer_only_abi_and_exact_component_receipt() { // Expectations are the independently frozen STRA-161/172 contract. @@ -114,35 +185,8 @@ fn qwen_ple_fixed_geometry_has_pointer_only_abi_and_exact_component_receipt() { (Operation::PleConv, c"leleka_ple_conv_history_f32", vec![368640, 40960, 81920, 40960, 368640], 24, 40), (Operation::PleResidual, c"leleka_ple_residual_f32", vec![40960, 40960, 40960, 40960], 8, 40), ] { - let layout = op.layout(); - assert_eq!(op.entry(), entry); - assert_eq!(layout.count, bytes.len()); - assert_eq!(layout.bytes[..layout.count], bytes); - assert!(layout.bytes[layout.count..].iter().all(|b| *b == 0)); - assert_eq!(layout.outputs, outputs); - assert_eq!((layout.grid, layout.grid_z, layout.block, layout.block_y), (grid, 1, 256, 1)); - assert!(!layout.projection && !op.has_epsilon()); - for i in 0..layout.count { - let expected = - if (op == Operation::PleValue && i == 1) || (op == Operation::PleConv && i == 2) { 2 } else { 4 }; - assert_eq!(layout.align[i], expected); - } - let mut args = Arguments::new(op, [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic), 0.0); - let pointers = args.parameters(); - // SAFETY: table storage belongs to live args. These fixed entries - // have no scalar or hidden shape arguments after their pointers. - unsafe { - for i in layout.count..9 { - assert!((*pointers.add(i)).is_null()); - } - } - let admitted = asset(op).expect("independently reviewed PLE component"); - assert_eq!(admitted.validate(op), Ok(())); - assert_eq!(admitted.receipt.qualification_receipt, "STRA-161 ada1a470-76ad-47af-a326-e388ae592d51"); - // A self-consistent forged pin still cannot admit different bytes. - let mut bad = admitted.receipt; - bad.ptx_sha256[0] ^= 1; - let corrupt = Asset { operation: op, ptx: admitted.ptx, receipt: bad, pin: bad }; - assert_eq!(corrupt.validate(op), Err(Error::UnsupportedQwenOperation)); + assert_ple_layout(op, entry, &bytes, (outputs, grid)); + assert_ple_pointer_only_table(op); + assert_ple_component_receipt(op); } } diff --git a/crates/cuda-driver/src/qwen_ffi/tests/mtp_new_qualified_assets.rs b/crates/cuda-driver/src/qwen_ffi/tests/mtp_new_qualified_assets.rs index f23565d5..845033b9 100644 --- a/crates/cuda-driver/src/qwen_ffi/tests/mtp_new_qualified_assets.rs +++ b/crates/cuda-driver/src/qwen_ffi/tests/mtp_new_qualified_assets.rs @@ -1,8 +1,49 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): mtp_new_qualified_assets_and_fixed_dense_scalar_abi. +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! mtp_new_qualified_assets_and_fixed_dense_scalar_abi. #[allow(unused_imports)] use super::*; +fn assert_forged_pin_is_refused(operation: Operation) { + let asset = asset(operation).unwrap(); + asset.validate(operation).unwrap(); + // A caller who modifies both the metadata and its duplicate pin + // still cannot admit different executable bytes. + let mut forged = Asset { operation, ptx: asset.ptx, receipt: asset.receipt, pin: asset.pin }; + forged.receipt.ptx_sha256[0] ^= 1; + forged.pin = forged.receipt; + assert_eq!(forged.validate(operation), Err(Error::UnsupportedQwenOperation)); +} + +fn assert_dense_chunk_table(layout: Layout, width: u32, chunks: u32) { + let handles = [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic); + let owner = Arguments::with_layout(Operation::MtpDenseChunk, layout, handles, 0.0); + let mut moved = std::hint::black_box(vec![owner]).pop().unwrap(); + let table = moved.parameters(); + // SAFETY: exact initialized fields in one live stable ABI owner. + unsafe { + for (i, address) in [11u64, 22, 33, 44, 55, 66].iter().enumerate() { + assert_eq!(*(*table.add(i)).cast::(), *address); + } + assert_eq!(*(*table.add(6)).cast::(), width); + assert_eq!(*(*table.add(7)).cast::(), chunks); + assert!((*table.add(8)).is_null()); + } +} + +fn assert_dense_position(position: u32, width: u32, chunks: u32) { + let layout = mtp_dense_layout(Operation::MtpDenseChunk, position).unwrap(); + assert_eq!((layout.rows, layout.columns, layout.grid, layout.grid_y), (width, chunks, chunks, 2)); + assert_eq!( + (layout.bytes[1], layout.bytes[3], layout.bytes[4]), + (width as usize * 1024, chunks as usize * 24576, chunks as usize * 96) + ); + assert_dense_chunk_table(layout, width, chunks); + let merge = mtp_dense_layout(Operation::MtpDenseMerge, position).unwrap(); + assert_eq!(merge.integer, Some((chunks, 4))); + assert_eq!((merge.grid, merge.block, merge.outputs), (24, 256, 8)); +} + #[test] fn mtp_new_qualified_assets_and_fixed_dense_scalar_abi() { for operation in [ @@ -12,38 +53,10 @@ fn mtp_new_qualified_assets_and_fixed_dense_scalar_abi() { Operation::MtpDenseChunk, Operation::MtpDenseMerge, ] { - let asset = asset(operation).unwrap(); - asset.validate(operation).unwrap(); - // A caller who modifies both the metadata and its duplicate pin - // still cannot admit different executable bytes. - let mut forged = Asset { operation, ptx: asset.ptx, receipt: asset.receipt, pin: asset.pin }; - forged.receipt.ptx_sha256[0] ^= 1; - forged.pin = forged.receipt; - assert_eq!(forged.validate(operation), Err(Error::UnsupportedQwenOperation)); + assert_forged_pin_is_refused(operation); } for (position, width, chunks) in [(0, 1, 1), (63, 64, 1), (64, 65, 2), (32767, 32768, 512), (262143, 32768, 512)] { - let layout = mtp_dense_layout(Operation::MtpDenseChunk, position).unwrap(); - assert_eq!((layout.rows, layout.columns, layout.grid, layout.grid_y), (width, chunks, chunks, 2)); - assert_eq!( - (layout.bytes[1], layout.bytes[3], layout.bytes[4]), - (width as usize * 1024, chunks as usize * 24576, chunks as usize * 96) - ); - let handles = [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic); - let owner = Arguments::with_layout(Operation::MtpDenseChunk, layout, handles, 0.0); - let mut moved = std::hint::black_box(vec![owner]).pop().unwrap(); - let table = moved.parameters(); - // SAFETY: exact initialized fields in one live stable ABI owner. - unsafe { - for (i, address) in [11u64, 22, 33, 44, 55, 66].iter().enumerate() { - assert_eq!(*(*table.add(i)).cast::(), *address); - } - assert_eq!(*(*table.add(6)).cast::(), width); - assert_eq!(*(*table.add(7)).cast::(), chunks); - assert!((*table.add(8)).is_null()); - } - let merge = mtp_dense_layout(Operation::MtpDenseMerge, position).unwrap(); - assert_eq!(merge.integer, Some((chunks, 4))); - assert_eq!((merge.grid, merge.block, merge.outputs), (24, 256, 8)); + assert_dense_position(position, width, chunks); } for position in [crate::MAX_CONTEXT_CELLS as u32, u32::MAX] { assert_eq!(mtp_dense_layout(Operation::MtpDenseChunk, position).err(), Some(Error::InvalidQwenShape)); diff --git a/crates/cuda-driver/src/qwen_ffi/tests/qsa_new_literal_abi_scalar.rs b/crates/cuda-driver/src/qwen_ffi/tests/qsa_new_literal_abi_scalar.rs index 0ee90032..8985be29 100644 --- a/crates/cuda-driver/src/qwen_ffi/tests/qsa_new_literal_abi_scalar.rs +++ b/crates/cuda-driver/src/qwen_ffi/tests/qsa_new_literal_abi_scalar.rs @@ -1,68 +1,198 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): qsa_new_literal_abi_scalar_order_and_geometry, qsa_new_position_block_boundaries_and_attention_width_refusals. +//! Tests of tests by topic (moved out of the test file by STRA-338): qsa_new_literal_abi_scalar_order_and_geometry, +//! qsa_new_position_block_boundaries_and_attention_width_refusals. #[allow(unused_imports)] use super::*; -#[test] -fn qsa_new_literal_abi_scalar_order_and_geometry() { - // Independently frozen producer ABI, STRA-172 AD10; no candidate PTX. - for (operation, entry, bytes, outputs, grid, grid_y, shared, index) in [ - (Operation::QsaSplit, c"leleka_qsa_split_q_gate", vec![49152, 24576, 24576], 6, 24, 1, 0, None), - (Operation::QsaNormQ, c"leleka_qsa_norm_q", vec![24576, 1024, 24576], 4, 24, 1, 0, None), - (Operation::QsaNormK, c"leleka_qsa_norm_k", vec![2048, 1024, 2048], 4, 2, 1, 0, None), - (Operation::QsaNormIndexQ, c"leleka_qsa_norm_index_q", vec![2048, 512, 2048], 4, 4, 1, 0, None), - (Operation::QsaRopeQ, c"leleka_qsa_rope_q", vec![24576, 24576], 2, 1, 24, 0, Some(1)), - (Operation::QsaRopeK, c"leleka_qsa_rope_k", vec![2048, 2048], 2, 1, 2, 0, Some(1)), - (Operation::QsaRopeIndexQ, c"leleka_qsa_rope_index_q", vec![2048, 2048], 2, 1, 4, 0, Some(1)), - (Operation::QsaIndexAppend, c"leleka_qsa_index_append", vec![512, 512, 2048, 2560], 8, 1, 1, 0, Some(4)), - (Operation::QsaPackKv, c"leleka_qsa_pack_kv", vec![2048, 2048, 1024, 1024], 12, 2, 1, 0, None), - (Operation::QsaBlockScores, c"leleka_qsa_block_scores", vec![1024, 512, 2048, 8], 8, 256, 1, 0, Some(4)), - (Operation::QsaBlockTopk, c"leleka_qsa_block_topk", vec![8, 8204], 2, 1, 1, 0, Some(2)), - (Operation::QsaAttend, c"leleka_qsa_attend", vec![24576, 3072, 3072, 24576], 8, 24, 1, 8332, Some(4)), - (Operation::QsaGate, c"leleka_qsa_gate_f32", vec![24576, 24576, 24576], 4, 24, 1, 0, None), - ] { - let layout = qsa_layout(operation, 3).unwrap(); - assert_eq!(operation.entry(), entry); - assert_eq!(&layout.bytes[..layout.count], bytes); - assert_eq!( - ( - layout.outputs, - layout.grid, - layout.grid_y, - layout.grid_z, - layout.block, - layout.block_y, - layout.shared_bytes - ), - (outputs, grid, grid_y, 1, 256, 1, shared) - ); - assert_eq!(layout.integer, index.map(|i| (3, i))); - asset(operation).expect("qualified fixed QSA asset").validate(operation).unwrap(); - let addresses = [101, 202, 303, 404, 505, 606, 707, 808, 0]; - let handles = addresses.map(ffi::BufferHandle::synthetic); - let arguments = Arguments::with_layout(operation, layout, handles, 0.0); - // Move the raw allocation owner, then read its initialized fields; - // no Box ownership/reborrow is introduced after pointer formation. - let mut moved = std::hint::black_box(arguments); - let table = moved.parameters(); - // SAFETY: table points into one live raw-owned allocation, exact - // parameter types/order are the independent frozen ABI above. - unsafe { - for (i, address) in addresses.iter().take(bytes.len()).enumerate() { - let slot = i + usize::from(index.is_some_and(|j| j <= i)); - assert_eq!(*(*table.add(slot)).cast::(), *address); - } - if let Some(i) = index { - assert_eq!(*(*table.add(i)).cast::(), 3); - } - assert!((*table.add(bytes.len() + usize::from(index.is_some()))).is_null()); +/// One independently frozen QSA entry: operation, entry name, ABI sizes, geometry and the scalar parameter index. +struct QsaCase { + operation: Operation, + entry: &'static std::ffi::CStr, + bytes: &'static [usize], + outputs: u16, + grid: u32, + grid_y: u32, + shared: u32, + index: Option, +} + +// Independently frozen producer ABI, STRA-172 AD10; no candidate PTX. +const QSA_CASES: [QsaCase; 13] = [ + QsaCase { + operation: Operation::QsaSplit, + entry: c"leleka_qsa_split_q_gate", + bytes: &[49152, 24576, 24576], + outputs: 6, + grid: 24, + grid_y: 1, + shared: 0, + index: None, + }, + QsaCase { + operation: Operation::QsaNormQ, + entry: c"leleka_qsa_norm_q", + bytes: &[24576, 1024, 24576], + outputs: 4, + grid: 24, + grid_y: 1, + shared: 0, + index: None, + }, + QsaCase { + operation: Operation::QsaNormK, + entry: c"leleka_qsa_norm_k", + bytes: &[2048, 1024, 2048], + outputs: 4, + grid: 2, + grid_y: 1, + shared: 0, + index: None, + }, + QsaCase { + operation: Operation::QsaNormIndexQ, + entry: c"leleka_qsa_norm_index_q", + bytes: &[2048, 512, 2048], + outputs: 4, + grid: 4, + grid_y: 1, + shared: 0, + index: None, + }, + QsaCase { + operation: Operation::QsaRopeQ, + entry: c"leleka_qsa_rope_q", + bytes: &[24576, 24576], + outputs: 2, + grid: 1, + grid_y: 24, + shared: 0, + index: Some(1), + }, + QsaCase { + operation: Operation::QsaRopeK, + entry: c"leleka_qsa_rope_k", + bytes: &[2048, 2048], + outputs: 2, + grid: 1, + grid_y: 2, + shared: 0, + index: Some(1), + }, + QsaCase { + operation: Operation::QsaRopeIndexQ, + entry: c"leleka_qsa_rope_index_q", + bytes: &[2048, 2048], + outputs: 2, + grid: 1, + grid_y: 4, + shared: 0, + index: Some(1), + }, + QsaCase { + operation: Operation::QsaIndexAppend, + entry: c"leleka_qsa_index_append", + bytes: &[512, 512, 2048, 2560], + outputs: 8, + grid: 1, + grid_y: 1, + shared: 0, + index: Some(4), + }, + QsaCase { + operation: Operation::QsaPackKv, + entry: c"leleka_qsa_pack_kv", + bytes: &[2048, 2048, 1024, 1024], + outputs: 12, + grid: 2, + grid_y: 1, + shared: 0, + index: None, + }, + QsaCase { + operation: Operation::QsaBlockScores, + entry: c"leleka_qsa_block_scores", + bytes: &[1024, 512, 2048, 8], + outputs: 8, + grid: 256, + grid_y: 1, + shared: 0, + index: Some(4), + }, + QsaCase { + operation: Operation::QsaBlockTopk, + entry: c"leleka_qsa_block_topk", + bytes: &[8, 8204], + outputs: 2, + grid: 1, + grid_y: 1, + shared: 0, + index: Some(2), + }, + QsaCase { + operation: Operation::QsaAttend, + entry: c"leleka_qsa_attend", + bytes: &[24576, 3072, 3072, 24576], + outputs: 8, + grid: 24, + grid_y: 1, + shared: 8332, + index: Some(4), + }, + QsaCase { + operation: Operation::QsaGate, + entry: c"leleka_qsa_gate_f32", + bytes: &[24576, 24576, 24576], + outputs: 4, + grid: 24, + grid_y: 1, + shared: 0, + index: None, + }, +]; + +fn assert_qsa_layout(case: &QsaCase, layout: &Layout) { + assert_eq!(case.operation.entry(), case.entry); + assert_eq!(&layout.bytes[..layout.count], case.bytes); + assert_eq!( + (layout.outputs, layout.grid, layout.grid_y, layout.grid_z, layout.block, layout.block_y, layout.shared_bytes), + (case.outputs, case.grid, case.grid_y, 1, 256, 1, case.shared) + ); + assert_eq!(layout.integer, case.index.map(|i| (3, i))); + asset(case.operation).expect("qualified fixed QSA asset").validate(case.operation).unwrap(); +} + +fn assert_qsa_parameter_table(case: &QsaCase, layout: Layout) { + let (bytes, index) = (case.bytes, case.index); + let addresses = [101, 202, 303, 404, 505, 606, 707, 808, 0]; + let handles = addresses.map(ffi::BufferHandle::synthetic); + let arguments = Arguments::with_layout(case.operation, layout, handles, 0.0); + // Move the raw allocation owner, then read its initialized fields; + // no Box ownership/reborrow is introduced after pointer formation. + let mut moved = std::hint::black_box(arguments); + let table = moved.parameters(); + // SAFETY: table points into one live raw-owned allocation, exact + // parameter types/order are the independent frozen ABI above. + unsafe { + for (i, address) in addresses.iter().take(bytes.len()).enumerate() { + let slot = i + usize::from(index.is_some_and(|j| j <= i)); + assert_eq!(*(*table.add(slot)).cast::(), *address); } - for (i, alignment) in layout.align.iter().take(layout.count).enumerate() { - let packed = (operation == Operation::QsaPackKv && i >= 2) - || (operation == Operation::QsaAttend && (i == 1 || i == 2)); - assert_eq!(*alignment, if packed { 2 } else { 4 }); + if let Some(i) = index { + assert_eq!(*(*table.add(i)).cast::(), 3); } + assert!((*table.add(bytes.len() + usize::from(index.is_some()))).is_null()); } +} + +fn assert_qsa_alignment(operation: Operation, layout: &Layout) { + for (i, alignment) in layout.align.iter().take(layout.count).enumerate() { + let packed = + (operation == Operation::QsaPackKv && i >= 2) || (operation == Operation::QsaAttend && (i == 1 || i == 2)); + assert_eq!(*alignment, if packed { 2 } else { 4 }); + } +} + +fn assert_older_layouts_have_no_qsa_fields() { assert_eq!(OPERATIONS.len(), 58); for operation in OPERATIONS.into_iter().filter(|op| { !QSA_OPERATIONS.contains(op) @@ -82,7 +212,17 @@ fn qsa_new_literal_abi_scalar_order_and_geometry() { } #[test] -fn qsa_new_position_block_boundaries_and_attention_width_refusals() { +fn qsa_new_literal_abi_scalar_order_and_geometry() { + for case in &QSA_CASES { + let layout = qsa_layout(case.operation, 3).unwrap(); + assert_qsa_layout(case, &layout); + assert_qsa_parameter_table(case, layout); + assert_qsa_alignment(case.operation, &layout); + } + assert_older_layouts_have_no_qsa_fields(); +} + +fn assert_qsa_block_boundaries() { // Literal causal/block boundaries, including one past the context. for (position, pooled, scores) in [ (0, 512, 4), @@ -101,6 +241,9 @@ fn qsa_new_position_block_boundaries_and_attention_width_refusals() { assert_eq!((ids.bytes[0], ids.bytes[1]), (scores, 8204)); assert_eq!(score.integer, Some((position, 4))); } +} + +fn assert_qsa_position_ceiling() { for operation in QSA_OPERATIONS.into_iter().filter(|op| *op != Operation::QsaAttend) { assert!(qsa_layout(operation, 262143).is_ok()); assert!(qsa_layout(operation, 262144).is_ok()); @@ -109,6 +252,12 @@ fn qsa_new_position_block_boundaries_and_attention_width_refusals() { assert!(matches!(qsa_layout(operation, position), Err(Error::InvalidQwenShape))); } } +} + +#[test] +fn qsa_new_position_block_boundaries_and_attention_width_refusals() { + assert_qsa_block_boundaries(); + assert_qsa_position_ceiling(); for (width, extent) in [(1, 1024), (2051, 2100224)] { let layout = qsa_layout(Operation::QsaAttend, width).unwrap(); assert_eq!((layout.bytes[1], layout.bytes[2]), (extent, extent)); diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_drop_for_sharedexpertworkspace.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_drop_for_sharedexpertworkspace.rs index 269a5ddb..e44de159 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_drop_for_sharedexpertworkspace.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_drop_for_sharedexpertworkspace.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Drop_for_SharedExpertWorkspace, fn staging, fn status_spans, fn first_refusal, fn append_finite, fn append_projection .... +//! Moved out of the parent module by STRA-338: impl Drop_for_SharedExpertWorkspace, fn staging, fn status_spans, fn +//! first_refusal, fn append_finite, fn append_projection .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedgukind.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedgukind.rs index 61fbaec1..80683243 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedgukind.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedgukind.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl SharedGuKind, impl SharedDownKind, impl SharedTailCompletion, impl Context. +//! Moved out of the parent module by STRA-338: impl SharedGuKind, impl SharedDownKind, impl SharedTailCompletion, impl +//! Context. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qwen_shared_tail_gpu/original_fn.rs b/crates/cuda-driver/src/qwen_shared_tail_gpu/original_fn.rs index e1c80063..710998a5 100644 --- a/crates/cuda-driver/src/qwen_shared_tail_gpu/original_fn.rs +++ b/crates/cuda-driver/src/qwen_shared_tail_gpu/original_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn original, fn compare, impl RestoreHandle, impl Drop_for_RestoreHandle. +//! Moved out of the parent module by STRA-338: fn original, fn compare, impl RestoreHandle, impl +//! Drop_for_RestoreHandle. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qwen_shared_tail_gpu/read_fn.rs b/crates/cuda-driver/src/qwen_shared_tail_gpu/read_fn.rs index fe285dc1..b3e7afaa 100644 --- a/crates/cuda-driver/src/qwen_shared_tail_gpu/read_fn.rs +++ b/crates/cuda-driver/src/qwen_shared_tail_gpu/read_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn read, fn f32_bytes, fn finite, fn input, fn packet, fn scalar_weights .... +//! Moved out of the parent module by STRA-338: fn read, fn f32_bytes, fn finite, fn input, fn packet, fn scalar_weights +//! .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/routed_group_workspace/impl_context.rs b/crates/cuda-driver/src/routed_group_workspace/impl_context.rs index fa05ce0c..0f955980 100644 --- a/crates/cuda-driver/src/routed_group_workspace/impl_context.rs +++ b/crates/cuda-driver/src/routed_group_workspace/impl_context.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Context, impl RoutedGroupWorkspace, impl Drop_for_RoutedGroupWorkspace, impl RoutedGroupWorkspace. +//! Moved out of the parent module by STRA-338: impl Context, impl RoutedGroupWorkspace, impl +//! Drop_for_RoutedGroupWorkspace, impl RoutedGroupWorkspace. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/routed_group_workspace/impl_routedgroupworkspace.rs b/crates/cuda-driver/src/routed_group_workspace/impl_routedgroupworkspace.rs index c4dbccfa..e0448007 100644 --- a/crates/cuda-driver/src/routed_group_workspace/impl_routedgroupworkspace.rs +++ b/crates/cuda-driver/src/routed_group_workspace/impl_routedgroupworkspace.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl RoutedGroupWorkspace, impl RoutedGroupWorkspace, impl RoutedColumnsLoan. +//! Moved out of the parent module by STRA-338: impl RoutedGroupWorkspace, impl RoutedGroupWorkspace, impl +//! RoutedColumnsLoan. #[allow(unused_imports)] use super::impl_context::{check_table, reserve_pointers}; diff --git a/crates/cuda-driver/src/routed_resident_queue/impl_drop_for_routedresidentqueue.rs b/crates/cuda-driver/src/routed_resident_queue/impl_drop_for_routedresidentqueue.rs index f71a7686..725b01b8 100644 --- a/crates/cuda-driver/src/routed_resident_queue/impl_drop_for_routedresidentqueue.rs +++ b/crates/cuda-driver/src/routed_resident_queue/impl_drop_for_routedresidentqueue.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Drop_for_RoutedResidentQueue, fn gu_operation, fn scan, impl Command. +//! Moved out of the parent module by STRA-338: impl Drop_for_RoutedResidentQueue, fn gu_operation, fn scan, impl +//! Command. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/s_gemv_legacy.rs b/crates/cuda-driver/src/s_gemv_legacy.rs index e4cc50aa..c30fd3b2 100644 --- a/crates/cuda-driver/src/s_gemv_legacy.rs +++ b/crates/cuda-driver/src/s_gemv_legacy.rs @@ -1,22 +1,24 @@ -//! Pure half of the Original legacy S-form GEMV kernels (`s_gemv.cu`, `s2_gemv.cu`, `s2_gemv_quads.cu`, `s2_gemv_q8.cu`, -//! `s2_gemv_fast.cu`): the host launchers' admission rules and launch geometry, and CPU models of the kernels' summation -//! order. CUDA source: `s_gemv_legacy.cu`, executed on the host shim by `oracle/drivers/s_gemv_legacy.cpp` against an FP64 -//! reference; the golden fixture `oracle/fixtures/s_gemv_legacy_golden.json` (inputs and shim-kernel outputs) is checked -//! bit-exactly by the models here. +//! Pure half of the Original legacy S-form GEMV kernels (`s_gemv.cu`, `s2_gemv.cu`, `s2_gemv_quads.cu`, +//! `s2_gemv_q8.cu`, `s2_gemv_fast.cu`): the host launchers' admission rules and launch geometry, and CPU models of the +//! kernels' summation order. CUDA source: `s_gemv_legacy.cu`, executed on the host shim by +//! `oracle/drivers/s_gemv_legacy.cpp` against an FP64 reference; the golden fixture +//! `oracle/fixtures/s_gemv_legacy_golden.json` (inputs and shim-kernel outputs) is checked bit-exactly by the models +//! here. //! //! Canonical S-form (docs/pack-format.md): `value = cb[code] * scale + offset`, `y[o] = sum_i value[o][i] * x[i]`; a //! tensor is `[n_in, n_out]` with `n_in` contiguous, row `o` holds `n_in / (8 / bits)` code bytes and `n_in / group` -//! scales (and offsets when the form has them). Activations are fp16, `block_q8_K` (292 B / 256 elements) or `block_q8_0` -//! (34 B / 32 elements). +//! scales (and offsets when the form has them). Activations are fp16, `block_q8_K` (292 B / 256 elements) or +//! `block_q8_0` (34 B / 32 elements). //! -//! No Rust GPU owner launches these yet (they are the legacy path: the production S-form packs go through the MMQ/native -//! kernels). The planners below are what such an owner calls before `Module::launch`; each returns `Err` where the Original -//! launcher printed to stderr and called `std::exit(1)`, and `Ok(None)` where it returned early (`n_in <= 0 || n_out <= 0`). +//! No Rust GPU owner launches these yet (they are the legacy path: the production S-form packs go through the +//! MMQ/native kernels). The planners below are what such an owner calls before `Module::launch`; each returns `Err` +//! where the Original launcher printed to stderr and called `std::exit(1)`, and `Ok(None)` where it returned early +//! (`n_in <= 0 || n_out <= 0`). //! -//! Checks stricter than the Original (all fail-closed, none changes a result the Original would have computed correctly): -//! the split/quads/q8/fast launchers also require a power-of-two `threads_per_row` in `1..=1024` (the in-kernel tree -//! reduction silently drops partial sums otherwise), and `s_gemv_split` also requires `n_in % group_elems == 0` and an -//! offset pointer when the form has one (the Original checked these only in `s_gemv`). +//! Checks stricter than the Original (all fail-closed, none changes a result the Original would have computed +//! correctly): the split/quads/q8/fast launchers also require a power-of-two `threads_per_row` in `1..=1024` (the +//! in-kernel tree reduction silently drops partial sums otherwise), and `s_gemv_split` also requires `n_in % +//! group_elems == 0` and an offset pointer when the form has one (the Original checked these only in `s_gemv`). pub const IQ4NL: [i8; 16] = [-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113]; pub const Q8K_BLOCK_BYTES: usize = 292; @@ -70,8 +72,8 @@ pub enum Kernel { S2GemvFastUnstaged, } -/// Everything a caller needs to launch: the entry, the geometry and the `group_shift` argument (log2 of the group; 0 where -/// the kernel takes `group_elems` instead). +/// Everything a caller needs to launch: the entry, the geometry and the `group_shift` argument (log2 of the group; 0 +/// where the kernel takes `group_elems` instead). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Plan { pub kernel: Kernel, @@ -87,7 +89,8 @@ pub enum Error { OffsetMissing { who: &'static str }, /// "s_gemv: unsupported code_bits " UnsupportedCodeBits { who: &'static str, bits: i32 }, - /// "s_gemv_q8k: code_bits has no Q8_K contract (S2 uses Q8_0; see docs/activation-contract.md)" and the Q8_0 twin + /// "s_gemv_q8k: code_bits has no Q8_K contract (S2 uses Q8_0; see docs/activation-contract.md)" and the Q8_0 + /// twin NoActivationContract { who: &'static str, bits: i32 }, /// ": n_in is not a multiple of the Q8_K block 256" (or of 32 for Q8_0 / the S2 launchers' 64 / 4) NInNotBlockMultiple { who: &'static str, n_in: i64, block: i64 }, @@ -95,7 +98,8 @@ pub enum Error { GroupNotPowerOfTwo { who: &'static str, group: i32 }, /// ": group_elems is not a multiple of " (4 for the fp16 split kernel, 16 for the Q8 kernels) GroupNotMultiple { who: &'static str, group: i32, multiple: i32 }, - /// "s_gemv_split: threads_per_row must be a power of two in 1..1024, got " (also stricter-than-Original for s2_*) + /// "s_gemv_split: threads_per_row must be a power of two in 1..1024, got " (also stricter-than-Original for + /// s2_*) ThreadsPerRow { who: &'static str, threads: i32 }, /// "s2_gemv_fast: n_in exceeds the 4096-half shared staging limit" StagingLimit { n_in: i64 }, diff --git a/crates/cuda-driver/src/s_gemv_legacy/impl_default_for_sform.rs b/crates/cuda-driver/src/s_gemv_legacy/impl_default_for_sform.rs index aa0f6a00..2828e6b5 100644 --- a/crates/cuda-driver/src/s_gemv_legacy/impl_default_for_sform.rs +++ b/crates/cuda-driver/src/s_gemv_legacy/impl_default_for_sform.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Default_for_SForm, impl Kernel, impl Error, fn grid_for, fn ceil_div, fn group_shift_of .... +//! Moved out of the parent module by STRA-338: impl Default_for_SForm, impl Kernel, impl Error, fn grid_for, fn +//! ceil_div, fn group_shift_of .... #[allow(unused_imports)] use super::*; @@ -150,7 +151,8 @@ pub(super) fn bits_u8(who: &'static str, bits: i32, allowed: &[i32], contract: b } } -/// `s_gemv`: one thread per output row, 128 threads, `ceil(n_out / 128)` blocks. `offset_present` is `offset != nullptr`. +/// `s_gemv`: one thread per output row, 128 threads, `ceil(n_out / 128)` blocks. `offset_present` is `offset != +/// nullptr`. pub fn plan_s_gemv(n_in: i64, n_out: i64, form: &SForm, offset_present: bool) -> Result, Error> { const WHO: &str = "s_gemv"; if n_in <= 0 || n_out <= 0 { @@ -193,8 +195,8 @@ fn split_checks( } Ok(()) } -/// `s_gemv_split` / `s_gemv_split_async`: one block of `threads_per_row` threads per row, `threads_per_row * 4` bytes of -/// dynamic shared memory for the reduction tree. +/// `s_gemv_split` / `s_gemv_split_async`: one block of `threads_per_row` threads per row, `threads_per_row * 4` bytes +/// of dynamic shared memory for the reduction tree. pub fn plan_s_gemv_split( n_in: i64, n_out: i64, diff --git a/crates/cuda-driver/src/s_gemv_legacy/plan_s2_gemv_quads_fn.rs b/crates/cuda-driver/src/s_gemv_legacy/plan_s2_gemv_quads_fn.rs index 61731266..73a92dc8 100644 --- a/crates/cuda-driver/src/s_gemv_legacy/plan_s2_gemv_quads_fn.rs +++ b/crates/cuda-driver/src/s_gemv_legacy/plan_s2_gemv_quads_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn plan_s2_gemv_quads, fn plan_s2_gemv_q8, fn plan_s2_gemv_fast, fn f16_to_f32, fn code_at, fn pack_codes .... +//! Moved out of the parent module by STRA-338: fn plan_s2_gemv_quads, fn plan_s2_gemv_q8, fn plan_s2_gemv_fast, fn +//! f16_to_f32, fn code_at, fn pack_codes .... #[allow(unused_imports)] use super::*; @@ -47,9 +48,9 @@ pub fn plan_s2_gemv_q8(n_in: i64, n_out: i64, threads_per_row: i32) -> Result Result, Error> { const WHO: &str = "s2_gemv_fast"; if n_in <= 0 || n_out <= 0 { @@ -77,7 +78,8 @@ fn fast_checks(who: &'static str, n_in: i64, (threads_per_row, stage_x): (i32, b Ok(()) } -// ---- CPU models ------------------------------------------------------------------------------------------------------- +// ---- CPU models +// ------------------------------------------------------------------------------------------------------- /// binary16 bits to f32 (exact). pub fn f16_to_f32(bits: u16) -> f32 { @@ -217,9 +219,10 @@ fn accumulate(w: &Weights, x: &[f32], o: usize, (first, stride) } a } -/// Literal model of `s_gemv_q8_split_kernel` (warp per row): lane `l` takes 16 consecutive elements at `l*16 + 512*k` into -/// sixteen accumulators; `acc = (((a0+a1)+(a2+a3))+((a4+a5)+(a6+a7))) + (((a8+a9)+(a10+a11))+((a12+a13)+(a14+a15)))`; lane 0 -/// then reads the `__shfl_down_sync` tree with steps 16, 8, 4, 2, 1. `act` holds the dequantised activations (`d * q`). +/// Literal model of `s_gemv_q8_split_kernel` (warp per row): lane `l` takes 16 consecutive elements at `l*16 + 512*k` +/// into sixteen accumulators; `acc = (((a0+a1)+(a2+a3))+((a4+a5)+(a6+a7))) + +/// (((a8+a9)+(a10+a11))+((a12+a13)+(a14+a15)))`; lane 0 then reads the `__shfl_down_sync` tree with steps 16, 8, 4, 2, +/// 1. `act` holds the dequantised activations (`d * q`). pub fn q8_split_f32(w: &Weights, act: &[f32]) -> Vec { const QE: usize = 16; (0..w.n_out) diff --git a/crates/cuda-driver/src/s_gemv_legacy/tests.rs b/crates/cuda-driver/src/s_gemv_legacy/tests.rs index 39bb5f08..02e46e2c 100644 --- a/crates/cuda-driver/src/s_gemv_legacy/tests.rs +++ b/crates/cuda-driver/src/s_gemv_legacy/tests.rs @@ -29,6 +29,44 @@ fn bits_eq(a: &[f32], b: &[f32], what: &str) { } } +fn check_fp16_case(w: &Weights, c: &Value, name: &str, exact: bool) { + // fp16 activations + let x: Vec = c["x"].as_array().unwrap().iter().map(|v| f16_to_f32(v.as_u64().unwrap() as u16)).collect(); + let y = f32s(&c["y_fp16"]); + bits_eq(&split_f32(w, &x, 64), &y, &format!("{name} split64")); + if exact { + // every order is exact: the naive kernel, the FP64 spec and the split kernel coincide + bits_eq(&naive_f32(w, &x), &y, &format!("{name} naive")); + let r: Vec = reference_f64(w, &x).iter().map(|&v| v as f32).collect(); + bits_eq(&r, &y, &format!("{name} f64")); + } +} + +fn check_q8k_case(w: &Weights, c: &Value, name: &str) { + // Q8_K activations (4- and 8-bit forms with n_in % 256 == 0) + let q8k = u8s(&c["q8k"]); + if w.form.code_bits != 2 && !q8k.is_empty() { + let a = q8k_dequant(&q8k, w.n_in); + bits_eq(&q8_split_f32(w, &a), &f32s(&c["y_q8k"]), &format!("{name} q8k split")); + } +} + +fn check_q80_case(w: &Weights, c: &Value, name: &str, exact: bool) { + // Q8_0 activations (the S2 entry is s2_gemv_q8, whose tree is the quad kernel's) + let q80 = u8s(&c["q80"]); + if !q80.is_empty() { + let a = q8_0_dequant(&q80, w.n_in); + let y80 = f32s(&c["y_q80"]); + if w.form.code_bits != 2 { + bits_eq(&q8_split_f32(w, &a), &y80, &format!("{name} q8_0 split")); + } else { + assert!(exact); + let r: Vec = reference_f64(w, &a).iter().map(|&v| v as f32).collect(); + bits_eq(&r, &y80, &format!("{name} s2_gemv_q8")); + } + } +} + #[test] fn golden_cases_match_the_shim_executed_kernels_bit_for_bit() { let g = golden(); @@ -42,35 +80,9 @@ fn golden_cases_match_the_shim_executed_kernels_bit_for_bit() { let offset = if f.has_offset { Some(f32s(&c["offset"])) } else { None }; let w = Weights { codes: &codes, scales: &scales, offset: offset.as_deref(), form: f, n_in, n_out }; let exact = c["exact"].as_i64().unwrap() == 1; - // fp16 activations - let x: Vec = c["x"].as_array().unwrap().iter().map(|v| f16_to_f32(v.as_u64().unwrap() as u16)).collect(); - let y = f32s(&c["y_fp16"]); - bits_eq(&split_f32(&w, &x, 64), &y, &format!("{name} split64")); - if exact { - // every order is exact: the naive kernel, the FP64 spec and the split kernel coincide - bits_eq(&naive_f32(&w, &x), &y, &format!("{name} naive")); - let r: Vec = reference_f64(&w, &x).iter().map(|&v| v as f32).collect(); - bits_eq(&r, &y, &format!("{name} f64")); - } - // Q8_K activations (4- and 8-bit forms with n_in % 256 == 0) - let q8k = u8s(&c["q8k"]); - if f.code_bits != 2 && !q8k.is_empty() { - let a = q8k_dequant(&q8k, n_in); - bits_eq(&q8_split_f32(&w, &a), &f32s(&c["y_q8k"]), &format!("{name} q8k split")); - } - // Q8_0 activations (the S2 entry is s2_gemv_q8, whose tree is the quad kernel's) - let q80 = u8s(&c["q80"]); - if !q80.is_empty() { - let a = q8_0_dequant(&q80, n_in); - let y80 = f32s(&c["y_q80"]); - if f.code_bits != 2 { - bits_eq(&q8_split_f32(&w, &a), &y80, &format!("{name} q8_0 split")); - } else { - assert!(exact); - let r: Vec = reference_f64(&w, &a).iter().map(|&v| v as f32).collect(); - bits_eq(&r, &y80, &format!("{name} s2_gemv_q8")); - } - } + check_fp16_case(&w, c, name, exact); + check_q8k_case(&w, c, name); + check_q80_case(&w, c, name, exact); checked += 1; } assert_eq!(checked, 8); @@ -98,6 +110,17 @@ fn f16_conversion_covers_normal_subnormal_and_special() { assert!(f16_to_f32(0x7e00).is_nan()); } +fn assert_every_entry_in_source(src: &str) { + for e in Kernel::ALL_ENTRIES { + // macro-expanded entries are checked above through their invocations; the explicit ones by name + let direct = src.contains(&format!("void {e}(")); + let via_macro = e.starts_with("leleka_s_gemv_") && !e.contains("q8k_split") && !e.contains("q8_0_split"); + let split = (e.contains("q8k_split") || e.contains("q8_0_split")) + && src.contains(&format!("LELEKA_S_GEMV_Q8_SPLIT({e},")); + assert!(direct || via_macro || split, "entry {e} not found in s_gemv_legacy.cu"); + } +} + #[test] fn cuda_source_carries_the_codebook_and_every_entry() { let src = include_str!("../s_gemv_legacy.cu"); @@ -110,14 +133,7 @@ fn cuda_source_carries_the_codebook_and_every_entry() { for b in [4, 8] { assert!(src.contains(&format!("LELEKA_S_GEMV_Q8K({b})"))); } - for e in Kernel::ALL_ENTRIES { - // macro-expanded entries are checked above through their invocations; the explicit ones by name - let direct = src.contains(&format!("void {e}(")); - let via_macro = e.starts_with("leleka_s_gemv_") && !e.contains("q8k_split") && !e.contains("q8_0_split"); - let split = (e.contains("q8k_split") || e.contains("q8_0_split")) - && src.contains(&format!("LELEKA_S_GEMV_Q8_SPLIT({e},")); - assert!(direct || via_macro || split, "entry {e} not found in s_gemv_legacy.cu"); - } + assert_every_entry_in_source(src); // the s2_gemv_fast code table was generated: row b is [(b>>2k & 3) - 1 for k in 0..4] assert!(src.contains("{-1.0f, -1.0f, -1.0f, -1.0f},")); assert!(src.contains("{2.0f, 2.0f, 2.0f, 2.0f}\n};")); @@ -189,6 +205,33 @@ fn plan_split_uses_a_row_per_block_and_shift_group() { assert!(plan_s_gemv_split(2562, 8, &f, 32, false).is_err()); } +fn assert_q8k_plans(f: &SForm) { + let p = plan_s_gemv_q8k_split(2560, 10240, f).unwrap().unwrap(); + assert_eq!(p.launch, Launch { grid: [1280, 1, 1], block: [256, 1, 1], dynamic_shared: 0 }); + assert_eq!(p.group_shift, 5); + assert_eq!(plan_s_gemv_q8k(2560, 10240, f).unwrap().unwrap().launch.grid, [80, 1, 1]); + // 640 is a multiple of 32 but not of 256: only the Q8_0 kernel serves ffn_down_shexp + assert_eq!( + plan_s_gemv_q8k_split(640, 2560, f), + Err(Error::NInNotBlockMultiple { who: "s_gemv_q8k_split", n_in: 640, block: 256 }) + ); +} + +fn assert_q8_0_plans(f: &SForm) { + let p0 = plan_s_gemv_q8_0_split(640, 2560, f).unwrap().unwrap(); + assert_eq!(p0.kernel, Kernel::SGemvQ80Split(4)); + assert_eq!(p0.launch.grid, [320, 1, 1]); + assert_eq!( + plan_s_gemv_q8_0_split(100, 8, f), + Err(Error::NInNotBlockMultiple { who: "s_gemv_q8_0_split", n_in: 100, block: 32 }) + ); + let g8 = SForm { group_elems: 8, ..*f }; + assert_eq!( + plan_s_gemv_q8_0_split(640, 8, &g8), + Err(Error::GroupNotMultiple { who: "s_gemv_q8_0_split", group: 8, multiple: 16 }) + ); +} + #[test] fn plan_q8_kernels_enforce_the_activation_contract() { let f = SForm { @@ -199,27 +242,8 @@ fn plan_q8_kernels_enforce_the_activation_contract() { has_offset: false, act_kind: 1, }; - let p = plan_s_gemv_q8k_split(2560, 10240, &f).unwrap().unwrap(); - assert_eq!(p.launch, Launch { grid: [1280, 1, 1], block: [256, 1, 1], dynamic_shared: 0 }); - assert_eq!(p.group_shift, 5); - assert_eq!(plan_s_gemv_q8k(2560, 10240, &f).unwrap().unwrap().launch.grid, [80, 1, 1]); - // 640 is a multiple of 32 but not of 256: only the Q8_0 kernel serves ffn_down_shexp - assert_eq!( - plan_s_gemv_q8k_split(640, 2560, &f), - Err(Error::NInNotBlockMultiple { who: "s_gemv_q8k_split", n_in: 640, block: 256 }) - ); - let p0 = plan_s_gemv_q8_0_split(640, 2560, &f).unwrap().unwrap(); - assert_eq!(p0.kernel, Kernel::SGemvQ80Split(4)); - assert_eq!(p0.launch.grid, [320, 1, 1]); - assert_eq!( - plan_s_gemv_q8_0_split(100, 8, &f), - Err(Error::NInNotBlockMultiple { who: "s_gemv_q8_0_split", n_in: 100, block: 32 }) - ); - let g8 = SForm { group_elems: 8, ..f }; - assert_eq!( - plan_s_gemv_q8_0_split(640, 8, &g8), - Err(Error::GroupNotMultiple { who: "s_gemv_q8_0_split", group: 8, multiple: 16 }) - ); + assert_q8k_plans(&f); + assert_q8_0_plans(&f); let s2 = SForm { code_bits: 2, ..f }; assert!(matches!(plan_s_gemv_q8k(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. }))); assert!(matches!(plan_s_gemv_q8k_split(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. }))); diff --git a/crates/cuda-driver/src/tests.rs b/crates/cuda-driver/src/tests.rs index 865154b0..617823e3 100644 --- a/crates/cuda-driver/src/tests.rs +++ b/crates/cuda-driver/src/tests.rs @@ -1,5 +1,45 @@ //! Moved out of the parent file by STRA-338 (same module path as before). +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +fn readback_source(size: usize, round: u32) -> Vec { + let words = [0u32, 0x8000_0000, 0x3f80_0000, 0xbf80_0000, 0x7f80_0000, 0xff80_0000, 0x7fc0_0101, 1]; + let mut source = Vec::with_capacity(size); + for i in 0..size / 4 { + let word = if i < words.len() { words[i] } else { (i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round) }; + source.extend_from_slice(&word.to_le_bytes()); + } + source +} + +/// One original-first round on a buffer of `size` bytes; returns (exact bytes read back, bounds refusals). +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +fn readback_round(buffer: &mut super::DeviceBuffer<'_>, size: usize, round: u32) -> (usize, usize) { + let (mut exact_bytes, mut bounds) = (0usize, 0usize); + let source = readback_source(size, round); + buffer.copy_from(&source).unwrap(); + let mut original = vec![0; size]; + buffer.copy_to(&mut original).unwrap(); + assert_eq!(original, source); + let owned = buffer.copy_to_owned(size).unwrap(); + assert_eq!(owned, original); + // The downstream original LE conversion preserves all bits, + // including signed zero and nonfinite values (later rejected + // by the unchanged GDN finite guard). + for (a, b) in original.as_chunks::<4>().0.iter().zip(owned.as_chunks::<4>().0) { + assert_eq!(f32::from_le_bytes(*a).to_bits(), f32::from_le_bytes(*b).to_bits()); + } + exact_bytes += size; + for invalid in [0, size - 1, size + 1] { + assert!(matches!(buffer.copy_to_owned(invalid), + Err(super::Error::ShapeMismatch { expected, actual }) + if expected == size && actual == invalid)); + bounds += 1; + } + assert_eq!(buffer.copy_to_owned(size).unwrap(), original); + exact_bytes += size; + (exact_bytes, bounds) +} + #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[test] #[ignore = "Root-only original-first owned whole-buffer readback proof"] @@ -12,34 +52,9 @@ fn owned_readback_original_first_preserves_gdn_extents_and_raw_words() { for size in [3_145_728usize, 122_880, 24_576] { let mut buffer = context.allocate(size).unwrap(); for round in 0..2u32 { - let words = [0u32, 0x8000_0000, 0x3f80_0000, 0xbf80_0000, 0x7f80_0000, 0xff80_0000, 0x7fc0_0101, 1]; - let mut source = Vec::with_capacity(size); - for i in 0..size / 4 { - let word = - if i < words.len() { words[i] } else { (i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round) }; - source.extend_from_slice(&word.to_le_bytes()); - } - buffer.copy_from(&source).unwrap(); - let mut original = vec![0; size]; - buffer.copy_to(&mut original).unwrap(); - assert_eq!(original, source); - let owned = buffer.copy_to_owned(size).unwrap(); - assert_eq!(owned, original); - // The downstream original LE conversion preserves all bits, - // including signed zero and nonfinite values (later rejected - // by the unchanged GDN finite guard). - for (a, b) in original.as_chunks::<4>().0.iter().zip(owned.as_chunks::<4>().0) { - assert_eq!(f32::from_le_bytes(*a).to_bits(), f32::from_le_bytes(*b).to_bits()); - } - exact_bytes += size; - for invalid in [0, size - 1, size + 1] { - assert!(matches!(buffer.copy_to_owned(invalid), - Err(super::Error::ShapeMismatch { expected, actual }) - if expected == size && actual == invalid)); - bounds += 1; - } - assert_eq!(buffer.copy_to_owned(size).unwrap(), original); - exact_bytes += size; + let (exact, refused) = readback_round(&mut buffer, size, round); + exact_bytes += exact; + bounds += refused; } buffer.release().unwrap(); assert_eq!(context.allocated_bytes(), 0); @@ -49,7 +64,8 @@ fn owned_readback_original_first_preserves_gdn_extents_and_raw_words() { assert_eq!(context.allocated_bytes(), 0); context.close().unwrap(); println!( - "owned_gdn_readback exact_bytes={exact_bytes} bounds={bounds} original_first=true allocated=0 raw_nonfinite_preserved=true" + "owned_gdn_readback exact_bytes={exact_bytes} bounds={bounds} original_first=true allocated=0 \ + raw_nonfinite_preserved=true" ); } @@ -144,11 +160,9 @@ fn matvec_allocation_identity_and_absent_handles() { assert!(matvec_allocations(h(4), h(4), h(12), &shape).is_ok()); } #[cfg(not(feature = "cuda-driver"))] -#[test] -fn matvec_private_admission_refuses_without_cuda() { - let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; - let context = Context { - driver: &driver, +fn bare_context(driver: &Driver) -> Context<'_> { + Context { + driver, handle: None, ordinal: 0, budget: 64, @@ -175,7 +189,13 @@ fn matvec_private_admission_refuses_without_cuda() { experimental: std::array::from_fn(|_| Cell::new(None)), window_modules: RefCell::new(Vec::new()), deferred_frees: RefCell::new(Vec::new()), - }; + } +} +#[cfg(not(feature = "cuda-driver"))] +#[test] +fn matvec_private_admission_refuses_without_cuda() { + let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; + let context = bare_context(&driver); let make = |handle| DeviceBuffer { context: &context, handle, bytes: 4, _thread: PhantomData, borrowed: false }; let matrix = make(Some(ffi::BufferHandle::synthetic(4))); let vector = make(Some(ffi::BufferHandle::synthetic(8))); diff --git a/crates/cuda-driver/src/vram_ledger.rs b/crates/cuda-driver/src/vram_ledger.rs index fd30d089..ceb3bf29 100644 --- a/crates/cuda-driver/src/vram_ledger.rs +++ b/crates/cuda-driver/src/vram_ledger.rs @@ -1,12 +1,12 @@ //! Per-call-site ledger of the device allocations made through `Context::allocate`, for the VRAM footprint audit. //! //! `LELEKA_VRAM_LEDGER=1` turns it on (default off: the hot path then costs one cached `bool` read). Every allocation -//! records its call site (the innermost `leleka_*` frames of a captured backtrace); every free removes it. `report(label)` -//! prints the live bytes per site that appeared or grew since the previous report, so a report after each opening stage -//! is the stage's own account. Beside the requested bytes it prints the bytes the driver is estimated to reserve: -//! on the WDDM laptop probe (`scripts/dev/alloc-granularity-probe.py`) an allocation above 1 MiB is rounded up to a -//! multiple of 2 MiB (3 MiB takes 4 MiB, 2.5 MiB takes 4 MiB) while smaller ones are packed; the 5090 load ledger -//! agrees (the 322.1 MiB token table takes 324 MiB). The estimate is the "granularity waste" column. +//! records its call site (the innermost `leleka_*` frames of a captured backtrace); every free removes it. +//! `report(label)` prints the live bytes per site that appeared or grew since the previous report, so a report after +//! each opening stage is the stage's own account. Beside the requested bytes it prints the bytes the driver is +//! estimated to reserve: on the WDDM laptop probe (`scripts/dev/alloc-granularity-probe.py`) an allocation above 1 MiB +//! is rounded up to a multiple of 2 MiB (3 MiB takes 4 MiB, 2.5 MiB takes 4 MiB) while smaller ones are packed; the +//! 5090 load ledger agrees (the 322.1 MiB token table takes 324 MiB). The estimate is the "granularity waste" column. use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; @@ -273,16 +273,23 @@ mod tests { #[test] fn the_site_key_is_the_innermost_workspace_frames_past_the_allocator() { - let trace = " 0: leleka_cuda_driver::vram_ledger::note_alloc::h0123456789abcdef\n\ - \x20 at ./crates/cuda-driver/src/vram_ledger.rs:1\n\ - \x20 1: leleka_cuda_driver::Context::allocate::hfedcba9876543210\n\ - \x20 2: leleka_runtime::qwen_forward::dense_weight_cache::DenseWeightCache::add::h0011223344556677\n\ - \x20 3: leleka_runtime::qwen_forward::dense_weight_cache::DenseWeightCache::new_with_selected::{{closure}}::h8899aabbccddeeff\n\ - \x20 4: core::ops::function::FnOnce::call_once::h0000000000000000\n\ - \x20 5: leleka_runtime::qwen_forward::original_serve_stack::OriginalServeStack::open::h1111111111111111\n"; + let trace = concat!( + " 0: leleka_cuda_driver::vram_ledger::note_alloc::h0123456789abcdef\n", + " at ./crates/cuda-driver/src/vram_ledger.rs:1\n", + " 1: leleka_cuda_driver::Context::allocate::hfedcba9876543210\n", + " 2: leleka_runtime::qwen_forward::dense_weight_cache::DenseWeightCache::add::h0011223344556677\n", + " 3: leleka_runtime::qwen_forward::dense_weight_cache::DenseWeightCache::new_with_selected::", + "{{closure}}::h8899aabbccddeeff\n", + " 4: core::ops::function::FnOnce::call_once::h0000000000000000\n", + " 5: leleka_runtime::qwen_forward::original_serve_stack::OriginalServeStack::open::h1111111111111111\n", + ); assert_eq!( site_key(trace), - "rt::dense_weight_cache::DenseWeightCache::add < rt::dense_weight_cache::DenseWeightCache::new_with_selected::{{closure}} < rt::original_serve_stack::OriginalServeStack::open" + concat!( + "rt::dense_weight_cache::DenseWeightCache::add < ", + "rt::dense_weight_cache::DenseWeightCache::new_with_selected::{{closure}} < ", + "rt::original_serve_stack::OriginalServeStack::open" + ) ); assert_eq!(site_key("nothing useful"), "unknown"); } diff --git a/crates/cuda-driver/tests/full_matrix_transport_gpu.rs b/crates/cuda-driver/tests/full_matrix_transport_gpu.rs index 17b8857a..139e2794 100644 --- a/crates/cuda-driver/tests/full_matrix_transport_gpu.rs +++ b/crates/cuda-driver/tests/full_matrix_transport_gpu.rs @@ -35,72 +35,96 @@ fn project( } .unwrap(); } -fn compare(c: &Context<'_>, format: Format, name: &str, rows: usize, columns: usize, zero: bool) { - let (elements, block_bytes) = match format { +fn format_geometry(format: Format) -> (usize, usize) { + match format { Format::Common(_, e, b) => (e, b), Format::Q5 => (256, 176), Format::Q6 => (256, 210), Format::Bf16 => (1, 2), - }; - let stride = columns / elements * block_bytes; - let mut encoded = vec![0; rows * stride]; - for (row, bytes) in encoded.chunks_exact_mut(stride).enumerate() { - for (block, bytes) in bytes.chunks_exact_mut(block_bytes).enumerate() { - for (i, byte) in bytes.iter_mut().enumerate() { - *byte = ((row * 17 + block * 29 + i * 37 + 11) % 256) as u8; - } - match format { - Format::Bf16 => { - let value = ((row + block * 3) % 17) as f32 / 16. - 0.5; - bytes.copy_from_slice(&((value.to_bits() >> 16) as u16).to_le_bytes()); - } - Format::Q6 => bytes[208..210].copy_from_slice(&0x3c00u16.to_le_bytes()), - _ => { - bytes[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - if matches!(format, Format::Q5 | Format::Common(K::Dense(D::Q4_K), _, _)) { - bytes[2..4].copy_from_slice(&0x3800u16.to_le_bytes()); - } - } + } +} +fn fill_block(format: Format, (row, block): (usize, usize), bytes: &mut [u8]) { + for (i, byte) in bytes.iter_mut().enumerate() { + *byte = ((row * 17 + block * 29 + i * 37 + 11) % 256) as u8; + } + match format { + Format::Bf16 => { + let value = ((row + block * 3) % 17) as f32 / 16. - 0.5; + bytes.copy_from_slice(&((value.to_bits() >> 16) as u16).to_le_bytes()); + } + Format::Q6 => bytes[208..210].copy_from_slice(&0x3c00u16.to_le_bytes()), + _ => { + bytes[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + if matches!(format, Format::Q5 | Format::Common(K::Dense(D::Q4_K), _, _)) { + bytes[2..4].copy_from_slice(&0x3800u16.to_le_bytes()); } } } - let activation: Vec = (0..columns) +} +fn encode_matrix(format: Format, rows: usize, stride: usize, block_bytes: usize) -> Vec { + let mut encoded = vec![0; rows * stride]; + for (row, bytes) in encoded.chunks_exact_mut(stride).enumerate() { + for (block, bytes) in bytes.chunks_exact_mut(block_bytes).enumerate() { + fill_block(format, (row, block), bytes); + } + } + encoded +} +fn activation_bytes(columns: usize, zero: bool) -> Vec { + (0..columns) .flat_map(|i| { let value = if zero { if i.is_multiple_of(2) { -0.0f32 } else { 0.0 } } else { ((i % 31) as f32 - 15.) / 8. }; value.to_le_bytes() }) - .collect(); - let x = upload(c, &activation); - let whole = upload(c, &encoded); - let mut output = upload(c, &vec![0xa5; rows * 4]); - project(c, format, &whole, &x, &mut output, rows, columns); - let mut actual = vec![0; rows * 4]; - output.copy_to(&mut actual).unwrap(); - let mut legacy = Vec::with_capacity(actual.len()); + .collect() +} +/// The previously admitted path: the same matrix projected in tiles of at most 64 rows. +fn legacy_tiles(c: &Context<'_>, format: Format, x: &DeviceBuffer<'_>, matrix: (&[u8], usize, usize)) -> Vec { + let (encoded, rows, columns) = matrix; + let stride = encoded.len() / rows; + let mut legacy = Vec::with_capacity(rows * 4); for first in (0..rows).step_by(64) { let count = (rows - first).min(64); let tile = upload(c, &encoded[first * stride..(first + count) * stride]); let mut tile_output = upload(c, &vec![0x5a; count * 4]); - project(c, format, &tile, &x, &mut tile_output, count, columns); + project(c, format, &tile, x, &mut tile_output, count, columns); let mut bytes = vec![0; count * 4]; tile_output.copy_to(&mut bytes).unwrap(); legacy.extend_from_slice(&bytes); tile_output.release().unwrap(); tile.release().unwrap(); } + legacy +} +fn assert_words_match(actual: &[u8], legacy: &[u8], name: &str, zero: bool) { for (i, (a, b)) in actual.as_chunks::<4>().0.iter().zip(legacy.as_chunks::<4>().0.iter()).enumerate() { let a = u32::from_le_bytes(*a); let b = u32::from_le_bytes(*b); assert!(f32::from_bits(a).is_finite(), "{name} row{i} nonfinite"); assert_eq!(a, b, "{name} row{i} zero={zero}"); } - let mut preserved = vec![0; encoded.len()]; - whole.copy_to(&mut preserved).unwrap(); - assert_eq!(preserved, encoded); - let mut preserved = vec![0; activation.len()]; - x.copy_to(&mut preserved).unwrap(); - assert_eq!(preserved, activation); +} +fn assert_preserved(buffer: &DeviceBuffer<'_>, expected: &[u8]) { + let mut preserved = vec![0; expected.len()]; + buffer.copy_to(&mut preserved).unwrap(); + assert_eq!(preserved, expected); +} +fn compare(c: &Context<'_>, format: Format, name: &str, (rows, columns): (usize, usize), zero: bool) { + let (elements, block_bytes) = format_geometry(format); + let stride = columns / elements * block_bytes; + let encoded = encode_matrix(format, rows, stride, block_bytes); + let activation = activation_bytes(columns, zero); + let x = upload(c, &activation); + let whole = upload(c, &encoded); + let mut output = upload(c, &vec![0xa5; rows * 4]); + project(c, format, &whole, &x, &mut output, rows, columns); + let mut actual = vec![0; rows * 4]; + output.copy_to(&mut actual).unwrap(); + let legacy = legacy_tiles(c, format, &x, (&encoded, rows, columns)); + assert_words_match(&actual, &legacy, name, zero); + assert_preserved(&whole, &encoded); + assert_preserved(&x, &activation); output.release().unwrap(); whole.release().unwrap(); x.release().unwrap(); @@ -133,7 +157,7 @@ fn complete_selected_matrices_match_legacy_64_row_bits() { ("dense-bf16-gdn-z", Format::Bf16, 6144, 2560), ]; for (name, format, rows, columns) in cases { - compare(&context, format, name, rows, columns, false); - compare(&context, format, name, rows, columns, true); + compare(&context, format, name, (rows, columns), false); + compare(&context, format, name, (rows, columns), true); } } diff --git a/crates/cuda-driver/tests/mock_driver/bootstrap_copies_fn.rs b/crates/cuda-driver/tests/mock_driver/bootstrap_copies_fn.rs index be327967..08530189 100644 --- a/crates/cuda-driver/tests/mock_driver/bootstrap_copies_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/bootstrap_copies_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn bootstrap_copies, fn bootstrap_copy_errors, fn bootstrap_htod_fault, fn bootstrap_dtoh_fault, fn bootstrap_release, fn bootstrap_close .... +//! Moved out of the parent module by STRA-338: fn bootstrap_copies, fn bootstrap_copy_errors, fn bootstrap_htod_fault, +//! fn bootstrap_dtoh_fault, fn bootstrap_release, fn bootstrap_close .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/tests/mock_driver/check_matvec_lengths_fn.rs b/crates/cuda-driver/tests/mock_driver/check_matvec_lengths_fn.rs index 3dc6317e..af1f935b 100644 --- a/crates/cuda-driver/tests/mock_driver/check_matvec_lengths_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/check_matvec_lengths_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn check_matvec_lengths, fn check_matvec_bad_length, fn check_matvec_error, fn matvec_poison_refusals, fn release_poisoned_fixture, fn check_poison_trace .... +//! Moved out of the parent module by STRA-338: fn check_matvec_lengths, fn check_matvec_bad_length, fn +//! check_matvec_error, fn matvec_poison_refusals, fn release_poisoned_fixture, fn check_poison_trace .... #[allow(unused_imports)] use super::*; @@ -110,9 +111,8 @@ pub(super) fn matvec_second_context(device: &leleka_cuda_driver::Device<'_>, f: drop((x, y, z)); second.close().unwrap(); } -pub(super) fn check_matvec_close(case: &str, closed: leleka_cuda_driver::Result<()>) { - use leleka_cuda_driver::Error; - let operation = if case.contains("unload") && case != "matvec_lookup_unload" { +fn matvec_close_failing_operation(case: &str) -> Option<&'static str> { + if case.contains("unload") && case != "matvec_lookup_unload" { Some("cuModuleUnload") } else if case.contains("pop") && !case.contains("wrong") { Some("cuCtxPopCurrent_v2") @@ -122,7 +122,11 @@ pub(super) fn check_matvec_close(case: &str, closed: leleka_cuda_driver::Result< Some("cuCtxDestroy_v2") } else { None - }; + } +} +pub(super) fn check_matvec_close(case: &str, closed: leleka_cuda_driver::Result<()>) { + use leleka_cuda_driver::Error; + let operation = matvec_close_failing_operation(case); if case.contains("wrong_pop") { assert_eq!(closed, Err(Error::UnexpectedContext)); } else if let Some(operation) = operation { diff --git a/crates/cuda-driver/tests/mock_driver/matvec_launch_count_fn.rs b/crates/cuda-driver/tests/mock_driver/matvec_launch_count_fn.rs index a4175310..732a6517 100644 --- a/crates/cuda-driver/tests/mock_driver/matvec_launch_count_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/matvec_launch_count_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn matvec_launch_count, fn check_matvec_geometry, fn check_matvec_both_cleanup, fn check_launch_sync. +//! Moved out of the parent module by STRA-338: fn matvec_launch_count, fn check_matvec_geometry, fn +//! check_matvec_both_cleanup, fn check_launch_sync. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/tests/mock_driver/row_types.rs b/crates/cuda-driver/tests/mock_driver/row_types.rs index ed27cfff..b537b504 100644 --- a/crates/cuda-driver/tests/mock_driver/row_types.rs +++ b/crates/cuda-driver/tests/mock_driver/row_types.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: Row, SCENARIOS, SCENARIO_FAILURES, WRONG_POP, COPY_POISON, VECTOR_EXECUTION_FAILURES .... +//! Moved out of the parent module by STRA-338: Row, SCENARIOS, SCENARIO_FAILURES, WRONG_POP, COPY_POISON, +//! VECTOR_EXECUTION_FAILURES .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/tests/mock_driver/trace_fn.rs b/crates/cuda-driver/tests/mock_driver/trace_fn.rs index c998d31b..7b735f73 100644 --- a/crates/cuda-driver/tests/mock_driver/trace_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/trace_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn trace, fn valid_context_trace, fn cuda_errors, fn run_fixture_case, fn scenario_command, fn scenario_failure .... +//! Moved out of the parent module by STRA-338: fn trace, fn valid_context_trace, fn cuda_errors, fn run_fixture_case, +//! fn scenario_command, fn scenario_failure .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs b/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs index 658b51eb..e33fbf87 100644 --- a/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn vector_bounds, fn vector_error, fn vector_poison_refusals, fn vector_expected, fn vector_success, fn vector_second_context .... +//! Moved out of the parent module by STRA-338: fn vector_bounds, fn vector_error, fn vector_poison_refusals, fn +//! vector_expected, fn vector_success, fn vector_second_context .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/tests/mock_driver/vector_module_context_trace_fn.rs b/crates/cuda-driver/tests/mock_driver/vector_module_context_trace_fn.rs index cec2c2ff..fa914c36 100644 --- a/crates/cuda-driver/tests/mock_driver/vector_module_context_trace_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/vector_module_context_trace_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn vector_module_context_trace, fn f32_bytes, fn rounded_product, fn rounded_add, fn matvec_oracle, fn check_f32_output .... +//! Moved out of the parent module by STRA-338: fn vector_module_context_trace, fn f32_bytes, fn rounded_product, fn +//! rounded_add, fn matvec_oracle, fn check_f32_output .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe.rs b/crates/cuda-driver/tests/original_serve_preflight_probe.rs index 8222b835..28fd1ba0 100644 --- a/crates/cuda-driver/tests/original_serve_preflight_probe.rs +++ b/crates/cuda-driver/tests/original_serve_preflight_probe.rs @@ -13,7 +13,8 @@ //! PROBE_BUDGET_GIB context budget in GiB (default 6) //! PROBE_CAPACITY prompt chunk capacity of the prefill arena (default 1024) //! PROBE_VERIFY_MAX_T verifier window width (`settings.max_t` = SPEC+2) (default 6) -//! PROBE_MTP_MAX_T MTP `max_t` = `settings.mtp_load_t()` = verify width (default 6; 4 reproduces the T=6 draft failure) +//! PROBE_MTP_MAX_T MTP `max_t` = `settings.mtp_load_t()` = verify width (default 6) +//! (4 reproduces the T=6 draft failure) //! PROBE_MAX_T max_t of the lazy-constructor sweep (default 8) //! PROBE_CELLS serving cell count `max_cells` (default 262144, the trained context) //! PROBE_GU_MAX/DOWN_MAX/MAX_BLOB per-expert byte sizes the arena is carved from diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe/env_usize_fn.rs b/crates/cuda-driver/tests/original_serve_preflight_probe/env_usize_fn.rs index dce65f62..700f1249 100644 --- a/crates/cuda-driver/tests/original_serve_preflight_probe/env_usize_fn.rs +++ b/crates/cuda-driver/tests/original_serve_preflight_probe/env_usize_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn env_usize, fn budget, fn geometry, fn layout_options, fn embed_row_bytes, fn synthetic_mtp .... +//! Moved out of the parent module by STRA-338: fn env_usize, fn budget, fn geometry, fn layout_options, fn +//! embed_row_bytes, fn synthetic_mtp .... #[allow(unused_imports)] use super::*; @@ -61,26 +62,245 @@ pub(super) fn layout_options(capacity: usize, max_cells: usize) -> PrefillLayout } } +//// `(ggml kind, bytes per 10 blocks)` of the embedding kinds `OriginalMtpEmbedding::native` admits +/// (`row_bytes == 10 * per`). +const EMBED_BYTES_PER_TEN_BLOCKS: [(i32, usize); 15] = [ + (16, 66), + (17, 74), + (18, 98), + (20, 144), + (21, 110), + (22, 82), + (23, 136), + (29, 56), + (11, 110), + (12, 144), + (13, 176), + (7, 192), + (8, 272), + (42, 72), + (30, 512), +]; + /// bytes per 10 blocks of the embedding kinds `OriginalMtpEmbedding::native` admits (`row_bytes == 10 * per`). pub(super) fn embed_row_bytes(kind: i32) -> usize { - 10 * match kind { - 16 => 66, - 17 => 74, - 18 => 98, - 20 => 144, - 21 => 110, - 22 => 82, - 23 => 136, - 29 => 56, - 11 => 110, - 12 => 144, - 13 => 176, - 7 => 192, - 8 => 272, - 42 => 72, - 30 => 512, - _ => 110, + 10 * EMBED_BYTES_PER_TEN_BLOCKS.iter().find(|(k, _)| *k == kind).map_or(110, |(_, per)| *per) +} + +/// The drafter ring and its actor. +type SyntheticMtp<'ctx> = (MtpOriginalInt8<'ctx>, OriginalMtpActor<'ctx>); + +/// Scalar prefix bank extents: 11 roles. +const SCALAR_EXTENTS: [usize; 11] = [ + 10240, + 2560 * 80 * 34, + 40960, + 2560 * 80 * 34, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, + 512 * 80 * 34, + 512 * 80 * 34, + 1024, + 4 * 10240 * 2, +]; + +/// Full-forward bank extents: 15 roles. +const FULL_EXTENTS: [usize; 15] = [ + 12288 * 80 * 34, + 1024, + 2560 * 192 * 34, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, + 4 * 10240 * 2, + 512 * 2560 * 2, + 640 * 80 * 34, + 640 * 80 * 34, + 2560 * 20 * 34, + 5120, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, +]; + +/// The shape knobs of one synthetic MTP assembly. +struct MtpShape { + max_t: usize, + capacity: usize, + vocab: usize, + coupled: bool, +} + +fn alloc_rc<'ctx>( + context: &'ctx Context<'ctx>, + bytes: usize, +) -> leleka_cuda_driver::Result>> { + context.allocate(bytes).map(std::rc::Rc::new) +} + +fn alloc_roles<'ctx>( + context: &'ctx Context<'ctx>, + extents: &[usize], + label: &str, +) -> Option>>> { + let mut roles = Vec::new(); + for &n in extents { + roles.push(step!(format!("synthetic {label} role alloc {n}"), alloc_rc(context, n))?); } + Some(roles) +} + +/// The scalar prefix bank: 11 roles plus the whole embedding table. +fn scalar_prefix<'ctx>( + context: &'ctx Context<'ctx>, + vocab: usize, +) -> Option>> { + use std::rc::Rc; + let embed_kind = env_usize("PROBE_EMBED_KIND", 21) as i32; + let roles = alloc_roles(context, &SCALAR_EXTENTS, "scalar")?; + let row_bytes = embed_row_bytes(embed_kind); + let table = step!("synthetic embedding alloc", alloc_rc(context, row_bytes * vocab))?; + let descriptor = + step!("OriginalMtpEmbedding::native", OriginalMtpEmbedding::native(&table, embed_kind, row_bytes, vocab))?; + let scalar_roles: [Rc; 11] = roles.try_into().ok().expect("11 roles"); + let scalar = step!( + "OriginalMtpRetainedScalarWeights::retain", + OriginalMtpRetainedScalarWeights::retain(context, scalar_roles, Rc::clone(&table), &descriptor) + )?; + step!( + "OriginalMtpRetainedPrefix::from_scalar", + OriginalMtpRetainedPrefix::from_scalar(Rc::new(scalar)).map(Rc::new) + ) +} + +/// The buffers of the full-forward bank. +struct FullBank<'ctx> { + roles: [std::rc::Rc>; 15], + experts: std::rc::Rc>, + head: std::rc::Rc>, +} + +/// The full-forward bank: 15 roles, the experts and the native head (lent, or allocated here). +fn full_bank<'ctx>( + context: &'ctx Context<'ctx>, + head: Option>>, + head_kind: u32, + vocab: usize, +) -> Option> { + let roles = alloc_roles(context, &FULL_EXTENTS, "full")?; + let roles: [std::rc::Rc; 15] = roles.try_into().ok().expect("15 roles"); + let experts = step!("synthetic experts alloc", alloc_rc(context, 512 * 1_382_400))?; + let head_row = step!(format!("native_head_row_bytes({head_kind})"), native_head_row_bytes(head_kind, 2560))?; + let head = match head { + Some(head) => head, + None => step!("synthetic head alloc", alloc_rc(context, head_row * vocab))?, + }; + eprintln!("PREFLIGHT synthetic mtp banks allocated={}MiB", context.allocated_bytes() >> 20); + Some(FullBank { roles, experts, head }) +} + +fn retain_full_weights<'ctx>( + context: &'ctx Context<'ctx>, + prefix: std::rc::Rc>, + bank: FullBank<'ctx>, + head_kind: u32, + vocab: usize, +) -> Option>> { + step!( + "OriginalMtpRetainedFullWeights::retain", + OriginalMtpRetainedFullWeights::retain( + context, + prefix, + bank.roles, + bank.experts, + bank.head, + head_kind, + vocab, + vocab, + None, + NativeHeadDispatch::default() + ) + .map(std::rc::Rc::new) + ) +} + +/// The load plan and its coupled-layout flag, exactly as `OriginalMtpFullOwner::assemble` builds them. +fn load_plan(context: &Context<'_>, shape: &MtpShape) -> Option<(OriginalMtpLoadPlan, bool)> { + let capture = OriginalMtpCapture { + device: context.device_ordinal(), + n_expert: 512, + top_k: 10, + max_cells: env_usize("PROBE_CELLS", 262_144) as u64, + max_t: shape.max_t as u64, + window: MTP_ORIGINAL_WINDOW as i64, + vocabulary: shape.vocab as u64, + kv: OriginalMtpKvStartup::ring_int8(20_480), + coupled_requested: shape.coupled, + }; + let plan = + step!("OriginalMtpLoadPlan::new", OriginalMtpLoadPlan::new(capture, 116_099_072).map_err(|e| e.message()))?; + let layout_coupled = step!("plan.coupled_layout(None)", plan.coupled_layout(None).map_err(|e| e.message()))?; + Some((plan, layout_coupled)) +} + +/// The load meter and the shared MTP layout (ring, scalar prefill, full forward) over the retained weights. +struct Opened<'ctx> { + meter: OriginalMtpLoadMeter, + ring: MtpOriginalInt8<'ctx>, + scalar_prefill: OriginalMtpScalarPrefill<'ctx>, + full: OriginalMtpFullForward<'ctx>, +} + +fn open_layout<'ctx>( + context: &'ctx Context<'ctx>, + weights: &std::rc::Rc>, + layout_coupled: bool, + shape: &MtpShape, +) -> Option> { + let meter = OriginalMtpLoadMeter::start(context); + let (ring, scalar_prefill, full) = step!( + "original_mtp_shared_layout_with_ring", + context.original_mtp_shared_layout_with_ring( + std::rc::Rc::clone(weights), + shape.max_t, + shape.capacity, + layout_coupled + ) + )?; + eprintln!("PREFLIGHT mtp shared layout allocated={}MiB", context.allocated_bytes() >> 20); + Some(Opened { meter, ring, scalar_prefill, full }) +} + +fn adopt_actor<'ctx>( + context: &'ctx Context<'ctx>, + plan: OriginalMtpLoadPlan, + opened: Opened<'ctx>, + weights: std::rc::Rc>, +) -> Option> { + let Opened { meter, ring, scalar_prefill, full } = opened; + let Some(drafter) = step!("OriginalMtpDrafter::new(full, scalar)", OriginalMtpDrafter::new(full, scalar_prefill)) + else { + let _ = ring.close(); + return None; + }; + let Some(evidence) = step!("meter.finish", meter.finish(context, None, 0).map_err(|e| e.message().to_owned())) + else { + let _ = drafter.close(); + let _ = ring.close(); + return None; + }; + let actor = step!( + "OriginalMtpActor::adopt", + OriginalMtpActor::adopt(context, plan, drafter, &ring, std::rc::Rc::clone(&weights), evidence) + .map_err(|e| e.message().to_owned()) + ); + let Some(actor) = actor else { + let _ = ring.close(); + return None; + }; + eprintln!("PREFLIGHT actor vram={}MiB device={}", actor.vram_bytes() >> 20, actor.device()); + Some((ring, actor)) } /// `OriginalMtpFullOwner::assemble` over SYNTHETIC (uninitialised, correctly sized) weights: the retained @@ -96,134 +316,16 @@ pub(super) fn synthetic_mtp<'ctx>( mtp_max_t: usize, capacity: usize, coupled: bool, -) -> Option<(MtpOriginalInt8<'ctx>, OriginalMtpActor<'ctx>)> { - use std::rc::Rc; - let embed_kind = env_usize("PROBE_EMBED_KIND", 21) as i32; - let alloc = |bytes: usize| context.allocate(bytes); - let rc = |bytes: usize| alloc(bytes).map(Rc::new); - - // ---- scalar prefix bank (11 roles + the whole embedding table) - let extents = [ - 10240, - 2560 * 80 * 34, - 40960, - 2560 * 80 * 34, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - 512 * 80 * 34, - 512 * 80 * 34, - 1024, - 4 * 10240 * 2, - ]; - let mut roles = Vec::new(); - for &n in &extents { - roles.push(step!(format!("synthetic scalar role alloc {n}"), rc(n))?); - } - let row_bytes = embed_row_bytes(embed_kind); - let table = step!("synthetic embedding alloc", rc(row_bytes * vocab))?; - let descriptor = - step!("OriginalMtpEmbedding::native", OriginalMtpEmbedding::native(&table, embed_kind, row_bytes, vocab))?; - let scalar_roles: [Rc; 11] = roles.try_into().ok().expect("11 roles"); - let scalar = step!( - "OriginalMtpRetainedScalarWeights::retain", - OriginalMtpRetainedScalarWeights::retain(context, scalar_roles, Rc::clone(&table), &descriptor) - )?; - let prefix = step!( - "OriginalMtpRetainedPrefix::from_scalar", - OriginalMtpRetainedPrefix::from_scalar(Rc::new(scalar)).map(Rc::new) - )?; - +) -> Option> { + let prefix = scalar_prefix(context, vocab)?; // ---- full-forward bank - let full_extents: [usize; 15] = [ - 12288 * 80 * 34, - 1024, - 2560 * 192 * 34, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - 4 * 10240 * 2, - 512 * 2560 * 2, - 640 * 80 * 34, - 640 * 80 * 34, - 2560 * 20 * 34, - 5120, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - ]; - let mut full_roles = Vec::new(); - for &n in &full_extents { - full_roles.push(step!(format!("synthetic full role alloc {n}"), rc(n))?); - } - let full_roles: [Rc; 15] = full_roles.try_into().ok().expect("15 roles"); - let experts = step!("synthetic experts alloc", rc(512 * 1_382_400))?; - let head_row = step!(format!("native_head_row_bytes({head_kind})"), native_head_row_bytes(head_kind, 2560))?; - let head = match head { - Some(head) => head, - None => step!("synthetic head alloc", rc(head_row * vocab))?, - }; - eprintln!("PREFLIGHT synthetic mtp banks allocated={}MiB", context.allocated_bytes() >> 20); - let weights = step!( - "OriginalMtpRetainedFullWeights::retain", - OriginalMtpRetainedFullWeights::retain( - context, - prefix, - full_roles, - experts, - head, - head_kind, - vocab, - vocab, - None, - NativeHeadDispatch::default() - ) - .map(Rc::new) - )?; - + let bank = full_bank(context, head, head_kind, vocab)?; + let weights = retain_full_weights(context, prefix, bank, head_kind, vocab)?; // ---- plan + meter exactly as OriginalMtpFullOwner::assemble does - let capture = OriginalMtpCapture { - device: context.device_ordinal(), - n_expert: 512, - top_k: 10, - max_cells: env_usize("PROBE_CELLS", 262_144) as u64, - max_t: mtp_max_t as u64, - window: MTP_ORIGINAL_WINDOW as i64, - vocabulary: vocab as u64, - kv: OriginalMtpKvStartup::ring_int8(20_480), - coupled_requested: coupled, - }; - let plan = - step!("OriginalMtpLoadPlan::new", OriginalMtpLoadPlan::new(capture, 116_099_072).map_err(|e| e.message()))?; - let layout_coupled = step!("plan.coupled_layout(None)", plan.coupled_layout(None).map_err(|e| e.message()))?; - let meter = OriginalMtpLoadMeter::start(context); - let (ring, scalar_prefill, full) = step!( - "original_mtp_shared_layout_with_ring", - context.original_mtp_shared_layout_with_ring(Rc::clone(&weights), mtp_max_t, capacity, layout_coupled) - )?; - eprintln!("PREFLIGHT mtp shared layout allocated={}MiB", context.allocated_bytes() >> 20); - let Some(drafter) = step!("OriginalMtpDrafter::new(full, scalar)", OriginalMtpDrafter::new(full, scalar_prefill)) - else { - let _ = ring.close(); - return None; - }; - let Some(evidence) = step!("meter.finish", meter.finish(context, None, 0).map_err(|e| e.message().to_owned())) - else { - let _ = drafter.close(); - let _ = ring.close(); - return None; - }; - let actor = step!( - "OriginalMtpActor::adopt", - OriginalMtpActor::adopt(context, plan, drafter, &ring, Rc::clone(&weights), evidence) - .map_err(|e| e.message().to_owned()) - ); - let Some(actor) = actor else { - let _ = ring.close(); - return None; - }; - eprintln!("PREFLIGHT actor vram={}MiB device={}", actor.vram_bytes() >> 20, actor.device()); - Some((ring, actor)) + let shape = MtpShape { max_t: mtp_max_t, capacity, vocab, coupled }; + let (plan, layout_coupled) = load_plan(context, &shape)?; + let opened = open_layout(context, &weights, layout_coupled, &shape)?; + adopt_actor(context, plan, opened, weights) } pub(super) fn env_list(name: &str, default: &str) -> Vec { diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe/preflight_00_sealed_asset_report.rs b/crates/cuda-driver/tests/original_serve_preflight_probe/preflight_00_sealed_asset_report.rs index 8c62c959..65720ff0 100644 --- a/crates/cuda-driver/tests/original_serve_preflight_probe/preflight_00_sealed_asset_report.rs +++ b/crates/cuda-driver/tests/original_serve_preflight_probe/preflight_00_sealed_asset_report.rs @@ -1,4 +1,6 @@ -//! Tests of original_serve_preflight_probe by topic (moved out of the test file by STRA-338): preflight_00_sealed_asset_report, preflight_01_device_limits, preflight_10_lazy_constructors, preflight_20_prefill_arena .... +//! Tests of original_serve_preflight_probe by topic (moved out of the test file by STRA-338): +//! preflight_00_sealed_asset_report, preflight_01_device_limits, preflight_10_lazy_constructors, +//! preflight_20_prefill_arena .... #[allow(unused_imports)] use super::*; @@ -43,18 +45,18 @@ fn preflight_01_device_limits() { drop(bank); } -/// Every no-weight constructor that the first request builds lazily (after `open`), or `open` builds without weights. -#[test] -#[ignore = "GPU bring-up probe; no model"] -fn preflight_10_lazy_constructors() { - let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device 0"); - let context = device.create_context(budget()).expect("context"); - let capacity = env_usize("PROBE_CAPACITY", 1024); - let max_t = env_usize("PROBE_MAX_T", 8); - let vocab = env_usize("PROBE_VOCAB", 248_320); +//// The knobs of the lazy-constructor sweep. +#[derive(Clone, Copy)] +struct LazyKnobs { + capacity: usize, + max_t: usize, + vocab: usize, +} +// The constructors are built in three stages that call the next one as their last statement: every object a stage +// builds stays alive until the whole sweep ends and drops in reverse order of construction, as in one flat function. +fn lazy_stage_1(context: &Context<'_>, knobs: LazyKnobs) { + let vocab = knobs.vocab; let _a = step!("original_sampler(rows 8, vocab, history 4096)", context.original_sampler(8, vocab, 4096)); let _b = step!("original_gpu_stream(BlockingCapture)", context.original_gpu_stream(OriginalStreamKind::BlockingCapture)); @@ -67,6 +69,11 @@ fn preflight_10_lazy_constructors() { let _i = step!("gdn_row_queue", context.gdn_row_queue()); let _j = step!("routed_stage_finite_guard", context.routed_stage_finite_guard()); let _k = step!("routed_group_workspace", context.routed_group_workspace()); + lazy_stage_2(context, knobs); +} + +fn lazy_stage_2(context: &Context<'_>, knobs: LazyKnobs) { + let (capacity, max_t) = (knobs.capacity, knobs.max_t); let _l = step!("routed_resident_queue", context.routed_resident_queue()); let _m = step!("mtp_input_workspace", context.mtp_input_workspace()); let _n = step!("native_mmq_workspace", context.native_mmq_workspace()); @@ -82,6 +89,11 @@ fn preflight_10_lazy_constructors() { let _x = step!("qsa_prompt_stage", context.qsa_prompt_stage()); let _y = step!("original_moe_prompt_device(capacity)", context.original_moe_prompt_device(capacity)); let _z = step!("original_mmq_copy_schedule(32)", context.original_mmq_copy_schedule(32)); + lazy_stage_3(context, knobs); +} + +fn lazy_stage_3(context: &Context<'_>, knobs: LazyKnobs) { + let (capacity, vocab) = (knobs.capacity, knobs.vocab); let streams = vec![0.0f32; capacity * 10240]; let _a1 = step!( "gr_native_prompt_batch(capacity)", @@ -104,6 +116,21 @@ fn preflight_10_lazy_constructors() { let _a9 = step!("mtp_original_int8 vocabulary guard", Ok::<_, Error>(vocab)); } +/// Every no-weight constructor that the first request builds lazily (after `open`), or `open` builds without weights. +#[test] +#[ignore = "GPU bring-up probe; no model"] +fn preflight_10_lazy_constructors() { + let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device 0"); + let context = device.create_context(budget()).expect("context"); + let capacity = env_usize("PROBE_CAPACITY", 1024); + let max_t = env_usize("PROBE_MAX_T", 8); + let vocab = env_usize("PROBE_VOCAB", 248_320); + + lazy_stage_1(&context, LazyKnobs { capacity, max_t, vocab }); +} + /// `OriginalServeStack::open` -> `context.original_prefill_arena(layout)` (sized from the blob byte sizes). #[test] #[ignore = "GPU bring-up probe; no model"] @@ -117,7 +144,8 @@ fn preflight_20_prefill_arena() { let options = layout_options(capacity, cells); match options.carve() { Ok(layout) => eprintln!( - "PREFLIGHT arena layout borrowed={}MiB separately_owned={}MiB source_needed={}MiB shared_region={}MiB ring_slots={}", + "PREFLIGHT arena layout borrowed={}MiB separately_owned={}MiB source_needed={}MiB \ + shared_region={}MiB ring_slots={}", layout.borrowed_bytes >> 20, layout.separately_owned_bytes >> 20, layout.source_bytes_needed >> 20, @@ -159,6 +187,38 @@ fn preflight_30_synthetic_mtp_full_owner() { } } +//// One verifier run: projection kinds, shared-expert kinds and the routed expert formats. +type Run = (Vec, Vec, Vec); + +fn projection_sets() -> Vec> { + match std::env::var("PROBE_PROJ_SET") { + Ok(_) => vec![env_list("PROBE_PROJ_SET", "8,8,8,8,8,8,8")], + Err(_) => env_list("PROBE_PROJ_KINDS", "8").into_iter().map(|k| vec![k; 7]).collect(), + } +} + +/// Adds one run per `;`-separated list of `len` kinds in the environment variable `var`. +fn push_env_runs(runs: &mut Vec, var: &str, len: usize, make: impl Fn(Vec) -> Run) { + if let Ok(list) = std::env::var(var) { + for item in list.split(';') { + let kinds: Vec = item.split(',').filter_map(|x| x.trim().parse().ok()).collect(); + if kinds.len() == len { + runs.push(make(kinds)); + } + } + } +} + +/// One dimension varies at a time: projections, then expert formats, then shared-expert kinds. +fn probe_runs(shared: &[u32], fmt: &[u32]) -> Vec { + let sets = projection_sets(); + let mut runs: Vec = sets.into_iter().map(|p| (p, shared.to_vec(), fmt.to_vec())).collect(); + let base = runs.first().map(|r| r.0.clone()).unwrap_or_else(|| vec![8; 7]); + push_env_runs(&mut runs, "PROBE_EXPERT_FMTS", 2, |f| (base.clone(), shared.to_vec(), f)); + push_env_runs(&mut runs, "PROBE_SHARED_SETS", 3, |k| (base.clone(), k, fmt.to_vec())); + runs +} + /// Records the verifier window graphs over synthetic weights; one run per projection-kind set. /// `PROBE_PROJ_KINDS` is a list of ggml types applied to all seven projection matrices (default `8`, i.e. Q8_0); /// the seven kinds can also be given as `PROBE_PROJ_SET=qkv,gate,out,k,v,q,qout`. @@ -176,31 +236,7 @@ fn preflight_40_synthetic_verifier_record_all() { let embed_kind = env_usize("PROBE_EMBED_KIND", 21) as u32; let shared = env_list("PROBE_SHARED_KINDS", "8,8,8"); let fmt = env_list("PROBE_EXPERT_FMT", "21,20"); - let sets: Vec> = match std::env::var("PROBE_PROJ_SET") { - Ok(_) => vec![env_list("PROBE_PROJ_SET", "8,8,8,8,8,8,8")], - Err(_) => env_list("PROBE_PROJ_KINDS", "8").into_iter().map(|k| vec![k; 7]).collect(), - }; - // one dimension varies at a time: projections, then expert formats, then shared-expert kinds - let mut runs: Vec<(Vec, Vec, Vec)> = - sets.into_iter().map(|p| (p, shared.clone(), fmt.clone())).collect(); - let base = runs.first().map(|r| r.0.clone()).unwrap_or_else(|| vec![8; 7]); - if let Ok(list) = std::env::var("PROBE_EXPERT_FMTS") { - for pair in list.split(';') { - let f: Vec = pair.split(',').filter_map(|x| x.trim().parse().ok()).collect(); - if f.len() == 2 { - runs.push((base.clone(), shared.clone(), f)); - } - } - } - if let Ok(list) = std::env::var("PROBE_SHARED_SETS") { - for triple in list.split(';') { - let k: Vec = triple.split(',').filter_map(|x| x.trim().parse().ok()).collect(); - if k.len() == 3 { - runs.push((base.clone(), k, fmt.clone())); - } - } - } - for (set, shared, fmt) in runs { + for (set, shared, fmt) in probe_runs(&shared, &fmt) { eprintln!("PREFLIGHT ==== projection kinds {set:?} shared {shared:?} expert fmt {fmt:?}"); synthetic_verifier(&context, &set, &shared, (fmt[0], fmt[1]), max_t, cells, vocab, head_kind, embed_kind); eprintln!("PREFLIGHT context allocated={}MiB", context.allocated_bytes() >> 20); diff --git a/crates/native-cpu-expert/src/rust_weight_iq/alloc_fn.rs b/crates/native-cpu-expert/src/rust_weight_iq/alloc_fn.rs index 92957655..6f6b9ffc 100644 --- a/crates/native-cpu-expert/src/rust_weight_iq/alloc_fn.rs +++ b/crates/native-cpu-expert/src/rust_weight_iq/alloc_fn.rs @@ -3,9 +3,6 @@ #[allow(unused_imports)] use super::*; -mod scale_search; -pub(super) use scale_search::{Block, Trial, fix_groups, flip, search_scale, sum_sq, vmax, weights}; - pub(super) fn alloc(n: usize) -> Result> { let mut v = Vec::new(); v.try_reserve_exact(n).map_err(|_| Error::Allocation)?; @@ -15,29 +12,14 @@ pub(super) fn alloc(n: usize) -> Result> { impl Grid { pub(super) fn new(codes: &[u16], dim: usize, bits: usize, want: usize) -> Result { let size = if dim == 8 { 43692 } else { 4096 }; - let (points, mut map) = Self::index_points(codes, dim, bits, size)?; + let (points, mut map) = Self::index_codes(codes, dim, bits, size)?; let mut dist = alloc::<(i32, u16)>(codes.len())?; - let (counts, total) = Self::neighbor_counts(&points, &map, (dim, bits, want), &mut dist)?; - let mut neighbors = alloc::(total)?; - let mut at = 0; - for i in 0..size { - if map[i] >= 0 { - continue; - } - Self::distances(i, dim, bits, &points, &mut dist); - dist.sort_unstable(); - let n = counts[i]; - map[i] = -((at + 1) as i32); - neighbors[at] = n as u16; - for j in 0..n { - neighbors[at + 1 + j] = dist[j].1; - } - at += n + 1; - } + let (counts, total) = Self::count_neighbors(&map, &points, (dim, bits, want), &mut dist)?; + let neighbors = Self::index_neighbors(&mut map, &points, (dim, bits), (&counts, total), &mut dist)?; Ok(Self { points, map, neighbors, dim, bits }) } - /// The grid points of the codes, and the map from code to point index (-1 for codes that are not on the grid). - fn index_points(codes: &[u16], dim: usize, bits: usize, size: usize) -> Result<(Vec<[i8; 8]>, Vec)> { + /// The lattice points of the codes, and the table from a code to its point (or -1 when off the grid). + fn index_codes(codes: &[u16], dim: usize, bits: usize, size: usize) -> Result<(Vec<[i8; 8]>, Vec)> { let mut points = alloc::<[i8; 8]>(codes.len())?; let mut map = alloc::(size)?; map.fill(-1); @@ -49,29 +31,56 @@ impl Grid { } Ok((points, map)) } - /// How many nearest points each off-grid code keeps, and the length of the neighbor table; - /// `shape` is (dim, bits, want). - fn neighbor_counts( - points: &[[i8; 8]], + /// Fills `dist` with the grid points ordered by distance from lattice position `i`. + fn sort_by_distance(i: usize, dim: usize, bits: usize, points: &[[i8; 8]], dist: &mut [(i32, u16)]) { + Self::distances(i, dim, bits, points, dist); + dist.sort_unstable(); + } + /// The neighbour count of every off-grid position, and the length of the neighbour table. + fn count_neighbors( map: &[i32], - shape: (usize, usize, usize), + points: &[[i8; 8]], + (dim, bits, want): (usize, usize, usize), dist: &mut [(i32, u16)], ) -> Result<(Vec, usize)> { - let (dim, bits, want) = shape; let mut counts = alloc::(map.len())?; let mut total = 0usize; for i in 0..map.len() { if map[i] >= 0 { continue; } - Self::distances(i, dim, bits, points, dist); - dist.sort_unstable(); + Self::sort_by_distance(i, dim, bits, points, dist); let n = Self::count(dist, want); counts[i] = n; total = total.checked_add(n + 1).ok_or(Error::Allocation)?; } Ok((counts, total)) } + /// Builds the neighbour table and points every off-grid map entry at its slot as `-(slot + 1)`. + fn index_neighbors( + map: &mut [i32], + points: &[[i8; 8]], + (dim, bits): (usize, usize), + (counts, total): (&[usize], usize), + dist: &mut [(i32, u16)], + ) -> Result> { + let mut neighbors = alloc::(total)?; + let mut at = 0; + for i in 0..map.len() { + if map[i] >= 0 { + continue; + } + Self::sort_by_distance(i, dim, bits, points, dist); + let n = counts[i]; + map[i] = -((at + 1) as i32); + neighbors[at] = n as u16; + for j in 0..n { + neighbors[at + 1 + j] = dist[j].1; + } + at += n + 1; + } + Ok(neighbors) + } pub(super) fn distances(i: usize, dim: usize, bits: usize, p: &[[i8; 8]], dist: &mut [(i32, u16)]) { for (j, pg) in p.iter().enumerate() { let mut d = 0; @@ -108,26 +117,30 @@ impl Grid { let i = self.map[self.key(l)]; if i < 0 { Err(Error::NativeFailure) } else { Ok(i as usize) } } + /// The neighbour of the off-grid slot `at` with the smallest weighted error for `scale`. + fn best_neighbor(&self, at: usize, scale: f32, x: &[f32], w: &[f32]) -> usize { + let mut best = f32::MAX; + let mut index = usize::MAX; + for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] { + let p = &self.points[g as usize]; + let mut err = 0.0; + for i in 0..self.dim { + let d = scale * p[i] as f32 - x[i]; + err += w[i] * d * d; + } + if err < best { + best = err; + index = g as usize; + } + } + index + } pub(super) fn resolve(&self, l: &mut [i8], x: &[f32], w: &[f32], scale: f32) -> bool { let mapped = self.map[self.key(l)]; let index = if mapped >= 0 { mapped as usize } else { - let at = (-mapped - 1) as usize; - let mut best = f32::MAX; - let mut index = usize::MAX; - for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] { - let p = &self.points[g as usize]; - let mut err = 0.0; - for i in 0..self.dim { - let d = scale * p[i] as f32 - x[i]; - err += w[i] * d * d; - } - if err < best { - best = err; - index = g as usize; - } - } + let index = self.best_neighbor((-mapped - 1) as usize, scale, x, w); assert_ne!(index, usize::MAX); index }; @@ -181,37 +194,29 @@ pub(in super::super) fn free(k: Kind) -> Result<()> { pub(super) fn put_h(y: &mut [u8], d: f32) { y[..2].copy_from_slice(&half_rn(d).to_le_bytes()); } -pub(super) fn signs(xb: &[f32], w: &[f32], parity: bool) -> ([f32; N], [u8; 4]) { - let mut xv = [0.0; N]; - let mut signs = [0u8; 4]; - for k in 0..N / 8 { - let mut flips = 0; - let mut s = 0; - for j in 0..8 { - let at = k * 8 + j; - if xb[at] >= 0.0 { - xv[at] = xb[at]; - } else { - xv[at] = -xb[at]; - flips += 1; - s |= 1 << j; - } +/// The sign mask of the 8-element group starting at `base` (bit `j` set for a negative value), with the flip count; +/// `xv` receives the magnitudes. +fn fold_group(xb: &[f32], xv: &mut [f32; N], base: usize) -> (u8, usize) { + let mut flips = 0; + let mut s = 0u8; + for j in 0..8 { + let at = base + j; + if xb[at] >= 0.0 { + xv[at] = xb[at]; + } else { + xv[at] = -xb[at]; + flips += 1; + s |= 1 << j; } - if parity && flips % 2 == 1 { - let least = least_error(xb, w, k * 8); - xv[k * 8 + least] = -xv[k * 8 + least]; - s ^= 1 << least; - } - signs[k] = if parity { s & 127 } else { s }; } - (xv, signs) + (s, flips) } -/// The position (0..8) in the group at `first` with the smallest weighted square, first one winning ties. -fn least_error(xb: &[f32], w: &[f32], first: usize) -> usize { +/// The position in the group at `base` whose weighted energy is smallest (the first on ties). +fn least_energy_index(xb: &[f32], w: &[f32], base: usize) -> usize { let mut least = 0; - let mut error = w[first] * xb[first] * xb[first]; + let mut error = w[base] * xb[base] * xb[base]; for j in 1..8 { - let at = first + j; + let at = base + j; let e = w[at] * xb[at] * xb[at]; if e < error { least = j; @@ -220,6 +225,20 @@ fn least_error(xb: &[f32], w: &[f32], first: usize) -> usize { } least } +pub(super) fn signs(xb: &[f32], w: &[f32], parity: bool) -> ([f32; N], [u8; 4]) { + let mut xv = [0.0; N]; + let mut signs = [0u8; 4]; + for k in 0..N / 8 { + let (mut s, flips) = fold_group(xb, &mut xv, k * 8); + if parity && flips % 2 == 1 { + let least = least_energy_index(xb, w, k * 8); + xv[k * 8 + least] = -xv[k * 8 + least]; + s ^= 1 << least; + } + signs[k] = if parity { s & 127 } else { s }; + } + (xv, signs) +} pub(super) fn totals(x: &[f32], w: &[f32], l: &[i8]) -> (f32, f32) { let (mut sx, mut s2) = (0.0, 0.0); for i in 0..x.len() { diff --git a/crates/native-cpu-expert/src/rust_weight_iq/impl_grid.rs b/crates/native-cpu-expert/src/rust_weight_iq/impl_grid.rs index a65c2f79..d52874fb 100644 --- a/crates/native-cpu-expert/src/rust_weight_iq/impl_grid.rs +++ b/crates/native-cpu-expert/src/rust_weight_iq/impl_grid.rs @@ -1,22 +1,41 @@ //! Moved out of the parent module by STRA-338: impl Grid, fn iq1_s. -use super::alloc_fn::{sum_sq, weights}; #[allow(unused_imports)] use super::*; impl Grid { + /// The neighbour of the off-grid slot `at` with the smallest weighted error when read through `values`. + fn best_valued_neighbor(&self, at: usize, scale: f32, (x, w): (&[f32], &[f32]), values: &[f32; 3]) -> usize { + let mut best = f32::MAX; + let mut index = usize::MAX; + for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] { + let p = &self.points[g as usize]; + let mut err = 0.0; + for i in 0..8 { + let q = values[((p[i] - 1) / 2) as usize]; + let d = scale * q - x[i]; + err += w[i] * d * d; + } + if err < best { + best = err; + index = g as usize; + } + } + index + } pub(super) fn resolve_one( &self, l: &mut [i8], - xw: (&[f32], &[f32]), + x: &[f32], + w: &[f32], scale: f32, - v: &[f32; 3], + values: &[f32; 3], ) -> Result<(usize, bool)> { let mapped = self.map[self.key(l)]; if mapped >= 0 { return Ok((mapped as usize, true)); } - let index = self.best_neighbor((-mapped - 1) as usize, |p| point_error(p, v, scale, xw)); + let index = self.best_valued_neighbor((-mapped - 1) as usize, scale, (x, w), values); // Finite inputs can still overflow this weighted error calculation. Pinned // GGML's no-finite-best fallback indexes beyond its local point array. // Refuse that arithmetic domain rather than reproducing an invalid access. @@ -28,121 +47,9 @@ impl Grid { } Ok((index, false)) } - /// The neighbor table entry at `at`: the point with the smallest `err`, the first one winning ties - /// (usize::MAX when no error is below f32::MAX). - fn best_neighbor(&self, at: usize, err: impl Fn(&[i8; 8]) -> f32) -> usize { - let mut best = f32::MAX; - let mut index = usize::MAX; - for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] { - let e = err(&self.points[g as usize]); - if e < best { - best = e; - index = g as usize; - } - } - index - } } -/// Weighted squared error of the grid point `p`, scaled by `scale` through the values `v`, against `xw` = (x, w). -fn point_error(p: &[i8; 8], v: &[f32; 3], scale: f32, xw: (&[f32], &[f32])) -> f32 { - let (x, w) = xw; - let mut err = 0.0; - for i in 0..8 { - let q = v[((p[i] - 1) / 2) as usize]; - let d = scale * q - x[i]; - err += w[i] * d * d; - } - err -} -/// Largest magnitude of a block. -pub(super) fn abs_max(xb: &[f32]) -> f32 { - let mut max = xb[0].abs(); - for &v in &xb[1..] { - if v.abs() > max { - max = v.abs(); - } - } - max -} -/// Level 0 for the first `b1` sorted values, 1 up to `b2`, 2 for the rest; indexed by original position. -pub(super) fn split_levels(p: &[Pair; N], b1: usize, b2: usize) -> [i8; N] { - let mut l = [0i8; N]; - for j in 0..N { - l[p[j].index as usize] = if j < b1 { - 0 - } else if j < b2 { - 1 - } else { - 2 - }; - } - l -} -/// Mirrors the levels for a negative scale. -pub(super) fn flip_levels(l: &mut [i8]) { - for q in l { - *q = 2 - *q; - } -} -/// What the IQ1_S search settled on for one block of 32. -struct Iq1Fit { - scale: f32, - shift: i8, - indices: [usize; 4], -} -pub(super) fn iq1_s(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> { - y.fill(0); - let mut scales = [0.0; 8]; - let mut shifts = [1i8; 8]; - let mut heads = [0u16; 8]; - let sigma = 2.0 * sum_sq(x) / 256.0; - let mut maxs = 0.0; - for ib in 0..8 { - let at = ib * 32; - let xb = &x[at..at + 32]; - let w: [f32; 32] = weights(xb, Some(&qw[at..at + 32]), sigma, |v| v * v); - let Some(fit) = iq1_s_block(g, xb, &w)? else { continue }; - let mut high = 0u16; - for k in 0..4 { - y[2 + ib * 4 + k] = fit.indices[k] as u8; - high |= ((fit.indices[k] >> 8) as u16) << (3 * k); - } - heads[ib] = high; - scales[ib] = fit.scale; - shifts[ib] = fit.shift; - if fit.scale > maxs { - maxs = fit.scale; - } - } - if maxs == 0.0 { - return Ok(()); - } - iq1_s_scales(y, maxs, &scales, &shifts, &mut heads); - Ok(()) -} -/// The fit of one block of 32; None for a block the search leaves empty. -fn iq1_s_block(g: &Grid, xb: &[f32], w: &[f32; 32]) -> Result> { - let max = abs_max(xb); - if max < 1e-12 { - return Ok(None); - } - let p = pairs::<32>(xb); - let Some((mut scale, mut shift, b1, b2)) = iq1_s_search(&iq1_prefix(&p, xb, w), max) else { return Ok(None) }; - let mut l = split_levels(&p, b1, b2); - if scale < 0.0 { - flip_levels(&mut l); - scale = -scale; - shift = -shift; - } - let values = if shift == 1 { &XP } else { &XM }; - let (indices, all) = iq1_s_resolve(g, &mut l, (xb, w), scale, values)?; - if !all { - scale = iq1_s_refit(g, &indices, (xb, w), values, scale); - } - Ok(Some(Iq1Fit { scale, shift, indices })) -} -/// Prefix sums of w*x and w over the values in sorted order (index 0 is the empty prefix). -fn iq1_prefix(p: &[Pair; 32], xb: &[f32], w: &[f32; 32]) -> ([f32; 33], [f32; 33]) { +/// Prefix sums of `w*x` and of `w` along the sorted order `p`. +fn prefix_sums(w: &[f32; 32], xb: &[f32], p: &[Pair; 32]) -> ([f32; 33], [f32; 33]) { let mut sx = [0.0; 33]; let mut sw = sx; for j in 0..32 { @@ -152,41 +59,37 @@ fn iq1_prefix(p: &[Pair; 32], xb: &[f32], w: &[f32; 32]) -> ([f32; 33], [f32; 33 } (sx, sw) } -/// The split points and sign with the best fit as (scale, shift, b1, b2); None when no split fits. -fn iq1_s_search(prefix: &([f32; 33], [f32; 33]), max: f32) -> Option<(f32, i8, usize, usize)> { - let mut best = -f32::MAX; - let mut scale = max; - let (mut b1, mut b2, mut shift) = (-1i32, -1i32, 0i8); - for i1 in 0..=32 { - for i2 in i1..=32 { - for (values, s) in [(&XP, 1i8), (&XM, -1i8)] { - let (qx, q2) = iq1_s_sums(prefix, (i1, i2), values); - if q2 > 0.0 && qx * qx > best * q2 { - scale = qx / q2; - best = scale * qx; - b1 = i1 as i32; - b2 = i2 as i32; - shift = s; - } - } - } - } - if b1 < 0 || b2 < 0 || shift == 0 { None } else { Some((scale, shift, b1 as usize, b2 as usize)) } -} -fn iq1_s_sums(prefix: &([f32; 33], [f32; 33]), split: (usize, usize), values: &[f32; 3]) -> (f32, f32) { - let (sx, sw) = prefix; - let (i1, i2) = split; +/// `sum(w*x*v)` and `sum(w*v*v)` of the split at `i1`, `i2` when the three runs take the levels `values`. +fn split_moments(sx: &[f32; 33], sw: &[f32; 33], (i1, i2): (usize, usize), values: &[f32; 3]) -> (f32, f32) { let qx = (sx[i1] - sx[0]) * values[0] + (sx[i2] - sx[i1]) * values[1] + (sx[32] - sx[i2]) * values[2]; let q2 = (sw[i1] - sw[0]) * values[0] * values[0] + (sw[i2] - sw[i1]) * values[1] * values[1] + (sw[32] - sw[i2]) * values[2] * values[2]; (qx, q2) } -/// Grid indices of the four groups of 8 and whether all of them sat on the grid; `xw` is (x, w). -fn iq1_s_resolve( +/// The split of the sorted block with the best fit over both shift variants, if any trial had positive weight. +fn best_split(sx: &[f32; 33], sw: &[f32; 33]) -> Option { + let mut best = -f32::MAX; + let mut found = None; + for i1 in 0..=32 { + for i2 in i1..=32 { + for (values, tag) in [(&XP, 1i8), (&XM, -1i8)] { + let (qx, q2) = split_moments(sx, sw, (i1, i2), values); + if q2 > 0.0 && qx * qx > best * q2 { + let scale = qx / q2; + best = scale * qx; + found = Some(Split { scale, b1: i1, b2: i2, tag }); + } + } + } + } + found +} +/// The grid indices of the four groups of eight, and whether all of them were on the grid already. +fn resolve_s_groups( g: &Grid, l: &mut [i8; 32], - xw: (&[f32], &[f32; 32]), + (xb, w): (&[f32], &[f32]), scale: f32, values: &[f32; 3], ) -> Result<([usize; 4], bool)> { @@ -194,28 +97,59 @@ fn iq1_s_resolve( let mut all = true; for k in 0..4 { let at = k * 8; - let (index, on) = g.resolve_one(&mut l[at..at + 8], (&xw.0[at..at + 8], &xw.1[at..at + 8]), scale, values)?; + let (index, on) = g.resolve_one(&mut l[at..at + 8], &xb[at..at + 8], &w[at..at + 8], scale, values)?; indices[k] = index; all &= on; } Ok((indices, all)) } -/// The scale refit against the chosen grid points; unchanged unless both sums are positive. `xw` is (x, w). -fn iq1_s_refit(g: &Grid, indices: &[usize; 4], xw: (&[f32], &[f32; 32]), values: &[f32; 3], scale: f32) -> f32 { - let (xb, w) = xw; - let (mut qx, mut q2) = (0.0, 0.0); +/// The scale refitted to the resolved grid points, kept when the fit has positive moments. +fn refit_s_scale(g: &Grid, indices: &[usize; 4], (xb, w): (&[f32], &[f32]), values: &[f32; 3], scale: f32) -> f32 { + let mut acc = (0.0, 0.0); for k in 0..4 { - let p = &g.points[indices[k]]; - for j in 0..8 { - let q = values[((p[j] - 1) / 2) as usize]; - qx += w[k * 8 + j] * q * xb[k * 8 + j]; - q2 += w[k * 8 + j] * q * q; - } + let at = k * 8; + acc = accumulate_group(g, indices[k], (&xb[at..at + 8], &w[at..at + 8]), (values, 1.0), acc); } - if qx > 0.0 && q2 > 0.0 { qx / q2 } else { scale } + if acc.0 > 0.0 && acc.1 > 0.0 { acc.0 / acc.1 } else { scale } } -/// The block-scale levels and shift flags (with the 3-bit group heads) and the super-block scale. -fn iq1_s_scales(y: &mut [u8], maxs: f32, scales: &[f32; 8], shifts: &[i8; 8], heads: &mut [u16; 8]) { +/// One fitted IQ1_S sub-block of 32 values: the four grid indices, the scale and the shift sign. +struct S1Block { + indices: [usize; 4], + scale: f32, + shift: i8, +} +fn s1_block(g: &Grid, xb: &[f32], w: &[f32; 32]) -> Result> { + if max_abs(xb) < 1e-12 { + return Ok(None); + } + let p = pairs::<32>(xb); + let (sx, sw) = prefix_sums(w, xb, &p); + let Some(split) = best_split(&sx, &sw) else { return Ok(None) }; + let mut l = three_levels(&p, split.b1, split.b2); + let (mut scale, mut shift) = (split.scale, split.tag); + if scale < 0.0 { + flip_levels(&mut l); + scale = -scale; + shift = -shift; + } + let values = if shift == 1 { &XP } else { &XM }; + let (indices, all) = resolve_s_groups(g, &mut l, (xb, w), scale, values)?; + if !all { + scale = refit_s_scale(g, &indices, (xb, w), values, scale); + } + Ok(Some(S1Block { indices, scale, shift })) +} +/// Writes the index bytes of sub-block `ib` and returns its word of ninth index bits. +fn s1_put_indices(y: &mut [u8], ib: usize, indices: &[usize; 4]) -> u16 { + let mut high = 0u16; + for k in 0..4 { + y[2 + ib * 4 + k] = indices[k] as u8; + high |= ((indices[k] >> 8) as u16) << (3 * k); + } + high +} +/// Writes the super-block scale and the per-sub-block scale codes with their shift bit. +fn s1_finish(y: &mut [u8], heads: &mut [u16; 8], (scales, shifts): (&[f32; 8], &[i8; 8]), maxs: f32) { let d = maxs / 15.0; put_h(y, d * 1.125); let inv = 1.0 / d; @@ -228,3 +162,28 @@ fn iq1_s_scales(y: &mut [u8], maxs: f32, scales: &[f32; 8], shifts: &[i8; 8], he y[34 + ib * 2..36 + ib * 2].copy_from_slice(&heads[ib].to_le_bytes()); } } +pub(super) fn iq1_s(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> { + y.fill(0); + let mut scales = [0.0; 8]; + let mut shifts = [1i8; 8]; + let mut heads = [0u16; 8]; + let sigma = 2.0 * sum_squares(x) / 256.0; + let mut maxs = 0.0; + for ib in 0..8 { + let at = ib * 32; + let xb = &x[at..at + 32]; + let w: [f32; 32] = block_weights(xb, at, Some(qw), sigma, |_| 0.0); + let Some(b) = s1_block(g, xb, &w)? else { continue }; + heads[ib] = s1_put_indices(y, ib, &b.indices); + scales[ib] = b.scale; + shifts[ib] = b.shift; + if b.scale > maxs { + maxs = b.scale; + } + } + if maxs == 0.0 { + return Ok(()); + } + s1_finish(y, &mut heads, (&scales, &shifts), maxs); + Ok(()) +} diff --git a/crates/native-cpu-expert/src/rust_weight_iq/iq1_m_fn.rs b/crates/native-cpu-expert/src/rust_weight_iq/iq1_m_fn.rs index 1b80adce..b743223f 100644 --- a/crates/native-cpu-expert/src/rust_weight_iq/iq1_m_fn.rs +++ b/crates/native-cpu-expert/src/rust_weight_iq/iq1_m_fn.rs @@ -1,99 +1,18 @@ //! Moved out of the parent module by STRA-338: fn iq1_m, fn row. -use super::alloc_fn::{sum_sq, weights}; -use super::impl_grid::{abs_max, flip_levels, split_levels}; #[allow(unused_imports)] use super::*; -/// What the IQ1_M search settled on for one block of 16. -struct Iq1MFit { - scale: f32, - which: usize, - indices: [usize; 2], -} -pub(super) fn iq1_m(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> { - y.fill(0); - let mut scales = [0.0; 16]; - let mut shifts = [0usize; 16]; - let sigma = 2.0 * sum_sq(x) / 256.0; - let mut maxs = 0.0; - for ib in 0..16 { - let at = ib * 16; - let xb = &x[at..at + 16]; - let w: [f32; 16] = weights(xb, qw.map(|q| &q[at..at + 16]), sigma, |v| v * v); - let Some(fit) = iq1_m_block(g, xb, &w)? else { continue }; - y[2 * ib] = fit.indices[0] as u8; - y[2 * ib + 1] = fit.indices[1] as u8; - y[32 + ib] = (fit.indices[0] >> 8) as u8 | (((fit.indices[1] >> 8) as u8) << 4); - scales[ib] = fit.scale; - shifts[ib] = fit.which; - if fit.scale > maxs { - maxs = fit.scale; - } - } - if maxs == 0.0 { - return Ok(()); - } - iq1_m_scales(g, (x, y), (qw, sigma), (&scales, &shifts), maxs); - Ok(()) -} -/// The values (+ or - shifted grid) of half `k` of a block of 16 for the shift pattern `which`. -fn half_values(k: usize, which: usize) -> &'static [f32; 3] { +/// The level values of group `k` for the delta pattern `which`: bit 1 picks the first group's sign, bit 0 the second's. +fn group_values(k: usize, which: usize) -> &'static [f32; 3] { if (k == 0 && which < 2) || (k == 1 && which % 2 == 0) { &XP } else { &XM } } -/// The fit of one block of 16; None for a block the search leaves empty. -fn iq1_m_block(g: &Grid, xb: &[f32], w: &[f32; 16]) -> Result> { - let max = abs_max(xb); - if max < 1e-7 { - return Ok(None); - } - let p = pairs::<16>(xb); - let Some((mut scale, mut which, b1, b2)) = iq1_m_search(&p, (xb, w), max) else { return Ok(None) }; - let mut l = split_levels(&p, b1, b2); - if scale < 0.0 { - flip_levels(&mut l); - scale = -scale; - which = 3 - which; - } - let mut indices = [0usize; 2]; - let mut all = true; - for k in 0..2 { - let at = k * 8; - let xw = (&xb[at..at + 8], &w[at..at + 8]); - let (index, on) = g.resolve_one(&mut l[at..at + 8], xw, scale, half_values(k, which))?; - indices[k] = index; - all &= on; - } - if !all { - scale = iq1_m_refit(g, &indices, (xb, w), (which, scale)); - } - Ok(Some(Iq1MFit { scale, which, indices })) +/// The level values element `i` takes in the search under delta pattern `k`. +fn search_values(i: usize, k: usize) -> &'static [f32; 3] { + if (i < 8 && k < 2) || (i >= 8 && k % 2 == 0) { &XP } else { &XM } } -/// The split points and shift pattern with the best fit as (scale, which, b1, b2); None when no split fits. -fn iq1_m_search(p: &[Pair; 16], xw: (&[f32], &[f32; 16]), max: f32) -> Option<(f32, usize, usize, usize)> { - let mut best = -f32::MAX; - let mut scale = max; - let (mut b1, mut b2, mut which) = (-1i32, -1i32, -1i32); - for i1 in 0..=16 { - for i2 in i1..=16 { - let (qx, q2) = iq1_m_sums(p, xw, (i1, i2)); - for k in 0..4 { - if q2[k] > 0.0 && qx[k] * qx[k] > best * q2[k] { - scale = qx[k] / q2[k]; - best = scale * qx[k]; - b1 = i1 as i32; - b2 = i2 as i32; - which = k as i32; - } - } - } - } - if b1 < 0 || b2 < 0 || which < 0 { None } else { Some((scale, which as usize, b1 as usize, b2 as usize)) } -} -/// The weighted sums (sum w*q*x, sum w*q*q) of the four shift patterns for the split `(i1, i2)`. -fn iq1_m_sums(p: &[Pair; 16], xw: (&[f32], &[f32; 16]), split: (usize, usize)) -> ([f32; 4], [f32; 4]) { - let (xb, w) = xw; - let (i1, i2) = split; +/// `sum(w*x*v)` and `sum(w*v*v)` of the split at `i1`, `i2` for each of the four delta patterns. +fn pattern_moments(w: &[f32; 16], xb: &[f32], p: &[Pair; 16], (i1, i2): (usize, usize)) -> ([f32; 4], [f32; 4]) { let mut qx = [0.0; 4]; let mut q2 = qx; for j in 0..16 { @@ -106,63 +25,136 @@ fn iq1_m_sums(p: &[Pair; 16], xw: (&[f32], &[f32; 16]), split: (usize, usize)) - 2 }; for k in 0..4 { - let vals = if (i < 8 && k < 2) || (i >= 8 && k % 2 == 0) { &XP } else { &XM }; + let vals = search_values(i, k); qx[k] += w[i] * vals[value] * xb[i]; q2[k] += w[i] * vals[value] * vals[value]; } } (qx, q2) } -/// The scale refit against the chosen grid points; unchanged unless both sums are positive. -/// `shape` is (which, scale). -fn iq1_m_refit(g: &Grid, indices: &[usize; 2], xw: (&[f32], &[f32; 16]), shape: (usize, f32)) -> f32 { - let (xb, w) = xw; - let (which, scale) = shape; - let (mut qx, mut q2) = (0.0, 0.0); - for k in 0..2 { - let values = half_values(k, which); - let p = &g.points[indices[k]]; - for j in 0..8 { - let q = values[((p[j] - 1) / 2) as usize]; - qx += w[k * 8 + j] * q * xb[k * 8 + j]; - q2 += w[k * 8 + j] * q * q; +/// The split and delta pattern of the sorted block with the best fit, if any trial had positive weight. +fn best_pattern_split(w: &[f32; 16], xb: &[f32], p: &[Pair; 16]) -> Option { + let mut best = -f32::MAX; + let mut found = None; + for i1 in 0..=16 { + for i2 in i1..=16 { + let (qx, q2) = pattern_moments(w, xb, p, (i1, i2)); + for k in 0..4 { + if q2[k] > 0.0 && qx[k] * qx[k] > best * q2[k] { + let scale = qx[k] / q2[k]; + best = scale * qx[k]; + found = Some(Split { scale, b1: i1, b2: i2, tag: k as i8 }); + } + } } } - if qx > 0.0 && q2 > 0.0 { qx / q2 } else { scale } + found } -/// Block-scale levels and shift flags into y, and the super-block scale refit against the stored indices. -/// `xy` is (x, y), `im` is (imatrix, sigma) and `blocks` is (scales, shifts). -fn iq1_m_scales( +/// The grid indices of the two groups of eight, and whether both were on the grid already. +fn resolve_m_groups( g: &Grid, - xy: (&[f32], &mut [u8]), - im: (Option<&[f32]>, f32), - blocks: (&[f32; 16], &[usize; 16]), - maxs: f32, -) { - let (x, y) = xy; - let (qw, sigma) = im; - let (scales, shifts) = blocks; - let mut d = maxs / 15.0; - let inv = 1.0 / d; - let mut sc = [0u16; 4]; + l: &mut [i8; 16], + (xb, w): (&[f32], &[f32]), + (scale, which): (f32, usize), +) -> Result<([usize; 2], bool)> { + let mut indices = [0usize; 2]; + let mut all = true; + for k in 0..2 { + let at = k * 8; + let values = group_values(k, which); + let (index, on) = g.resolve_one(&mut l[at..at + 8], &xb[at..at + 8], &w[at..at + 8], scale, values)?; + indices[k] = index; + all &= on; + } + Ok((indices, all)) +} +/// The scale refitted to the resolved grid points, kept when the fit has positive moments. +fn refit_m_scale(g: &Grid, indices: &[usize; 2], (xb, w): (&[f32], &[f32]), (scale, which): (f32, usize)) -> f32 { let mut acc = (0.0, 0.0); + for k in 0..2 { + let at = k * 8; + let values = group_values(k, which); + acc = accumulate_group(g, indices[k], (&xb[at..at + 8], &w[at..at + 8]), (values, 1.0), acc); + } + if acc.0 > 0.0 && acc.1 > 0.0 { acc.0 / acc.1 } else { scale } +} +/// One fitted IQ1_M sub-block of 16 values: the two grid indices, the scale and the delta pattern. +struct M1Block { + indices: [usize; 2], + scale: f32, + which: usize, +} +fn m1_block(g: &Grid, xb: &[f32], w: &[f32; 16]) -> Result> { + if max_abs(xb) < 1e-7 { + return Ok(None); + } + let p = pairs::<16>(xb); + let Some(split) = best_pattern_split(w, xb, &p) else { return Ok(None) }; + let mut l = three_levels(&p, split.b1, split.b2); + let (mut scale, mut which) = (split.scale, split.tag as usize); + if scale < 0.0 { + flip_levels(&mut l); + scale = -scale; + which = 3 - which; + } + let (indices, all) = resolve_m_groups(g, &mut l, (xb, w), (scale, which))?; + if !all { + scale = refit_m_scale(g, &indices, (xb, w), (scale, which)); + } + Ok(Some(M1Block { indices, scale, which })) +} +/// Writes the index bytes and the ninth-bit nibbles of sub-block `ib`. +fn m1_put_indices(y: &mut [u8], ib: usize, indices: &[usize; 2]) { + y[2 * ib] = indices[0] as u8; + y[2 * ib + 1] = indices[1] as u8; + y[32 + ib] = (indices[0] >> 8) as u8 | (((indices[1] >> 8) as u8) << 4); +} +/// The scale and delta-pattern state of the sub-blocks after the search. +struct M1Scales { + scales: [f32; 16], + shifts: [usize; 16], + maxs: f32, +} +/// Quantizes the sub-block scales to 3 bits (packed four to a word) and ORs each delta pattern into `y[32 + ib]`. +fn write_m1_scale_codes(y: &mut [u8], st: &M1Scales) -> ([u16; 4], [i32; 16]) { + let inv = 1.0 / (st.maxs / 15.0); let masks = [0u8, 128, 8, 136]; + let mut sc = [0u16; 4]; + let mut codes = [0i32; 16]; for ib in 0..16 { - let l = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 7); + let l = nearest(0.5 * (inv * st.scales[ib] - 1.0)).clamp(0, 7); sc[ib / 4] |= (l as u16) << (3 * (ib % 4)); - y[32 + ib] |= masks[shifts[ib]]; + y[32 + ib] |= masks[st.shifts[ib]]; + codes[ib] = l; + } + (sc, codes) +} +/// `sum(w*x*q)` and `sum(w*q*q)` of the stored grid points scaled by their sub-block codes, in sub-block order. +fn m1_stored_moments( + g: &Grid, + y: &[u8], + x: &[f32], + (qw, sigma): (Option<&[f32]>, f32), + st: &M1Scales, + codes: &[i32; 16], +) -> (f32, f32) { + let mut acc = (0.0, 0.0); + for ib in 0..16 { let at = ib * 16; let xb = &x[at..at + 16]; - let w: [f32; 16] = weights(xb, qw.map(|q| &q[at..at + 16]), sigma, |v| v * v); - iq1_m_accumulate(g, y, (ib, shifts[ib], l), (xb, &w), &mut acc); + let w: [f32; 16] = block_weights(xb, at, qw, sigma, |i| xb[i] * xb[i]); + for k in 0..2 { + let values = group_values(k, st.shifts[ib]); + let index = y[2 * ib + k] as usize | (((y[32 + ib] as usize) << (8 - 4 * k)) & 0x700); + let range = k * 8..k * 8 + 8; + let mult = (2 * codes[ib] + 1) as f32; + acc = accumulate_group(g, index, (&xb[range.clone()], &w[range]), (values, mult), acc); + } } - if acc.1 > 0.0 { - d = acc.0 / acc.1; - } - iq1_m_store_scales(y, sc, d); + acc } -/// Spreads the half-precision super-block scale over the top nibbles of the four scale words and stores them. -fn iq1_m_store_scales(y: &mut [u8], mut sc: [u16; 4], d: f32) { +/// Writes the half-float super-block scale into the top nibbles of the four scale words, then the words. +fn put_m1_scale_words(y: &mut [u8], mut sc: [u16; 4], d: f32) { let packed = half_rn(d * 1.1125); sc[0] |= (packed & 15) << 12; sc[1] |= (packed & 0xf0) << 8; @@ -172,40 +164,54 @@ fn iq1_m_store_scales(y: &mut [u8], mut sc: [u16; 4], d: f32) { y[48 + i * 2..50 + i * 2].copy_from_slice(&v.to_le_bytes()); } } -/// Adds block `ib`'s (sum w*q*x, sum w*q*q) at the stored grid indices and block scale level to `acc`; -/// `block` is (ib, shift pattern, scale level). -fn iq1_m_accumulate(g: &Grid, y: &[u8], block: (usize, usize, i32), xw: (&[f32], &[f32; 16]), acc: &mut (f32, f32)) { - let (ib, shift, l) = block; - let (xb, w) = xw; - for k in 0..2 { - let values = half_values(k, shift); - let index = y[2 * ib + k] as usize | (((y[32 + ib] as usize) << (8 - 4 * k)) & 0x700); - let p = &g.points[index]; - for j in 0..8 { - let q = values[((p[j] - 1) / 2) as usize] * (2 * l + 1) as f32; - acc.0 += w[k * 8 + j] * q * xb[k * 8 + j]; - acc.1 += w[k * 8 + j] * q * q; +fn finish_m1(g: &Grid, y: &mut [u8], x: &[f32], weighting: (Option<&[f32]>, f32), st: &M1Scales) { + let mut d = st.maxs / 15.0; + let (sc, codes) = write_m1_scale_codes(y, st); + let (qx, q2) = m1_stored_moments(g, y, x, weighting, st, &codes); + if q2 > 0.0 { + d = qx / q2; + } + put_m1_scale_words(y, sc, d); +} +pub(super) fn iq1_m(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> { + y.fill(0); + let mut st = M1Scales { scales: [0.0; 16], shifts: [0; 16], maxs: 0.0 }; + let sigma = 2.0 * sum_squares(x) / 256.0; + for ib in 0..16 { + let at = ib * 16; + let xb = &x[at..at + 16]; + let w: [f32; 16] = block_weights(xb, at, qw, sigma, |i| xb[i] * xb[i]); + let Some(b) = m1_block(g, xb, &w)? else { continue }; + m1_put_indices(y, ib, &b.indices); + st.scales[ib] = b.scale; + st.shifts[ib] = b.which; + if b.scale > st.maxs { + st.maxs = b.scale; } } + if st.maxs == 0.0 { + return Ok(()); + } + finish_m1(g, y, x, (qw, sigma), &st); + Ok(()) +} +fn row_block(g: &Grid, kind: Kind, x: &[f32], y: &mut [u8], w: Option<&[f32]>) -> Result<()> { + let required = || w.ok_or(Error::Shape); + match kind { + Kind::Iq2Xxs => required().and_then(|w| iq2_xxs(g, x, y, w)), + Kind::Iq2Xs => required().and_then(|w| iq2_xs(g, x, y, w)), + Kind::Iq2S => iq2_s(g, x, y, w), + Kind::Iq3Xxs | Kind::Iq3S => iq3(g, kind, x, y, w), + Kind::Iq1S => required().and_then(|w| iq1_s(g, x, y, w)), + Kind::Iq1M => iq1_m(g, x, y, w), + _ => Err(Error::Unsupported), + } } pub(in super::super) fn row(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> { let g = grid(kind)?; for (i, (x, y)) in x.chunks_exact(256).zip(y.chunks_exact_mut(kind.block().1)).enumerate() { let w = qw.map(|q| &q[i * 256..i * 256 + 256]); - row_block(kind, &g, (x, y), w)?; + row_block(&g, kind, x, y, w)?; } Ok(()) } -/// Quantizes one 256-value block with the quantizer of `kind`. -fn row_block(kind: Kind, g: &Grid, xy: (&[f32], &mut [u8]), w: Option<&[f32]>) -> Result<()> { - let (x, y) = xy; - match kind { - Kind::Iq2Xxs => iq2_xxs(g, x, y, w.ok_or(Error::Shape)?), - Kind::Iq2Xs => iq2_xs(g, x, y, w.ok_or(Error::Shape)?), - Kind::Iq2S => iq2_s(g, x, y, w), - Kind::Iq3Xxs | Kind::Iq3S => iq3(g, kind, x, y, w), - Kind::Iq1S => iq1_s(g, x, y, w.ok_or(Error::Shape)?), - Kind::Iq1M => iq1_m(g, x, y, w), - _ => Err(Error::Unsupported), - } -} diff --git a/crates/native-cpu-expert/src/rust_weight_iq/iq2_xxs_fn.rs b/crates/native-cpu-expert/src/rust_weight_iq/iq2_xxs_fn.rs index cb7747db..419df16f 100644 --- a/crates/native-cpu-expert/src/rust_weight_iq/iq2_xxs_fn.rs +++ b/crates/native-cpu-expert/src/rust_weight_iq/iq2_xxs_fn.rs @@ -1,36 +1,73 @@ //! Moved out of the parent module by STRA-338: fn iq2_xxs, fn iq2_xs. -use super::alloc_fn::{Block, Trial, fix_groups, flip, search_scale, sum_sq, vmax, weights}; #[allow(unused_imports)] use super::*; -pub(super) fn iq2_xxs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> { - let mut scales = [0.0; 8]; - let mut q2 = [0u32; 16]; - y.fill(0); - put_h(y, 0.0); - let sigma = sum_sq(x) / 256.0; - let mut maxs = 0.0; - for ib in 0..8 { - let at = ib * 32; - let Some((scale, l, sign)) = iq2_xxs_block(g, &x[at..at + 32], &qw[at..at + 32], sigma) else { continue }; - for k in 0..4 { - let i = g.index(&l[k * 8..k * 8 + 8])?; - q2[2 * ib] |= (i as u32) << (8 * k); - q2[2 * ib + 1] |= (sign[k] as u32) << (7 * k); - } - scales[ib] = scale; - if scale > maxs { - maxs = scale; +/// One fitted IQ2_XXS sub-block of 32 values: levels, sign bytes and scale. +struct Xxs { + l: [i8; 32], + sign: [u8; 4], + scale: f32, +} +/// Scale of the best of the 13 trials around `effective`, with the levels it produced. +fn xxs_search(g: &Grid, b: &Folded<32>, effective: f32, first: ([i8; 32], f32)) -> ([i8; 32], f32) { + let (mut l, mut scale) = first; + let mut best = 0.0; + for is in -6..=6 { + let inv = (5.0 + is as f32 * 0.1) / effective; + let mut aux = [0i8; 32]; + quant_candidates(g, inv, b.xv, b.wa, 1.0 / inv, &mut aux, 3, &mut [false; 4]); + let (sx, s2) = totals(b.xv, b.w, &aux); + if s2 > 0.0 && sx * sx > best * s2 { + scale = sx / s2; + best = scale * sx; + l = aux; } } - if maxs != 0.0 { - iq2_xxs_finish(y, &mut q2, &scales, maxs); + (l, scale) +} +/// Re-rounds all levels against the fitted scale and refits the scale to them. +fn xxs_refit(g: &Grid, b: &Folded<32>, l: &mut [i8; 32], scale: f32) -> f32 { + quant_candidates(g, 1.0 / scale, b.xv, b.wa, scale, l, 3, &mut [false; 4]); + let (sx, s2) = totals(b.xv, b.w, l); + if s2 > 0.0 { sx / s2 } else { scale } +} +fn xxs_block(g: &Grid, xb: &[f32], at: usize, qw: &[f32], sigma: f32) -> Option { + let w: [f32; 32] = block_weights(xb, at, Some(qw), sigma, |_| 0.0); + let wa = square_roots(&w); + let (xv, mut sign) = signs::<32>(xb, &w, true); + if max_value(&xv) < 1e-15 { + return None; + } + let mut lp = [0u8; 32]; + let mut scale = qp(&xv, 4, &mut lp, &w); + let mut l: [i8; 32] = std::array::from_fn(|i| lp[i] as i8); + let effective = scale * 3.0; + if effective <= 0.0 { + return None; + } + let b = Folded { xv: &xv, w: &w, wa: &wa }; + (l, scale) = xxs_search(g, &b, effective, (l, scale)); + if scale > 0.0 { + scale = xxs_refit(g, &b, &mut l, scale); + } + if scale < 0.0 { + scale = -scale; + negate_signs(&mut sign, 127); + } + Some(Xxs { l, sign, scale }) +} +/// Packs the four grid indices and sign groups of sub-block `ib` into the 32-bit words `q2`. +fn xxs_store(g: &Grid, q2: &mut [u32; 16], ib: usize, b: &Xxs) -> Result<()> { + for k in 0..4 { + let i = g.index(&b.l[k * 8..k * 8 + 8])?; + q2[2 * ib] |= (i as u32) << (8 * k); + q2[2 * ib + 1] |= (b.sign[k] as u32) << (7 * k); } Ok(()) } -/// Writes the super-block scale, merges the block scale levels into the packed words and stores them. -fn iq2_xxs_finish(y: &mut [u8], q2: &mut [u32; 16], scales: &[f32; 8], maxs: f32) { +/// Adds the 4-bit sub-block scale codes and writes the packed words. +fn xxs_finish(y: &mut [u8], q2: &mut [u32; 16], scales: &[f32; 8], maxs: f32) { let d = maxs / 31.0; put_h(y, d); let inv = 1.0 / d; @@ -41,75 +78,60 @@ fn iq2_xxs_finish(y: &mut [u8], q2: &mut [u32; 16], scales: &[f32; 8], maxs: f32 y[2 + i * 4..6 + i * 4].copy_from_slice(&v.to_le_bytes()); } } -/// (scale, levels, sign bytes) of one block of 32; None for a block that stays empty. -fn iq2_xxs_block(g: &Grid, xb: &[f32], qb: &[f32], sigma: f32) -> Option<(f32, [i8; 32], [u8; 4])> { - let b = Block::<32>::new(xb, weights(xb, Some(qb), sigma, |v| v * v), true); - if vmax(&b.xv) < 1e-15 { - return None; - } - let mut lp = [0u8; 32]; - let scale = qp(&b.xv, 4, &mut lp, &b.w); - let effective = scale * 3.0; - if effective <= 0.0 { - return None; - } - let (mut scale, l) = iq2_xxs_search(g, &b, (scale, lp.map(|v| v as i8)), effective); - let mut sign = b.sign; - if scale < 0.0 { - scale = -scale; - flip(&mut sign, 127); - } - Some((scale, l, sign)) -} -/// Tries the 13 scales around `effective`, keeps the best levels, then re-quantizes them at the final scale; -/// `start` is the initial (scale, levels). -fn iq2_xxs_search(g: &Grid, b: &Block<32>, start: (f32, [i8; 32]), effective: f32) -> (f32, [i8; 32]) { - let (mut scale, mut l) = start; - let mut best = 0.0; - for is in -6..=6 { - let inv = (5.0 + is as f32 * 0.1) / effective; - let mut aux = [0i8; 32]; - quant_candidates(g, inv, &b.xv, &b.wa, 1.0 / inv, &mut aux, 3, &mut [false; 4]); - let (sx, s2) = totals(&b.xv, &b.w, &aux); - if s2 > 0.0 && sx * sx > best * s2 { - scale = sx / s2; - best = scale * sx; - l = aux; - } - } - if scale > 0.0 { - quant_candidates(g, 1.0 / scale, &b.xv, &b.wa, scale, &mut l, 3, &mut [false; 4]); - let (sx, s2) = totals(&b.xv, &b.w, &l); - if s2 > 0.0 { - scale = sx / s2; - } - } - (scale, l) -} -pub(super) fn iq2_xs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> { - let mut scales = [0.0; 16]; - let mut q2 = [0u16; 32]; +pub(super) fn iq2_xxs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> { + let mut scales = [0.0; 8]; + let mut q2 = [0u32; 16]; y.fill(0); - let sigma = sum_sq(x) / 256.0; + put_h(y, 0.0); + let sigma = sum_squares(x) / 256.0; let mut maxs = 0.0; - for ib in 0..16 { - let at = ib * 16; - let Some((scale, l, sign)) = iq2_xs_block(g, &x[at..at + 16], &qw[at..at + 16], sigma) else { continue }; - for k in 0..2 { - q2[2 * ib + k] = g.index(&l[k * 8..k * 8 + 8])? as u16 | ((sign[k] as u16) << 9); - } - scales[ib] = scale; - if scale > maxs { - maxs = scale; + for ib in 0..8 { + let at = ib * 32; + let Some(b) = xxs_block(g, &x[at..at + 32], at, qw, sigma) else { continue }; + xxs_store(g, &mut q2, ib, &b)?; + scales[ib] = b.scale; + if b.scale > maxs { + maxs = b.scale; } } - if maxs != 0.0 { - iq2_xs_finish(y, &q2, &scales, maxs); + if maxs == 0.0 { + return Ok(()); + } + xxs_finish(y, &mut q2, &scales, maxs); + Ok(()) +} +/// One fitted IQ2_XS sub-block of 16 values: levels, sign bytes and scale. +struct Xs { + l: [i8; 16], + sign: [u8; 4], + scale: f32, +} +fn xs_block(g: &Grid, xb: &[f32], at: usize, qw: &[f32], sigma: f32) -> Option { + let w: [f32; 16] = block_weights(xb, at, Some(qw), sigma, |_| 0.0); + let wa = square_roots(&w); + let (xv, mut sign) = signs::<16>(xb, &w, true); + let max = max_value(&xv); + if max < 1e-15 { + return None; + } + let b = Folded { xv: &xv, w: &w, wa: &wa }; + let mut fit = search_scale(g, &b, max, &Plan { center: 5.0, step: 0.1, tries: 9, top: 3 }, [true; 2]); + refit_off_grid(g, &b, &mut fit, 3, false); + if fit.scale < 0.0 { + fit.scale = -fit.scale; + negate_signs(&mut sign[..2], 127); + } + Some(Xs { l: fit.l, sign, scale: fit.scale }) +} +/// Packs the two grid indices and 7-bit signs of sub-block `ib` into the 16-bit words `q2`. +fn xs_store(g: &Grid, q2: &mut [u16; 32], ib: usize, b: &Xs) -> Result<()> { + for k in 0..2 { + q2[2 * ib + k] = g.index(&b.l[k * 8..k * 8 + 8])? as u16 | ((b.sign[k] as u16) << 9); } Ok(()) } -/// Writes the super-block scale, the block scale levels and the packed words. -fn iq2_xs_finish(y: &mut [u8], q2: &[u16; 32], scales: &[f32; 16], maxs: f32) { +/// Writes the 4-bit sub-block scale codes and the packed words. +fn xs_finish(y: &mut [u8], q2: &[u16; 32], scales: &[f32; 16], maxs: f32) { let d = maxs / 31.0; put_h(y, d); let inv = 1.0 / d; @@ -121,20 +143,24 @@ fn iq2_xs_finish(y: &mut [u8], q2: &[u16; 32], scales: &[f32; 16], maxs: f32) { y[2 + i * 2..4 + i * 2].copy_from_slice(&v.to_le_bytes()); } } -/// (scale, levels, sign bytes) of one block of 16; None for a block that stays empty. -fn iq2_xs_block(g: &Grid, xb: &[f32], qb: &[f32], sigma: f32) -> Option<(f32, [i8; 16], [u8; 4])> { - let b = Block::<16>::new(xb, weights(xb, Some(qb), sigma, |v| v * v), true); - let max = vmax(&b.xv); - if max < 1e-15 { - return None; +pub(super) fn iq2_xs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> { + let mut scales = [0.0; 16]; + let mut q2 = [0u16; 32]; + y.fill(0); + let sigma = sum_squares(x) / 256.0; + let mut maxs = 0.0; + for ib in 0..16 { + let at = ib * 16; + let Some(b) = xs_block(g, &x[at..at + 16], at, qw, sigma) else { continue }; + xs_store(g, &mut q2, ib, &b)?; + scales[ib] = b.scale; + if b.scale > maxs { + maxs = b.scale; + } } - let trial = Trial { centre: 5.0, step: 0.1, tries: 9, levels: 3 }; - let mut fit = search_scale::<16, 2>(g, &b, max, trial, [true; 2]); - fix_groups(g, &b, &mut fit, true, 3); - let mut sign = b.sign; - if fit.scale < 0.0 { - fit.scale = -fit.scale; - flip(&mut sign[..2], 127); + if maxs == 0.0 { + return Ok(()); } - Some((fit.scale, fit.l, sign)) + xs_finish(y, &q2, &scales, maxs); + Ok(()) } diff --git a/crates/native-cpu-expert/src/rust_weight_iq/iq3_fn.rs b/crates/native-cpu-expert/src/rust_weight_iq/iq3_fn.rs index cb347059..4606262d 100644 --- a/crates/native-cpu-expert/src/rust_weight_iq/iq3_fn.rs +++ b/crates/native-cpu-expert/src/rust_weight_iq/iq3_fn.rs @@ -1,123 +1,131 @@ //! Moved out of the parent module by STRA-338: fn iq3, fn iq2_s, fn compare_pair, fn pairs. -use super::alloc_fn::{Block, Trial, fix_groups, flip, search_scale, sum_sq, vmax, weights}; #[allow(unused_imports)] use super::*; -/// The packed output of the IQ3 quantizers while the blocks are being fitted. -struct Iq3Out { - scales: [f32; 8], - flags: [u32; 8], - q3: [u8; 104], +/// One fitted IQ3 sub-block of 32 values: levels, sign bytes and scale. +struct Iq3Block { + l: [i8; 32], + sign: [u8; 4], + scale: f32, } -impl Iq3Out { - /// Stores the grid indices and signs of block `ib`; `fit` is (levels, sign bytes). - fn store(&mut self, g: &Grid, full: bool, y: &mut [u8], ib: usize, fit: (&[i8; 32], &[u8; 4])) -> Result<()> { - let (l, sign) = fit; - for k in 0..8 { - let index = g.index(&l[k * 4..k * 4 + 4])?; - self.q3[ib * 8 + k] = index as u8; - if full { - y[66 + ib] |= ((index >> 8) as u8) << k; - } - } - if full { - y[74 + ib * 4..78 + ib * 4].copy_from_slice(sign); - } else { - self.flags[ib] = - sign[0] as u32 | ((sign[1] as u32) << 7) | ((sign[2] as u32) << 14) | ((sign[3] as u32) << 21); - } - Ok(()) +fn iq3_block(g: &Grid, full: bool, xb: &[f32], at: usize, qw: Option<&[f32]>, sigma: f32) -> Option { + let w: [f32; 32] = block_weights(xb, at, qw, sigma, |i| xb[i] * xb[i]); + let wa = square_roots(&w); + let (xv, mut sign) = signs::<32>(xb, &w, !full); + let max = max_value(&xv); + if (full && max == 0.0) || (!full && max < 1e-8) { + return None; } - /// Writes the super-block scale, the block scale levels and the packed indices and flags. - fn finish(&mut self, full: bool, y: &mut [u8], maxs: f32) { - let d = maxs / 31.0; - put_h(y, d * if full { 1.033 } else { 1.0125 }); - let inv = 1.0 / d; - for ib in 0..8 { - let s = nearest(0.5 * (inv * self.scales[ib] - 1.0)).clamp(0, 15) as u8; - if full { - y[106 + ib / 2] |= s << (4 * (ib % 2)); - } else { - self.flags[ib] |= (s as u32) << 28; - } + let b = Folded { xv: &xv, w: &w, wa: &wa }; + let tries = if full { 9 } else { 15 }; + let mut fit = search_scale(g, &b, max, &Plan { center: 15.0, step: 0.2, tries, top: 8 }, [!full; 8]); + refit_off_grid(g, &b, &mut fit, 8, full); + if fit.scale < 0.0 { + fit.scale = -fit.scale; + negate_signs(&mut sign, if full { 255 } else { 127 }); + } + Some(Iq3Block { l: fit.l, sign, scale: fit.scale }) +} +/// Writes the low index bytes of sub-block `ib` to `q3` (and the ninth bits to `y` for IQ3_S). +fn iq3_put_indices(g: &Grid, y: &mut [u8], q3: &mut [u8; 104], full: bool, ib: usize, l: &[i8; 32]) -> Result<()> { + for k in 0..8 { + let index = g.index(&l[k * 4..k * 4 + 4])?; + q3[ib * 8 + k] = index as u8; + if full { + y[66 + ib] |= ((index >> 8) as u8) << k; } - y[2..66].copy_from_slice(&self.q3[..64]); - if !full { - for (i, v) in self.flags.into_iter().enumerate() { - y[66 + i * 4..70 + i * 4].copy_from_slice(&v.to_le_bytes()); - } + } + Ok(()) +} +/// IQ3_S keeps the sign bytes as they are, IQ3_XXS packs four 7-bit groups into one word. +fn iq3_put_signs(y: &mut [u8], flags: &mut [u32; 8], full: bool, ib: usize, sign: &[u8; 4]) { + if full { + y[74 + ib * 4..78 + ib * 4].copy_from_slice(sign); + } else { + flags[ib] = sign[0] as u32 | ((sign[1] as u32) << 7) | ((sign[2] as u32) << 14) | ((sign[3] as u32) << 21); + } +} +/// Adds the 4-bit sub-block scale codes and writes the index bytes (and the IQ3_XXS words). +fn iq3_finish(y: &mut [u8], q3: &[u8; 104], flags: &mut [u32; 8], (scales, maxs): (&[f32; 8], f32), full: bool) { + let d = maxs / 31.0; + put_h(y, d * if full { 1.033 } else { 1.0125 }); + let inv = 1.0 / d; + for ib in 0..8 { + let s = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 15) as u8; + if full { + y[106 + ib / 2] |= s << (4 * (ib % 2)); + } else { + flags[ib] |= (s as u32) << 28; + } + } + y[2..66].copy_from_slice(&q3[..64]); + if !full { + for (i, v) in flags.iter().enumerate() { + y[66 + i * 4..70 + i * 4].copy_from_slice(&v.to_le_bytes()); } } } pub(super) fn iq3(g: &Grid, kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> { let full = kind == Kind::Iq3S; - let mut out = Iq3Out { scales: [0.0; 8], flags: [0u32; 8], q3: [0u8; 104] }; + let mut scales = [0.0; 8]; + let mut flags = [0u32; 8]; + let mut q3 = [0u8; 104]; y.fill(0); - let sigma = 2.0 * sum_sq(x) / 256.0; + let sigma = 2.0 * sum_squares(x) / 256.0; let mut maxs = 0.0; for ib in 0..8 { let at = ib * 32; - let qb = qw.map(|q| &q[at..at + 32]); - let Some((scale, l, sign)) = iq3_block(g, full, (&x[at..at + 32], qb), sigma) else { continue }; - out.store(g, full, y, ib, (&l, &sign))?; - out.scales[ib] = scale; - if scale > maxs { - maxs = scale; + let Some(b) = iq3_block(g, full, &x[at..at + 32], at, qw, sigma) else { continue }; + iq3_put_indices(g, y, &mut q3, full, ib, &b.l)?; + iq3_put_signs(y, &mut flags, full, ib, &b.sign); + scales[ib] = b.scale; + if b.scale > maxs { + maxs = b.scale; } } if maxs == 0.0 { return Ok(()); } - out.finish(full, y, maxs); + iq3_finish(y, &q3, &mut flags, (&scales, maxs), full); Ok(()) } -/// (scale, levels, sign bytes) of one block of 32; None for a block that stays empty. `xq` is (x, imatrix). -fn iq3_block(g: &Grid, full: bool, xq: (&[f32], Option<&[f32]>), sigma: f32) -> Option<(f32, [i8; 32], [u8; 4])> { - let (xb, qb) = xq; - let b = Block::<32>::new(xb, weights(xb, qb, sigma, |v| v * v), !full); - let max = vmax(&b.xv); - if (full && max == 0.0) || (!full && max < 1e-8) { +/// One fitted IQ2_S sub-block of 16 values: levels, sign bytes and scale. +struct S2Block { + l: [i8; 16], + sign: [u8; 4], + scale: f32, +} +fn s2_block(g: &Grid, xb: &[f32], at: usize, qw: Option<&[f32]>, sigma: f32) -> Option { + let w: [f32; 16] = block_weights(xb, at, qw, sigma, |i| 0.25 * sigma + xb[i] * xb[i]); + let wa = square_roots(&w); + let (xv, mut sign) = signs::<16>(xb, &w, false); + let max = max_value(&xv); + if max < 1e-8 { return None; } - let trial = Trial { centre: 15.0, step: 0.2, tries: if full { 9 } else { 15 }, levels: 8 }; - let mut fit = search_scale::<32, 8>(g, &b, max, trial, [!full; 8]); - fix_groups(g, &b, &mut fit, !full, 8); - let mut sign = b.sign; + let b = Folded { xv: &xv, w: &w, wa: &wa }; + let mut fit = search_scale(g, &b, max, &Plan { center: 5.0, step: 0.1, tries: 9, top: 3 }, [true; 2]); + refit_off_grid(g, &b, &mut fit, 3, false); if fit.scale < 0.0 { fit.scale = -fit.scale; - flip(&mut sign, if full { 255 } else { 127 }); + negate_signs(&mut sign[..2], 255); } - Some((fit.scale, fit.l, sign)) + Some(S2Block { l: fit.l, sign, scale: fit.scale }) } -pub(super) fn iq2_s(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> { - let mut scales = [0.0; 16]; - y.fill(0); - let sigma = 2.0 * sum_sq(x) / 256.0; - let mut maxs = 0.0; - for ib in 0..16 { - let at = ib * 16; - let qb = qw.map(|q| &q[at..at + 16]); - let Some((scale, l, sign)) = iq2_s_block(g, (&x[at..at + 16], qb), sigma) else { continue }; - for k in 0..2 { - let index = g.index(&l[k * 8..k * 8 + 8])?; - let i8 = 2 * ib + k; - y[2 + i8] = index as u8; - y[66 + i8 / 4] |= ((index >> 8) as u8) << (2 * (i8 % 4)); - y[34 + i8] = sign[k]; - } - scales[ib] = scale; - if scale > maxs { - maxs = scale; - } - } - if maxs != 0.0 { - iq2_s_finish(y, &scales, maxs); +/// Writes the index bytes, ninth bits and sign bytes of the two groups of sub-block `ib`. +fn s2_store(g: &Grid, y: &mut [u8], ib: usize, b: &S2Block) -> Result<()> { + for k in 0..2 { + let index = g.index(&b.l[k * 8..k * 8 + 8])?; + let i8 = 2 * ib + k; + y[2 + i8] = index as u8; + y[66 + i8 / 4] |= ((index >> 8) as u8) << (2 * (i8 % 4)); + y[34 + i8] = b.sign[k]; } Ok(()) } -/// Writes the super-block scale and the block scale levels. -fn iq2_s_finish(y: &mut [u8], scales: &[f32; 16], maxs: f32) { +/// Writes the super-block scale and the 4-bit sub-block scale codes. +fn s2_finish(y: &mut [u8], scales: &[f32; 16], maxs: f32) { let d = maxs / 31.0; put_h(y, d * 0.9875); let inv = 1.0 / d; @@ -126,23 +134,25 @@ fn iq2_s_finish(y: &mut [u8], scales: &[f32; 16], maxs: f32) { y[74 + ib / 2] |= s << (4 * (ib % 2)); } } -/// (scale, levels, sign bytes) of one block of 16; None for a block that stays empty. `xq` is (x, imatrix). -fn iq2_s_block(g: &Grid, xq: (&[f32], Option<&[f32]>), sigma: f32) -> Option<(f32, [i8; 16], [u8; 4])> { - let (xb, qb) = xq; - let b = Block::<16>::new(xb, weights(xb, qb, sigma, |v| 0.25 * sigma + v * v), false); - let max = vmax(&b.xv); - if max < 1e-8 { - return None; +pub(super) fn iq2_s(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> { + let mut scales = [0.0; 16]; + y.fill(0); + let sigma = 2.0 * sum_squares(x) / 256.0; + let mut maxs = 0.0; + for ib in 0..16 { + let at = ib * 16; + let Some(b) = s2_block(g, &x[at..at + 16], at, qw, sigma) else { continue }; + s2_store(g, y, ib, &b)?; + scales[ib] = b.scale; + if b.scale > maxs { + maxs = b.scale; + } } - let trial = Trial { centre: 5.0, step: 0.1, tries: 9, levels: 3 }; - let mut fit = search_scale::<16, 2>(g, &b, max, trial, [true; 2]); - fix_groups(g, &b, &mut fit, true, 3); - let mut sign = b.sign; - if fit.scale < 0.0 { - fit.scale = -fit.scale; - flip(&mut sign[..2], 255); + if maxs == 0.0 { + return Ok(()); } - Some((fit.scale, fit.l, sign)) + s2_finish(y, &scales, maxs); + Ok(()) } pub(super) unsafe extern "C" fn compare_pair(a: *const std::ffi::c_void, b: *const std::ffi::c_void) -> i32 { unsafe { @@ -159,8 +169,9 @@ pub(super) unsafe extern "C" fn compare_pair(a: *const std::ffi::c_void, b: *con } pub(super) fn pairs(x: &[f32]) -> [Pair; N] { let mut p = std::array::from_fn(|j| Pair { value: x[j], index: j as i32 }); - // SAFETY: `p` is N initialized repr(C) Pair values and compare_pair reads exactly two of them; qsort retains - // nothing. NaN keys make the comparator inconsistent and can only mis-order the (<= 256 B) array. + // SAFETY: `p` is N initialized repr(C) Pair values and compare_pair reads exactly two of them; + // qsort retains nothing. NaN keys make the comparator inconsistent and can only mis-order the + // (<= 256 B) array. unsafe { qsort(p.as_mut_ptr().cast(), N, std::mem::size_of::(), compare_pair); } diff --git a/crates/native-cpu-expert/src/rust_weight_quant/best_fp4_fn.rs b/crates/native-cpu-expert/src/rust_weight_quant/best_fp4_fn.rs index 94d0434c..903dd3d3 100644 --- a/crates/native-cpu-expert/src/rust_weight_quant/best_fp4_fn.rs +++ b/crates/native-cpu-expert/src/rust_weight_quant/best_fp4_fn.rs @@ -1,6 +1,5 @@ //! Moved out of the parent module by STRA-338: fn best_fp4, fn fp4, fn ternary, fn pack_k2, fn q2k, fn pack_scale3 .... -use super::nearest_fn::{Qkx, Search, sum_sq}; #[allow(unused_imports)] use super::*; @@ -38,18 +37,8 @@ pub(super) fn fp4(kind: Kind, x: &[f32], y: &mut [u8]) { } } } -pub(super) fn ternary(kind: Kind, x: &[f32], y: &mut [u8]) { - let (a, _) = max_signed(x); - let inv = if a != 0.0 { 1.0 / a } else { 0.0 }; - if kind == Kind::Tq2 { - put_h(y, 64, a); - tq2_levels(x, y, inv); - } else { - put_h(y, 52, a); - tq1_levels(x, y, inv); - } -} -fn tq2_levels(x: &[f32], y: &mut [u8], inv: f32) { +fn ternary_tq2(x: &[f32], y: &mut [u8], a: f32, inv: f32) { + put_h(y, 64, a); for p in 0..2 { for j in 0..32 { let mut q = 0; @@ -60,20 +49,35 @@ fn tq2_levels(x: &[f32], y: &mut [u8], inv: f32) { } } } -fn tq1_levels(x: &[f32], y: &mut [u8], inv: f32) { +/// One base-3 byte of TQ1_0: `digits` trits taken `step` apart from `x[start + j]`, scaled to eight bits. +fn ternary_tq1_byte(x: &[f32], inv: f32, start: usize, step: usize, j: usize) -> u8 { + let digits = if start == 240 { 4 } else { 5 }; + let mut q = 0u16; + for k in 0..digits { + q = q * 3 + ((x[start + k * step + j] * inv).round() as i32 + 1) as u16; + } + if start == 240 { + q *= 3; + } + ((q * 256 + 242) / 243) as u8 +} +fn ternary_tq1(x: &[f32], y: &mut [u8], a: f32, inv: f32) { + put_h(y, 52, a); for (start, step, out, n) in [(0, 32, 0, 32), (160, 16, 32, 16), (240, 4, 48, 4)] { for j in 0..n { - let mut q = 0u16; - for k in 0..if start == 240 { 4 } else { 5 } { - q = q * 3 + ((x[start + k * step + j] * inv).round() as i32 + 1) as u16; - } - if start == 240 { - q *= 3; - } - y[out + j] = ((q * 256 + 242) / 243) as u8; + y[out + j] = ternary_tq1_byte(x, inv, start, step, j); } } } +pub(super) fn ternary(kind: Kind, x: &[f32], y: &mut [u8]) { + let (a, _) = max_signed(x); + let inv = if a != 0.0 { 1.0 / a } else { 0.0 }; + if kind == Kind::Tq2 { + ternary_tq2(x, y, a, inv); + } else { + ternary_tq1(x, y, a, inv); + } +} pub(super) fn pack_k2(l: &[u8], y: &mut [u8]) { for p in 0..2 { for j in 0..32 { @@ -82,60 +86,63 @@ pub(super) fn pack_k2(l: &[u8], y: &mut [u8]) { } } } -pub(super) fn q2k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) { - let mut l = [0u8; 256]; - let search = q2k_search(x, &mut l, qw); - let (ls, lm, d, m) = q2k_scales(&search, qw.is_some()); - put_h(y, 80, d); - put_h(y, 82, m); - let (d, m) = (h(y, 80), h(y, 82)); - q2k_requantize(x, y, [&ls, &lm], (d, m), &mut l); - pack_k2(&l, &mut y[16..80]); +/// The sixteen 16-element sub-block fits of a Q2_K block: scales, minimums, weight sums and their maxima. +struct Q2Fit { + l: [u8; 256], + scales: [f32; 16], + mins: [f32; 16], + sw: [f32; 16], + maxs: f32, + maxm: f32, } -/// Best (scale, minimum) of each 16-value block, with the levels of that fit in `l`. -fn q2k_search(x: &[f32], l: &mut [u8; 256], qw: Option<&[f32]>) -> Search<16> { - let sigma = sum_sq(x) / 256.0; - let mut s = Search::<16>::new(); - let plain = Qkx { rmin: -0.5, rdelta: 0.1, nstep: 15, mad: true, third: false }; +fn q2_weights(xb: &[f32], qw: Option<&[f32]>, k: usize, sigma: f32) -> [f32; 16] { + std::array::from_fn(|j| if let Some(q) = qw { q[k * 16 + j] * (sigma + xb[j] * xb[j]).sqrt() } else { xb[j].abs() }) +} +fn q2_subfit(xb: &[f32], w: &[f32; 16], l: &mut [u8], weighted: bool) -> (f32, f32) { + if weighted { qkx(xb, 3, w, l, -0.9, 0.05, 36, false, true) } else { qkx(xb, 3, w, l, -0.5, 0.1, 15, true, false) } +} +fn q2_fit_blocks(x: &[f32], qw: Option<&[f32]>, sigma: f32) -> Q2Fit { + let mut f = Q2Fit { l: [0; 256], scales: [0.0; 16], mins: [0.0; 16], sw: [0.0; 16], maxs: 0.0, maxm: 0.0 }; for k in 0..16 { let xb = &x[k * 16..k * 16 + 16]; - let w: [f32; 16] = std::array::from_fn(|j| { - if let Some(q) = qw { q[k * 16 + j] * (sigma + xb[j] * xb[j]).sqrt() } else { xb[j].abs() } - }); + let w = q2_weights(xb, qw, k, sigma); for &v in &w { - s.sw[k] += v; + f.sw[k] += v; + } + let (d, m) = q2_subfit(xb, &w, &mut f.l[k * 16..k * 16 + 16], qw.is_some()); + f.scales[k] = d; + f.mins[k] = m; + if d > f.maxs { + f.maxs = d; + } + if m > f.maxm { + f.maxm = m; } - let (d, m) = if qw.is_some() { - qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], Qkx::WEIGHTED) - } else { - qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], plain) - }; - s.record(k, d, m); } - s + f } -/// The 4-bit scale and minimum levels of the blocks and the super-block (d, m). -fn q2k_scales(s: &Search<16>, weighted: bool) -> ([u8; 16], [u8; 16], f32, f32) { +/// The 4-bit scale and minimum codes of the sixteen sub-blocks, with the super-block scale and minimum. +fn q2_scale_codes(f: &Q2Fit, weighted: bool) -> ([u8; 16], [u8; 16], f32, f32) { let mut ls = [0u8; 16]; let mut lm = ls; if weighted { - let (d, m) = (qp(&s.scales, 15, &mut ls, &s.sw), qp(&s.mins, 15, &mut lm, &s.sw)); + let d = qp(&f.scales, 15, &mut ls, &f.sw); + let m = qp(&f.mins, 15, &mut lm, &f.sw); return (ls, lm, d, m); } - let (si, mi) = s.factors(15.0); + let si = if f.maxs > 0.0 { 15.0 / f.maxs } else { 0.0 }; + let mi = if f.maxm > 0.0 { 15.0 / f.maxm } else { 0.0 }; for k in 0..16 { - ls[k] = nearest(si * s.scales[k]) as u8; - lm[k] = nearest(mi * s.mins[k]) as u8; + ls[k] = nearest(si * f.scales[k]) as u8; + lm[k] = nearest(mi * f.mins[k]) as u8; } - let (d, m) = s.steps(15.0); - (ls, lm, d, m) + (ls, lm, f.maxs / 15.0, f.maxm / 15.0) } -/// Stores the packed scales in y[..16] and requantizes the values against the stored (rounded) d and m. -fn q2k_requantize(x: &[f32], y: &mut [u8], levels: [&[u8; 16]; 2], dm: (f32, f32), l: &mut [u8; 256]) { - let [ls, lm] = levels; - let (d, m) = dm; +/// Re-derives the levels against the stored (half-rounded) scale and minimum of every sub-block. +fn q2_requantize(x: &[f32], y: &[u8], l: &mut [u8; 256]) { + let d = h(y, 80); + let m = h(y, 82); for k in 0..16 { - y[k] = ls[k] | (lm[k] << 4); let ds = d * (y[k] & 15) as f32; if ds == 0.0 { continue; @@ -146,6 +153,18 @@ fn q2k_requantize(x: &[f32], y: &mut [u8], levels: [&[u8; 16]; 2], dm: (f32, f32 } } } +pub(super) fn q2k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) { + let sigma = sum_squares(x) / 256.0; + let mut f = q2_fit_blocks(x, qw, sigma); + let (ls, lm, d, m) = q2_scale_codes(&f, qw.is_some()); + put_h(y, 80, d); + put_h(y, 82, m); + for k in 0..16 { + y[k] = ls[k] | (lm[k] << 4); + } + q2_requantize(x, y, &mut f.l); + pack_k2(&f.l, &mut y[16..80]); +} pub(super) fn pack_scale3(l: &[i8; 16], y: &mut [u8]) { y.fill(0); for j in 0..16 { @@ -162,81 +181,89 @@ pub(super) fn unpack_scale3(y: &[u8], j: usize) -> i32 { let low = if j < 8 { y[j] & 15 } else { y[j - 8] >> 4 }; (low | (((y[8 + j % 4] >> (2 * (j / 4))) & 3) << 4)) as i32 - 32 } -pub(super) fn q3k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) { - let mut l = [0i8; 256]; - let (scales, sw, maxs) = q3k_search(x, &mut l, qw); - let mut ls = [0i8; 16]; - let d = q3k_scale(&scales, &sw, maxs, &mut ls, qw.is_some()); - pack_scale3(&ls, &mut y[96..108]); - put_h(y, 108, d); - let d = h(y, 108); - q3k_requantize(x, y, d, &mut l); - q3k_pack(y, &mut l); +/// The sixteen 16-element sub-block scales of a Q3_K block, their weight sums and the largest-magnitude scale. +struct Q3Fit { + l: [i8; 256], + scales: [f32; 16], + sw: [f32; 16], + maxs: f32, } -/// The scale of each 16-value block (levels of that fit in `l`), the block weights, and the scale of largest magnitude. -fn q3k_search(x: &[f32], l: &mut [i8; 256], qw: Option<&[f32]>) -> ([f32; 16], [f32; 16], f32) { - let mut scales = [0.0; 16]; - let mut sw = scales; - let mut maxs = 0.0; +/// The scale of one sub-block and the sum of its weights (zero without an imatrix). +fn q3_subfit(xb: &[f32], qw: Option<&[f32]>, k: usize, sigma: f32, l: &mut [i8]) -> (f32, f32) { + let Some(q) = qw else { + return (q3(xb, l), 0.0); + }; + let w: [f32; 16] = std::array::from_fn(|j| q[k * 16 + j] * (sigma + xb[j] * xb[j]).sqrt()); + let mut sw = 0.0; + for &v in &w { + sw += v; + } + (qx(xb, 4, l, 1, Some(&w)), sw) +} +fn q3k_fit_blocks(x: &[f32], qw: Option<&[f32]>, sigma: f32) -> Q3Fit { + let mut f = Q3Fit { l: [0; 256], scales: [0.0; 16], sw: [0.0; 16], maxs: 0.0 }; let mut amax = 0.0; - let sigma = 2.0 * sum_sq(x) / 256.0; for k in 0..16 { let xb = &x[k * 16..k * 16 + 16]; - scales[k] = if let Some(q) = qw { - let w: [f32; 16] = std::array::from_fn(|j| q[k * 16 + j] * (sigma + xb[j] * xb[j]).sqrt()); - for &v in &w { - sw[k] += v; - } - qx(xb, 4, &mut l[k * 16..k * 16 + 16], 1, Some(&w)) - } else { - q3(xb, &mut l[k * 16..k * 16 + 16]) - }; - if scales[k].abs() > amax { - amax = scales[k].abs(); - maxs = scales[k]; + (f.scales[k], f.sw[k]) = q3_subfit(xb, qw, k, sigma, &mut f.l[k * 16..k * 16 + 16]); + if f.scales[k].abs() > amax { + amax = f.scales[k].abs(); + f.maxs = f.scales[k]; } } - (scales, sw, maxs) + f } -/// The super-block scale; the 6-bit block scale levels go to `ls`. -fn q3k_scale(scales: &[f32; 16], sw: &[f32; 16], maxs: f32, ls: &mut [i8; 16], weighted: bool) -> f32 { - if weighted { - return qx(scales, 32, ls, 1, Some(sw)); - } - if maxs == 0.0 { - return 0.0; - } - let inv = -32.0 / maxs; - for k in 0..16 { - ls[k] = (nearest(inv * scales[k]).clamp(-32, 31) + 32) as i8; - } - 1.0 / inv +/// The 6-bit scale codes of the sixteen sub-blocks and the super-block scale. +fn q3k_scale_codes(f: &Q3Fit, weighted: bool) -> ([i8; 16], f32) { + let mut ls = [0i8; 16]; + let d = if weighted { + qx(&f.scales, 32, &mut ls, 1, Some(&f.sw)) + } else if f.maxs != 0.0 { + let inv = -32.0 / f.maxs; + for k in 0..16 { + ls[k] = (nearest(inv * f.scales[k]).clamp(-32, 31) + 32) as i8; + } + 1.0 / inv + } else { + 0.0 + }; + (ls, d) } -/// Requantizes the values against the stored (rounded) super-block scale `d` and the packed block scales in y. -fn q3k_requantize(x: &[f32], y: &[u8], d: f32, l: &mut [i8; 256]) { +/// Re-derives the levels against the stored (half-rounded) scale of every sub-block. +fn q3k_requantize(x: &[f32], y: &[u8], l: &mut [i8; 256]) { + let d = h(y, 108); for k in 0..16 { let ds = d * unpack_scale3(&y[96..108], k) as f32; - if ds == 0.0 { - continue; - } - for j in 0..16 { - l[k * 16 + j] = (nearest(x[k * 16 + j] / ds).clamp(-4, 3) + 4) as i8; + if ds != 0.0 { + for j in 0..16 { + l[k * 16 + j] = (nearest(x[k * 16 + j] / ds).clamp(-4, 3) + 4) as i8; + } } } } -/// High bits into y[..32], the low two bits into y[32..96]. -fn q3k_pack(y: &mut [u8], l: &mut [i8; 256]) { +/// The high bit of every level goes to the 32-byte mask, the low two bits are packed like Q2_K. +fn q3k_pack_levels(l: &[i8; 256], y: &mut [u8]) { y[..32].fill(0); let mut low = [0u8; 256]; for j in 0..256 { - if l[j] > 3 { + let mut level = l[j]; + if level > 3 { y[j % 32] |= 1 << (j / 32); - l[j] -= 4; + level -= 4; } - low[j] = l[j] as u8; + low[j] = level as u8; } pack_k2(&low, &mut y[32..96]); } +pub(super) fn q3k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) { + let sigma = 2.0 * sum_squares(x) / 256.0; + let mut f = q3k_fit_blocks(x, qw, sigma); + let (ls, d) = q3k_scale_codes(&f, qw.is_some()); + pack_scale3(&ls, &mut y[96..108]); + put_h(y, 108, d); + q3k_requantize(x, y, &mut f.l); + q3k_pack_levels(&f.l, y); +} pub(super) fn pack_scale4(ls: &[u8; 8], lm: &[u8; 8], y: &mut [u8]) { for j in 0..8 { let s = ls[j]; diff --git a/crates/native-cpu-expert/src/rust_weight_quant/iq4_fn.rs b/crates/native-cpu-expert/src/rust_weight_quant/iq4_fn.rs index 631fda41..4ae39be1 100644 --- a/crates/native-cpu-expert/src/rust_weight_quant/iq4_fn.rs +++ b/crates/native-cpu-expert/src/rust_weight_quant/iq4_fn.rs @@ -1,62 +1,48 @@ //! Moved out of the parent module by STRA-338: fn iq4, fn row_without_iq. -use super::nearest_fn::sum_sq; #[allow(unused_imports)] use super::*; -pub(super) fn iq4(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, ntry: i32) { - let nb = x.len() / 32; - let mut sigma = sum_sq(x); - sigma *= 2.0 / x.len() as f32; - let mut l = [0u8; 256]; - y.fill(0); - put_h(y, 0, 0.0); - let (scales, maxs) = iq4_search(x, &mut l, qw, (sigma, ntry)); - let head = if kind == Kind::Iq4Xs { - iq4_xs_scales(x, y, &mut l, &scales[..nb], maxs) - } else { - iq4_nl_scale(x, y, &mut l, scales[0], ntry) - }; - for k in 0..nb { - pack4(&l[k * 32..k * 32 + 32], &mut y[head + k * 16..head + (k + 1) * 16]); - } +const IQ4_VALUES: &[i8; 16] = &super::super::rust_codebooks::KVALUES_IQ4NL; + +/// The levels of up to eight 32-element blocks with their scales and the scale of largest magnitude. +struct Iq4Fit { + l: [u8; 256], + scales: [f32; 8], + maxs: f32, } -/// The scale of each 32-value block (levels of that fit in `l`) and the scale of largest magnitude; -/// `fit` is (sigma, ntry). -fn iq4_search(x: &[f32], l: &mut [u8; 256], qw: Option<&[f32]>, fit: (f32, i32)) -> ([f32; 8], f32) { - let (sigma, ntry) = fit; - let mut scales = [0.0; 8]; - let (mut maxs, mut amax) = (0.0, 0.0); - for k in 0..x.len() / 32 { - let xb = &x[k * 32..k * 32 + 32]; - let w: [f32; 32] = std::array::from_fn(|j| { +fn iq4_weights(xb: &[f32], qw: Option<&[f32]>, k: usize, sigma: f32) -> [f32; 32] { + std::array::from_fn( + |j| { if let Some(q) = qw { q[k * 32 + j] * (sigma + xb[j] * xb[j]).sqrt() } else { xb[j] * xb[j] } - }); - scales[k] = iq4_block(xb, &w, &mut l[k * 32..k * 32 + 32], ntry); - if scales[k].abs() > amax { - amax = scales[k].abs(); - maxs = scales[k]; - } - } - (scales, maxs) + }, + ) } -/// The best scale of one block among the 2 * ntry + 1 tried; 0 for an all-zero block, whose levels stay untouched. -fn iq4_block(xb: &[f32], w: &[f32; 32], lb: &mut [u8], ntry: i32) -> f32 { - let values = &super::super::rust_codebooks::KVALUES_IQ4NL; - let (a, max) = max_signed(xb); - if a < EPS { - return 0.0; - } - let d = if ntry > 0 { -max / values[0] as f32 } else { max / values[0] as f32 }; - let inv = 1.0 / d; +/// `sum(w*q*x)` and `sum(w*q*q)` of the codebook levels nearest to `inv * xb`. +fn iq4_sums(xb: &[f32], w: &[f32; 32], inv: f32) -> (f32, f32) { + let (mut sx, mut s2) = (0.0, 0.0); for j in 0..32 { - lb[j] = best_iq4(inv * xb[j]); + let q = IQ4_VALUES[best_iq4(inv * xb[j]) as usize] as f32; + sx += w[j] * q * xb[j]; + s2 += w[j] * q * q; } + (sx, s2) +} +fn iq4_assign_levels(xb: &[f32], inv: f32, l: &mut [u8]) { + for j in 0..32 { + l[j] = best_iq4(inv * xb[j]); + } +} +/// Scale of the first guess (levels written to `l`) improved by the `ntry` neighbouring inverse scales. +fn iq4_fit_block(xb: &[f32], w: &[f32; 32], max: f32, ntry: i32, l: &mut [u8]) -> f32 { + let mut d = if ntry > 0 { -max / IQ4_VALUES[0] as f32 } else { max / IQ4_VALUES[0] as f32 }; + let inv = 1.0 / d; + iq4_assign_levels(xb, inv, l); let (sx, s2) = iq4_sums(xb, w, inv); - let mut d = if s2 > 0.0 { sx / s2 } else { 0.0 }; + d = if s2 > 0.0 { sx / s2 } else { 0.0 }; let mut best = d * sx; for itry in -ntry..=ntry { - let inv = (itry as f32 + values[0] as f32) / max; + let inv = (itry as f32 + IQ4_VALUES[0] as f32) / max; let (sx, s2) = iq4_sums(xb, w, inv); if s2 > 0.0 && sx * sx > best * s2 { d = sx / s2; @@ -65,85 +51,90 @@ fn iq4_block(xb: &[f32], w: &[f32; 32], lb: &mut [u8], ntry: i32) -> f32 { } d } -/// The weighted sums (sum w*q*x, sum w*q*q) of the codebook values nearest to `inv * x`. -fn iq4_sums(xb: &[f32], w: &[f32; 32], inv: f32) -> (f32, f32) { - let values = &super::super::rust_codebooks::KVALUES_IQ4NL; - let (mut sx, mut s2) = (0.0, 0.0); - for j in 0..32 { - let q = values[best_iq4(inv * xb[j]) as usize] as f32; - sx += w[j] * q * xb[j]; - s2 += w[j] * q * q; +fn iq4_fit_blocks(x: &[f32], qw: Option<&[f32]>, sigma: f32, ntry: i32) -> Iq4Fit { + let mut f = Iq4Fit { l: [0; 256], scales: [0.0; 8], maxs: 0.0 }; + let mut amax = 0.0; + for k in 0..x.len() / 32 { + let xb = &x[k * 32..k * 32 + 32]; + let w = iq4_weights(xb, qw, k, sigma); + let (a, max) = max_signed(xb); + if a < EPS { + f.scales[k] = 0.0; + continue; + } + let d = iq4_fit_block(xb, &w, max, ntry, &mut f.l[k * 32..k * 32 + 32]); + f.scales[k] = d; + if d.abs() > amax { + amax = d.abs(); + f.maxs = d; + } } - (sx, s2) + f } -/// IQ4_XS: the 6-bit block scales (low four bits in y[4..8], high two in y[2..4]) and the levels against them; -/// the offset of the packed levels. -fn iq4_xs_scales(x: &[f32], y: &mut [u8], l: &mut [u8; 256], scales: &[f32], maxs: f32) -> usize { - let d = -maxs / 32.0; +/// Re-derives the levels of block `k` against the stored scale `ds`. +fn iq4_xs_levels(x: &[f32], l: &mut [u8; 256], k: usize, ds: f32) { + let di = if ds != 0.0 { 1.0 / ds } else { 0.0 }; + for j in 0..32 { + l[k * 32 + j] = best_iq4(di * x[k * 32 + j]); + } +} +fn iq4_xs_put_scale(y: &mut [u8], k: usize, code: u8) { + if k % 2 == 0 { + y[4 + k / 2] = code & 15; + } else { + y[4 + k / 2] |= (code & 15) << 4; + } +} +/// IQ4_XS header: the super-block scale, the 6-bit block scales and the levels re-derived against them. +fn iq4_xs_head(x: &[f32], y: &mut [u8], f: &mut Iq4Fit) -> usize { + let d = -f.maxs / 32.0; put_h(y, 0, d); let inv = if d != 0.0 { 1.0 / d } else { 0.0 }; let mut high = 0u16; - for (k, &scale) in scales.iter().enumerate() { - let s = nearest(inv * scale).clamp(-32, 31); - let ds = d * s as f32; - let di = if ds != 0.0 { 1.0 / ds } else { 0.0 }; - for j in 0..32 { - l[k * 32 + j] = best_iq4(di * x[k * 32 + j]); - } - let s = (s + 32) as u8; - if k % 2 == 0 { - y[4 + k / 2] = s & 15; - } else { - y[4 + k / 2] |= (s & 15) << 4; - } - high |= ((s >> 4) as u16) << (2 * k); + for k in 0..x.len() / 32 { + let s = nearest(inv * f.scales[k]).clamp(-32, 31); + iq4_xs_levels(x, &mut f.l, k, d * s as f32); + let code = (s + 32) as u8; + iq4_xs_put_scale(y, k, code); + high |= ((code >> 4) as u16) << (2 * k); } y[2..4].copy_from_slice(&high.to_le_bytes()); 8 } -/// IQ4_NL: the single scale; with `ntry > 0` the levels are redone against it. The offset of the packed levels. -fn iq4_nl_scale(x: &[f32], y: &mut [u8], l: &mut [u8; 256], scale: f32, ntry: i32) -> usize { - put_h(y, 0, scale); +/// IQ4_NL header: the single block scale; the levels are re-derived against it only for the searched fit. +fn iq4_nl_head(x: &[f32], y: &mut [u8], f: &mut Iq4Fit, ntry: i32) -> usize { + put_h(y, 0, f.scales[0]); if ntry > 0 { - let inv = if scale != 0.0 { 1.0 / scale } else { 0.0 }; + let inv = if f.scales[0] != 0.0 { 1.0 / f.scales[0] } else { 0.0 }; for j in 0..x.len() { - l[j] = best_iq4(inv * x[j]); + f.l[j] = best_iq4(inv * x[j]); } } 2 } -/// Reference/weighted rows sharing one imatrix vector per row, as ggml_quantize_chunk. -/// IQ lookup quantizers are registered by the separate pinned grid module. -pub(in super::super) fn row_without_iq( - kind: Kind, - x: &[f32], - y: &mut [u8], - qw: Option<&[f32]>, - reference_iq4: bool, -) -> Result { +pub(super) fn iq4(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, ntry: i32) { + let mut sigma = sum_squares(x); + sigma *= 2.0 / x.len() as f32; + y.fill(0); + put_h(y, 0, 0.0); + let mut f = iq4_fit_blocks(x, qw, sigma, ntry); + let head = if kind == Kind::Iq4Xs { iq4_xs_head(x, y, &mut f) } else { iq4_nl_head(x, y, &mut f, ntry) }; + for k in 0..x.len() / 32 { + pack4(&f.l[k * 32..k * 32 + 32], &mut y[head + k * 16..head + (k + 1) * 16]); + } +} +fn validate_row_shape(kind: Kind, x: &[f32], y: &[u8], qw: Option<&[f32]>) -> Result<()> { if kind.row_bytes(x.len())? != y.len() || qw.is_some_and(|q| q.len() != x.len()) { return Err(Error::Shape); } - let (q, b) = kind.block(); - let sigma = sum_sq(x) / x.len() as f32; - for (i, (x, y)) in x.chunks_exact(q).zip(y.chunks_exact_mut(b)).enumerate() { - let w = qw.map(|w| &w[i * q..(i + 1) * q]); - if !block_without_iq(kind, (x, y), w, sigma, reference_iq4) { - return Ok(false); - } - } - Ok(true) + Ok(()) } -/// Quantizes one block of a kind this module handles; false for a kind it does not (the IQ lookup quantizers). -/// `block` is (values, output). -fn block_without_iq( - kind: Kind, - block: (&[f32], &mut [u8]), - w: Option<&[f32]>, - sigma: f32, - reference_iq4: bool, -) -> bool { - let (x, y) = block; +/// Search width of the IQ4 scale: the reference IQ4_NL path takes none. +fn iq4_tries(kind: Kind, reference_iq4: bool) -> i32 { + if reference_iq4 && kind == Kind::Iq4Nl { -1 } else { 7 } +} +/// Quantizes one block of a non-IQ-grid kind; `false` when the kind belongs to the grid module. +fn quantize_block(kind: Kind, x: &[f32], y: &mut [u8], w: Option<&[f32]>, sigma: f32, reference_iq4: bool) -> bool { match kind { Kind::F32 | Kind::F16 @@ -161,12 +152,28 @@ fn block_without_iq( Kind::Q3K => q3k(x, y, w), Kind::Q4K | Kind::Q5K => q45k(kind == Kind::Q5K, x, y, w), Kind::Q6K => q6k(x, y, w), - Kind::Iq4Nl | Kind::Iq4Xs => iq4(kind, x, y, w, iq4_ntry(kind, reference_iq4)), + Kind::Iq4Nl | Kind::Iq4Xs => iq4(kind, x, y, w, iq4_tries(kind, reference_iq4)), _ => return false, } true } -/// Search width of the IQ4 quantizers: 7, or -1 for the reference IQ4_NL. -fn iq4_ntry(kind: Kind, reference_iq4: bool) -> i32 { - if reference_iq4 && kind == Kind::Iq4Nl { -1 } else { 7 } +/// Reference/weighted rows sharing one imatrix vector per row, as ggml_quantize_chunk. +/// IQ lookup quantizers are registered by the separate pinned grid module. +pub(in super::super) fn row_without_iq( + kind: Kind, + x: &[f32], + y: &mut [u8], + qw: Option<&[f32]>, + reference_iq4: bool, +) -> Result { + validate_row_shape(kind, x, y, qw)?; + let (q, b) = kind.block(); + let sigma = sum_squares(x) / x.len() as f32; + for (i, (x, y)) in x.chunks_exact(q).zip(y.chunks_exact_mut(b)).enumerate() { + let w = qw.map(|w| &w[i * q..(i + 1) * q]); + if !quantize_block(kind, x, y, w, sigma, reference_iq4) { + return Ok(false); + } + } + Ok(true) } diff --git a/crates/native-cpu-expert/src/rust_weight_quant/nearest_fn.rs b/crates/native-cpu-expert/src/rust_weight_quant/nearest_fn.rs index cfaa3989..88c40b66 100644 --- a/crates/native-cpu-expert/src/rust_weight_quant/nearest_fn.rs +++ b/crates/native-cpu-expert/src/rust_weight_quant/nearest_fn.rs @@ -14,48 +14,6 @@ pub(super) fn put_h(y: &mut [u8], at: usize, x: f32) { pub(super) fn h(y: &[u8], at: usize) -> f32 { half(u16::from_le_bytes([y[at], y[at + 1]])) } -/// Sum of squares, accumulated left to right in f32. -pub(super) fn sum_sq(x: &[f32]) -> f32 { - let mut sum = 0.0; - for &v in x { - sum += v * v; - } - sum -} -/// Per-block (scale, minimum) of a K-quant search, the block weights, and the largest scale and minimum. -pub(super) struct Search { - pub(super) scales: [f32; N], - pub(super) mins: [f32; N], - pub(super) sw: [f32; N], - maxs: f32, - maxm: f32, -} -impl Search { - pub(super) fn new() -> Self { - Search { scales: [0.0; N], mins: [0.0; N], sw: [0.0; N], maxs: 0.0, maxm: 0.0 } - } - /// Stores the fit of block `k` and tracks the maxima. - pub(super) fn record(&mut self, k: usize, d: f32, m: f32) { - self.scales[k] = d; - self.mins[k] = m; - if d > self.maxs { - self.maxs = d; - } - if m > self.maxm { - self.maxm = m; - } - } - /// The 1/max factors for rounding scales and minima to `levels` steps (0 when the maximum is not positive). - pub(super) fn factors(&self, levels: f32) -> (f32, f32) { - let si = if self.maxs > 0.0 { levels / self.maxs } else { 0.0 }; - let mi = if self.maxm > 0.0 { levels / self.maxm } else { 0.0 }; - (si, mi) - } - /// maxs / levels and maxm / levels. - pub(super) fn steps(&self, levels: f32) -> (f32, f32) { - (self.maxs / levels, self.maxm / levels) - } -} pub(super) fn max_signed(x: &[f32]) -> (f32, f32) { let (mut a, mut v) = (0.0, 0.0); for &f in x { @@ -66,6 +24,14 @@ pub(super) fn max_signed(x: &[f32]) -> (f32, f32) { } (a, v) } +/// Sum of squares in element order. +pub(in super::super) fn sum_squares(x: &[f32]) -> f32 { + let mut sum = 0.0; + for &v in x { + sum += v * v; + } + sum +} pub(super) fn weight(x: f32, rmse: i32, qw: Option) -> f32 { qw.unwrap_or_else(|| match rmse { 1 => x * x, @@ -74,6 +40,59 @@ pub(super) fn weight(x: f32, rmse: i32, qw: Option) -> f32 { _ => x.abs().sqrt(), }) } +/// The running weighted sums `sum(w*x*q)` and `sum(w*q*q)` of a level assignment. +#[derive(Clone, Copy)] +pub(super) struct Sums { + pub(super) sx: f32, + pub(super) s2: f32, +} +/// One signed-level fit: the block, the largest level magnitude, the weighting rule and the optional weights. +struct SignedFit<'a> { + x: &'a [f32], + nmax: i32, + rmse: i32, + qw: Option<&'a [f32]>, +} +impl SignedFit<'_> { + fn level(&self, inv: f32, i: usize) -> i32 { + nearest(inv * self.x[i]).clamp(-self.nmax, self.nmax - 1) + } + fn weight_at(&self, i: usize) -> f32 { + weight(self.x[i], self.rmse, self.qw.map(|w| w[i])) + } + fn assign_levels(&self, inv: f32, l: &mut [i8]) { + for i in 0..self.x.len() { + l[i] = (self.nmax + self.level(inv, i)) as i8; + } + } + fn sums(&self, inv: f32) -> Sums { + let (mut sx, mut s2) = (0.0, 0.0); + for i in 0..self.x.len() { + let q = self.level(inv, i); + let w = self.weight_at(i); + sx += w * self.x[i] * q as f32; + s2 += w * q as f32 * q as f32; + } + Sums { sx, s2 } + } + fn search_scale(&self, l: &mut [i8], max: f32, start: f32, first: Sums) -> f32 { + let mut scale = start; + let mut best = scale * first.sx; + for is in -9..=9 { + if is == 0 { + continue; + } + let inv = -(self.nmax as f32 + 0.1 * is as f32) / max; + let Sums { sx, s2 } = self.sums(inv); + if s2 > 0.0 && sx * sx > best * s2 { + self.assign_levels(inv, l); + scale = sx / s2; + best = scale * sx; + } + } + scale + } +} pub(in super::super) fn qx(x: &[f32], nmax: i32, l: &mut [i8], mut rmse: i32, qw: Option<&[f32]>) -> f32 { let (amax, max) = max_signed(x); if amax < EPS { @@ -82,60 +101,28 @@ pub(in super::super) fn qx(x: &[f32], nmax: i32, l: &mut [i8], mut rmse: i32, qw } let inv = -(nmax as f32) / max; if rmse == 0 { - qx_levels(x, nmax, l, inv); - return 1.0 / inv; + return qx_direct(x, nmax, l, inv); } let early = rmse < 0; if early { rmse = -rmse; } - qx_levels(x, nmax, l, inv); - let (sx, s2) = qx_sums(x, nmax, inv, rmse, qw); - let scale = if s2 != 0.0 { sx / s2 } else { 0.0 }; + let fit = SignedFit { x, nmax, rmse, qw }; + fit.assign_levels(inv, l); + let first = fit.sums(inv); + let scale = if first.s2 != 0.0 { first.sx / first.s2 } else { 0.0 }; if early { - return if s2 > 0.0 { 0.5 * (scale + 1.0 / inv) } else { 1.0 / inv }; + return if first.s2 > 0.0 { 0.5 * (scale + 1.0 / inv) } else { 1.0 / inv }; } - qx_search(x, nmax, l, (max, rmse, qw), scale, sx) + fit.search_scale(l, max, scale, first) } -/// The levels `nmax + clamp(round(inv * x))` as stored in `l`. -fn qx_levels(x: &[f32], nmax: i32, l: &mut [i8], inv: f32) { +fn qx_direct(x: &[f32], nmax: i32, l: &mut [i8], inv: f32) -> f32 { for (&x, l) in x.iter().zip(l) { *l = (nmax + nearest(inv * x).clamp(-nmax, nmax - 1)) as i8; } + 1.0 / inv } -/// The weighted sums (sum w*x*q, sum w*q*q) of the levels at `inv`. -fn qx_sums(x: &[f32], nmax: i32, inv: f32, rmse: i32, qw: Option<&[f32]>) -> (f32, f32) { - let (mut sx, mut s2) = (0.0, 0.0); - for i in 0..x.len() { - let q = nearest(inv * x[i]).clamp(-nmax, nmax - 1); - let w = weight(x[i], rmse, qw.map(|w| w[i])); - sx += w * x[i] * q as f32; - s2 += w * q as f32 * q as f32; - } - (sx, s2) -} -/// Tries the 18 other scales -(nmax + 0.1 * is) / max and keeps the levels of the best fit; `fit` is (max, rmse, qw). -fn qx_search(x: &[f32], nmax: i32, l: &mut [i8], fit: (f32, i32, Option<&[f32]>), mut scale: f32, sx: f32) -> f32 { - let (max, rmse, qw) = fit; - let mut best = scale * sx; - for is in (-9..=9).filter(|&is| is != 0) { - let inv = -(nmax as f32 + 0.1 * is as f32) / max; - let (sx, s2) = qx_sums(x, nmax, inv, rmse, qw); - if s2 > 0.0 && sx * sx > best * s2 { - qx_levels(x, nmax, l, inv); - scale = sx / s2; - best = scale * sx; - } - } - scale -} -pub(super) fn q3(x: &[f32], l: &mut [i8]) -> f32 { - let (a, max) = max_signed(x); - if a < EPS { - l.fill(0); - return 0.0; - } - let inv = -4.0 / max; +fn q3_start(x: &[f32], l: &mut [i8], inv: f32) -> Sums { let (mut sx, mut s2) = (0.0, 0.0); for i in 0..x.len() { let q = nearest(inv * x[i]).clamp(-4, 3); @@ -144,138 +131,188 @@ pub(super) fn q3(x: &[f32], l: &mut [i8]) -> f32 { sx += w * x[i] * q as f32; s2 += w * q as f32 * q as f32; } - for _ in 0..5 { - if q3_pass(x, l, &mut sx, &mut s2) == 0 { - break; + Sums { sx, s2 } +} +/// Moves element `i` to its best level when that raises the objective; returns the new sums when it moved. +fn q3_move(x: &[f32], l: &mut [i8], i: usize, s: Sums) -> Option { + let w = x[i] * x[i]; + let mut tx = s.sx - w * x[i] * l[i] as f32; + if tx > 0.0 { + let mut t2 = s.s2 - w * l[i] as f32 * l[i] as f32; + let q = nearest(x[i] * t2 / tx).clamp(-4, 3); + if q != l[i] as i32 { + tx += w * x[i] * q as f32; + t2 += w * q as f32 * q as f32; + if t2 > 0.0 && tx * tx * s.s2 > s.sx * s.sx * t2 { + l[i] = q as i8; + return Some(Sums { sx: tx, s2: t2 }); + } } } - for l in l { - *l += 4; - } - if s2 > 0.0 { sx / s2 } else { 0.0 } + None } -/// One sweep moving single levels while the fit improves; the number of levels changed. -fn q3_pass(x: &[f32], l: &mut [i8], sx: &mut f32, s2: &mut f32) -> i32 { +fn q3_pass(x: &[f32], l: &mut [i8], mut s: Sums) -> (Sums, usize) { let mut changed = 0; for i in 0..x.len() { - if let Some((q, tx, t2)) = q3_move(x[i], l[i], *sx, *s2) { - l[i] = q; - *sx = tx; - *s2 = t2; + if let Some(moved) = q3_move(x, l, i, s) { + s = moved; changed += 1; } } - changed + (s, changed) } -/// The new level and sums when changing the level `li` of `xi` improves the fit. -#[allow(clippy::neg_cmp_op_on_partial_ord)] -fn q3_move(xi: f32, li: i8, sx: f32, s2: f32) -> Option<(i8, f32, f32)> { - let w = xi * xi; - let mut tx = sx - w * xi * li as f32; - if !(tx > 0.0) { - return None; +fn q3_refine(x: &[f32], l: &mut [i8], mut s: Sums) -> Sums { + for _ in 0..5 { + let (next, changed) = q3_pass(x, l, s); + s = next; + if changed == 0 { + break; + } } - let mut t2 = s2 - w * li as f32 * li as f32; - let q = nearest(xi * t2 / tx).clamp(-4, 3); - if q == li as i32 { - return None; - } - tx += w * xi * q as f32; - t2 += w * q as f32 * q as f32; - if t2 > 0.0 && tx * tx * s2 > sx * sx * t2 { Some((q as i8, tx, t2)) } else { None } + s } -/// qkx2/qkx3 have the same search tree; qkx3 differs in max<=min and implicit x^2 weights. -pub(super) fn qkx(x: &[f32], nmax: i32, w: &[f32], l: &mut [u8], p: Qkx) -> (f32, f32) { - let (mut min, max, sw, sx) = qkx_stats(x, w); - if (p.third && max <= min) || (!p.third && max == min) { +pub(super) fn q3(x: &[f32], l: &mut [i8]) -> f32 { + let (a, max) = max_signed(x); + if a < EPS { l.fill(0); - return (0.0, -min); + return 0.0; } - let inv = nmax as f32 / (max - min); - let mut scale = 1.0 / inv; - qkx_fill(x, l, nmax, inv, min); - let mut best = qkx_error(x, w, l, scale, min, p.mad); - let mut aux = [0u8; 32]; - for is in 0..=p.nstep { - let inv = (p.rmin + p.rdelta * is as f32 + nmax as f32) / (max - min); - let (sl, sl2, sxl) = qkx_trial(x, w, &mut aux, nmax, inv, min); - let det = sw * sl2 - sl * sl; - if det > 0.0 { - let (ds, dm) = qkx_solve([sw, sx, sl, sl2, sxl], det); - let error = qkx_error(x, w, &aux, ds, dm, p.mad); + let inv = -4.0 / max; + let start = q3_start(x, l, inv); + let s = q3_refine(x, l, start); + for l in l { + *l += 4; + } + if s.s2 > 0.0 { s.sx / s.s2 } else { 0.0 } +} +/// The block to fit with `qkx`: values, weights, the largest level and whether the error is absolute or squared. +struct MinMaxFit<'a> { + x: &'a [f32], + w: &'a [f32], + nmax: i32, + mad: bool, +} +/// Weighted sums of one level trial: `sum(w*q)`, `sum(w*q*q)` and `sum(w*q*x)`. +struct TrialSums { + sl: f32, + sl2: f32, + sxl: f32, +} +impl MinMaxFit<'_> { + fn penalty(&self, diff: f32) -> f32 { + if self.mad { diff.abs() } else { diff * diff } + } + /// Smallest value, largest value, `sum(w)` and `sum(w*x)`. + fn scan(&self) -> (f32, f32, f32, f32) { + let (x, w) = (self.x, self.w); + let (mut min, mut max) = (x[0], x[0]); + let (mut sw, mut sx) = (w[0], w[0] * x[0]); + for i in 1..x.len() { + if x[i] < min { + min = x[i]; + } + if x[i] > max { + max = x[i]; + } + sw += w[i]; + sx += w[i] * x[i]; + } + (min, max, sw, sx) + } + /// Writes the plain levels for `inv` and returns the error of that assignment. + fn assign_levels(&self, l: &mut [u8], inv: f32, scale: f32, min: f32) -> f32 { + let (x, w) = (self.x, self.w); + let mut best = 0.0; + for i in 0..x.len() { + l[i] = nearest(inv * (x[i] - min)).clamp(0, self.nmax) as u8; + let diff = scale * l[i] as f32 + min - x[i]; + best += w[i] * self.penalty(diff); + } + best + } + fn trial_levels(&self, aux: &mut [u8], inv: f32, min: f32) -> TrialSums { + let (x, w) = (self.x, self.w); + let (mut sl, mut sl2, mut sxl) = (0.0, 0.0, 0.0); + for i in 0..x.len() { + let q = nearest(inv * (x[i] - min)).clamp(0, self.nmax); + aux[i] = q as u8; + sl += w[i] * q as f32; + sl2 += w[i] * q as f32 * q as f32; + sxl += w[i] * q as f32 * x[i]; + } + TrialSums { sl, sl2, sxl } + } + fn trial_error(&self, aux: &[u8], ds: f32, dm: f32) -> f32 { + let (x, w) = (self.x, self.w); + let mut error = 0.0; + for i in 0..x.len() { + let diff = ds * aux[i] as f32 + dm - x[i]; + error += w[i] * self.penalty(diff); + } + error + } +} +/// Least-squares scale and minimum of a level trial, or `None` when the system is singular. +fn solve_trial(sw: f32, sx: f32, t: &TrialSums) -> Option<(f32, f32)> { + let det = sw * t.sl2 - t.sl * t.sl; + if det > 0.0 { + let mut ds = (sw * t.sxl - sx * t.sl) / det; + let mut dm = (t.sl2 * sx - t.sl * t.sxl) / det; + if dm > 0.0 { + dm = 0.0; + ds = t.sxl / t.sl2; + } + Some((ds, dm)) + } else { + None + } +} +/// The inverse-scale trials of `qkx`: first offset, step and count. +struct Steps { + rmin: f32, + rdelta: f32, + nstep: i32, +} +impl MinMaxFit<'_> { + fn search(&self, l: &mut [u8], steps: Steps, third: bool) -> (f32, f32) { + let (mut min, max, sw, sx) = self.scan(); + if min > 0.0 { + min = 0.0; + } + if (third && max <= min) || (!third && max == min) { + l.fill(0); + return (0.0, -min); + } + let inv = self.nmax as f32 / (max - min); + let mut scale = 1.0 / inv; + let mut best = self.assign_levels(l, inv, scale, min); + let mut aux = [0u8; 32]; + for is in 0..=steps.nstep { + let inv = (steps.rmin + steps.rdelta * is as f32 + self.nmax as f32) / (max - min); + let trial = self.trial_levels(&mut aux, inv, min); + let Some((ds, dm)) = solve_trial(sw, sx, &trial) else { continue }; + let error = self.trial_error(&aux, ds, dm); if error < best { - l.copy_from_slice(&aux[..x.len()]); + l.copy_from_slice(&aux[..self.x.len()]); best = error; scale = ds; min = dm; } } - } - (scale, -min) -} -/// The search parameters of qkx: the first step offset and the step size, the number of steps, whether the error is -/// absolute (not squared), and the qkx3 variant. -#[derive(Clone, Copy)] -pub(super) struct Qkx { - pub(super) rmin: f32, - pub(super) rdelta: f32, - pub(super) nstep: i32, - pub(super) mad: bool, - pub(super) third: bool, -} -impl Qkx { - /// The importance-weighted search of the imatrix quantizers (qkx3). - pub(super) const WEIGHTED: Qkx = Qkx { rmin: -0.9, rdelta: 0.05, nstep: 36, mad: false, third: true }; -} -/// (min clamped to <= 0, max, sum w, sum w*x) of the block. -fn qkx_stats(x: &[f32], w: &[f32]) -> (f32, f32, f32, f32) { - let (mut min, mut max) = (x[0], x[0]); - let (mut sw, mut sx) = (w[0], w[0] * x[0]); - for i in 1..x.len() { - if x[i] < min { - min = x[i]; - } - if x[i] > max { - max = x[i]; - } - sw += w[i]; - sx += w[i] * x[i]; - } - if min > 0.0 { - min = 0.0; - } - (min, max, sw, sx) -} -fn qkx_fill(x: &[f32], l: &mut [u8], nmax: i32, inv: f32, min: f32) { - for i in 0..x.len() { - l[i] = nearest(inv * (x[i] - min)).clamp(0, nmax) as u8; + (scale, -min) } } -/// Weighted error of the levels `q` against `x` under the affine map `scale * q + min`. -fn qkx_error(x: &[f32], w: &[f32], q: &[u8], scale: f32, min: f32, mad: bool) -> f32 { - let mut error = 0.0; - for i in 0..x.len() { - let diff = scale * q[i] as f32 + min - x[i]; - error += w[i] * if mad { diff.abs() } else { diff * diff }; - } - error -} -/// Quantizes into `aux` at `inv`; the sums (sum w*q, sum w*q*q, sum w*q*x). -fn qkx_trial(x: &[f32], w: &[f32], aux: &mut [u8; 32], nmax: i32, inv: f32, min: f32) -> (f32, f32, f32) { - let (mut sl, mut sl2, mut sxl) = (0.0, 0.0, 0.0); - for i in 0..x.len() { - let q = nearest(inv * (x[i] - min)).clamp(0, nmax); - aux[i] = q as u8; - sl += w[i] * q as f32; - sl2 += w[i] * q as f32 * q as f32; - sxl += w[i] * q as f32 * x[i]; - } - (sl, sl2, sxl) -} -/// Scale and (non-positive) minimum of the least-squares fit; `sums` is [sw, sx, sl, sl2, sxl]. -fn qkx_solve(sums: [f32; 5], det: f32) -> (f32, f32) { - let [sw, sx, sl, sl2, sxl] = sums; - let ds = (sw * sxl - sx * sl) / det; - let dm = (sl2 * sx - sl * sxl) / det; - if dm > 0.0 { (sxl / sl2, 0.0) } else { (ds, dm) } +/// qkx2/qkx3 have the same search tree; qkx3 differs in max<=min and implicit x^2 weights. +pub(super) fn qkx( + x: &[f32], + nmax: i32, + w: &[f32], + l: &mut [u8], + rmin: f32, + rdelta: f32, + nstep: i32, + mad: bool, + third: bool, +) -> (f32, f32) { + MinMaxFit { x, w, nmax, mad }.search(l, Steps { rmin, rdelta, nstep }, third) } diff --git a/crates/native-cpu-expert/src/rust_weight_quant/q45k_fn.rs b/crates/native-cpu-expert/src/rust_weight_quant/q45k_fn.rs index c24d210d..306e764a 100644 --- a/crates/native-cpu-expert/src/rust_weight_quant/q45k_fn.rs +++ b/crates/native-cpu-expert/src/rust_weight_quant/q45k_fn.rs @@ -1,72 +1,74 @@ //! Moved out of the parent module by STRA-338: fn q45k, fn q6k, fn best_iq4. -use super::nearest_fn::{Qkx, Search, sum_sq}; #[allow(unused_imports)] use super::*; -pub(super) fn q45k(five: bool, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) { - let nmax = if five { 31 } else { 15 }; - let mut l = [0u8; 256]; - let search = q45k_search(five, x, &mut l, qw); - // The sigma.sqrt() of the weighted implementation's no-imatrix branch is not used: public - // quantize_q4/5_K selects reference when qw=None, exactly as pinned GGML. - let (ls, lm, d, m) = q45k_scales(&search, qw.is_some()); - pack_scale4(&ls, &lm, &mut y[4..16]); - put_h(y, 0, d); - put_h(y, 2, m); - q45k_requantize(x, y, nmax, &mut l); - q45k_pack(five, y, &l); +/// The eight 32-element sub-block fits of a Q4_K / Q5_K block: scales, minimums, weight sums and their maxima. +struct Subfits { + l: [u8; 256], + scales: [f32; 8], + mins: [f32; 8], + sw: [f32; 8], + maxs: f32, + maxm: f32, } -/// Best (scale, minimum) of each 32-value block, with the levels of that fit in `l`. -fn q45k_search(five: bool, x: &[f32], l: &mut [u8; 256], qw: Option<&[f32]>) -> Search<8> { +/// The weights of one sub-block: the imatrix scaled by the block energy, or the unweighted magnitude rule. +fn q45_weights(xb: &[f32], qw: Option<&[f32]>, k: usize, sigma: f32) -> [f32; 32] { + if let Some(q) = qw { + std::array::from_fn(|j| q[k * 32 + j] * (sigma + xb[j] * xb[j]).sqrt()) + } else { + let avg = (sum_squares(xb) / 32.0).sqrt(); + std::array::from_fn(|j| avg + xb[j].abs()) + } +} +fn q45_subfit(xb: &[f32], nmax: i32, five: bool, w: &[f32; 32], l: &mut [u8], weighted: bool) -> (f32, f32) { + if weighted { + qkx(xb, nmax, w, l, -0.9, 0.05, 36, false, true) + } else { + let (rmin, nstep) = if five { (-0.5, 15) } else { (-1.0, 20) }; + qkx(xb, nmax, w, l, rmin, 0.1, nstep, false, false) + } +} +fn q45_fit_blocks(x: &[f32], qw: Option<&[f32]>, five: bool, sigma: f32) -> Subfits { let nmax = if five { 31 } else { 15 }; - let sigma = 2.0 * sum_sq(x) / 256.0; - let mut s = Search::<8>::new(); - let plain = Qkx { - rmin: if five { -0.5 } else { -1.0 }, - rdelta: 0.1, - nstep: if five { 15 } else { 20 }, - mad: false, - third: false, - }; + let mut f = Subfits { l: [0; 256], scales: [0.0; 8], mins: [0.0; 8], sw: [0.0; 8], maxs: 0.0, maxm: 0.0 }; for k in 0..8 { let xb = &x[k * 32..k * 32 + 32]; - let w = q45k_weights(xb, qw.map(|q| &q[k * 32..k * 32 + 32]), sigma); + let w = q45_weights(xb, qw, k, sigma); for &v in &w { - s.sw[k] += v; + f.sw[k] += v; + } + let (d, m) = q45_subfit(xb, nmax, five, &w, &mut f.l[k * 32..k * 32 + 32], qw.is_some()); + f.scales[k] = d; + f.mins[k] = m; + if d > f.maxs { + f.maxs = d; + } + if m > f.maxm { + f.maxm = m; } - let lb = &mut l[k * 32..k * 32 + 32]; - let (d, m) = if qw.is_some() { qkx(xb, nmax, &w, lb, Qkx::WEIGHTED) } else { qkx(xb, nmax, &w, lb, plain) }; - s.record(k, d, m); } - s + f } -/// Importance weights of a block: imatrix * sqrt(sigma + x^2), or rms + |x| without an imatrix. -fn q45k_weights(xb: &[f32], qb: Option<&[f32]>, sigma: f32) -> [f32; 32] { - if let Some(q) = qb { - return std::array::from_fn(|j| q[j] * (sigma + xb[j] * xb[j]).sqrt()); - } - let avg = (sum_sq(xb) / 32.0).sqrt(); - std::array::from_fn(|j| avg + xb[j].abs()) -} -/// The 6-bit scale and minimum levels of the blocks and the super-block (d, m). -fn q45k_scales(s: &Search<8>, weighted: bool) -> ([u8; 8], [u8; 8], f32, f32) { +/// The 6-bit scale and minimum codes of the eight sub-blocks, with the super-block scale and minimum. +fn q45_scale_codes(f: &Subfits, weighted: bool) -> ([u8; 8], [u8; 8], f32, f32) { let mut ls = [0u8; 8]; let mut lm = ls; if weighted { - let (d, m) = (qp(&s.scales, 63, &mut ls, &s.sw), qp(&s.mins, 63, &mut lm, &s.sw)); + let d = qp(&f.scales, 63, &mut ls, &f.sw); + let m = qp(&f.mins, 63, &mut lm, &f.sw); return (ls, lm, d, m); } - let (si, mi) = s.factors(63.0); + let si = if f.maxs > 0.0 { 63.0 / f.maxs } else { 0.0 }; + let mi = if f.maxm > 0.0 { 63.0 / f.maxm } else { 0.0 }; for k in 0..8 { - ls[k] = (nearest(si * s.scales[k]) as u8).min(63); - lm[k] = (nearest(mi * s.mins[k]) as u8).min(63); + ls[k] = (nearest(si * f.scales[k]) as u8).min(63); + lm[k] = (nearest(mi * f.mins[k]) as u8).min(63); } - let (d, m) = s.steps(63.0); - (ls, lm, d, m) + (ls, lm, f.maxs / 63.0, f.maxm / 63.0) } -/// Requantizes the values against the stored (rounded) d and m and the packed scales in y. -fn q45k_requantize(x: &[f32], y: &[u8], nmax: i32, l: &mut [u8; 256]) { +/// Re-derives the levels against the stored (half-rounded) scale and minimum of every sub-block. +fn q45_requantize(x: &[f32], y: &[u8], l: &mut [u8; 256], nmax: i32) { let d = h(y, 0); let m = h(y, 2); for k in 0..8 { @@ -81,8 +83,7 @@ fn q45k_requantize(x: &[f32], y: &[u8], nmax: i32, l: &mut [u8; 256]) { } } } -/// Low nibbles from y[head], and for Q5_K the fifth bits in y[16..48]. -fn q45k_pack(five: bool, y: &mut [u8], l: &[u8; 256]) { +fn q45_pack_levels(l: &[u8; 256], y: &mut [u8], five: bool) { let head = if five { y[16..48].fill(0); 48 @@ -95,29 +96,31 @@ fn q45k_pack(five: bool, y: &mut [u8], l: &[u8; 256]) { let b = l[k * 64 + j + 32]; y[head + k * 32 + j] = (a & 15) | ((b & 15) << 4); if five { - y[16 + j] |= (u8::from(a > 15) << (2 * k)) | (u8::from(b > 15) << (2 * k + 1)); + if a > 15 { + y[16 + j] |= 1 << (2 * k); + } + if b > 15 { + y[16 + j] |= 2 << (2 * k); + } } } } } -pub(super) fn q6k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) { - let mut l = [0i8; 256]; - let (scales, maxs, amax) = q6k_search(x, &mut l, qw); - if amax < EPS { - y.fill(0); - put_h(y, 208, 0.0); - return; - } - let inv = -128.0 / maxs; - put_h(y, 208, 1.0 / inv); - for k in 0..16 { - y[192 + k] = nearest(inv * scales[k]).min(127) as i8 as u8; - } - q6k_requantize(x, y, &mut l); - q6k_pack(y, &l); +pub(super) fn q45k(five: bool, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) { + let nmax = if five { 31 } else { 15 }; + let sigma = 2.0 * sum_squares(x) / 256.0; + // The weighted implementation's no-imatrix branch is not used: public + // quantize_q4/5_K selects reference when qw=None, exactly as pinned GGML. + let mut f = q45_fit_blocks(x, qw, five, sigma); + let (ls, lm, d, m) = q45_scale_codes(&f, qw.is_some()); + pack_scale4(&ls, &lm, &mut y[4..16]); + put_h(y, 0, d); + put_h(y, 2, m); + q45_requantize(x, y, &mut f.l, nmax); + q45_pack_levels(&f.l, y, five); } -/// The scale of each 16-value block (levels of that fit in `l`), the scale of largest magnitude and that magnitude. -fn q6k_search(x: &[f32], l: &mut [i8; 256], qw: Option<&[f32]>) -> ([f32; 16], f32, f32) { +/// The sixteen 16-element sub-block scales of a Q6_K block, with the one of largest magnitude. +fn q6_fit_blocks(x: &[f32], qw: Option<&[f32]>, l: &mut [i8; 256]) -> ([f32; 16], f32, f32) { let mut scales = [0.0; 16]; let (mut maxs, mut amax) = (0.0, 0.0); for k in 0..16 { @@ -130,8 +133,7 @@ fn q6k_search(x: &[f32], l: &mut [i8; 256], qw: Option<&[f32]>) -> ([f32; 16], f } (scales, maxs, amax) } -/// Requantizes the values against the stored (rounded) super-block scale and the block scales in y[192..208]. -fn q6k_requantize(x: &[f32], y: &[u8], l: &mut [i8; 256]) { +fn q6_requantize(x: &[f32], y: &[u8], l: &mut [i8; 256]) { let d = h(y, 208); for k in 0..16 { let ds = d * y[192 + k] as i8 as f32; @@ -143,8 +145,7 @@ fn q6k_requantize(x: &[f32], y: &[u8], l: &mut [i8; 256]) { } } } -/// Low nibbles into y[..128], the high two bits into y[128..192]. -fn q6k_pack(y: &mut [u8], l: &[i8; 256]) { +fn q6_pack_levels(l: &[i8; 256], y: &mut [u8]) { for k in 0..2 { for j in 0..32 { let a = l[k * 128 + j] as u8; @@ -157,6 +158,22 @@ fn q6k_pack(y: &mut [u8], l: &[i8; 256]) { } } } +pub(super) fn q6k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) { + let mut l = [0i8; 256]; + let (scales, maxs, amax) = q6_fit_blocks(x, qw, &mut l); + if amax < EPS { + y.fill(0); + put_h(y, 208, 0.0); + return; + } + let inv = -128.0 / maxs; + put_h(y, 208, 1.0 / inv); + for k in 0..16 { + y[192 + k] = nearest(inv * scales[k]).min(127) as i8 as u8; + } + q6_requantize(x, y, &mut l); + q6_pack_levels(&l, y); +} pub(super) fn best_iq4(x: f32) -> u8 { let v = &super::super::rust_codebooks::KVALUES_IQ4NL; if x <= v[0] as f32 { diff --git a/crates/native-cpu-expert/src/rust_weight_quant/qp_fn.rs b/crates/native-cpu-expert/src/rust_weight_quant/qp_fn.rs index aeda31ca..17d8f21e 100644 --- a/crates/native-cpu-expert/src/rust_weight_quant/qp_fn.rs +++ b/crates/native-cpu-expert/src/rust_weight_quant/qp_fn.rs @@ -1,112 +1,131 @@ //! Moved out of the parent module by STRA-338: fn qp, fn pack4, fn small, fn e8_half, fn ue4, fn pack_ue4. -use super::nearest_fn::Qkx; #[allow(unused_imports)] use super::*; -pub(in super::super) fn qp(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32]) -> f32 { +/// Unsigned level fit of `x` against the weights `w`: the block and the largest level. +struct UnsignedFit<'a> { + x: &'a [f32], + w: &'a [f32], + nmax: i32, +} +impl UnsignedFit<'_> { + fn assign_levels(&self, inv: f32, l: &mut [u8]) { + for i in 0..self.x.len() { + l[i] = nearest(inv * self.x[i]) as u8; + } + } + fn error_at(&self, l: &[u8], scale: f32) -> f32 { + let mut best = 0.0; + for i in 0..self.x.len() { + let d = self.x[i] - scale * l[i] as f32; + best += self.w[i] * d * d; + } + best + } + fn trial_error(&self, ti: f32, ds: f32) -> f32 { + let mut err = 0.0; + for i in 0..self.x.len() { + let q = nearest(ti * self.x[i]).min(self.nmax); + let d = self.x[i] - ds * q as f32; + err += self.w[i] * d * d; + } + err + } + /// The inverse scale among the nine trials around `inv` with the smallest error. + fn search_inverse(&self, max: f32, start: f32, mut best: f32) -> f32 { + let mut inv = start; + for is in -4..=4 { + if is == 0 { + continue; + } + let ti = (0.1 * is as f32 + self.nmax as f32) / max; + let err = self.trial_error(ti, 1.0 / ti); + if err < best { + best = err; + inv = ti; + } + } + inv + } + fn assign_clamped(&self, inv: f32, l: &mut [u8]) -> Sums { + let (mut sx, mut s2) = (0.0, 0.0); + for i in 0..self.x.len() { + let q = nearest(inv * self.x[i]).min(self.nmax); + l[i] = q as u8; + sx += self.w[i] * self.x[i] * q as f32; + s2 += self.w[i] * q as f32 * q as f32; + } + Sums { sx, s2 } + } + /// Moves element `i` to its best level when that raises the objective; returns the new sums when it moved. + fn move_level(&self, l: &mut [u8], i: usize, s: Sums) -> Option { + let (x, w) = (self.x, self.w); + let mut tx = s.sx - w[i] * x[i] * l[i] as f32; + let mut t2 = s.s2 - w[i] * l[i] as f32 * l[i] as f32; + if tx > 0.0 && t2 > 0.0 { + let q = nearest(x[i] * t2 / tx).min(self.nmax); + if q != l[i] as i32 { + tx += w[i] * x[i] * q as f32; + t2 += w[i] * q as f32 * q as f32; + if tx * tx * s.s2 > s.sx * s.sx * t2 { + l[i] = q as u8; + return Some(Sums { sx: tx, s2: t2 }); + } + } + } + None + } + fn refine_pass(&self, l: &mut [u8], mut s: Sums) -> (Sums, usize) { + let mut changed = 0; + for i in 0..self.x.len() { + if let Some(moved) = self.move_level(l, i, s) { + s = moved; + changed += 1; + } + } + (s, changed) + } + fn refine_levels(&self, l: &mut [u8], mut s: Sums) -> Sums { + for _ in 0..5 { + let (next, changed) = self.refine_pass(l, s); + s = next; + if changed == 0 { + break; + } + } + s + } +} +fn largest_positive(x: &[f32]) -> f32 { let mut max = 0.0; for &x in x { if x > max { max = x; } } + max +} +pub(in super::super) fn qp(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32]) -> f32 { + let max = largest_positive(x); if max < EPS { l.fill(0); return 0.0; } - let inv = qp_scale(x, nmax, l, w, max); - qp_refine(x, nmax, l, w, inv) -} -/// The inverse scale among nmax/max and the eight 0.1-steps around it with the smallest weighted error; -/// `l` holds the levels of nmax/max on return. -fn qp_scale(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32], max: f32) -> f32 { - let mut inv = nmax as f32 / max; - for i in 0..x.len() { - l[i] = nearest(inv * x[i]) as u8; - } - let scale = 1.0 / inv; - let mut best = 0.0; - for i in 0..x.len() { - let d = x[i] - scale * l[i] as f32; - best += w[i] * d * d; - } - for is in (-4..=4).filter(|&is| is != 0) { - let ti = (0.1 * is as f32 + nmax as f32) / max; - let err = qp_error(x, nmax, w, ti); - if err < best { - best = err; - inv = ti; - } - } - inv -} -/// Weighted squared error of the levels at the inverse scale `ti`. -fn qp_error(x: &[f32], nmax: i32, w: &[f32], ti: f32) -> f32 { - let ds = 1.0 / ti; - let mut err = 0.0; - for i in 0..x.len() { - let q = nearest(ti * x[i]).min(nmax); - let d = x[i] - ds * q as f32; - err += w[i] * d * d; - } - err -} -/// Levels at `inv`, then up to five sweeps moving single levels while the fit improves; the scale. -fn qp_refine(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32], inv: f32) -> f32 { - let (mut sx, mut s2) = (0.0, 0.0); - for i in 0..x.len() { - let q = nearest(inv * x[i]).min(nmax); - l[i] = q as u8; - sx += w[i] * x[i] * q as f32; - s2 += w[i] * q as f32 * q as f32; - } - for _ in 0..5 { - let mut changed = 0; - for i in 0..x.len() { - if let Some((q, tx, t2)) = qp_move(x[i], w[i], l[i], nmax, (sx, s2)) { - l[i] = q; - sx = tx; - s2 = t2; - changed += 1; - } - } - if changed == 0 { - break; - } - } - if s2 > 0.0 { sx / s2 } else { 0.0 } -} -/// The new level and sums when changing the level `li` of `xi` (weight `wi`) improves the fit; `sums` is (sx, s2). -fn qp_move(xi: f32, wi: f32, li: u8, nmax: i32, sums: (f32, f32)) -> Option<(u8, f32, f32)> { - let (sx, s2) = sums; - let mut tx = sx - wi * xi * li as f32; - let mut t2 = s2 - wi * li as f32 * li as f32; - if !(tx > 0.0 && t2 > 0.0) { - return None; - } - let q = nearest(xi * t2 / tx).min(nmax); - if q == li as i32 { - return None; - } - tx += wi * xi * q as f32; - t2 += wi * q as f32 * q as f32; - if tx * tx * s2 > sx * sx * t2 { Some((q as u8, tx, t2)) } else { None } + let fit = UnsignedFit { x, w, nmax }; + let inv = nmax as f32 / max; + fit.assign_levels(inv, l); + let best = fit.error_at(l, 1.0 / inv); + let inv = fit.search_inverse(max, inv, best); + let start = fit.assign_clamped(inv, l); + let s = fit.refine_levels(l, start); + if s.s2 > 0.0 { s.sx / s.s2 } else { 0.0 } } pub(super) fn pack4(l: &[u8], y: &mut [u8]) { for j in 0..16 { y[j] = l[j] | (l[j + 16] << 4); } } -pub(super) fn small(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) { - match kind { - Kind::F32 | Kind::F16 | Kind::Bf16 => small_float(kind, x, y), - Kind::Q1Zero => small_q1(x, y), - Kind::Q2Zero => small_q2(x, y), - Kind::Q8Zero => small_q8(x, y), - _ => small_q45(kind, x, y, qw, sigma), - } -} fn small_float(kind: Kind, x: &[f32], y: &mut [u8]) { match kind { Kind::F32 => y.copy_from_slice(&x[0].to_le_bytes()), @@ -154,51 +173,28 @@ fn small_q8(x: &[f32], y: &mut [u8]) { y[j + 2] = (x[j] * inv).round() as i8 as u8; } } -/// What distinguishes Q4_0/Q4_1/Q5_0/Q5_1: a minimum is stored, five bits, and the top level. -#[derive(Clone, Copy)] -struct Shape { - is_min: bool, - five: bool, - nmax: i32, -} -fn small_q45(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) { - let five = matches!(kind, Kind::Q5Zero | Kind::Q5One); - let shape = Shape { is_min: matches!(kind, Kind::Q4One | Kind::Q5One), five, nmax: if five { 31 } else { 15 } }; +/// The 32 levels with their scale and minimum. +type SmallFit = ([u8; 32], f32, f32); +/// Weighted fit of a 32-element block; `is_min` selects the scale-plus-minimum form. +fn small_weighted(is_min: bool, five: bool, x: &[f32], qw: &[f32], sigma: f32) -> SmallFit { let mut l = [0u8; 32]; - let (d, m) = match qw { - Some(qw) => small_weighted(x, qw, sigma, shape, &mut l), - None if shape.is_min => small_plain_min(x, shape, &mut l), - None => small_plain_sym(x, shape, &mut l), - }; - put_h(y, 0, d); - let head = if shape.is_min { - put_h(y, 2, m); - 4 - } else { - 2 - }; - if five { - pack5(&l, y, head); - } else { - pack4(&l, &mut y[head..]); - } -} -/// Levels from the importance-weighted search; (scale, minimum). -fn small_weighted(x: &[f32], qw: &[f32], sigma: f32, shape: Shape, l: &mut [u8; 32]) -> (f32, f32) { + let nmax = if five { 31 } else { 15 }; let w = std::array::from_fn::<_, 32, _>(|j| qw[j] * (sigma + x[j] * x[j]).sqrt()); - if shape.is_min { - let (s, m) = qkx(x, shape.nmax, &w, l, Qkx::WEIGHTED); - return (s, -m); + if is_min { + let (s, m) = qkx(x, nmax, &w, &mut l, -0.9, 0.05, 36, false, true); + (l, s, -m) + } else { + let mut q = [0i8; 32]; + let d = qx(x, if five { 16 } else { 8 }, &mut q, 1, Some(&w)); + for j in 0..32 { + l[j] = q[j] as u8; + } + (l, d, 0.0) } - let mut q = [0i8; 32]; - let d = qx(x, if shape.five { 16 } else { 8 }, &mut q, 1, Some(&w)); - for j in 0..32 { - l[j] = q[j] as u8; - } - (d, 0.0) } -/// Reference levels of Q4_1/Q5_1 from the min and max of the block; (scale, minimum). -fn small_plain_min(x: &[f32], shape: Shape, l: &mut [u8; 32]) -> (f32, f32) { +fn small_min_max(five: bool, x: &[f32]) -> SmallFit { + let mut l = [0u8; 32]; + let nmax = if five { 31 } else { 15 }; let (mut min, mut max) = (f32::MAX, -f32::MAX); for &v in x { if v < min { @@ -208,27 +204,35 @@ fn small_plain_min(x: &[f32], shape: Shape, l: &mut [u8; 32]) -> (f32, f32) { max = v; } } - let d = (max - min) / shape.nmax as f32; + let d = (max - min) / nmax as f32; let inv = if d != 0.0 { 1.0 / d } else { 0.0 }; for j in 0..32 { let q = ((x[j] - min) * inv + 0.5) as i32; - l[j] = if shape.five { q as u8 } else { q.min(15) as u8 }; + l[j] = if five { q as u8 } else { q.min(15) as u8 }; } - (d, min) + (l, d, min) } -/// Reference levels of Q4_0/Q5_0 around the centre level; (scale, 0). -fn small_plain_sym(x: &[f32], shape: Shape, l: &mut [u8; 32]) -> (f32, f32) { +fn small_centered(five: bool, x: &[f32]) -> SmallFit { + let mut l = [0u8; 32]; + let nmax = if five { 31 } else { 15 }; let (_, max) = max_signed(x); - let center = if shape.five { 16 } else { 8 }; + let center = if five { 16 } else { 8 }; let d = max / -(center as f32); let inv = if d != 0.0 { 1.0 / d } else { 0.0 }; for j in 0..32 { - l[j] = ((x[j] * inv + center as f32 + 0.5) as i8 as i32).min(shape.nmax) as u8; + l[j] = ((x[j] * inv + center as f32 + 0.5) as i8 as i32).min(nmax) as u8; } - (d, 0.0) + (l, d, 0.0) } -/// Five-bit packing: the low nibbles at `head + 4`, the fifth bits as a little-endian u32 at `head`. -fn pack5(l: &[u8; 32], y: &mut [u8], head: usize) { +fn small_levels(is_min: bool, five: bool, x: &[f32], qw: Option<&[f32]>, sigma: f32) -> SmallFit { + match qw { + Some(qw) => small_weighted(is_min, five, x, qw, sigma), + None if is_min => small_min_max(five, x), + None => small_centered(five, x), + } +} +/// Five-bit levels: the low nibbles after the 4-byte high-bit word at `head`. +fn pack_five(l: &[u8; 32], y: &mut [u8], head: usize) { let mut hi = 0u32; for j in 0..16 { y[head + 4 + j] = (l[j] & 15) | ((l[j + 16] & 15) << 4); @@ -237,6 +241,30 @@ fn pack5(l: &[u8; 32], y: &mut [u8], head: usize) { } y[head..head + 4].copy_from_slice(&hi.to_le_bytes()); } +fn small_q45(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) { + let is_min = matches!(kind, Kind::Q4One | Kind::Q5One); + let five = matches!(kind, Kind::Q5Zero | Kind::Q5One); + let (l, d, m) = small_levels(is_min, five, x, qw, sigma); + put_h(y, 0, d); + let head = if is_min { 4 } else { 2 }; + if is_min { + put_h(y, 2, m); + } + if five { + pack_five(&l, y, head); + } else { + pack4(&l, &mut y[head..]); + } +} +pub(super) fn small(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) { + match kind { + Kind::F32 | Kind::F16 | Kind::Bf16 => small_float(kind, x, y), + Kind::Q1Zero => small_q1(x, y), + Kind::Q2Zero => small_q2(x, y), + Kind::Q8Zero => small_q8(x, y), + _ => small_q45(kind, x, y, qw, sigma), + } +} pub(super) fn e8_half(e: u8) -> f32 { f32::from_bits(if e < 2 { 0x00200000u32 << e } else { ((e as u32) - 1) << 23 }) }